blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f047894dd19c89e769dfe6bd5fb9369f2d4c03c7
|
3a9bd82f9696143cd15d79b304a89dfe0f553767
|
/sources/C_CPP/OLD/Arduino_WiFi_RS232_converter_REST_server/eclipseCWorkspace/Satelita1_RestServer/SkipBytesUntilSequenceSubTask.cpp
|
5768102e16f1e14c12d183c50aa161cc8dfa6081
|
[] |
no_license
|
kermitas/intellihome
|
70ed6eae659ede659889416df79b60557ddc7d62
|
23c9f3c3202101125f5648257518aa58f7ab455c
|
refs/heads/master
| 2021-01-23T13:36:01.563695
| 2012-06-27T13:10:01
| 2012-06-27T13:10:01
| 4,650,476
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,207
|
cpp
|
SkipBytesUntilSequenceSubTask.cpp
|
/*
* SkipBytesUntilSequenceSubTask.cpp
*
* Created on: 18-04-2012
* Author: root
*/
// =================================================
#include "SkipBytesUntilSequenceSubTask.h"
// =================================================
//const PROGMEM prog_char SkipBytesUntilSequenceSubTask::className[] = "SkipBytesUntilSequenceSubTask";
// =================================================
//SkipBytesUntilSequenceSubTask::SkipBytesUntilSequenceSubTask( Print& _p , RestServerSubTask* _errorSubTask , unsigned int _skippingMaxTime , unsigned int _skippingMaxBytesCount ) : p( _p )
SkipBytesUntilSequenceSubTask::SkipBytesUntilSequenceSubTask( RestServerSubTask* _errorSubTask ) : dp( PSTR( "SkipBytesUntilSequenceSubTask" ) )//: p( _p ) //, streamSkipBytes( _p )
{
errorSubTask = _errorSubTask;
//skippingMaxTime = _skippingMaxTime;
//skippingMaxBytesCount = _skippingMaxBytesCount;
}
// =================================================
void SkipBytesUntilSequenceSubTask::setStopSequenceAndNextSubTask( char* _stopSequence , bool _leaveLastByteInStream , RestServerSubTask* _nextSubTask )
{
//workUsingSkipBytesCount = false;
//stopSequence = _stopSequence;
//leaveLastByteInStream = _leaveLastByteInStream;
nextSubTask = _nextSubTask;
streamSkipBytes.resetInternalState( _stopSequence , _leaveLastByteInStream );
}
// =================================================
void SkipBytesUntilSequenceSubTask::setSkipBytesCountAndNextSubTask( unsigned int _skipBytesCount , RestServerSubTask* _nextSubTask )
{
//workUsingSkipBytesCount = true;
//skipBytesCount = _skipBytesCount;
nextSubTask = _nextSubTask;
streamSkipBytes.resetInternalState( _skipBytesCount );
}
// =================================================
char* SkipBytesUntilSequenceSubTask::getSubTaskName()
{
return "SkipBytesUntilSequence-sub-task";
}
// =================================================
void SkipBytesUntilSequenceSubTask::resetInternalState()
{
//alreadySkippedBytesCount = 0;
//alreadyMatchedBytesCount = 0;
//startTime = millis();
}
// =================================================
RestServerSubTask* SkipBytesUntilSequenceSubTask::executeSubTask( Stream* stream )
{
static const PROGMEM prog_char functionName[] = "executeSubTask";
//static const char* prefix = "SkipBytesUntilSequenceSubTask:executeSubTask():";
int streamReadingResult = 0;
streamSkipBytes.setStream( stream );
while( ( streamReadingResult = streamSkipBytes.read() ) == 0 ){}
if( streamReadingResult == -1 )
{
return NULL;
}
else
if( streamReadingResult == 1 )
{
return nextSubTask;
}
else
{
return errorSubTask;
}
/*
if( workUsingSkipBytesCount )
{
while( alreadySkippedBytesCount < skipBytesCount )
{
if( millis() - startTime >= skippingMaxTime ) return errorSubTask;
if( stream->available() == 0 ) return NULL;
int readByte = stream->read();
if( readByte == -1 ) return NULL;
alreadySkippedBytesCount++;
}
return nextSubTask;
}
else
{
while( alreadySkippedBytesCount < skippingMaxBytesCount )
{
if( millis() - startTime >= skippingMaxTime ) return errorSubTask;
if( stream->available() == 0 ) return NULL;
int peekByte = stream->peek();
//info( p << prefix << "skipping peekByte " << (char)peekByte << endl; )
//info( p << (char)peekByte; )
if( peekByte == -1 ) return NULL;
if( stopSequence[alreadyMatchedBytesCount] == peekByte )
{
alreadyMatchedBytesCount++;
if( stopSequence[alreadyMatchedBytesCount] == 0 )
{
if( !leaveLastByteInStream )
{
stream->read();
//int readByte = stream->read();
//info( p << prefix << "skipping readByte (the last one) " << (char)readByte << endl; )
}
else
{
//info( p << prefix << "leaving peekByte (the last one) " << (char)peekByte << " in stream and exit" << endl; )
}
return nextSubTask;
}
}
else
alreadyMatchedBytesCount = 0;
stream->read();
//int readByte = stream->read();
//info( p << prefix << "skipping readByte " << (char)readByte << endl; )
alreadySkippedBytesCount++;
}
return errorSubTask;
}*/
}
// =================================================
|
fc40ca7ffaac9e61ce78489c86488d105a48d6b5
|
785f542387f302225a8a95af820eaccb50d39467
|
/codeforces/615-B/615-B-15248980.cpp
|
d7b733cddd27bc21e5cb31614ad07801bc6cea71
|
[] |
no_license
|
anveshi/Competitive-Programming
|
ce33b3f0356beda80b50fee48b0c7b0f42c44b0c
|
9a719ea3a631320dfa84c60300f45e370694b378
|
refs/heads/master
| 2016-08-12T04:27:13.078738
| 2015-01-19T17:30:00
| 2016-03-08T17:44:36
| 51,570,689
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,320
|
cpp
|
615-B-15248980.cpp
|
// Anve$hi $hukla
// Until the lion learns how to write, every story will glorify the hunter.
#include <bits/stdc++.h>
using namespace std;
#define TRACE
#ifdef TRACE
#define trace1(x) cerr<< #x <<": "<<x<<endl;
#define trace2(x, y) cerr<< #x <<": "<<x<<" | "<< #y <<": "<<y<< endl;
#define trace3(x, y, z) cerr<< #x <<": "<<x<<" | "<< #y <<": "<<y<<" | "<< #z <<": "<<z<< endl;
#else
#define trace1(x)
#define trace2(x, y)
#define trace3(x, y, z)
#endif
typedef long long LL;
inline void fastIO(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
}
const LL Maxn = 200005;
vector <LL> edge[Maxn];
LL In[Maxn], Dp[Maxn];
int main(){
fastIO();
LL n,M,x,y;
cin >> n >> M;
for(LL i=0;i<M;i++){
cin >> x >> y;
edge[x].push_back(y);
edge[y].push_back(x);
In[x]++;
In[y]++;
}
for(LL i=0;i<=n;i++){
sort(edge[i].begin(), edge[i].end());
}
Dp[1] = (In[1]>0?1:0);
for(LL i=2;i<=n;i++){
Dp[i] = (In[i]>0?1:0);
for(LL j=0;j<edge[i].size();j++){
if(edge[i][j]>i)
break;
else{
Dp[i] = max(Dp[i], 1+Dp[edge[i][j]]);
}
}
}
LL Ans = 0LL;
for(LL i=1;i<=n;i++){
LL temp = Dp[i] * In[i];
Ans = max(Ans, temp);
}
cout << Ans << endl;
return 0;
}
|
216760569e10b44e8d1035575faa2607ab77089f
|
14095d94663868d9b3a99ed9426f1d89f50c0c46
|
/src/flash_loader.cpp
|
c6361ed4570c9355d619e7326c98c3b577d24cae
|
[] |
no_license
|
iq-motion-control/iq-flasher
|
06901e00525989f6aaefd9a67c0e149f9e7f7d5c
|
36c0061a1a4e40b72fd84cc8c1b84991b8cd76f7
|
refs/heads/master
| 2023-06-25T11:19:22.975734
| 2023-06-14T17:52:22
| 2023-06-14T17:52:22
| 371,368,191
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,241
|
cpp
|
flash_loader.cpp
|
#include "schmi/include/Schmi/flash_loader.hpp"
#include <QDebug>
namespace Schmi {
void FlashLoader::Init() {
ser_->Init();
bin_->Init();
total_num_bytes_ = bin_->GetBinaryFileSize();
return;
}
bool FlashLoader::InitUsart() { return stm32_->InitUsart(); }
uint16_t FlashLoader::CalculatePageOffset(uint16_t memoryLocation){
return ceil((memoryLocation - START_ADDRESS_) / PAGE_SIZE_);
}
bool FlashLoader::Flash(bool init_usart, bool global_erase, uint32_t starting_flash) {
if (init_usart) {
if (!stm32_->InitUsart()) {
return 0;
}
}
if (global_erase) {
if (!stm32_->SpecialExtendedErase(0xFFFF)) {
return 0;
}
} else {
uint16_t page_offset = CalculatePageOffset(starting_flash);
uint16_t num_of_pages = GetPagesCodesFromBinary(page_offset);
//Let the page codes handle the offset in the erase
if (!stm32_->ExtendedErase(pages_codes_buffer, num_of_pages)) {
return 0;
}
}
if (!FlashBytes(starting_flash)) {
return 0;
}
if (!CheckMemory(starting_flash)) {
return 0;
}
if (!stm32_->GoToAddress(START_ADDRESS_)) {
return 0;
}
return 1;
}
uint16_t FlashLoader::GetPagesCodesFromBinary(uint16_t page_offset) {
float binary_file_size = bin_->GetBinaryFileSize();
uint16_t num_of_pages = ceil(binary_file_size / PAGE_SIZE_);
if (num_of_pages > MAX_NUM_PAGES_TO_ERASE) {
Schmi::Error err_message = {"GetPagesCodesFromBinary", ("num pages > 512"), num_of_pages};
err_->Init(err_message);
err_->DisplayAndDie();
return 0;
}
for (int ii = 0; ii < num_of_pages; ++ii) {
pages_codes_buffer[ii] = ii + page_offset;
}
return num_of_pages;
}
bool FlashLoader::FlashBytes(uint32_t curAddress) {
BinaryBytesData flash_data = {0, curAddress, total_num_bytes_};
bar_->StartLoadingBar(total_num_bytes_);
while (flash_data.bytes_left) {
uint32_t num_bytes = CheckNumBytesToWrite(flash_data.bytes_left);
uint8_t binary_buffer[MAX_WRITE_SIZE];
bin_->GetBytesArray(binary_buffer, {num_bytes, flash_data.current_byte_pos});
if (!stm32_->WriteMemory(binary_buffer, num_bytes, flash_data.current_memory_address)) {
return 0;
}
UpdateBinaryBytesData(flash_data, num_bytes);
bar_->UpdateLoadingBar(flash_data.bytes_left);
}
bar_->EndLoadingBar();
return 1;
}
bool FlashLoader::CheckMemory(uint32_t curAddress) {
BinaryBytesData memory_data = {0, curAddress, total_num_bytes_};
bar_->StartCheckingLoadingBar(total_num_bytes_);
while (memory_data.bytes_left) {
uint16_t num_bytes = CheckNumBytesToWrite(memory_data.bytes_left);
uint8_t binary_buffer[MAX_WRITE_SIZE];
bin_->GetBytesArray(binary_buffer, {num_bytes, memory_data.current_byte_pos});
uint8_t memory_buffer[MAX_WRITE_SIZE];
if (!stm32_->ReadMemory(memory_buffer, num_bytes, memory_data.current_memory_address)) {
return 0;
}
if (!CompareBinaryAndMemory(memory_buffer, binary_buffer, num_bytes)) {
return 0;
}
UpdateBinaryBytesData(memory_data, num_bytes);
bar_->UpdateLoadingBar(memory_data.bytes_left);
}
bar_->EndLoadingBar();
return 1;
}
bool FlashLoader::CompareBinaryAndMemory(uint8_t* memory_buffer, uint8_t* binary_buffer,
const uint16_t& num_bytes) {
uint8_t mem, buf;
for (int ii = 0; ii < num_bytes; ii++) {
mem = memory_buffer[ii];
buf = binary_buffer[ii];
if (mem != buf) {
Schmi::Error err = {"CheckBytes", "Bytes do not match", ii};
err_->Init(err);
err_->DisplayAndDie();
return 0;
}
}
return 1;
}
uint16_t FlashLoader::CheckNumBytesToWrite(const uint32_t& bytes_left) {
uint16_t num_bytes_to_write = 0;
if (bytes_left < MAX_WRITE_SIZE) {
num_bytes_to_write = bytes_left;
} else {
num_bytes_to_write = MAX_WRITE_SIZE;
}
return num_bytes_to_write;
}
void FlashLoader::UpdateBinaryBytesData(BinaryBytesData& binary_bytes_data,
const uint16_t& num_bytes) {
binary_bytes_data.current_byte_pos += num_bytes;
binary_bytes_data.current_memory_address += num_bytes;
binary_bytes_data.bytes_left -= num_bytes;
return;
}
} // namespace Schmi
|
51f1a627154937e2289b184bcf9db66f7fd778b0
|
73ceef53044657b0500e5bea07c8084d28bffbbe
|
/inc/board.h
|
f7e1522ba9ed26f94821efb3dcb1b694254932c1
|
[] |
no_license
|
rikanov/Planets
|
ce8fa23a19e1ce634fa62267889a42b947559a04
|
f1031ee3e089214a77775614e19804745212c573
|
refs/heads/master
| 2022-12-01T13:33:43.284138
| 2022-11-14T05:38:08
| 2022-11-14T05:38:08
| 203,871,799
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,130
|
h
|
board.h
|
#ifndef BOARD_H
#define BOARD_H
#include "generator.h"
#include "sstack.h"
class Board: public StepStack
{
protected:
const Node* _WINNER_SPOT;
private:
// Board grid [rows+2][columns+2]
Node ** __theGrid;
Collection * _collectionOfPlayer;
Collection * _collectionOfProgram;
Collection * _currentOpponent;
Node * _centerNodes[8];
Node * _treatingNodes[8][5];
const int _rows;
const int _cols;
void initCache();
public:
const Collection * getProgramCollection() const;
const Collection * getPlayerCollection() const;
const Collection * getCurrentCollection() const;
public:
Board ( const int& size = 5 );
virtual ~Board();
void reset();
void show() const;
bool isPlayerTurn() const;
bool getStep ( uint8_t, Step& ) const;
bool getStep ( uint8_t, uint8_t, Step& ) const;
bool getStep ( uint8_t, uint8_t, uint8_t, uint8_t, Step& ) const;
bool getStep ( uint8_t, uint8_t, uint8_t, Step& ) const;
Node * isWinnerStep() ;
bool isWinnerStep ( const Step& );
void swapPlayers();
bool isFinished() const;
};
#endif // BOARD_H
|
0e02b62734541310f04e77ab6e39159e3b470ba2
|
428cd933e5eb520232119720480f1f00cd0f99f0
|
/fingertracking.cpp
|
bb4c5eeeffa106174da24cbb375142f211d9218f
|
[] |
no_license
|
AadarshKumayan/finger-tracking-using-openCV
|
2be28965e96f210a7808248d1961630fc6cdbf83
|
655e2c38d6ace8848d484204a2bdec0b7223f3df
|
refs/heads/master
| 2021-01-25T08:06:56.031125
| 2017-06-09T04:44:34
| 2017-06-09T04:44:34
| 93,713,283
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,263
|
cpp
|
fingertracking.cpp
|
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
#include <math.H>
using namespace std;
using namespace cv;
#define pivalue 3.14159265358;
Mat img, img1, erosion_dst, dilation_dst, sampleOut;
VideoCapture wc(0);
int erosion_elem = 0;
int erosion_size = 0;
int dilation_elem = 0;
int dilation_size = 0;
void contournconvexhull()
{
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
int count = 0, ck = 0;
findContours(img1, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));
size_t largestContour = 0;
for (size_t i = 1; i < contours.size(); i++)
{
if (contourArea(contours[i]) > contourArea(contours[largestContour]))
largestContour = i;
}
drawContours(img, contours, largestContour, Scalar(0, 0, 255), 1);
if (!contours.empty())
{
vector<vector<Point> > hull(1);
convexHull(Mat(contours[largestContour]), hull[0], false);
drawContours(img, hull, 0, Scalar(0, 255, 0), 3);
if (hull[0].size() > 2)
{
vector<int> hullIndexes;
convexHull(Mat(contours[largestContour]), hullIndexes, true);
vector<Vec4i> cd;
convexityDefects(Mat(contours[largestContour]), hullIndexes, cd);
for (size_t i = 0; i < cd.size(); i++)
{
Point p1 = contours[largestContour][cd[i][0]]; //start
Point p2 = contours[largestContour][cd[i][1]]; //end
Point p3 = contours[largestContour][cd[i][2]]; //far
float a, b, c, b2, a2, c2, d;
a = sqrt(pow((p2.x - p1.x), 2) + pow((p2.y - p1.y), 2));
b = sqrt(pow((p3.x - p1.x), 2) + pow((p3.y - p1.y), 2));
c = sqrt(pow((p2.x - p3.x), 2) + pow((p2.y - p3.y), 2));
a2 = a*a;
b2 = b*b;
c2 = c*c;
d = 2 * b*c;
float angle = acos(((b2 + c2 - a2) / d));
float f1, f2;
f1 = pivalue;
f2 = pivalue;
f1 /= 2;
f2 = (f2 * 4) / 180;
if (angle <= f1 && angle > f2)
{
if (ck == 0)
{
ck++;
count = 1;
}
count += 1;
line(img, p1, p3, Scalar(255, 0, 0), 2);
line(img, p3, p2, Scalar(255, 0, 0), 2);
}
}
}
cout << count << endl;
}
imshow("hull", img);
}
void Erosion(int, void*)
{
int erosion_type;
if (erosion_elem == 0) { erosion_type = MORPH_RECT; }
else if (erosion_elem == 1) { erosion_type = MORPH_CROSS; }
else if (erosion_elem == 2) { erosion_type = MORPH_ELLIPSE; }
Mat element = getStructuringElement(erosion_type,
Size(2 * erosion_size + 1, 2 * erosion_size + 1),
Point(erosion_size, erosion_size));
erode(img1, img1, element);
}
void Dilation(int, void*)
{
int dilation_type;
if (dilation_elem == 0) { dilation_type = MORPH_RECT; }
else if (dilation_elem == 1) { dilation_type = MORPH_CROSS; }
else if (dilation_elem == 2) { dilation_type = MORPH_ELLIPSE; }
Mat element = getStructuringElement(dilation_type,
Size(2 * dilation_size + 1, 2 * dilation_size + 1),
Point(dilation_size, dilation_size));
dilate(img1, img1, element);
}
void skincolor()
{
int minH, maxH, minS, maxS, minV, maxV;
minH = 0;
maxH = 20;
minS = 30;
maxS = 150;
minV = 60;
maxV = 255;
cvtColor(img, img1, CV_BGR2HSV);
inRange(img1, Scalar(minH, minS, minV), Scalar(maxH, maxS, maxV), img1);
namedWindow("Skin Color image", CV_WINDOW_NORMAL);
imshow("Skin Color image", img1);
int blurSize = 5;
int elementSize = 5;
medianBlur(img1, img1, blurSize);
Dilation(0, 0);
Erosion(0, 0);
namedWindow("Original image", CV_WINDOW_NORMAL);
imshow("Original image", img);
namedWindow("After noise reduction", CV_WINDOW_NORMAL);
imshow("After noise reduction", img1);
contournconvexhull();
}
int main()
{
int choice;
char ekey = 0;
cout << "Choose your option";
cout << "1) Import image";
cout << "2)Live feed";
cin >> choice;
switch (choice)
{
case 1:
img = imread("yo.jpg");
skincolor();
while (ekey != 27)
{
ekey = waitKey(1);
}
break;
case 2:
if (wc.isOpened() == false)
{
cout << "Web Cam Not working";
return -1;
}
char ekey = 0;
while (ekey != 27 && wc.isOpened())
{
bool frame = wc.read(img);
if (!frame || img.empty())
{
cout << "frame not read from webcam\n";
break;
}
skincolor();
ekey = waitKey(1);
}
break;
}
return 0;
}
|
82d801c76e5644562097840223714d062eb1952b
|
b1545362a4bba38a14dcc2bf7cd06d369f9e4ae7
|
/4369/source/OJ.cpp
|
0a6cbcc1a83e55d25e2296e18608496b740079ae
|
[] |
no_license
|
guojun12002/Huaweitest
|
11fe1369e5808a3f981ade8f6bd485b35755c7e2
|
685c6ba0b7997bee97a1ed0065e2e0f80f5581db
|
refs/heads/master
| 2021-03-22T03:10:00.347847
| 2015-05-12T05:43:13
| 2015-05-12T05:43:13
| 35,462,145
| 1
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 514
|
cpp
|
OJ.cpp
|
#include <stdlib.h>
#include <cmath>
#include "oj.h"
// 功能:判断输入 nValue 是否为水仙花数
// 输入: nValue为正整数
// 输出:无
// 返回:如果输入为水仙花数,返回1,否则返回0
unsigned int IsDaffodilNum(unsigned int nValue)
{
int str[100];
int n = 0;
unsigned int num = nValue;
while(num > 0)
{
str[n++] = num % 10;
num = num / 10;
}
unsigned int sum = 0;
for(int i=0; i<n; ++i)
sum += pow(str[i]*1.0, n*1.0);
if(sum == nValue) return 1;
return 0;
}
|
610e3568ebee18f30dcb7cbbfe8c63fc950441aa
|
ef0de18bbc1d411b9af4feb410e0d1e8d4d3af0b
|
/MgmtConsole/main.h
|
8e0b3daa0017db736cb2edd97cc52c41a171c95a
|
[] |
no_license
|
tengyifei/SoundAuth
|
fe0afac9667cc0631805f536bf72c90a6b4cb623
|
8f0caf3443db9a6fed71ee9d6dc4c577e3939013
|
refs/heads/master
| 2021-01-19T00:24:49.084763
| 2014-01-30T08:52:34
| 2014-01-30T08:52:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,894
|
h
|
main.h
|
//---------------------------------------------------------------------------
#ifndef mainH
#define mainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ComCtrls.hpp>
#include <Mask.hpp>
#include <ExtCtrls.hpp>
#include <IdBaseComponent.hpp>
#include <IdSASL.hpp>
#include <IdSASL_CRAM_SHA1.hpp>
#include <IdSASL_CRAMBase.hpp>
#include <IdSASLUserPass.hpp>
#include <IdAntiFreeze.hpp>
#include <IdAntiFreezeBase.hpp>
#include <ButtonGroup.hpp>
#include <ActnList.hpp>
#include <CategoryButtons.hpp>
#include <ActnPopup.hpp>
#include <Menus.hpp>
#include <PlatformDefaultStyleActnCtrls.hpp>
//---------------------------------------------------------------------------
class TmainForm : public TForm
{
__published: // IDE-managed Components
TGroupBox *GroupBox1;
TGroupBox *GroupBox2;
TListView *ListView1;
TLabel *Label1;
TLabel *Label2;
TComboBox *ComboBox1;
TEdit *Edit1;
TButton *Button1;
TButton *Button2;
TButton *Button3;
TButton *Button4;
TMemo *Memo1;
TButton *Button5;
TProgressBar *ProgressBar1;
TTimer *Timer2;
TLabel *Label3;
TLabel *Label4;
TButton *Button6;
TButton *Button7;
TTimer *oneTimeTimer;
TButton *Button8;
TButton *Button9;
TTimer *oneTimeTimer2;
TActionList *ActionList1;
TPopupActionBar *PABar1;
TMenuItem *A1;
TMenuItem *AsConsole1;
TAction *Action1;
TAction *Action2;
TAction *Action3;
void __fastcall FormCreate(TObject *Sender);
void __fastcall Button5Click(TObject *Sender);
void __fastcall Timer2Timer(TObject *Sender);
void __fastcall Button6Click(TObject *Sender);
void __fastcall Button7Click(TObject *Sender);
void __fastcall Button9Click(TObject *Sender);
void __fastcall Button1Click(TObject *Sender);
void __fastcall oneTimeTimer2Timer(TObject *Sender);
void __fastcall Button2Click(TObject *Sender);
void __fastcall Button4MouseDown(TObject *Sender, TMouseButton Button, TShiftState Shift,
int X, int Y);
void __fastcall A1Click(TObject *Sender);
void __fastcall AsConsole1Click(TObject *Sender);
void __fastcall Button3Click(TObject *Sender);
private: // User declarations
public: // User declarations
__fastcall TmainForm(TComponent* Owner);
};
//---------------------------------------------------------------------------
#define SEND_DATA 0x13323444
#define DO_NOTHING 0xF9C1F9C1
//---------------------------------------------------------------------------
/* Communication Protocol
Process:
1. PIC receives a 'w' character from PC
2. PIC sends dummy response
3. Both enters communication cycle, sending and reading dummy response from each other non-stop
4. PIC acts passively
5. If PC wants to send command, it sends CPU_SEND_DATA instead of CPU_SEND_DUMMY,
followed by a 32-bit UINT representing length of data, and then data
6. PIC processes the information, and send the response data through PIC_SEND_DATA,
followed by a 32-bit UINT representing length of data, and then response data
*/
#define PIC_SEND_DATA 0xDA1A1011
#define PIC_SEND_DUMMY 0xB1B1CAFE
#define CPU_SEND_DATA 0x672BF915
#define CPU_SEND_DUMMY 0xD2D2CAFE
#define PIC_EXIT 0x11FF11FF
#define CPU_EXIT 0x39273FFF
//start command of data (pure message does not start with 0xFF)
#define CPU_DOWNLOAD 0xFF583B99
#define CPU_INSERT 0xFF912E55
#define CPU_DELETE 0xFF348D12
#define CPU_EDIT 0xFF7142BF
#define PIC_DOWNLOAD 0xFF71D1AA
#define PIC_DOWNLOAD_FIN 0xFFC1C2C3
/* Communication Protocol */
/* Data Storage
1st sector on SD card: database information
2-nth sector: user database
4 users per sector
Name(64bytes)+Data(8bytes)+Counter(4bytes)+Identification Info(4bytes)+deleted?(4bytes)
*/
typedef struct DBHeaderTag{
UINT32 dbmagic; //should always be 0x7968574D, used in checking for validity
char pwhash[32]; //sha-1 hash of db password. size is not 20 but 32 for alignment
UINT32 num_user;
UINT32 num_user_deleted;
UINT32 reserved1;
UINT32 reserved2;
UINT32 dbtailmagic; //should always be 0xE59B230C, used in checking for validity
}DBHeader, *PDBHeader;
typedef struct DBDataTag{
char name[64];
char message[8];
char counter[4];
UINT32 idinfo;
UINT32 isdeleted; //0=>deleted, 1=>present
}DBData, *PDBDATA;
/*Data Storage*/
extern PACKAGE TmainForm *mainForm;
extern HANDLE commHandle;
extern DWORD dwWrite;
extern DWORD dwRead;
extern char message[8192];
extern long current_command;
extern unsigned long current_size;
extern long cyclecnt;
extern DCB dcb;
extern LPOVERLAPPED theOverlapped;
extern bool downloaded;
extern bool downloading;
extern DBData dbdatastr;
extern bool shoulddie;
bool WriteFileAsn(HANDLE commHandle, void* data, long num, DWORD* reserved, void* reserved2, volatile bool* shoulddie=NULL);
bool ReadFileAsn(HANDLE commHandle, void* data, long num, DWORD* reserved, void* reserved2, volatile bool* shoulddie=NULL);
#endif
|
997990a08710b4ed5e6a21c5e8cc5cba8d0e1936
|
d4b2c93b199aa0713b4e47bd4166edbe62fa94f2
|
/cpp/libs/src/opendnp3/master/PollTaskBase.cpp
|
c5b5508f95afd05ce4fb5a1b8b5e3f31632e7f5b
|
[
"Apache-2.0"
] |
permissive
|
philwil/opendnp3
|
2502a29c9eab64c9007a1c5a50f4e4009b038edc
|
932bcde73b8c615a386818fbcc7cfad8dbb6e1b9
|
refs/heads/release-2.x
| 2022-06-11T09:26:59.127577
| 2020-05-01T15:47:52
| 2020-05-01T15:47:52
| 260,477,443
| 0
| 0
|
Apache-2.0
| 2020-05-01T15:47:53
| 2020-05-01T14:22:25
|
C++
|
UTF-8
|
C++
| false
| false
| 2,818
|
cpp
|
PollTaskBase.cpp
|
/*
* Copyright 2013-2019 Automatak, LLC
*
* Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak
* LLC (www.automatak.com) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. Green Energy Corp and Automatak LLC license
* this file to you under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may obtain
* a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "PollTaskBase.h"
#include <openpal/logging/LogMacros.h>
#include "opendnp3/LogLevels.h"
#include "opendnp3/master/MeasurementHandler.h"
using namespace openpal;
namespace opendnp3
{
PollTaskBase::PollTaskBase(const std::shared_ptr<TaskContext>& context,
IMasterApplication& application,
ISOEHandler& handler,
const TaskBehavior& behavior,
const openpal::Logger& logger,
TaskConfig config)
: IMasterTask(context, application, behavior, logger, config), handler(&handler)
{
}
void PollTaskBase::Initialize()
{
this->rxCount = 0;
}
IMasterTask::ResponseResult PollTaskBase::ProcessResponse(const APDUResponseHeader& header,
const openpal::RSlice& objects)
{
if (header.control.FIR)
{
if (this->rxCount > 0)
{
SIMPLE_LOG_BLOCK(logger, flags::WARN, "Ignoring unexpected FIR frame");
return ResponseResult::ERROR_BAD_RESPONSE;
}
return ProcessMeasurements(header, objects);
}
else
{
if (this->rxCount > 0)
{
return ProcessMeasurements(header, objects);
}
SIMPLE_LOG_BLOCK(logger, flags::WARN, "Ignoring unexpected non-FIR frame");
return ResponseResult::ERROR_BAD_RESPONSE;
}
}
IMasterTask::ResponseResult PollTaskBase::ProcessMeasurements(const APDUResponseHeader& header,
const openpal::RSlice& objects)
{
++rxCount;
if (MeasurementHandler::ProcessMeasurements(objects, logger, handler) == ParseResult::OK)
{
return header.control.FIN ? ResponseResult::OK_FINAL : ResponseResult::OK_CONTINUE;
}
return ResponseResult::ERROR_BAD_RESPONSE;
}
} // namespace opendnp3
|
b7d3e18c57927f277e4651b6fe5531f35ca47d85
|
d22c5bf9fa57d3ee419609cb14983dde75dff3fd
|
/code_for_rc522/curlpostrequest.cpp
|
6b68f00ff192f14cfd2684970fa5094ebfae947f
|
[] |
no_license
|
FelixTheC/timeclock
|
61bb433554943ca2af18993728760dd8ab1b6b49
|
6797ac0326c2640a073feaeba3edc1c200ac4a83
|
refs/heads/main
| 2023-06-22T03:16:50.776681
| 2021-07-22T14:19:29
| 2021-07-22T14:19:29
| 385,981,835
| 0
| 0
| null | 2021-07-22T14:19:30
| 2021-07-14T15:08:32
|
Python
|
UTF-8
|
C++
| false
| false
| 1,429
|
cpp
|
curlpostrequest.cpp
|
#include "curlpostrequest.h"
CurlPostRequest::CurlPostRequest()
{
}
CurlPostRequest::CurlPostRequest(const string new_base_url)
{
base_url = new_base_url;
}
CurlPostRequest::~CurlPostRequest()
{
curl_easy_cleanup(easyhandle);
easyhandle = nullptr;
}
void
CurlPostRequest::perform_post(const string path)
{
const string tornado_url = base_url + path; //"http://localhost:8888/add/" + card_uid;
// const string json_data = "{\"user_id\": " + card_uid + ",\"username\": \"Some Name\"}";
// cout << "Sending Post request..." << endl;
// CURL *easyhandle = curl_easy_init();
// CURLcode response;
if (easyhandle != nullptr)
{
curl_easy_setopt(easyhandle, CURLOPT_TIMEOUT, 1);
curl_easy_setopt(easyhandle, CURLOPT_URL, tornado_url.c_str());
curl_easy_setopt(easyhandle, CURLOPT_POST, 1);
curl_easy_setopt(easyhandle, CURLOPT_READFUNCTION, read_function);
curl_easy_setopt(easyhandle, CURLOPT_READDATA, nullptr);
response = curl_easy_perform(easyhandle);
if (response != CURLE_OK)
{
cout << "curl_easy_perform(easyhandle) failed: " << curl_easy_strerror(response) << endl;
} else
{
cout << "Reached next point" << endl;
}
}
}
size_t
CurlPostRequest::read_function(char *bufptr, size_t size, size_t nmemb, void *ourpointer)
{
return 1;
}
|
ba9481a3123102eb119337f8301b3f0e49db7eee
|
428ca720a37fc238340de46304bcb14c48e62bce
|
/Project/Peter-Huynh_CSCI4239_Final-Project/Source/PTHopengl.cpp
|
c62f70df6228a8452e40ff9408092176c7a5d7ae
|
[] |
no_license
|
PeterTranHuynh/CSCI4239_Spring2017
|
12be53624811d5565c60bb311ea50a7d7979bcb2
|
26f651915c1d98073201869421e0e4ed760279e7
|
refs/heads/master
| 2021-07-06T09:21:33.246178
| 2017-10-02T18:12:21
| 2017-10-02T18:17:59
| 105,567,510
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,504
|
cpp
|
PTHopengl.cpp
|
/* ******************************
* Name: Peter Tran Huynh
* Title: PTH - Final Project
* Course: CSCI 4239
* Semester: Spring 2017
* File Notes:
* OpenGL Widget
***************************** */
#include "Headers/PTHopengl.h"
#include <QtOpenGL>
#include <QMessageBox>
#include <QGLFunctions>
#include <QStringList>
#include "Headers/Cube.h"
#include "Headers/WaveOBJ.h"
#include "Headers/Teapot.h"
#include "Headers/Sphere.h"
#include "Headers/Noise.h"
#include <math.h>
#include <iostream>
#define Cos(th) cos(3.1415926/180*(th))
#define Sin(th) sin(3.1415926/180*(th))
// Set up array indexes for program
const int VELOCITY_ARRAY=4;
const int START_ARRAY=5;
const char* Name = ",,,,Vel,Start";
/*
* Random numbers with range and offset
*/
static float frand(float rng,float off)
{
return rand()*rng/RAND_MAX+off;
}
/*
* Initialize particles
*/
void PTHopengl::InitPart(void)
{
// Array Pointers
float* vert = Vert;
float* color = Color;
float* vel = Vel;
float* start = Start;
// Loop over NxN patch
n = mode ? 15 : N;
for (int i=0;i<n;i++)
for (int j=0;j<n;j++)
{
// Location x,y,z
*vert++ = (i+0.5)/n-0.75;
*vert++ = 0;
*vert++ = (j+0.5)/n-0.75;
// Color r,g,b (0.5-1.0)
*color++ = frand(0.5,0.5);
*color++ = frand(0.5,0.5);
*color++ = frand(0.5,0.5);
// Velocity
*vel++ = frand( 1.0,3.0);
*vel++ = frand(10.0,0.0);
*vel++ = frand( 1.0,3.0);
// Launch time
*start++ = frand(2.0,0.0);
}
}
/*
* Draw particles
*/
void PTHopengl::DrawPart(void)
{
QGLFunctions glf(QGLContext::currentContext());
// Set particle size
glPointSize(mode?50:5);
// Point vertex location to local array Vert
glVertexPointer(3,GL_FLOAT,0,Vert);
// Point color array to local array Color
glColorPointer(3,GL_FLOAT,0,Color);
// Point attribute arrays to local arrays
glf.glVertexAttribPointer(VELOCITY_ARRAY,3,GL_FLOAT,GL_FALSE,0,Vel);
glf.glVertexAttribPointer(START_ARRAY,1,GL_FLOAT,GL_FALSE,0,Start);
// Enable arrays used by DrawArrays
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glf.glEnableVertexAttribArray(VELOCITY_ARRAY);
glf.glEnableVertexAttribArray(START_ARRAY);
// Set transparent large particles
if (mode)
{
glEnable(GL_POINT_SPRITE);
glTexEnvi(GL_POINT_SPRITE,GL_COORD_REPLACE,GL_TRUE);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glDepthMask(0);
}
// Draw arrays
glDrawArrays(GL_POINTS,0,n*n);
// Reset
if (mode)
{
glDisable(GL_POINT_SPRITE);
glDisable(GL_BLEND);
glDepthMask(1);
}
// Disable arrays
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_COLOR_ARRAY);
glf.glDisableVertexAttribArray(VELOCITY_ARRAY);
glf.glDisableVertexAttribArray(START_ARRAY);
}
/*
* Initialize Scene
*/
void PTHopengl::InitScene(void)
{
// Teapot
pot = new Teapot(8);
pot->setScale(1.2);
pot->setTranslate(19.0, -4.8, -2.2);
pot->setRotate(135.0,0.0,1.0,0.0);
pot->setColor(0,1,1);
objects.push_back(pot);
// Objects
try
{
world[0] = new WaveOBJ("torus.obj",":/Assets/");
world[1] = new WaveOBJ("stove_top.obj",":/Assets/");
world[2] = new WaveOBJ("oven.obj",":/Assets/");
world[3] = new WaveOBJ("torus.obj",":/Assets/");
world[4] = new WaveOBJ("torus.obj",":/Assets/");
world[5] = new WaveOBJ("torus.obj",":/Assets/");
world[6] = new WaveOBJ("plate.obj",":/Assets/");
distort = new WaveOBJ("cylinder.obj",":/Assets/");
}
catch (QString err)
{
Fatal("Error loading one of the objects.\n"+err);
}
world[0]->setColor(1,1,0);
objects.push_back(world[0]);
world[0]->setScale(2.0);
world[0]->setTranslate(0.0,0.0,-0.5);
world[1]->setColor(1,1,0);
objects.push_back(world[1]);
world[1]->setScale(2.0);
world[1]->setTranslate(0.0,-3.0,-0.5);
world[2]->setColor(1,1,0);
objects.push_back(world[2]);
world[2]->setScale(1.5);
world[2]->setTranslate(0.18,-14.5,-1.4);
world[2]->setRotate(-90.0,0.0,1.0,0.0);
world[3]->setColor(1,1,0);
objects.push_back(world[3]);
world[3]->setScale(1.3);
world[3]->setTranslate(12.0,-5.5,0.5);
world[4]->setColor(1,1,0);
objects.push_back(world[4]);
world[4]->setScale(1.0);
world[4]->setRotate(45.0,1.0,0.0,0.0);
world[4]->setTranslate(12.0,-4.5, 1.9);
world[5]->setColor(1,1,0);
objects.push_back(world[5]);
world[5]->setScale(1.0);
world[5]->setRotate(30.0,0.0,0.0,1.0);
world[5]->setTranslate(10.0,-4.5, 0.5);
world[6]->setColor(1,1,0);
objects.push_back(world[6]);
world[6]->setScale(2.5);
world[6]->setTranslate(12.0,-6.0, 0.5);
// Cube for cube things
for(int i = 0; i < 6; i++)
{
background[i] = new Cube();
objects.push_back(background[i]);
}
background[0]->setScale(40.0,1.0,40.0);
background[0]->setTranslate(0.0,-40.0,0.0);
background[1]->setScale(40.0,40.0,1.0);
background[1]->setTranslate(0.0,0.0,40.0);
background[2]->setScale(1.0,40.0,40.0);
background[2]->setTranslate(-40.0,0.0,0.0);
background[3]->setScale(40.0,40.0,1.0);
background[3]->setTranslate(0.0,0.0,-40.0);
background[4]->setScale(1.0,40.0,40.0);
background[4]->setTranslate(40.0,0.0,0.0);
background[5]->setScale(40.0,1.0,40.0);
background[5]->setTranslate(0.0,40.0,0.0);
//distort = new Cube();
objects.push_back(distort);
//distort->setScale(2.0,3.0,2.0);
distort->setScale(2.5);
distort->setTranslate(0.0,0.5,-0.5);
for(int i = 0; i < 5; i++)
{
table[i] = new Cube();
objects.push_back(table[i]);
}
table[0]->setScale(7.0, 0.2, 5.0);
table[1]->setScale(0.2, 4.0, 0.2);
table[2]->setScale(0.2, 4.0, 0.2);
table[3]->setScale(0.2, 4.0, 0.2);
table[4]->setScale(0.2, 4.0, 0.2);
table[0]->setTranslate(15.0, -6.0, -0.5);
table[1]->setTranslate(21.5, -10.0, 4.0);
table[2]->setTranslate(21.5, -10.0, -5.0);
table[3]->setTranslate(8.5, -10.0, 4.0);
table[4]->setTranslate(8.5, -10.0, -5.0);
//setShader(1);
//setPerspective(1);
}
/*
* Draws Scene
*/
void PTHopengl::DrawScene(float t)
{
QPixmap pinkDonut(":/Assets/donut_pink.bmp");
QPixmap sugarDonut(":/Assets/donut_sugar.bmp");
QPixmap chocoDonut(":/Assets/donut_chocolate.bmp");
QPixmap planeDonut(":/Assets/donut_plane.bmp");
QPixmap stove(":/Assets/stove_metal.bmp");
QPixmap stove2(":/Assets/brushed_metal.png");
QPixmap tableWood(":/Assets/wood.bmp");
QPixmap floor(":/Assets/floor.bmp");
QPixmap wall1(":/Assets/wall1.bmp");
QPixmap wall2(":/Assets/wall2.bmp");
QPixmap wall3(":/Assets/wall3.bmp");
QPixmap wall4(":/Assets/wall4.bmp");
QPixmap poc(":/Assets/platePot.bmp");
// Apply shader
shader[2]->bind();
shader[2]->setUniformValue("time",t);
shader[2]->setUniformValue("img",0);
shader[2]->setUniformValue("Noise3D",1);
// Draw
bindTexture(pinkDonut, GL_TEXTURE_2D);
world[0]->display();
bindTexture(stove, GL_TEXTURE_2D);
world[1]->display();
bindTexture(stove2, GL_TEXTURE_2D);
world[2]->display();
bindTexture(poc, GL_TEXTURE_2D);
pot->display();
world[6]->display();
bindTexture(pinkDonut, GL_TEXTURE_2D);
world[3]->display();
bindTexture(chocoDonut, GL_TEXTURE_2D);
world[4]->display();
bindTexture(sugarDonut, GL_TEXTURE_2D);
world[5]->display();
bindTexture(tableWood, GL_TEXTURE_2D);
table[0]->display();
table[1]->display();
table[2]->display();
table[3]->display();
table[4]->display();
// Release shader
shader[2]->release();
/* ************************** */
// Apply shader
shader[3]->bind();
shader[3]->setUniformValue("time",t);
shader[3]->setUniformValue("img",0);
shader[3]->setUniformValue("Noise3D",1);
bindTexture(floor, GL_TEXTURE_2D);
background[0]->display();
bindTexture(wall1, GL_TEXTURE_2D);
background[1]->display();
bindTexture(wall2, GL_TEXTURE_2D);
background[2]->display();
bindTexture(wall3, GL_TEXTURE_2D);
background[3]->display();
bindTexture(wall4, GL_TEXTURE_2D);
background[4]->display();
bindTexture(floor, GL_TEXTURE_2D);
background[5]->display();
// Release shader
shader[3]->release();
// Apply shader Distortion for flame
//glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDepthMask(GL_FALSE);
shader[4]->bind();
shader[4]->setUniformValue("mode",mode);
shader[4]->setUniformValue("time",t);
shader[4]->setUniformValue("SimpTex",1);
shader[4]->setUniformValue("PermTex",2);
shader[4]->setUniformValue("GradTex",3);
distort->display();
// Release shader
shader[4]->release();
glDisable(GL_BLEND);
//glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
/* ************************** */
world[0]->setNX(0.0f);
world[0]->setNY(1.0f);
world[0]->setTH(1.0f);
//distort->setNX(0.0f);
//distort->setNY(1.0f);
//distort->setTH(0.5f);
}
// Constructor
PTHopengl::PTHopengl(QWidget* parent)
: CUgl(parent,false)
{
mode = 0;
mouse = false;
asp = 1;
dim = 5;
fov = 80;
th = 0;
ph = 25;
world[0] = 0;
// Particles
N = 15;
Vert = new float[3*N*N];
Color = new float[3*N*N];
Vel = new float[3*N*N];
Start = new float[N*N];
InitPart();
}
//
// Set mode
//
void PTHopengl::setMode(int m)
{
setShader(m);
InitPart();
}
void PTHopengl::initializeGL()
{
glEnable(GL_DEPTH_TEST);
// Load Texture
/*
tex[0] = loadImage(":/Assets/donut_pink.bmp");
tex[1] = loadImage(":/Assets/donut_plane.bmp");
tex[2] = loadImage(":/Assets/donut_sugar.bmp");
tex[3] = loadImage(":/Assets/donut_chocolate.bmp");
glActiveTexture(GL_TEXTURE0);
// Load first image to texture unit 0
glBindTexture(GL_TEXTURE_2D,tex[0]);
// Build shader
if (!shader.addShaderFromSourceFile(QGLShader::Vertex,":/Shaders/PTH.vert"))
Fatal("Error compiling PTH.vert\n"+shader.log());
if (!shader.addShaderFromSourceFile(QGLShader::Fragment,":/Shaders/PTH.frag"))
Fatal("Error compiling PTH.frag\n"+shader.log());
if (!shader.link())
Fatal("Error linking shader\n"+shader.log());
*/
QGLFunctions glf(QGLContext::currentContext());
// Load shaders
addShader(":/Shaders/smoke.vert","",Name);
addShader(":/Shaders/stove_flame.vert",":/Shaders/stove_flame.frag",Name);
addShader(":/Shaders/object_lighting.vert", ":/Shaders/object_lighting.frag", Name);
addShader("", ":/Shaders/background.frag", Name);
addShader(":/Shaders/distort.vert", ":/Shaders/distort.frag", Name);
InitScene();
// Load random texture
CreateNoise3D(GL_TEXTURE1);
}
//
// Draw the window
//
void PTHopengl::paintGL()
{
// Wall time (seconds)
float t = 0.001*time.elapsed();
zh = fmod(90*t,360);
QPixmap flame(":/Assets/ember_particle.png");
// Clear screen and Z-buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glEnable(GL_BLEND);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_DEPTH_TEST);
// Set view
doView();
setMode(0);
shader[0]->bind();
shader[0]->setUniformValue("time",t);
shader[0]->setUniformValue("img",0);
shader[0]->setUniformValue("Noise3D",1);
// Draw scene
DrawPart();
// Release shader
shader[0]->release();
// Draw scene
DrawScene(t);
// Apply shader
setMode(1);
shader[mode]->bind();
shader[mode]->setUniformValue("time",t);
shader[mode]->setUniformValue("img",0);
shader[mode]->setUniformValue("Noise3D",1);
// Draw scene
bindTexture(flame,GL_TEXTURE_2D);
DrawPart();
// Release shader
shader[mode]->release();
if(ph > 85) ph = 85;
if(ph < -60) ph = -60;
/*
// Draw axes
glBegin(GL_LINES);
glVertex3d(0,0,0);
glVertex3d(1,0,0);
glVertex3d(0,0,0);
glVertex3d(0,1,0);
glVertex3d(0,0,0);
glVertex3d(0,0,1);
glEnd();
// Label axes
renderText(1,0,0,"X");
renderText(0,1,0,"Y");
renderText(0,0,1,"Z");
*/
}
|
9306249bdbdef05a4efcb84332bdb28a5eb95f0a
|
4b28074774821a2dc4921f14feaa83336fc087a7
|
/InetTar/Server/StdAfx.cpp
|
3c7b791409312fc0281ab5174d620abc30693877
|
[] |
no_license
|
laz65/internet
|
b7522fcac209e7b1432ed4c6fbb0f6c88d47f660
|
fbeef8aa030d55b10147c98cc0f412b2473904cf
|
refs/heads/master
| 2021-01-10T09:16:09.346241
| 2015-10-03T06:38:12
| 2015-10-03T06:38:12
| 43,551,883
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 3,634
|
cpp
|
StdAfx.cpp
|
// stdafx.cpp : source file that includes just the standard includes
// InetTarif.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
void ClearComp(CompInfo *Comp)
{
Comp->Elapce=0;
Comp->TPos=0;
Comp->bTarif=false;
Comp->sTarif=false;
Comp->cTarif=false;
Comp->Tarif=0.0;
Comp->Start=false;
Comp->Rasch=false;
// 21.04.2011
//Comp->Connected=true;
Comp->AllZalog=0.0;
Comp->Zalog=0.0;
Comp->Time=0;
Comp->Ostatok=0.0;
Comp->sStudFio=" ";
Comp->sStudNum=" ";
delete[] Comp->Bills;
Comp->Bills = NULL;
Comp->nBills = 0;
}
double Round(double dSum, long lPrec)
{
double n, res;
int dl;
dl = (int) pow((double)10, lPrec);
// res=целая часть числа n=дробная 0.xx
n = modf(dSum* dl, &res);
if (fabs(n)>=0.5) res++;
res = res/dl;
return res;
}
void LogWrite(char *text)
{
FILE *log;
log = fopen ("inet.log" , "at");
char LogBuffer[500];
SYSTEMTIME lpSystemTime;
GetLocalTime(&lpSystemTime);
sprintf (LogBuffer, "%02d.%02d.%04d %02d:%02d:%02d -> %s\n", lpSystemTime.wDay, lpSystemTime.wMonth, lpSystemTime.wYear, lpSystemTime.wHour, lpSystemTime.wMinute, lpSystemTime.wSecond, text);
fprintf (log, "%s", LogBuffer);
fclose (log);
}
// Для перехвата ошибок
/*
__try
{
dfdf
}
__except(Except(GetExceptionCode(), GetExceptionInformation(), _T("CTipDlg")))
{
;
}
*/
int Except (unsigned int code, struct _EXCEPTION_POINTERS *ep, CString ProcName)
{
FILE *log;
log = fopen ("inet.err" , "at");
char LogBuffer[300];
SYSTEMTIME lpSystemTime;
GetLocalTime(&lpSystemTime);
char ErrName[100];
switch (code)
{
case EXCEPTION_ACCESS_VIOLATION:
strcpy (ErrName, "EXCEPTION_ACCESS_VIOLATION");
break;
case EXCEPTION_BREAKPOINT:
strcpy (ErrName, "EXCEPTION_BREAKPOINT");
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
strcpy (ErrName, "EXCEPTION_DATATYPE_MISALIGNMENT");
break;
case EXCEPTION_SINGLE_STEP:
strcpy (ErrName, "EXCEPTION_SINGLE_STEP");
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
strcpy (ErrName, "EXCEPTION_ARRAY_BOUNDS_EXCEEDED");
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
strcpy (ErrName, "EXCEPTION_FLT_DENORMAL_OPERAND");
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
strcpy (ErrName, "EXCEPTION_FLT_DIVIDE_BY_ZERO");
break;
case EXCEPTION_FLT_INEXACT_RESULT:
strcpy (ErrName, "EXCEPTION_FLT_INEXACT_RESULT");
break;
case EXCEPTION_FLT_INVALID_OPERATION:
strcpy (ErrName, "EXCEPTION_FLT_INVALID_OPERATION");
break;
case EXCEPTION_FLT_OVERFLOW:
strcpy (ErrName, "EXCEPTION_FLT_OVERFLOW");
break;
case EXCEPTION_FLT_STACK_CHECK:
strcpy (ErrName, "EXCEPTION_FLT_STACK_CHECK");
break;
case EXCEPTION_FLT_UNDERFLOW:
strcpy (ErrName, "EXCEPTION_FLT_UNDERFLOW");
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
strcpy (ErrName, "EXCEPTION_INT_DIVIDE_BY_ZERO");
break;
case EXCEPTION_INT_OVERFLOW:
strcpy (ErrName, "EXCEPTION_INT_OVERFLOW");
break;
case EXCEPTION_PRIV_INSTRUCTION:
strcpy (ErrName, "EXCEPTION_PRIV_INSTRUCTION");
break;
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
strcpy (ErrName, "EXCEPTION_NONCONTINUABLE_EXCEPTION");
break;
default:
strcpy (ErrName, "!!UNKNOWN EXCEPTION!!");
break;
}
sprintf (LogBuffer, "02d.%02d.%04d %02d:%02d:%02d. Error (%d:%s) in proc: (%s) \n",
lpSystemTime.wDay, lpSystemTime.wMonth, lpSystemTime.wYear,
lpSystemTime.wHour, lpSystemTime.wMinute, lpSystemTime.wSecond, code, ErrName, ProcName);
fprintf (log, "%s", LogBuffer);
fclose (log);
return EXCEPTION_EXECUTE_HANDLER;
}
|
01f9ae95f37f48462445556498aa732281375a72
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/git/gumtree/git_old_hunk_1081.cpp
|
e26723b59c3ddfa65d3bcf7fa3acd7750aa5cff1
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 871
|
cpp
|
git_old_hunk_1081.cpp
|
die("cannot deflate request; zlib end error %d", ret);
gzip_size = stream.total_out;
headers = curl_slist_append(headers, "Content-Encoding: gzip");
curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, gzip_body);
curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, gzip_size);
if (options.verbosity > 1) {
fprintf(stderr, "POST %s (gzip %lu to %lu bytes)\n",
rpc->service_name,
(unsigned long)rpc->len, (unsigned long)gzip_size);
fflush(stderr);
}
} else {
/* We know the complete request size in advance, use the
* more normal Content-Length approach.
*/
curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDS, rpc->buf);
curl_easy_setopt(slot->curl, CURLOPT_POSTFIELDSIZE, rpc->len);
if (options.verbosity > 1) {
fprintf(stderr, "POST %s (%lu bytes)\n",
rpc->service_name, (unsigned long)rpc->len);
fflush(stderr);
}
}
|
df8d2a6e1d129de4f8fd1ce9ef067ce231318ef5
|
a255dc54e6366310f12eb7e169cb832cc1a93025
|
/boost/is_palindrome/fuzzer.cpp
|
abac8a4f0780078dade2056c5ba59a36f4111e30
|
[] |
no_license
|
MyLibh/fuzzing
|
d867c77304d2a0bb64791ca2d6efce183f6e177b
|
1a0fa16ca4b153426ff8766ee1918ee68b10e570
|
refs/heads/master
| 2022-10-06T07:15:26.795349
| 2020-06-05T14:21:48
| 2020-06-05T14:21:48
| 258,853,113
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 270
|
cpp
|
fuzzer.cpp
|
#include <boost/algorithm/is_palindrome.hpp>
extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, const std::size_t size)
{
try
{
boost::algorithm::is_palindrome(reinterpret_cast<const char*>(data));
}
catch(...) { }
return 0;
}
|
90b450ef0ca56f08b043d97c00ffb871189865b9
|
59dec7b828f9e2acc226a41bb9e15f70d7523b74
|
/164_Maximum_Gap/main.cpp
|
94b5dc07954a40c429ee3c27f9b5c88e371a9238
|
[] |
no_license
|
zbxhome/Leetcode
|
3bca2f4f9caf6852e3480818ad0a67eb81c36749
|
8c6d33b653ff1d555d1106e69b355ef2be125b04
|
refs/heads/master
| 2021-07-25T16:36:23.951330
| 2017-11-06T13:36:19
| 2017-11-06T13:36:19
| 108,818,712
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,300
|
cpp
|
main.cpp
|
class Solution {
public:
vector<int> digits(vector<int>& nums, int digit){
vector<int> sortDigit;
for (int i=0; i<nums.size(); i++){
sortDigit.push_back((nums[i] & (1<<digit)) >> digit);
}
return sortDigit;
}
vector<int> countingSort(vector<int>& nums, vector<int>& order, int k){
vector<int> res, temp;
res.resize(nums.size());
for (int i=0; i<k; i++)
temp.push_back(0);
for (int i=0; i<order.size(); i++)
temp[order[i]]++;
for (int i=1; i<k; i++)
temp[i] += temp[i-1];
for (int i=order.size()-1; i>=0; i--){
res[temp[order[i]]-1] = nums[i];
temp[order[i]]--;
}
return res;
}
int maximumGap(vector<int>& nums) {
if (nums.size() < 2)
return 0;
vector<int> temp;
// radix sort
// Time complexity O(n)
for (int i=0; i<32; i++){
// sort nums on digit i
temp = digits(nums, i);
nums = countingSort(nums, temp, 2);
}
int maxDiff = -1;
for (int i=1; i<nums.size(); i++)
if (nums[i] - nums[i-1] > maxDiff)
maxDiff = nums[i] - nums[i-1];
return maxDiff;
}
};
|
2fd400f210140ce557a6ecf9616047a0da272f6e
|
d195abfd2e3cb3f11d4c1df4fc1676762f904d07
|
/moveit_planners/pilz_industrial_motion_planner/src/command_list_manager.cpp
|
5a544b13a30c84f8d25137c3f332e270e4a4efe7
|
[
"BSD-3-Clause"
] |
permissive
|
ros-planning/moveit
|
146a5c2648dd27d7bf4fc45ff2ceb90beca14f8a
|
1730d7b392a072bafaab37e6e3bb8ed11e58047e
|
refs/heads/master
| 2023-09-04T03:39:21.644592
| 2023-08-06T09:03:04
| 2023-08-06T09:03:04
| 64,340,188
| 1,499
| 1,117
|
BSD-3-Clause
| 2023-09-09T11:20:46
| 2016-07-27T20:38:09
|
C++
|
UTF-8
|
C++
| false
| false
| 12,184
|
cpp
|
command_list_manager.cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2018 Pilz GmbH & Co. KG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Pilz GmbH & Co. KG nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include "pilz_industrial_motion_planner/command_list_manager.h"
#include <cassert>
#include <functional>
#include <sstream>
#include <moveit/planning_pipeline/planning_pipeline.h>
#include <moveit/robot_state/conversions.h>
#include <ros/ros.h>
#include "pilz_industrial_motion_planner/cartesian_limits_aggregator.h"
#include "pilz_industrial_motion_planner/joint_limits_aggregator.h"
#include "pilz_industrial_motion_planner/tip_frame_getter.h"
#include "pilz_industrial_motion_planner/trajectory_blend_request.h"
#include "pilz_industrial_motion_planner/trajectory_blender_transition_window.h"
namespace pilz_industrial_motion_planner
{
static const std::string PARAM_NAMESPACE_LIMITS = "robot_description_planning";
CommandListManager::CommandListManager(const ros::NodeHandle& nh, const moveit::core::RobotModelConstPtr& model)
: nh_(nh), model_(model)
{
// Obtain the aggregated joint limits
pilz_industrial_motion_planner::JointLimitsContainer aggregated_limit_active_joints;
aggregated_limit_active_joints = pilz_industrial_motion_planner::JointLimitsAggregator::getAggregatedLimits(
ros::NodeHandle(PARAM_NAMESPACE_LIMITS), model_->getActiveJointModels());
// Obtain cartesian limits
pilz_industrial_motion_planner::CartesianLimit cartesian_limit =
pilz_industrial_motion_planner::CartesianLimitsAggregator::getAggregatedLimits(
ros::NodeHandle(PARAM_NAMESPACE_LIMITS));
pilz_industrial_motion_planner::LimitsContainer limits;
limits.setJointLimits(aggregated_limit_active_joints);
limits.setCartesianLimits(cartesian_limit);
plan_comp_builder_.setModel(model);
plan_comp_builder_.setBlender(std::unique_ptr<pilz_industrial_motion_planner::TrajectoryBlender>(
new pilz_industrial_motion_planner::TrajectoryBlenderTransitionWindow(limits)));
}
RobotTrajCont CommandListManager::solve(const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_pipeline::PlanningPipelinePtr& planning_pipeline,
const moveit_msgs::MotionSequenceRequest& req_list)
{
if (req_list.items.empty())
{
return RobotTrajCont();
}
checkForNegativeRadii(req_list);
checkLastBlendRadiusZero(req_list);
checkStartStates(req_list);
MotionResponseCont resp_cont{ solveSequenceItems(planning_scene, planning_pipeline, req_list) };
assert(model_);
RadiiCont radii{ extractBlendRadii(*model_, req_list) };
checkForOverlappingRadii(resp_cont, radii);
plan_comp_builder_.reset();
for (MotionResponseCont::size_type i = 0; i < resp_cont.size(); ++i)
{
plan_comp_builder_.append(planning_scene, resp_cont.at(i).trajectory_,
// The blend radii has to be "attached" to
// the second part of a blend trajectory,
// therefore: "i-1".
(i > 0 ? radii.at(i - 1) : 0.));
}
return plan_comp_builder_.build();
}
bool CommandListManager::checkRadiiForOverlap(const robot_trajectory::RobotTrajectory& traj_A, const double radii_A,
const robot_trajectory::RobotTrajectory& traj_B,
const double radii_B) const
{
// No blending between trajectories from different groups
if (traj_A.getGroupName() != traj_B.getGroupName())
{
return false;
}
auto sum_radii{ radii_A + radii_B };
if (sum_radii == 0.)
{
return false;
}
const std::string& blend_frame{ getSolverTipFrame(model_->getJointModelGroup(traj_A.getGroupName())) };
auto distance_endpoints = (traj_A.getLastWayPoint().getFrameTransform(blend_frame).translation() -
traj_B.getLastWayPoint().getFrameTransform(blend_frame).translation())
.norm();
return distance_endpoints <= sum_radii;
}
void CommandListManager::checkForOverlappingRadii(const MotionResponseCont& resp_cont, const RadiiCont& radii) const
{
if (resp_cont.empty())
{
return;
}
if (resp_cont.size() < 3)
{
return;
}
for (MotionResponseCont::size_type i = 0; i < resp_cont.size() - 2; ++i)
{
if (checkRadiiForOverlap(*(resp_cont.at(i).trajectory_), radii.at(i), *(resp_cont.at(i + 1).trajectory_),
radii.at(i + 1)))
{
std::ostringstream os;
os << "Overlapping blend radii between command [" << i << "] and [" << i + 1 << "].";
throw OverlappingBlendRadiiException(os.str());
}
}
}
CommandListManager::RobotState_OptRef
CommandListManager::getPreviousEndState(const MotionResponseCont& motion_plan_responses, const std::string& group_name)
{
for (MotionResponseCont::const_reverse_iterator it = motion_plan_responses.crbegin();
it != motion_plan_responses.crend(); ++it)
{
if (it->trajectory_->getGroupName() == group_name)
{
return it->trajectory_->getLastWayPoint();
}
}
return boost::none;
}
void CommandListManager::setStartState(const MotionResponseCont& motion_plan_responses, const std::string& group_name,
moveit_msgs::RobotState& start_state)
{
RobotState_OptRef rob_state_op{ getPreviousEndState(motion_plan_responses, group_name) };
if (rob_state_op)
{
moveit::core::robotStateToRobotStateMsg(rob_state_op.value(), start_state);
}
}
bool CommandListManager::isInvalidBlendRadii(const moveit::core::RobotModel& model,
const moveit_msgs::MotionSequenceItem& item_A,
const moveit_msgs::MotionSequenceItem& item_B)
{
// Zero blend radius is always valid
if (item_A.blend_radius == 0.)
{
return false;
}
// No blending between different groups
if (item_A.req.group_name != item_B.req.group_name)
{
ROS_WARN_STREAM("Blending between different groups (in this case: \""
<< item_A.req.group_name << "\" and \"" << item_B.req.group_name << "\") not allowed");
return true;
}
// No blending for groups without solver
if (!hasSolver(model.getJointModelGroup(item_A.req.group_name)))
{
ROS_WARN_STREAM("Blending for groups without solver not allowed");
return true;
}
return false;
}
CommandListManager::RadiiCont CommandListManager::extractBlendRadii(const moveit::core::RobotModel& model,
const moveit_msgs::MotionSequenceRequest& req_list)
{
RadiiCont radii(req_list.items.size(), 0.);
for (RadiiCont::size_type i = 0; i < (radii.size() - 1); ++i)
{
if (isInvalidBlendRadii(model, req_list.items.at(i), req_list.items.at(i + 1)))
{
ROS_WARN_STREAM("Invalid blend radii between commands: [" << i << "] and [" << i + 1
<< "] => Blend radii set to zero");
continue;
}
radii.at(i) = req_list.items.at(i).blend_radius;
}
return radii;
}
CommandListManager::MotionResponseCont
CommandListManager::solveSequenceItems(const planning_scene::PlanningSceneConstPtr& planning_scene,
const planning_pipeline::PlanningPipelinePtr& planning_pipeline,
const moveit_msgs::MotionSequenceRequest& req_list) const
{
MotionResponseCont motion_plan_responses;
size_t curr_req_index{ 0 };
const size_t num_req{ req_list.items.size() };
for (const auto& seq_item : req_list.items)
{
planning_interface::MotionPlanRequest req{ seq_item.req };
setStartState(motion_plan_responses, req.group_name, req.start_state);
planning_interface::MotionPlanResponse res;
planning_pipeline->generatePlan(planning_scene, req, res);
if (res.error_code_.val != res.error_code_.SUCCESS)
{
std::ostringstream os;
os << "Could not solve request\n---\n" << req << "\n---\n";
throw PlanningPipelineException(os.str(), res.error_code_.val);
}
motion_plan_responses.emplace_back(res);
ROS_DEBUG_STREAM("Solved [" << ++curr_req_index << "/" << num_req << "]");
}
return motion_plan_responses;
}
void CommandListManager::checkForNegativeRadii(const moveit_msgs::MotionSequenceRequest& req_list)
{
if (!std::all_of(req_list.items.begin(), req_list.items.end(),
[](const moveit_msgs::MotionSequenceItem& req) { return (req.blend_radius >= 0.); }))
{
throw NegativeBlendRadiusException("All blending radii MUST be non negative");
}
}
void CommandListManager::checkStartStatesOfGroup(const moveit_msgs::MotionSequenceRequest& req_list,
const std::string& group_name)
{
bool first_elem{ true };
for (const moveit_msgs::MotionSequenceItem& item : req_list.items)
{
if (item.req.group_name != group_name)
{
continue;
}
if (first_elem)
{
first_elem = false;
continue;
}
if (!(item.req.start_state.joint_state.position.empty() && item.req.start_state.joint_state.velocity.empty() &&
item.req.start_state.joint_state.effort.empty() && item.req.start_state.joint_state.name.empty()))
{
std::ostringstream os;
os << "Only the first request is allowed to have a start state, but"
<< " the requests for group: \"" << group_name << "\" violate the rule";
throw StartStateSetException(os.str());
}
}
}
void CommandListManager::checkStartStates(const moveit_msgs::MotionSequenceRequest& req_list)
{
if (req_list.items.size() <= 1)
{
return;
}
GroupNamesCont group_names{ getGroupNames(req_list) };
for (const auto& curr_group_name : group_names)
{
checkStartStatesOfGroup(req_list, curr_group_name);
}
}
CommandListManager::GroupNamesCont CommandListManager::getGroupNames(const moveit_msgs::MotionSequenceRequest& req_list)
{
GroupNamesCont group_names;
std::for_each(req_list.items.cbegin(), req_list.items.cend(),
[&group_names](const moveit_msgs::MotionSequenceItem& item) {
if (std::find(group_names.cbegin(), group_names.cend(), item.req.group_name) == group_names.cend())
{
group_names.emplace_back(item.req.group_name);
}
});
return group_names;
}
} // namespace pilz_industrial_motion_planner
|
1a00db88834f33647655c00960a4aba33199f9cf
|
3622c3528c39aaed7b6e28f839d5baf9846b6a1b
|
/QuickData/QuickData.Unity/MeshSchemeAPI.cpp
|
0f96913369ecbd110635526c17f2d6ba1e721b61
|
[] |
no_license
|
tylercamp/UICColum
|
4fc0bbfae81fc33ae2f6f82dd03b1e2c0d1f1546
|
41275bee353093fbbf9aff1606e43256d5f96e9a
|
refs/heads/master
| 2020-04-16T17:43:35.882235
| 2016-10-03T18:27:46
| 2016-10-03T18:27:46
| 45,938,280
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,843
|
cpp
|
MeshSchemeAPI.cpp
|
#include "../QuickData/MeshPartitionScheme.h"
#include "QuickData.Unity.h"
static MeshPartitionScheme * g_LoadedScheme = nullptr;
UNITY_NATIVE_EXPORT bool LoadMeshScheme( char * schemeFile )
{
if( g_LoadedScheme != nullptr )
delete g_LoadedScheme;
MeshPartitionScheme * scheme = new MeshPartitionScheme( );
scheme->LoadFrom( schemeFile );
g_LoadedScheme = scheme;
return true;
}
UNITY_NATIVE_EXPORT int MeshSchemeDescriptorsCount( )
{
if( g_LoadedScheme == nullptr )
return -1;
return g_LoadedScheme->descriptors.size( );
}
UNITY_NATIVE_EXPORT float MeshSchemeDescriptorPositionXAtIndex( int index )
{
if( g_LoadedScheme == nullptr )
return 0.0f;
return g_LoadedScheme->descriptors[index].bounds_start.x;
}
UNITY_NATIVE_EXPORT float MeshSchemeDescriptorPositionYAtIndex( int index )
{
if( g_LoadedScheme == nullptr )
return 0.0f;
return g_LoadedScheme->descriptors[index].bounds_start.y;
}
UNITY_NATIVE_EXPORT float MeshSchemeDescriptorPositionZAtIndex( int index )
{
if( g_LoadedScheme == nullptr )
return 0.0f;
return g_LoadedScheme->descriptors[index].bounds_start.z;
}
UNITY_NATIVE_EXPORT float MeshSchemeDescriptorSizeXAtIndex( int index )
{
if( g_LoadedScheme == nullptr )
return 0.0f;
auto descriptor = g_LoadedScheme->descriptors[index];
return ( descriptor.bounds_end - descriptor.bounds_start ).x;
}
UNITY_NATIVE_EXPORT float MeshSchemeDescriptorSizeYAtIndex( int index )
{
if( g_LoadedScheme == nullptr )
return 0.0f;
auto descriptor = g_LoadedScheme->descriptors[index];
return ( descriptor.bounds_end - descriptor.bounds_start ).y;
}
UNITY_NATIVE_EXPORT float MeshSchemeDescriptorSizeZAtIndex( int index )
{
if( g_LoadedScheme == nullptr )
return 0.0f;
auto descriptor = g_LoadedScheme->descriptors[index];
return ( descriptor.bounds_end - descriptor.bounds_start ).z;
}
|
30df55a1db4d76423f464fda4c2b18ba8e1b483b
|
36183993b144b873d4d53e7b0f0dfebedcb77730
|
/GameDevelopment/3D Game Engine Architecture/Linux/MagicSoftware/WildMagic3/SampleShaders/VertexNoise/Wm3VertexNoiseVShader.h
|
8ddf40a5a60d873c6d1ee31768953aba07a3e444
|
[] |
no_license
|
alecnunn/bookresources
|
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
|
4562f6430af5afffde790c42d0f3a33176d8003b
|
refs/heads/master
| 2020-04-12T22:28:54.275703
| 2018-12-22T09:00:31
| 2018-12-22T09:00:31
| 162,790,540
| 20
| 14
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,354
|
h
|
Wm3VertexNoiseVShader.h
|
// Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2004. All Rights Reserved
//
// The Wild Magic Library (WM3) source code is supplied under the terms of
// the license agreement http://www.wild-magic.com/License/WildMagic3.pdf and
// may not be copied or disclosed except in accordance with the terms of that
// agreement.
#ifndef WM3VERTEXNOISEVSHADER_H
#define WM3VERTEXNOISEVSHADER_H
#include "Wm3VertexShader.h"
namespace Wm3
{
class WM3_ITEM VertexNoiseVShader : public VertexShader
{
WM3_DECLARE_RTTI;
WM3_DECLARE_NAME_ID;
WM3_DECLARE_STREAM;
public:
VertexNoiseVShader ();
virtual ~VertexNoiseVShader ();
void SetNoiseTranslate (const Vector4f& rkNoiseTranslate);
Vector4f GetNoiseTranslate () const;
void SetNoiseScale (float fNoiseScale);
float GetNoiseScale () const;
void SetDisplacement (float fDisplacement);
float GetDisplacement () const;
void SetPg (int i, const Vector4f& rkData);
Vector4f GetPg (int i) const;
void SetBaseColor (const Vector4f& rkBaseColor);
Vector4f GetBaseColor () const;
private:
static const char* ms_aacProgram[Renderer::RT_QUANTITY];
};
WM3_REGISTER_STREAM(VertexNoiseVShader);
typedef Pointer<VertexNoiseVShader> VertexNoiseVShaderPtr;
#include "Wm3VertexNoiseVShader.inl"
}
#endif
|
8202fc2133f4f4b7c484cf2921d3e822123ce048
|
b230ebbc1b2d66d049f246726e568e3a16613d11
|
/Robot_BT/Sensor_TCRT5000.h
|
85c56fca3e92d7ecd0e0358161e3b818260cd749
|
[] |
no_license
|
ramporfy/Robot-BT
|
39dab429d9ddce463f00fa47d9957acafbcf41de
|
2c171b1af47032106c1a8767ed559ed1278f528b
|
refs/heads/master
| 2020-03-18T00:47:45.285781
| 2017-03-14T18:20:12
| 2017-03-14T18:20:12
| 134,112,874
| 1
| 0
| null | 2018-05-20T02:16:14
| 2018-05-20T02:16:13
| null |
UTF-8
|
C++
| false
| false
| 154
|
h
|
Sensor_TCRT5000.h
|
class Sensor
{
private:
int Pin_sensor;
public:
Sensor(int pin): Pin_sensor(pin){}//Constructor
void Inicializar();
int Leer_sensor();
};
|
5c71180acb2f1fb3c00e054522d4d15e097b8b6d
|
d0f2bb18c39ff5dac5d9d2cec8cc98e96a642d8a
|
/Examples/Cpp/source/Outlook/PST/DisplayInformationOfPSTFile.cpp
|
5ba27c0b9cdfc4d0eb16d45408daf7a5ee682838
|
[
"MIT"
] |
permissive
|
kashifiqb/Aspose.Email-for-C
|
d1e26c1eb6cb1467cee6a050ed5b52baaf186816
|
96684cb6ed9f4e321a00c74ca219440baaef8ba8
|
refs/heads/master
| 2023-03-24T22:44:20.264193
| 2021-02-10T14:07:51
| 2021-02-10T14:07:51
| 105,030,475
| 0
| 0
| null | 2017-09-27T14:43:20
| 2017-09-27T14:43:20
| null |
UTF-8
|
C++
| false
| false
| 2,261
|
cpp
|
DisplayInformationOfPSTFile.cpp
|
/* This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET
API reference when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq
for more information. If you do not wish to use NuGet, you can manually download
Aspose.Email for .NET API from https://www.nuget.org/packages/Aspose.Email/,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using https://forum.aspose.com/c/email
*/
#include <system/string.h>
#include <system/shared_ptr.h>
#include <system/console.h>
#include <system/collections/ienumerator.h>
#include <Storage/Pst/PersonalStorage.h>
#include <Storage/Pst/FolderInfoCollection.h>
#include <Storage/Pst/FolderInfo.h>
#include <cstdint>
#include "Examples.h"
using namespace Aspose::Email;
using namespace Aspose::Email::Storage::Pst;
void DisplayInformationOfPSTFile()
{
// ExStart:DisplayInformationOfPSTFile
// The path to the File directory.
System::String dataDir = GetDataDir_Outlook();
System::String dst = dataDir + u"PersonalStorage.pst";
// load PST file
System::SharedPtr<PersonalStorage> personalStorage = PersonalStorage::FromFile(dst);
// Get the folders information
System::SharedPtr<FolderInfoCollection> folderInfoCollection = personalStorage->get_RootFolder()->GetSubFolders();
// Browse through each folder to display folder name and number of messages
{
auto folderInfo_enumerator = (folderInfoCollection)->GetEnumerator();
decltype(folderInfo_enumerator->get_Current()) folderInfo;
while (folderInfo_enumerator->MoveNext() && (folderInfo = folderInfo_enumerator->get_Current(), true))
{
System::Console::WriteLine(System::String(u"Folder: ") + folderInfo->get_DisplayName());
System::Console::WriteLine(System::String(u"Total items: ") + folderInfo->get_ContentCount());
System::Console::WriteLine(System::String(u"Total unread items: ") + folderInfo->get_ContentUnreadCount());
System::Console::WriteLine(u"-----------------------------------");
}
}
// ExEnd:DisplayInformationOfPSTFile
}
|
c4971269981f2c51750ce7137e7311ad16578084
|
30b8561243cff67f758633327004cb378e5c5cef
|
/source/include/NGE/Media/Files/File.hpp
|
2d1d71698701feec9900d3fb81a06480398076ea
|
[] |
no_license
|
tkubicz/ngengine
|
56a7235de0c799f541d47841380da6fd90d3abed
|
75413c8b77587e5ec8f03164fa9b5dcd7697c0c6
|
refs/heads/master
| 2021-01-12T06:02:57.202296
| 2016-06-15T16:42:43
| 2016-06-15T16:42:43
| 77,282,542
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 931
|
hpp
|
File.hpp
|
/*
* File: File.hpp
* Author: tku
*
* Created on 11 lipiec 2015, 22:36
*/
#ifndef FILE_HPP
#define FILE_HPP
#ifdef ANDROID
#include "NGE/Core/Core.hpp"
#include <android/asset_manager.h>
namespace NGE {
namespace Media {
namespace Files {
class File {
private:
std::string name;
unsigned int length;
static AAssetManager* assetManager;
AAsset* asset;
public:
File();
explicit File(std::string name);
virtual ~File();
bool Open();
void Close();
void Read(void* buffer, size_t& bytesRead);
void Read(void* buffer, const unsigned int bytesToRead, size_t& bytesRead);
unsigned int GetLength() const;
void SetName(const std::string& name);
std::string GetName() const;
static const size_t READ_FAILED = 0xFFFFFFFF;
static void SetAssetManager(AAssetManager* assetManager);
};
}
}
}
#endif /* ANDROID */
#endif /* FILE_HPP */
|
9ce452d7a15af42ecc6af09d9fe27a3df088d235
|
7a376b7871fed50e8d7e81ae0917c41d33fff714
|
/Stand.h
|
44c0d932b318b8a59baf0e91fa8a044afa38f6b7
|
[] |
no_license
|
kmoran23/Lemonade
|
f3caa6071f06f486dd5d375f0339b258d505bba2
|
ae2e04fc2aee7ae0dafaaa12d339422bd5995441
|
refs/heads/main
| 2023-02-17T20:52:16.714974
| 2021-01-21T04:30:16
| 2021-01-21T04:30:16
| 331,513,938
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,887
|
h
|
Stand.h
|
//CS1300 Spring 2020
//Author: Patricia Chin & Kyra Moran
//Project 3
#include <iostream>
#include <string>
using namespace std;
#ifndef STAND_H
#define STAND_H
class Stand
{
public:
//default constructor
Stand();
//setter function
void setPlayerName(string playerName_); //sets private data member playerName
void setStandName(string standName_); //sets private data member standName
void setNumLemons(int numLemons_); //sets private data member numLemons
void setNumSugar(int numSugar_); //sets private data member numSugar
void setNumAdvert(int numAdvert_); //sets private data member numAdvert
void setNumBaskets(int numBaskets_); //sets private data member numBaskets
void setNumUmbrellas(int numUmbrellas_); //sets private data member numUmbrellas
void setNumCoolers(int numCoolers_); //sets private data member numCoolers
void setSpendAssets(double spendAssets_); //sets private data member spendAssets
void setProfit(double profit_); //sets private data member profit
void setMainVal(int mainVal_); //sets private data member mainVal
void setMainStatus(); //sets private data member mainStatus
//getter functions
string getPlayerName(); //Return private data member playerName
string getStandName(); //Return private data member standName
int getNumLemons(); //Return private data member numLemons
int getNumSugar(); //Return private data member numSugar
int getNumAdvert(); //Return private data member numAdvert
int getNumBaskets(); //Return private data member numBaskets
int getNumUmbrellas(); //Return private data member numUmbrellas
int getNumCoolers(); //Return private data member numCoolers
double getSpendAssets(); //Return private data member spendAssets
double getProfit(); //Return private data member profit
int getMainVal(); //Return private data member mainVal
string getMainStatus(); //Return private data member mainStatus
private:
//names
string playerName; //username of user
string standName; //name of user's lemonade stand
//supplies
int numLemons; //number of lemons
int numSugar; //number of sugar cubes
int numAdvert; //number of advertisements
int numBaskets; //number of baskets
int numUmbrellas; //number of umbrellas
int numCoolers; //number of coolers
double spendAssets; //money that the stand has to spend on supplies
double profit; //money that the stand has made
string mainStatus; //maintenance status can be good,fair, or poor
int mainVal; //maintenance value; if 0 --> lose game; if 1 or 2 --> poor; if 3 or 4 --> fair; if 5 or 6 --> good
};
#endif
|
d499dfdb72b80f381a56135dedbf38f083f5124e
|
7af9c24bb6cea6e77c74990fbdf061bd03c0e779
|
/src/Union_find.cpp
|
99903cd6fe8101ca8c525157563879fd0c983a0f
|
[] |
no_license
|
dtbinh/sedgewick_cpp
|
abfca17d774f03cfde912fe5404770fad68a8628
|
b488e5df2ad9c855aaaed66397c457dba55a4463
|
refs/heads/master
| 2023-03-16T09:11:31.240153
| 2017-08-23T23:39:20
| 2017-08-23T23:39:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,370
|
cpp
|
Union_find.cpp
|
#include <sstream>
#include "Union_find.h"
#include "utility.h"
// NOTE: this is the weighted quick union version
Union_find::Union_find(int n)
: _count{n},
_parent(static_cast<std::vector<int>::size_type>(n)),
_rank(static_cast<std::vector<short>::size_type>(n), 0)
{
if (n < 0) {
throw utility::Illegal_argument_exception{"The number of sites _in a Weighted_quick_union_uf must be non-negative"};
}
for (auto i = 0; i < n; ++i) { _parent[i] = i; }
}
int Union_find::find(int p)
{
_validate(p);
while (p != _parent[p]) {
_parent[p] = _parent[_parent[p]];
p = _parent[p];
}
return p;
}
void Union_find::create_union(int p, int q)
{
// _validate(p);
// _validate(q);
auto root_p = find(p);
auto root_q = find(q);
if (root_p == root_q) { return; }
if (_rank[root_p] < _rank[root_q]) {
_parent[root_p] = root_q;
} else if (_rank[root_p] > _rank[root_q]) {
_parent[root_q] = root_p;
} else {
_parent[root_q] = root_p;
_rank[root_p]++;
}
--_count;
}
void Union_find::_validate(int p) const
{
auto n = _parent.size();
if (p < 0 || p >= n) {
std::stringstream ss;
ss << "Index " << p << " is not between 0 and " << (n - 1);
throw utility::Index_out_of_bounds_exception{ss.str()};
}
}
|
03ab414bb8f2ea2b164626bc3a25aa226bd75f47
|
8d4d2dcba20c384ba0e5a07e9ad039af0f56acb8
|
/Source/Abstraction/Private/DefaultPlayerController.cpp
|
36614e1ea7eb266c5698bd1bfd36c176a40df6c6
|
[] |
no_license
|
Zaknarfen/Abstraction
|
cae76ded97362a148f61ad1b8969393685f00471
|
8f692ffb10877d371b2c00e4ae61f5f4a967525d
|
refs/heads/main
| 2023-06-27T11:21:25.719576
| 2021-07-09T06:21:00
| 2021-07-09T06:21:00
| 382,698,574
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,037
|
cpp
|
DefaultPlayerController.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Controllers/Entities/Players/DefaultPlayerController.h"
#include "Blueprint/AIBlueprintHelperLibrary.h"
#include "GameFramework/PlayerInput.h"
#include "GameFramework/Pawn.h"
ADefaultPlayerController::ADefaultPlayerController()
{
bShowMouseCursor = true;
DefaultMouseCursor = EMouseCursor::Crosshairs;
}
void ADefaultPlayerController::SetupInputComponent()
{
Super::SetupInputComponent();
// Actions
InputComponent->BindAction("LeftClick", IE_Pressed, this, &ADefaultPlayerController::OnLeftClick);
InputComponent->BindAction("LeftClick", IE_Released, this, &ADefaultPlayerController::OnLeftClickUp);
}
void ADefaultPlayerController::PlayerTick(float DeltaTime)
{
Super::PlayerTick(DeltaTime);
// keep updating the destination every tick while desired
if (bMoveToMouseCursor)
{
MovePlayer();
}
}
void ADefaultPlayerController::OnLeftClick()
{
bMoveToMouseCursor = true;
}
void ADefaultPlayerController::OnLeftClickUp()
{
bMoveToMouseCursor = false;
}
void ADefaultPlayerController::MovePlayer()
{
// Trace to see what is under the mouse cursor
FHitResult Hit;
GetHitResultUnderCursor(ECC_Visibility, false, Hit);
if (Hit.bBlockingHit)
{
UE_LOG(LogTemp, Display, TEXT("--------------------------------"));
UE_LOG(LogTemp, Display, TEXT("hit, %.2f, %.2f, %.2f"), Hit.ImpactPoint.X, Hit.ImpactPoint.Y, Hit.ImpactPoint.Z);
APawn* CubePawn = GetPawn();
if (CubePawn)
{
UE_LOG(LogTemp, Display, TEXT("--------------------------------"));
UE_LOG(LogTemp, Display, TEXT("pawn, %.2f, %.2f, %.2f"), CubePawn->GetActorLocation().X, CubePawn->GetActorLocation().Y, CubePawn->GetActorLocation().Z);
float const Distance = FVector::Dist(Hit.ImpactPoint, CubePawn->GetActorLocation());
// We need to issue move command only if far enough in order for walk animation to play correctly
if ((Distance > 120.0f))
{
UAIBlueprintHelperLibrary::SimpleMoveToLocation(this, Hit.ImpactPoint);
}
}
}
}
|
e98e09001620820a12c2b876eede979dadf99229
|
3c8bfae0880a10b429954e7eb68f47bf927b1328
|
/FastLED_RGBW2.h
|
c7297ebd5d537700340c959458ea473b4e50963d
|
[] |
no_license
|
jaygoldstuck/TeaShop
|
6b581a4e09ca423e40e0db5768e5a80937adfccd
|
2d38196c28cefbf926a31911b751c915de1eaa59
|
refs/heads/master
| 2022-10-25T21:34:25.445440
| 2022-10-08T23:52:54
| 2022-10-08T23:52:54
| 159,211,644
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,347
|
h
|
FastLED_RGBW2.h
|
/* FastLED_RGBW
*
* Hack to enable SK6812 RGBW strips to work with FastLED.
*
* Original code by Jim Bumgardner (http://krazydad.com).
* Modified by David Madison (http://partsnotincluded.com).
* Modified by Christof Kaufmann.
*
*/
// See: https://www.partsnotincluded.com/fastled-rgbw-neopixels-sk6812/
// See: https://www.dmurph.com/posts/2021/1/cabinet-light-3.html
#pragma once
#include <FastLED.h>
#include <memory> // for std::array in CRGBWArray
/**
* @brief Extends CRGB by white
*
* This contains RGB values and additionally a value for white. This allows to
* use RGBW LEDs with FastLED, but not perfectly. Things like color or
* temperature correction won't work, since it is applied right before sending.
* But this workaround does not give FastLED real RGBW capabilities, so to be
* clear: FastLED still thinks that it is sending color data to RGB LEDs:
* @code
* FastLED sees: R G B|R G B|R G B|R G B|R G B|R G B|
* True LEDs are: R G B W|R G B W|R G B W|R G B W|
* @endcode
*/
struct CRGBW : public CRGB {
union {
uint8_t w;
uint8_t white;
};
CRGBW() : CRGB(0, 0, 0), w{0} {}
CRGBW(uint8_t r, uint8_t g, uint8_t b, uint8_t w = 0)
: CRGB(r, g, b), w{w}
{}
inline void operator=(const CRGB c) __attribute__((always_inline)){
this->r = c.r;
this->g = c.g;
this->b = c.b;
this->w = 0;
}
/**
* @brief Blend two colors in screen mode
*
* This blends two colors nicely giving a bright color.
* Alpha is not supported here, since CRGBW does not support it.
*
* @see https://en.wikipedia.org/wiki/Blend_modes
*/
CRGBW& screen_blend(CRGB b) { // parameter type must be `CRGB` instead of `CRGB const&` due to a bug in operator-
CRGB complement = -(*this);
*this = -(complement.scale8(-b));
return *this;
}
};
CRGB blend(CRGBW a, CRGB const& b) {
return a.screen_blend(b);
}
using CRGBWSet = CPixelView<CRGBW>;
__attribute__((always_inline))
inline CRGBW* operator+(CRGBWSet const& pixels, int offset) {
return (CRGBW*)pixels + offset;
}
/**
* @brief Number of RGB LEDs required to contain the RGBW LEDs values
*
* For details, see #CRGBWArray::rgb_size()
*/
constexpr int rgb_size_from_rgbw_size(int nleds_rgbw){ // original name: getRGBWsize
return nleds_rgbw * 4 / 3 + (nleds_rgbw % 3 != 0);
}
/**
* @brief Calibration factors of the white LED
*
* The values here mean if white is set to 100 (and red, green and blue are
* off), it has the same color and brightness as if red is set to 255, green to
* 140 and blue to 25 (and white is off).
*
* To find these values, start by trying to match the color of white and then
* brightness. The brightness is hard to estimate, so looking at converted
* colors might help.
*/
constexpr float whitepoint_red_factor = 100. / 255.;
constexpr float whitepoint_green_factor = 100. / 140.; ///< @copydoc whitepoint_red_factor
constexpr float whitepoint_blue_factor = 100. / 25.; ///< @copydoc whitepoint_red_factor
/**
* @brief Convert the RGB values to RGBW values in send order
*
* For details, see #CRGBWArray::convert_to_rgbw()
*/
void rgb2rgbw(CRGBW leds[], size_t n_leds) {
for (uint16_t idx = 0; idx < n_leds; ++idx) {
CRGBW& led = leds[idx];
if (led.w > 0)
continue;
// These values are what the 'white' value would need to be to get the corresponding color value.
float white_val_from_red = led.r * whitepoint_red_factor;
float white_val_from_green = led.g * whitepoint_green_factor;
float white_val_from_blue = led.b * whitepoint_blue_factor;
// Set the white value to the highest it can be for the given color
// (without over saturating any channel - thus the minimum of them).
float min_white_value = std::min(white_val_from_red, std::min(white_val_from_green, white_val_from_blue));
// Don't use transformation for very dark values, since rounding errors are visible there
if (min_white_value > 4) {
// The rest of the channels will just be the original value minus the contribution by the white channel.
led.r = static_cast<uint8_t>(std::round(led.r - led.w / whitepoint_red_factor));
led.g = static_cast<uint8_t>(std::round(led.g - led.w / whitepoint_green_factor));
led.b = static_cast<uint8_t>(std::round(led.b - led.w / whitepoint_blue_factor));
led.w = static_cast<uint8_t>(std::floor(min_white_value));
}
// GRBW send order must be taken into account here and set outside to RGB
std::swap(led.r, led.g);
}
}
/// @copydoc rgb2rgbw
template <class LEDArray>
void rgb2rgbw(LEDArray& leds) {
rgb2rgbw(&leds[0], leds.size());
}
/**
* @brief Convert RGBW values back to RGB
*
* This converts the RGBW values back to RGB in case you want to modify them
* instead of completely overwriting them. It also accounts for the send order
* by swapping back red and green values.
*/
void rgbw2rgb(CRGBW leds[], size_t n_leds) {
for (uint16_t idx = 0; idx < n_leds; ++idx) {
CRGBW& led = leds[idx];
// Reverse send order here
CRGBW temp = led;
std::swap(temp.r, temp.g);
// Reverse transformation
led.r = static_cast<uint8_t>(std::max(255.0f, std::round(temp.r + temp.w / whitepoint_red_factor)));
led.g = static_cast<uint8_t>(std::max(255.0f, std::round(temp.g + temp.w / whitepoint_green_factor)));
led.b = static_cast<uint8_t>(std::max(255.0f, std::round(temp.b + temp.w / whitepoint_blue_factor)));
led.w = 0;
}
}
/// @copydoc rgbw2rgb
template <class LEDArray>
void rgbw2rgb(LEDArray& leds) {
rgbw2rgb(&leds[0], leds.size());
}
/**
* @brief CRGBW Array class
*
* Here is an example of how to use it. First, create the array as global
* variable:
* @code
* constexpr int NUM_LEDS = 87;
* CRGBWArray<NUM_LEDS> leds;
* @endcode
*
* Then, configure FastLED to use it (e. g. in the Arduino `setup()` function):
* @code
* constexpr int LED_IO = 19;
* FastLED.addLeds<SK6812, LED_IO, RGB>(leds, leds.rgb_size());
* @endcode
* Note, that the send order must be RGB, although the real send order is GRBW!
* After drawing your effects into `leds`, you have to convert the colors to
* RGBW, which also handles the send order (e. g. in the Arduino `loop()`
* function):
* @code
* leds.convert_to_rgbw();
* FastLED.delay(100); // send during delay
* @endcode
*/
template<int SIZE>
class CRGBWArray : public CPixelView<CRGBW> {
std::array<CRGBW, SIZE> rawleds;
public:
CRGBWArray() : CPixelView<CRGBW>(rawleds.data(), SIZE) {}
using CPixelView::operator=;
/**
* @brief Number of RGB LEDs required to contain the RGBW LEDs values
*
* This is useful for the `FastLED.addLeds()` call, see the example at
* #CRGBWArray.
*
* Example: For 10 RGBW LEDs you need 40 bytes color data, which fits into
* 14 RGB LEDs (42 bytes).
*/
static constexpr int rgb_size() {
return rgb_size_from_rgbw_size(SIZE);
}
/**
* @brief Convert this Array to a CRGB pointer onto the first element
*
* This is useful for the `FastLED.addLeds()` call.
*/
inline operator CRGB* () {
return reinterpret_cast<CRGB*>(rawleds.data());
}
/**
* @brief Convert the RGB values to RGBW values in send order
*
* The part in the RGB values, that can be represented by the white led is
* removed from the RGB values and set to the white value.
*
* Using the equivalent RGBW values reduces power consumption and enhances
* the light quality (RA value). However, it does not allow to go beyond
* the brightness of full RGB. You could set the white value afterwards if
* you really want.
*
* Besides it swaps the red and green channel in the converted values to
* handle the send order.
*/
inline void convert_to_rgbw() {
rgb2rgbw(*this);
}
/**
* @brief Convert the RGBW values in send order back to RGB values
*
* This swaps the red and green channel to revert the send order fix and
* then adds the white led value split into RGB color components back to
* the remained RGB values. This sets the white value to 0.
*
* This function is useful, if you want to modify the led values directly
* in the CRGBWArray.
*/
inline void revert_to_rgb() {
rgbw2rgb(*this);
}
};
|
9b3b74f03a3245abbe593b1c25b4940aa549b025
|
f34b5a529e2fa17b5d83a1e4a11115d591414ffa
|
/lib/Interface/rayleigh.h
|
a6ce54bd1e0135d7b07af29209e89edbdb72a85f
|
[] |
no_license
|
ReFRACtor/framework
|
89917d05e22dd031e12d12389157eb24cebeaada
|
882e13c3e94e6faa1281a0445abc0e08b2f8bf30
|
refs/heads/master
| 2022-12-08T17:12:49.696855
| 2022-11-28T23:30:50
| 2022-11-28T23:30:50
| 98,920,384
| 4
| 7
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,302
|
h
|
rayleigh.h
|
#ifndef RAYLEIGH_H
#define RAYLEIGH_H
#include <boost/shared_ptr.hpp>
#include "printable.h"
#include "array_ad.h"
namespace FullPhysics {
/****************************************************************//**
This class represents the interface for the calculation of
the Rayleigh portion of the optical depth
*******************************************************************/
class Rayleigh: public Printable<Rayleigh> {
public:
//-----------------------------------------------------------------------
/// This gives the optical depth for each layer, for the given wavenumber.
//-----------------------------------------------------------------------
virtual ArrayAd<double, 1> optical_depth_each_layer(double wn, int spec_index) const = 0;
//-----------------------------------------------------------------------
/// Clone a Ralyeigh object into a new copy
//-----------------------------------------------------------------------
virtual boost::shared_ptr<Rayleigh> clone() const = 0;
virtual void print(std::ostream& Os) const
{
Os << "Rayleigh";
}
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version);
};
}
FP_EXPORT_KEY(Rayleigh);
#endif
|
d18efaf63a2f562736d4dc9f58198cc9dcde68f5
|
2d3a162d458b57defe37b88eecea65edb494ad65
|
/Mover.cpp
|
ac1342fc92490a94cde9bc59f513d9e44c29c58d
|
[] |
no_license
|
DavletSaukin/Running_Ogre
|
2d056d9994cc2376a5936ca9e42abc873b20a78f
|
3d12867f00efe443c8629d416a0f9d9a8474ce2c
|
refs/heads/master
| 2020-04-09T17:44:30.814087
| 2018-04-19T14:46:46
| 2018-04-19T14:46:46
| 124,236,966
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,802
|
cpp
|
Mover.cpp
|
#include <Urho3D/Graphics/AnimatedModel.h>
#include <Urho3D/Graphics/AnimationState.h>
#include <Urho3D/Scene/Scene.h>
#include <Urho3D/Physics/RigidBody.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Physics/PhysicsWorld.h>
#include <random>
#include "Mover.h"
#include <Urho3D/DebugNew.h>
Mover::Mover(Context* context) :
LogicComponent(context),
moveSpeed_(0.0f)
{
// Only the scene update event is needed: unsubscribe from the rest for optimization
SetUpdateEventMask(USE_UPDATE);
}
void Mover::Start()
{
// Компонент вставлен в его ноду. Подписываемся на события
SubscribeToEvent(GetNode(), E_NODECOLLISIONSTART, URHO3D_HANDLER(Mover, HandleColissionStart));
}
void Mover::SetParameters(float moveSpeed, Vector3 dir)
{
moveSpeed_ = moveSpeed;
direction_ = dir;
}
void Mover::Update(float timeStep)
{
node_->Translate(direction_ * moveSpeed_ * timeStep);
AnimatedModel* model = node_->GetComponent<AnimatedModel>(true);
if (model->GetNumAnimationStates())
{
AnimationState* state = model->GetAnimationStates()[0];
state->AddTime(timeStep);
}
}
void Mover::HandleColissionStart(StringHash eventType, VariantMap& eventData)
{
using namespace NodeCollisionStart;
Node* otherNode = static_cast<Node*>(eventData[P_OTHERNODE].GetPtr());
std::random_device rd;
std::mt19937 gen(rd());
std::bernoulli_distribution d(0.5); //вероятность 50/50
if (otherNode->GetName() == "Box" || otherNode->GetName() == "Wall" ||
otherNode->GetName() == "Cannonbal")
{
//не знаем куда повернёт нода
if (d(gen))
{
node_->Yaw(90.0f);
}
else
{
node_->Yaw(-90.0f);
}
}
}
|
6b4f4e2775937164896105c8e3966cff0b1e8952
|
3dbf3b1a91f539631898624cfd8771cf8e395087
|
/src/game/main.cpp
|
2f23988cd8b7c6218c846977d98f4e756a18bd7c
|
[] |
no_license
|
FredTheDino/Tea
|
daa5596beef860ffcde0a543f407dae62614f0b0
|
4f838626bf3ac139863794fc0a3d2353f43a6f45
|
refs/heads/master
| 2021-01-17T20:57:21.435863
| 2016-11-03T21:06:54
| 2016-11-03T21:06:54
| 61,391,835
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,559
|
cpp
|
main.cpp
|
#include <iostream>
#include <stdio.h>
#include <math.h>
#include "bag.h"
#include "animation.cpp"
#include "gameobject.cpp"
Tea::GameObject obj;
static double a = 0;
static int frame = 0;
void update(double delta) {
static unsigned int lastFPS = 0;
unsigned int newFPS = Tea::Time::getFPS();
if (lastFPS != newFPS) {
//std::cout << "FPS: " << newFPS << std::endl;
lastFPS = newFPS;
}
//printf("A: %f\n", a);
obj.transform._position.x = a;
Tea::GraphicsComponent* gc;
obj.getComponent<Tea::GraphicsComponent>(&gc);
gc->setSubSprite(frame);
//std::cout << frame << std::endl;
}
int main(int argc, const char* argv[]) {
Tea::Bag bag;
bag.registerUpdateFunction(update);
Tea::Time::setMaxFrameRate(0);
Tea::InputManager::addInput(Tea::Input(-1, SDLK_ESCAPE, 0), "quit");
Tea::Animation<double> anim(&a, {0.1, 0.2, 0.3, 0.4, -0.5}, 0.5, Tea::EASE, true);
Tea::Animation<int> color(&frame, {0, 1, 2, 3}, 0.5, Tea::DIGITAL, true);
Tea::Animation<int>* colordelete = new Tea::Animation<int>(&frame, {0, 1, 2, 3}, 0.1, Tea::DIGITAL, true);
delete colordelete;
Tea::Shader sh("shader");
Tea::Texture tex("texture.jpg", 2, 2);
Tea::Material mat(&sh, &tex);
GLenum err = GL_NO_ERROR;
while ((err = glGetError()) != GL_NO_ERROR) {
std::cout << "GL error: " << err << std::endl;
}
Tea::GraphicsComponent com(&obj, &mat);
obj.addComponent<Tea::GraphicsComponent>(&com);
Tea::GraphicsComponent* c = nullptr;
obj.getComponent<Tea::GraphicsComponent>(&c);
c->setSubSprite(2);
bag.run();
return 0;
}
|
5a193ad723a8079a0a25d5c1fbfffcf041205ba3
|
776bb000f51a134300e8c84f3c01b8f0839a86e4
|
/www/util/gsk_log/src/mongo_driver.h
|
cd83fe6cf9ee50b765a567c43bc7e228f503a10d
|
[] |
no_license
|
SoulBringerOnline/ci_project
|
a096c716c8198bdcd0a537debba7c8df4cea9377
|
f6a5c13866a0fedb3c0755f2ad871ddc0344584c
|
refs/heads/master
| 2021-01-19T02:00:42.567250
| 2017-04-06T02:22:05
| 2017-04-06T02:22:05
| 87,257,421
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,055
|
h
|
mongo_driver.h
|
/* ======================================================================
* taal project
*
* ----------------------------------------------------------------------
* Author : yongsheng.zhao@lavaclan.com
* Date : 2014-08-15
*
* Copyright (c) 2014年 http://www.lavaclan.com All rights reserved.
* ======================================================================*/
#ifndef __YS_MONGO_H__
#define __YS_MONGO_H__
#include "oi_log.h"
#include <mongoc.h>
#include <unordered_map>
#include <string>
#include <vector>
class MongoDriver{
public:
MongoDriver( const char* sHost );
~MongoDriver();
static MongoDriver* instance (const char* sHost = "mongodb://192.168.1.106/");
static void destrory();
mongoc_collection_t* collection( const char* sCollName );
bool insert( const char* sCollName, bson_t* pDoc );
private:
std::unordered_map<std::string, mongoc_collection_t*> m_Colls;
mongoc_client_t* m_pClt;
static MongoDriver* m_pInstance;
std::string m_strHost;
LogFile m_stLog;
};
#endif
|
ef624da7f5ce9b3c3723d5ab3aa8058fd3b705eb
|
4858dcc1d54f8544563e31b4a649d276dcbfa9ad
|
/romanToInteger.cpp
|
02506670f53aa2f40b4f9a10c9882840f2cfd5c6
|
[] |
no_license
|
sunwit/Leetcode
|
cabc9dcc23419d865e218baecd3adb40dcb3e426
|
b57bf142bdc182bd8e5cd9f3f74ea8d6fd68a51c
|
refs/heads/master
| 2021-01-10T03:06:15.910956
| 2016-04-14T05:41:44
| 2016-04-14T05:41:44
| 55,280,374
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,134
|
cpp
|
romanToInteger.cpp
|
#include<iostream>
#include<string>
using namespace std;
int romanCharToInt(char ch){
int d = 0;
switch(ch){
case 'I':
d = 1;
break;
case 'V':
d = 5;
break;
case 'X':
d = 10;
break;
case 'L':
d = 50;
break;
case 'C':
d = 100;
break;
case 'D':
d = 500;
break;
case 'M':
d = 1000;
break;
}
return d;
}
int romanToInteger(string s){
if(s.size()<=0) return 0;
int result = romanCharToInt(s[0]);
for(int i = 1; i<s.size();i++)
{
int prev = romanCharToInt(s[i-1]);
int cur = romanCharToInt(s[i]);
if(prev<cur)
result = result - prev + (cur - prev);
else
result = result + cur;
}
return result;
}
int main(int argc ,char** argv)
{
string s("XL");
if(argc>1)
s = argv[1];
cout<<s<<":"<<romanToInteger(s)<<endl;
return 0;
}
|
f44acb00966e05c8117c1fefecbdb62e37ff84b0
|
aa10e3edb2d9db88b0fa48beee2c8a4c93d6958f
|
/ch14/1417ex.cpp
|
16ddedfe54d7d93cf6384ec0dcb697eab40cc1c9
|
[
"MIT"
] |
permissive
|
mallius/CppPrimer
|
e1a04d6e1a00d180ecca60a0207466a46a5651b7
|
0285fabe5934492dfed0a9cf67ba5650982a5f76
|
refs/heads/master
| 2021-06-05T10:32:55.651469
| 2021-05-20T03:36:22
| 2021-05-20T03:36:22
| 88,345,336
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,103
|
cpp
|
1417ex.cpp
|
#include <iostream>
#include <vector>
using namespace std;
struct Date {
string date;
Date& operator=(Date& d) { date = d.date; return *this; }
};
class CheckoutRecord {
public:
double get_bookId() { return book_id;}
void set_bookId(double id = 0.00) { book_id = id; }
void set_wait_list(pair<string, string>& wait);
CheckoutRecord& operator=(CheckoutRecord& cr);
pair<string, string>& operator[](const size_t);
const pair<string, string>& operator[](const size_t) const;
private:
double book_id;
string title;
Date date_borrowed;
Date date_due;
pair<string, string> borrower;
vector< pair<string, string>* > wait_list;
};
void CheckoutRecord::set_wait_list(pair<string, string> &wait)
{
auto *ppa = new pair<string, string>;
*ppa = wait;
wait_list.push_back(ppa);
}
CheckoutRecord& CheckoutRecord::operator=(CheckoutRecord& cr)
{
book_id = cr.book_id;
title = cr.title;
date_borrowed = cr.date_borrowed;
date_due = cr.date_due;
borrower = cr.borrower;
wait_list.clear();
for(auto it = wait_list.begin(); it != wait_list.end(); ++it){
auto *ppa = new pair<string, string>;
*ppa = **it;
wait_list.push_back(ppa);
}
return *this;
}
pair<string, string>& CheckoutRecord::operator[](const size_t index)
{
pair<string, string> spair;
pair<string, string>* sp = wait_list[index];
spair.first = sp->first;
spair.second = sp->second;
return spair;
}
const pair<string, string>& CheckoutRecord::operator[](const size_t index) const
{
pair<string, string> spair;
pair<string, string>* sp = wait_list[index];
spair.first = sp->first;
spair.second = sp->second;
return spair;
}
int main(void)
{
CheckoutRecord cra, crb;
pair<string, string> pa("abc","def");
pair<string, string> ret;
cra.set_bookId(100.01);
cra.set_wait_list(pa);
ret.first = cra[0].first;
ret.second = cra[0].second;
cout << ret.first << endl;
cout << ret.second << endl;
//crb = cra;
//cout << crb.get_bookId() << endl;
}
|
1cdb32f76555493d6d44c60b75ebb222497dd4a5
|
51bbc8724ff448bcda714e33b79022bb4a8caa22
|
/audioplay_sdl2.h
|
f6e8b95bcb3bf4626bc3d04bc27cef44df3a13cc
|
[] |
no_license
|
Imatch/ColorPlayer_CoWork
|
f9d39c59fb24e5588f40698439f0ce4d6f023ddc
|
ad223b071f4c60ed10a3326bc291161740ed69b9
|
refs/heads/master
| 2020-05-31T13:59:49.153474
| 2018-12-08T03:42:11
| 2018-12-08T03:42:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,317
|
h
|
audioplay_sdl2.h
|
#ifndef AUDIOPLAY_SDL2_H
#define AUDIOPLAY_SDL2_H
#include <QThread>
#include "colorplayer.h"
#include "messagequeue.h"
#include "masterclock.h"
#include "stdint.h"
#include <QMutex>
#include <QWaitCondition>
class SDL2AudioDisplayThread:public QThread
{
public:
static SDL2AudioDisplayThread *Get(void)
{
static SDL2AudioDisplayThread vt;
return &vt;
}
SDL2AudioDisplayThread();
void init();
void deinit();
void run();
void stop();
void flush();
void initPlayerInfo(PlayerInfo *pPI);
void initDisplayQueue(PlayerInfo *pPI);
void deinitDisplayQueue(PlayerInfo *pPI);
void initMasterClock(MasterClock * pMC);
void queueMessage(MessageCmd_t MsgCmd);
void setCallback(pFuncCallback callback);
void setMultiplePlay(float value);
virtual ~SDL2AudioDisplayThread();
PlayerInfo *player;
MasterClock * pMasterClock;
int bFirstFrame;
float volume;
pFuncCallback _funcCallback;
private:
PCMBuffer_t PCMBuffers[FRAME_QUEUE_SIZE];
message *pMessage;
int bStop;
int bInit;
int bFirstCallback;
float MultiplePlay = 1.0;
PCMBuffer_t *GetOneValidPCMBuffer();
QMutex mutex;
QWaitCondition WaitCondStopDone;
};
#endif // AUDIOPLAY_SDL2_H
|
bad02bf3e5e9db424d7d5ceeb6a9b80b9a03b310
|
66ce44bff21bf17fd1ad4fff402fe6042885488e
|
/Project 8/Book.h
|
9115c4b7cae714ccaee6a161cc36bd27e5402e20
|
[] |
no_license
|
KimiNoNawa1610/C-
|
09f31aa807e0b124d2b05a455ee71f1c8b75eeca
|
09445f1097bb560e6d3d1badce6ca0738cbb40d1
|
refs/heads/master
| 2023-02-05T10:27:37.276245
| 2020-12-21T04:50:49
| 2020-12-21T04:50:49
| 289,384,180
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 404
|
h
|
Book.h
|
/*
* Nhan Vo
* CECS 282-Lab 8
*/
#pragma once
#ifndef BOOK_H
#define BOOK_H
#include "publication.h"
#include "Sales.h"
/*
* Class Book definition
*/
class Book:public Publication, Sale {// Inherit Publication and Sale classes
public:
void getData();// get input from the user
void putData();// output the data of the Book object
private:
int pageCount;// number of page count of a book
};
#endif //
|
9ba44181b37c0b0d5bd28365122e4d88440bbbe5
|
1ca7266d80133e92f4025de746409337bcbc4b13
|
/anagrams.cpp
|
bd9525659918b4cd09d3645117e47c59eea9ccc4
|
[] |
no_license
|
inikhil/Competitive-Programming
|
23ca74b5f0ff2ac2bc73b3624850684926368d03
|
60c1aeecc953f7a5d08ada55989642dee4003b5c
|
refs/heads/master
| 2021-01-21T04:55:44.847041
| 2015-02-14T15:34:44
| 2015-02-14T15:34:44
| 30,800,260
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,036
|
cpp
|
anagrams.cpp
|
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<algorithm>
using namespace std;
void sw(char *x,char *y){
char temp;
temp = *x;
*x = *y;
*y= temp;
}
bool Match(char Str[],int i,int j)
{
if(i == j)
return false;
else
for(;i<j;i++)
if(Str[i]==Str[j])
return true;
return false;
}
void permute(char *s,int i,int n){
int j;
//cout<<"a";
if(i==n){
printf("%s\n",s);
}
else{
for(j=i;j<=n;j++){
//if(s[i]==s[j] && i!=j)
// continue;
if(!Match(s,i,j)){
sw(s+i,s+j);
permute(s,i+1,n);
sw(s+i,s+j);
}
}
}
}
int main(){
char s[100];
int n;cin>>n;
int i;
scanf("%s",s);
//permute(s,0,n-1);
sort(s,s+n);
do{
for(i=0;i<n;i++){cout<<s[i];}
cout<<"\n";
}while(next_permutation(s,s+n));
}
|
2d5f31813fe4bf1015cfc9373a0ff058117bd393
|
d6cdbf95ca197276053500e2f5e4fdc6fc2958b5
|
/test/testRollbackFMU.cpp
|
0803ce1a82d013d41b94be02ebca90dd01897b81
|
[
"BSD-2-Clause"
] |
permissive
|
qianqian121/fmipp
|
1f7fb52a2a7f92c54cbdc820016685d9c06db15e
|
38c309eae58c332b3d533dbdca7dd271a6e056d6
|
refs/heads/master
| 2020-05-18T09:32:40.720467
| 2016-10-19T15:52:10
| 2016-10-19T15:52:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,414
|
cpp
|
testRollbackFMU.cpp
|
// --------------------------------------------------------------
// Copyright (c) 2013, AIT Austrian Institute of Technology GmbH.
// All rights reserved. See file FMIPP_LICENSE for details.
// --------------------------------------------------------------
#include <import/utility/include/RollbackFMU.h>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE testRollbackFMU
#include <boost/test/unit_test.hpp>
#include <cmath>
#include <iostream>
BOOST_AUTO_TEST_CASE( test_fmu_load )
{
std::string MODELNAME( "zigzag" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
}
BOOST_AUTO_TEST_CASE( test_fmu_run_simulation_without_rollback )
{
std::string MODELNAME( "zigzag" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
fmiStatus status = fmu.instantiate( "zigzag1" );
BOOST_REQUIRE( status == fmiOK );
status = fmu.setValue( "k", 1.0 );
BOOST_REQUIRE( status == fmiOK );
status = fmu.initialize();
BOOST_REQUIRE( status == fmiOK );
fmiReal t = 0.0;
fmiReal stepsize = 0.0025;
fmiReal tstop = 1.0;
fmiReal x;
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
// with an eventsearchprecision of 1.0e-4, require the same accuracy for x.
BOOST_REQUIRE_MESSAGE( std::abs( x - 1.0 ) < 1e-4, "x = " << x );
}
BOOST_AUTO_TEST_CASE( test_fmu_run_simulation_with_rollback_1 )
{
std::string MODELNAME( "zigzag" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
fmiStatus status = fmu.instantiate( "zigzag1" );
BOOST_REQUIRE( status == fmiOK );
status = fmu.setValue( "k", 1.0 );
BOOST_REQUIRE( status == fmiOK );
status = fmu.initialize();
BOOST_REQUIRE( status == fmiOK );
fmiReal t = 0.0;
fmiReal stepsize = 0.025;
fmiReal tstop = 0.5;
fmiReal x;
// Integrate.
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
// Make integration step.
fmu.integrate( t + stepsize );
// Enforce rollback.
fmu.integrate( t + 0.5*stepsize );
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
// Check integration results.
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
BOOST_REQUIRE_MESSAGE( std::abs( x - 0.5 ) < 1e-6, "x = " << x );
}
BOOST_AUTO_TEST_CASE( test_fmu_run_simulation_with_rollback_2 )
{
std::string MODELNAME( "zigzag" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
fmiStatus status = fmu.instantiate( "zigzag1" );
BOOST_REQUIRE( status == fmiOK );
status = fmu.setValue( "k", 1.0 );
BOOST_REQUIRE( status == fmiOK );
status = fmu.initialize();
BOOST_REQUIRE( status == fmiOK );
fmiReal t = 0.0;
fmiReal stepsize = 0.0025;
fmiReal tstop = 0.5;
fmiReal x;
// Save initial state as rollback state.
fmu.saveCurrentStateForRollback();
// Integrate.
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
// Check integration results.
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
BOOST_REQUIRE_MESSAGE( std::abs( x - 0.5 ) < 1e-6, "x = " << x );
// Enforce rollback.
t = 0.0;
// Redo integration.
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
// Check integration results again.
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
BOOST_REQUIRE_MESSAGE( std::abs( x - 0.5 ) < 1e-6, "x = " << x );
}
BOOST_AUTO_TEST_CASE( test_fmu_run_simulation_without_rollback2 )
{
std::string MODELNAME( "zigzag2" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
fmiStatus status = fmu.instantiate( "zigzag21" );
BOOST_REQUIRE( status == fmiOK );
status = fmu.setValue( "k", 1.0 );
BOOST_REQUIRE( status == fmiOK );
status = fmu.initialize();
BOOST_REQUIRE( status == fmiOK );
fmiReal t = 0.0;
fmiReal stepsize = 0.0025;
fmiReal tstop = 1.0;
fmiReal x;
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
// with an eventsearchprecision of 1.0e-4, require the same accuracy for x.
BOOST_REQUIRE_MESSAGE( std::abs( x - 1.0 ) < 1e-4, "x = " << x );
}
BOOST_AUTO_TEST_CASE( test_fmu_run_simulation_with_rollback_11 )
{
std::string MODELNAME( "zigzag2" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
fmiStatus status = fmu.instantiate( "zigzag1" );
BOOST_REQUIRE( status == fmiOK );
status = fmu.setValue( "k", 1.0 );
BOOST_REQUIRE( status == fmiOK );
status = fmu.initialize();
BOOST_REQUIRE( status == fmiOK );
fmiReal t = 0.0;
fmiReal stepsize = 0.025;
fmiReal tstop = 0.5;
fmiReal x;
// Integrate.
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
// Make integration step.
fmu.integrate( t + stepsize );
// Enforce rollback.
fmu.integrate( t + 0.5*stepsize );
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
// Check integration results.
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
BOOST_REQUIRE_MESSAGE( std::abs( x - 0.5 ) < 1e-6, "x = " << x );
}
BOOST_AUTO_TEST_CASE( test_fmu_run_simulation_with_rollback_21 )
{
std::string MODELNAME( "zigzag2" );
RollbackFMU fmu( FMU_URI_PRE + MODELNAME, MODELNAME );
fmiStatus status = fmu.instantiate( "zigzag1" );
BOOST_REQUIRE( status == fmiOK );
status = fmu.setValue( "k", 1.0 );
BOOST_REQUIRE( status == fmiOK );
status = fmu.initialize();
BOOST_REQUIRE( status == fmiOK );
fmiReal t = 0.0;
fmiReal stepsize = 0.0025;
fmiReal tstop = 0.5;
fmiReal x;
// Save initial state as rollback state.
fmu.saveCurrentStateForRollback();
// Integrate.
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
// Check integration results.
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
BOOST_REQUIRE_MESSAGE( std::abs( x - 0.5 ) < 1e-6, "x = " << x );
// Enforce rollback.
t = 0.0;
// Redo integration.
while ( ( t + stepsize ) - tstop < EPS_TIME ) {
t = fmu.integrate( t + stepsize );
status = fmu.getValue( "x", x );
}
// Check integration results again.
t = fmu.getTime();
BOOST_REQUIRE_MESSAGE( std::abs( t - tstop ) < stepsize/2, "t = " << t );
status = fmu.getValue( "x", x );
BOOST_REQUIRE_MESSAGE( status == fmiOK, "status = " << status );
BOOST_REQUIRE_MESSAGE( std::abs( x - 0.5 ) < 1e-6, "x = " << x );
}
|
e96b75919de91cbb109291a8dd0857b489c54024
|
56bd544d88f3765efd25afb505476ca2af268726
|
/src/Entities/Bonus.cpp
|
b1ae1af6ec3335c348f857850f0b9205e969175f
|
[
"MIT"
] |
permissive
|
skwee357/TankSmasher
|
5c3945f8d782561cbf4745f5e75d99fc88eefb57
|
6afccb33aeb19e32a6dd26e3d91a7f1e416e7a77
|
refs/heads/master
| 2020-12-25T19:03:50.000651
| 2013-08-30T11:29:15
| 2013-08-30T11:29:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 929
|
cpp
|
Bonus.cpp
|
#include "Entities/Bonus.hpp"
#include "TankSmasherException.hpp"
#include "Game.hpp"
Bonus::Bonus(int type, int px, int py){
int left;
mType = type;
switch(type){
case TYPE_UPGRADE_WEAPON:
left = 0;
break;
case TYPE_1UP:
left = WIDHT;
break;
case TYPE_GRANADE:
left = 2 * WIDHT;
break;
default:
throw TankSmasherException("Invalid bonus type!");
}
mSprite.SetImage(*GetGlobalContext().imageManager->Get("bonus.png"));
mSprite.SetPosition(static_cast<float>(px), static_cast<float>(py));
mSprite.SetCenter(WIDHT / 2, HEIGHT / 2);
mSprite.SetSubRect(sf::IntRect(left, 0, left + WIDHT, HEIGHT));
}
int Bonus::GetRandomBonusType(){
int r = ::rand() % 50;
if(r >= 0 && r <= 30) return TYPE_NONE;
else if(r > 30 && r <= 35) return TYPE_UPGRADE_WEAPON;
else if(r > 35 && r <= 40) return TYPE_1UP;
else if(r > 40 && r <= 50) return TYPE_GRANADE;
return TYPE_NONE;
}
|
ef82e3720476258eb98176992c44a4ebb750cab6
|
7f258bdc8805984aa7444c853bce70d11c85dd69
|
/CronExpressionParser/include/CronExpression.h
|
0f7b23e550b8cb3ce1e213f6e7c14036671ac7b7
|
[] |
no_license
|
DenisPryt/Cron
|
0d2ec2b30c490101588900c0c5baeeea240083b7
|
2f36726b2769dce46a48e3d4e953d34fd21a58e0
|
refs/heads/master
| 2020-03-09T18:50:38.203734
| 2018-05-14T13:06:17
| 2018-05-14T13:06:17
| 128,942,544
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 690
|
h
|
CronExpression.h
|
#pragma once
#include "CronSheduleMasks.h"
#include <string_view>
#include <chrono>
namespace Cron
{
class Expression
{
public:
Expression() = default;
Expression(Expression&&) = default;
Expression(const Expression&) = default;
Expression& operator=(Expression&&) = default;
Expression& operator=(const Expression&) = default;
static Expression ParseCronExpression(const std::string_view& cronExpr);
std::chrono::system_clock::time_point NextTime(const std::chrono::system_clock::time_point& from);
std::chrono::system_clock::time_point PrevTime(const std::chrono::system_clock::time_point& from);
bool IsEmpty() const noexcept;
private:
SheduleMasks m_masks;
};
}
|
dee67ceaf2600826ae77f3e4f1cb47cff32ba163
|
b2b23771e540ab459eb1ab20c32a9238ae4535e8
|
/SlidingWindow/main.cpp
|
e6212f53c03302951829e0bb360e12bf8ea91d88
|
[] |
no_license
|
rsghotra/JUL_2021_DSA
|
8485de6585b074de68e8f424c650f035ef73b892
|
d5298e4353f14cc4a907c84f801c31cdf514a013
|
refs/heads/master
| 2023-08-16T22:55:44.005874
| 2021-09-19T18:42:32
| 2021-09-19T18:42:32
| 382,127,300
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 514
|
cpp
|
main.cpp
|
#include "SlidingWindow.h"
#include<iostream>
using namespace std;
int main () {
SlidingWindow::KSumAverage();
SlidingWindow::KMaxSum();
SlidingWindow::MinSizeSubArraySum();
SlidingWindow::LongestSubstringWithKDistinctChars();
SlidingWindow::FruitBasket();
SlidingWindow::NoRepeatSubstringMaxLength();
SlidingWindow::KCharacterReplacements();
SlidingWindow::LongestSubstringReplaceOnes();
SlidingWindow::PermutationExists();
SlidingWindow::StringAnagrams();
SlidingWindow::FindSubstring();
return 0;
}
|
508ad49a1ef0c3ccc39d4f300d15355d5c9a92e6
|
414b5914bc064ac22af52fa3d0b38981c6e53e1e
|
/app/src/main/cpp/Fluid.cpp
|
8f5975f17f6418c5ea0294dec899906909d7872a
|
[] |
no_license
|
gwenyu517/CIS4914_SeniorProject
|
a6706a5b61b8f9c55bce47bdcbd7fc3926e37b80
|
c71a426aad1b0b561b40c2a5004fdfe980122d73
|
refs/heads/master
| 2020-05-04T14:48:10.906133
| 2019-05-28T22:15:00
| 2019-05-28T22:15:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,125
|
cpp
|
Fluid.cpp
|
#include "Fluid.h"
static const int iter = 20;
Fluid::Fluid(GLfloat viscosity, GLfloat diffRate, int width, int height, int dH) {
this->viscosity = viscosity;
this->diffRate = diffRate;
this->W = width+2;
this->H = height+2;
this->dH = dH;
setupGrid();
}
Fluid::~Fluid() {
free(sForce->x);
free(sForce->y);
free(sForce);
free(sDensity);
free(u0->x);
free(u0->y);
free(u0);
free(u1->x);
free(u1->y);
free(u1);
free(s0);
free(s1);
}
void Fluid::updateVelocity(long dt) {
int i = (int)100 / dH;
int j = (int)100 / dH;
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER velocity was, %g", u1->y[index(i+1,j+1)]);
addSource(u1->x, sForce->x);
addSource(u1->y, sForce->y);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER velocity added to, %g", u1->y[index(i+1,j+1)]);
diffuse(u1->x, u0->x, viscosity, dt, 0);
diffuse(u1->y, u0->y, viscosity, dt, 1);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER velocity diffuse to, %g", u0->y[index(i+1,j+1)]);
project(u0, u1);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER velocity projected to, %g", u1->y[index(i+1,j+1)]);
advect(u1->x, u0->x, u1->x, u1->y, dt, 0);
advect(u1->y, u0->y, u1->x, u1->y, dt, 1);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER velocity advect to, %g", u0->y[index(i+1,j+1)]);
project(u0, u1);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER velocity should now be, %g", u1->y[index(i+1,j+1)]);
}
void Fluid::updateDensity(long dt) {
int i = (int)100 / dH;
int j = (int)100 / dH;
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER density was, %g", s1[index(i+1,j+1)]);
addSource(s1, sDensity);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER density added to, %g", s1[index(i+1,j+1)]);
diffuse(s1, s0, diffRate, dt, 0);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER density diffuse to, %g", s0[index(i+1,j+1)]);
advect(s0, s1, u1->x, u1->y, dt, 0);
//__android_log_print(ANDROID_LOG_DEBUG, "UPDATE", "-SOLVER density advect to, %g", s1[index(i+1,j+1)]);
}
void Fluid::addForce(int i, int j, GLfloat amountX, GLfloat amountY, GLfloat size) {
//__android_log_print(ANDROID_LOG_DEBUG, "addF", "was %g", sForce->y[index(i+1,j+1)]);
//__android_log_print(ANDROID_LOG_DEBUG, "addF", "add %g", amountY);
//sForce->x[index(i+1,j+1)] += amountX * 0.1;
//sForce->y[index(i+1,j+1)] += amountY * 0.1;
//amountX = amountX*0.1;
//amountY = amountY*0.1;
int radius = (int)(size * 100) / 2;
if (radius < 1){
sForce->x[index(i+1, j+1)] += amountX;
sForce->y[index(i+1, j+1)] += amountY;
//radius = 1;
return;
}
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "welp! %d", radius);
int pX, pY;
for (int x = -radius; x <= radius; x++) {
for (int y = -radius; y <= radius; y++) {
pX = i + 1 + x;
pY = j + 1 + y;
if (pX < 1)
pX = 1;
else if (pX > W - 2)
pX = W - 2;
if (pY < 1)
pY = 1;
else if (pY > H - 2)
pY = H - 2;
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "try pX*pX = %d, py*py = %d, radius*radius = %d", pX*pX, pY*pY, radius*radius);
if (x*x + y*y <= 0.5*radius*radius){
sForce->x[index(pX, pY)] += amountX;
sForce->y[index(pX, pY)] += amountY;
}
else if (x*x + y*y <= radius*radius) {
sForce->x[index(pX, pY)] += amountX / (x*x + y*y);
sForce->y[index(pX, pY)] += amountY / (x*x + y*y);
}
//__android_log_print(ANDROID_LOG_DEBUG, "addF", "is %g", sDensity[index(pX,pY)]);
//__android_log_print(ANDROID_LOG_DEBUG, "addF", "__________________________________");
}
}
//__android_log_print(ANDROID_LOG_DEBUG, "addF", "is %g", sForce->y[index(i+1,j+1)]);
//__android_log_print(ANDROID_LOG_DEBUG, "addF", "__________________________");
}
void Fluid::addDensity(int i, int j, GLfloat amount, GLfloat size) {
//sDensity[index(i+1,j+1)] += amount;
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "size = %g", size);
//amount = 255.0f + 1.0f / size;
int radius = (int)(size * 100) / 2;
if (radius < 1)
radius = 1;
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "welp! %d", radius);
int pX, pY;
for (int x = -radius; x <= radius; x++) {
for (int y = -radius; y <= radius; y++) {
pX = i + 1 + x;
pY = j + 1 + y;
if (pX < 1)
pX = 1;
else if (pX > W - 2)
pX = W - 2;
if (pY < 1)
pY = 1;
else if (pY > H - 2)
pY = H - 2;
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "try %g / (%d*%d + %d*%d) = %g", amount, x, x, y, y, amount / (x*x + y*y));
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "try pX*pX = %d, py*py = %d, radius*radius = %d", pX*pX, pY*pY, radius*radius);
if (x*x + y*y <= 0.7*radius*radius)
sDensity[index(pX, pY)] += amount;
else if (x*x + y*y <= radius*radius)
sDensity[index(pX, pY)] += amount / (x*x + y*y);
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "is %g", sDensity[index(pX,pY)]);
//__android_log_print(ANDROID_LOG_DEBUG, "addD", "__________________________________");
}
}
}
void Fluid::addGravity(GLfloat gx, GLfloat gy) {
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
sForce->x[index(i,j)] += gx;
sForce->y[index(i,j)] += gy;
}
}
}
void Fluid::reset() {
zeroFields();
}
GLfloat Fluid::densityAt(int i, int j) {
return s1[index(i+1,j+1)];
}
GLfloat Fluid::velocityAt(int i, int j) {
return u1->y[index(i+1,j+1)];
}
// ------ PRIVATE ------
void Fluid::setupGrid() {
allocateMemory();
zeroFields();
}
void Fluid::allocateMemory() {
sForce = (vectorField*)malloc(sizeof(vectorField));
sForce->x = (GLfloat*)malloc(W*H*sizeof(GLfloat));
sForce->y = (GLfloat*)malloc(W*H*sizeof(GLfloat));
sDensity = (GLfloat*)malloc(W*H*sizeof(GLfloat));
u0 = (vectorField*)malloc(sizeof(vectorField));
u0->x = (GLfloat*)malloc(W*H*sizeof(GLfloat));
u0->y = (GLfloat*)malloc(W*H*sizeof(GLfloat));
u1 = (vectorField*)malloc(sizeof(vectorField));
u1->x = (GLfloat*)malloc(W*H*sizeof(GLfloat));
u1->y = (GLfloat*)malloc(W*H*sizeof(GLfloat));
s0 = (GLfloat*)malloc(W*H*sizeof(GLfloat));
s1 = (GLfloat*)malloc(W*H*sizeof(GLfloat));
}
void Fluid::zeroFields() {
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
sForce->x[index(i,j)] = 0;
sForce->y[index(i,j)] = 0;
sDensity[index(i,j)] = 0;
u0->x[index(i,j)] = 0;
u0->y[index(i,j)] = 0;
u1->x[index(i,j)] = 0;
u1->y[index(i,j)] = 0;
s0[index(i,j)] = 0;
s1[index(i,j)] = 0;
}
}
}
int Fluid::index(int i, int j) {
return j*W + i;
}
void Fluid::addSource(GLfloat* u, GLfloat* source) {
for (int i = 0; i < W; i++) {
for (int j = 0; j < H; j++) {
u[index(i,j)] += source[index(i,j)];
source[index(i,j)] = 0;
}
}
}
void Fluid::diffuse(GLfloat* u0, GLfloat* u1, GLfloat v, long dt, int t) {
GLfloat a = v*dt / (dH*dH);
for (int m = 0; m < iter; m++){
for (int i = 1; i < W - 1; i++) {
for (int j = 1; j < H - 1; j++) {
u1[index(i,j)] = (u0[index(i,j)] - a*(u1[index(i-1,j)] + u1[index(i+1,j)]
+ u0[index(i,j-1)] + u0[index(i,j+1)])) / (1 + 4*a);
}
}
setBoundary(u1, t);
}
}
void Fluid::advect(GLfloat *u0, GLfloat *u1, GLfloat *x, GLfloat *y, long dt, int t) {
GLfloat posX, posY;
GLfloat posX0, posY0;
GLint c_posX0, c_posY0;
GLint c_posX1, c_posY1;
GLfloat x0, x1;
GLfloat y0, y1;
for (int i = 1; i < W - 1; i++) {
for (int j = 1; j < H - 1; j++) {
posX0 = i - dt*x[index(i,j)]/dH;
posY0 = j - dt*y[index(i,j)]/dH;
if (posX0 < 0.5)
posX0 = 0.5;
if (posX0 > W - 1.5)
posX0 = W - 1.5f;
if (posY0 < 0.5)
posY0 = 0.5;
if (posY0 > H - 1.5)
posY0 = H - 1.5f;
/*
if (posX0 < 0)
posX0 = 0;
if (posX0 > W - 1)
posX0 = W - 2;
if (posY0 < 0)
posY0 = 0;
if (posY0 > H - 1)
posY0 = H - 2;
*/
c_posX0 = (int)posX0;
c_posX1 = c_posX0 + 1;
c_posY0 = (int)posY0;
c_posY1 = c_posY0 + 1;
x0 = posX0 - c_posX0;
x1 = 1 - x0;
y0 = posY0 - c_posY0;
y1 = 1 - y0;
u1[index(i,j)] = x1*(y1*u0[index(c_posX0,c_posY0)]+y0*u0[index(c_posX0,c_posY1)])
+ x0*(y1*u0[index(c_posX1,c_posY0)]+y0*u0[index(c_posX1,c_posY1)]);
}
}
setBoundary(u1, t);
}
void Fluid::project(vectorField *u0, vectorField *u1) {
GLfloat* divU0 = (GLfloat*)malloc(W*H*sizeof(GLfloat));
GLfloat* q = (GLfloat*)malloc(W*H*sizeof(GLfloat));
for (int i = 1; i < W - 1; i++) {
for (int j = 1; j < H - 1; j++) {
divU0[index(i,j)] = 0.5f*dH*(u0->x[index(i+1,j)] - u0->x[index(i-1,j)]
+ u0->y[index(i,j+1)] - u0->y[index(i,j-1)]);
q[index(i,j)] = 0;
}
}
setBoundary(divU0, 2);
setBoundary(q, 2);
for (int m = 0; m < iter; m++) {
for (int i = 1; i < W - 1; i++) {
for (int j = 1; j < H - 1; j++) {
q[index(i,j)] = (q[index(i-1,j)] + q[index(i+1,j)]
+ q[index(i,j-1)] + q[index(i,j+1)] - divU0[index(i,j)]) / 4;
}
}
setBoundary(q, 2);
}
for (int i = 1; i < W - 1; i++) {
for (int j = 1; j < H - 1; j++) {
u1->x[index(i,j)] = u0->x[index(i,j)] - 0.5f*(q[index(i+1,j)] - q[index(i-1,j)])/dH;
u1->y[index(i,j)] = u0->y[index(i,j)] - 0.5f*(q[index(i,j+1)] - q[index(i,j-1)])/dH;
}
}
setBoundary(u1->x, 0);
setBoundary(u1->y, 1);
free(divU0);
free(q);
}
void Fluid::setBoundary(GLfloat *f, int fieldType) {
// vertical sides
for (int j = 1; j < H - 2; j++) {
switch(fieldType){
case 0: // x field
f[index(0, j)] = -f[index(1,j)];
f[index(W-1,j)] = -f[index(W-2,j)];
break;
case 1: // y field
f[index(0,j)] = f[index(1,j)];
f[index(W-1,j)] = f[index(W-2,j)];
break;
case 2: // scalar
f[index(0,j)] = f[index(1,j)];
f[index(W-1,j)] = f[index(W-2,j)];
}
}
// horizontal sides
for (int i = 1; i < W - 1; i++) {
switch(fieldType){
case 0: // x field
f[index(i,0)] = f[index(i,1)];
f[index(i,H-1)] = f[index(i,H-2)];
break;
case 1: // y field
f[index(i,0)] = -f[index(i,1)];
f[index(i,H-1)] = -f[index(i,H-2)];
break;
case 2: // scalar
f[index(i,0)] = f[index(i,1)];
f[index(i,H-1)] = f[index(i,H-2)];
}
}
f[index(0, 0)] = 0.5f * (f[index(0,1)] + f[index(1,0)]);
f[index(W-1, 0)] = 0.5f * (f[index(W-1,1)] + f[index(W-2,0)]);
f[index(W-1, H-1)] = 0.5f * (f[index(W-1,H-2)] + f[index(W-2,H-1)]);
f[index(0, H-1)] = 0.5f * (f[index(0, H-2)] + f[index(1,H-1)]);
}
|
539370c2fa00d22cf5e79a87cc8fa2be904e3481
|
e5720f95696653b496e5f927eac7492bfb9f132c
|
/lcof/lcof_025/cpp_025/Solution2.h
|
a0ebbdd39d36675720da4081f6fac3ccddc5d3a3
|
[
"MIT"
] |
permissive
|
ooooo-youwillsee/leetcode
|
818cca3dd1fd07caf186ab6d41fb8c44f6cc9bdc
|
2cabb7e3e2465e33e4c96f0ad363cf6ce6976288
|
refs/heads/master
| 2022-05-24T15:37:19.652999
| 2022-05-15T01:25:31
| 2022-05-15T01:25:31
| 218,205,693
| 12
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 513
|
h
|
Solution2.h
|
//
// Created by ooooo on 2020/3/16.
//
#ifndef CPP_025__SOLUTION2_H_
#define CPP_025__SOLUTION2_H_
#include "ListNode.h"
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if (!l1) return l2;
if (!l2) return l1;
ListNode * ans = nullptr;
if (l1->val <= l2->val) {
ans = l1;
ans->next = mergeTwoLists(l1->next, l2);
}else {
ans = l2;
ans->next = mergeTwoLists(l1, l2->next);
}
return ans;
}
};
#endif //CPP_025__SOLUTION2_H_
|
30e7265d758ea42934963709f77568cdc356d81e
|
53aecc4b8d646d6df2387fc30c2821d588c9520a
|
/test/temp_buffer/catch_temp_buffer.cpp
|
91c0b37706b496d771f7580e3eb7c993bba49576
|
[
"MIT"
] |
permissive
|
Chronimal/utl
|
8ecb074a379df06c98cddc53d8bad00e1ed78c78
|
a22c4b984e3452242ba6c1dde637d4a2b24b44c4
|
refs/heads/master
| 2023-03-14T15:55:56.791890
| 2021-04-02T06:16:02
| 2021-04-02T06:16:02
| 264,489,215
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,418
|
cpp
|
catch_temp_buffer.cpp
|
//
// Test harnesses for TempBuffer<L>
//
// Copyright(c) 2020 Chronimal. All rights reserved.
//
// Licensed under the MIT license; A copy of the license that can be
// found in the LICENSE file.
//
#define CATCH_CONFIG_MAIN
#include "temp_buffer.hpp"
#include "catch.hpp"
using namespace TB_NAMESPACE_NAME;
TEST_CASE("utl.temp_buffer. Stack only allocation")
{
SECTION("Default constructed TempBuffer")
{
TempBuffer<100> buffer;
REQUIRE(buffer.empty());
REQUIRE(buffer.size() == 0);
REQUIRE_FALSE(buffer.dynamic());
}
SECTION("Allocate a 100 bytes TempBuffer")
{
TempBuffer<100> buffer{100};
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == 100);
REQUIRE_FALSE(buffer.dynamic());
}
SECTION("Allocate a 100 bytes TempBuffer on the stack filled with 0xff bytes")
{
constexpr int pattern{0xc0};
constexpr std::size_t size = 100;
TempBuffer<size> buffer{size, pattern};
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == size);
REQUIRE_FALSE(buffer.dynamic());
auto p = buffer.as<std::byte const>();
REQUIRE(std::all_of(p, p + size, [&](auto v) { return v == static_cast<std::byte>(pattern); }));
}
}
TEST_CASE("utl.temp_buffer. Heap only allocation")
{
SECTION("Allocate 100 bytes on the heap")
{
TempBuffer<1> buffer{100};
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == 100);
REQUIRE(buffer.dynamic());
}
SECTION("Allocate a 100 bytes TempBuffer on the heap filled with 0xff bytes")
{
constexpr int pattern{0xc0};
constexpr std::size_t size = 100;
TempBuffer<size - 1> buffer{size, pattern};
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == size);
REQUIRE(buffer.dynamic());
auto p = buffer.as<std::byte const>();
REQUIRE(std::all_of(p, p + size, [&](auto v) { return v == static_cast<std::byte>(pattern); }));
}
}
TEST_CASE("utl.temp_buffer. Resizing")
{
constexpr int pattern{0xc0};
constexpr std::size_t size = 100;
TempBuffer<size - 1> buffer;
REQUIRE(buffer.empty());
REQUIRE(buffer.size() == 0);
REQUIRE_FALSE(buffer.dynamic());
buffer.resize(size);
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == size);
REQUIRE(buffer.dynamic());
auto p = buffer.as<std::byte>();
std::fill_n(p, size, static_cast<std::byte>(pattern));
REQUIRE(std::all_of(p, p + size, [&](auto v) { return v == static_cast<std::byte>(pattern); }));
constexpr std::size_t halfSize = size / 2;
buffer.resize(halfSize);
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == halfSize);
REQUIRE_FALSE(buffer.dynamic());
p = buffer.as<std::byte>();
std::fill_n(p, halfSize, static_cast<std::byte>(pattern - 1));
REQUIRE(std::all_of(p, p + halfSize, [&](auto v) { return v == static_cast<std::byte>(pattern - 1); }));
constexpr std::size_t doubleSize = size * 2;
buffer.resize(doubleSize);
REQUIRE_FALSE(buffer.empty());
REQUIRE(buffer.size() == doubleSize);
REQUIRE(buffer.dynamic());
p = buffer.as<std::byte>();
std::fill_n(p, doubleSize, static_cast<std::byte>(pattern + 1));
REQUIRE(std::all_of(p, p + doubleSize, [&](auto v) { return v == static_cast<std::byte>(pattern + 1); }));
}
|
e2e470b247c33384798d51c6b76d370cfe86315c
|
475b62e84674e1a4f2f92bdcf311a5d6eb7f76fe
|
/nibbler_core/header/Exception.hpp
|
1823d14fd27db53899d26ffdaf93c1dbde9fd97d
|
[] |
no_license
|
alatyshe/nibbler
|
c67b534ac1be5d30514bd15f9fe21c696377f389
|
ae788bff9eb9151e71cbe04b15a849c646225e21
|
refs/heads/master
| 2021-03-24T12:15:11.501144
| 2019-03-30T17:30:37
| 2019-03-30T17:30:37
| 119,737,791
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 384
|
hpp
|
Exception.hpp
|
#pragma once
# include <exception>
# include <string>
# include <sstream>
class Exception: public std::exception {
private:
std::string _error;
const Exception& operator=(const Exception &);
public:
Exception(void);
Exception(const Exception &src);
Exception(std::string const &error);
~Exception(void) throw();
char const *what(void) const throw();
};
|
dbff00311f8db99adcd17f61a2a1c128d43032eb
|
412b4c2a33d8ca5554fd607e07cee620cea9b463
|
/rmath/matrix/rsparsevector.h
|
c206a3f32c03efd272d711773a265ee2fbd03c2e
|
[] |
no_license
|
pfrancq/r
|
65df093d7cd31f4e5c521eadd61a54cb8da58925
|
bd78f3b2da3b357ca5d21e6055f809c83b488cd5
|
refs/heads/main
| 2023-08-17T09:01:37.815379
| 2021-10-04T06:15:01
| 2021-10-04T06:15:01
| 404,758,905
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,468
|
h
|
rsparsevector.h
|
/*
R Project Library
RSparseVector.h
Sparse Vector - Header.
Copyright 2005-2015 by Pascal Francq (pascal@francq.info).
Copyright 2003-2005 by Valery Vandaele.
Copyright 2003-2008 by the Université Libre de Bruxelles (ULB).
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2.0 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library, as a file COPYING.LIB; if not, write
to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
//-----------------------------------------------------------------------------
#ifndef RSparseVector_H
#define RSparseVector_H
//-----------------------------------------------------------------------------
// include file for R Project
#include <rvalue.h>
#include <rcontainer.h>
#include <rcursor.h>
//-----------------------------------------------------------------------------
namespace R{
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
* The RSparseVector provides a representation for a sparse vector. The vector
* is coded as a container of RValue. An identifier can be associate to the
* vector (this feature is used by RSparseMatrix).
*
* Here is an example of code:
* @code
* RSparseVector a(3);
* a[0]=1.0;
* a[5]=2.0;
* a[15]=3.0;
* for(size_t i=0;i<16;i++)
* cout<<static_cast<const RSparseVector&>(b)[i]<<endl;
* @endcode
* An important aspect is the use of static_cast<const RSparseVector&> to ensure
* the call of the const version of the operator(). If static_cast<const RSparseVector&>
* is not used, the different elements are created with uninitialized values.
* @short Sparse Vector.
*/
class RSparseVector : public RContainer<RValue,true,true>
{
private:
/**
* Identifier of the vector (used by RSparseMatrix).
*/
size_t Id;
public:
/**
* Construct a sparse vector.
* @param size Initial maximal size of the vector.
* @param id Identifier of the vector (cNoRef by default).
*/
RSparseVector(size_t size,size_t id=cNoRef);
/**
* Copy constructor.
* @param vec Sparse Vector used as source.
*/
RSparseVector(const RSparseVector& vec);
/**
* The assignment operator.
* @param vec Sparse Vector used as source.
*/
RSparseVector& operator=(const RSparseVector& vec);
/**
* Compare the identifiers of two sparse vectors.
* param vec Sparse vector to compared with.
*/
int Compare(const RSparseVector& vec) const;
/**
* Compare the identifier of the sparse vector with a given identifier.
* param id Identifier to compare with.
*/
int Compare(size_t id) const;
/**
* Set a given value to all the existing elements.
* @param val Value to set.
*/
void SetExistingElements(double val);
/**
* Return the value at position i. The first value is at position 0.
* @param i Index.
*/
double operator[](size_t i) const;
/**
* Return the value at position i. The first value is at position 0.
* @param i Index.
*/
double& operator[](size_t i);
/**
* Verify if a given index has a value defined in the vector.
* @param i Index.
* @return true or false.
*/
bool IsIn(size_t i) const {return(RContainer<RValue,true,true>::IsIn(i));}
/**
* Get a pointer over the value at a given index.
* @param i Index.
* @return Pointer or null if the index hasn't no value.
*/
const RValue* GetValue(size_t i) const {return(RContainer<RValue,true,true>::GetPtr(i));}
/**
* Get the identifier of the cell.
* @return Identifier of the cell.
*/
size_t GetId(void) const {return(Id);}
/**
* Destruct the sparse vector.
*/
~RSparseVector(void);
friend class RSparseMatrix;
};
} //-------- End of namespace R ----------------------------------------------
//-----------------------------------------------------------------------------
#endif
|
1144e35b84924b5d500b4e83a607b92ee23c0adc
|
5d1009c910c78eab434559c1c8fcd58fdc0a6adf
|
/HN_XML/HN_Xml.hpp
|
f2d3305c8a536bf913fcd40d72ae82393c333b73
|
[
"MIT"
] |
permissive
|
Jusdetalent/JT_Network
|
b4180709f0d88f5341b2a9282a19cd3c44a4a848
|
9af82a158be0fea1dbe2bcbc32bfac5ab54cdeba
|
refs/heads/master
| 2020-07-01T09:52:40.123704
| 2019-08-31T18:30:18
| 2019-08-31T18:30:18
| 201,134,804
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 195
|
hpp
|
HN_Xml.hpp
|
#ifndef HN_XML_HPP_INCLUDED
#define HN_XML_HPP_INCLUDED
// Include node reader
#include "HN_Node/HN_FNode.hpp"
#include "HN_Node/HN_SNode.hpp"
#endif // HN_XML_HPP_INCLUDED
|
bd401b554229371aac1b75c21dab15f7fecac4fe
|
6c02e9419c6cbb1f2992e4cbb3235430eff67dda
|
/SyntaxChecker.cpp
|
0d416d72819c9924030861869bcf5be03923bddc
|
[] |
no_license
|
jmcg213/Assignment3
|
3c24c309c86df6ef23a49f16e67dcb758ffac9c8
|
978350ca123c54aaf56e01745950d9757a23a226
|
refs/heads/master
| 2020-04-01T00:36:43.187995
| 2018-10-12T06:35:31
| 2018-10-12T06:35:31
| 152,704,688
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,821
|
cpp
|
SyntaxChecker.cpp
|
#include "SyntaxChecker.h"
#include "GenStack.h"
#include <fstream>
using namespace std;
SyntaxChecker::SyntaxChecker()
{
lineCount = 1;
foundError = false;
stack = new GenStack<char>(); //initializing new stack
}
SyntaxChecker::~SyntaxChecker()
{
delete stack;
}
//Reads in input file and checks for syntax errors
void SyntaxChecker::ReadInputFile(string fileName)
{
char checker = '\0'; //holds gs.pop()
GenStack<char> gs;
ifstream input(fileName);
if(input.fail()) //checking if input file exsists
{
cout<<"Invalid file path. Please compile again with a correct file."<<endl;
}
else
{
string line;
while(getline(input, line)) //iterates line by line
{
for(char& curChar : line) //iterates by character in that line
{
if(curChar == '{' || curChar == '[' || curChar == '(')
{
gs.push(curChar);
}
if(curChar == '}')
{
checker = gs.pop();
if(checker == '{')
{
//continue
}
if(checker == '(')
{
cout<<"Found } in line " << lineCount << ". Expected )" << endl;
foundError = true;
}
if(checker == '[')
{
cout<<"Found } in line " << lineCount << ". Expected ]" << endl;
foundError = true;
}
}
if(curChar == ']')
{
checker = gs.pop();
if(checker == '{')
{
cout<<"Found ] in line " << lineCount << ". Expected }" << endl;
foundError = true;
}
if(checker == '(')
{
cout<<"Found ] in line " << lineCount << ". Expected )" << endl;
foundError = true;
}
if(checker == '[')
{
//continue
}
}
if(curChar == ')')
{
checker = gs.pop();
if(checker == '{')
{
cout<<"Found ) in line " << lineCount << ". Expected }" << endl;
foundError = true;
}
if(checker == '(')
{
//continue
}
if(checker == '[')
{
cout<<"Found ) in line " << lineCount << ". Expected ]" << endl;
foundError = true;
}
}
}
lineCount++;
}
if(!foundError)
{
cout<<"No errors were found in the file."<<endl;
}
NextFile();
}
}
//checking if the user wants to input another file
void SyntaxChecker::NextFile()
{
string input;
string fileName;
cout<<"Would you like to input another file (y/n): "<<endl;
cin>>input;
if(input == "y")
{
cout<<"Please enter file name: "<<endl;
cin>>fileName;
ReadInputFile(fileName);
}
else
{
cout<<"Exiting program"<<endl;
}
}
|
d4c74585527fabd17a238a3e7b69a4cce8197b5c
|
f51689603d55891be26c4d628011d64e1379b730
|
/ModelFitting/Optimizer.h
|
75e2092e9133d180dc9e64a3b296b65e7825d680
|
[] |
no_license
|
gewirtz/APC_FinalProject
|
cb3b52d3316689a363b09af1968256a25a505248
|
7baea5accac77421d7aec31969395a0cf07bf078
|
refs/heads/master
| 2021-01-20T10:30:46.591062
| 2017-01-16T22:16:43
| 2017-01-16T22:16:43
| 74,398,491
| 2
| 0
| null | 2017-01-09T17:35:02
| 2016-11-21T19:29:05
|
C++
|
UTF-8
|
C++
| false
| false
| 345
|
h
|
Optimizer.h
|
/* Author : Chase Perlen and Ariel Gewirtz */
#ifndef OPTIMIZER_H_
#define OPTIMIZER_H_
class Model;
class KNN;
class GradientModel;
class Optimizer {
public:
virtual ~Optimizer() {}
virtual void fitParams(Model *m) = 0;
virtual void fitParams(KNN *m) = 0;
virtual void fitParams(GradientModel *m) = 0;
};
#endif // OPTIMIZER_H_
|
2d5673202485e1dc9da79d3ece1b0137d9cd3132
|
e018d8a71360d3a05cba3742b0f21ada405de898
|
/Client/Packet/Gpackets/GCSystemMessageHandler.cpp
|
cff2441da45f787cb22db7935cc2bae5ea51757b
|
[] |
no_license
|
opendarkeden/client
|
33f2c7e74628a793087a08307e50161ade6f4a51
|
321b680fad81d52baf65ea7eb3beeb91176c15f4
|
refs/heads/master
| 2022-11-28T08:41:15.782324
| 2022-11-26T13:21:22
| 2022-11-26T13:21:22
| 42,562,963
| 24
| 18
| null | 2022-11-26T13:21:23
| 2015-09-16T03:43:01
|
C++
|
UHC
|
C++
| false
| false
| 4,739
|
cpp
|
GCSystemMessageHandler.cpp
|
//////////////////////////////////////////////////////////////////////
//
// Filename : GCSystemMessageHandler.cc
// Written By : elca
//
//////////////////////////////////////////////////////////////////////
// include files
#include "Client_PCH.h"
#include "GCSystemMessage.h"
#include "ClientDef.h"
#include "UIFunction.h"
#include "MGameStringTable.h"
#include "Client.h"
//////////////////////////////////////////////////////////////////////
//
// 클라이언트에서 서버로부터 메시지를 받았을때 실행되는 메쏘드이다.
//
//////////////////////////////////////////////////////////////////////
void GCSystemMessageHandler::execute ( GCSystemMessage * pPacket , Player * pPlayer )
throw ( ProtocolException , Error )
{
__BEGIN_TRY
#ifdef __GAME_CLIENT__
static char previous1[128] = { NULL, };
switch(pPacket->getType())
{
case SYSTEM_MESSAGE_HOLY_LAND : // 아담의 성지 관련
if(g_pUserOption->DoNotShowHolyLandMsg)
return;
break;
case SYSTEM_MESSAGE_NORMAL:
break;
case SYSTEM_MESSAGE_OPERATOR: // 운영자 말씀
break;
case SYSTEM_MESSAGE_MASTER_LAIR: // 마스터 레어 관련
if(g_pUserOption->DoNotShowLairMsg)
return;
break;
case SYSTEM_MESSAGE_COMBAT: // 전쟁 관련
if(g_pUserOption->DoNotShowWarMsg)
return;
break;
case SYSTEM_MESSAGE_INFO: // 특정한 정보 관련
break;
case SYSTEM_MESSAGE_RANGER_CHAT:
{
char* message = (char*)pPacket->getMessage().c_str();
if(NULL != message)
{
UI_SetRangerChatString(message);
}
}
return;
case SYSTEM_MESSAGE_PLAYER: // add by Coffee 2007-8-2 藤속鯤소랙箇무멩
char* message = (char*)pPacket->getMessage().c_str();
if (NULL != message)
{
message = (char*)pPacket->getMessage().c_str();
// if (strcmp(previous1, message)==0)
// {
// BOOL bExist = FALSE;
//
// //--------------------------------------------------------------------
// // 이미 있는 메세지인지 검사한다.
// //--------------------------------------------------------------------
// for (int i=0; i<g_pPlayerMessage->GetSize(); i++)
// {
// if (strcmp((*g_pPlayerMessage)[i], message)==0)
// {
// bExist = TRUE;
// }
// }
//
// //--------------------------------------------------------------------
// // 없는거면 추가한다.
// //--------------------------------------------------------------------
// if (!bExist)
// {
// g_pPlayerMessage->Add( message );
// }
// }
// //--------------------------------------------------------------------
// // 새로운 메세지이면 추가한다.
// //--------------------------------------------------------------------
// else
// {
g_pPlayerMessage->Add( message );
strcpy( previous1, pPacket->getMessage().c_str() );
// }
}
return;
}
static char previous[128] = { NULL, };
const char* message = pPacket->getMessage().c_str();
// add by Coffee 2007-8-2 藤속溝固斤口혐깎
char *pMsg = NULL;
if (message!=NULL && pPacket->getType() != SYSTEM_MESSAGE_PLAYER )
{
pMsg = new char[strlen(message)+20];
sprintf(pMsg,(*g_pGameStringTable)[UI_STRING_MESSAGE_SYSTEM].GetString(),message);
pPacket->setMessage(pMsg);
SAFE_DELETE_ARRAY( pMsg );
}
message = pPacket->getMessage().c_str();
// add end by Coffee 2007-8-2
//--------------------------------------------------------------------
// system message에 출력
//--------------------------------------------------------------------
if (strcmp(previous, message)==0)
{
BOOL bExist = FALSE;
//--------------------------------------------------------------------
// 이미 있는 메세지인지 검사한다.
//--------------------------------------------------------------------
for (int i=0; i<g_pSystemMessage->GetSize(); i++)
{
if (strcmp((*g_pSystemMessage)[i], message)==0)
{
bExist = TRUE;
}
}
//--------------------------------------------------------------------
// 없는거면 추가한다.
//--------------------------------------------------------------------
if (!bExist)
{
g_pSystemMessage->Add( message );
}
}
//--------------------------------------------------------------------
// 새로운 메세지이면 추가한다.
//--------------------------------------------------------------------
else
{
g_pSystemMessage->Add( message );
strcpy( previous, pPacket->getMessage().c_str() );
}
#endif
__END_CATCH
}
|
c27cb00f973b23a003fee670c1f3bd6b5c27779d
|
30540bc3d3b9c86aebb0fa652a7ae827dd4a3456
|
/source/assembler/assembler_visitors.cpp
|
754e8fb4ddaaa33dad2e503e6efde65dbc2534d8
|
[
"MIT"
] |
permissive
|
skwirl42/robco-processor
|
28b1e91f39f63142601209bf123b1d3a892d8919
|
eb92ee0d2402403b36b9b796f80c3d46aaed1442
|
refs/heads/master
| 2023-08-12T13:56:11.768654
| 2021-10-13T15:16:18
| 2021-10-13T15:16:18
| 281,253,448
| 0
| 0
|
MIT
| 2021-01-18T22:10:01
| 2020-07-21T00:15:00
|
C++
|
UTF-8
|
C++
| false
| false
| 2,652
|
cpp
|
assembler_visitors.cpp
|
#include "assembler_visitors.hpp"
data_def_handler::data_def_handler(assembler_data_t* data) : data(data)
{
}
parser_state data_def_handler::begin(parser_state state, const rc_assembler::data_def& begin_data)
{
if (!in_progress && state == parser_state::normal)
{
in_progress = true;
spans_multiple_lines = false;
name = (begin_data.symbol) ? begin_data.symbol.value() : "";
data_bytes = begin_data.bytes;
return parser_state::data_def_in_progress;
}
return parser_state::error;
}
parser_state data_def_handler::add(parser_state state, const rc_assembler::byte_array& bytes)
{
if (in_progress && state == parser_state::data_def_in_progress)
{
data_bytes.insert(data_bytes.end(), bytes.begin(), bytes.end());
spans_multiple_lines = true;
return parser_state::data_def_in_progress;
}
return parser_state::error;
}
parser_state data_def_handler::end(parser_state state)
{
if (in_progress && state == parser_state::data_def_in_progress)
{
if (data_bytes.size() == 0)
{
data_bytes.push_back(0);
}
add_data(assembler_data, name, data_bytes);
data_bytes.clear();
name = "";
spans_multiple_lines = false;
in_progress = false;
return parser_state::normal;
}
return parser_state::error;
}
struct_def_handler::struct_def_handler(assembler_data_t* data) : data(data)
{
}
parser_state struct_def_handler::begin(parser_state state, const rc_assembler::struct_def& begin_def)
{
if (!in_progress && state == parser_state::normal)
{
in_progress = true;
name = begin_def.symbol;
return parser_state::struct_def_in_progress;
}
return parser_state::error;
}
parser_state struct_def_handler::add(parser_state state, const rc_assembler::struct_member_def& member_def)
{
if (in_progress && state == parser_state::struct_def_in_progress)
{
members.push_back(member_def);
return parser_state::struct_def_in_progress;
}
return parser_state::error;
}
parser_state struct_def_handler::end(parser_state state)
{
if (in_progress && state == parser_state::struct_def_in_progress)
{
if (members.size() == 0)
{
// error!
return parser_state::error;
}
// apply the struct's members to the symbol table
int current_offset = 0;
for (auto& member : members)
{
auto member_name = name + "." + member.symbol;
handle_symbol_def(data, member_name.c_str(), current_offset, SYMBOL_WORD);
current_offset += member.size;
}
auto size_of_string = "sizeof(" + name + ")";
handle_symbol_def(data, size_of_string.c_str(), current_offset, SYMBOL_WORD);
name = "";
in_progress = false;
members.clear();
return parser_state::normal;
}
return parser_state::error;
}
|
f79177a1a6b103f43a7c9d6fe4e58477be388551
|
fa4fa0e01ac89211fe69d0447c68779da1eaaf6a
|
/Module/Module16/Exercise1.cpp
|
bfb63592862053c7931812d857f4717f1b1d9cbb
|
[] |
no_license
|
hwilt/CS174
|
92a1bdc78c7d2ce4b882237d689efaea95f177b0
|
4fea28a294ec4d32ef8509937242c382facdbfd6
|
refs/heads/main
| 2023-02-13T03:47:10.048222
| 2021-01-05T02:25:18
| 2021-01-05T02:25:18
| 312,004,537
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,141
|
cpp
|
Exercise1.cpp
|
#include <stdio.h>
#include <string>
class TreeNode {
public:
int value;
int index;
TreeNode* left;
TreeNode* right;
//TreeNode* parent;
TreeNode(int value) {
this->value = value;
left = NULL;
right = NULL;
}
};
class BinaryTree {
public:
TreeNode* root;
int N;
BinaryTree() {
root = NULL;
N = 0;
}
};
TreeNode* makeLeftSubtree() {
TreeNode* node = new TreeNode(7);
node->left = new TreeNode(3);
node->right = new TreeNode(9);
node->right->left = new TreeNode(8);
return node;
}
TreeNode* makeRightSubtree() {
TreeNode* node = new TreeNode(15);
node->left = new TreeNode(12);
node->right = new TreeNode(20);
node->left->right = new TreeNode(14);
node->left->right->left = new TreeNode(13);
node->left->right->left->left = new TreeNode(13);
return node;
}
BinaryTree* makeExampleTree() {
BinaryTree* T = new BinaryTree();
T->root = new TreeNode(10);
T->root->left = makeLeftSubtree();
T->root->right = makeRightSubtree();
return T;
}
int getDepth(TreeNode* node, int depth){
int left = depth;
int right = depth;
if(node->left != NULL){
left = getDepth(node->left, depth+1);
}
if(node->right != NULL){
right = getDepth(node->right, depth+1);
}
int ret = left;
if(right > left){
ret = right;
}
return ret;
}
int getDepth(BinaryTree* T){
int depth = 0;
if(T->root != NULL){
depth = getDepth(T->root, 1);
}
return depth;
}
void printLevel(TreeNode* node, int curr, int level) {
// TODO: Modify this
if (node != NULL) {
printLevel(node->left, curr+1, level);
if(curr == level){
printf("%i ", node->value);
}
printLevel(node->right, curr+1, level);
}
}
void printLevel(BinaryTree* T, int level) {
printLevel(T->root, 1, level);
}
int main() {
BinaryTree* T = makeExampleTree();
int depth = getDepth(T);
printLevel(T, 3);
printf("\n");
delete T;
return 0;
}
|
b6da66f32b35f15a00bfe7d861df9bdc8bd5903d
|
3853ed9cb9a798b0a4ccfb8f18bbc2b23ecf35d3
|
/Source/Lumos/WRTK/RetrieveTriggerBox.cpp
|
ae753405e63b5bdc966da44c4d11839fd99dcdd7
|
[] |
no_license
|
michael-duan/Early-WRTK-Source-Code
|
f9a5c3c40916350b77949a43840ebd8c3868c231
|
3a2e3699fb8b22b9ea46a15e4658cd74d0610e67
|
refs/heads/master
| 2021-07-19T17:38:58.237974
| 2017-10-25T01:43:18
| 2017-10-25T01:43:18
| 108,204,962
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 779
|
cpp
|
RetrieveTriggerBox.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Lumos.h"
#include "RetrieveTriggerBox.h"
#include "RetrievableBehaviorComponent.h"
ARetrieveTriggerBox::ARetrieveTriggerBox()
{
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
}
void ARetrieveTriggerBox::BeginPlay()
{
Super::BeginPlay();
OnActorBeginOverlap.AddDynamic(this, &ARetrieveTriggerBox::AttemptRetrieval);
}
void ARetrieveTriggerBox::AttemptRetrieval(AActor* MyOverlappedActor, AActor* OtherActor)
{
if (OtherActor)
{
TArray<URetrievableBehaviorComponent*> RetrievableComponents;
OtherActor->GetComponents(RetrievableComponents);
for (auto retrievable : RetrievableComponents)
{
retrievable->RetrieveAfterDelay();
}
}
}
|
342feac7487490333fa21b7508e69e48ebfdfac3
|
12676cc44aeaf7ae604fdd7d3319052af7d0fbf2
|
/KMP.cpp
|
e72f4207f16e2ac2ab0ad6294b8cf83af6d83b4e
|
[] |
no_license
|
BIT-zhaoyang/competitive_programming
|
e42a50ae88fdd37b085cfaf64285bfd50ef0fbbc
|
a037dd40fd5665f3248dc9c6ff3254c7ab2addb2
|
refs/heads/master
| 2021-04-19T00:02:12.570233
| 2018-09-01T11:59:44
| 2018-09-01T11:59:44
| 51,271,209
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,192
|
cpp
|
KMP.cpp
|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class KMP{
public:
void setPattern(string &P){
this->P = P;
m = P.size();
kmpProcess();
}
void setText(string &T){
n = T.size();
this->T = T;
}
void kmpSearch(){
cout << "The text is: " << T << endl;
cout << "The pattern is: " << P << endl;
int i = 0, j = 0;
while(i < n){
while(j >= 0 && T[i] != P[j]) j = table[j];
++i, ++j;
if(j == m){
cout << "Pattern was found at index: " << i - m << endl;
j = table[j];
}
}
}
private:
void kmpProcess(){
table.resize(m + 1, -1);
int i = 0, j = -1;
while(i < m){
while(j >= 0 && P[j] != P[i]) j = table[j];
++i, ++j;
table[i] = j;
}
cout << "reset table content:";
for(int i = 0; i < table.size(); ++i){
cout << " " << table[i];
}
cout << endl;
}
private:
int n, m;
string P, T;
vector<int> table;
};
int main() {
string P, T;
KMP kmpProcessor;
while(getline(cin, T) && getline(cin, P)){
kmpProcessor.setText(T);
kmpProcessor.setPattern(P);
kmpProcessor.kmpSearch();
cout << endl;
}
}
|
5ff3368a06c85bc49481dc5b3726fb8c938219ec
|
98ef9f82f45320df070f670eac258c8365113642
|
/solution1-100/78. Subsets.cc
|
c923ae2fd10702608ff78912c3e959459a2b29e4
|
[] |
no_license
|
FrankWork/LeetCode
|
abbf6125b57e143073f89daf5cbcbd8ff67bb78b
|
6ec0c0d43cf4e8ef968051a4d125c4965d58e4f5
|
refs/heads/master
| 2021-01-22T07:27:43.963950
| 2018-11-12T08:44:18
| 2018-11-12T08:44:18
| 39,978,490
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,070
|
cc
|
78. Subsets.cc
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
void print(vector<vector<int>> &path){
for(auto vec: path){
for(int i: vec){
cout << i << " ";
}
cout << '\n';
}
}
class Solution {
public:
void subsets(vector<int>& nums, int start, int k, vector<int>& vec, vector<vector<int>>&res){
if(k==0){
res.push_back(vec);
return;
}
for(int i=start;i<nums.size()-k+1;++i){
// printf("k:%d i:%d nums[i]:%d\n", k, i, nums[i]);
vec.push_back(nums[i]);
// swap(nums[i], nums[start]);
subsets(nums, i+1, k-1, vec, res);
// swap(nums[i], nums[start]);
vec.pop_back();
}
}
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> vec;
for(int i=0;i<=nums.size();++i)
subsets(nums, 0, i, vec, res);
return res;
}
};
int main(){
Solution so;
vector<int> nums{1,2,3};
auto res = so.subsets(nums);
print(res);
}
|
5897051c96272dc0a1d8bbcaa020ea4d845fd79b
|
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
|
/Engine/Source/Developer/DeviceManager/Private/Widgets/Details/SDeviceDetails.h
|
6e2c3460e368d160dfce4a3ca5dfb3b77afa0e61
|
[
"MIT",
"LicenseRef-scancode-proprietary-license"
] |
permissive
|
windystrife/UnrealEngine_NVIDIAGameWorks
|
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
|
b50e6338a7c5b26374d66306ebc7807541ff815e
|
refs/heads/4.18-GameWorks
| 2023-03-11T02:50:08.471040
| 2022-01-13T20:50:29
| 2022-01-13T20:50:29
| 124,100,479
| 262
| 179
|
MIT
| 2022-12-16T05:36:38
| 2018-03-06T15:44:09
|
C++
|
UTF-8
|
C++
| false
| false
| 1,209
|
h
|
SDeviceDetails.h
|
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Containers/Array.h"
#include "Widgets/DeclarativeSyntaxSupport.h"
#include "Widgets/SCompoundWidget.h"
#include "Templates/SharedPointer.h"
#include "Widgets/Views/SListView.h"
class FDeviceManagerModel;
class SDeviceQuickInfo;
struct FDeviceDetailsFeature;
/**
* Implements the device details widget.
*/
class SDeviceDetails
: public SCompoundWidget
{
public:
SLATE_BEGIN_ARGS(SDeviceDetails) { }
SLATE_END_ARGS()
public:
/** Destructor. */
~SDeviceDetails();
public:
/**
* Construct the widget.
*
* @param InArgs The construction arguments.
* @param InModel The view model to use.
*/
void Construct(const FArguments& InArgs, const TSharedRef<FDeviceManagerModel>& InModel);
private:
/** The list of device features. */
TArray<TSharedPtr<FDeviceDetailsFeature>> FeatureList;
/** The device's feature list view. */
TSharedPtr<SListView<TSharedPtr<FDeviceDetailsFeature>> > FeatureListView;
/** Pointer the device manager's view model. */
TSharedPtr<FDeviceManagerModel> Model;
/** The quick information widget. */
TSharedPtr<SDeviceQuickInfo> QuickInfo;
};
|
f98a5bd5c25f6898f72b17d4f9ee0e3a11a2b1ca
|
f5d779b0b89b1f13f69c6acda517c7bf773c1e58
|
/backups/22-04-2014-1-50-pm/src/timer/header/timer.h
|
4f569501a9bb07cffefb5715ab60d686f5ef2140
|
[
"MIT"
] |
permissive
|
Samathy/Engine-du-Elephant
|
5b58c6b49b7802217f8f850ad3c19a158e6583a9
|
01e7c2c1394de440e715d42173816c179ad84b46
|
refs/heads/master
| 2016-09-10T22:10:56.458588
| 2014-10-19T20:02:14
| 2014-10-19T20:02:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 501
|
h
|
timer.h
|
/**************************
THIS IS NOT MY CODE. I copied it from this post: http://www.cplusplus.com/forum/beginner/317/#msg1047
Timer class.
***************************/
class timer
{
public:
timer();
void start();
void stop();
void reset();
bool isRunning();
unsigned long getTime();
bool isOver(unsigned long seconds);
private:
bool resetted;
bool running;
unsigned long beg;
unsigned long end;
};
|
55abb89fa00a2ca29eb5524ed714d5780aed3faf
|
d76d52d75bcc06fa1e5fd3b47e2cb6359dcd95d3
|
/Pandemic/Pawn.h
|
970360935287b701fd3804bd85371e83950825e4
|
[
"MIT"
] |
permissive
|
ddicorpo/PandemicBuild
|
6a2d61164519e5455b6fef143defd51237a68327
|
9c1ff34cd2bdfb2a5a1a26019d31f0b360fb9dd0
|
refs/heads/master
| 2021-04-29T14:31:25.034765
| 2017-03-17T18:47:56
| 2017-03-17T18:47:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 223
|
h
|
Pawn.h
|
#ifndef PAWN_H
#define PAWN_H
#include <string>
class Pawn
{
public:
Pawn();
Pawn(std::string color);
// setters
void setColor(std::string color);
std::string getColor();
private:
std::string color;
};
#endif
|
f974f241a66550b0a7071e3aef608a6fb14e4939
|
9402c9f35b6d895c3b6f7ddcfc87241e6b9145d8
|
/Spoj/ascdfib.cpp
|
c6ded95c2ebd5e7397ea48c7debf7f18d3f70cb7
|
[] |
no_license
|
siddharth94/competitive
|
586d42679558dcd1dcca3457c2ca7be089cbda30
|
ecda01521a7a9908225771d9374d5c18fa646515
|
refs/heads/master
| 2021-07-06T05:27:13.395384
| 2017-09-29T10:16:20
| 2017-09-29T10:16:20
| 105,229,373
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,404
|
cpp
|
ascdfib.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define R(i,a,b) for(int i=a;i<b;i++)
#define RE(i,a,b) for(int i=a;i<=b;i++)
#define RR(i,a,b) for(int i=a;i>b;i--)
#define RRE(i,a,b) for(int i=a;i>=b;i--)
#define F(i,n) for(int i=0;i<n;i++)
#define FE(i,n) for(int i=0;i<=n;i++)
#define FR(i,n) for(int i=n;i>0;i--)
#define FRE(i,n) for(int i=n;i>=0;i--)
#define mp(a,b) make_pair(a,b)
#define pii pair <int, int>
#define pb push_back
#define ft first
#define sd second
#define LL long long
#define gc getchar_unlocked
#define pc putchar_unlocked
inline void get(int &x)
{
register int c = gc();
x = 0;
int neg = 0;
for(;((c<48 || c>57) && c != '-');c = gc());
if(c=='-') {neg=1;c=gc();}
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
if(neg) x=-x;
}
int a[2000005];
int c[100005];
int main()
{
a[1] = 0;
a[2] = 1;
R(i, 3, 1100005)
{
a[i] = (a[i-1] + a[i-2])%100000;
if (a[i] >= 100000)
a[i] -= 100000;
}
int T;
get(T);
for (int __rep = 1; __rep <=T; __rep++)
{
printf("Case %d: ", __rep);
int x,y;
get(x);
get(y);
y = x+y;
memset(c, 0, sizeof(c));
int m = 100005;
RE(i,x,y)
{
c[a[i]]++;
m = min(m, a[i]);
}
int out = 0;
R(i,m,100000)
{
while(c[i] != 0)
{
printf("%d ", i);
out++;
if (out == 100)
break;
c[i]--;
}
if (out == 100)
break;
}
printf("\n");
}
return 0;
}
|
87d462bc63b3ce9aefc8853f5864c7294d9fa8ae
|
893cff54c0f3a0c73218fbae078b47d1a169bb42
|
/Users.h
|
ab65df98067352b1f64c06c8cb18c540898bcc03
|
[] |
no_license
|
xiaoyugan/Task2
|
d22bf246014b57b6f8b713c7a1878cbbbf4f4a9f
|
c25c6acf57ab90e7a498e9e20ff680facd34b529
|
refs/heads/master
| 2020-04-05T19:33:33.167709
| 2018-11-28T12:12:17
| 2018-11-28T12:12:17
| 157,140,128
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,035
|
h
|
Users.h
|
//C++ Boot Camp - Task 2 - 2018-19
//Name: Maodan Luo
//Student number: 27042120
#pragma once
#include <string>
#include <list>
//--
// UserTypeId represents an identifier for the specific user type.
//--
enum class UserTypeId
{
kInvalid = 0
, kPlayerUser
, kAdminUser
, kGuestUser
, kGameStudio
};
//--
// UserBase represents a user base class for the system.
//--
class UserBase
{
public:
using Username = std::string;
UserBase(const Username& username, const std::string& password, const std::string& email)
: m_username(username)
, m_password(password)
, m_email(email)
{}
virtual ~UserBase() {}
// mechanism for identifying the user type at runtime.
virtual const UserTypeId get_user_type() const = 0;
//virtual const double get_available_funds() const { return 0.0; }
const std::string get_username() const { return m_username; }
const std::string get_password() const { return m_password; }
void set_password(const std::string& val) { m_password = val; }
const std::string get_email() const { return m_email; }
void set_email(const std::string& val) { m_email = val; }
private:
const Username m_username; // The users username (unique key)
std::string m_password; // Users password.
std::string m_email; // Users email address.
};
//--
// PlayerUser represents a system user who owns games
//--
class PlayerUser : public UserBase
{
public:
using GameList = std::list<Game::GameId>;
PlayerUser(const Username& username, const std::string& password, const std::string& email, const double&accountFunds, const GameList& mygamelist, const int&age)
:UserBase(username, password, email)
, m_accountFunds(accountFunds)
, m_ownedGames(mygamelist)
, m_age(age)
{}
// define the specific user type.
virtual const UserTypeId get_user_type() const override { return UserTypeId::kPlayerUser; }
const PlayerUser::GameList& get_game_list() const { return m_ownedGames; }
const double get_available_funds() const { return m_accountFunds; }
const int get_myage()const { return m_age; }
void set_accountFunds(const double& val) { m_accountFunds = val; }
void add_ownedGame(const Game::GameId& val)
{
if (m_ownedGames.front() == 0)
{
m_ownedGames.remove(0);
}
m_ownedGames.push_back(val);
}
void pop_ownedGame(const Game::GameId& val)
{
if (m_ownedGames.size() == 1)
{
m_ownedGames.push_back(0);
}
m_ownedGames.remove(val);
}
private:
GameList m_ownedGames; // List of owned games.
double m_accountFunds; // The players available funds.
int m_age;// The player`s age.
};
//--
// AdminUser represents a system user who has privileges to modify the system.
//--
class AdminUser : public UserBase
{
public:
// inherit the constructor.
using UserBase::UserBase;
// define the specific user type.
virtual const UserTypeId get_user_type() const override { return UserTypeId::kAdminUser; }
};
//--
// GameStudio who can only access their own games and set a new version number to their games
//--
class GameStudio : public UserBase
{
public:
using GameList = std::list<Game::GameId>;
GameStudio(const Username& username, const std::string& password, const std::string& email, const GameList& mygamelist)
:UserBase(username, password, email)
, m_ownedGames(mygamelist)
{}
// define the specific user type.
virtual const UserTypeId get_user_type() const override { return UserTypeId::kGameStudio; }
const GameStudio::GameList& accessible_gamelist() const { return m_ownedGames; }
void add_ownedGame(const Game::GameId& val)
{
if (m_ownedGames.front() == 0)
{
m_ownedGames.remove(0);
}
m_ownedGames.push_back(val);
}
private:
GameList m_ownedGames; // List of owned games.
};
//--
// GusetUser who only have email data
//--
class GuestUser
{
public:
GuestUser(std::string&mail):m_email(mail){}
const std::string get_email() const { return m_email; }
// define the specific user type.
const UserTypeId get_user_type(){ return UserTypeId::kGuestUser; }
private:
std::string m_email; // Users email address.
};
|
1e7a6f1490e61d193b79bf037fe62f75de595b54
|
346f1f88acabca0a7b1d0c814d448f3d5e0f2345
|
/GoldOpt.h
|
86967360bb0e46d322d2c8e0461da496ec946b15
|
[] |
no_license
|
wilburCode/wilburCode
|
a7320fc501ac6036276d9c94571c0fed71864b1b
|
f77fca310bfa1cf7f9e15319646d58e29419fee4
|
refs/heads/main
| 2023-07-14T12:03:49.630543
| 2021-08-25T20:39:58
| 2021-08-25T20:39:58
| 399,828,762
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 597
|
h
|
GoldOpt.h
|
#ifndef GOLDOPT_H
#define GOLDOPT_H
#include <iostream>
#include <fstream>
namespace iret {
class GoldOpt {
public:
GoldOpt(void);
~GoldOpt(void);
void set_init_bracket(double a, double c);
double give_value();
void return_value(double xx);
int next(void);//It will set four points
void set_limit(double xx);
double eps;
double lower;
double mid1;
double mid2;
double upper;
double maxf;
double maxx;
double f1;
double f2;
long m1;
long flag;
};
}
#endif
|
94ace3bd60be50ba4584188126b879981a867559
|
befd90e800178e4cbf6d29b16570037eff90d11e
|
/app/src/main/jni/com_example_opencvexample_opencvnative_OpenCvNativeClass.cpp
|
2942a54623267190d7fb95c6bad0f82337157cf6
|
[] |
no_license
|
escuras/mcm_opencv
|
95879a569dc34612c99e0fefa4a77fd96c632dce
|
ea151d079eaf806af79b0bc2ac3e420c6a5ee291
|
refs/heads/master
| 2020-06-18T22:10:42.257697
| 2020-06-09T21:56:32
| 2020-06-09T21:56:32
| 196,468,627
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 585
|
cpp
|
com_example_opencvexample_opencvnative_OpenCvNativeClass.cpp
|
#include <com_example_opencvexample_opencvnative_OpenCvNativeClass.h>
JNIEXPORT jint JNICALL Java_com_example_opencvexample_opencvnative_OpenCvNativeClass_convertGray
(JNIEnv *, jclass, jlong addrRgba, jlong addrGray) {
Mat& mRgba = *(Mat*) addrRgba;
Mat& mGray = *(Mat*) addrGray;
int conv;
jint retVal;
conv = toGray(mRgba, mGray);
retVal = (jint) conv;
return retVal;
}
int toGray(Mat img, Mat& gray){
cvtColor(img, gray, COLOR_RGBA2GRAY);
if(gray.rows == img.rows && gray.cols == img.cols) {
return 1;
}
return 0;
}
|
c85e1ce00628db9889ff167304721eef2b38e299
|
bce0562272a45159171c17f12f8267ec8782183c
|
/CG_skel_w_MFC/MeshModel.cpp
|
0455e3d67f4689741d1824dc61bc152d24329e8a
|
[] |
no_license
|
bedoron/ComputerGraphics
|
15fed26b7913ff2b109d6cc4992de33048d9fc21
|
00efc4982991654e9525d6eb9d35769d6928bf1a
|
refs/heads/master
| 2021-06-02T11:16:46.593780
| 2013-03-20T10:32:28
| 2013-03-20T10:32:28
| 6,999,069
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,723
|
cpp
|
MeshModel.cpp
|
#include "StdAfx.h"
#include "MeshModel.h"
#include "vec.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include "Utils.h"
using namespace std;
struct FaceIdcs
{
int v[4];
int vn[4];
int vt[4];
FaceIdcs()
{
for (int i=0; i<4; i++)
v[i] = vn[i] = vt[i] = 0;
}
FaceIdcs(std::istream & aStream)
{
for (int i=0; i<4; i++)
v[i] = vn[i] = vt[i] = 0;
char c;
for(int i = 0; i < 3; i++)
{
aStream >> std::ws >> v[i] >> std::ws;
if (aStream.peek() != '/')
continue;
aStream >> c >> std::ws;
if (aStream.peek() == '/')
{
aStream >> c >> std::ws >> vn[i];
continue;
}
else
aStream >> vt[i];
if (aStream.peek() != '/')
continue;
aStream >> c >> vn[i];
}
}
};
vec3 vec3fFromStream(std::istream & aStream)
{
float x, y, z;
aStream >> x >> std::ws >> y >> std::ws >> z;
return vec3(x, y, z);
}
vec2 vec2fFromStream(std::istream & aStream)
{
float x, y;
aStream >> x >> std::ws >> y;
return vec2(x, y);
}
MeshModel::MeshModel(OBJItem modelItem):objItem(modelItem),_world_transform(mat4()),_color(vec3(255,255,255)),
_kAmbiant(vec3(1,1,1)),_kDiffuze(vec3(1,1,1)),_kspecular(vec3(1,1,1)),shine(18),_numOfColors(255),_cartoonize(false)
{
}
MeshModel::~MeshModel(void)
{
}
void MeshModel::reDraw(GLuint program,programType type)
{
objItem.setKvalue(_kAmbiant,_kDiffuze,_kspecular,shine,_world_transform);
objItem.reDraw(program, type);
}
void MeshModel::setObjectTransform(mat4 worldTransform)
{
_world_transform = worldTransform;
}
mat4 MeshModel::getObjectTransform()
{
return _world_transform;
}
vec3 MeshModel::getModelCenter()
{
return vec3(_world_transform[0][3],_world_transform[1][3],_world_transform[2][3]);
}
void MeshModel::scale(const vec3& scaler) {
_world_transform = _world_transform * Scale(scaler);
}
void MeshModel::rotate(const vec3& rotors) {
_world_transform = _world_transform * RotateX(rotors.x) * RotateY(rotors.y) * RotateZ(rotors.z);
}
void MeshModel::drawNormal(GLuint program)
{
objItem.setColor(_color);
objItem.setCalcNormals(useNormals);
objItem.setRenderType(renderMode);
objItem.setKvalue(_kAmbiant,_kDiffuze,_kspecular,shine,_world_transform);
objItem.draw(program);
}
void MeshModel::drawSilhoette()
{
objItem.drawSilhoette();
}
void MeshModel::drawTexture(GLuint program,GLuint textureID,GLint textid)
{
objItem.setColor(_color);
objItem.setCalcNormals(useNormals);
objItem.setRenderType(renderMode);
objItem.setKvalue(_kAmbiant,_kDiffuze,_kspecular,shine,_world_transform);
objItem.drawTexture(program,textureID,textid);
}
void MeshModel::drawEnviroment(GLuint program,GLuint enviroment,GLuint textureid)
{
objItem.drawEnviroment(program,enviroment,textureid);
}
|
748ca3a2be70ed412e1d0d68392446291cc883ba
|
b505ef7eb1a6c58ebcb73267eaa1bad60efb1cb2
|
/sample/0130guitest/comboboxsample.cpp
|
8458cf5cc6705fdcb04fc1087d3b25d162bc7fce
|
[] |
no_license
|
roxygen/maid2
|
230319e05d6d6e2f345eda4c4d9d430fae574422
|
455b6b57c4e08f3678948827d074385dbc6c3f58
|
refs/heads/master
| 2021-01-23T17:19:44.876818
| 2010-07-02T02:43:45
| 2010-07-02T02:43:45
| 38,671,921
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,032
|
cpp
|
comboboxsample.cpp
|
#include"comboboxsample.h"
using namespace Maid;
static const RECT2DI BOXRECT(0,0,200,20); // 最初のボックスの位置、大きさ
static const RECT2DI SELECTBOXRECT(0,0,BOXRECT.w-20,20); // 選択項目ボックスの位置、大きさ
static const SIZE2DI SLIDERBARSIZE(20,SELECTBOXRECT.h*3); // スライダバーの大きさ
static const RECT2DI SLIDERBUTTONRECT(0,0,SLIDERBARSIZE.w,20); // スライダボタンの大きさ
void ComboBoxElementSample::Initialize( Maid::Graphics2DRender* r, const Maid::String& Text )
{
m_pRender = r;
m_hFont.Create( SIZE2DI(8,16), true );
m_Text = Text;
}
void ComboBoxElementSample::UpdateFrame()
{
}
void ComboBoxElementSample::DrawNormal( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
m_pRender->BltText( pos, m_hFont, m_Text+MAIDTEXT("no"), COLOR_R32G32B32A32F(1,1,1,1) );
}
void ComboBoxElementSample::DrawMouseIn( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
m_pRender->BltText( pos, m_hFont, m_Text+MAIDTEXT("in"), COLOR_R32G32B32A32F(0,1,1,1) );
}
void ComboBoxElementSample::DrawSelect( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
m_pRender->BltText( pos, m_hFont, m_Text+MAIDTEXT("se"), COLOR_R32G32B32A32F(1,1,1,1) );
}
bool ComboBoxElementSample::IsCollision( const POINT2DI& pos ) const
{
return Collision<int>::IsPointToRect( pos, SELECTBOXRECT );
}
SIZE2DI ComboBoxElementSample::GetBoxSize() const
{
return SELECTBOXRECT.GetSize();
}
void ComboBoxSample::Initialize( Graphics2DRender* r )
{
m_pRender = r;
m_hFont.Create( SIZE2DI(8,16), true );
SetSelectBoxOffset( VECTOR2DI(0,BOXRECT.h) );
SetSliderOffset( VECTOR2DI(SELECTBOXRECT.w,BOXRECT.h) );
SetSliderBarLength( SLIDERBARSIZE.h );
SetSliderButtonLength( SLIDERBUTTONRECT.h );
}
void ComboBoxSample::OnUpdateFrame()
{
}
void ComboBoxSample::OnUpdateDraw( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
String str = MAIDTEXT("コンボ:");
const bool in = IsMouseIn();
const STATE state = GetState();
if( in ){ str += MAIDTEXT("in"); }
else { str += MAIDTEXT("out"); }
switch( state )
{
case STATE_NORMAL: { str += MAIDTEXT("通常"); }break;
case STATE_SELECTING: { str += MAIDTEXT("選択"); }break;
case STATE_SLIDERBUTTONDOWN:{ str += MAIDTEXT("スライダ"); }break;
}
{
POINT2DI p = pos;
p.x += BOXRECT.x;
p.y += BOXRECT.y;
// 下地
m_pRender->Fill( p, COLOR_R32G32B32A32F(1,0,0,1), BOXRECT.GetSize(), POINT2DI(0,0) );
}
{
// 現在の状態表示(デバッグ目的)
m_pRender->BltText( pos+VECTOR2DI(0,-16), m_hFont, str, COLOR_R32G32B32A32F(1,1,1,1) );
}
DrawElement( Target, Depth, pos );
}
void ComboBoxSample::DrawSlider( const RenderTargetBase& Target, const IDepthStencil& Depth, const POINT2DI& pos )
{
const POINT2DI ButtonPos( pos.x+SLIDERBUTTONRECT.x, pos.y+CalcSliderButtonOffset()+SLIDERBUTTONRECT.y );
m_pRender->Fill( pos, COLOR_R32G32B32A32F(1,0,0,1), SLIDERBARSIZE, POINT2DI(0,0) );
m_pRender->Fill( ButtonPos, COLOR_R32G32B32A32F(0,1,0,1), SLIDERBUTTONRECT.GetSize(), POINT2DI(0,0) );
}
bool ComboBoxSample::IsBoxCollision( const POINT2DI& pos ) const
{
return Collision<int>::IsPointToRect( pos, BOXRECT );
}
bool ComboBoxSample::IsSelectBoxCollision( const Maid::POINT2DI& pos ) const
{
return false;
}
bool ComboBoxSample::IsSliderCollision( const POINT2DI& pos ) const
{
const RECT2DI rc(POINT2DI(0,0), SLIDERBARSIZE );
return Collision<int>::IsPointToRect( pos, rc );
}
bool ComboBoxSample::IsSliderButtonCollision( const POINT2DI& pos ) const
{
const POINT2DI ButtonPos( pos.x, pos.y-CalcSliderButtonOffset() );
return Collision<int>::IsPointToRect( ButtonPos, SLIDERBUTTONRECT );
}
|
cda38a7577bece9418db24ba25a824e0700f9cc0
|
dbba95b9ae59cb2bb18709f28bc3be8ff1d9a910
|
/lis.cpp
|
8fb7af909beb19b9e3fd39349f77d43554829768
|
[] |
no_license
|
navyxliu/leetcode
|
a32de3777401803b16216773c968a506051d612e
|
cec8246d12b8cbdb15a6bf4ae625b0725d319b68
|
refs/heads/master
| 2021-01-19T00:25:22.489306
| 2016-08-03T06:55:05
| 2016-08-03T06:55:05
| 63,682,482
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 774
|
cpp
|
lis.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int lis(const vector<int> & seq) {
int sz = seq.size();
//L[i] = 1 + L[j] if j < i and arr[j] < arr[i]
vector<int> L(sz);
for (int i=0; i<sz; ++i) L[i] = 1;
for(int i=1; i<sz; ++i)
for (int j=0; j<i; ++j)
if (seq[j] < seq[i])
L[i] = max(L[i], L[j] + 1);
int m = 0;
for (int i=0; i<sz; ++i) if(L[i] > m) m = L[i];
return m;
}
int main() {
int t; cin >> t;
while (t > 0) {
int n, a;
vector<int> seq;
cin >> n;
for (int i=0; i<n; ++i) {
cin >> a;
seq.push_back(a);
}
cout << lis(seq) << "\n";
t--;
}
}
|
06fe458320b846769e3daf8dc70d293a41b7e469
|
f93e33e2c05541ad7a2d0acd849ded025ea041c3
|
/prj/habstractitem.cpp
|
531ea4305e1473e3665434160fc889706a7aa2f3
|
[] |
no_license
|
ithewei/ds
|
d52d3722e3efe6b234e042a5cab1773d2f544450
|
4e2631d9ae4f13360e0cdce6c358b5e7fd98f0f1
|
refs/heads/master
| 2021-04-18T21:54:51.805401
| 2018-03-22T08:05:00
| 2018-03-22T08:05:00
| 126,301,280
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,582
|
cpp
|
habstractitem.cpp
|
#include "habstractitem.h"
#include "hnetwork.h"
#include "hdsctx.h"
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
IMPL_SINGLETON(HItemUndo)
HAbstractItem::HAbstractItem()
{
type = NONE;
id = -1;
}
HAbstractItem::~HAbstractItem()
{
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
HCombItem::HCombItem()
{
type = SCREEN;
srvid = 0;
v = false;
a = false;
bMainScreen = false;
}
void HCombItem::add(){
HAbstractItem::add();
DsCombInfo si;
si.items[0] = *this;
for (int i = 0; i < g_dsCtx->m_tComb.itemCnt; ++i){
si.items[i+1] = g_dsCtx->m_tComb.items[i];
}
si.itemCnt = g_dsCtx->m_tComb.itemCnt + 1;
dsnetwork->postCombInfo(si);
}
void HCombItem::remove(){
HAbstractItem::remove();
DsCombInfo si = g_dsCtx->m_tComb;
if (si.items[id].srvid != 0){
si.items[id].srvid = 0;
si.items[id].a = false;
dsnetwork->postCombInfo(si);
}
}
void HCombItem::modify(){
HAbstractItem::modify();
DsCombInfo si = g_dsCtx->m_tComb;
si.items[id] = *this;
dsnetwork->postCombInfo(si);
}
bool HCombItem::undo(){
modify();
return true;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
HPictureItem::HPictureItem()
{
type = PICTURE;
pic_type = IMAGE;
}
void HPictureItem::add(){
HAbstractItem::add();
dsnetwork->addPicture(*this);
}
void HPictureItem::remove(){
HAbstractItem::remove();
dsnetwork->removePicture(*this);
}
void HPictureItem::modify(){
HAbstractItem::modify();
dsnetwork->modifyPicture(*this);
}
bool HPictureItem::undo(){
OPERATE opr = OPERATE_NONE;
if (id == -1){
opr = OPERATE_REMOVE;
for (int i = 0; i < g_dsCtx->m_pics.itemCnt; ++i){
if (g_dsCtx->m_pics.items[i].rc == rc && strstr(g_dsCtx->m_pics.items[i].src, src)){
id = g_dsCtx->m_pics.items[i].id;
break;
}
}
}else{
for (int i = 0; i < g_dsCtx->m_pics.itemCnt; ++i){
if (g_dsCtx->m_pics.items[i].id == id){
if (memcmp(&g_dsCtx->m_pics.items[i], this, sizeof(HPictureItem)) != 0)
opr = OPERATE_MODIFY;
break;
}
}
if (opr != OPERATE_MODIFY)
opr = OPERATE_ADD;
}
if (opr == OPERATE_ADD)
add();
else if (opr == OPERATE_REMOVE && id != -1)
remove();
else if (opr == OPERATE_MODIFY)
modify();
else
return false;
return true;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
HTextItem::HTextItem()
: text{0}
{
type = TEXT;
text_type = LABEL;
font_size = 32;
font_color = 0xFFFFFF;
}
void HTextItem::add(){
HAbstractItem::add();
dsnetwork->addText(*this);
}
void HTextItem::remove(){
HAbstractItem::remove();
dsnetwork->removeText(*this);
}
void HTextItem::modify(){
HAbstractItem::modify();
dsnetwork->modifyText(*this);
}
bool HTextItem::undo(){
OPERATE opr = OPERATE_NONE;
if (id == -1){
opr = OPERATE_REMOVE;
for (int i = 0; i < g_dsCtx->m_texts.itemCnt; ++i){
if (g_dsCtx->m_texts.items[i].rc.x() == rc.x() &&
g_dsCtx->m_texts.items[i].text_type == text_type &&
strcmp(g_dsCtx->m_texts.items[i].text, text) == 0){
id = g_dsCtx->m_texts.items[i].id;
break;
}
}
}else{
for (int i = 0; i < g_dsCtx->m_texts.itemCnt; ++i){
if (g_dsCtx->m_texts.items[i].id == id){
if (memcmp(&g_dsCtx->m_texts.items[i], this, sizeof(HTextItem)) != 0)
opr = OPERATE_MODIFY;
break;
}
}
if (opr != OPERATE_MODIFY)
opr = OPERATE_ADD;
}
if (opr == OPERATE_ADD)
add();
else if (opr == OPERATE_REMOVE && id != -1)
remove();
else if (opr == OPERATE_MODIFY)
modify();
else
return false;
return true;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
HAbstractItem* HItemFactory::createItem(HAbstractItem::TYPE type){
switch (type){
case HAbstractItem::SCREEN:
return new HCombItem;
case HAbstractItem::PICTURE:
return new HPictureItem;
case HAbstractItem::TEXT:
return new HTextItem;
}
return NULL;
}
|
d8b4b325e3b332fd35c27cba465722a6aabcf293
|
d6ebbe29a5ed512889b0488620e53bc9df3ec4e1
|
/leetcode/15-Programme/JD0804M-PowerSet/PowerSet_bitset.cpp
|
95a7e110a183ce3e926a32fdde9339ca7a4de8d1
|
[
"MIT"
] |
permissive
|
BinRay/Learning
|
ccfcfd88b4c73cf85fcdc0050b23534d16221e13
|
36a2380a9686e6922632e6b85ddb3d1f0903b37a
|
refs/heads/master
| 2021-07-16T20:33:38.587694
| 2021-03-05T08:53:29
| 2021-03-05T08:53:29
| 243,143,180
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 818
|
cpp
|
PowerSet_bitset.cpp
|
/**
* 执行用时:4 ms, 在所有 C++ 提交中击败了61.63%的用户
* 内存消耗:7.6 MB, 在所有 C++ 提交中击败了100.00%的用户
* 1. 每种组合都是2**len数字中的一个二进制位表示
* 2. 遍历,组装即可
*
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
// bit manipulation: O(n*2**n)
bitset<128> combination;
vector<vector<int>> subsets;
for ( int i = 0; i < pow( 2, nums.size() ); i++ ){
combination = i;
vector<int> subset;
for ( int j = 0; j < nums.size(); j++ ){
if ( combination.test(j) ){
subset.push_back( nums[j] );
}
}
subsets.push_back( subset );
}
return subsets;
}
};
|
569a9c5f9f2f829a09e6e2b4f01812cc83e5baff
|
23e5a183cba5e06c645d4a60f2ebd14f73c63ab2
|
/src/figures/figure.h
|
439719e35f8d5e74faccd6060f6282af26725baf
|
[] |
no_license
|
airat91140/tetris
|
ce6365626bd551d56a7af6ceaf3ab39538d1b1b4
|
c4619e6f5e0436f26280ea0dee3d19552960afc5
|
refs/heads/master
| 2023-07-03T08:57:00.018231
| 2021-07-31T18:46:20
| 2021-07-31T18:46:20
| 381,806,380
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 919
|
h
|
figure.h
|
//
// Created by airat on 30.06.2021.
//
#ifndef TETRIS_FIGURE_H
#define TETRIS_FIGURE_H
#include <QVector>
#include <QPointf>
#include <Qpair>
#include <QGraphicsScene>
#include "piece.h"
namespace tetris {
/**
* @brief abstract class of figure
*/
class Figure : public QObject {
Q_OBJECT
protected:
int angle;
qreal point_width, point_height;
QVector<piece *> pieces;
void step_fall();
void step_move(bool is_left);
public:
virtual void paint(QGraphicsScene *scene) = 0;
explicit Figure(qreal width = 0, qreal height = 0, QObject *parent = nullptr);
~Figure() override = default;
virtual void move(bool is_left) {};
static bool is_line(QGraphicsItem *it);
public slots:
virtual void fall() {};
signals:
void signal_check_figure_under();
};
}
#endif //TETRIS_FIGURE_H
|
9af0177b424ac8c04102717fc32156d1c78a4772
|
6dbb7829aa008d165c287f4ba5605c1eb6278065
|
/CodeForces_CodeChef/tempCodeRunnerFile.cpp
|
93a601451b533063b8f75b249c041babd2187e1b
|
[] |
no_license
|
2023PHOENIX/CP
|
08831756aebc74f01ab5c50259de4897215b8448
|
238b0417d4712414711eba8a6076849470645493
|
refs/heads/master
| 2023-06-30T01:22:08.349187
| 2021-08-05T18:02:55
| 2021-08-05T18:02:55
| 372,407,931
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 139
|
cpp
|
tempCodeRunnerFile.cpp
|
// for (int i = 1; i <= pf; i++)
// {
// if (dp[n][i] <= W)
// {
// cout<<i<<" ";
// }
// }
|
e5d5cc98319d38da2cf6427c81243f4eaf2a1307
|
02c201b1afd2de7f8237adc3737734e19b77cd2b
|
/src/wasm/wasm-io.cpp
|
65e6a982aec739b4a1f3a07be49f8322f595079e
|
[
"Apache-2.0"
] |
permissive
|
WebAssembly/binaryen
|
1ce65e58489c99b5a66ab51927a5b218c70ae315
|
90d8185ba2be34fa6b6a8f8ce0cbb87e0a9ed0da
|
refs/heads/main
| 2023-08-31T21:01:27.020148
| 2023-08-31T19:32:33
| 2023-08-31T19:32:33
| 45,208,608
| 7,061
| 768
|
Apache-2.0
| 2023-09-14T21:41:04
| 2015-10-29T20:26:28
|
WebAssembly
|
UTF-8
|
C++
| false
| false
| 6,138
|
cpp
|
wasm-io.cpp
|
/*
* Copyright 2017 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Abstracts reading and writing, supporting both text and binary
// depending on the suffix.
//
// When the suffix is unclear, writing defaults to text (this
// allows odd suffixes, which we use in the test suite), while
// reading will check the magic number and default to text if not
// binary.
//
#include "wasm-io.h"
#include "support/debug.h"
#include "wasm-binary.h"
#include "wasm-s-parser.h"
#include "wat-parser.h"
namespace wasm {
bool useNewWATParser = false;
#define DEBUG_TYPE "writer"
static void readTextData(std::string& input, Module& wasm, IRProfile profile) {
if (useNewWATParser) {
std::string_view in(input.c_str());
if (auto parsed = WATParser::parseModule(wasm, in);
auto err = parsed.getErr()) {
Fatal() << err->msg;
}
} else {
SExpressionParser parser(const_cast<char*>(input.c_str()));
Element& root = *parser.root;
SExpressionWasmBuilder builder(wasm, *root[0], profile);
}
}
void ModuleReader::readText(std::string filename, Module& wasm) {
BYN_TRACE("reading text from " << filename << "\n");
auto input(read_file<std::string>(filename, Flags::Text));
readTextData(input, wasm, profile);
}
void ModuleReader::readBinaryData(std::vector<char>& input,
Module& wasm,
std::string sourceMapFilename) {
std::unique_ptr<std::ifstream> sourceMapStream;
// Assume that the wasm has had its initial features applied, and use those
// while parsing.
WasmBinaryReader parser(wasm, wasm.features, input);
parser.setDebugInfo(debugInfo);
parser.setDWARF(DWARF);
parser.setSkipFunctionBodies(skipFunctionBodies);
if (sourceMapFilename.size()) {
sourceMapStream = std::make_unique<std::ifstream>();
sourceMapStream->open(sourceMapFilename);
parser.setDebugLocations(sourceMapStream.get());
}
parser.read();
if (sourceMapStream) {
sourceMapStream->close();
}
}
void ModuleReader::readBinary(std::string filename,
Module& wasm,
std::string sourceMapFilename) {
BYN_TRACE("reading binary from " << filename << "\n");
auto input(read_file<std::vector<char>>(filename, Flags::Binary));
readBinaryData(input, wasm, sourceMapFilename);
}
bool ModuleReader::isBinaryFile(std::string filename) {
std::ifstream infile;
std::ios_base::openmode flags = std::ifstream::in | std::ifstream::binary;
infile.open(filename, flags);
char buffer[4] = {1, 2, 3, 4};
infile.read(buffer, 4);
infile.close();
return buffer[0] == '\0' && buffer[1] == 'a' && buffer[2] == 's' &&
buffer[3] == 'm';
}
void ModuleReader::read(std::string filename,
Module& wasm,
std::string sourceMapFilename) {
// empty filename or "-" means read from stdin
if (!filename.size() || filename == "-") {
readStdin(wasm, sourceMapFilename);
return;
}
if (isBinaryFile(filename)) {
readBinary(filename, wasm, sourceMapFilename);
} else {
// default to text
if (sourceMapFilename.size()) {
std::cerr << "Binaryen ModuleReader::read() - source map filename "
"provided, but file appears to not be binary\n";
}
readText(filename, wasm);
}
}
// TODO: reading into a vector<char> then copying into a string is unnecessarily
// inefficient. It would be better to read just once into a stringstream.
void ModuleReader::readStdin(Module& wasm, std::string sourceMapFilename) {
std::vector<char> input = read_stdin();
if (input.size() >= 4 && input[0] == '\0' && input[1] == 'a' &&
input[2] == 's' && input[3] == 'm') {
readBinaryData(input, wasm, sourceMapFilename);
} else {
std::ostringstream s;
s.write(input.data(), input.size());
s << '\0';
std::string input_str = s.str();
readTextData(input_str, wasm, profile);
}
}
#undef DEBUG_TYPE
#define DEBUG_TYPE "writer"
void ModuleWriter::writeText(Module& wasm, Output& output) {
output.getStream() << wasm;
}
void ModuleWriter::writeText(Module& wasm, std::string filename) {
BYN_TRACE("writing text to " << filename << "\n");
Output output(filename, Flags::Text);
writeText(wasm, output);
}
void ModuleWriter::writeBinary(Module& wasm, Output& output) {
BufferWithRandomAccess buffer;
WasmBinaryWriter writer(&wasm, buffer);
// if debug info is used, then we want to emit the names section
writer.setNamesSection(debugInfo);
if (emitModuleName) {
writer.setEmitModuleName(true);
}
std::unique_ptr<std::ofstream> sourceMapStream;
if (sourceMapFilename.size()) {
sourceMapStream = std::make_unique<std::ofstream>();
sourceMapStream->open(sourceMapFilename);
writer.setSourceMap(sourceMapStream.get(), sourceMapUrl);
}
if (symbolMap.size() > 0) {
writer.setSymbolMap(symbolMap);
}
writer.write();
buffer.writeTo(output);
if (sourceMapStream) {
sourceMapStream->close();
}
}
void ModuleWriter::writeBinary(Module& wasm, std::string filename) {
BYN_TRACE("writing binary to " << filename << "\n");
Output output(filename, Flags::Binary);
writeBinary(wasm, output);
}
void ModuleWriter::write(Module& wasm, Output& output) {
if (binary) {
writeBinary(wasm, output);
} else {
writeText(wasm, output);
}
}
void ModuleWriter::write(Module& wasm, std::string filename) {
if (binary && filename.size() > 0) {
writeBinary(wasm, filename);
} else {
writeText(wasm, filename);
}
}
} // namespace wasm
|
6f45de629f54111b3565d55357ec47a4de327306
|
5682fdd3d0c8118da9f75ccb463ebacea174b3ed
|
/project3-sc9ny/shared_double_buffer.cpp
|
33675762d08bc0de30adbad2f71c03c9ca7bb66c
|
[] |
no_license
|
sc9ny/ECE3574
|
3642a79aca14def6f989f8bd901b2105bc0e2ce9
|
68d1512b5edba9a623c9d746d30d9db5f3dd68fa
|
refs/heads/MS1
| 2020-03-09T22:45:21.294037
| 2018-04-11T06:45:14
| 2018-04-11T06:45:14
| 129,041,874
| 0
| 0
| null | 2018-04-11T06:40:53
| 2018-04-11T05:59:32
|
C++
|
UTF-8
|
C++
| false
| false
| 2,557
|
cpp
|
shared_double_buffer.cpp
|
#include "shared_double_buffer.hpp"
#include <QDebug>
// Implement your shared double buffer here
template<typename T>
shared_double_buffer<T>::shared_double_buffer(size_t s)
{
size = s;
}
template<typename T>
bool shared_double_buffer<T>::s_d_b_push(const T &item)
{
std::unique_lock<std::mutex> lock(the_mutex);
// if the writing buffer is full
if (int(the_queue2.size()) ==int(size))
return false;
the_queue2.push(item);
return true;
}
//template<typename T>
//shared_double_buffer<T> & shared_double_buffer<T>::operator =(std::queue<T> const & q)
//{
// return *this;
//}
template<typename T>
bool shared_double_buffer<T>::empty()
{
std::lock_guard<std::mutex> lock(the_mutex);
return the_queue1.empty();
}
template<typename T>
void shared_double_buffer<T>::s_d_b_try_pop( T &item)
{
//
if (the_queue1.empty())
{
swap();
}
else if (!the_queue1.empty())
{
std::lock_guard<std::mutex> lock(the_mutex);
item = the_queue1.front();
the_queue1.pop();
}
}
template<typename T>
void shared_double_buffer<T>::s_d_b_wait_and_push(const T &item)
{
std::unique_lock<std::mutex> lock(the_mutex);
while (int(the_queue2.size()) == int(size))
{
cv.wait(lock);
}
the_queue2.push(item);
}
template<typename T>
bool shared_double_buffer<T>::swap()
{
std::unique_lock<std::mutex> lock(the_mutex);
the_queue1.swap(the_queue2);
lock.unlock();
cv.notify_one();
return true;
}
template<typename T>
void shared_double_buffer<T>::setBufferSize(size_t s)
{
std::lock_guard<std::mutex> lock(the_mutex);
size = s;
}
template<typename T>
int shared_double_buffer<T>::getBufferSize()
{
return size;
}
template<typename T>
void shared_double_buffer<T>::stopPressed()
{
std::lock_guard<std::mutex> lock (the_mutex);
while (!the_queue1.empty())
{
the_queue1.pop();
}
while (!the_queue2.empty())
{
// qDebug() <<"que2";
the_queue2.pop();
}
//qDebug() << "DONE";
}
//template<typename T>
//void shared_double_buffer<T>::suspend()
//{
// std::unique_lock<std::mutex> lock (the_mutex);
// while (flag)
// {
// cv.wait(lock);
// }
// flag = false;
//}
//template<typename T>
//void shared_double_buffer<T>::quitSuspension()
//{
// std::unique_lock<std::mutex> lock (the_mutex);
// flag = false;
// lock.unlock();
// cv.notify_one();
//}
template class shared_double_buffer<double>;
template class shared_double_buffer<int16_t>;
|
e6b478b2d076c2f83d000e4c5d38b62f1befa55f
|
8ebf49a1eac01a9757cff0444af247d66e0352c5
|
/2013-CJ-RoadNetworkRkNN/main.cpp
|
04ae63b2b9896da35892b83e1b9d55414b2b5c25
|
[] |
no_license
|
safarisoul/ResearchProjects
|
9a5f62cf9364f879e5ede27e9edfb57532c1fc76
|
7171965b07e70d73e643b82a084571ec8f8559ad
|
refs/heads/master
| 2021-01-01T19:21:07.628414
| 2015-12-21T02:33:03
| 2015-12-21T02:33:03
| 20,355,576
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,229
|
cpp
|
main.cpp
|
#include "main.h"
using namespace std;
int main(int argc, char* argv[])
{
cout << endl;
// read argument
Argument::readArguments(argc, argv);
Argument::printArguments();
// load data
if(Argument::network == "california")
{
CaliforniaDataLoader loader;
loader.load();
loader.checkData();
}
else if(Argument::network == "northAmerica")
{
NorthAmericaDataLoader loader;
loader.load();
loader.checkData();
}
// run
if(Argument::function == "genq")
{
QueryGenerator generator;
generator.run();
Data::clean();
}
else if(Argument::function == "geno")
{
ObjectGenerator generator;
generator.run();
// Data::clean(); not sure why this cause error, memory leaks present
}
else if(Argument::function == "genm")
{
if(Argument::network == "northAmerica")
{
NorthAmericaDataLoader loader;
loader.generateMap();
}
Data::clean();
}
else if(Argument::function == "m")
{
Monitor monitor;
monitor.zoneForAll();
monitor.monitor();
Argument::outputExperiment();
Data::clean();
}
else if(Argument::function == "mu")
{
Monitor monitor;
monitor.zoneForAll();
monitor.update();
Argument::outputExperiment();
Data::clean();
}
else if(Argument::function == "sac")
{
SAC sac;
sac.computeUnprunedNetworkForAll();
sac.monitor();
Argument::outputExperiment();
Data::clean();
}
else if(Argument::function == "u")
{
Update monitor;
monitor.zoneForAll();
monitor.update();
Argument::outputExperiment();
Data::clean();
}
else if(Argument::function == "um")
{
Update monitor;
monitor.zoneForAll();
monitor.monitor();
Argument::outputExperiment();
Data::clean();
}
else if(Argument::function == "us")
{
Update monitor;
monitor.zoneForAll();
monitor.updateSimple();
Argument::outputExperiment();
Data::clean();
}
}
|
7c0481bfc2e7ec426b9c9742ee1860169176883a
|
6b57141bf61b717cdb56ec0f356b7fbee5ee4c81
|
/MuxTest.cpp
|
e3f8d2ef62b2bcd1f6d56efb7a2f916373d982a9
|
[] |
no_license
|
AdamFulford/MuxTest
|
93696b1a1d199f50cc2b78bff25eb2fc2d991b56
|
07834743a50c7ff032156e51732f3bea38f2951e
|
refs/heads/master
| 2023-03-14T09:09:04.429291
| 2021-03-10T13:05:57
| 2021-03-10T13:05:57
| 346,176,276
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,758
|
cpp
|
MuxTest.cpp
|
#include "MuxTest.h"
//#include "daisy_seed.h"
#include "QSPI_Settings.h"
#include <string.h>
#include <atomic>
Settings setting{};
constexpr Settings defaultSetting
{
(25000.0f + 240000.0f) / 2.0f, //RevLength
1.0f, //tapRatio
0.0f, //ModDepth
(10.0f + 0.1f) / 2.0f, //ModFreq
200.0f, //HP_Cutoff
12000.0f, //LP_Cutoff
0.0f, //Filter Resonance
0.0f
};
float pot1,pot2,pot3,pot4,pot5,pot6,pot7,pot8;
float CV1,CV2,CV3,CV4,CV5,CV6,CV7,CV8;
Led led1,led2;
std::atomic<bool> save_flag{};
static void AudioCallback(float *in, float *out, size_t size)
{
led1.Update();
led2.Update();
static uint32_t timeSinceLast{};
//try to save every 5 seconds if not currently saving
if( ( (System::GetNow() - timeSinceLast) > 5000) && !save_flag )
{
save_flag = true;
timeSinceLast = System::GetNow(); //reset timer
}
for(size_t i = 0; i < size; i += 2)
{
out[i] = in[i];
out[i+1] = in[i+1];
}
}
int main(void)
{
hw.Configure();
hw.Init();
led1.Init(hw.GetPin(24), false, hw.AudioSampleRate());
led2.Init(hw.GetPin(10),false, hw.AudioSampleRate());
Settings setting2{LoadSettings()};
led2.Set(setting2.FilterPrePost);
AdcChannelConfig adcConfig[8];
//CV inputs
adcConfig[0].InitSingle(hw.GetPin(15));
adcConfig[1].InitSingle(hw.GetPin(16));
adcConfig[2].InitSingle(hw.GetPin(17));
adcConfig[3].InitSingle(hw.GetPin(18));
adcConfig[4].InitSingle(hw.GetPin(19));
adcConfig[5].InitSingle(hw.GetPin(20));
adcConfig[6].InitSingle(hw.GetPin(22));
//Muxed pot inputs
adcConfig[7].InitMux(hw.GetPin(25),8,hw.GetPin(14),hw.GetPin(13),hw.GetPin(12));
hw.adc.Init(adcConfig, 8);
hw.adc.Start();
hw.SetAudioBlockSize(1); //set blocksize.
hw.StartAudio(AudioCallback);
// Loop forever
for(;;)
{
pot1 = hw.adc.GetMuxFloat(7,0);
setting.FilterPrePost = pot1;
pot2 = hw.adc.GetMuxFloat(7,1);
pot3 = hw.adc.GetMuxFloat(7,2);
pot4 = hw.adc.GetMuxFloat(7,3);
pot5 = hw.adc.GetMuxFloat(7,4);
pot6 = hw.adc.GetMuxFloat(7,5);
pot7 = hw.adc.GetMuxFloat(7,6);
pot8 = hw.adc.GetMuxFloat(7,7);
CV1 = hw.adc.GetFloat(0);
CV2 = hw.adc.GetFloat(1);
CV3 = hw.adc.GetFloat(2);
CV4 = hw.adc.GetFloat(3);
CV5 = hw.adc.GetFloat(4);
CV6 = hw.adc.GetFloat(5);
CV7 = hw.adc.GetFloat(6);
led1.Set(pot1);
if(save_flag) //if save_flag set save settings
{
if (SaveSettings(setting) == DSY_MEMORY_OK)
{
save_flag = false;
}
}
}
}
|
e9ce7b60639ddcfbfb7da5f231172edeb10095fd
|
24e015bfc2883daf97c71a5c08cc3765d3678c74
|
/cpp/BatchWraperNewExemplars.cpp
|
ec23d03caba33befa62d9b1dab800b9542c283f6
|
[] |
no_license
|
herobd/crowdcat
|
4309a45fc9de0f42d7919d37af1034c78c392c67
|
67c24a18d5a6172b450bf4916557e10b3aebac43
|
refs/heads/master
| 2021-01-17T07:59:42.470951
| 2017-03-31T23:25:27
| 2017-03-31T23:25:27
| 83,824,594
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,982
|
cpp
|
BatchWraperNewExemplars.cpp
|
#include "BatchWraperNewExemplars.h"
BatchWraperNewExemplars::BatchWraperNewExemplars(NewExemplarsBatch* newExemplars)
{
base64::encoder E;
vector<int> compression_params={CV_IMWRITE_PNG_COMPRESSION,9};
batchId=to_string(newExemplars->getId());
int batchSize = newExemplars->size();
retData.resize(batchSize);
retNgram.resize(batchSize);
locations.resize(batchSize);
#ifdef NO_NAN
images.resize(batchSize);
#endif
//auto iter=newExemplars.begin();
for (int index=0; index<batchSize; index++)
{
retNgram[index]=newExemplars->at(index).ngram;
vector<uchar> outBuf;
cv::imencode(".png",newExemplars->at(index).ngramImg(),outBuf,compression_params);//or should we have them look at the ngram image?
stringstream ss;
ss.write((char*)outBuf.data(),outBuf.size());
stringstream encoded;
E.encode(ss, encoded);
string dataBase64 = encoded.str();
retData[index]=dataBase64;
locations[index]=Location( newExemplars->at(index).pageId,
newExemplars->at(index).tlx,
newExemplars->at(index).tly,
newExemplars->at(index).brx,
newExemplars->at(index).bry
);
#ifdef NO_NAN
images[index]=newExemplars->at(index).ngramImg();
#endif
}
}
#ifndef NO_NAN
void BatchWraperNewExemplars::doCallback(Callback *callback)
{
Nan:: HandleScope scope;
v8::Local<v8::Array> arr = Nan::New<v8::Array>(retData.size());
v8::Local<v8::Array> locs = Nan::New<v8::Array>(locations.size());
for (unsigned int index=0; index<retData.size(); index++) {
v8::Local<v8::Object> obj = Nan::New<v8::Object>();
Nan::Set(obj, Nan::New("ngram").ToLocalChecked(), Nan::New(retNgram[index]).ToLocalChecked());
Nan::Set(obj, Nan::New("data").ToLocalChecked(), Nan::New(retData[index]).ToLocalChecked());
Nan::Set(arr, index, obj);
Location l=locations[index];
v8::Local<v8::Object> loc = Nan::New<v8::Object>();
loc->Set(Nan::New("page").ToLocalChecked(), Nan::New(l.pageId));
loc->Set(Nan::New("x1").ToLocalChecked(), Nan::New(l.x1));
loc->Set(Nan::New("y1").ToLocalChecked(), Nan::New(l.y1));
loc->Set(Nan::New("x2").ToLocalChecked(), Nan::New(l.x2));
loc->Set(Nan::New("y2").ToLocalChecked(), Nan::New(l.y2));
Nan::Set(locs, index, loc);
}
Local<Value> argv[] = {
Nan::Null(),
Nan::New("newExemplars").ToLocalChecked(),
Nan::New(batchId).ToLocalChecked(),
Nan::New(arr),
Nan::Null(),
Nan::Null(),
Nan::New(locs),
Nan::New("UNKNOWN").ToLocalChecked()
};
callback->Call(8, argv);
}
#else
void BatchWraperNewExemplars::getNewExemplars(string* batchId,vector<string>* ngrams, vector<Location>* locs)
{
*batchId=this->batchId;
*ngrams=retNgram;
*locs=locations;
}
#endif
|
4d5ce7293d002f74f289fe47655762a2cdbd74d9
|
50c1593f3183e7fe578926ccabe1021105b88e90
|
/やさしいC++/lesson8/sample3.cpp
|
076092daa892f96b3afbdb082d6169a64df0949e
|
[] |
no_license
|
birune/learning-cpp
|
a30a8887c6fbcabeb2cb176ba22dd0119114ade1
|
6670bd15597d3d46c744f764c4814aa11cc84f84
|
refs/heads/master
| 2020-05-20T02:15:27.192662
| 2019-05-07T13:49:39
| 2019-05-07T13:49:39
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 565
|
cpp
|
sample3.cpp
|
#include <iostream>
using namespace std;
int main(){
int a;
int* pA;
a = 5;
pA = &a;
cout << "変数aの値は" << a << "です\n";
cout << "変数aのアドレスは" << &a << "です\n";
cout << "ポインタpAの値は" << pA << "です\n";
//"*ポインタ名"でポインタの指す変数の値を示す
//この"*"を間接参照演算子という
cout << "*pAの値は" << *pA << "です\n";
return 0;
}
//g++ ファイル名 --input-charset=utf-8 --exec-charset=cp932
//日本語出力するときのやつ
|
ef2e96bccdf6d6e6f1f15b9276b2d1423b3cec3d
|
afa8201826d9db8ed7c7692c2971103a9b798d7e
|
/Baekjoon/StronglyConnectedComponent/4013.cpp
|
f12a8712519b74e3c3b3c7df69c5811f1ed76ad8
|
[] |
no_license
|
lcy960729/Algorithm_Solution_Collection
|
bd346d8e2056d23b3ebc113d9220c4f622049ded
|
fa39ed55ecbc7ab17be9c22e74248078030768d5
|
refs/heads/main
| 2023-05-14T03:22:32.020737
| 2021-06-08T08:14:39
| 2021-06-08T08:14:39
| 294,163,662
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,143
|
cpp
|
4013.cpp
|
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <stack>
#include <queue>
#define pii pair<int, int>
#define ll long long
#define Int_MAX 1e9
#define LL_MAX 3e18
using namespace std;
int n, m, s, p;
int id, sn;
vector<int> discovered;
vector<int> sccid;
vector<int> money;
vector<bool> restaurant;
vector<vector<int>> g;
vector<vector<int>> SCC;
stack<int> st;
int dfs(int cur) {
int parent = discovered[cur] = ++id;
st.push(cur);
for (int next : g[cur]) {
if (discovered[next] == -1) {
parent = min(parent, dfs(next));
} else if (sccid[next] == -1) {
parent = min(parent, discovered[next]);
}
}
if (parent == discovered[cur]) {
vector<int> scc;
while (true) {
int t = st.top();
st.pop();
scc.push_back(t);
sccid[t] = sn;
if (t == cur) break;
}
SCC.push_back(scc);
sn++;
}
return parent;
}
int topologicalSort() {
int s2;
vector<vector<int>> g2(SCC.size());
vector<int> money2(SCC.size());
vector<bool> restaurant2(SCC.size());
vector<int> indegree(SCC.size());
for (int i = 0; i < n; ++i) {
int sid = sccid[i];
money2[sid] += money[i];
if (restaurant[i]) restaurant2[sid] = true;
if (i == s) s2 = sid;
for (int next : g[i]) {
if (sid == sccid[next])
continue;
g2[sid].push_back(sccid[next]);
indegree[sccid[next]]++;
}
}
vector<bool> check(SCC.size(), false);
vector<int> totalMoney(SCC.size());
queue<int> q;
check[s2] = true;
for (int i = 0; i < SCC.size(); ++i) {
totalMoney[i] = money2[i];
if (indegree[i] == 0) q.push(i);
}
for (int i = 0; i < SCC.size(); ++i) {
int cur = q.front();
q.pop();
for (int next : g2[cur]) {
if (check[cur]) {
totalMoney[next] = max(totalMoney[next], totalMoney[cur] + money2[next]);
check[next] = true;
}
if (--indegree[next] == 0) {
q.push(next);
}
}
}
int ret = 0;
for (int i = 0; i < SCC.size(); ++i) {
if (restaurant2[i] && check[i]) ret = max(ret, totalMoney[i]);
}
return ret;
}
int main() {
#ifdef LOCAL
freopen("input.txt", "r", stdin);
#endif
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
discovered.assign(n, -1);
sccid.assign(n, -1);
money.assign(n, 0);
restaurant.assign(n, false);
g.assign(n, vector<int>());
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
g[--u].push_back(--v);
}
for (int i = 0; i < n; ++i) {
cin >> money[i];
}
cin >> s >> p;
s--;
for (int i = 0; i < p; ++i) {
int r;
cin >> r;
restaurant[--r] = true;
}
for (int i = 0; i < n; ++i) {
if (discovered[i] == -1) dfs(i);
}
cout << topologicalSort();
}
|
37c9cb1b3b9f4245aad29fb8ed4f681172a4c7f1
|
a8e9ecef19ede99dfb4cd4516c7a243d565d726a
|
/src/ParseDotGraph.hpp
|
7cb8bba961b99ac0f014ca7a9836fc36b16cd041
|
[
"MIT"
] |
permissive
|
oesse/find-critical-path
|
b6caf76a8f6652bcc0eb48ff93421cd39b598854
|
1cd6ebd2ef1238307d5d63f2fe895fcbede5fc10
|
refs/heads/master
| 2020-09-03T02:43:58.701461
| 2019-11-05T08:13:48
| 2019-11-05T08:47:06
| 219,365,512
| 2
| 0
|
MIT
| 2019-11-05T08:47:08
| 2019-11-03T21:06:05
|
C++
|
UTF-8
|
C++
| false
| false
| 303
|
hpp
|
ParseDotGraph.hpp
|
#pragma once
#include <functional>
#include <istream>
using OnEdgeFunction = std::function<void(std::string, std::string)>;
void parseDotGraph(
std::istream &in,
const OnEdgeFunction &onEdge = [](const auto & /* srcId */,
const auto & /* destId */) {});
|
7894536915f298fcbe11046f5309dcae61b85bc0
|
4cec1ac5a533800299efb9929ffda16b8e28da56
|
/minheap.h
|
ead8c67b4b9e637a4189900a41314e22d49993e2
|
[] |
no_license
|
xjh199923/MinHeap
|
9f4e3857511a113bf646215b022c4079ecb5e88c
|
a4ec91e3a3b7822b81c96cc5f68e6a306959bab3
|
refs/heads/master
| 2020-08-29T22:08:46.371163
| 2019-10-29T02:24:37
| 2019-10-29T02:24:37
| 218,186,340
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,800
|
h
|
minheap.h
|
template<class E>
class MinHeap
{
private:
E *heap;//存放元素的数组
int count;//当前储存个数
int maxsize;//最小堆最多允许个数
void siftdown(int start,int m);//从start到m下滑调整成为最小堆
void siftup(int start);//从start到0上滑调整成为最小堆
int tmp;//封装一个tmp来计算比较次数
public:
MinHeap(int sz=1000);//构造函数建立空堆
MinHeap(E arr[],int n);//构造函数,通过一个数组建立堆
~MinHeap(){delete []heap;}//析构函数
bool Insert(E &x);//将x插入到最小堆中
bool Remove(E &x);//删除堆顶上的最小元素
bool Isempty()//判断堆是否为空
{
return (count==0)?true:false;
}
bool Isfull()//判断堆是否满
{
return (count==maxsize)?true:false;
}
void makeempty()
{
count=0;
}
void show();//打印当前堆的数据
};
template<class E>
MinHeap<E>::MinHeap(int sz)
{
maxsize=sz;
heap=new E[maxsize];
if(heap==NULL)
{
cerr<<"堆存储分配失败!"<<endl;
exit(1);
}
count=0;
tmp=0;
};
template<class E>
MinHeap<E>::MinHeap(E arr[],int n)
{
tmp=0;
if(10<n)
maxsize=n;
else
maxsize=10;
heap=new E[maxsize];
if(heap==NULL)
{
cerr<<"堆存储分配失败!"<<endl;
exit(1);
}
for(int i=0;i<n;i++)
{
heap[i]=arr[i];
}
count=n;//复制堆数组,建立当前大小
int pos=(count-2)/2;//找最初调整位置,最后分支结点
while(pos>=0)//自底向上逐步扩大形成堆
{
siftdown(pos,count-1);//局部自上向下下滑调整
pos--;
}
};
//最小堆下滑调整算法
template<class E>
void MinHeap<E>::siftdown(int start,int m)
{//私有函数,从start开始到m为止,自上向下比较,如果子女的值小于父节点的值,则关键码小的上浮,继续向下层比较,这样将一个集合局部调整为最小堆
int i=start,j=2*i+1;//j是i的左子女位置
E temp=heap[i];
while(j<=m)//检查是否到最后位置
{
if(j<m&&heap[j]>heap[j+1])//让j指向两个子女的小者
j++;
tmp++;
if(temp<=heap[j])//小则不做调整
break;
else//否则小者上移动,i,j,下降
{
heap[i]=heap[j];
i=j;j=2*i+1;
}
}
heap[i]=temp;//回放temp中暂存的元素
};
//最小堆上滑调整算法
template<class E>
void MinHeap<E>::siftup(int start)
{//私有函数,从start开始到结点0为止,自下向上比较,如果子女的值小于父节点的值,则互相交换,这样将一个集合局部调整为最小堆
int j=start,i=(j-1)/2;
E temp=heap[j];
while(j>0)//沿父节点路径向上直到极限
{
if(heap[i]<=temp)//父节点不调整
{
tmp++;
break;
}
else
{
heap[j]=heap[i];
j=i;
i=(i-1)/2;
}
}
heap[j]=temp;
};
//最小堆插入算法
template<class E>
bool MinHeap<E>::Insert(E &x)
{
if(count==maxsize)
{
cerr<<"Heap Full"<<endl;
return false;
}
heap[count]=x;//插入
siftup(count);//向上调整
count++;//当前堆加一
return true;
};
/*通常,从最小堆删除具有最小关键码记录的操作是将最小堆的堆顶元素,即其完全二又
树的顺序表示的第0号元素删去。在把这个元素取走后,一般以堆的最后一个结点填补取
走的堆顶元素,并将堆的实际元素个数减1。但是用最后一个元素取代堆顶元素将破书钱:
需要调用siftDown算法从堆顶向下进行调整。
*/
template<class E>
bool MinHeap<E>::Remove(E &x)
{
if(!count)
{
cout<<"Heap Empty!"<<endl;
return false;//堆空返回false
}
x=heap[0];
heap[0]=heap[count-1];//最后元素填补到根结点
count--;
siftdown(0,count-1);//向下调整
return true;
};
template<class E>
void MinHeap<E>::show()
{
E m;
while(count>0)
{
Remove(m);
cout<<m<<" ";
}
cout<<"\n最小堆排序的比较次数为:"<<tmp<<"次!"<<endl;
}
|
47a690ead838ee116b9404850b6a2f71b010a804
|
71decf3230d325a9586b9971d480d02b7bf7c86c
|
/cpp/archive/2020/03/21/Codeforces___acm_sgu_ru_archive___156__Strange_Graph/main.cpp
|
43f97f3ad926be322cc7c710265e07d5c235dd42
|
[] |
no_license
|
jaichhabra/contest
|
4d92fc8c50fdc7e6716e7b415688520775d57113
|
2cdd1ed4e2e98cc6eb86d66fe0d4cba8a0c47372
|
refs/heads/master
| 2021-04-14T16:16:45.203314
| 2020-03-22T17:37:23
| 2020-03-22T17:37:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,222
|
cpp
|
main.cpp
|
#include "../../libs/common.h"
#include "../../libs/debug.h"
#include "../../libs/dsu.h"
struct Edge {
int a;
int b;
bool visited;
};
vector<vector<int>> g;
vector<int> types;
vector<vector<int>> typeG;
vector<int> trace;
vector<Edge> edges;
vector<bool> occur;
vector<vector<int>> pend;
dsu::DSU<10000> dset;
void Dfs(int e) {
int type = types[edges[e].b];
while (!typeG[type].empty()) {
int back = typeG[type].back();
typeG[type].pop_back();
if (edges[back].visited) {
continue;
}
if (types[edges[back].a] == types[edges[back].b]) {
continue;
}
edges[back].visited = true;
if (types[edges[back].a] != type) {
swap(edges[back].a, edges[back].b);
}
Dfs(back);
}
trace.push_back(e);
}
void solve(int testId, istream &in, ostream &out) {
int n, m;
in >> n >> m;
g.resize(n);
types.resize(n, -1);
trace.reserve(n + 1);
edges.resize(m);
typeG.reserve(n);
occur.resize(n);
pend.resize(n);
for (int i = 0; i < m; i++) {
int a, b;
in >> a >> b;
a--;
b--;
edges[i].a = a;
edges[i].b = b;
g[edges[i].a].push_back(i);
g[edges[i].b].push_back(i);
}
for (int i = 0; i < n; i++) {
if (types[i] != -1) {
continue;
}
types[i] = typeG.size();
typeG.emplace_back();
if (g[i].size() == 2) {
continue;
}
for (int e : g[i]) {
int node = edges[e].a == i ? edges[e].b : edges[e].a;
if (g[node].size() == 2) {
continue;
}
types[node] = types[i];
}
}
for (int i = 0; i < n; i++) {
typeG[types[i]].insert(typeG[types[i]].end(), g[i].begin(), g[i].end());
}
dbg(typeG);
for (auto &e : edges) {
dset.merge(e.a, e.b);
}
bool valid = true;
for (int i = 0; i < n; i++) {
if (dset.find(i) != dset.find(0)) {
valid = false;
}
}
for (int i = 0; i < typeG.size(); i++) {
if (typeG[i].size() % 2) {
valid = false;
}
}
if (!valid) {
out << -1;
return;
}
for (int i = 0; i < edges.size(); i++) {
if (types[edges[i].a] != types[edges[i].b]) {
edges[i].visited = true;
Dfs(i);
break;
}
}
reverse(trace.begin(), trace.end());
dbg(g);
dbg(typeG);
dbg(types);
dbg(trace);
for (int t : trace) {
occur[edges[t].a] = true;
occur[edges[t].b] = true;
dbg(edges[t].a, edges[t].b);
}
for (int i = 0; i < n; i++) {
if (!occur[i]) {
pend[types[i]].push_back(i);
}
}
vector<int> ans;
ans.reserve(n);
ans.push_back(edges[trace[0]].a);
ans.push_back(edges[trace[0]].b);
for (int i = 1; i < trace.size(); i++) {
if (edges[trace[i - 1]].b != edges[trace[i]].a) {
int t = types[edges[trace[i]].a];
if (!pend[t].empty()) {
ans.insert(ans.end(), pend[t].begin(), pend[t].end());
pend[t].clear();
}
ans.push_back(edges[trace[i]].a);
}
ans.push_back(edges[trace[i]].b);
}
if (ans.size() > 1 && ans[0] == ans[ans.size() - 1]) {
ans.pop_back();
}
for (int i = 0; i < pend.size(); i++) {
if (!pend[i].empty()) {
ans.insert(ans.end(), pend[i].begin(), pend[i].end());
}
}
for (int x : ans) {
out << x + 1 << ' ';
}
}
RUN_ONCE
|
1c11dc05c662ca0143f43fea07e037fd5ca335cf
|
8abc331137bf2bbcc88dc691a22fd6a84f9a1683
|
/852.Peak Index in a Mountain Array/main.cpp
|
7fcda23117a96209ff94fc029634e8c22a061252
|
[
"Apache-2.0"
] |
permissive
|
Kingpie/leetcode
|
3cfbf18653b8b7c8f5b4b7a01bb350665e59fb8f
|
b5fd90a12f34f5baf24a3d4fa04c0914dd3e000f
|
refs/heads/master
| 2021-04-10T14:41:00.312568
| 2020-05-20T15:20:05
| 2020-05-20T15:20:05
| 248,941,566
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,126
|
cpp
|
main.cpp
|
/*Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1].
Example 1:
Input: [0,1,0]
Output: 1
Example 2:
Input: [0,2,1,0]
Output: 1
Note:
3 <= A.length <= 10000
0 <= A[i] <= 10^6
A is a mountain, as defined above.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/peak-index-in-a-mountain-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
class Solution {
public:
int peakIndexInMountainArray(vector<int>& A) {
int start = 0,end = A.size()-1;
while(start<end){
int mid = start+(end-start)/2;
if(A[mid]>A[mid-1]&&A[mid]>A[mid+1]) return mid;
else if(A[mid]>A[mid-1]){
start = mid+1;
}else{
end = mid-1;
}
}
return start;
}
};
|
e5561a824f75b30ef42c09fe2251ce465f797b0d
|
1dd1de8e298e95077fdd471c240d3abc5e11a510
|
/unittests/BackendCore/BackendCallTests.cpp
|
f7d0ed28176e10c4c6caf7be27717d354f268ad1
|
[
"Apache-2.0"
] |
permissive
|
thanm/dragongo
|
e4255166526071baaa515f7b679f0cbdfca6d07e
|
664cb6ae179fe512165971df694bb38da9f695ec
|
refs/heads/master
| 2022-10-27T13:03:12.288529
| 2022-10-11T19:53:58
| 2022-10-11T19:53:58
| 68,115,768
| 18
| 2
| null | 2017-05-18T12:44:14
| 2016-09-13T14:24:20
|
C++
|
UTF-8
|
C++
| false
| false
| 5,840
|
cpp
|
BackendCallTests.cpp
|
//===- llvm/tools/dragongo/unittests/BackendCore/BackendCallTests.cpp ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "TestUtils.h"
#include "go-llvm-backend.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "gtest/gtest.h"
using namespace llvm;
using namespace goBackendUnitTests;
namespace {
TEST(BackendCallTests, TestSimpleCall) {
FcnTestHarness h("foo");
Llvm_backend *be = h.be();
Bfunction *func = h.func();
Location loc;
Btype *bi64t = be->integer_type(false, 64);
Btype *bpi64t = be->pointer_type(bi64t);
Bexpression *fn = be->function_code_expression(func, loc);
std::vector<Bexpression *> args;
args.push_back(mkInt32Const(be, int64_t(3)));
args.push_back(mkInt32Const(be, int64_t(6)));
args.push_back(be->zero_expression(bpi64t));
Bexpression *call = be->call_expression(func, fn, args, nullptr, h.loc());
Bvariable *x = h.mkLocal("x", bi64t, call);
h.mkReturn(be->var_expression(x, VE_rvalue, loc));
const char *exp = R"RAW_RESULT(
%call.0 = call i64 @foo(i8* nest undef, i32 3, i32 6, i64* null)
store i64 %call.0, i64* %x
%x.ld.0 = load i64, i64* %x
ret i64 %x.ld.0
)RAW_RESULT";
bool isOK = h.expectBlock(exp);
EXPECT_TRUE(isOK && "Block does not have expected contents");
bool broken = h.finish(PreserveDebugInfo);
EXPECT_FALSE(broken && "Module failed to verify.");
}
TEST(BackendCallTests, CallToVoid) {
FcnTestHarness h("foo");
Llvm_backend *be = h.be();
Bfunction *func = h.func();
Location loc;
// Declare a function bar with no args and no return.
Btype *befty = mkFuncTyp(be, L_END);
bool is_decl = true; bool is_inl = false;
bool is_vis = true; bool is_split = true;
Bfunction *befcn = be->function(befty, "bar", "bar",
is_vis, is_decl, is_inl, is_split,
false, loc);
// Create call to it
Bexpression *fn = be->function_code_expression(befcn, loc);
std::vector<Bexpression *> args;
Bexpression *call = be->call_expression(func, fn, args, nullptr, loc);
h.mkExprStmt(call);
const char *exp = R"RAW_RESULT(
call void @bar(i8* nest undef)
)RAW_RESULT";
bool isOK = h.expectBlock(exp);
EXPECT_TRUE(isOK && "Block does not have expected contents");
bool broken = h.finish(StripDebugInfo);
EXPECT_FALSE(broken && "Module failed to verify.");
}
TEST(BackendCallTests, MultiReturnCall) {
FcnTestHarness h;
Llvm_backend *be = h.be();
// Create function with multiple returns
Btype *bi64t = be->integer_type(false, 64);
Btype *bi32t = be->integer_type(false, 32);
Btype *bi8t = be->integer_type(false, 8);
BFunctionType *befty1 = mkFuncTyp(be,
L_PARM, be->pointer_type(bi8t),
L_RES, be->pointer_type(bi8t),
L_RES, be->pointer_type(bi32t),
L_RES, be->pointer_type(bi64t),
L_RES, bi64t,
L_END);
Bfunction *func = h.mkFunction("foo", befty1);
// Emit a suitable return suitable for "foo" as declared above.
// This returns a constant expression.
std::vector<Bexpression *> rvals = {
be->nil_pointer_expression(),
be->nil_pointer_expression(),
be->nil_pointer_expression(),
mkInt64Const(be, 101) };
Bstatement *s1 = h.mkReturn(rvals, FcnTestHarness::NoAppend);
{
const char *exp = R"RAW_RESULT(
%cast.0 = bitcast { i8*, i32*, i64*, i64 }* %sret.formal.0 to i8*
%cast.1 = bitcast { i8*, i32*, i64*, i64 }* @const.0 to i8*
call void @llvm.memcpy.p0i8.p0i8.i64(i8* %cast.0, i8* %cast.1, i64 32, i32 8, i1 false)
ret void
)RAW_RESULT";
bool isOK = h.expectStmt(s1, exp);
EXPECT_TRUE(isOK && "First return stmt does not have expected contents");
}
// This is intended to be something like
//
// return p8, nil, nil, 101
//
Bvariable *p1 = func->getNthParamVar(0);
Bexpression *vex = be->var_expression(p1, VE_rvalue, Location());
std::vector<Bexpression *> rvals2 = {
vex,
be->nil_pointer_expression(),
be->nil_pointer_expression(),
mkInt64Const(be, 101) };
Bstatement *s2 = h.mkReturn(rvals2, FcnTestHarness::NoAppend);
{
const char *exp = R"RAW_RESULT(
%p0.ld.0 = load i8*, i8** %p0.addr
%field.0 = getelementptr inbounds { i8*, i32*, i64*, i64 }, { i8*, i32*, i64*, i64 }* %tmp.0, i32 0, i32 0
store i8* %p0.ld.0, i8** %field.0
%field.1 = getelementptr inbounds { i8*, i32*, i64*, i64 }, { i8*, i32*, i64*, i64 }* %tmp.0, i32 0, i32 1
store i32* null, i32** %field.1
%field.2 = getelementptr inbounds { i8*, i32*, i64*, i64 }, { i8*, i32*, i64*, i64 }* %tmp.0, i32 0, i32 2
store i64* null, i64** %field.2
%field.3 = getelementptr inbounds { i8*, i32*, i64*, i64 }, { i8*, i32*, i64*, i64 }* %tmp.0, i32 0, i32 3
store i64 101, i64* %field.3
%cast.3 = bitcast { i8*, i32*, i64*, i64 }* %sret.formal.0 to i8*
%cast.4 = bitcast { i8*, i32*, i64*, i64 }* %tmp.0 to i8*
call void @llvm.memcpy.p0i8.p0i8.i64(i8* %cast.3, i8* %cast.4, i64 32, i32 8, i1 false)
ret void
)RAW_RESULT";
bool isOK = h.expectStmt(s2, exp);
EXPECT_TRUE(isOK && "Second return stmt does not have expected contents");
}
// If statement
Location loc;
Bexpression *ve2 = be->var_expression(p1, VE_rvalue, Location());
Bexpression *npe = be->nil_pointer_expression();
Bexpression *cmp = be->binary_expression(OPERATOR_EQEQ, ve2, npe, loc);
h.mkIf(cmp, s1, s2);
bool broken = h.finish(StripDebugInfo);
EXPECT_FALSE(broken && "Module failed to verify.");
}
}
|
50067799aa85eff413fe395162eefff9ba2f3573
|
9b291d036ee7d4364734caab6fcf061e0e6de147
|
/Game/basicai/AIController.h
|
6793b1e6faecbaf4cdb4a179afce91fb2295932a
|
[] |
no_license
|
PSP-Archive/Rip-Off
|
0227db92c34b6f084a56ba122baa4b5bd74e6e6d
|
968c21162b0b44a539664400a0047ffaad4ad764
|
refs/heads/main
| 2023-04-13T12:52:36.275617
| 2021-04-24T15:15:23
| 2021-04-24T15:15:23
| 361,194,734
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 634
|
h
|
AIController.h
|
#pragma once
#include "engine/AI_ImplementationIF.h"
#include "engine/ControllerIF.h"
#include "engine/Ship.h"
class AIController : public ControllerIF {
public:
AIController();
~AIController();
void Update(float frameTime);
// set current AI implementation
// The controller will call delete on it when deleted itself
void SetImpl(AI_ImplementationIF* impl);
// currently without function, included for the coming AI ACW
// Might be good to call this for the different agent types, just in case
void setAgentType(int AIType);
void Init();
void Cleanup();
private:
AI_ImplementationIF* mp_impl;
int m_AIType;
};
|
a6b5e5c03a65167660914b88c3ad39ec6eddc843
|
0237a503f80482bbda913f1f9a500aa1d712f379
|
/TaskManager/TaskManager/WindowDlg.cpp
|
c2d5e6e4a246a686e264d0dc43e3f83af154a696
|
[] |
no_license
|
fa1c0n1/funny_learning
|
bce89d6edff46a0a6f78aa1fb2b0a95168e84f1e
|
10f500a1e06743379539b14e8a04a79d95a6a796
|
refs/heads/master
| 2021-12-29T18:52:38.588889
| 2021-12-27T01:54:52
| 2021-12-27T01:54:52
| 53,765,191
| 2
| 2
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,736
|
cpp
|
WindowDlg.cpp
|
// WindowDlg.cpp : implementation file
//
#include "stdafx.h"
#include "TaskManager.h"
#include "WindowDlg.h"
#include "afxdialogex.h"
#include <strsafe.h>
int CWindowDlg::m_nWndCnt = 0;
// CWindowDlg dialog
IMPLEMENT_DYNAMIC(CWindowDlg, CBaseDialog)
CWindowDlg::CWindowDlg(CWnd* pParent /*=NULL*/)
: CBaseDialog(CWindowDlg::IDD, pParent)
{
}
CWindowDlg::~CWindowDlg()
{
}
void CWindowDlg::DoDataExchange(CDataExchange* pDX)
{
CBaseDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_WINDOW_LIST, m_wndListCtrl);
}
BEGIN_MESSAGE_MAP(CWindowDlg, CBaseDialog)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CWindowDlg message handlers
BOOL CWindowDlg::OnInitDialog()
{
CBaseDialog::OnInitDialog();
// TODO: Add extra initialization here
InitControl();
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
//初始化控件
void CWindowDlg::InitControl()
{
CRect rect;
m_wndListCtrl.SetExtendedStyle(m_wndListCtrl.GetExtendedStyle() | LVS_EX_FULLROWSELECT
| LVS_EX_GRIDLINES);
m_wndListCtrl.GetClientRect(&rect);
m_wndListCtrl.AddColumns(2,
_T("窗口标题"), rect.Width() / 3 * 2,
_T("窗口句柄"), rect.Width() / 3);
m_wndListCtrl.InsertColumn(3, _T("窗口类名"), LVCFMT_LEFT, rect.Width() / 3, 3);
}
BOOL CALLBACK CWindowDlg::EnumWndProc(_In_ HWND hwnd, _In_ LPARAM lParam)
{
CMyListCtrl *pWndList = (CMyListCtrl *)lParam;
TCHAR szWndName[1024] = {};
//获取窗口标题
::GetWindowText(hwnd, szWndName, _countof(szWndName));
if (::IsWindowVisible(hwnd) == TRUE && wcslen(szWndName) > 0) {
//窗口没有被隐藏且窗口标题长度不为0, 则显示窗口信息
TCHAR szWndClassName[1024] = {0};
TCHAR szWndHandle[32] = {0};
//获取窗口的类名
GetClassName(hwnd, szWndClassName, _countof(szWndClassName));
//格式化窗口句柄
StringCchPrintf(szWndHandle, _countof(szWndHandle), _T("0x%016X"), hwnd);
pWndList->AddItems(m_nWndCnt, 3, szWndName, szWndHandle, szWndClassName);
m_nWndCnt++;
}
return TRUE;
}
//遍历窗口
void CWindowDlg::ListWindow()
{
m_nWndCnt = 0;
EnumWindows(&EnumWndProc, (LPARAM)&m_wndListCtrl);
}
void CWindowDlg::OnSize(UINT nType, int cx, int cy)
{
CBaseDialog::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
CRect clientRect;
GetClientRect(&clientRect);
clientRect.top += 10;
clientRect.bottom -= 10;
clientRect.left += 10;
clientRect.right -= 10;
if (m_wndListCtrl)
m_wndListCtrl.MoveWindow(&clientRect);
}
//刷新窗口列表
void CWindowDlg::RefreshSelf()
{
m_wndListCtrl.DeleteAllItems();
ListWindow();
}
|
e38c396aff2a618fc80e6744c21dfe691d93b7bb
|
e50a85ac350314d6ddc6bad162cead8c6d939be4
|
/AIPlayer.cpp
|
76c8ebf288aa1c654d5969e55cec17f361182b12
|
[] |
no_license
|
Jerorfigan/BlackJack
|
26c94d226f724a3c91594b088b2e82e4002adedf
|
f88efd8d2927e3eb46b8d6b8b1646277a0c709bc
|
refs/heads/master
| 2021-01-22T02:53:06.443801
| 2013-03-12T01:59:12
| 2013-03-12T01:59:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,125
|
cpp
|
AIPlayer.cpp
|
#include "stdafx.h"
#include "AIPlayer.h"
namespace BlackJack
{
/*******************/
/* Virtual methods */
/*******************/
///////////////////////
// CreateStartingBet //
///////////////////////
bool
AIPlayer::CreateStartingBet()
{
// Bet a random percentage between 15%-30% of total chips.
float percentage = RandomBetween( 15, 30 ) / 100.0f;
uint bet = static_cast< uint >( m_chips * percentage );
m_chips -= bet;
m_currentBets[ 0 ] = bet;
return true;
}
//////////////////////
// SelectHandStatus //
//////////////////////
bool
AIPlayer::SelectHandStatus( uint handIndex )
{
uint value;
m_hands[ handIndex ].GetValue( value );
// AI plays like dealer while taking advantage of splitting.
if( CanSplit() )
{
m_handStatuses[ handIndex ] = Split;
}
else if( value < 17 )
{
m_handStatuses[ handIndex ] = Hit;
}
else
{
m_handStatuses[ handIndex ] = Stand;
}
return true;
}
///////////////
// PlayAgain //
///////////////
bool
AIPlayer::PlayAgain( bool &again )
{
// AI doesnt influence player again outcome
return true;
}
}
|
7d25cb173bc51b56d17397d346e3caa8a564101c
|
5b0ba8d8f67ae18e12f914f1f3495a88d20597ee
|
/POC_UAV/neural/NeuralNet.h
|
4112f693a3558449e4b611813eff6a3dd20b2ca7
|
[] |
no_license
|
td1tfx/POC_UAV
|
885a9934a7b2d1c32f7427ccedc125ccc78b78a8
|
af9fd9860b5eeed275281bf7055759c4e9a24d01
|
refs/heads/master
| 2020-04-12T06:21:59.901349
| 2017-02-20T10:04:59
| 2017-02-20T10:04:59
| 63,743,225
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,376
|
h
|
NeuralNet.h
|
#pragma once
#include <stdio.h>
#include <vector>
#include <string.h>
#include <cmath>
#include "NeuralLayer.h"
#include "lib/libconvert.h"
#include "MNISTFunctions.h"
#include "Option.h"
#include "io.h"
#include <direct.h>
//学习模式
typedef enum
{
Batch = 0,
Online = 1,
MiniBatch = 2,
//输入向量如果0的项较多,在线学习会比较快
//通常情况下批量学习会考虑全局优先,应为首选
//在线学习每次都更新所有键结值,批量学习每一批数据更新一次键结值
} NeuralNetLearnMode;
//计算模式(no use)
/*
typedef enum
{
ByLayer,
ByNode,
} NeuralNetCalMode;
*/
//工作模式
typedef enum
{
Fit = 0, //拟合
Classify = 1, //分类,会筛选最大值设为1,其他设为0
Probability = 2, //几率,结果会归一化
} NeuralNetWorkMode;
//神经网
class NeuralNet
{
public:
NeuralNet();
virtual ~NeuralNet();
//神经层
std::vector<NeuralLayer*> Layers;
std::vector<NeuralLayer*>& getLayerVector() { return Layers; }
int Id;
NeuralLayer*& getLayer(int number) { return Layers[number]; }
NeuralLayer*& getFirstLayer() { return Layers[0]; }
NeuralLayer*& getLastLayer() { return Layers.back(); }
int getLayerCount() { return Layers.size(); };
int InputNodeCount;
int OutputNodeCount;
int InputTestNodeCount;
int OutputTestNodeCount;
NeuralNetLearnMode LearnMode = Batch;
int MiniBatchCount = -1;
void setLearnMode(NeuralNetLearnMode lm, int lb = -1);
double LearnSpeed = 0.5; //学习速度
void setLearnSpeed(double s) { LearnSpeed = s; }
double Lambda = 0.0; //正则化参数,防止过拟合
void setRegular(double l) { Lambda = l; }
NeuralNetWorkMode WorkMode = Fit;
void setWorkMode(NeuralNetWorkMode wm);
void createLayers(int layerCount); //包含输入和输出层
void learn();
void train(int times = 1000000, int interval = 1000, double tol = 1e-3, double dtol = 0); //训练过程
void activeOutputValue(double* input, double* output, int groupCount); //计算一组输出
void setInputData(double* input, int nodeCount, int groupid);
void setExpectData(double* expect, int nodeCount, int groupid);
void getOutputData(int nodeCount, int groupCount, double* output);
//数据
double* _train_inputData = nullptr;
double* _train_expectData = nullptr;
double* _train_outputData = nullptr;
int _train_groupCount = 0; //实际的数据量
void readData(const char* filename);
void readTestData(const char* filename);
void resetGroupCount(int n);
double* _test_inputData = nullptr;
double* _test_expectData = nullptr;
int _test_groupCount = 0;
//具体设置
virtual void createByData(int layerCount = 3, int nodesPerLayer = 7); //具体的网络均改写这里
void outputBondWeight(const char* filename = nullptr);
void createByLoad(const char* filename);
//NeuralNetCalMode activeMode = ByNode;
//NeuralNetCalMode backPropageteMode = ByNode;
void readMNIST();
Option _option;
void loadOptoin(const char* filename);
void init();
void resetOption(int nodeId, int isSingleMod = 0, int linkId = 0, int trainType = 0);
void run();
void inTrainData(double* inData, int inputGroupCount);
double* runOutput();
void selectTest();
void test();
void runTest();
void printResult(int nodeCount, int groupCount, double* output, double* expect);
std::string toString(int a);
};
|
23e329e71d8199ce98cf11fce9aa37ee91588d8b
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_log_2241.cpp
|
0bee195faae1a4d15a4a6f6b511e05e5b95cdcef
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 43
|
cpp
|
Kitware_CMake_repos_log_2241.cpp
|
fprintf(fout, "int foo() { return 0; }\n");
|
4052033005737d7c6e7b4471dbc427b552ff921a
|
fd9f5186fa5d19db077dbf302fe9c940cb42e82f
|
/src/graph/executor/query/GetVerticesExecutor.cpp
|
4e5e3c85c9a5646ee60b574cc133154c734acc8e
|
[
"Apache-2.0"
] |
permissive
|
vesoft-inc/nebula
|
a0b9af548e124e59ecbfb0c5152098a1020b621c
|
7c32088dec1891870a24aaa37ee5818e69f5ad6d
|
refs/heads/master
| 2023-08-17T00:00:29.022525
| 2023-08-16T04:02:03
| 2023-08-16T04:02:03
| 146,459,443
| 11,007
| 1,220
|
Apache-2.0
| 2023-09-05T05:48:16
| 2018-08-28T14:25:09
|
C++
|
UTF-8
|
C++
| false
| false
| 2,362
|
cpp
|
GetVerticesExecutor.cpp
|
// Copyright (c) 2020 vesoft inc. All rights reserved.
//
// This source code is licensed under Apache 2.0 License.
#include "graph/executor/query/GetVerticesExecutor.h"
using nebula::storage::StorageClient;
using nebula::storage::StorageRpcResponse;
using nebula::storage::cpp2::GetPropResponse;
namespace nebula {
namespace graph {
folly::Future<Status> GetVerticesExecutor::execute() {
return getVertices();
}
folly::Future<Status> GetVerticesExecutor::getVertices() {
SCOPED_TIMER(&execTime_);
auto *gv = asNode<GetVertices>(node());
StorageClient *storageClient = qctx()->getStorageClient();
auto res = buildRequestDataSet(gv);
NG_RETURN_IF_ERROR(res);
auto vertices = std::move(res).value();
if (vertices.rows.empty()) {
// TODO: add test for empty input.
return finish(
ResultBuilder().value(Value(DataSet(gv->colNames()))).iter(Iterator::Kind::kProp).build());
}
time::Duration getPropsTime;
StorageClient::CommonRequestParam param(gv->space(),
qctx()->rctx()->session()->id(),
qctx()->plan()->id(),
qctx()->plan()->isProfileEnabled());
return DCHECK_NOTNULL(storageClient)
->getProps(param,
std::move(vertices),
gv->props(),
nullptr,
gv->exprs(),
gv->dedup(),
gv->orderBy(),
gv->getValidLimit(),
gv->filter())
.via(runner())
.ensure([this, getPropsTime]() {
SCOPED_TIMER(&execTime_);
addState("total_rpc", getPropsTime);
})
.thenValue([this, gv](StorageRpcResponse<GetPropResponse> &&rpcResp) {
memory::MemoryCheckGuard guard;
SCOPED_TIMER(&execTime_);
addStats(rpcResp);
return handleResp(std::move(rpcResp), gv->colNames());
});
}
StatusOr<DataSet> GetVerticesExecutor::buildRequestDataSet(const GetVertices *gv) {
if (gv == nullptr) {
return nebula::DataSet({kVid});
}
// Accept Table such as | $a | $b | $c |... as input which one column indicate
// src
auto valueIter = ectx_->getResult(gv->inputVar()).iter();
return buildRequestDataSetByVidType(valueIter.get(), gv->src(), gv->dedup());
}
} // namespace graph
} // namespace nebula
|
5829461da668e50d26a2eabd99a6ed1e21c0b2a5
|
6f9e8e401a8a4253838fb7310cc7baaafcf52616
|
/json.cpp
|
eacaaecedd9f90c98c15419107b9a908e6a239f1
|
[
"MIT"
] |
permissive
|
alex-sherman/embedded-json
|
e7086ef2d4f4bf98b6454b4397de20ae7ce91b4d
|
d1aeeede32baeb28525718d85b66f078aa1703fb
|
refs/heads/master
| 2022-09-24T13:40:56.989940
| 2022-09-15T17:00:15
| 2022-09-15T17:00:15
| 64,700,309
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,581
|
cpp
|
json.cpp
|
/*
Copyright (c) 2001, Interactive Matter, Marcus Nowotny
Based on the cJSON Library, Copyright (C) 2009 Dave Gamble
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.
*/
// aJSON
// aJson Library for Arduino.
// This library is suited for Atmega328 based Arduinos.
// The RAM on ATmega168 based Arduinos is too limited
/******************************************************************************
* Includes
******************************************************************************/
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <float.h>
#include <ctype.h>
#ifdef __AVR__
#include <avr/pgmspace.h>
#else
#include <pgmspace.h>
#endif
#include "json.h"
/******************************************************************************
* Definitions
******************************************************************************/
//Default buffer sizes - buffers get initialized and grow acc to that size
#define BUFFER_DEFAULT_SIZE 4
//how much digits after . for float
#define FLOAT_PRECISION 5
using namespace Json;
Object *Object::clone() {
Object *copy = new Object(*this);
for(auto &kvp : *this) {
if(kvp.value.isArray())
kvp.value = *kvp.value.asArray().clone();
if(kvp.value.isObject())
kvp.value = *kvp.value.asObject().clone();
if(kvp.value.isString())
kvp.value = kvp.value.asString();
}
return copy;
}
Json::Value Object::default_init() {
return Value::invalid();
}
Array *Array::clone() {
Array *copy = new Array(*this);
for(auto &kvp : *this) {
if(kvp.isArray())
kvp = *kvp.asArray().clone();
if(kvp.isObject())
kvp = *kvp.asObject().clone();
if(kvp.isString())
kvp = kvp.asString();
}
return copy;
}
Object::~Object() {
for(auto kvp : (*this)) {
kvp.value.free_parsed();
}
}
Array::~Array() {
for(auto kvp : (*this)) {
kvp.free_parsed();
}
}
class JsonMeasurer : public Print {
public:
size_t write(uint8_t ch) { _length += 1; return 1; }
size_t length() { return _length; }
private:
size_t _length;
};
int Json::measure(Value value) {
JsonMeasurer m;
Json::print(value, m);
return m.length();
}
bool
aJsonStream::available()
{
if (bucket != EOF)
return true;
while (stream()->available())
{
/* Make an effort to skip whitespace. */
int ch = this->getch();
if (ch > 32)
{
this->ungetch(ch);
return true;
}
}
return false;
}
int
aJsonStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
// In case input was malformed - can happen, this is the
// real world, we can end up in a situation where the parser
// would expect another character and end up stuck on
// stream()->available() forever, hence the 500ms timeout.
unsigned long i= millis()+500;
while ((!stream()->available()) && (millis() < i)) /* spin with a timeout*/;
return stream()->read();
}
void
aJsonStream::ungetch(char ch)
{
bucket = ch;
}
size_t
aJsonStream::write(uint8_t ch)
{
return stream()->write(ch);
}
size_t
aJsonStream::readBytes(uint8_t *buffer, size_t len)
{
for (size_t i = 0; i < len; i++)
{
int ch = this->getch();
if (ch == EOF)
{
return i;
}
buffer[i] = ch;
}
return len;
}
int
aJsonClientStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
while (!stream()->available() && stream()->connected()) /* spin */;
if (!stream()->available()) // therefore, !stream()->connected()
{
stream()->stop();
return EOF;
}
return stream()->read();
}
bool
aJsonStringStream::available()
{
if (bucket != EOF)
return true;
return inbuf_len > 0;
}
int
aJsonStringStream::getch()
{
if (bucket != EOF)
{
int ret = bucket;
bucket = EOF;
return ret;
}
if (!inbuf || !inbuf_len)
{
return EOF;
}
char ch = *inbuf++;
inbuf_len--;
return ch;
}
size_t
aJsonStringStream::write(uint8_t ch)
{
if (!outbuf || outbuf_len <= 1)
{
return 0;
}
*outbuf++ = ch; outbuf_len--;
*outbuf = 0;
return 1;
}
// Parse the input text to generate a number, and populate the result into item.
int aJsonStream::parseNumber(Value *item)
{
int i = 0;
int sign = 1;
int in = this->getch();
if (in == EOF)
{
return EOF;
}
// It is easier to decode ourselves than to use sscnaf,
// since so we can easier decide between int & double
if (in == '-')
{
//it is a negative number
sign = -1;
in = this->getch();
if (in == EOF)
{
return EOF;
}
}
if (in >= '0' && in <= '9') {
do
{
i = (i * 10) + (in - '0');
in = this->getch();
}
while (in >= '0' && in <= '9'); // Number?
}
//end of integer part � or isn't it?
if (!(in == '.' || in == 'e' || in == 'E'))
{
*item = Value(i * (int) sign);
}
//ok it seems to be a double
else
{
double n = (double) i;
int scale = 0;
int subscale = 0;
char signsubscale = 1;
if (in == '.')
{
in = this->getch();
do
{
n = (n * 10.0) + (in - '0'), scale--;
in = this->getch();
}
while (in >= '0' && in <= '9');
} // Fractional part?
if (in == 'e' || in == 'E') // Exponent?
{
in = this->getch();
if (in == '+')
{
in = this->getch();
}
else if (in == '-')
{
signsubscale = -1;
in = this->getch();
}
while (in >= '0' && in <= '9')
{
subscale = (subscale * 10) + (in - '0'); // Number?
in = this->getch();
}
}
n = sign * n * pow(10.0, ((double) scale + (double) subscale
* (double) signsubscale)); // number = +/- number.fraction * 10^+/- exponent
*item = Value(float(n));
}
//preserve the last character for the next routine
this->ungetch(in);
return 0;
}
|
509516f05ca6abcf09488f582a1f3effedefb63d
|
677c697f108901e5403c94ac4874d3a760faba44
|
/II/ChM_sem2/lab1/Polynomial.cpp
|
1aa359f51a99922ab4df525726b3ab8c6072be93
|
[] |
no_license
|
BunnyBoss75/Labs
|
f63e205e5ad8db487ae80bb5af3d641db6542343
|
6f01d265321a3d7f656899f1efdfc71f38416767
|
refs/heads/master
| 2020-09-14T10:24:46.010521
| 2020-07-04T09:26:05
| 2020-07-04T09:26:05
| 223,102,840
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,266
|
cpp
|
Polynomial.cpp
|
#include "Polynomial.h"
Polynomial::Polynomial() : polynomial(0) {}
Polynomial::Polynomial(std::initializer_list<double> init) : polynomial(init) {}
Polynomial::Polynomial(int size, double value) : polynomial(size, value) {}
Polynomial::Polynomial(const std::vector<double>& _polynimial): polynomial(_polynimial) {}
Polynomial::Polynomial(const Polynomial& other) : polynomial(other.polynomial) {}
Polynomial::Polynomial(Polynomial&& other) : polynomial(move(other.polynomial)) {}
Polynomial::~Polynomial() {}
bool Polynomial::operator==(const Polynomial& other) {
return this->polynomial == other.polynomial;
}
Polynomial& Polynomial::operator=(Polynomial&& other) {
this->polynomial = move(other.polynomial);
return *this;
}
Polynomial& Polynomial::operator=(const Polynomial& other){
this->polynomial = other.polynomial;
return *this;
}
Polynomial Polynomial::operator+(const Polynomial& other) {
Polynomial result(0);
if (this->polynomial.size() < other.polynomial.size()) {
result = other;
for (int i = 0; i < this->polynomial.size(); ++i) {
result.polynomial[i] += this->polynomial[i];
}
}
else {
result = *this;
for (int i = 0; i < other.polynomial.size(); ++i) {
result.polynomial[i] += other.polynomial[i];
}
}
return result;
}
Polynomial Polynomial::operator-(const Polynomial& other) {
Polynomial result(0);
if (this->polynomial.size() < other.polynomial.size()) {
result = other;
for (int i = 0; i < this->polynomial.size(); ++i) {
result.polynomial[i] -= this->polynomial[i];
}
}
else {
result = *this;
for (int i = 0; i < other.polynomial.size(); ++i) {
result.polynomial[i] -= other.polynomial[i];
}
}
return result;
}
Polynomial Polynomial::operator*(const Polynomial& other){
Polynomial result(this->polynomial.size() + other.polynomial.size() - 1);
for (int i = 0; i < this->polynomial.size(); ++i) {
for (int j = 0; j < other.polynomial.size(); ++j) {
result.polynomial[i + j] += this->polynomial[i] * other.polynomial[j];
}
}
return result;
}
Polynomial Polynomial::operator/(const Polynomial& other) {
int sizeThis = this->polynomial.size();
int sizeOther = other.polynomial.size();
int sizeResult = sizeThis - sizeOther + 1;
Polynomial result(sizeResult);
Polynomial temp(sizeOther);
for (int j = 0; j < sizeOther; ++j) {
temp.polynomial[j] = this->polynomial[sizeThis - sizeOther + j];
}
for (int i = sizeResult - 1; i > -1; --i) {
result.polynomial[i] = temp.polynomial[sizeOther - 1] / other.polynomial[sizeOther - 1];
if (i == 0) {
continue;
}
for (int j = sizeOther - 1; j > 0; --j) {
temp.polynomial[j] = temp.polynomial[j - 1] - result.polynomial[i] * other.polynomial[j - 1];
}
temp.polynomial[0] = this->polynomial[sizeThis - sizeOther - sizeResult + i];
}
return result;
}
Polynomial& Polynomial::operator+=(const Polynomial& other) {
int deltaDegree = this->polynomial.size() - other.polynomial.size();
if (deltaDegree < 0) {
this->polynomial.reserve(-deltaDegree);
for (int i = 0; i < -deltaDegree; ++i) {
this->polynomial.push_back(0);
}
}
for (int i = 0; i < other.polynomial.size(); ++i) {
this->polynomial[i] += other.polynomial[i];
}
return *this;
}
Polynomial& Polynomial::operator-=(const Polynomial& other) {
int deltaDegree = this->polynomial.size() - other.polynomial.size();
if (deltaDegree < 0) {
this->polynomial.reserve(-deltaDegree);
for (int i = 0; i < deltaDegree; ++i) {
this->polynomial.push_back(0);
}
}
for (int i = 0; i < other.polynomial.size(); ++i) {
this->polynomial[i] -= other.polynomial[i];
}
return *this;
}
Polynomial& Polynomial::operator*=(const Polynomial& other) {
this->polynomial = this->operator*(other).polynomial;
return *this;
}
Polynomial& Polynomial::operator/=(const Polynomial& other) {
this->polynomial = this->operator/(other).polynomial;
return *this;
}
Polynomial Polynomial::operator+(double number) {
Polynomial result(*this);
result.polynomial[0] += number;
return result;
}
Polynomial Polynomial::operator-(double number) {
Polynomial result(*this);
result.polynomial[0] -= number;
return result;
}
Polynomial Polynomial::operator*(double number) {
Polynomial result(*this);
for (int i = 0; i < result.polynomial.size(); ++i) {
result.polynomial[i] *= number;
}
return result;
}
Polynomial Polynomial::operator/(double number) {
Polynomial result(*this);
for (int i = 0; i < result.polynomial.size(); ++i) {
result.polynomial[i] /= number;
}
return result;
}
Polynomial& Polynomial::operator+=(double number) {
this->polynomial[0] += number;
return *this;
}
Polynomial& Polynomial::operator-=(double number) {
this->polynomial[0] -= number;
return *this;
}
Polynomial& Polynomial::operator*=(double number) {
for (int i = 0; i < this->polynomial.size(); ++i) {
this->polynomial[i] *= number;
}
return *this;
}
Polynomial& Polynomial::operator/=(double number) {
for (int i = 0; i < this->polynomial.size(); ++i) {
this->polynomial[i] /= number;
}
return *this;
}
double Polynomial::calculate(double x) {
double result = this->polynomial[0];
double temp = 1;
for (int i = 1; i < this->polynomial.size(); ++i) {
temp *= x;
result += temp * this->polynomial[i];
}
return result;
}
|
1ce356eadc703c9b0db202606b22b9f5cd668159
|
cd9b125ccfc18b1beae2bf0eb4a5825087122040
|
/shua_ti_刷题/360/test.cpp
|
841e4e77065953cd098727431f5964a441589542
|
[] |
no_license
|
Tianxintong/git
|
06538c66916c4bd55d2dd0d240f0a182f18cbfd5
|
b943e9338f70e84922dd6784da52dd97455c323a
|
refs/heads/master
| 2021-01-20T01:59:05.496269
| 2017-09-13T13:18:21
| 2017-09-13T13:18:21
| 89,354,253
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 462
|
cpp
|
test.cpp
|
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
struct st_task
{
uint16_t id;
uint32_t value;
uint64_t timeatsmp;
}
int main()
{
st_task = {};
uint64_t = 0x00010001;
}
/*
struct Data
{
char a;
int b;
int64_t c;
char d;
};
int main()
{
Data a[2][10];
cout<<a<<endl;
cout<<&a[1][15]<<endl;
// cout<<(a - &a[1][15])<<endl;
cout<<sizeof(Data)<<endl;;
cout<<15*sizeof(Data)<<endl;
return 0;
}
*/
|
004b3b5c737c68e276a65aa851c8701b4b71f866
|
939e6f79ca9b9411fcab2dbc2b31f73e42d3fa00
|
/tiled_resources_2d/include/gxu/gxu_pinhole_camera_dispatcher.h
|
9f3d9a65a5a74632209de8d609cc6d42ebc61e86
|
[] |
no_license
|
kingofthebongo2008/examples
|
f5f8d4149b83b454d788b53ac2ac440d77af9230
|
17d421d0f7fe9f20b32f3a9510c46eddc86353af
|
refs/heads/master
| 2023-06-10T05:07:55.712393
| 2020-07-21T12:23:34
| 2020-07-21T12:23:34
| 7,283,947
| 3
| 0
| null | 2023-05-31T20:09:46
| 2012-12-22T08:30:16
|
C++
|
UTF-8
|
C++
| false
| false
| 5,154
|
h
|
gxu_pinhole_camera_dispatcher.h
|
#pragma once
#include <gx/gx_pinhole_camera.h>
#include <gxu/gxu_camera_command.h>
#include <math/math_quaternion.h>
#include <math/math_graphics.h>
namespace gxu
{
namespace details
{
void turn_pinhole_camera(gx::pinhole_camera* camera, float angle_in_radians)
{
auto view_direction_ws = camera->forward();
auto up_direction_ws = camera->up();
auto quaternion = math::quaternion_axis_angle(up_direction_ws, angle_in_radians);
auto view_direction_ws_2 = math::rotate_vector3(view_direction_ws, quaternion);
camera->set_forward(view_direction_ws_2);
}
void aim_pinhole_camera(gx::pinhole_camera* camera, float angle_in_radians)
{
auto view_direction_ws_1 = camera->forward();
auto up_direction_ws_1 = camera->up();
auto cross = math::cross3(view_direction_ws_1, up_direction_ws_1);
auto quaternion = math::quaternion_axis_angle(cross, angle_in_radians);
auto view_direction_ws_2 = math::rotate_vector3(view_direction_ws_1, quaternion);
auto up_direction_ws_2 = math::rotate_vector3(up_direction_ws_1, quaternion);
camera->set_forward(view_direction_ws_2);
camera->set_up(up_direction_ws_2);
}
}
//processes stream of camera commands and dispatches them
//suitable for recording and playback
class pinhole_camera_command_dispatcher : public camera_command_dispatcher
{
public:
explicit pinhole_camera_command_dispatcher(gx::pinhole_camera* pinhole_camera) :
m_pinhole_camera(pinhole_camera)
{
}
private:
void on_move_forward(const move_camera_forward* command) override
{
auto view_direction_ws = m_pinhole_camera->forward();
auto normalized_view_direction_ws = math::normalize3(view_direction_ws);
auto distance = fabsf(command->m_distance);
auto distance_ws = math::splat(distance);
auto displacement_ws = math::mul(distance_ws, normalized_view_direction_ws);
m_pinhole_camera->m_view_position_ws = math::add(m_pinhole_camera->m_view_position_ws, displacement_ws);
}
void on_move_backward(const move_camera_backward* command) override
{
auto view_direction_ws = m_pinhole_camera->forward();
auto normalized_view_direction_ws = math::normalize3(view_direction_ws);
auto distance = -1.0f * fabsf(command->m_distance);
auto distance_ws = math::splat(distance);
auto displacement_ws = math::mul(distance_ws, normalized_view_direction_ws);
m_pinhole_camera->m_view_position_ws = math::add(m_pinhole_camera->m_view_position_ws, displacement_ws);
}
void on_turn_left(const turn_camera_left* command) override
{
details::turn_pinhole_camera(m_pinhole_camera, -1.0f * fabsf(command->m_angle_radians));
}
void on_turn_right(const turn_camera_right* command) override
{
details::turn_pinhole_camera(m_pinhole_camera, 1.0f * fabsf(command->m_angle_radians));
}
void on_aim_up(const aim_camera_up* command) override
{
details::aim_pinhole_camera(m_pinhole_camera, 1.0f * fabsf(command->m_angle_radians));
}
void on_aim_down(const aim_camera_down* command) override
{
details::aim_pinhole_camera(m_pinhole_camera, -1.0f * fabsf(command->m_angle_radians));
}
void on_move_xy(const move_camera_xy* command) override
{
auto displacement_vs = math::set(command->m_direction_x, command->m_direction_y, 0.0f, 0.0f);
auto iv = math::transpose(math::inverse(gx::view_matrix(m_pinhole_camera)));
auto displacement_ws = math::mul(displacement_vs, iv );
m_pinhole_camera->m_view_position_ws = math::add(m_pinhole_camera->position(), displacement_ws);
}
void on_move_xz( const move_camera_xz* command ) override
{
auto displacement_vs = math::set(command->m_direction_x, 0.0f, command->m_direction_z, 0.0f);
auto iv = math::transpose(math::inverse(gx::view_matrix(m_pinhole_camera)));
auto displacement_ws = math::mul(displacement_vs, iv);
m_pinhole_camera->m_view_position_ws = math::add(m_pinhole_camera->position(), displacement_ws);
}
void on_move_z(const move_camera_z* command) override
{
auto view_direction_ws = m_pinhole_camera->forward();
auto normalized_view_direction_ws = math::normalize3(view_direction_ws);
auto distance = command->m_distance;
auto distance_ws = math::splat(distance);
auto displacement_ws = math::mul(distance_ws, normalized_view_direction_ws);
m_pinhole_camera->m_view_position_ws = math::add(m_pinhole_camera->m_view_position_ws, displacement_ws);
}
gx::pinhole_camera* m_pinhole_camera;
};
}
|
a30b8431816b0208e2c0e15e7c322c071d52a25f
|
bf580fc7c835fe3fa3ed132f767c45f3984f0379
|
/simulator.cpp
|
69fd3f3ecc9b1c6552b7114bd39172a713b12d18
|
[] |
no_license
|
flavioc/meld
|
eb9ddb9a244498769511cc6c9f2e9f3541d1169a
|
08511ad36d96386ff06ed9c695d05c3ac2761cb8
|
refs/heads/master
| 2016-09-16T00:18:00.744714
| 2013-12-05T19:00:23
| 2013-12-05T19:00:23
| 1,469,942
| 17
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,466
|
cpp
|
simulator.cpp
|
#include <cstdlib>
#include "conf.hpp"
#include "process/machine.hpp"
#include "utils/utils.hpp"
#include "process/router.hpp"
#include "interface.hpp"
#include "version.hpp"
#include "utils/atomic.hpp"
#include "utils/fs.hpp"
#include "ui/client.hpp"
#include "ui/manager.hpp"
#include "sched/sim.hpp"
using namespace utils;
using namespace process;
using namespace std;
using namespace sched;
using namespace boost;
using namespace utils;
#ifdef USE_SIM
static char *progname = NULL;
static char *meldprog = NULL;
static int port = 0;
static void
help(void)
{
cerr << "simulator: execute meld programs on a simulator" << endl;
cerr << "\t-p \t\tset server port" << endl;
cerr << "\t-f \t\tmeldprogram" << endl;
cerr << "\t-h \t\tshow this screen" << endl;
exit(EXIT_SUCCESS);
}
static vm::machine_arguments
read_arguments(int argc, char **argv)
{
vm::machine_arguments program_arguments;
progname = *argv++;
--argc;
while (argc > 0 && (argv[0][0] == '-')) {
switch(argv[0][1]) {
case 'p':
if(argc < 2)
help();
port = atoi(argv[1]);
argc--;
argv++;
break;
case 'f':
if(argc < 2)
help();
meldprog = argv[1];
argc--;
argv++;
break;
case 'h':
help();
break;
case '-':
for(--argc, ++argv ; argc > 0; --argc, ++argv)
program_arguments.push_back(string(*argv));
default:
help();
}
/* advance */
argc--; argv++;
}
if(port == 0) {
cerr << "Error: no server port set" << endl;
exit(EXIT_FAILURE);
}
return program_arguments;
}
#endif
int
main(int argc, char **argv)
{
(void)argc;
(void)argv;
#ifdef USE_SIM
vm::machine_arguments margs(read_arguments(argc, argv));
if(meldprog == NULL) {
cerr << "No program in input" << endl;
return EXIT_FAILURE;
}
if(!file_exists(meldprog)) {
cerr << "Meld program " << meldprog << " does not exist" << endl;
return EXIT_FAILURE;
}
// setup scheduler
sched_type = SCHED_SIM;
num_threads = 1;
sched::sim_sched::PORT = port;
show_database = true;
try {
run_program(argc, argv, meldprog, margs, NULL);
} catch(machine_error& err) {
cerr << "VM error: " << err.what() << endl;
exit(EXIT_FAILURE);
} catch(db::database_error& err) {
cerr << "Database error: " << err.what() << endl;
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
#else
return EXIT_FAILURE;
#endif
}
|
8ae29fff7bf81b7d19bf42a71eefb2a90b04d342
|
2b1b459706bbac83dad951426927b5798e1786fc
|
/src/lib/storage/vfs/cpp/paged_vnode.cc
|
cb674c8194f68fa057be9b2f6c72d769739f2306
|
[
"BSD-2-Clause"
] |
permissive
|
gnoliyil/fuchsia
|
bc205e4b77417acd4513fd35d7f83abd3f43eb8d
|
bc81409a0527580432923c30fbbb44aba677b57d
|
refs/heads/main
| 2022-12-12T11:53:01.714113
| 2022-01-08T17:01:14
| 2022-12-08T01:29:53
| 445,866,010
| 4
| 3
|
BSD-2-Clause
| 2022-10-11T05:44:30
| 2022-01-08T16:09:33
|
C++
|
UTF-8
|
C++
| false
| false
| 5,403
|
cc
|
paged_vnode.cc
|
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/lib/storage/vfs/cpp/paged_vnode.h"
#include <lib/async/task.h>
#include <zircon/errors.h>
#include <memory>
#include <mutex>
#include "src/lib/storage/vfs/cpp/paged_vfs.h"
namespace fs {
PagedVnode::PagedVnode(PagedVfs& vfs) : clone_watcher_(this), vfs_(vfs) {}
void PagedVnode::VmoDirty(uint64_t offset, uint64_t length) {
ZX_ASSERT_MSG(false, "Filesystem does not support VmoDirty() (maybe read-only filesystem).");
}
zx::result<> PagedVnode::EnsureCreatePagedVmo(uint64_t size, uint32_t options) {
if (paged_vmo_info_.vmo.is_valid()) {
return zx::ok();
}
if (!vfs_.has_value()) {
return zx::error(ZX_ERR_BAD_STATE); // Currently shutting down.
}
zx::result info_or = vfs_.value().get().CreatePagedNodeVmo(this, size, options);
if (info_or.is_error()) {
return info_or.take_error();
}
paged_vmo_info_ = std::move(info_or.value());
return zx::ok();
}
void PagedVnode::DidClonePagedVmo() {
// Ensure that there is an owning reference to this vnode that goes along with the VMO clones.
// This ensures that we can continue serving page requests even if all FIDL connections are
// closed. This reference will be released when there are no more clones.
if (!has_clones_reference_) {
has_clones_reference_ = fbl::RefPtr<PagedVnode>(this);
// Watch the VMO for the presence of no children. The VMO currently has no children because we
// just created it, but the signal will be edge-triggered.
WatchForZeroVmoClones();
}
}
fbl::RefPtr<Vnode> PagedVnode::FreePagedVmo() {
if (!paged_vmo_info_.vmo.is_valid())
return nullptr;
// Need to stop watching before deleting the VMO or there will be no handle to stop watching.
StopWatchingForZeroVmoClones();
if (vfs_.has_value()) {
vfs_.value().get().FreePagedVmo(std::move(paged_vmo_info_));
}
// Reset to known-state after moving (or in case the paged_vfs was destroyed and we skipped
// moving out of it).
paged_vmo_info_.vmo = zx::vmo();
paged_vmo_info_.id = 0;
// This function must not free itself since the lock must be held to call it and the caller can't
// release a deleted lock. The has_clones_reference_ may be the last thing keeping this class
// alive so return it to allow the caller to release it properly.
return std::move(has_clones_reference_);
}
void PagedVnode::OnNoPagedVmoClones() {
ZX_DEBUG_ASSERT(!has_clones());
// It is now save to release the VMO. Since we know there are no clones, we don't have to
// call zx_pager_detach_vmo() to stop delivery of requests. And since there are no clones, the
// has_clones_reference_ should also be null and there shouldn't be a reference to release
// returned by FreePagedVmo(). If there is, deleting it here would cause "this" to be deleted
// inside its own lock which will crash.
fbl::RefPtr<fs::Vnode> pager_reference = FreePagedVmo();
ZX_DEBUG_ASSERT(!pager_reference);
}
void PagedVnode::OnNoPagedVmoClonesMessage(async_dispatcher_t* dispatcher, async::WaitBase* wait,
zx_status_t status, const zx_packet_signal_t* signal) {
// The system will cancel our wait on teardown if we're still watching the vmo.
if (status == ZX_ERR_CANCELED)
return;
// Our clone reference must be freed, but we need to do that outside of the lock.
fbl::RefPtr<PagedVnode> clone_reference;
{
std::lock_guard lock(mutex_);
ZX_DEBUG_ASSERT(has_clones());
if (!vfs_.has_value()) {
return; // Called during tear-down.
}
// The kernel signal delivery could have raced with us creating a new clone. Validate that there
// are still no clones before tearing down.
zx_info_vmo_t info;
if (paged_vmo().get_info(ZX_INFO_VMO, &info, sizeof(info), nullptr, nullptr) != ZX_OK)
return; // Something wrong with the VMO, don't try to tear down.
if (info.num_children > 0) {
// Race with new VMO. Re-arm the clone watcher and continue as if the signal was not sent.
WatchForZeroVmoClones();
return;
}
// Move our reference for releasing outside of the lock. Clearing the member will also allow the
// OnNoPagedVmoClones() observer to see "has_clones() == false" which is the new state.
clone_reference = std::move(has_clones_reference_);
StopWatchingForZeroVmoClones();
OnNoPagedVmoClones();
}
// Release the reference to this class. This could be the last reference keeping it alive which
// can cause it to be freed.
clone_reference = nullptr;
// THIS OBJECT IS NOW POSSIBLY DELETED.
}
void PagedVnode::WatchForZeroVmoClones() {
clone_watcher_.set_object(paged_vmo().get());
clone_watcher_.set_trigger(ZX_VMO_ZERO_CHILDREN);
if (vfs_.has_value()) {
clone_watcher_.Begin(vfs_.value().get().dispatcher());
}
}
void PagedVnode::StopWatchingForZeroVmoClones() {
// This needs to tolerate calls where the cancel is unnecessary.
if (clone_watcher_.is_pending())
clone_watcher_.Cancel();
clone_watcher_.set_object(ZX_HANDLE_INVALID);
}
void PagedVnode::WillDestroyVfs() {
std::lock_guard lock(mutex_);
vfs_.reset();
}
void PagedVnode::TearDown() {
std::lock_guard lock(mutex_);
auto node = FreePagedVmo();
}
} // namespace fs
|
e4bd7d8e647f895aed74dd919b3c2f6f0bff6f5f
|
c4dbe510e88c94fce468cf6b475172268febdc5f
|
/utils/math/fifo_median.hpp
|
64d4458a931cab01c03f98ec3c4eb081282f99ae
|
[] |
no_license
|
FRC-Team-955/DuncansResources
|
2d7dbd6afd302c3082602c4f233744090f3a452c
|
ccb00725fa0f3f96348330825b9bb69fcc365f27
|
refs/heads/main
| 2021-06-16T13:37:24.443434
| 2019-03-23T03:01:39
| 2019-03-23T03:01:39
| 163,228,553
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
hpp
|
fifo_median.hpp
|
#pragma once
#include <algorithm>
#include <deque>
#include <stdio.h>
class FifoMedian {
private:
// First In First Out array
std::deque<float> fifo;
// Maximum length we allow the array to reach
size_t fifo_max_length;
public:
FifoMedian(size_t max_length);
void insert_data(float data);
float calculate_median();
};
|
3283aded28d982f961c2ed1fd90601a2a7399cef
|
60aff25ce7c0d3ce80e22423db0d84823a896f3a
|
/sfitsio/src/fits_hdu.h
|
4d6d60c41bcaa7f008273b7bafac2de1d9c48658
|
[
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
cyamauch/sli
|
8870f36ba273b415fb9cd0dd6c16cb22a235d924
|
c24ad209034f9f9fea46cac7915917694ab9cad5
|
refs/heads/master
| 2022-11-24T03:08:04.791714
| 2022-10-23T18:55:23
| 2022-10-23T18:55:23
| 18,258,864
| 7
| 2
| null | null | null | null |
EUC-JP
|
C++
| false
| false
| 17,801
|
h
|
fits_hdu.h
|
/* -*- Mode: C++ ; Coding: euc-japan -*- */
/* Time-stamp: <2014-05-08 02:20:24 cyamauch> */
#ifndef _SLI__FITS_HDU_H
#define _SLI__FITS_HDU_H 1
/**
* @file fits_hdu.h
* @brief FITS の HDU を表現する基底クラス fits_hdu の定義
*/
#include "fits_header.h"
#ifdef BUILD_SFITSIO
#include <sli/cstreamio.h>
#include <sli/tstring.h>
#else
#include "cstreamio.h"
#include "tstring.h"
#endif
namespace sli
{
class fitscc;
/*
* sil::fits_hdu class expresses an HDU of FITS data structure, and manages
* objects of sli::fits_header. An inherited class of this class (fits_image
* or fits_table) is used for general purposes, but reference of object of
* this class itself can be used for HDUs whose type are unknown. Objects of
* this class and inherited class are usually managed by an object of
* sli::fitscc class.
*/
/**
* @class sli::fits_hdu
* @brief FITS の HDU を表現する基底クラス
*
* fits_hdu クラスは,FITS の HDU を表現します.これを継承したクラスが
* 具体的な HDU (つまり Image か Table か) を表現します.
*
* @author Chisato YAMAUCHI
* @date 2013-03-26 00:00:00
*/
class fits_hdu
{
friend class fitscc;
friend class fits_header;
public:
/* constructor & destructor */
fits_hdu();
fits_hdu(const fits_hdu &obj);
virtual ~fits_hdu();
/* complete initialization of objects */
virtual fits_hdu &init();
/* returns type of HDU */
virtual int hdutype() const;
/* returns class level */
virtual int classlevel() const;
/* ヘッダまわり.ここからは header_rec の wrapper */
/* complete initialization of header */
virtual fits_hdu &header_init();
virtual fits_hdu &header_init( const fits_header &obj );
virtual fits_hdu &header_init( const fits::header_def defs[] );
/* swap contents between fits_header object of self and obj */
virtual fits_hdu &header_swap( fits_header &obj );
/*
* manipulate some header records
*/
/* update some header records */
/* If specified keyword is not found, new record is created. */
/* Note that this member function cannot handle description records. */
virtual fits_hdu &header_update_records( const fits_header &obj );
/* append some header records */
virtual fits_hdu &header_append_records( const fits::header_def defs[] );
virtual fits_hdu &header_append_records( const fits::header_def defs[],
long num_defs, bool warn );
virtual fits_hdu &header_append_records(const fits_header &obj, bool warn);
/* insert some header records */
virtual fits_hdu &header_insert_records( long index0,
const fits::header_def defs[] );
virtual fits_hdu &header_insert_records( const char *keyword0,
const fits::header_def defs[] );
virtual fits_hdu &header_insert_records( long index0,
const fits::header_def defs[],
long num_defs, bool warn );
virtual fits_hdu &header_insert_records( const char *keyword0,
const fits::header_def defs[],
long num_defs, bool warn );
virtual fits_hdu &header_insert_records( long index0,
const fits_header &obj, bool warn );
virtual fits_hdu &header_insert_records( const char *keyword0,
const fits_header &obj, bool warn );
/* erase some header records */
virtual fits_hdu &header_erase_records( long index0, long num_records );
virtual fits_hdu &header_erase_records( const char *keyword0, long num_records );
/*
* manipulate a header record
*/
/* update a header record. */
/* If specified keyword is not found, new record is created. */
/* Note that .header_upate() cannot handle description records. */
virtual fits_hdu &header_update( const char *keyword, const char *value,
const char *comment );
virtual fits_hdu &header_update( const fits_header_record &obj );
/* append a header record */
virtual fits_hdu &header_append( const char *keyword );
virtual fits_hdu &header_append( const char *keyword, const char *value,
const char *comment );
virtual fits_hdu &header_append( const char *keyword, const char *description );
virtual fits_hdu &header_append( const fits::header_def &def );
virtual fits_hdu &header_append( const fits_header_record &obj );
/* insert a header record */
virtual fits_hdu &header_insert( long index0, const char *kwd );
virtual fits_hdu &header_insert( const char *keyword0, const char *kwd );
virtual fits_hdu &header_insert( long index0,
const char *k, const char *v, const char *c );
virtual fits_hdu &header_insert( const char *keyword0,
const char *k, const char *v, const char *c );
virtual fits_hdu &header_insert( long index0,
const char *keywd, const char *description );
virtual fits_hdu &header_insert( const char *keyword0,
const char *keywd, const char *description );
virtual fits_hdu &header_insert( long index0,
const fits::header_def &def );
virtual fits_hdu &header_insert( const char *keyword0,
const fits::header_def &def );
virtual fits_hdu &header_insert( long index0,
const fits_header_record &obj );
virtual fits_hdu &header_insert( const char *keyword0,
const fits_header_record &obj );
/* rename keyword of a header record */
virtual fits_hdu &header_rename( long index0, const char *new_name );
virtual fits_hdu &header_rename( const char *keyword0, const char *new_name );
/* erase a header record */
virtual fits_hdu &header_erase( long index0 );
virtual fits_hdu &header_erase( const char *keyword0 );
/*
* low-level member functions for header
*/
/* set keyword, raw value, and comment of a header record */
virtual fits_hdu &header_assign(long index0, const fits::header_def &def);
virtual fits_hdu &header_assign( const char *keyword0,
const fits::header_def &def );
virtual fits_hdu &header_assign( long index0,
const fits_header_record &obj );
virtual fits_hdu &header_assign( const char *keyword0,
const fits_header_record &obj );
virtual fits_hdu &header_assign( long index0,
const char *keyword, const char *value,
const char *comment );
virtual fits_hdu &header_assign( const char *keyword0,
const char *keyword, const char *value,
const char *comment );
virtual fits_hdu &header_assign( long index0,
const char *keyword, const char *description );
virtual fits_hdu &header_assign( const char *keyword0,
const char *keyword, const char *description );
/* set a raw value of a header record */
virtual fits_hdu &header_vassignf_value( long index0,
const char *format, va_list ap );
virtual fits_hdu &header_vassignf_value( const char *keyword0,
const char *format, va_list ap );
virtual fits_hdu &header_assignf_value( long index0,
const char *format, ... );
virtual fits_hdu &header_assignf_value( const char *keyword0,
const char *format, ... );
/* set a comment string of a header record */
virtual fits_hdu &header_vassignf_comment( long index0,
const char *format, va_list ap );
virtual fits_hdu &header_vassignf_comment( const char *keyword0,
const char *format, va_list ap );
virtual fits_hdu &header_assignf_comment( long index0,
const char *format, ... );
virtual fits_hdu &header_assignf_comment( const char *keyword0,
const char *format, ... );
/* This overwrites existing all header comments with comment string in */
/* comment dictionary. */
virtual fits_hdu &header_assign_default_comments( int hdutype = FITS::ANY_HDU );
/* This fills only blank header comments with comment string in comment */
/* dictionary. */
virtual fits_hdu &header_fill_blank_comments(int hdutype = FITS::ANY_HDU);
/* These member functions returns reference of managed fits_header */
/* object. */
virtual fits_header &header();
#ifdef SLI__OVERLOAD_CONST_AT
virtual const fits_header &header() const;
#endif
virtual const fits_header &header_cs() const;
/* These member functions returns reference of managed */
/* fits_header_record object. */
/* i.e., same as .header().at(index) ... */
virtual fits_header_record &header( long index0 );
virtual fits_header_record &header( const char *keyword0 );
virtual fits_header_record &headerf( const char *fmt, ... );
virtual fits_header_record &vheaderf( const char *fmt, va_list ap );
#ifdef SLI__OVERLOAD_CONST_AT
virtual const fits_header_record &header( long index0 ) const;
virtual const fits_header_record &header( const char *keyword0 ) const;
virtual const fits_header_record &headerf( const char *fmt, ... ) const;
virtual const fits_header_record &vheaderf( const char *fmt, va_list ap ) const;
#endif
virtual const fits_header_record &header_cs( long index0 ) const;
virtual const fits_header_record &header_cs( const char *keyword0 ) const;
virtual const fits_header_record &headerf_cs( const char *fmt, ... ) const;
virtual const fits_header_record &vheaderf_cs( const char *fmt, va_list ap ) const;
/*
* member functions to read and search information of header records
*/
/* header_index() or header_regmatch() searches a keyword from header */
/* records which format is not descriptive (unlike COMMENT or HISTORY) */
/* and returns its record index. Negative value is returned when */
/* specified keyword or pattern is not found. Set true to */
/* is_description arg to search a keyword from descriptive records. */
/* keyword0: keyword name */
/* keypat: keyword pattern (POSIX extended regular expression) */
virtual long header_index( const char *keyword0 ) const;
virtual long header_index(const char *keyword0, bool is_description) const;
virtual long header_regmatch( const char *keypat,
ssize_t *rpos = NULL, size_t *rlen = NULL );
virtual long header_regmatch( long index0, const char *keypat,
ssize_t *rpos = NULL, size_t *rlen = NULL );
/* returns length of raw value. More than 0 means NON-NULL. */
/* Negative value is returned when a record is not found. */
virtual long header_value_length( const char *keyword ) const;
virtual long header_value_length( long index ) const;
/* returns number of header records */
virtual long header_length() const;
/* not recommended */
virtual long header_size() const; /* same as header_length() */
/* discard original 80-char record, and reformat all records */
virtual fits_hdu &header_reformat();
/* This returns formatted 80 * N bytes string of all header records. */
/* Returned result is a string of 80 * n characters without '\n' but */
/* with '\0' termination. */
virtual const char *header_formatted_string();
/* only for backward compatibility; do not use. */
/* システムヘッダ読み取り(互換を保つためにあるだけ:使わないこと) */
virtual long sysheader_length() const;
virtual long sysheader_size() const;
virtual long sysheader_index( const char *keyword0 ) const;
virtual const char *sysheader_keyword( long index ) const;
virtual const char *sysheader_value( long index ) const;
virtual const char *sysheader_value( const char *keyword ) const;
virtual const char *sysheader_comment( long index ) const;
virtual const char *sysheader_comment( const char *keyword ) const;
virtual const char *sysheader_formatted_string();
/* change a HDU name */
virtual fits_hdu &assign_hduname( const char *hduname );
/* same as assign_hduname() */
virtual fits_hdu &assign_extname( const char *extname );
/* change a HDU version number */
virtual fits_hdu &assign_hduver( long long hduver );
/* same as assign_hduver() */
virtual fits_hdu &assign_extver( long long extver );
/* change a HDU level number */
virtual fits_hdu &assign_hdulevel( long long hdulevel );
/* same as assign_hdulevel() */
virtual fits_hdu &assign_extlevel( long long extlevel );
/* returns HDU name */
virtual const char *hduname() const;
virtual const char *extname() const; /* same as hduname() */
/* returns HDU version */
virtual long long hduver() const;
virtual long long extver() const; /* same as hduver() */
/* returns HDU version (string) */
virtual const char *hduver_value() const;
virtual const char *extver_value() const; /* same as hduver_value() */
/* returns HDU level */
virtual long long hdulevel() const;
virtual long long extlevel() const; /* same as hdulevel() */
/* returns HDU level (string) */
virtual const char *hdulevel_value() const;
virtual const char *extlevel_value() const; /* same as hdulevel_value() */
/* check HDU version and level are set or not */
virtual bool hduver_is_set() const;
virtual bool extver_is_set() const;
virtual bool hdulevel_is_set() const;
virtual bool extlevel_is_set() const;
/* not implemented */
virtual bool checksum_error() const;
virtual bool datasum_error() const;
/* returns type of HDU based on header information */
virtual int hdutype_on_header();
/* only for backward compatibility; do not use. */
/* (互換を保つためにあるだけ:使わないこと) */
virtual const char *allheader_formatted_string();
protected:
/* 初期化など */
virtual fits_hdu &operator=(const fits_hdu &obj);
virtual fits_hdu &init( const fits_hdu &obj );
virtual fits_hdu &swap( fits_hdu &obj );
/* fits_header object からの入力 */
virtual int read_header_object( const fits_header &header_all );
/* ストリーム入出力 */
virtual ssize_t read_stream( cstreamio &sref, size_t max_bytes_read );
virtual ssize_t read_stream( cstreamio &sref );
virtual ssize_t write_stream( cstreamio &sref );
virtual ssize_t skip_data_stream( cstreamio &sref, size_t max_bytes_skip );
virtual ssize_t skip_data_stream( cstreamio &sref );
/* データ部保存のためのメンバ関数(継承クラスでオーバーライドする事) */
/* オーバーライドされた関数は,fits_hdu::write_stream() から呼び出される */
virtual ssize_t save_or_check_data( cstreamio *sptr, void *c_sum_info );
/* 書き込まれるであろうバイト数 */
virtual ssize_t stream_length();
/* */
virtual fits_hdu ®ister_manager( fitscc *ptr );
virtual fits_hdu &_assign_extname( const char *extname );
/* 継承クラスのコンストラクタで呼ぶ */
virtual int increase_classlevel();
/* 継承クラスのコンストラクタで呼ぶ */
virtual fits_hdu &set_hdutype( int hdutype );
/* 継承クラスから HDU 番号等を問い合わせる時に使う */
virtual long hdu_index() const;
//virtual const char *fmttype() const;
//virtual long long ftypever() const;
/* 保存する直前に呼ばれる */
//virtual int set_primary_hdu( bool is_primary_hdu );
/* setup_basic_sys_header() はファイルへ保存する直前に呼ばれる */
/* extension 用 */
virtual fits_hdu &setup_sys_header();
/* 継承クラスでシステムキーワードを書き込む場合に使用 */
virtual fits_hdu &header_set_sysrecords_prohibition( bool flag );
/* ユーザの拡張クラスで使用を想定 */
/* ポインタを張る場合に必要 */
virtual fits_header_record *header_record_ptr( long index );
/* ポインタを張った時,消えないように保護するために必要 */
virtual fits_hdu &set_header_protections( long index0,
bool keyword, bool value_type,
bool value, bool comment );
/* shallow copy を許可する場合に使用. */
/* (一時オブジェクトの return の直前で使用) */
virtual void set_scopy_flag();
private:
int header_setup_top_records( fits::header_def defs[],
const char *removed_keywords[] );
/* 読み込みを行なう */
ssize_t header_load( cstreamio &sref, const size_t *max_bytes_ptr );
ssize_t header_load( const char *header_all );
ssize_t header_load( const fits_header &header_all );
/* 1つのヘッダをフォーマットする */
ssize_t header_format_record( fits_header *target_header,
long index, tstring *result );
protected:
fits_header header_rec;
bool checksum_error_rec;
bool datasum_error_rec;
private:
/* これは,コンストラクタ内だけで更新される */
int classlevel_rec;
//bool is_primary_rec; /* これは fits_hdu.cc 内で管理 */
/* fits_hdu では初期化はするが,値の代入は継承クラスで行なう */
int hdutype_rec;
/* ヘッダすべて */
tstring extname_rec;
tstring extver_rec;
bool extver_is_set_rec;
tstring extlevel_rec;
bool extlevel_is_set_rec;
fitscc *manager; /* fitcc によって管理されていればその ptr */
};
}
#endif /* _SLI__FITS_HDU_H */
|
247ed5d7f642e76e76274cfbd80634ea68cc3cec
|
24004e1c3b8005af26d5890091d3c207427a799e
|
/Win32/NXOPEN/NXOpen/BaseSession.hxx
|
253ade980dc95ae009b0cd75631f0b650219cbca
|
[] |
no_license
|
15831944/PHStart
|
068ca6f86b736a9cc857d7db391b2f20d2f52ba9
|
f79280bca2ec7e5f344067ead05f98b7d592ae39
|
refs/heads/master
| 2022-02-20T04:07:46.994182
| 2019-09-29T06:15:37
| 2019-09-29T06:15:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 942
|
hxx
|
BaseSession.hxx
|
/*******************************************************************************
Copyright (c) 2003 Unigraphics Solutions Inc.
Unpublished - All Rights Reserved
*******************************************************************************/
#ifndef NXOpen_BASESESSION_HXX_INCLUDED
#define NXOpen_BASESESSION_HXX_INCLUDED
#include <NXOpen/TaggedObject.hxx>
#include <NXOpen/libnxopencpp_exports.hxx>
namespace NXOpen
{
/** A base class for NXOpen session objects */
class NXOPENCPPEXPORT BaseSession : public TaggedObject
{
public:
/// @cond NX_NO_DOC
virtual void initialize();
void SetTestOutput(const char *new_file);
void SetTestOutput(const char *new_file, int version);
void CloseTestOutput();
void CompareTestOutput(const char *master_file, const char *new_file);
/// @endcond
};
}
#undef EXPORTLIBRARY
#endif
|
43ee7f8e73d99a38975cfcf6c063523cada91873
|
d2396967fff0e4441711a34b04132ba8c3b20982
|
/src/Weapons/DualPistols.cpp
|
8f6f6c7bcbb5931891b8a3ba7df7d70658e4f16a
|
[] |
no_license
|
gbdb71/SuperFakeBox_cpp
|
5f25183c4134c8e67a2c3c96872b6ed92606d647
|
db85aeefea218a622feba72e2dedce7eb049bbf4
|
refs/heads/master
| 2020-03-22T12:52:27.193894
| 2017-10-15T05:54:34
| 2017-10-15T05:54:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 962
|
cpp
|
DualPistols.cpp
|
#include "DualPistols.h"
#include <iostream>
#include "Bullet.h"
#include "../Spieler.h"
DualPistols::DualPistols(Spielfeld * s) : Weapon(s)
{
//Change Body type to a Rect
maxFireDelay = 7;
name = "DUAL PISTUUL";
onePress = true;
screenShakeAmount = 5;
Resources::loadTexture(tex,"dualpistol.png");
}
void DualPistols::render(sf:: RenderWindow * rW)
{
setPos(spielfeld->getPlayer()->getBody()->getPos() + sf::Vector2f(0,7));
rW->draw(spr);
}
void DualPistols::shoot(bool right)
{
Resources::playSound("pistolshoot.wav");
Bullet * b1 = spielfeld->createObject<Bullet>(spr.getPosition().x,spr.getPosition().y);
b1->getBody()->setDecellMulti(1);
b1->getBody()->setVel(15,0);
b1->setDamage(1);
Resources::playSound("pistolshoot.wav");
Bullet * b2 = spielfeld->createObject<Bullet>(spr.getPosition().x,spr.getPosition().y);
b2->getBody()->setDecellMulti(1);
b2->getBody()->setVel(-15,0);
b2->setDamage(1);
}
|
a4440a3b3956a1f80350856bd7c64c1e3c77cfc6
|
e96140fe29ac734c9985ba8835b13a38deda8a23
|
/extension/include/wx/extension/log.h
|
3157c70b00f21733c8cbf8721f8b885904cd6469
|
[
"MIT"
] |
permissive
|
fanzcsoft/wxExtension
|
33efbd379188584d6ef6a2a08fff07ed7fc3e374
|
e99bd2c83502fac64db0aece657a480d0352d2ba
|
refs/heads/master
| 2020-03-27T04:36:04.115835
| 2018-08-17T18:45:56
| 2018-08-17T18:45:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,029
|
h
|
log.h
|
////////////////////////////////////////////////////////////////////////////////
// Name: log.h
// Purpose: Declaration of wxExLog class
// Author: Anton van Wezenbeek
// Copyright: (c) 2018 Anton van Wezenbeek
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include <sstream>
#include <pugixml.hpp>
/// The loglevel.
enum wxExLogLevel
{
LEVEL_INFO, ///< info
LEVEL_DEBUG, ///< debug
LEVEL_WARNING, ///< warning
LEVEL_ERROR, ///< error
LEVEL_FATAL, ///< fatal
};
class wxExItem;
/// This class offers logging.
/// You should give at least one << following one of the
/// constructors.
class wxExLog
{
public:
/// Default constructor.
/// This prepares a logging with default level error.
wxExLog(
const std::string& topic = std::string(),
wxExLogLevel level = LEVEL_ERROR);
/// Constructor for specified log level.
wxExLog(wxExLogLevel level);
/// Constructor for level error from a std exception.
wxExLog(const std::exception&);
/// Constructor for level error fron a pugi exception.
wxExLog(const pugi::xpath_exception&);
/// Constructor for level error from a pugi parse result.
wxExLog(const pugi::xml_parse_result&);
/// Destructor, flushes stringstream to logging.
~wxExLog();
/// Logs int according to level.
wxExLog& operator<<(int);
/// Logs stringstream according to level.
wxExLog& operator<<(const std::stringstream& ss);
/// Logs string according to level.
wxExLog& operator<<(const std::string&);
/// Logs char* according to level.
wxExLog& operator<<(const char*);
/// Logs pugi according to level.
wxExLog& operator<<(const pugi::xml_node&);
/// Logs item according to level.
wxExLog& operator<<(const wxExItem&);
/// Returns current logging.
const std::string Get() const {return m_ss.str();};
private:
void Log() const;
const std::string S(); // separator
std::stringstream m_ss;
bool m_Separator {true};
wxExLogLevel m_Level {LEVEL_ERROR};
};
|
a9a34a5f31161ae0763a51cd27460b751e5fdec2
|
35f1a2b751819d0e5741a87121cfdf2aae3e646b
|
/study/study/1003.cpp
|
7643b6f7114fffa795575f43d7140ebfdf50dc87
|
[] |
no_license
|
namhyo01/ForStudy
|
b15ec2dc8b3e659509b93604b4468fbd7460bed8
|
fa7b8f6279a02f1ed261a209fefccc96a4ef4752
|
refs/heads/master
| 2022-03-20T15:38:47.140018
| 2022-03-09T12:41:05
| 2022-03-09T12:41:05
| 250,731,941
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 785
|
cpp
|
1003.cpp
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
#include <cmath>
#include <set>
#pragma warning(disable:4996)
using namespace std;
/*
int dp[50];
int n;
int num_0 = 0, num_1 = 0;
int fibonacchi(int n) {
if (n == 0) {
dp[0] = 0;
return 0;
}
if (n == 1) {
dp[1] = 1;
return 1;
}
if (dp[n] != 0) {
return dp[n];
}
return dp[n] = fibonacchi(n - 1) + fibonacchi(n - 2);
}
int main() {
int T;
scanf("%d", &T);
for (int i = 0; i < T; i++) {
scanf("%d", &n);
if (n == 0)
printf("%d %d\n", 1, 0);
else if (n == 1)
printf("%d %d\n", 0, 1);
else {
fibonacchi(n);
printf("%d %d\n", dp[n - 1], dp[n]);
//도착 전까지가 n의 0의개수 도착한 것이 n의 1의개수이다
}
}
//system("pause");
return 0;
}*/
|
e360a69de1497138b3fcfd0adcf42c470c3b561c
|
adb16eaccac05b07dbc44bb7fe87a17bf59889f0
|
/worktree/hello-gm/gmalproxy.h
|
5574322595c61b369fbed3615c5f5cc92f658333
|
[] |
no_license
|
tech-ui/nao-gm
|
e29f6cc899e744b1faf596d770b440eb81039a53
|
bd0f201640701a0a3eaddc12a1fa12c0c7c48891
|
refs/heads/master
| 2021-05-27T12:07:25.586855
| 2012-12-20T05:05:15
| 2012-12-20T05:05:15
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 796
|
h
|
gmalproxy.h
|
//
// gmalproxy.h
//
#pragma once
#include "main.h"
using namespace funk;
class GMALProxy
: public HandledObj<GMALProxy>
{
public:
GM_BIND_TYPEID(GMALProxy);
GMALProxy(const char* type, const char* ip, int port);
gmVariable CallReturnVariable(const char* function, gmVariable arg);
float CallReturnFloat(const char* function, gmVariable arg);
void CallVoid(const char* function, gmVariable arg);
void PostCall(const char* function, gmVariable arg);
bool IsRunning();
private:
AL::ALProxy _proxy;
int _current_call;
};
class GMALBulkMemoryProxy
: public HandledObj<GMALBulkMemoryProxy>
{
public:
GM_BIND_TYPEID(GMALBulkMemoryProxy);
GMALBulkMemoryProxy(const char* ip, int port);
private:
//std::vector<
};
GM_BIND_DECL(GMALProxy);
|
776597c727b5d5c4babb0c09f92f4460a7e06624
|
b66367fda3db9089fd710be500fe40ef43062ae0
|
/Source/Game.h
|
767c9f5f5e760261c7ea4e05ed05ec94e13e6891
|
[] |
no_license
|
trevelyanuk/GGJ2013-Undying-Love
|
d788b1f4af2c1fe8155aa964caa3b609bb546525
|
6ec3b820a0d6c61a8c3b2d5501c946c294d4c0bf
|
refs/heads/master
| 2021-01-12T17:26:39.243984
| 2017-06-16T12:48:31
| 2017-06-16T12:48:31
| 71,569,409
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,073
|
h
|
Game.h
|
#pragma once
#include "Main.h"
//#include "Input.h"
#include "gl.h"
//#include "Audio.h"
//#include "boost/cstdint.hpp"
//#include <vector>
//#include <algorithm>
#include "Image.h"
#define x_player_fire "audio/x_dirtDig.wav"
class COverlay;
class CObject;
class CCamera;
class CGUI;
class CGame
{
public:
int score;
short xMin, xMax, yMin, yMax, xBet, yBet;
unsigned short m_usTimerFood;
float resetZombieTimer;
float zombieDifficultyNumPerSpawn;
unsigned short m_usScore;
float m_pCenterX;
float m_pCenterY;
//std::vector <CObject *> m_vArray;
CObject *m_pObjects[MAXOBJECTS];
CObject *m_pParticles[MAXPARTICLES];
unsigned int getNumObjects();
unsigned int iArrayItems;
CObject * getObjectByIndex(unsigned int index_);
CObject * m_pCharacter;
CObject * m_pBase;
CObject * m_pHuman;
CGUI * m_pGUI;
CObject *m_pMouse;
COverlay * m_pOverlay;
//CGameFont *m_pFont;
//CAudio * m_pAudio;
//how many Objects have been loaded (increments in .cpp file when Objects are added).
unsigned int m_uiObjectsLoaded;
unsigned int m_uiParticlesLoaded;
//enumeration game states (being able to switch states using words instead of 'ints').
enum eSTATE
{
eStateMENU,
eStatePLAY,
eStateLOSE,
eStateWIN
};
eSTATE eCurrentState;
public:
~CGame(void);
void Reset();
void gsPlay();
void gsMenu();
void gsLose();
void gsWin();
void spawnZombie();
//loop frame, keeps returning and continues to re-execute.
void doFrame(void);//bEnterFrame
void doRender(void);
void getInput(void);
void checkTagged(void);
void eCheckStateandSwitch(void);
void addInst(CObject * pObject_);
void addPart(CObject * pObject_);
void setAudioPosition(void);
void beginFrame(void);
bool m_bActiveWindow;
//static pointer function to grab the static pointer of the Game(this) instance.
static CGame *s_pgetInst();
int survivors;
int currentIncrement;
int nextDifficultyIncremement[10];
protected:
CGame(void);
private:
//static pointer to the Game(this) instance.
static CGame * _pGameinst;
float zombieTimer;
};
|
c905d617286eece32a1498775075f3cbd121085b
|
d1811d8d37b7ca54731b797b032f346267066d99
|
/src/ee/storage/persistenttable.h
|
1c3f3bbcb818c91b9d2f4864dd5067229023a4c5
|
[] |
no_license
|
chenbk85/HStoreJDBC
|
b5db42423648db4446a65d733ce2acee79876cf5
|
f05b056f65215ef33dc7ed5c567e880905fabc62
|
refs/heads/master
| 2021-01-16T20:23:46.705607
| 2015-03-16T02:57:54
| 2015-03-16T02:57:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 16,039
|
h
|
persistenttable.h
|
/* This file is part of VoltDB.
* Copyright (C) 2008-2010 VoltDB Inc.
*
* This file contains original code and/or modifications of original code.
* Any modifications made by VoltDB Inc. are licensed under the following
* terms and conditions:
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
/* Copyright (C) 2008 by H-Store Project
* Brown University
* Massachusetts Institute of Technology
* Yale University
*
* 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef HSTOREPERSISTENTTABLE_H
#define HSTOREPERSISTENTTABLE_H
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <errno.h>
#include <string>
#include <map>
#include <vector>
#include "boost/shared_ptr.hpp"
#include "boost/scoped_ptr.hpp"
#include "common/ids.h"
#include "common/valuevector.h"
#include "common/tabletuple.h"
#include "common/Pool.hpp"
#include "storage/table.h"
#include "storage/TupleStreamWrapper.h"
#include "storage/TableStats.h"
#include "storage/PersistentTableStats.h"
#include "storage/CopyOnWriteContext.h"
#include "storage/RecoveryContext.h"
namespace voltdb {
class TableColumn;
class TableIndex;
class TableIterator;
class TableFactory;
class TupleSerializer;
class SerializeInput;
class Topend;
class ReferenceSerializeOutput;
class ExecutorContext;
class MaterializedViewMetadata;
class RecoveryProtoMsg;
#ifdef ANTICACHE
class EvictedTable;
class AntiCacheEvictionManager;
class EvictionIterator;
#endif
/**
* Represents a non-temporary table which permanently resides in
* storage and also registered to Catalog (see other documents for
* details of Catalog). PersistentTable has several additional
* features to Table. It has indexes, constraints to check NULL and
* uniqueness as well as undo logs to revert changes.
*
* PersistentTable can have one or more Indexes, one of which must be
* Primary Key Index. Primary Key Index is same as other Indexes except
* that it's used for deletion and updates. Our Execution Engine collects
* Primary Key values of deleted/updated tuples and uses it for specifying
* tuples, assuming every PersistentTable has a Primary Key index.
*
* Currently, constraints are not-null constraint and unique
* constraint. Not-null constraint is just a flag of TableColumn and
* checked against insertion and update. Unique constraint is also
* just a flag of TableIndex and checked against insertion and
* update. There's no rule constraint or foreign key constraint so far
* because our focus is performance and simplicity.
*
* To revert changes after execution, PersistentTable holds UndoLog.
* PersistentTable does eager update which immediately changes the
* value in data and adds an entry to UndoLog. We chose eager update
* policy because we expect reverting rarely occurs.
*/
class PersistentTable : public Table {
friend class TableFactory;
friend class TableTuple;
friend class TableIndex;
friend class TableIterator;
friend class PersistentTableStats;
#ifdef ANTICACHE
friend class AntiCacheEvictionManager;
friend class IndexScanExecutor;
#endif
private:
// no default ctor, no copy, no assignment
PersistentTable();
PersistentTable(PersistentTable const&);
PersistentTable operator=(PersistentTable const&);
public:
virtual ~PersistentTable();
// ------------------------------------------------------------------
// OPERATIONS
// ------------------------------------------------------------------
void deleteAllTuples(bool freeAllocatedStrings);
bool insertTuple(TableTuple &source);
/*
* Inserts a Tuple without performing an allocation for the
* uninlined strings.
*/
void insertTupleForUndo(TableTuple &source, size_t elMark);
/*
* Note that inside update tuple the order of sourceTuple and
* targetTuple is swapped when making calls on the indexes. This
* is just an inconsistency in the argument ordering.
*/
bool updateTuple(TableTuple &sourceTuple, TableTuple &targetTuple,
bool updatesIndexes);
/*
* Identical to regular updateTuple except no memory management
* for unlined columns is performed because that will be handled
* by the UndoAction.
*/
void updateTupleForUndo(TableTuple &sourceTuple, TableTuple &targetTuple,
bool revertIndexes, size_t elMark);
/*
* Delete a tuple by looking it up via table scan or a primary key
* index lookup.
*/
bool deleteTuple(TableTuple &tuple, bool freeAllocatedStrings);
void deleteTupleForUndo(voltdb::TableTuple &tupleCopy, size_t elMark);
/*
* Lookup the address of the tuple that is identical to the specified tuple.
* Does a primary key lookup or table scan if necessary.
*/
voltdb::TableTuple lookupTuple(TableTuple tuple);
// ------------------------------------------------------------------
// INDEXES
// ------------------------------------------------------------------
virtual int indexCount() const { return m_indexCount; }
virtual int uniqueIndexCount() const { return m_uniqueIndexCount; }
virtual std::vector<TableIndex*> allIndexes() const;
virtual TableIndex *index(std::string name);
virtual TableIndex *primaryKeyIndex() { return m_pkeyIndex; }
virtual const TableIndex *primaryKeyIndex() const { return m_pkeyIndex; }
// ------------------------------------------------------------------
// UTILITY
// ------------------------------------------------------------------
std::string tableType() const;
virtual std::string debug();
int partitionColumn() { return m_partitionColumn; }
/** inlined here because it can't be inlined in base Table, as it
* uses Tuple.copy.
*/
TableTuple& getTempTupleInlined(TableTuple &source);
// Export-related inherited methods
virtual void flushOldTuples(int64_t timeInMillis);
virtual StreamBlock* getCommittedExportBytes();
virtual bool releaseExportBytes(int64_t releaseOffset);
virtual void resetPollMarker();
/** Add a view to this table */
void addMaterializedView(MaterializedViewMetadata *view);
/**
* Switch the table to copy on write mode. Returns true if the table was already in copy on write mode.
*/
bool activateCopyOnWrite(TupleSerializer *serializer, int32_t partitionId);
/**
* Create a recovery stream for this table. Returns true if the table already has an active recovery stream
*/
bool activateRecoveryStream(int32_t tableId);
/**
* Serialize the next message in the stream of recovery messages. Returns true if there are
* more messages and false otherwise.
*/
void nextRecoveryMessage(ReferenceSerializeOutput *out);
/**
* Process the updates from a recovery message
*/
void processRecoveryMessage(RecoveryProtoMsg* message, Pool *pool, bool allowExport);
/**
* Attempt to serialize more tuples from the table to the provided
* output stream. Returns true if there are more tuples and false
* if there are no more tuples waiting to be serialized.
*/
bool serializeMore(ReferenceSerializeOutput *out);
/**
* Create a tree index on the primary key and then iterate it and hash
* the tuple data.
*/
size_t hashCode();
/**
* Get the current offset in bytes of the export stream for this Table
* since startup.
*/
void getExportStreamSequenceNo(long &seqNo, size_t &streamBytesUsed) {
seqNo = m_exportEnabled ? m_tsSeqNo : -1;
streamBytesUsed = m_wrapper ? m_wrapper->bytesUsed() : 0;
}
/**
* Set the current offset in bytes of the export stream for this Table
* since startup (used for rejoin/recovery).
*/
virtual void setExportStreamPositions(int64_t seqNo, size_t streamBytesUsed) {
// assume this only gets called from a fresh rejoined node
assert(m_tsSeqNo == 0);
m_tsSeqNo = seqNo;
if (m_wrapper)
m_wrapper->setBytesUsed(streamBytesUsed);
}
// ------------------------------------------------------------------
// ANTI-CACHING OPERATIONS
// ------------------------------------------------------------------
#ifdef ANTICACHE
void setEvictedTable(voltdb::Table *evictedTable);
voltdb::Table* getEvictedTable();
// needed for LRU chain eviction
void setNewestTupleID(uint32_t id);
void setOldestTupleID(uint32_t id);
uint32_t getNewestTupleID();
uint32_t getOldestTupleID();
void setNumTuplesInEvictionChain(int num_tuples);
int getNumTuplesInEvictionChain();
AntiCacheDB* getAntiCacheDB(int level);
std::map<int32_t, int32_t> getUnevictedBlockIDs();
std::vector<char*> getUnevictedBlocks();
int32_t getMergeTupleOffset(int);
bool mergeStrategy();
int32_t getTuplesEvicted();
void setTuplesEvicted(int32_t tuplesEvicted);
int32_t getBlocksEvicted();
void setBlocksEvicted(int32_t blocksEvicted);
int64_t getBytesEvicted();
void setBytesEvicted(int64_t bytesEvicted);
int32_t getTuplesWritten();
void setTuplesWritten(int32_t tuplesWritten);
int32_t getBlocksWritten();
void setBlocksWritten(int32_t blocksWritten);
int64_t getBytesWritten();
void setBytesWritten(int64_t bytesWritten);
voltdb::TableTuple * getTempTarget1();
void insertUnevictedBlockID(std::pair<int32_t,int32_t>);
void insertUnevictedBlock(char* unevicted_tuples);
void insertTupleOffset(int32_t tuple_offset);
bool isAlreadyUnEvicted(int32_t blockId);
int32_t getTuplesRead();
void setTuplesRead(int32_t tuplesRead);
void setBatchEvicted(bool batchEvicted);
bool isBatchEvicted();
void clearUnevictedBlocks();
void clearMergeTupleOffsets();
int64_t unevictTuple(ReferenceSerializeInput * in, int j, int merge_tuple_offset);
void clearUnevictedBlocks(int i);
char* getUnevictedBlocks(int i);
int unevictedBlocksSize();
#endif
void updateStringMemory(int tupleStringMemorySize);
void setEntryToNewAddressForAllIndexes(const TableTuple *tuple, const void* address);
protected:
virtual void allocateNextBlock();
size_t allocatedBlockCount() const {
return m_data.size();
}
// ------------------------------------------------------------------
// FROM PIMPL
// ------------------------------------------------------------------
void insertIntoAllIndexes(TableTuple *tuple);
void deleteFromAllIndexes(TableTuple *tuple);
void updateFromAllIndexes(TableTuple &targetTuple, const TableTuple &sourceTuple);
bool tryInsertOnAllIndexes(TableTuple *tuple);
bool tryUpdateOnAllIndexes(TableTuple &targetTuple, const TableTuple &sourceTuple);
bool checkNulls(TableTuple &tuple) const;
size_t appendToELBuffer(TableTuple &tuple, int64_t seqNo, TupleStreamWrapper::Type type);
PersistentTable(ExecutorContext *ctx, bool exportEnabled);
PersistentTable(ExecutorContext *ctx, const std::string name, bool exportEnabled);
void onSetColumns();
/*
* Implemented by persistent table and called by Table::loadTuplesFrom
* to do additional processing for views and Export
*/
virtual void processLoadedTuple(bool allowExport, TableTuple &tuple);
/*
* Implemented by persistent table and called by Table::loadTuplesFrom
* to do add tuples to indexes
*/
virtual void populateIndexes(int tupleCount);
// pointer to current transaction id and other "global" state.
// abstract this out of VoltDBEngine to avoid creating dependendencies
// between the engine and the storage layers - which complicate test.
ExecutorContext *m_executorContext;
// CONSTRAINTS
TableIndex** m_uniqueIndexes;
int m_uniqueIndexCount;
bool* m_allowNulls;
// INDEXES
TableIndex** m_indexes;
int m_indexCount;
TableIndex *m_pkeyIndex;
// temporary for tuplestream stuff
TupleStreamWrapper *m_wrapper;
int64_t m_tsSeqNo;
// ANTI-CACHE VARIABLES
#ifdef ANTICACHE
voltdb::Table *m_evictedTable;
std::map<int32_t, int32_t> m_unevictedBlockIDs;
// std::vector<int16_t> m_unevictedBlockIDs;
std::vector<char*> m_unevictedBlocks;
std::vector<int32_t> m_mergeTupleOffset;
std::map<int, int> m_unevictedTuplesPerBlocks;
char* m_unevictedTuples;
int m_numUnevictedTuples;
uint32_t m_oldestTupleID;
uint32_t m_newestTupleID;
int m_numTuplesInEvictionChain;
bool m_blockMerge;
bool m_batchEvicted;
#endif
// partition key
int m_partitionColumn;
// Partition id of where this table is stored in
int32_t m_partitionId;
// list of materialized views that are sourced from this table
std::vector<MaterializedViewMetadata *> m_views;
// STATS
voltdb::PersistentTableStats stats_;
voltdb::TableStats* getTableStats();
// is Export enabled
bool m_exportEnabled;
// Snapshot stuff
boost::scoped_ptr<CopyOnWriteContext> m_COWContext;
//Recovery stuff
boost::scoped_ptr<RecoveryContext> m_recoveryContext;
};
inline TableTuple& PersistentTable::getTempTupleInlined(TableTuple &source) {
assert (m_tempTuple.m_data);
m_tempTuple.copy(source);
return m_tempTuple;
}
inline void PersistentTable::allocateNextBlock() {
#ifdef MEMCHECK
int bytes = m_schema->tupleLength() + TUPLE_HEADER_SIZE;
#else
int bytes = m_tableAllocationTargetSize;
#endif
char *memory = (char*)(new char[bytes]);
m_data.push_back(memory);
#ifdef ANTICACHE_TIMESTAMPS_PRIME
m_evictPosition.push_back(0);
m_stepPrime.push_back(-1);
#endif
#ifdef MEMCHECK_NOFREELIST
assert(m_allocatedTuplePointers.insert(memory).second);
m_deletedTuplePointers.erase(memory);
#endif
m_allocatedTuples += m_tuplesPerBlock;
if (m_tempTableMemoryInBytes) {
(*m_tempTableMemoryInBytes) += bytes;
if ((*m_tempTableMemoryInBytes) > MAX_TEMP_TABLE_MEMORY) {
throw SQLException(SQLException::volt_temp_table_memory_overflow,
"More than 100MB of temp table memory used while"
" executing SQL. Aborting.");
}
}
}
}
#endif
|
7df63b7d2854a66ce8da862fad37e6f24600a740
|
f45caafc90b013ead12619bf5d3a4f1698db19a1
|
/src/list_widget.h
|
1206dc8c49df7daafb78ba99edce56dc39f58a73
|
[] |
no_license
|
gotoss08/engine
|
71c59e1c9afac8a73bb06945718861cd9898ab3d
|
e71aa085a975247cc5e967e8a180cd959fb32480
|
refs/heads/master
| 2020-03-12T18:50:12.797184
| 2018-05-04T18:22:08
| 2018-05-04T18:22:08
| 130,770,692
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 801
|
h
|
list_widget.h
|
#ifndef LIST_WIDGET_H_
#define LIST_WIDGET_H_
#include <string>
#include <vector>
#include "libs/loguru.hpp"
#include "text_renderer.h"
struct ListWidgetItem {
std::string text;
void (*action)();
};
class ListWidget {
private:
TextRenderer* text_renderer;
int x;
int y;
std::vector<ListWidgetItem> list_items;
std::string font_name = "main_menu_font";
SDL_Color normal_color{164, 167, 176, 255};
SDL_Color highlighted_color{214, 216, 221, 255};
int vertical_spacing = 7;
int item_index = 0;
public:
ListWidget(TextRenderer* _text_renderer, int _x, int _y,
std::vector<ListWidgetItem> _list_items);
void Render();
void Update();
void Up();
void Down();
void Activate();
};
#endif /* LIST_WIDGET_H_ */
|
6c93f2df7409906304bce16b103644e855f4401c
|
38310f59421bc65256bde942aad70108b6c0d411
|
/Source/cmExtraCodeLiteGenerator2.cxx
|
afc1a89f158fd57db5019ec95a81b55da6075d7f
|
[
"BSD-3-Clause"
] |
permissive
|
pbondo/CMake
|
7eb2882059e3440e8d486aa6a13d0f0aa9cd4cba
|
e2cca3e6fbecb586c396fdd64b14cd9282ed5f6f
|
refs/heads/master
| 2021-07-25T03:52:28.007769
| 2021-02-13T17:55:12
| 2021-02-13T17:55:12
| 8,237,030
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,091
|
cxx
|
cmExtraCodeLiteGenerator2.cxx
|
/*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2004-2009 Kitware, Inc.
Copyright 2004 Alexander Neundorf (neundorf@kde.org)
Copyright 2012-2020 Poul Bondo (poul.bondo@gmail.com)
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmExtraCodeLiteGenerator2.h"
#include "cmGlobalUnixMakefileGenerator3.h"
#include "cmLocalUnixMakefileGenerator3.h"
#include "cmMakefile.h"
#include "cmake.h"
#include "cmSourceFile.h"
#include "cmGeneratedFileStream.h"
#include "cmSystemTools.h"
#include "cmTarget.h"
#include "cmState.h"
#include "cmSystemTools.h"
#include <cmsys/SystemTools.hxx>
#include <cmsys/Directory.hxx>
#include <fstream>
using namespace std;
static std::ofstream logf2("codelite2.log");
//----------------------------------------------------------------------------
cmExtraCodeLiteGenerator2::cmExtraCodeLiteGenerator2()
:cmExternalMakefileProjectGenerator()
{
}
cmExternalMakefileProjectGeneratorFactory*
cmExtraCodeLiteGenerator2::GetFactory()
{
static cmExternalMakefileProjectGeneratorSimpleFactory<
cmExtraCodeLiteGenerator2>
factory("CodeLite2", "Generates CodeLite project files.");
if (factory.GetSupportedGlobalGenerators().empty()) {
factory.AddSupportedGlobalGenerator("Ninja");
factory.AddSupportedGlobalGenerator("Unix Makefiles");
}
return &factory;
}
std::string cmExtraCodeLiteGenerator2::CreateWorkspaceHeader()
{
std::ostringstream result;
result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<CodeLite_Workspace Name=\"" << workspaceProjectName << "\" Database=\"./" << workspaceProjectName << ".tags\">\n";
return result.str();
}
std::string cmExtraCodeLiteGenerator2::CreateWorkspaceFooter( const std::string& configCMake )
{
std::ostringstream result;
result << " <BuildMatrix>\n"
" <WorkspaceConfiguration Name=\"CMake\" Selected=\"yes\">\n"
<< configCMake <<
" </WorkspaceConfiguration>\n"
" </BuildMatrix>\n"
"</CodeLite_Workspace>\n";
return result.str();
}
void cmExtraCodeLiteGenerator2::Generate()
{
std::string workspaceFileName;
std::string configCMake;
cmGeneratedFileStream fout;
// loop projects and locate the root project.
for (auto& p : this->GlobalGenerator->GetProjectMap())
{
auto mf = p.second[0]->GetMakefile();
this->generator = mf->GetSafeDefinition("CMAKE_GENERATOR");
if (mf->GetCurrentBinaryDirectory() == mf->GetHomeOutputDirectory())
{
sourcePath = std::string(mf->GetCurrentSourceDirectory()) + "/";
workspaceProjectName = p.second[0]->GetProjectName();
workspacePath = std::string(mf->GetCurrentBinaryDirectory()) + "/";
workspaceFileName = workspacePath + workspaceProjectName + ".workspace";
break;
}
}
this->LoadSettingFile(sourcePath + "settings.codelite");
logf2 << "workspace: " << workspaceProjectName << " => " << workspaceFileName << " source " << sourcePath << std::endl;
// The following section attempts to find and remember the current active project. Will be restored at the end.
std::string activeProject;
{
std::ifstream ifs(workspaceFileName.c_str());
if (ifs.good())
{
std::string tmp;
while (cmSystemTools::GetLineFromStream(ifs, tmp))
{
char sz1[1000] = "", sz2[1000] = "", sz3[1000] = "", sz4[1000] = "";
// Looking for: <Project Name="myproject" Path="/home/user/somewhere/cmake/build/myproject/myproject.project" Active="Yes"/>
if (sscanf(tmp.c_str(),"%s Name=\"%s Path=\"%s Active=\"%s\"", sz1, sz2, sz3, sz4 ) >= 4)
{
logf2 << "Found project: " << sz1 << " : " << sz2 << " : " << sz3 << " : " << sz4 << std::endl;
if (std::string(sz4).substr(0,3) == "Yes")
{
size_t pos = std::string(sz2).find("\"");
if ( pos != std::string::npos )
{
activeProject = std::string(sz2).substr(0,pos);
}
}
}
}
}
}
fout.Open(workspaceFileName.c_str(),false,false);
fout << this->CreateWorkspaceHeader();
// For all the projects, for all the generators, find all the targets
for (auto& p : this->GlobalGenerator->GetProjectMap())
{
// Local Generators
for (auto& lg : p.second)
{
// Generator Targets
for (auto& gt : lg->GetGeneratorTargets())
{
logf2 << "\tTarget: " << " : " << gt->GetType() << " : " << gt->GetName() << endl;
switch(gt->GetType())
{
case cmStateEnums::EXECUTABLE: // 0
case cmStateEnums::STATIC_LIBRARY: // 1
case cmStateEnums::SHARED_LIBRARY: // 2
//case cmTarget::MODULE_LIBRARY:
//case cmTarget::OBJECT_LIBRARY:
{
std::string projectName;
std::string filename;
if (this->CreateProjectFile(*gt, *lg, projectName, filename))
{
std::string activeValue = "No";
if (projectName == activeProject)
{
activeValue = "Yes";
}
fout << " <Project Name=\"" << projectName << "\" Path=\"" << filename << "\" Active=\"" << activeValue << "\"/>\n";
configCMake += " <Project Name=\"" + projectName + "\" ConfigName=\"CMake\"/>\n";
}
}
break;
case cmStateEnums::UTILITY: // 5
case cmStateEnums::GLOBAL_TARGET: // 6
case cmStateEnums::INTERFACE_LIBRARY: // 7
case cmStateEnums::UNKNOWN_LIBRARY: // 8
default:
break;
}
}
}
}
fout << this->CreateWorkspaceFooter(configCMake);
}
std::string cmExtraCodeLiteGenerator2::CreateProjectHeader( const std::string& projectName )
{
std::ostringstream result;
result << "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<CodeLite_Project Name=\"" << projectName << "\" InternalType=\"\">\n\n";
return result.str();
}
std::string cmExtraCodeLiteGenerator2::CreateProjectFooter(const std::string& projectType, const std::string& make_cmd,
const std::string& generalTag, const std::string& projectName)
{
std::string make_single_target = make_cmd + " -f$(ProjectPath)/Makefile $(CurrentFileName).o";
std::string make_project = make_cmd + " " + projectName;
logf2 << "gen " << generator << " " << make_cmd << " " << endl;
if (generator == "Ninja")
{ // ninja -C /home/pba/tmp/cl2/ /home/pba/user/gh/ais-r138/impl/atonmonitor/aisconf.cpp^
make_single_target = make_cmd + " -C " + workspacePath + " $(CurrentFilePath)/$(CurrentFileFullName)^";
//make_single_target = make_cmd + " -C " + workspacePath + " $(CurrentFilePath)/$(CurrentFileName).cpp^"; // This trick will match header files with .cpp files, but fail with other types of files?
//make_single_target = make_cmd + " -C " + workspacePath + " $(ProjectName)/CMakeFiles/$(ProjectName).dir/$(CurrentFileFullName).o^";
make_project = make_cmd + " -C " + workspacePath + " $(ProjectName)";
}
std::ostringstream result;
result << "\n"
" <Settings Type=\"" << projectType << "\">\n"
" <Configuration Name=\"CMake\" CompilerType=\"gnu g++\" DebuggerType=\"GNU gdb debugger\" Type=\"" << projectType << "\" BuildCmpWithGlobalSettings=\"append\" BuildLnkWithGlobalSettings=\"append\" BuildResWithGlobalSettings=\"append\">\n"
" <Compiler Options=\"-g\" Required=\"yes\" PreCompiledHeader=\"\">\n"
" <IncludePath Value=\".\"/>\n"
" </Compiler>\n"
" <Linker Options=\"\" Required=\"yes\"/>\n"
" <ResourceCompiler Options=\"\" Required=\"no\"/>\n"
<< generalTag <<
" <Debugger IsRemote=\"no\" RemoteHostName=\"\" RemoteHostPort=\"\" DebuggerPath=\"\">\n"
" <PostConnectCommands/>\n"
" <StartupCommands/>\n"
" </Debugger>\n"
" <CustomBuild Enabled=\"yes\">\n"
" <RebuildCommand/>\n"
" <CleanCommand>make clean</CleanCommand>\n"
//" <BuildCommand>" << make_cmd << " " << projectName << "</BuildCommand>\n"
" <BuildCommand>" << make_project << "</BuildCommand>\n"
" <PreprocessFileCommand>" << make_cmd << " -f$(ProjectPath)/Makefile $(CurrentFileName).i</PreprocessFileCommand>\n"
//" <SingleFileCommand>" << make_cmd << " -f$(ProjectPath)/Makefile $(CurrentFileName).o</SingleFileCommand>\n"
" <SingleFileCommand>" << make_single_target << "</SingleFileCommand>\n"
" <ThirdPartyToolName>Other</ThirdPartyToolName>\n"
" <WorkingDirectory>$(IntermediateDirectory)</WorkingDirectory>\n"
" </CustomBuild>\n"
" <Completion EnableCpp11=\"yes\">\n"
" <SearchPaths/>\n"
" </Completion>\n"
" </Configuration>\n"
" </Settings>\n"
" <Dependencies Name=\"CMake\"/>\n"
"</CodeLite_Project>\n";
return result.str();
}
class source_group
{
public:
source_group(std::string name, std::string regex)
: sogr_(name.c_str(),regex.c_str())
{
}
source_group(cmSourceGroup g)
: sogr_(g){}
cmSourceGroup sogr_;
std::vector<std::string> filenames_;
};
bool cmExtraCodeLiteGenerator2::CreateProjectFile(const cmGeneratorTarget &_target, const cmLocalGenerator& _local,
std::string &_projectName, std::string &_projectFilename)
{
// Retrieve information from the cmake makefile
const cmMakefile* mf = _local.GetMakefile();
const std::vector<cmSourceGroup> &sogr1 = mf->GetSourceGroups();
std::vector<source_group> sogr;
for (std::vector<cmSourceGroup>::const_iterator it = sogr1.begin(); it != sogr1.end(); it++)
{
sogr.insert(sogr.begin(),source_group(*it));
}
std::string outputDir=mf->GetCurrentBinaryDirectory();
_projectName= _target.GetName();
std::string targettype; // Defaults to empty if no recognized target type is detected.
std::string make_cmd = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
_projectFilename = outputDir + "/" + _projectName + ".project";
//logf2 << "Project: " << _projectName << " " << _projectFilename << " " << mf->GetHomeDirectory() << " | " << mf->GetHomeOutputDirectory() << " | " << mf->GetCurrentSourceDirectory() << " | " << mf->GetCurrentBinaryDirectory() << "|" << outputDir << std::endl;
std::string workingDirectory = "$(IntermediateDirectory)";
if (auto wd = this->mapping[_projectName]["Working Directory"]; !wd.empty())
{
workingDirectory = wd;
}
std::string commandArguments = this->mapping[_projectName]["Program Arguments"]; // Using the names from the codelite visual project settings
// We try to merge some of the usable information from the project file.
std::string generalTag = " <General OutputFile=\"$(IntermediateDirectory)/$(ProjectName)\" IntermediateDirectory=\"" + outputDir + "\" Command=\"$(IntermediateDirectory)/$(ProjectName)\" CommandArguments=\"" + commandArguments + "\" WorkingDirectory=\"" + workingDirectory + "\" PauseExecWhenProcTerminates=\"yes\"/>\n";
{
// Look in the existing project file (if it exists) for the <General OutputFile tag.
// It contains the debug settings i.e: OutputFile, IntermediateDirectory, Command, CommandArguments
std::ifstream ifs(_projectFilename.c_str());
if (ifs.good())
{
std::string tmp;
while (cmSystemTools::GetLineFromStream(ifs, tmp))
{
if (tmp.find("<General ") != std::string::npos && tmp.find("OutputFile") != std::string::npos)
{
generalTag = tmp + "\n";
}
}
}
}
cmGeneratedFileStream fout(_projectFilename.c_str());
fout << this->CreateProjectHeader(_projectName);
//logf2 << "\tTarget: " << _target.GetType() << " : " << _target.GetName() << endl;
std::vector<cmSourceFile*> sources;
_target.GetSourceFiles(sources, mf->GetSafeDefinition("CMAKE_BUILD_TYPE"));
std::vector<std::string> filenames;
//for (std::vector<cmSourceFile*>::const_iterator si=sources.begin(); si!=sources.end(); si++)
for (auto& si : sources)
{
//logf2 << "Target: " << _projectName << " => " << (si)->GetFullPath() << std::endl;
filenames.push_back((si)->GetFullPath());
}
{ // Check if we have a local CMakeLists.txt we want to add.
std::string cmakelist_txt = std::string(mf->GetCurrentSourceDirectory()) + "/CMakeLists.txt";
std::ifstream ifs(cmakelist_txt);
if (ifs.good())
{
filenames.push_back(cmakelist_txt);
}
}
// For each file check if we have a matching source group.
for (auto& file : filenames)
{
for (auto& sg : sogr)
{
if (sg.sogr_.MatchesFiles(file.c_str()) || sg.sogr_.MatchesRegex(file.c_str()))
{
sg.filenames_.push_back(file);
break;
}
}
}
for (auto& sg : sogr)
{
this->AddFolder(sg.filenames_, sg.sogr_.GetName(), fout);
}
std::string project_build = "$(ProjectName)";
if (_projectName == workspaceProjectName)
{
project_build.clear();
}
std::string j;
if (cmsys::SystemTools::GetEnv("NUMCPUS", j) && !j.empty())
{
project_build = " -j " + j + " " + project_build;
}
fout << this->CreateProjectFooter(targettype, make_cmd, generalTag, project_build);
return true;
}
void cmExtraCodeLiteGenerator2::AddFolder( const std::vector<std::string>& folder, std::string foldername, cmGeneratedFileStream & fout )
{
if ( folder.size() > 0 )
{
if (foldername.empty())
{
foldername = "Other";
}
fout << "<VirtualDirectory Name=\"" << foldername << "\">\n";
for ( std::vector<std::string>::const_iterator iter = folder.begin(); iter != folder.end(); iter++)
{
fout << "<File Name=\"" << (*iter) << "\"/>\n";
}
fout << "</VirtualDirectory>\n";
}
}
void cmExtraCodeLiteGenerator2::LoadSettingFile(std::string filename)
{
std::ifstream ifs(filename);
if (ifs.good())
{
std::string line;
while (std::getline(ifs, line))
{
auto v = cmSystemTools::SplitString(line, '|');
if (v.size() > 1) // Not really interesting unless we have some data
{
for (size_t index = 1; index < v.size(); index++)
{
auto kv = cmSystemTools::SplitString(v[index], ':');
if (kv.size() == 2)
{
this->mapping[v[0]][kv[0]] = kv[1];
}
}
}
}
for (auto m : this->mapping)
{
for (auto e : m.second)
{
logf2 << "Setting: " << m.first << " " << e.first << "=" << e.second << endl;
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.