text
stringlengths 8
6.88M
|
|---|
#include<iostream>
using namespace std;
int main()
{int n;
while (cin >> n && n != 0)
{int x = 0,x0 = 0,sum = 0;
for (int i = 1;i <= n;i++)
{cin >> x;
sum+=5;
if (x > x0) sum+=(x-x0)*6;
else sum+=(x0-x)*4;
x0 = x;
}
cout << sum << endl;
}
return 0;
}
|
// singleCameraProject.cpp : Defines the entry point for the console application.
/* Kalev Roomann-Kurrik
3/30/2011
Interim Senior Design Project
A single camera computer vision-based percussion system.
These components will be combined with the stereo imaging in TwoFeedTest
to produce the final two camera three dimensional senior project
*/
#include "stdafx.h"
#include "math.h"
#include <windows.h>
#include <mmsystem.h>
#include <cv.h>
#include <cxcore.h>
#include <highgui.h>
int main(int argc, CHAR* argv[])
{
CvCapture* capture;
IplImage* frame;
capture = cvCreateCameraCapture(0);
assert(capture != NULL);
frame = cvQueryFrame(capture);
IplImage* prev_frame = cvCreateImage(cvGetSize(frame), 8, 3);
IplImage* grayFrame = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1);
IplImage* grayPrevFrame = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1);
// Component images
IplImage* red = cvCreateImage(cvGetSize(frame), 8, 1);
IplImage* green = cvCreateImage(cvGetSize(frame), 8, 1);
IplImage* blue = cvCreateImage(cvGetSize(frame), 8, 1);
// HSV image
IplImage* hsvFrame = cvCreateImage(cvGetSize(frame), 8, 3);
// Threshold image
IplImage* threshFrame = cvCreateImage(cvGetSize(frame), 8, 1);
// Setup prev_frame and frame
frame = cvQueryFrame(capture);
cvCopy(frame,prev_frame,0);
frame = cvQueryFrame(capture);
// Matrices to store x,y locations of tracked features for two images in sequence
int *firstX = new int[100];
int *firstY = new int[100];
int *secondX = new int[100];
int *secondY = new int[100];
for(int k=0;k<100;k++)
{
firstX[k] = 0;
firstY[k] = 0;
secondX[k] = 0;
secondY[k] = 0;
}
int firstCounter = 0;
int secondCounter = 0;
// Flags for whether a specific hit box had a tracked point in it the previous frame
int snareFlag = 0;
int hihatFlag = 0;
int kickFlag = 0;
// Flags for which sounds to play each frame
int playSnare = 0;
int playHihat = 0;
int playKick = 0;
// Take one frame first to start things off for comparing two frames
// Capture the new current frame
frame = cvQueryFrame(capture);
/* Tracking Red Object
- If this works then can tape tip of drumsticks and shoes red to track them
- Needs to be fast and reliable
*/
// Convert Image to HSV colorspace
cvCvtColor(frame, hsvFrame, CV_BGR2HSV);
// Threshold in HSV colorspace
cvInRangeS(hsvFrame, cvScalar(0, 130, 60), cvScalar(8, 255, 120), threshFrame);
cvShowImage("Thresholded HSV Image", threshFrame);
// Process thresholded image block by block and see where the areas of greatest intensity are
// At those locations right now just draw boxes over the feed image and display that
int sum = 0;
// Go through with a 11x11 block across the 640x480 image
for(int y=6;y<(threshFrame->height-10);y=y+10)
{
// Get pointers to desired rows
uchar* pointer1 = (uchar*) (threshFrame->imageData + (y-5) * threshFrame->widthStep);
uchar* pointer2 = (uchar*) (threshFrame->imageData + (y-4) * threshFrame->widthStep);
uchar* pointer3 = (uchar*) (threshFrame->imageData + (y-3) * threshFrame->widthStep);
uchar* pointer4 = (uchar*) (threshFrame->imageData + (y-2) * threshFrame->widthStep);
uchar* pointer5 = (uchar*) (threshFrame->imageData + (y-1) * threshFrame->widthStep);
uchar* pointer6 = (uchar*) (threshFrame->imageData + (y) * threshFrame->widthStep);
uchar* pointer7 = (uchar*) (threshFrame->imageData + (y+1) * threshFrame->widthStep);
uchar* pointer8 = (uchar*) (threshFrame->imageData + (y+2) * threshFrame->widthStep);
uchar* pointer9 = (uchar*) (threshFrame->imageData + (y+3) * threshFrame->widthStep);
uchar* pointer10 = (uchar*) (threshFrame->imageData + (y+4) * threshFrame->widthStep);
uchar* pointer11 = (uchar*) (threshFrame->imageData + (y+5) * threshFrame->widthStep);
// Go through the current row of the image by intervals of 10
for(int x=6;x<(threshFrame->width-10);x=x+10)
{
// reset sum
sum = 0;
// add up pixel values in 11x11 box
for(int i = 0; i<6; i++)
{
if(i==0)
{
sum = sum + pointer1[x] + pointer2[x] + pointer3[x] + pointer4[x] + pointer5[x] + pointer6[x]
+ pointer7[x] + pointer8[x] + pointer9[x] + pointer10[x] + pointer11[x];
}
else
{
sum = sum + pointer1[x-i] + pointer1[x+i] + pointer2[x-i] + pointer2[x+i]
+ pointer3[x-i] + pointer3[x+i] + pointer4[x-i] + pointer4[x+i]
+ pointer5[x-i] + pointer5[x+i] + pointer6[x-i] + pointer6[x+i]
+ pointer7[x-i] + pointer7[x+i] + pointer8[x-i] + pointer8[x+i]
+ pointer9[x-i] + pointer9[x+i] + pointer10[x-1] + pointer10[x+i]
+ pointer11[x-i] + pointer11[x+i];
}
}
// if the sum of the values across the entire 11x11 window is above a certain
// threshold value then draw a rectangle at that location and store the
// x and y coordinates of the center of the window
if(sum>1500)
{
CvPoint point0 = cvPoint(x-5,y-5);
CvPoint point1 = cvPoint(x+5,y+5);
cvRectangle(frame,point0,point1,CV_RGB(255,0,0),2);
firstX[firstCounter] = x;
firstY[firstCounter] = y;
firstCounter++;
}
}
}
// loop to continually perform thresholding, tracking, event recognition, and sound playback
while(1)
{
// Capture the new current frame
frame = cvQueryFrame(capture);
/* Tracking Red Object
- If this works then can tape tip of drumsticks and shoes red to track them
- Needs to be fast and reliable
*/
// Convert Image to HSV colorspace
cvCvtColor(frame, hsvFrame, CV_BGR2HSV);
// Threshold in HSV colorspace
// 0 < H < 5
// 200 < S < 255
// 80 < V < 120
cvInRangeS(hsvFrame, cvScalar(0, 130, 20), cvScalar(7, 255, 140), threshFrame);
cvShowImage("Thresholded HSV Image", threshFrame);
// Process thresholded image block by block and see where the areas of greatest intensity are
// At those locations right now just draw boxes over the feed image and display that
int sum = 0;
secondCounter = 0;
for(int k=0;k<100;k++)
{
secondX[k] = 0;
secondY[k] = 0;
}
// Go through with a 11x11 block across the 640x480 image
for(int y=6;y<(threshFrame->height-10);y=y+10)
{
// Get pointers to desired rows
uchar* pointer1 = (uchar*) (threshFrame->imageData + (y-5) * threshFrame->widthStep);
uchar* pointer2 = (uchar*) (threshFrame->imageData + (y-4) * threshFrame->widthStep);
uchar* pointer3 = (uchar*) (threshFrame->imageData + (y-3) * threshFrame->widthStep);
uchar* pointer4 = (uchar*) (threshFrame->imageData + (y-2) * threshFrame->widthStep);
uchar* pointer5 = (uchar*) (threshFrame->imageData + (y-1) * threshFrame->widthStep);
uchar* pointer6 = (uchar*) (threshFrame->imageData + (y) * threshFrame->widthStep);
uchar* pointer7 = (uchar*) (threshFrame->imageData + (y+1) * threshFrame->widthStep);
uchar* pointer8 = (uchar*) (threshFrame->imageData + (y+2) * threshFrame->widthStep);
uchar* pointer9 = (uchar*) (threshFrame->imageData + (y+3) * threshFrame->widthStep);
uchar* pointer10 = (uchar*) (threshFrame->imageData + (y+4) * threshFrame->widthStep);
uchar* pointer11 = (uchar*) (threshFrame->imageData + (y+5) * threshFrame->widthStep);
// Go through the current row of the image by intervals of 10
for(int x=6;x<(threshFrame->width-10);x=x+10)
{
// reset sum
sum = 0;
// add up pixel values in 11x11 box
for(int i = 0; i<6; i++)
{
if(i==0)
{
sum = sum + pointer1[x] + pointer2[x] + pointer3[x] + pointer4[x] + pointer5[x] + pointer6[x]
+ pointer7[x] + pointer8[x] + pointer9[x] + pointer10[x] + pointer11[x];
}
else
{
sum = sum + pointer1[x-i] + pointer1[x+i] + pointer2[x-i] + pointer2[x+i]
+ pointer3[x-i] + pointer3[x+i] + pointer4[x-i] + pointer4[x+i]
+ pointer5[x-i] + pointer5[x+i] + pointer6[x-i] + pointer6[x+i]
+ pointer7[x-i] + pointer7[x+i] + pointer8[x-i] + pointer8[x+i]
+ pointer9[x-i] + pointer9[x+i] + pointer10[x-1] + pointer10[x+i]
+ pointer11[x-i] + pointer11[x+i];
}
}
// if the sum of the values across the entire 11x11 window is above a certain
// threshold value then draw a rectangle at that location and store the
// x and y coordinates of the center of the window
if(sum>1500)
{
CvPoint point0 = cvPoint(x-5,y-5);
CvPoint point1 = cvPoint(x+5,y+5);
cvRectangle(frame,point0,point1,CV_RGB(255,0,0),2);
secondX[secondCounter] = x;
secondY[secondCounter] = y;
secondCounter++;
}
}
}
// check to see if any points were inside hit box in previous frame
for(int k=0;k<firstCounter;k++)
{
// check snare
if(firstX[k] < 360 && firstX[k] > 280 && firstY[k] < 300 && firstY[k] > 240)
{
snareFlag = 1;
break;
}
else
{
snareFlag = 0;
}
}
for(int k=0;k<firstCounter;k++)
{
// check hi-hat
if(firstX[k] < 460 && firstX[k] > 370 && firstY[k] < 330 && firstY[k] > 290)
{
hihatFlag = 1;
break;
}
else
{
hihatFlag = 0;
}
}
for(int k=0;k<firstCounter;k++)
{
// check kick
if(firstX[k] < 280 && firstX[k] > 200 && firstY[k] < 479 && firstY[k] > 460)
{
kickFlag = 1;
break;
}
else
{
kickFlag = 0;
}
}
// If no points were in the box in the previous frame then check to see if any points were in
// the box this frame and if so trigger an event
for(int l=0;l<secondCounter;l++)
{
if(secondX[l] < 360 && secondX[l] > 280 && secondY[l] < 340 && secondY[l] > 300 && snareFlag == 0)
{
playSnare = 1;
}
else if(secondX[l] < 460 && secondX[l] > 370 && secondY[l] < 330 && secondY[l] > 290 && hihatFlag == 0)
{
playHihat = 1;
}
else if(secondX[l] < 280 && secondX[l] > 200 && secondY[l] < 479 && secondY[l] > 460 && kickFlag == 0)
{
playKick = 1;
}
}
// Check playing flags to see which sounds to play
// Kick, Snare, and Hi-hat
if(playKick == 1 && playSnare == 1 && playHihat == 1)
{
printf("Kick Snare Hi-hat\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\kicksnarehihat.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Kick and Snare
else if(playKick == 1 && playSnare == 1)
{
printf("Kick Snare\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\kicksnare.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Kick and Hi-hat
else if(playKick == 1 && playHihat == 1)
{
printf("Kick Hi-hat\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\kickhihat.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Snare and Hi-hat
else if(playSnare == 1 && playHihat == 1)
{
printf(" Snare Hi-hat\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\snarehihat.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Snare only
else if(playSnare == 1)
{
printf(" Snare\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\snareshort.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Hi-hat only
else if(playHihat == 1)
{
printf(" Hi-hat\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\hihatshort.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Kick only
else if(playKick == 1)
{
printf("Kick\n");
PlaySound(_T("C:\\Users\\Kalev\\Desktop\\Drums\\kickshort.wav"), 0, SND_FILENAME|SND_ASYNC|SND_NOSTOP);
}
// Draw hit boxes onto current frame
// Snare
cvRectangle(frame, cvPoint(280,300), cvPoint(360,340), CV_RGB(255,0,0), 1);
// Hi-hat
cvRectangle(frame, cvPoint(370,290), cvPoint(460,330), CV_RGB(255,0,0), 1);
// Kick
cvRectangle(frame, cvPoint(200,460), cvPoint(280,479), CV_RGB(255,0,0), 1);
cvShowImage("Feed", frame);
// copy the last frame into the prev_frame image
cvCopy(frame,prev_frame,0);
// copy set of points from second image in sequence to be used as set of points from
// first image in sequence next time
for(int k=0;k<secondCounter;k++)
{
firstX[k] = secondX[k];
firstY[k] = secondY[k];
}
firstCounter = secondCounter;
// Reset playing flags
playSnare = 0;
playHihat = 0;
playKick = 0;
if(cvWaitKey(5) == 27)
break;
}
cvReleaseCapture(&capture);
cvReleaseImage(&red);
cvReleaseImage(&green);
cvReleaseImage(&blue);
cvReleaseImage(&hsvFrame);
cvReleaseImage(&threshFrame);
cvDestroyWindow("Feed");
delete [] firstX;
delete [] firstY;
delete [] secondX;
delete [] secondY;
return 0;
}
|
#include "SeparatedExtendedReadsList.h"
#include "../../utils/LzmaLib.h"
#include "../SeparatedPseudoGenomeBase.h"
namespace PgTools {
template <int maxMismatches>
SeparatedExtendedReadsListIterator<maxMismatches>::SeparatedExtendedReadsListIterator(const string &pseudoGenomePrefix)
: pseudoGenomePrefix(pseudoGenomePrefix) {
ownProps = true;
SeparatedPseudoGenomeBase::getPseudoGenomeProperties(pseudoGenomePrefix, pgh, rsProp, plainTextReadMode);
if (PgSAReadsSet::isReadLengthMin(pgh->getMaxReadLength()))
PgSAHelpers::bytePerReadLengthMode = true;
initSrcs();
}
template<int maxMismatches>
SeparatedExtendedReadsListIterator<maxMismatches>::SeparatedExtendedReadsListIterator(istream& pgrcIn,
PseudoGenomeHeader* pgh, ReadsSetProperties* rsProp, const string pseudoGenomePrefix)
: pseudoGenomePrefix(pseudoGenomePrefix), pgh(pgh), rsProp(rsProp),
plainTextReadMode(false) {
ownProps = false;
if (PgSAReadsSet::isReadLengthMin(pgh->getMaxReadLength()))
PgSAHelpers::bytePerReadLengthMode = true;
decompressSrcs(pgrcIn);
}
template<int maxMismatches>
SeparatedExtendedReadsListIterator<maxMismatches>* SeparatedExtendedReadsListIterator<maxMismatches>::getIterator(const string &pseudoGenomePrefix) {
return new SeparatedExtendedReadsListIterator(pseudoGenomePrefix);
}
template <int maxMismatches>
SeparatedExtendedReadsListIterator<maxMismatches>::~SeparatedExtendedReadsListIterator() {
if (ownProps) {
delete (pgh);
delete (rsProp);
}
freeSrcs();
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::initSrc(istream *&src, const string &fileSuffix) {
if (!pseudoGenomePrefix.empty()) {
src = new ifstream(pseudoGenomePrefix + fileSuffix, ios_base::in | ios_base::binary);
if (src->fail()) {
delete (src);
src = 0;
}
}
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::initSrcs() {
initSrc(rlPosSrc, SeparatedPseudoGenomeBase::READSLIST_POSITIONS_FILE_SUFFIX);
initSrc(rlOrgIdxSrc, SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX);
initSrc(rlRevCompSrc, SeparatedPseudoGenomeBase::READSLIST_REVERSECOMPL_FILE_SUFFIX);
initSrc(rlMisCntSrc, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_COUNT_FILE_SUFFIX);
if (maxMismatches == 0 && rlMisCntSrc) {
fprintf(stderr, "WARNING: mismatches unsupported in current routine working on %s Pg\n", pseudoGenomePrefix.c_str());
}
initSrc(rlMisSymSrc, SeparatedPseudoGenomeBase::READSLIST_MISMATCHED_SYMBOLS_FILE_SUFFIX);
initSrc(rlMisOffSrc, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_POSITIONS_FILE_SUFFIX);
initSrc(rlOffSrc, SeparatedPseudoGenomeBase::READSLIST_OFFSETS_FILE_SUFFIX);
initSrc(rlMisRevOffSrc, SeparatedPseudoGenomeBase::READSLIST_MISMATCHES_REVOFFSETS_FILE_SUFFIX);
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::decompressSrc(istream *&src, istream &pgrcIn,
SymbolsPackingFacility *symPacker) {
uint64_t resLength = 0;
if (symPacker)
PgSAHelpers::readValue<uint64_t>(pgrcIn, resLength, false);
string tmp;
readCompressed(pgrcIn, tmp);
if (symPacker)
tmp = symPacker->reverseSequence((uint8_t*) tmp.data(), 0, resLength);
src = new istringstream(tmp);
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::decompressMisRevOffSrc(istream &pgrcIn, bool transposeMode) {
uint8_t mismatchesCountSrcsLimit = 0;
PgSAHelpers::readValue<uint8_t>(pgrcIn, mismatchesCountSrcsLimit, false);
vector<uint8_t> misCnt2SrcIdx(UINT8_MAX, mismatchesCountSrcsLimit);
if (mismatchesCountSrcsLimit == 1) {
decompressSrc(rlMisRevOffSrc, pgrcIn);
return;
}
for(uint8_t m = 1; m < mismatchesCountSrcsLimit; m++)
PgSAHelpers::readValue<uint8_t>(pgrcIn, misCnt2SrcIdx[m], false);
istream* srcs[UINT8_MAX];
for(uint8_t m = 1; m <= mismatchesCountSrcsLimit; m++) {
*logout << (int) m << ": ";
decompressSrc(srcs[m], pgrcIn);
}
if (transposeMode) {
for (uint8_t s = 1; s < mismatchesCountSrcsLimit; s++) {
if (misCnt2SrcIdx[s] == misCnt2SrcIdx[s - 1] || misCnt2SrcIdx[s] == misCnt2SrcIdx[s + 1])
continue;
string matrix = ((istringstream *) srcs[s])->str();
uint64_t readsCount = matrix.size() / s / (bytePerReadLengthMode ? 1 : 2);
if (bytePerReadLengthMode)
((istringstream *) srcs[s])->str(transpose<uint8_t>(matrix, s, readsCount));
else
((istringstream *) srcs[s])->str(transpose<uint16_t>(matrix, s, readsCount));
}
}
ostringstream misRevOffDest;
uint8_t misCnt = 0;
uint16_t revOff = 0;
for(uint_reads_cnt_max i = 0; i < this->rsProp->readsCount; i++) {
PgSAHelpers::readValue<uint8_t>(*rlMisCntSrc, misCnt, false);
for(uint8_t m = 0; m < misCnt; m++) {
PgSAHelpers::readReadLengthValue(*srcs[misCnt2SrcIdx[misCnt]], revOff, false);
PgSAHelpers::writeReadLengthValue(misRevOffDest, revOff);
}
}
rlMisCntSrc->seekg(0, ios::beg);
rlMisRevOffSrc = new istringstream(misRevOffDest.str());
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::decompressSrcs(istream &pgrcIn) {
decompressSrc(rlOffSrc, pgrcIn);
decompressSrc(rlRevCompSrc, pgrcIn);//, &SymbolsPackingFacility<uint8_t>::BinaryPacker);
decompressSrc(rlMisCntSrc, pgrcIn);
if (maxMismatches == 0 && rlMisCntSrc) {
fprintf(stderr, "WARNING: mismatches unsupported in current routine working on %s Pg\n", pseudoGenomePrefix.c_str());
}
decompressSrc(rlMisSymSrc, pgrcIn);//, &SymbolsPackingFacility<uint8_t>::QuaternaryPacker);
decompressMisRevOffSrc(pgrcIn);
initSrc(rlOrgIdxSrc, SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX);
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::freeSrc(istream *&src) {
if (src) {
/* if (fromFileMode())
((ifstream*) src)->close();*/
delete (src);
src = 0;
}
}
template <int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::freeSrcs() {
freeSrc(rlPosSrc);
freeSrc(rlOrgIdxSrc);
freeSrc(rlRevCompSrc);
freeSrc(rlMisCntSrc);
freeSrc(rlMisSymSrc);
freeSrc(rlMisOffSrc);
freeSrc(rlOffSrc);
freeSrc(rlMisRevOffSrc);
}
template <int maxMismatches>
bool SeparatedExtendedReadsListIterator<maxMismatches>::moveNext() {
if (++current < pgh->getReadsCount()) {
uint_reads_cnt_std idx = 0;
uint8_t revComp = 0;
PgSAHelpers::readValue<uint_reads_cnt_std>(*rlOrgIdxSrc, idx, plainTextReadMode);
if (rlRevCompSrc)
PgSAHelpers::readValue<uint8_t>(*rlRevCompSrc, revComp, plainTextReadMode);
if (rlOffSrc) {
uint_read_len_max offset = 0;
PgSAHelpers::readReadLengthValue(*rlOffSrc, offset, plainTextReadMode);
entry.advanceEntryByOffset(offset, idx, revComp == 1);
} else {
uint_pg_len_max pos = 0;
PgSAHelpers::readValue<uint_pg_len_max>(*rlPosSrc, pos, plainTextReadMode);
entry.advanceEntryByPosition(pos, idx, revComp == 1);
}
if (maxMismatches != 0 && rlMisCntSrc) {
uint8_t mismatchesCount = 0;
PgSAHelpers::readValue<uint8_t>(*rlMisCntSrc, mismatchesCount, plainTextReadMode);
for(uint8_t i = 0; i < mismatchesCount; i++) {
uint8_t mismatchCode = 0;
uint_read_len_max mismatchOffset = 0;
PgSAHelpers::readValue<uint8_t>(*rlMisSymSrc, mismatchCode, plainTextReadMode);
if (rlMisOffSrc)
PgSAHelpers::readReadLengthValue(*rlMisOffSrc, mismatchOffset, plainTextReadMode);
else
PgSAHelpers::readReadLengthValue(*rlMisRevOffSrc, mismatchOffset, plainTextReadMode);
entry.addMismatch(mismatchCode, mismatchOffset);
}
if (!rlMisOffSrc)
convertMisRevOffsets2Offsets(entry.mismatchOffset, entry.mismatchesCount, pgh->getMaxReadLength());
}
return true;
}
return false;
}
template<int maxMismatches>
void SeparatedExtendedReadsListIterator<maxMismatches>::rewind() {
fprintf(stderr, "Error: Rewinding SeparatedExtendedReadsListIterator unimplemented.");
exit(EXIT_FAILURE);
}
template <int maxMismatches>
PgTools::ReadsListEntry<maxMismatches, uint_read_len_max, uint_reads_cnt_max, uint_pg_len_max> &
SeparatedExtendedReadsListIterator<maxMismatches>::peekReadEntry() {
return entry;
}
template <int maxMismatches>
bool SeparatedExtendedReadsListIterator<maxMismatches>::isRevCompEnabled() {
return rlRevCompSrc;
}
template <int maxMismatches>
bool SeparatedExtendedReadsListIterator<maxMismatches>::areMismatchesEnabled() {
return rlMisCntSrc;
}
ExtendedReadsListWithConstantAccessOption *ExtendedReadsListWithConstantAccessOption::loadConstantAccessExtendedReadsList(
const string &pseudoGenomePrefix, uint_pg_len_max pgLengthPosGuard, bool skipMismatches) {
DefaultSeparatedExtendedReadsListIterator rl(pseudoGenomePrefix);
return loadConstantAccessExtendedReadsList(rl, pgLengthPosGuard, skipMismatches);
}
ExtendedReadsListWithConstantAccessOption *ExtendedReadsListWithConstantAccessOption::loadConstantAccessExtendedReadsList(
DefaultSeparatedExtendedReadsListIterator &rl, uint_pg_len_max pgLengthPosGuard, bool skipMismatches) {
ExtendedReadsListWithConstantAccessOption *res = new ExtendedReadsListWithConstantAccessOption(rl.pgh->getMaxReadLength());
if (rl.plainTextReadMode) {
fprintf(stderr, "Unsupported text plain read mode in creating ExtendedReadsListWithConstantAccessOption for %s\n\n",
rl.pseudoGenomePrefix.c_str());
exit(EXIT_FAILURE);
}
const uint_reads_cnt_max readsCount = rl.pgh->getReadsCount();
if (rl.rlOrgIdxSrc) {
res->orgIdx.resize(readsCount);
PgSAHelpers::readArray(*(rl.rlOrgIdxSrc), res->orgIdx.data(), sizeof(uint_reads_cnt_std) * readsCount);
} else
res->orgIdx.resize(readsCount, 0);
if (rl.rlRevCompSrc) {
res->revComp.resize(readsCount);
PgSAHelpers::readArray(*(rl.rlRevCompSrc), res->revComp.data(), sizeof(uint8_t) * readsCount);
}
res->pos.reserve(readsCount + 1);
if (rl.rlOffSrc) {
uint_pg_len_max pos = 0;
uint_read_len_max offset = 0;
for(uint_reads_cnt_max i = 0; i < readsCount; i++) {
PgSAHelpers::readReadLengthValue(*(rl.rlOffSrc), offset, rl.plainTextReadMode);
pos = pos + offset;
res->pos.push_back(pos);
}
} else {
res->pos.resize(readsCount);
PgSAHelpers::readArray(*(rl.rlPosSrc), res->pos.data(), sizeof(uint_pg_len_max) * readsCount);
}
if (pgLengthPosGuard)
res->pos.push_back(pgLengthPosGuard);
if (!skipMismatches && rl.rlMisCntSrc) {
uint_reads_cnt_max cumCount = 0;
uint8_t mismatchesCount = 0;
res->misCumCount.reserve(readsCount + 1);
res->misCumCount.push_back(0);
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
PgSAHelpers::readValue<uint8_t>(*(rl.rlMisCntSrc), mismatchesCount, rl.plainTextReadMode);
cumCount += mismatchesCount;
res->misCumCount.push_back(cumCount);
}
res->misSymCode.resize(cumCount);
PgSAHelpers::readArray(*(rl.rlMisSymSrc), res->misSymCode.data(), sizeof(uint8_t) * cumCount);
res->misOff.resize(cumCount);
bool misRevOffMode = rl.rlMisOffSrc == 0;
PgSAHelpers::readArray(misRevOffMode?*(rl.rlMisRevOffSrc):*(rl.rlMisOffSrc), res->misOff.data(),
sizeof(uint8_t) * cumCount);
if (misRevOffMode) {
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
PgSAHelpers::convertMisRevOffsets2Offsets<uint8_t>(res->misOff.data() + res->misCumCount[i],
res->getMisCount(i), res->readLength);
}
}
}
cout << "Loaded Pg reads list containing " << readsCount << " reads." << endl;
return res;
}
ExtendedReadsListWithConstantAccessOption* ExtendedReadsListWithConstantAccessOption::loadConstantAccessExtendedReadsList(
istream& pgrcIn, PseudoGenomeHeader* pgh, ReadsSetProperties* rsProp, const string validationPgPrefix,
bool preserveOrderMode, bool disableRevCompl, bool disableMismatches) {
ExtendedReadsListWithConstantAccessOption *res = new ExtendedReadsListWithConstantAccessOption(pgh->getMaxReadLength());
const uint_reads_cnt_max readsCount = pgh->getReadsCount();
if (!preserveOrderMode)
readCompressed(pgrcIn, res->off);
if (!disableRevCompl)
readCompressed(pgrcIn, res->revComp);
if (!disableMismatches) {
readCompressed(pgrcIn, res->misCnt);
readCompressed(pgrcIn, res->misSymCode);
uint8_t mismatchesCountSrcsLimit = 0;
PgSAHelpers::readValue<uint8_t>(pgrcIn, mismatchesCountSrcsLimit, false);
vector<uint8_t> misCnt2SrcIdx(UINT8_MAX, mismatchesCountSrcsLimit);
for (uint8_t m = 1; m < mismatchesCountSrcsLimit; m++)
PgSAHelpers::readValue<uint8_t>(pgrcIn, misCnt2SrcIdx[m], false);
vector<uint8_t> srcs[UINT8_MAX];
vector<uint_reads_cnt_std> srcCounter(UINT8_MAX, 0);
for (uint8_t m = 1; m <= mismatchesCountSrcsLimit; m++) {
*logout << (int) m << ": ";
readCompressed(pgrcIn, srcs[m]);
}
res->misOff.reserve(res->misSymCode.size());
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
uint8_t misCnt = res->misCnt[i];
uint8_t srcIdx = misCnt2SrcIdx[misCnt];
uint64_t misOffStartIdx = res->misOff.size();
for (uint8_t m = 0; m < misCnt; m++)
res->misOff.push_back(srcs[srcIdx][srcCounter[srcIdx]++]);
PgSAHelpers::convertMisRevOffsets2Offsets<uint8_t>(res->misOff.data() + misOffStartIdx,
res->misCnt[i], res->readLength);
}
}
if (!validationPgPrefix.empty()) {
std::ifstream in((validationPgPrefix + SeparatedPseudoGenomeBase::READSLIST_ORIGINAL_INDEXES_FILE_SUFFIX).c_str(), std::ifstream::binary);
res->orgIdx.resize(readsCount);
readArray(in, res->orgIdx.data(), readsCount * sizeof(uint_reads_cnt_std));
}
cout << "Loaded Pg reads list containing " << readsCount << " reads." << endl;
return res;
}
bool ExtendedReadsListWithConstantAccessOption::moveNext() {
if (++current < readsCount) {
entry.advanceEntryByOffset(off[current], orgIdx[current], this->getRevComp(current));
if (!misCnt.empty()) {
uint8_t mismatchesCount = misCnt[current];
for (uint8_t i = 0; i < mismatchesCount; i++)
entry.addMismatch(misSymCode[curMisCumCount], misOff[curMisCumCount++]);
}
return true;
}
return false;
}
void ExtendedReadsListWithConstantAccessOption::rewind() {
current = -1;
curMisCumCount = 0;
}
bool ExtendedReadsListWithConstantAccessOption::isRevCompEnabled() {
return !this->revComp.empty();
}
bool ExtendedReadsListWithConstantAccessOption::areMismatchesEnabled() {
return !this->misCumCount.empty() || !this->misOff.empty();
}
bool ExtendedReadsListWithConstantAccessOption::getRevComp(uint_reads_cnt_std idx) {
return isRevCompEnabled()?revComp[idx]:false;
}
void ExtendedReadsListWithConstantAccessOption::enableConstantAccess(bool disableIterationMode) {
if (pos.empty()) {
pos.reserve(readsCount + 1);
uint_pg_len_max currPos = 0;
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
currPos += off[i];
this->pos.push_back(currPos);
}
this->pos.push_back(this->pos.back() + this->readLength);
}
if (disableIterationMode)
off.clear();
if (!misCnt.empty()) {
uint_reads_cnt_max cumCount = 0;
misCumCount.reserve(readsCount + 1);
misCumCount.push_back(0);
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
cumCount += misCnt[i];
misCumCount.push_back(cumCount);
}
if (disableIterationMode)
misCnt.clear();
}
}
bool ExtendedReadsListWithConstantAccessOption::isConstantAccessEnalbed() {
return !this->pos.empty();
}
template class SeparatedExtendedReadsListIterator<UINT8_MAX>;
template class SeparatedExtendedReadsListIterator<0>;
}
|
// "Copyright [2020] <Taraymovich Igor>"
#include "integrate.hpp"
namespace integrate {
double Integrate(func F, double left, double right, double eps) {
double sum = 0;
for (double x = left + eps; x <= right - eps; x += eps) {
sum += F(x);
}
sum += (F(left) + F(right)) / 2;
return sum * eps;
}
} // namespace integrate
|
#pragma once
#include "Shape.h"
#include "Triangle.h"
#include "Sphere.h"
#include <vector>
namespace RayTracer
{
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace std;
struct intersections
{
float distance;
int indice;
} intersection;
public ref class RayTracer : public System::Windows::Forms::Form
{
public:
RayTracer(void)
{
InitializeComponent();
}
protected:
~RayTracer()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::PictureBox^ surfacePictureBox;
protected:
private: System::Windows::Forms::Button^ Render;
private: System::Windows::Forms::Label^ label1;
private: System::Windows::Forms::TextBox^ timeBox;
private:
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->surfacePictureBox = (gcnew System::Windows::Forms::PictureBox());
this->Render = (gcnew System::Windows::Forms::Button());
this->label1 = (gcnew System::Windows::Forms::Label());
this->timeBox = (gcnew System::Windows::Forms::TextBox());
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->surfacePictureBox))->BeginInit();
this->SuspendLayout();
//
// surfacePictureBox
//
this->surfacePictureBox->BorderStyle = System::Windows::Forms::BorderStyle::Fixed3D;
this->surfacePictureBox->Location = System::Drawing::Point(12, 12);
this->surfacePictureBox->Name = L"surfacePictureBox";
this->surfacePictureBox->Size = System::Drawing::Size(800, 450);
this->surfacePictureBox->TabIndex = 0;
this->surfacePictureBox->TabStop = false;
//
// Render
//
this->Render->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(162)));
this->Render->Location = System::Drawing::Point(376, 477);
this->Render->Name = L"Render";
this->Render->Size = System::Drawing::Size(79, 24);
this->Render->TabIndex = 1;
this->Render->Text = L"Render";
this->Render->UseVisualStyleBackColor = true;
this->Render->Click += gcnew System::EventHandler(this, &RayTracer::Render_Click);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(162)));
this->label1->Location = System::Drawing::Point(604, 481);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(136, 16);
this->label1->TabIndex = 2;
this->label1->Text = L"Rendering Time (sn) :";
//
// timeBox
//
this->timeBox->Font = (gcnew System::Drawing::Font(L"Consolas", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(162)));
this->timeBox->Location = System::Drawing::Point(742, 476);
this->timeBox->Name = L"timeBox";
this->timeBox->Size = System::Drawing::Size(68, 26);
this->timeBox->TabIndex = 3;
this->timeBox->TextAlign = System::Windows::Forms::HorizontalAlignment::Center;
//
// RayTracer
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(823, 510);
this->Controls->Add(this->timeBox);
this->Controls->Add(this->label1);
this->Controls->Add(this->Render);
this->Controls->Add(this->surfacePictureBox);
this->Name = L"RayTracer";
this->Text = L"RayTracer : Transparency";
(cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->surfacePictureBox))->EndInit();
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
#pragma region ShadeDiffuse ShadeSpecular ShadingModel
Color ShadeDiffuse(Shape* S, Vertex iPoint)
{
Vertex light = Vertex(0, 30, 60);
Vertex toLight = (light - iPoint).Normalize();
Vertex normal = S->NormalAt(iPoint).Normalize();
Color c = S->ShapeColor;
float diffuseKatsayi = normal * toLight;
if (diffuseKatsayi < 0.0f) return Color::Black;
float r = 0, g = 0, b = 0;
r += diffuseKatsayi * c.R;
g += diffuseKatsayi * c.G;
b += diffuseKatsayi * c.B;
r = r > 255 ? 255 : r; r = r < 0 ? 0 : r;
g = g > 255 ? 255 : g; g = g < 0 ? 0 : g;
b = b > 255 ? 255 : b; b = b < 0 ? 0 : b;
return Color::FromArgb((int)r, (int)g, (int)b);
}
Color ShadeSpecular(Shape* S, Vertex iPoint, Vertex camera)
{
Vertex light = Vertex(0, 30, 60);
Vertex fromLight = (iPoint - light).Normalize();
Vertex normal = S->NormalAt(iPoint).Normalize();
Vertex toCamera = (camera - iPoint).Normalize();
Color Lamba = Color::White;
Vertex reflected = (fromLight - 2 * (normal * fromLight) * normal).Normalize();
float dotProduct = reflected * toCamera;
if (dotProduct < 0.0f) return Color::Black;
float specularKatsayi = (float)Math::Pow((double)(dotProduct), (double)8);
float r = 0, g = 0, b = 0;
r += specularKatsayi * Lamba.R;
g += specularKatsayi * Lamba.G;
b += specularKatsayi * Lamba.B;
r = r > 255 ? 255 : r; r = r < 0 ? 0 : r;
g = g > 255 ? 255 : g; g = g < 0 ? 0 : g;
b = b > 255 ? 255 : b; b = b < 0 ? 0 : b;
return Color::FromArgb((int)r, (int)g, (int)b);
}
Color ShadingModel(Shape* S, Color diffuseColor, Color specularColor, Color reflectedColor, Color transmittedColor, float amb, float dif, float spec, float refl, float trans)
{
Color ambientcolor = S->ShapeColor;
int r = Math::Min(255, (int)(amb * ambientcolor.R + dif * diffuseColor.R + spec * specularColor.R + refl * reflectedColor.R + trans * transmittedColor.R));
int g = Math::Min(255, (int)(amb * ambientcolor.G + dif * diffuseColor.G + spec * specularColor.G + refl * reflectedColor.G + trans * transmittedColor.G));
int b = Math::Min(255, (int)(amb * ambientcolor.B + dif * diffuseColor.B + spec * specularColor.B + refl * reflectedColor.B + trans * transmittedColor.B));
return Color::FromArgb(r, g, b);
}
#pragma endregion
#pragma region Calculate Reflection Transmission
Vertex CalculateReflection(Shape* S, Vertex iPoint, Vertex Rd)
{
Vertex normal = S->NormalAt(iPoint).Normalize();
return (Rd - 2 * (normal * Rd) * normal).Normalize();
}
Vertex CalculateTransmission(Shape* S, Vertex iPoint, Vertex Rd)
{
return Rd;
}
#pragma endregion
Color TraceRay(Vertex Ro, Vertex Rd, Shape* Shapes[], Vertex camera, int depth, Shape* prevShape)
{
if (depth > 4)
{
return prevShape->ShapeColor;
//return Color::Black;
}
vector<intersections> Intersections;
for (int i = 0; i < 16; i++)
{
float t = Shapes[i]->Intersect(Ro, Rd);
if (t > 0.1F) // 0.1 is a bias value for avoiding self intersection
{
intersection.distance = t;
intersection.indice = i;
Intersections.push_back(intersection);
}
}
if (Intersections.size() > 0)
{
float min_distance = FLT_MAX;
int min_indis = -1;
for (int i = 0; i < Intersections.size(); i++)
{
if (Intersections[i].distance < min_distance)
{
min_indis = Intersections[i].indice;
min_distance = Intersections[i].distance;
}
}
Vertex iPoint = Ro + min_distance * Rd;
Shape* S = Shapes[min_indis];
Color reflectedColor;
if (S->Refl != 0.0F)
{
Vertex reflectedDirection = CalculateReflection(S, iPoint, Rd);
reflectedColor = TraceRay(iPoint, reflectedDirection, Shapes, camera, depth + 1, S);
}
Color transmittedColor;
if (S->Trans != 0.0F)
{
Vertex transmittedDirection = CalculateTransmission(S, iPoint, Rd);
transmittedColor = TraceRay(iPoint, transmittedDirection, Shapes, camera, depth + 1, S);
}
Color diffuseColor = ShadeDiffuse(S, iPoint);
Color specularColor = ShadeSpecular(S, iPoint, camera);
return ShadingModel(S, diffuseColor, specularColor, reflectedColor, transmittedColor, S->Ambient, S->Dif, S->Spec, S->Refl, S->Trans);
}
return Color::Black;
}
private: System::Void Render_Click(System::Object^ sender, System::EventArgs^ e)
{
DateTime startTime;
startTime = startTime.Now;
Bitmap^ surface = gcnew Bitmap(800, 450);
surfacePictureBox->Image = surface;
// Oda
Triangle T1 (Vertex( 60, -40, 120), Vertex(-60, -40, 120), Vertex(-60, 40, 120), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T2 (Vertex( 60, -40, 120), Vertex(-60, 40, 120), Vertex( 60, 40, 120), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T3 (Vertex( 60, -40, 0), Vertex(-60, -40, 0), Vertex( 60, -40, 120), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T4 (Vertex(-60, -40, 120), Vertex( 60, -40, 120), Vertex(-60, -40, 0), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T5 (Vertex( 60, 40, 120), Vertex(-60, 40, 0), Vertex( 60, 40, 0), 0.7F, 0.5F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T6 (Vertex( 60, 40, 120), Vertex(-60, 40, 120), Vertex(-60, 40, 0), 0.7F, 0.5F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T7 (Vertex( 60, 40, 120), Vertex( 60, 40, 0), Vertex( 60, -40, 0), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T8 (Vertex( 60, 40, 120), Vertex( 60, -40, 0), Vertex( 60, -40, 120), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T9 (Vertex(-60, 40, 120), Vertex(-60, -40, 0), Vertex(-60, 40, 0), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T10(Vertex(-60, 40, 120), Vertex(-60, -40, 120), Vertex(-60, -40, 0), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T11(Vertex( 60, -40, 0), Vertex(-60, 40, 0), Vertex(-60, -40, 0), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Triangle T12(Vertex( 60, -40, 0), Vertex( 60, 40, 0), Vertex(-60, 40, 0), 0.3F, 0.7F, 0.0F, 0.0F, 0.0F, Color::White);
Sphere S1(Vertex( 20, 10, 95), 20, 0.2F, 0.3F, 0.5F, 0.0F, 0.0F, Color::Blue);
Sphere S2(Vertex(-10, -5, 40), 10, 0.2F, 0.3F, 0.5F, 0.0F, 0.0F, Color::Red);
Sphere S3(Vertex( 5, -25, 80), 15, 0.2F, 0.3F, 0.5F, 0.0F, 0.0F, Color::Yellow);
Sphere S4(Vertex( 10, 0, 30), 10, 0.1F, 0.1F, 0.0F, 0.0F, 0.8F, Color::White);
Shape* Shapes[16] = { &T1, &T2, &T3, &T4, &T5, &T6, &T7, &T8, &T9, &T10, &T11, &T12, &S1, &S2, &S3, &S4 };
Vertex camera = Vertex(0, 0, 0);
for (int y = 0; y < 450; y++)
{
for (int x = 0; x < 800; x++)
{
Vertex pixel = Vertex(16 * x / 799.0F - 8, 4.5 - y * 9 / 449.0F, 10);
Vertex Rd = (pixel - camera).Normalize();
Color c = TraceRay(camera, Rd, Shapes, camera, 0, NULL);
surface->SetPixel(x, y, c);
}
surfacePictureBox->Refresh();
}
DateTime endTime;
endTime = endTime.Now;
TimeSpan deltaTime = endTime - startTime;
timeBox->Text = (Math::Round(100 * deltaTime.TotalSeconds) / 100.0F).ToString();
DateTime date;
String^ filename = date.Now.Year.ToString() + date.Now.Month.ToString() + date.Now.Day.ToString() +
date.Now.Hour.ToString() + date.Now.Minute.ToString() + date.Now.Second.ToString() + ".jpg";
surface->Save("image/" + filename);
}
};
}
|
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#include "ChatRoom.h"
#include "Person.h"
int main() {
ChatRoom room;
auto john = room.join(Person{"john"});
auto jane = room.join(Person{"jane"});
john->say("hi room");
jane->say("oh, hey john");
auto simon = room.join(Person{"simon"});
simon->say("hi everyone!");
jane->pm("simon", "glad you could join us, simon");
return 0;
}
|
#ifndef _SORTING_ADT_H
#define _SORTING_ADT_H
#include "bag.h"
namespace cs2420 {
template<typename T>
class SortBy {
public:
SortBy(Bag<T>& bag) : elements(bag) {}
virtual void sort(bool reversed = false) = 0;
protected:
Bag<T>& elements;
virtual int findMinOrMax(int start, int sz, bool reversed){
int result = start;
for(int i = start; i < sz; i++){
if(lessOrGreaterThan(i, result, reversed)){
result = i;
}
}
return result;
}
virtual bool lessOrGreaterThan(int i, int j, bool reversed){
return (reversed && elements[i] > elements[j]) ||
(!reversed && elements[i] < elements[j]);
}
virtual void swap(int i, int j){
T tmp = elements[i];
elements[i] = elements[j];
elements[j] = tmp;
}
};
}
#endif
|
#pragma once
#include <Arduino.h>
class AsyncWebServer;
class AsyncWebServerRequest;
class ESPReactWifiManager
{
public:
ESPReactWifiManager();
struct WifiResult {
String ssid;
uint8_t encryptionType;
int32_t rssi;
uint8_t* bssid;
int32_t channel;
int quality;
bool isHidden = false;
bool duplicate = false;
};
void loop();
void disconnect();
void setHostname(String hostname);
void setApOptions(String apName, String apPassword = String());
void setStaOptions(String ssid, String password = String(), String login = String(), String bssid = String());
bool connect();
bool autoConnect();
bool startAP();
void setFallbackToAp(bool enable);
void setupHandlers(AsyncWebServer *server);
void onFinished(void (*func)(bool)); // arg bool "is AP mode"
void onNotFound(void (*func)(AsyncWebServerRequest*));
void onCaptiveRedirect(bool (*func)(AsyncWebServerRequest*));
void finishConnection(bool apMode);
void scheduleScan(int timeout = 2000);
bool scan();
int size();
std::vector<WifiResult> results();
};
|
#include <Arduino.h>
#include <Ticker.h>
#include <PubSubClient.h>
#include "WifiManagement.h"
const char *ssidWifi = "CG";
const char *passwordWifi = "12ImpEglAnt69";
const char *serveurMqtt = "192.168.10.200";
String nomDevice = "MobilePIR";
String categorieDevice = "Capteurs";
WiFiClient clientWifi;
IPAddress adresseIP;
PubSubClient clientMqtt(clientWifi);
Ticker ticker;
void blink()
{
//Inversion de l'état de la led
int state = digitalRead(LED_BUILTIN); // récupération de son état
digitalWrite(LED_BUILTIN, !state); // on le positionne en opposition d'état
}
void connecterAuServeurMQTT()
{
if (clientMqtt.connect(nomDevice.c_str()))
{
Serial.println("Connected to server");
}
else
Serial.println("I think connection failed!");
}
void envoyerLeMessageMQTT()
{
Serial.println(F("Envoi message MQTT"));
String topic = "Maison/" + categorieDevice + "/" + nomDevice + "/FromObject/State";
if (!clientMqtt.connected())
{
connecterAuServeurMQTT();
}
Serial.println(F("Publication ON"));
clientMqtt.publish(topic.c_str(), "1");
delay(2000);
Serial.println(F("Publication OFF"));
clientMqtt.publish(topic.c_str(), "0");
}
void setup()
{
// Fait clignoter la LED intégré durant la connexion au réseau WiFi - Blink Bleu Led during WiFi connexion
pinMode(LED_BUILTIN, OUTPUT);
ticker.attach(0.5, blink);
Serial.begin(115200);
adresseIP = connectToWifi(ssidWifi, passwordWifi);
clientMqtt.setServer(serveurMqtt, 1883);
envoyerLeMessageMQTT();
Serial.println("Je m'endors");
ticker.detach();
digitalWrite(LED_BUILTIN, LOW);
ESP.deepSleep(0);
}
void loop()
{
}
|
#pragma once
#include <iostream>
#include <ctime>
#include <cstdlib>
enum Parti{
G,D,ED,EG,C,_
};
int rand_a_b(int a, int b);
int max(int nb1,int nb2);
|
int motor_one1=9;
int motor_one2=10;
int motor_two1=5;
int motor_two2=3;
void setup() {
// put your setup code here, to run once:
pinMode(6,INPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,INPUT);
pinMode(5,OUTPUT);
pinMode(3,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int sensorstate1= digitalRead(6);
int sensorstate2= digitalRead(11);
if(sensorstate1==LOW && sensorstate2==LOW)
{analogWrite(9,200);
analogWrite(10,0);
analogWrite(5,200);
analogWrite(3,0);
if(sensorstate1==HIGH && sensorstate2==HIGH)
{analogWrite(9,0);
analogWrite(10,200);
analogWrite(5,0);
analogWrite(3,200);
delay(1000);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(5,0);
analogWrite(3,0);
delay(1500);
{analogWrite(9,0);
analogWrite(10,50);
analogWrite(5,125);
analogWrite(3,0);
}
}
}
}
|
/* print a directory tree
*/
#include <stdio.h>
#include "fat32.h"
#define BDS_ATTR_RO (1<<0) // read only
#define BDS_ATTR_HID (1<<1) // hidden
#define BDS_ATTR_SYS (1<<2) // operating syste,
#define BDS_ATTR_VID (1<<3) // volume id
#define BDS_ATTR_DIR (1<<4) // subdirectory
#define BDS_ATTR_ARC (1<<5) // archive: changed since last backup
void print_attrs(uint8_t attrs)
{
//printf("--"); //unused
putchar(attrs & BDS_ATTR_ARC ? 'A' : '-');
putchar(attrs & BDS_ATTR_VID ? 'V' : '-');
putchar(attrs & BDS_ATTR_SYS ? 'S' : '-');
putchar(attrs & BDS_ATTR_HID ? 'H' : '-');
putchar(attrs & BDS_ATTR_DIR ? 'D' : 'F');
putchar(attrs & BDS_ATTR_RO ? 'R' : 'W');
}
void pindent(int indent)
{
for(int i = 0; i<indent; i++) putchar(' ');
}
void dir_recurse(uint32_t cluster, int indent)
{
bds_t bds;
//Dir dir(cluster);
dir32_t dir;
dir32_init_cluster(&dir, cluster);
while(dir32_read(&dir, &bds)) {
bool isdir = (bds.attr & BDS_ATTR_DIR);
pindent(indent);
printf("%-11.11s %8d %8d ", bds.name, bds.size, bds.fcl);
print_attrs(bds.attr);
puts("");
if(bds.name[0] == '.') continue; // either current or parent dir
if(isdir) {
pindent(indent);
printf("subdir begin: %s\n", bds.name);
dir_recurse(bds.fcl, indent+3);
pindent(indent);
printf("subdir end: %s\n", bds.name);
}
}
}
int main()
{
fat32_init();
dir_recurse(0, 0);
fat32_deinit();
return 0;
}
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/es_pch.h"
#include "modules/ecmascript/carakan/src/builtins/es_builtins.h"
#include "modules/ecmascript/carakan/src/builtins/es_error_builtins.h"
#include "modules/ecmascript/carakan/src/object/es_error_object.h"
/* static */ BOOL
ES_ErrorBuiltins::CommonErrorConstructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value, ES_Class *klass)
{
ES_Object *object;
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
if (argc != 0 && !argv[0].IsUndefined())
{
if (!argv[0].ToString(context))
return FALSE;
object = ES_Error::Make(context, global_object, klass, TRUE);
object->PutCachedAtIndex(ES_PropertyIndex(ES_Error::PROP_message), argv[0].GetString());
}
else
object = ES_Error::Make(context, global_object, klass->GetParent(), TRUE);
return_value->SetObject(object);
return TRUE;
}
/* static */ void
ES_ErrorBuiltins::CommonPopulatePrototype(ES_Context *context, ES_Object *prototype, JString *error_name, BOOL with_empty_message)
{
ES_Value_Internal undefined;
ASSERT_CLASS_SIZE(ES_CommonErrorBuiltins);
APPEND_PROPERTY(ES_CommonErrorBuiltins, constructor, undefined);
APPEND_PROPERTY(ES_CommonErrorBuiltins, name, error_name);
if (with_empty_message)
APPEND_PROPERTY(ES_CommonErrorBuiltins, message, context->rt_data->strings[STRING_empty]);
else
APPEND_PROPERTY(ES_CommonErrorBuiltins, message, undefined);
}
/* static */ void
ES_ErrorBuiltins::CommonPopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class)
{
OP_ASSERT(prototype_class->GetPropertyTable()->Capacity() >= ES_CommonErrorBuiltinsCount);
JString **idents = context->rt_data->idents;
ES_Layout_Info layout;
DECLARE_PROPERTY(ES_CommonErrorBuiltins, constructor, DE | CP, ES_STORAGE_WHATEVER);
DECLARE_PROPERTY(ES_CommonErrorBuiltins, name, DE | CP, ES_STORAGE_STRING);
DECLARE_PROPERTY(ES_CommonErrorBuiltins, message, DE | CP, ES_STORAGE_WHATEVER);
}
/* static */ void
ES_ErrorBuiltins::PopulatePrototype(ES_Context *context, ES_Global_Object *global_object, ES_Object *prototype)
{
ES_Value_Internal undefined;
ASSERT_CLASS_SIZE(ES_ErrorBuiltins);
CommonPopulatePrototype(context, prototype, context->rt_data->idents[ESID_Error], TRUE);
APPEND_PROPERTY(ES_ErrorBuiltins, toString, MAKE_BUILTIN(0, toString));
ASSERT_OBJECT_COUNT(ES_ErrorBuiltins);
}
/* static */ void
ES_ErrorBuiltins::PopulatePrototypeClass(ES_Context *context, ES_Class_Singleton *prototype_class)
{
// OP_ASSERT(prototype_class->GetPropertyTable()->Capacity() >= ES_ErrorBuiltinsCount);
CommonPopulatePrototypeClass(context, prototype_class);
JString **idents = context->rt_data->idents;
ES_Layout_Info layout;
DECLARE_PROPERTY(ES_ErrorBuiltins, toString, DE, ES_STORAGE_OBJECT);
}
/* static */ BOOL
ES_ErrorBuiltins::toString(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
const ES_Value_Internal &this_value = argv[-2];
if (this_value.IsObject())
{
ES_Object *object = this_value.GetObject(context);
JString *error_string = ES_Error::GetErrorString(context, object, TRUE/*allow getter invocations*/);
if (error_string)
{
return_value->SetString(error_string);
return TRUE;
}
else
return FALSE;
}
return_value->SetString(context->rt_data->strings[STRING_empty]);
return TRUE;
}
/* static */ BOOL
ES_ErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetErrorClass());
}
/* static */ BOOL
ES_EvalErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetEvalErrorClass());
}
/* static */ BOOL
ES_RangeErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetRangeErrorClass());
}
/* static */ BOOL
ES_ReferenceErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetReferenceErrorClass());
}
/* static */ BOOL
ES_SyntaxErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetSyntaxErrorClass());
}
/* static */ BOOL
ES_TypeErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetTypeErrorClass());
}
/* static */ BOOL
ES_URIErrorBuiltins::constructor(ES_Execution_Context *context, unsigned argc, ES_Value_Internal *argv, ES_Value_Internal *return_value)
{
ES_Global_Object *global_object = ES_GET_GLOBAL_OBJECT();
return CommonErrorConstructor(context, argc, argv, return_value, global_object->GetURIErrorClass());
}
|
/**********************************************************************************
General Jaw Header file
Has overall class definition and private and public functions
Edited by Ethan Lauer on 2/24/20
*********************************************************************************/
#include<Arduino.h>
class Jaw {
private:
// Servo Pins /// change these based on design of jaw system
int jawLVertPin;
int jawRVertPin;
int jawLHorPin;
int jawRHorPin;
//Servo Type
int servoType = towerpro;
//JAW POSITIONS
int jawLHorBack = 120;
int jawLHorForw = 80;
int jawRHorBack = 60;
int jawRHorForw = 102;
int jawLVertClose = 165;
int jawLVertOpen = 130;
int jawRVertClose = 34;
int jawRVertOpen = 80;
int jawState = 0;
// Timing variables
unsigned long timeNow = 0; //time variable for moving motors without delays
unsigned long timeBtwnEvenTalk = 250; //motor command pulse
unsigned long timeBtwnFastTalk = 150;
// keep track of the previous command for each of the servos
int cmdJawVertL;
int cmdJawVertR;
int cmdJawHorL;
int cmdJawHorR;
boolean initRun = true;
int hingeCycleCount = 0;
int thrustCycleCount = 0;
public:
//**************************************************************INITIALIZE AND SETUP*********************************************************
Jaw() {
}
void setUp() {
jawLVertPin = jawLVert;
jawRVertPin = jawRVert;
jawLHorPin = jawLHor;
jawRHorPin = jawRHor;
servoType = towerpro;
neutralMouth();
Serial.println("Initializing Jaw");
}
//*************************************************************************FUNCTIONS*********************************************************
//***************************************************Basics**************************************
/*
moveLeftVert - move servo to specified degree
int deg - degree you want to move to
*/
void moveLeftVert(int deg) {
driveServo(jawLVertPin, deg, servoType);
}
/*
moveRightVert - move servo to specified degree
int deg - degree you want to move to
*/
void moveRightVert(int deg) {
driveServo(jawRVertPin, deg, servoType);
}
/*
moveLeftHor - move servo to specified degree
int deg - degree you want to move to
*/
void moveLeftHor(int deg) {
driveServo(jawLHorPin, deg, servoType);
}
/*
moveRightHor - move servo to specified degree
int deg - degree you want to move to
*/
void moveRightHor(int deg) {
driveServo(jawRHorPin, deg, servoType);
}
/*
openJawPercent- open the jaw
float percent- floating number of how much you want jaw to be open (ex. open jaw 75%)
*/
void openJawPercent(float percent) {
//calculate the position based on the open and close positions, the given percentage and make into integer
int leftPos = (int) ((jawLVertClose - jawLVertOpen) * (percent / 100));
int rightPos = (int) ((jawRVertOpen - jawRVertClose) * (percent / 100));
//when left jaw servo opens, servo pos is decreasing (the num)
leftPos = jawLVertClose - leftPos;
//when right jaw servo opens, servo pos is increasing (the num)
rightPos = jawRVertClose + rightPos;
//move the left and right jaw servos to the left/right position
moveLeftVert(leftPos);
moveRightVert(rightPos);
}
/* thrustJawPercent -thrust the jaw
float percent - floating percent to thrust (ex. thrust the jaw by 50% of full range of motion)
*/
void thrustJawPercent(float percent) {
//Serial.println(((jawLHorForw-jawLHorBack)*(percent/100)));
//calculate the position based on the fwd and back positions, the given percentage and make into integer
int leftPos = (int) ((jawLHorForw - jawLHorBack) * (percent / 100));
int rightPos = (int) ((jawRHorBack - jawRHorForw) * (percent / 100));
//when left jaw servo moves fwd, servo pos is decreasing (the num)
leftPos = jawLHorBack + leftPos;
//when right jaw servo moves fwd, servo pos is increasing (the num)
rightPos = jawRHorBack - rightPos;
moveLeftHor(leftPos);
moveRightHor(rightPos);
}
//******************************************************************** Setpoints******************************
/*
move the left and right jaw vertical linkages to a neutral position
*/
void neutralMouth() {
openJawPercent(20);
thrustJawPercent(0);
}
/*
close the jaw by moving the left and right vertical jaw servos
*/
void closeMouth() {
openJawPercent(0);
thrustJawPercent(0);
}
/*
move the left and right jaw vertical linkages to a open position
*/
void openMouth() {
openJawPercent(100);
thrustJawPercent(20);
}
//******************************************************************* Dynamic movements******************************************
//***********************************************************MOVING TO SETPOINTS******************************************
/*
openAndClose - open and close jaw quickly by setting to open and closed position
int timeOpen - the pause time for the mouth to stay open
int timeClose - the pause time for the mouth to stay closed
int numCycles - the number of cycles (one cycle = open and close);
return boolean - true if opened and closed the number of times provided
*/
boolean openAndClose(int timeOpen, int timeClose, int numCycles) {
boolean result = false;
if (hingeCycleCount < numCycles) {
switch (jawState) {
case 0: // open jaw
openMouth();
if (millis() > timeNow + timeOpen) {
timeNow = millis();
jawState = 1;
}
break;
case 1: // close jaw
closeMouth();
if (millis() > timeNow + timeClose) {
timeNow = millis();
hingeCycleCount++;
jawState = 0;
}
break;
}
} else {
hingeCycleCount = 0;
result = true;
}
return result;
}
/*
regOpenAndClose - open and close mouth with an even time difference betwen open and closed
*/
void regOpenAndClose() {
openAndClose(timeBtwnEvenTalk, timeBtwnEvenTalk, 3);
}
boolean helloJaw() {
boolean result = false;
result = openAndClose(timeBtwnEvenTalk,timeBtwnEvenTalk, 2);
return result;
}
/*
thrustAndRetract - thrust jaw quickly by setting to thrust fwd pos and back position
int timeFwd - the pause time for the mouth to stay fwd
int timeBack - the pause time for the mouth to stay back
int numCycles - the number of cycles (one cycle = fwd and back);
return boolean - true if thrustAndRetractthe number of times provided
*/
boolean thrustAndRetract(int timeFwd, int timeBack, int numCycles) {
boolean result = false;
if (thrustCycleCount < numCycles) {
switch (jawState) {
case 0: // open jaw
thrustJawPercent(100);
if (millis() > timeNow + timeFwd) {
timeNow = millis();
jawState = 1;
}
break;
case 1: // close jaw
thrustJawPercent(0);
if (millis() > timeNow + timeBack) {
timeNow = millis();
thrustCycleCount++;
jawState = 0;
}
break;
}
} else {
thrustCycleCount = 0;
result = true;
}
return result;
}
//**************************************************************************SLOW MOVENTS (STEPPING)***************************************************
/*
stepVertOpen - step the jawtp opens up slowly.
int degChange - how big of a degree change to move the jaw servos
return boolean - true if both sides of the jaw have stepped to the open position
*/
boolean stepVertOpen(int degChange) {
boolean result = false;
// if initial run, set points to the close position
if (initRun) {
cmdJawVertL = jawLVertClose;
cmdJawVertR = jawRVertClose;
initRun = false;
}
// drive servos
moveLeftVert(cmdJawVertL);
moveRightVert(cmdJawVertR);
// if left and right jaws are not at the open positions
if (cmdJawVertL <= jawLVertOpen && cmdJawVertR >= jawRVertOpen) {
result = true;
} else if (millis() > timeNow + 100) {
if (cmdJawVertL != jawLVertOpen) {
cmdJawVertL -= degChange;
}
if (cmdJawVertR != jawRVertOpen) {
cmdJawVertR += degChange;
}
timeNow = millis();
}
return result;
}
/*
stepVertClose - step the jaw closes slowly.
int degChange - how big of a degree change to move the jaw servos
return boolean - true if both sides of the jaw have stepped to the close position
*/
boolean stepVertClose(int degChange) {
boolean result = false;
if (initRun) {
cmdJawVertL = jawLVertOpen;
cmdJawVertR = jawRVertOpen;
initRun = false;
}
moveLeftVert(cmdJawVertL);
moveRightVert(cmdJawVertR);
if ( cmdJawVertL >= jawLVertClose && cmdJawVertR <= jawRVertClose) {
result = true;
} else if (millis() > timeNow + 100) {
if (cmdJawVertL != jawLVertClose) {
cmdJawVertL += degChange;
}
if (cmdJawVertR != jawRVertClose) {
cmdJawVertR -= degChange;
}
timeNow = millis();
}
return result;
}
/*
stepVertOpenClose- step the jaw open and close and continue to repeat this
int degChange - the degree change for both moving up and down
int numCycles - the number of cycles (one cycle = open and close);
return boolean - true if opened and closed the number of times provided
*/
boolean stepVertOpenClose(int degChange, int numCycles) {
boolean result = false;
boolean isSet = false;
if (hingeCycleCount < numCycles) {
switch (jawState) {
case 0:
Serial.println("opening jaw");
isSet = stepVertOpen(degChange);
if (isSet) {
isSet = false;
jawState = 1;
}
break;
case 1:
Serial.println("closing jaw");
isSet = stepVertClose(degChange);
if (isSet) {
hingeCycleCount++;
isSet = false;
jawState = 0;
}
break;
}
} else {
hingeCycleCount = 0;
result = true;
}
return result;
}
boolean helloJawSlow() {
return stepVertOpenClose(3, 2);
}
};
|
#include <iostream>
#include "vector.hpp"
void Vector::pushBack(int val) {
++m_size;
if(reserve == m_size) {
reserve += 10;
int* newVec = m_vec;
m_vec = new int[reserve];
for(int i =0; i < m_size - 1; ++i) {
m_vec[i] = newVec[i];
}
m_vec[m_size - 1] = val;
delete []newVec;
} else {
m_vec[m_size - 1] = val;
}
}
void Vector::popBack() {
--m_size;
m_vec[m_size] = 0;
}
void Vector::pushFront(int val) {
++m_size;
if(reserve == m_size) {
reserve += 10;
}
int* newVec = m_vec;
m_vec = new int[reserve];
m_vec[0] = val;
for(int i =1; i < m_size; ++i) {
m_vec[i] = newVec[i - 1];
}
delete []newVec;
}
void Vector::popFront() {
--m_size;
int* newVec = m_vec;
m_vec = new int[reserve];
for(int i =0; i < m_size; ++i) {
m_vec[i] = newVec[i + 1];
}
delete []newVec;
}
void Vector::insert(int index, int val) {
if (0 > index || m_size < index) {
std::cout << "Sxal indexi mutqagrum \n";
return;
}
++m_size;
if(reserve != m_size) {
int* newVec = new int[m_size - 1 - index];
for (int i = 0; i < m_size - 1 - index ; ++i) {
newVec[i] = m_vec[i + index];
}
m_vec[index] = val;
for (int i = index + 1; i < m_size; ++i) {
m_vec[i] = newVec[i - 1 - index];
}
delete []newVec;
} else {
int* newVec = m_vec;
m_vec = new int[reserve];
for (int i = 0; i < index; ++i) {
m_vec[i] = newVec[i];
}
m_vec[index] = val;
for (int i = index + 1; i < m_size; ++i) {
m_vec[i] = newVec[i - 1];
}
delete []newVec;
}
}
void Vector::erase(int index) {
if (0 > index || m_size < index) {
std::cout << "Sxal indexi mutqagrum \n";
return;
}
--m_size;
int* newVec = new int[m_size - index];
for (int i = 0; i < m_size - index ; ++i) {
newVec[i] = m_vec[i +1 + index];
}
for (int i = index; i < m_size; ++i) {
m_vec[i] = newVec[i - index];
}
delete []newVec;
}
void Vector::printVector() {
for (int i = 0; i < m_size; ++i) {
std::cout << m_vec[i] << " ";
}
std::cout << std::endl;
}
int Vector::getSize() {
return m_size;
}
int Vector::getVal(int index) {
return m_vec[index];
}
Vector::Vector() {
m_size = 0;
reserve = 10;
m_vec = new int[reserve];
for(int i = 0; i < reserve; ++i) {
m_vec[i] = 0;
}
}
Vector::Vector(int count, int val) {
if (0 < count) {
reserve = count - (count % 10) + 10;
m_vec = new int[reserve];
for (int i = 0; i < count; ++i) {
m_vec[i] = val;
}
m_size = count;
}
}
Vector::Vector(const Vector& obj) {
this->m_size = obj.m_size;
this->reserve = obj.reserve;
this->m_vec = new int[reserve];
for (int i = 0; i < m_size; ++i) {
this->m_vec[i] = obj.m_vec[i];
}
}
Vector::Vector (Vector&& obj) {
this->m_vec = obj.m_vec;
this->reserve = obj.reserve;
this->m_size = obj.m_size;
obj.m_size = 0;
obj.m_vec = nullptr;
}
Vector::~Vector() {
delete []m_vec;
m_vec = nullptr;
}
|
// unordered_set and unordered_map are all based on hash table, which find O(1)
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int> s(nums.begin(), nums.end());
int maxLen = 0;
for (int num : nums) {
if (s.find(num) == s.end()) continue;
int prev = num - 1, next = num + 1;
while (s.find(prev) != s.end()) s.erase(prev--);
while (s.find(next) != s.end()) s.erase(next++);
s.erase(num);
maxLen = max(maxLen, next - prev - 1);
}
return maxLen;
}
};
|
#ifndef APPLICATION_PARSER_H
#define APPLICATION_PARSER_H
#include <string>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string/replace.hpp>
// JSON parser
class Parser {
public:
// Add template value
template <typename T>
void addValue(T& value, const std::string& name) {
tree.put(name, value);
}
// Get template value
template <typename T>
T getValue(const std::string& name) {
return tree.get<T>(name);
}
// Add template array
template <typename T>
void addArray(const std::vector<T>& vector, const std::string& name) {
boost::property_tree::ptree tmpTree;
if (vector.empty())
tmpTree.put("", "[]");
for (const auto& value : vector) {
boost::property_tree::ptree element;
element.put("", value);
tmpTree.push_back(std::make_pair("", element));
}
tree.add_child(name, tmpTree);
};
// Get template array
template <typename T>
std::vector<T> getArray(const std::string& name) {
std::vector<T> result;
for (const auto& value : tree.get_child(name)) {
auto tmpValue = value.second.get_value_optional<T>();
if (tmpValue)
result.push_back(tmpValue.value());
}
return result;
};
// Set JSON string for parsing
void setJson(const std::string& jsonStr);
// Get JSON string
std::string getJson();
// Add JSON str
void addJsonStr(const std::string &json, const std::string &name);
// Add JSON array
void addArrayJsonStr(const std::vector<std::string> &jsonStr, const std::string &name);
// Get JSON str
std::string getJsonStr(const std::string &name);
// Get JSON array
std::vector<std::string> getArrayJsonStr(const std::string& name);
void clear();
private:
boost::property_tree::ptree tree;
};
#endif //APPLICATION_PARSER_H
|
#include "platforms/mac/QuickOperaApp/QuickWidgetApp.h"
#include "platforms/mac/QuickOperaApp/QuickWidgetLibHandler.h"
#include "platforms/mac/QuickOperaApp/CocoaQuickWidgetMenu.h"
#include "platforms/mac/QuickOperaApp/QuickCommandConverter.h"
#include "adjunct/quick/managers/LaunchManager.h"
#ifdef AUTO_UPDATE_SUPPORT
#include "adjunct/autoupdate/updater/auupdater.h"
#endif // AUTO_UPDATE_SUPPORT
#include "platforms/mac/QuickOperaApp/CocoaApplication.h"
Boolean Initialize(int argc, const char** argv);
void BuildStandardMenu();
extern QuickWidgetMenu * gAppleQuickMenu;
extern const char* g_crashaction;
#include "platforms/crashlog/crashlog.h"
#include "platforms/mac/util/systemcapabilities.h"
int main(int argc, const char** argv)
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "int main(%d, {", argc);
for (int i = 0; i<argc; i++) {
if (i)
fprintf(stderr, ", ");
fprintf(stderr, "\"%s\"", argv[i]);
}
fprintf(stderr, "});\n");
#endif
if (argc >= 2 && !strncmp(argv[1], "-autotestmode", 13))
{
g_crashaction = "exit";
}
if (argc >= 3 && !strncmp(argv[1], "-write_crashlog", 15))
{
char crashlog_filename[48];
unsigned long u1, u2;
sscanf(argv[2], "%lu %lu", &u1, &u2);
pid_t pid = u1;
GpuInfo *gpu_info = (GpuInfo *)u2;
WriteCrashlog(pid, gpu_info, crashlog_filename, 48);
if (argc >= 5 && !strncmp(argv[3], "-crashaction", 12) && !strncmp(argv[4], "exit", 4))
return 0;
pid_t fork_pid = fork();
if (!fork_pid)
{
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: in restarting child\n", time(NULL));
#endif
// child process
// give the crashed instance and the crashlogging instance time to exit
usleep(10000);
#ifdef CRASHLOG_DEBUG
fprintf(stderr, "opera [crashlog debug %d]: restarting %s\n", time(NULL), argv[0]);
#endif
// now we restart Opera
execl(argv[0], argv[0], "-crashlog", crashlog_filename, (char *)0);
}
return 0;
}
// Only install the crash handler if this isn't a -crashlog run
if (argc >= 3 && !strncmp(argv[1], "-crashlog", 9))
{
// A restart from a crashlog crash so don't install the crash handler or you will
// be stuck in an endless launch loop
}
else
{
BOOL skip = FALSE;
for (int i = 1; i < argc && !skip; i++)
skip = !strncmp(argv[i], "-nocrashhandler", 16);
if (!skip)
InstallCrashSignalHandler();
}
if (argc >= 3 && !strncmp(argv[1], "-multiproc", 10))
{
// Load the Opera.Framework
CFBundleRef bundle = CFBundleGetMainBundle(), opera_framework_bundle = NULL;
opera_framework_bundle = QuickWidgetLibHandler::LoadOperaFramework(bundle);
// Call the function in the framework to Create the PosixIpcComponentPlatform
if (opera_framework_bundle)
{
typedef int (*RunComponentP)(const char *token);
RunComponentP run_component = (RunComponentP)CFBundleGetFunctionPointerForName(opera_framework_bundle, CFSTR("RunComponent"));
if (run_component)
run_component(argv[2]);
}
}
else
{
#ifdef AUTO_UPDATE_SUPPORT
// Store the command line so if the upgrade is fired at the end it will launch with
// the same command line which can be passed back to Opera when it restarts
// Always skip over the application name
if (argc > 1)
g_launch_manager->SetOriginalArgs(argc - 1, argv + 1);
#endif
#ifdef AUTO_UPDATE_SUPPORT
AUUpdater au_updater;
if (!au_updater.Run())
return 0;
#endif // AUTO_UPDATE_SUPPORT
BuildStandardMenu();
gQuickCommandConverter = new QuickCommandConverter;
gWidgetLibHandler = new QuickWidgetLibHandler(argc, argv);
if (gWidgetLibHandler && gWidgetLibHandler->Initialized())
{
// Commented out as part of fix for bug 210821, Opera window doesn't activate completely
//ProcessSerialNumber psnOpera = {0, kCurrentProcess};
//::SetFrontProcess(&psnOpera);
ApplicationActivate();
if (Initialize(argc, argv))
{
ApplicationRun();
}
}
delete gWidgetLibHandler;
delete gQuickCommandConverter;
delete gAppleQuickMenu;
}
#ifdef AUTO_UPDATE_SUPPORT
// Launch any application waiting to run on exit
g_launch_manager->LaunchOnExitApplication();
g_launch_manager->Destroy();
#endif // AUTO_UPDATE_SUPPORT
return 0;
}
Boolean Initialize(int argc, const char** argv)
{
if (emBrowserNoErr != gWidgetLibHandler->CallStartupQuickMethod(argc, argv))
ExitToShell();
switch (gWidgetLibHandler->CallStartupQuickSecondPhaseMethod(argc, argv))
{
case emBrowserNoErr:
// Nothing to do
break;
case emBrowserExitingErr:
// This is to force a "clean" exit
return false;
default:
ExitToShell();
break;
}
return true;
}
|
#ifndef MOUSECONTROL_H
#define MOUSECONTROL_H
#include <QObject>
#include <QTimer>
#include <opencv2/opencv.hpp>
namespace mouse {
#if defined(__APPLE__)
#include <ApplicationServices/ApplicationServices.h>
#elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
#define _WIN_
#include <windows.h>
#else
#include <X11.h>
#endif
}
using namespace cv;
#ifdef USE_GPU
using namespace cv::cuda;
#endif
#define DEFAULT_MOUSE_ACTION_INTERVAL 500 // ms
#define DEFAULT_MOUSE_SENSITIVITY 5 // frames
#define MOUSE_ACTION_MOVE 1
#define MOUSE_ACTION_DRAG 3
#define MOUSE_ACTION_SINGLE_CLICK 2
#define MOUSE_ACTION_DOUBLE_CLICK 5
#define MOUSE_ACTION_RIGHT_CLICK 4
class MouseController : public QObject
{
Q_OBJECT
signals:
void mouseReleased();
public:
typedef int MouseAction;
MouseController();
~MouseController();
Point estimateCursorPos(const Point & tracked_point);
int makeAction(const int & cursor_pos_x, const int & cursor_pos_y,
const std::vector<Point> & finger_points);
void clearActionFrameCount();
void mouseMove(const int & x, const int & y);
void mouseLeftClick(const int &x, const int &y);
void mouseDoubleClick(const int &x, const int &y);
void mouseDrag(const int &x, const int &y);
void mouseRightClick(const int &x, const int &y);
bool hasReleased();
public slots:
void setActionInterval(const int & interval_in_ms);
void setActionSensitivity(const int & interval_in_frames);
protected slots:
void _releaseMouse();
protected:
KalmanFilter * _kalman_filter = nullptr;
std::vector<int> _action_frame_count{0,0,0,0,0,0};
QTimer * _action_timer; // Timer who counts the interval between two actions
bool _has_released = true; // if mouse button has been released
int _action_interval = DEFAULT_MOUSE_ACTION_INTERVAL;
int _action_sensitivity = DEFAULT_MOUSE_SENSITIVITY;
std::pair<int,int> _last_drag_pos; // last pos of drag action, used to release mouse left button
};
#endif // MOUSECONTROL_H
|
#include <ros/ros.h>
#include <std_msgs/Float64.h>
#include <std_msgs/String.h>
#include <cloudSegmentation/objects.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/filters/statistical_outlier_removal.h>
#include <pcl/io/pcd_io.h>
#include <pcl_conversions/pcl_conversions.h>
#include "util.h"
class ShowObjects
{
private:
pcl::PCDReader reader;
pcl::visualization::CloudViewer viewer;
Parameter parameter;
std::string workingPath;
//std::string cloudPath;
//pcl::PCLPointCloud2 inputCloud;
cloudSegmentation::objects obj;
public:
ShowObjects (std::string workingPath) : viewer("Object Viewer")
{
this->workingPath = workingPath;
this->viewer.registerKeyboardCallback(keyboardEventOccurred, (void*)¶meter);
}
void CloudCallback (const cloudSegmentation::objects::ConstPtr& input)
{
if (!viewer.wasStopped())
{
obj = *input;
parameter.maxCount = input->Count;
//cloudPath = objectPath->Path;
parameter.count=0;
parameter.change = true;
}
}
void run ()
{
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe<cloudSegmentation::objects>("recognized_objects", 1, &ShowObjects::CloudCallback, this);
pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZRGBA>());
ros::Publisher pub = nh.advertise<sensor_msgs::PointCloud2>("object_cloud", 1);
std_msgs::String objPath;
int idx=0,helpIdx=0;
ros::Rate loop_rate(10);
while (!viewer.wasStopped() && !parameter.stop)
{
if(parameter.change){
// Cloud File einlesen
/*std::stringstream path;
path << cloudPath << "object_" <<parameter.count<<".pcd";
reader.read(path.str(),*cloud);*/
pcl::fromROSMsg(obj.Objects[parameter.count], *cloud);
std::cout << "PointCloud besteht aus: " << cloud->points.size () << " Punkten." << std::endl;
viewer.showCloud(cloud);
parameter.change = false;
//objPath.data = path.str();
}
if(parameter.send)
{
pub.publish(obj.Objects[parameter.count]);
parameter.send = false;
}
ros::spinOnce();
loop_rate.sleep();
}
}
};
int main (int argc, char** argv)
{
ros::init (argc, argv, "ShowObjects");
ShowObjects cloudGrabber(argv[0]);
cloudGrabber.run();
return 0;
}
|
/*
* forward.cpp
*
* Created on: May 19, 2016
* Author: bakhvalo
*/
#include "gtest/gtest.h"
#include <type_traits>
namespace
{
class testMoves
{
public:
testMoves() {}
testMoves(const testMoves&) { x = 1;}
testMoves& operator=(const testMoves&) { x = 2; return *this; }
testMoves(testMoves&&) { x = 3;}
testMoves& operator=(testMoves&&) { x = 4; return *this; }
~testMoves() {}
int x {0};
};
template <typename T>
void callWithRvalue(T && uref)
{
testMoves moveObj = std::forward<T>(uref);
ASSERT_EQ(3, moveObj.x);
}
template <typename T>
void callWithLvalue(T && uref)
{
testMoves copyObj = std::forward<T>(uref);
ASSERT_EQ(1, copyObj.x);
}
}
TEST(ForwardUnitTest, forward_produce_rvalue_or_lvalue_ref_based_on_a_param)
{
int x = 1;
static_assert( std::is_same< decltype(std::forward<int>(7)), int&&>::value, "types are not the same" );
static_assert( std::is_same< decltype(std::forward<int>(x)), int&&>::value, "types are not the same" );
testMoves obj;
callWithLvalue(obj);
callWithRvalue(std::move(obj));
}
namespace
{
template<typename T>
T&& Myforward(std::remove_reference_t<T>& param)
{
return static_cast<T&&>(param);
}
template <typename T>
void callWithRvalueWithMyforward(T && uref)
{
testMoves moveObj = std::forward<T>(uref);
ASSERT_EQ(3, moveObj.x);
}
template <typename T>
void callWithLvalueWithMyforward(T && uref)
{
testMoves copyObj = std::forward<T>(uref);
ASSERT_EQ(1, copyObj.x);
}
}
TEST(ForwardUnitTest, check_my_forward_version)
{
int x = 1;
// not compiles: can't convert int to int&
//static_assert( std::is_same< decltype(Myforward<int>(7)), int&&>::value, "types are not the same" );
static_assert( std::is_same< decltype(Myforward<int>(x)), int&&>::value, "types are not the same" );
testMoves obj;
callWithLvalueWithMyforward(obj);
callWithRvalueWithMyforward(std::move(obj));
}
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
vector<string> PalindromFilter (vector<string> words, unsigned long minLength)
{
vector<string> Result;
string buffer;
for (auto x : words)
{
buffer = x;
reverse(buffer.begin(), buffer.end());
if (buffer == x && buffer.size() >= minLength) Result.push_back(buffer);
}
return Result;
}
int main()
{
vector<string> Input;
string buffer1;
unsigned long minLength;
cout << "Введите минимальную длину слова" << endl;
cin >> minLength;
cout << "Введите слова. По окончанию ввода введите 0" << endl;
while (true)
{
cin >> buffer1;
if (buffer1 != "0") {
Input.push_back(buffer1);
buffer1.clear();
}
else break;
}
vector<string> Result = PalindromFilter( Input, minLength);
for (auto x : Result)
{
cout << x << endl;
}
return 0;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
using namespace std;
class Solution {
public:
int fourSumCount(vector<int>& A, vector<int>& B, vector<int>& C, vector<int>& D) {
//基本思想:哈希表,典型的空间换时间,将四重循环转化为两重循环
//用哈表表存储AB中元素之和出现的次数,如果CD中元素和的相反数在哈希表中出现,说明ABCD组合为0
int res=0;
unordered_map<int,int> Map;
for(auto a:A)
{
for(auto b:B)
Map[a+b]++;
}
for(auto c:C)
{
for(auto d:D)
res+=Map[-(c+d)];
}
return res;
}
};
int main()
{
Solution solute;
vector<int> A={1, 2},B = {-2,-1},C = {-1, 2},D = { 0, 2};
cout<<solute.fourSumCount(A,B,C,D)<<endl;
return 0;
}
|
#ifndef _CDLSocketHandler_H_
#define _CDLSocketHandler_H_
#include "cache.h"
#include "CDL_Decoder.h"
#include "CDL_TCP_Handler.h"
#include "CDL_Timer_Handler.h"
using namespace comm::sockcommu;
#define MAX_WEB_RECV_LEN 10240
#define MAX_SEQ_LEN 512
enum CConnState
{
CONN_IDLE,
CONN_FATAL_ERROR,
CONN_DATA_ERROR,
CONN_CONNECTING,
CONN_DISCONNECT,
CONN_CONNECTED,
CONN_DATA_SENDING,
CONN_DATA_RECVING,
CONN_SEND_DONE,
CONN_RECV_DONE,
CONN_APPEND_SENDING,
CONN_APPEND_DONE,
CONN_DECODE_NULL1,
CONN_DECODE_NULL2,
CONN_XML_POLICY,
CONN_COLSE_CONNECT,
};
// class CDLSocketHandler;
// class CSocketErrorTimer : public CCTimer
// {
// public:
// CSocketErrorTimer() {}
// ~CSocketErrorTimer() {}
//
// void startErrorTimer(CDLSocketHandler *handle);
//
// virtual int ProcessOnTimerOut();
//
// private:
// CDLSocketHandler *m_handle;
// };
class CDLSocketHandler : public CDL_TCP_Handler
{
public:
CDLSocketHandler();
virtual ~CDLSocketHandler();
public:
virtual int Init();
virtual int InputNotify();
virtual int OutputNotify ();
virtual int HangupNotify ();
virtual int OnClose();
/*
>=0 : 成功
<0 : 网络失败,可以close
*/
virtual int Send(const char * buff, int len);
void CloseConnect();
class PacketListener
{
public:
virtual ~PacketListener() {}
virtual bool OnPacketCompleteEx(const char* data, int len) = 0;
};
void setPacketListener(PacketListener* listener) { _packetListener = listener; }
protected:
virtual int OnConnected() ;
virtual int OnPacketComplete(const char * data, int len);
virtual CDL_Decoder* CreateDecoder()=0;
private:
int handle_input();
int handle_output();
void Reset();
bool _bclose;
CDL_Decoder* _decode;
CConnState _stage;
CRawCache _r;
CRawCache _w;
PacketListener* _packetListener;
};
#endif
|
#include "add_feature.h" // import file to test
#include <cmath>
#include "linalg.h"
#include "ut.hpp"
using namespace boost::ut;
using namespace boost::ut::bdd;
int main() {
"add feature"_test = [] {
given(
"A particle with three known features and vehicle position "
"{1,1,acos(4/5)}) " // the angle is so that we can have a triangle with 3,4,5 side lengths for the landmark
"and two features at {1,3} and {5,4} in local coordinates") = [] {
/* y
* | F2 (1,3)
* | | F1 (5,4)
* | | 5____/|
* | | ____/ | 3
* | | /__________|
* | R(1,1) 4 // Robot R points straight at F1
* ------------------------x
*/
Particle p;
double xv_initial[3] = {0,0,0};
initParticle(&p, 10, xv_initial);
Vector3d pos = {1., 1., acos(4. / 5.)};
copy(pos, 3, p.xv);
p.Nfa = 3;
Vector2d landmarks[2] = {
{5, 0}, {2, M_PI / 2 - acos(4. / 5.)}}; // local robot frame
Matrix2d R __attribute__((aligned(32))) =
{pow(0.1, 2), 0,
0, pow(1.0 * M_PI / 180, 2)}; // this is from the yglee config
when("I add the new features to the particle") = [&]() mutable {
add_feature(&p, landmarks, 2, R);
then("I expect there to be feature means at (1,3) and (5,4)") = [&] {
"F1"_test = [&] {
expect(that % fabs(p.xf[2 * 3 + 0] - 5) < 1e-14) << "F1 - distance";
expect(that % fabs(p.xf[2 * 3 + 1] - 4) < 1e-14) << "F1 - angle";
};
"F2"_test = [&] {
expect(that % fabs(p.xf[2 * 4 + 0] - 1) < 1e-14) << "F2 - distance";
expect(that % fabs(p.xf[2 * 4 + 1] - 3) < 1e-14) << "F2 - angle";
};
};
then(
"I expect there to be two more features and the same number of max "
"features") = [&] {
"Nfa"_test = [&] {
expect(that % p.Nfa == 3 + 2) << "number of actual features";
expect(that % p.Nf == 10) << "number of max features";
};
};
};
delParticleMembers(&p);
};
};
}
|
#include "storage.h"
Storage::Storage(QObject *parent) {
}
Storage::~Storage() {
file.close();
}
void Storage::writeHeader(int height, int width, int colorMode, int bytesPerFrame) {
QString path = "d:\\work\\";
QString filename = QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
QString extension = ".msr";
file.setFileName(path + filename + extension);
qDebug() << "open file" << file.open(QIODevice::WriteOnly | QIODevice::Append);
if(file.isOpen()) {
file.write((const char*) &colorMode, sizeof(int));
file.write((const char*) &bytesPerFrame, sizeof(int));
file.write((const char*) &height, sizeof(int));
file.write((const char*) &width, sizeof(int));
}
else
qDebug() << "storage: cant write, file not open";
}
//appends a buffer to a dump file, this needs error checking since
//we won't know, when we are losing frames
void Storage::saveBuffer(char *buf, int bytesPerFrame, int numberOfFrames, ULongLongVector timestamps) {
if(file.isOpen()) {
QTime timer;
timer.start();
for(int i=0; i<numberOfFrames; i++) {
unsigned long long timestamp = timestamps.at(i);
file.write((const char*) ×tamp, sizeof(unsigned long long));
file.write(buf+i*bytesPerFrame, bytesPerFrame); //this can't be right
}
qDebug() << "done writing, elapsed time:" << timer.elapsed() << "ms";
}
else
qDebug() << "storage: cant write, file not open";
}
void Storage::finalize() {
file.close();
}
|
#include <ionir/misc/inst_builder.h>
#include <ionir/passes/pass.h>
namespace ionir {
BasicBlock::BasicBlock(const BasicBlockOpts &opts) :
ConstructWithParent(opts.parent, ConstructKind::BasicBlock),
ScopeAnchor<Inst>(opts.symbolTable),
Named{opts.id},
basicBlockKind(opts.kind),
insts(opts.insts) {
//
}
void BasicBlock::accept(Pass &visitor) {
// TODO: Casting fails. CRITICAL: This needs to work! LlvmCodegen's contextBuffer depends on it.
// visitor.visitScopeAnchor(this->dynamicCast<ScopeAnchor<>>());
visitor.visitBasicBlock(this->dynamicCast<BasicBlock>());
}
Ast BasicBlock::getChildrenNodes() {
return Construct::convertChildren(this->insts);
}
bool BasicBlock::verify() {
return this->hasTerminalInst()
&& ionshared::util::hasValue(this->parent)
&& Construct::verify();
}
void BasicBlock::insertInst(uint32_t order, const ionshared::Ptr<Inst> &inst) {
const uint32_t maxOrder = this->insts.empty() ? 0 : this->insts.size() - 1;
if (order > maxOrder) {
throw std::out_of_range("Order is larger than the size of elements in the vector");
}
this->insts.insert(this->insts.begin() + order, inst);
// TODO: --- Repeated code below (appendInst). Simplify? Maybe create registerInst() function? ---
const std::optional<std::string> id = util::findInstId(inst);
// Instruction is named. Register it in the symbol table.
if (id.has_value()) {
this->getSymbolTable()->set(*id, inst);
}
// ----------------------------------------------------------
}
void BasicBlock::appendInst(const ionshared::Ptr<Inst> &inst) {
this->insts.push_back(inst);
std::optional<std::string> id = util::findInstId(inst);
// Instruction is named. Register it in the symbol table.
if (id.has_value()) {
this->getSymbolTable()->set(*id, inst);
}
}
void BasicBlock::prependInst(const ionshared::Ptr<Inst> &inst) {
this->insertInst(0, inst);
}
uint32_t BasicBlock::relocateInsts(BasicBlock &target, const uint32_t from) {
uint32_t count = 0;
for (uint32_t i = from; i < this->insts.size(); i++) {
target.insts.push_back(this->insts[i]);
this->insts.erase(this->insts.begin() + i - 1);
count++;
}
return count;
}
ionshared::Ptr<BasicBlock> BasicBlock::split(uint32_t atOrder, std::string id) {
// TODO: If insts are empty, atOrder parameter is ignored (useless). Address that.
// TODO: Symbol table is not being relocated/split.
if (!this->insts.empty() && (atOrder < 0 || atOrder > this->insts.size() - 1)) {
throw std::out_of_range("Provided order is outsize of bounds");
}
std::vector<ionshared::Ptr<Inst>> insts = {};
if (!this->insts.empty()) {
auto from = this->insts.begin() + atOrder;
auto to = this->insts.end();
insts = std::vector<ionshared::Ptr<Inst>>(from, to);
// Erase the instructions from the local basic block.
this->insts.erase(from, to);
}
ionshared::Ptr<BasicBlock> newBasicBlock = std::make_shared<BasicBlock>(BasicBlockOpts{
this->getUnboxedParent(),
this->basicBlockKind,
std::move(id),
insts
});
/**
* Register the newly created basic block on the parent's
* symbol table (parent is a function body).
*/
this->getUnboxedParent()->insertBasicBlock(newBasicBlock);
return newBasicBlock;
}
ionshared::Ptr<JumpInst> BasicBlock::link(const ionshared::Ptr<BasicBlock> &basicBlock) {
return this->createBuilder()->createJump(basicBlock);
}
std::optional<uint32_t> BasicBlock::locate(ionshared::Ptr<Inst> inst) {
return ionshared::util::locateInVector(this->insts, std::move(inst));
}
ionshared::OptPtr<Inst> BasicBlock::findInstByOrder(uint32_t order) const noexcept {
/**
* Provided order is larger than the amount of elements in the
* insts vector. No need to continue, return std::nullopt.
*/
if (this->insts.empty() || this->insts.size() < order + 1) {
return std::nullopt;
}
return this->insts[order];
}
ionshared::Ptr<InstBuilder> BasicBlock::createBuilder() {
return std::make_shared<InstBuilder>(this->dynamicCast<BasicBlock>());
}
ionshared::OptPtr<Inst> BasicBlock::findTerminalInst() const noexcept {
// TODO: There can only be a single return instruction.
for (const auto &inst : this->insts) {
if (inst->isTerminal()) {
return inst;
}
}
return std::nullopt;
}
bool BasicBlock::hasTerminalInst() const noexcept {
return ionshared::util::hasValue(this->findTerminalInst());
}
ionshared::OptPtr<Inst> BasicBlock::findFirstInst() noexcept {
if (!this->insts.empty()) {
return this->insts.front();
}
return std::nullopt;
}
ionshared::OptPtr<Inst> BasicBlock::findLastInst() noexcept {
if (!this->insts.empty()) {
return this->insts.back();
}
return std::nullopt;
}
}
|
#include "_pch.h"
#include "wxDataViewRenderer.h"
// -------------------------------------
// wxDataViewChoiceRenderer
// -------------------------------------
IMPLEMENT_CLASS(wxDataViewChoiceRenderer2, wxDataViewCustomRenderer)
wxDataViewChoiceRenderer2::wxDataViewChoiceRenderer2( const wxArrayString& choices, wxDataViewCellMode mode, int alignment )
:wxDataViewCustomRenderer(wxT("string"), mode, alignment )
{
m_choices = choices;
}
wxControl* wxDataViewChoiceRenderer2::CreateEditorCtrl( wxWindow *parent, wxRect labelRect, const wxVariant &value )
{
wxPoint pt=labelRect.GetTopLeft();
wxSize sz=labelRect.GetSize();
wxSize szfont=parent->GetFont().GetPixelSize();
if( (sz.y-szfont.y)<8 )
{
pt.y -= (szfont.y+8 - sz.y)/2;
sz.y=szfont.y+8+1;
}
wxChoice* c = new wxChoice(parent, wxID_ANY,pt ,sz , m_choices );
c->SetStringSelection( value.GetString() );
return c;
}
bool wxDataViewChoiceRenderer2::GetValueFromEditorCtrl( wxControl* editor, wxVariant &value )
{
wxChoice *c = (wxChoice*) editor;
wxString s = c->GetStringSelection();
value = s;
return true;
}
bool wxDataViewChoiceRenderer2::Render( wxRect rect, wxDC *dc, int state )
{
RenderText( m_data, 0, rect, dc, state );
return true;
}
wxSize wxDataViewChoiceRenderer2::GetSize() const
{
return wxSize(80,16);
}
bool wxDataViewChoiceRenderer2::SetValue( const wxVariant &value )
{
m_data = value.GetString();
return true;
}
bool wxDataViewChoiceRenderer2::GetValue( wxVariant &value ) const
{
value = m_data;
return false;
}
// -------------------------------------
// wxDataViewComboRenderer
// -------------------------------------
IMPLEMENT_CLASS(wxDataViewComboRenderer, wxDataViewTextRenderer)
wxDataViewComboRenderer::wxDataViewComboRenderer( wxDataViewCellMode mode, int alignment )
//:wxDataViewCustomRenderer(wxT("string"), mode, alignment )
:wxDataViewTextRenderer(wxT("string"), mode, alignment),m_Dlg(NULL)
{
}
wxControl* wxDataViewComboRenderer::CreateEditorCtrl( wxWindow *parent, wxRect labelRect, const wxVariant &value )
{
wxPoint pt=labelRect.GetTopLeft();
wxSize sz=labelRect.GetSize();
wxSize szfont=parent->GetFont().GetPixelSize();
if( (sz.y-szfont.y)<8 )
{
pt.y -= (szfont.y+8 - sz.y)/2;
sz.y=szfont.y+8+1;
}
//wxTextCtrl* c = new wxTextCtrl( parent, wxID_ANY, value,pt ,sz,wxTE_PROCESS_ENTER);
wxTextCtrlWithBtn* c = new wxTextCtrlWithBtn( parent, wxID_ANY, value, pt ,sz,wxTE_PROCESS_ENTER );
wxPoint pos=parent->GetScreenPosition () ;
pos.x+= labelRect.x;
pos.y+= labelRect.height* wxPtrToUInt(m_item);
if(m_Dlg)
m_Dlg->SetPosition(pos);
c->SetDialogPtr(m_Dlg);
c->SetInsertionPointEnd();
c->SelectAll();
return c;
}
|
// Name : Angel E Hernandez
// Date : April 17
// CIS 1202.800
// Project name : Inheritance
#pragma once
#include <iostream>
#include "Car.h"
using namespace std;
void Car::displayInfo()
{
string manufact;
int vYear;
int numDoors;
// prompt user to enter information
cout << "Car: \n";
cout << "Enter the manufacturer: ";
cin.ignore();
getline(cin, manufact);
cout << "Enter the year built: ";
cin >> vYear;
cout << "Enter the number of doors: ";
cin >> numDoors;
// define a vehicle object
Car car(manufact, vYear, numDoors);
// display information
cout << "Vehicle information: \n";
cout << "Manufacturer: " << car.getManufacturer() << endl;
cout << "Year Buil: " << car.getYear() << endl;
cout << "Doors: " << car.getDoors() << endl;
cout << endl;
}
|
#include <iostream>
using std::cout;
class A{
public:
A(){ cout << "I am constructor of A.\n"; }
};
class B{
public:
B(){ cout << "I am constructor of B.\n"; }
};
class C{
A obj_a;
B obj_b;
};
int main(){
C cx;
}
|
/*
* Copyright (c) 2014-2017 Detlef Vollmann, vollmann engineering gmbh
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
#ifndef CAIROMOCK_HH_SEEN_
#define CAIROMOCK_HH_SEEN_
#include "trompeloeil.hpp"
#include "graphmock.hh"
namespace exerciseTest
{
class CairoWrap
{
public:
CairoWrap()
{
curObj = this;
}
virtual ~CairoWrap()
{
curObj = &defaultObj;
}
virtual cairo_surface_t *cairo_xlib_surface_create(
Display *
, Drawable
, Visual *
, int /*width*/
, int /*height*/)
{
return &s;
}
virtual cairo_surface_t *cairo_win32_surface_create(HDC)
{
return &s;
}
virtual void cairo_surface_destroy(cairo_surface_t *)
{
}
virtual cairo_t *cairo_create(cairo_surface_t *)
{
return &cr;
}
virtual void cairo_destroy(cairo_t *)
{
}
virtual void cairo_show_text(cairo_t *, char const *)
{
}
static CairoWrap &getCurrent()
{
return *curObj;
}
private:
static CairoWrap defaultObj;
static CairoWrap *curObj;
cairo_surface_t s;
cairo_t cr;
};
struct CairoMock : public CairoWrap
{
MAKE_MOCK5(cairo_xlib_surface_create, cairo_surface_t*(
Display *, Drawable, Visual *
, int, int));
MAKE_MOCK1(cairo_win32_surface_create, cairo_surface_t *(HDC));
MAKE_MOCK1(cairo_surface_destroy, void(cairo_surface_t *));
MAKE_MOCK1(cairo_create, cairo_t*(cairo_surface_t *));
MAKE_MOCK1(cairo_destroy, void(cairo_t *));
MAKE_MOCK2(cairo_show_text, void(cairo_t *, char const *));
};
} // namespace exerciseTest
#endif /* CAIROMOCK_HH_SEEN_ */
|
#include <iostream>
namespace mylib {
template<typename T>
class allocator {
public:
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using const_pointer = T const*;
using reference = T&;
using const_reference = const T&;
using value_type = T;
template<typename U>
struct rebind { using other = allocator<U>; };
// or
// template<typename U>
// using other = allocator<U>;
allocator() noexcept;
allocator(allocator const&) noexcept;
template<typename U>
allocator(allocator<U> const&) noexcept;
~allocator();
pointer address(reference x) const noexcept;
const_pointer address(const_reference x) const noexcept;
pointer allocate(size_type n, void const* hint = 0);
void deallocate(pointer p, size_type n);
size_type max_size() const noexcept;
template<typename U, typename... Args>
void construct(U* p, Args&&... args);
template<typename U>
void destroy(U* p);
};
template<typename T>
allocator<T>::allocator() noexcept {}
template<typename T>
allocator<T>::allocator(allocator<T> const&) noexcept{}
template<typename T>
template<typename U>
allocator<T>::allocator(allocator<U> const&) noexcept {}
template<typename T>
allocator<T>::~allocator() {}
template<typename A>
struct allocator_traits {
using allocator_type = A;
using value_type = typename A::value_type;
using pointer = typename A::pointer;
using const_pointer = Pointer_traits<pointer>::rebind<value_type const>;
using void_pointer = Pointer_traits<pointer>::rebind<void>;
using const_void_pointer = Pointer_traits<pointer>::rebind<void const>;
using difference_type = Pointer_traits<pointer>::difference_type;
using size_type = Make_unsigned<difference_type>;
using propogate_on_container_copy_assingment = std::false_type;
using propogate_on_container_move_assignment = std::false_type;
using propogate_on_container_swap = std::false_type;
};
template<typename P>
struct pointer_traits {
using pointer = P;
using element_type = T;
};
template<typename OuterA, typename... InnerA>
struct scoped_allocator_adaptor : public OuterA {
using Tr = allocator_traits<OuterA>;
using outer_allocator_type = OuterA;
// using inner_allocator_type =
using value_type = typename Tr::value_type;
using size_type = typename Tr::size_type;
using difference_type = typename Tr::difference_type;
using pointer = typename Tr::pointer;
using const_pointer = typename Tr:const_pointer;
using void_pointer = typename tr::void_pointer;
using const_void_pointer = typename Tr::void_pointer;
using propogate_on_container_copy_assingment = typename Tr::const_void_pointer;
// and more
};
}
int main() {
mylib::allocator<int> alloc_ints;
return 0;
}
|
#include "stubs.hpp"
// Definicoes de metodo da classe stub do controlador da logica de negocio de autenticacao.
bool StubSAutenticacao::autenticar(const Email &email, const Senha &senha, Usuario *current_user) throw(runtime_error) {
// Apresentar dados recebidos.
cout << endl << "StubSAutenticacao::autenticar" << endl ;
cout << "Email = " << email.getValor() << endl ;
cout << "Senha = " << senha.getValor() << endl ;
// Diferentes comportamentos dependendo do valor do email.
if (email.getValor() == TRIGGER_FALHA) {
current_user = NULL;
return false;
} else if (email.getValor() == TRIGGER_ERRO_SISTEMA) {
current_user = NULL;
throw runtime_error("Erro de sistema!");
}
// Simula usuario encontrado na base de dados
current_user->setCpf("591.581.540-51");
current_user->setEmail(email.getValor());
current_user->setNome("Jurandismar");
current_user->setSenha(senha.getValor());
current_user->setTelefone("55-61-999999999");
return true;
}
bool StubSUsuario::cadastrar(Usuario &usuario, Conta &conta) throw(runtime_error) {
// Apresentar dados recebidos.
cout << endl << "StubSUsuario::cadastrar" << endl ;
cout << "Nome = " << usuario.getNome().getValor() << endl ;
if(usuario.getNome().getValor() == TRIGGER_FALHA_CAD) {
return false;
} else if (usuario.getNome().getValor() == TRIGGER_ERRO_SISTEMA_CAD) {
throw runtime_error("Erro de sistema!");
}
return true;
}
bool StubSUsuario::excluir(Usuario &usuario) throw(runtime_error) {
// Apresentar dados recebidos.
if (usuario.getEmail().getValor() == TRIGGER_FALHA_EXC) {
return false;
} else if (usuario.getEmail().getValor() == TRIGGER_ERRO_SISTEMA_EXC) {
throw runtime_error("Erro de sistema!");
}
return true;
}
bool StubSCarona::cadastrar(Carona &carona, Usuario &usuario) throw(runtime_error) {
//Apresentar dados recebidos
cout << endl << "StubSCarona::cadastrar" << endl ;
cout << "Nome = " << carona.getCodigo_de_carona().getValor() << endl ;
if(carona.getCodigo_de_carona().getValor() == TRIGGER_FALHA_CAD) {
return false;
} else if (carona.getCodigo_de_carona().getValor() == TRIGGER_ERRO_SISTEMA_CAD) {
throw runtime_error("Erro de sistema!");
}
return true;
}
bool StubSCarona::pesquisar(Carona &carona, vector<Carona> *caronas, vector<Usuario> *motoristas) throw(runtime_error) {
//Apresentar dados recebidos
if (carona.getCidadeOrigem().getValor() == TRIGGER_FALHA_PES) {
return false;
} else if (carona.getCidadeOrigem().getValor() == TRIGGER_ERRO_SISTEMA_PES) {
throw runtime_error("Erro de sistema!");
}
// Simula motoristas de caronas
Usuario m1;
m1.setCpf("591.581.540-51");
m1.setEmail("juris@uvt.com");
m1.setNome("Jurandismar");
m1.setSenha("S3nh4");
m1.setTelefone("55-61-999999999");
motoristas->push_back(m1);
Usuario m2;
m2.setCpf("608.596.560-55");
m2.setEmail("hermenegildo@uvt.com");
m2.setNome("Hermenegildo");
m2.setSenha("P3ixe");
m2.setTelefone("55-61-555555555");
motoristas->push_back(m2);
// Simula caronas
Carona c1;
c1.setCodigo_de_carona("0123");
c1.setCidade_origem(carona.getCidadeOrigem().getValor());
c1.setCidade_destino(carona.getCidadedestino().getValor());
c1.setEstado_origem(carona.getEstado_origem().getValor());
c1.setEstado_destino(carona.getEstado_destino().getValor());
c1.setData(carona.getData().getValor());
c1.setVagas("3");
c1.setDuracao("22");
c1.setPreco("550,00");
caronas->push_back(c1);
Carona c2;
c2.setCodigo_de_carona("4735");
c2.setCidade_origem(carona.getCidadeOrigem().getValor());
c2.setCidade_destino(carona.getCidadedestino().getValor());
c2.setEstado_origem(carona.getEstado_origem().getValor());
c2.setEstado_destino(carona.getEstado_destino().getValor());
c2.setData(carona.getData().getValor());
c2.setVagas("4");
c2.setDuracao("48");
c2.setPreco("360,99");
caronas->push_back(c2);
return true;
}
bool StubSCarona::reservar(Reserva *reserva, Codigo_de_carona &codCarona, Usuario &usuario, Conta *conta_motorista) throw(runtime_error) {
//Apresentar dados recebidos
if (codCarona.getValor() == TRIGGER_FALHA_RES) {
return false;
} else if (codCarona.getValor() == TRIGGER_ERRO_SISTEMA_RES) {
throw runtime_error("Erro de sistema!");
}
// Simula geração de codigo de carona
reserva->setCodigo_de_reserva("12345");
// Simula conta do motorista
conta_motorista->setCodigo_de_banco("123");
conta_motorista->setNumero_de_agencia("7992-1");
conta_motorista->setNumero_de_conta("799273-8");
return true;
}
bool StubSCarona::pesquisarReservas(Codigo_de_carona &codCarona, vector<Reserva> *reservas, vector<Usuario> *passageiros) throw(runtime_error) {
//Apresentar dados recebidos
if (codCarona.getValor() == TRIGGER_FALHA_RES) {
return false;
} else if (codCarona.getValor() == TRIGGER_ERRO_SISTEMA_RES) {
throw runtime_error("Erro de sistema!");
}
// Simula motoristas de caronas
Usuario p1;
p1.setCpf("591.581.540-51");
p1.setEmail("seynon@uvt.com");
p1.setNome("Seynon");
p1.setSenha("S3nh4");
p1.setTelefone("55-61-111111111");
passageiros->push_back(p1);
Usuario p2;
p2.setCpf("608.596.560-55");
p2.setEmail("hermenegildo@uvt.com");
p2.setNome("Hermenegildo");
p2.setSenha("P3ixe");
p2.setTelefone("55-61-555555555");
passageiros->push_back(p2);
// Simula reservas
Reserva r1;
r1.setAssento("T");
r1.setBagagem("1");
r1.setCodigo_de_reserva("12345");
reservas->push_back(r1);
Reserva r2;
r2.setAssento("D");
r2.setBagagem("3");
r2.setCodigo_de_reserva("54321");
reservas->push_back(r2);
return true;
}
bool StubSCarona::cancelar(Codigo_de_reserva &codReserva, Usuario ¤t_user) throw(runtime_error) {
//Apresentar dados recebidos
cout << endl << "StubSCarona::cancelar" << endl ;
cout << "Nome = " << codReserva.getValor() << endl ;
if(codReserva.getValor() == TRIGGER_FALHA_CAN) {
return false;
} else if (codReserva.getValor() == TRIGGER_ERRO_SISTEMA_CAN) {
throw runtime_error("Erro de sistema!");
}
return true;
}
bool StubSCarona::excluir(Codigo_de_carona &codigo, Usuario ¤t_user) throw(runtime_error) {
//Apresentar dados recebidos
cout << endl << "StubSCarona::excluir" << endl ;
cout << "Nome = " << codigo.getValor() << endl ;
if(codigo.getValor() == TRIGGER_FALHA_DEL) {
return false;
} else if (codigo.getValor() == TRIGGER_ERRO_SISTEMA_DEL) {
throw runtime_error("Erro de sistema!");
}
return true;
}
|
// (C) 1992-2016 Intel Corporation.
// Intel, the Intel logo, Intel, MegaCore, NIOS II, Quartus and TalkBack words
// and logos are trademarks of Intel Corporation or its subsidiaries in the U.S.
// and/or other countries. Other marks and brands may be claimed as the property
// of others. See Trademarks on intel.com for full list of Intel trademarks or
// the Trademarks & Brands Names Database (if Intel) or See www.Intel.com/legal (if Altera)
// Your use of Intel Corporation's design tools, logic functions and other
// software and tools, and its AMPP partner logic functions, and any output
// files any of the foregoing (including device programming or simulation
// files), and any associated documentation or information are expressly subject
// to the terms and conditions of the Altera Program License Subscription
// Agreement, Intel MegaCore Function License Agreement, or other applicable
// license agreement, including, without limitation, that your use is for the
// sole purpose of programming logic devices manufactured by Intel and sold by
// Intel or its authorized distributors. Please refer to the applicable
// agreement for further details.
// timer.cpp
#include "timer.h"
#ifdef WINDOWS
Timer::Timer() {
QueryPerformanceFrequency( &m_ticks_per_second );
}
void Timer::start() {
QueryPerformanceCounter( &m_start_time );
}
void Timer::stop() {
QueryPerformanceCounter( &m_stop_time );
}
float Timer::get_time_s() {
LONGLONG delta = (m_stop_time.QuadPart - m_start_time.QuadPart);
return (float)delta / (float)(m_ticks_per_second.QuadPart);
}
#else // LINUX
#include <stdio.h>
Timer::Timer() {
}
void Timer::start() {
m_start_time = get_cur_time_s();
}
void Timer::stop() {
m_stop_time = get_cur_time_s();
}
float Timer::get_time_s() {
return (float)(m_stop_time - m_start_time);
}
double Timer::get_cur_time_s(void) {
struct timespec a;
const double NS_PER_S = 1000000000.0;
clock_gettime (CLOCK_REALTIME, &a);
return ((double)a.tv_nsec / NS_PER_S) + (double)(a.tv_sec);
}
#endif
|
#include <iostream>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
inline int love(string s){
int result = 0;
for ( char ch : s ){
ch = ( ch + 1 - 65 ) % 32;
if ( 1 <= ch && ch <= 26 ){
result += ch;
}
}
return result;
}
inline int love(int i){
int result = 0;
while ( i > 0 ) {
result += i % 10;
i /= 10;
}
return result;
}
int main(){
string name1, name2;
int res1, res2;
double ratio;
while( getline(cin, name1), getline(cin, name2) ){
res1 = love(name1);
res2 = love(name2);
while(res1 >= 10) {
res1 = love(res1);
}
while(res2 >= 10){
res2 = love(res2);
}
if(res1 > res2){
swap(res1, res2);
}
ratio = ((double)res1 / res2) * 100;
cout << fixed << setprecision(2) << ratio << " %" << endl;
}
return 0;
}
|
#pragma once
#include "resource.h"
class WinFramework
{
public:
WinFramework () {}
virtual ~WinFramework () {}
void quitGame ();
virtual int winWidth () { return 640; }
virtual int winHeight () { return 480; }
HWND hwnd () { return hMainWnd; }
void setHWnd ( HWND hwnd );
private:
HWND hMainWnd;
};
|
#ifndef CELLTRACKER_PROBLEM_ASSEMBLER_H__
#define CELLTRACKER_PROBLEM_ASSEMBLER_H__
#include <pipeline/all.h>
#include <inference/LinearConstraints.h>
#include <sopnet/segments/Segments.h>
#include "ProblemConfiguration.h"
class ProblemAssembler : public pipeline::SimpleProcessNode<> {
public:
ProblemAssembler();
private:
void updateOutputs();
void collectSegments();
void collectLinearConstraints();
void addConsistencyConstraints();
void setCoefficient(const EndSegment& end);
void setCoefficient(const ContinuationSegment& continuation);
void setCoefficient(const BranchSegment& branch);
void extractSliceIdsMap();
void addSlices(const EndSegment& end);
void addSlices(const ContinuationSegment& continuation);
void addSlices(const BranchSegment& branch);
void addId(unsigned int id);
unsigned int getSliceNum(unsigned int sliceId);
// a list of segments for each pair of frames
pipeline::Inputs<Segments> _segments;
// linear constraints on the segments for each pair of frames
pipeline::Inputs<LinearConstraints> _linearConstraints;
// all segments in the problem
pipeline::Output<Segments> _allSegments;
// all linear constraints on all segments
pipeline::Output<LinearConstraints> _allLinearConstraints;
// mapping of segment ids to a continous range of variable numbers
pipeline::Output<ProblemConfiguration> _problemConfiguration;
// the consistency constraints extracted for the segments
LinearConstraints _consistencyConstraints;
// a mapping from slice ids to the number of the consistency constraint it
// is used in
std::map<unsigned int, unsigned int> _sliceIdsMap;
// a counter for the number of segments that came in
unsigned int _numSegments;
// the total number of slices
unsigned int _numSlices;
};
#endif // CELLTRACKER_PROBLEM_ASSEMBLER_H__
|
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/random.hpp>
#include <cppmc/cppmc.hpp>
using namespace boost;
using namespace arma;
using namespace CppMC;
using std::vector;
using std::ofstream;
using std::cout;
using std::endl;
class EstimatedY : public MCMCDeterministic<double,Mat> {
private:
mat& X_;
MCMCStochastic<double,Col>& b_;
public:
EstimatedY(Mat<double>& X, MCMCStochastic<double,Col>& b): MCMCDeterministic<double,Mat>(X * b()), X_(X), b_(b)
{}
void getParents(std::vector<MCMCObject*>& parents) const {
parents.push_back(&b_);
}
Mat<double> eval() const {
return X_ * b_();
}
};
// global rng generators
CppMCGeneratorT MCMCObject::generator_;
int main() {
const int NR = 1000;
const int NC = 2;
mat X = randn<mat>(NR,NC);
mat y = randn<mat>(NR,1);
Uniform<Col> B(-100.0,100.0, randn<vec>(NC));
EstimatedY obs_fcst(X, B);
Uniform<Mat> tauY(0, 100, vec(1)); tauY[0] = 1.0;
NormalLikelihood<Mat> likelihood(y, obs_fcst, tauY);
int iterations = 1e5;
likelihood.sample(iterations, 1e2, 4);
return 1;
}
|
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include <iomanip>
#include <map>
#include <string>
#include <cstdio>
using namespace std;
int post[31];
int in[31];
int lch[31];
int rch[31];
int build(int inlow, int inhigh, int postlow, int posthigh) {
//cout << inlow << ' ' << inhigh << ' ' << postlow << ' ' << posthigh << endl;
if (inlow > inhigh) return 0;
int root = post[posthigh];
int rootIn = 0;
while (in[rootIn] != root) rootIn++;
int dividePost = postlow + rootIn - inlow;
lch[root] = build(inlow, rootIn - 1, postlow, dividePost - 1);
rch[root] = build(rootIn + 1, inhigh, dividePost, posthigh - 1);
return root;
}
void printLevel(int root) {
queue<int> q;
vector<int> v;
q.push(root);
while (!q.empty()) {
int n = q.front(); q.pop();
v.push_back(n);
if (lch[n] != 0) q.push(lch[n]);
if (rch[n] != 0) q.push(rch[n]);
}
for (auto it = v.begin(); it != v.end(); it++) {
if (it == v.begin()) cout << *it;
else cout << ' ' << *it;
}
cout << endl;
}
int main() {
int n;
while (cin >> n) {
for (int i = 0; i < n; i++) cin >> post[i];
for (int i = 0; i < n; i++) cin >> in[i];
int root = build(0, n-1, 0, n-1);
/*for (int i = 0; i < n; i++) cout << lch[i] << ' ';
cout << endl;
for (int i = 0; i < n; i++) cout << rch[i] << ' ';
cout << endl;*/
printLevel(root);
}
return 0;
}
|
#ifndef __CTRLMAIN_H
#define __CTRLMAIN_H
#include "ICtrlWindow.h"
#include "CtrlNotebook.h"
#include "ViewMain.h"
#include "ModelMain.h"
#include "globaldata.h"
namespace wh{
//---------------------------------------------------------------------------
class CtrlMain : public CtrlWindowBase<ViewMain, ModelMain>
{
std::shared_ptr<CtrlNotebook> mCtrlNotebook;
sig::scoped_connection conn_ShowHelp;
sig::scoped_connection connAfterDbConnected;
sig::scoped_connection connBeforeDbDisconnected;
sig::scoped_connection connViewCmd_MkPageGroup;
sig::scoped_connection connViewCmd_MkPageUser;
sig::scoped_connection connViewCmd_MkPageProp;
sig::scoped_connection connViewCmd_MkPageAct;
sig::scoped_connection connViewCmd_MkPageObjByType;
sig::scoped_connection connViewCmd_MkPageObjByPath;
sig::scoped_connection connViewCmd_MkPageHistory;
sig::scoped_connection connViewCmd_MkPageReportList;
sig::scoped_connection connViewCmd_MkPageBrowserCls;
sig::scoped_connection connViewCmd_MkPageBrowserObj;
sig::scoped_connection connViewCmd_DoConnectDB;
sig::scoped_connection connViewCmd_DoDisconnectDB;
sig::scoped_connection connViewCmd_ShowDoc;
sig::scoped_connection connViewCmd_ShowWhatIsNew;
sig::scoped_connection connViewCmd_Close;
void OnConnectDb(const whDB& db);
void OnDicsonnectDb(const whDB& db);
public:
CtrlMain(const std::shared_ptr<ViewMain>& view, const std::shared_ptr<ModelMain>& model);
void ConnectDB();
void DisconnectDB();
void MkPageGroup();
void MkPageUser();
void MkPageProp();
void MkPageAct();
void MkPageObjByType();
void MkPageObjByPath();
void MkPageHistory();
void MkPageReportList();
void MkPageBrowserCls();
void MkPageBrowserObj();
std::shared_ptr<CtrlNotebook> GetNotebook();
virtual void RmView()override;
void Load();
void Save();
void ShowHelp(const wxString& index)const;
void ShowDoc()const;
void ShowWhatIsNew()const;
};
//---------------------------------------------------------------------------
} //namespace wh
#endif // __***_H
|
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
cout << "Enter your keyword : ";
string input;
//cin >> input;
char transform;
char operate;
while(cin >> input)
{
for(int i = 0; i != input.length(); i++)
{
transform = input[i];
operate = toupper(transform);
cout << "[" << transform << operate << "]";
}
cout << "\n\n";
cout << "Enter another keyword or ctrl+Z to exit\n";
}
cout << endl;
return 0;
}
|
#ifndef GLOBAL_H
#define GLOBAL_H
#include <string>
namespace gnGame {
/// <summary>
/// 定数などを定義する名前空間
/// </summary>
namespace global {
namespace {
// マップのフォルダパス
static std::string MapFile = "Asset/MapData/";
// 画像のフォルダパス
static std::string ImageFile = "Asset/Image/";
// 音楽のフォルダパス
static std::string AudioPath = "Asset/BGM/";
}
// マップのフォルダパスを追加して返す
static std::string MapAsset(const std::string& _map) {
return MapFile + _map;
}
// 画像のフォルダパスを追加して返す
static std::string ImageAsset(const std::string& _image) {
return ImageFile + _image;
}
// 音楽のフォルダパスを追加して返す
static std::string AudioAsset(const std::string& _audio) {
return AudioPath + _audio;
}
}
}
#endif // !GLOBAL_H
|
#include "_pch.h"
#include "PGPTypeId.h"
#include "dbFieldType.h"
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxPGPSmallType, wxEnumProperty)
WX_PG_IMPLEMENT_PROPERTY_CLASS_PLAIN(wxPGPSmallType, long, Choice)
wxPGPSmallType::wxPGPSmallType(const wxString& label, const wxString& name, int value)
:wxEnumProperty(label, name)
{
wxPGChoices soc;
for (const auto& ft : wh::gFieldTypeArray)
soc.Add(ft.mTitle, ft.mType);
this->SetChoices(soc);
if (soc.GetCount())
this->SetChoiceSelection(value);
}
|
#define T1 160
#define T2 120
#define debug false
#define MAIN_LED_PIN 5
#define SECOND_LED_PIN 4
volatile boolean mainLed = false;
volatile boolean secondLed = false;
byte addressArray[10] = {3,4,5,6,7,8,11,12,13,14};
byte dataArray[10] = {4,154,43,166,244,34,82,136,42,128};
//Serial Number for demo purpose
//byte addressArray[4] = {11,12,13,14};
//byte dataArray[4] = {82,136,42,128};
int count = 0; //counter for SN/GTIN send times
void setup()
{
pinMode(MAIN_LED_PIN,OUTPUT);
pinMode(SECOND_LED_PIN,OUTPUT);
attachInterrupt(0,pin2ISR,RISING); //attach ISR on pin 2
attachInterrupt(1,pin3ISR,RISING); //attach ISR on pin 3
Serial.begin(9600);
Serial.println("--Start--");
}
void loop()
{
//mark(4);
//space(4);
//digitalWrite(8,HIGH);
//pin2ReadNew = digitalRead(SWITCHPIN1);
/*if((pin2ReadNew==1) && (pin2ReadNew != pin2ReadOld))
{
switch1Flag = !switch1Flag;
count = 0;
}
pin2ReadOld = pin2ReadNew;*/
//if(debug) Serial.println(pin2ReadNew);
//if(debug) Serial.println();
//Serial.println(ledFlag);
if(true)
{
for(int i=0; i<10;i++)
{
//Serial.println(micros());
//if(debug) Serial.println();
//digitalWrite(5,LOW);
//delayMicroseconds(4000);
if(true){
startBits(MAIN_LED_PIN);
sendBit(MAIN_LED_PIN,addressArray[i]);
sendBit(MAIN_LED_PIN,dataArray[i]);
//endBits(MAIN_LED_PIN);
}
//digitalWrite(5,LOW);
//delayMicroseconds(4000);
if(secondLed){
startBits(SECOND_LED_PIN);
sendBit(SECOND_LED_PIN,addressArray[i]);
sendBit(SECOND_LED_PIN,dataArray[i]);
}
//Serial.println(micros());
digitalWrite(MAIN_LED_PIN,LOW);
digitalWrite(SECOND_LED_PIN,LOW);
//pwm @ 1kHZ 25%
//analogWrite(MAIN_LED_PIN,56);
// manually PWM 25%
// 200HZ
/*for(int i=0; i<225;i++)
{
digitalWrite(MAIN_LED_PIN,LOW);
delayMicroseconds(306);
digitalWrite(MAIN_LED_PIN,LOW);
delayMicroseconds(94);
}*/
//method 3
// reduce pulse width
delay(92); //92
}
count ++;
}
}
void sendBit(int pin,byte data)
{
//send each data bits
for(int i=7; i>=0; i--)
{
if(bitRead(data,i))
{
if(debug) Serial.print("1");
if(debug) Serial.print(" ");
one(pin);
}
else {
if(debug) Serial.print("0");
if(debug) Serial.print(" ");
zero(pin);
}
}
}
void startBits(int pin)
{
zero(pin);
zero(pin);
//zero(pin);
}
void endBits(int pin)
{
zero(pin);
}
void one(int pin)
{
space(pin);
mark(pin);
}
void zero(int pin)
{
mark(pin);
space(pin);
}
void mark(int pin)
{
//digitalWrite(pin,HIGH);
//delayMicroseconds(T1);
for(int i=0; i<9;i++)
{
digitalWrite(pin,HIGH);
delayMicroseconds(5); //5
digitalWrite(pin,LOW);
delayMicroseconds(4); //4
}
}
void space(int pin)
{
digitalWrite(pin,LOW);
delayMicroseconds(T2);
}
void pin3ISR(){
mainLed = !mainLed;
count = 0;
if (debug) Serial.print("Main led status: ");
if (debug )Serial.println(mainLed);
}
void pin2ISR(){
secondLed = !secondLed;
count = 0;
if (debug) Serial.print("Blue led status: ");
if (debug) Serial.println(secondLed);
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
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.
====================================================================*/
#pragma once
#include <opencv2/video.hpp>
namespace HoloIntervention
{
namespace Algorithm
{
class KalmanFilter
{
public:
const cv::Mat& Predict(const cv::Mat& control = cv::Mat());
const cv::Mat& Correct(const cv::Mat& measurement);
void Init(int dynamParams, int measureParams, int controlParams = 0);
void SetTransitionMatrix(const cv::Mat& transition);
void SetStatePre(const cv::Mat& statePre);
void SetStatePre(const std::vector<float>& statePre);
public:
KalmanFilter(int dynamParams, int measureParams, int controlParams = 0);
~KalmanFilter();
protected:
cv::KalmanFilter m_kalmanFilter;
};
}
}
|
#ifndef TOPOLOGY_CONTAINER
#define TOPOLOGY_CONTAINER
#include "DataTypes/Define.h"
#include "DataTypes/Vec.h"
#include "DataTypes/Mat.h"
#include <afxwin.h>
#include <GL/glu.h>
#include <GL/gl.h>
#include <vector>
class TopologyContainer
{
public:
TopologyContainer(void);
~TopologyContainer(void);
//functions
public:
void init(std::vector<Vec3f>* point0, std::vector<Vec3f>* point, std::vector<Vec3i>* face, std::vector<Vec2i>* edge);
std::vector<std::vector<int>>* pointsAroundPoint();
std::vector<std::vector<int>>* edgesAroundPoint();
std::vector<std::vector<int>>* facesAroundPoint();
std::vector<std::vector<int>>* facesAroundEdge();
std::vector<int> facesAroundEdge(int idx);
std::vector<std::vector<int>>* edgesInFace();
arrayInt faceShareEdgeWithFace(int idxInQ);
std::vector<Vec3f>* point0();
std::vector<Vec3f>* point();
std::vector<Vec2i>* edge();
std::vector<Vec3i>* face();
//variables
private:
std::vector<Vec3f>* Point0;
std::vector<Vec3f>* Point;
std::vector<Vec3i>* Face;
std::vector<Vec2i>* Edge;
std::vector<std::vector<int>>* PointsAroundPoint;
std::vector<std::vector<int>>* EdgesAroundPoint;
std::vector<std::vector<int>>* FacesAroundPoint;
std::vector<std::vector<int>>* FacesAroundEdge;
std::vector<std::vector<int>>* EdgesInFace;
};
#endif
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "Serialization/JsonInputStreamSerializer.h"
#include <ctype.h>
#include <exception>
namespace cn {
namespace {
common::JsonValue getJsonValueFromStreamHelper(std::istream& stream) {
common::JsonValue value;
stream >> value;
return value;
}
}
JsonInputStreamSerializer::JsonInputStreamSerializer(std::istream& stream) : JsonInputValueSerializer(getJsonValueFromStreamHelper(stream)) {
}
} //namespace cn
|
#include "OptionState.h"
#include "SpriteNode.h"
#include "Game.hpp"
OptionState::OptionState(StateStack* stack, Context* context) : State(stack, context)
{
mAllRitems.clear();
mContext->game->ResetFrameResources();
mContext->game->BuildMaterials();
std::unique_ptr<SpriteNode> backgroundSprite = std::make_unique<SpriteNode>(this);
backgroundSprite->SetMatGeoDrawName("StarWars_Option", "boxGeo", "box");
backgroundSprite->setScale(11.5, 1.0, 10.0);
backgroundSprite->setPosition(0, 0, 0);
mSceneGraph->attachChild(std::move(backgroundSprite));
mSceneGraph->build();
mContext->game->BuildFrameResources(mAllRitems.size());
}
OptionState::~OptionState()
{
}
void OptionState::draw()
{
mSceneGraph->draw();
}
bool OptionState::update(const GameTimer& gt)
{
mSceneGraph->update(gt);
return true;
}
bool OptionState::handleEvent(WPARAM btnState)
{
// 1 - Arrow Keys
if (d3dUtil::IsKeyDown('1'))
{
mContext->player->remapKeys(1);
requestStackPop();
requestStackPush(States::Menu);
}
// 2 - WASD
else if (d3dUtil::IsKeyDown('2'))
{
mContext->player->remapKeys(2);
requestStackPop();
requestStackPush(States::Menu);
}
// B - Back
else if (d3dUtil::IsKeyDown('B'))
{
requestStackPop();
requestStackPush(States::Menu);
}
return true;
}
bool OptionState::handleRealtimeInput()
{
return true;
}
|
#include <stdio.h>
int main()
{
int x = 5;
int *j;
j = &x;
printf("%d \n", x);
printf("%d \n", *j); //will print value of x
printf("%d", j); // it will print containing address of x
return 0;
}
|
// Created on: 1996-09-04
// Created by: Christian CAILLET
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Transfer_TransientProcess_HeaderFile
#define _Transfer_TransientProcess_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TColStd_HSequenceOfTransient.hxx>
#include <Transfer_ProcessForTransient.hxx>
#include <Standard_Integer.hxx>
#include <Standard_CString.hxx>
#include <Standard_Transient.hxx>
#include <TCollection_AsciiString.hxx>
#include <NCollection_DataMap.hxx>
class Interface_InterfaceModel;
class Interface_HGraph;
class Interface_Graph;
class Interface_EntityIterator;
class Transfer_TransientProcess;
DEFINE_STANDARD_HANDLE(Transfer_TransientProcess, Transfer_ProcessForTransient)
//! Adds specific features to the generic definition :
//! TransientProcess is intended to work from an InterfaceModel
//! to a set of application objects.
//!
//! Hence, some information about starting entities can be gotten
//! from the model : for Trace, CheckList, Integrity Status
class Transfer_TransientProcess : public Transfer_ProcessForTransient
{
public:
//! Sets TransientProcess at initial state, with an initial size
Standard_EXPORT Transfer_TransientProcess(const Standard_Integer nb = 10000);
//! Sets an InterfaceModel, used by StartTrace, CheckList, queries
//! on Integrity, to give information significant for each norm.
Standard_EXPORT void SetModel (const Handle(Interface_InterfaceModel)& model);
//! Returns the Model used for StartTrace
Standard_EXPORT Handle(Interface_InterfaceModel) Model() const;
//! Sets a Graph : superseedes SetModel if already done
Standard_EXPORT void SetGraph (const Handle(Interface_HGraph)& HG);
Standard_EXPORT Standard_Boolean HasGraph() const;
Standard_EXPORT Handle(Interface_HGraph) HGraph() const;
Standard_EXPORT const Interface_Graph& Graph() const;
//! Sets a Context : according to receiving appli, to be
//! interpreted by the Actor
Standard_EXPORT void SetContext (const Standard_CString name, const Handle(Standard_Transient)& ctx);
//! Returns the Context attached to a name, if set and if it is
//! Kind of the type, else a Null Handle
//! Returns True if OK, False if no Context
Standard_EXPORT Standard_Boolean GetContext (const Standard_CString name, const Handle(Standard_Type)& type, Handle(Standard_Transient)& ctx) const;
//! Returns (modifiable) the whole definition of Context
//! Rather for internal use (ex.: preparing and setting in once)
Standard_EXPORT NCollection_DataMap<TCollection_AsciiString, Handle(Standard_Transient)>& Context();
//! Specific printing to trace an entity : prints label and type
//! (if model is set)
Standard_EXPORT virtual void PrintTrace (const Handle(Standard_Transient)& start, Standard_OStream& S) const Standard_OVERRIDE;
//! Specific number of a starting object for check-list : Number
//! in model
Standard_EXPORT virtual Standard_Integer CheckNum (const Handle(Standard_Transient)& ent) const Standard_OVERRIDE;
//! Returns the list of sharings entities, AT ANY LEVEL, which are
//! kind of a given type. Calls TypedSharings from Graph
//! Returns an empty list if the Graph has not been aknowledged
Standard_EXPORT Interface_EntityIterator TypedSharings (const Handle(Standard_Transient)& start, const Handle(Standard_Type)& type) const;
//! Tells if an entity is well loaded from file (even if its data
//! fail on checking, they are present). Mostly often, answers
//! True. Else, there was a syntactic error in the file.
//! A non-loaded entity MAY NOT BE transferred, unless its Report
//! (in the model) is interpreted
Standard_EXPORT Standard_Boolean IsDataLoaded (const Handle(Standard_Transient)& ent) const;
//! Tells if an entity fails on data checking (load time,
//! syntactic, or semantic check). Normally, should answer False.
//! It is not prudent to try transferring an entity which fails on
//! data checking
Standard_EXPORT Standard_Boolean IsDataFail (const Handle(Standard_Transient)& ent) const;
//! Prints statistics on a given output, according mode
Standard_EXPORT void PrintStats (const Standard_Integer mode, Standard_OStream& S) const;
Standard_EXPORT Handle(TColStd_HSequenceOfTransient) RootsForTransfer();
DEFINE_STANDARD_RTTIEXT(Transfer_TransientProcess,Transfer_ProcessForTransient)
protected:
private:
Handle(Interface_InterfaceModel) themodel;
Handle(Interface_HGraph) thegraph;
NCollection_DataMap<TCollection_AsciiString, Handle(Standard_Transient)> thectx;
Handle(TColStd_HSequenceOfTransient) thetrroots;
};
#endif // _Transfer_TransientProcess_HeaderFile
|
#include <iostream>
namespace mine {
template<typename T1, typename T2>
struct my_pair {
my_pair() = default;
my_pair(my_pair const&) = default;
my_pair(T1 const& first, T2 const& second)
: first{first}, second{second}
{}
T1 first;
T2 second;
};
template<typename T1, typename T2>
my_pair(T1 const&, T2 const&) -> my_pair<T1, T2>;
//template<typename T>
//my_pair(T const&, char const*) -> my_pair<T, std::string>;
}
template<typename T>
void test_func(T const&);
template<>
void test_func<char const*>(char const*const &) {
std::cout << "using c string" << std::endl;
}
template<>
void test_func<std::string>(std::string const&) {
std::cout << "using std string" << std::endl;
}
void test0() {
std::pair p{1, 2};
mine::my_pair p1{1,2};
mine::my_pair p2{1, "some string"};
test_func(p2.second);
}
int main() {
test0();
return 0;
}
|
// Created on: 2011-08-01
// Created by: Sergey ZERCHANINOV
// Copyright (c) 2011-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef OpenGl_Group_HeaderFile
#define OpenGl_Group_HeaderFile
#include <Graphic3d_Group.hxx>
#include <Graphic3d_Structure.hxx>
#include <OpenGl_Aspects.hxx>
#include <OpenGl_Element.hxx>
class OpenGl_Structure;
struct OpenGl_ElementNode
{
OpenGl_Element* elem;
OpenGl_ElementNode* next;
DEFINE_STANDARD_ALLOC
};
//! Implementation of low-level graphic group.
class OpenGl_Group : public Graphic3d_Group
{
public:
//! Create empty group.
//! Will throw exception if not created by OpenGl_Structure.
Standard_EXPORT OpenGl_Group (const Handle(Graphic3d_Structure)& theStruct);
Standard_EXPORT virtual void Clear (const Standard_Boolean theToUpdateStructureMgr) Standard_OVERRIDE;
//! Return line aspect.
virtual Handle(Graphic3d_Aspects) Aspects() const Standard_OVERRIDE
{
return myAspects != NULL
? myAspects->Aspect()
: Handle(Graphic3d_Aspects)();
}
//! Return TRUE if group contains primitives with transform persistence.
bool HasPersistence() const
{
return !myTrsfPers.IsNull()
|| (myStructure != NULL && !myStructure->TransformPersistence().IsNull());
}
//! Update aspect.
Standard_EXPORT virtual void SetGroupPrimitivesAspect (const Handle(Graphic3d_Aspects)& theAspect) Standard_OVERRIDE;
//! Append aspect as an element.
Standard_EXPORT virtual void SetPrimitivesAspect (const Handle(Graphic3d_Aspects)& theAspect) Standard_OVERRIDE;
//! Update presentation aspects after their modification.
Standard_EXPORT virtual void SynchronizeAspects() Standard_OVERRIDE;
//! Replace aspects specified in the replacement map.
Standard_EXPORT virtual void ReplaceAspects (const Graphic3d_MapOfAspectsToAspects& theMap) Standard_OVERRIDE;
//! Add primitive array element
Standard_EXPORT virtual void AddPrimitiveArray (const Graphic3d_TypeOfPrimitiveArray theType,
const Handle(Graphic3d_IndexBuffer)& theIndices,
const Handle(Graphic3d_Buffer)& theAttribs,
const Handle(Graphic3d_BoundBuffer)& theBounds,
const Standard_Boolean theToEvalMinMax) Standard_OVERRIDE;
//! Adds a text for display
Standard_EXPORT virtual void AddText (const Handle(Graphic3d_Text)& theTextParams,
const Standard_Boolean theToEvalMinMax) Standard_OVERRIDE;
//! Add flipping element
Standard_EXPORT virtual void SetFlippingOptions (const Standard_Boolean theIsEnabled,
const gp_Ax2& theRefPlane) Standard_OVERRIDE;
//! Add stencil test element
Standard_EXPORT virtual void SetStencilTestOptions (const Standard_Boolean theIsEnabled) Standard_OVERRIDE;
public:
OpenGl_Structure* GlStruct() const { return (OpenGl_Structure* )(myStructure->CStructure().operator->()); }
Standard_EXPORT void AddElement (OpenGl_Element* theElem);
Standard_EXPORT virtual void Render (const Handle(OpenGl_Workspace)& theWorkspace) const;
Standard_EXPORT virtual void Release (const Handle(OpenGl_Context)& theGlCtx);
//! Returns first OpenGL element node of the group.
const OpenGl_ElementNode* FirstNode() const { return myFirst; }
//! Returns OpenGL aspect.
const OpenGl_Aspects* GlAspects() const { return myAspects; }
//! Is the group ray-tracable (contains ray-tracable elements)?
Standard_Boolean IsRaytracable() const { return myIsRaytracable; }
//! Dumps the content of me into the stream
Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE;
protected:
Standard_EXPORT virtual ~OpenGl_Group();
private:
//! Render element if it passes the filtering procedure.
//! This method should be used for elements which can be used in scope of rendering algorithms.
//! E.g. elements of groups during recursive rendering.
//! If render filter is null, pure rendering is performed.
//! @param theWorkspace [in] the rendering workspace
//! @param theFilter [in] the rendering filter to check whether the element should be rendered or not
//! @return True if element passes the check and renders
Standard_EXPORT bool renderFiltered (const Handle(OpenGl_Workspace)& theWorkspace,
OpenGl_Element* theElement) const;
protected:
OpenGl_Aspects* myAspects;
OpenGl_ElementNode* myFirst;
OpenGl_ElementNode* myLast;
Standard_Boolean myIsRaytracable;
public:
DEFINE_STANDARD_RTTIEXT(OpenGl_Group,Graphic3d_Group) // Type definition
};
DEFINE_STANDARD_HANDLE(OpenGl_Group, Graphic3d_Group)
#endif // _OpenGl_Group_Header
|
//
// Created by griha on 06.01.18.
//
#include <misc/logger.hpp>
DECLARE_LOG_DEBUG(Standard, "MICRON SST");
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen 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 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#include "main.h"
#include <Eigen/SVD>
template<typename MatrixType> void upperbidiag(const MatrixType& m)
{
const typename MatrixType::Index rows = m.rows();
const typename MatrixType::Index cols = m.cols();
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<typename MatrixType::RealScalar, MatrixType::RowsAtCompileTime, MatrixType::ColsAtCompileTime> RealMatrixType;
MatrixType a = MatrixType::Random(rows,cols);
UpperBidiagonalization<MatrixType> ubd(a);
RealMatrixType b(rows, cols);
b.setZero();
b.block(0,0,cols,cols) = ubd.bidiagonal();
MatrixType c = ubd.householderU() * b * ubd.householderV().adjoint();
VERIFY_IS_APPROX(a,c);
}
void test_upperbidiagonalization()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( upperbidiag(MatrixXf(3,3)) );
CALL_SUBTEST_2( upperbidiag(MatrixXd(17,12)) );
CALL_SUBTEST_3( upperbidiag(MatrixXcf(20,20)) );
CALL_SUBTEST_4( upperbidiag(MatrixXcd(16,15)) );
CALL_SUBTEST_5( upperbidiag(Matrix<float,6,4>()) );
CALL_SUBTEST_6( upperbidiag(Matrix<float,5,5>()) );
CALL_SUBTEST_7( upperbidiag(Matrix<double,4,3>()) );
}
}
|
//
// Team.cpp
// Polygons
//
// Created by Italo Ricardo Geske on 2021/05/16.
// Copyright © 2021 Italo Ricardo Geske. All rights reserved.
//
#include <stdio.h>
#include <string>
#include "Team.h"
#include "Player.h"
Team::Team() {
name = "";
}
Team::Team (std::string name, bool isPlayerTeam) {
this->name = name;
this->isPlayerTeam = isPlayerTeam;
}
std::string Team::GetName() {
return name;
}
bool Team::IsPlayerTeam() {
return isPlayerTeam;
}
|
/**
* Create a templated value-like library class to store books, movies etc
* Each library item has the data and a set of related works
* Each related work object has a ptr to the related works item.
*/
#include <iostream>
#include "Library.hpp"
// class to store the description of an item.
class Description {
public:
Description(const std::string& d) : desc{d} {}
friend std::ostream& operator<<(std::ostream&, const Description &);
private:
std::string desc;
};
// function to print out a description object
std::ostream& operator<<(std::ostream &os, const Description &d) {
os << d.desc;
return os;
}
// class to store a Book
class Book {
public:
Book(const std::string& b) : name{b} {}
friend bool operator==(const Book&, const Book &);
friend std::ostream& operator<<(std::ostream&, const Book &);
private:
std::string name;
};
// method to compare books
bool operator==(const Book& a, const Book & b) {
return a.name == b.name;
}
// method to print the book details
std::ostream& operator<<(std::ostream &os, const Book &b) {
os << b.name;
return os;
}
// TODO: create this class
class Movie {
public:
Movie(const std::string& n, const std::string& dir, int s) : name{n}, director{dir}, stars{s} {}
friend bool operator==(const Movie&, const Movie&);
friend std::ostream& operator<<(std::ostream&, const Movie &);
private:
std::string name;
std::string director;
int stars;
};
// method to compare movies
bool operator==(const Movie& a, const Movie &b) {
return (a.name == b.name) && (a.stars == b.stars) && (a.director == b.director);
}
// method to print the movie details
std::ostream& operator<<(std::ostream &os, const Movie &b) {
os << "(" << b.name << ", " << b.director << ", " << b.stars << ")\n";
return os;
}
int main() {
// create a book library
Library<int, Description> intLibrary;
intLibrary.add(1);
intLibrary.add(2);
Description d("they are both numbers less than 3 and greater than 0");
intLibrary.addRelated(1, 2, d);
std::cout << "the items related to 1 are...\n";
intLibrary.printRelated(1);
}
|
#include "orientation.h"
#include "./../constants/vector.h"
Orientation::Orientation()
:_forward(Constants::Vec4::forward), _right(Constants::Vec4::right), _up(Constants::Vec4::up)
{}
Orientation::Orientation(const glm::quat& quaternion)
: _quaternion(quaternion)
{
update_direction_vectors();
}
void Orientation::rotate(const glm::vec3& axis, const float degreesOfRotation)
{
_quaternion = glm::rotate(_quaternion, degreesOfRotation, axis);
update_direction_vectors();
}
Orientation Orientation::operator*(const Orientation& rhs) const
{
return Orientation(this->_quaternion * rhs._quaternion);
}
glm::mat4 Orientation::get_rotation_matrix() const
{
return glm::mat4_cast(glm::inverse(_quaternion));
}
glm::vec3 Orientation::forward() const
{
return glm::vec3(_forward);
}
glm::vec3 Orientation::backward() const
{
return -1.0f * forward();
}
glm::vec3 Orientation::up() const
{
return glm::vec3(_up);
}
glm::vec3 Orientation::down() const
{
return -1.0f * up();
}
glm::vec3 Orientation::right() const
{
return glm::vec3(_right);
}
glm::vec3 Orientation::left() const
{
return -1.0f * right();
}
void Orientation::update_direction_vectors()
{
_quaternion = glm::normalize(_quaternion);
const glm::mat4 rotation = get_rotation_matrix();
_forward = rotation * Constants::Vec4::forward;
_right = rotation * Constants::Vec4::right;
_up = rotation * Constants::Vec4::up;
}
|
#include <iostream>
#include <stdlib.h>
#include <string>
#include <vector>
#include <algorithm>
#define min(x, y) (x > y ? y : x)
using namespace std;
vector<long long> num;
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
int tmp;
cin >> tmp;
num.push_back(tmp);
}
sort(num.begin(), num.end());
int len = num.size();
long long ans = 0;
ans += abs(num[num.size() - 1] - num[0]);
//printf("%d\n", ans);
for (int i = 0; i < (len / 2) - 1; i++)
{
ans += abs(num[num.size() - 1 - i] - num[i + 1]);
//printf("%d\n", ans);
ans += abs(num[num.size() - 2 - i] - num[i]);
//printf("%d\n", ans);
}
if (len % 2 == 1)
{
long long tmp1, tmp2;
tmp1 = abs(num[len / 2] - num[len / 2 - 1]);
tmp2 = abs(num[len / 2 + 1] - num[len / 2]);
if (tmp1 <= tmp2)
{
ans += tmp2;
}
else
{
ans += tmp1;
}
}
//printf("%d", ans);
cout << ans << endl;
}
|
#include <bits/stdc++.h>
using namespace std;
int main(){
double n, k;
cin >> n >> k;
double ans = 0;
int lim = n;
if(k <= n) lim = k-1;
for(int i=1; i<=lim; i++){
double base = 1;
double x = 0;
while(k > base * i){
base *= 2;
x++;
}
ans += 1/n * pow(0.5, x);
}
if(k <= n){
ans += (n-k+1)/n;
}
cout << setprecision(12) << ans << endl;
}
|
#include "Operations.h"
double expression(Token_stream &ts);
double primary(Token_stream &ts)
{
Token t = ts.get();
switch (t.kind)
{
case '(':
{
double d = expression(ts);
t = ts.get();
if (t.kind != ')')
error("')' expected");
return d;
}
case '8':
return t.value;
default:
error("primary expected");
}
}
double term(Token_stream &ts)
{
double left = primary(ts);
Token t = ts.get();
while (true)
{
switch (t.kind)
{
case '*': {
left *= primary(ts);
t = ts.get();
break;
}
case '/':
{
double d = primary(ts);
if (d == 0) error("divide by zero");
left /= d;
t = ts.get();
break;
}
default:
ts.putback(t);
return left;
}
}
}
double expression(Token_stream &ts)
{
double left = term(ts);
Token t = ts.get();
while (true)
{
switch (t.kind)
{
case '+':
left += term(ts);
t = ts.get();
break;
case '-':
left -= term(ts);
t = ts.get();
break;
default:
ts.putback(t);
return left;
}
}
}
|
#pragma once
#include "SIngletonBase.h"
// 헤더랑 cpp 합친거
#include "./FMOD/inc/fmod.hpp"
#pragma comment(lib, "./FMOD/lib/fmodex_vc.lib")
// fmod
/*
미리 만들어져있는거
사운드 플레이 하기 위해 도와주는 녀석
DirectX랑 같음
옛날에 만들어져서 개발이 중단되었으나 요즘에도 많이 사용하고 있음
간단하게 사용할 수 있고 지원하는 확장자가 많아서 자주 쓰고 있는거
사운드 편집 가능
fmod studio 사이트 가보면 확인 가능
*/
// 외부에서 include 해야 되는것들은 보통 네임스페이스도 같이 있음
using namespace FMOD;
// 미리 여유분으로 잡아두는 사운드가 총 20개라고 보면됨 + 5
// 많이 잡아두는거는 다양한 효과음이 들어가서
// 또는 사운드가 씹혀서 안나오는 경우 때문에 크게 크게 잡는거
#define EXTRACHANNELBUFFER 5
#define SOUNDBUFFER 20
#define TOTALSOUNDBUFFER (SOUNDBUFFER + EXTRACHANNELBUFFER)
class SoundManager : public SingletonBase<SoundManager>
{
private:
map<string, Sound**> m_totalSounds;
// fmod 사용할지 안할지 fopen 에서 file 같은거
// fmod 사용하기위한 시작지점, 끝지점
System* m_system;
// 더블 포인터를 쓰는 이유는
// 사운드로 들어가는 인자값이 더블 포인터로 되어있어서
Sound** m_sound; // 사운드 1 개 (앨범에 노래 하나)
Channel** m_channel; // 앨범 자체를 나타내는거
public:
SoundManager();
~SoundManager();
HRESULT Init();
void Release();
void Update(); // play가 되는 녀석
// bgm은 bgm으로 쓸건지 효과음으로 쓸건지
// loop는 반복할건지
void AddSound(string keyName, string fileName,
bool bgm = FALSE, bool loop = FALSE);
// volume 소리크기 지정
// volume = 0.0 ~ 1.0f 1.0f으로 했는데도 파일자체 소리를 키워야함
void Play(string keyName, float volume = 1.0f);
void Stop(string keyName); // 정지 그 사운드값의 처음으로 돌아감
void Pause(string keyName); // 일시정지 그 위치의 멈추는거
void Resume(string keyName); // 다시 재생
bool IsPlaySound(string keyName);
bool isPauseSound(string keyName);
};
#define SOUND SoundManager::GetSingleton()
|
/*
* File: TraverseOperationTest.h
* Author: azamat
*
* Created on Feb 12, 2013, 3:05:31 PM
*/
#ifndef TRAVERSEOPERATIONTEST_H
#define TRAVERSEOPERATIONTEST_H
#include <cppunit/extensions/HelperMacros.h>
#include <kdl_extensions/functionalcomputation_kdl.hpp>
class TraverseOperationTest : public CPPUNIT_NS::TestFixture
{
CPPUNIT_TEST_SUITE(TraverseOperationTest);
CPPUNIT_TEST(testTraverseOperation);
CPPUNIT_TEST(testFailedTraverseOperation);
CPPUNIT_TEST_SUITE_END();
public:
TraverseOperationTest();
virtual ~TraverseOperationTest();
void setUp();
void tearDown();
private:
KDL::Tree testTree;
std::vector<kdle::SegmentState> a_segmentState;
std::vector<kdle::JointState> a_jointState;
kdle::transform<kdle::kdl_tree_iterator, kdle::pose> a_operation1;
kdle::transform<kdle::kdl_tree_iterator, kdle::twist> a_operation2;
kdle::DFSPolicy<KDL::Tree, kdle::outward> a_policy1;
void testTraverseOperation();
void testFailedTraverseOperation();
};
#endif /* TRAVERSEOPERATIONTEST_H */
|
#include <iostream>
#include "diabetes.h"
#include <string>
using namespace std;
void diabetesproblems()
{
string Thirst;
string Polyurea;
string Polyphagia;
string BlurredVision;
string WeightLoss;
string RecurrentInfections;
string Tiredness;
string Itchiness;
string SlowHealing;
string SkinCondition;
diabetes bproblems;//create date object
std::cout << "Q1: Have you been feeling abnormally thirsty?" << endl;
std::getline(std::cin, Thirst);
std::cout << "Q2: Have you been urinating more often than normal, particularly at night?" << endl;
std::getline(std::cin, Polyurea);
std::cout << "Q3: Do you often feel hungry, particularly if you feel hungry shortly after eating? " << endl;
std::getline(std::cin, Polyphagia);
std::cout << "Q4: Have you been experiencing episodes of blurred vision? " << endl;
std::getline(std::cin, BlurredVision);
std::cout << "Q5: Have you recently experienced sudden weight loss or loss of muscle mass? " << endl;
std::getline(std::cin, WeightLoss);
std::cout << "Q6: Have you been experiencing recurrent infections recently? " << endl;
std::getline(std::cin, RecurrentInfections);
std::cout << "Q7: Have you been feeling tired during the day, particularly after meals? " << endl;
std::getline(std::cin, Tiredness);
std::cout << "Q8: Have you been experiencing any itching of skin, particularly around genitals? " << endl;
std::getline(std::cin, Itchiness);
std::cout << "Q9: Have you been experiencing slow healing of any wounds or cuts? " << endl;
std::getline(std::cin, SlowHealing);
std::cout << "Q10: Have you developed any skin conditions i.e psoriasis or acanthosis nigricans?" << endl;
std::getline(std::cin, SkinCondition);
bproblems.setQ1Thirst(Thirst);
bproblems.setQ2Polyurea(Polyurea);
bproblems.setQ3Polyphagia(Polyphagia);
bproblems.setQ4BlurredVision(BlurredVision);
bproblems.setQ5WeightLoss(WeightLoss);
bproblems.setQ6RecurrentInfections(RecurrentInfections);
bproblems.setQ7Tiredness(Tiredness);
bproblems.setQ8Itchiness(Itchiness);
bproblems.setQ9SlowHealing(SlowHealing);
bproblems.setQ10SkinCondition(SkinCondition);
bproblems.displayQuestions();
}
int main()
{
//GeneralQuestions();
diabetesproblems();
}
|
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
// Copyright (C) 2016, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
/*
Declaration of various functions which are related to Tensorflow models reading.
*/
#ifndef __OPENCV_DNN_TF_IO_HPP__
#define __OPENCV_DNN_TF_IO_HPP__
#ifdef HAVE_PROTOBUF
#include "graph.pb.h"
namespace cv {
namespace dnn {
// Read parameters from a file into a GraphDef proto message.
void ReadTFNetParamsFromBinaryFileOrDie(const char* param_file,
tensorflow::GraphDef* param);
}
}
#endif
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#include "platforms/windows/installer/CreateRegKeyOperation.h"
#include "platforms/windows/windows_ui/registry.h"
CreateRegKeyOperation::CreateRegKeyOperation(HKEY ancestor_handle, const OpStringC& key_name)
: m_ancestor_handle(ancestor_handle)
, m_restore_access_info(NULL)
{
if (OpStatus::IsError(m_key_name.Set(key_name)))
m_key_name.Empty();
}
OP_STATUS CreateRegKeyOperation::Do()
{
if (m_key_name.IsEmpty())
return OpStatus::ERR;
HKEY key;
//Fail if the key already exists
DWORD err = RegOpenKeyEx(m_ancestor_handle, m_key_name.CStr(), 0, KEY_QUERY_VALUE, &key);
if (err != ERROR_FILE_NOT_FOUND)
{
if (err == ERROR_SUCCESS)
RegCloseKey(key);
return OpStatus::ERR;
}
OpString object_name;
if (OpStatus::IsSuccess(WindowsUtils::RegkeyToObjectname(m_ancestor_handle, m_key_name, object_name)))
{
OpString subkey_path;
RETURN_IF_ERROR(subkey_path.Set(m_key_name));
HKEY subkey;
do
{
int pos = subkey_path.FindLastOf('\\');
if (pos == KNotFound)
return OpStatus::ERR;
else
subkey_path.Delete(pos);
DWORD err = RegOpenKeyEx(m_ancestor_handle, subkey_path.CStr(), 0, KEY_CREATE_SUB_KEY, &subkey);
if (err == ERROR_SUCCESS)
RegCloseKey(subkey);
if (err == ERROR_SUCCESS || err == ERROR_ACCESS_DENIED)
{
RETURN_IF_ERROR(WindowsUtils::RegkeyToObjectname(m_ancestor_handle, subkey_path, object_name));
//Sometimes, opening the key succeeds even though we have no access
if (err == ERROR_ACCESS_DENIED || !WindowsUtils::CheckObjectAccess(object_name, SE_REGISTRY_KEY, KEY_QUERY_VALUE | KEY_SET_VALUE))
{
if (m_restore_access_info || !WindowsUtils::GiveObjectAccess(object_name, SE_REGISTRY_KEY, KEY_CREATE_SUB_KEY, FALSE, m_restore_access_info))
return OpStatus::ERR;
}
break;
}
if (err != ERROR_FILE_NOT_FOUND)
return OpStatus::ERR;
}
while (TRUE);
}
if (RegCreateKeyEx(m_ancestor_handle, m_key_name, NULL, NULL, 0, KEY_ALL_ACCESS, NULL, &key, NULL) == ERROR_SUCCESS)
{
RegCloseKey(key);
return OpStatus::OK;
}
return OpStatus::ERR;
}
void CreateRegKeyOperation::Undo()
{
OP_ASSERT(m_key_name.HasContent());
RegDeleteKeyNT(m_ancestor_handle, m_key_name);
}
HKEY CreateRegKeyOperation::GetAncestorHandle() const
{
return m_ancestor_handle;
}
const OpStringC& CreateRegKeyOperation::GetKeyName() const
{
return m_key_name;
}
CreateRegKeyOperation::~CreateRegKeyOperation()
{
if (m_restore_access_info)
WindowsUtils::RestoreAccessInfo(m_restore_access_info);
}
|
// 跨平台的epoll
// Created by 邦邦 on 2022/6/17.
//
#ifndef BB_S_EPOLL_H
#define BB_S_EPOLL_H
#include <cstring>
#include <csignal> //kill
#include <functional>
#include "bb/Log.h"
#include "IpTcp.h"
#include "bb/FloodIP.hpp"
namespace bb {
class S_Epoll {
IpTcp *tcp_{};
const unsigned short EPOLL_MAX_SIZE{2000}; //epoll_fd最大值
//添加epoll事件(往epoll(内核事件表)里添加事件)
bool addEventF_(int &epoll_fd,int &client_fd,uint32_t &client_ip,const unsigned &events);
//删除epoll事件
bool deleteEventF_(int &epoll_fd, int &client_fd);
//修改epoll事件
bool modifyEventF_(int &epoll_fd, int &client_fd,const unsigned &events);
public:
S_Epoll(const int &port,const unsigned &timeout){
tcp_ = new IpTcp({}, port,timeout);
}
~S_Epoll(){
delete tcp_;
}
//epoll使用
void runF(const std::function<bool(int &client_fd,unsigned &client_ip)> &f);
};
}
#endif //BB_S_EPOLL_H
|
// Created on: 2015-07-14
// Created by: Irina KRYLOVA
// Copyright (c) 2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepDimTol_SimpleDatumReferenceModifier_HeaderFile
#define _StepDimTol_SimpleDatumReferenceModifier_HeaderFile
enum StepDimTol_SimpleDatumReferenceModifier {
StepDimTol_SDRMAnyCrossSection,
StepDimTol_SDRMAnyLongitudinalSection,
StepDimTol_SDRMBasic,
StepDimTol_SDRMContactingFeature,
StepDimTol_SDRMDegreeOfFreedomConstraintU,
StepDimTol_SDRMDegreeOfFreedomConstraintV,
StepDimTol_SDRMDegreeOfFreedomConstraintW,
StepDimTol_SDRMDegreeOfFreedomConstraintX,
StepDimTol_SDRMDegreeOfFreedomConstraintY,
StepDimTol_SDRMDegreeOfFreedomConstraintZ,
StepDimTol_SDRMDistanceVariable,
StepDimTol_SDRMFreeState,
StepDimTol_SDRMLeastMaterialRequirement,
StepDimTol_SDRMLine,
StepDimTol_SDRMMajorDiameter,
StepDimTol_SDRMMaximumMaterialRequirement,
StepDimTol_SDRMMinorDiameter,
StepDimTol_SDRMOrientation,
StepDimTol_SDRMPitchDiameter,
StepDimTol_SDRMPlane,
StepDimTol_SDRMPoint,
StepDimTol_SDRMTranslation
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef MESSAGE_CONSOLE_MANAGER_H
#define MESSAGE_CONSOLE_MANAGER_H
#ifdef OPERA_CONSOLE
#include "adjunct/quick/managers/DesktopManager.h"
#include "modules/console/opconsoleengine.h"
#include "modules/console/opconsolefilter.h"
#include "modules/console/opconsoleview.h"
class MailMessageDialog;
class MessageConsoleDialog;
#define g_message_console_manager (MessageConsoleManager::GetInstance())
/**
* This class keeps track of the dialog part of the message console dialog.
* It manages when it needs to be created, and inserts messages into it.
*
* This is the class that the OpConsoleView sees when it posts messages.
* It is the responsebility of this class to know if the visible dialog
* exists and to create it when needed. The interface consists mainly of
* two functions apart from the constructor and destructor:
*
* PostNewMessage receives a pointer to a message that is to be displayed.
* The MessageConsoleHandler makes sure that the dialog exists, and then
* calls the corresponding function in the dialog class to post the
* message.
*
* ConsoleDialogClosed MUST be called by the dialog when it is deleted. If the
* dialog fails to notify the handler that it has died, incoming new
* messages will not correctly trigger the creation of a new dialog
* before trying to insert the new message, which will lead to crashing
* or at least no message will be displayed.
*/
class MessageConsoleManager :
public DesktopManager<MessageConsoleManager>,
public OpConsoleViewHandler
{
public:
/**
* Constructor. You must also call Construct.
*/
MessageConsoleManager();
/**
* Second phase constructor.
* Creates the view that channels messages to this console.
* @return OpStatus::ERR_NO_MEMORY if OOM.
*/
virtual OP_STATUS Init();
/**
* Destructor. Deletes the view and makes sure that the dialog is closed.
*/
~MessageConsoleManager();
/**
* The function that is used by the view to post new messages to the
* console. This function creates a new dialog if it is closed, and
* decides wheter to bring it to the front and give it focus.
*
* The message may contain severities from the OpConsoleEngine::Severity enum, which are
* Debugging, Verbose, Information, Error and Critical. The console
* maps the severities to three different severities visually: Information,
* Warning and Error. Debugging and Verbose will be mapped to Information,
* Information will map to Warning, and Error and Critical will be
* mapped to Error. BUT: Messages with severity Critical will always cause
* the dialog to be brought to focus. So if you have a warning message
* that requires user attention, use severity critical. Also, the filter should
* allow messages with severity critical through even if that component is
* not selected.
*
* Messages from the mailer will get special treatment because this is the
* most common type of error that have to be displayed.
*
* @param message The message to display.
*
*/
OP_STATUS PostNewMessage(const OpConsoleEngine::Message* message);
/**
* If you need to post more than one message at a time to the console
* you should use BeginUpdate before the first message is posted,
* and EndUpdate after the last one is updated to speed up posting.
*/
void BeginUpdate();
void EndUpdate();
/**
* Function that is used to open the dialog regardless of whether there are messages or not.
* Used when the user manually opens the console from the Opera UI.
*
* @return OK when the dialog is opened or was already open. OOM if the dialog can't be created.
*/
OP_STATUS OpenDialog();
/**
* Funciton to open the dialog with a special component selected.
*
* Used when opening console to display mailer warnings.
*
* @param component The component to select.
* @param severity The severity to select.
* @return ERR if there was a problem, OK otherwise.
*/
OP_STATUS OpenDialog(OpConsoleEngine::Source component, OpConsoleEngine::Severity severity);
/**
* Closes the console dialog.
*
* Used to close the console dialog when needed
*/
void CloseDialog();
/**
* Console Dialog closed. The console dialog must call this function when it closes.
*
* This will enable the handler to null out the dialog pointer to avoid crashes and
* ensure that the dialog is displayed again, if a new message comes through.
*/
void ConsoleDialogClosed();
/**
* Mail Message Dialog closed. Must be called by the mail message dialog when it closes.
*
* Enables the handler to know if it needs to open a new dialog or if it can post the
* new message to the old dialog.
*/
void MailMessageDialogClosed();
// Message console interaction management. Allows the user to
// Change the filter from the message console while it is running.
/**
* Call to obtain current filtering state.
*
* @param source Set with current source filter value.
* @param severity Set with current severity filter value.
*/
void GetSelectedComponentAndSeverity(OpConsoleEngine::Source& source, OpConsoleEngine::Severity& severity);
/**
* Call when the user selected a specific component and severity.
* Updates the filter with the settings, but these settings will
* be dropped when the console is closed. Then the filter is reset
* to what the prefs say.
*
* @param source The source to set
* @param severity The severity to set.
*/
void SetSelectedComponentAndSeverity(OpConsoleEngine::Source source, OpConsoleEngine::Severity severity);
/**
* Call when the user selected all components and a specific severity.
* Updates the filter with the settings, but these settings will
* be dropped when the console is closed. Then the filter is reset
* to what the prefs say.
*
* @param severity The severity to set.
*/
void SetSelectedAllComponentsAndSeverity(OpConsoleEngine::Severity severity);
/**
* Call when the user cleared the filter.
* This sets a permanent cutoff point in the filter that will be persistent
* even after the user closes the message console.
*/
void UserClearedConsole();
/**
* Turn M2 console loggin on or off.
*
* @param enable TRUE to turn M2 logging on, FALSE to turn off.
*/
void SetM2ConsoleLogging(BOOL enable);
// Message console preferences management. (For JavaScript)
/**
* Turn JavaScript errors on or off.
*/
void SetJavaScriptConsoleLogging(BOOL enable);
/**
* Retrieve the JavaScript setting
*/
BOOL GetJavaScriptConsoleSetting();
/**
* Turn JavaScript errors on or off for a specific site.
* The change only applies if the site setting is _different_
* from the previous setting, or the general setting.
* This means that you don't get site settings written
* unless you actually change the setting for a site.
*/
void SetJavaScriptConsoleLoggingSite(const OpString &site, BOOL enable);
/**
* Retrieves site specific JavaScript console setting.
* If this site is not overridden it returns the general
* javascript console setting.
*/
BOOL GetJavaScriptConsoleSettingSite(const OpString &site);
private:
// Members
MessageConsoleDialog* m_message_console_dialog; ///< The dialog that this instance keeps track of.
MailMessageDialog* m_mail_message_dialog; ///< The mail message dialog that will open on mail errors.
OpConsoleView* m_using_view; ///< The console view that this handler created to listen for messages.
OpConsoleEngine::Source m_last_source; ///< The source filter setting stored per session.
OpConsoleEngine::Severity m_last_severity; ///< The severity filter setting stored per session.
/**
* This function ensures that the member m_message_console_dialog exists. If
* it doesen't it will instantiates a new MessageConsoleDialog on the heap using new, and calls Init on it.
* It will return OOM if new fails.
* @param front_and_focus If true, the dialog is brought to front and focussed. Otherwise it is left to whatever state it is in.
*/
OP_STATUS MakeNewMessageConsole(BOOL front_and_focus);
/**
* Function to read the current filter state from prefs.
* @param filter The filter to fill with information.
* @return OK if the read was ok, ERR otherwise.
*/
OP_STATUS ReadFilterFromPrefs(OpConsoleFilter &filter);
/**
* Function to write a filter to prefs.
* @param filter The filter to write.
* @return OK if the write was successful, ERR otherwise.
*/
OP_STATUS WriteFilterToPrefs(const OpConsoleFilter &filter);
};
#endif // OPERA_CONSOLE
#endif // MESSAGE_CONSOLE_MANAGER_H
|
#include "Butterfly.hpp"
using namespace bfly;
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!GLOBAL STATES AND VARIABLES!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
int component_counter = 0;
GLuint vertices_id;
GLuint edges_id;
GLuint program_id;
GLuint check_full;
GLuint orto_location;
GLuint model_location;
GLuint type_location;
GLuint color1_location;
GLuint color2_location;
GLuint opacity_location;
GLuint rect_size_location;
GLuint border_width_location;
GLuint z_location;
bool mouse_hold = false;
bool mouse_click = false;
bool mouse_hold_begin = false;
bool mouse_hold_end = false;
int mouse_state = GLFW_RELEASE;
int key_pressed = -1;
Style panel_style;
Font regular_font;
int mouse_x = 0;
int mouse_y = 0;
int delta_x=0;
int delta_y=0;
int window_height = 0;
pair<Drawable *, float> focused_element = make_pair(nullptr, -1.0f);
pair<Drawable *, float> current_focused_element = make_pair(nullptr, -1.0f);
//!!!!!!!!!!!!!!!!!!!!
//!!HELPER FUNCTIONS!!
//!!!!!!!!!!!!!!!!!!!!
void focus(Drawable *d)
{
if (d != nullptr)
{
focused_element = make_pair(d, 0);
}
}
void clear_focus()
{
if (focused_element.first != nullptr)
{
focused_element.first->on_focus_lost();
}
focused_element = make_pair(nullptr, -1.0f);
}
void update_focus(pair<Drawable *, float> p)
{
if (current_focused_element.second <= p.second)
current_focused_element = make_pair(p.first, p.second);
}
void compute_focus()
{
if (current_focused_element.first != nullptr)
{
current_focused_element.first->on_focus();
current_focused_element = make_pair(nullptr, -1.0f);
}
else
{
if (mouse_click)
clear_focus();
}
}
void load_projection_matrix(float left, float right, float up, float down)
{
float znear = -1.0f;
float zfar = 1.0f;
float mat[4][4] = {
{2.0f / (right - left), 0, 0, -(right + left) / (right - left)},
{0, 2.0f / (up - down), 0, -(up + down) / (up - down)},
{0, 0, -2.0f / (zfar - znear), -(zfar + znear) / (zfar - znear)},
{0, 0, 0, 1.0f}};
glUniformMatrix4fv(orto_location, 1, GL_TRUE, &(mat[0][0]));
}
void load_model_matrix(float x, float y, float width, float heigth)
{
float mat[4][4] = {
{width, 0, 0, x},
{0, heigth, 0, y},
{0, 0, 1, 0},
{0, 0, 0, 1}};
glUniformMatrix4fv(model_location, 1, GL_TRUE, &(mat[0][0]));
}
bool mouse_in_rect(Rectangle r)
{
return (mouse_x >= r.x && mouse_x <= r.x + r.width && mouse_y >= r.y && mouse_y <= r.y + r.height);
}
void load_vec3(GLuint id, Vector3 v)
{
glUniform3f(id, v.r, v.g, v.b);
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!IMAGE AND FILE LOADING!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!
GLuint load_bmp(string path)
{
ifstream file(path, ios::binary | ios::in);
GLuint text_id;
if (file.is_open())
{
char buffer[10];
unsigned int width;
unsigned int heigth;
unsigned int bit_per_pixel;
unsigned int data_position;
file.read(buffer, 2);
file.read(buffer, 4);
file.read(buffer, 2);
file.read(buffer, 2);
file.read(buffer, 4);
memcpy(&data_position, buffer, sizeof(unsigned int));
file.read(buffer, 4);
file.read(buffer, 4);
memcpy(&width, buffer, sizeof(unsigned int));
file.read(buffer, 4);
memcpy(&heigth, buffer, sizeof(unsigned int));
file.read(buffer, 2);
file.read(buffer, 2);
memcpy(&bit_per_pixel, buffer, sizeof(unsigned int));
if (bit_per_pixel != 24 && bit_per_pixel != 32)
{
cerr << "Bfly error when loading image data for" << path << endl;
cerr << "image contains " << bit_per_pixel << " bits per pixel" << endl;
cerr << "image is not 24 bits per pixel or 32 bits per pixel" << endl;
return 0;
}
file.seekg(data_position);
char pixels[width][heigth * (bit_per_pixel / 8)];
for (int i = 0; i < heigth; i++)
for (int j = 0; j < width; j++)
{
unsigned int r;
unsigned int g;
unsigned int b;
unsigned int a;
file.read(buffer, 1);
memcpy(&b, buffer, sizeof(unsigned int));
file.read(buffer, 1);
memcpy(&g, buffer, sizeof(unsigned int));
file.read(buffer, 1);
memcpy(&r, buffer, sizeof(unsigned int));
if (bit_per_pixel == 32)
{
file.read(buffer, 1);
memcpy(&a, buffer, sizeof(unsigned int));
pixels[heigth - (i + 1)][4 * j] = g;
pixels[heigth - (i + 1)][4 * j + 1] = b;
pixels[heigth - (i + 1)][4 * j + 2] = r;
pixels[heigth - (i + 1)][4 * j + 3] = a;
}
else
{
pixels[heigth - (i + 1)][3 * j] = g;
pixels[heigth - (i + 1)][3 * j + 1] = b;
pixels[heigth - (i + 1)][3 * j + 2] = r;
}
}
glGenTextures(1, &text_id);
glBindTexture(GL_TEXTURE_2D, text_id);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D,
GL_TEXTURE_MIN_FILTER, GL_NEAREST);
if (bit_per_pixel == 24)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, heigth, 0, GL_RGB, GL_UNSIGNED_BYTE, &pixels);
else
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, heigth, 0, GL_RGBA, GL_UNSIGNED_BYTE, &pixels);
file.close();
return text_id;
}
cerr << "Bfly couldn't open " << path << endl;
return 0;
}
Font load_font(string path)
{
Font fnt;
ifstream file(path + ".fnt");
string line;
while (getline(file, line))
{
if (!line.rfind("char id=", 0))
{
int x, y, w, h, xo, yo, xa;
int c;
sscanf(line.c_str(), "char id=%d x=%d y=%d width=%d height=%d xoffset=%d yoffset=%d xadvance=%d", &c, &x, &y, &w, &h, &xo, &yo, &xa);
fnt.characters[c] = {x, y, w, h, xo, yo, xa};
}
if (!line.rfind("common lineHeight", 0))
{
int lin;
int base;
int sw;
int sh;
sscanf(line.c_str(), "common lineHeight=%d base=%d scaleW=%d scaleH=%d", &lin, &base, &sw, &sh);
fnt.line_height = lin;
fnt.base = base;
fnt.scale_w = sw;
fnt.scale_h = sh;
}
if (!line.rfind("info face=", 0))
{
int size;
char name[50];
sscanf(line.c_str(), "info face=\"%s size=%d", name, &size);
fnt.size = size;
fnt.name = string(name);
fnt.name.pop_back();
}
}
fnt.font_atlas = load_bmp(path + ".bmp");
return fnt;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!INPUT HANDLING SECTION!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!
void character_callback(GLFWwindow *window, unsigned int codepoint)
{
key_pressed = codepoint;
}
void key_callback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
}
void mouse_button_callback(GLFWwindow *window, int button, int action, int mods)
{
if (action == GLFW_PRESS)
{
mouse_hold = true;
}
if (action == GLFW_RELEASE && mouse_state == GLFW_PRESS)
{
mouse_click = true;
mouse_hold = false;
mouse_hold_end = true;
}
if (action == GLFW_PRESS && mouse_state == GLFW_RELEASE)
{
mouse_hold_begin=true;
}
mouse_state = action;
}
void cursor_position_callback(GLFWwindow *window, double xpos, double ypos)
{
delta_x=(int)xpos-mouse_x;
delta_y=(int)ypos-mouse_y;
mouse_x = (int)xpos;
mouse_y = (int)ypos;
}
void Butterfly_Input(GLFWwindow *window)
{
glfwPollEvents();
glfwSetKeyCallback(window, key_callback);
glfwSetMouseButtonCallback(window, mouse_button_callback);
glfwSetCharCallback(window, character_callback);
glfwSetCursorPosCallback(window, cursor_position_callback);
}
void Butterfly_Refresh()
{
key_pressed = -1;
mouse_click = false;
mouse_hold_begin = false;
mouse_hold_end = false;
delta_x=0;
delta_y=0;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!CONSTRUCTORS AND DATA INITIALIZATION!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void Styles_Initialize()
{
regular_font = load_font("./Resources/Butterfly");
panel_style.font = regular_font;
panel_style.color1 = {0.32f, 0.34f, 0.32f};
panel_style.color2 = {0.22f, 0.24f, 0.22f};
panel_style.border_width = 1;
panel_style.opacity = 1.0f;
panel_style.text_color = {1.0f, 1.0f, 1.0f};
panel_style.text_size = 25;
panel_style.border_color = {0.9f, 0.9f, 0.9f};
}
void Butterfly_Initialize()
{
Styles_Initialize();
load_bmp("Resources/ikon.bmp");
load_bmp("Resources/down.bmp");
load_bmp("Resources/right.bmp");
check_full = load_bmp("Resources/check.bmp");
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
ifstream file("./Resources/v_shader.vert");
if (file.is_open())
{
stringstream ss;
ss << file.rdbuf();
string s = ss.str();
const char *text = s.c_str();
glShaderSource(vertex_shader, 1, &text, NULL);
glCompileShader(vertex_shader);
int result;
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &result);
if (!result)
{
char info[512];
glGetShaderInfoLog(vertex_shader, 512, NULL, info);
cerr << "Bfly Error compiling vertex shader" << endl;
cerr << info << endl;
}
file.close();
}
else
cerr << "error opening vertex shader" << endl;
file.open("./Resources/f_shader.frag");
if (file.is_open())
{
stringstream ss;
ss << file.rdbuf();
string s = ss.str();
const char *text = s.c_str();
glShaderSource(fragment_shader, 1, &text, NULL);
glCompileShader(fragment_shader);
int result;
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &result);
if (!result)
{
char info[512];
glGetShaderInfoLog(fragment_shader, 512, NULL, info);
cerr << "Bfly Error compiling fragment shader" << endl;
cerr << info << endl;
}
}
else
cerr << "error opening vertex shader" << endl;
program_id = glCreateProgram();
glAttachShader(program_id, vertex_shader);
glAttachShader(program_id, fragment_shader);
glLinkProgram(program_id);
int result;
glGetProgramiv(program_id, GL_LINK_STATUS, &result);
if (!result)
{
char info[512];
glGetProgramInfoLog(program_id, 512, NULL, info);
cerr << "Bfly Error linking shaders" << endl;
}
orto_location = glGetUniformLocation(program_id, "projection");
model_location = glGetUniformLocation(program_id, "model");
type_location = glGetUniformLocation(program_id, "type");
color1_location = glGetUniformLocation(program_id, "color1");
color2_location = glGetUniformLocation(program_id, "color2");
opacity_location = glGetUniformLocation(program_id, "opacity");
rect_size_location = glGetUniformLocation(program_id, "rect_size");
border_width_location = glGetUniformLocation(program_id, "border_width");
z_location = glGetUniformLocation(program_id, "z");
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
float array[] = {
0.0, 0.0,
1.0, 0.0,
1.0, 1.0,
1.0, 1.0,
0.0, 1.0,
0.0, 0.0};
GLuint vbo;
glGenVertexArrays(1, &vertices_id);
glBindVertexArray(vertices_id);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(array), array, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void *)0);
glEnableVertexAttribArray(1);
glBindVertexArray(0);
glBindVertexArray(0);
}
GLuint make_text(string text, Style &style, float &text_width, float &text_height)
{
float scale = (float)style.text_size / (float)style.font.line_height;
GLuint vao;
GLuint vbo;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
vector<float> arr;
float x_it = 0;
float y_it = 0;
text_width = 0;
text_height = 0;
for (auto it : text)
{
Glyph glyph = style.font.characters[it];
float x0 = x_it + glyph.x_off * scale;
float x1 = x0 + glyph.width * scale;
float y0 = y_it + (glyph.y_off * scale);
float y1 = y0 + glyph.height * scale;
if (fabs(y1) > text_height)
text_height = fabs(y1);
float ux = (float)glyph.uv_x / (float)style.font.scale_w;
float ux1 = ux + (float)glyph.width / (float)style.font.scale_w;
float uy = (float)glyph.uv_y / style.font.scale_h;
float uy1 = uy + (float)glyph.height / (float)style.font.scale_h;
float ar[] = {
x0, y0, ux, uy,
x1, y0, ux1, uy,
x1, y1, ux1, uy1,
x1, y1, ux1, uy1,
x0, y1, ux, uy1,
x0, y0, ux, uy};
for (auto f : ar)
arr.push_back(f);
x_it += glyph.x_adv * scale;
}
text_width = x_it;
glBufferData(GL_ARRAY_BUFFER, arr.size() * sizeof(float), &arr[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void *)(2 * sizeof(float)));
glEnableVertexAttribArray(1);
glBindVertexArray(0);
return vao;
}
void Component::set_text(string t)
{
if (text != t)
{
text = t;
glDeleteVertexArrays(1, &vao);
vao = make_text(text, style, text_width, text_height);
}
}
void Component::set_text_size(int size)
{
if (style.text_size != size)
{
style.text_size = size;
glDeleteVertexArrays(1, &vao);
vao = make_text(text, style, text_width, text_height);
}
}
Panel::Panel() : Component("tmp_panel_" + to_string(component_counter++))
{
rect = {50, 50, 400, 400};
name = "tmp_panel_" + to_string(component_counter++);
tooltip = "";
text = "header";
elements.clear();
style = panel_style;
style.color1 = {0.4f, 0.42f, 0.41f};
style.color2 = {0.34f, 0.32f, 0.33f};
vao = make_text(text, style, text_width, text_height);
z=-0.5f;
horizontal=new ScrollBar();
horizontal->set_position(rect.x,rect.height+rect.y-20);
horizontal->set_width(rect.width);
vertical=new ScrollBar();
vertical->set_position(rect.x,rect.y+26);
vertical->set_size(20,rect.height-20);
vertical->set_orientation(VERTICAL_SLIDER);
}
Label::Label():Component("tmp_label_" + to_string(component_counter++)){
rect = {75, 75, 100, 35};
tooltip = "";
text = "label";
style = panel_style;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
icon = false;
state = IDLE;
order=LEFT_TO_RIGHT;
allign_h=LEFT;
allign_v=TOP;
}
Button::Button() : Component("tmp_button_" + to_string(component_counter++))
{
rect = {75, 75, 100, 35};
tooltip = "";
text = "button";
style = panel_style;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
click = nullptr;
background_rectangle = true;
icon = false;
state = IDLE;
order=LEFT_TO_RIGHT;
}
void Button::rect_uniforms()
{
glUniform1i(type_location, 0);
if (state == IDLE)
{
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
}
if (state == HOVER)
{
load_vec3(color1_location, press_color);
load_vec3(color2_location, press_color);
}
if (state == PRESS)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
if (state == CLICKED)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
}
void Slider::rect_uniforms(){
glUniform1i(type_location, 0);
if (state == IDLE)
{
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
}
if (state == HOVER)
{
load_vec3(color1_location, press_color);
load_vec3(color2_location, press_color);
}
if (state == PRESS)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
if (state == CLICKED)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
}
ToggleButton::ToggleButton() : Component("tmp_toggle_button" + to_string(component_counter++))
{
rect = {75, 75, 100, 35};
tooltip = "";
text = "toggle";
style = panel_style;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
toggle = nullptr;
background_rectangle = true;
icon = false;
value = false;
}
void ToggleButton::rect_uniforms()
{
glUniform1i(type_location, 0);
if (state == IDLE)
{
if (value)
{
load_vec3(color1_location, {0.2f, 0.30f, 0.20f});
load_vec3(color2_location, {0.2f, 0.30f, 0.20f});
}
else
{
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
}
}
if (state == HOVER)
{
load_vec3(color1_location, press_color);
load_vec3(color2_location, press_color);
}
if (state == PRESS)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
if (state == CLICKED)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
}
CheckBox::CheckBox() : Component("tmp_checkbox" + to_string(component_counter++))
{
rect = {75, 75, 100, 35};
tooltip = "";
text = "checkbox";
style = panel_style;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
toggle = nullptr;
icon = false;
value = false;
}
RadioButton::RadioButton() : Component("tmp_radio" + to_string(component_counter++))
{
rect = {75, 75, 100, 35};
tooltip = "";
text = "radio button";
style = panel_style;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
toggle = nullptr;
icon = false;
value = false;
}
ComboItem::ComboItem() : Component("tmp_combo_item" + to_string(component_counter++))
{
rect = {75, 75, 175, 25};
tooltip = "";
text = "combo item";
style = panel_style;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
opened = false;
sub_item_width = 175;
sub_item_height = 25;
}
ComboBox::ComboBox() : Component("tmp_combo_box" + to_string(component_counter++))
{
rect = {75, 75, 175, 25};
tooltip = "";
text = "combo box";
style = panel_style;
style.text_size = rect.height - 1;
vao = make_text(text, style, text_width, text_height);
image_id = 0;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
opened = false;
item_width = 175;
item_height = 25;
selected = nullptr;
opened = false;
change = nullptr;
}
void ComboBox::set_default_text(string t)
{
glDeleteVertexArrays(1, &default_vao);
default_vao = make_text(t, style, text_width, text_height);
}
void ComboBox::rect_uniforms()
{
glUniform1i(type_location, 0);
if (state == IDLE)
{
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
}
if (state == HOVER)
{
load_vec3(color1_location, press_color);
load_vec3(color2_location, press_color);
}
if (state == PRESS)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
if (state == CLICKED)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
}
void ComboBox::change_selected(ComboItem *item)
{
if (item != nullptr && item != selected)
{
glDeleteVertexArrays(1, &vao);
selected = item;
vao = make_text(selected->get_text(), style, text_width, text_height);
image_id=item->get_image();
if (change != nullptr)
change();
}
}
void ComboItem::rect_uniforms()
{
glUniform1i(type_location, 0);
if (state == IDLE)
{
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
}
if (state == HOVER)
{
load_vec3(color1_location, press_color);
load_vec3(color2_location, press_color);
}
if (state == PRESS)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
if (state == CLICKED)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
}
Slider::Slider():Component("tmp_slider_" + to_string(component_counter++)){
minimum=0;
maximum=100;
value=0;
step=1;
orientation=HORIZONTAL_SLIDER;
rect = {75, 75, 175, 25};
tooltip = "";
text = "0";
style = panel_style;
style.text_size = rect.height - 1;
vao = make_text(text, style, text_width, text_height);
rect.width+=text_width;
image_id = 0;
state = IDLE;
slider_size=10;
}
ScrollBar::ScrollBar():Component("tmp_scrollbar" + to_string(component_counter++)){
maximum=0;
hidden=true;
slider_position=0;
orientation=HORIZONTAL_SLIDER;
rect = {75, 75, 100, 20};
style = panel_style;
style.text_size = 0;
vao = 0;
image_id = 0;
state = IDLE;
press_color = {style.color1.r + 0.1f, style.color1.g + 0.1f, style.color1.b + 0.1f};
click_color = {style.color1.r + 0.05f, style.color1.g + 0.05f, style.color1.b + 0.05f};
}
void ScrollBar::rect_uniforms()
{
glUniform1i(type_location, 0);
if (state == IDLE)
{
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
}
if (state == HOVER)
{
load_vec3(color1_location, press_color);
load_vec3(color2_location, press_color);
}
if (state == PRESS)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
if (state == CLICKED)
{
load_vec3(color1_location, click_color);
load_vec3(color2_location, click_color);
}
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!DRAWING METHODS!!!!!!!!!!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void draw_rectangle(Rectangle r)
{
load_model_matrix((float)r.x, (float)r.y, (float)r.width, (float)r.height);
glBindVertexArray(vertices_id);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
}
void draw_text(GLuint vao, int x, int y, int size)
{
load_model_matrix((float)x, (float)y, 1, 1);
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, size);
glBindVertexArray(0);
}
void Panel::prepare_style()
{
glUniform3f(color1_location, style.color1.r, style.color1.g, style.color1.b);
glUniform3f(color2_location, style.color2.r, style.color2.g, style.color2.b);
glUniform1f(opacity_location, style.opacity);
glUniform1i(type_location, 0);
}
void Panel::prepare_style_text()
{
glUniform3f(color1_location, style.text_color.r, style.text_color.g, style.text_color.b);
glUniform1f(opacity_location, style.opacity);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
glUniform1i(type_location, 1);
}
void Panel::prepare_style_header()
{
glUniform3f(color1_location, style.color1.r, style.color1.g, style.color1.b);
glUniform3f(color2_location, style.color2.r, style.color2.g, style.color2.b);
glUniform1f(opacity_location, style.opacity);
glUniform1i(type_location, 0);
}
void Panel::draw()
{
glUniform1i(border_width_location, style.border_width);
glUniform2f(rect_size_location, rect.width, rect.height);
glUniform1f(opacity_location, style.opacity);
glUniform1f(z_location, z);
prepare_style();
draw_rectangle(rect);
prepare_style_header();
glUniform2f(rect_size_location, rect.width, style.text_size + 2);
draw_rectangle({rect.x, rect.y, rect.width, style.text_size + 2});
prepare_style_text();
draw_text(vao, rect.x + 5, rect.y, text.size() * 12);
float box[4];
glGetFloatv(GL_SCISSOR_BOX, box);
glScissor(rect.x, window_height - rect.y - rect.height, rect.width, rect.height);
for (auto it : elements){
int x_curr=it->get_x();
int y_curr=it->get_y();
it->set_x(it->get_x()-horizontal->get_value());
it->set_y(it->get_y()-vertical->get_value());
it->draw();
it->set_x(x_curr);
it->set_y(y_curr);
}
horizontal->draw();
vertical->draw();
glScissor(box[0], box[1], box[2], box[3]);
}
void Button::draw()
{
glUniform1i(border_width_location, style.border_width);
glUniform2f(rect_size_location, rect.width, rect.height);
glUniform1f(z_location, z);
process_events();
float box[4];
glGetFloatv(GL_SCISSOR_BOX, box);
glScissor(max(rect.x,(int)box[0]), window_height - rect.y - rect.height, rect.width, rect.height);
if (background_rectangle)
{
rect_uniforms();
draw_rectangle(rect);
}
int x_pos = 0;
int y_pos = 0;
x_pos = rect.width - text_width;
if (icon)
x_pos -= text_height;
y_pos = rect.height - text_height;
x_pos = max(0, x_pos / 2);
y_pos = max(0, y_pos / 2);
if (!icon)
{
glBindTexture(GL_TEXTURE_2D, image_id);
glUniform1i(type_location, 2);
if (image_id != 0)
draw_rectangle({rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1});
}
else
{
glBindTexture(GL_TEXTURE_2D, image_id);
glUniform1i(type_location, 2);
int ord = 0;
if (order == LEFT_TO_RIGHT)
ord = text_width;
if (image_id != 0)
draw_rectangle({rect.x + x_pos + ord, rect.y + y_pos, (int)text_height, (int)text_height});
}
load_vec3(color1_location, style.text_color);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
glUniform1i(type_location, 1);
int ord = 0;
if (order == RIGHT_TO_LEFT)
ord = +text_height;
draw_text(vao, rect.x + x_pos + ord, rect.y + y_pos, text.size() * 12);
glScissor(box[0], box[1], box[2], box[3]);
}
void Label::draw(){
glUniform1f(opacity_location, style.opacity);
glUniform1f(z_location, z);
process_events();
float box[4];
glGetFloatv(GL_SCISSOR_BOX, box);
glScissor(max(rect.x,(int)box[0]), window_height - rect.y - rect.height, rect.width, rect.height);
if(icon==false){
glBindTexture(GL_TEXTURE_2D,image_id);
glUniform1i(type_location,2);
if(image_id!=0)
draw_rectangle(rect);
}
float width=text_width;
if(icon==true)
width+=4+text_height;
float x_pos=0;
float y_pos=0;
if(allign_h==LEFT) x_pos=rect.x;
if(allign_h==CENTER) {
x_pos=rect.width-width;
x_pos=max(0.0f,x_pos/2.0f);
x_pos=rect.x+x_pos;
}
if(allign_h==RIGHT) x_pos=rect.x+rect.width-width;
if(allign_v==TOP) y_pos=rect.y;
if(allign_v==CENTER) {
y_pos=rect.height-text_height;
y_pos=max(0.0f,y_pos/2.0f);
y_pos=rect.y+y_pos;
}
if(allign_v==BOTTOM) y_pos=rect.y+rect.height-text_height;
glBindTexture(GL_TEXTURE_2D,style.font.font_atlas);
glUniform1i(type_location,1);
load_vec3(color1_location,style.text_color);
draw_text(vao,x_pos,y_pos,text.size()*12);
if(icon){
glBindTexture(GL_TEXTURE_2D,image_id);
glUniform1i(type_location,2);
if(image_id!=0)
draw_rectangle({(int)(x_pos+text_width),(int)y_pos,(int)text_height,(int)text_height});
}
glScissor(box[0], box[1], box[2], box[3]);
}
void ToggleButton::draw()
{
glUniform1i(border_width_location, style.border_width);
glUniform2f(rect_size_location, rect.width, rect.height);
glUniform1f(z_location, z);
process_events();
float box[4];
glGetFloatv(GL_SCISSOR_BOX, box);
glScissor(max(rect.x,(int)box[0]), window_height - rect.y - rect.height, rect.width, rect.height);
if (background_rectangle)
{
rect_uniforms();
draw_rectangle(rect);
}
int x_pos = 0;
int y_pos = 0;
x_pos = rect.width - text_width;
if (icon)
x_pos -= text_height;
y_pos = rect.height - text_height;
x_pos = max(0, x_pos / 2);
y_pos = max(0, y_pos / 2);
if (!icon)
{
glBindTexture(GL_TEXTURE_2D, image_id);
glUniform1i(type_location, 2);
if (image_id != 0)
draw_rectangle({rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1});
}
else
{
glBindTexture(GL_TEXTURE_2D, image_id);
glUniform1i(type_location, 2);
int ord = 0;
if (order == LEFT_TO_RIGHT)
ord = text_width;
if (image_id != 0)
draw_rectangle({rect.x + x_pos + ord, rect.y + y_pos, (int)text_height, (int)text_height});
}
load_vec3(color1_location, style.text_color);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
glUniform1i(type_location, 1);
int ord = 0;
if (order == RIGHT_TO_LEFT)
ord = +text_height;
draw_text(vao, rect.x + x_pos + ord, rect.y + y_pos, text.size() * 12);
glScissor(box[0], box[1], box[2], box[3]);
}
void CheckBox::draw()
{
glUniform1i(border_width_location, style.border_width);
glUniform2f(rect_size_location, text_height, text_height);
glUniform1f(z_location, z);
process_events();
glUniform1i(type_location, 1);
load_vec3(color1_location, style.text_color);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
draw_text(vao, rect.x, rect.y, text.size() * 12);
glUniform1i(type_location, 0);
glBindTexture(GL_TEXTURE_2D, check_full);
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
draw_rectangle({rect.x + (int)text_width + 5, rect.y + 2, (int)text_height, (int)text_height});
if (value)
{
glUniform1i(type_location, 2);
draw_rectangle({rect.x + (int)text_width + 5, rect.y + 2, (int)text_height, (int)text_height});
}
}
void RadioButton::draw()
{
glUniform1i(border_width_location, style.border_width);
glUniform2f(rect_size_location, text_height, text_height);
glUniform1f(z_location, z);
process_events();
glUniform1i(type_location, 1);
load_vec3(color1_location, style.text_color);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
draw_text(vao, rect.x, rect.y, text.size() * 12);
glUniform1i(type_location, 3);
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
draw_rectangle({rect.x + (int)text_width + 5, rect.y + 2, (int)text_height, (int)text_height});
if (value)
{
load_vec3(color1_location, {0.2f, 0.3f, 0.2f});
draw_rectangle({rect.x + (int)text_width + 5, rect.y + 2, (int)text_height, (int)text_height});
}
}
void ComboItem::draw()
{
glUniform1i(border_width_location, 0);
glUniform2f(rect_size_location, text_height, text_height);
glUniform1f(z_location, 1);
process_events();
rect_uniforms();
if(state==HOVER || state==PRESS || state==CLICKED)
draw_rectangle({rect.x+1,rect.y+1,rect.width-1,rect.height-1});
glUniform1i(type_location, 1);
load_vec3(color1_location, style.text_color);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
draw_text(vao, rect.x + text_height + 5, rect.y, text.size() * 12);
if (image_id != 0)
{
glUniform1i(type_location, 2);
glBindTexture(GL_TEXTURE_2D, image_id);
draw_rectangle({rect.x, rect.y+2, (int)text_height, (int)text_height});
}
if (sub_items.size() >= 1)
{
glUniform1i(type_location, 2);
glBindTexture(GL_TEXTURE_2D, 4);
draw_rectangle({rect.x + rect.width - rect.height, rect.y+5, (int)text_height, (int)text_height});
if (opened)
{
int x = rect.x + rect.width;
int y = rect.y;
glUniform2f(rect_size_location, rect.width, (int)sub_items.size() * sub_item_height);
glUniform1i(type_location, 0);
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
glUniform1i(border_width_location, 1);
draw_rectangle({x, rect.y, sub_item_width, (int)sub_items.size() * sub_item_height});
for (auto it : sub_items)
{
it->set_position(x, y);
it->draw();
y += sub_item_height;
}
}
}
}
void ComboBox::draw()
{
glUniform1i(border_width_location, style.border_width);
glUniform2f(rect_size_location, rect.width, rect.height);
glUniform1f(z_location, z);
process_events();
rect_uniforms();
draw_rectangle(rect);
if(image_id!=0){
glUniform1i(type_location, 2);
glBindTexture(GL_TEXTURE_2D, image_id);
draw_rectangle({rect.x+5,rect.y+2,(int)text_height,(int)text_height});
}
glUniform1i(type_location, 1);
load_vec3(color1_location, style.text_color);
glBindTexture(GL_TEXTURE_2D, style.font.font_atlas);
draw_text(vao, rect.x + 10+text_height, rect.y, text.size() * 12);
glUniform1i(type_location, 2);
glBindTexture(GL_TEXTURE_2D, 3);
draw_rectangle({rect.x + rect.width - rect.height - 5, rect.y, rect.height, rect.height});
float x = rect.x;
float y = rect.y + rect.height;
if (opened)
{
glUniform2f(rect_size_location, rect.width, (int)items.size() * item_height );
glUniform1i(type_location, 0);
load_vec3(color1_location, style.color1);
load_vec3(color2_location, style.color2);
glUniform1f(z_location, 1.0f);
draw_rectangle({rect.x, rect.y + rect.height, item_width, (int)items.size() * item_height});
for (auto it : items)
{
it->set_z(1.0f);
it->set_position(x, y);
it->draw();
y += item_height;
}
}
}
void Slider::draw(){
glUniform1i(border_width_location, 0);
glUniform2f(rect_size_location, rect.width, rect.height);
glUniform1f(z_location, 0);
process_events();
load_vec3(color1_location,style.color1);
load_vec3(color2_location,style.color2);
glUniform1i(type_location,0);
draw_rectangle({rect.x,rect.y+rect.height/2-2,rect.width,4});
rect_uniforms();
float scale=value/(maximum-minimum);
int x_pos=(int)(scale*((float)rect.width-text_height));
glUniform1i(type_location,3);
glUniform1i(border_width_location, 1);
glUniform2f(rect_size_location, rect.height, rect.height);
draw_rectangle({rect.x+x_pos,rect.y+2,(int)text_height,(int)text_height});
load_vec3(color1_location,style.text_color);
glBindTexture(GL_TEXTURE_2D,style.font.font_atlas);
glUniform1i(type_location,1);
draw_text(vao,rect.x+rect.width+5,rect.y,text.size()*12);
}
void ScrollBar::draw(){
glUniform1i(border_width_location, 0);
glUniform2f(rect_size_location, rect.width, rect.height);
glUniform1i(border_width_location, 1);
glUniform1f(z_location, 0);
process_events();
glUniform3f(color1_location+0.1, style.color1.r+0.1, style.color1.g+0.1, style.color1.b+0.1);
glUniform3f(color2_location+0.1, style.color2.r+0.1, style.color2.g+0.1, style.color2.b+0.1);
glUniform1i(type_location,0);
draw_rectangle(rect);
rect_uniforms();
if(orientation==HORIZONTAL_SLIDER){
glUniform2f(rect_size_location, slider_size, rect.height);
draw_rectangle({rect.x+slider_position,rect.y,slider_size,rect.height});
}
else{
glUniform2f(rect_size_location, rect.width, slider_size);
draw_rectangle({rect.x,rect.y+slider_position,rect.width,slider_size});
}
}
void Window::draw(GLFWwindow *window)
{
glUseProgram(program_id);
int w, h;
glfwGetFramebufferSize(window, &w, &h);
load_projection_matrix(0, w, 0, h);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_SCISSOR_TEST);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glScissor(0, 0, w, h);
window_height = h;
glViewport(0, 0, w, h);
for (auto panel : panels)
panel->draw();
compute_focus();
glDisable(GL_SCISSOR_TEST);
glDisable(GL_BLEND);
glDisable(GL_DEPTH_TEST);
glUseProgram(0);
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!EVENT PROCESSING METHODS!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void Button::process_events()
{
if (mouse_in_rect(rect))
{
update_focus(make_pair(this, z));
}
else
state = IDLE;
}
void Label::process_events(){
if (mouse_in_rect(rect))
{
update_focus(make_pair(this, z));
}
}
void ToggleButton::process_events()
{
int box[4];
glGetIntegerv(GL_SCISSOR_BOX, box);
int real_x=max(box[0],rect.x);
int real_width=min(box[0]+box[2]-rect.x,rect.width);
Rectangle real_rect=rect;
real_rect.x=real_x;
real_rect.width=real_width;
int real_y=max(box[0],rect.y);
int real_height=min(box[1]+box[3]-rect.y,rect.height);
real_rect.y=real_y;
real_rect.height=real_height;
if(mouse_in_rect(real_rect))
{
update_focus(make_pair(this, z));
}
else
state = IDLE;
}
void CheckBox::process_events()
{
if (mouse_in_rect({rect.x + (int)text_width + 5, rect.y + 2, (int)text_height, (int)text_height}))
{
update_focus(make_pair(this, z));
}
else
state = IDLE;
}
void RadioButton::process_events()
{
if (mouse_in_rect({rect.x + (int)text_width + 5, rect.y + 2, (int)text_height, (int)text_height}))
{
update_focus(make_pair(this, z));
}
else
state = IDLE;
}
void ComboItem::process_events()
{
if (mouse_in_rect(rect))
{
update_focus(make_pair(this, z));
}
else
state = IDLE;
}
void ComboBox::process_events()
{
if (mouse_in_rect(rect))
{
update_focus(make_pair(this, z));
}else
state = IDLE;
}
void Slider::process_events()
{
float scale=value/(maximum-minimum);
int x_pos=(int)(scale*((float)rect.width-text_height));
if (mouse_in_rect({rect.x+x_pos,rect.y+2,(int)text_height,(int)text_height}) && mouse_hold_begin)
{
update_focus(make_pair(this, z));
}else
state = IDLE;
if(focused_element.first!=nullptr && focused_element.first==this){
int x=mouse_x-rect.x;
x=max(0,x);
x=min(rect.width-(int)text_height,x);
float scale=(float)x/((float)rect.width-text_height);
value=scale*maximum;
glDeleteVertexArrays(1,&vao);
stringstream ss;
ss<<fixed<<setprecision(0)<<value;
text=ss.str();
vao=make_text(ss.str(),style,text_width,text_height);
}
}
void ScrollBar::process_events()
{
if(orientation==HORIZONTAL_SLIDER){
if (mouse_in_rect({rect.x+slider_position,rect.y,slider_size,rect.height}))
{
state = HOVER;
if(mouse_hold_begin){
relative_pos=mouse_x;
update_focus(make_pair(this, z));
}
}else {
state = IDLE;
}
if(focused_element.first!=nullptr && focused_element.first==this){
state = PRESS;
int x=delta_x;
slider_position+=x;
slider_position=max(slider_position,0);
slider_position=min(slider_position,rect.width-slider_size);
}
}
if(orientation==VERTICAL_SLIDER){
if (mouse_in_rect({rect.x,rect.y+slider_position,rect.width,slider_size}))
{
state = HOVER;
if(mouse_hold_begin){
relative_pos=mouse_x;
update_focus(make_pair(this, z));
}
}else {
state = IDLE;
}
if(focused_element.first!=nullptr && focused_element.first==this){
state = PRESS;
int x=delta_y;
slider_position+=x;
slider_position=max(slider_position,0);
slider_position=min(slider_position,rect.height-slider_size);
}
}
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//!!!!!!!!!!!FOCUS PROCESSING METHODS!!!!!
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void Button::on_focus()
{
if (mouse_click)
{
clear_focus();
state = CLICKED;
if (click != nullptr)
click();
}
else if (mouse_hold)
state = PRESS;
else
state = HOVER;
}
void Button::on_focus_lost()
{
state = IDLE;
}
void Label::on_focus()
{
if (mouse_click)
{
clear_focus();
}
}
void Label::on_focus_lost()
{
}
void ToggleButton::on_focus()
{
if (mouse_click)
{
clear_focus();
state = CLICKED;
value = !value;
if (toggle != nullptr)
toggle();
}
else if (mouse_hold)
state = PRESS;
else
state = HOVER;
}
void ToggleButton::on_focus_lost()
{
state = IDLE;
}
void CheckBox::on_focus()
{
if (mouse_click)
{
clear_focus();
state = CLICKED;
value = !value;
if (toggle != nullptr)
toggle();
}
else if (mouse_hold)
state = PRESS;
else
state = HOVER;
}
void CheckBox::on_focus_lost()
{
state = IDLE;
}
void RadioButton::on_focus()
{
if (mouse_click)
{
clear_focus();
state = CLICKED;
if (rg->multiple == false)
{
if (rg->allow_none == false)
{
if (rg->selected == nullptr)
{
value = true;
rg->selected = this;
}
else if(rg->selected!=this)
{
value = true;
rg->selected->value = false;
rg->selected = this;
}
}
else
{
if (rg->selected != nullptr && rg->selected != this)
rg->selected->value = false;
value = !value;
rg->selected = this;
}
}
else
{
if (rg->allow_none)
{
value = !value;
if (value)
rg->num_selected++;
else
rg->num_selected--;
}
else
{
if (value && rg->num_selected == 1)
{
}
else
{
value = !value;
if (value)
rg->num_selected++;
else
rg->num_selected--;
}
}
}
}
else if (mouse_hold)
state = PRESS;
else
state = HOVER;
}
void RadioButton::on_focus_lost()
{
state = IDLE;
}
void ComboBox::on_focus()
{
if (mouse_click)
{
opened = !opened;
clear_focus();
state = CLICKED;
if (opened)
{
focus(this);
}
}
else if (mouse_hold)
state = PRESS;
else
state = HOVER;
}
void ComboBox::on_focus_lost()
{
state = IDLE;
opened = false;
for (auto it : items)
it->close();
}
void ComboItem::on_focus()
{
if (mouse_click)
{
if (sub_items.size() > 0)
{
opened = !opened;
if (opened==true)
{
clear_focus();
state = CLICKED;
focus(this);
ComboItem *curr=this;
while(curr!=nullptr){
curr->opened=true;
curr=curr->parent_item;
}
parent_box->set_open(true);
}
}
else
{
clear_focus();
parent_box->change_selected(this);
}
}
else if (mouse_hold)
state = PRESS;
else
state = HOVER;
}
void ComboItem::on_focus_lost()
{
state = IDLE;
ComboItem *curr = this;
while (curr != nullptr)
{
curr->opened = false;
curr = curr->parent_item;
}
parent_box->set_open(false);
}
void Slider::on_focus()
{
if(mouse_hold){
clear_focus();
focus(this);
}
else state=IDLE;
}
void Slider::on_focus_lost()
{
state=IDLE;
}
void ScrollBar::on_focus()
{
if(mouse_hold){
clear_focus();
focus(this);
}
else state=IDLE;
}
void ScrollBar::on_focus_lost()
{
state=IDLE;
}
void Slider::update_value(int x){
x=x-rect.x;
x=max(0,x);
x=min(rect.width,x);
float scale=(float)x/(float)rect.width;
value=scale*maximum;
glDeleteVertexArrays(1,&vao);
stringstream ss;
ss<<fixed<<setprecision(8)<<value;
text=ss.str();
vao=make_text(ss.str(),style,text_width,text_height);
}
|
//
// FootSwitchActuator.hpp
//
//
// Created by Markus Buhl on 15.11.18.
//
#ifndef FootSwitchActuator_hpp
#define FootSwitchActuator_hpp
#include <stdio.h>
#include "Arduino.h"
enum ActuatorState {
UNCHANGED = 0,
INACTIVE,
ACTIVE
};
enum ActuatorType {
ONESHOT,
HOLD,
TOGGLE
};
typedef void (*FootSwitchActuatorCallback)(int id);
class FootSwitchActuator {
protected:
//Analog or Digital Button Pin?
static int lastID;
int m_actuatorPin = -1;
bool m_ready = false;
bool m_isAnalog = false;
int m_actuatorState = 0;
int m_prevActuatorState = HIGH; //Begin on HIGH since we are dealing with Pullup Resistors (which are HIGH when circuit is open)
int m_ID = lastID;
//Debounce timing
unsigned long m_lastDebounceTime = 0;
const unsigned long m_debounceDelay = 30;
bool m_active = false;
ActuatorType m_actuatorType = ActuatorType::ONESHOT;
FootSwitchActuatorCallback m_callback;
int getActuatorState() {
if(!m_ready) {
initPin();
m_ready = true;
}
int reading = digitalRead(m_actuatorPin);
if(reading != m_prevActuatorState) {
m_lastDebounceTime = millis();
}
if((millis() - m_lastDebounceTime) > m_debounceDelay) {
if(reading != m_actuatorState) {
m_actuatorState = reading;
}
}
m_prevActuatorState = reading;
return m_actuatorState;
}
void updateActuatorONESHOT(int state) {
if(state) {
if(m_active) {
return;
}
activate();
} else {
if(!m_active) {
return;
}
deactivate();
}
}
void updateActuatorHOLD(int state) {
if(state) {
if(m_active) {
return;
}
Serial.println("called an actuator");
activate();
} else {
deactivate();
}
}
void updateActuatorTOGGLE(int state) {
}
void activate() {
m_active = true;
if(m_callback != nullptr) {
m_callback(m_ID);
}
}
void deactivate() {
m_active = false;
}
public:
//GETTERS & SETTERS
FootSwitchActuator() {
m_ID = lastID;
lastID++;
}
FootSwitchActuator(int actuatorPin, bool isAnalog = false) {
FootSwitchActuator();
m_actuatorPin = actuatorPin;
m_isAnalog = isAnalog;
}
void initPin() {
pinMode(m_actuatorPin, INPUT_PULLUP);
}
void setIsAnalog(bool isAnalog) {
m_isAnalog = isAnalog;
}
bool isAnalog() {
return m_isAnalog;
}
void setID(int id) {
m_ID = id;
}
int getID() {
return m_ID;
}
void updateActuatorState() {
if(m_isAnalog) {
updateActuatorStateANALOG();
return;
}
int state = !getActuatorState();
//inverse logic: active actuator returns 0!
switch(m_actuatorType) {
case ActuatorType::ONESHOT:
updateActuatorONESHOT(state);
break;
case ActuatorType::HOLD:
updateActuatorHOLD(state);
break;
case ActuatorType::TOGGLE:
updateActuatorTOGGLE(state);
break;
}
}
void updateActuatorStateANALOG() {
int input = analogRead(m_actuatorPin);
Serial.print("Analog 7: ");
Serial.println(input);
}
void setActuatorPin(int actuatorPin) {
m_actuatorPin = actuatorPin;
}
int getActuatorPin() {
return m_actuatorPin;
}
int getReading() {
if(m_isAnalog) {
return analogRead(m_actuatorPin);
} else {
return digitalRead(m_actuatorPin);
}
}
void setCallback(FootSwitchActuatorCallback callback) {
m_callback = callback;
}
};
#endif /* FootSwitchActuator_hpp */
|
#include <iostream>
#include "libFunction.h" // 使用此声明是该自定义函数调用了"libFunction.h"中的printHSLAM()
using namespace std;
void printHCPlus2();
void printHWorld()
{
cout << "hello, world" << endl;
printHCPlus2();
printHSLAM();
return;
}
void printHCPlus2()
{
cout << "hello, cplusplus" << endl;
return;
}
|
#pragma once
#include "../space/triangulation.hpp"
namespace space {
double Integrate(const std::function<double(double, double)>& f,
const Element2D& elem, size_t degree);
} // namespace space
|
// The main function - entry point into an executable.
//
// argc: number of arguments
// argv: array of arguments (array of character array, each character array terminated with NULL)
//
// char * is a character array (i.e. a string)
// char ** is an array of character arrays - could also be written as char *argv[]
#include <stdio.h> // printf
#include <assert.h> // assert
int main(int argc, char *argv[])
{
unsigned int i = 182981;
unsigned int *ptr = &i; // "&i" gives address (pointer) - store in a pointer "unsigned int *"
// i = the value
// ptr = the address of i
// *ptr = dereference the pointer ptr to get the value i
printf("%d %d %d\n", i, ptr, *ptr);
assert(i == *ptr);
int array[100]; // array of 100 items - allocated memory
int *arrayPtr = array; // the array object is just a pointer
int *arrayPtrAlt = &array[0]; // can use the address of the first element of the array to get the pointer
assert(arrayPtr == arrayPtrAlt);
for (int i = 0; i < argc; ++i)
{
printf("%s\n", argv[i]);
}
// Return 0 to indicate success (implicit - can be removed)
return 0;
}
|
/*
Token object definition
2013, Tivins <https://github.com/tivins>
*/
#ifndef V_TOKEN_H
#define V_TOKEN_H
#include "str.h"
#include "tokdef.h"
namespace v {
class Token {
public:
Token(int column, int line, int type = TOKEN_NONE, const char * data = NULL) ;
~Token() ;
const char *getTypeName() ;
static const char *getTypeName(int _type,int _subtype) ;
void getDataChain(String * str) ;
// Browsing :
static int nextid(Token * tk);
static int previd(Token * tk);
static int parentid(Token * tk);
static int fchildid(Token * tk);
int id, type, subtype, line, col;
char * ptr ;
String data;
Token * next, * prev, * parent, * firstChild; // browse tree.
private:
static int counter ;
};
} // namespace
#endif /* V_TOKEN_H */
|
#include "CustomItem.h"
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
CustomItem::CustomItem(std::string size):IceCreamItem(size)
{
if(size == "small"){
price = 3.00;
}
if(size == "medium"){
price = 5.00;
}
if(size == "large"){
price = 6.50;
}
}
CustomItem::~CustomItem(){
}
void CustomItem::addTopping(std::string topping){
for(size_t i = 0; i<toppings.size(); i++){
if(toppings[i].first == topping){
toppings[i].second ++;
price += 0.4;
return;
}
}
std::pair<std::string, int> entry;
entry.first = topping;
entry.second = 1;
toppings.push_back(entry);
price+= 0.4;
}
double CustomItem::getPrice(){
return price;
}
std::string CustomItem::composeItem(){
std::pair<std::string,int> temp;
for(size_t i = 0; i<toppings.size(); i++){
for(size_t j=i+1; j<toppings.size(); j++){
if (toppings[i].first>toppings[j].first){
temp = toppings[i];
toppings[i] = toppings[j];
toppings[j] = temp;
}
}
}
std::string output = "";
output = "Custom Size: "+ size + "\nToppings:\n";
for(size_t i = 0; i < toppings.size(); i++){
output+= toppings[i].first+": "+std::to_string(toppings[i].second)+" oz\n";
}
stringstream stream;
stream << fixed << setprecision(2) << price;
output += "Price: $" + stream.str() + "\n";
return output;
}
|
#include <iostream>
#include <unistd.h>
#include <ncurses.h>
#include <time.h>
#include <dirent.h>
#include <wiringPi.h>
#include <pca9685.h>
#include <fstream>
#include <ctime>
#include <string>
#include <chrono>
#include "servo_commands.h"
#include <stdio.h>
#include "../../raspicam/src/raspicam_still.h"
using namespace std;
const int TASK_TIME_LIMIT_SECS = 20;
int main ()
{
// required by ncurses.h; inits key read
int TASK_ATTEMPT_DURATION_SECS = 0;
cout << "beginning" << endl;
int fd = pca9685Setup(PIN_BASE, 0x40, HERTZ);
if (fd < 0) {
printf("Error in setup\n");
return fd;
}
pca9685PWMReset(fd);
int tick, i, j = 0;
// start servos at some base position every time
tick = calcTicks(i, HERTZ);
pwmWrite(SERVO_0, tick);
// resetServos();
initscr();
while (1==1)
{
int key = getch(); // read keyboard input
cout << "key" << key << "pressed" << endl;
if (key == ' ' || key == 32 || TASK_ATTEMPT_DURATION_SECS >= TASK_TIME_LIMIT_SECS) // TODO which one?
{
// Capture an image
// Save it to a file to be read into TensorFlow later
// initiate/instantiate Raspicam
raspicam::RaspiCam_Still Camera;
sleep(1);
cout << "opening camera capturing an image" << endl;
Camera.setWidth(1280);
Camera.setHeight(960);
Camera.setISO(600);
Camera.setBrightness(60);
Camera.setEncoding(raspicam::RASPICAM_ENCODING_JPEG);
Camera.open();
sleep(1);
unsigned int length = Camera.getImageBufferSize(); // Header + Image Data + Padding
unsigned char * data = new unsigned char[length];
if (!Camera.grab_retrieve(data, length)) {
cerr<<"Error in grab"<<endl;
return -1;
}
int highest_file_num = getMaxFileNum();
std::string file_name = std::to_string(highest_file_num);
file_name = file_name + ".jpg";
cout << "saving training image with num " << file_name << endl;
ofstream file (file_name, ios::binary);
file.write(( char*)data, length);
delete data;
appendImageToFile(file_name);
bool SUCCESSFUL = false; // has arm successfully completed its task?
// time to complete task counter;
// if time greater than some max amount, don't even include it in our dataset - start over.
// This could go on for ours if exploring to much or something else goes wrong.
time_t begin = time(NULL);
cout << "Beginning attempt of robotic task. I have " << TASK_TIME_LIMIT_SECS << " seconds to complete it" << endl;
while (!SUCCESSFUL && TASK_ATTEMPT_DURATION_SECS < TASK_TIME_LIMIT_SECS)
{
// init ints that will hold keypress time for each servo button. These numbers will ultimately fed to TensorFlow
int h,i,j,k = 0;
// if key pressed is one of our desired servo keys... http://www.asciitable.com/
nodelay(stdscr, TRUE); // make the screen input non-blocking
while (key && key <= 107 && key >= 104)
{
cout << key << " pressed" << endl;
// Record buttons for time depressed
// Each loop increments key counter one second - see sleep(1) below
// increase position of servo while its key is pressed
switch (key)
{
case 104:
{
// increaseServo(300);
h++;
cout << " h pressed" << endl;
}
case 105:
{
// increaseServo(301);
i++;
cout << " i pressed" << endl;
}
case 106:
{
// increaseServo(302);
j++;
cout << " j pressed" << endl;
}
case 107:
{
// increaseServo(303);
k++;
cout << " k pressed" << endl;
}
}
}
// If electronic circuit has been completed
int CIRCUIT_CONNECTED = digitalRead(4);
if (1==2/*pin is high*/)
{
SUCCESSFUL = true; // exit loop that will store servo times
pca9685PWMReset(fd); // do we need this?
resetServos(); // reset servo positions to base
}
time_t now = time(NULL);
TASK_ATTEMPT_DURATION_SECS = difftime(now, begin);
cout << "SECONDS PASSED: " << TASK_ATTEMPT_DURATION_SECS << endl;
cout << "I have " << TASK_TIME_LIMIT_SECS - TASK_ATTEMPT_DURATION_SECS << " seconds left to complete the task"<< endl;
sleep(1);
}
// write individual servo times somewhere once task was successful
// reset servo to initial state and wait for another 32/space bar
}
sleep(.5);
}
return 0;
}
|
#include <iostream>
#include <cstdlib>
#include <string>
#include "manager.h"
#include "visitor.h"
#include "sort_by_price_visitor.h"
#include "sort_by_name_visitor.h"
using namespace std;
Manager::Manager():_name("Manager"), _number("1"){
}
Manager::Manager(string name = "Manager",string number = "1"):_name(name),_number(number)
{
}
void Manager::PrintOperations()
{
cout<<"\t++++++++++++++++++++++++++++++++++++++++"<<endl
<<"\t+ +"<<endl
<<"\t+ Welcome to the ManagerSystem +"<<endl
<<"\t+ 1. Display Menu +"<<endl
<<"\t+ 2. Add Category +"<<endl
<<"\t+ 3. Delete Category +"<<endl
<<"\t+ 4. Modify Categories +"<<endl
<<"\t+ 5. Manage Storage +"<<endl
<<"\t+ 6. Delete Item +"<<endl
<<"\t+ 7. Exit +"<<endl
<<"\t+ +"<<endl
<<"\t++++++++++++++++++++++++++++++++++++++++"<<endl;
}
void Manager::MenuOptions(FullMenu& fullMenu) {
system("clear");
fullMenu.ShowMenu();
cout << endl;
string input;
int index;
do {
cout << "1. Order items by price" << endl
<< "2. Order items by name" << endl
<< "3. Go back" << endl;
cout << "choose command: ";
cin >> input;
if(input != "1" && input != "2" && input != "3")
cout << "Invalid input, please try again\n";
else CallVisitor(fullMenu, input);
}while(input != "3");
system("clear");
}
void Manager::CallVisitor(FullMenu& menu, string command) {
if(command == "1") {
system("clear");
Visitor *v = new SortByPriceVisitor();
menu.accept(*v);
}
if(command == "2"){
system("clear");
Visitor *v = new SortByNameVisitor();
menu.accept(*v);
}
}
void Manager::AddCategory(FullMenu& menu)
{
string name, description;
do {
cout<<"Please input category name(input 'x' to cancel):";
cin.ignore();
getline(cin, name);
}while(IsCategoryRepeated(menu, name) && name != "x");
if(name == "x") return;
cout<<"Please input category description:";
cin.ignore();
getline(cin, description);
Category newCat(name, description);
menu.AddCategory(newCat);
system("clear");
cout << name << " successfully added!\n";
}
void Manager::AddCategory(FullMenu& menu, Category& newCat)
{
menu.AddCategory(newCat);
}
void Manager::DelCategory(FullMenu& menu)
{
system("clear");
string input;
int index;
menu.DisplayCategories();
do {
cout << "Please input the category you want to delete(input 'x' to cancel): ";
cin >> input;
index = atoi(input.c_str());
if(index > 0 && index <= menu.GetSize() || input == "x") break;
else cout << "Invalid input, please try again.\n";
}while(1);
system("clear");
if(input != "x") {
cout << menu.GetCategory(index - 1).GetName() << " successfully deleted!\n";
menu.DelCategory(menu.GetCategory(index - 1).GetName());
}
}
void Manager::ModifyCategory(FullMenu& menu, vector<Item>& item)
{
string command;
cout << "1. Add items to category" << endl << "2. Delete items from category" << endl << "3. Go back\n\n";
cout << "Please choose your command: ";
cin.ignore();
do{
getline(cin, command);
if(command == "1")
AddItemToCategory(menu, item);
else if(command == "2")
DeleteItemFromCategory(menu);
else if(command == "3")
return;
else
cout << "invalid input, please try again\n";
}while(command != "1" && command != "2" && command != "3");
}
void Manager::AddItemToCategory(FullMenu& menu, vector<Item>& item)
{
string input;
int category;
cout << endl;
for(int n = 0; n < menu.GetSize(); n++) {
cout << n + 1 << ". " << menu.GetCategory(n).GetName() << endl;
}
do{
cout << "Choose category(input 'x' to cancel): ";
cin >> input;
category = atoi(input.c_str());
if(category > 0 && category <= menu.GetSize() || input == "x") break;
else cout << "invalid input, please try again\n";
}while(1);
if(input == "x") return;
cout << endl;
int itemChosen;
for(int n = 0; n < item.size(); n++) {
cout << n + 1 << ". " << item[n].GetName() << endl;
}
do {
cout << "Choose item to add(input 'x' to cancel): ";
cin >> input;
itemChosen = atoi(input.c_str());
if(itemChosen > 0 && itemChosen <= item.size()) {
menu.GetCategory(category - 1).AddItem(&item[itemChosen - 1]);
cout << item[itemChosen - 1].GetName() << " added\n";
}
else if(input != "x")
cout << "invalid input, please try again\n";
}while(input != "x");
system("clear");
}
void Manager::AddItemToCategory(FullMenu& menu, vector<Item>& item, int catIndex, int itemIndex)
{
menu.GetCategory(catIndex - 1).AddItem(&item[itemIndex - 1]);
}
void Manager::DeleteItemFromCategory(FullMenu& menu)
{
int category, itemChosen;
cout << endl;
for(int n = 0; n < menu.GetSize(); n++) {
cout << n + 1 << ". " << menu.GetCategory(n).GetName() << endl;
}
cout << "Choose category: ";
cin >> category;
cout << endl;
for(int n = 0; n < menu.GetCategory(category - 1).GetSize(); n++) {
cout << n + 1 << ". " << menu.GetCategory(category - 1).GetItem(n).GetName() << endl;
}
cout << "Choose item to delete: ";
cin >> itemChosen;
string itemName = menu.GetCategory(category - 1).GetItem(itemChosen - 1).GetName();
menu.GetCategory(category - 1).DelItem(itemName);
}
void Manager::ManageStorage(vector<Item>& item, vector<Ingredient>& ingredient)
{
string command;
cout << "\n1. Create new item" << endl << "2. Delete item" << endl;
cout << "Please choose your command: ";
cin.ignore();
do{
getline(cin, command);
if(command == "1")
CreateItem(item, ingredient);
else if(command == "2")
DeleteItemFromStorage(item);
else if(command == "3")
return;
else
cout << "invalid input, please try again\n";
}while(command != "1" && command != "2" && command != "3");
}
void Manager::CreateItem(vector<Item>& item, vector<Ingredient>& ingredient)
{
system("clear");
double price;
string name, description, itemCode, priceInput;
do{
cout << "Enter the item's name(input 'x' to cancel): ";
getline(cin, name);
}while(IsItemNameRepeated(item, name) && name != "x");
if(name == "x") return;
cout << "Enter the item's description(input 'x' to cancel): ";
getline(cin, description);
if(description == "x") return;
do{
cout << "Enter the item's price(input 'x' to cancel): ";
getline(cin, priceInput);
price = atof(priceInput.c_str());
}while(price < 0 && priceInput != "x");
if(priceInput == "x") return;
do{
cout << "Enter the item's code: ";
cin >> itemCode;
}while(IsItemCodeRepeated(item, itemCode));
item.push_back(Item(name, description, itemCode, price));
AddIngredientToItem(item[item.size() - 1], ingredient);
system("clear");
cout << name << " successfully created!\n";
}
bool Manager::IsItemNameRepeated(vector<Item>& item, string name) {
for(int n = item.size() - 1; n >= 0; n--) {
if(item[n].GetName() == name) {
cout << "This item already exist, please choose another name\n";
return true;
}
}
return false;
}
bool Manager::IsItemCodeRepeated(vector<Item>& item, string code) {
for(int n = item.size() - 1; n >= 0; n--) {
if(item[n].GetProductCode() == code) {
cout << "This code is already taken, please choose another one\n";
return true;
}
}
return false;
}
bool Manager::IsCategoryRepeated(FullMenu& menu, string name) {
Iterator<Category>* it = menu.createIterator();
for(it->first(); !it->isDone(); it->next()) {
if(it->currentItem().GetName() == name) {
cout << "This category already exists, please choose another name\n";
return true;
}
}
return false;
}
void Manager::DeleteItemFromStorage(vector<Item>& item) {
system("clear");
string input;
int index;
do{
for(int n = 0; n < item.size(); n++)
cout << n+1 << ". " << item[n].GetName() << endl;
cout << "Enter the item you want to delete(input 'x' to go back): ";
cin >> input;
index = atoi(input.c_str());
if(index > 0 && index <= item.size()) {
item[index - 1].NotifyDeletion();
system("clear");
cout << item[index - 1].GetName() << " successfully deleted!\n";
item.erase(item.begin() + index - 1);
}
if(input == "x") break;
}while(1);
system("clear");
}
void Manager::AddIngredientToItem(Item& item, vector<Ingredient>& ingredient)
{
string command;
cout << endl;
for(int n = 0; n < ingredient.size(); n++) {
cout << n + 1 << ". " << ingredient[n].GetName() << endl;
}
do {
cout << "Add ingredients to your item(input 'x' when finished): ";
cin >> command;
int index = atoi(command.c_str());
if(command == "x")
break;
else if(index >= 0 && index <= ingredient.size()) {
item.AddIngredient(&ingredient[index - 1]);
}
else
cout << "Invalid input\n";
}while(1);
}
|
#include<cstdio>
#include<iostream>
#include<ctime>
#define N 100000000
#define REP(i,N) for(int i=0; i<N; i++)
int D;
using namespace std;
int main() {
printf("通常のforループ ");
clock_t start = clock();
for(int i=0; i<N; i++){
D = i;
}
clock_t end = clock();
cout << (double)(end - start) / CLOCKS_PER_SEC << "sec.\n";
printf("インライン展開を利用したループ ");
start = clock();
REP(i,N)D=i;
end = clock();
cout << (double)(end - start) / CLOCKS_PER_SEC << "sec.\n";
return 0;
}
|
#pragma once
#include <map>
#include <string>
class DynLib;
class DynLibManager
{
public:
DynLibManager();
~DynLibManager();
public:
DynLib* Load(const std::string& filename);
void Unload(DynLib* lib);
private:
typedef std::map<std::string, DynLib*> DynLibList;
DynLibList mDynLibList;
private:
static DynLibManager* instance;
public:
static DynLibManager* GetSingleton();
};
|
#include <iostream>
#include "sales_data.h"
// This assumes that all books read in have the same bookId (ISBN)
int main()
{
Sales_data bookIn, bookTotal;
std::cin >> bookTotal.bookId >> bookTotal.unitsSold >> bookTotal.revenue;
std::cout << "Transaction Read: " << bookTotal.bookId << " "
<< bookTotal.unitsSold << " "
<< bookTotal.revenue << " " << std::endl;
while (std::cin >> bookIn.bookId >> bookIn.unitsSold >> bookIn.revenue){
std::cout << "Transaction Read: " << bookIn.bookId << " "
<< bookIn.unitsSold << " "
<< bookIn.revenue << " " << std::endl;
bookTotal.unitsSold += bookIn.unitsSold;
bookTotal.revenue += bookIn.revenue;
}
std::cout << std::endl; // print blank line
std::cout << "Total: " << bookTotal.bookId << " "
<< bookTotal.unitsSold << " "
<< bookTotal.revenue << " " << std::endl;
}
|
#ifndef __ENGINECOMMON__
#define __ENGINECOMMON__
#include <Windows.h>
#include <chrono>
typedef struct {
float r, b, g, a;
} GLCOLORARGB;
typedef struct {
double x, y;
} GLVECTOR2, GLVERTEX2;
typedef struct {
double x, y, w, h;
} BOUNDINGBOX;
class ClockKeeper {
private:
std::chrono::high_resolution_clock::time_point prev;
bool run;
public:
ClockKeeper();
double DeltaT();
void Reset();
};
GLVECTOR2 VectorOf(double x, double y);
GLCOLORARGB AColorOf(float a, float r, float g, float b);
GLCOLORARGB ColorOf(float r, float g, float b);
double Magnitude(GLVECTOR2 vec);
#endif
|
#pragma once
#include<string>
#include "utility.hh"
std::ostream& operator<<(std::ostream & out, Parti val);
class Personnage{
protected:
Parti val;
Parti vote;
public:
Personnage();
Personnage(Parti _val);
Parti getvote();
static int nbPerso;
void voter();
void afficher();
Parti getval();
void setval(Parti choix);
void setvote(Parti choix);
};
|
/********************************************************************************
** Form generated from reading UI file 'CStatisticsWidget.ui'
**
** Created by: Qt User Interface Compiler version 5.3.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_CSTATISTICSWIDGET_H
#define UI_CSTATISTICSWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QGroupBox>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_CStatisticsWidget
{
public:
QGridLayout *gridLayout_2;
QGroupBox *groupBox;
QGridLayout *gridLayout;
QHBoxLayout *horizontalLayout;
QSpacerItem *horizontalSpacer;
QPushButton *btn_ExportAll;
QTableWidget *tableWidget;
void setupUi(QWidget *CStatisticsWidget)
{
if (CStatisticsWidget->objectName().isEmpty())
CStatisticsWidget->setObjectName(QStringLiteral("CStatisticsWidget"));
CStatisticsWidget->resize(495, 381);
gridLayout_2 = new QGridLayout(CStatisticsWidget);
gridLayout_2->setSpacing(6);
gridLayout_2->setContentsMargins(11, 11, 11, 11);
gridLayout_2->setObjectName(QStringLiteral("gridLayout_2"));
groupBox = new QGroupBox(CStatisticsWidget);
groupBox->setObjectName(QStringLiteral("groupBox"));
gridLayout = new QGridLayout(groupBox);
gridLayout->setSpacing(6);
gridLayout->setContentsMargins(11, 11, 11, 11);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
horizontalLayout = new QHBoxLayout();
horizontalLayout->setSpacing(6);
horizontalLayout->setObjectName(QStringLiteral("horizontalLayout"));
horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer);
btn_ExportAll = new QPushButton(groupBox);
btn_ExportAll->setObjectName(QStringLiteral("btn_ExportAll"));
horizontalLayout->addWidget(btn_ExportAll);
gridLayout->addLayout(horizontalLayout, 1, 0, 1, 1);
tableWidget = new QTableWidget(groupBox);
if (tableWidget->columnCount() < 6)
tableWidget->setColumnCount(6);
QTableWidgetItem *__qtablewidgetitem = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(0, __qtablewidgetitem);
QTableWidgetItem *__qtablewidgetitem1 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(1, __qtablewidgetitem1);
QTableWidgetItem *__qtablewidgetitem2 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(2, __qtablewidgetitem2);
QTableWidgetItem *__qtablewidgetitem3 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(3, __qtablewidgetitem3);
QTableWidgetItem *__qtablewidgetitem4 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(4, __qtablewidgetitem4);
QTableWidgetItem *__qtablewidgetitem5 = new QTableWidgetItem();
tableWidget->setHorizontalHeaderItem(5, __qtablewidgetitem5);
tableWidget->setObjectName(QStringLiteral("tableWidget"));
tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
tableWidget->setAlternatingRowColors(true);
tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
tableWidget->horizontalHeader()->setStretchLastSection(true);
tableWidget->verticalHeader()->setVisible(false);
gridLayout->addWidget(tableWidget, 0, 0, 1, 1);
gridLayout_2->addWidget(groupBox, 0, 0, 1, 1);
retranslateUi(CStatisticsWidget);
QMetaObject::connectSlotsByName(CStatisticsWidget);
} // setupUi
void retranslateUi(QWidget *CStatisticsWidget)
{
CStatisticsWidget->setWindowTitle(QApplication::translate("CStatisticsWidget", "CStatisticsWidget", 0));
groupBox->setTitle(QApplication::translate("CStatisticsWidget", "\350\275\257\344\273\266\344\277\241\346\201\257\347\273\237\350\256\241", 0));
btn_ExportAll->setText(QApplication::translate("CStatisticsWidget", "\345\205\250\351\203\250\345\257\274\345\207\272", 0));
QTableWidgetItem *___qtablewidgetitem = tableWidget->horizontalHeaderItem(0);
___qtablewidgetitem->setText(QApplication::translate("CStatisticsWidget", "\350\275\257\344\273\266\345\220\215\347\247\260", 0));
QTableWidgetItem *___qtablewidgetitem1 = tableWidget->horizontalHeaderItem(1);
___qtablewidgetitem1->setText(QApplication::translate("CStatisticsWidget", "\347\211\210\346\234\254\345\217\267", 0));
QTableWidgetItem *___qtablewidgetitem2 = tableWidget->horizontalHeaderItem(2);
___qtablewidgetitem2->setText(QApplication::translate("CStatisticsWidget", "\345\256\211\350\243\205\345\217\260\346\225\260", 0));
QTableWidgetItem *___qtablewidgetitem3 = tableWidget->horizontalHeaderItem(3);
___qtablewidgetitem3->setText(QApplication::translate("CStatisticsWidget", "\346\234\252\345\215\207\347\272\247\345\217\260\346\225\260", 0));
QTableWidgetItem *___qtablewidgetitem4 = tableWidget->horizontalHeaderItem(4);
___qtablewidgetitem4->setText(QApplication::translate("CStatisticsWidget", "\350\275\257\344\273\266\347\261\273\345\210\253", 0));
QTableWidgetItem *___qtablewidgetitem5 = tableWidget->horizontalHeaderItem(5);
___qtablewidgetitem5->setText(QApplication::translate("CStatisticsWidget", "\346\223\215\344\275\234", 0));
} // retranslateUi
};
namespace Ui {
class CStatisticsWidget: public Ui_CStatisticsWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_CSTATISTICSWIDGET_H
|
// jsonpack.cpp : Defines the entry point for the console application.
//
#ifdef _WIN32
#include <io.h>
#endif
#include <fcntl.h>
#include <fstream>
#include "../imtjson/json.h"
#include "../imtjson/compress.tcc"
int main(int argc, char **argv)
{
#ifdef _WIN32
_setmode(_fileno(stdin), _O_BINARY);
#endif
try {
using namespace json;
Value v = Value::parse(decompress(fromStream(std::cin)));
v.toStream(emitUtf8, std::cout);
return 0;
}
catch (std::exception &e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
return 1;
}
}
|
#ifndef EVENT_H
#define EVENT_H
#include "TTH/Plotting/interface/metree.h"
//JSON parser https://github.com/vivkin/gason
#include "TTH/Plotting/interface/gason.h"
#include "TTH/Plotting/interface/gen.h"
#include "TLorentzVector.h"
#include "TH1D.h"
#include "THnSparse.h"
#include "TFile.h"
#include "TPython.h"
#include <tuple>
#include <unordered_map>
#include <functional>
#include <cassert>
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
//Simple 3-tuple of (category, systematic, histname) to keep track of
//final histograms.
typedef tuple<
ProcessKey::ProcessKey,
vector<CategoryKey::CategoryKey>,
SystematicKey::SystematicKey,
HistogramKey::HistogramKey
> ResultKey;
//Write ResultKey to string
string to_string(const ResultKey& k);
//We need to specialize the std::hash function for ResultKey
//To define ResultMap
namespace std {
template <> struct hash<ResultKey>
{
//const static std::hash<unsigned long> ResultKey_hash_fn;
size_t operator()(const ResultKey & x) const
{
//make a compound hash
unsigned long long r = 0;
int ninc = 8; // how many bits to shift each
int ic = 0; //shift counter
r += static_cast<int>(get<0>(x)) << (ninc*ic);
ic++;
//shift vector of category keys
for (auto& v : get<1>(x)) {
r += static_cast<int>(v) << (ninc*ic);
}
ic++;
r += static_cast<int>(get<2>(x)) << (ninc*ic);
ic++;
r += static_cast<int>(get<3>(x)) << (ninc*ic);
std::hash<unsigned long long> _hash_fn;
return _hash_fn(r);
}
};
template <> struct hash<vector<CategoryKey::CategoryKey>>
{
//const static std::hash<unsigned long> ResultKey_hash_fn;
size_t operator()(const vector<CategoryKey::CategoryKey> & x) const
{
//make a compound hash
unsigned long long r = 0;
int ninc = 8; // how many bits to shift each
int ic = 0; //shift counter
//shift vector of category keys
for (auto& v : x) {
r += static_cast<int>(v) << (ninc*ic);
}
std::hash<unsigned long long> _hash_fn;
return _hash_fn(r);
}
};
}
//Simple representation of a jet
class Jet {
public:
TLorentzVector p4;
float btagCSV;
float btagBDT;
int hadronFlavour;
Jet(TLorentzVector& _p4, float _btagCSV, float _btagBDT, int _hadronFlavour);
const string to_string() const;
};
//Simple representation of a jet
class Lepton {
public:
const TLorentzVector p4;
int pdgId;
Lepton(const TLorentzVector& _p4, int _pdgId);
const string to_string() const;
};
//fwd decl
class Event;
typedef std::function<float(const Event& ev, const ProcessKey::ProcessKey& proc, const vector<CategoryKey::CategoryKey>& cats, const SystematicKey::SystematicKey& syst)> AxisFunction;
class SparseAxis {
public:
SparseAxis(
const string& _name,
AxisFunction _evalFunc,
int _nBins,
float _xMin,
float _xMax
) :
name(_name),
evalFunc(_evalFunc),
nBins(_nBins),
xMin(_xMin),
xMax(_xMax) {};
string name;
AxisFunction evalFunc;
int nBins;
float xMin, xMax;
};
class Configuration {
public:
typedef unordered_map<
const vector<CategoryKey::CategoryKey>,
double,
hash<vector<CategoryKey::CategoryKey>>
> CutValMap;
vector<string> filenames;
double lumi;
double xsweight;
ProcessKey::ProcessKey process;
string prefix;
long firstEntry;
long numEntries;
int printEvery;
string outputFile;
vector<SparseAxis> sparseAxes;
vector<vector<CategoryKey::CategoryKey>> enabledCategories;
bool recalculateBTagWeight;
Configuration(
vector<string>& _filenames,
double _lumi,
double _xsweight,
ProcessKey::ProcessKey _process,
string _prefix,
long _firstEntry,
long _numEntries,
int _printEvery,
string _outputFile,
vector<SparseAxis> _sparseAxes,
vector<vector<CategoryKey::CategoryKey>> _enabledCategories
) :
filenames(_filenames),
lumi(_lumi),
xsweight(_xsweight),
process(_process),
prefix(_prefix),
firstEntry(_firstEntry),
numEntries(_numEntries),
printEvery(_printEvery),
outputFile(_outputFile),
sparseAxes(_sparseAxes),
enabledCategories(_enabledCategories),
recalculateBTagWeight(false)
{
}
static const Configuration makeConfiguration(JsonValue& value);
string to_string() const;
};
//maps systematics to function(event, conf)->double
typedef unordered_map<
SystematicKey::SystematicKey,
double (*)(const Event&, const Configuration& conf),
hash<int>
> WeightMap;
double nominal_weight(const Event& ev, const Configuration& conf);
//These functions return the list of weights used
//all systematic weights
WeightMap getSystWeights();
//only nominal weights
WeightMap getNominalWeights();
//Simple event representation
//Designed to be immutable
class Event {
public:
bool is_sl;
bool is_dl;
bool passPV;
int numJets;
int nBCSVM;
int nBCSVL;
//list of all jets
vector<Jet> jets;
//list of all jets
vector<Lepton> leptons;
//map of SystematicKey -> weight func(event) of all syst. weights to evaluate
//WeightMap weightFuncs;
//cross-section weight
double weight_xs;
double puWeight;
double Wmass;
//mem hypotheses
double mem_SL_0w2h2t;
double mem_SL_1w2h2t;
double mem_SL_2w2h2t;
double mem_SL_2w2h2t_sj;
double mem_DL_0w2h2t;
// Our BDT
double tth_mva;
//KIT BDT
double common_bdt;
//btag weights
map<SystematicKey::SystematicKey, double> bTagWeights;
//btag likelihood
double blr1;
double blr2;
//boosted variables
int n_excluded_bjets;
int n_excluded_ljets;
int ntopCandidate;
double topCandidate_pt;
double topCandidate_eta;
double topCandidate_mass;
double topCandidate_masscal;
double topCandidate_fRec;
double topCandidate_n_subjettiness;
int nhiggsCandidate;
double higgsCandidate_pt;
double higgsCandidate_eta;
double higgsCandidate_mass;
double higgsCandidate_bbtag;
double higgsCandidate_n_subjettiness;
double higgsCandidate_dr_genHiggs;
const TreeData *data;
Event(
const TreeData *_data,
bool _is_sl,
bool _is_dl,
bool _passPV,
int _numJets,
int _nBCSVM,
int _nBCSVL,
const vector<Jet>& _jets,
const vector<Lepton>& _leptons,
double _weight_xs,
double _puWeight,
double _Wmass,
double _mem_SL_0w2h2t,
double _mem_SL_1w2h2t,
double _mem_SL_2w2h2t,
double _mem_SL_2w2h2t_sj,
double _mem_DL_0w2h2t,
double _tth_mva,
double _common_bdt,
double _blr1,
double _blr2
);
const string to_string() const;
};
//A map for ResultKey -> TH1D for all the output histograms
typedef unordered_map<
ResultKey,
TObject*,
std::hash<ResultKey>
> ResultMap;
//Saves all results into a ROOT file in a structured way
void saveResults(ResultMap& res, const string& prefix, const string& filename);
//Writes the results into a string for debugging
string to_string(const ResultMap& res);
//Helper class to make various variated jet collections from TreeData
class JetFactory {
public:
static const Jet makeNominal(const TreeData& data, int njet);
static const Jet makeJESUp(const TreeData& data, int njet);
static const Jet makeJESDown(const TreeData& data, int njet);
static const Jet makeJERUp(const TreeData& data, int njet);
static const Jet makeJERDown(const TreeData& data, int njet);
};
//Helper class to make various variated Event representations from TreeData
class EventFactory {
public:
static const Event makeNominal(const TreeData& data, const Configuration& conf);
static const Event makeJESUp(const TreeData& data, const Configuration& conf);
static const Event makeJESDown(const TreeData& data, const Configuration& conf);
static const Event makeJERUp(const TreeData& data, const Configuration& conf);
static const Event makeJERDown(const TreeData& data, const Configuration& conf);
};
//A class combining a cut function, evaluated with this() along
//with a method that fills histograms
class CategoryProcessor {
public:
CategoryProcessor(
AxisFunction _cutFunc,
const vector<CategoryKey::CategoryKey>& _keys,
const Configuration& _conf,
const vector<const CategoryProcessor*>& _subCategories={},
const WeightMap _weightFuncs={
{SystematicKey::nominal, nominal_weight}
}
) :
cutFunc(_cutFunc),
keys(_keys),
conf(_conf),
subCategories(_subCategories),
weightFuncs(_weightFuncs)
{}
const bool operator()(const Event& ev, const ProcessKey::ProcessKey& proc, const vector<CategoryKey::CategoryKey>& cats, const SystematicKey::SystematicKey& syst) const {
return cutFunc(ev, proc, cats, syst);
}
const vector<CategoryKey::CategoryKey> keys;
const Configuration& conf;
const vector<const CategoryProcessor*> subCategories;
const WeightMap weightFuncs;
virtual void fillHistograms(
const Event& event,
ResultMap& results,
tuple<
ProcessKey::ProcessKey,
vector<CategoryKey::CategoryKey>,
SystematicKey::SystematicKey> key,
double weight,
const Configuration& conf
) const;
void process(
const Event& event,
const Configuration& conf,
ResultMap& results,
const vector<CategoryKey::CategoryKey>& catKeys,
SystematicKey::SystematicKey systKey
) const;
private:
AxisFunction cutFunc;
};
class SparseCategoryProcessor : public CategoryProcessor {
public:
SparseCategoryProcessor(
AxisFunction _cutFunc,
const vector<CategoryKey::CategoryKey>& _keys,
const Configuration& _conf,
const vector<const CategoryProcessor*>& _subCategories={},
const WeightMap _weightFuncs=getSystWeights()
) :
CategoryProcessor(_cutFunc, _keys, _conf, _subCategories, _weightFuncs),
axes(_conf.sparseAxes)
{
nAxes = axes.size();
for (auto& ax : _conf.sparseAxes) {
nBinVec.push_back(ax.nBins);
xMinVec.push_back(ax.xMin);
xMaxVec.push_back(ax.xMax);
}
};
vector<SparseAxis> axes;
int nAxes;
vector<int> nBinVec;
vector<double> xMinVec;
vector<double> xMaxVec;
THnSparseF* makeHist() const {
THnSparseF* h = new THnSparseF("sparse", "sparse events", nAxes, &(nBinVec[0]), &(xMinVec[0]), &(xMaxVec[0]));
h->CalculateErrors(true); //Enable THnSparse error accounting (otherwise wrong)
int iax = 0;
for (auto& ax : axes) {
h->GetAxis(iax)->SetName(ax.name.c_str());
h->GetAxis(iax)->SetTitle(ax.name.c_str());
iax += 1;
}
return h;
}
virtual void fillHistograms(
const Event& event,
ResultMap& results,
tuple<
ProcessKey::ProcessKey,
vector<CategoryKey::CategoryKey>,
SystematicKey::SystematicKey> key,
double weight,
const Configuration& conf
) const;
};
Configuration parseJsonConf(const string& infile);
namespace BaseCuts {
bool sl(const Event& ev);
bool sl_mu(const Event& ev);
bool sl_el(const Event& ev);
bool dl(const Event& ev);
bool dl_mumu(const Event& ev);
bool dl_ee(const Event& ev);
bool dl_emu(const Event& ev);
}
bool isMC(ProcessKey::ProcessKey proc);
bool isSignalMC(ProcessKey::ProcessKey proc);
bool isData(ProcessKey::ProcessKey proc);
double process_weight(ProcessKey::ProcessKey procm, const Configuration& conf);
//Checks if this category, specified by a list of keys, was enabled in the JSON
bool isCategoryEnabled(const Configuration& conf, const vector<CategoryKey::CategoryKey>& catKeys);
ProcessKey::ProcessKey getProcessKey(const Event& ev, ProcessKey::ProcessKey proc_key);
#endif
|
#include <iostream>
#include <utility>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
pair<int, TreeNode*> res = findLca(root, p, q);
return res.second;
}
pair<int, TreeNode*> findLca(TreeNode* node, TreeNode* p, TreeNode* q){
if(!node)
return pair<int, TreeNode*>(0, nullptr);
int find_node = 0;
if(node == p || node == q)
find_node++;
pair<int, TreeNode*> l_res = findLca(node->left, p, q);
find_node += l_res.first;
if(find_node == 2){
if(l_res.first == 2)
return l_res;
return pair<int, TreeNode*>(2, node);
}
pair<int, TreeNode*> r_res = findLca(node->right, p, q);
find_node += r_res.first;
if(find_node < 2)
return pair<int, TreeNode*>(find_node, nullptr);
if(r_res.first == 2)
return r_res;
return pair<int, TreeNode*>(2, node);
}
};
int main(void){
return 0;
}
|
#include "ply_loader.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "helpers.h"
#include <SDL.h>
PlyLoader::PlyLoader()
{
}
PlyLoader::~PlyLoader()
{
}
void PlyLoader::load( std::string filepath, std::vector<GLfloat>& data )
{
// TODO: find out if we can just leave the file as always binary?
// - doesn't seem to be causing problems when loading text files.
std::ifstream file( filepath, std::ios::binary );
if( !file.good() )
{
std::cout << "ERROR: could not open '" << filepath << "'" << std::endl;
return;
}
else
{
// Check the filesize
file.seekg( 0, std::ios::end );
size_t size = file.tellg();
file.seekg( 0, std::ios::beg );
std::cout << "Opened '" << filepath << "', size: " << size / 1024 << "KB" << std::endl;
}
// Construct a the vertex description by parsing the header
std::string line;
std::vector<VertexProperty> vertex_desc;
bool binary_data = false;
bool swap_endian = false;
size_t num_verts = 0;
// Check the first line is 'ply', so we actually have a .ply file
std::getline( file, line );
if( line != "ply" )
{
std::cout << "ERROR: unknown file type" << std::endl;
return;
}
// Loop until we reach the end of the header
while( line != "end_header" )
{
// Convert the std::string to a std::stringtream for convinience
std::getline( file, line );
std::stringstream stream( line );
std::cout << ": " << line << std::endl;
std::string identifier;
stream >> identifier;
if( identifier == "comment" || identifier == "end_header" )
{
// discard line
}
else if( identifier == "format" )
{
std::string type;
stream >> type;
if( type == "ascii" )
{
// The format is ASCII, we can continue as normal
}
else if( type == "binary_big_endian" )
{
swap_endian = true;
binary_data = true;
}
else if( type == "binary_little_endian" )
{
binary_data = true;
}
else
{
std::cout << "ERROR: unkown data format: '" << type << "'" << std::endl;
}
}
else if( identifier == "element" )
{
std::string type;
stream >> type;
if( type == "vertex" )
{
// The next number shoud be the number of verticies
stream >> num_verts;
}
}
else if( identifier == "property" )
{
std::string type;
stream >> type;
if( type == "list" )
{
// discard line
}
else if( type == "float" || type == "uchar" )
{
std::string name;
stream >> name;
// Set the size of the property in bytes
unsigned char size = (type == "float" ? 4 : 1);
PropertyIdent ident;
switch( name[0] )
{
case 'x': ident = PropertyIdent::x; break;
case 'y': ident = PropertyIdent::y; break;
case 'z': ident = PropertyIdent::z; break;
case 'r': ident = PropertyIdent::r; break;
case 'g': ident = PropertyIdent::g; break;
case 'b': ident = PropertyIdent::b; break;
default: ident = PropertyIdent::discard; break;
}
vertex_desc.push_back( VertexProperty{ ident, size } );
}
else
{
std::cout << "ERROR: unknown property type '" << type << "' in '" << filepath << "'" << std::endl;
}
}
} // Done parsing header
// Print out the format for the verticies
std::cout << "Format" << std::endl;
for( auto& vd : vertex_desc )
{
std::cout << "\tType: " << toString( vd.type ) << ", size: " << (int)vd.size << std::endl;
}
/*
if( binary_data )
{
// Repoen the file as binary
size_t pos = file.tellg(); // Store the current position
file.close(); // Close the ASCII file
file.open( filepath, std::ios::binary ); // Reopen the file as binary
file.seekg( pos, std::ios::beg ); // Restore the stream position
// Ensure everything is fine
if( !file.good() )
{
std::cout << "ERROR: could not reopen file as binary '" << filepath << "'" << std::endl;
return;
}
else
{
std::cout << "Reading file '" << filepath << "' as binary from location Ox" << std::hex << std::uppercase << pos << std::dec << std::nouppercase << std::endl;
}
}*/
// Prepare the data vector
data.clear();
data.reserve( num_verts * 6 );
// Now we can actually read the data from the file
for( size_t i = 0; i < num_verts && file.good(); i++ )
{
GLfloat x = 0, y = 0, z = 0;
GLfloat r = 1, g = 1, b = 1;
std::string discard;
for( auto& vd : vertex_desc )
{
if( binary_data )
{
if( vd.size == 1 )
{
unsigned char byte;
file.read( (char*)&byte, 1 );
switch( vd.type )
{
case PropertyIdent::x: x = byte / 255.0f; break;
case PropertyIdent::y: y = byte / 255.0f; break;
case PropertyIdent::z: z = byte / 255.0f; break;
case PropertyIdent::r: r = byte / 255.0f; break;
case PropertyIdent::g: g = byte / 255.0f; break;
case PropertyIdent::b: b = byte / 255.0f; break;
case PropertyIdent::discard: break;
}
}
else if( vd.size == 4 )
{
// WARNING: floats are hardcoded at 4 bytes in size
// TODO: indicate somehow if floats are not infact 4 bytes, maybe crash nicely
char byte_array[4] = { 0 };
file.read( byte_array, sizeof( byte_array ) );
if( swap_endian )
{
SDL_Swap32( *(Uint32*)byte_array );
}
switch( vd.type )
{
case PropertyIdent::x: x = *(float*)byte_array; break;
case PropertyIdent::y: y = *(float*)byte_array; break;
case PropertyIdent::z: z = *(float*)byte_array; break;
case PropertyIdent::r: r = *(float*)byte_array; break;
case PropertyIdent::g: g = *(float*)byte_array; break;
case PropertyIdent::b: b = *(float*)byte_array; break;
case PropertyIdent::discard: break;
}
}
else
{
std::cout << "ERROR: cannot read binary poperty type with size " << vd.size << " bytes." << std::endl;
break;
}
}
else // ASCII data
{
// TODO: what if RGB values are a uchar,
// do we need to divide by 255 when the file is ASCII? probably maybe?
switch( vd.type )
{
case PropertyIdent::x: file >> x; break;
case PropertyIdent::y: file >> y; break;
case PropertyIdent::z: file >> z; break;
case PropertyIdent::r: file >> r; break;
case PropertyIdent::g: file >> g; break;
case PropertyIdent::b: file >> b; break;
case PropertyIdent::discard: file >> discard; break;
}
}
}
data.push_back( x );
data.push_back( y );
data.push_back( z );
data.push_back( r );
data.push_back( g );
data.push_back( b );
}
// Check we actually read the correct number of verts
if( data.size() / 6 == num_verts )
{
std::cout << "Read " << num_verts << " verticies" << std::endl;
}
else
{
std::cout << "ERROR: header indicated " << num_verts << " veticies, but we read " << data.size() / 6 << std::endl;
}
}
std::string PlyLoader::toString( PropertyIdent p )
{
switch( p )
{
case PropertyIdent::x: return "x";
case PropertyIdent::y: return "y";
case PropertyIdent::z: return "z";
case PropertyIdent::r: return "r";
case PropertyIdent::g: return "g";
case PropertyIdent::b: return "b";
case PropertyIdent::discard: return "discard";
}
}
|
#ifndef _ITEM_SWORD_HPP
#define _ITEM_SWORD_HPP
#define SWORD_MODIFIER 4
void sword_deal_damage(entity_t *enemy) {
enemy->enemy_health -= 1 + SWORD_MODIFIER;
std::cout << "Damage taken. Current health: " << enemy->enemy_health << std::endl;
}
// Use this to achieve a "magic" effect on the player or whatever you want
// e.g. player gains +1 hp after using the item or moving with it
void sword_special_effect(entity_t *player) {
std::cout << "special effect" << std::endl;
player->player_health += 1;
}
#endif
|
//===========================================================================
/*
This file is part of the CHAI 3D visualization and haptics libraries.
Copyright (C) 2003-2004 by CHAI 3D. All rights reserved.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License("GPL") version 2
as published by the Free Software Foundation.
For using the CHAI 3D libraries with software that can not be combined
with the GNU GPL, and for taking advantage of the additional benefits
of our support services, please contact CHAI 3D about acquiring a
Professional Edition License.
\author: <http://www.chai3d.org>
\author: Dan Morris
\version 1.0
\date 3/2005
*/
//===========================================================================
#include "CLabelPanel.h"
// Default values for the user-adjustable parameters
#define DEFAULT_TOP_INTERNAL_BORDER 15
#define DEFAULT_BOTTOM_INTERNAL_BORDER 15
#define DEFAULT_LEFT_INTERNAL_BORDER 10
#define DEFAULT_RIGHT_INTERNAL_BORDER 10
#define DEFAULT_KEY_LABEL_SPACE 10
#define DEFAULT_KEY_SQUARE_SIZE 10
#define DEFAULT_INTER_LABEL_Y_STEP 25
#define DEFAULT_PANEL_WIDTH 150
#define DEFAULT_PANEL_HEIGHT 200
//===========================================================================
/*!
Constructor of cLabelPanel
\fn cLabelPanel::cLabelPanel(cWorld* a_world)
\param a_world The parent CHAI world
*/
//===========================================================================
cLabelPanel::cLabelPanel(cWorld* a_world) : cPanel(a_world)
{
m_halignment = ALIGN_CENTER;
m_valignment = VALIGN_CENTER;
m_interLabelSpacing = DEFAULT_INTER_LABEL_Y_STEP;
// We don't create our font until we render, since font information is
// only available once a display context has been created
// m_font = 0;
m_font = cFont::createFont();
m_backupFont = 0;
m_showSquares = false;
m_textColor = cColorf(1,1,1,1);
setSize(cVector3d(DEFAULT_PANEL_WIDTH,DEFAULT_PANEL_HEIGHT,0));
m_layoutPending = 0;
m_useLighting = true;
m_topBorder = DEFAULT_TOP_INTERNAL_BORDER;
m_leftBorder = DEFAULT_LEFT_INTERNAL_BORDER;
m_bottomBorder = DEFAULT_BOTTOM_INTERNAL_BORDER;
m_rightBorder = DEFAULT_RIGHT_INTERNAL_BORDER;
}
//===========================================================================
/*!
Destructor of cLabelPanel
\fn cLabelPanel::~cLabelPanel()
*/
//===========================================================================
cLabelPanel::~cLabelPanel()
{
clearLabels();
if (m_font) delete m_font;
if (m_backupFont) delete m_backupFont;
}
//===========================================================================
/*!
Clear all stored strings
\fn cLabelPanel::clearLabels()
*/
//===========================================================================
void cLabelPanel::clearLabels()
{
std::vector<char*>::iterator iter;
for(iter = m_labels.begin(); iter != m_labels.end(); iter++) {
delete [] (*iter);
}
m_labels.clear();
m_materials.clear();
layout();
}
//===========================================================================
/*!
Add a new line of text to be rendered.
\fn void cLabelPanel::addLabel(const char* a_label, const cMaterial* a_mat)
\param a_label The text to print
\param a_mat The color to put in the iconic box for this string, if you
have called setShowSquares(true) to render squares for each
label. Pass 0 (the default) to use a default material.
*/
//===========================================================================
void cLabelPanel::addLabel(const char* a_label, const cMaterial* a_mat)
{
char* buf = new char[strlen(a_label)+1];
strcpy(buf,a_label);
m_labels.push_back(buf);
if (a_mat == 0) {
// Default material
cMaterial mat;
m_materials.push_back(mat);
}
else {
m_materials.push_back(*a_mat);
m_showSquares = true;
}
layout();
}
//===========================================================================
/*!
Add a new line of text to be rendered.
\fn void cLabelPanel::setLabel(const unsigned int& a_index, const char* a_label)
\param a_index Which label are we changing?
\param a_label The text to print
*/
//===========================================================================
void cLabelPanel::setLabel(const unsigned int& a_index, const char* a_label)
{
if (a_index > m_labels.size()) return;
char* oldstr = m_labels[a_index];
char* buf = new char[strlen(a_label)+1];
strcpy(buf,a_label);
m_labels[a_index] = buf;
delete [] oldstr;
layout();
}
//===========================================================================
/*!
Re-compute the size of the box; actually just sets a flag to do this the next
time we render.
\fn void cLabelPanel::layout()
*/
//===========================================================================
void cLabelPanel::layout()
{
m_layoutPending = 1;
}
//===========================================================================
/*!
Re-compute the size of the box.
\fn void cLabelPanel::layoutImmediately()
*/
//===========================================================================
void cLabelPanel::layoutImmediately()
{
// Initialize our font if necessary
if (m_font == 0) buildFont();
m_layoutPending = 0;
// The longest line of text in our panel
int maxwidth = 0;
unsigned int numLabels = m_labels.size();
unsigned int i;
// Find the longest line of text in our panel
for(i=0; i<numLabels; i++)
{
char* label = m_labels[i];
char* ptr;
int width = 0;
for (ptr = label; *ptr; ptr++) width += m_font->getCharacterWidth(*ptr);
if (width > maxwidth) maxwidth = width;
}
// What should the total width of our panel be?
float width = (float)(maxwidth) + m_leftBorder + m_rightBorder;
if (m_showSquares) width += DEFAULT_KEY_LABEL_SPACE + DEFAULT_KEY_SQUARE_SIZE;
// What should the total height of our panel be?
float height = (float)(
m_interLabelSpacing * (numLabels-1) +
m_font->getPointSize() * numLabels +
m_topBorder +
m_bottomBorder
);
setSize(cVector3d(width,height,0));
m_yStep = (int)(m_interLabelSpacing + m_font->getPointSize());
}
//===========================================================================
/*!
Allows us to re-create font information after a GL context change
\fn void cLabelPanel::onDisplayReset(const bool a_affectChildren)
\param a_affectChildren Should we recursively affect our children?
*/
//===========================================================================
void cLabelPanel::onDisplayReset(const bool a_affectChildren) {
if (m_backupFont) delete m_backupFont;
m_backupFont = m_font;
m_font = 0;
m_layoutPending = true;
// Use the superclass method to call the same function on the rest of the
// scene graph...
cPanel::onDisplayReset(a_affectChildren);
}
//===========================================================================
/*!
Build a font object, optionally referring to our "backup" copy of an old font
\fn void cLabelPanel::buildFont()
*/
//===========================================================================
void cLabelPanel::buildFont()
{
if (m_font) delete m_font;
// Copy the font from an old version of the font (from a previous context)...
if (m_backupFont)
{
m_font = cFont::createFont(m_backupFont);
delete m_backupFont;
m_backupFont = 0;
}
// Otherwise just build a new font...
else
{
m_font = cFont::createFont();
}
}
//===========================================================================
/*!
Render the panel and all strings to the screen
\fn void cLabelPanel::render(const int a_renderMode)
\param a_renderMode The current rendering pass; see cGenericObject
*/
//===========================================================================
void cLabelPanel::render(const int a_renderMode)
{
// Initialize our font if necessary
if (m_font == 0) buildFont();
// We don't do multipass for this pure-2D class, so only render on the opaque passes
if (a_renderMode != CHAI_RENDER_MODE_RENDER_ALL &&
a_renderMode != CHAI_RENDER_MODE_TRANSPARENT_FRONT_ONLY) return;
// Lay myself out if necessary
if (m_layoutPending) layoutImmediately();
glPushMatrix();
// Move my origin to reflect alignment
if (m_halignment == ALIGN_LEFT) glTranslated(getSize().x/2.0,0,0);
else if (m_halignment == ALIGN_RIGHT) glTranslated(-1.0*getSize().x/2.0,0,0);
if (m_valignment == VALIGN_TOP) glTranslated(0,-1.0*getSize().y/2.0,0);
else if (m_valignment == VALIGN_BOTTOM) glTranslated(0,getSize().y/2.0,0);
// Render the background panel
cPanel::render(a_renderMode);
// Back up OpenGL normal state
float old_normal[3];
glGetFloatv(GL_CURRENT_NORMAL,old_normal);
glDisableClientState(GL_NORMAL_ARRAY);
glNormal3f(0,0,1.0f);
if (m_useLighting) glEnable(GL_LIGHTING);
else glDisable(GL_LIGHTING);
cVector3d size = getSize();
int starting_y = (int)(size.y/2.0 - m_topBorder - m_font->getPointSize());
int current_y = starting_y;
int current_x = (int)(-1.0*size.x/2.0) + m_leftBorder;
int num_labels = m_labels.size();
// Render each line of text
int i;
for(i=0; i<num_labels; i++)
{
char* label = m_labels[i];
cMaterial mat = m_materials[i];
current_x = (int)(-1.0*size.x/2.0) + m_leftBorder;
// Render this line's colored square if necessary
if (m_showSquares)
{
m_materials[i].render();
glTranslatef((float)current_x,(float)(current_y-1),0);
glBegin(GL_QUADS);
glVertex3f(0,0,0);
glVertex3f(DEFAULT_KEY_SQUARE_SIZE,0,0);
glVertex3f(DEFAULT_KEY_SQUARE_SIZE,DEFAULT_KEY_SQUARE_SIZE,0);
glVertex3f(0,DEFAULT_KEY_SQUARE_SIZE,0);
glEnd();
glTranslatef((float)(-current_x),(float)(-(current_y-1)),0);
current_x += DEFAULT_KEY_SQUARE_SIZE;
current_x += DEFAULT_KEY_LABEL_SPACE;
}
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE);
glColor4f(m_textColor[0],m_textColor[1],m_textColor[2],m_textColor[3]);
// We set the z-position to 1 to push him up a bit
glRasterPos3f((float)current_x,(float)current_y,1);
//glGetFloatv(GL_CURRENT_RASTER_POSITION,pos);
//glGetFloatv(GL_CURRENT_RASTER_POSITION_VALID,&valid);
m_font->renderString(label);
current_y -= m_yStep;
}
// Restore opengl state
glEnable(GL_LIGHTING);
glNormal3f(old_normal[0],old_normal[1],old_normal[2]);
glPopMatrix();
}
//===========================================================================
/*!
Read out a particular label
\fn const char* cLabelPanel::getLabel(const unsigned int& a_index) const
\param a_index Which label do you want to read?
\return The requested label, or 0 for an error
*/
//===========================================================================
const char* cLabelPanel::getLabel(const unsigned int& a_index) const
{
if (a_index >= m_labels.size()) return 0;
return m_labels[a_index];
}
//===========================================================================
/*!
Should we show iconic colored squares next to each line of text?
\fn void cLabelPanel::setShowSquares(const bool& a_showSquares)
\param a_showSquares True to show iconic squares
*/
//===========================================================================
void cLabelPanel::setShowSquares(const bool& a_showSquares)
{
if (m_showSquares == a_showSquares) return;
m_showSquares = a_showSquares;
layout();
}
//===========================================================================
/*!
Set the border size and spacing for labels within the panel
\fn void cLabelPanel::setBorders(const int& a_topBorder, const int& a_bottomBorder,
const int& a_leftBorder, const int& a_rightBorder,
const int& a_interLabelSpacing)
\param a_topBorder Sets the width, in pixels, of a particular border.
\param a_bottomBorder Sets the width, in pixels, of a particular border.
\param a_leftBorder Sets the width, in pixels, of a particular border.
\param a_rightBorder Sets the width, in pixels, of a particular border.
\param a_interLabelSpacing Sets the spacing, in pixels, between labels.
*/
//===========================================================================
void cLabelPanel::setBorders(const int& a_topBorder, const int& a_bottomBorder, const int& a_leftBorder,
const int& a_rightBorder, const int& a_interLabelSpacing)
{
bool newValue = false;
if ((a_topBorder >= 0) && (a_topBorder != m_topBorder)) newValue = true;
if ((a_leftBorder >= 0) && (a_leftBorder != m_leftBorder)) newValue = true;
if ((a_rightBorder >= 0) && (m_rightBorder != m_rightBorder)) newValue = true;
if ((a_bottomBorder >= 0) && (a_bottomBorder != m_bottomBorder)) newValue = true;
if ((a_interLabelSpacing >= 0) && (a_interLabelSpacing != m_interLabelSpacing)) newValue = true;
if (!newValue) return;
if (a_topBorder != -1) m_topBorder = a_topBorder;
if (a_rightBorder != -1) m_rightBorder = a_rightBorder;
if (a_leftBorder != -1) m_leftBorder = a_leftBorder;
if (a_bottomBorder != -1) m_bottomBorder = a_bottomBorder;
if (a_interLabelSpacing != -1) m_interLabelSpacing = a_interLabelSpacing;
layout();
}
//===========================================================================
/*!
Get the border size and spacing for labels within the panel
\fn void cLabelPanel::getBorders(int& a_topBorder, int& a_bottomBorder, int& a_leftBorder,
int& a_rightBorder, int& a_interLabelSpacing) const
\param a_topBorder Returns the width, in pixels, of a particular border.
\param a_bottomBorder Returns the width, in pixels, of a particular border.
\param a_leftBorder Returns the width, in pixels, of a particular border.
\param a_rightBorder Returns the width, in pixels, of a particular border.
\param a_interLabelSpacing Returns the spacing, in pixels, between labels.
*/
//===========================================================================
void cLabelPanel::getBorders(int& a_topBorder, int& a_bottomBorder, int& a_leftBorder,
int& a_rightBorder, int& a_interLabelSpacing) const
{
a_topBorder = m_topBorder;
a_bottomBorder = m_bottomBorder;
a_leftBorder = m_leftBorder;
a_rightBorder = m_rightBorder;
a_interLabelSpacing = m_interLabelSpacing;
}
//===========================================================================
/*!
Set the alignment of the _panel_ relative to its position (_not_ the text alignment).
Use the horizontal_label_panel_alignments and vertical_label_panel_alignments
enumerations found in cLabelPanel.h . For example, a right-aligned panel extends to the
left of its current position and vice-versa.
\fn void cLabelPanel::setAlignment(const int& a_horizontalAlignment, const int& a_verticalAlignment)
\param a_horizontalAlignment Should be ALIGN_CENTER, ALIGN_LEFT, or ALIGN_RIGHT
\param a_verticalAlignment Should be VALIGN_CENTER, VALIGN_TOP, or VALIGN_BOTTOM
*/
//===========================================================================
void cLabelPanel::setAlignment(const int& a_horizontalAlignment, const int& a_verticalAlignment)
{
bool newValue = false;
if (a_horizontalAlignment >= 0 && a_horizontalAlignment != m_halignment) newValue = true;
if (a_verticalAlignment >= 0 && a_verticalAlignment != m_valignment) newValue = true;
if (!newValue) return;
if (a_horizontalAlignment != -1) m_halignment = a_horizontalAlignment;
if (a_verticalAlignment != -1) m_valignment = a_verticalAlignment;
layout();
}
void cLabelPanel::getAlignment(int& a_horizontalAlignment, int& a_verticalAlignment) const
{
a_horizontalAlignment = m_halignment;
a_verticalAlignment = m_valignment;
}
|
//---------------------------------------------------------------------------
#ifndef AllSourceGenH
#define AllSourceGenH
//---------------------------------------------------------------------------
#include "WorkSpaceManager.h"
#include "PluginManager.h"
#include "SourceGen.h"
class AllSourceGen
{
private:
WorkSpaceManager * m_WorkSpaceManager;
PluginManager * m_PluginManager;
SourceGen m_SourceGen;
TStringList * m_AllClassList;
public:
AllSourceGen();
~AllSourceGen();
void SaveSource(WorkSpaceManager * workSpaceManager,
PluginManager * pluginManager,
String fileName,
String sourceMod);
};
#endif
|
/**
* @file No_Track.hpp
*
* @author Matthew
* @version 1.0.0
* @date Apr 17, 2015
*/
#ifndef VALKNUT_CORE_TRACKING_POLICIES_NO_TRACKING_HPP_
#define VALKNUT_CORE_TRACKING_POLICIES_NO_TRACKING_HPP_
namespace valknut{
namespace tracking_policies{
//////////////////////////////////////////////////////////////////////////
/// @class valknut::tracking_policies::No_Tracking
///
/// Empty tracking policy, used in production for allocators that don't
/// need overhead
//////////////////////////////////////////////////////////////////////////
class No_Tracking{
//----------------------------------------------------------------------
// Constructors / Assignment / Destructor
//----------------------------------------------------------------------
public:
inline No_Tracking( void* /* unused */, size_t /* unused */ ){}
//----------------------------------------------------------------------
// Tracking Policy API
//----------------------------------------------------------------------
public:
inline void on_allocate( void* /* unused */, size_t /* unused */ ){};
inline void on_deallocate( void* /* unused */, size_t /* unused */ ){};
inline void on_reset(){}
};
} // namespace tracking_policies
} // namespace valknut
#endif /* VALKNUT_CORE_TRACKING_POLICIES_NO_TRACKING_HPP_ */
|
#include <stdexcept>
#include "am_pm_clock.h"
am_pm_clock::am_pm_clock():
hours(12),
minutes(0),
seconds(0),
am(true) {}
am_pm_clock::am_pm_clock(unsigned int hrs, unsigned int mins,
unsigned int secs, bool am_val):
hours(hrs),
minutes(mins),
seconds(secs),
am(am_val) {}
am_pm_clock::am_pm_clock(const am_pm_clock & clock):
hours(clock.hours),
minutes(clock.minutes),
seconds(clock.seconds),
am(clock.am) {}
am_pm_clock & am_pm_clock::operator = (const am_pm_clock & clock) {
this -> hours = clock.hours;
this -> minutes = clock.minutes;
this -> seconds = clock.seconds;
this -> am = clock.am;
return *this;
}
unsigned int am_pm_clock::get_hours() const {
return hours;
}
void am_pm_clock::set_hours(unsigned int hrs) {
hours = hrs;
if (hrs > 12 || hrs < 1) throw std::invalid_argument("is not a legal");
}
unsigned int am_pm_clock::get_minutes() const {
return minutes;
}
void am_pm_clock::set_minutes(unsigned int mins) {
minutes = mins;
if (mins > 59 || mins < 0) throw std::invalid_argument("is not a legal");
}
unsigned int am_pm_clock::get_seconds() const {
return seconds;
}
void am_pm_clock::set_seconds(unsigned int secs) {
seconds = secs;
if (secs > 59 || secs < 0) throw std::invalid_argument("is not a legal");
}
bool am_pm_clock::is_am() const {
return am;
}
void am_pm_clock::set_am(bool am_val) {
am = am_val;
}
void am_pm_clock::toggle_am_pm() {
if (am == false) {
am = true;
} else {
am = false;
}
}
void am_pm_clock::reset() {
hours = 12;
minutes = 0;
seconds = 0;
am = true;
}
void am_pm_clock::advance_one_sec() {
if (seconds == 59) {
seconds = 00;
if (minutes == 59) {
minutes = 00;
if (hours == 11) {
toggle_am_pm();
hours++;
} else if (hours == 12) {
hours = 1;
} else {
hours++;
}
} else {
minutes++;
}
} else {
seconds++;
}
}
void am_pm_clock::advance_n_secs(unsigned int n) {
int i = n - 59;
minutes = minutes + 1;
while (i > 59) {
minutes = minutes + 1;
i = i - 60;
}
seconds = i;
if (minutes > 59) {
int j = minutes - 60;
hours = hours + 1;
while (j > 59) {
hours = hours + 1;
j = j - 60;
}
minutes = j;
}
if (hours > 12) {
hours = hours - 12;
}
}
am_pm_clock::~am_pm_clock() {}
|
#include "compiler/grammar.hpp"
#include "compiler/conversions.hpp"
#include "compiler/ast_adapted.hpp"
#include <boost/spirit/home/qi.hpp>
#include <boost/spirit/home/lex.hpp>
using namespace std::string_literals;
namespace perseus
{
namespace detail
{
namespace ast
{
// import ast::parser into ast namespace, since the parser exclusively creates ast::parser AST nodes
using namespace parser;
}
namespace qi = boost::spirit::qi;
// rule definition; optional attributes are generated from the matched code
template< typename attribute = boost::spirit::unused_type >
using rule = qi::rule< token_iterator, attribute(), skip_grammar >;
// terminals
// literals
static rule< ast::string_literal > string{ string_literal_parser{}, "string literal"s };
static rule< std::int32_t > decimal_integer{ decimal_integer_literal_parser{}, "decimal integer"s };
static rule< std::int32_t > hexadecimal_integer{ hexadecimal_integer_literal_parser{}, "hexadecimal integer"s };
static rule< std::int32_t > binary_integer{ binary_integer_literal_parser{}, "binary integer"s };
static rule< std::int32_t > integer{ decimal_integer | hexadecimal_integer | binary_integer, "integer"s };
static rule< bool > true_{ qi::omit[ qi::token( token_id::true_ ) ] > qi::attr( true ), "true"s };
static rule< bool > false_{ qi::omit[ qi::token( token_id::false_ ) ] > qi::attr( false ), "false"s };
static rule< ast::identifier > identifier{ qi::token( token_id::identifier ), "identifier"s };
static rule< ast::identifier > operator_identifier{ qi::token( token_id::operator_identifier ), "operator identifier"s };
#define PERSEUS_TERMINAL( identifier, name ) static rule<> identifier{ qi::token( token_id::identifier ), name }
PERSEUS_TERMINAL( if_, "if"s );
PERSEUS_TERMINAL( else_, "else"s );
PERSEUS_TERMINAL( while_, "while"s );
PERSEUS_TERMINAL( return_, "return"s );
PERSEUS_TERMINAL( colon, "colon"s );
PERSEUS_TERMINAL( semicolon, "semicolon"s );
PERSEUS_TERMINAL( dot, "dot"s );
PERSEUS_TERMINAL( comma, "comma"s );
PERSEUS_TERMINAL( equals, "equals sign"s );
PERSEUS_TERMINAL( backtick, "backtick"s );
PERSEUS_TERMINAL( arrow_right, "arrow right"s );
PERSEUS_TERMINAL( paren_open, "opening paren"s );
PERSEUS_TERMINAL( paren_close, "closing paren"s );
PERSEUS_TERMINAL( brace_open, "opening brace"s );
PERSEUS_TERMINAL( brace_close, "closing brace"s );
PERSEUS_TERMINAL( square_bracket_open, "opening square bracket"s );
PERSEUS_TERMINAL( square_bracket_close, "closing square bracket"s );
PERSEUS_TERMINAL( let_, "let" );
PERSEUS_TERMINAL( function_, "function" );
PERSEUS_TERMINAL( mutable_, "mutable" );
PERSEUS_TERMINAL( impure_, "impure" );
#undef PERSEUS_TERMINAL
// non-terminals
static grammar::start_type file;
static rule< ast::expression > expression{ "expression"s };
static rule< ast::operand > operand{ "operand"s };
static rule< ast::operation > operation{ "operation"s };
static rule< ast::binary_operation > binary_operation{ "binary operation"s };
static rule< ast::unary_operation > unary_operation{ "unary operation"s };
static rule< ast::if_expression > if_expression{ "if expression"s };
static rule< ast::while_expression > while_expression{ "while expression"s };
static rule< ast::return_expression > return_expression{ "return expression"s };
static rule< ast::call_expression > call_expression{ "call expression"s };
static rule< ast::block_expression > block_expression{ "block expression"s };
static rule< ast::expression > parens_expression{ "parens expression"s };
static rule< ast::index_expression > index_expression{ "index expression"s };
static rule< ast::explicit_variable_declaration > explicit_variable_declaration{ "explicit variable declaration"s };
static rule< ast::deduced_variable_declaration > deduced_variable_declaration{ "deduced variable declaration"s };
static rule< ast::function_definition > function_definition{ "function definition"s };
static rule< ast::function_argument > function_argument{ "function argument"s };
static rule< ast::block_member > block_member{ "block member"s };
static rule< bool > optional_mutable{ "optional mutable"s };
static rule< bool > optional_impure{ "optional impure"s };
grammar::grammar()
: base_type( file, "perseus script"s )
{
// EOI = End of Input
file = +function_definition > qi::eoi;
function_definition = (optional_impure >> function_) > identifier > paren_open > -( function_argument % comma ) > paren_close > -( arrow_right > identifier ) > expression;
{
optional_impure = ( impure_ >> qi::attr( false ) ) | qi::attr( true );
function_argument = identifier > colon > identifier;
// this split is required to prevent left recursion, which in the parser turns into an infinite recursion.
expression = operand >> *operation;
{
// what about operator_identifier? first class functions and all that?
operand = string | integer | true_ | false_ | identifier | unary_operation | if_expression | while_expression | return_expression | block_expression | parens_expression;
{
// `op` x
unary_operation = operator_identifier > operand;
// if cond then_body else_body
// Logically there's always an else, but it may be "nothing" (i.e. void).
// > is an expectation concatenation: after an "if" terminal there *must* be an expression (allows for early abortion in case of errors and better errors)
// this parsing is eager, i.e. `if c1 if c2 t else e` means `if c1 { if c2 t else e }`
auto default_to_void = qi::attr( ast::expression{ ast::void_expression{},{} } );
if_expression = if_ > expression > expression > ( ( else_ > expression ) | default_to_void );
// while cond body
while_expression = while_ > expression > expression;
// return exp
return_expression = return_ > ( expression | default_to_void );
// { exp1; exp2 }
block_expression = brace_open > ( ( block_member | default_to_void ) % semicolon ) > brace_close;
{
block_member = expression | explicit_variable_declaration | deduced_variable_declaration;
{
// let [mut] x : t = v
explicit_variable_declaration = let_ >> optional_mutable >> identifier >> colon >> identifier >> equals >> expression; // > (expectation) won't compile? I don't even?
// let [mut] x = v
deduced_variable_declaration = let_ >> optional_mutable >> identifier >> ( equals > expression ); // similar deal - only compiles with the parens?!
{
optional_mutable = ( mutable_ >> qi::attr( true ) ) | qi::attr( false );
}
}
}
// ( expression )
parens_expression = paren_open > expression > paren_close;
}
operation = binary_operation | call_expression | index_expression;
{
// x `op` y
binary_operation = ( operator_identifier | ( backtick > identifier > backtick ) ) >> operand;
// name( arg1, arg2 )
// a % b means list of a separated by b; that has a minimum length of 1, thus the - (optional)
call_expression = paren_open > -( expression % comma ) > paren_close;
// object[index]
index_expression = square_bracket_open > expression > square_bracket_close;
}
}
}
// in order for debug output to work, operator<<( std::ostream&, Attribute ) must be defined
/*
debug( expression );
debug( operand );
debug( operation );
debug( binary_operation );
debug( unary_operation );
debug( if_expression );
debug( while_expression );
debug( return_expression );
debug( call_expression );
debug( block_expression );
debug( parens_expression );
debug( index_expression );
debug( explicit_variable_declaration );
debug( deduced_variable_declaration );
debug( function_definition );
debug( function_argument );
debug( block_member );
debug( optional_mutable );
debug( optional_impure );
*/
}
using skip_rule = qi::rule< token_iterator >;
// terminals
static skip_rule whitespace{ qi::token( token_id::whitespace ), "whitespace"s };
static skip_rule comment{ qi::token( token_id::comment ), "comment"s };
// start symbol
static skip_grammar::start_type skip{ whitespace | comment };
skip_grammar::skip_grammar()
: base_type( skip )
{
}
}
}
|
#pragma once
// CAppendAccountDlg 대화 상자
class CAppendAccountDlg : public CDialogEx
{
DECLARE_DYNAMIC(CAppendAccountDlg)
public:
CAppendAccountDlg(CWnd* pParent = nullptr); // 표준 생성자입니다.
virtual ~CAppendAccountDlg();
// 대화 상자 데이터입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DIALOG_MEMAPP };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
CString m_strID;
CString m_strPw;
CString m_strName;
CString m_strAddress;
CString m_strMailAcc;
bool m_bGender;
CString m_strMailDom;// 메일 도메인
afx_msg void OnCbnSelchangeComboDomain();
afx_msg void OnBnClickedRadioMale();
afx_msg void OnBnClickedRadioFemale();
CComboBox m_cbDomain;
afx_msg void OnBnClickedButtonAppeand();
};
|
// -----------------------------------------------------------------------------
// MCParticle.h
//
// Class definition of MCParticle
// * Author: Everybody is an author!
// * Creation date: 7 August 2020
// -----------------------------------------------------------------------------
#ifndef MCParticle_h
#define MCParticle_h 1
// Q-Pix includes
#include "geo_types.h"
// GEANT4 includes
#include "G4LorentzVector.hh"
#include "G4Step.hh"
// ROOT includes
#include "TLorentzVector.h"
// C++ includes
#include <string>
#include <tuple>
#include <utility>
#include <vector>
// struct TrajectoryPoint
// {
// TLorentzVector position_;
// TLorentzVector momentum_;
// std::string process_ = "unknown";
// double energy_deposit_ = 0;
// double length_ = 0;
//
// TLorentzVector Position() const { return position_; }
// TLorentzVector Momentum() const { return momentum_; }
// std::string Process() const { return process_; }
// double EnergyDeposit() const { return energy_deposit_; }
// double Length() const { return length_; }
//
// double X() const { return position_.X(); }
// double Y() const { return position_.Y(); }
// double Z() const { return position_.Z(); }
// double T() const { return position_.T(); }
//
// double Px() const { return momentum_.Px(); }
// double Py() const { return momentum_.Py(); }
// double Pz() const { return momentum_.Pz(); }
// double E() const { return momentum_.E(); }
// };
struct TrajectoryHit
{
Point_t start_ = {0., 0., 0.};
Point_t end_ = {0., 0., 0.};
double energy_deposit_ = 0;
double start_time_ = 0;
double end_time_ = 0;
int track_id_ = -1;
int pdg_code_ = -1;
double length_ = 0;
std::string process_ = "unknown";
Point_t StartPoint() const { return start_; }
Point_t EndPoint() const { return end_; }
Point_t MidPoint() const { return { (start_.X() + end_.X())/2.0,
(start_.Y() + end_.Y())/2.0,
(start_.Z() + end_.Z())/2.0 }; }
double StartTime() const { return start_time_; }
double EndTime() const { return end_time_; }
double Time() const { return (start_time_ + end_time_)/2.0; }
double Energy() const { return energy_deposit_; }
double TrackID() const { return track_id_; }
double PDGCode() const { return pdg_code_; }
double Length() const { return length_; }
std::string Process() const { return process_; }
};
class MCParticle
{
public:
MCParticle();
~MCParticle();
// void AddTrajectoryPoint(const TrajectoryPoint &);
void AddTrajectoryHit(TrajectoryHit const &);
void AddTrajectoryHit(G4Step const *);
void AddPmtHit(TrajectoryHit const &);
void AddPmtHit(G4Step const *);
inline std::vector< TrajectoryHit > Hits() const { return hits_; }
inline std::vector< TrajectoryHit > PmtHits() const { return pmt_hits_; }
inline int TrackID() const { return track_id_; }
inline int ParentTrackID() const { return parent_track_id_; }
inline int PDGCode() const { return pdg_code_; }
inline double Mass() const { return mass_; }
inline double Charge() const { return charge_; }
inline double GlobalTime() const { return global_time_; }
inline std::string Process() const { return process_; }
inline int TotalOccupancy() const { return total_occupancy_; }
inline TLorentzVector InitialPosition() const { return initial_position_; }
inline TLorentzVector InitialMomentum() const { return initial_momentum_; }
inline void SetTrackID(int const trackID) { track_id_ = trackID; }
inline void SetParentTrackID(int const parentTrackID) { parent_track_id_ = parentTrackID; }
inline void SetPDGCode(int const pdgCode) { pdg_code_ = pdgCode; }
inline void SetMass(double const mass) { mass_ = mass; }
inline void SetCharge(double const charge) { charge_ = charge; }
inline void SetGlobalTime(double const globalTime) { global_time_ = globalTime; }
inline void SetProcess(std::string const process) { process_ = process; }
inline void SetTotalOccupancy(int const totalOccupancy) { total_occupancy_ = totalOccupancy; }
inline void SetInitialPosition(TLorentzVector const initialPosition) { initial_position_ = initialPosition; }
inline void SetInitialMomentum(TLorentzVector const initialMomentum) { initial_momentum_ = initialMomentum; }
private:
int track_id_;
int parent_track_id_;
int pdg_code_;
double mass_;
double charge_;
double global_time_;
std::string process_;
int total_occupancy_;
TLorentzVector initial_position_;
TLorentzVector initial_momentum_;
// std::vector< TrajectoryPoint > trajectory_;
std::vector< TrajectoryHit > hits_;
std::vector< TrajectoryHit > pmt_hits_;
};
#endif
|
/*
* Session.cpp
*
* Created on: Jun 11, 2017
* Author: root
*/
#include "Session.h"
#include "EpollMain.h"
#include "Context.h"
#include "../util.h"
#include "../Log/Logger.h"
#include "MessageManager.h"
#include "DispatchMessage.h"
#include "GroupSession.h"
namespace CommBaseOut
{
Session::Session(Context *c, CSessionMgr *s, int sock, int flag, struct sockaddr_in &addr, bool isSecurity):m_c(c),m_remoteID(0),
m_remoteType(0),m_accSock(sock),m_lastPacketTime(0), m_flag(flag),m_bufRecv(0),dwRecvPos(0),m_s(s), m_security(isSecurity),bufSend(0),m_groupID(-1)
#ifdef USE_PACKAGE_COUNT
,m_recvCount(0),m_sendCount(0),m_recvTime(0),m_sendTime(0)
#endif
{
m_addr = NEW Inet_Addr(&addr);
m_bufRecv = NEW_BASE(char, MAX_RECV_MSG_SIZE);// char[MAX_RECV_MSG_SIZE];
bufSend = NEW CCircleBuff(MAX_NET_MSG_SIZE[eClientBuf]);
}
Session::~Session()
{
if(m_accSock >= 0)
{
m_accSock = -1;
}
DELETE_BASE(m_bufRecv, eMemoryArray);
m_bufRecv = 0;
delete bufSend;
bufSend = 0;
}
char * Session::GetRecvBuf()
{
return m_bufRecv;
}
DWORD Session::GetRecvPos()
{
return dwRecvPos;
}
int Session::AddMessage(Safe_Smart_Ptr<Message> &message)
{
try
{
if(message->GetMessageType() == ConnMessage)
{
int res = -1;
if((res=m_s->ConnectSuccess(message)) != 0 && res != eGroupContinue)
{
m_c->GetEpollMgr()->DeleteChannel(message->GetChannelID(), res);
// printf("\n---------------connectsuccess close session = %d-----------\n", message->GetChannelID());
return -1;
}
if(res != eGroupContinue)
{
if(message->GetGroup() >= 0)
m_c->SystemErr(message->GetGroup(), message->GetLocalID(), message->GetLocalType(),
message->GetRemoteID(), message->GetRemoteType(), 0, message->GetAddr()->GetIPToString(),message->GetAddr()->GetPort());
else
m_c->SystemErr(message->GetChannelID(), message->GetLocalID(), message->GetLocalType(),
message->GetRemoteID(), message->GetRemoteType(), 0, message->GetAddr()->GetIPToString(),message->GetAddr()->GetPort());
}
return 1;
}
// if(message->GetMessageType() == Ack)
// {
// if(0 != m_c->GetAckTimeout()->DelAckTimeOut(message))
// {
//// LOG_BASE(FILEINFO,"request already ack but ack timeout is null");
//
// return -1;
// }
// }
// m_c->GetDispatch()->GetDispatch(message->GetChannelID())->AddMessage(message);
// m_c->GetEpollMgr()->GetEpollLoop((m_flag >> 8) & 0xff)->GetDispatch()->AddMessage(message);
}
catch(exception &e)
{
LOG_BASE(FILEINFO, "add message error[errmsg = %s]", e.what());
return -1;
}
catch(...)
{
LOG_BASE(FILEINFO, "add message unknown error");
return -1;
}
return 0;
}
int Session::Recv(deque<Safe_Smart_Ptr<Message> > &vec)
{
int ret = 0;
packetHeader head;
const char *tmpHead = m_bufRecv;
int nLeftSize = dwRecvPos;
while(1)
{
if(nLeftSize < HEADER_LENGTH)
{
dwRecvPos = nLeftSize;
if(0 != CUtil::SafeMemmove(m_bufRecv, MAX_RECV_MSG_SIZE - dwRecvPos, tmpHead, dwRecvPos))
{
dwRecvPos = 0;
LOG_BASE(FILEINFO, "the rest is less than header and recv copy error ,so clear package content");
}
break;
}
int moveRes = CUtil::SafeMemmove(&head, HEADER_LENGTH, tmpHead, HEADER_LENGTH);
if (0 != moveRes)
{
dwRecvPos = nLeftSize;
if(0 != CUtil::SafeMemmove(m_bufRecv, MAX_RECV_MSG_SIZE - dwRecvPos, tmpHead, nLeftSize))
{
dwRecvPos = 0;
LOG_BASE(FILEINFO, "copy header and recv copy error, so clear package content ");
break;
}
break;
}
head.toBigEndian();
// head.toSmallEndian();
if(head.remoteID < 0 || head.length < 0 || head.remoteType >= eMax || head.localType >= eMax || head.messageType > SystemMessage)
{
LOG_BASE(FILEINFO, "serialize header but header content error, so clear package content ip[%s]", m_addr->GetIPToChar());
if(m_remoteType == eClient)
return eSocketClose;
dwRecvPos = 0;
break;
}
if(MAX_MSG_PACKET_SIZE < head.length + HEADER_LENGTH)
{
LOG_BASE(FILEINFO, "recv but length more than package length ip[%s]", m_addr->GetIPToChar());
if(m_remoteType == eClient)
return eSocketClose;
dwRecvPos = 0;
break;
}
if (nLeftSize < HEADER_LENGTH + head.length)
{
dwRecvPos = nLeftSize;
if(0 != CUtil::SafeMemmove(m_bufRecv, MAX_RECV_MSG_SIZE - dwRecvPos, tmpHead, nLeftSize))
{
dwRecvPos = 0;
LOG_BASE(FILEINFO, "the rest is not all package and recv copy error, so clear package content ");
}
break;
}
#ifdef USE_PACKAGE_COUNT
m_recvCount++;
#endif
Safe_Smart_Ptr<Message> recvMessage = NEW Message(m_remoteID, m_remoteType);
if(recvMessage && recvMessage->GetContent())
{
recvMessage->SetHead(head);
if(head.remoteID == m_c->GetConfig()->local_id_ && head.remoteType == m_c->GetConfig()->local_type_ && recvMessage->GetSecurity() == m_security)
{
recvMessage->SetContent(tmpHead+HEADER_LENGTH, head.length);
recvMessage->SetAddr(m_addr);
recvMessage->SetChannelID(m_accSock);
recvMessage->SetGroup(m_groupID);
recvMessage->SetLoopIndex((m_flag >> 8) & 0xff);
if(recvMessage->UnEncryptMessage())
{
if(recvMessage->GetMessageTime() > 0)
{
// printf("\n recv message session[ msgid = %d] recv time = %lld bbbbbbbbbbbbbbbbbbbbb\n", recvMessage->GetMessageID(), CUtil::GetNowSecond() - recvMessage->GetMessageTime());
}
ret = AddMessage(recvMessage);
if(ret < 0)
{
LOG_BASE(FILEINFO, "recv but add message error and throw out pakcage");
}
else if(ret == 0)
{
vec.push_back(recvMessage);
}
}
}
}
tmpHead += (HEADER_LENGTH + head.length);
nLeftSize -= (HEADER_LENGTH + head.length);
if(nLeftSize <= 0)
{
dwRecvPos = 0;
break;
}
}
return ret;
}
int Session::Recv()
{
int ret = 0;
deque<Safe_Smart_Ptr<Message> > vec;
while(1)
{
int nRet = recv(m_accSock, m_bufRecv + dwRecvPos, MAX_RECV_MSG_SIZE - dwRecvPos, 0);
if(nRet == 0)
{
return eSocketClose;
}
else if(nRet < 0)
{
if(errno == EAGAIN)
{
break;
}
else
{
char errorMsg[1024] = {0};
perror(errorMsg);
LOG_BASE(FILEINFO, "recv find net error[%s] and recv end", errorMsg);
ret = eNetError;
break;
}
}
dwRecvPos += nRet;
const char *tmpHead = m_bufRecv;
// if(dwRecvPos == 23 && strcmp(tmpHead, "<policy-file-request/>") == 0)
// {
// char rbuf[512]="<?xml version=\"1.0\"?><cross-domain-policy><site-control permitted-cross-domain-policies=\"all\"/><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>\0";
// LOG_BASE(FILEINFO, "\n ++++++++++++ recv http[%s] socket[%d] +++++++++++++++++++\n", rbuf, m_accSock);
// Write(rbuf, strlen(rbuf) + 1);
//
// return eNetSuccess;
// }
if(dwRecvPos < (DWORD)HEADER_LENGTH )
{
continue;
}
ret = Recv(vec);
if(ret == eSocketClose)
{
return ret;
}
}
ret = Recv(vec);
if(ret == eSocketClose)
{
return ret;
}
m_c->GetDispatch()->GetDispatch(m_accSock)->AddMessage(vec);
#ifdef USE_PACKAGE_COUNT
if(m_recvTime <= 0)
{
m_recvTime = CUtil::GetNowSecond();
}
else
{
int64 nowTime = CUtil::GetNowSecond();
if(nowTime - m_recvTime > 20 * 1000)
{
int tCount = m_recvCount / 20;
if(tCount > 60)
{
if(m_remoteType <= eClient || m_remoteType >= eMax)
{
LOG_BASE(FILEINFO, "session send to many package[%d] and close session", tCount);
return eSocketClose;
}
}
m_recvCount = 0;
m_recvTime = nowTime;
}
}
#endif
return eNetSuccess;
}
int Session::Write(Safe_Smart_Ptr<Message> &message)
{
int res = -1;
packetHeader head;
if(message->GetSecurity() != m_security)
{
message->SetSecurity(m_security);
}
message->EncryptMessage();
message->GetHead(&head);
// printf("\n++++++++++++++++write2 begin session = %x+++++++++++++++++++++++++++\n", this);
GUARD(CSimLock, obj, &m_bufLock);
if((res = bufSend->WriteSend(message->GetContent(), &head)) != 0)
{
LOG_BASE(FILEINFO, "send writebuff error and session[rid=%d, rtype=%d, messageid=%d]", m_remoteID, m_remoteType, head.messageID);
return res;
}
obj.UnLock();
// printf("\n++++++++++++++++write2 end session = %x+++++++++++++++++++++++++++\n", this);
struct epoll_event ev;
bzero(&ev, sizeof(ev));
ev.events = EPOLLIN | EPOLLET | EPOLLOUT | EPOLLRDHUP | EPOLLERR | EPOLLHUP;
// ev.data.fd = m_accSock;
ev.data.ptr = (void *)m_s->GetEventPtr(m_accSock);
if (m_c->GetEpollMgr()->GetEpollLoop(m_accSock)->EpollCtl(EPOLL_CTL_MOD, m_accSock, &ev) != 0)
{
LOG_BASE(FILEINFO, "send get epoll error");
return eCtlEpollErr;
}
return eNetSuccess;
}
int Session::Write(char *buf, int len)
{
int res = -1;
// printf("\n++++++++++++++++write1 begin session = %x+++++++++++++++++++++++++++\n", this);
GUARD(CSimLock, obj, &m_bufLock);
if((res = bufSend->WriteBuffer(buf, len)) != 0)
{
LOG_BASE(FILEINFO, "send writebuff error and session[rid=%d, rtype=%d]", m_remoteID, m_remoteType);
return res;
}
obj.UnLock();
// printf("\n++++++++++++++++write1 end session = %x+++++++++++++++++++++++++++\n", this);
struct epoll_event ev;
bzero(&ev, sizeof(ev));
ev.events = EPOLLIN | EPOLLET | EPOLLOUT | EPOLLRDHUP | EPOLLERR | EPOLLHUP;
// ev.data.fd = m_accSock;
ev.data.ptr = (void *)m_s->GetEventPtr(m_accSock);
if (m_c->GetEpollMgr()->GetEpollLoop(m_accSock)->EpollCtl(EPOLL_CTL_MOD, m_accSock, &ev) != 0)
{
LOG_BASE(FILEINFO, "send get epoll error");
return eCtlEpollErr;
}
return eNetSuccess;
}
int Session::Write(char *content, packetHeader* head)
{
int res = -1;
// printf("\n++++++++++++++++write2 begin session = %x+++++++++++++++++++++++++++\n", this);
GUARD(CSimLock, obj, &m_bufLock);
if((res = bufSend->WriteSend(content, head)) != 0)
{
if(m_remoteType == eClient)
head->toBigEndianEx();
LOG_BASE(FILEINFO, "send writebuff error[return[%d]] and session[socket=%d,rid=%d, rtype=%d, messageid=%d, length=%d]", res, m_accSock, m_remoteID, m_remoteType, head->messageID, head->length);
return res;
}
obj.UnLock();
// printf("\n++++++++++++++++write2 end session = %x+++++++++++++++++++++++++++\n", this);
struct epoll_event ev;
bzero(&ev, sizeof(ev));
ev.events = EPOLLIN | EPOLLET | EPOLLOUT | EPOLLRDHUP | EPOLLERR | EPOLLHUP;
// ev.data.fd = m_accSock;
ev.data.ptr = (void *)m_s->GetEventPtr(m_accSock);
if (m_c->GetEpollMgr()->GetEpollLoop(m_accSock)->EpollCtl(EPOLL_CTL_MOD, m_accSock, &ev) != 0)
{
LOG_BASE(FILEINFO, "send get epoll error socket[%d]", m_accSock);
return eCtlEpollErr;
}
return eNetSuccess;
}
int Session::Send()
{
int64 belocktime = CUtil::GetNowMicrosecod();
GUARD(CSimLock, obj, &m_bufLock);
int64 endlocktime = CUtil::GetNowMicrosecod();
if(endlocktime - belocktime >= 100 * 1000)
LOG_BASE(FILEINFO, "send message but lock too more time[%lld]", endlocktime - belocktime);
if(bufSend->IsEmpty())
{
return eNetSuccess;
}
const char *bufRead = NULL;
int nBuffLen = 0;
if (bufSend->ReadSendBuff(bufRead, nBuffLen) != 0)
{
return eNetSuccess;
}
int nSendTotal = 0;
// printf("\n----------------%d session=%x send=%x readindex=%d writeindex=%d lastindex = %d------------------------\n", m_accSock, this, bufSend,bufSend->GetReadIndex(), bufSend->GetWriteIndex(), bufSend->GetLastIndex());
while(1)
{
int nRet = send(m_accSock, bufRead + nSendTotal, nBuffLen - nSendTotal, MSG_NOSIGNAL);
if(nRet == 0)
{
LOG_BASE(FILEINFO, "send socket error");
return eSocketClose;
}
else if(nRet < 0)
{
if(errno == EAGAIN)
{
break;
}
else
{
LOG_BASE(FILEINFO, "socket send error");
return eSockSendErr;
}
}
nSendTotal += nRet;
if(nSendTotal >= nBuffLen)
{
break;
}
}
// printf("\n----------------%d session=%x send=%x send size=%d------------------------\n", m_accSock, this, bufSend, nSendTotal);
bufSend->HadRead(nSendTotal);
int64 endtime = CUtil::GetNowMicrosecod();
if(endtime - belocktime >= 100 * 1000)
LOG_BASE(FILEINFO, "send message from tcp too more time[%lld]", endtime - belocktime);
return eNetSuccess;
}
void Session::AddPos(DWORD len)
{
dwRecvPos += len;
}
void Session::SetPos(DWORD len)
{
dwRecvPos = len;
}
void Session::SetRemoteID(short int id)
{
m_remoteID = id;
}
void Session::SetRemoteType(unsigned char type)
{
m_remoteType = type;
}
int Session::GetFlag()
{
return m_flag;
}
CSessionMgr::CSessionMgr(Context *c):m_bTime(CUtil::GetNowMicrosecod()),m_tick(0),m_epollPtr(0),m_c(c)
{
m_epollPtr = new EpollEventPtr[MAX_EPOLL_EVENT];
}
CSessionMgr::~CSessionMgr()
{
m_session.clear();
m_timeOutSe.clear();
if(m_epollPtr)
{
delete[] m_epollPtr;
m_epollPtr = 0;
}
}
EpollEventPtr * CSessionMgr::AddTimerSessionEx(int sock, struct sockaddr_in &addr, ChannelConfig * config, WORD index, unsigned char type)
{
if(MAX_EPOLL_EVENT <= sock)
{
return 0;
}
int key = index;
Safe_Smart_Ptr<Session> se;
key = ((key << 8) | type);
if(config->channel_keep_time_ > 0)
{
GUARD_WRITE(CRWLock, obj, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_timeOutSe.find(sock);
if(it != m_timeOutSe.end())
{
LOG_BASE(FILEINFO, "add session same timer so error");
return 0;
}
se = NEW Session(m_c, this, sock, key, addr, config->security_);
m_timeOutSe[sock] = se;
obj.UnLock();
m_timeout[sock] = config->channel_keep_time_ + CUtil::GetNowSecond();
m_epollPtr[sock].se = se;
return &m_epollPtr[sock];
}
else
{
return 0;
}
return 0;
}
int CSessionMgr::ConnectSuccess(Safe_Smart_Ptr<Message> &message)
{
int successRet = 0;
GUARD_WRITE(CRWLock, obj, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_timeOutSe.find(message->GetChannelID());
if(it != m_timeOutSe.end())
{
if(message->GetMessageID() == C2SMessage)
{
if(message->GetLength() != 3)
{
LOG_BASE(FILEINFO, "client to server connection packet error");
return eConMessageErr;
}
short int id = 0;
unsigned char type = 0;
CUtil::SafeMemmove(&type, 1, message->GetContent(), 1);
CUtil::SafeMemmove(&id, 2, message->GetContent() + 1, 2);
if(message->GetRemoteType() <= 0)
id = ntohs(id);
if(type >= eMax)
{
LOG_BASE(FILEINFO, "client to server connection packet type error");
return eConMessageErr;
}
message->SetRemoteID(id);
message->SetRemoteType(type);
it->second->SetRemoteID(id);
it->second->SetRemoteType(type);
}
else if(message->GetMessageID() == S2CMessage)
{
if(message->GetLength() != 1)
{
LOG_BASE(FILEINFO, "server to client connection packet error");
return eConMessageErr;
}
unsigned char ret = 0;
CUtil::SafeMemmove(&ret, 1, message->GetContent(), 1);
if(ret != 0)
{
LOG_BASE(FILEINFO, "server to client connection packet return error");
return eConMessageErr;
}
int id = m_c->GetConnConfig(it->second->GetFlag() >> 16)->remote_id_;
int type = m_c->GetConnConfig(it->second->GetFlag() >> 16)->remote_type_;
message->SetRemoteID(id);
message->SetRemoteType(type);
it->second->SetRemoteID(id);
it->second->SetRemoteType(type);
}
else if(message->GetMessageID() == C2SGroupMessage)
{
if(message->GetLength() != 4)
{
LOG_BASE(FILEINFO, "client to server group message error");
return eConMessageErr;
}
short int id = 0;
unsigned char type = 0;
BYTE groupCount = 0;
int res = -1;
bool isSuccess = false;
CUtil::SafeMemmove(&type, 1, message->GetContent(), 1);
CUtil::SafeMemmove(&id, 2, message->GetContent() + 1, 2);
CUtil::SafeMemmove(&groupCount, 1, message->GetContent() + 3, 1);
if(type >= eMax)
{
LOG_BASE(FILEINFO, "client to server group message type error");
return eConMessageErr;
}
message->SetRemoteID(id);
message->SetRemoteType(type);
it->second->SetRemoteID(id);
it->second->SetRemoteType(type);
if((res = m_c->GetGroupSession()->AddGroupSession(type, id, message->GetChannelID(), groupCount, isSuccess)) < -1)
{
LOG_BASE(FILEINFO, "client to server group message and add group error");
return eConMessageErr;
}
if(!isSuccess)
{
successRet = eGroupContinue;
}
it->second->SetGroupID(res);
message->SetGroup(res);
}
else if(message->GetMessageID() == S2CGroupMessage)
{
if(message->GetLength() != 1)
{
LOG_BASE(FILEINFO, "server to client group message error");
return eConMessageErr;
}
unsigned char ret = 0;
int res = -1;
int type = 0;
int id = 0;
int groupCount = 0;
bool isSuccess = false;
CUtil::SafeMemmove(&ret, 1, message->GetContent(), 1);
if(ret != 0)
{
LOG_BASE(FILEINFO, "server to client group message return error");
return eConMessageErr;
}
type = m_c->GetConnConfig(it->second->GetFlag() >> 16)->remote_type_;
id = m_c->GetConnConfig(it->second->GetFlag() >> 16)->remote_id_;
groupCount = m_c->GetConnConfig(it->second->GetFlag() >> 16)->group_count;
message->SetRemoteID(id);
message->SetRemoteType(type);
it->second->SetRemoteID(id);
it->second->SetRemoteType(type);
if((res = m_c->GetGroupSession()->AddGroupSession(type, id, message->GetChannelID(), groupCount, isSuccess)) < 0)
{
LOG_BASE(FILEINFO, "server to client group message and add group error");
return eConMessageErr;
}
if(!isSuccess)
{
successRet = eGroupContinue;
}
it->second->SetGroupID(res);
message->SetGroup(res);
}
else
{
LOG_BASE(FILEINFO, "connection packet unknown messageid error");
return eConMessageErr;
}
Safe_Smart_Ptr<Session> se = it->second;
m_timeOutSe.erase(it);
obj.UnLock();
m_timeout.erase(message->GetChannelID());
GUARD_WRITE(CRWLock, objSe, &m_seLock);
m_session[se->GetSock()] = se;
objSe.UnLock();
if(se->GetRemoteType() != eClient)
{//非客户端的连接,把发送缓冲调大
se->ResetSendBuf();
}
if(message->GetMessageID() == C2SMessage)
{
Safe_Smart_Ptr<Message> messageret = NEW Message();
AcceptorConfig * config = m_c->GetAccConfig(se->GetFlag() >> 16);
messageret->SetSecurity(config->security_);
messageret->SetRemoteID(se->GetRemoteID());
messageret->SetRemoteType(se->GetRemoteType());
messageret->SetLocalType(config->local_type_);
messageret->SetChannelID(message->GetChannelID());
messageret->SetMessageID(S2CMessage);
messageret->SetMessageType(ConnMessage);
char con[8] = {0};
BYTE conRet = eNetSuccess;
CUtil::SafeMemmove(con, 8, &conRet, 1);
messageret->SetContent(con, 1);
if(Write(messageret))
{
LOG_BASE(FILEINFO, "server to client connection packet write buff error");
}
}
else if(message->GetMessageID() == C2SGroupMessage)
{
Safe_Smart_Ptr<Message> messageret = NEW Message();
AcceptorConfig * config = m_c->GetAccConfig(se->GetFlag() >> 16);
messageret->SetSecurity(config->security_);
messageret->SetRemoteID(se->GetRemoteID());
messageret->SetRemoteType(se->GetRemoteType());
messageret->SetLocalType(config->local_type_);
messageret->SetChannelID(message->GetChannelID());
messageret->SetMessageID(S2CGroupMessage);
messageret->SetMessageType(ConnMessage);
char con[8] = {0};
BYTE conRet = eNetSuccess;
CUtil::SafeMemmove(con, 8, &conRet, 1);
messageret->SetContent(con, 1);
if(Write(messageret))
{
LOG_BASE(FILEINFO, "server to client connection packet write buff error");
}
}
}
else
{
return eConnPacketErr;
}
return successRet;
}
unsigned char CSessionMgr::GetRemoteType(int fd)
{
if(fd < 0)
{
return 0;
}
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_session.find(fd);
if(it != m_session.end())
{
return it->second->GetRemoteType();
}
obj.UnLock();
GUARD_READ(CRWLock, objTime, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_timeOutSe.find(fd);
if(itTime != m_timeOutSe.end())
{
return itTime->second->GetRemoteType();
}
return 0;
}
Safe_Smart_Ptr<Inet_Addr> CSessionMgr::GetAddr(int fd)
{
if(fd < 0)
{
return 0;
}
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_session.find(fd);
if(it != m_session.end())
{
return it->second->GetAddr();
}
obj.UnLock();
GUARD_READ(CRWLock, objTime, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_timeOutSe.find(fd);
if(itTime != m_timeOutSe.end())
{
return itTime->second->GetAddr();
}
return 0;
}
short int CSessionMgr::GetRemoteID(int fd)
{
if(fd < 0)
{
return 0;
}
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_session.find(fd);
if(it != m_session.end())
{
return it->second->GetRemoteID();
}
obj.UnLock();
GUARD_READ(CRWLock, objTime, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_timeOutSe.find(fd);
if(itTime != m_timeOutSe.end())
{
return itTime->second->GetRemoteID();
}
return 0;
}
int CSessionMgr::Write(Safe_Smart_Ptr<Message> &message)
{
Safe_Smart_Ptr<Session> se;
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_session.find(message->GetChannelID());
if(it != m_session.end())
{
se = it->second;
}
obj.UnLock();
if(!se)
{
GUARD_READ(CRWLock, objTime, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_timeOutSe.find(message->GetChannelID());
if(itTime != m_timeOutSe.end())
{
se = itTime->second;
}
}
if((bool)se)
{
packetHeader head;
if(message->GetSecurity() != se->GetSecurity())
{
message->SetSecurity(se->GetSecurity());
}
message->EncryptMessage();
message->GetHead(&head);
if(se->Write(message->GetContent(), &head) == eCtlEpollErr)
{
m_c->GetEpollMgr()->DeleteChannelEx(message->GetChannelID(), eCtlEpollErr);
LOG_BASE(FILEINFO, "write message to session[%d] buff error", message->GetChannelID());
return eCtlEpollErr;
}
}
return eNetSuccess;
}
void CSessionMgr::DeleteAll()
{
m_session.clear();
m_timeOutSe.clear();
// {
// map<int, EpollEventPtr *>::iterator itPtr = m_epollPtr.begin();
// for(; itPtr != m_epollPtr.end(); ++itPtr)
// {
// delete itPtr->second;
// itPtr->second = 0;
// }
//
// m_epollPtr.clear();
// }
}
void CSessionMgr::Tick()
{
int64 nowTime = CUtil::GetNowMicrosecod();
vector<int> delChannel;
m_tick += nowTime - m_bTime;
m_bTime = nowTime;
if(m_tick >= 1000 * 1000)
{
m_tick -= 1000 * 1000;
map<int, int64>::iterator it = m_timeout.begin();
for(; it!=m_timeout.end(); )
{
if(nowTime >= (it->second * 1000))
{
delChannel.push_back(it->first);
m_timeout.erase(it++);
}
else
{
++it;
}
}
vector<int>::iterator itDel = delChannel.begin();
for(; itDel!=delChannel.end(); ++itDel)
{
DeleteSession(*itDel, eSessionTimeout);
LOG_BASE(FILEINFO, "session timeout delete session[%d]", *itDel);
}
}
}
void CSessionMgr::DeleteSessionEx(int fd, int err)
{
bool isDel = false;
#ifdef DEBUG
int64 beTime = CUtil::GetNowSecond();
#endif
{
GUARD_WRITE(CRWLock, objTime, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_timeOutSe.find(fd);
if(itTime != m_timeOutSe.end())
{
// m_c->SystemErr(fd, m_c->GetConfig()->local_id_, m_c->GetConfig()->local_type_,
// itTime->second->GetRemoteID(), itTime->second->GetRemoteType(), err, itTime->second->GetAddr()->GetIPToString(), itTime->second->GetAddr()->GetPort());
itTime->second->closeSocket();
isDel = true;
m_timeOutSe.erase(itTime);
objTime.UnLock();
m_timeout.erase(fd);
}
}
if(!isDel)
{
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_session.find(fd);
if(it != m_session.end())
{
m_c->SystemErr(fd, m_c->GetConfig()->local_id_, m_c->GetConfig()->local_type_,
it->second->GetRemoteID(), it->second->GetRemoteType(), err, it->second->GetAddr()->GetIPToString(), it->second->GetAddr()->GetPort());
}
}
#ifdef DEBUG
int64 endTime = CUtil::GetNowSecond();
if(endTime - beTime > 100)
{
LOG_BASE(FILEINFO,"1111111111111111111111 delete session[%d] time[%lld] too more11111111111111111", fd, endTime - beTime);
}
#endif
}
void CSessionMgr::DeleteSession(int fd, int err)
{
bool isDel = false;
#ifdef DEBUG
int64 beTime = CUtil::GetNowSecond();
#endif
{
GUARD_WRITE(CRWLock, objTime, &m_timeSeLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_timeOutSe.find(fd);
if(itTime != m_timeOutSe.end())
{
itTime->second->closeSocket();
isDel = true;
m_timeOutSe.erase(itTime);
objTime.UnLock();
m_timeout.erase(fd);
// printf("\n --------------- delete timeout socket[%d] -----------------\n", fd);
}
}
if(!isDel)
{
GUARD_WRITE(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator it = m_session.find(fd);
if(it != m_session.end())
{
if(it->second->GetGroupID() > 0)
m_c->GetGroupSession()->DeleteGroupSession(it->second->GetGroupID(), fd);
it->second->closeSocket();
m_session.erase(it);
// printf("\n --------------- delete socket[%d] -----------------\n", fd);
}
}
#ifdef DEBUG
int64 endTime = CUtil::GetNowSecond();
if(endTime - beTime > 100)
{
LOG_BASE(FILEINFO,"1111111111111111111111 delete session[%d] time[%lld] too more11111111111111111", fd, endTime - beTime);
}
#endif
}
void CSessionMgr::AddMessage(int channel, deque<Safe_Smart_Ptr<Message> > &messageDeque)
{
Safe_Smart_Ptr<Session> se;
{
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_session.find(channel);
if(itTime != m_session.end())
{
se = itTime->second;
}
else
{
return;
}
}
deque<Safe_Smart_Ptr<Message> >::iterator itDeque = messageDeque.begin();
for(; itDeque!=messageDeque.end(); ++itDeque)
{
// if((*itDeque)->GetMessageType() == Request)
// {
// if(0 != m_c->GetAckTimeout()->AddAckTimeOut(*itDeque))
// {
// continue;
// }
// }
packetHeader head;
if((*itDeque)->GetRemoteID() < 0)
{
(*itDeque)->SetRemoteID(se->GetRemoteID());
(*itDeque)->SetRemoteType(se->GetRemoteType());
}
if((*itDeque)->GetSecurity() != se->GetSecurity())
{
(*itDeque)->SetSecurity(se->GetSecurity());
}
(*itDeque)->EncryptMessage();
(*itDeque)->GetHead(&head);
if(se->Write((*itDeque)->GetContent(), &head) == eCtlEpollErr)
{
LOG_BASE(FILEINFO, "write message to session buff error");
}
}
}
void CSessionMgr::AddMessage(Safe_Smart_Ptr<Message> message)
{
Safe_Smart_Ptr<Session> se;
{
GUARD_READ(CRWLock, obj, &m_seLock);
map<int, Safe_Smart_Ptr<Session> >::iterator itTime = m_session.find(message->GetChannelID());
if(itTime != m_session.end())
{
se = itTime->second;
}
else
{
return;
}
}
packetHeader head;
if(message->GetRemoteID() < 0)
{
message->SetRemoteID(se->GetRemoteID());
message->SetRemoteType(se->GetRemoteType());
}
if(message->GetSecurity() != se->GetSecurity())
{
message->SetSecurity(se->GetSecurity());
}
message->EncryptMessage();
message->GetHead(&head);
if(se->Write(message->GetContent(), &head) == eCtlEpollErr)
{
LOG_BASE(FILEINFO, "write message to session buff error");
}
}
}
|
#pragma once
#include <Dot++/parser/ParserStateInterface.hpp>
#include <Dot++/Exceptions.hpp>
#include <Dot++/lexer/Token.hpp>
#include <Dot++/lexer/TokenType.hpp>
namespace dot_pp { namespace parser { namespace states {
template<class ConstructionPolicy>
class ReadAttributeNameState : public ParserStateInterface<ConstructionPolicy>
{
public:
ParserState consume(const TokenInfoHandle& handle, TokenStack&, TokenStack&, ConstructionPolicy&) override
{
const auto& token = handle->token();
if(token.type() == lexer::TokenType::equal)
{
return ParserState::ReadAttributeEqual;
}
throw dot_pp::SyntaxError("Unexpected token encountered, expected '=', found '" + token.to_string() + "'", *handle);
}
};
}}}
|
// Import required libraries
#include "ESP8266WiFi.h"
// WiFi parameters
const char* ssid = "dd-wrt";
const char* password = "";
int fullPin = 0;
int halfPin = 2;
const char* host = "192.168.1.125";
void setup() {
// Start Serial
Serial.begin(115200);
pinMode(fullPin, INPUT);
pinMode(halfPin, INPUT);
}
void loop() {
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
delay(16000);
return;
}
int FULL = digitalRead(fullPin);
delay(100);
int HALF = digitalRead(halfPin);
delay(100);
String STATUS;
Serial.println(String(FULL) + " FULL " + String(HALF) + " HALF");
if (FULL == 1 && HALF == 1) {
STATUS = "FULL";
} else if (FULL == 0 && HALF == 1) {
STATUS = "HALF";
} else if (FULL == 0 && HALF == 0) {
STATUS = "EMPTY";
}
Serial.println(STATUS);
client.print(String("GET /vanguard/index.php?status=") + STATUS + " HTTP/1.1\r\n" +
"Host: " + "127.0.0.1" + "\r\n" +
"Connection: close\r\n\r\n");
Serial.print(String("GET /vanguard/index.php?status=") + STATUS + " HTTP/1.1\r\n" +
"Host: " + "127.0.0.1" + "\r\n" +
"Connection: close\r\n\r\n");
delay(10);
// Read all the lines of the reply from server and print them to Serial
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
// ESP.deepSleep(5000000, WAKE_RF_DEFAULT);
delay(15000);
}
|
// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
//!@file
//! Functions working with plain C strings
#ifndef _Standard_CString_HeaderFile
#define _Standard_CString_HeaderFile
#include <Standard_Macro.hxx>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#if defined(_MSC_VER)
#if !defined(strcasecmp)
#define strcasecmp _stricmp
#endif
#if !defined(strncasecmp)
#define strncasecmp _strnicmp
#endif
#endif
// C++ only definitions
#ifdef __cplusplus
#include <Standard_Integer.hxx>
//! Returns bounded hash code for the null-terminated string, in the range [1, theUpperBound]
//! @param theString the null-terminated string which hash code is to be computed
//! @param theUpperBound the upper bound of the range a computing hash code must be within
//! @return a computed hash code, in the range [1, theUpperBound]
Standard_EXPORT Standard_Integer HashCode (Standard_CString theString, Standard_Integer theUpperBound);
//! Returns 32-bit hash code for the first theLen characters in the string theStr.
//! The result is unbound (may be not only positive, but also negative)
//! @param theString the string which hash code is to be computed
//! @param theLength the length of the given string
//! @return a computed hash code of the given string
Standard_EXPORT Standard_Integer HashCodes (Standard_CString theString, Standard_Integer theLength);
//! Returns bounded hash code for the first theLength characters in the string theString, in the range [1, theUpperBound]
//! @param theString the string which hash code is to be computed
//! @param theLength the length of the initial substring of the given string which hash code is to be computed
//! @param theUpperBound the upper bound of the range a computing hash code must be within
//! @return a computed hash code of the given string
inline Standard_Integer HashCode (const Standard_CString theString,
const Standard_Integer theLength,
const Standard_Integer theUpperBound)
{
// return (Abs( HashCodes( Value , Len ) ) % Upper ) + 1 ;
return HashCode (HashCodes (theString, theLength), theUpperBound);
}
//! Returns Standard_True if two strings are equal
inline Standard_Boolean IsEqual (const Standard_CString theOne, const Standard_CString theTwo)
{
return strcmp (theOne, theTwo) == 0;
}
#endif /* __cplusplus */
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
//! Equivalent of standard C function atof() that always uses C locale
Standard_EXPORT double Atof (const char* theStr);
//! Optimized equivalent of standard C function strtod() that always uses C locale
Standard_EXPORT double Strtod (const char* theStr, char** theNextPtr);
//! Equivalent of standard C function printf() that always uses C locale
Standard_EXPORT int Printf (const char* theFormat, ...);
//! Equivalent of standard C function fprintf() that always uses C locale
Standard_EXPORT int Fprintf (FILE* theFile, const char* theFormat, ...);
//! Equivalent of standard C function sprintf() that always uses C locale
Standard_EXPORT int Sprintf (char* theBuffer, const char* theFormat, ...);
//! Equivalent of standard C function vsprintf() that always uses C locale.
//! Note that this function does not check buffer bounds and should be used with precaution measures
//! (only with format fitting into the buffer of known size).
//! @param theBuffer [in] [out] string buffer to fill
//! @param theFormat [in] format to apply
//! @param theArgList [in] argument list for specified format
//! @return the total number of characters written, or a negative number on error
Standard_EXPORT int Vsprintf (char* theBuffer, const char* theFormat, va_list theArgList);
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif
|
//
// Created by Celeste Tan on 11/24/20.
//
#include "NextPiece.h"
/**this function sends a new block from the loaded queue to the top of the screen**/
Blocks NextPiece::giveNext() {
/**random length and height**/
l = rand()%5;
h = rand()%5;
/**new block to push later**/
Blocks nBlock(l, h);
/**starting coorindates**/
float xpos = rand()&920, ypos = 0;
/**takes the front block of the queue and pops it to the screen**/
item = q.front();
q.pop();
item.setPosition(xpos, ypos);
/**pushes a block to the prequeue**/
q.push(nBlock);
return item;
}
/**the next piece constructor allows 3 blocks to be prelaoded in queue**/
NextPiece::NextPiece() {
for(int i = 0; i < 3; i++) {
int l = rand() % 5;
int h = rand() % 5;
Blocks b(l, h);
q.push(b);//push a block to a prequeue
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.