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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d5fd74d2c11c67004c4f0e9e4318f23060808c21
|
20fffb1bc2795021c4612ad4b408d96fa5b761cf
|
/2016暑假集训第一周周赛/E/std.cpp
|
9e557b293c17193ae40cdde33084af91c3203612
|
[] |
no_license
|
myk502/ACM
|
244c0a614ab2454332d11fd9afd7a5434d22b090
|
7c4d55a4655e58de89307965a322dd862758adbd
|
refs/heads/master
| 2021-01-01T16:42:05.678466
| 2018-10-01T14:31:57
| 2018-10-01T14:34:42
| 97,893,148
| 7
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 974
|
cpp
|
std.cpp
|
#include<iostream>
#define NMAX 100005
using namespace std;
long long fight_power[NMAX];
int main(){
int T, n;
long long WH;
// freopen("stdin.txt", "r", stdin);
// freopen("stdout.txt", "w", stdout);
while(scanf("%d", &n) != EOF){
scanf("%lld", &WH);
for(int i = 1; i < n; i++){
scanf("%lld", &fight_power[i]);
}
sort(fight_power + 1, fight_power + n);
int mark = 0;
for(int i = 1; i < n; i++){
if(fight_power[i] > WH){
printf("-1\n");
mark = 1;
break;
}
else{
if(fight_power[i] <= WH / 2){
WH += fight_power[i];
}
else{
WH += fight_power[i] / 2;
}
}
}
if(mark == 0){
printf("%lld\n", WH);
}
}
return 0;
}
|
20bcecf1ac7cb3eb4dde3c85aae0376002917937
|
2609137765a5fb9a7646361e47d1c5f68440faa3
|
/src/VDST.cpp
|
caba8f8531c07ec3c8a5abc4b698f68599c94d25
|
[
"BSD-3-Clause"
] |
permissive
|
Eventdisplay/Eventdisplay
|
6133a1fcac44efb37baf25f6d91d337c1965fcd2
|
50e297561ddac0ca2db39e0391a672f2f275994b
|
refs/heads/main
| 2023-06-24T03:58:48.287734
| 2023-06-14T06:29:25
| 2023-06-14T06:29:25
| 221,222,023
| 15
| 3
|
BSD-3-Clause
| 2023-08-23T15:17:56
| 2019-11-12T13:17:01
|
C++
|
UTF-8
|
C++
| false
| false
| 19,137
|
cpp
|
VDST.cpp
|
/*! \class VDST
\brief writes data summary files with sums and times for each pixel
output is after pedestal substraction, gain and toffset correction
*/
#include <VDST.h>
VDST::VDST( bool iMode, bool iMC )
{
if( getDebugFlag() )
{
cout << "VDST::VDST()" << endl;
}
// laser run as source file? (Hardcoded, should be in VEvndispRunParameter)
fBLaser = false;
fRaw = false;
// initalize flag (true after first event)
fDSTini = false;
fDSTfile = 0;
// no dst output, don't do anything
if( !iMode )
{
return;
}
// open dst output file
fDSTfile = new TFile( getRunParameter()->fdstfile.c_str(), "RECREATE" );
if( fDSTfile->IsZombie() )
{
cout << "VDST::VDST error while create dst file" << endl;
exit( EXIT_FAILURE );
}
initDSTTree( true, getRunParameter()->fdstcalibration );
setMC( iMC );
fVImageCleaning = new VImageCleaning( getData() );
}
VDST::~VDST()
{
if( fDSTfile && !fDSTfile->IsZombie() )
{
fDSTfile->Close();
}
if( fVImageCleaning )
{
delete fVImageCleaning;
}
}
void VDST::initialize()
{
initializeDataReader();
}
/*
analyse this event and fill the DST tree
*/
void VDST::fill()
{
if( getDebugFlag() )
{
cout << "VDST::fill()" << endl;
}
if( fDST_tree == 0 )
{
return;
}
// init base analyzer
if( !fDSTini )
{
for( unsigned int i = 0; i < getTeltoAna().size(); i++ )
{
setTelID( getTeltoAna()[i] );
// set summation vectors
setAnaData();
// find dead channels
findDeadChans( false, true );
findDeadChans( true, true );
// set special channels
setSpecialChannels();
}
fDSTini = true;
}
// get geometry
fDSTntel = getNTel();
// test geometry
if( fDSTntel > VDST_MAXTELESCOPES || ( int )getNChannels() > VDST_MAXCHANNELS )
{
cout << "void VDST::fill(): error: too many cameras or pmts, maximum is " << VDST_MAXTELESCOPES << "/" << VDST_MAXCHANNELS << endl;
exit( -1 );
}
// ignore following code
// (GM) XXXX check muon/laser list
/* int iZ = 0;
for( unsigned int k = 0; k < vEventList.size(); k++ )
{
iZ++;
if( vEventList[k] != getEventNumber() ) continue;
else break;
}
if( iZ > 12 ) return; */
// (GM) XXXX end check muon/laser list
// get basic event data
fDSTrunnumber = getRunNumber();
fDSTeventnumber = getEventNumber();
fDSTeventtype = ( unsigned int )( getReader()->getATEventType() );
fDSTgps0 = getReader()->getGPS0();
fDSTgps1 = getReader()->getGPS1();
fDSTgps2 = getReader()->getGPS2();
fDSTgps3 = getReader()->getGPS3();
fDSTgps4 = getReader()->getGPS4();
fDSTgpsyear = ( unsigned int )getReader()->getATGPSYear() + 2000;
fDSTATgpsyear = ( unsigned int )getReader()->getATGPSYear();
// update pointing
// get pointing and local trigger (stored as unsigned long)
bitset<8 * sizeof( unsigned long ) > i_localTrigger;
fDSTNTrig = 0;
for( unsigned int i = 0; i < getNTel(); i++ )
{
if( isTeltoAna( i ) )
{
// local trigger
if( fReader->hasLocalTrigger( i ) )
{
i_localTrigger.set( i, 1 );
fDSTLTrig_list[fDSTNTrig] = i;
fDSTNTrig++;
}
else
{
fDSTLTrig_list[i] = 0;
}
// pointing
getPointing()[i]->setTelPointing( getEventMJD(), getEventTime() );
if( i < fReader->getTelAzimuth().size() )
{
fDSTpointAzimuth[i] = fReader->getTelAzimuth()[i];
}
else if( i < getPointing().size() && getPointing()[i] )
{
fDSTpointAzimuth[i] = getPointing()[i]->getTelAzimuth();
}
if( i < fReader->getTelElevation().size() )
{
fDSTpointElevation[i] = fReader->getTelElevation()[i];
}
else if( i < getPointing().size() && getPointing()[i] )
{
fDSTpointElevation[i] = getPointing()[i]->getTelElevation();
}
}
}
fDSTLTrig = i_localTrigger.to_ulong();
// fill DST tree only for triggered events
if( fMC && getRunParameter()->fIsMC == 2 && fDSTLTrig == 0 )
{
return;
}
// get the Monte Carlo data
if( fMC )
{
fDSTprimary = fReader->getMC_primary();
fDSTenergy = ( float )fReader->getMC_energy();
fDSTxcore = ( float )fReader->getMC_X();
fDSTycore = ( float )fReader->getMC_Y();
fDSTze = ( float )fReader->getMC_Ze();
fDSTaz = ( float )fReader->getMC_Az();
fDSTTel_xoff = ( float )fReader->getMC_Xoffset();
fDSTTel_yoff = ( float )fReader->getMC_Yoffset();
}
// check if there was an array trigger, otherwise skip event
if( fReader->isMC() && fDSTLTrig == 0 )
{
resetDataVectors();
fDST_tree->Fill();
return;
}
// temporary variable
vector< float > t_PulseTimingTemp;
// ntel is always to total number of telescopes in the DST file
fDSTntel_data = getNTel();
for( unsigned int i = 0; i < fDSTntel_data; i++ )
{
fDSTtel_data[i] = i;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
// loop over all telescope and analyse channel by channel
// get sums and toffsets
int intubes = 0;
for( unsigned int i = 0; i < getNTel(); i++ )
{
double i_total = 0;
if( isTeltoAna( i ) )
{
intubes = 0;
setTelID( i );
// set number of samples
setNSamples( fReader->getNumSamples() );
// set hilo
fillHiLo();
// find dead channels (time dependent)
// findDeadChans( false, false );
// findDeadChans( true, false );
// integrate FADC traces -> calculate integrated charges and pulse timing
calcTZerosSums( getSumFirst(), getSumFirst() + getSumWindow(), getTraceIntegrationMethod() );
// image cleaning if image threshold is > 0.
if( getImageCleaningParameter() && getImageCleaningParameter()->fimagethresh > 0. )
{
if( fVImageCleaning )
{
fVImageCleaning->cleanImagePedvars( getImageCleaningParameter() );
}
if( i < getRunParameter()->fDoublePass.size() && getRunParameter()->fDoublePass[i] )
{
calcSecondTZerosSums();
if( fVImageCleaning )
{
fVImageCleaning->cleanImagePedvars( getImageCleaningParameter() );
}
}
}
else
{
setImage( true );
setBorder( false );
}
// calculate total sum over all channels
for( unsigned int j = 0; j < getNChannels(); j++ )
{
i_total += getSums()[j];
}
}
// fill pulse timing level
if( fRunPar->fpulsetiminglevels.size() < getDSTpulsetiminglevelsN() )
{
for( unsigned int t = 0; t < fRunPar->fpulsetiminglevels.size(); t++ )
{
fDSTpulsetiminglevels[i][t] = fRunPar->fpulsetiminglevels[t];
}
}
// fill dst arrays
for( unsigned int j = 0; j < getNChannels(); j++ )
{
fDSTChan[i][j] = j;
// fill values for this event, this telescope and this pixel if:
// i) this is a valid laser event
// or
// ii) fRunPar->fdstwriteallpixel is set to true
// or
// iii) this is a border or image pixel
if( isTeltoAna( i ) && ( ( !fBLaser || ( i_total > fRunPar->fLaserSumMin ) )
&& ( fRunPar->fdstwriteallpixel || getBorder()[j] || getImage()[j] ) ) )
{
intubes++;
///////////////////////////////////////////////
// for laser only
if( fBLaser )
{
int corrfirst = TMath::Nint( getTZeros()[j] ) - 3;
fDSTpedestal[i][j] = ( float )getPeds( getHiLo()[j] )[j];
fDSTsums[i][j] = ( float )fTraceHandler->getTraceSum( corrfirst, corrfirst + getSumWindow(), false );
fDSTsums2[i][j] = fDSTsums[i][j];
// ignore dead low gain channels
fDSTdead[i][j] = ( unsigned int )getDead()[j];
fDSTsumwindow[i][j] = getCurrentSumWindow()[j];
fDSTsumfirst[i][j] = getTCorrectedSumFirst()[j];
// fill pulse timing
if( fRunPar->fpulsetiminglevels.size() < getDSTpulsetiminglevelsN() )
{
t_PulseTimingTemp = fTraceHandler->getPulseTiming( corrfirst, corrfirst + getSumWindow(), 0, getNSamples() );
for( unsigned int t = 0; t < fRunPar->fpulsetiminglevels.size(); t++ )
{
fDSTpulsetiming[i][t][j] = t_PulseTimingTemp[t];
}
}
double i_max = 0.;
unsigned int maxpos = 0;
unsigned int n255 = 0;
fTraceHandler->getTraceMax( corrfirst, corrfirst + getSumWindow(), i_max, maxpos, n255 );
if( maxpos != 99999 )
{
fDSTMax[i][j] = ( short )i_max;
fDSTRawMax[i][j] = ( short )( i_max + getPeds( getHiLo()[j] )[j] );
}
else
{
fDSTMax[i][j] = 0;
fDSTRawMax[i][j] = 0;
}
}
///////////////////////////////////////////////
// normal data
else
{
fDSTpedestal[i][j] = ( float )getPeds( getHiLo()[j] )[j];
fDSTsums[i][j] = ( float )getSums()[j];
fDSTsums2[i][j] = ( float )getSums2()[j];
//set channel dead if it is ( dead in low gain AND in low gain ) OR (dead in high gain AND in high gain )
fDSTdead[i][j] = ( unsigned int )getDead( getHiLo()[j] )[j];
fDSTsumwindow[i][j] = getCurrentSumWindow()[j];
fDSTsumfirst[i][j] = getTCorrectedSumFirst()[j];
if( fRunPar->fpulsetiminglevels.size() < getDSTpulsetiminglevelsN() )
{
for( unsigned int t = 0; t < fRunPar->fpulsetiminglevels.size(); t++ )
{
fDSTpulsetiming[i][t][j] = ( float )getPulseTiming()[t][j];
}
}
fDSTTraceWidth[i][j] = ( float )getTraceWidth()[j];
fDSTMax[i][j] = ( short )getTraceMax()[j];
fDSTN255[i][j] = getTraceN255()[j];
fDSTRawMax[i][j] = ( short )getTraceRawMax()[j];
}
fDSTHiLo[i][j] = ( unsigned int )getHiLo()[j];
}
else
{
fDSTpedestal[i][j] = 0.;
fDSTsums[i][j] = 0.;
fDSTsums2[i][j] = 0.;
fDSTsumwindow[i][j] = 0;
fDSTsumfirst[i][j] = 0;
if( fRunPar->fpulsetiminglevels.size() < getDSTpulsetiminglevelsN() )
{
for( unsigned int t = 0; t < fRunPar->fpulsetiminglevels.size(); t++ )
{
fDSTpulsetiming[i][t][j] = 0.;
}
}
fDSTMax[i][j] = 0;
fDSTRawMax[i][j] = 0;
fDSTHiLo[i][j] = 0;
fDSTN255[i][j] = 0;
}
}
if( fMC )
{
fDSTLTtime[i] = ( float )getReader()->getLocalTriggerTime( i );
fDSTLDTtime[i] = ( float )getReader()->getLocalDelayedTriggerTime( i );
fDSTL2TrigType[i] = ( int )getReader()->getLocalTriggerType( i );
}
}
// only write events with more than NN ntubes to disk (for one telescope only)
if( getNTel() == 1 && intubes < getRunParameter()->fdstminntubes )
{
return;
}
fDST_tree->Fill();
}
void VDST::terminate()
{
if( getDebugFlag() )
{
cout << "VDST::terminate()" << endl;
}
// now write everything to disk
if( fDSTfile )
{
if( fDSTfile->cd() )
{
cout << "writing data summary tree to " << fDSTfile->GetName() << endl;
cout << "\t total number of events in dst tree: " << fDST_tree->GetEntries() << endl;
fDST_tree->Write();
getRunParameter()->Write();
// write detector tree
if( getDetectorTree() )
{
if( fDebug )
{
cout << "\t writing detector tree: " << getDetectorTree()->GetName() << endl;
}
getDetectorTree()->Write();
}
if( fDebug )
{
cout << "\t writing mean pulses " << endl;
}
// write pulse shape histograms
if( fDSTfile->mkdir( "meanPulses" )->cd() )
{
for( unsigned int i = 0; i < getNTel(); i++ )
{
setTelID( i );
if( getMeanPulseHistograms() )
{
getMeanPulseHistograms()->Write();
}
}
}
// write pulse sum histograms
if( fDSTfile->mkdir( "pulseSums" )->cd() )
{
for( unsigned int i = 0; i < getNTel(); i++ )
{
setTelID( i );
if( getIntegratedChargeHistograms() )
{
getIntegratedChargeHistograms()->Write();
}
}
}
// write calibration data
writeCalibrationData();
}
fDSTfile->Close();
}
}
bool VDST::writeCalibrationData()
{
if( fDebug )
{
cout << "VDST::writeCalibrationData()" << endl;
}
if( fDSTfile )
{
fDSTfile->cd();
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// DST analysis
// (same code as in c_VDST)
// max channels very different for CTA and VERITAS; adjust
float* fPedvar_high = 0;
float* fPedvar_low = 0;
if( fRunPar->getObservatory() == "VERITAS" )
{
fPedvar_high = new float[500 * 120];
fPedvar_low = new float[500 * 120];
}
else
{
fPedvar_high = new float[VDST_MAXCHANNELS * VDST_MAXSUMWINDOW];
fPedvar_low = new float[VDST_MAXCHANNELS * VDST_MAXSUMWINDOW];
}
int fTelID = 0;
unsigned int nPixel = 0;
// integration window
unsigned int fnum_sumwindow = 1;
unsigned int fsumwindow[VDST_MAXSUMWINDOW];
float fPed_high[VDST_MAXCHANNELS];
float fPed_low[VDST_MAXCHANNELS];
float fConv_high[VDST_MAXCHANNELS];
float fConv_low[VDST_MAXCHANNELS];
float fTZero[VDST_MAXCHANNELS];
for( unsigned int i = 0; i < VDST_MAXCHANNELS; i++ )
{
fPed_high[i] = 0.;
fPed_low[i] = 0.;
fConv_high[i] = 0.;
fConv_low[i] = 0.;
fTZero[i] = -999.;
for( unsigned int j = 0; j < VDST_MAXSUMWINDOW; j++ )
{
fPedvar_high[i * VDST_MAXSUMWINDOW + j] = 0;
fPedvar_low[i * VDST_MAXSUMWINDOW + j] = 0;
}
}
TTree* t = new TTree( "calibration", "calibration data" );
char hname[200];
t->Branch( "TelID", &fTelID, "TelID/I" );
t->Branch( "NPixel", &nPixel, "NPixel/i" );
if( t->GetBranchStatus( "num_sumwindow" ) )
{
t->Branch( "num_sumwindow", &fnum_sumwindow, "num_sumwindow/i" );
t->Branch( "sumwindow", fsumwindow, "sumwindow[num_sumwindow]/i" );
}
else
{
fnum_sumwindow = 0;
}
t->Branch( "ped_high", fPed_high, "ped_high[NPixel]/F" );
sprintf( hname, "pedvar_high[%d]/F", VDST_MAXCHANNELS * VDST_MAXSUMWINDOW );
t->Branch( "pedvar_high", fPedvar_high, hname );
t->Branch( "ped_low", fPed_low, "ped_low[NPixel]/F" );
sprintf( hname, "pedvar_low[%d]/F", VDST_MAXCHANNELS * VDST_MAXSUMWINDOW );
t->Branch( "pedvar_low", fPedvar_low, hname );
t->Branch( "conv_high", fConv_high, "conv_high[NPixel]/F" );
t->Branch( "conv_low", fConv_low, "conv_low[NPixel]/F" );
t->Branch( "tzero", fTZero, "tzero[NPixel]/F" );
fnum_sumwindow = getRunParameter()->fCalibrationSumWindow;
for( unsigned int i = 0; i < ( unsigned int )getRunParameter()->fCalibrationSumWindow; i++ )
{
fsumwindow[i] = i + 1;
}
for( unsigned int itel = 0; itel < getNTel(); itel++ )
{
setTelID( itel );
fTelID = getTelID();
// correct number of samples
if( getNSamples() < fnum_sumwindow )
{
fnum_sumwindow = getNSamples();
}
nPixel = ( unsigned int )getNChannels();
if( VDST_MAXCHANNELS < nPixel )
{
cout << "DST_fillCalibrationTree error: number of pixels (" << nPixel << ") exeeds allowed range (" << VDST_MAXCHANNELS << ")" << endl;
cout << "\t adjust arrays..." << endl;
return false;
}
for( unsigned int p = 0; p < nPixel; p++ )
{
fPed_high[p] = getPeds()[p];
for( unsigned int i = 0; i < ( unsigned int )fnum_sumwindow; i++ )
{
fPedvar_high[p * VDST_MAXSUMWINDOW + i] = getPedvars( i + 1 )[p];
fPedvar_low[p * VDST_MAXSUMWINDOW + i] = getPedvars( i + 1, true )[p];
}
fPed_low[p] = getPeds( true )[p];
fConv_high[p] = 1.;
fConv_low[p] = 1.;
if( p < getAverageTZeros().size() )
{
fTZero[p] = getAverageTZeros()[p];
}
else
{
fTZero[p] = 0.;
}
}
t->Fill();
}
t->Write();
if( fDebug )
{
cout << "END VDST::writeCalibrationData()" << endl;
}
delete [] fPedvar_high;
delete [] fPedvar_low;
return true;
}
|
28f7e84e0697306e5ee9c096897d469a98f65387
|
614850f5190bea7c4a52f0432dea9beb8678be23
|
/12.cpp
|
37f2a941f368874996f839ba86cd5ae8c8efbece
|
[] |
no_license
|
zigaroula/ACM-ICPC-Training
|
33a72ccf647afa2bdded48dee26665349242f86c
|
fd4ad1d23d5f20090f8a62393024fdd2635feb92
|
refs/heads/master
| 2021-01-12T21:05:11.834502
| 2015-09-28T20:44:46
| 2015-09-28T20:44:46
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,412
|
cpp
|
12.cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
int cases, n, m;
vector<vector<int> > rel;
vector<int> tar;
int main() {
scanf("%d", &cases);
for (int numbercases = 0 ; numbercases < cases ; numbercases++) {
rel.clear();
tar.clear();
scanf("%d", &n);
scanf("%d", &m);
rel.resize(n);
for (int i = 0 ; i < m ; i++) {
int a, b;
scanf("%d", &a);
scanf("%d", &b);
rel[a].push_back(b);
rel[b].push_back(a);
}
vector<int> cycle;
for (int i = 0 ; i < n ; i++) {
tar.clear();
int start = i;
int target = i;
int cpt = 0;
int last = 0;
tar.push_back(start);
vector<bool> par(n, false);
par[start] = true;
bool stop = false;
bool nocycle = false;
while(1) {
int taille = tar.size();
if (cpt == 1) {
fill(par.begin(), par.end(), false);
par[target] = true;
}
if (cpt == 2) {
par[target] = false;
}
for (int h = last ; h < taille ; h++) {
for (int i = 0 ; i < rel[tar[h]].size() ; i++) {
if (!par[rel[tar[h]][i]]) {
tar.push_back(rel[tar[h]][i]);
par[rel[tar[h]][i]] = true;
}
}
if (par[target] && cpt>=2) {
stop = true;
break;
}
}
last = taille;
if (stop) {
break;
}
cpt++;
if (cpt>=n+1) {
nocycle = true;
break;
}
}
if (!nocycle) {
cycle.push_back(cpt+1);
} else {
cycle.push_back(n+10);
}
}
int res = *min_element(cycle.begin(), cycle.end());
if (res == n+10) {
printf("Case %d: impossible\n", numbercases+1);
} else {
printf("Case %d: %d\n", numbercases+1, res);
}
}
return 0;
}
|
fe5a68f24ed3f1ea5191f0dfff559573d9efc160
|
bcafd8102f07bc16ccb09b5c6d213ffa8efa75ea
|
/gyak09/gumimaci.cpp
|
1841374fb2c70372888fcefd75f832ba3b1d0473
|
[] |
no_license
|
juditacs/villprog
|
c5a04fb70ef12acaa18b39949d8b86173548df31
|
95184da6b129f23d3a3b4b88314cc13f58aaf505
|
refs/heads/master
| 2021-01-21T13:53:22.762407
| 2016-05-18T10:48:31
| 2016-05-18T10:48:31
| 52,074,874
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,517
|
cpp
|
gumimaci.cpp
|
/*
* gumimaci.cpp
* Copyright (C) 2016 Judit Acs <judit@sch.bme.hu>
*
* Distributed under terms of the MIT license.
*/
#include <iostream>
#include <string>
class Partner {
protected:
Partner* recommender;
std::string name;
public:
Partner(std::string name): name(name) {}
void setRecommender(Partner* p) {recommender = p;}
void printRecommender() const {recommender->print(); std::cout << std::endl;}
//virtual void print() const {std::cout << "Partner: " << name;}
virtual void print() const = 0;
virtual ~Partner() {std::cout << "Partner " << name << " destroyed" << std::endl;}
};
class Company: public Partner {
char taxnum[12];
public:
Company(std::string name): Partner(name) {}
void setTaxnum(char t[12]) {for(int i=0; i<12; i++) taxnum[i] = t[i];}
void print() const {std::cout << "Company: " << name;}
~Company() {std::cout << "Company " << name << " destroyed" << std::endl;}
};
class Person: public Partner {
char taxid[11];
public:
Person(std::string name): Partner(name) {}
void setTaxid(char t[11]) {for(int i=0; i<11; i++) taxid[i] = t[i];}
void print() const {std::cout << "Person: " << name;}
~Person() {std::cout << "Person " << name << " destroyed" << std::endl;}
};
int main(int argc, char* argv[]) {
Partner** p = new Partner*[2];
p[0] = new Person("Kati");
p[1] = new Company("Microsoft");
p[0]->print();
std::cout << std::endl;
p[1]->print();
std::cout << std::endl;
delete[] p;
}
|
7858f5c8ef83aeec513e454e8c19cdb47e1b5087
|
71445ce9808412c0dc0b559250ca4d2f37c78413
|
/ParaView/Qt/Components/pqPlotMatrixDisplayPanel.cxx
|
486422fffb76ef209b505a04acc257dfe2a71a23
|
[
"LicenseRef-scancode-protobuf",
"LicenseRef-scancode-paraview-1.2"
] |
permissive
|
alexisylchan/CollabVRGUI
|
400f2169898e6ed2b962dba29a2776b1dc3442df
|
8392162df5d115bb1128b92d267886c5227e7708
|
refs/heads/master
| 2021-01-01T06:33:45.035077
| 2012-09-10T04:58:34
| 2012-09-10T04:58:34
| 5,745,206
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,369
|
cxx
|
pqPlotMatrixDisplayPanel.cxx
|
/*=========================================================================
Program: ParaView
Module: pqPlotMatrixDisplayPanel.h
Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqPlotMatrixDisplayPanel.h"
#include "pqChartSeriesSettingsModel.h"
#include "pqDataRepresentation.h"
#include "pqSignalAdaptors.h"
#include "vtkSMProxy.h"
#include "ui_pqPlotMatrixDisplayPanel.h"
pqPlotMatrixDisplayPanel::pqPlotMatrixDisplayPanel(pqRepresentation *representation, QWidget *pWidget)
: pqDisplayPanel(representation, pWidget)
{
Ui::pqPlotMatrixDisplayPanel ui;
ui.setupUi(this);
this->SettingsModel = new pqChartSeriesSettingsModel(this);
pqDataRepresentation* dispRep = qobject_cast<pqDataRepresentation*>(representation);
this->SettingsModel->setRepresentation(dispRep);
ui.Series->setModel(this->SettingsModel);
ui.Series->setAcceptDrops(true);
ui.Series->setDragEnabled(true);
ui.Series->setDropIndicatorShown(true);
ui.Series->setDragDropOverwriteMode(false);
ui.Series->setDragDropMode(QAbstractItemView::InternalMove);
vtkSMProxy *proxy = representation->getProxy();
// add color buttons
ui.ActivePlotColor->setChosenColor(Qt::black);
ui.ScatterPlotsColor->setChosenColor(Qt::black);
ui.HistogramColor->setChosenColor(Qt::black);
this->ActivePlotColorAdaptor = new pqSignalAdaptorColor(ui.ActivePlotColor,
"chosenColor",
SIGNAL(chosenColorChanged(const QColor&)),
false);
this->ScatterPlotsColorAdaptor = new pqSignalAdaptorColor(ui.ScatterPlotsColor,
"chosenColor",
SIGNAL(chosenColorChanged(const QColor&)),
false);
this->HistogramColorAdaptor = new pqSignalAdaptorColor(ui.HistogramColor,
"chosenColor",
SIGNAL(chosenColorChanged(const QColor&)),
false);
this->Links.addPropertyLink(this->ActivePlotColorAdaptor,
"color",
SIGNAL(colorChanged(QVariant)),
proxy,
proxy->GetProperty("ActivePlotColor"));
this->Links.addPropertyLink(this->ScatterPlotsColorAdaptor,
"color",
SIGNAL(colorChanged(QVariant)),
proxy,
proxy->GetProperty("Color"));
this->Links.addPropertyLink(this->HistogramColorAdaptor,
"color",
SIGNAL(colorChanged(QVariant)),
proxy,
proxy->GetProperty("HistogramColor"));
this->Links.addPropertyLink(ui.ActivePlotMarkerSize,
"value",
SIGNAL(valueChanged(double)),
proxy,
proxy->GetProperty("ActivePlotMarkerSize"));
this->Links.addPropertyLink(ui.ScatterPlotMarkerSize,
"value",
SIGNAL(valueChanged(double)),
proxy,
proxy->GetProperty("ScatterPlotMarkerSize"));
this->ActivePlotMarkerStyleAdaptor = new pqSignalAdaptorComboBox(ui.ActivePlotMarkerStyle);
this->ScatterPlotsMarkerStyleAdaptor = new pqSignalAdaptorComboBox(ui.ScatterPlotMarkerStyle);
this->Links.addPropertyLink(this->ActivePlotMarkerStyleAdaptor,
"currentIndex",
SIGNAL(currentIndexChanged(int)),
proxy,
proxy->GetProperty("ActivePlotMarkerStyle"));
this->Links.addPropertyLink(this->ScatterPlotsMarkerStyleAdaptor,
"currentIndex",
SIGNAL(currentIndexChanged(int)),
proxy,
proxy->GetProperty("ScatterPlotMarkerStyle"));
QObject::connect(this->SettingsModel,
SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this,
SLOT(dataChanged(QModelIndex, QModelIndex)));
QObject::connect(this->SettingsModel, SIGNAL(redrawChart()),
this, SLOT(updateAllViews()));
QObject::connect(dispRep, SIGNAL(dataUpdated()), this, SLOT(reloadSeries()));
this->reloadSeries();
}
pqPlotMatrixDisplayPanel::~pqPlotMatrixDisplayPanel()
{
}
void pqPlotMatrixDisplayPanel::dataChanged(QModelIndex topLeft, QModelIndex bottomRight)
{
Q_UNUSED(topLeft);
Q_UNUSED(bottomRight);
this->Representation->renderViewEventually();
}
//-----------------------------------------------------------------------------
void pqPlotMatrixDisplayPanel::reloadSeries()
{
this->updateAllViews();
this->SettingsModel->reload();
}
|
f41ae6553a0a31f7afb4a3c22fc89b6f28228920
|
1f9ae86f8176058a751afb7c9af666aa6c61785e
|
/State-I/StateCls.h
|
a2bba987a4961d8a93944982acc1efaf110f31d1
|
[] |
no_license
|
RamazanDemirci/DesignPatternExamples
|
e13dfdcbf7937c6adbf7175f1e42d64fa565af4c
|
3be595f2028f0315d2f28b8cc51cbcd26d1f1c96
|
refs/heads/master
| 2020-03-23T05:35:30.449884
| 2018-08-13T21:18:11
| 2018-08-13T21:18:11
| 141,153,982
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 306
|
h
|
StateCls.h
|
/*
* StateCls.h
*
* Created on: 30 Tem 2018
* Author: tr1d5042
*/
#ifndef STATECLS_H_
#define STATECLS_H_
class MachineCls;
class StateCls {
public:
StateCls();
virtual ~StateCls();
virtual void on(MachineCls *machine);
virtual void off(MachineCls *machine);
};
#endif /* STATECLS_H_ */
|
896f13fe1930b5ea351323ea310285b25d936895
|
b7d447ce4834ff96580bd02991cde604dc25ec2c
|
/threadedtree.cpp
|
c0965f6f25281aa75fe008b6b9b092311e829470
|
[] |
no_license
|
Ruhika1417/DSA_CPP
|
df74f7a3ceab16a1db12a991ab9a8bcddc7a0c9f
|
71d5ebc32094d8fafeb28d7dc63f605ca8c0d8ff
|
refs/heads/master
| 2023-02-25T10:35:35.635178
| 2021-02-06T11:30:01
| 2021-02-06T11:30:01
| 287,519,009
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,467
|
cpp
|
threadedtree.cpp
|
//threaded binary tree.
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *left;
Node *right;
int leftThread; // leftThread=0 -> left pointer points to the inorder predecessor
int rightThread; // rightThread=0 -> right pointer points to the inorder successor
Node(int val)
{
this->data = val;
}
};
class DoubleThreadedBinaryTree
{
private:
Node *root;
public:
DoubleThreadedBinaryTree()
{
// dummy Node with value as INT_MAX
root = new Node(INT_MAX);
root->left = root->right = root;
root->leftThread = 0;
root->rightThread = 1;
}
void insert(int data)
{
Node *new_node = new Node(data);
if (root->left == root && root->right == root)
{
//Empty Tree
new_node->left = root;
root->left = new_node;
new_node->leftThread = 0;
new_node->rightThread = 0;
root->leftThread = 1;
new_node->right = root;
return;
}
else
{
Node *current = root->left;
while (true)
{
if (current->data > data)
{
if (current->leftThread == 0)
{
// this is the last Node
new_node->left = current->left;
current->left = new_node;
new_node->leftThread = current->leftThread;
new_node->rightThread = 0;
current->leftThread = 1;
new_node->right = current;
break;
}
else
{
current = current->left;
}
}
else
{
if (current->rightThread == 0)
{
// this is the last Node
new_node->right = current->right;
current->right = new_node;
new_node->rightThread = current->rightThread;
new_node->leftThread = 0;
current->rightThread = 1;
new_node->left = current;
break;
}
else
{
current = current->right;
}
}
}
}
}
Node *findNextInorder(Node *current)
{
if (current->rightThread == 0)
{
return current->right;
}
current = current->right;
while (current->leftThread != 0)
{
current = current->left;
}
return current;
}
void inorder()
{
Node *current = root->left;
while (current->leftThread == 1)
{
current = current->left;
}
while (current != root)
{
cout << current->data << " ";
current = findNextInorder(current);
}
cout <<" \n";
}
void preorder()
{
Node *current = root->left;
while (current != root)
{
cout << current->data << " ";
if (current->left != root && current->leftThread != 0)
current = current->left;
else if (current->rightThread == 1)
{
current = current->right;
}
else
{
while (current->right != root && current->rightThread == 0)
{
current = current->right;
}
if (current->right == root)
break;
else
{
current = current->right;
}
}
}
cout << "\n";
}
};
int main()
{
DoubleThreadedBinaryTree dtbt;
dtbt.insert(109);
dtbt.insert(45);
dtbt.insert(76);
dtbt.insert(17);
dtbt.insert(23);
dtbt.insert(100);
dtbt.inorder();
dtbt.preorder();
return 0;
}
|
c4bd2e7b2b400838173c60196cc95406e95afdc9
|
fb17b4cb741d9ab81ec9cc9d4a8c70ad2700e203
|
/vfh/polarhistogram.h
|
ed88e3edea6d974821b2f37b3c541bad22ec22a7
|
[] |
no_license
|
silei862/robotic
|
34273caec1c94cead3c1dcc44518925f956e2126
|
0b92de89848a6830a522ebf0b595db6b34c3604b
|
refs/heads/master
| 2020-05-17T06:06:12.746432
| 2013-03-18T07:33:31
| 2013-03-18T07:33:31
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,792
|
h
|
polarhistogram.h
|
/*
* =====================================================================================
*
* Filename: polarhistogram.h
*
* Description: 方位直方图的实现
*
* Version: 1.0
* Created: 2012年11月21日 11时29分30秒
* Revision: none
* Compiler: gcc
*
* Author: 思磊 (Silei), silei862@gmail.com
* Organization: TSA@PLA
*
* =====================================================================================
*/
#ifndef _POLARHISTOGRAM_H_
#define _POLARHISTOGRAM_H_
#include <stdlib.h>
#include <stdint.h>
#include <vector>
#include <cmath>
namespace SlamLab
{
template< typename TP >
class PolarHistogram
{
public:
static const size_t SECTOR_NUM=72;
static const double PI=3.1415926535;
public:
PolarHistogram( size_t sector_num=SECTOR_NUM )
:_sector_size( 2*PI/double(sector_num) ){ _histogram.resize( sector_num ); }
virtual ~PolarHistogram() { }
public:
size_t sector_num( ){ return _histogram.size(); }
double sector_size( ){ return _sector_size; }
// 设置直方图内所有值
void set_all_val( TP val )
{
for( size_t i=0;i<_histogram.size();i++ )
_histogram[i] = val;
}
// 获取元素引用
TP& get_ref( size_t index ){ return _histogram[index]; }
TP& get_ref( double polar )
{
//double _polar=fmod( polar,2*PI );
return _histogram[ size_t(polar/_sector_size) ];
}
// 判断整型索引是否越界
bool in( size_t index ){ return index >=0 && index<_histogram.size(); }
// 存取操作符
TP& operator[]( size_t index ){ return get_ref( index ); }
TP& operator[]( double polar ){ return get_ref( polar ); }
private:
std::vector<TP> _histogram;
double _sector_size;
};
}
#endif //_POLARHISTOGRAM_H_
|
5057da1139a45bc49f122c0e961a1f9f851cfefc
|
b7671e7c80f7529911a6fd15a3830f469fe435f3
|
/src/common/common/network/Net.hpp
|
f64ce1e71f4a73e6c47bbd71e97d0373e0535f52
|
[
"MIT"
] |
permissive
|
QualityHammer/CrossPlat
|
cf1ca50b4ae09ef2ec999be6ed7aaff2c11b5a20
|
60ea4e9849253e3753fa0becf6c3cf68c67d4b36
|
refs/heads/master
| 2023-01-13T20:38:51.659183
| 2020-04-22T02:37:44
| 2020-04-22T02:37:44
| 253,580,188
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 186
|
hpp
|
Net.hpp
|
#pragma once
#include <enet/enet.h>
namespace Net {
// Calls enet initialization on win32 systems
void netInit();
// Calls enet de-initialization on win32 systems
void netClose();
}
|
027b8652d1a9fd08ea29b540bf0a714c7a35943d
|
e675455f2e207638445c4cd093a9a4ec971bc047
|
/src/algorithm_practice/Datastructure_Algorithms/SLL/mergeTwoSortedLists/ojAns.cpp
|
5238d5efce5161ee3bfd11ec644113ced6e60142
|
[] |
no_license
|
domfarolino/algorithms
|
5e1969f092fc66acdce5f560a35056fdb0adc2e2
|
8120051a7615236bbb473fb95b90fa8589921400
|
refs/heads/master
| 2023-05-24T05:38:41.326685
| 2023-05-13T16:22:06
| 2023-05-13T16:22:06
| 67,319,532
| 52
| 71
| null | 2023-05-13T16:22:08
| 2016-09-04T01:25:14
|
C++
|
UTF-8
|
C++
| false
| false
| 1,278
|
cpp
|
ojAns.cpp
|
// Source: https://leetcode.com/problems/merge-two-sorted-lists/description/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *curr1 = l1, *curr2 = l2, *tmp, *potentialNext;
if (!l1 && !l2) return NULL;
if (!l1 || !l2) return (l1) ? l1 : l2;
while (curr1 && curr2) {
if (curr1->val <= curr2->val) {
potentialNext = curr1->next;
if (potentialNext && potentialNext->val <= curr2->val) {
curr1 = curr1->next;
} else {
tmp = curr1->next;
curr1->next = curr2;
curr1 = tmp;
}
} else {
potentialNext = curr2->next;
if (potentialNext && potentialNext->val < curr1->val) {
curr2 = curr2->next;
} else {
tmp = curr2->next;
curr2->next = curr1;
curr2 = tmp;
}
}
}
return (l1->val <= l2->val) ? l1 : l2;
}
};
|
84271f24d3cc2bc2ba6278499d17dd0445a7e477
|
1d3b0b0d5337adb8335b1a970b0c34924b8baf96
|
/AtCoder/abc/1~30/abc025/B.cpp
|
5d21f8931dbb90331bb69d25cc0b0db2e99afd08
|
[] |
no_license
|
pyst1g/Programming-Cplus
|
6a2bdbbc63935fe7b4ebd00f6c9d13565cb05bcf
|
7d2c41075382e606e4c572c3ebd239755f36e72a
|
refs/heads/master
| 2021-05-14T16:14:49.720215
| 2020-01-26T09:53:16
| 2020-01-26T09:53:16
| 116,015,340
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 843
|
cpp
|
B.cpp
|
// finish date: 2018/01/08
#include <iostream>
#include <cmath>
#include <vector>
#include <bitset>
#include <algorithm>
#include <stack>
#include <limits>
#include <map>
using namespace std;
#define FOR(i, a, b) for(int i=a;i<b;i++)
#define rep(i, n) FOR(i,0,n)
bool isExist(char c, string str) {
rep(i, str.length()) {
if (c == str[i]) return true;
}
return false;
}
int main() {
int N, A, B;
cin >> N >> A >> B;
int pos = 0;
string s;
int d;
rep(i, N) {
cin >> s >> d;
d = min(B, max(A, d)); // 実際移動する距離
if (s == "West") {
pos -= d;
} else {
pos += d;
}
}
if (pos == 0) cout << 0 << endl;
else if (pos > 0) cout << "East " << pos << endl;
else cout << "West " << -pos << endl;
return 0;
}
|
95c9f592f73d7c9476380a1de8d97f504e111987
|
b2580b87161110baa3452d082703aed26e420b31
|
/src/main.cpp
|
84cccebddb98081d036b24b1e8e040ae1a9553fe
|
[
"MIT"
] |
permissive
|
onionka/IMS-CAS
|
e5cba04418fdea96a1a1a61286740588bcb70fc5
|
12a2521be94ee7605e3ce7d846c2cb7cdc6744c0
|
refs/heads/master
| 2021-05-30T13:24:20.115419
| 2015-12-07T19:13:29
| 2015-12-07T19:15:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,285
|
cpp
|
main.cpp
|
/**
* @file main.cpp
* @author Miroslav Cibulka
* @created 12/4/15
* @copyright Copyright (c) 2015 XXX
* @detail
*
*/
#include <stdexcept>
#include "state.hh"
#include "cell.hh"
#include "cellular_automata.hh"
#include "bmp.hh"
#include "plot.hh"
#ifndef MAP_SIZE
# define MAP_SIZE 1000
#endif
#ifndef LOOP_COUNT
# define LOOP_COUNT 200
#endif
#ifndef DEFAULT_T
# define DEFAULT_T 4
#endif
#define DEFAULT_HIV 0.05
#define DEFAULT_REPLACE 0.99
#ifndef DEFAULT_INFECTION
# define DEFAULT_INFECTION 0.00001
#endif
static inline bool take_chance(double chance)
{ return ((double)::std::rand() / (double)RAND_MAX) < chance; }
enum class CellStatus : unsigned
{
Healthy, Infected, HeavyInfected, Dead
};
struct CellState :
public State<CellStatus>
{
typedef State<CellStatus> _BaseC;
CellState() { }
CellState(int T_steps, double HIV, double REPLACE, double INFECT) :
_t(T_steps), _hiv(HIV), _replace(REPLACE), _infect(INFECT)
{
// Cell is infected
if (take_chance(HIV))
value = CellStatus::Infected;
else
value = CellStatus::Healthy;
}
virtual _BaseC &operator<<(const State &another_state)
{
// We are only interested in surrounding states, so collect them for later
surrounding_states.push_back(another_state.getValue());
return *this;
}
virtual _BaseC::value_type getValue() const
{ return value; }
virtual void setValue(_BaseC::value_type _value)
{ value = _value; }
/** One tick */
virtual void renew()
{
_BaseC::value_type new_value = value;
if (newly_created && value == CellStatus::Healthy && take_chance(_infect))
new_value = CellStatus::Infected;
// Changes by surrounding cells
else if (value == CellStatus::Healthy && ::std::count(
surrounding_states.begin(), surrounding_states.end(),
CellStatus::Infected) > 0)
{ new_value = CellStatus::Infected; }
else if (value == CellStatus::Healthy && ::std::count(
surrounding_states.begin(), surrounding_states.end(),
CellStatus::HeavyInfected) > 1)
{ new_value = CellStatus::Infected; }
// Stepps for CellStatus::Infected to become CellStatus::HeavyInfected
else if (value == CellStatus::Infected && step_counter == _t)
{
new_value = CellStatus::HeavyInfected;
step_counter = 0;
}
// Every tick HeavyInfected cell die
else if (value == CellStatus::HeavyInfected)
{ new_value = CellStatus::Dead; }
// Replace chances
else if (value == CellStatus::Dead && take_chance(_replace))
{
newly_created = true;
if (take_chance(_infect))
new_value = CellStatus::Infected;
else
new_value = CellStatus::Healthy;
}
if (value == CellStatus::Infected)
{ step_counter++; }
else
{ step_counter = 0; }
surrounding_states.clear();
value = new_value;
}
private:
int _t = DEFAULT_T;
double _hiv = DEFAULT_HIV;
double _replace = DEFAULT_REPLACE;
double _infect = DEFAULT_INFECTION;
bool newly_created = false;
int step_counter = 0;
_BaseC::value_type value;
::std::vector<_BaseC::value_type> surrounding_states;
};
class HIVCell :
public Cell<8, CellState, CellStatus>
{
typedef Cell<8, CellState, CellStatus> _BaseT;
public:
struct params
{
params() { }
int T_steps = DEFAULT_T;
double HIV = DEFAULT_HIV;
double REPLACE= DEFAULT_REPLACE;
double INFECT = DEFAULT_INFECTION;
};
/**
* @param T_steps until CellStatus::Infected becomes CellStatus::HeavyInfected
* @param HIV is chance to cell become CellStatus::Infected on initialization
* @param REPLACE is chance to resurrect CellStatus::Dead Cell
* (it will become CellStatus::Healthy)
* @param INFECT is chance that newborn cell that is CellStatus::Healthy
* becomes CellStatus::Infected right after creation
*/
HIVCell(struct params p = params())
{ state = CellState(p.T_steps, p.HIV, p.REPLACE, p.INFECT); }
virtual _BaseT *die()
{
state.setValue(CellStatus::Dead);
return this;
}
/** @return Status of this cell */
virtual value_type getValue() const
{ return state.getValue(); }
};
class CellAutomata :
public CellularAutomata2D<MAP_SIZE, MAP_SIZE, CellState, HIVCell>
{
public:
typedef CellularAutomata2D<MAP_SIZE, MAP_SIZE, CellState, HIVCell> _BaseT;
/**
* if chance is out of bounds then exception is called
*/
CellAutomata() : _BaseT(HIVCell::params())
{
::std::srand((unsigned)::std::time(0));
// Filling neighbour list
for (size_t x = 0; x < height; ++x)
for (size_t y = 0; y < width; ++y)
{
auto _cell = map[x * width + y];
if (x < height - 1)
_cell->setNeighbour(0, map[(x + 1) * width + y]);
if (x < height - 1 && y < width - 1)
_cell->setNeighbour(4, map[(x + 1) * width + y + 1]);
if (x > 0)
_cell->setNeighbour(1, map[(x - 1) * width + y]);
if (x > 0 && y > 0)
_cell->setNeighbour(5, map[(x - 1) * width + y - 1]);
if (y < width - 1)
_cell->setNeighbour(2, map[x * width + y + 1]);
if (y < width - 1 && x > 0)
_cell->setNeighbour(6, map[(x - 1) * width + y + 1]);
if (y > 0)
_cell->setNeighbour(3, map[x * width + y - 1]);
if (y > 0 && x < height - 1)
_cell->setNeighbour(7, map[(x + 1) * width + y - 1]);
}
}
::std::vector<typename state_type::value_type> getValues()
{
::std::vector<typename state_type::value_type> _ret;
for (auto &_m : map)
_ret.push_back(_m->getValue());
return _ret;
}
};
struct Statistics
{
typedef GnuPlot<long, long> plot_type;
Statistics (::std::string fn) : filename(fn)
{ }
Statistics &operator << (CellStatus &c)
{ ++counts[(unsigned)c]; return *this; }
void notify()
{
for (int i = 0; i < 4; ++i)
{
_statuses[i].push_back(counts[i]);
counts[i] = 0;
}
header.push_back(++disc_time);
}
void flush()
{
plot_type(filename+"_healty.gp").write_data(header, _statuses[0]);
plot_type(filename+"_infected.gp").write_data(header, _statuses[1]);
plot_type(filename+"_heavy_infected.gp").write_data(header, _statuses[2]);
plot_type(filename+"_dead.gp").write_data(header, _statuses[3]);
}
private:
long counts[4] = { 0 };
::std::vector<long> _statuses[4];
::std::vector<long> header;
::std::string filename;
int disc_time = 0;
};
int main(int /*argc*/, const char **/*argv*/)
{
CellAutomata _aut;
Statistics _stats ("plot");
for (int i = 0; i < LOOP_COUNT; ++i)
{
::std::vector<unsigned> _vals;
for (CellStatus &_c : _aut.getValues())
{
switch(_c)
{
case CellStatus::Healthy: _vals.push_back(0x0033CC33); break;
case CellStatus::Infected: _vals.push_back(0x00FFFF00); break;
case CellStatus::HeavyInfected: _vals.push_back(0x00FF0000); break;
case CellStatus::Dead: _vals.push_back(0x00000000); break;
}
_stats << _c;
}
BMP(::std::string("obr") + ::std::to_string(i) + ".bmp", MAP_SIZE, MAP_SIZE)
<< _vals;
_aut.notify();
_stats.notify();
}
_stats.flush();
return 0;
}
|
0937033a07bbe7f3a168cf74821bfe99d392b4cb
|
b2f16656f82ccd347f83c9c902d9dbf21dce4e59
|
/Terminal/LogicWrapper/LogicWrapper.cpp
|
31cb7dd4185119b9b8885e4581fbb8670b6cd59d
|
[] |
no_license
|
victor84/AutoHandWash
|
e3a084fc1ba40b1d2ea1b3490296f989e83dfb7d
|
d62d6a209d06afa352f60268cecd15a077f148a8
|
refs/heads/master
| 2021-01-01T19:20:35.845115
| 2015-07-10T15:45:44
| 2015-07-10T15:45:44
| 31,407,033
| 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 7,048
|
cpp
|
LogicWrapper.cpp
|
// Главный DLL-файл.
#include "stdafx.h"
#include "LogicWrapper.h"
using namespace System::Collections::Generic;
void LogicWrapper::Logic::OnServiceChangedInner(logic::e_service_name service_id, const wchar_t* service_name)
{
if (nullptr == _on_service_changed)
return;
e_service_id sid = static_cast<e_service_id>(service_id);
String^ sn = gcnew String(service_name);
_on_service_changed(sid, sn);
}
void LogicWrapper::Logic::OnStateChangedInner(logic::e_state state)
{
if (nullptr == _on_state_changed)
return;
e_state_id state_id = static_cast<e_state_id>(state);
_on_state_changed(state_id);
}
void LogicWrapper::Logic::OnServiceInfoReadedInner(std::vector<logic::tag_service_info> collection)
{
if (nullptr == _on_service_info_readed)
return;
_servicesInfo = ConvertServicesInfo(collection);
_on_service_info_readed(_servicesInfo);
}
List<LogicWrapper::tag_service_info^>^ LogicWrapper::Logic::ConvertServicesInfo(std::vector<logic::tag_service_info> collection)
{
List<tag_service_info^>^ result = gcnew List<tag_service_info^>();
for (logic::tag_service_info elem : collection)
{
tag_service_info^ man_elem = gcnew tag_service_info();
man_elem->button_number = elem.button_number;
man_elem->cost = elem.cost;
man_elem->service_name = gcnew String(elem.service_name.c_str());
man_elem->id = static_cast<e_service_id>(elem.id);
result->Add(man_elem);
}
return result;
}
void LogicWrapper::Logic::OnTerminalStateChangedInner(logic::e_terminal_state state)
{
if (nullptr == _on_terminal_state_changed)
return;
if (nullptr == _servicesInfo)
return;
e_terminal_state terminal_state = static_cast<e_terminal_state>(state);
_on_terminal_state_changed(terminal_state);
}
void LogicWrapper::Logic::OnShowCountersInner(std::vector<logic::tag_service_counter> counters)
{
if (nullptr == _on_show_counters)
return;
List<tag_service_counter^>^ result = gcnew List < tag_service_counter^ >();
for (logic::tag_service_counter counter : counters)
{
tag_service_info^ si = nullptr;
for each (tag_service_info^ s in _servicesInfo)
{
if (s->id == static_cast<e_service_id>(counter.service.id))
{
si = s;
break;
}
}
if (nullptr == si)
break;
tag_service_counter^ c = gcnew tag_service_counter();
c->service = si;
c->counter = counter.counter;
result->Add(c);
}
_on_show_counters(result);
}
LogicWrapper::Logic::Logic()
: _on_service_changed(nullptr)
, _on_time_and_money_changed(nullptr)
, _on_state_changed(nullptr)
, _on_cache_refilled(nullptr)
, _on_service_info_readed(nullptr)
, _servicesInfo(nullptr)
{
_logic = new CLogicPimpl();
_on_service_changed_inner = gcnew OnServiceChangedDelegateInner(this, &Logic::OnServiceChangedInner);
_on_state_changed_inner = gcnew OnStateChangedDelegateInner(this, &Logic::OnStateChangedInner);
_on_service_info_readed_inner = gcnew OnServiceInfoReadedDelegateInner(this, &Logic::OnServiceInfoReadedInner);
_on_terminal_state_changed_inner = gcnew OnTerminalStateChangedDelegateInner(this, &Logic::OnTerminalStateChangedInner);
_on_show_counters_inner = gcnew OnShowCountersDelegateInner(this, &Logic::OnShowCountersInner);
}
LogicWrapper::Logic::~Logic()
{
delete _logic;
}
void LogicWrapper::Logic::SetDelegate(OnTimeAndMoneyChangedDelegate^ on_time_and_money_changed)
{
_on_time_and_money_changed = on_time_and_money_changed;
if (false == _tmc_handle.IsAllocated)
_tmc_handle = GCHandle::Alloc(_on_time_and_money_changed);
_logic->SetOnTimeAndMoneyFn(Marshal::GetFunctionPointerForDelegate(_on_time_and_money_changed).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnShowCountersDelegate^ on_show_counters)
{
_on_show_counters = on_show_counters;
if (false == _sco_handle.IsAllocated)
_sco_handle = GCHandle::Alloc(_on_show_counters_inner);
_logic->SetOnShowCountersFn(Marshal::GetFunctionPointerForDelegate(_on_show_counters_inner).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnTerminalStateChangedDelegate^ on_terminal_state_changed)
{
_on_terminal_state_changed = on_terminal_state_changed;
if (false == _tsc_handle.IsAllocated)
_tsc_handle = GCHandle::Alloc(_on_terminal_state_changed_inner);
_logic->SetOnTerminalStateChangedFn(Marshal::GetFunctionPointerForDelegate(_on_terminal_state_changed_inner).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnShowAdvertisingDelegate^ on_show_advertising)
{
_on_show_advertising = on_show_advertising;
if (false == _sa_handle.IsAllocated)
_sa_handle = GCHandle::Alloc(_on_show_advertising);
_logic->SetOnShowAdvertisingFn(Marshal::GetFunctionPointerForDelegate(_on_show_advertising).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnEmptyHopperDelegate^ on_empty_hopper)
{
_on_empty_hopper = on_empty_hopper;
if (false == _eh_handle.IsAllocated)
_eh_handle = GCHandle::Alloc(_on_empty_hopper);
_logic->SetOnEmptyHopperFn(Marshal::GetFunctionPointerForDelegate(_on_empty_hopper).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnDistributionPrizeDelegate^ on_distribution_prize)
{
_on_distribution_prize = on_distribution_prize;
if (false == _dp_handle.IsAllocated)
_dp_handle = GCHandle::Alloc(_on_distribution_prize);
_logic->SetOnDistributionPrizeFn(Marshal::GetFunctionPointerForDelegate(_on_distribution_prize).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnServiceInfoReadedDelegate^ on_service_info_readed)
{
_on_service_info_readed = on_service_info_readed;
if (false == _sir_handle.IsAllocated)
_sir_handle = GCHandle::Alloc(_on_service_info_readed_inner);
_logic->SetOnServiceInfoReadedFn(Marshal::GetFunctionPointerForDelegate(_on_service_info_readed_inner).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnCacheRefilledDelegate^ on_cache_refilled)
{
_on_cache_refilled = on_cache_refilled;
if (false == _cr_handle.IsAllocated)
_cr_handle = GCHandle::Alloc(_on_cache_refilled);
_logic->SetOnCacheRefilledFn(Marshal::GetFunctionPointerForDelegate(_on_cache_refilled).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnStateChangedDelegate^ on_state_changed)
{
_on_state_changed = on_state_changed;
if (false == _stc_handle.IsAllocated)
_stc_handle = GCHandle::Alloc(_on_state_changed_inner);
_logic->SetOnStateChangedFn(Marshal::GetFunctionPointerForDelegate(_on_state_changed_inner).ToPointer());
}
void LogicWrapper::Logic::SetDelegate(OnServiceChangedDelegate^ on_service_changed)
{
_on_service_changed = on_service_changed;
if (false == _sc_handle.IsAllocated)
_sc_handle = GCHandle::Alloc(_on_service_changed_inner);
_logic->SetOnServiceChangedFn(Marshal::GetFunctionPointerForDelegate(_on_service_changed_inner).ToPointer());
}
bool LogicWrapper::Logic::Start()
{
return _logic->Start();
}
void LogicWrapper::Logic::Stop()
{
_logic->Stop();
}
|
5ef533563ba0612abc1427aa608894e735be0463
|
811ff0c8389ad4aa5496872227324e6185c5bba1
|
/UIs/DesignScriptRunner/LiveRunnerWrapper.h
|
7bd5600bc818969f947bab3eaf9b46f461b7afc7
|
[
"Apache-2.0"
] |
permissive
|
DynamoDS/designscript-archive
|
2c2bb2182f6214a262a56d685168dc8a345616e0
|
2cfafd1299af0ffddacf77c41f51150556e88b80
|
refs/heads/master
| 2020-04-10T20:12:10.737867
| 2014-02-17T12:24:45
| 2014-02-17T12:24:45
| 11,632,510
| 4
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,061
|
h
|
LiveRunnerWrapper.h
|
#pragma once
#include "WrapperObject.h"
using namespace ProtoScript::Runners;
using namespace GraphToDSCompiler;
class LiveRunnerWrapper : public WrapperObject<LiveRunner, DesignScriptRunner>
{
public:
LiveRunnerWrapper(DesignScriptRunnerCallback* pCallback);
virtual ~LiveRunnerWrapper();
virtual void updateGraph(const wchar_t* codesegment);
virtual void importLibrary(const wchar_t* codesegment);
virtual void updateCLInterpreter(const wchar_t* codesegment);
virtual void updateGraphAsync(const wchar_t* codesegment);
virtual void updateCLInterpreterAsync(const wchar_t* codesegment);
virtual DesignScriptObject* queryNodeValue(const wchar_t* nodeName);
virtual void queryNodeValuesAsync(const std::list<unsigned int>& nodeIds);
virtual DesignScriptObject* getCoreDump();
virtual const wchar_t* getCoreDumpCmdLineREPL();
private:
SynchronizeData^ createSyncDataFromCode(System::String^ codesegment);
DesignScriptRunnerCallback* mpCallback;
unsigned int mNodeId;
};
|
05aa85ec30b6c9d318abfc8760455c6361cbaa29
|
366e2cdd40f6afef727cf24f71c70e555410fef5
|
/dev/pickers/dimensionbasedcenterspicker.h
|
0f2e082448901db13cb463b500c0940d0cf8dd97
|
[] |
no_license
|
benkopolis/kmeanstriangleclustering
|
20a1060040074dfd28125c8b87b2d387e6bf65f5
|
8714d70f1a3e6542d44cfe16e29ce97de64622ff
|
refs/heads/master
| 2020-12-24T13:17:10.643581
| 2017-03-22T20:31:07
| 2017-03-22T20:31:07
| 32,231,248
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,179
|
h
|
dimensionbasedcenterspicker.h
|
#ifndef DIMENSIONBASEDCENTERSPICKER_H
#define DIMENSIONBASEDCENTERSPICKER_H
#include <map>
#include <unordered_map>
#include <limits>
#include <set>
#include <utility>
#include <iostream>
#include "abstractcenterspicker.h"
#include "commons/abstractpoint.h"
#include "distances/manhattandistance.h"
#include "commons/pair_hash.h"
template <class PointType>
class DimensionBasedCentersPicker: public AbstractCentersPicker<PointType>
{
public:
DimensionBasedCentersPicker() { }
virtual ~DimensionBasedCentersPicker() {}
virtual PartitionData *performInitialPartition(unsigned clusters, AbstractPointsSpace* ps);
private:
std::multimap<unsigned, unsigned> _distanceToPoint;
std::unordered_map<unsigned, unsigned> _pointToDistance;
std::unordered_map<std::pair<unsigned, unsigned>, unsigned> _distances;
};
template <class PointType>
PartitionData *DimensionBasedCentersPicker<PointType>::performInitialPartition(unsigned clusters, AbstractPointsSpace *ps)
{
PartitionData* data = new PartitionData(clusters, ps->getDeclaredNumPoints());
this->initialData = new CentersData(clusters);
ManhattanDistance distance;
std::set<unsigned> distValues;
unsigned dist = 0, totalDist = 0, minDist = std::numeric_limits<unsigned>::max();
unsigned numPoints = ps->getNumOfInsertedPoints();
for(unsigned pid1 = 0; pid1 < numPoints - 1; ++pid1)
{
for(unsigned pid2 = pid1 + 1; pid2< numPoints; ++pid2)
{
dist = static_cast<unsigned>(distance.distance(ps->getPoint(pid1), ps->getPoint(pid2)) + 0.5);
if(distValues.count(dist) == 0)
distValues.insert(dist);
if(dist < minDist)
minDist = dist;
this->_distances.insert({{pid1, pid2}, dist});
totalDist = totalDist + dist;
}
unsigned reversedPid2 = pid1 - 1;
while(reversedPid2 >= 0 && reversedPid2 < pid1)
{
totalDist = totalDist + this->_distances[std::make_pair(reversedPid2, pid1)];
--reversedPid2;
} // now we are finished with total dist for this point
this->_distanceToPoint.insert({totalDist, pid1});
this->_pointToDistance.insert({pid1, totalDist});
totalDist = 0;
}
unsigned gensClusters = 0, currentPid = 0;
std::multimap<unsigned, unsigned>::iterator theTotal;
std::set<unsigned>::const_iterator currMinDist = distValues.cbegin();
std::cerr << "MinDist initial: " << *currMinDist << std::endl;
std::vector<unsigned> seeds;
std::pair<unsigned, unsigned> keyForDist;
unsigned loopCount = 0, innerLoop = 0;
while(data->assigned_points() < ps->getNumOfInsertedPoints())
{
theTotal = this->_distanceToPoint.begin();
if (theTotal != this->_distanceToPoint.end()
&& seeds.size() < clusters
&& !data->is_assigned(theTotal->second))
{
data->assign_unsafe(theTotal->second, gensClusters);
this->_pointToDistance.erase(theTotal->second);
currentPid = theTotal->second;
this->_distanceToPoint.erase(theTotal);
seeds.push_back(currentPid);
}
else
currentPid = seeds[gensClusters];
for(unsigned pid = 0; pid < numPoints; ++pid)
{
if (pid == currentPid || data->is_assigned(pid))
continue;
if (pid < currentPid)
keyForDist = std::make_pair(pid, currentPid);
else
keyForDist = std::make_pair(currentPid, pid);
dist = this->_distances[keyForDist];
if (dist <= *currMinDist)
{
data->assign_unsafe(pid, gensClusters);
totalDist = this->_pointToDistance[pid];
this->_pointToDistance.erase(pid);
this->_distanceToPoint.erase(totalDist);
}
++innerLoop;
}
++gensClusters;
++loopCount;
if(gensClusters == clusters)
{
gensClusters = 0;
++currMinDist;
}
}
return data;
}
#endif // DIMENSIONBASEDCENTERSPICKER_H
|
1e659bb093aa5d5271d832f466e17697d6470ab8
|
85d76011522140692ca5329547844c42fa857baf
|
/ReformMediaServer/PushServer.cpp
|
dd784cc28bc9e1408cef34c24bb8fad33a46df8f
|
[] |
no_license
|
curious-boy/RMS
|
67825e69cb622cfc861628512be08737e03704ce
|
0774891ad04d837ea654b656100fa847b59d572b
|
refs/heads/master
| 2020-12-28T20:55:27.002461
| 2015-05-09T08:23:49
| 2015-05-09T08:23:49
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 4,072
|
cpp
|
PushServer.cpp
|
#include "PushServer.h"
#include <process.h>
bool CPushServer::_isRun = false;
int CPushServer::_port;
SOCKET CPushServer::_bind_socket = INVALID_SOCKET;
fd_set CPushServer::_rfds;
hash_map<SOCKET, int> CPushServer::_ClientList;
hash_map<int, SOCKET> CPushServer::_ReadyList;
BOOL CPushServer::init(int port)
{
_port = port;
_bind_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(_bind_socket == INVALID_SOCKET)
{
//g_pLog->WriteLog("Init MediaServer Fail:%d\n", GetLastError());
return FALSE;
}
unsigned long ul = 1;
int nRet = ioctlsocket(_bind_socket, FIONBIO, (unsigned long *)&ul);
if(nRet == SOCKET_ERROR)
{
//g_pLog->WriteLog("rtspserv initialization failure(%d)!\n", GetLastError());
closesocket(_bind_socket);
_bind_socket = INVALID_SOCKET;
return FALSE;
}
struct sockaddr_in server_sockaddr; // 服务器的RTSP地址信息
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(port); // RTSP的端口
server_sockaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(_bind_socket,(struct sockaddr *)&server_sockaddr, sizeof(server_sockaddr)) == SOCKET_ERROR)
{
DWORD err = GetLastError();
closesocket(_bind_socket);
_bind_socket = INVALID_SOCKET;
//g_pLog->WriteLog("Init MediaServer Fail:bind[%d](%d)\n", port, err);
return FALSE;
}
if(listen(_bind_socket, 100) == SOCKET_ERROR)
{
//g_pLog->WriteLog("Init MediaServer Fail:listen(%d)\n", GetLastError());
closesocket(_bind_socket);
_bind_socket = INVALID_SOCKET;
return FALSE;
}
unsigned int theId = 0;
_beginthreadex( NULL, 0, _run, NULL, 0, &theId );
return FALSE;
}
unsigned int WINAPI CPushServer::_run(LPVOID inThread)
{
_isRun = true;
int ret = 0;
int err = 0;
while(_isRun)
{
setfds();
ret = select(_bind_socket+1, &_rfds, 0, 0, 0);
if( ret == SOCKET_ERROR)
{
DWORD err = GetLastError();
if(err == WSAENOTSOCK)
{
}
else
{
closesocket(_bind_socket);
_bind_socket = INVALID_SOCKET;
//g_pLog->WriteLog("RecvThread Exit:%d\n", GetLastError());
break;
}
}
else if(ret == 0)
continue;
//new connect
if(FD_ISSET(_bind_socket,&_rfds))
{
int s = accept(_bind_socket, 0, 0);
if(s == INVALID_SOCKET)
err = WSAGetLastError();
else
{
_ClientList[s] = -1;
}
}
else
{
//receive from client
for(hash_map<SOCKET, int>::iterator iter = _ClientList.begin();iter!=_ClientList.end();iter++)
{
SOCKET s = iter->first;
if(FD_ISSET(s,&_rfds))
{
if(iter->second == -1)
{
iter->second = 1;
//recv session
int session=0;
if(recvMSG(s, (char*)&session, sizeof(session)))
{
_ReadyList[session] = s;
}
else
{
closesocket(s);
_ClientList.erase(iter);
}
}
else
{
//recv and discard
char buf[1024]={'\0'};
if(recvMSG(s, buf, 1024) == -1)
{
closesocket(s);
_ClientList.erase(iter);
}
}
break;
}
}
}
}
_isRun = false;
return 0;
}
BOOL CPushServer::pushMSG(const int session, const char* buf, const int len)
{
hash_map<int, SOCKET>::iterator iter = _ReadyList.find(session);
if(iter != _ReadyList.end())
{
//send
if(send(iter->second, buf, len, 0) == len)
return TRUE;
else
return FALSE;
}
return FALSE;
}
void CPushServer::setfds()
{
FD_ZERO(&_rfds);
if(_bind_socket != INVALID_SOCKET)
FD_SET(_bind_socket, &_rfds);
for(hash_map<SOCKET, int>::iterator iter = _ClientList.begin();iter!=_ClientList.end();)
{
if(iter->first != INVALID_SOCKET)
{
FD_SET(iter->first, &_rfds);
iter++;
}
else
{
iter = _ClientList.erase(iter);
}
}
}
BOOL CPushServer::recvMSG(SOCKET s, char* buf, int buf_len)
{
if(buf_len == 0)
return TRUE;
int ret = recv(s, buf, buf_len, 0);
if(ret == buf_len)
return TRUE;
else if(ret <= 0)
return -1;
return FALSE;
}
BOOL CPushServer::isReady(const int session)
{
hash_map<int, SOCKET>::iterator iter = _ReadyList.find(session);
if(iter != _ReadyList.end())
{
return TRUE;
}
return FALSE;
}
|
d7384a35b2efe274359c1cfd805a20b454f42a95
|
0cce8934cf563b1ae12cfb1e1e610ca725c8cfe9
|
/competitive/ep4.cpp
|
e1dc518cfa5aaa75deee7a3e590ff23d533d746e
|
[] |
no_license
|
prayasjain/c-c-codes
|
a7695d394662e7f8dd3eb6fc35317271346a36b4
|
d02a964b452c93f69ae0d7d55b2efbd3a61a5c34
|
refs/heads/master
| 2022-11-24T01:32:36.704602
| 2020-07-23T18:51:15
| 2020-07-23T18:51:15
| 282,031,467
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 991
|
cpp
|
ep4.cpp
|
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <map>
#include <vector>
#include <stdlib.h>
#include <memory.h>
#include <time.h>
#include <string>
#include <algorithm>
#include <set>
#include <stack>
#include <cassert>
#include <queue>
#include <numeric>
#define slld(x) scanf("%lld",&x)
#define sd(x) scanf("%d",&x)
#define sld(x) scanf("%ld",&x)
#define ss(x) scanf("%s",x)
long long a[1000001] ;
long long fun(long long i , long long j , long long l){
long long t,s=0 ;
for(t=0;t<l;t++){
s=s+a[i+t]*a[j+l-1-t] ;
}
return s ;
}
int main(){
long long t ,n,x,y,z,i,j,k ,l,m,p,f ;
slld(n);
m=0 ;
f=0 ;
for(i=0;i<n;i++)
slld(a[i]);
for(l=1;l<=(n/2);l++){
for(i=0;i+l<=n;i++){
for(j=i+l;j+l<=n;j++){
x=fun(i,j,l) ;
if(f==0){
m=x;
f++;
}
if(x>m)
m=x ;
}
}
}
printf("%lld\n",m);
return 0 ;
}
|
df15f4c21065c5c4675e23665ba2370b5e5f5e5c
|
31d193b62e025a07aa36805d9459f5553ac4d783
|
/OMO_ADUINO_IDE/Point.cpp
|
1fd0ce4c6473ae416f2a409c72d5e1c6c8649026
|
[] |
no_license
|
omarelkawokgy/Area_Coverage
|
d76b600f8fcdc2214814eb0b9e7c1a764334f02a
|
9f2e1f588a9ca6fe51428bede22a2a9ef1ab0256
|
refs/heads/master
| 2021-07-06T12:45:29.700513
| 2018-04-16T15:28:19
| 2018-04-16T15:28:19
| 51,238,911
| 1
| 2
| null | 2016-02-07T18:47:00
| 2016-02-07T07:03:06
|
C++
|
UTF-8
|
C++
| false
| false
| 2,494
|
cpp
|
Point.cpp
|
#include "OBJD.h"
Point::Point()
{
ClasspointPos.X_Column = 0;
ClasspointPos.Y_Row = 0;
}
Point::Point(PointPos pointpos)
{
ClasspointPos.X_Column = pointpos.X_Column;
ClasspointPos.Y_Row = pointpos.Y_Row;
}
PointPos Point::getPointPos(void)
{
return ClasspointPos;
}
void Point::SetPosition(PointPos pos)
{
ClasspointPos.X_Column = pos.X_Column;
ClasspointPos.Y_Row = pos.Y_Row;
}
#ifdef DONE_IN_SCAN
return_type Point::CalPointPos(SensorID side, RobotPos robPos, uint16 distance)
{
return_type ret = RET_NOT_OK;
Heading heading = Comp::ReadComp();
if (heading != INVALID_DIRECTION)
{
switch (side)
{
case LEFT_SENSOR:
if (heading == NORTH)
{
ClasspointPos.X_Column = robPos.X_pos - distance;
ClasspointPos.Y_Row = robPos.Y_pos;
}
else if (heading == WEST)
{
ClasspointPos.X_Column = robPos.X_pos;
ClasspointPos.Y_Row = robPos.Y_pos + distance;
}
else if (heading == SOUTH)
{
ClasspointPos.X_Column = robPos.X_pos + distance;
ClasspointPos.Y_Row = robPos.Y_pos;
}
else if (heading == EAST)
{
ClasspointPos.X_Column = robPos.X_pos;
ClasspointPos.Y_Row = robPos.Y_pos - distance;
}
break;
case RIGHT_SENSOR:
if (heading == NORTH)
{
ClasspointPos.X_Column = robPos.X_pos + distance;
ClasspointPos.Y_Row = robPos.Y_pos;
}
else if (heading == WEST)
{
ClasspointPos.X_Column = robPos.X_pos;
ClasspointPos.Y_Row = robPos.Y_pos - distance;
}
else if (heading == SOUTH)
{
ClasspointPos.X_Column = robPos.X_pos - distance;
ClasspointPos.Y_Row = robPos.Y_pos;
}
else if (heading == EAST)
{
ClasspointPos.X_Column = robPos.X_pos;
ClasspointPos.Y_Row = robPos.Y_pos + distance;
}
break;
}
ret = RET_OK;
}
else
{
ret = RET_NOT_OK;
}
return ret;
}
#endif
/*filtering is done in ULSH itself taking many readings and finding the average*/
#if 1
/*filtering using average between the position of 2 points*/
PointPos Point::FilteredPointReading(PointPos* newPointPosList, const uint8 PointListSize)
{
PointPos filteredPointPos;
uint8 i;
filteredPointPos.X_Column = 0;
filteredPointPos.Y_Row = 0;
for(i = 0; i < PointListSize ; i++)
{
filteredPointPos.X_Column += newPointPosList[i].X_Column;
filteredPointPos.Y_Row += newPointPosList[i].Y_Row;
}
filteredPointPos.X_Column = filteredPointPos.X_Column / PointListSize;
filteredPointPos.Y_Row = filteredPointPos.Y_Row / PointListSize;
return filteredPointPos;
}
#endif
|
f03f97fc1062bc9f0c52843a905e1d9511a85c96
|
7c081d13d66b203b816ee94e0d736d10403a1b13
|
/llvm/include/llvm/ExecutionEngine/Orc/Layer.h
|
fc8c5ade1b1265349e15fd1e80495b26296f491b
|
[
"NCSA"
] |
permissive
|
jfourie1/llvm-project-20170507
|
84dcd723de76502d4d0f1f0a9df1a31bdc593f36
|
d8f895786c16a3b6a90eb9895ac786500bf5370c
|
refs/heads/master
| 2021-04-12T09:47:12.874041
| 2018-05-22T17:38:22
| 2018-05-22T17:38:22
| 126,182,492
| 0
| 0
| null | 2018-03-21T13:24:59
| 2018-03-21T13:24:58
| null |
UTF-8
|
C++
| false
| false
| 2,960
|
h
|
Layer.h
|
//===---------------- Layer.h -- Layer interfaces --------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Layer interfaces.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_EXECUTIONENGINE_ORC_LAYER_H
#define LLVM_EXECUTIONENGINE_ORC_LAYER_H
#include "llvm/ExecutionEngine/Orc/Core.h"
#include "llvm/IR/Module.h"
namespace llvm {
namespace orc {
class MangleAndInterner {
public:
MangleAndInterner(ExecutionSession &ES, const DataLayout &DL);
SymbolStringPtr operator()(StringRef Name);
private:
ExecutionSession &ES;
const DataLayout &DL;
};
/// Layer interface.
class IRLayer {
public:
IRLayer(ExecutionSession &ES);
virtual ~IRLayer();
ExecutionSession &getExecutionSession() { return ES; }
virtual Error add(VSO &V, VModuleKey K, std::unique_ptr<Module> M);
virtual void emit(MaterializationResponsibility R, VModuleKey K,
std::unique_ptr<Module> M) = 0;
private:
ExecutionSession &ES;
};
class IRMaterializationUnit : public MaterializationUnit {
public:
IRMaterializationUnit(ExecutionSession &ES, std::unique_ptr<Module> M);
protected:
std::unique_ptr<Module> M;
private:
void discard(const VSO &V, SymbolStringPtr Name) override;
std::map<SymbolStringPtr, GlobalValue *> Discardable;
};
class BasicIRLayerMaterializationUnit : public IRMaterializationUnit {
public:
BasicIRLayerMaterializationUnit(IRLayer &L, VModuleKey K,
std::unique_ptr<Module> M);
private:
void materialize(MaterializationResponsibility R) override;
IRLayer &L;
VModuleKey K;
};
class ObjectLayer {
public:
ObjectLayer(ExecutionSession &ES);
virtual ~ObjectLayer();
ExecutionSession &getExecutionSession() { return ES; }
virtual Error add(VSO &V, VModuleKey K, std::unique_ptr<MemoryBuffer> O);
virtual void emit(MaterializationResponsibility R, VModuleKey K,
std::unique_ptr<MemoryBuffer> O) = 0;
private:
ExecutionSession &ES;
};
/// The MemoryBuffer should represent a valid object file.
/// If there is any chance that the file is invalid it should be validated
/// prior to constructing a BasicObjectLayerMaterializationUnit.
class BasicObjectLayerMaterializationUnit : public MaterializationUnit {
public:
BasicObjectLayerMaterializationUnit(ObjectLayer &L, VModuleKey K,
std::unique_ptr<MemoryBuffer> O);
private:
void materialize(MaterializationResponsibility R) override;
void discard(const VSO &V, SymbolStringPtr Name) override;
ObjectLayer &L;
VModuleKey K;
std::unique_ptr<MemoryBuffer> O;
};
} // End namespace orc
} // End namespace llvm
#endif // LLVM_EXECUTIONENGINE_ORC_LAYER_H
|
15c7c472f073a8a12d1969516ca70b70a4466ddb
|
acb1fd7cb61bdd3abeadecd7d2855a8e7c0ccf8f
|
/rbc_stalker/rbc_stalker/stlkGroup.hpp
|
af826552b4e927063ace06d6727aae94a8d57470
|
[] |
no_license
|
Zealot111/SW_MissionExample
|
51a835e5300c5f8dec2b82f360917bf02c85ad71
|
d1b12972d2c9700b1ea1c4f583a94252e241c9ab
|
refs/heads/master
| 2021-01-10T14:42:55.915456
| 2015-12-06T18:23:57
| 2015-12-06T18:23:57
| 44,381,228
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 751
|
hpp
|
stlkGroup.hpp
|
class SW_Stalkers {
name = "Сталкеры";
class Infantry {
name = "Пехота";
class SW_Stalkers_team {
name = "Группа сталкеров";
faction = "SW_Stalkers";
side = 2;
aliveCategory = "Infantry";
class Unit0 {
side = 2;
vehicle = "SW_Stalker_Loner_Leader_F";
rank = "Corporal";
position[] = {0,0,0};
};
class Unit1 {
side = 2;
vehicle = "SW_Stalker_Loner_F";
rank = "Private";
position[] = {1,0,0};
};
class Unit2 {
side = 2;
vehicle = "SW_Stalker_Loner_F";
rank = "Private";
position[] = {2,0,0};
};
class Unit3 {
side = 2;
vehicle = "SW_Stalker_Loner_F";
rank = "Private";
position[] = {3,0,0};
};
};
};
};
|
35f0d34c4f29425f8d06eb805242ec6b2efccd81
|
3fad5a40d5f24e177f73cb0d9fef8252679c3447
|
/TapeEquilibrium.cpp
|
6070d8efdb761778324188ee27693ec121a4dbda
|
[] |
no_license
|
tpyda/codility
|
180056dfab30c09982924a12cdda6e69daf540a1
|
bb7b68042cbe0105addcb60bd791afd3af582c04
|
refs/heads/master
| 2020-12-31T04:41:45.482809
| 2016-02-02T00:52:28
| 2016-02-02T00:52:28
| 50,883,022
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,114
|
cpp
|
TapeEquilibrium.cpp
|
// you can use includes, for example:
// #include <algorithm>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
#include <gtest/gtest.h>
using namespace std;
#include <limits>
int solution(vector<int> &A) {
// write your code in C++11 (g++ 4.8.2)
int sumr = 0;
int suml = 0;
for (auto it = A.begin(); it < A.end(); ++it )
{
sumr += *it;
}
int diff = numeric_limits<int>::max();
for (auto it = A.begin(); it < A.end()-1; ++it)
{
suml+=*it;
sumr-=*it;
//cout << *it << " " << suml << " " << sumr << " " << suml - sumr << " " << it - A.begin() << endl;
if (abs(suml - sumr) < diff)
{
diff = abs(suml - sumr);
}
}
return diff;
}
TEST (test,test) {
vector<int> v = {3,1,2,4,3};
vector<int> v2 = {6,10};
vector<int> v3 = {-1000,1000};
vector<int> v4 = {2000,0};
EXPECT_EQ(1,solution(v));
EXPECT_EQ(4,solution(v2));
EXPECT_EQ(2000,solution(v3));
EXPECT_EQ(2000,solution(v4));
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
9d5b88a23978454ecda64c6fc8470457d3a4e80d
|
e993fb1a77cf8df900e5da3c2062d5e3047d1940
|
/Effective_Modern_Cpp/Item17-autogen_member_functions/default.cc
|
6beb9c3eb34d99fcd8476e42983778b9f91cc848
|
[] |
no_license
|
activeion/Books_SourceCode
|
2dba4e8d988106a902fc4bb7c084bda0c1a42ea3
|
7c6c23d4c22aa0ad3c8f01b0bba962527bdc599e
|
refs/heads/master
| 2021-07-23T14:47:35.489523
| 2021-02-23T12:16:12
| 2021-02-23T12:16:12
| 100,842,985
| 19
| 11
| null | 2021-02-26T02:13:43
| 2017-08-20T06:28:48
|
C++
|
UTF-8
|
C++
| false
| false
| 3,122
|
cc
|
default.cc
|
#include <cstdlib>
#include <cstdio>
class MemberClass
{
public:
MemberClass()
{
x_=0;
y_=0; printf("MemberClass: Constructor be called!\n");
}
~MemberClass(){}
MemberClass(const MemberClass& mc)
{
x_=mc.x_;
y_=mc.y_;
printf("MemberClass: Copy Constructor called!//因为写在了Test(拷贝)构造函数的初始化列表里\n");
}
const MemberClass& operator=(const MemberClass& right)
{
x_=right.x_;
y_=right.y_;
printf("MemberClass: Operator = be called! //因为写在了Test(拷贝)构造函数的函数体里\n");
return *this;
}
private:
int x_,y_;
};
class Test
{
public:
Test()
{
printf("Test: Constructor be called!\n");
}
explicit Test(const MemberClass& mc)
{
mc_=mc;
}
~Test()
{
}
Test(const Test& test):mc_(test.mc_)
{
mc_=test.mc_;
printf("Test: Copy Constructor be called!\n");
}
const Test & operator=(const Test& right)
{
mc_=right.mc_;
printf("Test: Operator= be called!\n");
return *this;
}
private:
MemberClass mc_;
};
int main()
{
printf("1、Test中包含一个MemberClass,这两个类分别具有构造函数、\n 拷贝构造函数、重载operator=。\n\n");
printf("2、在调用Test的构造函数和拷贝构造函数之前,会根据跟在\n 这些函数后的初始化列表去初始化其\n MemberClass变量(调用MemberClass的拷贝构造函数去初始化)\n\n");
printf("3、一旦进入Test的构造函数体或拷贝构造函数体,则说明其成员变量MemberClass已\n 经通过MemberClass的构造函数或MemberClass的拷贝构造函数构造出了对象\n");
printf(" 所以,在Test的构造函数体或拷贝构造函数体中,再去使用=号\n 给MemberClass的时候,调用的就是MemberClass的operator=,\n 而不是MemberClass的拷贝构造函数了\n");
printf(" 这就是Test构造函数后面 “:” 初始化列表的存在意义!(\n 为了调用成员变量的构造函数或者拷贝构造函数)\n\n");
printf("4、最后!揪出让人困惑的终极原因!!!!!\n Test test2=test1和Test test2(test1)这两种是TM一模一样的\n (都调用拷贝构造函数)!!!!除了这点儿之外,其他地方都是该是什么是什么(\"()\"调用构造函数,\"=\"调用赋值操作符)!!!\n\n");
printf("5、一个对象初始化完毕后,所有对这个对象的赋值都调用operator=\n\n输出如下:");
printf("Test test1; DO:\n");
Test test1;
printf("\n");
printf("Test test2=test1; DO:\n");
Test test2=test1;
printf("\n");
printf("Test test3(test2); DO:\n");
Test test3(test2);
printf("\n");
printf("test3=test1; DO:\n");
test3=test1;
return 0;
}
|
dc328d353a4014eb46cc31cf23fe64e9f8ab72a7
|
95adecbd4b7e019132c7d0157bc78e4d5e3fdce4
|
/Classes/BasePage.h
|
30b08f599b26aec7dadb3f0cded402438ecfeb79
|
[] |
no_license
|
onvia/cocos-custom-framework
|
11809a6fac21cdcb3ff1efc0d76e7b345d30cfcb
|
ae28c3a0062ae06ef1dc562e630fcd7e7afb7efd
|
refs/heads/master
| 2021-09-21T18:14:56.044037
| 2018-08-30T09:16:55
| 2018-08-30T09:16:55
| 96,005,185
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 890
|
h
|
BasePage.h
|
#ifndef __BasePage_H__
#define __BasePage_H__
#include "PublicCoco.h"
#include "Finder.h"
class BaseDialog;
class BasePage : public Layout, public FinderAdapter
{
public:
BasePage();
~BasePage();
static BasePage* create(const std::string& filename);
static BasePage* create(Node* node);
virtual bool init(const std::string& filename);
virtual bool init(Node* node);
virtual void runTimeLineAction(Action* action);
virtual Node* getChildByPath(const std::string& path);
template<typename T> T getChildByPath(const std::string& name)
{
return dynamic_cast<T>(getChildByPath(name));
}
virtual Node* getRoot();
virtual std::string getRootName();
virtual bool onKeyBack();
public:
protected:
virtual void initAdapter();
virtual void registerEvent();
protected:
Node* _pRoot = nullptr;
std::string _sRootFileName;
};
#endif /* defined(__BasePage_H__) */
|
1f7b2725b329f03045cb5d6a98642f5887e91a49
|
b93288a88bafe8e178386ebfee7a79c0f817a05d
|
/STL containers/stl.stack.cpp
|
d0ca98cd33b4b2cb9a2f9cdab2c11adcef9c38c9
|
[] |
no_license
|
AshutoshLembhe/Object-Oriented-Programming-in-CPP
|
96e776b51b7a3b68cda3d53dfcdf6cab8a5237d1
|
75de6dc1f2211eaddfea928f8fbb69efeb8eafe2
|
refs/heads/master
| 2022-11-21T03:31:42.169028
| 2020-07-28T09:54:03
| 2020-07-28T09:54:03
| 262,872,099
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 250
|
cpp
|
stl.stack.cpp
|
#include<iostream>
using namespace std;
int main()
{
stack<int> st;
st.push_back(1);
st.push_back(2);
st.push_back(3);
st.push_back(4);
cout<<st.top()<<endl;
st.pop();
cout<<st.top<<endl;
st.pop();
cout<<st.size()<<endl;
}
|
a9f2d6780b37809cf5e694bc898e484600ec9fb9
|
7729d3ad5795abbf6b57cae04249e5e99f6b3b09
|
/tcp/TcpFram/main.cpp
|
a53d4966f6ef9fa256729814c7786887717a5d2f
|
[] |
no_license
|
ban771349788/Qt-demo
|
d5878d6f034294d365f6ae19d349f21bcc505ade
|
b429edcd012d5ab301b942d4eb2a98a4ac8d377f
|
refs/heads/main
| 2023-02-01T18:24:23.818992
| 2020-12-08T08:02:21
| 2020-12-08T08:02:21
| 319,493,264
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 264
|
cpp
|
main.cpp
|
#include "tcpwidget.h"
#include "socketform.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TcpWidget w;
w.show();
SocketForm w2;
w2.show();
SocketForm w3;
w3.show();
return a.exec();
}
|
6d9c39a5c557d629fc3f144b7a65ee1bb2549bcd
|
46c417bd246c9802d071a86a7f2147d6c111ae74
|
/l_multicast.cpp
|
67b433aaec60014c895ec204ad9a1b116614f508
|
[] |
no_license
|
linuslin/CPP_Thread
|
3187a50d4c23e9e0d7d86f3b4a6c8466fc4dd74c
|
8cd2d710bdcaedbada98bedcb394d718e333e00c
|
refs/heads/master
| 2021-01-22T20:49:13.064780
| 2017-04-26T23:46:54
| 2017-04-26T23:46:54
| 85,362,393
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,190
|
cpp
|
l_multicast.cpp
|
#include "l_multicast.h"
#include "l_multicast_util.h"
#include <string>
#include <iostream>
//tmp
#include "bmpheader.h"
//
L_Multicast::L_Multicast(L_M_Queue<L_Message*>& queue,std::string name,char * group, int port):m_queue(queue),m_name(name),m_group(group),m_port(port){}
void L_Multicast::setupConnection(char * group, const int port){
this->m_group=group;
this->m_port=port;
}
int L_Multicast::start()
{
std::string errorMsg;
int result=0;
if((result=L_Multicast_Util::connect(this->m_fd,this->m_group,this->m_port,this->m_addr,errorMsg))<0){
std::cout<<"setup connection failed\n";
return -1;
}else{
return this->L_Thread::start();
}
}
void* L_Multicast::run(){
int result;
ssize_t nbyte;
int size = BUFFERSIZE;
unsigned char msgbuf[size];
L_Message * msg;
while(1){ // need to add condition var
memset(msgbuf, 0, sizeof(msgbuf));
if((nbyte=L_Multicast_Util::receive(this->m_fd,msgbuf,size,this->m_addr))<0){
//std::cerr<<"receive failed"<<std::endl;
}else{
msg = new L_Message(msgbuf,size);
this->m_queue.add(msg);
}
}
}
|
78e0de7431e945d9c2d16916fa57e3ea7ef44685
|
f46c34e9632aa3b3234d0bfa725fa954dcf553ad
|
/scratch.cpp
|
0fe9129d50fd1de053002670d96c46e5f538d002
|
[] |
no_license
|
BYUCS235/BST-Lab
|
45eb49efcb1a8c2ce0464dea47b92dadcde6961e
|
856de3772760077cd327e9a0023b7aa4ce359cf8
|
refs/heads/master
| 2023-04-07T01:18:54.682135
| 2023-03-16T17:59:17
| 2023-03-16T17:59:17
| 115,233,418
| 0
| 18
| null | 2023-03-15T16:44:29
| 2017-12-24T01:55:08
|
C++
|
UTF-8
|
C++
| false
| false
| 416
|
cpp
|
scratch.cpp
|
#include <iostream>
#include "BST.h"
#include "printing.h"
int main(int argc, char *argv[]) {
// Write your test code here. Remember that `printing.h` gives you access to
// the functions `pretty_print_tree` and `ugly_print_tree`, which you can
// use to print a representation of your tree like so:
BST tree;
pretty_print_tree(tree);
ugly_print_tree(tree);
return 0;
}
|
ccb8ad189909b148519ab5d31b1e87fb813d0a2e
|
69047ea11b9fa5e72328c0ba96e3044b270309dc
|
/jni/SDL2/build/org.libsdl.arkanoid/jni/src/scoresysytem.cpp
|
312feed162dcfc5adbc4881183c6f7d4ffe9cd03
|
[
"Zlib"
] |
permissive
|
dixtel/arakanoid_android
|
bb22740f4700ea179af4500e10edcc5a1124eed0
|
e38486f51d7e2258a2e66cb2e4fd26eed8da9517
|
refs/heads/master
| 2021-01-15T08:53:21.984846
| 2017-08-12T13:04:19
| 2017-08-12T13:04:19
| 99,568,902
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,939
|
cpp
|
scoresysytem.cpp
|
#include "include/scoresysytem.h"
int ToInt(std::string str) {
int num;
std::istringstream stream(str);
stream >> num;
return num;
}
ScoreSystem::ScoreSystem() {
bestScore = 0;
currentScore = 0;
}
ScoreSystem::~ScoreSystem() {
if (!SaveBestScore()) {
std::cout << "Error: Cannot save bestscore (ScoreSystem)" << std::endl;
}
}
void ScoreSystem::IncreaseCurrentScore(BrickType type) {
if (type == type1) {
currentScore += 1;
}
else if (type == type2) {
currentScore += 2;
}
else if (type == type3) {
currentScore += 3;
}
if (currentScore > bestScore) {
bestScore = currentScore;
}
}
bool ScoreSystem::LoadBestScore() {
std::fstream file;
file.open(pathToScoreFile.c_str(), std::fstream::in);
if (!file.is_open()) {
return false;
}
std::string line;
while (std::getline(file, line)) {
if (line.find("bestscore:") != std::string::npos) {
std::string score = line.substr((line.find("bestscore:") + 10), line.size() - 10);
bestScore = ToInt(score);
return true;
}
}
return false;
}
bool ScoreSystem::SaveBestScore() {
std::remove(pathToScoreFile.c_str());
std::ofstream file(pathToScoreFile.c_str());
file << "bestscore:" + std::to_string(bestScore);
return true;
}
bool ScoreSystem::Init(std::string pathToScoreFile) {
this->pathToScoreFile = pathToScoreFile;
if (!LoadBestScore()) {
return false;
}
return true;
}
void ScoreSystem::ResetCurrentScore() {
currentScore = 0;
}
void ScoreSystem::Save() {
if (!SaveBestScore()) {
std::cout << "Error: Cannot save bestscore (ScoreSystem)" << std::endl;
}
}
unsigned ScoreSystem::GetBestScore() {
return bestScore;
}
unsigned ScoreSystem::GetCurrentScore() {
return currentScore;
}
|
14e822dc3953ac965771100c188d7783411961fa
|
65ce464a6361d2d4096ee8d0d97bca76c8025a5e
|
/P3_Networked_Spell_Checker/client/src/Client.cpp
|
e18559cd87145f711fb3652a597b397dca28527f
|
[] |
no_license
|
tuh37046/CIS3207
|
857a7aa85ab62cba75481bb31b951e3862799d0c
|
e98219c47930eae59dc7775ae1ef81dd89087752
|
refs/heads/master
| 2020-07-20T08:45:02.680671
| 2019-12-09T05:46:30
| 2019-12-09T05:46:30
| 206,610,915
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,525
|
cpp
|
Client.cpp
|
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#include <netdb.h>
#include <random>
#include <chrono>
#include <thread>
#include <queue>
#include <vector>
#include <pthread.h>
#include <mutex>
#include <fstream>
#define NUM_CLIENTS 5
#define WORDS_MAX 100
void clear_client_log() {
std::ofstream log("client.log");
log << "";
log.close();
}
void write_log(const std::string &s) {
std::ofstream log("client.log",std::ios_base::app);
if(!log.is_open()) {
std::cerr << "ERROR writing to logfile" << std::endl;
return;
} else {
log << s;
log.close();
}
}
pthread_t client_spool[NUM_CLIENTS];
int connections[NUM_CLIENTS];
std::queue<std::string> client_log_queue;
pthread_mutex_t clientLock;
pthread_cond_t clientLogFill;
pthread_cond_t clientLogEmpty;
std::vector<std::string> client_dict;
void init_client_dictionary(const std::string& filename) {
std::ifstream words(filename);
std::string newWord;
while(std::getline(words,newWord)) {
client_dict.push_back(newWord);
}
}
void push_client_log_queue(const std::string &line) {
pthread_mutex_lock(&clientLock);
client_log_queue.push(line);
pthread_cond_signal(&clientLogFill);
pthread_mutex_unlock(&clientLock);
}
int new_connection() {
int socket_desc = socket(AF_INET, SOCK_STREAM,0);
struct addrinfo server_info, *res;
int socket_fd;
memset(&server_info, 0, sizeof server_info);
server_info.ai_family = AF_UNSPEC;
server_info.ai_socktype = SOCK_STREAM;
getaddrinfo("127.0.0.1", "8888", &server_info, &res);
socket_fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(connect(socket_fd, res->ai_addr, res->ai_addrlen) < 0) {
std::cout << "Connection error, exiting" << std::endl;
exit(0);
}
return socket_fd;
}
void client_routine(int socket_fd) {
int wordcount = random()%WORDS_MAX;
push_client_log_queue("Starting client with wordcount "+std::to_string(wordcount)+"...\n");
if(socket_fd == -1) {
std::cout << "Connection error, exiting" << std::endl;
exit(0);
}
char* word;
char buffer[1024] = {0};
std::string logstr = "";
for(int i=0;i<wordcount;i++) {
word = (client_dict.at(random()%client_dict.size())+"\n").c_str();
if(send(socket_fd,word,strlen(word),0) < 0) std::cout << "ERROR" << std::endl;
//defunct
/*if(read(socket_fd,buffer,1024) <= 0) {
push_client_log_queue("Client "+std::to_string(socket_fd)+": Server disconnected");
pthread_cond_signal(&clientLogFill);
close(socket_fd);
return;
} else {
std::string reply(buffer);
if(reply.find("SERV") == std::string::npos) {
*/
std::string w(word);
logstr = "Client "+std::to_string(socket_fd)+": "+w;
/*
} else {
continue;
}
}
*/
push_client_log_queue(logstr);
pthread_mutex_lock(&clientLock);
pthread_cond_signal(&clientLogFill);
pthread_mutex_unlock(&clientLock);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
//close connection remotely
word = "0\n";
if(send(socket_fd,word,strlen(word),0) < 0) std::cout << "ERROR" << std::endl;
return;
}
void client_log_thread_routine() {
std::string line = "";
while(1) {
pthread_mutex_lock(&clientLock);
while(client_log_queue.empty()) {
pthread_cond_wait(&clientLogFill,&clientLock);
}
line = client_log_queue.front();
client_log_queue.pop();
pthread_mutex_unlock(&clientLock);
write_log(line);
}
}
void spawn_threads() {
//log thread
for(int i=0;i<NUM_CLIENTS;i++) {
connections[i] = new_connection();
std::this_thread::sleep_for(std::chrono::milliseconds(300));
}
pthread_t logThread;
if(pthread_create(&logThread,NULL,client_log_thread_routine,NULL) != 0) {
std::cout << "Failed to create thread" << std::endl;
exit(0);
}
for(int i=0;i<NUM_CLIENTS;i++) {
if(pthread_create(&client_spool[i],NULL,client_routine,connections[i]) != 0) {
std::cout << "Failed to create thread" << std::endl;
exit(0);
}
}
}
int main(int argc, char** argv) {
srand(time(NULL));
std::cout << "Simulating " << NUM_CLIENTS << " clients..." << std::endl;
clear_client_log();
init_client_dictionary("words.txt");
spawn_threads();
for(int i=0;i<NUM_CLIENTS;i++) {
pthread_join(client_spool[i],NULL);
std::cout << "Client " << i+1 << " finished" << std::endl;
}
push_client_log_queue("Clients finished\n");
return 0;
}
|
d1e10f6c1bbc165f4f8d22a2db03f01e52d74c9c
|
3e644fa536a60c449ed44c674ec437c10d4e74bf
|
/KristalliProtocolModule/KristalliProtocolModuleEvents.h
|
e5e757a7524068aa3074737ef2d6571dd66786a2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
jarmovh/naali
|
3a29a2baff715637a0986ed56d3f6e433772f9e2
|
bcbd92499cdbb6e891774a4694a150bf06499e22
|
refs/heads/master
| 2021-01-09T05:40:50.550403
| 2011-08-12T05:42:22
| 2011-08-12T05:42:22
| 1,462,841
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,354
|
h
|
KristalliProtocolModuleEvents.h
|
// For conditions of distribution and use, see copyright notice in license.txt
#pragma once
#include "IEventData.h"
namespace kNet
{
class MessageConnection;
typedef unsigned long message_id_t;
}
namespace KristalliProtocol
{
namespace Events
{
// This event is posted whenever a new inbound network message is received from a Kristalli peer. KristalliNetMessageIn structure.
static const event_id_t NETMESSAGE_IN = 1;
// This event is posted for a new user connection to a server. KristalliUserConnected structure.
static const event_id_t USER_CONNECTED = 2;
// This event is posted for a new user connection to a server. KristalliUserDisconnected structure.
static const event_id_t USER_DISCONNECTED = 3;
// This event is posted when a connection attempt has failed so many times that we stop trying. No eventdata.
static const event_id_t CONNECTION_FAILED = 4;
// The message received from a Kristalli server is wrapped in this Naali event structure.
class KristalliNetMessageIn : public IEventData
{
public:
KristalliNetMessageIn(kNet::MessageConnection *source_, kNet::message_id_t id_, const char *data_, size_t numBytes_)
:source(source_), id(id_), data(data_), numBytes(numBytes_)
{
}
kNet::MessageConnection *source;
kNet::message_id_t id;
const char *data;
size_t numBytes;
};
// Event structure for user connected
class KristalliUserConnected : public IEventData
{
public:
KristalliUserConnected(UserConnection *connection_) :
connection(connection_)
{
}
UserConnection *connection;
};
// Event structure for user connected
class KristalliUserDisconnected : public IEventData
{
public:
KristalliUserDisconnected(UserConnection *connection_) :
connection(connection_)
{
}
UserConnection *connection;
};
// Event structure for failed connection
class KristalliConnectionFailed : public IEventData
{
public:
KristalliConnectionFailed(unsigned short con) :
removedConnection_(con)
{
}
unsigned short removedConnection_;
};
} // ~Events namespace
} // ~KristalliProtocolModule namespace
|
8d3ae173b2405367ec074b73e0fcbd8dca5fa680
|
ceca10c49f709958535004770d1688f0ee04988a
|
/NRPS library/lib/nrpsdesigner/domains/domaintypet.cpp
|
1839cebeff749a5ade68fca237f0535d8fb57e71
|
[] |
no_license
|
igemsoftware/Heidelberg_2013
|
13c20de982b51606367ee69f1ba71e957e2dfb87
|
85e4966d7ebf04173ae3db8d72f5b122d9a2475e
|
refs/heads/master
| 2020-04-04T09:00:38.005070
| 2013-10-28T15:26:45
| 2013-10-28T15:26:45
| 12,770,105
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 673
|
cpp
|
domaintypet.cpp
|
#include "domaintypet.h"
#define POSITION_NODE "position"
using namespace nrps;
DomainTypeT::DomainTypeT(uint32_t id)
: Domain(DomainType::T, id)
{}
DomainTypeT::DomainTypeT(uint32_t id, DomainTPosition pos)
: Domain(DomainType::T, id), m_position(pos)
{}
DomainTypeT::~DomainTypeT()
{}
DomainTPosition DomainTypeT::position() const
{
return m_position;
}
void DomainTypeT::setPosition(DomainTPosition p)
{
m_position = p;
}
#ifdef WITH_INTERNAL_XML
void DomainTypeT::writeXml(xmlTextWriterPtr writer) const
{
Domain::writeXml(writer);
xmlTextWriterWriteElement(writer, BAD_CAST POSITION_NODE, BAD_CAST nrps::toString(position()).c_str());
}
#endif
|
dccff626bc5ea94ff00c5e550888136ce80389ea
|
89681bd752c14344221da488724f422ee3cca516
|
/PA2/hull/hull_new.cpp
|
6d8c6c30db0710b92908aa66e84cc046e3dfecca
|
[] |
no_license
|
lyh983012/DSA2018-THU
|
81ff1e8e045baf23ec0b9c0db5a5664583f94a2f
|
48cd7add71a16b9da93f566dfceca855e873161a
|
refs/heads/master
| 2020-04-02T13:35:16.483141
| 2018-12-19T13:25:12
| 2018-12-19T13:25:12
| 154,487,507
| 0
| 2
| null | 2020-04-18T12:49:55
| 2018-10-24T11:12:20
|
C++
|
UTF-8
|
C++
| false
| false
| 3,219
|
cpp
|
hull_new.cpp
|
#include<iostream>
using namespace std;
#define pass(x1,y4,x2,y2,x3,y3) (((x2)-(x1))*((y3)-(y2))-((x3)-(x2))*((y2)-(y4))>(0) || ((x1)==(x3) && (y3)==(y4)) )
int main(){
/*
测试自己的二进制数据文件
int testData[]={11,1,6,1,0,4,11,5,5,7,11,7,0,7,7,8,1,8,12,9,3,10,6};
FILE* fp = fopen("test.in", "wb");
for(int i=0;i<25;i++){
fwrite(&testData[i], sizeof(int), 1, fp);
}
fclose(fp);
FILE* fp1 = fopen("test.in", "rb");
int n;
//fread(&n,sizeof(int) , 1, stdin);
fread(&n,sizeof(int) , 1, fp1);
int testData[]={11,1,0,1,6,4,11,5,5,7,11,7,0,7,7,8,1,8,12,9,3,10,6};
int n=testData[0];
*/
//读入二进制数据
int n;
fread(&n,sizeof(int) , 1, stdin);
int *X=new int [n];
int *Y=new int [n];
for (int i=0;i<n;i++)//先读xy坐标值
{
fread(&X[i], sizeof(int), 1, stdin);
fread(&Y[i], sizeof(int), 1, stdin);
}
///
long*L =new long[n]; //对应每个坐标x中y的最小值
long*H =new long[n]; //对应每个坐标x中y的最大值
long*X0 =new long[n]; //对应“出现过的x”
long temp=0;
long temp1=0;
long ymin=Y[0];
long ymax=Y[0];
////////////////////////////////////////////////////////////
//找出点集的一个密的边界:由每个x的最高/最低点构成
for(int i=1;i<n;i++){
if( X[i]==X[i-1]){
if(ymax<Y[i])
ymax=Y[i];
if(ymin>Y[i])
ymin=Y[i];
if(i==(n-1)){
L[temp]=ymin;
H[temp1]=ymax;
X0[temp]=X[i];
temp++;
if(ymax!=ymin)
temp1++;
break;
}
}else{
L[temp]=ymin;
H[temp1]=ymax;
X0[temp]=X[i-1];
temp++;
temp1++;
ymin=Y[i];
ymax=Y[i];
if(i==(n-1)){
L[temp]=ymin;
X0[temp]=X[i];
temp++;
break;
}}}
////////////////////////////////////////////////////////////////
//把点集从x,y都最小的点开始,逆时针排列成一个环,存在一个数组中(将H反向和L拼接,
//并且最后一个点和第一个点相同
)
for(int i=0;i<temp1;i++){
L[temp+i]=H[temp1-i-1];
X0[temp+i]=X0[temp1-i-1];
}
long len=temp+temp1+1;//
if((H[0]==L[0]))
{
len--;
}else{
X0[len-1]=X0[0];
L[len-1]=L[0];
}
////////////////////////////////////////////////////////////
//用一个栈存储凸包点,相邻三个点判断是否在凸包上,破坏凸性质则放弃中间点,再次检查
long* zhan=new long[len];
zhan[0]=0,zhan[1]=1;
long head=2;
long lenth=2;
while(head!=len){
if(pass(X0[zhan[lenth-2]],L[zhan[lenth-2]],X0[zhan[lenth-1]],L[zhan[lenth-1]],X0[head],L[head])){
lenth++;
zhan[lenth-1]=head;
head++;
}else{
zhan[lenth-1]=head;
head++;
while(lenth>=3 && !pass(X0[zhan[lenth-3]],L[zhan[lenth-3]],X0[zhan[lenth-2]],L[zhan[lenth-2]],X0[zhan[lenth-1]],L[zhan[lenth-1]])){
zhan[lenth-2]=zhan[lenth-1];
lenth--;
}
}
}
/////////////////////////////////////////////////
//找出题目要求的点,进行逆时针输出
ymin=L[0];
long xmin=X0[0];
long count=0;
for(int i=0;i<lenth-1;i++){
if(L[zhan[i]]<ymin){
ymin=L[zhan[i]];
xmin=X[zhan[i]];
count=i;
}else if(L[zhan[i]]==ymin && xmin>X[zhan[i]]){
xmin=X[zhan[i]];
count=i;
}
}
for(int i=count;i<lenth-1;i++){
printf("%d %d\n",X0[zhan[i]],L[zhan[i]]);
}
for(int i=0;i<count;i++){
printf("%d %d\n",X0[zhan[i]],L[zhan[i]]);
}
return 0;
}
|
87b0316e11612478b400ea2591db5c175dc52f7c
|
1a69b230bf59c4cc6cf604dfe8153fb5d179eb81
|
/entrenos/rohspc2/B.cpp
|
6e9401ca04c29249b9e94c47c28ae1ab8d19e7ae
|
[] |
no_license
|
FelixMorenoPenarrubia/CompetitiveProgramming
|
36de722b5512ba975d9db9e939df2f155092d276
|
d459ce5683ad464c34b3a8d0bc0b77557ccfdc24
|
refs/heads/master
| 2023-03-14T13:35:43.938876
| 2021-03-04T17:01:36
| 2021-03-04T17:01:36
| 344,264,136
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,814
|
cpp
|
B.cpp
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef vector<ll> vi;
ld K= 1.3492;
struct point {
ld x, y;
point() {
}
point(ld _x, ld _y) {
x = _x;
y = _y;
}
};
point operator-(point a, point b) {
return point(a.x-b.x, a.y-b.y);
}
ld operator^(point a, point b) {
return a.x*b.y-a.y*b.x;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int T;
cin >> T;
while(T--) {
point a1;
point a2;
point b1;
point b2;
point v;
cin >> a1.x >> a1.y >> a2.x >> a2.y >> b1.x >> b1.y >> b2.x >> b2.y >> v.x >> v.y;
a1.x = K*a1.x+a1.y;
a2.x = K*a2.x+a2.y;
b1.x = K*b1.x+b1.y;
b2.x = K*b2.x+b2.y;
v.x = K*v.x+v.y;
a2 = a2-a1;
b1 = b1-a1;
b2 = b2-a1;
ld det = v.x*a2.y-v.y*a2.x;
if(det == 0) {
b1.y -= b1.x * (v.y/v.x);
b2.y -= b2.x * (v.y/v.x);
if(b1.y < 0) {
if(b2.y < 0) {
cout << "No" << endl;
}
else {
ld xc = ((b2.y*b2.x)-(b1.y*b1.x))/(b2.y-b1.y);
if(xc*v.x >= 0) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
}
else if(b2.y < 0) {
ld xc = ((b1.y*b1.x)-(b2.y*b2.x))/(b1.y-b2.y);
if(xc*v.x >= 0) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
else {
cout << "No" << endl;
}
continue;
}
ld a = -(v.y)/det;
ld b = v.x/det;
ld c = a2.y/det;
ld d = (-a2.x)/det;
v = point(a*v.x+b*v.y, c*v.x+d*v.y);
a2 = point(a*a2.x+b*a2.y, c*a2.x+d*a2.y);
// cerr << a2.x << " " << a2.y << " " << v.x << " " << v.y << endl;
b1 = point(a*b1.x+b*b1.y, c*b1.x+d*b1.y);
b2 = point(a*b2.x+b*b2.y, c*b2.x+d*b2.y);
if(b1.y < 0) {
if(b2.y < 0) {
cout << "No" << endl;
continue;
}
else {
b1 = point((-b1.y*b1.x+b2.y*b2.x)/(b2.y-b1.y), 0);
}
}
else if(b2.y < 0) {
b2 = point((-b2.y*b2.x+b1.y*b1.x)/(b1.y-b2.y), 0);
}
if(b1.x > b2.x) swap(b1, b2);
if(b2.x < 0 or b1.x > 1) {
cout << "No" << endl;
}
else cout << "Yes" << endl;
}
}
|
e8ac7ff71cc6e549e8949afb565a05f2508c1e45
|
bef04e5146b264b88786216d09dff0c8d20e2cc7
|
/Firmware/Example2-20MinuteTest/Example2-20MinuteTest.ino
|
2f22b3d10addf4ae69c5b13b9829dc19fb57133f
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
sparkfunX/Qwiic_Air_Quality_Combo_Board-CCS811-BME280
|
b55f916a29b4b6902f473d40077ce307cc234888
|
d0caa331562d7d179b13e8da8be39c4d7bc1d355
|
refs/heads/master
| 2021-01-19T18:14:23.299631
| 2017-04-06T22:46:21
| 2017-04-06T22:46:21
| 82,707,255
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,162
|
ino
|
Example2-20MinuteTest.ino
|
/*
CCS811 Air Quality Sensor Example Code
By: Nathan Seidle
SparkFun Electronics
Date: February 7th, 2017
License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
Works with SparkFun CCS811 board https://www.sparkfun.com/products/14181
Or Combo board https://www.sparkfun.com/products/14241
Enjoy this code? Buy a board and help support SparkFun!
Calculates the current run time and indicates when 20 minutes has passed
Read the TVOC and CO2 values from the SparkFun CSS811 breakout board
A new sensor requires at 48-burn in. Once burned in a sensor requires
20 minutes of run in before readings are considered good.
Hardware Connections (Breakoutboard to Arduino):
3.3V = 3.3V
GND = GND
SDA = A4
SCL = A5
Serial.print it out at 9600 baud to serial monitor.
*/
#include <Wire.h>
//These are the air quality values obtained from the sensor
unsigned int tVOC = 0;
unsigned int CO2 = 0;
void setup()
{
Serial.begin(9600);
Serial.println("CCS811 Read Example");
Wire.begin();
if (configureCCS811() == false)
{
Serial.println("Problem with CCS811");
while(1);
}
else
{
Serial.println("CCS811 online");
}
}
void loop()
{
if (dataAvailable())
{
readAlgorithmResults(); //Calling this function updates the global tVOC and CO2 variables
Serial.print("CO2[");
Serial.print(CO2);
Serial.print("] tVOC[");
Serial.print(tVOC);
Serial.print("] ");
printRunTime();
Serial.println();
}
else if (checkForError())
{
printError();
}
delay(1000); //Wait for next reading
}
//Prints the amount of time the board has been running
//Does the hour, minute, and second calcs
void printRunTime()
{
char buffer[50];
unsigned long runTime = millis();
int hours = runTime / (60 * 60 * 1000L);
runTime %= (60 * 60 * 1000L);
int minutes = runTime / (60 * 1000L);
runTime %= (60 * 1000L);
int seconds = runTime / 1000L;
sprintf(buffer, "RunTime[%02d:%02d:%02d]", hours, minutes, seconds);
Serial.print(buffer);
if(hours == 0 && minutes < 20) Serial.print(" Not yet valid");
}
|
fa6e643aa20f5ffa39b947ce4bfff9ef6ff9f599
|
e5d4aafc228130ee89304cea390bbb45f5018fa1
|
/组合数/习题/满足条件的01序列.cpp
|
f294ef6c9ef40c09ced0bff4021e3db0b534a7b1
|
[
"MIT"
] |
permissive
|
LauZyHou/AlgorithmTemplate
|
2ec2efbba6fcd5e42292da0a0aa9aed6103019e3
|
42bc9385a028508301d3f0e4a58adc4f510ffaf6
|
refs/heads/master
| 2023-01-05T22:56:25.825032
| 2020-11-09T10:59:10
| 2020-11-09T10:59:10
| 297,931,438
| 6
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,474
|
cpp
|
满足条件的01序列.cpp
|
#include <iostream>
using namespace std;
// https://www.acwing.com/problem/content/891/
// 画张坐标系,从原点开始,0表示向右走,1表示向上走
// 从而可以转换成到(n,n)的路径问题
// 要求的就是y=x这根线及其下面的到(n,n)路径总数
// 也就是严格不能接触y=x+1这根线的路径总数
// 从(0,0)走到(n,n),路径总数是C_{2n}^n
// 只要再减去接触y=x+1这根线的路径数
// 只要接触了y=x+1,就从这个点开始把后面的路径对于y=x+1做轴对称
// 这样路径就一定到达(n-1,n+1)这个点
// 所以要减去的就是从(0,0)到(n-1,n+1)的路径数量
// 所以答案就是C_{2n}^n - C_{2n}^{n-1}
// 化简得C_{2n}^n / (n + 1),也称为卡特兰数,很多问题的方案数都是卡特兰数
typedef long long LL;
const int mod = 1e9 + 7;
// 快速幂
int qmi(int a, int k, int p) {
int res = 1;
while (k) {
if (k & 1)
res = (LL)res * a % p;
k >>= 1;
a = (LL)a * a % p;
}
return res;
}
int main() {
int n;
scanf("%d", &n);
// 求C_{2n}^n / (n + 1) 模 mod
// 因为mod是一个质数,所以可以用费马小定理+快速幂求逆元来算
int a = 2 * n, b = n;
int res = 1;
for (int i = a; i > a - b; i --)
res = (LL)res * i % mod;
for (int i = 1; i <= b; i ++)
res = (LL)res * qmi(i, mod - 2, mod) % mod; // 除法就是乘以逆元
res = (LL)res * qmi(n + 1, mod - 2, mod) % mod; // 除以n+1
printf("%d\n", res);
return 0;
}
|
5d457710e952f399e05d28006d3a898554aaf7ec
|
0170ec1923ad9f830bfa7c4d89d96577e141198c
|
/watopoly/GooseNesting.cc
|
98c317c2ca7ead4b0150d3fb054f92da294a134b
|
[] |
no_license
|
StidZhang/Watopoly
|
2811a465ffb48b24679990ca724f22c5451033fb
|
9c9e5ff3a38871103aa381cd4f7cda6a65b1471c
|
refs/heads/master
| 2021-01-11T20:47:01.214339
| 2017-01-17T03:32:15
| 2017-01-17T03:32:15
| 79,183,514
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 450
|
cc
|
GooseNesting.cc
|
#include "Nonproperty.h"
#include "GooseNesting.h"
#include "Player.h"
#include <iostream>
#include <string>
using namespace std;
GooseNesting::GooseNesting(std::string name, int cellIndex, GameBoard *g)
:Nonproperty{name, cellIndex, g}{}
GooseNesting::~GooseNesting() {}
void GooseNesting::doEvent(Player *p){
cout << "You are currently on " << getName() << "." << endl;
cout << "Attack by a flock of nesting geese!" << endl;
}
|
1b3df93873036337c9d83f7629984be979c95feb
|
7b8ea628726c77532fc07d9a3c3c325aac388bee
|
/Labs Estructuras/Lab13/Codigo/PQSorted.cpp
|
e90443dc45424c0b7db100a8f6e27a36a6ca5204
|
[] |
no_license
|
dvarasm/Laboratorios-Estructuras-de-datos
|
c4ca0c11337b979f7ec6814e1be45546dd727242
|
c33753316b532f77c3eb7f544c845b7141eb0478
|
refs/heads/master
| 2020-03-28T07:13:46.898986
| 2018-09-08T00:55:51
| 2018-09-08T00:55:51
| 147,888,388
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,045
|
cpp
|
PQSorted.cpp
|
#include "PQSorted.h"
#include <iostream>
#include <cstdlib>
using namespace std;
PQSorted::PQSorted(){
num =10;
a = (int *)malloc(num*sizeof(int));
index=0;
count=0;
}
bool PQSorted::empty(){
if(count==0)return true;
else return false;
}
int PQSorted::size(){
return count;
}
int PQSorted::top(){
return a[0];
}
void PQSorted::push(int n){
if(index >= num-1){
int tmp = num;
num = tmp*2;
a = (int *)realloc(a,num*sizeof(int));
}
a[index]=n;
int j,tmp;
for (int i = 1; i < index; i++) {
j = i;
while (j > 0 && a[j - 1] > a[j]) {
tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
j--;
}
}
index++;
count++;
}
void PQSorted::pop(){
int *tmp=(int*)malloc(index*sizeof(int));
for(int i=0;i<index;i++)tmp[i]=a[i];
int j=1;
for(int i=0;i<index-1;i++){
a[0]=tmp[j];
j++;
}
free(tmp);
index--;
count--;
}
PQSorted::~PQSorted(){
free(a);
}
|
6dcdfb908c9a144e62b062599b59939360c108bf
|
cd5413e60ccd241eddbcb88d5502b5a62bad4191
|
/Examples/Qiniu/QiniuPic/v2/v2/MainWindow.h
|
66956c96b4cf5d7fef534af0eaaa15841eb02ce9
|
[] |
no_license
|
PikachuHy/Oak-Pokemon-Research-Lab
|
51e00e9c184058fe0d856faf4e8fe62e089d2a6e
|
9b13e5bddac6cd30ae1726b12e6ab61b7d74faf1
|
refs/heads/master
| 2023-05-11T17:55:35.558012
| 2023-05-02T07:31:40
| 2023-05-02T07:31:40
| 138,909,225
| 13
| 6
| null | 2021-04-26T18:50:40
| 2018-06-27T16:54:22
|
C++
|
UTF-8
|
C++
| false
| false
| 560
|
h
|
MainWindow.h
|
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_MainWindow.h"
namespace Ui {
class MainWindow;
}
class Side;
class SystemTray;
class Setting;
class PicUpload;
class QStackedLayout;
class QiniuSetting;
class MainWindow : public QMainWindow
{
private:
Q_OBJECT
public:
MainWindow(QWidget *parent = Q_NULLPTR);
~MainWindow();
private:
Ui::MainWindow ui;
Side* m_side;
SystemTray* m_tray;
Setting* m_setting;
QStackedLayout * m_stack;
PicUpload* m_picUpload;
QiniuSetting* m_qiniuSetting;
private slots:
void onClipboardDataChange();
};
|
f7b6e47421837864ba48aaaeea99736da18ec6a3
|
c26c92d1d8eec93c597d5b161698128ff09ec1f8
|
/svo_install_ws/install/include/svo/common/imu_calibration.h
|
81d526cdb7edf50e130967c84e8451911e1a30f6
|
[] |
no_license
|
pi-gslam/gslam_svo2
|
678c4336bb2c4b98d78f00856ab529e1b7b152e2
|
1ee134afada8a31e5df6a0a58b6688455a0499fb
|
refs/heads/master
| 2020-08-11T12:04:31.309113
| 2019-10-12T02:16:13
| 2019-10-12T02:16:13
| 214,561,879
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,101
|
h
|
imu_calibration.h
|
#pragma once
#include <deque>
#include <iostream>
#include <svo/common/types.h>
namespace svo {
/// \brief Settings for the IMU statistics
/// Check the following references for more information about the IMU parameters:
/// * https://github.com/ethz-asl/kalibr/wiki/IMU-Noise-Model-and-Intrinsics
/// * http://www-users.cs.umn.edu/~trawny/Publications/Quaternions_3D.pdf (Sec. 2.1)
/// Default parameters are for ADIS16448 IMU.
class ImuCalibration
{
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
typedef std::shared_ptr<ImuCalibration> Ptr;
/// Camera-IMU delay: delay_imu_cam = cam_ts - cam_ts_delay
double delay_imu_cam = 0.0;
/// Maximum delay camera-imu
double max_imu_delta_t = 0.01;
/// Gyro noise density (sigma). [rad/s*1/sqrt(Hz)]
double gyro_noise_density = 0.00073088444;
/// Accelerometer noise density (sigma). [m/s^2*1/sqrt(Hz)]
double acc_noise_density = 0.01883649;
/// IMU integration sigma (sigma). GTSAM preintegration option.
double imu_integration_sigma = 0.0;
/// Gyro bias random walk (sigma). [rad/s^2*1/sqrt(Hz)]
double gyro_bias_random_walk_sigma = 0.00038765;
/// Accelerometer bias random walk (sigma). [m/s^3*1/sqrt(Hz)]
double acc_bias_random_walk_sigma = 0.012589254;
/// Norm of the Gravitational acceleration. [m/s^2]
double gravity_magnitude = 9.81007;
/// Coriolis acceleration (earth rotation rate).
Eigen::Vector3d omega_coriolis = Eigen::Vector3d::Zero();
/// Accelerometer saturation. [m/s^2]
double saturation_accel_max = 150;
/// Gyroscope saturation. [rad/s]
double saturation_omega_max = 7.8;
/// Expected IMU Rate [1/s]
double imu_rate = 20;
ImuCalibration() = default;
~ImuCalibration() = default;
inline void print(const std::string& s = "IMU Calibration: ") const
{
std::cout << s << std::endl
<< " delay_imu_cam = " << delay_imu_cam << std::endl
<< " sigma_omega_c = " << gyro_noise_density << std::endl
<< " sigma_acc_c = " << acc_noise_density << std::endl
<< " sigma_integration_c = " << imu_integration_sigma << std::endl
<< " sigma_omega_bias_c = " << gyro_bias_random_walk_sigma << std::endl
<< " sigma_acc_bias_c = " << acc_bias_random_walk_sigma << std::endl
<< " g = " << gravity_magnitude << std::endl
<< " coriolis = " << omega_coriolis.transpose() << std::endl;
}
};
class ImuInitialization
{
public:
typedef std::shared_ptr<ImuInitialization> Ptr;
/// Initial velocity, in world frame!
Eigen::Vector3d velocity = Eigen::Vector3d::Zero();
/// Initial gyroscope bias
Eigen::Vector3d omega_bias = Eigen::Vector3d::Zero();
/// Initial accelerometer bias
Eigen::Vector3d acc_bias = Eigen::Vector3d::Zero();
/// Initial velocity uncertainty
double velocity_sigma = 2.0;
/// Initial gyroscope bias uncertainty
double omega_bias_sigma = 0.01;
/// Initial acceleromter bias uncertainty
double acc_bias_sigma = 0.1;
inline void print(const std::string& s = "IMU Initialization: ") const
{
std::cout << s << std::endl
<< " velocity = " << velocity.transpose() << std::endl
<< " omega_bias = " << omega_bias.transpose() << std::endl
<< " acc_bias = " << acc_bias.transpose() << std::endl
<< " velocity_sigma = " << velocity_sigma << std::endl
<< " omega_bias_sigma = " << omega_bias_sigma << std::endl
<< " acc_bias_sigma = " << acc_bias_sigma << std::endl;
}
};
// TODO(cfo) Deprecate
struct ImuMeasurement
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
double timestamp_; ///< In seconds.
Eigen::Vector3d angular_velocity_;
Eigen::Vector3d linear_acceleration_;
ImuMeasurement() {}
ImuMeasurement(
const double timestamp,
const Eigen::Vector3d& angular_velocity,
const Eigen::Vector3d& linear_acceleration)
: timestamp_(timestamp)
, angular_velocity_(angular_velocity)
, linear_acceleration_(linear_acceleration)
{}
};
typedef std::deque<ImuMeasurement> ImuMeasurements;
} // namespace svo
|
f9d19764daf56265fd715a44a2784aed86ace712
|
573694b142f7b6bee32866d14957275f4e9417be
|
/mi/test/test-ok-condition-vars-elf.cpp
|
e78b84d047ee1ee2dc99e6aa49052f46e8cf5d2c
|
[] |
no_license
|
SergeySatskiy/mi-analyzer
|
eb8385369b2cee22d7265b73deab948349a0a2e3
|
e78a3b487402936436ab320e1f92f466496a9946
|
refs/heads/master
| 2016-09-06T21:16:04.697130
| 2012-08-27T19:58:46
| 2012-08-27T19:58:46
| 32,541,383
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,440
|
cpp
|
test-ok-condition-vars-elf.cpp
|
//
// File: test-ok-condition-vars-elf.cpp
//
// Author: Sergey Satskiy, copyright (c) 2009
//
// Date: January 24, 2010
//
// $Id$
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
#include <pthread.h>
#include <unistd.h>
#include <iostream>
using namespace std;
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
void * thread0( void * )
{
pthread_mutex_lock( &condition_mutex );
pthread_cond_wait( &condition_cond, &condition_mutex );
pthread_mutex_unlock( &condition_mutex );
return 0;
}
void * thread1( void * )
{
usleep( 250 );
pthread_mutex_lock( &condition_mutex );
pthread_cond_signal( &condition_cond );
pthread_mutex_unlock( &condition_mutex );
return 0;
}
int main( void )
{
cout << "Test (ok, elf, condition variable) t0: m.lock -> c.wait -> m.unlock" << endl
<< " t1: m.lock -> c.signal -> m.unlock" << endl;
pthread_t t0;
pthread_t t1;
pthread_create( &t0, NULL, &thread0, NULL);
pthread_create( &t1, NULL, &thread1, NULL);
pthread_join( t0, NULL);
pthread_join( t1, NULL);
return 0;
}
|
2cb42c908b90cf5c09068958edc5c8ee950ab1cc
|
1b02aa884af5021cf7b643189f3b2a0e79bab035
|
/TeachingAssistant/StudentModel.h
|
090ee21790b0d371abc5c71612f8ba6b7aa9dd59
|
[] |
no_license
|
bachns/TeachingAssistant
|
6745d40455e2144f2cecafaeeb20bf4586a6cb93
|
3b6ee6a57b9cbe7fc2f9f43da618c8ef36101ff8
|
refs/heads/master
| 2020-07-31T20:16:22.755447
| 2019-09-25T02:43:27
| 2019-09-25T02:43:27
| 210,741,670
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,208
|
h
|
StudentModel.h
|
/********************************************************************************
* Copyright (C) 2019 by Bach Nguyen Sy *
* Unauthorized copying of this file via any medium is strictly prohibited *
* *
* <bachns.dev@gmail.com> *
* https://bachns.wordpress.com *
* https://www.facebook.com/bachns.dev *
* *
********************************************************************************/
/**
* File name: TeachingAssistant/StudentModel.h
* Date created: September 23, 2019
* Written by Bach Nguyen Sy
*/
#ifndef STUDENTMODEL_H
#define STUDENTMODEL_H
#include "Student.h"
#include <QList>
class StudentModel
{
public:
StudentModel();
explicit StudentModel(const Student& stu);
~StudentModel();
bool insert() const;
bool update() const;
bool remove() const;
static QList<Student> getStudents();
private:
Student m_student;
};
#endif // STUDENTMODEL_H
|
d7a1f855c46f1ba70fe28d598a9ffc150c140b66
|
ed2a818203bf140ebe9a04d4e3559f1cece1d31d
|
/cpp_series/cf_for_loops.cpp
|
0ad327015c5e74b9d113868ab52138527fabbb2e
|
[] |
no_license
|
olszewskip/coffee_before_arch
|
cc5c614aedaf77706a4512ff573d9baa1d5e13a5
|
41aba7615bfa3c7c7a270cc9c6d039d40b269e32
|
refs/heads/master
| 2020-05-04T17:37:31.925002
| 2019-04-11T19:28:45
| 2019-04-11T19:28:45
| 179,319,033
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 272
|
cpp
|
cf_for_loops.cpp
|
#include <iostream>
using namespace std;
int main() {
int multiplicand = 5;
int multiplier = 10;
int product = 0;
cout << "before" << endl;
for (int i = 0; i < multiplier; i++) {
product += multiplicand;
cout << i << " " << product << endl;
}
return 0;
}
|
440fd142ca3a723950bffcdab211702ff5512b29
|
720098f107c1f59ea90024347e233c696ee33ce1
|
/rv.cpp
|
fb2c9fe8c4e46f0e23fc4a3eabcd934f5999a4b7
|
[] |
no_license
|
joker9357/performance-of-computer
|
0af957ce666699ce626e636381c0dee5215e71a9
|
ab5d6768deb28242ab6afb6e9a469e26755fdb66
|
refs/heads/master
| 2021-01-09T05:34:59.302700
| 2017-02-03T03:33:00
| 2017-02-03T03:33:00
| 80,793,806
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 871
|
cpp
|
rv.cpp
|
//
// This file contains programs for generating random numbers with
// uniform distributions and exponential distributions.
//
#include <math.h>
#include <iostream>
double Seed = 1111.0;
/*******************************************/
/* returns a uniform (0,1) random variable */
/*******************************************/
double uni_rv()
{
double k = 16807.0;
double m = 2.147483647e9;
double rv;
Seed=fmod((k*Seed),m);
rv=Seed/m;
//std::cout << "uni_rv=\t" << rv << std::endl;
return(rv);
}
/*******************************/
/* given arrival rate lambda */
/* returns an exponential r.v. */
/*******************************/
double exp_rv(double lambda)
{
double exp;
exp = ((-1) / lambda) * log(uni_rv());
//std::cout << "lambda=\t"<< lambda << "\t" << "exp_rv=\t" << exp << std::endl;
return(exp);
}
|
129151739b45834209fafd237907cdd4ad6d804d
|
df76a804422288ef6bac9670bf0c2d4523e7229c
|
/contractmgmt/controller.h
|
b864b89239b9219c61929561e12e0d919b3ef9f0
|
[
"Apache-2.0"
] |
permissive
|
lijunjun/controller
|
1667e395e2bc77a95d92c31a62b3ec85dd305a43
|
e81fafd693c5af03ddeafd989622e75aa5e107b6
|
refs/heads/master
| 2016-09-05T19:46:27.839161
| 2014-07-31T10:49:21
| 2014-07-31T10:49:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 230
|
h
|
controller.h
|
#ifndef CONTROLLER_H
#define CONTROLLER_H
#include <iostream>
#include <string>
#define CONSOLE_WAIT(iEndString) \
std::string lEnd; \
while (true) \
{ \
std::cin >> lEnd; \
if (lEnd == iEndString) break; \
}
#endif
|
ca600d09aa6d5acd0b7b48a7e9596ef16b566a09
|
191642346aea40bbd387842e62e001140355ef37
|
/uri1257.cpp
|
4500d2ff6b8a4d72bc2af63fdcef1301052800bf
|
[] |
no_license
|
yurifarod/UVA-URI
|
00ca0c4d73e7519e3c1f040c616cd750489c3659
|
a2f574695dfbd681efcf405141c02e1d09464f68
|
refs/heads/master
| 2023-01-11T04:24:27.420261
| 2023-01-08T22:39:26
| 2023-01-08T22:39:26
| 71,098,135
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 407
|
cpp
|
uri1257.cpp
|
#include <stdio.h>
#include<string.h>
using namespace std;
int main(){
int n, l, vl;
char p[50];
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &l);
for(int j = 0; j < l; j++){
scanf("%s", &p);
int length = strlen(p);
for(int k = 0; k < length; k++){
vl += (int)p[k] - 65 + j + k;
}
}
printf("%d\n", vl);
vl = 0;
}
return 0;
}
|
f33439c22a2e49f1e28baeeb8c9d700bdd9d1d4e
|
7d5593b9bbaf6bb8eaacca88449d90c9c305c36e
|
/problems/103-binary-tree-zigzag-level-order-traversal/103.cc
|
364e3200b48431158b4ee6802867e7cb79557c99
|
[] |
no_license
|
yottacto/leetcode
|
fc98052ed9d643be8a79116d28540596bcc7c26b
|
9a41e41c0982c1a313803d1d8288d086fbdbd5b6
|
refs/heads/master
| 2021-04-25T12:05:55.671066
| 2019-12-15T03:07:31
| 2019-12-15T03:07:31
| 111,814,868
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 34
|
cc
|
103.cc
|
#include "103.hh"
int main()
{
}
|
b50c8b7d3ba649132522b59d1eaba76ca871a42e
|
29b2d2f8f375035260c4f8cfb7de9ba78bcceb22
|
/sd.h
|
1ca272ce59eb07ab90af8dc83af9529c2ec5c0c5
|
[] |
no_license
|
tomtompurin/CanSat2019
|
51180db86826240ffb061cf40abe59eedb41a0fe
|
88c1f68e99944d7ee2d69f1027dbb13da753ea39
|
refs/heads/master
| 2021-06-10T23:23:49.038888
| 2021-05-13T05:58:41
| 2021-05-13T05:58:41
| 181,634,072
| 0
| 0
| null | 2021-05-13T03:29:45
| 2019-04-16T07:05:35
|
C++
|
UTF-8
|
C++
| false
| false
| 429
|
h
|
sd.h
|
/**
@file sd.h
@author Tomiyoshi Yuta
@date Created: 20180531
*/
#ifndef _SD_H_
#define _SD_H_
//#include <stdio.h>
#include "constant.h"
#include <string.h>
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
class Sd {
public:
// 関数
Sd();
~Sd();
void setupSd(); // setup
void printSd(String log_data); // log保存
void printlnSd(String log_data); // log保存
String log_data;
};
#endif
|
ba847fd7f48e220ab44b856f04dbd490fc23b543
|
4c8702112054c9a2db2f85d540c5bff9e33237e8
|
/cplusplus_version/N-Queens II.cpp
|
922143a5fd462c14c7f01e54065251cc8a5c8417
|
[] |
no_license
|
wjk20120522/leetcode
|
dba48fc90ca113cb0ee1e821fecff86941c160c0
|
2659a0ae08331e48f134318fa1eebade5e7ada4a
|
refs/heads/master
| 2016-09-05T18:24:05.695657
| 2015-10-05T02:14:30
| 2015-10-05T02:14:30
| 18,658,115
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 860
|
cpp
|
N-Queens II.cpp
|
class Solution {
int *place;
int sp;
int count;
public:
int totalNQueens(int n) {
place = new int[n];
sp = 0;
count = 0;
queens(0, 0, n);
return count;
}
void push(int x)
{
place[sp] = x;
sp++;
}
int pop()//出栈
{
return place[--sp];
}
int judge(int i, int j, int n)
{
if (j>=n) //已经遍历完该行
return 1;
for (int k = i - 1; k >= 0; k--)
{
if (j == place[k])//对角线,同列,斜对角线
return 1;
if (i - k == j - place[k])
return 1;
if (i - k == place[k] - j)
return 1;
}
return 0;
}
void queens(int i, int j, int n)
{
if (i >= n)
{
count++;
}
for (int k = j; k < n; k++) {
if (judge(i, k, n) == 0) {
push(k);
queens(i+1, 0, n);
pop();
}
}
}
};
|
7cda8d9ae38db4ae34e2d0cdecf8e6eb6debd5c0
|
d7b15fb6c1238b3fe9d120624c87927e3b45e1cb
|
/uHunt/UVA 11002 - TowardsZero/TowardsZero.cpp
|
d9e45dc5fdbd21fc5d8b66766f838cdf238120be
|
[] |
no_license
|
maxyuan6717/Competitive_Programming
|
ade652a76ae89ac38e354cb688d9730a731039e4
|
d799d8b5a8915fea7d68d8dbaf742f72d065e4a9
|
refs/heads/master
| 2022-12-08T04:08:03.647310
| 2020-08-25T20:46:15
| 2020-08-25T20:46:15
| 290,319,070
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,430
|
cpp
|
TowardsZero.cpp
|
#include <iostream>
#include <cstdio>
#include <sstream>
#include <fstream>
#include <string>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <utility>
#include <bitset>
#include <iomanip>
#include <climits>
#define LARGE INT_MAX
#define mp make_pair
#define f first
#define s second
using namespace std;
typedef pair<int,int> pii;
typedef vector<pii> vii;
int N,arr[60][60];
bool dp[60][60][6001];
int main() {
while (cin >> N, N) {
for (int i = 2*N-1; i >= N+1; i--) {
for (int j = 0; j < 2*N - i; j++) {
cin >> arr[i-1][j];
}
}
for (int i = N; i >= 1; i--) {
for (int j = 0; j < i; j++) {
cin >> arr[i-1][j];
}
}
memset(dp,0,sizeof(dp));
dp[0][0][arr[0][0]+3000] = 1;
for (int i = 0; i < N-1; i++) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= 6000; k++) {
if (!dp[i][j][k]) continue;
int ni = i+1, nj = j, val = arr[ni][nj];
if (k + val >= 0 && k + val <= 6000) dp[ni][nj][k+val] = 1;
if (k - val >= 0 && k - val <= 6000) dp[ni][nj][k-val] = 1;
nj++; val = arr[ni][nj];
if (k + val >= 0 && k + val <= 6000) dp[ni][nj][k+val] = 1;
if (k - val >= 0 && k - val <= 6000) dp[ni][nj][k-val] = 1;
}
}
}
for (int i = N-1; i < 2*N-2; i++) {
for (int j = 0; j < 2*N - 1- i; j++) {
for (int k = 0; k <= 6000; k++) {
if (!dp[i][j][k]) continue;
if (!j) {
int ni = i+1, nj = j, val = arr[ni][nj];
if (k + val >= 0 && k + val <= 6000) dp[ni][nj][k+val] = 1;
if (k - val >= 0 && k - val <= 6000) dp[ni][nj][k-val] = 1;
}
else if (j == 2*N-i-2) {
int ni = i+1, nj = j-1, val = arr[ni][nj];
if (k + val >= 0 && k + val <= 6000) dp[ni][nj][k+val] = 1;
if (k - val >= 0 && k - val <= 6000) dp[ni][nj][k-val] = 1;
}
else {
int ni = i+1, nj = j-1, val = arr[ni][nj];
if (k + val >= 0 && k + val <= 6000) dp[ni][nj][k+val] = 1;
if (k - val >= 0 && k - val <= 6000) dp[ni][nj][k-val] = 1;
nj++; val = arr[ni][nj];
if (k + val >= 0 && k + val <= 6000) dp[ni][nj][k+val] = 1;
if (k - val >= 0 && k - val <= 6000) dp[ni][nj][k-val] = 1;
}
}
}
}
int ans = LARGE;
for (int i = 0; i <= 6000; i++) {
if (!dp[2*N-2][0][i]) continue;
ans = min(ans,abs(i-3000));
}
cout << ans << endl;
}
return 0;
}
|
f7cfd22d0f2425a449127b0b83b8041311f5dd49
|
9602e36990888087b0d3405218e5b0a850c00315
|
/project/src/galois/src/carryless_multiplier_galois.cpp
|
75fbcdadec74150460563bf619a5a71b8cbcbc89
|
[
"MIT"
] |
permissive
|
fafianie/multiway_cut
|
e6360f3e48f4ac6b666cae0b135e638fe76e06d6
|
52355c9a754287545c060b3ae97b4e11aacd0bfb
|
refs/heads/master
| 2021-06-02T13:20:55.710095
| 2020-08-15T15:40:14
| 2020-08-15T15:40:14
| 133,058,079
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,033
|
cpp
|
carryless_multiplier_galois.cpp
|
#include "stdafx.h"
#include "carryless_multiplier_galois.h"
#include "powers.cpp"
CarrylessMultiplierGalois::CarrylessMultiplierGalois() : Galois(64) {}
CarrylessMultiplierGalois::~CarrylessMultiplierGalois() {}
uint64_t CarrylessMultiplierGalois::divide(uint64_t leftOperand, uint64_t rightOperand) {
if (leftOperand == 0) return 0;
if (rightOperand == 0) return -1;
return multiply(leftOperand, inverse(rightOperand));
}
uint64_t CarrylessMultiplierGalois::multiply(uint64_t leftOperand, uint64_t rightOperand) {
uint64_t x1x0, x2x3;
__asm__ (
"movd %2, %%xmm0;"
"movd %3, %%xmm1;"
"pclmulqdq $0, %%xmm0, %%xmm1;"
"movd %%xmm1, %0;"
"psrldq $8, %%xmm1;"
"movd %%xmm1, %1;"
: "=r" (x1x0), "=r" (x2x3)
: "r" (leftOperand), "r" (rightOperand)
);
uint64_t x2 = x2x3 & pwm1[32];
uint64_t x3 = x2x3 >> 32;
uint64_t x3d = (x3 << 32) ^ (x3 >> 31) ^ (x3 >> 29) ^ (x3 >> 28) ^ x2;
uint64_t h1h0 = (x3d << 1) ^ (x3d << 3) ^ (x3d << 4) ^ x3d;
return h1h0 ^ x1x0;
}
|
42326362282c7776fd66067c58635f54d797ef74
|
9a5660497e08e9fe09268fb50989674db32adbfc
|
/OpenGL_Rodrigo_Costa_52718/OpenGL_Rodrigo_Costa_52718/Rodrigo_52718.cpp
|
7eeb2efafb7c28f16c0258395ce9538341fabf9f
|
[] |
no_license
|
svork/OpenGL
|
af8d935fde5da86c77497a59e5fe38ca17592a5c
|
841be01cba60fce2046efa1c4657a6ccc97ab5b7
|
refs/heads/master
| 2021-01-25T07:01:16.930644
| 2017-06-13T23:03:50
| 2017-06-13T23:03:50
| 93,639,871
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 7,450
|
cpp
|
Rodrigo_52718.cpp
|
#include <glut.h>
GLfloat angle, fAspect, win;
GLfloat angulo = 15.0f; // Angulo de Rotacao
GLfloat posX = 0.0f, posY = 0.0f;
// Função callback para fazer o desenho
void Desenha(void) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Assento do banco
glPushMatrix(); // Inicio do objeto
glTranslatef(1.0f, 1.0f, 1.0f); // Movimenta o assento do banco para o centro da tela
glScalef(4.0f, 0.1f, 1.0f); // Transforma o cubo em assento do banco
glColor3f(0.5f, 0.3f, 0.2f); // Cor do banco da praca - Marrom
glutSolidCube(25.0f); // Cria o cubo
glPopMatrix(); // Fim do objeto
// Encosto do banco
glPushMatrix();
glTranslatef(1.0f, 12.75f, -13.5f);
glScalef(6.0f, 1.5f, 0.2f);
glColor3f(0.5f, 0.3f, 0.2f);
glutSolidCube(15.0f);
glPopMatrix();
// Perna 1
glPushMatrix();
glTranslatef(-30.0f, -15.0f, 10.0f);
glScalef(0.3f, 2.0f, 0.2f);
glColor3f(0.5f, 0.3f, 0.2f);
glutSolidCube(15.0f);
glPopMatrix();
// Perna 2
glPushMatrix();
glTranslatef(30.0f, -15.0f, 10.0f);
glScalef(0.3f, 2.0f, 0.2f);
glColor3f(0.5f, 0.3f, 0.2f);
glutSolidCube(15.0f);
glPopMatrix();
// Perna 3
glPushMatrix();
glTranslatef(-30.0f, -15.0f, -10.0f);
glScalef(0.3f, 2.0f, 0.2f);
glColor3f(0.5f, 0.3f, 0.2f);
glutSolidCube(15.0f);
glPopMatrix();
// Perna 4
glPushMatrix();
glTranslatef(30.0f, -15.0f, -10.0f);
glScalef(0.3f, 2.0f, 0.2f);
glColor3f(0.5f, 0.3f, 0.2f);
glutSolidCube(15.0f);
glPopMatrix();
// Gramado
glPushMatrix();
glTranslatef(1.0f, -30.0f, 1.0f);
glScalef(10.0f, 0.1f, 10.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glutSolidCube(25.0f);
glPopMatrix();
// Poste de Luz
glPushMatrix();
glTranslatef(-90.0f, 40.0f, -50.0f);
glScalef(0.2f, 10.0f, 0.2f);
glColor3f(0.1f, 0.1f, 0.0f);
glutSolidCube(15.0f);
glPopMatrix();
// Luz do Poste
glPushMatrix();
glTranslatef(-90.0f, 120.0f, -50.0f);
glScalef(1.0f, 1.0f, 1.0f);
glColor3f(1.0f, 1.0f, 0.0f);
glutSolidSphere(10.0, 10, 10);
glPopMatrix();
// Tronco da Arvore
glPushMatrix();
glTranslatef(90.0f, 40.0f, 80.0f);
glScalef(0.8f, 10.0f, 0.8f);
glColor3f(1.0f, 0.0f, 0.0f);
glutSolidCube(15.0f);
glPopMatrix();
// Folhas do Pinheiro, um cone
glPushMatrix();
glTranslatef(90.0f, 40.0f, 80.0f);
glRotatef(90.0f, -90.0f, 1.0f, 1.0f);
glScalef(1.0f, 1.0f, 2.0f);
glColor3f(0.0f, 1.0f, 0.0f);
glutSolidCone(40.0, 50.0, 10, 10);
glPopMatrix();
// Executa os comandos OpenGL
glutSwapBuffers();
}
// Inicializa parametros de rendering
void Inicializa(void) {
GLfloat luzAmbiente[4] = { 0.2, 0.2, 0.2, 1.0 };
GLfloat luzDifusa[4] = { 0.7, 0.7, 0.7, 1.0 }; // Cor
GLfloat luzEspecular[4] = { 1.0, 1.0, 1.0, 1.0 }; // Brilho
GLfloat posicaoLuz[4] = { 0.0, 50.0, 50.0, 1.0 };
// Capacidade de brilho do material
GLfloat especularidade[4] = { 1.0, 1.0, 1.0, 1.0 };
GLint especMaterial = 60;
// Especifica que a cor de fundo da janela será preta
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Habilita o modelo de colorizacao de Gouraud
glShadeModel(GL_SMOOTH);
// Define a refletancia do material
//glMaterialfv(GL_FRONT, GL_SPECULAR, especularidade);
// Define a concentracao do brilho
glMateriali(GL_FRONT, GL_SHININESS, especMaterial);
// Ativa o uso da luz ambiente
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, luzAmbiente);
// Define os parametros da luz de numero 0
glLightfv(GL_LIGHT0, GL_AMBIENT, luzAmbiente);
glLightfv(GL_LIGHT0, GL_DIFFUSE, luzDifusa);
glLightfv(GL_LIGHT0, GL_SPECULAR, luzEspecular);
glLightfv(GL_LIGHT0, GL_POSITION, posicaoLuz);
// Habilita a definicao da cor do material a partir da cor atual
glEnable(GL_COLOR_MATERIAL);
// Habilita o uso de iluminacao
glEnable(GL_LIGHTING);
// Habilita a luz de numero 0
glEnable(GL_LIGHT0);
// Habilita o depth-buffering
glEnable(GL_DEPTH_TEST);
angle = 45;
win = 250.0f;
}
// Funcao usada para especificar o volume de visualizacao
void EspecificaParametrosVisualizacao(void) {
// Especifica sistema de coordenadas de projecao
glMatrixMode(GL_PROJECTION);
// Inicializa sistema de coordenadas de projecao
glLoadIdentity();
// Especifica a projecao perspectiva
gluPerspective(angle, fAspect, 0.1, 500);
// Especifica sistema de coordenadas do modelo
glMatrixMode(GL_MODELVIEW);
// Inicializa sistema de coordenadas do modelo
glLoadIdentity();
// Especifica posicao do observador e do alvo
gluLookAt(0, 80, 200, 0, 0, 0, 0, 1, 0);
}
// Funcao callback chamada quando o tamanho da janela e alterado
void AlteraTamanhoJanela(GLsizei w, GLsizei h) {
// Para evitar divisao por zero
if (h == 0) h = 1;
// Especifica o tamanho da viewport
glViewport(0, 0, w, h);
// Calcula a correcao de aspecto
fAspect = (GLfloat)w / (GLfloat)h;
// Inicializa o sistema de coordenadas
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-win, win, -win, win);
EspecificaParametrosVisualizacao();
}
// Funcao callback chamada para gerenciar eventos do mouse
void GerenciaMouse(int button, int state, int x, int y) {
if (button == GLUT_LEFT_BUTTON)
if (state == GLUT_DOWN) { // zoom in
if (angle >= 10) angle -= 5;
}
if (button == GLUT_RIGHT_BUTTON)
if (state == GLUT_DOWN) { // zoom out
if (angle <= 130) angle += 5;
}
EspecificaParametrosVisualizacao();
glutPostRedisplay();
}
// Funcao callback chamada para gerenciar eventos do teclado
void GerenciaTeclado(unsigned char key, int x, int y) {
switch (key) {
case 'R':
case 'r': // Muda a cor para vermelho
glColor3f(1.0f, 0.0f, 0.0f);
break;
case 'G':
case 'g': // Muda a cor para verde
glColor3f(0.0f, 1.0f, 0.0f);
break;
case 'B':
case 'b': // Muda a cor para azul
glColor3f(0.0f, 0.0f, 1.0f);
break;
case 'Z':
case 'z': // Rotacao positiva no eixo X
glRotatef(angulo, 1.0f, 0.0f, 0.0f);
break;
case 'X':
case 'x': // Rotacao negativa no eixo X
glRotatef(-angulo, 1.0f, 0.0f, 0.0f);
break;
case 'A':
case 'a': // Rotacao positiva no eixo Y
glRotatef(angulo, 0.0f, 1.0f, 0.0f);
break;
case 'S':
case 's': // Rotacao negativa no eixo Y
glRotatef(-angulo, 0.0f, 1.0f, 0.0f);
break;
case 'Q':
case 'q': // Rotacao positiva no eixo Z
glRotatef(angulo, 0.0f, 0.0f, 1.0f);
break;
case 'W':
case 'w': // Rotacao negativa no eixo Z
glRotatef(-angulo, 0.0f, 0.0f, 1.0f);
break;
default:
break;
}
glutPostRedisplay();
}
// Funcao callback chamada para gerenciar eventos do teclado (especiais)
void TeclasEspeciais(int key, int x, int y) {
if (key == GLUT_KEY_UP) {
glTranslatef(0.0f, 15.0f, 0.0f);
}
if (key == GLUT_KEY_DOWN) {
glTranslatef(0.0f, -15.0f, 0.0f);
}
if (key == GLUT_KEY_RIGHT) {
glTranslatef(15.0f, 0.0f, 0.0f);
}
if (key == GLUT_KEY_LEFT) {
glTranslatef(-15.0f, 0.0f, 0.0f);
}
glutPostRedisplay();
}
// Programa Principal
int main(void) {
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(1024, 768);
glutInitWindowPosition(10, 10);
glutCreateWindow("Rodrigo Costa 52718 - Cenario Open GL");
glutDisplayFunc(Desenha);
glutReshapeFunc(AlteraTamanhoJanela);
glutMouseFunc(GerenciaMouse);
glutKeyboardFunc(GerenciaTeclado);
glutSpecialFunc(TeclasEspeciais);
Inicializa();
glutMainLoop();
return 0;
}
|
e66fd5c7cce439b7fe0f1e900143be6c916d2048
|
ce109b9240b838523c0854c0fabcf59d396cf4b9
|
/Test.ino
|
50304ddc268815e7af0935104d2ef6dace7cf748
|
[] |
no_license
|
Namlitruong/Design-3A
|
bb982d6cbc560f2b17b596ea83eff054f20d2d8c
|
f8501e26bf68ff8de60a3c3c27c0bea4c628d456
|
refs/heads/master
| 2020-03-13T00:41:19.509177
| 2019-07-06T14:42:31
| 2019-07-06T14:42:31
| 130,891,421
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,838
|
ino
|
Test.ino
|
#include <Arduino.h>
#include <avr/io.h>
#include <SPI.h>
#include <MFRC522.h>
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspServer.h>
#include <PubSubClient.h>
#include <SoftwareSerial.h>
//###################################################################
//WIFI configuration
SoftwareSerial esp(A5 ,2); // RX, TX
char ssid[] = "Namli"; // your network SSID (name)
char pass[] = "9903098610"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
//char mqttServer[] = "mqtt.thingspeak.com";
char mqttServer[] = "192.168.137.98";
char ClientID[] = "Robot1";
String arrivedData;
bool messageArrived = 0;
WiFiEspClient espClient;
PubSubClient client(espClient);
//######################################################################
//RFID Configuration
MFRC522 mfrc522(10, 9);
unsigned long UID, UIDtemp;
//###################################################################
//=====DECLARATION=====
uint8_t sensor[5];
char Case;
unsigned long sec;
int count;
// VARIABLES FOR SENSOR READING
float activeSensor = 0; // Count active sensors
float totalSensor = 0; // Total sensor readings
float avgSensor =3; // Average sensor reading
// VARIABLES FOR PID CONTROLLER
float Kp = 30;//44
float Ki = 0.025;
float Kd = 0;
float error = 0;
float *er_pt = &error; // error pointer
float previousError = 0;
float totalError = 0;
int PIDstatus = 1;
int i;
float power = 0;
// VARIABLES FOR ADJUSTING SPEED
int turnSpeed =180;
int flag;
// VARIABLES FOR PATH OPTIMISATION
bool finish = false;
char option[50];
int index = 0;
// PATH PLANNING
char path[100] = " ";
int pathReadNumber = 0;
//###############################################################
//=====WiFi Functions=====
void RobotInfor(){
// print the SSID of the network you're attached to
Serial.print("###ClientID: ");
Serial.print (ClientID);
// print your WiFi shield's IP address
IPAddress ip = WiFi.localIP();
Serial.print("---IP Address: ");
Serial.println(ip);
}
void ConnectToWiFi (){
esp.begin(9600);
// initialize ESP module
WiFi.init(&esp);
// check for the presence of the shield
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("ESP is not connected");
// don't continue
while (true);
}
// attempt to connect to WiFi network
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network
status = WiFi.begin(ssid, pass);
}
Serial.println("You're connected to the network");
}
void callback(char* topic, byte* payload, unsigned int length) {
arrivedData = "";
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
arrivedData += (char)payload[i];
}
Serial.println();
Serial.println("########################");
Serial.println(arrivedData);
Serial.println("########################");
Serial.println();
messageArrived = 1;
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.println ("Attempting MQTT connection...");
// Attempt to connect, just a name to identify the client
if (client.connect(ClientID)) {
Serial.println("connected");
// Once connected, publish an announcement...
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay_ms(5000);
}
}
}
void mqttPublish (){
Serial.println ("Sending data");
// Data
//String Data = String(UID)+';'+String(v);
String Data = String(UID) + String(Battery);
int length = Data.length();
char Buff[length];
Data.toCharArray (Buff, length + 1);
//Publish packet
client.publish( ClientID, Buff, 1);
return;
}
//###############################################################
//========================
//=====RFID FUNCTION=====
void RFIDCard (){
UID = 0;
for (byte i = 0; i < mfrc522.uid.size; i++) {
UIDtemp = mfrc522.uid.uidByte[i];
UID = UID*256+UIDtemp;
}
Serial.println (UID);
mfrc522.PICC_HaltA();
return;
}
//=====DELAY FUNCTION=====
void delay_ms (uint16_t millisecond) {
sec = ((16000000/12)/1000)*millisecond;
for (count = 0; count < sec; count = count + 1);
}
//=================================
//=====Battery Reader FUNCTION=====
float BatteryReader (){
float BatteryLv = (((analogRead(A0) - 736.0) / 124.0) * 100.0);
return BatteryLv;
}
//=====MOTOR FUNCTIONS=====
void setPWM_leftmotor (uint8_t PWM6){
OCR0B = PWM6;
}
void setPWM_rightmotor (uint8_t PWM5){
OCR0A = PWM5;
}
void Forward (){
PORTD |= (1 << PD3);
PORTD &=~ ((1 << PD4));
PORTD |= (1 << PD7);
PORTB &=~ ((1 << PB0));
}
void Backward (){
PORTD &=~ (1 << PD3);
PORTD |= ((1 << PD4));
PORTD &=~ (1 << PD7);
PORTB |= ((1 << PB0));
}
void Stop (){
PORTD &=~ ((1 << PD3));
PORTD &=~ ((1 << PD4));
OCR0B = 0;
PORTD &=~ ((1 << PD7));
PORTB &=~ ((1 << PB0));
OCR0A = 0;
}
void TurnLeft (){ //left motor runs backward, right motor runs forward
PORTD &=~ ((1 << PD3));
PORTD |= (1 << PD4);
//OCR0B = startSpeed + rotate; //the speed of left motor = 65 + 30 = 95
PORTD |= (1 << PD7);
PORTB &=~ ((1 << PB0));
// OCR0A = startSpeed + rotate; //the speed of right motor = 65 + 30 = 95
}
void TurnRight (){ //left motor runs forward, right motor runs backward
PORTD |= (1 << PD3);
PORTD &=~ ((1 << PD4));
//OCR0B = startSpeed + rotate; //the speed of left motor = 65 + 30 = 95
PORTD &=~ ((1 << PD7));
PORTB |= (1 << PB0);
//OCR0A = startSpeed + rotate; //the speed of right motor = 65 + 30 = 95
}
//========================
//=====READ SENSORS AND ASSIGN VALUE TO SENSOR ARRAY=====
void ReadSensors (){
// Sensor 0
if (PINC & (1<<0)){
sensor[0] = 1;
}else{
sensor[0] = 0;}
// Sensor 1
if (PINC & (1<<1)){
sensor[1] = 1;
}else{
sensor[1] = 0;}
// Sensor 2
if (PINC & (1<<2)){
sensor[2] = 1;
}else{
sensor[2] = 0;}
// Sensor 3
if (PINC & (1<<3)){
sensor[3] = 1;
}else{
sensor[3] = 0;}
// Sensor 4
if (PINC & (1<<4)){
sensor[4] = 1;
}else{
sensor[4] = 0;}
//Print in the serial monitor
Serial.print (sensor[0]);
Serial.print (" ");
Serial.print (sensor[1]);
Serial.print (" ");
Serial.print (sensor[2]);
Serial.print (" ");
Serial.print (sensor[3]);
Serial.print (" ");
Serial.print (sensor[4]);
Serial.println (" ");
}
//========================
//=====DETERMINE RUNNING CASE=====
void SensorsCondition (){
ReadSensors ();
// STRAIGHT
if ((sensor[0]==0 && sensor[1]==1 && sensor[2]==1 && sensor[3]==0 && sensor[4]==0) //01100
|| (sensor[0]==1 && sensor[1]==1 && sensor[2]==0 && sensor[3]==0 && sensor[4]==0) //11000
|| (sensor[0]==1 && sensor[1]==0 && sensor[2]==0 && sensor[3]==0 && sensor[4]==0) //10000
|| (sensor[0]==0 && sensor[1]==0 && sensor[2]==0 && sensor[3]==1 && sensor[4]==0) //00010
|| (sensor[0]==0 && sensor[1]==0 && sensor[2]==1 && sensor[3]==1 && sensor[4]==0) //00110
|| (sensor[0]==0 && sensor[1]==0 && sensor[2]==0 && sensor[3]==1 && sensor[4]==1) //00011
|| (sensor[0]==0 && sensor[1]==0 && sensor[2]==0 && sensor[3]==0 && sensor[4]==1) //00001
|| (sensor[0]==0 && sensor[1]==1 && sensor[2]==0 && sensor[3]==0 && sensor[4]==0) //01000
||(sensor[0]==0 && sensor[1]==0 && sensor[2]==1 && sensor[3]==0 && sensor[4]==0) //00100
||(sensor[0]==1 && sensor[1]==1 && sensor[2]==1 && sensor[3]==0 && sensor[4]==0)
|| (sensor[0]==1 && sensor[1]==1 && sensor[2]==1 && sensor[3]==1 && sensor[4]==0)
||(sensor[0]==0 && sensor[1]==0 && sensor[2]==1 && sensor[3]==1 && sensor[4]==1)
|| (sensor[0]==0 && sensor[1]==1 && sensor[2]==1 && sensor[3]==1 && sensor[4]==1)) {
Case = 'S'; // Straight 00100
}
//
// // FINISH
// else if(sensor[0]==1 && sensor[1]==1 && sensor[2]==1 && sensor[3]==1 && sensor[4]==1){
// Case = 'F'; // Finish 11111
// }
// // TURN LEFT
// else if ((sensor[0]==1 && sensor[1]==1 && sensor[2]==1 && sensor[3]==0 && sensor[4]==0)
// || (sensor[0]==1 && sensor[1]==1 && sensor[2]==1 && sensor[3]==1 && sensor[4]==0)) {
// Case = 'L'; // Turn Left 11100
// // 11110
// }
//
//// TURN RIGHT
// else if ((sensor[0]==0 && sensor[1]==0 && sensor[2]==1 && sensor[3]==1 && sensor[4]==1)
// || (sensor[0]==0 && sensor[1]==1 && sensor[2]==1 && sensor[3]==1 && sensor[4]==1)) {
// Case = 'R'; // Turn Right 00111
// // 01111
// }
// DEADEND
else if (sensor[0]==0 && sensor[1]==0 && sensor[2]==0 && sensor[3]==0 && sensor[4]==0){
Case = 'D'; // Dead End 00000
//Situation = 0;
}
}
//=====TURNING FUNCTIONS=====
void turnRight(){
setPWM_leftmotor (80);
setPWM_rightmotor (135);
TurnRight();
delay_ms(455);
// ReadSensors();
// while (sensor[4] == 0){
// ReadSensors();
// setPWM_leftmotor (80);
// setPWM_rightmotor (135);
// TurnRight();
// }
Stop ();
delay_ms (500);
}
void turnLeft () {
setPWM_leftmotor (80);
setPWM_rightmotor (135);
TurnLeft();
delay_ms(455);
// ReadSensors();
// while (sensor[0] == 0){
// ReadSensors();
// setPWM_leftmotor (80);
// setPWM_rightmotor (135);
// TurnLeft();
// }
Stop ();
delay_ms (500);
}
//=================================
//=====PID CONTROLLER=====
void PID_program()
{
Error(er_pt);
totalError += error; // Accumulate error for integral
if (isnan(totalError)){
totalError = 0;
}
power = ((Kp*error) + (Kd*(error-previousError)) + (Ki*totalError));//*(1*error) + (Ki*totalError));
previousError = error; // save previous error for differential
if( power>255 ) { power = 255; }
if( power<-255 ) { power = -255; }
if(power<0) // Turn left
{
setPWM_rightmotor(105);
setPWM_leftmotor(57 - abs(int(power)));
}
else // Turn right
{
setPWM_rightmotor(105 - int(power));
setPWM_leftmotor(57);
}
Serial.print ("Error: ");
Serial.print (error);
Serial.print (" TotalError: ");
Serial.print (totalError);
Serial.print (" Power: ");
Serial.print (power);
Serial.print (" PWM Right: ");
Serial.print (OCR0A);
Serial.print (" PWM Left: ");
Serial.print (OCR0B);
Serial.print (" ");
}
void ID_program()
{
Error(er_pt);
// if(isnan(error)){
// error = 0;
// }
totalError += error; // Accumulate error for integral
if (isnan(totalError)){
totalError = 0;
}
power = (1*error) + (Ki*totalError);
previousError = error; // save previous error for differential
if( power>255 ) { power = 255; }
if( power<-255 ) { power = -255; }
if(power<0) // Turn left
{
setPWM_rightmotor(135);
setPWM_leftmotor(80 - abs(int(power)));
}
else // Turn right
{
setPWM_rightmotor(135 - int(power));
setPWM_leftmotor(80);
}
}
void Error(float *error) {
for(int i=0; i<=4; i++)
{
if(sensor[i]==1) {
activeSensor+=1;
}
totalSensor += sensor[i] * (i+1);
}
avgSensor = totalSensor/activeSensor;
*error = (avgSensor - 3);
activeSensor = 0; totalSensor = 0;
}
////##################################################
////=====CONTROL ROBOT ACCORDING TO OUTPUT FROM SENSORS=====
void RunCase (){
SensorsCondition ();
switch (path[pathReadNumber]){
// GO STRAIGHT
case 'S':
//Situation =0;
SensorsCondition ();
switch (Case){
// GO STRAIGHT
case 'S':
//Situation =0;
Forward ();
PID_program();
//ID_program();
Serial.println ("Straight");
break;
default:
setPWM_leftmotor (150);
setPWM_rightmotor (255);
TurnLeft();
delay_ms(200);
setPWM_leftmotor (180);
setPWM_rightmotor (255);
TurnRight();
delay_ms(380);
Stop ();
delay_ms (500);
Serial.println ("Errors");
break;
}
break;
case 'R':
ReadSensors();
turnRight ();
pathReadNumber += 1;
Serial.println ("Turn Right");
break;
case 'L': // Left
ReadSensors ();
turnLeft ();
pathReadNumber += 1;
Serial.println ("Turn Left");
break;
}
}
//##################################################
//=================================
//=====MAIN PROGRAM=====
void setup() {
path[0] = 'S';
path[1] = 'S';
path[2] = 'S';
path[3] = 'L';
path[4] = 'S';
path[5] = 'S';
path[6] = 'S';
path[7] = 'S';
path[8] = 'R';
path[9] = 'S';
path[10] = 'S';
path[11] = 'L';
path[12] = 'S';
path[13] = 'L';
path[14] = 'S';
path[15] = 'S';
path[16] = 'S';
path[17] = 'L';
path[18] = 'S';
path[19] = 'L';
//###################
//General
Serial.begin(9600);
SPI.begin();
// //####################
//ESP
ConnectToWiFi ();
client.setServer (mqttServer, 1883);
client.setCallback (callback);
// //####################
//RFID
mfrc522.PCD_Init();
mfrc522.PCD_SetAntennaGain(0b01110000);
//RobotInfor();
// //###################
DDRD |= (1 << 7) | (1 << 6)| (1 << 5)| (1 << 4)| (1 << 3); //set pin 3 OUPUT (motor) and pin 2-4-5-6-7 INPUT (sensors)
DDRB |= (1 << 7) | (1 << 6)| (1 << 5)| (1 << 4)| (1 << 3)| (1 << 0); //set pins 8-9-10-11-12 OUTPUT (motors)
TCCR0A = 0;
TCCR0B = 0;
//reset 2 registers
TCCR0A |= (1 << WGM21) | (1 << WGM20); //mode fast PWM
TCCR0B |= (1 << CS22) | (1 << CS20);
//prescaler= 128
TCCR0A |= (1 << COM2B1); //(PD3) (pin 3) ( none-inverting)
TCCR0A |= (1 << COM2A1); //(PB3) (pin 11) ( none-inverting)
OCR0B = 255; //(PD3) (pin 3) motor left
OCR0A = 255; //(PB3) (pin 11) motor right
PORTD |= (1<<5) | (1<<6);
}
void loop() {
RunCase ();
Serial.print("current pathReadNumber: ");
Serial.println (pathReadNumber);
if (!client.connected()) {
reconnect();
client.subscribe ("System", 0);
}
client.loop();
if ( ! mfrc522.PICC_IsNewCardPresent()) {
return;
}
if ( ! mfrc522.PICC_ReadCardSerial()) {
return;
}
//RFIDCard();
Serial.println ("#################################");
RFIDCard();
RobotInfor();
mqttPublish();
Stop();
delay_ms (500);
pathReadNumber += 1;
Serial.println ("#################################");
return;
}
//void loop () {
// setPWM_leftmotor (57);
// setPWM_rightmotor (105);
// Forward();
//// delay_ms(453);
//// Stop();delay_ms(300);
//// ReadSensors();
//// TestCodeMotor ();
//}
void TestCodeMotor (){
// BASIC MOVING FUNCTION AND PWM TESTING
Forward ();
Serial.println ("Forward");
delay_ms (5000);
Backward ();
Serial.println ("Backward");
delay_ms (1000);
TurnLeft ();
Serial.println ("Left");
delay_ms (300);
Forward ();
Serial.println ("Forward");
delay_ms (5000);
TurnRight ();
Serial.println ("Right");
delay_ms (300);
Forward ();
Serial.println ("Forward");
delay_ms (5000);
Stop ();
Serial.println ("Stop");
delay_ms (1000);
for (int a = 0; a <= 255; a+=5){
setPWM_leftmotor (a);
Forward ();
Serial.println ("PWM Left");
delay_ms (100);
}
for (int a = 0; a <= 255; a+=5){
setPWM_rightmotor (a);
Backward ();
Serial.println ("PWM Right");
delay_ms (100);
}
}
|
8c219d7e7cee6e7b85fec9110479a988ed58e166
|
4b19135464a032c1d5271cd1ae58afb21df38584
|
/Samples/C++/DirectShow/VMR9/MultiVMR9/GamePlayer/GamePlayer.cpp
|
207505b2c463eb7ac168dc3350ab94c44af8bbc3
|
[] |
no_license
|
sjk7/DX90SDK
|
f47cebbba53133923880004bc6e3a33cff1fe895
|
dd155425badb2cd3993c27f869efc007764e599b
|
refs/heads/master
| 2021-08-26T07:47:03.826451
| 2021-08-12T05:03:03
| 2021-08-12T05:03:03
| 253,911,891
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,012
|
cpp
|
GamePlayer.cpp
|
//------------------------------------------------------------------------------
// File: GamePlayer.cpp
//
// Desc: DirectShow sample code - MultiVMR9 GamePlayer
// Defines the class behaviors for the application
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
#include "stdafx.h"
#include "GamePlayer.h"
#include "StartDialog.h"
#include "dxutil.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
HINSTANCE g_hInstance = NULL;
// CGamePlayerApp
BEGIN_MESSAGE_MAP(CGamePlayerApp, CWinApp)
ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()
// CGamePlayerApp construction
CGamePlayerApp::CGamePlayerApp()
{
}
// The one and only CGamePlayerApp object
CGamePlayerApp theApp;
//----------------------------------------------------------------------------
// VerifyVMR9
//
// Verifies that VMR9 COM objects exist on the system and that the VMR9
// can be instantiated.
//
// Returns: FALSE if the VMR9 can't be created
//----------------------------------------------------------------------------
BOOL CGamePlayerApp::VerifyVMR9(void)
{
HRESULT hr;
// Verify that the VMR exists on this system
IBaseFilter* pBF = NULL;
hr = CoCreateInstance(CLSID_VideoMixingRenderer9, NULL,
CLSCTX_INPROC,
IID_IBaseFilter,
(LPVOID *)&pBF);
if(SUCCEEDED(hr))
{
pBF->Release();
return TRUE;
}
else
{
MessageBox(NULL,
TEXT("This application requires the Video Mixing Renderer, which is present\r\n")
TEXT("only on DirectX 9 systems with hardware video acceleration enabled.\r\n\r\n")
TEXT("The Video Mixing Renderer (VMR9) is not enabled when viewing a \r\n")
TEXT("remote Windows XP machine through a Remote Desktop session.\r\n")
TEXT("You can run VMR-enabled applications only on your local machine.\r\n\r\n")
TEXT("To verify that hardware acceleration is enabled on a Windows XP\r\n")
TEXT("system, follow these steps:\r\n")
TEXT("-----------------------------------------------------------------------\r\n")
TEXT(" - Open 'Display Properties' in the Control Panel\r\n")
TEXT(" - Click the 'Settings' tab\r\n")
TEXT(" - Click on the 'Advanced' button at the bottom of the page\r\n")
TEXT(" - Click on the 'Troubleshooting' tab in the window that appears\r\n")
TEXT(" - Verify that the 'Hardware Acceleration' slider is at the rightmost position\r\n")
TEXT("\r\nThis sample will now exit."),
TEXT("Video Mixing Renderer (VMR9) capabilities are required"), MB_OK);
return FALSE;
}
}
// CGamePlayerApp initialization
BOOL CGamePlayerApp::InitInstance()
{
// InitCommonControls() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
InitCommonControls();
CWinApp::InitInstance();
g_hInstance = m_hInstance;
HRESULT hr = CoInitialize(NULL);
// Verify that the VMR9 is present on this system
if(!VerifyVMR9())
{
CoUninitialize();
return FALSE;
}
CStartDialog dlg;
m_pMainWnd = &dlg;
dlg.DoModal();
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}
///////////////////////////////////// CGamePlayerSession //////////////////////////
/*********************************************************************************\
* CGamePlayerSession
* constructor
\*********************************************************************************/
CGamePlayerSession::CGamePlayerSession()
: CMultigraphSession()
, m_pMixer( NULL )
, m_pUI( NULL )
{
}
/*********************************************************************************\
* ~CGamePlayerSession
* destructor
\*********************************************************************************/
CGamePlayerSession::~CGamePlayerSession()
{
Terminate();
RELEASE( m_pMixer );
RELEASE( m_pUI );
}
/*********************************************************************************\
* Initialize
* loads and initializes custom mixer control and UI Layer
\*********************************************************************************/
HRESULT CGamePlayerSession::Initialize()
{
HRESULT hr = S_OK;
CComPtr<IMultiVMR9RenderEngine> pRenderEngine;
try
{
if( m_pWizard )
throw VFW_E_WRONG_STATE;
// create wizard
hr = CoCreateInstance( CLSID_MultiVMR9Wizard,
NULL,
CLSCTX_INPROC_SERVER,
IID_IMultiVMR9Wizard,
(void**)&m_pWizard);
CHECK_HR( hr, DbgMsg("CGamePlayerSession::Initialize: Failed to create instance of MultiVMR9Wizard, hr = 0x%08x", hr));
// create render engine
hr = CoCreateInstance( CLSID_MultiVMR9RenderEngine,
NULL,
CLSCTX_INPROC_SERVER,
IID_IMultiVMR9RenderEngine,
(void**)&(pRenderEngine.p));
CHECK_HR( hr, DbgMsg("CGamePlayerSession::Initialize: Failed to create instance of MultiVMR9RenderEngine, hr = 0x%08x", hr));
// create video window
CHECK_HR(
hr = CreateVideoWindow_(800,600,WS_OVERLAPPED|WS_BORDER),
DbgMsg("CGamePlayerSession::Initialize: failed to create video window"));
// create mixer control
m_pMixer = new CGameMixer(NULL, &hr);
CHECK_HR(
FAILED(hr) ? hr : (!m_pMixer ? E_OUTOFMEMORY : S_OK),
DbgMsg("CGamePlayerSession::Initialize: failed to create custom mixer control"));
m_pMixer->AddRef();
// create UI layer
m_pUI = new CGameUILayer( NULL, &hr);
CHECK_HR(
FAILED(hr) ? hr : (!m_pUI ? E_OUTOFMEMORY : S_OK),
DbgMsg("CGamePlayerSession::Initialize: failed to create custom UI layer"));
m_pUI->AddRef();
CHECK_HR(
hr = m_pUI->SetMixer( m_pMixer),
DbgMsg("CGamePlayerSession::Initialize: failed to sync mixer and UI layer"));
// initialize render engine with custom mixer control and UI layer
CHECK_HR(
hr = pRenderEngine->Initialize( m_hwndVideo, NULL, m_pMixer, m_pUI),
DbgMsg("CGamePlayerSession::Initialize: failed to initialize customized render engine, hr = 0x%08x", hr));
// initialize wizard with customized render engine
CHECK_HR(
hr = m_pWizard->Initialize(NULL, m_hwndVideo, pRenderEngine),
DbgMsg("CMultiPlayerSession::Initialize: failed to initialize the wizard, hr = 0x%08x", hr));
// get interfaces
CHECK_HR(
hr = m_pWizard->GetRenderEngine( &m_pRenderEngine),
DbgMsg("CMultiPlayerSession::Initialize: failed to get Render Engine, hr = 0x%08x", hr));
CHECK_HR(
hr = m_pRenderEngine->GetMixerControl( &m_pMixerControl),
DbgMsg("CMultiPlayerSession::Initialize: failed to get Mixer Control, hr = 0x%08x", hr));
CHECK_HR(
hr = m_pRenderEngine->GetUILayer( &m_pUILayer),
DbgMsg("CMultiPlayerSession::Initialize: failed to get UILayer, hr = 0x%08x", hr));
CHECK_HR(
hr = m_pRenderEngine->SetFrameRate( 5000 ),
DbgMsg("CMultiPlayerSession::Initialize: failed to set frame rate, hr = 0x%08x", hr));
::ShowWindow( m_hwndVideo, SW_SHOW);
}
catch( HRESULT hr1 )
{
if( pRenderEngine )
{
pRenderEngine->Terminate();
}
hr = hr1;
}
return hr;
}
/*********************************************************************************\
* Terminate
*
\*********************************************************************************/
HRESULT CGamePlayerSession::Terminate()
{
HRESULT hr = S_OK;
hr = CMultigraphSession::Terminate();
return hr;
}
/*********************************************************************************\
* FindMediaFile
* Searches for a media file in (a) current directory, (b) DirectX SDK media folder,
* (c) resources
\*********************************************************************************/
HRESULT FindMediaFile( TCHAR* achPath,
DWORD size,
TCHAR* achShortName,
LPCTSTR lpResourceName,
LPCTSTR lpResourceType )
{
HRESULT hr = S_OK;
TCHAR achTempPath[MAX_PATH];
bool bSuccess = false;
HANDLE hFile = NULL;
HRSRC hRsrc = NULL;
HGLOBAL hResMem = NULL;
HBITMAP hBitmap = NULL;
DWORD dwSize = 0L;
LPVOID pData = NULL;
CBitmap* pBitmap = NULL;
BITMAP bitmap;
BITMAPINFOHEADER bmpHdr;
BITMAPFILEHEADER bmpFHdr;
DWORD dwWritten = 0L;
if( !achPath || !achShortName || !lpResourceName )
{
return E_POINTER;
}
// first, try current directory
GetCurrentDirectory( MAX_PATH, achTempPath );
_tcsncat( achTempPath, TEXT("\\"), MAX_PATH);
_tcsncat( achTempPath, achShortName, MAX_PATH);
if( INVALID_FILE_ATTRIBUTES != ::GetFileAttributes( achTempPath ))
{
// file is in the current folder
if( size < _tcslen( achTempPath ))
return E_OUTOFMEMORY;
_tcsncpy( achPath, achTempPath, size );
return S_OK;
}
// second, try DXSDK media folder
hr = DXUtil_FindMediaFileCb( achTempPath, sizeof(TCHAR) * MAX_PATH, (TCHAR*)achShortName );
if( S_OK == hr )
{
if( INVALID_FILE_ATTRIBUTES != ::GetFileAttributes( achTempPath ))
{
// file is in the DXSDK media folder
if( size < _tcslen( achTempPath ))
return E_OUTOFMEMORY;
_tcsncpy( achPath, achTempPath, size );
return S_OK;
}
}
// create specified file in the current directory
GetCurrentDirectory( MAX_PATH, achTempPath );
_tcsncat( achTempPath, TEXT("\\"), MAX_PATH);
_tcsncat( achTempPath, achShortName, MAX_PATH);
hFile = ::CreateFile( achTempPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if( INVALID_HANDLE_VALUE == hFile )
{
return E_FAIL;
}
// third, try to load it from the resource
hRsrc = FindResource( AfxGetInstanceHandle(), lpResourceName, lpResourceType);
if( NULL != hRsrc )
{
// if the resource is a bitmap
if( lpResourceType == RT_BITMAP )
{
hBitmap = LoadBitmap( AfxGetInstanceHandle(), lpResourceName);
if( hBitmap )
{
pBitmap = CBitmap::FromHandle( hBitmap );
pBitmap->GetBitmap( &bitmap );
ZeroMemory( &bmpHdr, sizeof(BITMAPINFOHEADER));
bmpHdr.biSize = sizeof(BITMAPINFOHEADER);
bmpHdr.biWidth = bitmap.bmWidth;
bmpHdr.biHeight = -bitmap.bmHeight;
bmpHdr.biPlanes = bitmap.bmPlanes;
bmpHdr.biBitCount = bitmap.bmBitsPixel;
bmpHdr.biCompression = bitmap.bmType;
bmpHdr.biSizeImage = bitmap.bmHeight * bitmap.bmWidthBytes;
pData = malloc(bmpHdr.biSizeImage);
pBitmap->GetBitmapBits( bmpHdr.biSizeImage, pData );
bmpFHdr.bfType = static_cast<WORD>(L'B'|(L'M'<<8));
bmpFHdr.bfSize = 14 + sizeof(BITMAPINFOHEADER) + bmpHdr.biSizeImage;
bmpFHdr.bfOffBits = 14 + bmpHdr.biSize;
bmpFHdr.bfReserved1 = 0;
bmpFHdr.bfReserved2 = 0;
if( TRUE == WriteFile(hFile, static_cast<LPVOID>(&bmpFHdr), 14, &dwWritten, NULL) )
{
if( TRUE == WriteFile(hFile, static_cast<LPVOID>(&bmpHdr), bmpHdr.biSize, &dwWritten, NULL))
{
if( TRUE == WriteFile(hFile, static_cast<LPVOID>(pData), bmpHdr.biSizeImage, &dwWritten, NULL))
{
bSuccess = true;
}
}
}
free( pData );
pData = NULL;
}
}
else // consider it a raw data
{
// ::MessageBox(NULL, TEXT("Cannot find mesh file for the character. Make sure you have DirectX SDK installed"), TEXT("GamePlayer"), MB_OK);
/*
hResMem = ::LoadResource( AfxGetInstanceHandle(), hRsrc );
if( NULL != hResMem )
{
dwSize = ::SizeofResource( AfxGetInstanceHandle(), hRsrc);
pData = ::LockResource( hResMem );
if( pData )
{
if( TRUE == ::WriteFile( hFile, pData, dwSize, &dwWritten, NULL))
{
bSuccess = true;
}
}
}*/
}
}
CloseHandle( hFile );
if( false == bSuccess )
{
return E_FAIL;
}
if( size < _tcslen( achTempPath ))
return E_OUTOFMEMORY;
_tcsncpy( achPath, achTempPath, size );
return S_OK;
}
/*********************************************************************************\
* DbgMsg
* debug tracing function
\*********************************************************************************/
#ifdef _DEBUG
void DbgMsg( char* szMessage, ... )
{
char szFullMessage[MAX_PATH];
char szFormatMessage[MAX_PATH];
DWORD dwWritten = 0L;
// format message
va_list ap;
va_start(ap, szMessage);
_vsnprintf( szFormatMessage, MAX_PATH, szMessage, ap);
va_end(ap);
strncat( szFormatMessage, "\n", MAX_PATH);
strcpy( szFullMessage, "~*~*~*~*~*~ ");
strcat( szFullMessage, szFormatMessage );
OutputDebugStringA( szFullMessage );
/*
if( INVALID_HANDLE_VALUE != g_hLog )
{
WriteFile( g_hLog, (LPVOID)szFullMessage, (DWORD)strlen(szFullMessage), &dwWritten, NULL);
FlushFileBuffers( g_hLog);
}
*/
}
#else
void DbgMsg( char* szMessage, ... ){;}
#endif
|
72c2bffd7167424fc4c8b320abc70a2a836d41ec
|
83238ef961922b5200834d3c3368921bff7cba61
|
/Week 4/Maximal Square.cpp
|
37fed5ec317bb4e73daf312d92af3a999bfdfaa0
|
[] |
no_license
|
saidrishya/30-Days-Leetcode-Challenge
|
76c809f506ae2297e7cfb765606cdedc286374c3
|
2c08a18036cef850ff27e6b406eb59a81cc372dc
|
refs/heads/master
| 2023-01-06T00:14:29.396191
| 2020-11-02T02:06:46
| 2020-11-02T02:06:46
| 260,265,182
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 679
|
cpp
|
Maximal Square.cpp
|
class Solution {
public:
int maximalSquare(vector<vector<char>>& matrix) {
int row = matrix.size();
if(row == 0 || matrix[0].empty()) return 0;
int col = matrix[0].size();
vector<vector<int>> dp(row, vector<int>(col));
int ans=0;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
if(matrix[i][j] == '1'){
dp[i][j] = 1;
if(i>0 && j>0){
dp[i][j] += min({dp[i-1][j] , dp[i][j-1], dp[i-1][j-1]});
}
ans = max(ans, dp[i][j]);
}
}
}
return ans*ans;
}
};
|
29c9ebe17ce851d97ebb1cab24e9dd199ac3f2b5
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/components/media_router/common/pref_names.cc
|
1d2b1bfd505ae803b655b84aa75714360ae23ed7
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 1,111
|
cc
|
pref_names.cc
|
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/media_router/common/pref_names.h"
namespace media_router {
namespace prefs {
// Whether the enterprise policy allows Cast devices on all IPs.
const char kMediaRouterCastAllowAllIPs[] = "media_router.cast_allow_all_ips";
// Whether or not the user has enabled Media Remoting. Defaults to true.
const char kMediaRouterMediaRemotingEnabled[] =
"media_router.media_remoting.enabled";
// The per-profile randomly generated token to include with the hash when
// externalizing MediaSink IDs.
const char kMediaRouterReceiverIdHashToken[] =
"media_router.receiver_id_hash_token";
// Whether or not the user has enabled to show Cast sessions started by
// other devices on the same network. This change only affects the Zenith
// dialog. Defaults to true.
const char kMediaRouterShowCastSessionsStartedByOtherDevices[] =
"media_router.show_cast_sessions_started_by_other_devices.enabled";
} // namespace prefs
} // namespace media_router
|
f4ef81332b5fb6dd460e44dfbc1981bf094fccc0
|
6f78b867ba12798230f896a16a85ee432e4fb963
|
/HW/firmware/_2-TMP/_2-TMP.ino
|
0e05c6225a497274321a2e1451fde01297647a77
|
[] |
no_license
|
JTrillo/TFG
|
0f71fbb87af9dd384c4482088a4ceec523d5df7b
|
93aa60e96229efc7f260f361e211ab00c8ffdf0f
|
refs/heads/master
| 2020-12-03T17:59:20.862441
| 2020-01-02T20:55:52
| 2020-01-02T20:55:52
| 231,420,273
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,644
|
ino
|
_2-TMP.ino
|
#include <LiquidCrystal.h>
#define RS 12
#define E 11
#define D4 2
#define D5 3
#define D6 4
#define D7 5
#define S_TEMP A0
unsigned curr_ms;
LiquidCrystal lcd(RS,E,D4,D5,D6,D7);
struct Sensor {
byte pin;
unsigned long periodo_ms;
unsigned long last_ms;
float valor;
int cont;
float suma;
};
void setup_sensor(struct Sensor * s, byte pin, unsigned long per, unsigned long ms){
s->pin=pin;
s->periodo_ms=per;
s->last_ms=ms;
s->cont=0;
s->suma=0.0;
}
void loop_sensor(struct Sensor * s, unsigned long ms){
int lectura = analogRead(s->pin);
float volt = (lectura / 1024.0) * 5.0;
s->suma = s->suma + ((volt - 0.5) * 100.0);
s->cont = s->cont + 1;
if(ms-s->last_ms>=s->periodo_ms){
s->valor = s->suma / (float)s->cont;
s->cont=0;
s->suma=0.0;
s->last_ms=ms;
}
}
struct Monitor{
unsigned long periodo_ms;
unsigned long last_ms;
};
void setup_monitor(struct Monitor * m, unsigned long per, unsigned long ms){
m->periodo_ms=per;
m->last_ms=ms;
}
void loop_monitor(struct Monitor * m, const struct Sensor * temp, unsigned long ms){
if(ms-m->last_ms>=m->periodo_ms){
m->last_ms=ms;
lcd.clear();
lcd.print("Temp. actual:");
lcd.setCursor(0,1);
lcd.print(temp->valor);
lcd.print(" C");
}
}
struct Sensor temp;
struct Monitor mnt;
void setup() {
lcd.begin(16,2);
lcd.print("Pruebas LCD:");
lcd.setCursor(0,1);
lcd.print("Prueba 2");
delay(3500);
curr_ms=millis();
setup_sensor(&temp, S_TEMP, 3000, curr_ms);
setup_monitor(&mnt, 5000, curr_ms);
}
void loop() {
curr_ms=millis();
loop_sensor(&temp, curr_ms);
loop_monitor(&mnt, &temp, curr_ms);
}
|
8b0b85088a4f2a12bd7810027cd4219b5c7932aa
|
b7a3e07cd399fc608951bcd2c2438272d926ae33
|
/第k轮选择排序.cpp
|
21397c9ec182b27fde6f590edd76dff732428cff
|
[] |
no_license
|
JackYifan/Learning-Code
|
327840389f3b48fce10009c247acb2a2e34e321f
|
c2a994014018b89b1b30262dd3681cbe67b915c1
|
refs/heads/main
| 2022-12-19T21:26:42.173148
| 2020-10-05T14:12:19
| 2020-10-05T14:12:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 465
|
cpp
|
第k轮选择排序.cpp
|
#include<stdio.h>
int main()
{
int n,k;
scanf("%d %d",&n,&k);
int a[100];
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(int i=0;i<k+1;i++)
{
int index=i;
for(int j=i+1;j<n;j++)
{
if(a[j]<a[index]) index=j;
}
int temp=a[i];
a[i]=a[index];
a[index]=temp;
}
for(int i=0;i<n;i++)
{
printf("%d",a[i]);
if(i<n-1) printf(" ");
}
}
|
5a605c4a4cd07e2697c0b2708bad81e51e8e704d
|
b5d7e814aac471eeabc6a0d23c74e5154e793f93
|
/C++/C++视频课程练习/常对象成员和常对象函数/常对象成员和常对象函数/Line.h
|
ce2e4969ebbfcbde779606252c1da512ab29aec2
|
[] |
no_license
|
SelmerZhang/Code
|
b4064758c141c0c9db112b97a55986f52fac998a
|
84fb3245f12177e7294523dfea2938933ae9e813
|
refs/heads/master
| 2022-11-17T00:04:55.380889
| 2018-06-09T12:07:47
| 2018-06-09T12:07:47
| 138,289,233
| 0
| 1
| null | 2022-11-04T14:54:45
| 2018-06-22T10:23:03
|
Python
|
UTF-8
|
C++
| false
| false
| 222
|
h
|
Line.h
|
#include"Coordinate.h"
class Line
{
public:
Line(int x1,int y1,int x2,int y2);
~Line();
void setA(int x, int y);
void setB(int x, int y);
void printInfo();
private:
Coordinate *m_coorA;
Coordinate *m_coorB;
};
|
709bc06996e430acd216867479a192b88e1056d9
|
972a33289ceb2591b663e5e322481e482ecfb80a
|
/Pong/src/Utilities/ShaderBuilder.cpp
|
ce99c3828a166182cb46e5f01fac8f9b78071fbb
|
[] |
no_license
|
AlessandroRavaglia6/PongSolo
|
7457bcf13bf5712745778cc99307b5fe137e3b64
|
393f1a5f1d2b689bffc24a15128aab2710acb742
|
refs/heads/master
| 2023-06-24T18:01:08.977343
| 2023-06-17T11:42:22
| 2023-06-17T11:42:22
| 284,456,857
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,177
|
cpp
|
ShaderBuilder.cpp
|
#include "ShaderBuilder.h"
#include "../PreprocessorSettings.h"
#include "FileReader.h"
#include <vector>
ShaderBuilder::ShaderBuilder() : _shaderType(0), _shaderSourceCode(nullptr), _sourceCode(nullptr), _numLines(0) {}
ShaderBuilder& ShaderBuilder::AddShaderType(ShaderType shaderType)
{
_shaderType = shaderType;
return *this;
}
ShaderBuilder& ShaderBuilder::AddShaderSourceCode(const std::string& fileName)
{
FileReader fileReader(fileName);
_shaderSourceCode = new char[fileReader.GetFileLenght() + 1]();
std::vector<GLchar*> pointers{};
pointers.push_back(_shaderSourceCode);
for (int i = 0; i < fileReader.GetFileLenght(); ++i)
{
fileReader >> _shaderSourceCode[i];
if (_shaderSourceCode[i] == '\r')
{
_shaderSourceCode[i] = '\n';
}
else if (_shaderSourceCode[i] == '\n')
{
++_numLines;
_shaderSourceCode[i] = '\0';
pointers.push_back((&_shaderSourceCode[i]) + 1);
}
}
++_numLines;
_shaderSourceCode[fileReader.GetFileLenght()] = '\0';
_sourceCode = new char*[_numLines]();
for (int i = 0; i < _numLines; ++i)
{
_sourceCode[i] = pointers[i];
}
return *this;
}
ShaderBuilder& ShaderBuilder::AddShaderSourceCode(std::string&& fileName)
{
FileReader fileReader(fileName);
_shaderSourceCode = new char[fileReader.GetFileLenght() + 1]();
std::vector<GLchar*> pointers{};
pointers.push_back(_shaderSourceCode);
for (int i = 0; i < fileReader.GetFileLenght(); ++i)
{
fileReader >> _shaderSourceCode[i];
if (_shaderSourceCode[i] == '\r')
{
_shaderSourceCode[i] = '\n';
}
else if (_shaderSourceCode[i] == '\n')
{
++_numLines;
_shaderSourceCode[i] = '\0';
pointers.push_back((&_shaderSourceCode[i]) + 1);
}
}
++_numLines;
_shaderSourceCode[fileReader.GetFileLenght()] = '\0';
_sourceCode = new char*[_numLines]();
for (int i = 0; i < _numLines; ++i)
{
_sourceCode[i] = pointers[i];
}
return *this;
}
Shader ShaderBuilder::BuildShader()
{
Shader out{ _shaderType, _sourceCode, _numLines };
delete[](_shaderSourceCode); _shaderSourceCode = nullptr;
delete[](_sourceCode); _sourceCode = nullptr;
_shaderType = 0;
_numLines = 0;
return static_cast<Shader&&>(out);
}
|
ab83482c7477c8e01cf933ea01a599ab3b9519df
|
3c8cf4de6c08e21b2c10094ef20488e93d7a34be
|
/TktkGameProcessDxlibAppendLib/TktkAppendDxlib2DComponentLib/inc/TktkAppendDxlib2DComponent/Graphics/Figure/Polygon2DDrawer.h
|
39a4efd16eaf30b2cc0f5c25980d8a330a00b917
|
[] |
no_license
|
tktk2104/TktkLib
|
07762028c8a3a7378d7e82be8f1ed8c6a0cdc97c
|
2af549bfb8448ace9f9fee6c2225ea7d2e6329b8
|
refs/heads/master
| 2022-11-30T12:26:33.290941
| 2020-08-11T17:50:14
| 2020-08-11T17:50:14
| 213,307,835
| 0
| 0
| null | null | null | null |
SHIFT_JIS
|
C++
| false
| false
| 3,191
|
h
|
Polygon2DDrawer.h
|
#ifndef POLYGON_2D_DRAWER_H_
#define POLYGON_2D_DRAWER_H_
#include <vector>
#include <TktkMath/Color.h>
#include <TktkMath/Vector2.h>
#include <TktkClassFuncProcessor/ProcessingClass/CfpPtr.h>
#include <TktkComponentFramework/Component/ComponentBase.h>
#include <TktkAppend2DComponent/Transform2D.h>
#include "../../../TktkDxlib2DWrapper/Graphics/BlendMode.h"
namespace tktk
{
// 2次元ポリゴンを描画するコンポーネント
// 【前提コンポーネント:Transform2D】
class Polygon2DDrawer
: public ComponentBase
{
public:
Polygon2DDrawer(
const std::vector<Vector2>& vertexs,
float lineThickness,
bool isFill,
const Color& polygonColor,
float drawPriority,
BlendMode blendMode,
float blendParam
);
public:
// <PolymorphismFunc>
void start();
void draw() const;
private:
void drawPolygon2D() const;
void drawPolygon2DFlame() const;
public:
// ポリゴンを形成する頂点の配列を取得(時計回り)
const std::vector<Vector2>& getVertexs() const;
// ポリゴンを形成する頂点の配列を再設定(時計回り)
void setVertexs(const std::vector<Vector2>& vertexs);
// ポリゴンを形成する頂点の配列を再設定(時計回り)
template<class... Args>
void setVertexs(Args... vertexs);
// 真円の線の太さを取得
float getLineThickness() const;
// 真円の線の太さを再設定
void setLineThickness(float lineThickness);
// 塗りつぶしフラグを取得
bool getIsFill() const;
// 塗りつぶしフラグを再設定
void setIsFill(bool isFill);
// ポリゴンの描画色を取得
const Color& getPolygonColor() const;
// ポリゴンの描画色を再設定
void setPolygonColor(const Color& polygonColor);
// 描画のブレンド方法の種類を取得
BlendMode getBlendMode() const;
// 描画のブレンド方法の種類を再設定
void setBlendMode(BlendMode blendMode);
// 描画のブレンドに使用する値を取得
float getBlendParam() const;
// 描画のブレンドに使用する値を再設定
void setBlendParam(float blendParam);
// 指定したレンダーターゲットに描画する
void useRenderTarget(int renderTargetId);
// レンダーターゲットを使用せずに描画する
void unUseRenderTarget();
private:
// 自身の2次元座標コンポーネント
CfpPtr<Transform2D> m_transform2D;
// ポリゴンを形成する頂点の配列(時計回り)
std::vector<Vector2> m_vertexs;
// ポリゴンの線の太さ
float m_lineThickness;
// 塗りつぶしフラグ
bool m_isFill;
// ポリゴンの描画色
Color m_polygonColor;
// 描画のブレンド方法の種類
BlendMode m_blendMode;
// 描画のブレンドに使用する値
float m_blendParam;
// レンダーターゲットに描画するか
bool m_useRenderTarget{ false };
// 描画するレンダーターゲットのId
int m_renderTargetId{ -1 };
};
template<class ...Args>
inline void Polygon2DDrawer::setVertexs(Args ...vertexs)
{
setVertexs(std::vector<Vector2>({ vertexs... }));
}
}
#endif // !POLYGON_2D_DRAWER_H_
|
4695cf8e165e621a86e551360b810cfc69df2ea6
|
5063e835b777523f6f92b290b5179198244b0c2b
|
/3 глава/10 з/10 з/10 з.cpp
|
34042e276332f8628b8374c53994dfe8fa62d49f
|
[] |
no_license
|
NikitaAS-56/Lafore
|
9e74a6aed5b67fb496676ec5687f09ae9753d3e4
|
958a78c15106fac706c6926ca9696afd8d38243a
|
refs/heads/main
| 2023-02-14T04:27:16.964909
| 2021-01-10T13:53:19
| 2021-01-10T13:53:19
| 315,608,322
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 537
|
cpp
|
10 з.cpp
|
#include <iostream>
using namespace std;
int main()
{
setlocale(0, "");
bool k;
float vklad;
float summ;
float prc;
int let = 0;
cout << " сумма вклада ";
cin >> vklad;
cout << " запрашиваемая сумма = ";
cin >> summ;
cout << "процентная ставка = ";
cin >> prc;
do
{
if (vklad > summ){
k = false;
}
vklad += (prc/100 * vklad);
let++;
} while (k==true);
cout << "через "<<let<<" на счете будет сумма "<<summ;
return 0;
}
|
4c1f47844c6d94a474ade8b5ffe440101d299f00
|
81f48e10228a87d8f7c950f704e68718af35c235
|
/addressbook.h
|
e46f4a6fc5433c2a170c09a657e9d74d27a6a3f7
|
[] |
no_license
|
1569870359/test
|
3b26844266ac2125b9f2bf317cc7ed1f674fc2bd
|
650a84c44dc7ca42b733b07505595eeadce6a08f
|
refs/heads/main
| 2023-06-05T07:18:31.145167
| 2021-06-22T08:13:49
| 2021-06-22T08:13:49
| 379,171,859
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,447
|
h
|
addressbook.h
|
#ifndef ADDRESSBOOK_H
#define ADDRESSBOOK_H
#include <QWidget>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QLineEdit>
#include <QTextEdit>
#include <QString>
#include <QMap>
#include "finddialog.h"
namespace Ui {
class addressbook;
}
class addressbook : public QWidget
{
Q_OBJECT
public:
explicit addressbook(QWidget *parent = 0);
~addressbook();
enum Mode { NavigationMode, AddingMode, EditingMode };
public slots:
void add();
void submit();
void cancel();
void edit();
void remove();
void find();
void load();
void save();
void previous();
void next();
private:
Ui::addressbook *ui;
void updateInterface(Mode mode);
QPushButton *AddBtn;
QPushButton *EditBtn;
QPushButton *RemoveBtn;
QPushButton *FindBtn;
QPushButton *SubmitBtn;
QPushButton *CancelBtn;
QPushButton *LoadBtn;
QPushButton *SaveBtn;
QPushButton *PreviousBtn;
QPushButton *NextBtn;
QVBoxLayout *m_vLayout;
QHBoxLayout *m_hLayout;
QGridLayout *m_gLayout;
QLabel *Name;
QLabel *Address;
QLineEdit *nameLine;
QTextEdit *addressText;
QString oldName;
QString oldAddress;
QMap<QString, QString> contacts;
Mode currentMode;
FindDialog *dialog;
};
#endif // ADDRESSBOOK_H
|
c2cee9b3d1379b7b7b2f019cc511d6b5efc50615
|
99fafa682d2d596422092f259c6ba755fd07851e
|
/include/optimization/LoopSearch.hpp
|
2a1638b69496eb2e1bbf66ee966e28c20fd4be3a
|
[] |
no_license
|
XiaoYaoYouUSTC/Cminusf-Compiler
|
b6d8138c49387a7b462329f1ee85c7556655db7e
|
f43b0d23fcc6fec5315c1f1287a3f8c31b1aab1e
|
refs/heads/main
| 2023-06-25T00:14:43.411377
| 2023-06-14T03:24:34
| 2023-06-14T03:24:34
| 336,243,041
| 44
| 19
| null | 2023-06-14T03:24:35
| 2021-02-05T10:48:21
|
C++
|
UTF-8
|
C++
| false
| false
| 2,229
|
hpp
|
LoopSearch.hpp
|
#ifndef LOOPSEARCH_HPP
#define LOOPSEARCH_HPP
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include "PassManager.hpp"
#include "Function.h"
#include "BasicBlock.h"
#include <memory>
#include <vector>
struct CFGNode;
using CFGNodePtr = CFGNode*;
using CFGNodePtrSet = std::unordered_set<CFGNode*>;
using BBset_t = std::unordered_set<BasicBlock *>;
class LoopSearch : public Pass{
public:
explicit LoopSearch(Module* m, bool dump=false) : Pass(m), dump(dump){}
~LoopSearch() = default;
void build_cfg(Function *func,std::unordered_set<CFGNode *> &result);
void run() override;
bool strongly_connected_components(
CFGNodePtrSet &nodes,
std::unordered_set<CFGNodePtrSet *> &result
);
void dump_graph(CFGNodePtrSet& nodes,std::string title);
void traverse(
CFGNodePtr n,
std::unordered_set<CFGNodePtrSet *> &result);
CFGNodePtr find_loop_base(
CFGNodePtrSet *set,
CFGNodePtrSet &reserved);
// 利用iterator来遍历所有的loop
auto begin(){ return loop_set.begin();}
auto end(){ return loop_set.end(); }
BasicBlock* get_loop_base(BBset_t *loop) { return loop2base[loop]; }
// 得到bb所在最低层次的loop
BBset_t *get_inner_loop(BasicBlock* bb){
if(bb2base.find(bb) == bb2base.end())
return nullptr;
return base2loop[bb2base[bb]];
}
// 得到输入loop的外一层的循环,如果没有则返回空
BBset_t *get_parent_loop(BBset_t *loop);
// 得到函数 f 里的所有循环
std::unordered_set<BBset_t *> get_loops_in_func(Function *f);
private:
int index_count;
bool dump;
std::vector<CFGNodePtr> stack;
// loops found
std::unordered_set<BBset_t *> loop_set;
// loops found in a function
std::unordered_map<Function *, std::unordered_set<BBset_t *>> func2loop;
// { entry bb of loop : loop }
std::unordered_map<BasicBlock *, BBset_t *> base2loop;
// { loop : entry bb of loop }
std::unordered_map<BBset_t *, BasicBlock *> loop2base;
// { bb : entry bb of loop} 默认最低层次的loop
std::unordered_map<BasicBlock *, BasicBlock *> bb2base;
};
#endif
|
2297ff9b857009ebe05062c348eb548254834d59
|
1aecb09f0284b06317dab1be7abf554ed80680ae
|
/BvRenderGL/BvDebugReportGl.h
|
2826e57d5bafe0e65a91110d4a741d56691c4430
|
[] |
no_license
|
brunovergilio/BDeV-Engine
|
6b22fb533c48112453bed2a836dd5ee30ce68eee
|
f56c41633d55787c94742a4132cc5d6238635d68
|
refs/heads/master
| 2023-08-08T00:30:15.620489
| 2023-07-25T00:52:04
| 2023-07-25T00:52:04
| 208,153,042
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 373
|
h
|
BvDebugReportGl.h
|
#pragma once
#include "BvCommonGl.h"
#include "BDeV/Utils/BvUtils.h"
class BvDebugReportGl
{
BV_NOCOPYMOVE(BvDebugReportGl);
public:
BvDebugReportGl();
~BvDebugReportGl();
void Create();
void Destroy();
private:
static void DebugMessageCallback(GLenum src, GLenum type, GLuint id, GLenum severity, GLsizei length, GLchar const* pMsg, void const* pUserData);
};
|
3612e3dcd43b098ecd31a4baf4b1a1b739372e83
|
c591b56220405b715c1aaa08692023fca61f22d4
|
/Milijolly/Milestone11/M11(Q8).cpp
|
0a2c652d639de7442cf62b3c9ea66ade4fb73e48
|
[] |
no_license
|
Girl-Code-It/Beginner-CPP-Submissions
|
ea99a2bcf8377beecba811d813dafc2593ea0ad9
|
f6c80a2e08e2fe46b2af1164189272019759935b
|
refs/heads/master
| 2022-07-24T22:37:18.878256
| 2021-11-16T04:43:08
| 2021-11-16T04:43:08
| 263,825,293
| 37
| 105
| null | 2023-06-05T09:16:10
| 2020-05-14T05:39:40
|
C++
|
UTF-8
|
C++
| false
| false
| 669
|
cpp
|
M11(Q8).cpp
|
//Write a program to check if elements of an array are same or not it read from front or back.
#include<fstream> // cin, cout and file related functions
#include<iostream>
#include<string.h> // strcmp, strcmpi, strcpy
#include<conio.h>
using namespace std;
int main()
{ int a[10],count=0;
cout<<"Enter 10 intergers "<<endl;
for(int i=0;i<10;i++)
cin>>a[i];
for(int i=0,j=9;i<10,j>=0;i++,j--)
{ if(a[i]==a[j])
count=0;
else
count++;
}
if(count==0)
cout<<"Elements of array are same as reverse "<<endl;
else
cout<<"Elements of array are not same as reverse "<<endl;
getch();
return 0;
}
|
218187b09ca6963b22ab7d0a751a5935055bb3c1
|
00ece3c55b47ada650ac3f22bfd786be269b42ce
|
/tablePipe/pdf_xref.h
|
ab95dbc682170b9466444370f35c288cc484a26a
|
[] |
no_license
|
lonelam/TablePipe
|
81965c09bc2f5a02092141ad68c234690ad447a8
|
0ea2ae8d354c1ebe63161ab16ea63bb61fabed56
|
refs/heads/master
| 2020-03-23T21:29:18.688340
| 2018-07-24T05:50:53
| 2018-07-24T05:50:53
| 142,110,630
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 136
|
h
|
pdf_xref.h
|
#pragma once
#include "stdafx.h"
#include <string>
using std::cout;
using std::string;
void pdf_type(fz_context * ctx, pdf_obj * obj);
|
b25c2f1ba575b0e49a97ec9606ed8330e940ef0a
|
976d89a84253ec7113fb8a5fe2c6daa69346f8fa
|
/Human_riboSNitch_alleles/DMSTrunc/DMSTruncation/DMSTruncation.cpp
|
adf650606fb9e6d8c758518203deb08f4388fa1c
|
[] |
no_license
|
MingleiYang/SLEQ
|
e7b1012f5b18c6814c48fa53cac164e706d80822
|
41701fffe8bbcf78b33d875a70a8c5c2a49e4fce
|
refs/heads/master
| 2021-08-31T11:40:34.609878
| 2017-12-21T07:31:02
| 2017-12-21T07:31:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,969
|
cpp
|
DMSTruncation.cpp
|
// Created by Hua Li
// Copyright © 2016 Hua Li. All rights reserved.
#include "DMSTruncation.hpp"
using namespace std;
using namespace std;
///////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////// Parameter initialization ///////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
string Allele_A = "TGCTGCCATCTCTTTTCTTCTCTATGCGAGGATTTGGACTGGCAGTG";
string Allele_C = "ATCTCTTTTCTTCTCTCTGCGAGGATTTGGACTGGCAGTGAGAATAAGAGACAA";
string CommonSeq = "TTCTTCTCTMTGCGAGGATTTGGACTGGCAGTG";
vector<int>Aidx_AlleleA;//{9,14,17,23,29}
vector<int>Cidx_AlleleA;//{2,5,7,12,24,28}
vector<int>Aidx_AlleleC;//{14,17,23,29}
vector<int>Cidx_AlleleC;//{2,5,7,9,12,24,28}
int RNALenFoldA = 47;
int RNALenFoldC = 54;
int RNALen = 33;
int stOverlapA = 14;
int stOverlapC = 7;
int edOverlapA = 46;
int edOverlapC = 39;
double RhoA = 0.678;
double RhoC = 0.322;
string RNAname = "Allele";
string Folder = "/Users/huali/Desktop/Codes/Human_riboSNitch_alleles/DMSTrunc/"; //!!!!!!!!!!NOTE: Set your own path please.!!!!!!!!!!!!
int main(int argc, const char * argv[]) {
ofstream myfilew;
ifstream myfile;
for(int i = stOverlapA; i<=edOverlapA; ++i)
{
if(Allele_A[i]=='A')
Aidx_AlleleA.push_back(i-stOverlapA);
else if(Allele_A[i]=='C')
Cidx_AlleleA.push_back(i-stOverlapA);
}
for(int i = stOverlapC; i<=edOverlapC; ++i)
{
if(Allele_C[i]=='A')
Aidx_AlleleC.push_back(i-stOverlapC);
else if(Allele_C[i]=='C')
Cidx_AlleleC.push_back(i-stOverlapC);
}
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// INPUT 1 -- READS ///////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
int ReadsNum = 0;
int PatternsNum = 614;//12289;//614;
vector<Pattern>ReadsAC;
myfile.open(Folder+"AlleleReadsAC");
if(myfile)
{
for(int i = 0; i<PatternsNum;++i)
{
char buffer;
Pattern tmp;
for(int j = 0; j<RNALen; ++j)
{
myfile>>buffer;
tmp.pat.push_back(bool(buffer-'0'));
}
myfile>>tmp.count;
ReadsAC.push_back(tmp);
}
}
myfile.close();
//Reduce mutation patterns into truncation patterns
vector<int>ReadsSeq(RNALen+1,0);//complete,5'to3'
for(int i = 0; i<ReadsAC.size(); ++i)
{
int j = (int)ReadsAC[i].pat.size()-1;
for(; j>=0; --j)
if(ReadsAC[i].pat[j]==1)
{
ReadsSeq[j+1] += ReadsAC[i].count;
break;
}
if(j == -1)
ReadsSeq[0] += ReadsAC[i].count;
}
for(int i = 0; i<ReadsSeq.size(); ++i)
ReadsNum += ReadsSeq[i];
////////////////////////////// Downsampling to compare the performance between SEQ and MAP -- Start
// First calculate the frequencies of all patterns from the data
/*
vector<double>Pattern_Freq;
vector<int>ReadCounts;
for(int i = 0; i<ReadsSeq.size();++i)
{
Pattern_Freq.push_back(double(ReadsSeq[i])/double(ReadsNum));
}
//Draw reads according to above frequencies
int ReadsNum_test = 100;
vector<double>RandUnifData(ReadsNum_test,0);
runif(ReadsNum_test,0.0,1.0,RandUnifData);
sort(RandUnifData.begin(),RandUnifData.end());
DrawReadsSEQ(RNALen,ReadsNum_test, RandUnifData,Pattern_Freq, ReadCounts);
//Reput them into ReadsAC
for(int i = 0; i<ReadsSeq.size(); ++i)
{
ReadsSeq[i]= ReadCounts[i];
}
ReadsNum = ReadsNum_test;
*/
////////////////////////////// Downsampling to compare the performance between SEQ and MAP -- end
///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////// INPUT 2 -- CANDIDATE STRUCTURES ///////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//Read dot files of candiate structure of two alleles and remove the duplicates
int SampleSize = 1000;
int FoldsNumA = 0;
int FoldsNumC = 0;
vector<vector<bool>>FoldsA;//from 3' to 5'
vector<vector<bool>>FoldsC;
//Read files & get unique folds & get indices of dominant folds
string FileNameA = Folder + RNAname+"_A10.txt";
ConstructFolds(FileNameA, RNALenFoldA, SampleSize, stOverlapA, edOverlapA, FoldsA, FoldsNumA);
string FileNameC = Folder + RNAname+"_C10.txt";
ConstructFolds(FileNameC, RNALenFoldC, SampleSize, stOverlapC, edOverlapC, FoldsC, FoldsNumC);
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////// ETA & BETA ESTIMATION ///////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//Order: beta and gama here are from 5' to 3'. Here we do not need reorder beta
vector<double>SEQbetaest(RNALen,0);//remove the last nucleotide
for(int i = 0; i<RNALen; ++i)
{
//Must have complete reads
double tempX = (double)accumulate(ReadsSeq.begin(), ReadsSeq.begin()+i+2, 0);
SEQbetaest[RNALen-i-1] = double(ReadsSeq[i+1])/tempX;
if(SEQbetaest[RNALen-i-1]<0) SEQbetaest[RNALen-i-1]=0;
}
// Manually caluclate EtaA and EtaC
double EtaA = (SEQbetaest[15]+SEQbetaest[9])/2/RhoC;
double EtaC = (SEQbetaest[30]/RhoC+(SEQbetaest[27]+SEQbetaest[25]+SEQbetaest[20]+SEQbetaest[8])/RhoA)/5;
///////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////// DESIGN MATRIX CONSTRUCTION ///////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
int FoldsNum = FoldsNumA+FoldsNumC;
vector<vector<double>>SEQDSMatrix(RNALen+1,vector<double>(FoldsNum,0));
ConstructDMSEQ(RNALen, FoldsA, FoldsC, EtaA, EtaC, SEQDSMatrix);
//Calculate Y
vector<double>SEQResponse(RNALen+1,0);//3' to 5', complete
for(int i = 0; i<RNALen+1; ++i)
SEQResponse[i] = (double)ReadsSeq[RNALen-i]/(double)ReadsNum;
//Write Y
myfilew.open (Folder+RNAname+"SEQResponse.txt");
for(int i = 0; i<RNALen+1;++i)
myfilew<<SEQResponse[i]<<" ";
myfilew.close();
//Write Design Matrix
myfilew.open(Folder+RNAname+"SEQDSMatrix.txt");
for(int i = 0; i<RNALen+1; ++i)
for(int j = 0; j<FoldsNum; ++j)
myfilew<<SEQDSMatrix[i][j]<<" ";
myfilew.close();
return 0;
}
int ConstructDMSEQ(int RNALen, vector<vector<bool>>FoldsA,vector<vector<bool>>FoldsC,double EtaA, double EtaC, vector<vector<double>>&DSMatrix)
{
int FoldsNumA = (int)FoldsA.size();
int FoldsNumC = (int)FoldsC.size();
//with complete reads
for (int k = 0; k < RNALen+1; ++k)//k starts from 3'
{
//FoldsA
//site k is A/C/UG
if(k==RNALen)
{
for (int c = 0; c < FoldsNumA; ++c)
{
float tempsum_plus = 1;
for (int i = 0; i < k; ++i) //Prob(no adducts on sites from 0 to k-1)
{
if (FoldsA[c][i+(RNALenFoldA-1-edOverlapA)] == 1)
{
//site i is A/C/UG
int flagACbefore = 0;
for(vector<int>::iterator itA = Aidx_AlleleA.begin(); itA!=Aidx_AlleleA.end(); ++itA)
{
if(RNALen-1-*itA == i)
{
flagACbefore = 1;
break;
}
}
for(vector<int>::iterator itC = Cidx_AlleleA.begin(); itC!=Cidx_AlleleA.end() & (flagACbefore == 0); ++itC)
{
if(RNALen-1-*itC == i)
{
flagACbefore = 2;
break;
}
}
//if UG, tempsum = tempsum * 1;
if(flagACbefore == 1)
tempsum_plus = tempsum_plus*(1 - EtaA);
else if (flagACbefore == 2)
tempsum_plus = tempsum_plus*(1 - EtaC);
}
}
DSMatrix[k][c] = tempsum_plus;
}
for(int c = 0; c<FoldsNumC; ++c)
{
float tempsum_plus = 1;
for (int i = 0; i < k; ++i) //Prob(no adducts on sites from 0 to k-1)
{
if (FoldsC[c][i+(RNALenFoldC-1-edOverlapC)] == 1)
{
int flagACbefore = 0;
for(vector<int>::iterator itA = Aidx_AlleleC.begin(); itA!=Aidx_AlleleC.end(); ++itA)
{
if(RNALen-1-*itA == i)
{
flagACbefore = 1;
break;
}
}
for(vector<int>::iterator itC = Cidx_AlleleC.begin(); itC!=Cidx_AlleleC.end()&(flagACbefore==0); ++itC)
{
if(RNALen-1-*itC == i)
{
flagACbefore = 2;
break;
}
}
if(flagACbefore == 1)
tempsum_plus = tempsum_plus*(1 - EtaA);
else if (flagACbefore == 2)
tempsum_plus = tempsum_plus*(1 - EtaC);
}
}
DSMatrix[k][c+FoldsNumA] = tempsum_plus;
}
continue;
}
int flagAC = 0;
for(vector<int>::iterator itA = Aidx_AlleleA.begin(); itA!=Aidx_AlleleA.end(); ++itA)
{
if(RNALen-1-*itA == k)
{
flagAC = 1;
break;
}
}
for(vector<int>::iterator itC = Cidx_AlleleA.begin(); itC!=Cidx_AlleleA.end() & (flagAC == 0); ++itC)
{
if(RNALen-1-*itC == k)
{
flagAC = 2;
break;
}
}
if(flagAC == 0)//UG,if in UG, mutation is impossible since we processed it.
{//Prob of forming an adduct on UG sites is 0;//already initialized 0
//for(int c = 0; c<FoldsNumA+FoldsNumC; ++c)
// DSMatrix[k][c] = 0;
continue;
}
else
{
for (int c = 0; c < FoldsNumA; ++c)
{
float tempsum_plus = 1;
if(k < RNALen) //Prob(adduct on site k)
{
if(FoldsA[c][k+(RNALenFoldA-1-edOverlapA)] == 1)
{
if(flagAC == 1)
tempsum_plus = EtaA;
else if (flagAC == 2)
tempsum_plus = EtaC;
}
else
{
//tempsum_plus = 0;//initialization is 0
continue;
}
}
for (int i = 0; i < k; ++i) //Prob(no adducts on sites from 0 to k-1)
{
if (FoldsA[c][i+(RNALenFoldA-1-edOverlapA)] == 1)
{
//site i is A/C/UG
int flagACbefore = 0;
for(vector<int>::iterator itA = Aidx_AlleleA.begin(); itA!=Aidx_AlleleA.end(); ++itA)
{
if(RNALen-1-*itA == i)
{
flagACbefore = 1;
break;
}
}
for(vector<int>::iterator itC = Cidx_AlleleA.begin(); itC!=Cidx_AlleleA.end() & (flagACbefore == 0); ++itC)
{
if(RNALen-1-*itC == i)
{
flagACbefore = 2;
break;
}
}
//if UG, tempsum = tempsum * 1;
if(flagACbefore == 1)
tempsum_plus = tempsum_plus*(1 - EtaA);
else if (flagACbefore == 2)
tempsum_plus = tempsum_plus*(1 - EtaC);
}
}
DSMatrix[k][c] = tempsum_plus;
}
}
//FoldsC
flagAC = 0;
for(vector<int>::iterator itA = Aidx_AlleleC.begin(); itA!=Aidx_AlleleC.end(); ++itA)
{
if(RNALen-1-*itA == k)
{
flagAC = 1;
break;
}
}
for(vector<int>::iterator itC = Cidx_AlleleC.begin(); itC!=Cidx_AlleleC.end()& (flagAC==0); ++itC)
{
if(RNALen-1-*itC == k)
{
flagAC = 2;
break;
}
}
if(flagAC != 0)
{
for(int c = 0; c<FoldsNumC; ++c)
{
float tempsum_plus = 1;
if(k < RNALen) //Prob(adduct on site k)
{
if(FoldsC[c][k+(RNALenFoldC-1-edOverlapC)] == 1)
{
if(flagAC == 1)
tempsum_plus = EtaA;
else if (flagAC == 2)
tempsum_plus = EtaC;
}
else
continue;
//tempsum_plus = 0;
}
for (int i = 0; i < k; ++i) //Prob(no adducts on sites from 0 to k-1)
{
if (FoldsC[c][i+(RNALenFoldC-1-edOverlapC)] == 1)
{
int flagACbefore = 0;
for(vector<int>::iterator itA = Aidx_AlleleC.begin(); itA!=Aidx_AlleleC.end(); ++itA)
{
if(RNALen-1-*itA == i)
{
flagACbefore = 1;
break;
}
}
for(vector<int>::iterator itC = Cidx_AlleleC.begin(); itC!=Cidx_AlleleC.end()&(flagACbefore==0); ++itC)
{
if(RNALen-1-*itC == i)
{
flagACbefore = 2;
break;
}
}
if(flagACbefore == 1)
tempsum_plus = tempsum_plus*(1 - EtaA);
else if (flagACbefore == 2)
tempsum_plus = tempsum_plus*(1 - EtaC);
}
}
DSMatrix[k][c+FoldsNumA] = tempsum_plus;
}
}
}
return 0;
}
int ConstructFolds(string FileName, int RNALen, int SampleSize, int st, int ed, vector<vector<bool>>&Folds, int&FoldsNum)
{
ifstream myfile;
myfile.open (FileName.c_str());
char * dump = new char[6];
char * Buffer = new char[RNALen];
vector<bool> FoldsUnit(RNALen,0);//from 3' to 5'
FoldsNum = 0;
int dumpnum = 0;
//Read Files, convert to 0,1 form, remain unique folds
for(int i = 0; i<20; ++i)
{
myfile.read(dump,sizeof(char)*1);
if(dump[0]=='('||dump[0]==')'||dump[0]=='.')
{
Buffer[0] = dump[0];
myfile.read(&Buffer[1],sizeof(char)*(RNALen-1));
if(i == 5) dumpnum = 1;
if(i == 6) dumpnum = 2;
break;
}
}
myfile.read(dump,sizeof(char)*dumpnum);
for(int j = 0; j<RNALen; ++j)
{
if(Buffer[j] == '.')
FoldsUnit[RNALen-1-j] = 1;
else
FoldsUnit[RNALen-1-j] = 0;
}
Folds.push_back(FoldsUnit);
++FoldsNum;
for(int i = 1; i<SampleSize; ++i)
{
bool flag = 0;
myfile.read(Buffer,sizeof(char)*RNALen);
myfile.read(dump,sizeof(char)*dumpnum);
for(int j = 0; j<RNALen; ++j)
{
if(Buffer[j] == '.')
FoldsUnit[RNALen-1-j] = 1;
else
FoldsUnit[RNALen-1-j] = 0;
}
for(int k = 0; k<FoldsNum; ++k)
{
/*if(Folds[k] == FoldsUnit)
{
flag = 1;
break;
}*/
int q = RNALen-ed-1;
for(; q<=RNALen-st-1; ++q)
{
if(Folds[k][q]!=FoldsUnit[q])
break;
}
if(q == RNALen-st)
{
flag = 1;
break;
}
}
if(flag == 0)
{
Folds.push_back(FoldsUnit);
++FoldsNum;
}
}
myfile.close();
delete []dump;
delete []Buffer;
return 0;
}
int DrawReadsSEQ(int RNALen,int ReadsNum, vector<double>RandUnifData,vector<double>&ProbPlus, vector<int>& PlusReads)
{
vector<double>ProbPlusCumsum(RNALen+1,0);
partial_sum(ProbPlus.begin(), ProbPlus.end(), ProbPlusCumsum.begin());
int PlusBegin = 0;
for(int i = 0; i<RNALen+1; ++i)
{
for(int j = PlusBegin; j<ReadsNum; ++j)
{
if(RandUnifData[j]>ProbPlusCumsum[i])
{
PlusReads.push_back(j - PlusBegin);
PlusBegin = j;
break;
}
if(j == ReadsNum-1)
{
PlusReads.push_back(ReadsNum - PlusBegin);
PlusBegin = ReadsNum;
}
}
}
for(int i = (int)PlusReads.size(); i<RNALen+1; ++i)
PlusReads.push_back(0);
return 0;
}
template<typename T>
int runif(int len, T min, T max, vector<T>&out)
{
unsigned seed = (unsigned)chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
uniform_real_distribution<T> distribution(min,max);
for (int i=0; i<len; ++i) {
out[i]= distribution(generator);
}
return 0;
}
|
7347e69842b5be14b9771d006a88038a6a1b571c
|
fd615e51ca266084353f842197839d61afe2739e
|
/core/server/src/ClientCallback.h
|
4f76d6ec01d670dc2ae1cf0804e026b06e0de5f8
|
[
"Apache-2.0"
] |
permissive
|
loentar/ngrest
|
8ee8ffeab1293529dfa9d8c4b59304204c049018
|
75801cde9c2c9d263ff39df5a810e4aa94b095ab
|
refs/heads/master
| 2022-08-05T05:48:40.444951
| 2022-01-24T19:36:08
| 2022-01-24T19:36:08
| 47,983,339
| 516
| 110
|
Apache-2.0
| 2018-11-11T11:29:26
| 2015-12-14T15:25:46
|
C++
|
UTF-8
|
C++
| false
| false
| 2,826
|
h
|
ClientCallback.h
|
/*
* Copyright 2016 Utkin Dmitry <loentar@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* This file is part of ngrest: http://github.com/loentar/ngrest
*/
#ifndef NGREST_CLIENTCALLBACK_H
#define NGREST_CLIENTCALLBACK_H
#ifndef HAS_EPOLL
#ifndef WIN32
#include <sys/select.h>
#else
#include <winsock2.h>
#endif
#endif
#include "servercommon.h"
struct sockaddr_storage;
namespace ngrest {
/**
* @brief status code
*/
enum class Status {
Success, //!< no action
Done, //!< response finished, remove socket from write queue
Again, //!< response processedd partially, add socket to write queue
Close //!< close client connection
};
/**
* @brief callback to close connections from handler
*/
class CloseConnectionCallback {
public:
/**
* @brief virtual destructor
*/
virtual ~CloseConnectionCallback() {}
/**
* @brief close connection to client
* @param fd client socket descriptor
*/
virtual void closeConnection(Socket fd) = 0;
};
/**
* @brief callback class to process events from client
*/
class ClientCallback {
public:
/**
* @brief virtual destructor
*/
virtual ~ClientCallback()
{
}
/**
* @brief client connected event
* @param fd client socket descriptor
* @param addr client address
*/
virtual void connected(Socket fd, const sockaddr_storage* addr) = 0;
/**
* @brief client disconnected event
* @param fd client socket descriptor
*/
virtual void disconnected(Socket fd) = 0;
/**
* @brief client error event
* @param fd client socket descriptor
*/
virtual void error(Socket fd) = 0;
/**
* @brief data available from client
* @param fd client socket descriptor
* @return true - read success, false - close connection
*/
virtual bool readyRead(Socket fd) = 0;
/**
* @brief client socket is ready for writing
* @param fd client socket descriptor
* @return write status code
*/
virtual Status readyWrite(Socket fd) = 0;
/**
* @brief set calback to close connection
* @param callback callback
*/
virtual void setCloseConnectionCallback(CloseConnectionCallback* callback) = 0;
};
}
#endif // NGREST_CLIENTCALLBACK_H
|
4f447e143f13dbc31b10906fa3fe704f5d7a4114
|
ba8fccb04ade627d1fe4c37521e32be25845abf2
|
/sdp/tree.cpp
|
c643c38a7105522ac54903c98519394a64195642
|
[] |
no_license
|
DimitarHKostov/Tasks_cpp
|
78f3a69f550ebde81d85886fdb4b2fb5fd1bc2d1
|
69336002d93e3856385239a833614d584b900630
|
refs/heads/master
| 2021-08-22T04:13:58.775707
| 2020-09-02T18:14:56
| 2020-09-02T18:14:56
| 219,054,878
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,616
|
cpp
|
tree.cpp
|
#include <iostream>
struct Node{
int data;
Node* left;
Node* right;
Node(int data, Node* left=nullptr, Node* right=nullptr):data(data), left(left), right(right){}
};
class binTree{
public:
binTree();
void insert(int);
void print();
void mirrorNegative();
int height();
bool isBalanced();
void remove(int);
void removeEvenAddSum();
~binTree();
private:
Node*& minP(Node*&);
void removeHelper(Node*&, int);
void readHelper(int&, Node*);
bool ibHelper(Node*);
int heightHelper(Node*);
void mnHelper(Node*);
void deleteHelper(Node*);
void printHelper(Node*);
void insertHelper(Node*&, int);
Node* root;
};
binTree::binTree(){
this->root=nullptr;
}
Node*& binTree::minP(Node*& root){
if(root==nullptr){
return root;
}
while(root&&root->left){
root=root->left;
}
return root;
}
bool binTree::isBalanced(){
return this->ibHelper(this->root);
}
void binTree::remove(int x){
return this->removeHelper(this->root, x);
}
void binTree::removeHelper(Node*& root, int x){
if (root == nullptr){
return;
}
if (x < root->data){
removeHelper (root->left, x);
} else if (root->data < x){
removeHelper (root->right, x);
} else if (root->right == nullptr){
Node* save = root;
root = root->left;
delete save;
} else{
Node *&minimal = minP (root->right);
Node *saveMinAdd = minimal;
minimal = minimal->right;
saveMinAdd->left = root->left;
saveMinAdd->right = root->right;
Node* saveCurrentAddr = root;
root = saveMinAdd;
delete saveCurrentAddr;
}
}
bool binTree::ibHelper(Node* root){
if(root==nullptr){
return true;
}
int l=heightHelper(root->left);
int r=heightHelper(root->right);
if(abs(l-r)<=1 && ibHelper(root->left) && ibHelper(root->right)){
return true;
}
return false;
}
int binTree::heightHelper(Node* root){
if(root==nullptr){
return 0;
}
int l=heightHelper(root->left);
int r=heightHelper(root->right);
if(l>r){
return l+1;
}
return r+1;
}
int binTree::height(){
return this->heightHelper(this->root);
}
void binTree::readHelper(int& sum, Node* root){
if(root==nullptr){
return;
}
readHelper(sum, root->left);
readHelper(sum, root->right);
if(root->data%2==0){
sum+=root->data;
remove(root->data);
}
}
void binTree::removeEvenAddSum(){
int sum = 0;
this->readHelper(sum, this->root);
this->insert(sum);
}
void binTree::mnHelper(Node* root){
if(root==nullptr){
return;
}
mnHelper(root->left);
mnHelper(root->right);
Node* temp = root->left;
root->left=root->right;
root->right=temp;
root->data = -root->data;
}
void binTree::mirrorNegative(){
this->mnHelper(this->root);
}
void binTree::deleteHelper(Node* root){
if(root==nullptr){
return;
}
deleteHelper(root->left);
deleteHelper(root->right);
delete root;
}
binTree::~binTree(){
this->deleteHelper(this->root);
}
void binTree::insertHelper(Node*& root, int value){
if(root==nullptr){
root = new Node(value);
return;
}
if(value > root->data){
insertHelper(root->right, value);
return;
}
insertHelper(root->left, value);
}
void binTree::insert(const int value){
return this->insertHelper(this->root, value);
}
void binTree::print(){
return this->printHelper(this->root);
}
void binTree::printHelper(Node* root){
if(root==nullptr){
return;
}
printHelper(root->left);
printHelper(root->right);
std::cout << root->data << std::endl;
}
int main(){
binTree a;
a.insert(20);
a.insert(30);
a.insert(50);
a.insert(10);
a.insert(21);
a.insert(5);
a.removeEvenAddSum();
a.print();
return 0;
}
|
4a05fd0e08bd570eca3e857bc10a02b2722d361d
|
19a012b6a66374235771a8c2baee19560e98f8d7
|
/Codeforces/CR51/b.cpp
|
4b78a236ccca36606193c2123c4bc8e36c89e73b
|
[] |
no_license
|
juancate/CompetitivePrograming
|
735e992fd6ac9c264059604fb7a2f2dfce74d330
|
8cea3695fd0dec7122c94ab45b4517cb13232fb3
|
refs/heads/master
| 2021-01-25T10:06:47.576470
| 2018-12-19T01:11:41
| 2018-12-19T01:11:41
| 14,966,965
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,495
|
cpp
|
b.cpp
|
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cassert>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <algorithm>
#define D(x) cerr << #x << " = " << x << endl
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
typedef long long int64;
const int INF = (int)(1e9);
const int64 INFLL = (int64)(1e18);
const double EPS = 1e-13;
using namespace std;
long long best;
void solve(vector<long long> a, int l, string op) {
if(a.size() == 1) {
best = min(best, a[0]);
return;
}
int n = a.size();
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j) continue;
long long curr = a[i];
if(op[l] == '+')
curr += a[j];
else
curr *= a[j];
vector<long long> b;
b.push_back(curr);
for(int k = 0; k < n; k++)
if(k != i && k != j)
b.push_back(a[k]);
solve(b, l+1, op);
}
}
}
int main() {
ios_base::sync_with_stdio(false);
vector<long long> a(4);
for(int i = 0; i < 4; i++)
cin >> a[i];
string op;
for(int i = 0; i < 3; i++) {
char ch;
cin >> ch;
op.push_back(ch);
}
best = INFLL;
solve(a, 0, op);
cout << best << "\n";
return 0;
}
|
7af8f287a8beb0fc01c9bc46e0d4a199f77b4a27
|
bf5ce9b868def81a63fc386809addd0444e899d7
|
/src/filters/filter_menu.hpp
|
7eb62383a86f5886276db1b59c841019ef927f02
|
[
"MIT"
] |
permissive
|
Haseoo/Simple_Paint
|
8d741d7d0e5be94d5fe94da8c87d3067ca854a02
|
4b0c251b84c8580e85a8d305c3298dfc3a4a14e9
|
refs/heads/master
| 2020-04-16T20:02:14.082694
| 2019-03-28T20:51:28
| 2019-03-28T20:51:28
| 165,884,268
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,313
|
hpp
|
filter_menu.hpp
|
/** \file filter_menu.hpp
* \brief Plik definicję klasy filter_menu.
*/
#ifndef FILTER_MENU_H
#define FILTER_MENU_H
#include "../gtk_base_window.hpp"
#include "basic_filter.hpp"
#include <deque>
/** \brief Struktura przechowująca dane o wybranym filtrze.
* Umożliwia korzystanie z prostych sygnałów GTK bez użycia zmiennych globalnych.
*/
struct filter_type_data {
enum filter_type type; /**< Typ narzędzia. */
enum filter_type *response; /**< Wskaźnik na zmienną przechowującą wybór użytkownika. */
};
/** \brief Klasa menu do wyboru filtrów.
*/
class filter_menu : public gtk_base_window
{
public:
/** \brief Konstruktor klasy. Odczytuje informacje z pliku zasobów. Może "rzucić" wyjątek typu paint_exception w przypadku błędu.
*
*/
filter_menu();
/** \brief Metoda zawiera inicjuje menu filtrów oraz zawiera pętlę main GTK. Metoda nie przyjmuje żadnych argumentów wywołania.
* Metoda może "rzucić" wyjątek typu paint_exception gdy operacja inicjacji menu się nie powiedzie.
*
* \return bool Funkcja zwraca wartość true jeśli nie wystąpił w niej krytyczny błąd.
*
*/
bool open_gtk_window();
/** \brief Getter wybranego w menu rodzaju filtru.
*
*\return enum filter_type wybrany rodzaj filtru.
*/
enum filter_type get_filter_response();
private:
std::size_t number_of_filters; /**< Liczba filtrów programu. */
std::deque <struct filter_type_data> filter_types; /**< Kolejka, która ułatwia działanie GTK. */
enum filter_type filter_response; /**< Filter wybrany przez użytkownika. */
/** \brief Funkcja obsługująca sygnał kliknięcia na przycisk z wyborem filtra.
* Funkcja nie zwraca żadnej wartości.
*
* \param[out] widget GtkWidget* Wskaźnik na okno z którego pochodził sygnał.
* \param[out] data gpointer Dane dla funkcji.
*
*/
static void get_filter_type(GtkWidget *widget, gpointer data) {
*((reinterpret_cast <struct filter_type_data*>(data))->response) = (reinterpret_cast <struct filter_type_data*>(data))->type;
}
};
#endif
|
f375df9ca89dc8e29925796961d5b6f60a14bb73
|
81c74937fd4586b264b9ff3242be616292d06bdf
|
/trunk/src/c++/include/segreg/types/TypeDescription.h
|
b145c6b88fba6f338be3927cf0e444798c0a9710
|
[] |
no_license
|
rahulkr007/sageCore
|
be877ff6bb2ee5825e5cc9b9d71e03ac32f4e29f
|
b1b19b95d80637b48fca789a09a8de16cdaad3ab
|
refs/heads/master
| 2021-06-01T12:41:41.374258
| 2016-09-02T19:14:02
| 2016-09-02T19:14:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,941
|
h
|
TypeDescription.h
|
#ifndef TYPES_TYPE_DESCRIPTION_H
#define TYPES_TYPE_DESCRIPTION_H
#include "output/Output.h"
#include <ostream>
#include <vector>
namespace SAGE {
namespace SEGREG {
class TypeDescription
{
public:
class State
{
friend class TypeDescription;
public:
inline State();
inline State(const State&);
inline State& operator=(const State&);
inline size_t get_index () const;
inline std::string get_name () const;
private:
inline State(size_t index, std::string name);
size_t my_index;
std::string my_name;
};
private:
typedef std::vector<State> StateVector;
public:
typedef StateVector::const_iterator StateIterator;
inline TypeDescription();
inline TypeDescription(const TypeDescription&);
inline TypeDescription& operator=(const TypeDescription&);
inline void set_name (std::string);
inline std::string get_name ( ) const;
inline void set_description(std::string);
inline std::string get_description( ) const;
/// \name State management
//@{
inline void reserve_state_count(size_t);
inline size_t add_state(std::string);
inline size_t get_state_count() const;
inline const State& get_state(size_t) const;
inline StateIterator begin() const;
inline StateIterator end() const;
//@}
private:
std::string my_name;
std::string my_description;
StateVector my_states;
};
OUTPUT::Section convert_to_output(const TypeDescription& t);
inline std::ostream& operator<<(std::ostream&, const TypeDescription&);
} // End Namespace SEGREG
} // End Namespace SAGE
#include "segreg/types/TypeDescription.ipp"
#endif
|
b15109b24ee93c671d5ee2e04ddce9c3f840c010
|
afb38d3dac22ea282689b7b2076bad0f2d9df874
|
/paraccumulate/main.cpp
|
5645a8b7d5f36d269f66eb214d29aa47f2144a91
|
[] |
no_license
|
katarinasupe/NapredniCpp
|
b8f1576c4f74ac7b0ae1daa4d84114f12bc0a5e7
|
0a4e0fda27b726bb717468e7ed5f749be9bb98e0
|
refs/heads/master
| 2023-03-01T13:33:00.382674
| 2021-02-11T11:19:51
| 2021-02-11T11:19:51
| 313,115,756
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,152
|
cpp
|
main.cpp
|
#include "clock.h"
#include "paraccumulate.h"
#include "partransform.h"
#include <iostream>
#include <vector>
#include <iomanip>
#include <string>
#include <algorithm>
#include <cmath>
//pomocna fja koja prima vektor koji ce transformirati i funkciju koju ce primijeniti na svaku komponentu danog vektora
//vraca transformirani vektor (transformiran paralelnim transform algoritmom)
template <typename T, typename F>
std::vector<T> calculate(std::vector<T> v, F&& f){
parallel_transform(std::begin(v), std::end(v), std::forward<F>(f)); //lokalno promijeni v
return v;
}
// Glavni program koji testira paralelnu verziju accumulate() algoritma.
// Potrebno je na par primjera usporediti serijsku i paralelnu verziju
// algoritma i usporediti njihova vremena izvršavanja kao funkciju veličine
// spremnika na kojem rade
int main(){
/*Uzela sam za primjer 2-dim do 200000000-dim vektor cija je svaka komponenta jednaka 10. Vidimo da je za manje dimenzije
serijski accumulate algoritam brzi od paralelnog (za 200000-dim vektor je serijski jos malo brzi). Kada dodemo na 2000000-dim vektor,
tada paralelni algoritam postaje brzi te vidimo da sto je veca dimenzija vektora, paralelni algoritam postaje sve brzi.
Za 200000000-dim vektor nas paralelni algoritam je gotovo 19 puta brzi od serijskog.*/
/*Za transform paralelni algoritam primjecujemo da postaje brzi od serijskog za dimenziju vektora 20000.
Ukoliko pokusamo s kompleksnijom transformacijom (npr. sqrt(x)), tada ćemo vidjeti da je benefit paralelizacije transform
algoritma manji.*/
std::vector<int> par_result;
std::vector<int> ser_result;
for(int i = 0; i < 9; ++i){
int n = 2 * (int)pow(10, i); //dimenzija vektora
std::cout << "----------------------------------------" << std::endl;
std::cout << "vector dimension = " << n << std::endl;
std::cout << "----------------------------------------" << std::endl;
std::vector<int> v(n, 10); //popuni desetkama
std::cout << std::endl;
//mjerenje paralelnog accumulate u mikrosekundama
Clock par_myClock;
auto par_sum = parallel_accumulate(v.begin(), v.end(), 0);
auto par_time = par_myClock.stop(Clock::microsec); //zaustavi sat
std::cout << "parallel_accumulate sum = " << std::setprecision(10) << par_sum << ", time = " << par_time << " us" << std::endl;
//mjerenje serijskog accumulate u mikrosekundama
Clock ser_myClock;
auto ser_sum = std::accumulate(v.begin(), v.end(), 0.0);
auto ser_time = ser_myClock.stop(Clock::microsec);
std::cout << "serial_accumulate sum = " << std::setprecision(10) << ser_sum << ", time = " << ser_time << " us" << std::endl;
std::cout << std::endl;
//mjerenje paralelnog transform u mikrosekundama
Clock par_myClock_transf;
par_result = calculate(v, [](int x) { return x * 3; }); //primjer: fja koja utrostrucuje svaku komponentu vektora v
auto par_time_transf = par_myClock_transf.stop(Clock::microsec);
std::cout << "parallel_transform time = " << std::setprecision(10) << par_time_transf << " us" << std::endl;
//mjerenje serijskog transform u mikrosekundama
Clock ser_myClock_transf;
std::transform(v.begin(), v.end(), std::back_inserter(ser_result), [](int x) { return x * 3; });
auto ser_time_transf = ser_myClock_transf.stop(Clock::microsec);
std::cout << "serial_transform time = " << std::setprecision(10) << ser_time_transf << " us" << std::endl;
std::cout << std::endl;
//mjerenje paralelnog transform u mikrosekundama
Clock par_myClock_transf_compl;
par_result = calculate(v, [](int x) { return (int)std::sqrt(x); }); //primjer: korijen
auto par_time_transf_compl = par_myClock_transf_compl.stop(Clock::microsec);
std::cout << "parallel_transform_compl time = " << std::setprecision(10) << par_time_transf_compl << " us" << std::endl;
//mjerenje serijskog transform u mikrosekundama
Clock ser_myClock_transf_compl;
std::transform(v.begin(), v.end(), std::back_inserter(ser_result), [](int x) { return (int)std::sqrt(x); });
auto ser_time_transf_compl = ser_myClock_transf_compl.stop(Clock::microsec);
std::cout << "serial_transform_compl time = " << std::setprecision(10) << ser_time_transf_compl << " us" << std::endl;
std::cout << std::endl;
}
//provjera rada transform metode - nisam htjela vracati izlaze iznad, jer su ti vektori prevelike dimenzije
/*
std::vector<int> v = { 1,2,3 };
std::vector<int> par_result;
std::vector<int> ser_result;
par_result = calculate(v, [](int x) { return x * 3; }); //fja koja utrostrucuje vektor
std::for_each(par_result.begin(), par_result.end(), [](const int& s) { std::cout << s << std::endl; });
std::transform(v.begin(), v.end(), std::back_inserter(ser_result), [](int x) { return x * 3; });
std::for_each(ser_result.begin(), ser_result.end(), [](const int& s) { std::cout << s << std::endl; }); */
return 0;
}
|
94be72010f06d09f0a47a4c526153ea36de55910
|
5fd1e0e2ce1f9bc2c3d5f4a1d368bcde1bc17ae5
|
/hackerearth-increasingvalues.cpp
|
14b4d9b13152f16305a19f57a66427362b0e51c6
|
[] |
no_license
|
srivastavaman641/Competitive-Coding
|
ec3177cecaf33081fd68f8da4fec4c3cc7669c0d
|
c3b8f576d41f1aa2f608812c013c4392be3d3392
|
refs/heads/master
| 2020-03-22T18:11:23.882989
| 2018-07-10T14:18:44
| 2018-07-10T14:18:44
| 140,443,258
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,542
|
cpp
|
hackerearth-increasingvalues.cpp
|
#include<bits/stdc++.h>
#define ll long long int
#define s(a) scanf("%d",&a)
#define sl(a) scanf("%lld",&a)
#define ss(a) scanf("%s",a)
#define w(t) while(t--)
#define f(i,n) for(int i=0;i<n;i++)
#define fd(i,n) for(int i=n-1;i>=0;i--)
#define p(a) printf("%d",a)
#define pl(a) printf("%lld",a)
#define ps(a) printf("%s",a)
#define pc(a) printf("%c",a)
#define ent printf("\n")
#define mod 1000000007
#define PI 3.14159265
#define gs getline(cin,s)
#define pb push_back
#define mp make_pair
#define INF 1e18
#define pii pair<int,int>
using namespace std;
vector<ll>v[100005];
ll vis[100005],tree[100005],a[100005],parent[100005],mark[100005];
ll cnt=0;
ll lim;
void dfs(ll x)
{
vis[x]=1;
tree[x]=a[x];
for(ll i=0;i<v[x].size();i++)
{
if(!vis[v[x][i]])
{
dfs(v[x][i]);
parent[v[x][i]]=x;
tree[x]+=tree[v[x][i]];
}
}
if(tree[x]>lim){
mark[x]=1;
cnt++;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n,q;
cin>>n>>q>>lim;
for (int i=0;i<n-1;i++)
{
int x,y;
cin>>x>>y;
v[x].pb(y);
v[y].pb(x);
}
for(int i=1;i<=n;i++)
cin>>a[i];
parent[1]=0;
dfs(1);
while(q--)
{
ll x,val;
cin>>x>>val;
tree[x]+=val;
while(x>0)
{
if(tree[x]>lim){
if(!mark[x]){
mark[x]=1;
cnt++;
}
else
break;
}
tree[parent[x]]+=val;
if(tree[parent[x]]>lim && parent[x]!=0)
{
if(!mark[parent[x]])
{
mark[parent[x]]=1;
cnt++;
}
else
break;
}
x=parent[parent[x]];
tree[x]+=val;
}
cout<<cnt<<endl;
}
return 0;
}
|
32823fc1ccb99238ae9aef435b2aae8264831ce7
|
ed2da1e8158b10e22cd65d028218e46e9c3bb663
|
/include/ZombieAftermath.h
|
34db2bd9c779612db7e5060709c25950f39ef4ff
|
[] |
no_license
|
chaoticgood1/Zombie-Aftermath
|
c163482335e3662ff1721eed6330173988096f2f
|
26a55630aeea09c8ada04a53028e6c4236d03d07
|
refs/heads/master
| 2023-08-26T12:15:34.802576
| 2014-05-04T06:00:36
| 2014-05-04T06:00:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 315
|
h
|
ZombieAftermath.h
|
#ifndef ZOMBIEAFTERMATH_H
#define ZOMBIEAFTERMATH_H
#include "framework/Game.h"
class ZombieAftermath : public Game {
public:
ZombieAftermath(const float width, const float height, const string gameName);
virtual ~ZombieAftermath();
protected:
private:
};
#endif // ZOMBIEAFTERMATH_H
|
cca70a81693baf609c2bc1b5d04f599496937901
|
2e27a1de1e8771e760696e605e6f48755f518aa3
|
/Examples/Subscriptions/src/SubscriptionsComponent2.cpp
|
d64e02e4142591b123bd55a92429ed7792de1e72
|
[
"MIT"
] |
permissive
|
PLCnext/CppExamples
|
c710a751afbe78a6f775a17df69533304cb57a90
|
58439a536e53fb79e55638ded888bbd14302c497
|
refs/heads/master
| 2023-08-18T15:17:44.395635
| 2023-08-11T05:37:52
| 2023-08-11T05:37:52
| 172,078,078
| 26
| 24
|
MIT
| 2023-05-24T07:49:21
| 2019-02-22T14:15:46
|
Shell
|
UTF-8
|
C++
| false
| false
| 10,784
|
cpp
|
SubscriptionsComponent2.cpp
|
///////////////////////////////////////////////////////////////////////////////"
//
// Copyright PHOENIX CONTACT Electronics GmbH
//
///////////////////////////////////////////////////////////////////////////////
#include "SubscriptionsComponent2.hpp"
#include "Arp/Plc/Commons/Domain/PlcDomainProxy.hpp"
#include "SubscriptionsLibrary.hpp"
#include "Arp/System/Rsc/ServiceManager.hpp"
namespace Subscriptions
{
using Arp::System::Rsc::ServiceManager;
using namespace Arp::Plc::Commons::Domain;
const String SubscriptionsComponent2::varTask100msName = "Arp.Plc.Eclr/RealTimeProgram100ms.varUInt16";
const String SubscriptionsComponent2::varTask500msName = "Arp.Plc.Eclr/RealTimeProgram500ms.varUInt16";
SubscriptionsComponent2::SubscriptionsComponent2(IApplication& application, const String& name)
: ComponentBase(application, ::Subscriptions::SubscriptionsLibrary::GetInstance(), name, ComponentCategory::Custom)
, MetaComponentBase(::Subscriptions::SubscriptionsLibrary::GetInstance().GetNamespace())
, subscriptionThread(this, &SubscriptionsComponent2::LogSubscription, 1000, "SubscriptionLogThread"){
}
void SubscriptionsComponent2::Initialize()
{
// never remove next line
PlcDomainProxy::GetInstance().RegisterComponent(*this, false);
// initialize singletons here, subscribe notifications here
PlcDomainProxy& plcDomainProxy = PlcDomainProxy::GetInstance();
// register all Plc event handler
plcDomainProxy.PlcLoaded += make_delegate(this, &SubscriptionsComponent2::OnPlcLoaded);
plcDomainProxy.PlcStarted += make_delegate(this, &SubscriptionsComponent2::OnPlcStarted);
plcDomainProxy.PlcStopping += make_delegate(this, &SubscriptionsComponent2::OnPlcStopping);
plcDomainProxy.PlcUnloading += make_delegate(this, &SubscriptionsComponent2::OnPlcUnloading);
plcDomainProxy.PlcChanging += make_delegate(this, &SubscriptionsComponent2::OnPlcChanging);
plcDomainProxy.PlcChanged += make_delegate(this, &SubscriptionsComponent2::OnPlcChanged);
}
void SubscriptionsComponent2::SubscribeServices()
{
// gets the ISubscritpionService pointer
this->subscriptionServicePtr = ServiceManager::GetService<ISubscriptionService>();
}
void SubscriptionsComponent2::LoadSettings(const String& /*settingsPath*/)
{
// load firmware settings here
}
void SubscriptionsComponent2::SetupSettings()
{
// never remove next line
MetaComponentBase::SetupSettings();
// setup firmware settings here
}
void SubscriptionsComponent2::PublishServices()
{
// publish the services of this component here
}
void SubscriptionsComponent2::LoadConfig()
{
// load project config here
}
void SubscriptionsComponent2::SetupConfig()
{
// setup project config here
}
void SubscriptionsComponent2::ResetConfig()
{
// implement this inverse to SetupConfig() and LoadConfig()
}
void SubscriptionsComponent2::Dispose()
{
// never remove next line
MetaComponentBase::Dispose();
// implement this inverse to SetupSettings(), LoadSettings() and Initialize()
PlcDomainProxy& plcDomainProxy = PlcDomainProxy::GetInstance();
// unregister all Plc event handler
plcDomainProxy.PlcLoaded -= make_delegate(this, &SubscriptionsComponent2::OnPlcLoaded);
plcDomainProxy.PlcStarted -= make_delegate(this, &SubscriptionsComponent2::OnPlcStarted);
plcDomainProxy.PlcStopping -= make_delegate(this, &SubscriptionsComponent2::OnPlcStopping);
plcDomainProxy.PlcUnloading -= make_delegate(this, &SubscriptionsComponent2::OnPlcUnloading);
plcDomainProxy.PlcChanging -= make_delegate(this, &SubscriptionsComponent2::OnPlcChanging);
plcDomainProxy.PlcChanged -= make_delegate(this, &SubscriptionsComponent2::OnPlcChanged);
}
void SubscriptionsComponent2::PowerDown()
{
// implement this only if data must be retained even on power down event
}
void SubscriptionsComponent2::OnPlcLoaded()
{
}
void SubscriptionsComponent2::OnPlcStarted()
{
this->StartSubscription();
}
void SubscriptionsComponent2::OnPlcStopping()
{
this->StopSubscription();
}
void SubscriptionsComponent2::OnPlcUnloading(bool)
{
}
void SubscriptionsComponent2::OnPlcChanging()
{
this->StopSubscription();
}
void SubscriptionsComponent2::OnPlcChanged(bool /*success*/)
{
this->StartSubscription();
}
void SubscriptionsComponent2::StartSubscription()
{
// First the subscription has to be created.
// There exists several subscription kinds, in this simple example the 'HightPerformance' kind is used,
// which operates with a double-buffer and ensures that the read data is task consistent.
// Check the description of Subscription/SubscriptionKind for more information.
this->subscriptionId = this->subscriptionServicePtr->CreateSubscription(SubscriptionKind::HighPerformance);
// The previous call should return a valid, non-zero subscription id otherwise anything failed.
// After the subscription has been created, at least one variable has to be added.
// To add more than one variable, this function could be called another time or the 'AddVariables' function could be used
// to add a set of variables. In this example the 2 variables from tow different tasks are added.
this->subscriptionServicePtr->AddVariable(this->subscriptionId, varTask100msName);
this->subscriptionServicePtr->AddVariable(this->subscriptionId, varTask500msName);
// Finally the 'Subscribe' function has to be called to start the data sampling of the previous added variables.
this->subscriptionServicePtr->Subscribe(this->subscriptionId, 0);
// now the subscription is created, configured and subscribed and the sampled data might be processed in the function
// 'LogSubscription' which is triggered by the 'subscriptionThread'.
// When reading data from a subscription, the values are sorted by the belonging write task regardless of the order
// in which the variables were added.
// So it is neccessary to obtain variable infos describing the order of the read variables.
// All variable values belonging to the same task are compound in a data record which begins with the recording timestamp.
// Because two variables from two different tasks were added in this example the exact order is unknown in advance.
// So before the data could be read, a mapping has to be applied to ensure the data is copied to the correct
// destination.
std::vector<VariableInfo> variableInfos;
// To get the varialbe values order the function 'GetTimeStampedVariableInfos' is used, and a delegate is required:
// declare a more handy delegate typename
using GetInfosDelegate = ISubscriptionService::GetTimeStampedVariableInfosVariableInfoDelegate;
GetInfosDelegate infosDelegate = GetInfosDelegate::create([&variableInfos](IRscReadEnumerator<VariableInfo>& readEnumerator)
{
// This call should return '4', the two added variables with one timestamp each.
size_t size = readEnumerator.BeginRead();
variableInfos.reserve(size);
VariableInfo currentInfo;
while (readEnumerator.ReadNext(currentInfo))
{
variableInfos.push_back(currentInfo);
}
readEnumerator.EndRead();
});
// Now the read function is called using the info-delegate is called to get the current order of variables
this->subscriptionServicePtr->GetTimeStampedVariableInfos(this->subscriptionId, infosDelegate);
// Using the previously obtained infos, the variables might be assigned to the correct values.
// As long as the subscription is not modified, the variable infos remain exactly the same.
if (variableInfos[1].Name.CStr() == varTask100msName)
{
this->value1->varName = varTask100msName;
this->value2->varName = varTask500msName;
}
else
{
this->value1->varName = varTask500msName;
this->value2->varName = varTask100msName;
}
this->subscriptionThread.Start();
}
void SubscriptionsComponent2::StopSubscription()
{
this->subscriptionServicePtr->Unsubscribe(this->subscriptionId);
this->subscriptionThread.Stop();
}
void SubscriptionsComponent2::LogSubscription()
{
// To read the data from the subscription a delegate function is required.
// In this example the delegate is created locally in this method and in every thread cycle because we don't
// care about the performance, but it is recommended, to create it in
// the same context in which the subscription is created, e.g. SetupConfig()
// declare a more handy delegate typename
using ReadValuesDelegate = ISubscriptionService::ReadTimeStampedValuesValuesDelegate;
ReadValuesDelegate readValuesDelegate = ReadValuesDelegate::create([this](IRscReadEnumerator<RscVariant<512>>& readEnumerator)
{
// This call should return '4' the two added variables with one timestamp each.
auto varCount = readEnumerator.BeginRead();
// Since the exact sequence of incoming data is known, we can easily read
// the data and store it directly at its destination.
RscVariant<512> value;
for (size_t i = 0; i < varCount; i++)
{
readEnumerator.ReadNext(value);
switch (value.GetType())
{
case RscType::Int64:
{
int64 usTicks = value.GetValue<int64>();
if ((i / 2) == 0)
{
this->value1->timestamp = DateTime::FromUnixTimeMicroseconds(usTicks);
}
else
{
this->value2->timestamp = DateTime::FromUnixTimeMicroseconds(usTicks);
}
break;
}
case RscType::Uint16:
{
uint16 v = value.GetValue<uint16>();
if ((i / 2) == 0)
{
this->value1->value = v;
}
else
{
this->value2->value = v;
}
break;
}
default:
break;
}
}
readEnumerator.EndRead();
});
// Now read function could be called with the previous created read-delegate to write the value to the system log.
this->subscriptionServicePtr->ReadTimeStampedValues(this->subscriptionId, readValuesDelegate);
log.Info("{}: {} - {}", this->value1->varName, this->value1->timestamp.ToIso8601String(), this->value1->value);
log.Info("{}: {} - {}", this->value2->varName, this->value2->timestamp.ToIso8601String(), this->value2->value);
}
} // end of namespace Subscriptions
|
80fc07f625cd08db8f77662c4c3d9036d87fa62b
|
0f70cdda109e4fbe8f970d9759ad7163fca6e0a1
|
/Fase_1/Benchmark1a/TPZDarcy2DMaterial.cpp
|
a049b7189e8f86b122530cd01624f2d76af4ac27
|
[] |
no_license
|
labmec/geomec_bench
|
7c0c32f7b7df26e10d78c4dab1ed384f95012173
|
4de62d21b5cc262e0a32f396b02d942c38f7ec26
|
refs/heads/master
| 2021-01-24T13:24:17.766372
| 2020-02-14T17:01:51
| 2020-02-14T17:01:51
| 123,172,542
| 0
| 3
| null | 2018-09-25T19:34:58
| 2018-02-27T18:44:22
|
C++
|
UTF-8
|
C++
| false
| false
| 36,970
|
cpp
|
TPZDarcy2DMaterial.cpp
|
/*
* TPZDarcy2DMaterial.cpp
* PZ
*
* Created by Pablo G. S. Carvalho on 08/09/2016.
* Copyright 2016 __MyCompanyName__. All rights reserved.
*
*/
#include "TPZDarcy2DMaterial.h"
#include "pzbndcond.h"
#include "pzaxestools.h"
#include "TPZMatWithMem.h"
#include "pzfmatrix.h"
TPZDarcy2DMaterial::TPZDarcy2DMaterial() : TPZMatWithMem<TPZFMatrix<STATE>, TPZDiscontinuousGalerkin >(){
TPZFNMatrix<3,STATE> Vl(1,1,0.);
this->SetDefaultMem(Vl);
fk=1.;
fViscosity=1.;
fTensorK.Resize(fDimension, fDimension);
fInvK.Resize(fDimension, fDimension);
for (int i=0; i<fDimension; i++) {
fTensorK(i,i) = 1.;
fInvK(i,i) = 1.;
}
}
////////////////////////////////////////////////////////////////////
TPZDarcy2DMaterial::TPZDarcy2DMaterial(int matid, int dimension, int space, STATE theta) : TPZMatWithMem<TPZFMatrix<STATE>, TPZDiscontinuousGalerkin >(matid),fDimension(dimension),fSpace(space),fTheta(theta)
{
TPZFNMatrix<3,STATE> Vl(1,1,0.);
this->SetDefaultMem(Vl);
fk=1.;
fViscosity=1.;
fTensorK.Resize(fDimension, fDimension);
fInvK.Resize(fDimension, fDimension);
for (int i=0; i<fDimension; i++) {
fTensorK(i,i) = 1.;
fInvK(i,i) = 1.;
}
}
////////////////////////////////////////////////////////////////////
TPZDarcy2DMaterial::TPZDarcy2DMaterial(const TPZDarcy2DMaterial &mat) : TPZMatWithMem<TPZFMatrix<STATE>, TPZDiscontinuousGalerkin >(mat),fDimension(mat.fDimension),fSpace(mat.fSpace), fTheta(mat.fTheta)
{
}
////////////////////////////////////////////////////////////////////
TPZDarcy2DMaterial::~TPZDarcy2DMaterial(){
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::FillDataRequirements(TPZMaterialData &data)
{
TPZMaterial::FillDataRequirements(data);
data.fNeedsSol = true;
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::FillDataRequirements(TPZVec<TPZMaterialData> &datavec)
{
int ndata = datavec.size();
for (int idata=0; idata < ndata ; idata++) {
datavec[idata].SetAllRequirements(false);
datavec[idata].fNeedsNormal = true;
datavec[idata].fNeedsSol = true;
}
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::FillBoundaryConditionDataRequirement(int type,TPZVec<TPZMaterialData> &datavec)
{
int ndata = datavec.size();
for (int idata=0; idata < ndata ; idata++) {
datavec[idata].SetAllRequirements(false);
datavec[idata].fNeedsSol = true;
datavec[idata].fNeedsNormal = true;
}
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::FillDataRequirementsInterface(TPZMaterialData &data)
{
data.fNeedsNormal = false;
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::Print(std::ostream &out) {
out << "\t Base class print:\n";
out << " name of material : " << this->Name() << "\n";
TPZMaterial::Print(out);
}
////////////////////////////////////////////////////////////////////
int TPZDarcy2DMaterial::VariableIndex(const std::string &name) {
if (!strcmp("P", name.c_str())) return 0;
if (!strcmp("V", name.c_str())) return 1;
if (!strcmp("f", name.c_str())) return 2;
if (!strcmp("V_exact", name.c_str())) return 3;
if (!strcmp("P_exact", name.c_str())) return 4;
if (!strcmp("Vx", name.c_str())) return 5;
if (!strcmp("Vy", name.c_str())) return 6;
// if (!strcmp("V_exactBC", name.c_str())) return 5;
std::cout << " Var index not implemented " << std::endl;
DebugStop();
return 0;
}
////////////////////////////////////////////////////////////////////
int TPZDarcy2DMaterial::NSolutionVariables(int var) {
switch(var) {
case 0:
return 1; // Pressure, Scalar
case 1:
return this->Dimension(); // Velocity, Vector
case 2:
return 1; // f, Scalar
case 3:
return this->Dimension(); // V_exact, Vector
case 4:
return 1; // P_exact, Scalar
case 5:
return 1; // V_x, Scalar
case 6:
return 1; // V_y, Scalar
default:
{
std::cout << " Var index not implemented " << std::endl;
DebugStop();
}
}
return 0;
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::Solution(TPZVec<TPZMaterialData> &datavec, int var, TPZVec<STATE> &Solout) {
//itapopo conferir esse metodo
int vindex = this->VIndex();
int pindex = this->PIndex();
TPZManVector<STATE,3> v_h = datavec[vindex].sol[0];
STATE p_h = datavec[pindex].sol[0][0];
TPZFNMatrix<9,STATE> gradu(2,1);
Solout.Resize(this->NSolutionVariables(var));
switch(var) {
case 0: //Pressure
{
Solout[0] = p_h;
}
break;
case 1: //Velocity
{
Solout[0] = v_h[0]; // Vx
Solout[1] = v_h[1]; // Vy
}
break;
case 2: //f
{
TPZVec<STATE> f(1,0.);
if(this->HasForcingFunction()){
this->ForcingFunction()->Execute(datavec[vindex].x, f, gradu);
}
Solout[0] = f[0]; // fx
}
break;
case 3: //v_exact
{
TPZVec<STATE> sol;
if(this->HasForcingFunctionExact()){
this->fForcingFunctionExact->Execute(datavec[vindex].x, sol, gradu); // @omar::check it!
}
Solout[0] = sol[0]; // vx
Solout[1] = sol[1]; // vy
}
break;
case 4: //p_exact
{
TPZVec<STATE> sol;
if(this->HasForcingFunctionExact()){
this->fForcingFunctionExact->Execute(datavec[pindex].x, sol, gradu); // @omar::check it!
}
Solout[0] = sol[2]; // px
}
break;
case 5: //Velocity X
{
Solout[0] = v_h[0]; // Vx
}
break;
case 6: //Velocity Y
{
Solout[0] = v_h[1]; // Vy
}
break;
default:
{
std::cout << " Var index not implemented " << std::endl;
DebugStop();
}
}
}
////////////////////////////////////////////////////////////////////
// Divergence on deformed element
void TPZDarcy2DMaterial::ComputeDivergenceOnDeformed(TPZVec<TPZMaterialData> &datavec, TPZFMatrix<STATE> &DivergenceofPhi)
{
//itapopo conferir esse método. Foi copiado do TPZDarcyFlow3D
int ublock = 0;
// Getting test and basis functions
TPZFMatrix<REAL> phiuH1 = datavec[ublock].phi; // For H1 test functions Q
TPZFMatrix<REAL> dphiuH1 = datavec[ublock].dphi; // Derivative For H1 test functions
TPZFMatrix<REAL> dphiuH1axes = datavec[ublock].dphix; // Derivative For H1 test functions
TPZFNMatrix<660> GradphiuH1;
TPZAxesTools<REAL>::Axes2XYZ(dphiuH1axes, GradphiuH1, datavec[ublock].axes);
int nphiuHdiv = datavec[ublock].fVecShapeIndex.NElements();
DivergenceofPhi.Resize(nphiuHdiv,1);
REAL JacobianDet = datavec[ublock].detjac;
TPZFMatrix<REAL> Qaxes = datavec[ublock].axes;
TPZFMatrix<REAL> QaxesT;
TPZFMatrix<REAL> Jacobian = datavec[ublock].jacobian;
TPZFMatrix<REAL> JacobianInverse = datavec[ublock].jacinv;
TPZFMatrix<REAL> GradOfX;
TPZFMatrix<REAL> GradOfXInverse;
TPZFMatrix<REAL> VectorOnMaster;
TPZFMatrix<REAL> VectorOnXYZ(3,1,0.0);
Qaxes.Transpose(&QaxesT);
QaxesT.Multiply(Jacobian, GradOfX);
JacobianInverse.Multiply(Qaxes, GradOfXInverse);
int ivectorindex = 0;
int ishapeindex = 0;
if (HDivPiola == 1)
{
for (int iq = 0; iq < nphiuHdiv; iq++)
{
ivectorindex = datavec[ublock].fVecShapeIndex[iq].first;
ishapeindex = datavec[ublock].fVecShapeIndex[iq].second;
VectorOnXYZ(0,0) = datavec[ublock].fNormalVec(0,ivectorindex);
VectorOnXYZ(1,0) = datavec[ublock].fNormalVec(1,ivectorindex);
VectorOnXYZ(2,0) = datavec[ublock].fNormalVec(2,ivectorindex);
GradOfXInverse.Multiply(VectorOnXYZ, VectorOnMaster);
VectorOnMaster *= JacobianDet;
/* Contravariant Piola mapping preserves the divergence */
DivergenceofPhi(iq,0) = (1.0/JacobianDet) * ( dphiuH1(0,ishapeindex)*VectorOnMaster(0,0) +
dphiuH1(1,ishapeindex)*VectorOnMaster(1,0) +
dphiuH1(2,ishapeindex)*VectorOnMaster(2,0) );
}
}
else
{
for (int iq = 0; iq < nphiuHdiv; iq++)
{
ivectorindex = datavec[ublock].fVecShapeIndex[iq].first;
ishapeindex = datavec[ublock].fVecShapeIndex[iq].second;
/* Computing the divergence for constant jacobian elements */
DivergenceofPhi(iq,0) = datavec[ublock].fNormalVec(0,ivectorindex)*GradphiuH1(0,ishapeindex) +
datavec[ublock].fNormalVec(1,ivectorindex)*GradphiuH1(1,ishapeindex) +
datavec[ublock].fNormalVec(2,ivectorindex)*GradphiuH1(2,ishapeindex) ;
}
}
return;
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::Write(TPZStream &buf, int withclassid) {
TPZDiscontinuousGalerkin::Write(buf, withclassid);
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::Read(TPZStream &buf, void *context) {
TPZDiscontinuousGalerkin::Read(buf, context);
}
// Divergence on master element
void TPZDarcy2DMaterial::ComputeDivergenceOnMaster(TPZVec<TPZMaterialData> &datavec, TPZFMatrix<STATE> &DivergenceofPhi, STATE &DivergenceofU)
{
int ublock = 0;
// Getting test and basis functions
TPZFNMatrix<100,REAL> phiuH1 = datavec[ublock].phi; // For H1 test functions Q
TPZFNMatrix<300,REAL> dphiuH1 = datavec[ublock].dphi; // Derivative For H1 test functions
TPZFNMatrix<300,REAL> dphiuH1axes = datavec[ublock].dphix; // Derivative For H1 test functions
TPZFNMatrix<9,STATE> gradu = datavec[ublock].dsol[0];
TPZFNMatrix<9,STATE> graduMaster;
gradu.Transpose();
TPZFNMatrix<660> GradphiuH1;
TPZAxesTools<REAL>::Axes2XYZ(dphiuH1axes, GradphiuH1, datavec[ublock].axes);
int nphiuHdiv = datavec[ublock].fVecShapeIndex.NElements();
DivergenceofPhi.Resize(nphiuHdiv,1);
REAL JacobianDet = datavec[ublock].detjac;
TPZFNMatrix<9,REAL> Qaxes = datavec[ublock].axes;
TPZFNMatrix<9,REAL> QaxesT;
TPZFNMatrix<9,REAL> Jacobian = datavec[ublock].jacobian;
TPZFNMatrix<9,REAL> JacobianInverse = datavec[ublock].jacinv;
TPZFNMatrix<9,REAL> GradOfX;
TPZFNMatrix<9,REAL> GradOfXInverse;
TPZFNMatrix<9,REAL> VectorOnMaster;
TPZFNMatrix<9,REAL> VectorOnXYZ(3,1,0.0);
Qaxes.Transpose(&QaxesT);
QaxesT.Multiply(Jacobian, GradOfX);
JacobianInverse.Multiply(Qaxes, GradOfXInverse);
TPZFMatrix<STATE> GradOfXInverseSTATE(GradOfXInverse.Rows(), GradOfXInverse.Cols());
for (unsigned int i = 0; i < GradOfXInverse.Rows(); ++i) {
for (unsigned int j = 0; j < GradOfXInverse.Cols(); ++j) {
GradOfXInverseSTATE(i,j) = GradOfXInverse(i,j);
}
}
int ivectorindex = 0;
int ishapeindex = 0;
if (HDivPiola == 1)
{
for (int iq = 0; iq < nphiuHdiv; iq++)
{
ivectorindex = datavec[ublock].fVecShapeIndex[iq].first;
ishapeindex = datavec[ublock].fVecShapeIndex[iq].second;
for (int k = 0; k < fDimension; k++) {
VectorOnXYZ(k,0) = datavec[ublock].fNormalVec(k,ivectorindex);
}
GradOfXInverse.Multiply(VectorOnXYZ, VectorOnMaster);
VectorOnMaster *= JacobianDet;
/* Contravariant Piola mapping preserves the divergence */
for (int k = 0; k < fDimension; k++) {
DivergenceofPhi(iq,0) += dphiuH1(k,ishapeindex)*VectorOnMaster(k,0);
}
}
}
else
{
for (int iq = 0; iq < nphiuHdiv; iq++)
{
ivectorindex = datavec[ublock].fVecShapeIndex[iq].first;
ishapeindex = datavec[ublock].fVecShapeIndex[iq].second;
/* Computing the divergence for constant jacobian elements */
REAL dot = 0.0;
for (int i = 0; i < fDimension; i++) {
dot += datavec[ublock].fNormalVec(i,ivectorindex)*GradphiuH1(i,ishapeindex);
}
DivergenceofPhi(iq,0) = dot;
}
}
return;
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::FillGradPhi(TPZMaterialData &dataV, TPZVec< TPZFMatrix<REAL> > &GradPhi){
TPZFMatrix<REAL> &dphiV = dataV.dphix;
const int dim = this->Dimension();
GradPhi.clear();
GradPhi.resize(dim);
//for each shape
for(int shape = 0; shape < dphiV.Rows(); shape++){
TPZFMatrix<REAL> GPhi(dim,dim,0.);
for(int i = 0; i < dim; i++){
for(int j = 0; j < dim; j++){
GPhi(i,j) = dphiV(j,shape);// itapopo H1 ??
}//j
}//i
GradPhi[shape] = GPhi;
}//shape
}
// Contricucao dos elementos internos
void TPZDarcy2DMaterial::Contribute(TPZVec<TPZMaterialData> &datavec, REAL weight, TPZFMatrix<STATE> &ek, TPZFMatrix<STATE> &ef){
#ifdef PZDEBUG
//2 = 1 Vel space + 1 Press space
int nref = datavec.size();
if (nref != 2 ) {
std::cout << " Erro. The size of the datavec is different from 2 \n";
DebugStop();
}
#endif
const int vindex = this->VIndex();
const int pindex = this->PIndex();
if (datavec[vindex].fVecShapeIndex.size() == 0) {
FillVecShapeIndex(datavec[vindex]);
}
// Setting the phis
// V
TPZFMatrix<REAL> &phiV = datavec[vindex].phi;
TPZFMatrix<REAL> &dphiV = datavec[vindex].dphix;
// P
TPZFMatrix<REAL> &phiP = datavec[pindex].phi;
TPZFMatrix<REAL> &dphiP = datavec[pindex].dphix;
TPZFNMatrix<220,REAL> dphiVx(fDimension,dphiV.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiV, dphiVx, datavec[vindex].axes);
TPZFNMatrix<220,REAL> dphiPx(fDimension,phiP.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiP, dphiPx, datavec[pindex].axes);
int nshapeV=0, nshapeP=0;
nshapeP = phiP.Rows();
nshapeV = datavec[vindex].fVecShapeIndex.NElements();
TPZVec<STATE> f(fDimension);
for (int e=0; e<fDimension; e++) {
f[e] = 0.;
}
TPZFNMatrix<9,REAL> InvPermTensor = fInvK;
TPZFMatrix<STATE> phiVi(fDimension,1,0.0),phiVj(fDimension,1,0.0);
TPZFNMatrix<100,STATE> divphi;
STATE divu=0.;
this->ComputeDivergenceOnMaster(datavec, divphi, divu);
for(int i = 0; i < nshapeV; i++ )
{
int iphi = datavec[vindex].fVecShapeIndex[i].second;
int ivec = datavec[vindex].fVecShapeIndex[i].first;
TPZFNMatrix<4> GradVi(fDimension,fDimension);
for (int e=0; e<fDimension; e++) {
phiVi(e,0) = phiV(iphi,0)*datavec[vindex].fNormalVec(e,ivec);
for (int f=0; f<fDimension; f++) {
GradVi(e,f) = datavec[vindex].fNormalVec(e,ivec)*dphiVx(f,iphi);
}
}
// matrix A - velocity * test-funtion velocity
for(int j = 0; j < nshapeV; j++){
int jphi = datavec[vindex].fVecShapeIndex[j].second;
int jvec = datavec[vindex].fVecShapeIndex[j].first;
TPZFNMatrix<4> GradVj(fDimension,fDimension);
for (int e=0; e<fDimension; e++) {
phiVj(e,0) = phiV(jphi,0)*datavec[vindex].fNormalVec(e,jvec);
}
TPZFNMatrix<3,REAL> KphiVj(fDimension,1,0.);
//dot product between Kinv[u]v
for(int id=0; id<fDimension; id++){
for(int jd=0; jd<fDimension; jd++){
KphiVj(id,0) += InvPermTensor(id,jd)*phiVj(jd,0);
}
}
STATE val = InnerVec(phiVi, KphiVj);
ek(i,j) += weight * fViscosity * val ;
// InvPermTensor.Print("InvK = ");
// PermTensor.Print("K = ");
// KphiVj.Print("Kphi = ");
// phiVj.Print("phi = ");
}
// matrix B and Bt - pressure * test-funtion velocity and symmetry
for (int j = 0; j < nshapeP; j++) {
TPZManVector<REAL,3> GradPj(fDimension);
for (int e=0; e<fDimension; e++) {
GradPj[e] = dphiPx(e,j);
}
STATE fact=0.;
if (HDivPiola == 1) {
fact = weight * phiP(j,0) * divphi(i,0) / datavec[vindex].detjac; ///p*div(U)
}
else{
fact = weight * phiP(j,0) * Tr( GradVi ); ///p*div(U)
}
// colocar vectoriais vezes pressao
// Matrix B
ek(i, nshapeV+j) += -fact;
// colocar pressao vezes vectoriais
// Matrix B^T
ek(nshapeV+j,i) += fact;
}
}
if(this->HasForcingFunction()){
TPZFMatrix<STATE> gradu;
this->ForcingFunction()->Execute(datavec[vindex].x, f, gradu);
}
else{
f[0] = 0.0;
}
for (int i = 0; i < nshapeP; i++) {
STATE factf= weight * phiP(i,0)*f[0];
ef(nshapeV+i,0) += factf;
}
}
void TPZDarcy2DMaterial::ContributeBC(TPZVec<TPZMaterialData> &datavec, REAL weight, TPZFMatrix<STATE> &ek, TPZFMatrix<STATE> &ef, TPZBndCond &bc){
#ifdef PZDEBUG
//2 = 1 Vel space + 1 Press space
int nref = datavec.size();
if (nref != 2 ) {
std::cout << " Erro. The size of the datavec is different from 2 \n";
DebugStop();
}
#endif
const int vindex = this->VIndex();
const int pindex = this->PIndex();
if (datavec[vindex].fVecShapeIndex.size() == 0) {
FillVecShapeIndex(datavec[vindex]);
}
// Setting the phis
// V
TPZFMatrix<REAL> &phiV = datavec[vindex].phi;
TPZFMatrix<REAL> &dphiV = datavec[vindex].dphix;
// P
TPZFMatrix<REAL> &phiP = datavec[pindex].phi;
// Getting the linear combination or finite element approximations
TPZManVector<STATE> v_h = datavec[vindex].sol[0];
TPZManVector<STATE> p_h = datavec[pindex].sol[0];
TPZFNMatrix<220,REAL> dphiVx(fDimension,dphiV.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiV, dphiVx, datavec[vindex].axes);
int nshapeV, nshapeP;
nshapeP = phiP.Rows();
// nshapeV = datavec[vindex].fVecShapeIndex.NElements();
nshapeV = phiV.Rows();
//Adaptação para Hdiv
// int ekr= ek.Rows();
//Vefifica se HDiv
// if(ekr!=nshapeP+nshapeV){
// nshapeV=nshapeV/2;
// }
TPZFNMatrix<9> phiVi(fDimension,1), phiVj(fDimension,1), phiPi(fDimension,1),phiPj(fDimension,1);
TPZFMatrix<STATE> v_2=bc.Val2();
TPZFMatrix<STATE> v_1=bc.Val1();
STATE p_D = bc.Val1()(0,0);
switch (bc.Type()) {
case 0: //Dirichlet for continuous formulation
{
if(bc.HasForcingFunction())
{
TPZManVector<STATE> vbc(3);
TPZFNMatrix<9,STATE> gradu(2,1);
bc.ForcingFunction()->Execute(datavec[vindex].x,vbc,gradu);
v_2(0,0) = vbc[0];
v_2(1,0) = vbc[1];
p_D = vbc[2];
}
for(int i = 0; i < nshapeV; i++ )
{
ef(i,0) += -weight * p_D * phiV(i,0);
}
}
break;
case 1: //Neumann for continuous formulation
{
if(bc.HasForcingFunction())
{
TPZManVector<STATE> vbc(3);
TPZFNMatrix<9,STATE> gradu(2,1);
bc.ForcingFunction()->Execute(datavec[vindex].x,vbc,gradu);
v_2(0,0) = vbc[0];
v_2(1,0) = vbc[1];
p_D = vbc[2];
}
bool strong_Neumann = true; // @omar:: why enforced Neumann data results in a wrong solution?
if(strong_Neumann){
TPZManVector<REAL,3> n = datavec[0].normal;
REAL Vn = n[0]*v_2(0,0) + n[1]*v_2(1,0);
for(int i = 0; i < nshapeV; i++ )
{
ef(i) += gBigNumber * Vn * phiV(i,0);
for(int j = 0; j < nshapeV; j++){
ek(i,j) += gBigNumber * (phiV(i,0) * phiV(j,0));
}
}
}
else{
for(int i = 0; i < nshapeP; i++ )
{
TPZManVector<REAL> n = datavec[0].normal;
REAL v_n = n[0] * v_2[0] + n[1] * v_2[1];
STATE factf=(-1.) * weight * v_n * phiP(i,0);
//ef(i+nshapeV,0) += fTheta*factf ; //apapaPablo
}
}
}
break;
case 5: //Ponto pressao
{
p_D = bc.Val2()(0,0);
for(int i = 0; i < nshapeP; i++ )
{
ef(i+phiV.Rows()) += 1.0 * p_D * phiP(i,0);
for(int j = 0; j < nshapeP; j++){
ek(i+phiV.Rows(),j+phiV.Rows()) += 1.0 * (phiP(i,0) * phiP(j,0));
}
}
}
break;
default:
{
std::cout << "Boundary not implemented " << std::endl;
DebugStop();
}
break;
}
std::ofstream plotfileM("ekBC_Darcy2D.txt");
ek.Print("KBC = ",plotfileM,EMathematicaInput);
}
////////////////////////////////////////////////////////////////////
void TPZDarcy2DMaterial::ContributeInterface(TPZMaterialData &data, TPZVec<TPZMaterialData> &datavecleft, TPZVec<TPZMaterialData> &datavecright, REAL weight, TPZFMatrix<STATE> &ek,TPZFMatrix<STATE> &ef){
#ifdef PZDEBUG
//2 = 1 Vel space + 1 Press space for datavecleft
int nrefleft = datavecleft.size();
if (nrefleft != 2 ) {
std::cout << " Erro. The size of the datavec is different from 2 \n";
DebugStop();
}
//2 = 1 Vel space + 1 Press space for datavecright
int nrefright = datavecright.size();
if (nrefright != 2 ) {
std::cout << " Erro. The size of the datavec is different from 2 \n";
DebugStop();
}
#endif
const int vindex = this->VIndex();
const int pindex = this->PIndex();
if (datavecleft[vindex].fVecShapeIndex.size() == 0) {
FillVecShapeIndex(datavecleft[vindex]);
}
if (datavecright[vindex].fVecShapeIndex.size() == 0) {
FillVecShapeIndex(datavecright[vindex]);
}
// Setting the phis
// V - left
TPZFMatrix<REAL> &dphiV1 = datavecleft[vindex].dphix;
// V - right
TPZFMatrix<REAL> &dphiV2 = datavecright[vindex].dphix;
// P - left
TPZFMatrix<REAL> &phiP1 = datavecleft[pindex].phi;
TPZFMatrix<REAL> &dphiP1 = datavecleft[pindex].dphix;
// P - right
TPZFMatrix<REAL> &phiP2 = datavecright[pindex].phi;
TPZFMatrix<REAL> &dphiP2 = datavecright[pindex].dphix;
//Normal
TPZManVector<REAL,3> &normal = data.normal;
TPZFNMatrix<220,REAL> dphiVx1(fDimension,dphiV1.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiV1, dphiVx1, datavecleft[vindex].axes);
TPZFNMatrix<220,REAL> dphiVx2(fDimension,dphiV2.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiV2, dphiVx2, datavecright[vindex].axes);
TPZFNMatrix<220,REAL> dphiPx1(fDimension,phiP1.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiP1, dphiPx1, datavecleft[pindex].axes);
TPZFNMatrix<220,REAL> dphiPx2(fDimension,phiP2.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiP2, dphiPx2, datavecright[pindex].axes);
int nshapeV1, nshapeV2, nshapeP1,nshapeP2;
nshapeV1 = datavecleft[vindex].fVecShapeIndex.NElements();
nshapeV2 = datavecright[vindex].fVecShapeIndex.NElements();
nshapeP1 = phiP1.Rows();
nshapeP2 = phiP2.Rows();
for(int i1 = 0; i1 < nshapeV1; i1++ )
{
int iphi1 = datavecleft[vindex].fVecShapeIndex[i1].second;
int ivec1 = datavecleft[vindex].fVecShapeIndex[i1].first;
TPZFNMatrix<9> GradV1ni(fDimension,1,0.),phiV1i(fDimension,1),phiV1ni(1,1,0.);
for (int e=0; e<fDimension; e++) {
phiV1i(e,0)=datavecleft[vindex].fNormalVec(e,ivec1)*datavecleft[vindex].phi(iphi1,0);
phiV1ni(0,0)+=phiV1i(e,0)*normal[e];
for (int f=0; f<fDimension; f++) {
GradV1ni(e,0)+=datavecleft[vindex].fNormalVec(e,ivec1)*dphiVx1(f,iphi1)*normal[f];
}
}
TPZFNMatrix<9> GradV1nj(fDimension,1,0.);
// K12 e K21 - (trial V left) * (test P left)
for(int j1 = 0; j1 < nshapeP1; j1++){
TPZFNMatrix<9> phiP1j(1,1,0.);
phiP1j(0,0)=phiP1(j1,0);
REAL fact = (1./2.) * weight * Inner(phiV1ni,phiP1j);
ek(i1,j1+nshapeV1) += fact;
ek(j1+nshapeV1,i1) += fact*fTheta;
}
// K14 e K41 - (trial V left) * (test P right)
for(int j2 = 0; j2 < nshapeP2; j2++){
TPZFNMatrix<9> phiP2j(1,1,0.);
phiP2j(0,0)=phiP2(j2,0);
REAL fact = (1./2.) * weight * InnerVec(phiV1ni,phiP2j);
ek(i1,j2+2*nshapeV1+nshapeP1) += fact;
ek(j2+2*nshapeV1+nshapeP1,i1) += fact*fTheta;
}
}
for(int i2 = 0; i2 < nshapeV2; i2++ ){
TPZFNMatrix<9> GradV2ni(fDimension,1,0.),phiV2i(fDimension,1),phiV2ni(1,1,0.);
int iphi2 = datavecright[vindex].fVecShapeIndex[i2].second;
int ivec2 = datavecright[vindex].fVecShapeIndex[i2].first;
for (int e=0; e<fDimension; e++) {
phiV2i(e,0)=datavecright[vindex].fNormalVec(e,ivec2)*datavecright[vindex].phi(iphi2,0);
phiV2ni(0,0)+=phiV2i(e,0)*normal[e];
for (int f=0; f<fDimension; f++) {
GradV2ni(e,0) += datavecright[vindex].fNormalVec(e,ivec2)*dphiVx2(f,iphi2)*normal[f];
}
}
// K32 - (trial V right) * (test P left)
for(int j1 = 0; j1 < nshapeP1; j1++){
TPZFNMatrix<9> phiP1j(1,1,0.);
phiP1j(0,0)=phiP1(j1,0);
REAL fact = (-1./2.) * weight * InnerVec(phiV2ni,phiP1j);
ek(i2+nshapeV1+nshapeP1,j1+nshapeV1) += fact;
ek(j1+nshapeV1,i2+nshapeV1+nshapeP1) += fact*fTheta;
}
// K34 - (trial V right) * (test P right)
for(int j2 = 0; j2 < nshapeP2; j2++){
TPZFNMatrix<9> phiP2j(1,1,0.);
phiP2j(0,0)=phiP2(j2,0);
REAL fact = (-1./2.) * weight * InnerVec(phiV2ni,phiP2j);
ek(i2+nshapeV1+nshapeP1,j2+2*nshapeV1+nshapeP1) += fact;
ek(j2+2*nshapeV1+nshapeP1,i2+nshapeV1+nshapeP1) += fact*fTheta;
}
}
}
void TPZDarcy2DMaterial::ContributeBCInterface(TPZMaterialData &data, TPZVec<TPZMaterialData> &datavec, REAL weight, TPZFMatrix<STATE> &ek, TPZFMatrix<STATE> &ef, TPZBndCond &bc){
#ifdef IsH1
//Caso H1 -> return
return;
#endif
#ifdef PZDEBUG
//2 = 1 Vel space + 1 Press space
int nref = datavec.size();
if (nref != 2 ) {
std::cout << " Erro. The size of the datavec is different from 2 \n";
DebugStop();
}
#endif
const int vindex = this->VIndex();
const int pindex = this->PIndex();
if (datavec[vindex].fVecShapeIndex.size() == 0) {
FillVecShapeIndex(datavec[vindex]);
}
// Setting the phis
// V
TPZFMatrix<REAL> &dphiV = datavec[vindex].dphix;
// P
TPZFMatrix<REAL> &phiP = datavec[pindex].phi;
TPZFMatrix<REAL> &dphiP = datavec[pindex].dphix;
TPZFNMatrix<220,REAL> dphiVx(fDimension,dphiV.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiV, dphiVx, datavec[vindex].axes);
TPZFNMatrix<220,REAL> dphiPx(fDimension,phiP.Cols());
TPZAxesTools<REAL>::Axes2XYZ(dphiP, dphiPx, datavec[pindex].axes);
int nshapeV, nshapeP;
nshapeP = phiP.Rows();
nshapeV = datavec[vindex].fVecShapeIndex.NElements();
TPZManVector<STATE> v_h = datavec[vindex].sol[0];
TPZManVector<STATE> p_h = datavec[pindex].sol[0];
//Dirichlet
TPZFMatrix<STATE> v_2=bc.Val2();
TPZFMatrix<STATE> v_1=bc.Val1();
STATE p_D = bc.Val1()(0,0);
if(bc.HasForcingFunction())
{
TPZManVector<STATE> vbc(3);
TPZFNMatrix<9,STATE> gradu(2,1);
bc.ForcingFunction()->Execute(datavec[vindex].x,vbc,gradu);
v_2(0,0) = vbc[0];
v_2(1,0) = vbc[1];
p_D=vbc[2];
}
for(int i = 0; i < nshapeP; i++ )
{
TPZManVector<REAL> n = data.normal;
REAL v_n = n[0] * v_2[0] + n[1] * v_2[1];
REAL v_t = n[1] * v_2[0] + n[0] * v_2[1];
if(fSpace==1){
STATE factf=(-1.) * weight * v_t * phiP(i,0) ;
ef(i+nshapeV,0) += fTheta*factf*0. ;
}
if(fSpace==3){
STATE factf2=(-1.) * weight * v_n * phiP(i,0) ;
ef(i+nshapeV,0) += fTheta*factf2*0.;
}
}
}
////////////////////////////////////////////////////////////////////
template <typename TVar>
TVar TPZDarcy2DMaterial::Inner(TPZFMatrix<TVar> &S, TPZFMatrix<TVar> &T){
//inner product of two tensors
if( S.Rows() != S.Cols() || T.Cols() != T.Rows() || S.Rows() != T.Rows() ) {
DebugStop();
}
#ifdef DEBUG
if( S.Rows() != S.Cols() || T.Cols() != T.Rows() || S.Rows() != T.Rows() ) {
DebugStop();
}
#endif
TVar Val = 0;
for(int i = 0; i < S.Cols(); i++){
for(int j = 0; j < S.Cols(); j++){
Val += S(i,j)*T(i,j);
}
}
return Val;
}
////////////////////////////////////////////////////////////////////
template <typename TVar>
TVar TPZDarcy2DMaterial::InnerVec(TPZFMatrix<TVar> &S, TPZFMatrix<TVar> &T){
//inner product of two vectors
#ifdef DEBUG
if( S.Rows() != S.Cols() || T.Cols() != T.Rows() || S.Rows() != T.Rows() ) {
DebugStop();
}
#endif
TVar Val = 0;
for(int j = 0; j < S.Cols(); j++){
for(int i = 0; i < S.Rows(); i++){
Val += S(i,j)*T(i,j);
}
}
return Val;
}
////////////////////////////////////////////////////////////////////
STATE TPZDarcy2DMaterial::Tr( TPZFMatrix<REAL> &GradU ){
#ifdef DEBUG
if( GradU.Rows() != GradU.Cols() ) {
DebugStop();
}
#endif
STATE Val = 0.;
for(int i = 0; i < GradU.Rows(); i++){
Val += GradU(i,i);
}
return Val;
}
/// transform a H1 data structure to a vector data structure
void TPZDarcy2DMaterial::FillVecShapeIndex(TPZMaterialData &data)
{
data.fNormalVec.Resize(fDimension,fDimension);
data.fNormalVec.Identity();
data.fVecShapeIndex.Resize(fDimension*data.phi.Rows());
for (int d=0; d<fDimension; d++) {
for (int i=0; i<data.phi.Rows(); i++) {
data.fVecShapeIndex[i*fDimension+d].first = d;
data.fVecShapeIndex[i*fDimension+d].second = i;
}
}
}
void TPZDarcy2DMaterial::Errors(TPZVec<TPZMaterialData> &data, TPZVec<STATE> &u_exact, TPZFMatrix<STATE> &du_exact, TPZVec<REAL> &errors)
{
errors.Resize(NEvalErrors());
errors.Fill(0.0);
TPZManVector<STATE> Velocity, Pressure;
Velocity.Fill(0.0);
Pressure.Fill(0.0);
this->Solution(data,VariableIndex("V"), Velocity);
this->Solution(data,VariableIndex("P"), Pressure);
int vindex = this->VIndex();
int pindex = this->PIndex();
TPZFMatrix<REAL> dudx(Dimension(),Dimension());
TPZFMatrix<STATE> &dsol = data[vindex].dsol[0];
TPZFMatrix<STATE> &dsolp = data[pindex].dsol[0];
//std::cout<<dsol<<std::endl;
//Adaptação feita para Hdiv
dsol.Resize(Dimension(),Dimension());
TPZFNMatrix<2,STATE> dsolxy(2,2), dsolxyp(2,1);
TPZAxesTools<STATE>::Axes2XYZ(dsol, dsolxy, data[vindex].axes);
TPZAxesTools<STATE>::Axes2XYZ(dsolp, dsolxyp, data[pindex].axes);
int shift = 3;
// velocity
//values[2] : erro norma L2
REAL diff, diffp;
errors[1] = 0.;
for(int i=0; i<Dimension(); i++) {
diff = Velocity[i] - u_exact[i];
errors[1] += diff*diff;
}
////////////////////////////////////////////////// H1 / GD
if(fSpace==2){
//values[2] : erro em semi norma H1
errors[2] = 0.;
TPZFMatrix<STATE> S(Dimension(),Dimension(),0.0);
for(int i=0; i<Dimension(); i++) {
for(int j=0; j<Dimension(); j++) {
S(i,j) = dsolxy(i,j) - du_exact(i,j);
}
}
diff = Inner(S, S);
errors[2] += diff;
//values[0] : erro em norma H1 <=> norma Energia
errors[0] = errors[1]+errors[2];
}
if(fSpace==3){
//values[2] : erro em semi norma H1
errors[2] = 0.;
TPZFMatrix<STATE> S(Dimension(),Dimension(),0.0);
for(int i=0; i<Dimension(); i++) {
for(int j=0; j<Dimension(); j++) {
S(i,j) = dsolxy(i,j) - du_exact(i,j);
}
}
diff = Inner(S, S);
errors[2] += diff;
//values[0] : erro em norma H1 <=> norma Energia
errors[0] = errors[1]+errors[2];
}
////////////////////////////////////////////////// H1 / GD
// pressure
/// values[1] : eror em norma L2
diffp = Pressure[0] - u_exact[2];
errors[shift+1] = diffp*diffp;
// pressure gradient error ....
errors[shift+2] = 0.;
TPZFMatrix<STATE> Sp(Dimension(),1,0.0);
for(int i=0; i<Dimension(); i++) {
Sp(i,0) = dsolxyp(i,0) - du_exact(2,i);
}
diffp = InnerVec(Sp, Sp);
errors[shift+2] += diffp;
//values[0] : erro em norma H1 <=> norma Energia
errors[shift] = errors[1+shift]+errors[2+shift];
////////////////////////////////////////////////// HDIV
if(fSpace==1){
/// erro norma HDiv
STATE Div_exact=0., Div=0.;
for(int i=0; i<Dimension(); i++) {
Div_exact+=du_exact(i,i);
Div+=dsolxy(i,i);
}
diff = Div-Div_exact;
errors[2] = diff*diff;
errors[0] = errors[1]+errors[2];
}
////////////////////////////////////////////////// HDIV
}
|
ae4996e1ac27a62908a9493539d1e978671a55f9
|
4f7cdc175fd45cf8e84ee8d99b9cdc341035d34c
|
/Dziedziczenie/ConsoleApplication27/Osobowe.cpp
|
f5eb74d406718cbe04802c46dffaff5b03c6d4c9
|
[] |
no_license
|
rafstudent/C_Plus_Plus_Cwiczenia
|
d2f975d20c05326df16883d78d3bcae19fe802f2
|
7789ef979bcc96aedd96b1112e121727b9afaf03
|
refs/heads/main
| 2023-08-11T13:09:01.259492
| 2021-10-01T10:43:10
| 2021-10-01T10:43:10
| 412,422,421
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 170
|
cpp
|
Osobowe.cpp
|
#include "stdafx.h"
#include "Osobowe.h"
Osobowe::Osobowe()
{
}
Osobowe::~Osobowe()
{
}
void Osobowe::typ_pojazdu()
{
std::cout << "Pojazd osobowy" << std::endl;
}
|
fe687d302e307141607f0e3f699b8e1ceaaf1cbd
|
6c4908ab3a012f18990b39d7e38b6dd6309f8cc5
|
/v2015_for_windows/helpers.h
|
58046588215cfde1e7665733448bea7f9508c237
|
[
"MIT"
] |
permissive
|
sea-kg/homemoney
|
729fe903c09d585cc7c7e971d260845bfd7cd3b1
|
ca74681cadee2ca195d45673f93524611eb8486f
|
refs/heads/master
| 2021-05-02T07:36:00.149296
| 2020-04-01T06:58:02
| 2020-04-01T06:58:02
| 34,119,520
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 662
|
h
|
helpers.h
|
//---------------------------------------------------------------------------
#ifndef helpersH
#define helpersH
#include <vcl.h>
//---------------------------------------------------------------------------
struct exlSheet {
int Number;
UnicodeString Name;
};
struct exlClass {
UnicodeString Class;
UnicodeString Name;
UnicodeString Comment;
UnicodeString Monthes;
};
struct exlMonth {
UnicodeString Name;
UnicodeString Class;
double Price;
UnicodeString Month;
// std::vector<UnicodeString> Hyperlinks;
UnicodeString LinkToClassification;
};
struct exlSumClass {
UnicodeString Name;
double Sum;
};
#endif
|
b1ca3461b305913dd35d8b0d494b7930fc392ada
|
4a39b3629aac3e436ea109a1fa6cb945a5b439be
|
/MPIRadixSort/Source.cpp
|
05ec25b8a3eec8b817665740d46f3e57b398f1d1
|
[] |
no_license
|
bogdandr14/RadixSortProject
|
c00433064d022319d5fbf0ae3d11d1f5c8ec2acb
|
5471b86c65238804cfd7196b0231c41f3febcc61
|
refs/heads/master
| 2023-04-05T02:58:50.663124
| 2021-04-27T10:21:29
| 2021-04-27T10:21:29
| 348,397,258
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,859
|
cpp
|
Source.cpp
|
#include<iostream>
#include<fstream>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<mpi.h>
#include<chrono>
#include<ctime>
#include<ratio>
using namespace std;
ifstream fin("../Inputs & Output/input5.txt");
ofstream fout("../Inputs & Output/output.txt");
#define BASE 256
int main(int& argc, char** argv) {
int PID, NO_PROCS, ELEM_FOR_PROCS, NO_ELEMENTS, element, addedZeros;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &NO_PROCS);
MPI_Comm_rank(MPI_COMM_WORLD, &PID);
fin >> NO_ELEMENTS;
addedZeros = (NO_PROCS - NO_ELEMENTS % NO_PROCS) % NO_PROCS;
NO_ELEMENTS += addedZeros;
//Initialize array for elements to be sorted.
int** toSort = new int*[2];
toSort[0] = new int[NO_ELEMENTS];
toSort[1] = new int[NO_ELEMENTS];
for (int i = 0; i < NO_ELEMENTS; ++i) {
if (i < addedZeros) {
toSort[0][i] = 0;
}
else {
fin >> element;
toSort[0][i] = element;
}
}
ELEM_FOR_PROCS = NO_ELEMENTS / NO_PROCS;
//Get the current moment of the clock for timing the sorting duration.
std::chrono::steady_clock::time_point t1;
if (!PID) {
t1 = std::chrono::high_resolution_clock::now();
}
/*--------------------------------------------------------------------------------------------------*/
/*Compute the maximum value of numbers in the given array*/
//Initialize array for local elements and variables
int* maxSort = new int[ELEM_FOR_PROCS];
int globalMaxNumber, localMaxNumber = -1, noDigits = 0;
//Scatter data to each processor in order cu calculate the maximum number in the array.
MPI_Scatter(toSort[0], ELEM_FOR_PROCS, MPI_INT, maxSort, ELEM_FOR_PROCS, MPI_INT, 1, MPI_COMM_WORLD);
// Compute the local maximum number from the array of the current process.
for (int i = 0; i < ELEM_FOR_PROCS; i++) {
localMaxNumber = (maxSort[i] > localMaxNumber) ? maxSort[i] : localMaxNumber;
}
// Compute the global maximum number by comparing the local maximum numbers.
MPI_Reduce(&localMaxNumber, &globalMaxNumber, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD);
/*if (0 == PID) {
printf("Maximum number is %d.\n", globalMaxNumber);
}*/
// Compute the number of digits of the maximum number.
while (globalMaxNumber) {
++noDigits;
globalMaxNumber /= BASE;
}
delete[] maxSort;
// Initialize the arrays for counting.
int* countingSort = new int[ELEM_FOR_PROCS];
int* globalDigitCounter = new int[BASE], * localDigitCounter = new int[BASE];
//Repeat counting sort for each digit position.
for (int pos = 0; pos < noDigits; ++pos) {
int digitPos = (int)pow(BASE, pos);
int current = pos % 2, next = (pos + 1) % 2;
/*--------------------------------------------------------------------------------------------------*/
/*Parallel calculation that implements the counting sort in each process for a portion of the array.*/
//Send to each process an equally sized array that contains a different data segment.
MPI_Scatter(toSort[current], ELEM_FOR_PROCS, MPI_INT, countingSort, ELEM_FOR_PROCS, MPI_INT, 0, MPI_COMM_WORLD);
//Initialize the counter vector of the digits, at the position [pos].
for (int i = 0; i < BASE; ++i) {
localDigitCounter[i] = 0;
}
//Copy each element in the array in a new one and increment the counter for the digit at the [pos].
for (int i = 0; i < ELEM_FOR_PROCS; ++i) {
++localDigitCounter[(countingSort[i] / digitPos) % BASE];
}
//Create the prefix sum for the counter vector.
for (int i = 1; i < BASE; ++i) {
localDigitCounter[i] += localDigitCounter[i - 1];
}
//Sums the values from each counting array [parallelDigitCounter] and store the result in the counter [globalDigitCounter].
MPI_Reduce(localDigitCounter, globalDigitCounter, BASE, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
/*------------------------------------------------------------------------------------------------------*/
/* Move the elements to their new position in the array, according to the radix sort algorithm.*/
//Bottleneck must be improved
if (!PID) {
//for (int i = 0; i < BASE; ++i) {
// cout << globalDigitCounter[i] << " ";
//}
//cout << endl;
for (int i = NO_ELEMENTS - 1; i >= 0; --i) {
toSort[next][--globalDigitCounter[(toSort[current][i] / digitPos) % BASE]] = toSort[current][i];
}
}
}
if (!PID) {
//Get the current moment of the clock for the ending time of the sorting algorithm.
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
/*for (int i = addedZeros; i < NO_ELEMENTS; ++i) {
cout << toSort[noDigits % 2][i] << " ";
}*/
fout << time_span.count() * 1000;
}
delete[] localDigitCounter;
delete[] globalDigitCounter;
delete[] countingSort;
delete[] toSort[0];
delete[] toSort[1];
delete[] toSort;
MPI_Finalize();
return 0;
}
|
6e23631f712bcf26555a118f510e0a79922a1c3b
|
2f10f807d3307b83293a521da600c02623cdda82
|
/deps/boost/win/debug/include/boost/spirit/home/classic/phoenix/new.hpp
|
7d6047990a22516bdb746bc744a614d8611b804b
|
[] |
no_license
|
xpierrohk/dpt-rp1-cpp
|
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
|
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
|
refs/heads/master
| 2021-05-23T08:19:48.823198
| 2019-07-26T17:35:28
| 2019-07-26T17:35:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 130
|
hpp
|
new.hpp
|
version https://git-lfs.github.com/spec/v1
oid sha256:2242b6a8a4ca7b14837e5e9c0d23633e12dfe748cd7038bc35aed45d693df696
size 36855
|
feec2135afe7f748b6329d931568e750da072ae0
|
c5a9020dcb95483d1f051d47c7be1029da0fac23
|
/Олимпиадная теория/skanline/skanline.cpp
|
46c355a1f0ce198561c6904496afe59ae0f0ab52
|
[] |
no_license
|
ksercs/algo_school_base
|
4ec8635ff7df116ac5c914034e53aecf234df69c
|
7ced69b7e89e05299a7bcf4f6feac69eafa327de
|
refs/heads/master
| 2023-07-16T07:54:09.218823
| 2021-07-25T15:19:04
| 2021-07-25T15:19:04
| 389,377,358
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 823
|
cpp
|
skanline.cpp
|
#include <iostream>
#include <utility>
#include <algorithm>
#include <vector>
using namespace std;
const int MAX_SIZE = 2*1e5+15;
int st, fn, n;
vector <pair <int,int> > sg;
bool cmp(pair <int, int> pi1, pair <int, int> pi2)
{
if (pi1.first != pi2.first)
{
return pi1.first < pi2.first;
}
else
{
return pi1.second > pi2.second;
}
}
int main()
{
cin >>st >> fn;
cin>>n;
for(int i=0;i<n;i++)
{
int s,f;
cin >> s >>f;
sg.push_back(make_pair(s,1));
sg.push_back(make_pair(f,-1));
}
sort(sg.begin(), sg.end(), cmp);
cout <<"\nVIVOD:\n";
for(int i=0; i < sg.size(); i++)
{
cout <<"koor: "<< sg[i].first <<" flag: "<< sg[i].second<< "\n";
}
return 0;
}
|
79ee3c9c19b39f6ee4007d45151ff8f8ec31fcc2
|
e8b8bb87a29be924e24b40c51c666c5dcae1570f
|
/DashaMDM/Mdm/calendarwidget.h
|
c5daa38e381ab0d56cefcb552fbf8daf71698c34
|
[] |
no_license
|
Kennocke/Projects-QT
|
2c1cc2fdf475974f22276a6f47b6ac12054b454c
|
2c7aee87615126f80bebae8d7c9ac0385edfb7a5
|
refs/heads/master
| 2020-04-30T15:49:18.992945
| 2019-09-21T08:18:51
| 2019-09-21T08:18:51
| 176,931,052
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 407
|
h
|
calendarwidget.h
|
#ifndef CALENDARWIDGET_H
#define CALENDARWIDGET_H
#include <QCalendarWidget>
#include <QtGui>
class CalendarWidget : public QCalendarWidget
{
public:
CalendarWidget();
void addMeetDate(const QDate &date, QStringList list);
void paintCell(QPainter *painter, const QRect &rect, const QDate &date) const;
private:
QMap<QDate, QStringList> map;
};
#endif // CALENDARWIDGET_H
|
8fa9d8fc03a49009f51498380487d45b43419750
|
fe1dde5115a8ed3f88a56ffc29aeac5c8d846de6
|
/Practicum/Practicum 3/test.cpp
|
a5bdf1617450a2be4eb6ef52a2bc8bbc1e83a3f1
|
[] |
no_license
|
kevinawongw/CSCI1300-IntroToProgrammingCPP
|
301576c7910cda93e9774aeb509c64449efe32e3
|
3d223685e35618b9524ee1a92dac9017f77a4ca0
|
refs/heads/main
| 2023-09-02T13:20:48.115325
| 2021-11-16T21:21:42
| 2021-11-16T21:21:42
| 428,732,316
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 254
|
cpp
|
test.cpp
|
#include <iostream>
#include <string>
#include <math.h>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
int main (){
int mynum [5];
for (int i =1; i<5; i++){
mynum [i] = i +1;
cout << mynum[i];
}
}
|
9a550a7da65cf55cd7eb16f503857c78d83c28e4
|
427f48b76d1b312cff7af2d9b535ea333e8d154e
|
/cpp/preprocessor_conditional.cpp
|
40b4c6330e1ca51aafa8bbbc486fe34fa19e3e32
|
[
"MIT"
] |
permissive
|
rpuntaie/c-examples
|
8925146dd1a59edb137c6240363e2794eccce004
|
385b3c792e5b39f81a187870100ed6401520a404
|
refs/heads/main
| 2023-05-31T15:29:38.919736
| 2021-06-28T16:53:07
| 2021-06-28T16:53:07
| 381,098,552
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 560
|
cpp
|
preprocessor_conditional.cpp
|
/*
g++ --std=c++20 -pthread -o ../_build/cpp/preprocessor_conditional.exe ./cpp/preprocessor_conditional.cpp && (cd ../_build/cpp/;./preprocessor_conditional.exe)
https://en.cppreference.com/w/cpp/preprocessor/conditional
*/
#define ABCD 2
#include <iostream>
int main()
{
#ifdef ABCD
std::cout << "1: yes\n";
#else
std::cout << "1: no\n";
#endif
#ifndef ABCD
std::cout << "2: no1\n";
#elif ABCD == 2
std::cout << "2: yes\n";
#else
std::cout << "2: no2\n";
#endif
#if !defined(DCBA) && (ABCD < 2*4-3)
std::cout << "3: yes\n";
#endif
}
|
324fa1ba0f9279f621e3a9dc28e700ec0a8b5e86
|
d730d60cb911feeb0fea21af33a21d5fe4181484
|
/zombie_game/Floor.h
|
1158b6e2c623566a5c07a9532f6c248cdfd13c8d
|
[] |
no_license
|
marhotiewer/thga_groep9
|
5781b850e4c67b0d270fb78000b6147e5ba31d53
|
f9f0b1cef8c9cfcb3824df84885c2347f1b80f36
|
refs/heads/master
| 2023-02-27T20:47:44.641540
| 2021-01-31T19:35:00
| 2021-01-31T19:35:00
| 318,533,945
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,481
|
h
|
Floor.h
|
#ifndef FLOOR_H
#define FLOOR_H
#include <SFML/Graphics.hpp>
#include "Static.h"
/// @file
/// \class Floor
/// \brief
/// Class for floor tiles.
/// \details
/// The Floor Class is a class for the floors in the game.
/// The Floor Class has one overriding functions(isCoolliding).
/// All functions are inherited from Static, and Static inherited it's functions from Drawable.
/// The Texture used for the Floor is the FloorTexture and is loaded from the AssetManager class.
class Floor : public Static
{
public:
/// <summary>
/// The floor needs a AssetManager to load the texture of the floor.
/// The floor also needs a position and a size. To place the floor on the correct spot.
/// </summary>
/// <param name="assets">AssetManager required for textures</param>
/// <param name="pos">Position to place the Floor</param>
/// <param name="size">Size of the Floor to be placed</param>
Floor(AssetManager& assets, sf::Vector2f pos, sf::Vector2i size);
/// <summary>
/// Overriding isColliding function Floor.
/// </summary>
/// <param name="drawable"></param>
/// <param name="delta"></param>
/// <returns>Bool if colliding with other object.</returns>
bool isColliding(Drawable& drawable, sf::Vector2f delta = sf::Vector2f(0.f, 0.f)) override;
/// <summary>
/// Function that return the order of draw order.
/// </summary>
/// <returns>A 0. Because the floor is always lowest.</returns>
float Z_Order() override;
};
#endif
|
8269e9cd01bcb14a8c68822ea1e8e22394499378
|
b367fe5f0c2c50846b002b59472c50453e1629bc
|
/xbox_leak_may_2020/xbox trunk/xbox/private/windows/directx/dxg/tests/psprite/main.cpp
|
4a1e4c87610cf3d3ab6735f66b73c44ce53cf8f7
|
[] |
no_license
|
sgzwiz/xbox_leak_may_2020
|
11b441502a659c8da8a1aa199f89f6236dd59325
|
fd00b4b3b2abb1ea6ef9ac64b755419741a3af00
|
refs/heads/master
| 2022-12-23T16:14:54.706755
| 2020-09-27T18:24:48
| 2020-09-27T18:24:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,137
|
cpp
|
main.cpp
|
/*--
Copyright (c) 1999 - 2000 Microsoft Corporation - Xbox SDK
Module Name:
Main.cpp
Abstract:
Complete DX8 application to draw a screen space triangle.
Revision History:
Derived from a DX8 sample.
--*/
#ifdef XBOX
#include <xtl.h>
#else // XBOX
#include <windows.h>
#include <d3d8.h>
#include <d3dx8.h>
#endif // XBOX
const GUID DECLSPEC_SELECTANY IID_IUnknown =
{ 0x00000000, 0x0000, 0x0000, { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 } };
#define timeGetTime GetTickCount
#define g_pd3dDevice pDev
IDirect3DDevice8* pDev = NULL;
DWORD g_dwVertexShaderHandle; // Handle for the vertex shader
LPDIRECT3DTEXTURE8 g_pTexture = NULL;
struct CUSTOMVERTEX
{
FLOAT x,y,z;
float size;
};
CUSTOMVERTEX g_Vertices[] =
{
{ -0.6f, -1.0f, 0.0f, 10.1f, },
{ 0.0f, 1.0f, 0.0f, 30.5f, },
{ 0.6f, -1.0f, 0.0f, 60.9f, },
};
DWORD dwShaderVertexDecl[] =
{
D3DVSD_STREAM( 0 ),
D3DVSD_REG( 0, D3DVSDT_FLOAT3 ), // Position
D3DVSD_REG( 1, D3DVSDT_FLOAT1 ), // Point size
D3DVSD_END()
};
BOOL InitApp()
{
#ifdef XBOX
// Load the pre-compiled vertex shader microcode
HANDLE hFile = CreateFileA( "D:\\media\\Shader.xvu", GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN, NULL );
if( hFile == INVALID_HANDLE_VALUE )
{
OutputDebugStringA( "ERROR: Could not load the vertex shader!\n" );
return E_FAIL;
}
DWORD dwSize = GetFileSize( hFile, NULL );
BYTE* pData = new BYTE[dwSize];
ReadFile( hFile, pData, dwSize, &dwSize, NULL );
CloseHandle( hFile );
HRESULT hr = g_pd3dDevice->CreateVertexShader( dwShaderVertexDecl,
(DWORD*)pData,
&g_dwVertexShaderHandle, 0 );
delete pData;
#else // XBOX
ID3DXBuffer *pShader;
D3DXAssembleShaderFromFileA("shader.vsh", 0, NULL, &pShader, NULL);
HRESULT hr = g_pd3dDevice->CreateVertexShader( dwShaderVertexDecl,
(DWORD*)pShader->GetBufferPointer(),
&g_dwVertexShaderHandle, 0 );
pShader->Release();
#endif // XBOX
if (FAILED(hr))
return FALSE;
#ifdef XBOX
D3DXCreateTextureFromFileA(g_pd3dDevice, "D:\\media\\wall.bmp", &g_pTexture);
#else // XBOX
D3DXCreateTextureFromFileA(g_pd3dDevice, "wall.bmp", &g_pTexture);
#endif // XBOX
if (g_pTexture == NULL)
return FALSE;
return TRUE;
}
VOID Render()
{
// Clear the backbuffer and the zbuffer
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );
// Begin the scene
g_pd3dDevice->BeginScene();
// Set state
g_pd3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
g_pd3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, true);
g_pd3dDevice->SetRenderState( D3DRS_POINTSCALEENABLE, true);
float size = 40.0f;
g_pd3dDevice->SetRenderState( D3DRS_POINTSIZE, *((DWORD*)&size));
#ifdef XBOX
g_pd3dDevice->SetTexture(3, g_pTexture);
g_pd3dDevice->SetTextureStageState(3, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
g_pd3dDevice->SetTextureStageState(3, D3DTSS_COLORARG1, D3DTA_TEXTURE);
g_pd3dDevice->SetTextureStageState(3, D3DTSS_COLORARG2, D3DTA_CURRENT);
g_pd3dDevice->SetTextureStageState(3, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
#else // XBOX
g_pd3dDevice->SetTexture(0, g_pTexture);
g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
g_pd3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT);
g_pd3dDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_DISABLE);
#endif // XBOX
// Draw the vertices using the vertex shader
g_pd3dDevice->SetVertexShader( g_dwVertexShaderHandle );
g_pd3dDevice->DrawPrimitiveUP( D3DPT_POINTLIST, 3, g_Vertices,
sizeof(g_Vertices[0]) );
// End the scene
g_pd3dDevice->EndScene();
// Present the backbuffer contents to the display
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
VOID FrameMove()
{
// Rotate around the Y axis
D3DXMATRIX matWorld;
D3DXMatrixIdentity( &matWorld );
D3DXMatrixRotationX( &matWorld, timeGetTime()/600.0f );
// Set up our view matrix. A view matrix can be defined given an eye point,
// a point to lookat, and a direction for which way is up.
D3DXMATRIX matView;
D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( 0.0f, 0.0f,-3.0f ),
&D3DXVECTOR3( 0.0f, 0.0f, 0.0f ),
&D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) );
// For the projection matrix, we set up a perspective transform (which
// transforms geometry from 3D view space to 2D viewport space, with
// a perspective divide making objects smaller in the distance). To build
// a perpsective transform, we need the field of view (1/4 pi is common),
// the aspect ratio, and the near and far clipping planes (which define at
// what distances geometry should be no longer be rendered).
D3DXMATRIX matProj;
float aspectRatio = 480.f / 640.f;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, aspectRatio, 1.0f, 800.0f );
// Calculate concatenated World x ( View x Projection) matrix.
// We transpose the matrix at the end because that's how matrix math
// works in vertex shaders. (Because the vertex shader DP4 operator works on
// rows, not on columns.)
D3DXMATRIX mat;
D3DXMatrixMultiply( &mat, &matView, &matProj );
D3DXMatrixMultiply( &mat, &matWorld, &mat );
D3DXMatrixTranspose( &mat, &mat );
g_pd3dDevice->SetVertexShaderConstant( 0, &mat, 4 );
}
BOOL InitD3D(HWND hWnd)
{
D3DPRESENT_PARAMETERS d3dpp;
IDirect3D8 *pD3D;
// Create D3D 8.
pD3D = Direct3DCreate8(D3D_SDK_VERSION);
if (pD3D == NULL)
return FALSE;
// Set the screen mode.
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.BackBufferWidth = 640;
d3dpp.BackBufferHeight = 480;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.BackBufferCount = 1;
d3dpp.Windowed = FALSE; // Must be FALSE for Xbox.
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D24S8;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.hDeviceWindow = hWnd;
d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
// Create the device.
if (IDirect3D8_CreateDevice(
pD3D,
D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
&d3dpp,
&pDev) != S_OK)
{
return FALSE;
}
// Now we no longer need the D3D interface so lets free it.
IDirect3D8_Release(pD3D);
return InitApp();
}
#ifdef XBOX
//-----------------------------------------------------------------------------
void __cdecl main()
{
if (!InitD3D(NULL))
{
return;
}
while (TRUE)
{
FrameMove();
Render();
}
}
#else // XBOX
LRESULT WINAPI MessageHandler(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
if (Msg == WM_DESTROY)
PostQuitMessage(0);
return DefWindowProc(hWnd, Msg, wParam, lParam);
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
BOOL bQuit = FALSE;
MSG msg;
HWND hwnd;
WNDCLASSEX classex;
ZeroMemory( &classex, sizeof(classex) );
classex.cbSize = sizeof(WNDCLASSEX);
classex.style = CS_CLASSDC;
classex.lpfnWndProc = MessageHandler;
classex.hInstance = hInstance;
classex.lpszClassName = L"XBOX";
RegisterClassEx(&classex);
hwnd = CreateWindowEx(WS_EX_TOPMOST, L"XBOX", L"XBOX Basic Shell",
WS_VISIBLE|WS_POPUP,
CW_USEDEFAULT,CW_USEDEFAULT, 0, 0,
NULL, NULL, hInstance, NULL);
if (!InitD3D(hwnd))
{
return EXIT_FAILURE;
}
ShowCursor(FALSE);
while (!bQuit)
{
while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE))
{
if (!GetMessage(&msg, NULL, 0, 0))
{
bQuit = TRUE;
}
TranslateMessage(&msg);
DispatchMessage(&msg);
}
FrameMove();
Render();
}
return EXIT_SUCCESS;
}
#endif // XBOX
|
23c7af4052b8ffe6f36bb5b683ec8301dcd54cb0
|
43193782119bdd410538c0f9c8a83be0053351e4
|
/Opportunity.ChakraBridge.WinRT/Value/JsBoolean.h
|
f81cb84069e75555ec48b01d8ed9f264b68d0c87
|
[
"MIT"
] |
permissive
|
OpportunityLiu/ChakraBridge
|
454e89ed1d766a139a3228ab1178f1c89ad7237e
|
38e3eb058a94fb2f8bab0aed19af2dbfdbb556f3
|
refs/heads/master
| 2020-03-21T20:52:55.327616
| 2018-07-31T08:31:49
| 2018-07-31T08:31:49
| 139,034,175
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,954
|
h
|
JsBoolean.h
|
#pragma once
#include "JsValue.h"
#include "JsEnum.h"
namespace Opportunity::ChakraBridge::WinRT
{
/// <summary>
/// A JavaScript boolean value.
/// </summary>
public interface class IJsBoolean : IJsValue
{
/// <summary>
/// Retrieves the <see langword="bool"/> value of a <see cref="IJsBoolean"/> value.
/// </summary>
/// <remarks>Requires an active script context.</remarks>
bool ToBoolean();
};
ref class JsBooleanImpl sealed : JsValueImpl, [Default] IJsBoolean
{
internal:
JsBooleanImpl(RawValue ref);
INHERIT_INTERFACE_R_PROPERTY(Type, JsType, IJsValue);
INHERIT_INTERFACE_R_PROPERTY(Context, JsContext^, IJsValue);
INHERIT_INTERFACE_METHOD(ToInspectable, object^, IJsValue);
public:
virtual string^ ToString() override;
virtual bool ToBoolean();
};
/// <summary>
/// Static methods of <see cref="IJsBoolean"/>.
/// </summary>
public ref class JsBoolean sealed
{
private:
JsBoolean() {}
public:
/// <summary>
/// Gets the value of <see langword="true"/> in the current script context.
/// </summary>
/// <remarks>Requires an active script context.</remarks>
static DECL_R_PROPERTY(IJsBoolean^, True);
/// <summary>
/// Gets the value of <see langword="false"/> in the current script context.
/// </summary>
/// <remarks>Requires an active script context.</remarks>
static DECL_R_PROPERTY(IJsBoolean^, False);
/// <summary>
/// Creates a <see cref="IJsBoolean"/> value from a <see langword="bool"/> value.
/// </summary>
/// <param name="booleanValue">The value to be converted.</param>
/// <returns>The converted value.</returns>
/// <remarks>Requires an active script context.</remarks>
static IJsBoolean^ Create(bool value);
};
}
|
e8867be946782cc9a4c268ee25ebd84d15e0535f
|
d5f29c6d41922ce565f0eb1ba932631f62076b27
|
/DatabaseDisplay/loginface.cpp
|
b20bb0e5566cdb67dafe90dfd4fcc63fa5330721
|
[] |
no_license
|
oliewalcp/DisplayDatabaseData
|
37ffefe7f69fdf6a76bafefec1a35b4ef9d30336
|
7dc309a09750fd38e88ac07baa9f076e88e1604d
|
refs/heads/master
| 2020-03-17T00:03:26.418290
| 2018-05-12T01:53:54
| 2018-05-12T01:53:54
| 133,101,830
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,771
|
cpp
|
loginface.cpp
|
#include "loginface.h"
#include "ui_loginface.h"
LoginFace::LoginFace(QTimer *time, QTimer *viceTimer, QWidget *parent) :
QDialog(parent),
ui(new Ui::LoginFace)
{
ui->setupUi(this);
this->timer = time;
this->vicetimer = viceTimer;
Application = parent;
AlreadyLogin = false;
ApplicationData::ReadLoginDataFile();//获取用户帐号数据
ui->IPPortNumber->setText(ApplicationData::IPPortNumber);
ui->UserID->setText(ApplicationData::UserID);
ui->Password->setText(ApplicationData::Password);
ui->Password->setEchoMode(QLineEdit::Password);
this->setWindowModality(Qt::ApplicationModal);//阻塞非当前窗口
cdbf = new ConnectDBFailed(parent);
}
LoginFace::~LoginFace()
{
delete conn;
delete cdbf;
delete ui;
}
//退出按钮按下事件
void LoginFace::on_pushButton_2_clicked()
{
exit(0);
}
//窗口关闭事件(重写)
void LoginFace::closeEvent(QCloseEvent *event)
{
exit(0);
}
//登录按钮按下事件
void LoginFace::on_pushButton_clicked()
{
ApplicationData::UserID = ui->UserID->text();
ApplicationData::Password = ui->Password->text();
ApplicationData::IPPortNumber = ui->IPPortNumber->text();
if(LoginEnterDatabase())
{
AlreadyLogin = true;
ApplicationData::WriteLoginDataFile();
timer->setInterval(1000);
vicetimer->setInterval(1000);
vicetimer->start();
timer->start();
this->hide();
}
else cdbf->show();//连接失败,弹出提示框
}
//判断是否成功连接数据库
bool LoginFace::LoginEnterDatabase()
{
QList<QString> host = ApplicationData::IPPortNumber.split(":");
QSqlDatabase con = QSqlDatabase::addDatabase("QODBC");
conn = &con;
QString dsn = QString("Driver={sql server};SERVER=%1;PORT=%2;UID=%3;PWD=%4;")
.arg(host[0])//主机IP
.arg(host[1].toInt())//端口号
.arg(ApplicationData::UserID)//用户名
.arg(ApplicationData::Password);//密码
conn->setDatabaseName(dsn);//设置驱动
return conn->open();
}
//获取登录状态
bool LoginFace::getStatus()
{
return AlreadyLogin;
}
QSqlQuery* LoginFace::getQueryObject(bool &success)
{
QSqlQuery* query = new QSqlQuery();
query->exec(ApplicationData::UseDB);
query->prepare(ApplicationData::SQLCode);
success = query->exec();
return query;
}
QSqlQuery* LoginFace::getQueryObject(QString sql, bool &success)
{
if(sql == "")
{
success = false;
return nullptr;
}
QSqlQuery* query = new QSqlQuery();
query->exec(ApplicationData::UseDB);
query->prepare(sql);
success = query->exec();
return query;
}
|
2cb490758250b92de165b9fbe991e64385741e8c
|
ea7f03d849b1c4f2175bfbaf6e4859d7e49c52d6
|
/APMMAVLink/DataLink/DebugDataLink.h
|
456a3310ff83eb32288b858cd769340c5e873913
|
[] |
no_license
|
rdmenezes/lucas-research
|
c71260e676f5d87a88eefa759ee04828267ea215
|
e6f4e90da8674d3abb9be76772c9ab682b2c4685
|
refs/heads/master
| 2021-01-01T05:32:32.143559
| 2012-07-23T12:35:10
| 2012-07-23T12:35:10
| 32,968,961
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 303
|
h
|
DebugDataLink.h
|
#ifndef DebugDataLink_h
#define DebugDataLink_h
#include <stdio.h>
#include "FileDataLink.h"
#ifdef _WIN32
class __declspec( dllexport ) DebugDataLink : public FileDataLink {
#else
class DebugDataLink : public FileDataLink
#endif
public:
DebugDataLink() : FileDataLink(stdout, stdin) {}
};
#endif
|
c3c50f32fb3c51d28ca643b2161ae44d4d770878
|
b0dfae6aad9c84a202e21adfbeba912dcba6bafb
|
/BinaryPreOrder.cpp
|
c004ebf78bf5ff3884b856142f39342843c16d01
|
[] |
no_license
|
Botao326/LeetCodeSolution
|
487386719eae62282812908bbb2572417e419a2c
|
fa01b5eb025a9cd9a330a4a490376ae174d7c46b
|
refs/heads/master
| 2021-01-13T04:14:29.277354
| 2018-05-15T12:43:56
| 2018-05-15T12:43:56
| 77,462,596
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,260
|
cpp
|
BinaryPreOrder.cpp
|
//
// Created by Tao on 23/12/2016.
//
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <algorithm>
#include <stack>
using namespace std;
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if (root == NULL) return res;
stack<TreeNode *> stk;
stk.push(root);
while(!stk.empty()) {
TreeNode *current = stk.top();
res.push_back(current->val);
stk.pop();
if (current->right != NULL) {
stk.push(current->right);
}
if (current->left != NULL){
stk.push(current->left);
}
}
return res;
}
/*
* void inorderTranverse(TreeNode* node, vector<int> & res){
if (node == NULL)
return;
inorderTranverse(node->left, res);
res.push_back(node->val);
inorderTranverse(node->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorderTranverse(root, res);
return res;
}
*/
};
|
3d203bc959bf8ee1fd7cfb66f5698fae00cc1ff2
|
df3b4413977f6385aafcd9c54e07200d52b59684
|
/RBV2/RBV2.ino
|
68e1199cfac649a6344726cd899f8c0a592dd6b4
|
[] |
no_license
|
vmsrobotics/RBV2
|
8e7473cdd05aed30ce7c9616d5af3a73f07663f9
|
3b6ad7546bd7fbae9f20b9991df2c767c781cc98
|
refs/heads/master
| 2021-01-11T04:45:59.837343
| 2017-10-04T21:00:06
| 2017-10-04T21:00:06
| 71,125,650
| 1
| 0
| null | 2016-10-25T13:09:19
| 2016-10-17T10:15:29
|
HTML
|
UTF-8
|
C++
| false
| false
| 300
|
ino
|
RBV2.ino
|
bool oldMotorController = false; //set this to true if your robot is using the old-style, L298 dual H-bridge motor controller
//****************************** ENTER YOUR FUNCTIONS HERE *******************************************************************
void studentCode()
{
}
|
8ee8596ae50d7e5cf7d2cd4dad300ee4cb0ee96d
|
a3d6556180e74af7b555f8d47d3fea55b94bcbda
|
/extensions/common/manifest_constants.h
|
9d28f1b62db40212a9b50ce41a3a59495ec01754
|
[
"BSD-3-Clause"
] |
permissive
|
chromium/chromium
|
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
|
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
|
refs/heads/main
| 2023-08-24T00:35:12.585945
| 2023-08-23T22:01:11
| 2023-08-23T22:01:11
| 120,360,765
| 17,408
| 7,102
|
BSD-3-Clause
| 2023-09-10T23:44:27
| 2018-02-05T20:55:32
| null |
UTF-8
|
C++
| false
| false
| 20,485
|
h
|
manifest_constants.h
|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_COMMON_MANIFEST_CONSTANTS_H_
#define EXTENSIONS_COMMON_MANIFEST_CONSTANTS_H_
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
namespace extensions {
// Keys used in JSON representation of extensions.
namespace manifest_keys {
extern const char kAboutPage[];
extern const char kAction[];
extern const char kActionDefaultIcon[];
extern const char kActionDefaultPopup[];
extern const char kActionDefaultState[];
extern const char kActionDefaultTitle[];
extern const char kApp[];
extern const char kAutomation[];
extern const char kBackground[];
extern const char kBackgroundAllowJsAccess[];
extern const char kBackgroundPage[];
extern const char kBackgroundPersistent[];
extern const char kBackgroundScripts[];
extern const char kBackgroundServiceWorkerScript[];
extern const char kBackgroundServiceWorkerType[];
extern const char kBluetooth[];
extern const char kBookmarkUI[];
extern const char kBrowserAction[];
extern const char kBrowseURLs[];
extern const char kChromeOSSystemExtension[];
extern const char kCommands[];
extern const char kContentCapabilities[];
extern const char kContentSecurityPolicy[];
extern const char kContentSecurityPolicy_ExtensionPagesPath[];
extern const char kContentSecurityPolicy_IsolatedWorldPath[];
extern const char kContentSecurityPolicy_SandboxedPagesPath[];
extern const char kConvertedFromUserScript[];
extern const char kCurrentLocale[];
extern const char kDefaultLocale[];
extern const char kDescription[];
extern const char kDevToolsPage[];
extern const char kDifferentialFingerprint[];
extern const char kDisplayInLauncher[];
extern const char kDisplayInNewTabPage[];
extern const char kEventName[];
extern const char kExternallyConnectable[];
extern const char kEventRules[];
extern const char kFileAccessList[];
extern const char kFileHandlers[];
extern const char kFileHandlerExtensions[];
extern const char kFileHandlerIncludeDirectories[];
extern const char kFileHandlerTypes[];
extern const char kFileHandlerVerb[];
extern const char kFileFilters[];
extern const char kFileBrowserHandlerId[];
extern const char kFileBrowserHandlers[];
extern const char kGlobal[];
extern const char kHandwritingLanguage[];
extern const char kHideBookmarkButton[];
extern const char kHomepageURL[];
extern const char kHostPermissions[];
extern const char kIcons[];
extern const char kId[];
extern const char kImeOptionsPage[];
extern const char kIndicator[];
extern const char kInputComponents[];
extern const char kInputView[];
extern const char kKey[];
extern const char kKiosk[];
extern const char kKioskAlwaysUpdate[];
extern const char kKioskEnabled[];
extern const char kKioskOnly[];
extern const char kKioskMode[];
extern const char kKioskRequiredPlatformVersion[];
extern const char kKioskSecondaryApps[];
extern const char kLanguage[];
extern const char kLaunch[];
extern const char kLaunchContainer[];
extern const char kLauncherPage[];
extern const char kLauncherPagePage[];
extern const char kLaunchHeight[];
extern const char kLaunchLocalPath[];
extern const char kLaunchWebURL[];
extern const char kLaunchWidth[];
extern const char kLayouts[];
extern const char kLinkedAppIcons[];
extern const char kLinkedAppIconURL[];
extern const char kLinkedAppIconSize[];
extern const char kManifestVersion[];
extern const char kMatches[];
extern const char kMIMETypes[];
extern const char kMimeTypesHandler[];
extern const char kMinimumChromeVersion[];
extern const char kNaClModules[];
extern const char kNaClModulesMIMEType[];
extern const char kNaClModulesPath[];
extern const char kName[];
extern const char kNativelyConnectable[];
extern const char kOfflineEnabled[];
extern const char kOmniboxKeyword[];
extern const char kOptionalHostPermissions[];
extern const char kOptionalPermissions[];
extern const char kOptionsPage[];
extern const char kOptionsUI[];
extern const char kOverrideHomepage[];
extern const char kOverrideSearchProvider[];
extern const char kOverrideStartupPage[];
extern const char kPageAction[];
extern const char kPermissions[];
extern const char kPlatformAppBackground[];
extern const char kPlatformAppBackgroundPage[];
extern const char kPlatformAppBackgroundScripts[];
extern const char kPlatformAppContentSecurityPolicy[];
extern const char kPublicKey[];
extern const char kRemoveButton[];
extern const char kReplacementWebApp[];
extern const char kSandboxedPages[];
extern const char kSandboxedPagesCSP[];
extern const char kSettingsOverride[];
extern const char kSettingsOverrideAlternateUrls[];
extern const char kShortName[];
extern const char kSockets[];
extern const char kStorageManagedSchema[];
extern const char kSuggestedKey[];
extern const char kSystemIndicator[];
extern const char kTheme[];
extern const char kThemeColors[];
extern const char kThemeDisplayProperties[];
extern const char kThemeImages[];
extern const char kThemeTints[];
extern const char kTtsEngine[];
extern const char kTtsEngineSampleRate[];
extern const char kTtsEngineBufferSize[];
extern const char kTtsVoices[];
extern const char kTtsVoicesEventTypeEnd[];
extern const char kTtsVoicesEventTypeError[];
extern const char kTtsVoicesEventTypeMarker[];
extern const char kTtsVoicesEventTypeSentence[];
extern const char kTtsVoicesEventTypeStart[];
extern const char kTtsVoicesEventTypeWord[];
extern const char kTtsVoicesEventTypes[];
extern const char kTtsVoicesGender[];
extern const char kTtsVoicesLang[];
extern const char kTtsVoicesRemote[];
extern const char kTtsVoicesVoiceName[];
extern const char kUpdateURL[];
extern const char kUrlHandlers[];
extern const char kUrlHandlerTitle[];
extern const char kUsbPrinters[];
extern const char kVersion[];
extern const char kVersionName[];
extern const char kWebURLs[];
extern const char kWebview[];
extern const char kWebviewName[];
extern const char kWebviewAccessibleResources[];
extern const char kWebviewPartitions[];
#if BUILDFLAG(IS_CHROMEOS)
extern const char kFileSystemProviderCapabilities[];
extern const char kActionHandlers[];
extern const char kActionHandlerActionKey[];
extern const char kActionHandlerEnabledOnLockScreenKey[];
#endif
} // namespace manifest_keys
// Some values expected in manifests.
namespace manifest_values {
extern const char kActionCommandEvent[];
extern const char kApiKey[];
extern const char kBrowserActionCommandEvent[];
extern const char kIncognitoNotAllowed[];
extern const char kIncognitoSplit[];
extern const char kIncognitoSpanning[];
extern const char kKeybindingPlatformChromeOs[];
extern const char kKeybindingPlatformDefault[];
extern const char kKeybindingPlatformLinux[];
extern const char kKeybindingPlatformMac[];
extern const char kKeybindingPlatformWin[];
extern const char kKeyAlt[];
extern const char kKeyShift[];
extern const char kKeyCommand[];
extern const char kKeyCtrl[];
extern const char kKeyComma[];
extern const char kKeyDel[];
extern const char kKeyDown[];
extern const char kKeyHome[];
extern const char kKeyEnd[];
extern const char kKeyIns[];
extern const char kKeyLeft[];
extern const char kKeyMacCtrl[];
extern const char kKeyMediaNextTrack[];
extern const char kKeyMediaPlayPause[];
extern const char kKeyMediaPrevTrack[];
extern const char kKeyMediaStop[];
extern const char kKeyPgDwn[];
extern const char kKeyPgUp[];
extern const char kKeyPeriod[];
extern const char kKeyRight[];
extern const char kKeySearch[];
extern const char kKeySeparator[];
extern const char kKeySpace[];
extern const char kKeyTab[];
extern const char kKeyUp[];
extern const char kLaunchContainerPanelDeprecated[];
extern const char kLaunchContainerTab[];
extern const char kLaunchContainerWindow[];
extern const char kPageActionCommandEvent[];
} // namespace manifest_values
// Error messages returned from extension installation.
namespace manifest_errors {
extern const char kActiveTabPermissionNotGranted[];
extern const char kAllURLOrActiveTabNeeded[];
extern const char kAppsNotEnabled[];
extern const char16_t kBackgroundPermissionNeeded[];
extern const char16_t kBackgroundRequiredForPlatformApps[];
extern const char kBackgroundSpecificationInvalidForManifestV3[];
extern const char kCannotAccessAboutUrl[];
extern const char kCannotAccessChromeUrl[];
extern const char kCannotAccessExtensionUrl[];
extern const char kCannotAccessPage[];
extern const char kCannotAccessPageWithUrl[];
extern const char kCannotChangeExtensionID[];
extern const char kCannotClaimAllHostsInExtent[];
extern const char kCannotClaimAllURLsInExtent[];
extern const char kCannotScriptGallery[];
extern const char kCannotScriptNtp[];
extern const char kCannotScriptSigninPage[];
extern const char kCannotUninstallManagedExtension[];
extern const char16_t kChromeStyleInvalidForManifestV3[];
extern const char kChromeVersionTooLow[];
extern const char kDeclarativeNetRequestPermissionNeeded[];
extern const char16_t kDefaultStateShouldNotBeSet[];
extern const char kDevToolsExperimental[];
extern const char kExecutionWorldRestrictedToMV3[];
extern const char kExpectString[];
extern const char kFileNotFound[];
extern const char kHasDifferentialFingerprint[];
extern const char16_t kInvalidAboutPage[];
extern const char16_t kInvalidAboutPageExpectRelativePath[];
extern const char kInvalidAction[];
extern const char16_t kInvalidActionDefaultIcon[];
extern const char16_t kInvalidActionDefaultPopup[];
extern const char16_t kInvalidActionDefaultState[];
extern const char16_t kInvalidActionDefaultTitle[];
extern const char16_t kInvalidBackground[];
extern const char16_t kInvalidBackgroundAllowJsAccess[];
extern const char16_t kInvalidBackgroundCombination[];
extern const char kInvalidBackgroundScript[];
extern const char16_t kInvalidBackgroundScripts[];
extern const char16_t kInvalidBackgroundServiceWorkerScript[];
extern const char16_t kInvalidBackgroundServiceWorkerType[];
extern const char16_t kInvalidBackgroundInHostedApp[];
extern const char16_t kInvalidBackgroundPersistent[];
extern const char kInvalidBackgroundPersistentInPlatformApp[];
extern const char16_t kInvalidBackgroundPersistentNoPage[];
extern const char kInvalidBrowserAction[];
extern const char kInvalidBrowseURL[];
extern const char kInvalidBrowseURLs[];
extern const char kInvalidChromeURLOverrides[];
extern const char16_t kInvalidCommandsKey[];
extern const char16_t kInvalidContentCapabilities[];
extern const char kInvalidContentCapabilitiesMatch[];
extern const char kInvalidContentCapabilitiesMatchOrigin[];
extern const char kInvalidContentCapabilitiesPermission[];
extern const char kInvalidCSPInsecureValueIgnored[];
extern const char kInvalidCSPInsecureValueError[];
extern const char kInvalidCSPMissingSecureSrc[];
extern const char kInvalidDefaultLocale[];
extern const char16_t kInvalidDefaultLocale16[];
extern const char16_t kInvalidDescription[];
extern const char16_t kInvalidDevToolsPage[];
extern const char16_t kInvalidDisplayInLauncher[];
extern const char16_t kInvalidDisplayInNewTabPage[];
extern const char kInvalidEmptyDictionary[];
extern const char kInvalidExcludeMatch[];
extern const char kInvalidExcludeMatches[];
extern const char kInvalidExportPermissions[];
extern const char kInvalidExportAllowlistString[];
extern const char16_t kInvalidFileAccessList[];
extern const char kInvalidFileAccessValue[];
extern const char kInvalidFileBrowserHandler[];
extern const char16_t kInvalidFileBrowserHandler16[];
extern const char16_t kInvalidFileBrowserHandlerId[];
extern const char kInvalidFileBrowserHandlerMissingPermission[];
extern const char16_t kInvalidFileFiltersList[];
extern const char kInvalidFileFilterValue[];
extern const char16_t kInvalidFileHandlers[];
extern const char kInvalidWebFileHandlers[];
extern const char16_t kInvalidFileHandlersTooManyTypesAndExtensions[];
extern const char kInvalidFileHandlerExtension[];
extern const char kInvalidFileHandlerExtensionElement[];
extern const char kInvalidFileHandlerIncludeDirectories[];
extern const char kInvalidFileHandlerNoTypeOrExtension[];
extern const char kInvalidFileHandlerType[];
extern const char kInvalidFileHandlerTypeElement[];
extern const char kInvalidFileHandlerVerb[];
extern const char kInvalidHomepageOverrideURL[];
extern const char kInvalidHomepageURL[];
extern const char kInvalidHostPermission[];
extern const char kInvalidHostPermissions[];
extern const char kInvalidIconKey[];
extern const char kInvalidIconPath[];
extern const char16_t kInvalidIcons[];
extern const char16_t kInvalidImportAndExport[];
extern const char kInvalidImportId[];
extern const char kInvalidImportVersion[];
extern const char kInvalidInputComponents[];
extern const char16_t kInvalidInputComponents16[];
extern const char kInvalidInputComponentLayoutName[];
extern const char kInvalidInputComponentName[];
extern const char kInvalidInputView[];
extern const char16_t kInvalidIsolation[];
extern const char kInvalidIsolationValue[];
extern const char16_t kInvalidKey[];
extern const char kInvalidKeyBinding[];
extern const char kInvalidKeyBindingDescription[];
extern const char kInvalidKeyBindingDictionary[];
extern const char kInvalidKeyBindingMediaKeyWithModifier[];
extern const char kInvalidKeyBindingMissingPlatform[];
extern const char kInvalidKeyBindingTooMany[];
extern const char kInvalidKeyBindingUnknownPlatform[];
extern const char16_t kInvalidKioskAlwaysUpdate[];
extern const char16_t kInvalidKioskEnabled[];
extern const char16_t kInvalidKioskOnly[];
extern const char16_t kInvalidKioskOnlyButNotEnabled[];
extern const char16_t kInvalidKioskRequiredPlatformVersion[];
extern const char16_t kInvalidKioskSecondaryApps[];
extern const char16_t kInvalidKioskSecondaryAppsBadAppEntry[];
extern const char kInvalidKioskSecondaryAppsDuplicateApp[];
extern const char kInvalidKioskSecondaryAppsPropertyUnavailable[];
extern const char kInvalidLauncherPage[];
extern const char kInvalidLauncherPagePage[];
extern const char16_t kInvalidLaunchContainer[];
extern const char kInvalidLaunchValue[];
extern const char kInvalidLaunchValueContainer[];
extern const char kInvalidLinkedAppIcon[];
extern const char kInvalidLinkedAppIconSize[];
extern const char kInvalidLinkedAppIconURL[];
extern const char kInvalidLinkedAppIcons[];
extern const char kInvalidManifest[];
extern const char kInvalidManifestKey[];
extern const char kInvalidManifestVersionMissingKey[];
extern const char kInvalidManifestVersionUnsupported[];
extern const char kInvalidMatch[];
extern const char kInvalidMatchCount[];
extern const char kInvalidMatches[];
extern const char16_t kInvalidMIMETypes[];
extern const char16_t kInvalidMimeTypesHandler[];
extern const char16_t kInvalidMinimumChromeVersion[];
extern const char16_t kInvalidNaClModules[];
extern const char kInvalidNaClModulesMIMEType[];
extern const char kInvalidNaClModulesPath[];
extern const char kInvalidName[];
extern const char16_t kInvalidName16[];
extern const char16_t kInvalidNativelyConnectable[];
extern const char kInvalidNativelyConnectableValue[];
extern const char16_t kInvalidNativelyConnectableValue16[];
extern const char16_t kInvalidOAuth2ClientId[];
extern const char16_t kInvalidOfflineEnabled[];
extern const char16_t kEmptyOmniboxKeyword[];
extern const char kInvalidOptionsUIChromeStyle[];
extern const char kInvalidOptionsUIOpenInTab[];
extern const char kInvalidOptionsPage[];
extern const char16_t kInvalidOptionsPageExpectUrlInPackage[];
extern const char16_t kInvalidOptionsPageInHostedApp[];
extern const char kInvalidPageAction[];
extern const char kInvalidPermission[];
extern const char kInvalidPermissions[];
extern const char kInvalidPermissionScheme[];
extern const char kInvalidPermissionWithDetail[];
extern const char16_t kInvalidReplacementWebApp[];
extern const char kInvalidRulesetID[];
extern const char16_t kInvalidSandboxedPagesList[];
extern const char kInvalidSandboxedPage[];
extern const char kInvalidSearchEngineMissingKeys[];
extern const char kInvalidSearchEngineURL[];
extern const char16_t kInvalidShortName[];
extern const char kInvalidStartupOverrideURL[];
extern const char16_t kInvalidSystemIndicator[];
extern const char16_t kInvalidTheme[];
extern const char16_t kInvalidThemeColors[];
extern const char16_t kInvalidThemeImages[];
extern const char kInvalidThemeImagesMissing[];
extern const char16_t kInvalidThemeTints[];
extern const char16_t kInvalidTts[];
extern const char16_t kInvalidTtsSampleRateFormat[];
extern const char kInvalidTtsSampleRateRange[];
extern const char16_t kInvalidTtsBufferSizeFormat[];
extern const char kInvalidTtsBufferSizeRange[];
extern const char16_t kInvalidTtsRequiresSampleRateAndBufferSize[];
extern const char16_t kInvalidTtsVoices[];
extern const char16_t kInvalidTtsVoicesEventTypes[];
extern const char kInvalidTtsVoicesGender[];
extern const char16_t kInvalidTtsVoicesLang[];
extern const char16_t kInvalidTtsVoicesRemote[];
extern const char16_t kInvalidTtsVoicesVoiceName[];
extern const char kInvalidUpdateURL[];
extern const char kInvalidURLPatternError[];
extern const char16_t kInvalidURLHandlers[];
extern const char kInvalidURLHandlerPatternElement[];
extern const char16_t kInvalidURLHandlerPatternElement16[];
extern const char16_t kInvalidURLHandlerTitle[];
extern const char kInvalidURLHandlerPattern[];
extern const char16_t kInvalidVersion[];
extern const char16_t kInvalidVersionName[];
extern const char kInvalidWebAccessibleResourcesList[];
extern const char kInvalidWebAccessibleResource[];
extern const char kInvalidSidePanel[];
extern const char16_t kInvalidWebview[];
extern const char16_t kInvalidWebviewAccessibleResourcesList[];
extern const char kInvalidWebviewAccessibleResource[];
extern const char kInvalidWebviewPartition[];
extern const char kInvalidWebviewPartitionName[];
extern const char16_t kInvalidWebviewPartitionsList[];
extern const char kInvalidWebURL[];
extern const char kInvalidWebURLs[];
extern const char kInvalidZipHash[];
extern const char kKeyIsDeprecatedWithReplacement[];
extern const char kLauncherPagePageRequired[];
extern const char16_t kLaunchPathAndExtentAreExclusive[];
extern const char16_t kLaunchPathAndURLAreExclusive[];
extern const char16_t kLaunchURLRequired[];
extern const char kLocalesInvalidLocale[];
extern const char16_t kLocalesMessagesFileMissing[];
extern const char kLocalesNoDefaultMessages[];
extern const char kLocalesNoValidLocaleNamesListed[];
extern const char kLocalesTreeMissing[];
extern const char kManifestParseError[];
extern const char kManifestUnreadable[];
extern const char kManifestV2IsDeprecatedWarning[];
extern const char kManifestVersionTooHighWarning[];
extern const char kMatchOriginAsFallbackCantHavePaths[];
extern const char kMatchOriginAsFallbackRestrictedToMV3[];
extern const char kMissingFile[];
extern const char16_t kMultipleOverrides[];
extern const char kNoWildCardsInPaths[];
extern const char16_t kNPAPIPluginsNotSupported[];
extern const char16_t kOneUISurfaceOnly[];
extern const char kPageCaptureNeeded[];
extern const char kPermissionCannotBeOptional[];
extern const char kPermissionMarkedOptionalAndRequired[];
extern const char kPermissionNotAllowed[];
extern const char kPermissionUnknownOrMalformed[];
extern const char kPluginsRequirementDeprecated[];
extern const char kReservedMessageFound[];
extern const char16_t kSandboxPagesCSPKeyNotAllowed[];
extern const char kRulesFileIsInvalid[];
extern const char kRulesetCountExceeded[];
extern const char kEnabledRulesetCountExceeded[];
extern const char kSidePanelManifestDefaultPathError[];
extern const char16_t kTransientBackgroundConflictsWithPersistentBackground[];
extern const char kTtsGenderIsDeprecated[];
extern const char kUnrecognizedManifestKey[];
extern const char kUnrecognizedManifestProperty[];
extern const char16_t kWebRequestConflictsWithLazyBackground[];
extern const char kInvalidExtensionOriginPopup[];
extern const char kNonexistentDefaultPopup[];
extern const char kCommandActionIncorrectForManifestActionType[];
#if BUILDFLAG(IS_CHROMEOS)
extern const char16_t kInvalidFileSystemProviderMissingCapabilities[];
extern const char kInvalidFileSystemProviderMissingPermission[];
extern const char kDuplicateActionHandlerFound[];
extern const char kIllegalPlugins[];
extern const char16_t kInvalidActionHandlerDictionary[];
extern const char kInvalidActionHandlersActionType[];
extern const char16_t kInvalidActionHandlersType[];
#endif
} // namespace manifest_errors
} // namespace extensions
#endif // EXTENSIONS_COMMON_MANIFEST_CONSTANTS_H_
|
cea46a73c812be8f089d46b438df1da7024704fa
|
eb827d7993b146cf507b57a45e420fffdf641eef
|
/tinkoff/2020/strings1/src/a.cpp
|
9cd7b2ac53c6d204b2e3af742a162ec9faaad950
|
[] |
no_license
|
khbminus/code2020
|
dfdbcae71d61d03d4457aad47ff7d4136e6fcc1e
|
a0d2230b0905df79ba78cb98353f4ba03f16e8b0
|
refs/heads/master
| 2023-07-16T16:08:20.629283
| 2021-08-29T20:35:14
| 2021-08-29T20:35:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,394
|
cpp
|
a.cpp
|
#include <bits/stdc++.h>
#include <ostream>
using namespace std;
using ll = long long;
#define SZ(x) (int)((x).size())
#define ALL(x) (x).begin(), (x).end()
#define RALL(x) (x).rbegin(), (x).rend()
#define TMAX(type) numeric_limits<type>::max()
#define TMIN(type) numeric_limits<type>::min()
#ifdef LOCAL
#define ass(X) assert(X)
#else
#define ass(X) {}
#endif
int n;
const int MAXN = 1e6 + 7;
template<int ALP, int SIZE>
struct AhoCorasick {
struct Node {
char pCh = -1;
int p = 0;
int suf_link = -1;
bool used = false;
int edges[ALP];
vector<int> terminal;
Node() {
fill(edges, edges + ALP, -1);
}
explicit Node(int pp, char _pCh) : p(pp), pCh(_pCh) {
fill(edges, edges + ALP, -1);
}
};
Node nodes[SIZE];
int first_free = 1;
AhoCorasick() {}
void add(const string &s, int ind) {
int pos = 0;
for (char c : s) {
int cc = c - 'a';
if (nodes[pos].edges[cc] == -1) {
nodes[pos].edges[cc] = first_free;
nodes[first_free++] = Node(pos, cc);
}
pos = nodes[pos].edges[cc];
}
nodes[pos].terminal.push_back(ind);
}
int link(int v) {
if (nodes[v].suf_link != -1)
return nodes[v].suf_link;
if (v == 0 || nodes[v].p == 0)
return nodes[v].suf_link = 0;
return nodes[v].suf_link = go(link(nodes[v].p), nodes[v].pCh);
}
int go(int v, int c) {
if (nodes[v].edges[c] != -1)
return nodes[v].edges[c];
if (v == 0)
return nodes[v].edges[c] = 0;
return nodes[v].edges[c] = go(link(v), c);
}
void get_ans_offline(int v) {
if (nodes[v].used)
return;
nodes[v].used = true;
if (v == 0)
return;
get_ans_offline(link(v));
for (int x : nodes[link(v)].terminal)
nodes[v].terminal.push_back(x);
}
int last_pos[MAXN]; // for offline
vector<int> ans[MAXN];
void process_offline(const string &s) {
int pos = 0;
for (int i = 0; i < SZ(s); i++) {
pos = go(pos, s[i] - 'a');
last_pos[i] = pos;
}
for (int i = 0; i < SZ(s); i++) {
get_ans_offline(last_pos[i]);
for (int x : nodes[last_pos[i]].terminal)
ans[x].push_back(i);
}
}
};
string s;
int sizes[MAXN];
int solve() {
if (!(cin >> s >> n))
return 1;
string t;
AhoCorasick<26, (int) 1e6> ahoCorasick;
for (int i = 0; i < n; i++) {
cin >> t;
ahoCorasick.add(t, i);
sizes[i] = SZ(t);
}
ahoCorasick.process_offline(s);
for (int i = 0; i < n; i++) {
cout << SZ(ahoCorasick.ans[i]) << " ";
for (int x : ahoCorasick.ans[i])
cout << x - sizes[i] + 2 << ' ';
cout << '\n';
}
return 0;
}
signed main() {
#ifdef LOCAL
freopen("a.in", "r", stdin);
#else
freopen("inputik.txt", "r", stdin);
freopen("outputik.txt", "w", stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tests = 1e9;
// cin >> tests;
for (int i = 1; i <= 1; i++) {
if (solve())
break;
#ifdef LOCAL
cout << "------------------------------\n";
#endif
}
}
|
68ffae3f8803f1bc5328aeff70afc64bb4d67c1f
|
370a7847ee047dfe5c11a8dfa8272d9fd333b911
|
/C_C++/array_MaxSub.cpp
|
cc09371a68110a77b70df7067f6671350d7cc87c
|
[] |
no_license
|
TimChanCHN/LinuxProgram
|
d2e3e8b70d90d1a9956628086419949c2570af82
|
67082ba23a21033d903c94a642673d64115ed756
|
refs/heads/master
| 2020-07-28T19:05:15.158684
| 2020-04-24T10:51:23
| 2020-04-24T10:51:23
| 209,504,126
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,747
|
cpp
|
array_MaxSub.cpp
|
#include <iostream>
#include <vector>
#include <map>
#include <stack>
/*
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
解法:
1. 暴力解法:穷举出每种连续排列,算出最大值
2. 动态规划:记录每个第i位结束的字串最大值,所有max的最大值即为全部的最大值。当i-1位的max<0是,最大值就是nums[i],否则就是max[i-1]+nums[i]
*/
using namespace std;
class solution
{
public:
/* 穷举法 */
int maxSubArray(vector<int>& nums)
{
int len = nums.size();
int max1 = INT_MIN;
for( int i = 0; i < len; i++ )
{
int sum = 0;
for( int j = i; j < len; j++ )
{
sum += nums[j];
max1 = max(max1, sum);
}
}
return max1;
}
/* 动态规划 */
int maxSubArray1(vector<int>& nums)
{
int len = nums.size();
int dp[len]; //记录以第i位结束的字串最大值
dp[0] = nums[0];
for( int i = 1; i < len; i++ )
{
if( dp[i-1] >= 0 )
dp[i] = dp[i-1] + nums[i];
else
{
dp[i] = nums[i];
}
}
int max1 = dp[0];
for( int i = 1; i < len; i++ )
{
max1 = max(max1,dp[i]);
}
return max1;
}
};
int main()
{
vector<int> num{-2,1,-3,4,-1,2,1,-5,4};
class solution test;
int out = test.maxSubArray1(num);
cout << out << endl;
while(1);
return 0;
}
|
cbed71255d7281ea33dad560bcf5ca3e1c5ed6f4
|
1b8bba9b8a4a655a0acc7fed805a03f32720c57e
|
/src/Menge/MengeVis/SceneGraph/Transform.cpp
|
0f44c9cb7a844f43414a7d515bce0b7c2a4cf456
|
[
"Apache-2.0"
] |
permissive
|
tcarnoldussen/Menge
|
8f42d2987189380c4784341fa9b92bff2cf1e57e
|
ce276e3014c6f7681ce1509533028b76c1f38e10
|
refs/heads/master
| 2021-02-05T05:49:25.871675
| 2020-03-06T12:06:36
| 2020-03-06T12:06:36
| 243,750,295
| 0
| 0
|
Apache-2.0
| 2020-02-28T11:47:49
| 2020-02-28T11:47:48
| null |
WINDOWS-1252
|
C++
| false
| false
| 3,923
|
cpp
|
Transform.cpp
|
/*
License
Menge
Copyright © and trademark ™ 2012-14 University of North Carolina at Chapel Hill.
All rights reserved.
Permission to use, copy, modify, and distribute this software and its documentation
for educational, research, and non-profit purposes, without fee, and without a
written agreement is hereby granted, provided that the above copyright notice,
this paragraph, and the following four paragraphs appear in all copies.
This software program and documentation are copyrighted by the University of North
Carolina at Chapel Hill. The software program and documentation are supplied "as is,"
without any accompanying services from the University of North Carolina at Chapel
Hill or the authors. The University of North Carolina at Chapel Hill and the
authors do not warrant that the operation of the program will be uninterrupted
or error-free. The end-user understands that the program was developed for research
purposes and is advised not to rely exclusively on the program for any reason.
IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE AUTHORS
BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL OR THE
AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS SPECIFICALLY
DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AND ANY STATUTORY WARRANTY
OF NON-INFRINGEMENT. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL AND THE AUTHORS HAVE NO OBLIGATIONS
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Any questions or comments should be sent to the authors {menge,geom}@cs.unc.edu
*/
#include "MengeVis/SceneGraph/Transform.h"
#include "MengeVis/SceneGraph/graphCommon.h"
namespace MengeVis {
namespace SceneGraph {
using Menge::Math::Matrix4x4;
///////////////////////////////////////////////////////////////////////////
// IMPLEMENTATION FOR Transform
///////////////////////////////////////////////////////////////////////////
Transform::Transform(GLDagNode* parent) : GLDagNode(parent) {}
///////////////////////////////////////////////////////////////////////////
void Transform::getWorldMatrix(Matrix4x4& mat) {
if (_parent) {
Matrix4x4 thisMat(false), pMat(false);
getMatrix(thisMat);
_parent->getWorldMatrix(pMat);
mat.product(thisMat, pMat);
} else {
getMatrix(mat);
}
}
///////////////////////////////////////////////////////////////////////////
void Transform::getWorldInverseMatrix(Matrix4x4& mat) {
if (_parent) {
Matrix4x4 pIMat(false), thisIMat(false);
_parent->getWorldInverseMatrix(pIMat);
getInverseMatrix(thisIMat);
mat.product(pIMat, thisIMat);
} else {
getInverseMatrix(mat);
}
}
///////////////////////////////////////////////////////////////////////////
void Transform::getParentMatrix(Matrix4x4& mat) {
if (_parent) {
_parent->getWorldMatrix(mat);
} else {
mat.identity();
}
}
///////////////////////////////////////////////////////////////////////////
void Transform::getParentInverseMatrix(Matrix4x4& mat) {
if (_parent) {
_parent->getWorldInverseMatrix(mat);
} else {
mat.identity();
}
}
///////////////////////////////////////////////////////////////////////////
void Transform::drawGL(bool select) {
if (_visible) {
glPushMatrix();
Matrix4x4 mat(false);
_xform.getMatrix(mat);
glMultMatrixf(mat.getFlattened());
GLDagNode::drawGL(select);
glPopMatrix();
}
}
///////////////////////////////////////////////////////////////////////////
} // namespace SceneGraph
} // namespace MengeVis
|
6477ea93bd10da3f53f90a67382b5c6054e2a35e
|
6929dfe68f55e30b4369a9224bb38b1281ea4935
|
/langtonAnt.cpp
|
1416c67a485f59595af15100a11214e5ae39f7fc
|
[] |
no_license
|
mnutt346/Langton-s-Ant
|
ef41dca25f3211e338cd849ecf095a3069002630
|
0f1ee1d7b21bdfce1f3de9320e2a2881b7ccc8cf
|
refs/heads/master
| 2020-08-08T07:58:29.962948
| 2019-10-12T15:30:34
| 2019-10-12T15:30:34
| 213,786,140
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,475
|
cpp
|
langtonAnt.cpp
|
/**************************************************************************************
** Program name: langtonAnt.cpp
** Author: Michael Nutt
** Date: 10/03/2019
** Description: Implemetation of the main() function for the Langton's Ant program.
**************************************************************************************/
#include <iostream>
#include "Menu.hpp"
#include "RandomStartGenerator.hpp"
#include "Ant.hpp"
#include "Board.hpp"
#include "PrintAnt.hpp"
using std::cin;
using std::cout;
using std::endl;
using std::string;
int main()
{
const string TITLE = "Langton's Ant";
const int MIN_STEPS = 1;
const int MAX_STEPS = 500;
const int MIN_START = 0;
const int MIN_ROWS = 2;
const int MAX_ROWS = 100;
const int MIN_COLS = 2;
const int MAX_COLS = 100;
int programSelection = menu(TITLE);
// While the user chooses to enter the simulation:
while (programSelection)
{
int rowCount; //user-determined number of rows on the board
int colCount; //user-determined number of columns on the board
int totalSteps; //user-determined number of steps the ant will take
int currentRow; //tracks the current row of the ant
int currentCol; //tracks the current column of the ant
int currentStep = 0; //tracks the ants total steps taken
// Prompt user to select number of rows
cout << endl;
cout << "Please enter a positive integer between " << MIN_ROWS << " and " << MAX_ROWS << ", inclusive." << endl;
cout << "This number will represent the number of rows on the board." << endl;
// Validate input for rows
rowCount = convertInputToInt();
// While the input is out of range:
while (rowCount < MIN_ROWS || rowCount > MAX_ROWS)
{
cout << "Invalid input." << endl;
cout << "Please enter a positive integer between " << MIN_ROWS << " and " << MAX_ROWS << ", inclusive." << endl;
// Re-validate new input
rowCount = convertInputToInt();
}
// Prompt user to select number of columns
cout << endl;
cout << "Now, please enter a positive integer between " << MIN_COLS << " and " << MAX_COLS << ", inclusive." << endl;
cout << "This number will represent the number of columns on the board." << endl;
// Validate input for columns
colCount = convertInputToInt();
// While input is out of range:
while (colCount < MIN_COLS || colCount > MAX_COLS)
{
cout << "Invalid input." << endl;
cout << "Please enter a positive integer between " << MIN_COLS << " and " << MAX_COLS << ", inclusive." << endl;
// Re-validate new input
colCount = convertInputToInt();
}
// If the user wants to use a random starting point:
if (selectRandomStart())
{
// Generate a random starting column
currentRow = generateRandomStart((rowCount - 1));
// Generate a random starting row
currentCol = generateRandomStart((colCount - 1));
}
// Otherwise, prompt the user to select a sarting point
else
{
// Select the starting row
cout << endl;
cout << "Please select the starting row of the ant by entering an integer between " << MIN_START << " and " << rowCount - 1 << "." << endl;
// Validate input
currentRow = convertInputToInt();
// While the input is out of range:
while (currentRow < MIN_START || currentRow >= rowCount)
{
cout << "Invalid input." << endl;
cout << "Please enter an integer between " << MIN_START << " and " << rowCount - 1 << "." << endl;
// Re-validate input
currentRow = convertInputToInt();
}
// Select the starting column
cout << endl;
cout << "Please select the starting column of the ant by entering an integer between " << MIN_START << " and " << colCount - 1 << "." << endl;
// Validate input
currentCol = convertInputToInt();
// While the input is out of range:
while (currentCol < 0 || currentCol >= colCount)
{
cout << "Invalid input." << endl;
cout << "Please enter an integer between " << MIN_START << " and " << colCount - 1 << "." << endl;
// Re-validate input
currentCol = convertInputToInt();
}
}
// Prompt the user to select the total number of steps in the simulation
cout << endl;
cout << "Please enter and integer between " << MIN_STEPS << " and " << MAX_STEPS << ", inclusive" << endl;
cout << "This will determine the number of steps the simulation will take." << endl;
// Validate input
totalSteps = convertInputToInt();
// While the input is out of range:
while (totalSteps < MIN_STEPS || totalSteps > MAX_STEPS)
{
cout << "Invalid input." << endl;
cout << "Please enter an integer between " << MIN_STEPS << " and " << MAX_STEPS << "." << endl;
// Re-validate input
totalSteps = convertInputToInt();
}
// Generate a 2D array to track the state of the board
// https://stackoverflow.com/questions/1533687/write-a-class-using-a-two-dimensional-dynamic-array
char **tracker = new char *[rowCount];
for (int i = 0; i < rowCount; i++)
{
tracker[i] = new char[colCount];
}
// Generate pointer to Board object using rowCount, colCount, and the 2D array
Board *board = new Board(rowCount, colCount, tracker);
// Generate Ant object using currentRow and currentCol as its starting point, and the board object
// to allow the ant to track its state
Ant ant(currentRow, currentCol, board);
// While the ant has not completed the simulation
while (currentStep < totalSteps)
{
// Increment currentStep
currentStep++;
//Store the ant's current location to use as reference after it moves
int prevRow = ant.getCurrentRow();
int prevCol = ant.getCurrentCol();
printAnt(ant, board);
ant.moveAnt(prevRow, prevCol);
int nextRow = ant.getCurrentRow();
int nextCol = ant.getCurrentCol();
cout << "Please press enter to continue." << endl;
cin.get();
}
// Deallocate memory used by the 2D array
for (int i = 0; i < rowCount; i++)
{
delete[] tracker[i];
}
delete[] tracker;
// Deallocate memory used by the board
delete board;
// Provide the user with the option to run the simulation again, or quit
programSelection = menu(TITLE);
}
if (!programSelection)
{
return 0;
}
}
|
dc88ff21919e670451be2eb243b517a79175a504
|
628f60ea185d57334e350a6e3bbbb6eac6f77bd0
|
/Framework/Engine/Utility/Code/UI.cpp
|
c3811a59200dd255acdc5c902d7924f86c15f400
|
[] |
no_license
|
ems789/Wizard-of-Legend-2.5D-Team-Project
|
e31a2a50e1971f88b8ec1d9320332f1f5608d16d
|
345136dc7a76dc66b9b864945804dddabf88be8e
|
refs/heads/master
| 2022-05-26T12:41:44.766735
| 2020-04-29T01:24:52
| 2020-04-29T01:24:52
| 252,634,747
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 539
|
cpp
|
UI.cpp
|
#include "UI.h"
USING(Engine)
Engine::CUI::CUI(LPDIRECT3DDEVICE9 pGraphicDev)
: CGameObject(pGraphicDev)
{
}
Engine::CUI::~CUI()
{
}
HRESULT Engine::CUI::Ready_GameObject()
{
FAILED_CHECK_RETURN(CGameObject::Ready_GameObject(), E_FAIL);
return S_OK;
}
_int Engine::CUI::Update_GameObject(const _float& fTimeDelta)
{
_int iExit = CGameObject::Update_GameObject(fTimeDelta);
if (iExit & 0x80000000)
return -1;
return iExit;
}
void Engine::CUI::Render_GameObjcet()
{
}
void Engine::CUI::Free()
{
CGameObject::Free();
}
|
fd7574b9ccf35ded31844913396cedb3521fb46f
|
75ebe655e31196c0532fb332d50b8f9389a58b4f
|
/spsc_lib/spsc_wrapper.cc
|
6cc4bb61ee3abd1e9c6bf7dce330f76e6c6c9558
|
[] |
no_license
|
pinczakko/boost_spsc_queue_c_wrapper
|
106092887a961a61f588d2c41607ba40cb535fe4
|
21ae89d69e14dca6f7802582c08ced0b1e93f78d
|
refs/heads/master
| 2021-01-10T06:16:35.792912
| 2016-01-22T01:54:37
| 2016-01-22T01:54:37
| 49,368,813
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,423
|
cc
|
spsc_wrapper.cc
|
#include "spsc_interface.hpp"
#include "spsc_wrapper.h"
#ifdef __cplusplus
extern "C" {
#endif
spsc_interface * create_spsc_interface()
{
return new spsc_interface();
}
void destroy_spsc_interface(spsc_interface * q)
{
delete q;
}
int push_item(spsc_interface * const q, const struct account * const acc)
{
return q->push_item(acc);
}
int pop_item(spsc_interface * const q, struct account * acc)
{
return q->pop_item(acc);
}
int is_lock_free(spsc_interface * const q)
{
return q->is_lock_free();
}
void inc_producer_count(spsc_interface * q)
{
q->inc_producer_count();
}
void inc_consumer_count(spsc_interface * q)
{
q->inc_consumer_count();
}
int get_consumer_count(spsc_interface * q)
{
return q->get_consumer_count();
}
int get_producer_count(spsc_interface * q)
{
return q->get_producer_count();
}
const int get_iterations_count(spsc_interface * const q)
{
return q->get_iterations_count();
}
void signal_done(spsc_interface * const q)
{
q->signal_done();
}
int is_done(spsc_interface * const q)
{
return q->is_done();
}
#ifdef NDEBUG
void use_as_consumer(spsc_interface * const q) {}
void use_as_producer(spsc_interface * const q) {}
#else
void use_as_consumer(spsc_interface * const q)
{
q->inc_connected_consumer();
}
void use_as_producer(spsc_interface * const q)
{
q->inc_connected_producer();
}
#endif //NDEBUG
#ifdef __cplusplus
}
#endif
|
15d4e3bf398db6edf6476f9219f3980abcd2dce2
|
7ece83a3894d7610e8367eb0a19f9d50ba5e3ce5
|
/mex/principal_curvature.cpp
|
00da1107a414119f6e5fec4bebd1f57a748f6d54
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
alecjacobson/gptoolbox
|
b4d1a3cb6cd604f8dcf2527d08c9a63efc110b72
|
dda5c0d3ae7773837945631463134e577990263a
|
refs/heads/master
| 2023-08-20T05:50:46.191141
| 2023-08-08T17:38:45
| 2023-08-08T17:38:45
| 17,057,368
| 598
| 189
|
MIT
| 2023-05-22T23:41:52
| 2014-02-21T13:46:13
|
MATLAB
|
UTF-8
|
C++
| false
| false
| 1,830
|
cpp
|
principal_curvature.cpp
|
#include <igl/principal_curvature.h>
#include <igl/matlab/mexErrMsgTxt.h>
#include <igl/matlab/MexStream.h>
#include <igl/matlab/parse_rhs.h>
#include <igl/matlab/prepare_lhs.h>
#include <igl/matlab/validate_arg.h>
// Los que tienen el tipo de objeto definido son input, el resto output??
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
using namespace igl;
using namespace igl::matlab;
using namespace Eigen;
MatrixXd V,PD1,PD2,PV1,PV2;
MatrixXi F;
int radius = 2;
bool useKring = true;
igl::matlab::MexStream mout;
std::streambuf *outbuf = std::cout.rdbuf(&mout);
mexErrMsgTxt(nrhs>=2,"nrhs should be >= 2");
parse_rhs_double(prhs,V); // Aquí se pasa del prhs a la matriz V de Eigen
parse_rhs_index(prhs+1,F); // Aquí se pasa del prhs a la matriz F de Eigen
mexErrMsgTxt(V.cols()==3,"V must be #V by 3");
mexErrMsgTxt(F.cols()==3,"F must be #F by 3");
{
int i = 2;
while(i<nrhs)
{
mexErrMsgTxt(mxIsChar(prhs[i]),"Parameter names should be strings");
// Cast to char
const char * name = mxArrayToString(prhs[i]);
if(strcmp("Radius",name) == 0)
{
validate_arg_scalar(i,nrhs,prhs,name);
validate_arg_double(i,nrhs,prhs,name);
radius = (int)*mxGetPr(prhs[++i]);
}else
{
mexErrMsgTxt(false,C_STR("Unknown parameter: "<<name));
}
i++;
}
}
igl::principal_curvature(V,F,PD1,PD2,PV1,PV2,radius,useKring);
switch(nlhs)
{
case 4:
prepare_lhs_double(PV2,plhs+3);
case 3:
prepare_lhs_double(PV1,plhs+2);
case 2:
prepare_lhs_double(PD2,plhs+1);
case 1:
prepare_lhs_double(PD1,plhs+0);
default:break;
}
// Restore the std stream buffer Important!
std::cout.rdbuf(outbuf);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.