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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
46657e924615ef445019f7d034bdadb18841d674
|
33cdd5ccd542e647b72972b634203b20277852eb
|
/Css343Lab4/History.cpp
|
620850f77768a17e92da2442d85fa9e5e536e0d1
|
[
"MIT"
] |
permissive
|
Whompithian/css343-project4
|
1430e7ab3551f84921b9edac3e7c549c92b0b445
|
b527c4a35126c0be41bf0a2c0d70d1a2d986b164
|
refs/heads/main
| 2023-07-20T08:50:18.728804
| 2016-06-09T05:08:27
| 2016-06-09T05:08:27
| 60,750,946
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,057
|
cpp
|
History.cpp
|
/*
* File: history.cpp
* Author: brendan
*
* Created on February 14, 2012, 8:13 PM
*/
#include "History.h"
#include "Merch.h"
History::History() : head(NULL)
{
} // end Default Constructor
History::History(const History& orig)
{
if (orig.head == NULL)
{
head = NULL; // original list is empty
}
else
{
// copy first node
head = new ListNode;
head->record = orig.head->record;
// copy rest of list
ListNode *newPtr = head; // new list pointer
// newPtr points to last node in new list
// origPtr points to nodes in original list
for (ListNode *origPtr = orig.head->next;
origPtr != NULL;
origPtr = origPtr->next)
{
newPtr->next = new ListNode;
newPtr = newPtr->next;
newPtr->record = origPtr->record;
} // end for (ListNode *origPtr = orig.head->next;
newPtr->next = NULL;
} // end if (orig.head == NULL)
} // end Copy Constructor
History::~History()
{
clearHistory();
} // end Destructor
void History::clearHistory(void)
{
ListNode *tempPtr;
while(head != NULL) // still items in History
{
tempPtr = head; // keep first item available
head = head->next; // move up list
delete tempPtr; // delete previous first item
} // end while(head != NULL)
tempPtr = NULL;
} // end clearHistory()
void History::insertItem(Transaction *latest)
{
ListNode *tempNode = new ListNode;
tempNode->record = latest->copy(); // copy record into new node
tempNode->next = head->next; // new link to rest of chain
head = tempNode; // insert at head of list
} // end insertItem()
Transaction* History::getLatest(void) const
{
return head->record->copy(); // create copy and return pointer
} // end getLatest()
bool History::isBorrowed(const Merch *target) const
{
ListNode *tempNode = head;
Merch *tempMerch = NULL;
while(tempNode != NULL) // there is something to check
{
tempMerch = tempNode->record->getItem();
// item found - determine if last Transaction was a Borrow and return
if (tempMerch->getSearchKey() == target->getSearchKey())
{
delete tempMerch;
tempMerch = NULL;
return tempNode->record->getMediaCode() == 'B';
} // end if (tempMerch->getSearchKey() == target->getSearchKey())
tempNode = tempNode->next; // set to search next node
delete tempMerch; // delete copy of Merchandise
} // end while(tempNode != NULL)
tempMerch = NULL; // clean up pointer
return false; // no Borrow Transaction found for target item
} // end isBorrowed(Transaction*)
void History::displayHistory(ostream& output) const
{
ListNode *tempPtr = head;
while(tempPtr != NULL)
{
tempPtr->record->display(output);
tempPtr = tempPtr->next;
} // end while()
} // end showHistory()
|
5ff4c5a0ff030adc17b7a978705c081852a3800f
|
12f32d9f53c178ae128a62bbaad8255ee99fc412
|
/CodeSignal/Intro Section/matrixElementsSum.cpp
|
a6e2a7ea4e0f76924fd5e71a9a6c16d6ae8c3754
|
[] |
no_license
|
C0DINGLE/DSA_Practice
|
512fec909752f8b2ea7255da72f08105c428edf4
|
3782af051d3566bda69f461e5777bde0feb8c764
|
refs/heads/main
| 2023-06-24T12:51:42.258551
| 2021-07-19T20:33:56
| 2021-07-19T20:33:56
| 347,957,899
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,292
|
cpp
|
matrixElementsSum.cpp
|
#include <iostream>
#include <vector>
using namespace std;
int matrixElementsSum(vector<vector<int> > matrix)
{
int sum = 0, count = 0;
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
if (matrix[i][j] == 0)
{
while (i < matrix.size())
{
matrix[i++][j] = 0;
count++;
}
i = i - count;
count = 0;
}
}
}
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
sum = sum + matrix[i][j];
}
}
return sum;
}
int main()
{
int q;
std::vector<std::vector<int> > matrix;
vector<int > row1;
vector<int > row2;
vector<int > row3;
row1.push_back(0);
row1.push_back(1);
row1.push_back(1);
row1.push_back(2);
row2.push_back(0);
row2.push_back(5);
row2.push_back(0);
row2.push_back(0);
row3.push_back(2);
row3.push_back(0);
row3.push_back(3);
row3.push_back(3);
matrix.push_back(row1);
matrix.push_back(row2);
matrix.push_back(row3);
q = matrixElementsSum(matrix);
cout << "Result" << q;
}
|
0cf4fe8bae77f6d7e36ab8b3caf262137da72649
|
4d107a97633559963f6510767bb9297febbcbb02
|
/applications/ConstitutiveModelsApplication/custom_python/add_custom_processes_to_python.cpp
|
3c382ba36bb0000b04c0ce2cfa6e0f220e4298c4
|
[
"BSD-2-Clause"
] |
permissive
|
asroy/Kratos
|
45dc4a9ad77a2b203ab2e0c6c5fe030633433181
|
e89d6808670d4d645319c7678da548b37825abe3
|
refs/heads/master
| 2021-03-24T13:28:43.618915
| 2017-12-19T15:38:20
| 2017-12-19T15:38:20
| 102,793,791
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 868
|
cpp
|
add_custom_processes_to_python.cpp
|
//
// Project Name: KratosConstitutiveModelsApplication $
// Created by: $Author: JMCarbonell $
// Last modified by: $Co-Author: $
// Date: $Date: April 2017 $
// Revision: $Revision: 0.0 $
//
//
// System includes
#include <boost/python.hpp>
// External includes
// Project includes
#include "includes/node.h"
#include "includes/define.h"
#include "processes/process.h"
//Application includes
#include "custom_python/add_custom_processes_to_python.h"
namespace Kratos
{
namespace Python
{
void AddCustomProcessesToPython()
{
using namespace boost::python;
typedef Process ProcessBaseType;
}
} // namespace Python.
} // Namespace Kratos
|
4aa921d4068147bece63cf2aec9039a532abb717
|
0006f89c8d952bcf14a6150e9c26c94e47fab040
|
/src/support/QuadInt.h
|
7366234d6ccbac37ac986cb6c7fc2d395edac128
|
[
"BSD-3-Clause"
] |
permissive
|
cooperyuan/attila
|
eceb5d34b8c64c53ffcc52cd96b684d4f88b706f
|
29a0ceab793b566c09cf81af26263e4855842c7a
|
refs/heads/master
| 2016-09-05T18:55:56.472248
| 2013-06-29T14:42:02
| 2013-06-29T14:42:02
| 10,222,034
| 8
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,144
|
h
|
QuadInt.h
|
/**************************************************************************
*
* Copyright (c) 2002 - 2011 by Computer Architecture Department,
* Universitat Politecnica de Catalunya.
* All rights reserved.
*
* The contents of this file may not be disclosed to third parties,
* copied or duplicated in any form, in whole or in part, without the
* prior permission of the authors, Computer Architecture Department
* and Universitat Politecnica de Catalunya.
*
* $RCSfile: QuadInt.h,v $
* $Revision: 1.5 $
* $Author: vmoya $
* $Date: 2008-02-22 18:32:56 $
*
* Quad Int class definition file.
*
*/
#ifndef __QUADINT__
#define __QUADINT__
#include "GPUTypes.h"
#include <ostream>
namespace gpu3d
{
//! Class QuadInt defines a 4-component 32 bit integer vector
class QuadInt {
private:
s32bit component[4]; //!< Data
public:
//! Constructor
QuadInt( s32bit x = 0, s32bit y = 0, s32bit z = 0, s32bit w = 0 );
//!Allows indexed access & LH position ( implements set & get ) to individual components
s32bit& operator[]( u32bit index );
/*!
* Modifies ALL components with new values, components without values are set to 0
* i.e: qi.setComponents( 1, 3 );
* The QuadInt resultant is ( 1, 3, 0, 0 )
*/
void setComponents( s32bit x = 0, s32bit y = 0, s32bit z = 0, s32bit w = 0 );
/*!
* Gets all the QuadInt components
*/
void getComponents( s32bit& x, s32bit& y, s32bit& z, s32bit& w );
/**
* Get the pointer to the s32bit vector for QuadInt.
*
*/
s32bit *getVector();
/**
*
* Assignment operator. Copy values from an array of integer values.
*
*/
QuadInt& operator=(s32bit *source);
//! Must be declared and defined inside the class
friend std::ostream& operator<<( std::ostream& theStream, const QuadInt& qi ) {
theStream << "(" << qi.component[0] << "," << qi.component[1] << ","
<< qi.component[2] << "," << qi.component[3] << ")";
return theStream;
}
};
} // namespace gpu3d
#endif
|
c3a68d932546a1923b2f9f90147e4e8c865fe87b
|
95779127b6b7baac57ba169103bff27d3732c0ba
|
/src/test_main.cpp
|
633ea5d2b0e575585e17ba33344bcb6d0d1efdf3
|
[] |
no_license
|
aimie99/Project7-11-18
|
7592ac1f438248727393368295ef69ad0619c136
|
cc0ca2c0a6d3f7b3fcd2fdaac9b6e65a9f2faf4b
|
refs/heads/master
| 2020-04-02T06:08:55.040693
| 2018-11-02T16:27:12
| 2018-11-02T16:27:12
| 154,132,346
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,591
|
cpp
|
test_main.cpp
|
#include <gtest/gtest.h>
#include <algorithm>
#include "network.h"
#include "random.h"
#define MAX 15
RandomNumbers RNG(101);
Network net;
TEST(networkTest, initialize) {
net.resize(MAX);
EXPECT_EQ(net.size(), MAX);
std::vector<double> vals = net.sorted_values();
EXPECT_TRUE(std::is_sorted(vals.begin(), vals.end(), std::greater<double>()));
double var = 0;
for (auto I : vals) var += I*I;
EXPECT_GT(var, sqrt(MAX));
}
TEST(networkTest, connect) {
bool trylink = net.add_link(0,0);
EXPECT_FALSE(trylink);
trylink = net.add_link(0, MAX);
EXPECT_FALSE(trylink);
trylink = net.add_link(MAX-2, MAX-1);
EXPECT_TRUE(trylink);
trylink = net.add_link(MAX-2, MAX-1);
EXPECT_FALSE(trylink);
EXPECT_EQ(net.degree(MAX-2)+net.degree(MAX-1), 2);
trylink = net.add_link(MAX-2,MAX-3);
trylink = net.add_link(1,MAX-2);
std::vector<size_t> ngb = net.neighbors(MAX-2);
EXPECT_EQ(ngb.size(), 3);
/*EXPECT_TRUE(ngb[0] == MAX-1 && ngb[1] == MAX-2 && ngb[2] == 1);*/
double numlink = 0;
for (int rep(0); rep < 100; rep++)
numlink += 0.01 * net.random_connect(2);
EXPECT_NEAR(numlink, 2*MAX, 15);
}
TEST(networkTest, values) {
std::vector<double> vals{1.0, 10.0, -0.4, .2, -21.8, 11.0};
size_t numv = net.set_values(vals);
EXPECT_EQ(numv, 6);
double checksum = 0;
for (size_t n=0; n<6; n++) checksum += net.value(n);
EXPECT_NEAR(checksum, 0.0, 0.01);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
28283fad74fc8592cebd12902d015d758ad5abc6
|
63c45712f8223e4333902db3be6b79366c557d84
|
/Engine/System.h
|
8656fed309101493ebd63fa65f367ccb2303629e
|
[] |
no_license
|
kaisavi/GAT150_ZBEPixelEngine
|
43aca326b59bb30b3e694893db4fe8017e2dc6ec
|
bb8f5907032535dbc15ec11beb28fc2c6c3279ed
|
refs/heads/master
| 2023-07-11T23:51:01.317957
| 2020-08-26T03:47:22
| 2020-08-26T03:47:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 143
|
h
|
System.h
|
#pragma once
namespace zbe {
class System {
public:
virtual bool Init() = 0;
virtual void Close() = 0;
virtual void Update() = 0;
};
}
|
d492ac9c611aa6f0041cfb0e747f66ec4661a549
|
18170b95a5e85de02ae87bb3180178e7c54adf5c
|
/Modules/MonteCarlon/Solver/solver_montecarlon_02_execute.cc
|
2212b1b5856e998aa89045e86507e87f69f84a11
|
[] |
no_license
|
rodriguez-jay/chi-tech
|
f3aed16d26f86f0656d70e81b7735b29a90ad7f5
|
ca2aa804dbccfad6cf179126662568d980a6acd1
|
refs/heads/master
| 2022-11-16T18:08:16.639976
| 2019-10-03T22:15:08
| 2022-11-11T16:10:20
| 204,505,220
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,621
|
cc
|
solver_montecarlon_02_execute.cc
|
#include "solver_montecarlon.h"
#include <chi_log.h>
#include <ChiTimer/chi_timer.h>
extern ChiLog chi_log;
extern ChiTimer chi_program_timer;
typedef unsigned long long TULL;
//#########################################################
/**Executes the solver*/
void chi_montecarlon::Solver::Execute()
{
chi_log.Log(LOG_0) << "Executing Montecarlo solver";
chi_montecarlon::Source* src = sources.back();
nps_global = 0;
TULL nps_last = 0;
double start_time = chi_program_timer.GetTime()/1000.0;
double time = 0.0;
double last_time = 0.0;
double particle_rate = 0.0;
for (int b=0; b<batch_sizes_per_loc.size(); b++)
{
nps = 0;
nps_last = 0;
current_batch = b;
for (TULL pi=0; pi<batch_sizes_per_loc[b]; pi++)
{
nps++;
nps_last++;
chi_montecarlon::Particle prtcl = src->CreateParticle(&rng0);
// chi_log.Log(LOG_0)
// << "Src particle " << prtcl.pos.PrintS()
// << " " << prtcl.dir << " " << prtcl.cur_cell_ind;
// usleep(100000);
while (prtcl.alive)
{
Raytrace(&prtcl);
// chi_log.Log(LOG_0)
// << "Ray particle " << prtcl.pos.PrintS()
// << " " << prtcl.dir << " " << prtcl.cur_cell_ind;
// usleep(100000);
}
ComputeTallySqr();
}//for pi in batch
RendesvouzTallies();
ComputeRelativeStdDev();
time = chi_program_timer.GetTime()/1000.0;
particle_rate = (nps_global)*60.0e-6/(time-start_time);
chi_log.Log(LOG_0)
<< chi_program_timer.GetTimeString()
<< " TFC-rendesvouz: # of particles ="
<< std::setw(14)
<< nps_global
<< " avg-rate = "
<< std::setw(6) << std::setprecision(4)
<< particle_rate << " M/min"
<< " Max Rel.Sigma = "
<< std::setw(6) << std::setprecision(4) << std::scientific
<< max_relative_error
<< " "
<< std::setw(6) << std::setprecision(4) << std::scientific
<< max_relative_error2
<< " "
<< std::setw(6) << std::setprecision(4) << std::scientific
<< max_relative_error3;
}
//Normalize tallies
int num_cells = grid->local_cell_glob_indices.size();
for (int lc=0; lc<num_cells; lc++)
{
for (int g=0; g<num_grps; g++)
{
int ir = lc*num_grps + g;
phi_global[ir] = phi_global[ir]*tally_multipl_factor/nps_global;
}
}
//Print group 0
for (int lc=0; lc<num_cells; lc++)
{
chi_log.Log(LOG_0)
<< "Cell " << lc
<< " phi=" << phi_global[lc*num_grps]
<< " std=" << phi_local_relsigma[lc*num_grps+0];
}
chi_log.Log(LOG_0) << "Done executing Montecarlo solver";
}
|
dadcf9c9f74e0aa56fe54723e52643948899a917
|
dd14ba9eb17efcd24b39872481d7fef6d67d72c5
|
/src/Mods.h
|
25d54b22c75db61dcc9fe73b887342a16f262bbe
|
[
"MIT"
] |
permissive
|
myran2/BrickBreaker
|
b0b1587ce99a3921c84b86359bd9fc756b486a9c
|
52daab6002345c4d07d9eef8a2a17013d3db3b6d
|
refs/heads/master
| 2021-01-10T06:56:34.051670
| 2016-04-20T04:58:55
| 2016-04-20T04:58:55
| 55,006,716
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 477
|
h
|
Mods.h
|
#ifndef _MODS_H
#define _MODS_H
#include "Entity.h"
#include "Log.h"
#include <iostream>
class Mods : public Entity
{
public:
Mods(Window* window, const std::string& textureName, int xPos, int yPos);
virtual void update();
void fastPaddle();
void slowerPaddle();
void largePaddle();
void smallPaddle();
private:
int xVelocity; //left and right velocity
int yVelocity; //up and down velocity
};
#endif
|
f54edfa05144285832f88848d26421c0dd127779
|
1d90f8b17b6d77f8513e80a439fc934ae905c8ec
|
/lista10/3primaridade.cpp
|
0eb3e6fe04db751d0670814a12463e09a4d6e210
|
[
"MIT"
] |
permissive
|
GE28/exercicios-CPP
|
e42464f4a7a1071080a35c967e3cff0bc8240d30
|
7070d6f749c859ca0a7bac39812558b0795d18c6
|
refs/heads/main
| 2023-08-05T10:49:27.092274
| 2021-09-12T22:38:23
| 2021-09-12T22:38:23
| 391,167,771
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 273
|
cpp
|
3primaridade.cpp
|
#include "lista10.h"
#include <iostream>
using namespace std;
int main() {
int n;
cout << "O número: ";
cin >> n;
cout << endl;
if (!verificarPrimaridade(n)) {
cout << "Não é primo";
} else {
cout << "É primo";
}
cout << endl;
return 0;
}
|
0bae9e20c9acc1fa64e4abf6128f8706d3df2b59
|
32689b9f29f957a07add26b4ad1e57673b6050e9
|
/soft_debug_p3/sw/src/femb_test.cxx
|
b28dff41f32c1945f93878c4e95039aae95c8113
|
[] |
no_license
|
madorskya/wib_sim
|
127956c934f317b5edbd99bda49b6bcba74d7d1e
|
6669d1c6a7ed1155a09c702255d077c400cb8db3
|
refs/heads/master
| 2023-08-31T13:15:01.921512
| 2023-08-29T00:40:48
| 2023-08-29T00:40:48
| 269,816,973
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,688
|
cxx
|
femb_test.cxx
|
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fstream>
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include "femb.h"
using namespace std;
int main (int argc, char * argv[])
{
int femb_ind = -1;
sscanf (argv[1], "%d", &femb_ind);
if (femb_ind < 0 || femb_ind > 3)
{
printf ("invalid FEMB index. Usage: femb_test index(0..3)");
exit (4);
}
printf ("Configuring FEMB %d\n", femb_ind);
FEMB* femb = new FEMB(femb_ind);
int reg3;
// chip_num_on_FEMB=(0|1), chip_addr=2, reg_page, reg_addr
int i;
if (argc == 2)
{
printf ("COLDATA soft reset, all chips\n");
femb->i2c_write (0, 0, 0, 6, 0); // COLDATA soft reset
for (i = 1; i >= 0; i--)
{
printf ("writing COLDATA %d\n", i);
// i2c_write (coldata_idx, chip_addr, page, reg_addr, data)
// i2c_read (coldata_idx, chip_addr, page, reg_addr)
femb->i2c_write (0, 3-i, 0, 1, 1); // 0=frame-12 1=frame-14 3=frame-DD
femb->i2c_write (0, 3-i, 0, 3, 0x3c); // 3c=normal operation, c3=PRBS7
// COLDADC reset is done after COLDADC power is enabled.
femb->i2c_write (0, 3-i, 0, 0x20, 0x5); // ACT = COLDADC reset
}
}
for (i = 0; i < 2; i++)
//for (i = 1; i >= 0; i--)
{
printf ("reading COLDATA %d\n", i);
int err = 0;
reg3 = femb->i2c_read (0, 3-i, 0, 0x01); if (reg3 != 0x1 ) err = 0x01; printf("FRAME = %x\n",reg3);
reg3 = femb->i2c_read (0, 3-i, 0, 0x03); if (reg3 != 0x3c) err = 0x03; printf("PRBS = %x\n",reg3);
reg3 = femb->i2c_read (0, 3-i, 0, 0x20); if (reg3 != 0x05) err = 0x20; printf("ACT = %x\n",reg3);
if (err != 0) printf ("FEMB: %d COLDATA: %d register %x mismatch\n", femb_ind, i, err);
}
}
|
83e886d3d9151801f2c4fbfcd19f30d4fc3e199b
|
de146d24e0c97af73fb351e02d23833e1dd4e660
|
/ROS_Problem/topic_problem2/src/topic_problem2_pub.cpp
|
eb911a07a09039157f7a1a923def19b3267f5901
|
[
"Unlicense"
] |
permissive
|
ing03201/Learning_ROS
|
b68085ecc82764e74ac57a4fe6b94c66e1cc77a5
|
dd36f2cba4a376d35c9e8029f4741392cb693c0d
|
refs/heads/master
| 2020-04-04T09:31:18.915814
| 2019-01-07T02:09:47
| 2019-01-07T02:09:47
| 155,820,312
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 535
|
cpp
|
topic_problem2_pub.cpp
|
#include <ros/ros.h>
// #include <패키지 이름 / 메시지.h>
#include "topic_problem2/topic_problem2_msg.h"
int main(int argc, char* argv[])
{
ros::init(argc, argv, "topic_problem2_pub");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<topic_problem2::topic_problem2_msg>("topic_problem2_pub",10);
topic_problem2::topic_problem2_msg msg;
ros::Rate loop_rate(10);
srand(time(NULL));
while(true)
{
msg.num = 1 + rand()%4;
pub.publish(msg);
loop_rate.sleep();
}
}
|
25a314b7b2e610255118a95e69ead714d2cfffc4
|
069ab8a8a3d4b434895fd133ea522017715c3491
|
/c++/core/VisibleE.h
|
dac28dcea883a42ad23192b80b493195df6e5eee
|
[] |
no_license
|
ngphubinh/neurons
|
542b3b7d54dc5422464450eade21cf3b0ec44168
|
1de5d3b18e1f617201996733429d136f42ec09d8
|
refs/heads/master
| 2021-01-10T06:22:01.256850
| 2014-07-22T23:40:56
| 2014-07-22T23:40:56
| 50,171,074
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,543
|
h
|
VisibleE.h
|
/** Class VisibleE
* defines a visible object with extended attributes, such as color
*/
#ifndef VISIBLEE_H_
#define VISIBLEE_H_
#include "neseg.h"
#include "Visible.h"
class VisibleE : public Visible
{
public:
/** Options for drawing the object.*/
bool v_draw_projection; // true for maximum intensity, false for minimum
double v_r; // Color of the object
double v_g;
double v_b;
double v_radius; //In case the object has a radius
bool v_enable_depth_test;
bool v_blend;
/** In case we need to create a list to speed things up.*/
int v_glList;
bool v_saveVisibleAttributes; //If we want to save the vissible attributes.
VisibleE() : Visible(){
v_draw_projection = false;
v_r = 1.0;
v_g = 0.0;
v_b = 0.0;
v_radius = 1;
v_glList = 0;
v_saveVisibleAttributes = true;
v_enable_depth_test = false;
v_blend = true;
}
virtual void save(ostream &out)
{
if(v_saveVisibleAttributes){
out << "<VisibleE>" << std::endl;
out << "v_r " << v_r << std::endl;
out << "v_g " << v_g << std::endl;
out << "v_b " << v_b << std::endl;
out << "v_radius " << v_radius << std::endl;
out << "v_enable_depth_test " << v_enable_depth_test << std::endl;
out << "v_blend " << v_blend << std::endl;
out << "</VisibleE>" << std::endl;
}
}
bool load(istream& in)
{
if(v_saveVisibleAttributes){
string s;
string val;
int start = in.tellg();
in >> s;
if(s!="<VisibleE>")
return false;
in >> s;
while(s!="</VisibleE>"){
in >> val;
// std::cout << s << " " << val << std::endl;
stringstream iss(val);
if(s=="v_r")
iss >> v_r;
else if(s=="v_g")
iss >> v_g;
else if(s=="v_b")
iss >> v_b;
else if(s=="v_radius")
iss >> v_radius;
else if(s=="v_enable_depth_test")
iss >> v_enable_depth_test;
else if(s=="v_blend")
iss >> v_blend;
else{
printf("Vissible:error: parameter %s not known. Exiting the parsing\n", s.c_str());
in.seekg(start);
return false;
}
in >> s;
}
} //if
return true;
}
virtual void draw(){
glColor3f(v_r, v_g, v_b);
// glLineWidth(v_radius);
if(v_enable_depth_test)
glEnable(GL_DEPTH_TEST);
else
glDisable(GL_DEPTH_TEST);
}
//Simple crappy method to communicate with the object
virtual void listen(int action){
}
};
#endif
|
ef653bdf8da68628e7fad47bae60aa7e33577569
|
26bd0708eecf955cc203dad16b71a8c2c0b42f7e
|
/hw6/Library_backup.h
|
1ce1c46d6d5352412eddb8f316396800879d83e2
|
[] |
no_license
|
stockdillon/cse_320
|
8311237d6734e96315ac9113cf9a3fc492b5d5ca
|
b3e4888b669e05862738c16ba3cce5b56b1bcd97
|
refs/heads/master
| 2020-03-22T10:08:19.677067
| 2016-12-05T23:19:32
| 2016-12-05T23:19:32
| 139,883,298
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,315
|
h
|
Library_backup.h
|
#include <iostream>
#include <string>
using namespace std;
#ifndef LIBRARY_LIBRARY_H
#define LIBRARY_LIBRARY_H
struct Book {
Book() = delete;
Book(string _isbn, string _title, string _author) : isbn(_isbn), title(_title), author(_author) {};
string isbn;
string title;
string author;
bool operator<(const Book &other) { return isbn < other.isbn; };
bool operator>(const Book &other) { return isbn > other.isbn; };
bool operator==(const Book &other) { return isbn == other.isbn; };
bool operator!=(const Book &other) { return isbn != other.isbn; };
};
class Library {
public:
Library();
void add(Book);
void check_in(Book);
Book *check_out(Book);
Book *search(Book);
long available_copies(Book);
private:
struct BookNode {
Book value;
BookNode *left;
BookNode *right;
size_t count = 1;
BookNode(Book b) : value(b), left(nullptr), right(nullptr) {};
};
BookNode *root;
void add(BookNode *&root_node, BookNode *&new_node);
BookNode *search(Book, BookNode *root);
void display(BookNode *current_node); //*************
};
void Library::display(BookNode *current_node)
{
cout << "... Displaying contents of Library..." << endl;
if (current_node->left != nullptr)
{
display(current_node->left);
}
if ( current_node->right != nullptr)
{
display(current_node->right);
}
cout << endl << "isbn: " << current_node->value.isbn << endl;
cout << "title: " << current_node->value.title << endl;
cout << "author: " << current_node->value.author << endl << endl;
}
Library::Library()
{
this->root = nullptr;
}
void Library::add(Book val)
{
if(this->root == nullptr)
{
BookNode node = BookNode(val);
this->root = &node;
////////
cout << "value at library root: " << this->root->value.title << endl;
display(this->root);
////////
return;
}
/*
if(search(val) != nullptr)
{
cout << "value at library root: " << this->root->value.title << endl; ///////
cout << "This library already contains that book. (" << val.title << ")" << endl;
return;
}
*/
BookNode node = BookNode(val);
BookNode *current_node = this->root;
while(true)
{
if(current_node->value < val)
{
if(current_node->right == nullptr)
{
current_node->right = &node;
return;
}
else
{
current_node = current_node->right;
continue;
}
}
if(current_node->value > val)
{
if(current_node->left == nullptr)
{
current_node->left == &node;
cout << "Hamlet->left became MacBeth" << endl;
return;
}
else
{
current_node = current_node->left;
continue;
}
}
else break;
}
}
void Library::check_in(Book val)
{
if(this->root == nullptr)
{
cout << "That book can not be checked in to this library." << endl;
cout << "There are currently no books in this library." << endl << endl;
return;
}
if(search(val) == nullptr)
{
cout << "That book can not be checked in to this library." << endl << endl;
return;
}
if(this->root->value == val)
{
this->root->count++;
}
if( this->root->value < val)
{
BookNode *node = search(val, this->root->right);
node->count++;
//search(val, this->root->right)->count++;
}
else
{
BookNode *node = search(val, this->root->left);
node->count++;
}
}
Book* Library::check_out(Book val)
{
if(this->root == nullptr)
{
cout << "There are currently no books in this library." << endl << endl;
//cout << "This library does not contain the requested book. (" << val.title << ")" << endl << endl;
return nullptr;
}
}
Book* Library::search(Book val)
{
if(this->root == nullptr)
{
cout << "There are currently no books in this library." << endl << endl;
return nullptr;
}
cout << "check 1" << endl;
if(this->root->value == val)
{
cout << this->root->value.title << endl;
cout << val.title << endl;
return &this->root->value;
}
cout << "check 2" << endl;
if(this->root->value < val)
{
if((this->root->right == nullptr))
return nullptr;
return &search(val, this->root->right)->value;
}
cout << "check 3" << endl;
if(this->root->left == nullptr)
{
cout << "check 4" << endl; //
return nullptr;
}
else
{
return &search(val, this->root->left)->value;
}
}
Library::BookNode* Library::search(Book val, BookNode *new_root)
{
if(new_root->value == val)
return new_root;
if((new_root->left == nullptr) && (new_root->right == nullptr))
return nullptr;
if(new_root->value < val)
{
if(new_root->right == nullptr)
return nullptr;
return search(val, new_root->right);
}
else return search(val, new_root->left);
}
long Library::available_copies(Book val)
{
if(this->root == nullptr)
{
cout << "There are currently no books in this library." << endl << endl;
return 0;
}
if(search(val) == nullptr)
{
cout << "There are no available copies of this book." << endl;
cout << "This library does not contain the requested book." << endl << endl;
return 0;
}
if( this->root->value < val)
{
BookNode *node = search(val, this->root->right);
return node->count;
//search(val, this->root->right)->count++;
}
else
{
BookNode *node = search(val, this->root->left);
return node->count;
}
}
#endif //LIBRARY_LIBRARY_H
|
e05aeee058646f249e295b59e76c4cf562c10515
|
dd15d41123ada0b8a6ac09e0aface5a3d04e9a62
|
/Day 12/p3.cpp
|
293a031673dbcf55399a772a5e0883d73af0cddd
|
[] |
no_license
|
Aman2241/Coding
|
27fd2b773f976fbddd709c07f94e6cb3d84b76b9
|
6b9f9fa422daf3014ce1ed86a203e2446c6abeb4
|
refs/heads/master
| 2022-11-13T15:03:18.525332
| 2020-07-04T15:27:01
| 2020-07-04T15:27:01
| 261,521,813
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 363
|
cpp
|
p3.cpp
|
#include<bits/stdc++.h>
using namespace std;
class Base{
public:
void fun1()
{
cout<<"Hello I am Base"<<endl;
}
void fun2()
{
cout<<"Hello I am base fun"<<endl;
}
};
class Derrived:public Base{
public:
void fun3()
{
cout<<"I am derrived"<<endl;
}
};
int main()
{
Base *p;
p=new Derrived();
p->fun1();
p->fun2();
return 0;
}
|
e7b2b41a6276ea491ce96be4bccc452f45673f84
|
6550126ec9f3310fb7083edb17edb84faac71e9f
|
/src/M/6/M648_ReplaceWords.cpp
|
42d88eed1c22a425a024a56afaa3de933f647fb7
|
[] |
no_license
|
d2macster/leetcode-cpp
|
d9dd988a18f3721141b4a174e44fb4cbffa47e1d
|
48caf45921107f5003bf5b766242c11840e5b84c
|
refs/heads/master
| 2021-07-16T20:50:55.500503
| 2018-08-26T22:10:05
| 2018-08-26T22:10:05
| 116,715,207
| 0
| 1
| null | 2019-10-24T17:45:49
| 2018-01-08T18:54:01
|
C++
|
UTF-8
|
C++
| false
| false
| 1,415
|
cpp
|
M648_ReplaceWords.cpp
|
//
// Created by Andrii Cherniak on 3/19/18.
//
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
struct Node {
vector<Node *> links = vector<Node *>(26, nullptr);
bool end = false;
char ch;
Node(char c) { ch = c; };
};
class Solution {
Node *root = new Node((char) 0);
void insertWord(string &word) {
Node *n = root;
for (char c: word) {
if (n->links[c - 'a'] == nullptr) {
Node *nn = new Node(c);
n->links[c - 'a'] = nn;
}
n = n->links[c - 'a'];
}
n->end = true;
}
string replacement(string &word) {
Node *n = root;
int l = 0;
for (char c: word) {
if (n->links[c - 'a'] == nullptr) return word;
n = n->links[c - 'a'];
l++;
if (n->end)
return word.substr(0, l);
}
return word;
}
public:
string replaceWords(vector<string> &dict, string sentence) {
if (sentence == "") return sentence;
for (string &s: dict) insertWord(s);
istringstream iss(sentence);
ostringstream oss;
string s;
bool first = true;
while (iss >> s) {
if (!first) oss << " ";
oss << replacement(s);
first = false;
}
return oss.str();
}
};
|
d603ff6e204c4e9b571392753c48d27a105288b1
|
11ee3388d2aaddeb7643e3bcf7b345c2920f0bc9
|
/src/0813.cpp
|
8cb9515c7e426145974d401f3f37281e6573af1f
|
[] |
no_license
|
cdsama/LeetCode
|
5172ba02e5a32e4a8155a236f19fac19967b6159
|
afc59f4c4a2b3ca393d7eea22d996a3b5eb2de5d
|
refs/heads/master
| 2020-03-29T01:44:35.028235
| 2019-09-27T03:08:35
| 2019-09-27T03:08:35
| 149,404,114
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,042
|
cpp
|
0813.cpp
|
#include "LeetCode.hpp"
/*
813. Largest Sum of Averages
Medium
We partition a row of numbers A into at most K adjacent (non-empty) groups, then our score is the sum of the average of each group. What is the largest score we can achieve?
Note that our partition must use every number in A, and that scores are not necessarily integers.
Example:
Input:
A = [9,1,2,3,9]
K = 3
Output: 20
Explanation:
The best choice is to partition A into [9], [1, 2, 3], [9]. The answer is 9 + (1 + 2 + 3) / 3 + 9 = 20.
We could have also partitioned A into [9, 1], [2], [3, 9], for example.
That partition would lead to a score of 5 + 2 + 6 = 13, which is worse.
Note:
1 <= A.length <= 100.
1 <= A[i] <= 10000.
1 <= K <= A.length.
Answers within 10^-6 of the correct answer will be accepted as correct.
Tags:
1. Dynamic Programming
*/
class Solution {
public:
double largestSumOfAverages(vector<int>& A, int K) {
}
};
TEST_CASE("largest-sum-of-averages", "[813][Medium][dynamic-programming]") {
//TODO
CHECK(true);
}
|
0dbf27e9056c1a3ef0922c82d496ef8affa65872
|
3266ed5f196b3a34c1fe0d27c72bbbe9dcde6866
|
/lightoj/1009 - Back to Underworld .cpp
|
ab4559be7db1568580f5710ca7b5145c5c8808be
|
[] |
no_license
|
akazad7567/Practice
|
f7cbd3d759654fcbaed8054b1cc9b06344a99241
|
a2817e984be521bbe1c50cdcaed383db338196ae
|
refs/heads/master
| 2021-09-28T04:51:38.038418
| 2021-09-24T08:22:35
| 2021-09-24T08:22:35
| 242,341,281
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,520
|
cpp
|
1009 - Back to Underworld .cpp
|
#include<bits/stdc++.h>
using namespace std;
#define MAX 200050
vector<int>adj[MAX];
vector<bool>vis(MAX,false);
vector<int>d(MAX,0);
int enemy=0,frnd=0;
int fenemy=0,ffrnd=0;
void clean()
{
for(int i=0;i<MAX;i++) adj[i].clear(),vis[i]=false,d[i]=0;
enemy=0,frnd=0;
fenemy=0,ffrnd=0;
}
int bfs(int st)
{
queue<int>q;
q.push(st);
vis[st]=true;
while(!q.empty())
{
int p=q.front();
q.pop();
if(d[p] & 1) enemy++;
else frnd++;
for(int it:adj[p])
{
if(vis[it]==false)
{
vis[it]=true;
q.push(it);
d[it]=d[p]+1;
}
}
}
}
int main()
{
// freopen("out.txt","w",stdout);
int t;
scanf("%d",&t);
int tks=0;
while(t--)
{
tks++;
int n;
scanf("%d",&n);
int mx=0;
for(int i=0;i<n;i++)
{
int u,v,sz;
scanf("%d %d",&u,&v);
adj[u].push_back(v);
adj[v].push_back(u);
}
int ans=0;
for(int i=1;i<MAX;i++)
{
enemy=0,frnd=0;
for(int it:adj[i]){
if(vis[it]==false) {bfs(it);
// cout<<it<<"-> "<<enemy<<' '<<frnd<<endl;
ans+=max(enemy,frnd);
}
}
}
// cout<<fenemy<<' '<<ffrnd<<endl;
printf("Case %d: %d\n",tks,ans);
clean();
}
}
|
4d1a7b137072f4fcd278aaec2b598875bd2da725
|
b654e2c059f8460b6a46929033ec24368cd1f64d
|
/2_DerivCreOrder.cpp
|
c4f688e8290cbb0c69a77f686db6b4e248ff22ab
|
[] |
no_license
|
devlek/Dev
|
9b0fc567628b3e336a1d58efe274b3d7b42724cc
|
42c4f76dd75380837e52211b03c422f265630498
|
refs/heads/master
| 2021-01-13T16:22:12.233235
| 2017-01-25T09:53:37
| 2017-01-25T09:53:37
| 79,899,191
| 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,580
|
cpp
|
2_DerivCreOrder.cpp
|
#include<iostream>
using namespace std;
/*
* 유도 클래스의 객체 생성과정 -> 기초 클래스의 생성자 호출에 관심
결1. 유도 클래스의 객체생성 과정에서 기초 클래스의 생성자는 100% 호출된다.
결2. 유도 클래스의 생성자에서 기초 클래스의 생성자 호출을 명시하지 않으면, 기초 클래스의 void 생성자가 호출된다.
클래스 생성 순서.
유도 클래스만 생성한다고 해도
자동으로 기초 클래스 -> 유도 클래스 순으로 생성
*/
class SoBase
{
private:
int baseNum;
public:
SoBase() : baseNum(20)
{
cout << "SoBase()" << endl;
}
SoBase(int n) :baseNum(n)
{
cout << "SoBase(int n)" << endl;
}
void ShowBaseData()
{
cout << baseNum << endl;
}
};
class SoDerived :public SoBase
{
private:
int derivNum;
public:
SoDerived() :derivNum(30)
{
cout << "SoDerived()" << endl;
}
SoDerived(int n) :derivNum(n)
{
cout << "SoDerived(int n)" << endl;
}
SoDerived(int n1, int n2) : SoBase(n1), derivNum(n2)
{
cout << "SoDerived(int n1, int n2)" << endl;
}
void ShowDerivData()
{
ShowBaseData();
cout << derivNum << endl;
}
};
int main(void)
{
cout << "case1..... " << endl;
SoDerived dr1;
dr1.ShowDerivData();
cout << "--------------------" << endl;
cout << "case2..... " << endl;
SoDerived dr2(12);
dr2.ShowDerivData();
cout << "--------------------" << endl;
cout << "case3..... " << endl;
SoDerived dr3(23, 24);
dr3.ShowDerivData();
return 0;
}
|
64f0aeef944c6d6aafa9429e19285e48ca32ef11
|
fdf2e46c71d7d973cc3607dc7c0ff859567a7417
|
/core/ps/table/sparse_table.cc
|
a9024c273180c8c5fc4e0d7bf6d1c438ae690f49
|
[
"Apache-2.0"
] |
permissive
|
zz198808/tensornet
|
9821e668a617e5befbbc96b4d148ce142bdcd23a
|
115e267f84ed60c3ea080f17b1e2cfbe4dfb6061
|
refs/heads/master
| 2022-12-15T23:40:40.456589
| 2020-09-18T08:20:23
| 2020-09-18T08:20:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,691
|
cc
|
sparse_table.cc
|
// Copyright (c) 2020, Qihoo, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "core/ps/table/sparse_table.h"
#include <set>
#include <string>
#include <butil/containers/flat_map.h>
#include <butil/logging.h>
#include <butil/object_pool.h>
#include "core/ps/optimizer/optimizer_kernel.h"
#include "core/ps/ps_cluster.h"
namespace tensornet {
SparseTable::SparseTable(const OptimizerBase* opt, int dimension)
: opt_(opt)
, dim_(dimension) {
CHECK(opt_ != nullptr);
op_kernel_ = opt_->CreateSparseOptKernel(dim_);
}
void SparseTable::SetHandle(uint32_t handle) {
CHECK(handle_ == 0) << "sparse table handle has already set:" << handle_;
handle_ = handle;
}
void SparseTable::Pull(const SparsePullRequest* req, SparsePullResponse* resp) {
resp->set_table_handle(req->table_handle());
CHECK_EQ(dim_, req->dim());
resp->set_dim(req->dim());
for (int i = 0; i < req->signs_size(); ++i) {
SparseWeightInfo weight_info;
uint64_t sign = req->signs(i);
if (false == op_kernel_->GetWeight(sign, weight_info)) {
weight_info.weight = nullptr;
CHECK(op_kernel_->NewSignWithWeight(sign, weight_info));
CHECK(nullptr != weight_info.weight);
}
VariableWeight* weight = resp->add_weight();
weight->set_sign(sign);
// weight_info.weight size is guaranteed by op_kernel_ same with dim_
for (int j = 0; j < dim_; j++) {
weight->add_w(weight_info.weight[j]);
}
}
}
void SparseTable::Push(const SparsePushRequest* req, SparsePushResponse* resp) {
CHECK_EQ(dim_, req->dim());
std::vector<float> grad(dim_);
for (int i = 0; i < req->weight_size(); i++) {
const VariableWeight& weight = req->weight(i);
CHECK_EQ(weight.w_size(), dim_);
for (int j = 0; j < weight.w_size(); j++) {
grad[j] = weight.w(j);
}
SparseGradInfo grad_info;
grad_info.grad = grad.data();
grad_info.show = weight.show();
op_kernel_->Apply(weight.sign(), grad_info);
}
}
void SparseTable::Save(const std::string& filepath) const {
butil::Timer timer(butil::Timer::STARTED);
int shard_id = PsCluster::Instance()->Rank();
std::string file = filepath + "/sparse_table/" + std::to_string(GetHandle())
+ "/rank_" + std::to_string(shard_id);
op_kernel_->Serialized(file);
timer.stop();
LOG(INFO) << "SparseTable save. rank:" << shard_id
<< " table_id:" << GetHandle()
<< " latency:" << timer.s_elapsed() << "s"
<< " keys_count:" << op_kernel_->KeyCount();
}
void SparseTable::Load(const std::string& filepath) const {
butil::Timer timer(butil::Timer::STARTED);
int shard_id = PsCluster::Instance()->Rank();
std::string file = filepath + "/sparse_table/" + std::to_string(GetHandle())
+ "/rank_" + std::to_string(shard_id);
op_kernel_->DeSerialized(file);
timer.stop();
LOG(INFO) << "SparseTable load. rank:" << shard_id
<< " table_id:" << GetHandle()
<< " latency:" << timer.s_elapsed() << "s"
<< " keys_count:" << op_kernel_->KeyCount();
}
void SparseTable::ShowDecay() const {
op_kernel_->ShowDecay();
}
SparseTableRegistry* SparseTableRegistry::Instance() {
static SparseTableRegistry instance;
return &instance;
}
SparseTable* SparseTableRegistry::Get(uint32_t table_handle) {
CHECK(table_handle < tables_.size())
<< " table_handle:" << table_handle << " table size:" << tables_.size();
return tables_[table_handle];
}
uint32_t SparseTableRegistry::Register(SparseTable* table) {
const std::lock_guard<std::mutex> lock(mu_);
uint32_t table_handle = tables_.size();
tables_.emplace_back(table);
return table_handle;
}
SparseTable* CreateSparseTable(const OptimizerBase* opt, int dimension) {
SparseTable* table = new SparseTable(opt, dimension);
table->SetHandle(SparseTableRegistry::Instance()->Register(table));
return table;
}
} // namespace tensornet
|
ad51e943e0731db927acfd31f7ee314a62e966e7
|
5c7b99c11768a6af134d3dc9244dc03b48bce4d5
|
/Computational Geometry/2009_Shape_CAD:CAM/release/lib/simp/si_inter.cc
|
59e4edfc48fdf0a9454af9aa9564c7f0bf03ad55
|
[] |
no_license
|
symphonylyh/research-readings
|
d241b7570681fd47ab414dec21686496be07f246
|
04e70f7de7caff56430db8540302f7147d7613fc
|
refs/heads/master
| 2021-09-15T09:52:43.691539
| 2021-09-03T03:52:07
| 2021-09-03T03:52:07
| 162,491,848
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,335
|
cc
|
si_inter.cc
|
/*****************************************************************************
si_inter.cc last edit 10.22.92
****************************************************************************/
#include "simpoly.h"
#include "compiler.h"
/* The heart of the intersection algorithm */
#ifndef NO
#define NO 0
#endif
#ifndef YES
#define YES 1
#endif
using namespace std;
int PRINT_BOX = NO;
extern int si_reset_flag; /* Do we reset everything? */
int szplug;
void si_multipush (Rstack &stack, int_array &l, Bbox &B)
/* Push unresolved problems onto the stack */
{
// cout << " in si_multipush " << endl;
int i,j; /* Loop counters */
int n = B.n; /* Number of dimensions */
int m = 1; /* Number of recursive subproblems */
for (i=0; i < n; i++)
if (l[i]) m *= 2; /* Get new value of m */
Bbox **B_list = /* List of boxes */
new Bbox*[m];
for (i=0; i < m; i++) /* Allocate B_list elements */
B_list[i] =
new Bbox(n);
// cout << "original box is " << B << endl;
for (i=0; i < m; i++) { /* Set up boxes */
int k=1; /* k = 2^(number of 1's we have passed) */
for (j=0; j < n; j++)
if (l[j]) {
// cout << j << "-th dir has been subdivided " << endl;
if (i & k) { /* Position equal to 1? */
#ifdef USE_INTERVAL
B_list[i]->a[j] = /* Second half of the interval */
(0.5 * (B.b[j]+B.a[j])).lower();
B_list[i]->b[j] =
B.b[j].upper();
#else
#ifdef USE_RAT
B_list[i]->a[j] = /* Second half of the interval */
(Rat(1,2) * (B.b[j]+B.a[j]));
B_list[i]->b[j] =
B.b[j];
#else
B_list[i]->a[j] = /* Second half of the interval */
(0.5 * (B.b[j]+B.a[j]));
B_list[i]->b[j] =
B.b[j];
#endif
#endif
} else {
#ifdef USE_INTERVAL
B_list[i]->a[j] = /* First half of interval */
B.a[j].lower();
B_list[i]->b[j] =
(0.5 * (B.b[j]+B.a[j])).upper();
#else
#ifdef USE_RAT
B_list[i]->a[j] = /* First half of interval */
B.a[j];
B_list[i]->b[j] =
(Rat(1,2) * (B.b[j]+B.a[j]));
#else
B_list[i]->a[j] = /* First half of interval */
B.a[j];
B_list[i]->b[j] =
(0.5 * (B.b[j]+B.a[j]));
#endif
#endif
}
k *= 2; /* Increment k's exponent; we passed a 1 */
} else { /* No binary subdivision in this index */
// cout << j << "-th dir has not been subdivided " << endl;
B_list[i]->a[j] =
B.a[j];
B_list[i]->b[j] =
B.b[j];
}
}
// cout<<"one multinomial has been subdivided into " << m << "multis"<< endl;
for (i=0; i < m; i++) {
stack.push (B_list[i]); /* Push onto the stack */
// cout << *(B_list[i]) << endl;
}
delete B_list; /* Free array of pointers (but not the boxes!) */
// cout << " out si_multipush " << endl;
}
void si_sub (mn_array &mns, mn_array &mn_list, Bbox &B)
/* Subdivide mns, making mn_list correspond to the subdivision of mns
according to the box B. Calls mnr_sub as a driver. */
{
int i,j;
int n = mns.size(); // n is number of equations
int n_dim; /* number of unknows */
n_dim = mns[0].ndim();
// cout << "inside si_sub " << endl;
// cout << " B = " << B << endl;
// cout << " no of eqs = " << n << endl;
// cout << " no of unknowns = " << n_dim << endl;
/* {
for (int ii = 0; ii < n ; ii++) {
cout << "mn_list[" << ii << "] is " << endl;
cout << mn_list[ii] << endl;
}
}
*/
for (i=0; i < n; i++) { // number of equations
// cout << " i = " << i << endl;
// cout << B.a[0].lower() << endl;
// cout << B.b[0].upper() << endl;
// cout << mn_list[i] << endl;
#ifdef USE_INTERVAL
mns[i].sub /* Subdivide in first direction */
(0, B.a[0].lower(), B.b[0].upper(), &mn_list[i]);
#else
mns[i].sub /* Subdivide in first direction */
(0, B.a[0], B.b[0], &mn_list[i]);
#endif
for (j=1; j < n_dim; j++) { /* Subdivide in other directions */
// cout << " B.a[" << j << "] = " << B.a[j] ;
// cout << " B.b[" << j << "] = " << B.b[j] << endl;
#ifdef USE_INTERVAL
mn_list[i].sub
(j, B.a[j].lower(), B.b[j].upper(), &mn_list[i]);
#else
mn_list[i].sub
(j, B.a[j], B.b[j], &mn_list[i]);
#endif
}
}
/* cout << " after sub " << endl;
{
for (int ii = 0; ii < n ; ii++) {
cout << "mn_list[" << ii << "] is " << endl;
cout << mn_list[ii] << endl;
}
}
cout << " multi.sub " << endl;
*/
}
rootlist *si_pinter (mn_array &mns, real eps)
/* Intersect the multinomials iteratively using the
Projected-Polyhedron algorithm. Start with the box [0,1] x ... x [0,1]
bounding all possible roots, and then subdivide the multinomials,
eliminating areas where no roots can occur. This elimination results
from checking intersections of the convex hulls of the multinomials
with one another. If at any point the size of the new box is more than
80% of the current interval size, split the problem into two
subproblems of approximately equal size by splitting the interval in
half. Use an event stack to hold all the pending subproblems.
When all intervals are small enough, we stop splitting and splice
the root onto the list of roots which already exists. Return 0
if something very wrong occurs.
We assume without checking that the size of mn_list is equal to the
number of dimensions of any multinomial in the list. */
{
rootlist *points; /* The list we return */
int i; /* loop counters */
int ndim = mns[0].ndim(); /* number of unknowns */
mn_array mn_list(mns); /* Major list for subdivision -- make a copy */
Bbox *B = new Bbox (ndim); /* The current bounding box */
Rstack stack; /* The event stack */
int nbinary = 0 ; /* the number of binary subdivision */
int counter = 0 ; /* the number of Iterations */
int lastcheck=0; /* Added 1/3/94; this flag checks to see
if we are doing a final verification check
on a sufficiently small box. */
// cout << " just in si_pinter " << endl;
// cout << " ndim = " << ndim << endl;
// cout << " mn_list[0] = \n " << setprecision(15) << mn_list[0] << endl;
// if (ndim >1)
// cout << " mn_list[1] = \n " << setprecision(15) << mn_list[1] << endl;
/* Initialize points and mn_list */
points = new rootlist;
stack.push (B); /* Push governing data onto the event stack */
/* Now begin the intersection process */
while (stack.pop (&B)) { /* While there are things to process */
// cout << "*******************************************" <<endl;
// cout << " counter = " << counter << endl;// counter++;
counter++;
/* Reduce the box in question to the necessary size.
Use a bounding box approach to generate a new box. */
if (PRINT_BOX) {
// cout << "try box " << setprecision(15) << *B << flush;
// cout << endl;
}
int_array check(ndim);
Bbox *B2 = new Bbox(ndim); /* Allocate B2 */
for (i=0; i < ndim; i++)
if (B->b[i] - B->a[i] < eps) {
// cout << " i= " << i << " a= " << B->a[i] ;
// cout << " b= " << B->b[i] <<endl;
real b_a = B->b[i] - B->a[i];
// cout << " b - a= " << b_a << endl;
real mid =
#ifndef USE_RAT
(B->b[i] + B->a[i]) / 2.;
B->a[i] = mid-eps/2.01;
/* This makes some artificial correction */
B->b[i] = mid+eps/2.01;
#else
(B->b[i] + B->a[i]) / Rat(2,1);
B->a[i] = mid-eps/Rat(201,100);
/* This makes some artificial correction */
B->b[i] = mid+eps/Rat(201,100);
#endif
check[i] = 0;
#ifndef USE_RAT
B2->a[i] = 0.0;
B2->b[i] = 1.0;
#else
B2->a[i] = Rat(0,1);
B2->b[i] = Rat(1,1);
#endif
// cout << " check[" << i <<"] = " << check[i] << endl;
} else {
check[i] = 1;
// cout << " check[" << i <<"] = " << check[i] << endl;
}
// cout << "inside si_pinter just before si_sub" << endl;
// cout << " B = " << setprecision(8) << *B << endl;
// cout << " mn_list[0] = \n " << mn_list[0] << endl;
// if (ndim >1)
// cout << " mn_list[1] = \n " << mn_list[1] << endl;
si_sub (mns, mn_list, *B); /* Subdivision or Bezier clipping */
si_phull(mn_list, *B2, check); /* Generate it */
// cout << " after su_sub" << endl;
// cout << " last check = " << lastcheck << endl;
// cout << " mn_list[0] = \n " << mn_list[0] << endl;
// if (ndim >1) cout << " mn_list[1] = \n " << mn_list[1] << endl;
if (B2->flag()) { /* Nothing in the box? */
// cout << " No root" << endl;
delete B2; /* Added */
delete B; /* Added */
continue; /* Break away */
}
B2->scale (*B); /* Scale the second box with the first */
// cout << " after scale " << endl;
// cout << " B2 = " << setprecision(8) << *B << endl;
/* Now, check the new box. We may need to do some binary */
/* subdivision. If so, perform the subdivision and push the other */
/* subproblems onto the event stack. */
if (lastcheck) {
real_array root(ndim);
for (i=0; i < ndim; i++) {
#ifdef USE_INTERVAL
Interval low(0.0);
Interval high(0.0);
Interval epsilon_correction(0.0);
// due to artificial correction (above)
epsilon_correction = eps * ( 1.0 / 2.0 - 1.0 / 2.01);
// cout << " ep_cor = "<< epsilon_correction << endl;
// cout << " B2->a[i] = " << B2->a[i] << endl;
// cout << " B2->b[i] = " << B2->b[i] << endl;
low = B2->a[i] - 1.0 * epsilon_correction;
high = B2->b[i] + 1.0 * epsilon_correction;
// cout << " low = " << low << endl;
// cout << " high = " << high << endl;
root[i] = merge(low, high);
// root[i] = merge(B2->a[i], B2->b[i]);
/* Put points in */
#else
#ifdef USE_RAT
root[i] = (Rat(1,2) * (B2->a[i] + B2->b[i]));
#else
root[i] = (0.5 * (B2->a[i] + B2->b[i]));
#endif
#endif
// cout << root[i] << " , ";
}
//cout << endl;
// cout << " before final check " << endl;
int yes_or_no;
yes_or_no = mn_list.convex_hull_cross_every_axis();
if( yes_or_no == YES) /* Added by Hu 2/4/94 */
{
//cout << "Add to points!" << endl;
points->insert(root);
}
delete B2;
lastcheck = 0;
}
else if (B2->small(eps)) {
/* Small enough? */
// cout << "B2 small enough" << setprecision(15) << *B2 << endl;
// cout << " eps = " << eps << endl;
// for (i=0; i<B2->n; i++)
// cout <<"b[i] - a[i] = "<< B2->b[i] - B2->a[i] << endl;
// cout << " root" << endl;
lastcheck = 1;
stack.push(B2);
} else {
int_array flags (ndim);
B->subcheck /* Subdivison flags */
(*B2, check, flags);
if (B->flag()) { /* Binary subdivision needed? */
si_multipush /* Push new boxes onto the stack */
(stack, flags, *B2);
delete B2; /* Added */
nbinary++;
// cout << " Binary sub." << endl;
} else { /* No binary subdivision needed */
stack.push (B2); /* Push it on for reconsideration */
// cout << endl;
}
}
delete B; /* Trash B */
} /* End of while loop */
//cout << " number of roots = " << points->size() << endl;
//cout << " number of iterations = " << counter << endl;
//cout << " number of binary subdivision = " << nbinary << endl;
points->head(); /* Move back to head of list */
return (points);
} /* End of si_pinter */
|
ab2e92e1f37ee6012bf774cf8f1a1695a74fe41e
|
7d976a680d234e932041e2712c4afe75df1df752
|
/UE3_SDK_Generator/SDK_Main.h
|
04ba2809d8dac669b32fc7c9d22faab85800734b
|
[
"MIT"
] |
permissive
|
confl8/ue3gen
|
dd6cc706a296ef99acac8dc5e4850838b07b4dda
|
827da750000dea60de1dcbd46adc3d0051761a34
|
refs/heads/master
| 2020-04-02T23:35:07.520411
| 2015-05-19T08:59:52
| 2015-05-19T08:59:52
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,645
|
h
|
SDK_Main.h
|
//Start including the nessicary UE Core files...this includes stuff like the data needed to walk the tables and such
#ifndef _SDK_MAIN_
#define _SDK_MAIN_
#define GObjects 0x01DE5FA4
#define GNames 0x01DD46E8
#define CPF_Edit 0x1
#define CPF_Const 0x2
#define CPF_OptionalParm 0x10
#define CPF_Net 0x20
#define CPF_Parm 0x80
#define CPF_OutParm 0x100
#define CPF_ReturnParm 0x400
#define CPF_CoerceParm 0x800
#define CPF_Native 0x1000
#define CPF_Transient 0x2000
#define CPF_Config 0x4000
#define CPF_Localized 0x8000
template < class T > struct TArray
{
public:
T* Data;
int Count;
int Max;
public:
int Num ()
{
return Count;
};
T at ( int Index )
{
return Data[ Index ];
};
};
class FNameEntry
{
public:
__int32 Index;
__int32 Unknown001;
__int32 Unknown002;
__int32 Unknown003;
wchar_t Name[ 16 ];
};
class FName
{
public:
int Index;
unsigned char unknown_data00[ 4 ];
public:
static TArray< FNameEntry* >* Names ()
{
return ((TArray<FNameEntry *>*)GNames);
};
wchar_t* GetName ()
{
TArray< FNameEntry* >* pNames = Names();
if( pNames == NULL ) return NULL;
FNameEntry *pNameEntry = pNames->at( Index );
if( pNameEntry == NULL ) return NULL;
return pNameEntry->Name;
};
};
class FString : public TArray< wchar_t >
{
public:
FString ()
{
};
FString ( wchar_t *s )
{
Set( s );
}
~FString ()
{
};
void Set ( wchar_t* Buffer )
{
this->Data = Buffer;
this->Count = this->Max = static_cast< int >( wcslen( Buffer ) ) + 1;
};
};
struct FScriptDelegate
{
unsigned char unknowndata00[ 10 ];
};
struct FIntPoint
{
int X;
int Y;
};
struct FPointer
{
int Dummy;
};
struct FDouble
{
int A;
int B;
};
struct FQWord
{
int A;
int B;
};
class UObject
{
public:
int VfTableObject; //0000
int ObjectInternalInteger; //0004
struct FQWord ObjectFlags; //0008
struct FPointer HashNext; //0010
struct FPointer HashOuterNext; //0014
struct FPointer StateFrame; //0018
class UObject* Linker; //001C
struct FPointer LinkerIndex; //0020
int NetIndex; //0024
class UObject* Outer; //0028
class FName Name; //002C
class UClass* Class; //0034
class UObject* ObjectArchetype; //0038
static UClass* StaticClass ()
{
static UClass* ClassPointer = NULL;
if ( ClassPointer == NULL )
{
ClassPointer = ( UClass* )UObject::FindObject( "Class Core.Object" );
}
return ClassPointer;
};
public:
static TArray< UObject* >* GObjObjects ();
std::wstring GetName();
std::wstring GetNameCPP();
std::wstring GetFullName();
std::wstring GetPackageName();
bool IsA ( UClass* pClass );
static UObject* FindObject ( wchar_t* pObjectName );
static UObject* FindObject ( char* pObjectName );
};
class UField : public UObject
{
public:
class UField* SuperField;
class UField* Next;
public:
static UClass* StaticClass ()
{
static UClass *ClassPointer = NULL;
if ( !ClassPointer )
ClassPointer = ( UClass* )UObject::FindObject( "Class Core.Field" );
return ClassPointer;
};
};
class UEnum : public UField
{
public:
TArray< FName > Names;
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* ) FindObject( "Class Core.Enum" );
return PrivStaticClass;
}
};
class UConst : public UField
{
public:
FString Value;
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* ) FindObject( "Class Core.Const" );
return PrivStaticClass;
};
};
class UStruct : public UField
{
public:
DWORD ScriptText; // 0x48
DWORD CppText; // 0x4C
UField* Children; // 0x50
DWORD PropertySize; // 0x54
TArray< BYTE > Script; // 0x58
unsigned char unknown_data0x1[0x30]; // 0x60
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* ) FindObject( "Class Core.Struct" );
return PrivStaticClass;
};
};
class UFunction : public UStruct
{
public:
DWORD FunctionFlags;
WORD iNative;
WORD RepOffset;
BYTE OperPrecedence;
FName FriendlyName;
BYTE NumParms;
WORD ParmsSize;
WORD ReturnValueOffset;
class UStructProperty* FirstStructWithDefaults;
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* ) FindObject( "Class Core.Function" );
return PrivStaticClass;
};
};
class UState : public UStruct
{
public:
unsigned char unknown_data24[ 44 ];
public:
static UClass* StaticClass ()
{
static UClass *ClassPointer = NULL;
if ( !ClassPointer )
ClassPointer = ( UClass* )UObject::FindObject( "Class Core.State" );
return ClassPointer;
};
};
class UClass : public UState
{
public:
unsigned char unknown_data25[ 192 ];
public:
static UClass* StaticClass ()
{
static UClass *ClassPointer = NULL;
if ( !ClassPointer )
ClassPointer = ( UClass* )UObject::FindObject( "Class Core.Class" );
return ClassPointer;
};
};
class UProperty : public UField
{
public:
DWORD ArrayDim;
DWORD ElementSize;
DWORD PropertyFlags;
DWORD PropertyFlags2;
char unknown_data[0x10];
DWORD PropertyOffset;
char unknown_data0x1[0x1C];
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.Property" );
return PrivStaticClass;
}
};
class UByteProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.ByteProperty" );
return PrivStaticClass;
}
};
class UIntProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.IntProperty" );
return PrivStaticClass;
}
};
class UFloatProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.FloatProperty" );
return PrivStaticClass;
}
};
class UBoolProperty : public UProperty
{
public:
int Order;
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.BoolProperty" );
return PrivStaticClass;
}
};
class UStrProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.StrProperty" );
return PrivStaticClass;
}
};
class UNameProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.NameProperty" );
return PrivStaticClass;
}
};
class UObjectProperty : public UProperty
{
public:
UClass* PropertyClass;
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.ObjectProperty" );
return PrivStaticClass;
}
};
class UClassProperty : public UProperty
{
public:
UClass* MetaClass;
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.ClassProperty" );
return PrivStaticClass;
}
};
class UStructProperty : public UProperty
{
public:
UStruct* Struct;
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.StructProperty" );
return PrivStaticClass;
}
};
class UArrayProperty : public UProperty
{
public:
UProperty* Inner;
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.ArrayProperty" );
return PrivStaticClass;
}
};
class UDelegateProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.DelegateProperty" );
return PrivStaticClass;
}
};
class UPointerProperty : public UProperty
{
public:
static UClass* StaticClass( void )
{
static UClass* PrivStaticClass = NULL;
if ( !PrivStaticClass )
PrivStaticClass = ( UClass* )FindObject( "Class Core.PointerProperty" );
return PrivStaticClass;
}
};
#endif
|
a97cd49167dd22839de39dadc04204b84370bd78
|
0ca2f0107a3292984b5ad149896ab47c756d1068
|
/item.hpp
|
1cd0facdfc55e2f066793ac4d6cc0d74cf3346ca
|
[] |
no_license
|
Zou1c/OSfinal
|
0ec87a591e598bbf3c1a7ca226a05862e7c10702
|
41e7a0786acfdef88258543161c48c747789239a
|
refs/heads/master
| 2023-01-23T09:40:26.324906
| 2020-12-04T06:11:52
| 2020-12-04T06:11:52
| 318,426,651
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,004
|
hpp
|
item.hpp
|
#pragma once
#include <map>
#include <string>
#include <iostream>
#include <mutex>
#include <stdexcept>
#include <ostream>
#include <istream>
class Item
{
private:
std::map<std::string, std::map<std::string, int>> itemList;
std::mutex mtx_itemList;
public:
Item();
Item(std::istream& inputStream);
int addItem(const std::string& name);
int addProperty(const std::string& itemName, const std::string& propertyName);
int changePropertyValue(const std::string& itemName, const std::string& propertyName, int value);
int getPropertyValue(const std::string& itemName, const std::string& propertyName);
int increaseQuantity(const std::string& itemName, int offset = 1);
int decreaseQuantity(const std::string& itemName, int offset = -1);
int getQuantity(const std::string& itemName);
void writeObject(std::ostream& outputStream);
void readObject(std::istream& inputStream);
~Item();
};
|
d461080d3d2a69b5742073b0dd6ac60be525e5d4
|
932e4071ce41fc4e2a3d505fe0349ecba59023f6
|
/thread_1.cpp
|
c41693db26ca10a22284d964c8e5d4e24d254b83
|
[] |
no_license
|
highlightz/Learn-C-CPP
|
54af5aa14567d129e0fe0940886f93edff45ec0e
|
75c97e21930d4440690abb0f6de7935dea5c2876
|
refs/heads/master
| 2020-04-10T13:29:10.227131
| 2016-03-26T11:51:29
| 2016-03-26T11:51:29
| 40,968,430
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 649
|
cpp
|
thread_1.cpp
|
// Compile:
// g++ main.cpp -o main -pthread -std=c++11
#include <thread>
#include <iostream>
void foo( )
{
std::cout << "foo executed!\n";
}
void bar( int x )
{
std::cout << "bar executed! " << x << " passed in!\n";
}
int main( )
{
std::thread first( foo ); // Spawn new thread that calls foo()
std::thread second( bar, 10 ); // Spawn new thread that calls bar()
std::cout << "main, foo and bar now execute concurrently...\n";
// Synchronize threads
first.join( ); // Pause until first finishes
second.join( ); // Pause until second finishes
std::cout << "foo and bar completed.\n";
return 0;
}
|
f2de1ced1d2347778b77045708f988f94832a459
|
8df563b58a3bb7e395a04eb3fb78384d328e8fc6
|
/Pokemon/Main.cpp
|
d9aa915dcfdb750efe2d0ffeaebd8e24f2e592c0
|
[] |
no_license
|
freckie/PokemonConsole
|
f48b3ae239d067b448954336de5c92d50d35c560
|
82a1919d27e68bb286143e142c9b28680f9d5418
|
refs/heads/master
| 2021-01-02T08:52:58.977509
| 2017-08-02T07:00:10
| 2017-08-02T07:00:10
| 99,083,321
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 98
|
cpp
|
Main.cpp
|
#include<iostream>
#include"App.h"
using namespace std;
int main(void)
{
App app;
app.run();
}
|
8a1f41b33a75ad51c990e04cf6b39c7278997445
|
7c779fb0d0cf55fa221c34e25f13d0605b124564
|
/Bigmod.cpp
|
6e7e5be68370d5368db7543a88a61656c61ea4be
|
[] |
no_license
|
TariqueNasrullah/Cheat
|
619fac167ca944a08407675563a09c2079da7081
|
0234d430bed06fd888b28e29a615825dfa7f0d2b
|
refs/heads/master
| 2021-04-29T02:21:33.791622
| 2020-03-30T14:44:57
| 2020-03-30T14:44:57
| 78,027,045
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 347
|
cpp
|
Bigmod.cpp
|
#include <bits/stdc++.h>
using namespace std;
#define lli long long
lli m;
lli big_mod(lli n, lli p)
{
if(p == 0) return 1;
if(p%2 == 0)
{
lli ret = big_mod(n, p/2);
return ((ret%m) * (ret%m))%m;
}
else return ((n%m) * (big_mod(n, p-1)%m))%m;
}
int main()
{
m = 4;
cout << big_mod(34, 1) << endl;;
}
|
817a23e90095f7211bbcfb6ed1b047ccebaa2fda
|
3782e25b6db35d82d63bb81e398deab85ef2236e
|
/Fw/Port/InputSerializePort.cpp
|
6201fa3857c1ccf4a58c4194a429c45a18ed0c91
|
[
"Apache-2.0"
] |
permissive
|
nasa/fprime
|
e0c8d45dfc0ff08b5ef6c42a31f47430ba92c956
|
a56426adbb888ce4f5a8c6a2be3071a25b11da16
|
refs/heads/devel
| 2023-09-03T15:10:33.578646
| 2023-08-29T15:39:59
| 2023-08-29T15:39:59
| 95,114,723
| 10,071
| 1,426
|
Apache-2.0
| 2023-09-08T14:31:00
| 2017-06-22T12:45:27
|
C++
|
UTF-8
|
C++
| false
| false
| 1,645
|
cpp
|
InputSerializePort.cpp
|
#include <Fw/Port/InputSerializePort.hpp>
#include <Fw/Types/Assert.hpp>
#include <cstdio>
#if FW_PORT_SERIALIZATION == 1
namespace Fw {
// SerializePort has no call interface. It is to pass through serialized data
InputSerializePort::InputSerializePort() : InputPortBase(), m_func(nullptr) {
}
InputSerializePort::~InputSerializePort() {
}
void InputSerializePort::init() {
InputPortBase::init();
}
SerializeStatus InputSerializePort::invokeSerial(SerializeBufferBase &buffer) {
FW_ASSERT(this->m_comp);
FW_ASSERT(this->m_func);
this->m_func(this->m_comp,this->m_portNum,buffer);
// The normal input ports perform deserialize() on the passed buffer,
// which is what this status is based on. This is not the case for the
// InputSerializePort, so just return an okay status
return FW_SERIALIZE_OK;
}
void InputSerializePort::addCallComp(Fw::PassiveComponentBase* callComp, CompFuncPtr funcPtr) {
FW_ASSERT(callComp);
FW_ASSERT(funcPtr);
this->m_comp = callComp;
this->m_func = funcPtr;
}
#if FW_OBJECT_TO_STRING == 1
void InputSerializePort::toString(char* buffer, NATIVE_INT_TYPE size) {
#if FW_OBJECT_NAMES == 1
FW_ASSERT(size > 0);
if (snprintf(buffer, size, "Input Serial Port: %s %s->(%s)", this->m_objName, this->isConnected() ? "C" : "NC",
this->isConnected() ? this->m_connObj->getObjName() : "None") < 0) {
buffer[0] = 0;
}
#else
(void)snprintf(buffer,size,"%s","InputSerializePort");
#endif
}
#endif
}
#endif
|
6ee59cb9a0319e53b16721eb8d78c11a634e00c0
|
93974aab719a519bd6d4a22f8647b5a0f7ea6472
|
/QtChat/QtEncChatClientWindows/EncMessengerConnectionDialog.cpp
|
941b08dbfd9ce0e8735def2b653249663c17b2b9
|
[] |
no_license
|
Exordio/qt_chat
|
aa23164eda9b9b2043c71f7490598c5b6b1c097c
|
8f2d8ba215052405bf229ab571608c59a1f13c57
|
refs/heads/master
| 2020-11-24T19:14:27.108090
| 2019-12-16T05:13:58
| 2019-12-16T05:13:58
| 228,307,273
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 645
|
cpp
|
EncMessengerConnectionDialog.cpp
|
#include "EncMessengerConnectionDialog.h"
#include "ui_EncMessengerConnectionDialog.h"
namespace SandZero {
EncMessengerConnectionDialog::EncMessengerConnectionDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::EncMessengerConnectionDialog)
{
ui->setupUi(this);
}
EncMessengerConnectionDialog::~EncMessengerConnectionDialog()
{
delete ui;
}
void EncMessengerConnectionDialog::on_Okbut_clicked()
{
mHostname = ui->Hostname->text();
mPort = ui->port->value();
accept();
}
void EncMessengerConnectionDialog::on_Cancelbut_clicked()
{
reject();
}
} // end namespace SandZero
|
d660151556d6d48bdb90ac49ae290b5832085810
|
7e1cf39ff92a577249fb9a28c9ef2a63af82a574
|
/project4/IntelWeb.cpp
|
a5562573711b177fdfe4e0b56b37ff6686f71137
|
[] |
no_license
|
lboymoushakian/project4
|
29f75886c800e91b7feb3f97c322e98d12f7149b
|
b2204d1e916f9642f99682022ce8c58b07adda79
|
refs/heads/master
| 2021-01-10T09:16:26.862813
| 2016-03-11T01:23:53
| 2016-03-11T01:23:53
| 53,474,358
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,992
|
cpp
|
IntelWeb.cpp
|
#include "IntelWeb.h"
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
IntelWeb::IntelWeb()
{}
IntelWeb::~IntelWeb()
{
m_map_f.close();
m_map_r.close();
}
bool IntelWeb::createNew(const std::string& filePrefix, unsigned int maxDataItems)
{
m_map_f.close();
m_map_r.close();
std::string name1 = filePrefix + ".forward";
std::string name2 = filePrefix + ".reverse";
bool success1 =m_map_f.createNew(name1, 2 * maxDataItems);
bool success2 = m_map_r.createNew(name2, 2 * maxDataItems);
if(success1 && success2)
return true;
return false;
}
void IntelWeb::close()
{
m_map_f.close();
m_map_r.close();
}
bool IntelWeb::openExisting(const std::string& filePrefix)
{
m_map_f.close();
m_map_r.close();
bool success1= false; bool success2 = false;
if( m_map_f.openExisting(filePrefix + ".forward"))
success1 = true;
if(m_map_r.openExisting(filePrefix + ".reverse"))
success2 = true;
if(success1 && success2)
return true;
else
{
m_map_f.close();
m_map_r.close();
return false;
}
}
bool IntelWeb::ingest(const std::string& telemetryFile)
{
ifstream inf(telemetryFile);
if(!inf)
cout <<"fail to open file!!!!!\n";
string line;
while(getline(inf, line))
{
istringstream iss(line);
string context;
string key;
string value;
if(!(iss >> context >> key >> value))
cout << "not format right!!!!\n";
bool success1 = m_map_f.insert(key, value, context);
bool success2 = m_map_r.insert(value, key, context);
if(success1 && success2)
cout << "success!!!\n";
}
return true;
}
unsigned int IntelWeb::crawl(const std::vector<std::string>& indicators,
unsigned int minPrevalenceToBeGood,
std::vector<std::string>& badEntitiesFound,
std::vector<InteractionTuple>& badInteractions
)
{
//go through the list of indicators
for(auto i = indicators.begin(); i != indicators.end(); i++)
{
//search up each indicator in m_map_f
DiskMultiMap::Iterator z = m_map_f.search(*i);
//if you find the indicator, insert it into bad_entities
if(z.isValid())
bad_entities.insert((*z).key);
while(z.isValid())
{
string value;
value = (*z).value;
//calculate prevalence by searching through each diskmultimap and counting how many times the indicator shows up as a key
int prevalence = 0;
DiskMultiMap::Iterator x = m_map_f.search(*i);
while(x.isValid())
{
prevalence++;
++x;
}
x = m_map_r.search(*i);
while(x.isValid())
{
prevalence++;
++x;
}
//if prevalence is too low, insert the thing associated with the indicator into bad_entities
if(prevalence < minPrevalenceToBeGood)
{
bad_entities.insert(value);
InteractionTuple h;
h.context = (*z).context;
h.to = value;
h.from = *i;
interactions.insert(h);
}
++z;
}
//do the same thing with m_map_r to find associations that go the other way
DiskMultiMap::Iterator y = m_map_r.search(*i);
if(y.isValid())
bad_entities.insert((*y).key);
while(y.isValid())
{
string value;
value = (*y).value;
//calculate prevalence by searching through each diskmultimap and counting how many times the indicator shows up as a key
int prevalence = 0;
DiskMultiMap::Iterator x = m_map_r.search(*i);
while(x.isValid())
{
prevalence++;
++x;
}
x = m_map_r.search(*i);
while(x.isValid())
{
prevalence++;
++x;
}
if(prevalence < minPrevalenceToBeGood)
{
bad_entities.insert(value);
InteractionTuple h;
h.context = (*z).context;
h.to = *i;
h.from = value;
interactions.insert(h);
}
++y;
}
}
//we've gone through the list of indicators and found everything associated to them
//now we want to go through the bad_entities list to find more
bool anyFound = true;
while(anyFound == true)
{
anyFound = false;
for(auto p = bad_entities.begin(); p != bad_entities.end(); p++)
{
//first, if *p is an indicator, skip all this bc its already done
bool inIndicators = false;
for(auto u = indicators.begin(); u != indicators.end(); u++)
{
if((*u) == (*p))
inIndicators = true;
}
if(inIndicators == true)
continue;
//check for associations for each item in bad_entities
//search up each indicator in m_map_f
DiskMultiMap::Iterator z = m_map_f.search(*p);
//if you find the indicator, insert it into bad_entities
if(z.isValid())
bad_entities.insert((*z).key);
while(z.isValid())
{
string value;
value = (*z).value;
//calculate prevalence by searching through each diskmultimap and counting how many times the indicator shows up as a key
int prevalence = 0;
DiskMultiMap::Iterator x = m_map_f.search(*p);
while(x.isValid())
{
prevalence++;
++x;
}
x = m_map_r.search(*p);
while(x.isValid())
{
prevalence++;
++x;
}
//if prevalence is too low, insert the thing associated with the indicator into bad_entities
if(prevalence < minPrevalenceToBeGood)
{
auto pair = bad_entities.insert(value);
if(pair.second == true)
anyFound = true;
InteractionTuple h;
h.context = (*z).context;
h.to = value;
h.from = *p;
interactions.insert(h);
}
++z;
}
//do the same thing with m_map_r to find associations that go the other way
DiskMultiMap::Iterator y = m_map_r.search(*p);
if(y.isValid())
bad_entities.insert((*y).key);
while(y.isValid())
{
string value;
value = (*y).value;
//calculate prevalence by searching through each diskmultimap and counting how many times the indicator shows up as a key
int prevalence = 0;
DiskMultiMap::Iterator x = m_map_r.search(*p);
while(x.isValid())
{
prevalence++;
++x;
}
x = m_map_r.search(*p);
while(x.isValid())
{
prevalence++;
++x;
}
if(prevalence < minPrevalenceToBeGood)
{
auto pair = bad_entities.insert(value);
if(pair.second == true)
anyFound = true;
InteractionTuple h;
h.context = (*z).context;
h.to = *p;
h.from = value;
interactions.insert(h);
}
++y;
}
}
}
//transfer everything from bad_entities to badEntitiesFound
//also transfer from interactions to badInteractions
for(auto i = bad_entities.begin(); i != bad_entities.end(); i++)
{
badEntitiesFound.push_back(*i);
}
for(auto i = interactions.begin(); i != interactions.end(); i++)
badInteractions.push_back(*i);
return static_cast<unsigned int>(badEntitiesFound.size());
}
bool IntelWeb::purge(const std::string& entity)
{
bool found = false;
DiskMultiMap::Iterator i = m_map_f.search(entity);
if(i.isValid())
found = true;
while (i.isValid())
{
string key = (*i).key;
string value = (*i).value;
string context = (*i).context;
m_map_f.erase(key, value, context);
++i;
}
DiskMultiMap::Iterator j = m_map_r.search(entity);
if(j.isValid())
found = true;
while (j.isValid())
{
string key = (*j).key;
string value = (*j).value;
string context = (*j).context;
m_map_f.erase(key, value, context);
++j;
}
return found;
}
bool operator<(const InteractionTuple one, const InteractionTuple two)
{
string to1 = one.to;
string from1 = one.from;
string context1 = one.context;
string to2 = two.to;
string from2 = two.from;
string context2 = two.context;
if(to1 < to2)
return true;
else if(to1 == to2 && from1 < from2)
return true;
else if (to1 == to2 && from1 == from2 && context1 < context2)
return true;
return false;
}
|
5594c800ef1cb1d124a86ece6feaf03296df23e4
|
2cdf872caafaf0d8acefdba40a7663f122910f9a
|
/libraries/Mitov/Mitov_SMTP_Client.h
|
7f18605b049b53fe2ffc1a5ab289c95688eb2b27
|
[
"MIT"
] |
permissive
|
AlexRogalskiy/Duino
|
39557285df4871b260740250e37cbc62897e32e6
|
bef05838fe73970dea856779957fd3a3e406f295
|
refs/heads/master
| 2021-06-12T04:26:12.202107
| 2019-11-12T10:19:33
| 2019-11-12T10:19:33
| 164,288,034
| 0
| 0
|
MIT
| 2021-04-17T19:30:16
| 2019-01-06T08:12:52
|
C++
|
UTF-8
|
C++
| false
| false
| 21,962
|
h
|
Mitov_SMTP_Client.h
|
////////////////////////////////////////////////////////////////////////////////
// //
// This software is supplied under the terms of a license agreement or //
// nondisclosure agreement with Mitov Software and may not be copied //
// or disclosed except in accordance with the terms of that agreement. //
// Copyright(c) 2002-2018 Mitov Software. All Rights Reserved. //
// //
////////////////////////////////////////////////////////////////////////////////
#ifndef _MITOV_SMTP_CLIENT_h
#define _MITOV_SMTP_CLIENT_h
#include <Mitov.h>
#ifdef __TEST_FOR_DEBUG_PRINTS__
#define Serial UNGUARDED DEBUG PRINT!!!
#endif
//#define __SMTP__DEBUG__
namespace Mitov
{
class SMTPClient;
class SMTPEMailAccountBasic;
class SMTPEMail;
//---------------------------------------------------------------------------
namespace SMTPEMail_
{
struct TEMailTransaction
{
public:
uint8_t FRefCount = 0;
public:
SMTPEMailAccountBasic *SenderAccount;
SMTPEMail *Mail;
public:
void Acquire()
{
++FRefCount;
}
void Release()
{
--FRefCount;
if( ! FRefCount )
delete this;
}
public:
TEMailTransaction( SMTPEMail *AMail ) :
Mail( AMail )
{
}
};
}
//---------------------------------------------------------------------------
class SMTPEMailAccountBasic
{
public:
Mitov::String ClientID;
Mitov::String UserName;
Mitov::String Password;
uint16_t Timeout = 5000;
};
//---------------------------------------------------------------------------
template<typename T_OWNER, T_OWNER &C_OWNER> class SMTPEMailAccount : public SMTPEMailAccountBasic
{
public:
void MessageInputPin_o_Receive( void *_Data )
{
SMTPEMail_::TEMailTransaction *ATransaction = (SMTPEMail_::TEMailTransaction *)_Data;
// ATransaction->Acquire();
ATransaction->SenderAccount = this;
C_OWNER.ProcessTransaction( ATransaction );
}
};
//---------------------------------------------------------------------------
class SMTPEMailBasicFunction
{
public:
bool Disconnect : 1;
uint8_t RetryCount : 4;
uint32_t Timeout;
uint32_t Delay;
SMTPEMail_::TEMailTransaction *Transaction;
public:
virtual bool TryProcessRequestedInput( Mitov::String ALine, bool &AResponseCompleted, bool &ASuccess ) { return false; }
virtual void TimedOut() {}
public:
SMTPEMailBasicFunction( SMTPEMail_::TEMailTransaction *ATransaction, bool ADisconnect, uint8_t ARetryCount, uint32_t ATimeout, uint32_t ADelay ) :
Disconnect( ADisconnect ),
RetryCount( ARetryCount ),
Timeout( ATimeout ),
Delay( ADelay ),
Transaction( ATransaction )
{
}
virtual ~SMTPEMailBasicFunction() {}
};
//---------------------------------------------------------------------------
/*
class SMTPEMailDisconnectFunction : public SMTPEMailBasicFunction
{
typedef SMTPEMailBasicFunction inherited;
public:
SMTPEMailDisconnectFunction() :
inherited( true, 0, 2000, 0 )
{
}
}
*/
//---------------------------------------------------------------------------
class SMTPEMailConnectFunction : public SMTPEMailBasicFunction
{
typedef SMTPEMailBasicFunction inherited;
protected:
SMTPClient *FOwner;
public:
virtual bool TryProcessRequestedInput( Mitov::String ALine, bool &AResponseCompleted, bool &ASuccess ) override
{
if( ALine.startsWith( "220 " ) )
{
#ifdef __SMTP__DEBUG__
Serial.println( "STARTED" );
#endif
AResponseCompleted = true;
ASuccess = true;
return true;
}
return false;
}
virtual void TimedOut() override;
public:
SMTPEMailConnectFunction( SMTPClient *AOwner, SMTPEMail_::TEMailTransaction *ATransaction ) :
inherited( ATransaction, false, 5, 2000, 0 ),
FOwner( AOwner )
{
}
};
//---------------------------------------------------------------------------
class SMTPEMailSendWaitResponse : public SMTPEMailBasicFunction
{
typedef SMTPEMailBasicFunction inherited;
protected:
int FResponse;
public:
virtual bool TryProcessRequestedInput( Mitov::String ALine, bool &AResponseCompleted, bool &ASuccess ) override
{
// if( ALine.startsWith( "250 " ) )
if( ALine.startsWith( Mitov::String( FResponse ) + " " ) )
{
#ifdef __SMTP__DEBUG__
Serial.print( "RES: " );
Serial.println( FResponse );
#endif
AResponseCompleted = true;
ASuccess = true;
return true;
}
return false;
}
public:
SMTPEMailSendWaitResponse( SMTPEMail_::TEMailTransaction *ATransaction, int AResponse ) :
inherited( ATransaction, false, 5, 2000, 0 ),
FResponse( AResponse )
{
}
SMTPEMailSendWaitResponse( SMTPEMail_::TEMailTransaction *ATransaction, int AResponse, int ACountReply ) :
inherited( ATransaction, false, ACountReply, 2000, 0 ),
FResponse( AResponse )
{
}
};
//---------------------------------------------------------------------------
class SMTPEMailSendDataResponse : public SMTPEMailBasicFunction
{
typedef SMTPEMailBasicFunction inherited;
protected:
SMTPClient *FOwner;
public:
virtual bool TryProcessRequestedInput( Mitov::String ALine, bool &AResponseCompleted, bool &ASuccess ) override;
public:
SMTPEMailSendDataResponse( SMTPClient *AOwner, SMTPEMail_::TEMailTransaction *ATransaction ) :
inherited( ATransaction, false, 5, 2000, 0 ),
FOwner( AOwner )
{
Transaction->Acquire();
}
virtual ~SMTPEMailSendDataResponse()
{
Transaction->Release();
}
};
//---------------------------------------------------------------------------
class TArduinoSMTPEMailAddress
{
public:
Mitov::String Name;
Mitov::String Address;
public:
Mitov::String GetText()
{
if( Name == "" )
return "<" + Address + ">";
return Name + " <" + Address + ">";
}
};
//---------------------------------------------------------------------------
class SMTPEMailMessageBasic
{
public:
virtual void SendLines( SMTPClient *AClient ) = 0;
};
//---------------------------------------------------------------------------
class SMTPEMailMessageText : public SMTPEMailMessageBasic
{
public:
Mitov::String Text;
public:
virtual void SendLines( SMTPClient *AClient ) override;
};
//---------------------------------------------------------------------------
class SMTPEMailMessageHTML : public SMTPEMailMessageBasic
{
public:
Mitov::String Text;
public:
virtual void SendLines( SMTPClient *AClient ) override;
};
//---------------------------------------------------------------------------
class SMTPEMailMessageTextTHML : public SMTPEMailMessageBasic
{
public:
Mitov::String Boundary;
Mitov::String PlainText;
Mitov::String HTMLText;
public:
virtual void SendLines( SMTPClient *AClient ) override;
};
//---------------------------------------------------------------------------
class SMTPEMail
{
public:
OpenWire::SourcePin MessageOutputPin;
public:
TArduinoSMTPEMailAddress From;
Mitov::SimpleList<TArduinoSMTPEMailAddress *> To;
Mitov::SimpleList<TArduinoSMTPEMailAddress *> CC;
Mitov::SimpleList<TArduinoSMTPEMailAddress *> BCC;
Mitov::String Subject;
SMTPEMailMessageBasic *Message;
public:
void SendLines( SMTPClient *AClient );
public:
void ClockInputPin_o_Receive( void *_Data )
{
if( ! To.size() )
return;
SMTPEMail_::TEMailTransaction *ATransaction = new SMTPEMail_::TEMailTransaction( this );
ATransaction->Acquire();
MessageOutputPin.Notify( ATransaction );
ATransaction->Release();
}
};
//---------------------------------------------------------------------------
class SMTPClient
{
public:
OpenWire::SourcePin OutputPin;
OpenWire::SourcePin ConnectOutputPin;
protected:
struct TQueryElement
{
public:
Mitov::String Command;
SMTPEMailBasicFunction *ResponseElement;
public:
TQueryElement() :
ResponseElement( nullptr )
{
}
TQueryElement( Mitov::String ACommand, SMTPEMailBasicFunction *AResponseElement ) :
Command( ACommand ),
ResponseElement( AResponseElement )
{
}
};
protected:
char FBuffer[ 256 ];
uint8_t FIndex = 0;
protected:
Mitov::SimpleList<TQueryElement *> FQueryQueue;
TQueryElement *FCurrentElement = nullptr;
uint32_t FDelay = 0;
unsigned long FCurrentMillis = 0;
protected:
SMTPEMailAccountBasic *FActiveAccount = nullptr;
public:
void SendTextLine( Mitov::String AText )
{
#ifdef __SMTP__DEBUG__
Serial.print( "SEND: " );
Serial.println( AText );
#endif
AText += "\r\n";
Mitov::TDataBlock ABlock( AText.length(), AText.c_str() );
OutputPin.Notify( &ABlock );
FCurrentMillis = millis();
}
void SendTextLineNoDot( Mitov::String AText )
{
if( AText.startsWith( "." ))
AText = "." + AText;
SendTextLine( AText );
}
void SendLinesNoDot( Mitov::String ALines )
{
int AStart = 0;
for( int i = 0; i < ALines.length(); ++i )
{
if( ALines[ i ] == '\n' )
{
if( AStart != i )
{
Mitov::String ALine = ALines.substring( AStart, i );
// Serial.println( i - AStart );
SendTextLineNoDot( ALine );
}
AStart = i + 1;
}
if( ALines[ i ] == '\r' )
{
Mitov::String ALine = ALines.substring( AStart, i );
// Serial.println( i - AStart );
SendTextLineNoDot( ALine );
AStart = i + 1;
}
else if ( i == ALines.length() - 1 )
{
Mitov::String ALine = ALines.substring( AStart );
SendTextLineNoDot( ALine );
}
}
}
inline void Disconnect()
{
ConnectOutputPin.SendValue( false );
}
void QuitConnection()
{
TrySendQuery( new TQueryElement( "QUIT", new SMTPEMailSendWaitResponse( nullptr, 221 ) ));
TrySendQuery( new TQueryElement( "", new SMTPEMailBasicFunction( nullptr, true, 0, 0, 0 )));
FActiveAccount = nullptr;
}
void ProcessTransaction( SMTPEMail_::TEMailTransaction *ATransaction )
{
if( FActiveAccount != ATransaction->SenderAccount )
{
if( FActiveAccount )
QuitConnection();
TrySendQuery( new TQueryElement( "", new SMTPEMailConnectFunction( this, ATransaction )));
// ConnectOutputPin.SendValue( true );
TrySendQuery( new TQueryElement( "EHLO " + ATransaction->SenderAccount->ClientID, new SMTPEMailSendWaitResponse( ATransaction, 250 )));
if( ATransaction->SenderAccount->UserName != "" )
{
TrySendQuery( new TQueryElement( "AUTH LOGIN", new SMTPEMailSendWaitResponse( ATransaction, 334 )));
TrySendQuery( new TQueryElement( Func::Base64Encode( ATransaction->SenderAccount->UserName ), new SMTPEMailSendWaitResponse( ATransaction, 334 )));
TrySendQuery( new TQueryElement( Func::Base64Encode( ATransaction->SenderAccount->Password ), new SMTPEMailSendWaitResponse( ATransaction, 235 )));
TrySendQuery( new TQueryElement( "MAIL FROM: <" + ATransaction->Mail->From.Address + ">", new SMTPEMailSendWaitResponse( ATransaction, 250 )));
}
}
for( int i = 0; i < ATransaction->Mail->To.size(); ++i )
TrySendQuery( new TQueryElement( "RCPT TO: <" + ATransaction->Mail->To[ i ]->Address + ">", new SMTPEMailSendWaitResponse( ATransaction, 250 )));
for( int i = 0; i < ATransaction->Mail->CC.size(); ++i )
TrySendQuery( new TQueryElement( "RCPT TO: <" + ATransaction->Mail->CC[ i ]->Address + ">", new SMTPEMailSendWaitResponse( ATransaction, 250 )));
for( int i = 0; i < ATransaction->Mail->BCC.size(); ++i )
TrySendQuery( new TQueryElement( "RCPT TO: <" + ATransaction->Mail->BCC[ i ]->Address + ">", new SMTPEMailSendWaitResponse( ATransaction, 250 )));
TrySendQuery( new TQueryElement( "DATA", new SMTPEMailSendDataResponse( this, ATransaction )));
FActiveAccount = ATransaction->SenderAccount;
// TrySendQuery( new SMTPEMailSendMessage
}
public:
void SendData( SMTPEMail_::TEMailTransaction *ATransaction )
{
ATransaction->Mail->SendLines( this );
// Send .
FQueryQueue.push_front( new TQueryElement( ".", new SMTPEMailSendWaitResponse( ATransaction, 250, 1 )) );
}
protected:
void SendQuery( TQueryElement *AElement )
{
#ifdef __SMTP__DEBUG__
Serial.print( "QUERY : \"" ); Serial.print( AElement->Command ); Serial.println( "\"" );
#endif
if( AElement->Command == "" )
{
if( AElement->ResponseElement->Disconnect )
{
Disconnect();
delete AElement;
}
else
{
FCurrentMillis = millis();
ConnectOutputPin.SendValue( true );
FCurrentElement = AElement;
}
return;
}
FCurrentMillis = millis();
// FStream.println( AQuery );
// FStream.write( AElement->Command, AElement->Command.size() );
SendTextLine( AElement->Command );
FCurrentElement = AElement;
}
void ProcessNextCommand()
{
if( FCurrentElement )
{
FDelay = FCurrentElement->ResponseElement->Delay;
#ifdef __SMTP__DEBUG__
Serial.print( "DELAY: " ); Serial.println( FDelay );
#endif
delete FCurrentElement;
FCurrentElement = nullptr;
}
if( FDelay )
return;
#ifdef __SMTP__DEBUG__
Serial.println( "ProcessNextCommand" );
#endif
// Serial.print( "RESP_QUEUE: " ); Serial.println( FResponseHandlersQueue.size() );
if( FQueryQueue.size() )
{
// Serial.print( "SEND_QUERY: " ); Serial.println( FQueryQueue.size() );
TQueryElement *AElement = FQueryQueue[ 0 ];
// Serial.print( "ESTRACT_QUERY: " ); Serial.println( ACommand );
FQueryQueue.pop_front();
#ifdef __SMTP__DEBUG__
Serial.println( "QUEUE>>" );
for( int i = 0; i < FQueryQueue.size(); ++i )
Serial.println( FQueryQueue[ i ]->Command );
Serial.println( "<<QUEUE" );
#endif
SendQuery( AElement );
// Serial.print( "SEND_QUERY: " ); Serial.println( FQueryQueue.size() );
}
}
public:
void TrySendQuery( TQueryElement *AElement )
{
// if( ( PowerOn || ( AQuery == "AT" ) ) && ( FResponseHandlersQueue.size() == 0 ) && ( !FInPowerSwitch ))
// if( FResponseHandlersQueue.size() == 0 )
if( ! FCurrentElement )
SendQuery( AElement );
else
{
// while( FQueryQueue.size() > 10 )
// SystemLoopBegin( micros());
#ifdef __SMTP__DEBUG__
Serial.print( "ADD TO QUERY : \"" ); Serial.print( AElement->Command ); Serial.println( "\"" );
#endif
FQueryQueue.push_back( AElement );
#ifdef __SMTP__DEBUG__
Serial.println( "QUEUE>>" );
for( int i = 0; i < FQueryQueue.size(); ++i )
Serial.println( FQueryQueue[ i ]->Command );
Serial.println( "<<QUEUE" );
#endif
}
}
protected:
void DeleteTransactionElements( SMTPEMail_::TEMailTransaction *ATransaction )
{
if( ! ATransaction )
return;
#ifdef __SMTP__DEBUG__
Serial.print( "DELETE TRANSACTION: " );
Serial.print( FQueryQueue.size() );
#endif
for( int i = FQueryQueue.size(); i--; )
if( FQueryQueue[ i ]->ResponseElement->Transaction == ATransaction )
FQueryQueue.Delete( i );
#ifdef __SMTP__DEBUG__
Serial.print( " -> " );
Serial.println( FQueryQueue.size() );
#endif
}
public:
void ConnectedInputPin_o_Receive( void *_Data )
{
if( ((bool *)_Data ))
return;
FActiveAccount = nullptr;
}
void InputPin_o_Receive( void *_Data )
{
Mitov::TDataBlock ABlock = *(Mitov::TDataBlock *)_Data;
if( ! ABlock.Size )
return;
for( int i = 0; i < ABlock.Size; ++i )
{
char AChar = ABlock.Data[ i ];
if( AChar == 13 )
return;
if( AChar != 10 )
{
FBuffer[ FIndex ++ ] = AChar;
if( FIndex < 255 )
return;
}
FBuffer[ FIndex ] = '\0';
FIndex = 0;
Mitov::String AString = FBuffer;
#ifdef __SMTP__DEBUG__
Serial.println( AString );
#endif
/*
if( AString.startsWith( "220 " ) )
{
Serial.println( "STARTED" );
}
*/
bool AResponseCompleted = false;
if( FCurrentElement )
{
bool ASuccess = false;
if( FCurrentElement->ResponseElement->TryProcessRequestedInput( AString, AResponseCompleted, ASuccess ))
{
if( AResponseCompleted )
{
if( ( ! ASuccess ) && FCurrentElement->Command && FCurrentElement->ResponseElement->RetryCount )
{
#ifdef __SMTP__DEBUG__
Serial.println( "RETRY2" );
Serial.println( FCurrentElement->Command );
#endif
-- FCurrentElement->ResponseElement->RetryCount;
SendQuery( FCurrentElement );
}
else
{
if( ! ASuccess )
DeleteTransactionElements( FCurrentElement->ResponseElement->Transaction );
#ifdef __SMTP__DEBUG__
Serial.println( "Queue Delete 2" );
Serial.print( "DELETING: " ); Serial.println( FCurrentElement->Command );
// Serial.print( "RESP_QUEUE: " ); Serial.println( FResponseHandlersQueue.size() );
#endif
// Serial.println( "ProcessNextCommand 2" );
ProcessNextCommand();
}
}
}
}
}
}
public:
inline void SystemLoopBegin( unsigned long currentMicros )
{
if( FCurrentElement )
{
// Serial.println( "test2" );
unsigned long AMillis = millis();
if( ( AMillis - FCurrentMillis ) > FCurrentElement->ResponseElement->Timeout )
{
#ifdef __SMTP__DEBUG__
Serial.print( "TIMEOUT: " ); Serial.println( FCurrentElement->Command );
Serial.println( FCurrentElement->ResponseElement->Timeout );
Serial.println( AMillis );
Serial.println( FCurrentMillis );
#endif
// FLockRequestedInputIndex = 0;
if( FCurrentElement->Command && FCurrentElement->ResponseElement->RetryCount )
{
#ifdef __SMTP__DEBUG__
Serial.println( "RETRY3" );
Serial.println( FCurrentElement->Command );
#endif
-- FCurrentElement->ResponseElement->RetryCount;
SendQuery( FCurrentElement );
}
else
{
FCurrentElement->ResponseElement->TimedOut();
DeleteTransactionElements( FCurrentElement->ResponseElement->Transaction );
// Serial.println( "ProcessNextCommand 3" );
ProcessNextCommand();
}
}
}
else if( FActiveAccount )
{
// Serial.println( "test1" );
unsigned long AMillis = millis();
if( ( AMillis - FCurrentMillis ) > FActiveAccount->Timeout )
{
#ifdef __SMTP__DEBUG__
Serial.println( "CLOSING!!!" );
#endif
QuitConnection();
}
}
if( FDelay )
{
unsigned long AMillis = millis();
if( ( AMillis - FCurrentMillis ) > FDelay )
{
#ifdef __SMTP__DEBUG__
Serial.println( "DELAY COMPLETED" );
#endif
FDelay = 0;
ProcessNextCommand();
}
}
}
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void SMTPEMailConnectFunction::TimedOut()
{
FOwner->Disconnect();
}
//---------------------------------------------------------------------------
bool SMTPEMailSendDataResponse::TryProcessRequestedInput( Mitov::String ALine, bool &AResponseCompleted, bool &ASuccess )
{
// if( ALine.startsWith( "250 " ) )
if( ALine.startsWith( "354 " ) )
{
#ifdef __SMTP__DEBUG__
Serial.println( "DATA!" );
#endif
FOwner->SendData( Transaction );
AResponseCompleted = true;
ASuccess = true;
return true;
}
return false;
}
//---------------------------------------------------------------------------
void SMTPEMail::SendLines( SMTPClient *AClient )
{
AClient->SendTextLine( "From: " + From.GetText() );
{ // AToLine Scope
Mitov::String AToLine;
for( int i = 0; i < To.size(); ++i )
{
if( i )
AToLine += ", ";
AToLine += To[ i ]->GetText();
}
AClient->SendTextLine( "To: " + AToLine );
if( CC.size() )
{
AToLine = "";
for( int i = 0; i < CC.size(); ++i )
{
if( i )
AToLine += ", ";
AToLine += CC[ i ]->GetText();
}
AClient->SendTextLine( "CC: " + AToLine );
}
if( CC.size() )
{
AToLine = "";
for( int i = 0; i < BCC.size(); ++i )
{
if( i )
AToLine += ", ";
AToLine += BCC[ i ]->GetText();
}
AClient->SendTextLine( "BCC: " + AToLine );
}
}
AClient->SendTextLine( "Subject: " + Subject );
AClient->SendTextLine( "Mime-Version: 1.0" );
Message->SendLines( AClient );
}
//---------------------------------------------------------------------------
void SMTPEMailMessageText::SendLines( SMTPClient *AClient )
{
AClient->SendTextLine( "Content-Type: text/plain; charset=\"UTF-8\"" );
AClient->SendTextLine( "Content-Transfer-Encoding: 7bit" );
AClient->SendTextLine( "" );
AClient->SendLinesNoDot( Text );
}
//---------------------------------------------------------------------------
void SMTPEMailMessageHTML::SendLines( SMTPClient *AClient )
{
AClient->SendTextLine( "Content-Type: text/html; charset=\"UTF-8\"" );
AClient->SendTextLine( "Content-Transfer-Encoding: 7bit" );
AClient->SendTextLine( "" );
AClient->SendLinesNoDot( Text );
}
//---------------------------------------------------------------------------
void SMTPEMailMessageTextTHML::SendLines( SMTPClient *AClient )
{
AClient->SendTextLine( "Content-Type: multipart/alternative; boundary=" + Boundary );
AClient->SendTextLine( "\r\n--" + Boundary );
AClient->SendTextLine( "Content-Type: text/plain; charset=\"UTF-8\"" );
AClient->SendTextLine( "Content-Transfer-Encoding: 7bit" );
AClient->SendTextLine( "" );
AClient->SendLinesNoDot( PlainText );
AClient->SendTextLine( "--" + Boundary );
AClient->SendTextLine( "Content-Type: text/html; charset=\"UTF-8\"" );
AClient->SendTextLine( "Content-Transfer-Encoding: 7bit" );
AClient->SendTextLine( "" );
AClient->SendLinesNoDot( HTMLText );
AClient->SendTextLine( "--" + Boundary + "--" );
}
//---------------------------------------------------------------------------
}
#ifdef __TEST_FOR_DEBUG_PRINTS__
#undef Serial
#endif
#endif
|
90e2895d1b41cf03036c0edeb752addd5ef7d1ea
|
c033641fa7223daa3ec4d7f80e12e0b6ceb1927a
|
/ReplaySaver.h
|
004c5ddaa6d33a7b16235199666b072f25241cd3
|
[] |
no_license
|
PyrokinesisStudio/STG-Engine
|
c403ea3a343dd96f2df7ac66ea54921707fdadc4
|
8d83f05c66c1b3854268ee8cb4590dca84188cc1
|
refs/heads/master
| 2020-03-18T11:29:52.273691
| 2012-11-04T09:57:21
| 2012-11-04T09:57:21
| 134,675,358
| 1
| 0
| null | 2018-05-24T07:05:54
| 2018-05-24T07:05:54
| null |
UTF-8
|
C++
| false
| false
| 476
|
h
|
ReplaySaver.h
|
#ifndef INCLUDED_RTG_REPLAYSAVER_H
#define INCLUDED_RTG_REPLAYSAVER_H
#include "ReplayLoader.h"
namespace RTG
{
class ReplaySaver
{
private:
ReplayEntry m_Entry;
int m_CurFrame;
char m_Name[ 16 ];
int m_Score;
int m_Progress;
::time_t m_Date;
public:
ReplaySaver();
~ReplaySaver();
void Save( const char* pFileName,
const char* pName,
int score,
int progress);
void Add( char* pEntry );
void Reset();
};
}
#endif
|
16e664474670b474e6b639f9774d6a8b4030ae6a
|
645c6766afe021387b0d391e20e77514e4222b13
|
/12015.cpp
|
837a3df0d4a1b8853c03ac0e372a047084ad2fc7
|
[] |
no_license
|
krofna/uva
|
2d48218c26e59ccf56dabc1ec75fa1acb2ac75ea
|
fbc956d98c14b55a62b606747acdf467d304b142
|
refs/heads/master
| 2020-06-22T09:31:03.786648
| 2019-03-11T22:10:22
| 2019-03-11T22:10:22
| 74,597,336
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 475
|
cpp
|
12015.cpp
|
#include <iostream>
using namespace std;
int main()
{
int t, max;
int R[10];
string W[10];
cin >> t;
for (int i = 0; i < t; ++i)
{
max = 0;
for (int j = 0; j < 10; ++j)
{
cin >> W[j] >> R[j];
if (R[j] > max)
max = R[j];
}
cout << "Case #" << i + 1 << ":\n";
for (int j = 0; j < 10; ++j)
if (R[j] == max)
cout << W[j] << '\n';
}
}
|
395ad22bf028099cca4edc2ca8947cfdabf8c47c
|
2ba7ea1556d8b17023c89afb316a79a113aa3205
|
/Ceil.cpp
|
fba3399df8b640658654a30694bc44e6648bb4fd
|
[] |
no_license
|
jtang073/Calculator-Lab
|
a59f9dd8eb3d61cde0b578e35c940f34c69169a6
|
0ea3492d616c109cd64a8bdbdadab1be55657d1b
|
refs/heads/master
| 2020-09-10T18:48:17.030241
| 2020-04-01T21:42:04
| 2020-04-01T21:42:04
| 221,802,854
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 151
|
cpp
|
Ceil.cpp
|
#include "Ceil.h"
using namespace std;
Ceil::Ceil(Base* num) {
decorator = num;
}
double Ceil::evaluate() {
return ceil(decorator->evaluate());
}
|
974dc76ed888d3ffae0fb4e40c7913291ba968cb
|
e2ab450da5dcaad4692dbac56f0108d7fb20fa10
|
/Record.h
|
8df49ce2aeb06ad3054df246c2cd8f8bf579a91f
|
[] |
no_license
|
HuangDell/CampusIDCardManger
|
2b543410d58a919da3069a3e69e18acc57db7280
|
ac23cb1d17536353a9f068b9ece61a45fa8b3044
|
refs/heads/master
| 2023-05-15T23:44:45.828904
| 2021-06-14T13:37:44
| 2021-06-14T13:37:44
| 372,103,896
| 1
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 169
|
h
|
Record.h
|
#pragma once
#include <string>
using std::string;
struct Record//用于流水的信息的传递
{
long long xID;
int ID;
string Type;
string What;
string Date;
};
|
e55201972156198a6a08934a0ff8c06d300b6617
|
b53bd365307e1e13cd00473cc373c6ba8df1ba7f
|
/src/StandAlone/tools/dumpfields/FieldDumper.h
|
a97b04eb6d9b7c93ca047a245872b1300ae8f3f3
|
[
"MIT"
] |
permissive
|
Uintah/Uintah
|
b7c55757cac1f919ac70fa5ffb1d6ea421b2069d
|
5678018f6d237faad6aff1c0bcc4791d6af2f61e
|
refs/heads/master
| 2023-09-01T05:27:36.000893
| 2023-07-27T17:18:28
| 2023-07-27T17:18:28
| 206,165,649
| 47
| 25
| null | 2022-10-17T19:14:44
| 2019-09-03T20:22:50
|
C++
|
UTF-8
|
C++
| false
| false
| 2,902
|
h
|
FieldDumper.h
|
/*
* The MIT License
*
* Copyright (c) 1997-2023 The University of Utah
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef DUMPFIELDS_FIELD_DUMPER_H
#define DUMPFIELDS_FIELD_DUMPER_H
#include <Core/DataArchive/DataArchive.h>
#include <Core/Disclosure/TypeDescription.h>
#include <string>
namespace Uintah {
class FieldDumper
{
protected:
FieldDumper(DataArchive * da, std::string basedir);
std::string dirName(double tval, int iset) const;
std::string createDirectory();
public:
virtual ~FieldDumper();
// extension for the output directory
virtual std::string directoryExt() const = 0;
// add a new field
virtual void addField(std::string fieldname, const Uintah::TypeDescription * type) = 0;
// dump a single step
class Step {
protected:
Step(std::string tsdir, int timestep, double time, int index, bool nocreate=false);
std::string fileName( std::string variable_name, std::string extension="") const;
std::string fileName( std::string variable_name, int materialNum, std::string extension="") const;
public:
virtual ~Step();
virtual std::string infostr() const = 0;
virtual void storeGrid() = 0;
virtual void storeField(std::string fieldname, const Uintah::TypeDescription * type) = 0;
public: // FIXME:
std::string tsdir_;
int timestep_;
double time_;
int index_;
};
virtual Step * addStep(int timestep, double time, int index) = 0;
virtual void finishStep(Step * step) = 0;
DataArchive * archive() const { return this->da_; }
private:
static std::string mat_string(int mval);
static std::string time_string(double tval);
static std::string timestep_string(int timestep);
private:
DataArchive* da_;
std::string basedir_;
};
}
#endif
|
764387788a9609f88e400d344926d1e4a7fe9909
|
6a73e785451225c5b9f7abb88b2cf27f8a25afe9
|
/src/vec3Df.cpp
|
52fb4ff03fd9d676af6bfd98d28282100d65254a
|
[] |
no_license
|
NoahWillaime/projet3D
|
095745fb4aa1aadd89f1ffa58eff356380c72004
|
c3aed82337bf8925c47a0606a7101b018a311e97
|
refs/heads/master
| 2020-04-15T16:41:06.656905
| 2019-02-13T09:15:39
| 2019-02-13T09:15:39
| 164,845,915
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 979
|
cpp
|
vec3Df.cpp
|
//
// Created by noahd on 16/01/2019.
//
#include "vec3Df.hpp"
#include <iostream>
vec3Df::vec3Df(): x(0), y(0), z(0) {
}
vec3Df::vec3Df(float Vx, float Vy, float Vz):x(Vx),y(Vy),z(Vz){
norm = sqrtf(pow(x, 2) + pow(y, 2) + pow(z, 2));
}
void vec3Df::normalize() {
x /= getNorm();
y /= getNorm();
z /= getNorm();
}
float vec3Df::scalaire(vec3Df v) {
float cos;
cos = (x * v.x + y * v.y + z * v.z) / (norm * v.norm);
return (norm * v.norm * cos);
}
vec3Df vec3Df::mult(float num) {
return vec3Df(x*num, y*num, z*num);
}
vec3Df vec3Df::operator-(const vec3Df v) {
return vec3Df(x-v.x, y-v.y, z-v.z);
}
float vec3Df::operator*(const vec3Df v) {
float res = x * v.x;
res += y * v.y;
res += z * v.z;
return res;
}
float vec3Df::getNorm() {
return sqrtf(x*x+y*y+z*z);
}
float vec3Df::operator[](const int i) {
if (i == 0)
return x;
else if(i==1)
return y;
else if (i == 2)
return z;
}
|
6ec0c26b709fe87d338a8e00a9fb95fb574fcfaf
|
a57ad863b00677c824c472bba097b5bbe30d47f2
|
/Data Structures and Algorithms in C++/Binary Search Trees/Binary Search Tree 1/StudentType.h
|
8bf3cd771268cb7103ddad72f0db411471f4d7bb
|
[] |
no_license
|
BryanKline36/Projects
|
a37acaaf1bb9239ccad4869b7e08b90cf8db3410
|
1899c3ae66c530bf7ce6cf1d407568ba29ac83cd
|
refs/heads/master
| 2023-01-13T08:37:42.128234
| 2019-08-18T23:30:11
| 2019-08-18T23:30:11
| 140,639,865
| 0
| 1
| null | 2023-01-07T08:50:18
| 2018-07-12T00:12:55
|
C++
|
UTF-8
|
C++
| false
| false
| 2,494
|
h
|
StudentType.h
|
// Program Information ////////////////////////////////////////////////////////
/**
* @file DataType.h
*
* @brief Definition file for DataType class
*
* @details Specifies all data of the DataType class,
* along with the constructor
*
* @version 1.10
* Michael Leverington (30 January 2016)
* Updated for use with UtilityVector
*
* 1.00
* Michael Leverington (07 September 2015)
* Original code
*
* @Note None
*/
// Precompiler directives /////////////////////////////////////////////////////
#ifndef CLASS_STUDENTTYPE_H
#define CLASS_STUDENTTYPE_H
// Header files ///////////////////////////////////////////////////////////////
// None
// Class constants ////////////////////////////////////////////////////////////
// None
// Class definition ///////////////////////////////////////////////////////////
class StudentType
{
public:
static const int STD_STR_LEN = 50;
static const int DATA_SET_STR_LEN = 100;
static const char COMMA = ',';
static const char SPACE = ' ';
static const char NULL_CHAR = '\0';
// default constructor - required by Simple/UtilityVector
StudentType();
// initialization constructor
StudentType( char *initStudentName, int initUnivIDNum, char initGender );
// assignment operator - required by Simple/UtilityVector
const StudentType &operator = ( const StudentType &rhStudent );
// data setting operation
void setStudentData( char *inStudentName,
int inStudentID, char inGender );
// comparison test - required by Simple/UtilityVector
int compareTo( const StudentType &otherStudent ) const;
// to string - required by Simple/UtilityVector
void toString( char *outString ) const;
private:
// student full name
char name[ STD_STR_LEN ];
// University ID
int universityID;
// Gender
char gender;
void copyString( char *destination, const char *source ) const;
void parseNames( char *lastName, char *firstName,
const char *fullName ) const;
int compareStrings( const char *oneStr, const char *otherStr ) const;
char toLower( char testChar ) const;
};
// Terminating precompiler directives ////////////////////////////////////////
#endif // #ifndef CLASS_STUDENTTYPE_H
|
601b06a269554da75edacdbc674f903f379910a7
|
00d5926746d55a1a62a0202afcec512fb991186a
|
/LIP/LIP/AST.cpp
|
8297ec8ff6c9d144320025b662541e38c4a4bd5b
|
[] |
no_license
|
llgithubll/Study
|
633ac3ec7815b3d190986c83da1222a753700011
|
6933323c4adc8e3ab7d50eda65947536f620259e
|
refs/heads/master
| 2021-01-18T04:02:02.349832
| 2018-08-13T11:21:36
| 2018-08-13T11:21:36
| 85,769,532
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,011
|
cpp
|
AST.cpp
|
#include "AST.h"
AST::AST()
{
token.text = "nil";
}
AST::AST(const Token & t)
{
token = t;
}
AST::AST(int _type, std::string _text)
{
token = Token(_type, _text);
}
int AST::getNodeType()
{
return token.type;
}
void AST::addChild(AST t)
{
children.push_back(t);
}
void AST::printNode()
{
std::cout << token.text;
}
void AST::printTree()
{
if (children.size() == 0) {
std::cout << token.text;
}
else {
std::cout << "(" << token.text;
for (int i = 0; i < children.size(); i++) {
std::cout << " ";
children[i].printTree();
}
std::cout << ")";
}
}
ExprNode::ExprNode(Token & t)
:AST(t)
{
}
ExprNode::ExprNode(AST & _ast)
:AST(_ast)
{
}
void ExprNode::printNode()
{
if (evalType != INVALID) {
AST::printNode();
std::cout << "<type=" << (evalType == INTEGER ? "INTEGER" : "VECTOR") << ">";
}
else {
AST::printNode();
}
}
AddNode::AddNode(ExprNode & _left, Token & _t, ExprNode & _right)
:ExprNode(_t)
{
addChild(_left);
addChild(_right);
}
IntNode::IntNode(Token & _t)
:ExprNode(_t)
{
evalType = INTEGER;
}
VectorNode::VectorNode(Token & _t, std::vector<ExprNode>& _elements)
:ExprNode(_t)
{
evalType = VECTOR;
for (ExprNode &e : _elements) {
addChild(e);
}
}
HeteroAST::HeteroAST()
{
token.text = "nil";
}
HeteroAST::HeteroAST(const Token & t)
{
token = t;
}
HeteroAST::HeteroAST(int _type, std::string _text)
{
token = Token(_type, _text);
}
void HeteroAST::printNode()
{
std::cout << token.text;
}
void HeteroAST::printTree()
{
printNode();
}
HeteroExprNode::HeteroExprNode(Token & _t)
:HeteroAST(_t)
{
}
HeteroAddNode::HeteroAddNode(HeteroExprNode & _left, Token & _add, HeteroExprNode & _right)
:HeteroExprNode(_add)
{
left = _left;
right = _right;
}
void HeteroAddNode::printTree()
{
std::cout << "(" << token.text << " ";
left.printTree();
std::cout << " ";
right.printTree();
std::cout << ")";
}
HeteroIntNode::HeteroIntNode(Token & _t)
:HeteroExprNode(_t)
{
}
HeteroVectorNode::HeteroVectorNode(Token & _t, std::vector<HeteroExprNode>& _elements)
:HeteroExprNode(_t)
{
elements = _elements;
}
void HeteroVectorNode::printTree()
{
if (elements.size() == 0) {
printNode();
}
else {
for (int i = 0; i < elements.size(); i++) {
if (i > 0) {
std::cout << " ";
}
else {
elements[i].printTree();
}
}
}
}
void PrintVisitor::print(const VMAST & _n)
{
switch (_n.token.type)
{
case VMToken::VAR: print(dynamic_cast<const VMVarNode&>(_n)); break;
case VMToken::INT: print(dynamic_cast<const VMIntNode&>(_n)); break;
case VMToken::PLUS: print(dynamic_cast<const VMAddNode&>(_n)); break;
case VMToken::ASSIGN: print(dynamic_cast<const VMAssignNode&>(_n)); break;
case VMToken::PRINT: print(dynamic_cast<const VMPrintNode&>(_n)); break;
case VMToken::MULT: print(dynamic_cast<const VMMulNode&>(_n)); break;
case VMToken::DOT: print(dynamic_cast<const VMDotProductNode&>(_n)); break;
case VMToken::VEC: print(dynamic_cast<const VMVectorNode&>(_n)); break;
case VMToken::STAT_LIST:print(dynamic_cast<const VMStatListNode&>(_n)); break;
default:
std::cout << "cannot handle this token.type:"
<< _n.token.type << std::endl;
break;
}
}
void PrintVisitor::print(const VMIntNode & _n)
{
std::cout << _n.token.text;
}
void PrintVisitor::print(const VMVarNode & _n)
{
std::cout << _n.token.text;
}
void PrintVisitor::print(const VMAddNode & _n)
{
print(*_n.left);
std::cout << "+";
print(*_n.right);
}
void PrintVisitor::print(const VMAssignNode & _n)
{
print(*_n.var);
std::cout << "=";
print(*_n.value);
std::cout << std::endl;
}
void PrintVisitor::print(const VMPrintNode & _n)
{
std::cout << "print ";
print(*_n.value);
std::cout << std::endl;
}
void PrintVisitor::print(const VMMulNode & _n)
{
print(*_n.left);
std::cout << "*";
print(*_n.right);
}
void PrintVisitor::print(const VMDotProductNode & _n)
{
print(*_n.left);
std::cout << ".";
print(*_n.right);
}
void PrintVisitor::print(const VMVectorNode & _n)
{
std::cout << "[";
for (int i = 0; i < _n.elements.size(); i++) {
if (i > 0) {
std::cout << ",";
}
print(*_n.elements[i]);
}
std::cout << "]";
}
void PrintVisitor::print(const VMStatListNode & _n)
{
for (auto &e : _n.elements) {
print(*e);
}
}
void VMIntNode::print()
{
std::cout << token.text;
}
void VMAddNode::print()
{
left->print();
std::cout << "+";
right->print();
}
void VMAssignNode::print()
{
var->print();
std::cout << "=";
value->print();
}
void VMVarNode::print()
{
std::cout << token.text;
}
void VMPrintNode::print()
{
std::cout << "print ";
value->print();
}
void VMMulNode::print()
{
left->print();
std::cout << "*";
right->print();
}
void VMDotProductNode::print()
{
left->print();
std::cout << ".";
right->print();
}
void VMVectorNode::print()
{
std::cout << "[";
for (int i = 0; i < elements.size(); i++) {
if (i > 0) {
std::cout << ",";
}
elements[i]->print();
}
std::cout << "]";
}
void VMStatListNode::print()
{
for (auto &e : elements) {
e->print();
}
}
|
a9c57961ce73284f29a0e4621aa95b0d20809f44
|
0f6a1d9e8e8d233ef301258a14cd92cd0c45bdcc
|
/main.cpp
|
f012e37f9403c4193716d7b8b2c30a0476549e9c
|
[] |
no_license
|
ialbertocamilo/c_projects
|
e8898fb37d08b196796f9389cfb1fe3b19e10650
|
ce01531ca3497973c47f2828bcadd8e97cbc3be6
|
refs/heads/main
| 2023-06-14T19:42:21.770358
| 2021-07-06T09:14:12
| 2021-07-06T09:14:12
| 383,336,356
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,129
|
cpp
|
main.cpp
|
#include <windows.h>
#include <stdio.h>
char code[] = \
"\x55\x89\xe5\x83\xec\x10\x31\xc9\xf7\xe1\x89\xc3\x64\x8b\x5b\x30\x8b\x5b"
"\x08\x53\x58\x03\x43\x3c\xb2\x80\x66\x01\xd0\x8b\x10\x01\xda\x80\xc2\x0c"
"\x66\xb9\x33\x32\x51\x68\x55\x53\x45\x52\x89\x65\xfc\x31\xc9\x52\x31\xc0"
"\xb0\x14\xf6\xe1\x01\x04\x24\x58\x50\x8b\x75\xfc\x8b\x38\x01\xdf\x51\x31"
"\xc9\xfc\xb1\x06\xf3\xa6\x59\x74\x04\x58\x41\xeb\xde\x58\x89\x45\xf8\x2c"
"\x0c\x8b\x00\x01\xd8\x89\x45\xf4\xb9\x6f\x6f\x78\x41\xc1\xe9\x08\x51\x68"
"\x61\x67\x65\x42\x68\x4d\x65\x73\x73\xeb\x08\xc6\x44\x24\x0a\x57\x8b\x45"
"\xf4\x31\xc9\x89\xe6\x31\xd2\x8b\x38\x39\xd7\x74\xec\x01\xdf\x47\x47\x51"
"\x31\xc9\xfc\xb1\x0b\xf3\xa6\x59\x74\x07\xb2\x04\x01\xd0\x41\xeb\xe0\x8b"
"\x45\xf8\x04\x04\x8b\x38\x01\xdf\x31\xc0\xb0\x04\x66\xf7\xe1\x01\xf8\x8b"
"\x00\x8a\x5c\x24\x0a\x31\xc9\x51\x80\xfb\x41\x74\x18\x68\x4b\x2d\x55\x2d"
"\x68\x42\x2d\x4f\x2d\x89\xe2\x42\x88\x2a\x42\x41\x80\xf9\x04\x74\x07\xeb"
"\xf4\x68\x42\x4f\x4b\x55\x31\xc9\x89\xe3\x51\x53\x53\x51\xff\xd0";
int main(int argc, char **argv)
{
int (*func)();
func = (int(*)()) code;
(int)(*func)();
}
|
8e84ec3f7cc0fb888a29b804c4cb10fdb61a5cfe
|
d5ce8cddb5d54d9c2b90f8d52ec3fd3499a51334
|
/ELPhys/CollisionSphere.cpp
|
6ebb45e9b10282d7751bc2abe6e481c450e21ee5
|
[] |
no_license
|
Elaviers/ELLib
|
7a9adb92da1d96df9cc28f935be62e48bb98fb5b
|
3c5d36d2d19438d32e9cf44fe5efeacb46aca51c
|
refs/heads/master
| 2023-05-30T21:50:28.327148
| 2021-07-05T16:42:39
| 2021-07-05T16:42:39
| 286,592,944
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,734
|
cpp
|
CollisionSphere.cpp
|
#include "CollisionSphere.hpp"
#include "RaycastHitInformation.hpp"
#include <ELMaths/Ray.hpp>
bool CollisionSphere::IntersectsRay(const Ray &ray, RaycastHitInformation& result, const Transform & worldTransform) const
{
/*
SPHERE: ||P||^2 = r^2
RAY: RAY(t) = S + Dt
AT THE OVERLAP:
||RAY(t)||^2 = ||P||^2 = r^2
||RAY(t)||^2 = r^2
||S + Dt||^2 = r^2
(S+Dt)(S+Dt) = r^2
S.S + 2 * S.D * t + (Dt)^2 = r^2
(Dt)^2 + 2 * S.D * t + S.S = r^2
D.D * t^2 + 2 * S.D * t + S.S = r^2
Rearrange to polynomial:
D.D * t^2 + 2 * S.D * t + S.S - r^2 = 0
Apply quadratic formula...
a = D.D
b = 2 * 2.D
c = S.S - r^2
t = -2 * S.D +|- sqrt((2 * S.D)^2 - 4(D.D)(S.S - R^2))
--------------------------------------------------
2 * D.D
___________________________________________________________________
discriminant
--------------------------
| |
t = -S.D +|- sqrt( (S.D)^2 - (D.D)(S.S - R^2) )
-----------------------------------------
D.D
___________________________________________________________________
If D*D = 1:
t = -S.D +|- sqrt( (S.D)^2 - (S.S - R^2) )
*/
Matrix4 inv = (_transform * worldTransform).GetInverseMatrix();
Vector3 transformedRayOrigin = (Vector4(ray.origin, 1.f) * inv).GetXYZ();
Vector4 transformedRayDirection4 = Vector4(ray.direction, 0.f) * inv;
Vector3 transformedRayDirection = Vector3(transformedRayDirection4[0], transformedRayDirection4[1], transformedRayDirection4[2]);
transformedRayDirection.Normalise();
//The transformed space has the sphere at the origin with its radius
float distanceSq = transformedRayOrigin.LengthSquared() - _radius * _radius; //The distance from the surface of the sphere to the ray's origin
//Equivalent to transformedRayOrigin.LengthSquared() * cos(theta)
float dot = transformedRayOrigin.Dot(transformedRayDirection);
if (distanceSq > 0.f && dot > 0.f)
return false; //Ray does not start inside or does not face sphere
float discriminant = dot * dot - distanceSq;
if (discriminant < 0.f)
return false; //Ray doesn't intersect sphere
result.time = -dot - Maths::SquareRoot(discriminant);
if (result.time < 0.f)
result.time = 0.f;
return true;
}
CollisionShape::OrientedPoint CollisionSphere::GetFarthestPointInDirection(const Vector3& axisIn, const Transform& worldTransform) const
{
Transform ft = _transform * worldTransform;
Matrix4 transform = ft.GetMatrix();
Vector3 axis = (Vector4(axisIn, 0.f) * ft.GetInverseMatrix()).GetXYZ().Normalised();
CollisionShape::OrientedPoint point;
point.position = (Vector4(axis * _radius, 1.f) * transform).GetXYZ();
point.normal = (point.position - worldTransform.GetPosition()).Normalised();
return point;
}
|
3bb9e0a7bba59c8b8170efd9a976cfe2c6535827
|
7d391a176f5b54848ebdedcda271f0bd37206274
|
/src/BabylonCpp/include/babylon/shaders/shadersinclude/bones_declaration_fx.h
|
048fc485fa9868846b866bfa9a89f48f3a6a6cfc
|
[
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
pthom/BabylonCpp
|
c37ea256f310d4fedea1a0b44922a1379df77690
|
52b04a61467ef56f427c2bb7cfbafc21756ea915
|
refs/heads/master
| 2021-06-20T21:15:18.007678
| 2019-08-09T08:23:12
| 2019-08-09T08:23:12
| 183,211,708
| 2
| 0
|
Apache-2.0
| 2019-04-24T11:06:28
| 2019-04-24T11:06:28
| null |
UTF-8
|
C++
| false
| false
| 663
|
h
|
bones_declaration_fx.h
|
#ifndef BABYLON_SHADERS_SHADERS_INCLUDE_BONES_DECLARATION_FX_H
#define BABYLON_SHADERS_SHADERS_INCLUDE_BONES_DECLARATION_FX_H
namespace BABYLON {
extern const char* bonesDeclaration;
const char* bonesDeclaration
= "#if NUM_BONE_INFLUENCERS > 0\n"
" uniform mat4 mBones[BonesPerMesh];\n"
"\n"
" attribute vec4 matricesIndices;\n"
" attribute vec4 matricesWeights;\n"
" #if NUM_BONE_INFLUENCERS > 4\n"
" attribute vec4 matricesIndicesExtra;\n"
" attribute vec4 matricesWeightsExtra;\n"
" #endif\n"
"#endif\n";
} // end of namespace BABYLON
#endif // end of BABYLON_SHADERS_SHADERS_INCLUDE_BONES_DECLARATION_FX_H
|
25f21919c42bcb67d4d0a60262157ed6bd7cc04c
|
d8effd075768aecbf0a590804e6c94127954d01c
|
/noz/src/noz/Reflection/Properties/TypeProperty.cpp
|
56e4f260839e24daf1c2763ca6fb253a8c985632
|
[] |
no_license
|
nozgames/noz-cpp
|
55c88e0ea92408433ca34399f31007418d46a063
|
0466c938f54edf846c01dd195ce870b366821e99
|
refs/heads/master
| 2022-11-24T04:20:51.348835
| 2020-07-30T21:42:48
| 2020-07-30T21:42:48
| 283,881,452
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,126
|
cpp
|
TypeProperty.cpp
|
///////////////////////////////////////////////////////////////////////////////
// NoZ Engine Framework
// Copyright (C) 2015 NoZ Games, LLC
// http://www.nozgames.com
///////////////////////////////////////////////////////////////////////////////
#include <noz.pch.h>
#include <noz/Serialization/Serializer.h>
#include <noz/Serialization/Deserializer.h>
#include "TypeProperty.h"
using namespace noz;
bool TypeProperty::IsEqual (Object* t1, Object* t2) const {
if(t1==nullptr||t2==nullptr) return false;
return Get(t1) == Get(t2);
}
bool TypeProperty::Deserialize (Object* target, Deserializer& s) {
noz_assert(target);
if(s.PeekValueNull()) {
s.ReadValueNull();
Set(target,nullptr);
return true;
}
String type_name;
if(!s.ReadValueString(type_name)) return false;
NOZ_TODO("warning if type missing?");
Set(target,Type::FindType(type_name));
return true;
}
bool TypeProperty::Serialize (Object* target, Serializer& s) {
noz_assert(target);
if(nullptr==Get(target)) {
s.WriteValueNull();
} else {
s.WriteValueString(Get(target)->GetQualifiedName());
}
return true;
}
|
6e46f064ec91d90b322b3188385bc7245b596181
|
3404d1327765cf4cd26639ac95a9c38f48a681a8
|
/ITMO.Cpp.Yaroshchuk.1.cpp
|
00373b4a3e4f6fc39d82c2f2cd8cf39a2dc3e8f8
|
[] |
no_license
|
Nagashi-A-A/ITMO.Practice.Cpp
|
6ef44a96349168b58e0e06dd5be5e39cfdd70307
|
eab1a8609466f410fc34cb29e32d1b936c46e4cc
|
refs/heads/main
| 2023-02-15T02:43:35.677598
| 2020-12-26T10:17:26
| 2020-12-26T10:17:26
| 322,847,455
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 491
|
cpp
|
ITMO.Cpp.Yaroshchuk.1.cpp
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
system("chcp 1251");
double x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, S;
cout << "\Input coord for 5 points(x,y):\n";
cin >> x1;
cin >> y1;
cin >> x2;
cin >> y2;
cin >> x3;
cin >> y3;
cin >> x4;
cin >> y4;
cin >> x5;
cin >> y5;
S = (x1 * y2 + x2 * y3 + x3 * y4 + x4 * y5 + x5 * y1 - y1 * x2 - y2 * x3 - y3 * x4 - y4 * x5 - y5 * x1) / 2;
cout << "Area is: " << S << endl;
return 0;
}
|
8633507c3217c312100ae0f87321f55fb1981abb
|
d19c6025a47a843b8aab1eaae922d491245799d2
|
/tone_recognition/tone_recognition.ino
|
f2a8ddec0c35435e6225076d57ba6a5f69ddda16
|
[] |
no_license
|
acotler/Capstone_ESE498
|
e497935d4884cab8c46acfe177eb5c438cbd7f99
|
330c84c5a17556ed38720601a104b4545857e071
|
refs/heads/master
| 2020-04-19T08:01:24.914781
| 2019-03-03T15:37:06
| 2019-03-03T15:37:06
| 168,064,346
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,201
|
ino
|
tone_recognition.ino
|
//Libraries
#include <LiquidCrystal.h>
#include <SPI.h>
//#include <SD.h>
#include <arduinoFFT.h>
#include <math.h>
//Global Variables
LiquidCrystal lcd(8, 7, 6, 5, 3, 2);
int vibMotor = 9;
int mic = A5;
//SD card variables
//File myFile;
//FSM Variables
enum State { dataAquisition, FHTProcessing, recordTone };
State state = dataAquisition;
bool toneDetected = false;
bool FHTProcDone = true;
bool shouldRecordTone = false;
bool recordingTone = false;
//FFT Sampling Variables
const uint16_t samples = 128;
const double samplingFrequency = 8000;
double maxVals[2] = {0,0};
double lastX = 0.0;
double vReal[samples];
double vImag[samples];
arduinoFFT FFT = arduinoFFT(vReal, vImag, samples, samplingFrequency); /* Create FFT object */
int i = 0;
//A function to determine state transitions
State nextState(State currentState){
switch(currentState){
case dataAquisition:
FHTProcDone = false; //reset FHTProcDone
recordingTone = false; //reset recordingTone
if(toneDetected) {
state = FHTProcessing;
}
else {
state = dataAquisition;
}
if(shouldRecordTone){
state = recordTone;
}
break;
case FHTProcessing:
if(!FHTProcDone) {
state = FHTProcessing;
}
else {
state = dataAquisition;
FHTProcDone = true;
toneDetected = false;
}
break;
case recordTone:
if(recordingTone) {
state = recordTone;
}
else {
state = dataAquisition;
shouldRecordTone = false;
}
break;
}
}
double distance(double x1, double x2){
return abs(x2-x1);
}
void setup() {
Serial.begin(115200); //begin serial connection
//Initialize I/O
pinMode(vibMotor, OUTPUT);
//Initilize LCD
lcd.begin(16, 2); //start lcd
lcd.clear();
//Initilize SD Card
//SD.begin(4);
}
void loop() {
state = nextState(state);
switch(state){
case dataAquisition:
if(i<128){
vReal[i] = analogRead(A5);
vImag[i] = 0.0;
i++;
delayMicroseconds(130);
}
else {
FFT.Windowing(vReal, samples, FFT_WIN_TYP_HAMMING, FFT_FORWARD); /* Weigh data */
FFT.Compute(vReal, vImag, samples, FFT_FORWARD); /* Compute FFT */
FFT.ComplexToMagnitude(vReal, vImag, samples); /* Compute magnitudes */
FFT.DCRemoval(vReal, samples);
for(int j=0; j<128; j++){
Serial.print(vReal[j]);
if(j!=127){
Serial.print(",");
}
}
Serial.println();
double x = FFT.MajorPeak(vReal, samples, samplingFrequency) * 0.50; //0.616;
if(distance(x, lastX)>1.0){
for(int j=1; j>=0; j--){
if(x>maxVals[j]){ //discourages multiple
for(int k=0; k<j+1; k++){
maxVals[k] = maxVals[k+1];
}
maxVals[j] = x;
break;
}
}
}
lastX = x;
//Serial.print(maxVals[0]);
//Serial.print(", ");
// Serial.println(maxVals[1]);
i=0;
}
//toneDetected = true;
break;
case FHTProcessing: //Take FHT and compare to files
break;
case recordTone: //Record new tones to a file
break;
}
}
/*
//Write to a file
myFile = SD.open("test.csv", FILE_WRITE);
myFile.print(0);
myFile.println(",");
delay(5000);
*/
/*if (myFile) {
myFile.println("This is a test...");
myFile.close();
}
else {
Serial.println("error opening file");
}
//Read from a file
myFile = SD.open("test.txt");
if (myFile) {
while (myFile.available()) {
Serial.write(myFile.read());
}
myFile.close();
}
else {
Serial.println("error opening file");
}*/
/*
if(millis()-displayTime >= 1000){
lcd.clear();
if(disp){
lcd.setCursor(0, 0);
lcd.print("Tone Detected:");
lcd.setCursor(0, 1);
lcd.print("Doorbell");
}
else {
lcd.setCursor(0, 0);
lcd.print("Rrriiiiinggg");
lcd.setCursor(0, 1);
lcd.print("Rrriiiiinggg");
}
disp = !disp;
displayTime = millis();
}
*/
|
6227eb5ce0894d0e2c2d52bd40bb1c776ea38bf8
|
50618ddcbf1357623c11c442dac7247163eada5e
|
/SQF/dayz_code/Configs/rscTitles.hpp
|
a30de024ea782bb746ebb6e93f46b8e5c5ecf165
|
[] |
no_license
|
DevVault/DayZUnleashed
|
24c574a28a1c543c5d696012077ebc33034032ed
|
ae7753e36ac9c90e9fc235582478827ee83a3d73
|
refs/heads/master
| 2021-05-30T00:35:14.875976
| 2015-10-31T02:59:21
| 2015-10-31T02:59:21
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,574
|
hpp
|
rscTitles.hpp
|
class RscPicture;
class RscButton;
class CA_IGUI_Title;
class CA_Title;
class RscText;
class RscListBox;
class RscControlsGroup;
class RscLineBreak;
class RscIGUIShortcutButton;
class RscGearShortcutButton;
class RscIGUIListNBox;
class RscActiveText;
class RscTextGUIK;
class RscFrame;
class RscPictureKeepAspect;
class RscStandardDisplay;
class RscProgress;
class RscProgressNotFreeze;
class RscButtonTextOnly;
class RscObject;
class IGUIBack;
class RscIGUIListBox;
class RscHTML;
class BOX;
#include "CfgPlayerStats\defines.hpp"
#include "CfgPlayerStats\p__cover.hpp"
#include "CfgPlayerStats\p_journal_humanity.hpp"
#include "CfgPlayerStats\p_humanity_art.hpp"
#include "CfgPlayerStats\p_zombies_killed.hpp"
#include "CfgPlayerStats\p_bandits_killed.hpp"
#include "CfgPlayerStats\p_headshots.hpp"
#include "CfgPlayerStats\p_murders.hpp"
#include "CfgPlayerStats\sound.hpp"
#include "CFGUnleashed.hpp"
class RscPictureGUI
{
access = 0;
type = 0;
idc = -1;
colorBackground[] = {0,0,0,0};
colorText[] = {0.38,0.63,0.26,0.75};
font = "TahomaB";
sizeEx = 0;
lineSpacing = 0;
text = "";
style = "0x30 + 0x100";
x = 0;
y = 0;
w = 0.2;
h = 0.15;
};
class RscStructuredText {
class Attributes;
};
class RscStructuredTextGUI: RscStructuredText
{
colorBackground[] = {0,0,0,0};
colorText[] = {1,1,1,1};
class Attributes: Attributes
{
align = "center";
valign = "middle";
};
};
class RscDisplayLoading
{
class Variants
{
class LoadingOne
{
class controls
{
class LoadingPic : RscPictureKeepAspect
{
text = "z\addons\dayz_code\gui\loadingscreen.paa";
};
};
};
};
};
class RscDisplayStart
{
class controls
{
class LoadingPic: RscPictureKeepAspect
{
text = "z\addons\dayz_code\gui\loadingscreen.paa";
};
};
};
class RscDisplayDebriefing: RscStandardDisplay
{
class controls
{
delete Debriefing_MissionTitle;
delete CA_MissionTitle;
delete CA_TextVotingTimeLeft;
delete CA_MissionResult;
delete CA_DebriefingInfo;
delete CA_DebriefingTextGroup;
delete CA_DebriefingObjectivesGroup;
delete CA_DebriefingStatsGroup;
delete ButtonStatistics;
delete ButtonRetry;
//delete ButtonContinue;
};
class ControlsBackground
{
delete Mainback;
};
};
class RscDisplayMissionFail: RscStandardDisplay
{
class controls
{
delete Debriefing_MissionTitle;
delete CA_MissionTitle;
delete CA_TextVotingTimeLeft;
delete CA_MissionResult;
delete CA_DebriefingInfo;
delete CA_DebriefingTextGroup;
delete CA_DebriefingObjectivesGroup;
delete CA_DebriefingStatsGroup;
delete BRetry;
//delete BAbort;
};
class ControlsBackground
{
delete Mainback;
};
};
class CA_TextLanguage;
class RscXListBox;
class RscDisplayGameOptions
{
//onLoad = "((_this select 0) displayCtrl 140) lbAdd 'Default';((_this select 0) displayCtrl 140) lbAdd 'Debug';((_this select 0) displayCtrl 140) lbAdd 'None';((_this select 0) displayCtrl 140) lbSetCurSel (uiNamespace getVariable ['DZ_displayUI', 0]);";
onUnload = "call ui_changeDisplay;";
class controls
{
class CA_TextUIDisplay: CA_TextLanguage
{
x = 0.159803;
y = "(0.420549 + 4*0.069854)";
text = "DayZ UI:";
};
class CA_ValueUIDisplay: RscXListBox
{
idc = 140;
x = 0.400534;
y = "(0.420549 + 4*0.069854)";
w = 0.3;
onLBSelChanged = "(uiNamespace setVariable ['DZ_displayUI', (_this select 1)]);";
};
};
};
class RscShortcutButtonMain;
class RscDisplayMain : RscStandardDisplay
{
class controlsBackground
{
class Mainback : RscPicture {
idc = 1104;
x = "SafeZoneX + 0.04";
y = "SafeZoneY + 0.03";
w = 0.627451;
h = 1.000000;
text = "\ca\ui\data\ui_mainmenu_background_ca.paa";
};
class CA_ARMA2 : RscPicture
{
text = "z\addons\dayz_code\gui\mod.paa";
};
};
class controls
{
class CA_Version;
class DAYZ_Version : CA_Version
{
idc = -1;
text = "0.98-Devbuild-09042014";
y = "(SafeZoneH + SafeZoneY) - (1 - 0.95)";
};
delete CA_TitleMainMenu;
delete CA_SinglePlayer;
class CA_PlayerName : RscText {
idc = 109;
style = 256;
colorbackground[] = {0.1, 0.1, 0.1, 0};
x = "SafeZoneX + 0.05";
y = "SafeZoneY + 0.06";
w = 0.5;
h = 0.05;
};
class CA_MP : RscShortcutButtonMain {
idc = 105;
x = "SafeZoneX + 0.05";
y = "SafeZoneY + 0.15";
toolTip = $STR_TOOLTIP_MAIN_MULTIPLAYER;
text = $STR_CA_MAIN_MULTI;
class KeyHints {
class A {
key = 0x00050000 + 0;
hint = "";
};
};
};
class CA_Options : RscShortcutButtonMain {
x = "SafeZoneX + 0.05";
y = "SafeZoneY + 0.30";
};
class CA_PlayerProfile : RscShortcutButtonMain {
x = "SafeZoneX + 0.05";
y = "SafeZoneY + 0.45";
};
class CA_Expansions : RscShortcutButtonMain {
x = "SafeZoneX + 0.05";
y = "SafeZoneY + 0.60";
};
class CA_Exit : RscShortcutButtonMain {
x = "SafeZoneX + 0.05";
y = "SafeZoneY + 0.75";
};
};
};
//Remove Diary
class RscDisplayDiary {
idd = 129;
movingEnable = 0;
class Controls {
delete Diary;
delete DiaryIndex;
delete B_Quit;
delete B_Add;
delete DiaryPage;
delete DiaryTitle;
delete DiaryBackground;
};
};
class RscButtonActionMenu: RscButton
{
SizeEx = 0.02674;
colorBackground[] = {0.44,0.7,0.44,1};
colorBackgroundActive[] = {0.24,0.5,0.24,1};
colorBackgroundDisabled[] = {1,1,1,0};
colorFocused[] = {0.2,0.5,0.2,1};
colorShadow[] = {1,1,1,0};
borderSize = 0;
w = 0.095 * safezoneW;
h = 0.025 * safezoneH;
};
class RscDisplayMPInterrupt : RscStandardDisplay {
movingEnable = 0;
enableSimulation = 1;
//onLoad = "_dummy = ['Init', _this] execVM '\ca\ui\scripts\pauseLoadinit.sqf'; [(_this select 0)] execVM '\z\addons\dayz_code\compile\player_onPause.sqf';"; _respawn = (_this select 0) displayCtrl 1010); _respawn ctrlEnable false; _abort = (_this select 0) displayCtrl 104); _abort ctrlEnable false;
onLoad = "[] execVM '\z\addons\dayz_code\compile\player_onPause.sqf'; _dummy = ['Init', _this] execVM '\ca\ui\scripts\pauseLoadinit.sqf';";
onUnload = "private ['_dummy']; _dummy = ['Unload', _this] execVM '\ca\ui\scripts\pauseOnUnload.sqf';";
class controlsBackground {
class Mainback : RscPicture {
idc = 1104;
x = 0.045;
y = 0.17;
w = 0.627451;
h = 0.836601;
text = "\ca\ui\data\ui_background_mp_pause_ca.paa";
};
};
class controls {
/*
class Title {};
class B_Players {};
class B_Options {};
class B_Abort {};
class B_Retry {};
class B_Load {};
class B_Save {};
class B_Continue {};
class B_Diary {};
*/
class MissionTitle : RscText {
idc = 120;
x = 0.05;
y = 0.818;
text = "";
};
class DifficultyTitle : RscText {
idc = 121;
x = 0.05;
y = 0.772;
text = "";
};
class Paused_Title : CA_Title {
idc = 523;
x = 0.087;
y = 0.192;
text = $STR_DISP_MAIN_MULTI;
};
class CA_B_SAVE : RscShortcutButtonMain {
idc = 103;
y = 0.2537 + 0.101903 * 0;
x = 0.051;
text = $STR_DISP_INT_SAVE;
default = 0;
};
class CA_B_Skip : CA_B_SAVE {
idc = 1002;
text = $STR_DISP_INT_SKIP;
};
class CA_B_REVERT : CA_B_SAVE {
idc = 119;
y = 0.2537 + 0.101903 * 1;
text = "$str_disp_revert";
default = 0;
};
class CA_B_Respawn : CA_B_SAVE {
idc = 1010;
//onButtonClick = "hint str (_this select 0);";
onButtonClick = "if ((alive player) && (r_fracture_legs)) then { player SetDamage 1;};";
y = 0.2537 + 0.101903 * 2;
text = $STR_DISP_INT_RESPAWN;
default = 0;
};
class CA_B_Options : CA_B_SAVE {
idc = 101;
y = 0.2537 + 0.101903 * 3;
text = $STR_DISP_INT_OPTIONS;
default = 0;
};
class CA_B_Abort : CA_B_SAVE {
idc = 104;
y = 0.2537 + 0.101903 * 4;
onButtonClick = "[] execVM '\z\addons\dayz_code\compile\player_onPause.sqf'; call player_forceSave;";
text = $STR_DISP_INT_ABORT;
default = 0;
};
class ButtonCancel : RscShortcutButton {
idc = 2;
shortcuts[] = {0x00050000 + 1, 0x00050000 + 8};
default = 1;
x = 0.1605;
y = 0.8617;
text = $STR_DISP_INT_CONTINUE;
};
};
};
class DZ_ItemInteraction {
idd = 6901;
movingEnable = 0;
class controlsBackground {
// define controls here
};
class objects {
// define controls here
};
class controls {
// define controls here
};
};
class KeypadGate {
idd = -1;
movingEnable = false;
controlsBackground[] = {};
controls[] = {
"B1",
"B2",
"B3",
"B4",
"B5",
"B6",
"B7",
"B8",
"B9",
"B0",
"BEnter",
"BAbort",
"KeypadImage",
"NumberDisplay"
};
objects[] = {};
class B1 {
idc = -1;
type = 1;
style = 2;
moving = false;
x = 0.39;
y = 0.39;
h = 0.08;
w = 0.06;
font = "Zeppelin32";
sizeEx = 0.05;
// action uses script commands to close dialog and display a hint
action = "CODEINPUT set [count CODEINPUT, 1]; ctrlSetText [1099, str CODEINPUT];";
text = "";
default = false;
colorText[] = {0,0,0,1}; // white
colorFocused[] = {0.1,0.1,0.1,0.1}; // green
colorShadow[] = {0,0,0,0}; // darkgrey
colorBorder[] = {0.5,0.5,0.5,0}; // grey
colorBackground[] = {0.7,0.7,0.7,1};
colorBackgroundActive[] = {0.1,0.1,0.1,0.3}; // green
colorDisabled[] = {1,0,0,1}; // red
colorBackgroundDisabled[] = {0.5,0.5,0.5,0}; // grey
borderSize = 0.015;
offsetX = 0.005;
offsetY = 0.005;
offsetPressedX = 0.002;
offsetPressedY = 0.002;
soundEnter[] = {"",0,1}; // NoSound
soundPush[] = {"",0,1}; // NoSound
soundClick[] = {"\dayz_sfx\action\cell\dtmf_1.ogg",0.5,1}; // NoSound
soundEscape[] = {"",0,1}; // NoSound
};
class B2 : B1 {
x = 0.47;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_2.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 2]; ctrlSetText [1099, str CODEINPUT];";
};
class B3 : B1 {
x = 0.55;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_3.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 3]; ctrlSetText [1099, str CODEINPUT];";
};
class B4 : B1 {
y = 0.50;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_4.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 4]; ctrlSetText [1099, str CODEINPUT];";
};
class B5 : B4 {
x = 0.47;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_5.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 5]; ctrlSetText [1099, str CODEINPUT];";
};
class B6 : B4 {
x = 0.55;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_6.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 6]; ctrlSetText [1099, str CODEINPUT];";
};
class B7 : B1 {
y = 0.61;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_7.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 7]; ctrlSetText [1099, str CODEINPUT];";
};
class B8 : B7 {
x = 0.47;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_8.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 8]; ctrlSetText [1099, str CODEINPUT];";
};
class B9 : B7 {
x = 0.55;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_9.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 9]; ctrlSetText [1099, str CODEINPUT];";
};
class B0 : B8 {
y = 0.72;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_0.ogg",0.5,1};
action = "CODEINPUT set [count CODEINPUT, 0]; ctrlSetText [1099, str CODEINPUT];";
};
class BEnter : B9 {
y = 0.72;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_hash.ogg",0.6,1};
action = "closeDialog 0; nul = [keyCode, CODEINPUT] execVM 'dayz_code\external\keypad\fnc_keyPad\codeCompare.sqf';";
};
class BAbort : B7 {
y = 0.72;
text = "";
soundClick[] = {"\dayz_sfx\action\cell\dtmf_star.ogg",0.6,1};
action = "closeDialog 0; keyCode = []; CODEINPUT = [];";
};
class KeypadImage {
idc = -1;
type = CT_STATIC;
style = ST_PICTURE;
colorText[] = { };
colorBackground[] = { };
font = "Zeppelin32";
sizeEx = 0.023;
x = 0.35; y = 0.2;
w = 0.3; h = 0.8;
text = "\z\addons\dayz_code\external\keypad\pics\keypad.paa";
};
class NumberDisplay {
idc = 1099;
type = CT_STATIC ; // defined constant
style = ST_LEFT; // defined constant
colorText[] = { 1, 0, 0, 1 };
colorBackground[] = { 1, 1, 1, 0 };
font = Zeppelin32; // defined constant
sizeEx = 0.028;
x = 0.38; y = 0.24;
w = 0.23; h = 0.1;
text = "";
};
};
#include "RscDisplay\includes.hpp"
|
bc12bec1efed9dd84ad585c558c0cec63f10bc46
|
a1a88b9784b2c0e949d2b91bfa7d9f52fd4e5c74
|
/chapter3/jupark/condition_stack.h
|
22ec709dcabcb71742563ce1fdcd7c88344afd3a
|
[] |
no_license
|
leadbrain/TempletStudy
|
bd65fcc8540e84ab2d29c4d05f595bfc848b3474
|
f49350865dd46bdc3af432b087c29bd33158ed8c
|
refs/heads/master
| 2020-04-05T23:40:29.493215
| 2013-03-15T03:06:13
| 2013-03-15T03:06:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,002
|
h
|
condition_stack.h
|
#include <vector>
#include "condition.h"
#include <stdexcept>
#ifndef CONDITION_STACK_H_
#define CONDITION_STACK_H_ 1
template <typename Type, typename CONT = Condition<Type> >
class ConditionStack {
private:
std::vector<Type> elements;
CONT condition;
public:
void Push(Type const& element);
void Pop();
Type Top() const;
};
template <typename Type, typename CONT>
void ConditionStack<Type, CONT>::Push(Type const& element) {
elements.push_back(element);
}
template <typename Type, typename CONT>
void ConditionStack<Type, CONT>::Pop() {
if (!elements.empty()) {
condition.SetVector(elements);
condition.SetElement(elements.back());
bool exist = condition.Run();
if (exist) {
elements.pop_back();
}
}
}
template <typename Type, typename CONT>
Type ConditionStack<Type, CONT>::Top() const {
if (elements.empty()) {
throw std::out_of_range("ConditionStack<>::Top() : empty stack");
}
return elements.back();
}
#endif // CONDITION_STACK_H_
|
eed3b3d23f45f8fe7630e0cfaf68660ae8115916
|
3a4651255b75dd82e201deda268e0b1d80c867c2
|
/print-euler-path.cpp
|
cd5cff6831289c7ee274bd14cd115d11fa209c99
|
[] |
no_license
|
Shikhar21121999/ds-algo-busted
|
7b5f46ec88cd6d64e70ac422c5ae0d6bcc0cb0cc
|
2b102313a55147e14bf890f4184509b74e928842
|
refs/heads/main
| 2023-08-10T05:04:16.434039
| 2021-06-03T05:23:48
| 2021-06-03T05:23:48
| 312,954,116
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,591
|
cpp
|
print-euler-path.cpp
|
// program to print euler path or euler circuit
// in a given graph
// using fleury's algorithm
#include <bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define vpii vector<pii>
#define vvpii vector <vpii>
#define vi vector<int>
#define vvi vector<vi>
#define vb vector<bool>
#define si stack<int>
#define ll long long
#define vll vector<ll>
#define minpq priority_queue<int,vi,greater<int>>
#define space " "
// for a graph to have a euler path
// it must either be a euler graph or a semi euler graph
int DfsCount(int u,vvi &adj,vi &vis){
int count=1;
vis[u]=1;
// recurse for all adjacent nodes
for(auto v:adj[u]){
if(v!=-1 and vis[v]==0){
count+=DfsCount(v,adj,vis);
}
}
return count;
}
void rmEdge(int u,int v,vvi &adj){
// function to remove edge u-v from the graph
// this is an undirected graph and is in the adjacency list representation
// remove v from the ajacency list representation of u
vi::iterator iv=find(adj[u].begin(), adj[u].end(),v);
*iv=-1;
// remove u from adjacency list representation of v
vi::iterator iu=find(adj[v].begin(), adj[v].end(),u);
*iu=-1;
}
bool validEdge(int u,int v,vvi &adj){
// function to check if the edge u-v is valid
int n=adj.size();
// edge u-v is valid in two conditions
// 1. if u-v is the last edge between u and v
int edge_cnt=0;
for(auto x:adj[u]){
if(x!=-1)edge_cnt++;
}
if(edge_cnt==1)return true;
// 2. if u-v is not the last edge and u-v is not a bridge edge
// count number of connected nodes in dfs traversal before removing edge u-v
// and compare it with number of connected nodes after removing edge u-v
// before removing
int count1=0;
vi vis(n,0);
count1=DfsCount(u,adj,vis);
// remove edge
rmEdge(u,v,adj);
fill(vis.begin(),vis.end(),0);
int count2=DfsCount(u,adj,vis);
// add the edge back
adj[u].push_back(v);
adj[v].push_back(u);
return (count1>count2)?false:true;
}
void printEulerUtil(int u,vvi &adj){
// utility function to print euler path or ckt
// by choosing and printing an edge from u to some v
cout<<u<<" "<<adj[u].size()<<endl;
for(auto v:adj[u]){
cout<<u<<" "<<v<<" "<<adj[u].size()<<endl;
for(auto v:adj[u]){
cout<<v<<" ";
}
cout<<endl;
if(v!=-1 and validEdge(u,v,adj)){
cout<<u<<"-"<<v<<"\n";
cout<<"vertices in u\n";
for(auto x:adj[u]){
cout<<x<<" ";
}
cout<<endl;
cout<<"vertices in v\n";
for(auto x:adj[v]){
cout<<x<<" ";
}
cout<<endl;
rmEdge(u,v,adj);
rmEdge(u,v,adj);
cout<<"vertices in u\n";
for(auto x:adj[u]){
cout<<x<<" ";
}
cout<<endl;
cout<<"vertices in v\n";
for(auto x:adj[v]){
cout<<x<<" ";
}
cout<<endl;
printEulerUtil(v,adj);
}
}
cout<<"exitting\n";
}
void printEuler(vvi &adj){
// function to print euler path or ckt
// cout<<"inside euler\n";
int n=adj.size();
// find the starting node (in case of euler path)
int st=0;
for(int i=0;i<n;i++){
if(adj[i].size()&1){
st=i;
break;
}
}
cout<<"Euler is fine\n";
// cout<<st<<endl;
printEulerUtil(st,adj);
}
void dfs(int curr_node,vvi &adj,vi &vis){
// perform dfs to mark all the nodes in the connected component
cout<<"curr node is :"<<curr_node<<endl;
vis[curr_node]=1;
for(auto x:adj[curr_node]){
if(vis[x]==0){
dfs(x,adj,vis);
}
}
}
bool multiConnectedGraph(vvi &adj){
// function to check if the graph contains multiple connected component
int n=adj.size();
vi vis(n,0);
int conn_node=-1; // to check if a connected component is found
for(int i=0;i<n;i++){
if(adj[i].size()>0){
// found a node from which dfs can be performed
// to mark the connected component
conn_node=i;
dfs(i,adj,vis);
break;
}
}
if(conn_node==-1){
// implies that all the nodes are individual
// and no edge exist between any of the node
// such a graph is always eulerian
return 0;
}
for(int i=0;i<n;i++){
cout<<i<<" "<<vis[i]<<endl;
}
// otherwise a connected component exist and we have marked it
for(int i=0;i<n;i++){
if(vis[i]==0 and adj[i].size()>1){
// if any node that is not part of the connected component
// and has an edge is found then this is not a eulerian graph
// not even semi eulerian graph
cout<<i<<" "<<adj[i].size()<<endl;
return 1;
}
}
return 0;
}
int eulerGraphType(vvi &adj){
int n=adj.size();
// first we need to check if all the nodes that have degree
// greater than 1 lie in the same connected component
if(multiConnectedGraph(adj)){
cout<<"multiple connected graph"<<endl;
return 0;
}
// now graph only has a single connected component
// in which degree are greater than 1
// rest all the nodes of the graph have degree equal to 0
// now we check the nodes in the connected component
// that is how many of the nodes have degree as odd
int oddDegCnt=0;
for(int i=0;i<n;i++){
if(adj[i].size()&1){
oddDegCnt++;
}
}
if(oddDegCnt>2){
// not a euler and not a semi euler graph
return 0;
}
if(oddDegCnt==2){
// a semi euler graph
printEuler(adj);
cout<<endl;
return 1;
}
printEuler(adj);
cout<<endl;
return 2;
}
int main(){
int n,m;
cin>>n>>m;
vvi adj(n);
int u,v;
vi temp(3);
for(int i=0;i<m;i++){
cin>>u>>v;
adj[u].push_back(v);
adj[v].push_back(u);
}
cout<<"prinitng the graph\n";
for(int i=0;i<n;i++){
for(auto x:adj[i]){
cout<<i<<" "<<x<<endl;
}
}
int graph_type=eulerGraphType(adj);
if(graph_type==0){
cout<<"graph is not a euler graph"<<endl;
}
else if(graph_type==1){
cout<<"graph is a semi eulerian graph"<<endl;
}
else{
cout<<"euler graph"<<endl;
}
return 0;
}
|
98c855d002d722cd7410be986c5c113d93d61096
|
846d0d840f789e721c5a90ec455f5bf4f0ca143e
|
/intro/read2numbers.cpp
|
6e6933584d6ced4c06bea02fb67acdaf9cebad37
|
[] |
no_license
|
CubeSolver25/cPlusPlusChallenges
|
2e2c56dd880bd8c8b536b720567195d4287c19d8
|
4037d1114b7668fa046f761fd3dcb8dcad8258cb
|
refs/heads/master
| 2020-04-22T01:48:49.464069
| 2019-05-05T22:59:01
| 2019-05-05T22:59:01
| 170,025,842
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 799
|
cpp
|
read2numbers.cpp
|
#include <iostream>
int main() {
int num1, num2;
double dnum1, dnum2;
std::string str;
num1 = 101000;
num2 = 100101001;
dnum1 = 978487934798;
dnum2 = 74334739897879324;
str = "8478676768746666746676268686863286489689798969678986767886725687697543678936678568959769786567896789569875786767889f56738uytr8eufiogdyiehurwjskfdyhiouqwjesyf8ouijq45whegrsutiuroeghu8oitjrgkfhduoijfdh8uoijt34yre7908u45ioweyrhouijtheriujo4w5hrfuijohesrfuidojkh3reuiojkmht3riueojsklhsupijah8quoijshe8oiu34wjeyh873u4iwojehij3o4kmwh379u4iowjhredsjkmghbirejkdhuncyhpuweijrsy78huiy47weiuskdhkjclwhesijdkf";
std::cout << num1+num2 << std::endl;
std::cout << dnum1+dnum2 << std::endl;
std::cout << str << std::endl;
std::cin >> num1;
std::cin >> num2;
std::cout << num1+num2 << std::endl;
}
|
e9f171686c172f0ce55f9d3e4205c05fb0354ac8
|
f3775d1d7d454fd5e16adbf2bf0b0aaa89e491b5
|
/testHeaderFiles/tetsHeaderFiles.cpp
|
bcfee582dbded3daee832c13e9d6e215534e50b7
|
[] |
no_license
|
foocoder/TestCPP
|
7db2c4863fd8eb0bcdd940643022720632f08e23
|
5e7b02c01c31ed164a99862fe7e53c97696e9016
|
refs/heads/master
| 2021-01-23T12:46:56.034797
| 2017-09-11T15:19:49
| 2017-09-11T15:19:49
| 53,111,383
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 435
|
cpp
|
tetsHeaderFiles.cpp
|
// ---- Program Info Start----
//FileName: tetsHeaderFiles.cpp
//
//Author: Fuchen Duan
//
//Email: slow295185031@gmail.com
//
//CreatedAt: 2016-03-22 10:51:46
// ---- Program Info End ----
#include <iostream>
#include "tetsHeaderFiles.h"
#include "tetsHeaderFiles1.h"
using namespace std;
int foo(int a){
return a;
}
int main(int argc, char *argv[])
{
cout<<foo(1);
cout<<seq_cnt;
return 0;
}
|
ebd2f6500683ab12782996efd96bfa535efe802d
|
e5ae07079109b03e1e421bfeae901e9ba82773c9
|
/src/mempool/mempoolcomponent.h
|
470a80d9554cb5a53606dd4faca2f4ac7906083b
|
[
"MIT"
] |
permissive
|
bluesnowcandy/SuperBitcoin
|
e3dc180811415dc0d172a874b7d4972e5be61293
|
94097096b3e2c2934e99ac05a7e218776651eb1a
|
refs/heads/master
| 2020-03-21T22:32:15.761337
| 2018-06-23T07:17:13
| 2018-06-23T07:17:13
| 139,132,849
| 1
| 0
| null | 2018-06-29T09:55:09
| 2018-06-29T09:55:08
| null |
UTF-8
|
C++
| false
| false
| 1,706
|
h
|
mempoolcomponent.h
|
///////////////////////////////////////////////////////////
// mempoolcomponent.h
// Created on: 7-3-2018 16:40:57
// Original author: marco
///////////////////////////////////////////////////////////
#pragma once
#include <stdint.h>
#include <log4cpp/Category.hh>
#include "util.h"
#include "interface/imempoolcomponent.h"
#include "orphantx.h"
#include "txmempool.h"
class CMempoolComponent : public ITxMempoolComponent
{
public:
CMempoolComponent();
~CMempoolComponent();
bool ComponentInitialize() override;
bool ComponentStartup() override;
bool ComponentShutdown() override;
CTxMemPool &GetMemPool() override;
bool DoesTxExist(uint256 txHash) override;
unsigned int GetTransactionsUpdated() const override;
bool NetRequestTxData(ExNode *xnode, uint256 txHash, bool witness, int64_t timeLastMempoolReq) override;
bool NetReceiveTxData(ExNode *xnode, CDataStream &stream, uint256 &txHash) override;
bool NetRequestTxInventory(ExNode *xnode, bool sendMempool, int64_t minFeeFilter, CBloomFilter *txFilter,
std::vector<uint256> &toSendTxHashes, std::vector<uint256> &haveSentTxHashes) override;
bool RemoveOrphanTxForNode(int64_t nodeId) override;
bool RemoveOrphanTxForBlock(const CBlock *pblock) override;
private:
void InitializeForNet();
CTxMemPool mempool;
COrphanTxMgr orphanTxMgr;
CCriticalSection cs;
bool bFeeEstimatesInitialized = false;
bool bDumpMempoolLater = false;
/** Dump the mempool to disk. */
void DumpMempool();
/** Load the mempool from disk. */
bool LoadMempool();
void InitFeeEstimate();
void FlushFeeEstimate();
};
|
b4c22d316237b43a55ef7d4eeb91b3b51a269d10
|
cfa0d73422fc32c12f8bade7355a68e0fd0581d9
|
/week_6_2/1/test.cpp
|
d75b5fbaa0f0ff173835ee582a11e1abb664ef0e
|
[] |
no_license
|
wususu/cpp-assignment
|
2abb216fbc4dbfeb88b553efe58b5a6a596b4c00
|
ee2ef5bffb292dca314d14f524c4dea97740b433
|
refs/heads/master
| 2021-09-02T10:45:22.715833
| 2018-01-02T01:48:05
| 2018-01-02T01:48:05
| 104,063,655
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 220
|
cpp
|
test.cpp
|
#include <iostream>
#include "golf.h"
int main()
{
golf user[10];
for(int i=0; i<10; i++)
{
setgolf(user[i]);
}
for(int i=0; i<10; i++)
{
showgolf(user[i]);
}
return 0;
}
|
12c445850e11322aa26d60f8405213029dbf5e57
|
7c4704d447dfd4c98e79045276f843e8272cff06
|
/abc46/a.cpp
|
1bf70882ac732a8c5c405a5bddbc726eca1b71e6
|
[] |
no_license
|
ratea/abc
|
63f30cc5c362609c33cac9cebf12125e89dc656c
|
66ea8922587bf994c206c7d0bc91290157530c8c
|
refs/heads/master
| 2021-01-20T09:06:53.089128
| 2018-01-24T20:34:04
| 2018-01-24T20:34:04
| 90,221,158
| 0
| 1
| null | 2017-05-07T14:49:51
| 2017-05-04T04:20:27
|
C++
|
UTF-8
|
C++
| false
| false
| 206
|
cpp
|
a.cpp
|
#include<iostream>
using namespace std;
int main(){
int a,b,c;
cin>>a>>b>>c;
int ans = 3;
if(a==b)ans--;
if(c==b)ans--;
if(a==c)ans--;
if(ans==0)ans=1;
cout<<ans<<endl;
return 0;
}
|
c021a29a52e15afdb00fe7c672c20ff5977702a9
|
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
|
/3rdParty/V8/v7.9.317/src/builtins/builtins-microtask-queue-gen.cc
|
62aee3b300b37184426f746b5d02e1d18a49d58b
|
[
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"Zlib",
"GPL-1.0-or-later",
"OpenSSL",
"ISC",
"LicenseRef-scancode-gutenberg-2020",
"MIT",
"GPL-2.0-only",
"CC0-1.0",
"BSL-1.0",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"Bison-exception-2.2",
"LicenseRef-scancode-public-domain",
"JSON",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Unlicense",
"BSD-4-Clause",
"Python-2.0",
"LGPL-2.1-or-later",
"bzip2-1.0.6",
"SunPro"
] |
permissive
|
arangodb/arangodb
|
0980625e76c56a2449d90dcb8d8f2c485e28a83b
|
43c40535cee37fc7349a21793dc33b1833735af5
|
refs/heads/devel
| 2023-08-31T09:34:47.451950
| 2023-08-31T07:25:02
| 2023-08-31T07:25:02
| 2,649,214
| 13,385
| 982
|
Apache-2.0
| 2023-09-14T17:02:16
| 2011-10-26T06:42:00
|
C++
|
UTF-8
|
C++
| false
| false
| 21,855
|
cc
|
builtins-microtask-queue-gen.cc
|
// Copyright 2018 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/api/api.h"
#include "src/builtins/builtins-utils-gen.h"
#include "src/codegen/code-stub-assembler.h"
#include "src/execution/microtask-queue.h"
#include "src/objects/js-weak-refs.h"
#include "src/objects/microtask-inl.h"
#include "src/objects/promise.h"
#include "src/objects/smi-inl.h"
namespace v8 {
namespace internal {
class MicrotaskQueueBuiltinsAssembler : public CodeStubAssembler {
public:
explicit MicrotaskQueueBuiltinsAssembler(compiler::CodeAssemblerState* state)
: CodeStubAssembler(state) {}
TNode<RawPtrT> GetMicrotaskQueue(TNode<Context> context);
TNode<RawPtrT> GetMicrotaskRingBuffer(TNode<RawPtrT> microtask_queue);
TNode<IntPtrT> GetMicrotaskQueueCapacity(TNode<RawPtrT> microtask_queue);
TNode<IntPtrT> GetMicrotaskQueueSize(TNode<RawPtrT> microtask_queue);
void SetMicrotaskQueueSize(TNode<RawPtrT> microtask_queue,
TNode<IntPtrT> new_size);
TNode<IntPtrT> GetMicrotaskQueueStart(TNode<RawPtrT> microtask_queue);
void SetMicrotaskQueueStart(TNode<RawPtrT> microtask_queue,
TNode<IntPtrT> new_start);
TNode<IntPtrT> CalculateRingBufferOffset(TNode<IntPtrT> capacity,
TNode<IntPtrT> start,
TNode<IntPtrT> index);
void PrepareForContext(TNode<Context> microtask_context, Label* bailout);
void RunSingleMicrotask(TNode<Context> current_context,
TNode<Microtask> microtask);
void IncrementFinishedMicrotaskCount(TNode<RawPtrT> microtask_queue);
TNode<Context> GetCurrentContext();
void SetCurrentContext(TNode<Context> context);
TNode<IntPtrT> GetEnteredContextCount();
void EnterMicrotaskContext(TNode<Context> native_context);
void RewindEnteredContext(TNode<IntPtrT> saved_entered_context_count);
void RunPromiseHook(Runtime::FunctionId id, TNode<Context> context,
SloppyTNode<HeapObject> promise_or_capability);
};
TNode<RawPtrT> MicrotaskQueueBuiltinsAssembler::GetMicrotaskQueue(
TNode<Context> native_context) {
CSA_ASSERT(this, IsNativeContext(native_context));
return LoadObjectField<RawPtrT>(native_context,
NativeContext::kMicrotaskQueueOffset);
}
TNode<RawPtrT> MicrotaskQueueBuiltinsAssembler::GetMicrotaskRingBuffer(
TNode<RawPtrT> microtask_queue) {
return Load<RawPtrT>(microtask_queue,
IntPtrConstant(MicrotaskQueue::kRingBufferOffset));
}
TNode<IntPtrT> MicrotaskQueueBuiltinsAssembler::GetMicrotaskQueueCapacity(
TNode<RawPtrT> microtask_queue) {
return Load<IntPtrT>(microtask_queue,
IntPtrConstant(MicrotaskQueue::kCapacityOffset));
}
TNode<IntPtrT> MicrotaskQueueBuiltinsAssembler::GetMicrotaskQueueSize(
TNode<RawPtrT> microtask_queue) {
return Load<IntPtrT>(microtask_queue,
IntPtrConstant(MicrotaskQueue::kSizeOffset));
}
void MicrotaskQueueBuiltinsAssembler::SetMicrotaskQueueSize(
TNode<RawPtrT> microtask_queue, TNode<IntPtrT> new_size) {
StoreNoWriteBarrier(MachineType::PointerRepresentation(), microtask_queue,
IntPtrConstant(MicrotaskQueue::kSizeOffset), new_size);
}
TNode<IntPtrT> MicrotaskQueueBuiltinsAssembler::GetMicrotaskQueueStart(
TNode<RawPtrT> microtask_queue) {
return Load<IntPtrT>(microtask_queue,
IntPtrConstant(MicrotaskQueue::kStartOffset));
}
void MicrotaskQueueBuiltinsAssembler::SetMicrotaskQueueStart(
TNode<RawPtrT> microtask_queue, TNode<IntPtrT> new_start) {
StoreNoWriteBarrier(MachineType::PointerRepresentation(), microtask_queue,
IntPtrConstant(MicrotaskQueue::kStartOffset), new_start);
}
TNode<IntPtrT> MicrotaskQueueBuiltinsAssembler::CalculateRingBufferOffset(
TNode<IntPtrT> capacity, TNode<IntPtrT> start, TNode<IntPtrT> index) {
return TimesSystemPointerSize(
WordAnd(IntPtrAdd(start, index), IntPtrSub(capacity, IntPtrConstant(1))));
}
void MicrotaskQueueBuiltinsAssembler::PrepareForContext(
TNode<Context> native_context, Label* bailout) {
CSA_ASSERT(this, IsNativeContext(native_context));
// Skip the microtask execution if the associated context is shutdown.
GotoIf(WordEqual(GetMicrotaskQueue(native_context), IntPtrConstant(0)),
bailout);
EnterMicrotaskContext(native_context);
SetCurrentContext(native_context);
}
void MicrotaskQueueBuiltinsAssembler::RunSingleMicrotask(
TNode<Context> current_context, TNode<Microtask> microtask) {
CSA_ASSERT(this, TaggedIsNotSmi(microtask));
StoreRoot(RootIndex::kCurrentMicrotask, microtask);
TNode<IntPtrT> saved_entered_context_count = GetEnteredContextCount();
TNode<Map> microtask_map = LoadMap(microtask);
TNode<Uint16T> microtask_type = LoadMapInstanceType(microtask_map);
TVARIABLE(HeapObject, var_exception, TheHoleConstant());
Label if_exception(this, Label::kDeferred);
Label is_callable(this), is_callback(this),
is_promise_fulfill_reaction_job(this),
is_promise_reject_reaction_job(this),
is_promise_resolve_thenable_job(this),
is_unreachable(this, Label::kDeferred), done(this);
int32_t case_values[] = {CALLABLE_TASK_TYPE, CALLBACK_TASK_TYPE,
PROMISE_FULFILL_REACTION_JOB_TASK_TYPE,
PROMISE_REJECT_REACTION_JOB_TASK_TYPE,
PROMISE_RESOLVE_THENABLE_JOB_TASK_TYPE};
Label* case_labels[] = {
&is_callable, &is_callback, &is_promise_fulfill_reaction_job,
&is_promise_reject_reaction_job, &is_promise_resolve_thenable_job};
static_assert(arraysize(case_values) == arraysize(case_labels), "");
Switch(microtask_type, &is_unreachable, case_values, case_labels,
arraysize(case_labels));
BIND(&is_callable);
{
// Enter the context of the {microtask}.
TNode<Context> microtask_context =
LoadObjectField<Context>(microtask, CallableTask::kContextOffset);
TNode<NativeContext> native_context = LoadNativeContext(microtask_context);
PrepareForContext(native_context, &done);
TNode<JSReceiver> callable =
LoadObjectField<JSReceiver>(microtask, CallableTask::kCallableOffset);
Node* const result = CallJS(
CodeFactory::Call(isolate(), ConvertReceiverMode::kNullOrUndefined),
microtask_context, callable, UndefinedConstant());
GotoIfException(result, &if_exception, &var_exception);
RewindEnteredContext(saved_entered_context_count);
SetCurrentContext(current_context);
Goto(&done);
}
BIND(&is_callback);
{
TNode<Object> const microtask_callback =
LoadObjectField(microtask, CallbackTask::kCallbackOffset);
TNode<Object> const microtask_data =
LoadObjectField(microtask, CallbackTask::kDataOffset);
// If this turns out to become a bottleneck because of the calls
// to C++ via CEntry, we can choose to speed them up using a
// similar mechanism that we use for the CallApiFunction stub,
// except that calling the MicrotaskCallback is even easier, since
// it doesn't accept any tagged parameters, doesn't return a value
// and ignores exceptions.
//
// But from our current measurements it doesn't seem to be a
// serious performance problem, even if the microtask is full
// of CallHandlerTasks (which is not a realistic use case anyways).
TNode<Object> const result =
CallRuntime(Runtime::kRunMicrotaskCallback, current_context,
microtask_callback, microtask_data);
GotoIfException(result, &if_exception, &var_exception);
Goto(&done);
}
BIND(&is_promise_resolve_thenable_job);
{
// Enter the context of the {microtask}.
TNode<Context> microtask_context = LoadObjectField<Context>(
microtask, PromiseResolveThenableJobTask::kContextOffset);
TNode<NativeContext> native_context = LoadNativeContext(microtask_context);
PrepareForContext(native_context, &done);
TNode<Object> const promise_to_resolve = LoadObjectField(
microtask, PromiseResolveThenableJobTask::kPromiseToResolveOffset);
TNode<Object> const then =
LoadObjectField(microtask, PromiseResolveThenableJobTask::kThenOffset);
TNode<Object> const thenable = LoadObjectField(
microtask, PromiseResolveThenableJobTask::kThenableOffset);
TNode<Object> const result =
CallBuiltin(Builtins::kPromiseResolveThenableJob, native_context,
promise_to_resolve, thenable, then);
GotoIfException(result, &if_exception, &var_exception);
RewindEnteredContext(saved_entered_context_count);
SetCurrentContext(current_context);
Goto(&done);
}
BIND(&is_promise_fulfill_reaction_job);
{
// Enter the context of the {microtask}.
TNode<Context> microtask_context = LoadObjectField<Context>(
microtask, PromiseReactionJobTask::kContextOffset);
TNode<NativeContext> native_context = LoadNativeContext(microtask_context);
PrepareForContext(native_context, &done);
TNode<Object> const argument =
LoadObjectField(microtask, PromiseReactionJobTask::kArgumentOffset);
TNode<Object> const handler =
LoadObjectField(microtask, PromiseReactionJobTask::kHandlerOffset);
TNode<HeapObject> const promise_or_capability = CAST(LoadObjectField(
microtask, PromiseReactionJobTask::kPromiseOrCapabilityOffset));
// Run the promise before/debug hook if enabled.
RunPromiseHook(Runtime::kPromiseHookBefore, microtask_context,
promise_or_capability);
TNode<Object> const result =
CallBuiltin(Builtins::kPromiseFulfillReactionJob, microtask_context,
argument, handler, promise_or_capability);
GotoIfException(result, &if_exception, &var_exception);
// Run the promise after/debug hook if enabled.
RunPromiseHook(Runtime::kPromiseHookAfter, microtask_context,
promise_or_capability);
RewindEnteredContext(saved_entered_context_count);
SetCurrentContext(current_context);
Goto(&done);
}
BIND(&is_promise_reject_reaction_job);
{
// Enter the context of the {microtask}.
TNode<Context> microtask_context = LoadObjectField<Context>(
microtask, PromiseReactionJobTask::kContextOffset);
TNode<NativeContext> native_context = LoadNativeContext(microtask_context);
PrepareForContext(native_context, &done);
TNode<Object> const argument =
LoadObjectField(microtask, PromiseReactionJobTask::kArgumentOffset);
TNode<Object> const handler =
LoadObjectField(microtask, PromiseReactionJobTask::kHandlerOffset);
TNode<HeapObject> const promise_or_capability = CAST(LoadObjectField(
microtask, PromiseReactionJobTask::kPromiseOrCapabilityOffset));
// Run the promise before/debug hook if enabled.
RunPromiseHook(Runtime::kPromiseHookBefore, microtask_context,
promise_or_capability);
TNode<Object> const result =
CallBuiltin(Builtins::kPromiseRejectReactionJob, microtask_context,
argument, handler, promise_or_capability);
GotoIfException(result, &if_exception, &var_exception);
// Run the promise after/debug hook if enabled.
RunPromiseHook(Runtime::kPromiseHookAfter, microtask_context,
promise_or_capability);
RewindEnteredContext(saved_entered_context_count);
SetCurrentContext(current_context);
Goto(&done);
}
BIND(&is_unreachable);
Unreachable();
BIND(&if_exception);
{
// Report unhandled exceptions from microtasks.
CallRuntime(Runtime::kReportMessage, current_context,
var_exception.value());
RewindEnteredContext(saved_entered_context_count);
SetCurrentContext(current_context);
Goto(&done);
}
BIND(&done);
}
void MicrotaskQueueBuiltinsAssembler::IncrementFinishedMicrotaskCount(
TNode<RawPtrT> microtask_queue) {
TNode<IntPtrT> count = Load<IntPtrT>(
microtask_queue,
IntPtrConstant(MicrotaskQueue::kFinishedMicrotaskCountOffset));
TNode<IntPtrT> new_count = IntPtrAdd(count, IntPtrConstant(1));
StoreNoWriteBarrier(
MachineType::PointerRepresentation(), microtask_queue,
IntPtrConstant(MicrotaskQueue::kFinishedMicrotaskCountOffset), new_count);
}
TNode<Context> MicrotaskQueueBuiltinsAssembler::GetCurrentContext() {
auto ref = ExternalReference::Create(kContextAddress, isolate());
// TODO(delphick): Add a checked cast. For now this is not possible as context
// can actually be Smi(0).
return TNode<Context>::UncheckedCast(LoadFullTagged(ExternalConstant(ref)));
}
void MicrotaskQueueBuiltinsAssembler::SetCurrentContext(
TNode<Context> context) {
auto ref = ExternalReference::Create(kContextAddress, isolate());
StoreFullTaggedNoWriteBarrier(ExternalConstant(ref), context);
}
TNode<IntPtrT> MicrotaskQueueBuiltinsAssembler::GetEnteredContextCount() {
auto ref = ExternalReference::handle_scope_implementer_address(isolate());
TNode<RawPtrT> hsi = Load<RawPtrT>(ExternalConstant(ref));
using ContextStack = DetachableVector<Context>;
TNode<IntPtrT> size_offset =
IntPtrConstant(HandleScopeImplementer::kEnteredContextsOffset +
ContextStack::kSizeOffset);
return Load<IntPtrT>(hsi, size_offset);
}
void MicrotaskQueueBuiltinsAssembler::EnterMicrotaskContext(
TNode<Context> native_context) {
CSA_ASSERT(this, IsNativeContext(native_context));
auto ref = ExternalReference::handle_scope_implementer_address(isolate());
TNode<RawPtrT> hsi = Load<RawPtrT>(ExternalConstant(ref));
using ContextStack = DetachableVector<Context>;
TNode<IntPtrT> capacity_offset =
IntPtrConstant(HandleScopeImplementer::kEnteredContextsOffset +
ContextStack::kCapacityOffset);
TNode<IntPtrT> size_offset =
IntPtrConstant(HandleScopeImplementer::kEnteredContextsOffset +
ContextStack::kSizeOffset);
TNode<IntPtrT> capacity = Load<IntPtrT>(hsi, capacity_offset);
TNode<IntPtrT> size = Load<IntPtrT>(hsi, size_offset);
Label if_append(this), if_grow(this, Label::kDeferred), done(this);
Branch(WordEqual(size, capacity), &if_grow, &if_append);
BIND(&if_append);
{
TNode<IntPtrT> data_offset =
IntPtrConstant(HandleScopeImplementer::kEnteredContextsOffset +
ContextStack::kDataOffset);
TNode<RawPtrT> data = Load<RawPtrT>(hsi, data_offset);
StoreFullTaggedNoWriteBarrier(data, TimesSystemPointerSize(size),
native_context);
TNode<IntPtrT> new_size = IntPtrAdd(size, IntPtrConstant(1));
StoreNoWriteBarrier(MachineType::PointerRepresentation(), hsi, size_offset,
new_size);
using FlagStack = DetachableVector<int8_t>;
TNode<IntPtrT> flag_data_offset =
IntPtrConstant(HandleScopeImplementer::kIsMicrotaskContextOffset +
FlagStack::kDataOffset);
TNode<RawPtrT> flag_data = Load<RawPtrT>(hsi, flag_data_offset);
StoreNoWriteBarrier(MachineRepresentation::kWord8, flag_data, size,
BoolConstant(true));
StoreNoWriteBarrier(
MachineType::PointerRepresentation(), hsi,
IntPtrConstant(HandleScopeImplementer::kIsMicrotaskContextOffset +
FlagStack::kSizeOffset),
new_size);
Goto(&done);
}
BIND(&if_grow);
{
TNode<ExternalReference> function =
ExternalConstant(ExternalReference::call_enter_context_function());
CallCFunction(function, MachineType::Int32(),
std::make_pair(MachineType::Pointer(), hsi),
std::make_pair(MachineType::Pointer(),
BitcastTaggedToWord(native_context)));
Goto(&done);
}
BIND(&done);
}
void MicrotaskQueueBuiltinsAssembler::RewindEnteredContext(
TNode<IntPtrT> saved_entered_context_count) {
auto ref = ExternalReference::handle_scope_implementer_address(isolate());
TNode<RawPtrT> hsi = Load<RawPtrT>(ExternalConstant(ref));
using ContextStack = DetachableVector<Context>;
TNode<IntPtrT> size_offset =
IntPtrConstant(HandleScopeImplementer::kEnteredContextsOffset +
ContextStack::kSizeOffset);
#ifdef ENABLE_VERIFY_CSA
TNode<IntPtrT> size = Load<IntPtrT>(hsi, size_offset);
CSA_ASSERT(this, IntPtrLessThan(IntPtrConstant(0), size));
CSA_ASSERT(this, IntPtrLessThanOrEqual(saved_entered_context_count, size));
#endif
StoreNoWriteBarrier(MachineType::PointerRepresentation(), hsi, size_offset,
saved_entered_context_count);
using FlagStack = DetachableVector<int8_t>;
StoreNoWriteBarrier(
MachineType::PointerRepresentation(), hsi,
IntPtrConstant(HandleScopeImplementer::kIsMicrotaskContextOffset +
FlagStack::kSizeOffset),
saved_entered_context_count);
}
void MicrotaskQueueBuiltinsAssembler::RunPromiseHook(
Runtime::FunctionId id, TNode<Context> context,
SloppyTNode<HeapObject> promise_or_capability) {
Label hook(this, Label::kDeferred), done_hook(this);
Branch(IsPromiseHookEnabledOrDebugIsActiveOrHasAsyncEventDelegate(), &hook,
&done_hook);
BIND(&hook);
{
// Get to the underlying JSPromise instance.
TNode<HeapObject> promise = Select<HeapObject>(
IsPromiseCapability(promise_or_capability),
[=] {
return CAST(LoadObjectField(promise_or_capability,
PromiseCapability::kPromiseOffset));
},
[=] { return promise_or_capability; });
GotoIf(IsUndefined(promise), &done_hook);
CallRuntime(id, context, promise);
Goto(&done_hook);
}
BIND(&done_hook);
}
TF_BUILTIN(EnqueueMicrotask, MicrotaskQueueBuiltinsAssembler) {
TNode<Microtask> microtask = CAST(Parameter(Descriptor::kMicrotask));
TNode<Context> context = CAST(Parameter(Descriptor::kContext));
TNode<NativeContext> native_context = LoadNativeContext(context);
TNode<RawPtrT> microtask_queue = GetMicrotaskQueue(native_context);
// Do not store the microtask if MicrotaskQueue is not available, that may
// happen when the context shutdown.
Label if_shutdown(this, Label::kDeferred);
GotoIf(WordEqual(microtask_queue, IntPtrConstant(0)), &if_shutdown);
TNode<RawPtrT> ring_buffer = GetMicrotaskRingBuffer(microtask_queue);
TNode<IntPtrT> capacity = GetMicrotaskQueueCapacity(microtask_queue);
TNode<IntPtrT> size = GetMicrotaskQueueSize(microtask_queue);
TNode<IntPtrT> start = GetMicrotaskQueueStart(microtask_queue);
Label if_grow(this, Label::kDeferred);
GotoIf(IntPtrEqual(size, capacity), &if_grow);
// |microtask_queue| has an unused slot to store |microtask|.
{
StoreNoWriteBarrier(MachineType::PointerRepresentation(), ring_buffer,
CalculateRingBufferOffset(capacity, start, size),
BitcastTaggedToWord(microtask));
StoreNoWriteBarrier(MachineType::PointerRepresentation(), microtask_queue,
IntPtrConstant(MicrotaskQueue::kSizeOffset),
IntPtrAdd(size, IntPtrConstant(1)));
Return(UndefinedConstant());
}
// |microtask_queue| has no space to store |microtask|. Fall back to C++
// implementation to grow the buffer.
BIND(&if_grow);
{
TNode<ExternalReference> isolate_constant =
ExternalConstant(ExternalReference::isolate_address(isolate()));
TNode<ExternalReference> function =
ExternalConstant(ExternalReference::call_enqueue_microtask_function());
CallCFunction(function, MachineType::AnyTagged(),
std::make_pair(MachineType::Pointer(), isolate_constant),
std::make_pair(MachineType::IntPtr(), microtask_queue),
std::make_pair(MachineType::AnyTagged(), microtask));
Return(UndefinedConstant());
}
Bind(&if_shutdown);
Return(UndefinedConstant());
}
TF_BUILTIN(RunMicrotasks, MicrotaskQueueBuiltinsAssembler) {
// Load the current context from the isolate.
TNode<Context> current_context = GetCurrentContext();
TNode<RawPtrT> microtask_queue =
UncheckedCast<RawPtrT>(Parameter(Descriptor::kMicrotaskQueue));
Label loop(this), done(this);
Goto(&loop);
BIND(&loop);
TNode<IntPtrT> size = GetMicrotaskQueueSize(microtask_queue);
// Exit if the queue is empty.
GotoIf(WordEqual(size, IntPtrConstant(0)), &done);
TNode<RawPtrT> ring_buffer = GetMicrotaskRingBuffer(microtask_queue);
TNode<IntPtrT> capacity = GetMicrotaskQueueCapacity(microtask_queue);
TNode<IntPtrT> start = GetMicrotaskQueueStart(microtask_queue);
TNode<IntPtrT> offset =
CalculateRingBufferOffset(capacity, start, IntPtrConstant(0));
TNode<RawPtrT> microtask_pointer = Load<RawPtrT>(ring_buffer, offset);
TNode<Microtask> microtask = CAST(BitcastWordToTagged(microtask_pointer));
TNode<IntPtrT> new_size = IntPtrSub(size, IntPtrConstant(1));
TNode<IntPtrT> new_start = WordAnd(IntPtrAdd(start, IntPtrConstant(1)),
IntPtrSub(capacity, IntPtrConstant(1)));
// Remove |microtask| from |ring_buffer| before running it, since its
// invocation may add another microtask into |ring_buffer|.
SetMicrotaskQueueSize(microtask_queue, new_size);
SetMicrotaskQueueStart(microtask_queue, new_start);
RunSingleMicrotask(current_context, microtask);
IncrementFinishedMicrotaskCount(microtask_queue);
Goto(&loop);
BIND(&done);
{
// Reset the "current microtask" on the isolate.
StoreRoot(RootIndex::kCurrentMicrotask, UndefinedConstant());
Return(UndefinedConstant());
}
}
} // namespace internal
} // namespace v8
|
8de1ed68016bd1d9bfde3cba317919d7f49eca8a
|
1d40d80e75e4a1529f50e7a2bc8bf396281d24c1
|
/src/kbookmarkmanager.cpp
|
56d6acc1d65bbc47e00f59e5cf0c78a0aa21dbdd
|
[] |
no_license
|
KDE/kbookmarks
|
1d884764b369b26ae924d7b93a9152cf4fcd88f7
|
e5daf758f056bf020a699b5de3fb8a8612173b82
|
refs/heads/master
| 2023-09-03T18:13:31.154655
| 2023-09-03T02:53:09
| 2023-09-03T02:53:09
| 42,732,619
| 8
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,916
|
cpp
|
kbookmarkmanager.cpp
|
// -*- c-basic-offset:4; indent-tabs-mode:nil -*-
/*
This file is part of the KDE libraries
SPDX-FileCopyrightText: 2000 David Faure <faure@kde.org>
SPDX-FileCopyrightText: 2003 Alexander Kellett <lypanov@kde.org>
SPDX-FileCopyrightText: 2008 Norbert Frese <nf2@scheinwelt.at>
SPDX-License-Identifier: LGPL-2.0-only
*/
#include "kbookmarkmanager.h"
#include "kbookmarkmenu_p.h"
#include "kbookmarks_debug.h"
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QMessageBox>
#include <QProcess>
#include <QReadWriteLock>
#include <QRegularExpression>
#include <QTextStream>
#include <QThread>
#include <KBackup>
#include <KConfig>
#include <KConfigGroup>
#include <KDirWatch>
#include <QSaveFile>
#include <QStandardPaths>
namespace
{
namespace Strings
{
QString piData()
{
return QStringLiteral("version=\"1.0\" encoding=\"UTF-8\"");
}
}
}
class KBookmarkManagerList : public QList<KBookmarkManager *>
{
public:
KBookmarkManagerList();
~KBookmarkManagerList()
{
cleanup();
}
void cleanup()
{
QList<KBookmarkManager *> copy = *this;
qDeleteAll(copy); // auto-delete functionality
clear();
}
QReadWriteLock lock;
};
Q_GLOBAL_STATIC(KBookmarkManagerList, s_pSelf)
KBookmarkManagerList::KBookmarkManagerList()
{
if (s_pSelf.exists()) {
s_pSelf->cleanup();
}
}
class KBookmarkMap : private KBookmarkGroupTraverser
{
public:
KBookmarkMap()
: m_mapNeedsUpdate(true)
{
}
void setNeedsUpdate()
{
m_mapNeedsUpdate = true;
}
void update(KBookmarkManager *);
QList<KBookmark> find(const QString &url) const
{
return m_bk_map.value(url);
}
private:
void visit(const KBookmark &) override;
void visitEnter(const KBookmarkGroup &) override
{
;
}
void visitLeave(const KBookmarkGroup &) override
{
;
}
private:
typedef QList<KBookmark> KBookmarkList;
QMap<QString, KBookmarkList> m_bk_map;
bool m_mapNeedsUpdate;
};
void KBookmarkMap::update(KBookmarkManager *manager)
{
if (m_mapNeedsUpdate) {
m_mapNeedsUpdate = false;
m_bk_map.clear();
KBookmarkGroup root = manager->root();
traverse(root);
}
}
void KBookmarkMap::visit(const KBookmark &bk)
{
if (!bk.isSeparator()) {
// add bookmark to url map
m_bk_map[bk.internalElement().attribute(QStringLiteral("href"))].append(bk);
}
}
// #########################
// KBookmarkManagerPrivate
class KBookmarkManagerPrivate
{
public:
KBookmarkManagerPrivate(bool bDocIsloaded)
: m_doc(QStringLiteral("xbel"))
, m_docIsLoaded(bDocIsloaded)
, m_update(false)
, m_dialogAllowed(true)
, m_dialogParent(nullptr)
, m_dirWatch(nullptr)
{
}
mutable QDomDocument m_doc;
mutable QDomDocument m_toolbarDoc;
QString m_bookmarksFile;
mutable bool m_docIsLoaded;
bool m_update;
bool m_dialogAllowed;
QWidget *m_dialogParent;
KDirWatch *m_dirWatch; // for monitoring changes on bookmark files
KBookmarkMap m_map;
};
// ################
// KBookmarkManager
static KBookmarkManager *lookupExisting(const QString &bookmarksFile)
{
for (KBookmarkManagerList::ConstIterator bmit = s_pSelf()->constBegin(), bmend = s_pSelf()->constEnd(); bmit != bmend; ++bmit) {
if ((*bmit)->path() == bookmarksFile) {
return *bmit;
}
}
return nullptr;
}
KBookmarkManager *KBookmarkManager::managerForFile(const QString &bookmarksFile)
{
KBookmarkManager *mgr(nullptr);
{
QReadLocker readLock(&s_pSelf()->lock);
mgr = lookupExisting(bookmarksFile);
if (mgr) {
return mgr;
}
}
QWriteLocker writeLock(&s_pSelf()->lock);
mgr = lookupExisting(bookmarksFile);
if (mgr) {
return mgr;
}
mgr = new KBookmarkManager(bookmarksFile);
s_pSelf()->append(mgr);
return mgr;
}
static QDomElement createXbelTopLevelElement(QDomDocument &doc)
{
QDomElement topLevel = doc.createElement(QStringLiteral("xbel"));
topLevel.setAttribute(QStringLiteral("xmlns:mime"), QStringLiteral("http://www.freedesktop.org/standards/shared-mime-info"));
topLevel.setAttribute(QStringLiteral("xmlns:bookmark"), QStringLiteral("http://www.freedesktop.org/standards/desktop-bookmarks"));
topLevel.setAttribute(QStringLiteral("xmlns:kdepriv"), QStringLiteral("http://www.kde.org/kdepriv"));
doc.appendChild(topLevel);
doc.insertBefore(doc.createProcessingInstruction(QStringLiteral("xml"), Strings::piData()), topLevel);
return topLevel;
}
KBookmarkManager::KBookmarkManager(const QString &bookmarksFile)
: d(new KBookmarkManagerPrivate(false))
{
d->m_update = true;
Q_ASSERT(!bookmarksFile.isEmpty());
d->m_bookmarksFile = bookmarksFile;
if (!QFile::exists(d->m_bookmarksFile)) {
createXbelTopLevelElement(d->m_doc);
} else {
parse();
}
d->m_docIsLoaded = true;
// start KDirWatch
KDirWatch::self()->addFile(d->m_bookmarksFile);
QObject::connect(KDirWatch::self(), &KDirWatch::dirty, this, &KBookmarkManager::slotFileChanged);
QObject::connect(KDirWatch::self(), &KDirWatch::created, this, &KBookmarkManager::slotFileChanged);
QObject::connect(KDirWatch::self(), &KDirWatch::deleted, this, &KBookmarkManager::slotFileChanged);
// qCDebug(KBOOKMARKS_LOG) << "starting KDirWatch for" << d->m_bookmarksFile;
}
KBookmarkManager::KBookmarkManager()
: d(new KBookmarkManagerPrivate(true))
{
d->m_update = false; // TODO - make it read/write
createXbelTopLevelElement(d->m_doc);
}
void KBookmarkManager::slotFileChanged(const QString &path)
{
if (path == d->m_bookmarksFile) {
// qCDebug(KBOOKMARKS_LOG) << "file changed (KDirWatch) " << path ;
// Reparse
parse();
// Tell our GUI
// (emit where group is "" to directly mark the root menu as dirty)
Q_EMIT changed(QLatin1String(""), QString());
}
}
KBookmarkManager::~KBookmarkManager()
{
if (!s_pSelf.isDestroyed()) {
s_pSelf()->removeAll(this);
}
}
bool KBookmarkManager::autoErrorHandlingEnabled() const
{
return d->m_dialogAllowed;
}
void KBookmarkManager::setAutoErrorHandlingEnabled(bool enable, QWidget *parent)
{
d->m_dialogAllowed = enable;
d->m_dialogParent = parent;
}
void KBookmarkManager::setUpdate(bool update)
{
d->m_update = update;
}
QDomDocument KBookmarkManager::internalDocument() const
{
if (!d->m_docIsLoaded) {
parse();
d->m_toolbarDoc.clear();
}
return d->m_doc;
}
void KBookmarkManager::parse() const
{
d->m_docIsLoaded = true;
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::parse " << d->m_bookmarksFile;
QFile file(d->m_bookmarksFile);
if (!file.open(QIODevice::ReadOnly)) {
qCWarning(KBOOKMARKS_LOG) << "Can't open" << d->m_bookmarksFile;
d->m_doc = QDomDocument(QStringLiteral("xbel"));
createXbelTopLevelElement(d->m_doc);
return;
}
d->m_doc = QDomDocument(QStringLiteral("xbel"));
d->m_doc.setContent(&file);
if (d->m_doc.documentElement().isNull()) {
qCWarning(KBOOKMARKS_LOG) << "KBookmarkManager::parse : main tag is missing, creating default " << d->m_bookmarksFile;
QDomElement element = d->m_doc.createElement(QStringLiteral("xbel"));
d->m_doc.appendChild(element);
}
QDomElement docElem = d->m_doc.documentElement();
QString mainTag = docElem.tagName();
if (mainTag != QLatin1String("xbel")) {
qCWarning(KBOOKMARKS_LOG) << "KBookmarkManager::parse : unknown main tag " << mainTag;
}
QDomNode n = d->m_doc.documentElement().previousSibling();
if (n.isProcessingInstruction()) {
QDomProcessingInstruction pi = n.toProcessingInstruction();
pi.parentNode().removeChild(pi);
}
QDomProcessingInstruction pi;
pi = d->m_doc.createProcessingInstruction(QStringLiteral("xml"), Strings::piData());
d->m_doc.insertBefore(pi, docElem);
file.close();
d->m_map.setNeedsUpdate();
}
bool KBookmarkManager::save(bool toolbarCache) const
{
return saveAs(d->m_bookmarksFile, toolbarCache);
}
bool KBookmarkManager::saveAs(const QString &filename, bool toolbarCache) const
{
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::save " << filename;
// Save the bookmark toolbar folder for quick loading
// but only when it will actually make things quicker
const QString cacheFilename = filename + QLatin1String(".tbcache");
if (toolbarCache && !root().isToolbarGroup()) {
QSaveFile cacheFile(cacheFilename);
if (cacheFile.open(QIODevice::WriteOnly)) {
QString str;
QTextStream stream(&str, QIODevice::WriteOnly);
stream << root().findToolbar();
const QByteArray cstr = str.toUtf8();
cacheFile.write(cstr.data(), cstr.length());
cacheFile.commit();
}
} else { // remove any (now) stale cache
QFile::remove(cacheFilename);
}
// Create parent dirs
QFileInfo info(filename);
QDir().mkpath(info.absolutePath());
QSaveFile file(filename);
if (file.open(QIODevice::WriteOnly)) {
KBackup::simpleBackupFile(file.fileName(), QString(), QStringLiteral(".bak"));
QTextStream stream(&file);
// In Qt6 it's UTF-8 by default
stream << internalDocument().toString();
stream.flush();
if (file.commit()) {
return true;
}
}
static int hadSaveError = false;
if (!hadSaveError) {
QString err = tr("Unable to save bookmarks in %1. Reported error was: %2. "
"This error message will only be shown once. The cause "
"of the error needs to be fixed as quickly as possible, "
"which is most likely a full hard drive.")
.arg(filename, file.errorString());
if (d->m_dialogAllowed && qobject_cast<QApplication *>(qApp) && QThread::currentThread() == qApp->thread()) {
QMessageBox::critical(QApplication::activeWindow(), QApplication::applicationName(), err);
}
qCCritical(KBOOKMARKS_LOG)
<< QStringLiteral("Unable to save bookmarks in %1. File reported the following error-code: %2.").arg(filename).arg(file.error());
Q_EMIT const_cast<KBookmarkManager *>(this)->error(err);
}
hadSaveError = true;
return false;
}
QString KBookmarkManager::path() const
{
return d->m_bookmarksFile;
}
KBookmarkGroup KBookmarkManager::root() const
{
return KBookmarkGroup(internalDocument().documentElement());
}
KBookmarkGroup KBookmarkManager::toolbar()
{
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::toolbar begin";
// Only try to read from a toolbar cache if the full document isn't loaded
if (!d->m_docIsLoaded) {
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::toolbar trying cache";
const QString cacheFilename = d->m_bookmarksFile + QLatin1String(".tbcache");
QFileInfo bmInfo(d->m_bookmarksFile);
QFileInfo cacheInfo(cacheFilename);
if (d->m_toolbarDoc.isNull() && QFile::exists(cacheFilename) && bmInfo.lastModified() < cacheInfo.lastModified()) {
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::toolbar reading file";
QFile file(cacheFilename);
if (file.open(QIODevice::ReadOnly)) {
d->m_toolbarDoc = QDomDocument(QStringLiteral("cache"));
d->m_toolbarDoc.setContent(&file);
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::toolbar opened";
}
}
if (!d->m_toolbarDoc.isNull()) {
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::toolbar returning element";
QDomElement elem = d->m_toolbarDoc.firstChild().toElement();
return KBookmarkGroup(elem);
}
}
// Fallback to the normal way if there is no cache or if the bookmark file
// is already loaded
QDomElement elem = root().findToolbar();
if (elem.isNull()) {
// Root is the bookmark toolbar if none has been set.
// Make it explicit to speed up invocations of findToolbar()
root().internalElement().setAttribute(QStringLiteral("toolbar"), QStringLiteral("yes"));
return root();
} else {
return KBookmarkGroup(elem);
}
}
KBookmark KBookmarkManager::findByAddress(const QString &address)
{
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::findByAddress " << address;
KBookmark result = root();
// The address is something like /5/10/2+
static const QRegularExpression separator(QStringLiteral("[/+]"));
const QStringList addresses = address.split(separator, Qt::SkipEmptyParts);
// qCWarning(KBOOKMARKS_LOG) << addresses.join(",");
for (QStringList::const_iterator it = addresses.begin(); it != addresses.end();) {
bool append = ((*it) == QLatin1String("+"));
uint number = (*it).toUInt();
Q_ASSERT(result.isGroup());
KBookmarkGroup group = result.toGroup();
KBookmark bk = group.first();
KBookmark lbk = bk; // last non-null bookmark
for (uint i = 0; ((i < number) || append) && !bk.isNull(); ++i) {
lbk = bk;
bk = group.next(bk);
// qCWarning(KBOOKMARKS_LOG) << i;
}
it++;
// qCWarning(KBOOKMARKS_LOG) << "found section";
result = bk;
}
if (result.isNull()) {
qCWarning(KBOOKMARKS_LOG) << "KBookmarkManager::findByAddress: couldn't find item " << address;
}
// qCWarning(KBOOKMARKS_LOG) << "found " << result.address();
return result;
}
void KBookmarkManager::emitChanged()
{
emitChanged(root());
}
void KBookmarkManager::emitChanged(const KBookmarkGroup &group)
{
(void)save(); // KDE5 TODO: emitChanged should return a bool? Maybe rename it to saveAndEmitChanged?
// Tell the other processes too
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::emitChanged : broadcasting change " << group.address();
Q_EMIT bookmarksChanged(group.address());
// We do get our own broadcast, so no need for this anymore
// emit changed( group );
}
void KBookmarkManager::emitConfigChanged()
{
Q_EMIT bookmarkConfigChanged();
}
void KBookmarkManager::notifyCompleteChange(const QString &caller) // DBUS call
{
if (!d->m_update) {
return;
}
// qCDebug(KBOOKMARKS_LOG) << "KBookmarkManager::notifyCompleteChange";
// The bk editor tells us we should reload everything
// Reparse
parse();
// Tell our GUI
// (emit where group is "" to directly mark the root menu as dirty)
Q_EMIT changed(QLatin1String(""), caller);
}
///////
bool KBookmarkManager::updateAccessMetadata(const QString &url)
{
d->m_map.update(this);
QList<KBookmark> list = d->m_map.find(url);
if (list.isEmpty()) {
return false;
}
for (QList<KBookmark>::iterator it = list.begin(); it != list.end(); ++it) {
(*it).updateAccessMetadata();
}
return true;
}
KBookmarkSettings *KBookmarkSettings::s_self = nullptr;
void KBookmarkSettings::readSettings()
{
KConfig config(QStringLiteral("kbookmarkrc"), KConfig::NoGlobals);
KConfigGroup cg(&config, "Bookmarks");
// add bookmark dialog usage - no reparse
s_self->m_advancedaddbookmark = cg.readEntry("AdvancedAddBookmarkDialog", false);
// this one alters the menu, therefore it needs a reparse
s_self->m_contextmenu = cg.readEntry("ContextMenuActions", true);
}
KBookmarkSettings *KBookmarkSettings::self()
{
if (!s_self) {
s_self = new KBookmarkSettings;
readSettings();
}
return s_self;
}
#include "moc_kbookmarkmanager.cpp"
|
863a2102125faf7945c448ae8cee98e18a8a95f2
|
e372d895d7a55b9031403ce04822ae1c36ab055f
|
/d06/ex02/Base.class.cpp
|
f23954e4d50add5598f07fe03e917041b9d2402a
|
[] |
no_license
|
maryna-kryshchuk/CPP-Piscine
|
9b74766a5aa31dbf0ff7026a86b5bdb9a9e9f09f
|
1bd945498f5d7ec2809b43ee77eea520ede4cee6
|
refs/heads/master
| 2021-09-17T14:00:19.635452
| 2018-07-02T11:31:03
| 2018-07-02T11:31:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,001
|
cpp
|
Base.class.cpp
|
// ************************************************************************** //
// //
// ::: :::::::: //
// Base.class.cpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: avolgin <marvin@42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2018/06/25 14:54:23 by avolgin #+# #+# //
// Updated: 2018/06/27 20:58:19 by avolgin ### ########.fr //
// //
// ************************************************************************** //
#include "Base.class.hpp"
Base::~Base(void) {
std::cout << "Base destructor called" << std::endl;
return ;
}
|
e6b821103582e85428974a256ace98ff4a37858c
|
eed7f497c013890e6df4ba9f30c63453aef484b1
|
/TileBag.h
|
de1acafdcc162ba28daabcab7412b2255fa76302
|
[] |
no_license
|
aalonto/MAA-Azul-Game
|
e1050eff6638d1ff646c70d3136c7b80ef048e4e
|
dfb2e5b32167240353c31f8a115ebbb6e1ecea5c
|
refs/heads/master
| 2023-03-08T19:44:02.564144
| 2020-05-20T03:02:55
| 2020-05-20T03:02:55
| 264,061,995
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 488
|
h
|
TileBag.h
|
#ifndef TILEBAG_H
#define TILEBAG_H
#include "Tile.h"
#include <istream>
class Node {
public:
Node(TilePtr tile, Node* next);
Node(Node& other);
TilePtr tile;
Node* next;
};
class TileBag {
public:
TileBag();
~TileBag();
unsigned int size();
void addTile(TilePtr tile);
void removeTileFront();
TilePtr getHead();
void clear();
void loadTileBag(std::istream& inputStream);
private:
Node* head;
int length;
};
#endif //TILEBAG_H
|
a228f29f0f60846a0bf12e35fa7a5245d8f4ae12
|
3f4062c28e027ec4c928bd94bab96d9c7a5904bc
|
/Entities/Array/ArrayValue.h
|
98cf873fde4e171cba4384f3500388b824347b62
|
[] |
no_license
|
ELOVSKIY/JOSLIN
|
8d1cfdd88be40636694253064a96c9dd704370c1
|
685a514aa46feea5f3d1664563ca029d5bc190a2
|
refs/heads/master
| 2020-09-30T20:21:46.084969
| 2019-12-11T12:51:14
| 2019-12-11T12:51:14
| 227,365,149
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 375
|
h
|
ArrayValue.h
|
//---------------------------------------------------------------------------
#ifndef ArrayValueH
#define ArrayValueH
#include "Value.h"
class ArrayValue: public Value {
private:
Value *arrayValue;
public:
ArrayValue(string name, Value *value);
Value * getArrayValue();
};
//---------------------------------------------------------------------------
#endif
|
3fb3444191c4f2105ca8d8622ddf34c34a1b7536
|
847245c3b5935b9b76a8442da9fce02ae36e9309
|
/Main.cpp
|
5834929fc918c970fab3d6de4143a42c0e7a990f
|
[] |
no_license
|
AndrewGREMORI/Dynamic_structure
|
c90fe06e9bbddbedb1eb5408574c588fa0379a19
|
5317b5bea1c4bae32f2c3bb99efaa7ff71ba84e0
|
refs/heads/master
| 2021-01-13T00:52:24.850134
| 2015-12-26T10:39:09
| 2015-12-26T10:39:09
| 43,589,871
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 448
|
cpp
|
Main.cpp
|
// Stack_(1_1).cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include "Stack.h"
int main()
{
Node *top = first(1);
int k;
cout << "Enter";
cin >> k;
for (int i = 2; i < k; i++)
push(&top, i);
cout << "Print" <<endl;
print(top);
cout << endl<< endl <<"Print and delete"<<endl;
while (top)
cout << pop(&top) << endl;
return 0;
}
|
76f89366e4fe383b6cfbc8a56ac7d2c22d78e7df
|
81b4f76dbcfd42b95953adfe5c8158e9e1a60896
|
/AttendanceRecord/Canceled.xaml.h
|
14164b9533ee773af7e18da9cfe510bf4cf46859
|
[] |
no_license
|
re-ma2000/proapp2019
|
0229fdac62b6db0ff993da55f76b5afa25f1ec56
|
55b5b56ed265d13c0e9835c5a47503f402eab79e
|
refs/heads/master
| 2020-07-29T06:49:06.214748
| 2019-10-11T03:11:53
| 2019-10-11T03:11:53
| 209,704,380
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 568
|
h
|
Canceled.xaml.h
|
//
// Canceled.xaml.h
// Canceled クラスの宣言
//
#pragma once
#include "Canceled.g.h"
namespace AttendanceRecord
{
/// <summary>
/// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
/// </summary>
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Canceled sealed
{
public:
Canceled();
private:
void button_MainPage(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
void click_hokou(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e);
};
}
|
332085e88a8d869836c664c48ccd3470e87db944
|
423cc5d4f67ecf06e084a8715d0fb65b7afa1a12
|
/5. Queue/Queue1/Queue1/Queue1_main.cpp
|
209707917c1db81c1a2e71f282adc594d294e127
|
[] |
no_license
|
barnaba94/C-Projects
|
f85d2bebe15bd6787c404a5b4c06fe78a0b6907c
|
8d7f2b7093e298e71647189f04516309d4fbd400
|
refs/heads/master
| 2021-04-18T22:08:15.920701
| 2018-03-25T12:50:02
| 2018-03-25T12:50:02
| 126,691,184
| 0
| 0
| null | null | null | null |
WINDOWS-1250
|
C++
| false
| false
| 721
|
cpp
|
Queue1_main.cpp
|
// Queue1.cpp: Określa punkt wejścia dla aplikacji konsoli.
//
#include "queue.h"
//TEST
#define MAX 100
void QBuild( Queque*, int);
void QPrint( Queque*);
int main(int argc , char* argv[])
{
Queque* que = QCreate();
QBuild(que, MAX);
QDequeue(que);
QDequeue(que);
QEnqueue( que, 10 );
QPrint(que);
QDel(&que);
getchar();
return 0;
}
void QBuild( Queque* pQueue, int nSize ) {
for ( int i = 0; i < nSize ; i++ )
QEnqueue( pQueue, i );
}
void QPrint( Queque* pQueue )
{
if ( QEmpty ( pQueue ) ) {
printf( "ERROR: Queue is empty!\n" );
return;
}
QItem* tmp = pQueue -> pHead;
while ( tmp ) {
printf( " %d ", tmp -> nKey);
tmp = tmp -> pNext;
}
}
|
677751b9da08a8f8d2045d16205be6b94a6d214e
|
20a9846649c09dd847b1ebb34e36c733045ef740
|
/SC.Game/Details.IntegratedFactory.cpp
|
82b9ebe749c7cb5481b4dc948d313594d7516f21
|
[] |
no_license
|
CC-s-DDAKARI/Touhou_Hourai_Story
|
a0c5cf0821a4ccc798f1dca5335754e47a9fe664
|
051c625e3497c76dff3e3ef5efac88b7cbf86938
|
refs/heads/master
| 2021-03-12T03:10:48.003052
| 2020-04-03T16:19:24
| 2020-04-03T16:19:24
| 246,584,604
| 3
| 1
| null | null | null | null |
UHC
|
C++
| false
| false
| 1,236
|
cpp
|
Details.IntegratedFactory.cpp
|
using namespace SC;
using namespace SC::Game;
using namespace SC::Game::Details;
using namespace std;
IntegratedFactory::IntegratedFactory()
{
// COM 기능을 사용하는 구성 요소를 사용하기 위해 CoInitialize 함수를 호출합니다.
HR( CoInitializeEx( nullptr, COINIT_MULTITHREADED ) );
// DXGI 팩토리 개체를 생성합니다.
HR( CreateDXGIFactory( IID_PPV_ARGS( &pDXGIFactory ) ) );
// DirectWrite 팩토리 개체를 생성합니다.
HR( DWriteCreateFactory( DWRITE_FACTORY_TYPE_SHARED, __uuidof( IDWriteFactory ), ( IUnknown** )&pDWriteFactory ) );
// WIC 팩토리 개체를 생성합니다.
HR( CoCreateInstance( CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS( &pWICFactory ) ) );
}
ComPtr<IDXGIAdapter1> IntegratedFactory::SearchHardwareAdapter()
{
for ( int i = 0; true; ++i )
{
ComPtr<IDXGIAdapter1> pAdapter;
HRESULT hr = pDXGIFactory->EnumAdapters1( ( UINT )i, &pAdapter );
if ( hr == DXGI_ERROR_NOT_FOUND )
{
return nullptr;
}
else if ( FAILED( hr ) ) HR( hr );
else
{
DXGI_ADAPTER_DESC1 desc{ };
HR( pAdapter->GetDesc1( &desc ) );
if ( ( desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE ) == 0 )
{
return move( pAdapter );
}
}
}
}
|
cb8c1c9d1c736ca4c93a942c92ccc6b5d176f007
|
5f552344baa57f868f167b0c0a94e7657cdc78f4
|
/lab14/lab14.cpp
|
949e3d7de53bccb82691091039457a804001f60e
|
[] |
no_license
|
rslater003/RileySlater-CSCI20-SPR2017
|
dd93b2c09c3e9900595b209e407c7b923637b6dd
|
85199e6ef98a663104a53d69ad1f0d00cfa6fdd2
|
refs/heads/master
| 2021-01-11T14:34:24.146913
| 2017-05-09T21:56:35
| 2017-05-09T21:56:35
| 80,164,092
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,919
|
cpp
|
lab14.cpp
|
//Riley Slater
//February 9, 2017
//This Program asks user if they would like to use a certain coin, by inputting a number corresponding to different coins.
//Then it asks how much change user has as a whole number. Converts that into minimum amounts of coins used. Then deducts a 10.9% fee for the service.
#include <iostream>
using namespace std;
int main() {
int amountOfChange = 0;
int quarter = 25;
int dime = 10;
int nickel = 5;
int penny = 1;
int includeHalfDollars;
int prioritize;
cout << "Which Type of Coin would you like to use first? (0 for Half-Dollars. 1 for Quarters. 2 for Dimes. 3 for Nickels. 4 for Pennies.) ";
cin >> prioritize;
cout << "How much change do you have? (As a Whole Number) ";
cin >> amountOfChange;
int totalAmount = amountOfChange;
if (prioritize == 0) { //If User Prioritizes Half Dollars
cout << amountOfChange/50 << " Half-Dollars" << endl;
amountOfChange = amountOfChange % 50;
cout << amountOfChange/25 << " Quarters" << endl;
amountOfChange = amountOfChange % 25;
cout << amountOfChange/10 << " Dimes" << endl;
amountOfChange = amountOfChange % 10;
cout << amountOfChange/5 << " Nickels" << endl;
amountOfChange = amountOfChange % 5;
cout << amountOfChange/1 << " Pennies" << endl;
}
if (prioritize == 1) { //If User Prioritizes Quarters
cout << amountOfChange/25 << " Quarters" << endl;
amountOfChange = amountOfChange % 25;
cout << amountOfChange/10 << " Dimes" << endl;
amountOfChange = amountOfChange % 10;
cout << amountOfChange/5 << " Nickels" << endl;
amountOfChange = amountOfChange % 5;
cout << amountOfChange/1 << " Pennies" << endl;
}
if (prioritize == 2) { //If User Prioritizes Dimes
cout << amountOfChange/10 << " Dimes" << endl;
amountOfChange = amountOfChange % 10;
cout << amountOfChange/5 << " Nickels" << endl;
amountOfChange = amountOfChange % 5;
cout << amountOfChange/1 << " Pennies" << endl;
}
if (prioritize == 3) { //If User Prioritizes Nickels
cout << amountOfChange/5 << " Nickels" << endl;
amountOfChange = amountOfChange % 5;
cout << amountOfChange/1 << " Pennies" << endl;
}
if (prioritize == 4) { //If User Prioritizes Pennies
cout << amountOfChange/1 << " Pennies" <<endl;
}
totalAmount = (totalAmount * .891);
cout << "Total Earned: " << static_cast<double>(totalAmount) << "¢" << endl;
} //ends int main() {
|
00804f89d4ccf0047d88cca4e77ae7a0f1c5d99c
|
70f1c9f7814ce0ba808176f3eda43930e28ffa73
|
/z__MRTestDev/ExperimentDllLoader/ExperimentDllLoader.cpp
|
76bf1765ec178b15f969202871376788938f68a6
|
[] |
no_license
|
MichaelRoop/CPP_TestHarness
|
9acff5fcc0c1d4ca87eedaa6d6f715657d68f3ee
|
3d4008a20ab03e4f51606e5c098a5a4c901ee1e2
|
refs/heads/master
| 2021-01-10T20:28:57.798744
| 2013-10-20T23:15:25
| 2013-10-20T23:15:25
| 5,349,717
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,420
|
cpp
|
ExperimentDllLoader.cpp
|
// ExperimentDllLoader.cpp : Defines the entry point for the console application.
//
//#define WIN32_LEAN_AND_MEAN
//#define VC_EXTRALEAN
#include "windows.h"
//#include <WinNT.h>
//#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
#include <assert.h>
#include <algorithm>
//#include "Winbase.h"
//void ListDLLFunctions(std::string sADllName, std::vector<std::string>& slListOfDllFunctions);
// typedef void (__stdcall *ptrFunc) () ;
//ptrFunc Func ;
#include "DllReflection.h"
typedef void (__cdecl *ptrFunc)();
class ExecDllFunctionFunctor {
public:
ExecDllFunctionFunctor(HINSTANCE handle) : m_handle(handle) {
}
void operator () (const std::string& s) {
std::cout << "Before getting function pointer '" << s << "'" << std::endl;
ptrFunc Func = (ptrFunc) ( GetProcAddress(this->m_handle,s.c_str()) );
std::cout << "After getting function pointer" << std::endl;
Func() ;
std::cout << "After calling function pointer" << std::endl;
}
private:
HINSTANCE m_handle;
};
//int _tmain(int argc, _TCHAR* argv[])
int main(int argc, char* argv[])
{
// HMODULE lib = LoadLibraryEx(L"C:\\Dev\\ExperimentDll.dll", NULL, DONT_RESOLVE_DLL_REFERENCES);
// assert(((PIMAGE_DOS_HEADER)lib)->e_magic == IMAGE_DOS_SIGNATURE);
//
// PIMAGE_NT_HEADERS header = (PIMAGE_NT_HEADERS) ((BYTE *)lib + ((PIMAGE_DOS_HEADER)lib)->e_lfanew);
// assert(header->Signature == IMAGE_NT_SIGNATURE);
// assert(header->OptionalHeader.NumberOfRvaAndSizes > 0);
//
// PIMAGE_EXPORT_DIRECTORY exports = (PIMAGE_EXPORT_DIRECTORY)
// ((BYTE *)lib + header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);
// PVOID names = (BYTE *)lib + exports->AddressOfNames;
//
//std::vector<std::string> namesV;
//
//std::cout << "DLL Exported Method Names discovery" << std::endl;
//for (int i = 0; i < exports->NumberOfNames; i++) {
// printf("Export Function Name: %s\n", (BYTE *)lib + ((DWORD *)names)[i]);
// namesV.push_back( (char*)((BYTE *)lib + ((DWORD *)names)[i]));
//}
//
//FreeLibrary(lib);
//std::cout << std::endl;
std::vector<std::string> namesV = cppTest::GetMethodNames(std::wstring(L"C:\\Dev\\ExperimentDll.dll"));
std::cout << "DLL Exported Method Execution" << std::endl;
std::cout << "Before load library" << std::endl;
HINSTANCE handle = LoadLibrary(L"C:\\Dev\\ExperimentDll.dll") ;
std::cout << "After load library" << std::endl;
std::for_each(namesV.begin(), namesV.end(), ExecDllFunctionFunctor(handle));
FreeLibrary(handle);
////ptrFunc Func = static_cast < ptrFunc > ( GetProcAddress(handle,"Func1") );
//ptrFunc Func = (ptrFunc) ( GetProcAddress(handle,"Func1") );
//std::cout << "After getting function pointer" << std::endl;
//Func() ;
//std::cout << "After calling function pointer" << std::endl;
/*
for (
for (int i = 0; i < exports->NumberOfNames; i++) {
//printf("Export: %s\n", (BYTE *)lib + ((DWORD *)names)[i]);
ptrFunc Func = (ptrFunc) ( GetProcAddress(handle,"Func1") );
std::cout << "After getting function pointer" << std::endl;
Func() ;
std::cout << "After calling function pointer" << std::endl;
}
*/
//std::vector<std::string> names;
// ListDLLFunctions("KERNEL32.DLL", names);
return 0;
}
//void ListDLLFunctions(std::string sADllName, std::vector<std::string>& slListOfDllFunctions)
//{
// DWORD *dNameRVAs(0);
// _IMAGE_EXPORT_DIRECTORY *ImageExportDirectory;
// unsigned long cDirSize;
// _LOADED_IMAGE LoadedImage;
// string sName;
// slListOfDllFunctions.clear();
// if (MapAndLoad(sADllName.c_str(), NULL, &LoadedImage, TRUE, TRUE))
// {
// ImageExportDirectory = (_IMAGE_EXPORT_DIRECTORY*)
// ImageDirectoryEntryToData(LoadedImage.MappedAddress,
// false, IMAGE_DIRECTORY_ENTRY_EXPORT, &cDirSize);
// if (ImageExportDirectory != NULL)
// {
// dNameRVAs = (DWORD *)ImageRvaToVa(LoadedImage.FileHeader,
// LoadedImage.MappedAddress,
// ImageExportDirectory->AddressOfNames, NULL);
// for(size_t i = 0; i < ImageExportDirectory->NumberOfNames; i++)
// {
// sName = (char *)ImageRvaToVa(LoadedImage.FileHeader,
// LoadedImage.MappedAddress,
// dNameRVAs[i], NULL);
// slListOfDllFunctions.push_back(sName);
// }
// }
// UnMapAndLoad(&LoadedImage);
// }
//}
|
8a62a5c768312b05587e7ee72659ff8843bd0185
|
ad454f987ebde118c38081850527eb0f8e6d422b
|
/202_197_224_59/ex3/1296.cpp
|
68688aedbddd57c120401a3112fa0f4347aa3c10
|
[] |
no_license
|
BackTo2012/homework
|
b6e2f3e2a9a91dcc444b374214de1a6f85b73b7d
|
79857e0a468eceb5618d8cfdd3abc851ec9819e0
|
refs/heads/master
| 2023-01-13T14:08:48.377637
| 2020-11-06T02:13:48
| 2020-11-06T02:13:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 277
|
cpp
|
1296.cpp
|
//GCD
#include <cstdio>
int main() {
int K;
int a, b;
scanf("%d", &K);
while (K--) {
scanf("%d %d", &a, &b);
a--;
int sa = a - a/2 - a/3 + a/6;
int sb = b - b/2 - b/3 + b/6;
printf("%d\n", sb - sa);
}
return 0;
}
|
a298507b5df07cc45052dc0d4cdd81308b3197fa
|
b3a8c68db3e202c7296026f46cfc9ce8661018a4
|
/N-Queens.cpp
|
a3b8d1add92863d2b7a3d6e7ccd7ac54b9270d46
|
[] |
no_license
|
sampatghosh/leetcode-solutions
|
5d1613561022f1fb3fc17e78493eebcec9d86c9e
|
ed60b6ef24fd138d7f69ac8c512e058951ce770a
|
refs/heads/master
| 2022-12-13T19:11:30.950024
| 2020-09-09T18:22:21
| 2020-09-09T18:22:21
| 294,072,505
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,418
|
cpp
|
N-Queens.cpp
|
class Solution {
public:
vector<vector<string>> out;
bool valid(vector<string>& board, int i, int j) {
int x = i-1, y = j-1;
while(x >= 0 && y >= 0) {
if(board[x][y] == 'Q')
return false;
--x;
--y;
}
x = i - 1;
y = j + 1;
while(x >= 0 && y < board.size()) {
if(board[x][y] == 'Q')
return false;
--x;
++y;
}
for(int k = 0; k < i; ++k) {
if(board[k][j] == 'Q')
return false;
}
return true;
}
void backtrack(vector<string>& board, int row) {
if(row == board.size()) {
out.push_back(board);
return;
}
else {
for(int j = 0; j < board.size(); ++j) {
board[row][j] = 'Q';
if(valid(board,row,j))
backtrack(board,row+1);
board[row][j] = '.';
}
return;
}
}
vector<vector<string>> solveNQueens(int n) {
ios_base::sync_with_stdio(false);
vector<string> board;
string x;
for(int i = 0; i < n; ++i)
x.push_back('.');
for(int i = 0; i < n; ++i)
board.push_back(x);
backtrack(board,0);
return out;
}
};
|
4176ebeca5696c252723018098c65c94e310452f
|
5ee7b59b955ebde297f0dd924382a96a79771681
|
/dbsplnr/PlnrMBlock.cpp
|
3ca2e48199ba2596b9a0161e9470d25cca58e151
|
[] |
no_license
|
epsitech/planar
|
a3b22468e6718342218143538a93e7af50debee0
|
e97374190feaf229dac4ec941e19f6661150e400
|
refs/heads/master
| 2021-01-21T04:25:32.542626
| 2016-08-07T19:20:49
| 2016-08-07T19:20:49
| 48,572,177
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 20,624
|
cpp
|
PlnrMBlock.cpp
|
/**
* \file PlnrMBlock.cpp
* database access for table TblPlnrMBlock (implementation)
* \author Alexander Wirthmueller
* \date created: 4 Dec 2015
* \date modified: 4 Dec 2015
*/
#include "PlnrMBlock.h"
/******************************************************************************
class PlnrMBlock
******************************************************************************/
PlnrMBlock::PlnrMBlock(
const ubigint ref
, const ubigint refPlnrMDesign
, const ubigint refPlnrMStructure
, const ubigint refPlnrMLayer
) {
this->ref = ref;
this->refPlnrMDesign = refPlnrMDesign;
this->refPlnrMStructure = refPlnrMStructure;
this->refPlnrMLayer = refPlnrMLayer;
};
bool PlnrMBlock::operator==(
const PlnrMBlock& comp
) {
return false;
};
bool PlnrMBlock::operator!=(
const PlnrMBlock& comp
) {
return(!operator==(comp));
};
/******************************************************************************
class ListPlnrMBlock
******************************************************************************/
ListPlnrMBlock::ListPlnrMBlock() {
};
ListPlnrMBlock::ListPlnrMBlock(
const ListPlnrMBlock& src
) {
nodes.resize(src.nodes.size(), NULL);
for (unsigned int i=0;i<nodes.size();i++) nodes[i] = new PlnrMBlock(*(src.nodes[i]));
};
ListPlnrMBlock::~ListPlnrMBlock() {
clear();
};
void ListPlnrMBlock::clear() {
for (unsigned int i=0;i<nodes.size();i++) delete nodes[i];
nodes.resize(0);
};
unsigned int ListPlnrMBlock::size() const {
return(nodes.size());
};
void ListPlnrMBlock::append(
PlnrMBlock* rec
) {
nodes.push_back(rec);
};
PlnrMBlock* ListPlnrMBlock::operator[](
const uint ix
) {
PlnrMBlock* retval = NULL;
if (ix < size()) retval = nodes[ix];
return retval;
};
ListPlnrMBlock& ListPlnrMBlock::operator=(
const ListPlnrMBlock& src
) {
PlnrMBlock* rec;
if (&src != this) {
clear();
for (unsigned int i=0;i<src.size();i++) {
rec = new PlnrMBlock(*(src.nodes[i]));
nodes.push_back(rec);
};
};
return(*this);
};
bool ListPlnrMBlock::operator==(
const ListPlnrMBlock& comp
) {
bool retval;
retval = (size() == comp.size());
if (retval) {
for (unsigned int i=0;i<size();i++) {
retval = ( *(nodes[i]) == *(comp.nodes[i]) );
if (!retval) break;
};
};
return retval;
};
bool ListPlnrMBlock::operator!=(
const ListPlnrMBlock& comp
) {
return(!operator==(comp));
};
/******************************************************************************
class TblPlnrMBlock
******************************************************************************/
TblPlnrMBlock::TblPlnrMBlock() {
};
TblPlnrMBlock::~TblPlnrMBlock() {
};
bool TblPlnrMBlock::loadRecBySQL(
const string& sqlstr
, PlnrMBlock** rec
) {
return false;
};
ubigint TblPlnrMBlock::loadRstBySQL(
const string& sqlstr
, const bool append
, ListPlnrMBlock& rst
) {
return 0;
};
void TblPlnrMBlock::insertRec(
PlnrMBlock* rec
) {
};
ubigint TblPlnrMBlock::insertNewRec(
PlnrMBlock** rec
, const ubigint refPlnrMDesign
, const ubigint refPlnrMStructure
, const ubigint refPlnrMLayer
) {
ubigint retval = 0;
PlnrMBlock* _rec = NULL;
_rec = new PlnrMBlock(0, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer);
insertRec(_rec);
retval = _rec->ref;
if (rec == NULL) delete _rec;
else *rec = _rec;
return retval;
};
ubigint TblPlnrMBlock::appendNewRecToRst(
ListPlnrMBlock& rst
, PlnrMBlock** rec
, const ubigint refPlnrMDesign
, const ubigint refPlnrMStructure
, const ubigint refPlnrMLayer
) {
ubigint retval = 0;
PlnrMBlock* _rec = NULL;
retval = insertNewRec(&_rec, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer);
rst.nodes.push_back(_rec);
if (rec != NULL) *rec = _rec;
return retval;
};
void TblPlnrMBlock::insertRst(
ListPlnrMBlock& rst
, bool transact
) {
};
void TblPlnrMBlock::updateRec(
PlnrMBlock* rec
) {
};
void TblPlnrMBlock::updateRst(
ListPlnrMBlock& rst
, bool transact
) {
};
void TblPlnrMBlock::removeRecByRef(
ubigint ref
) {
};
bool TblPlnrMBlock::loadRecByRef(
ubigint ref
, PlnrMBlock** rec
) {
return false;
};
ubigint TblPlnrMBlock::loadRstByDsn(
ubigint refPlnrMDesign
, const bool append
, ListPlnrMBlock& rst
) {
return 0;
};
ubigint TblPlnrMBlock::loadRstByDsnLyr(
ubigint refPlnrMDesign
, ubigint refPlnrMLayer
, const bool append
, ListPlnrMBlock& rst
) {
return 0;
};
ubigint TblPlnrMBlock::loadRstByRefs(
vector<ubigint>& refs
, const bool append
, ListPlnrMBlock& rst
) {
ubigint numload = 0;
PlnrMBlock* rec = NULL;
if (!append) rst.clear();
for (unsigned int i=0;i<refs.size();i++) if (loadRecByRef(refs[i], &rec)) {
rst.nodes.push_back(rec);
numload++;
};
return numload;
};
// IP myTbl --- BEGIN
/******************************************************************************
class MyTblPlnrMBlock
******************************************************************************/
MyTblPlnrMBlock::MyTblPlnrMBlock() : TblPlnrMBlock(), MyTable() {
stmtInsertRec = NULL;
stmtUpdateRec = NULL;
stmtRemoveRecByRef = NULL;
};
MyTblPlnrMBlock::~MyTblPlnrMBlock() {
if (stmtInsertRec) delete(stmtInsertRec);
if (stmtUpdateRec) delete(stmtUpdateRec);
if (stmtRemoveRecByRef) delete(stmtRemoveRecByRef);
};
void MyTblPlnrMBlock::initStatements() {
stmtInsertRec = createStatement("INSERT INTO TblPlnrMBlock (refPlnrMDesign, refPlnrMStructure, refPlnrMLayer) VALUES (?,?,?)", false);
stmtUpdateRec = createStatement("UPDATE TblPlnrMBlock SET refPlnrMDesign = ?, refPlnrMStructure = ?, refPlnrMLayer = ? WHERE ref = ?", false);
stmtRemoveRecByRef = createStatement("DELETE FROM TblPlnrMBlock WHERE ref = ?", false);
};
bool MyTblPlnrMBlock::loadRecBySQL(
const string& sqlstr
, PlnrMBlock** rec
) {
MYSQL_RES* dbresult; MYSQL_ROW dbrow; unsigned long* dblengths;
PlnrMBlock* _rec = NULL;
bool retval = false;
if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) throw DbsException("DbsException / MySQL: error executing query '" + sqlstr + "'\n");
dbresult = mysql_store_result(dbs);
if (!dbresult) throw DbsException("DbsException / MySQL: error storing result! (TblPlnrMBlock / loadRecBySQL)\n");
if (mysql_num_rows(dbresult) == 1) {
dbrow = mysql_fetch_row(dbresult);
dblengths = mysql_fetch_lengths(dbresult);
_rec = new PlnrMBlock();
if (dbrow[0]) _rec->ref = atoll((char*) dbrow[0]); else _rec->ref = 0;
if (dbrow[1]) _rec->refPlnrMDesign = atoll((char*) dbrow[1]); else _rec->refPlnrMDesign = 0;
if (dbrow[2]) _rec->refPlnrMStructure = atoll((char*) dbrow[2]); else _rec->refPlnrMStructure = 0;
if (dbrow[3]) _rec->refPlnrMLayer = atoll((char*) dbrow[3]); else _rec->refPlnrMLayer = 0;
retval = true;
};
mysql_free_result(dbresult);
*rec = _rec;
return retval;
};
ubigint MyTblPlnrMBlock::loadRstBySQL(
const string& sqlstr
, const bool append
, ListPlnrMBlock& rst
) {
MYSQL_RES* dbresult; MYSQL_ROW dbrow; unsigned long* dblengths; ubigint numrow; ubigint numread = 0;
PlnrMBlock* rec;
if (!append) rst.clear();
if (mysql_real_query(dbs, sqlstr.c_str(), sqlstr.length())) throw DbsException("DbsException / MySQL: error executing query '" + sqlstr + "'\n");
dbresult = mysql_store_result(dbs);
if (!dbresult) throw DbsException("DbsException / MySQL: error storing result! (TblPlnrMBlock / loadRstBySQL)\n");
numrow = mysql_num_rows(dbresult);
if (numrow > 0) {
rst.nodes.reserve(rst.nodes.size() + numrow);
while (numread < numrow) {
dbrow = mysql_fetch_row(dbresult);
dblengths = mysql_fetch_lengths(dbresult);
rec = new PlnrMBlock();
if (dbrow[0]) rec->ref = atoll((char*) dbrow[0]); else rec->ref = 0;
if (dbrow[1]) rec->refPlnrMDesign = atoll((char*) dbrow[1]); else rec->refPlnrMDesign = 0;
if (dbrow[2]) rec->refPlnrMStructure = atoll((char*) dbrow[2]); else rec->refPlnrMStructure = 0;
if (dbrow[3]) rec->refPlnrMLayer = atoll((char*) dbrow[3]); else rec->refPlnrMLayer = 0;
rst.nodes.push_back(rec);
numread++;
};
};
mysql_free_result(dbresult);
return(numread);
};
void MyTblPlnrMBlock::insertRec(
PlnrMBlock* rec
) {
unsigned long l[3]; my_bool n[3]; my_bool e[3];
MYSQL_BIND bind[] = {
bindUbigint(&rec->refPlnrMDesign,&(l[0]),&(n[0]),&(e[0])),
bindUbigint(&rec->refPlnrMStructure,&(l[1]),&(n[1]),&(e[1])),
bindUbigint(&rec->refPlnrMLayer,&(l[2]),&(n[2]),&(e[2]))
};
if (mysql_stmt_bind_param(stmtInsertRec, bind)) throw DbsException("DbsException / MySQL: error binding to statement! (TblPlnrMBlock / stmtInsertRec)\n");
// IP myInsertRec.execNounq --- BEGIN
if (mysql_stmt_execute(stmtInsertRec)) throw DbsException("DbsException / MySQL: error executing statement! (TblPlnrMBlock / stmtInsertRec)\n");
rec->ref = mysql_stmt_insert_id(stmtInsertRec);
// IP myInsertRec.execNounq --- END
};
void MyTblPlnrMBlock::insertRst(
ListPlnrMBlock& rst
, bool transact
) {
// IP myInsertRst.transact --- BEGIN
if (transact) begin();
for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]);
// IP myInsertRst.transact --- END
};
void MyTblPlnrMBlock::updateRec(
PlnrMBlock* rec
) {
unsigned long l[4]; my_bool n[4]; my_bool e[4];
MYSQL_BIND bind[] = {
bindUbigint(&rec->refPlnrMDesign,&(l[0]),&(n[0]),&(e[0])),
bindUbigint(&rec->refPlnrMStructure,&(l[1]),&(n[1]),&(e[1])),
bindUbigint(&rec->refPlnrMLayer,&(l[2]),&(n[2]),&(e[2])),
bindUbigint(&rec->ref,&(l[3]),&(n[3]),&(e[3]))
};
if (mysql_stmt_bind_param(stmtUpdateRec, bind)) throw DbsException("DbsException / MySQL: error binding to statement! (TblPlnrMBlock / stmtUpdateRec)\n");
if (mysql_stmt_execute(stmtUpdateRec)) throw DbsException("DbsException / MySQL: error executing statement! (TblPlnrMBlock / stmtUpdateRec)\n");
};
void MyTblPlnrMBlock::updateRst(
ListPlnrMBlock& rst
, bool transact
) {
// IP myUpdateRst.transact --- BEGIN
if (transact) begin();
for (unsigned int i=0;i<rst.nodes.size();i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) updateRec(rst.nodes[i]);
// IP myUpdateRst.transact --- END
};
void MyTblPlnrMBlock::removeRecByRef(
ubigint ref
) {
unsigned long l; my_bool n; my_bool e;
MYSQL_BIND bind = bindUbigint(&ref,&l,&n,&e);
if (mysql_stmt_bind_param(stmtRemoveRecByRef, &bind)) throw DbsException("DbsException / MySQL: error binding to statement! (TblPlnrMBlock / stmtRemoveRecByRef)\n");
if (mysql_stmt_execute(stmtRemoveRecByRef)) throw DbsException("DbsException / MySQL: error executing statement! (TblPlnrMBlock / stmtRemoveRecByRef)\n");
};
bool MyTblPlnrMBlock::loadRecByRef(
ubigint ref
, PlnrMBlock** rec
) {
return loadRecBySQL("SELECT * FROM TblPlnrMBlock WHERE ref = " + to_string(ref), rec);
};
ubigint MyTblPlnrMBlock::loadRstByDsn(
ubigint refPlnrMDesign
, const bool append
, ListPlnrMBlock& rst
) {
return loadRstBySQL("SELECT ref, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer FROM TblPlnrMBlock WHERE refPlnrMDesign = " + to_string(refPlnrMDesign) + "", append, rst);
};
ubigint MyTblPlnrMBlock::loadRstByDsnLyr(
ubigint refPlnrMDesign
, ubigint refPlnrMLayer
, const bool append
, ListPlnrMBlock& rst
) {
return loadRstBySQL("SELECT ref, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer FROM TblPlnrMBlock WHERE refPlnrMDesign = " + to_string(refPlnrMDesign) + " AND refPlnrMLayer = " + to_string(refPlnrMLayer) + "", append, rst);
};
// IP myTbl --- END
// IP pgTbl --- BEGIN
/******************************************************************************
class PgTblPlnrMBlock
******************************************************************************/
PgTblPlnrMBlock::PgTblPlnrMBlock() : TblPlnrMBlock(), PgTable() {
};
PgTblPlnrMBlock::~PgTblPlnrMBlock() {
// TODO: run SQL DEALLOCATE to free prepared statements
};
void PgTblPlnrMBlock::initStatements() {
PGresult* res;
res = PQprepare(dbs, "TblPlnrMBlock_insertRec", "INSERT INTO TblPlnrMBlock (refPlnrMDesign, refPlnrMStructure, refPlnrMLayer) VALUES ($1,$2,$3) RETURNING ref", 3, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) initStatementsErr(res);
res = PQprepare(dbs, "TblPlnrMBlock_updateRec", "UPDATE TblPlnrMBlock SET refPlnrMDesign = $1, refPlnrMStructure = $2, refPlnrMLayer = $3 WHERE ref = $4", 4, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) initStatementsErr(res);
res = PQprepare(dbs, "TblPlnrMBlock_removeRecByRef", "DELETE FROM TblPlnrMBlock WHERE ref = $1", 1, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) initStatementsErr(res);
res = PQprepare(dbs, "TblPlnrMBlock_loadRecByRef", "SELECT ref, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer FROM TblPlnrMBlock WHERE ref = $1", 1, NULL);
res = PQprepare(dbs, "TblPlnrMBlock_loadRstByDsn", "SELECT ref, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer FROM TblPlnrMBlock WHERE refPlnrMDesign = $1", 1, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) initStatementsErr(res);
res = PQprepare(dbs, "TblPlnrMBlock_loadRstByDsnLyr", "SELECT ref, refPlnrMDesign, refPlnrMStructure, refPlnrMLayer FROM TblPlnrMBlock WHERE refPlnrMDesign = $1 AND refPlnrMLayer = $2", 2, NULL);
if (PQresultStatus(res) != PGRES_COMMAND_OK) initStatementsErr(res);
};
bool PgTblPlnrMBlock::loadRec(
PGresult* res
, PlnrMBlock** rec
) {
char* ptr;
PlnrMBlock* _rec = NULL;
bool retval = false;
if (PQntuples(res) == 1) {
_rec = new PlnrMBlock();
int fnum[] = {
PQfnumber(res, "ref"),
PQfnumber(res, "refplnrmdesign"),
PQfnumber(res, "refplnrmstructure"),
PQfnumber(res, "refplnrmlayer")
};
ptr = PQgetvalue(res, 0, fnum[0]); _rec->ref = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[1]); _rec->refPlnrMDesign = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[2]); _rec->refPlnrMStructure = atoll(ptr);
ptr = PQgetvalue(res, 0, fnum[3]); _rec->refPlnrMLayer = atoll(ptr);
retval = true;
};
PQclear(res);
*rec = _rec;
return retval;
};
ubigint PgTblPlnrMBlock::loadRst(
PGresult* res
, const bool append
, ListPlnrMBlock& rst
) {
ubigint numrow; ubigint numread = 0; char* ptr;
PlnrMBlock* rec;
if (!append) rst.clear();
numrow = PQntuples(res);
if (numrow > 0) {
rst.nodes.reserve(rst.nodes.size() + numrow);
int fnum[] = {
PQfnumber(res, "ref"),
PQfnumber(res, "refplnrmdesign"),
PQfnumber(res, "refplnrmstructure"),
PQfnumber(res, "refplnrmlayer")
};
while (numread < numrow) {
rec = new PlnrMBlock();
ptr = PQgetvalue(res, numread, fnum[0]); rec->ref = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[1]); rec->refPlnrMDesign = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[2]); rec->refPlnrMStructure = atoll(ptr);
ptr = PQgetvalue(res, numread, fnum[3]); rec->refPlnrMLayer = atoll(ptr);
rst.nodes.push_back(rec);
numread++;
};
};
PQclear(res);
return numread;
};
bool PgTblPlnrMBlock::loadRecByStmt(
const string& srefStmt
, const unsigned int N
, const char** vals
, const int* l
, const int* f
, PlnrMBlock** rec
) {
PGresult* res;
res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) throw DbsException("DbsException / PgSQL: error executing statement! (TblPlnrMBlock / " + srefStmt + ")\n");
return loadRec(res, rec);
};
// IP pgLoadRstByStmt --- BEGIN
ubigint PgTblPlnrMBlock::loadRstByStmt(
const string& srefStmt
, const unsigned int N
, const char** vals
, const int* l
, const int* f
, const bool append
, ListPlnrMBlock& rst
) {
PGresult* res;
res = PQexecPrepared(dbs, srefStmt.c_str(), N, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK) throw DbsException("DbsException / PgSQL: error executing statement! (TblPlnrMBlock / " + srefStmt + ")\n");
return loadRst(res, append, rst);
};
// IP pgLoadRstByStmt --- END
bool PgTblPlnrMBlock::loadRecBySQL(
const string& sqlstr
, PlnrMBlock** rec
) {
PGresult* res;
res = PQexec(dbs, sqlstr.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) throw DbsException("DbsException / PgSQL: error executing query '" + sqlstr + "'\n");
return loadRec(res, rec);
};
ubigint PgTblPlnrMBlock::loadRstBySQL(
const string& sqlstr
, const bool append
, ListPlnrMBlock& rst
) {
PGresult* res;
res = PQexec(dbs, sqlstr.c_str());
if (PQresultStatus(res) != PGRES_TUPLES_OK) throw DbsException("DbsException / PgSQL: error executing query '" + sqlstr + "'\n");
return loadRst(res, append, rst);
};
void PgTblPlnrMBlock::insertRec(
PlnrMBlock* rec
) {
PGresult* res;
char* ptr;
ubigint _refPlnrMDesign = htonl64(rec->refPlnrMDesign);
ubigint _refPlnrMStructure = htonl64(rec->refPlnrMStructure);
ubigint _refPlnrMLayer = htonl64(rec->refPlnrMLayer);
const char* vals[] = {
(char*) &_refPlnrMDesign,
(char*) &_refPlnrMStructure,
(char*) &_refPlnrMLayer
};
const int l[] = {
sizeof(ubigint),
sizeof(ubigint),
sizeof(ubigint)
};
const int f[] = {1, 1, 1};
res = PQexecPrepared(dbs, "TblPlnrMBlock_insertRec", 3, vals, l, f, 0);
// IP pgInsertRec.execNounq --- BEGIN
if (PQresultStatus(res) != PGRES_TUPLES_OK) throw DbsException("DbsException / PgSQL: error executing statement! (TblPlnrMBlock_insertRec)\n");
ptr = PQgetvalue(res, 0, 0); rec->ref = atoll(ptr);
// IP pgInsertRec.execNounq --- END
PQclear(res);
};
void PgTblPlnrMBlock::insertRst(
ListPlnrMBlock& rst
, bool transact
) {
// IP pgInsertRst.transact --- BEGIN
if (transact) begin();
for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) insertRec(rst.nodes[i]);
// IP pgInsertRst.transact --- END
};
void PgTblPlnrMBlock::updateRec(
PlnrMBlock* rec
) {
PGresult* res;
ubigint _refPlnrMDesign = htonl64(rec->refPlnrMDesign);
ubigint _refPlnrMStructure = htonl64(rec->refPlnrMStructure);
ubigint _refPlnrMLayer = htonl64(rec->refPlnrMLayer);
ubigint _ref = htonl64(rec->ref);
const char* vals[] = {
(char*) &_refPlnrMDesign,
(char*) &_refPlnrMStructure,
(char*) &_refPlnrMLayer,
(char*) &_ref
};
const int l[] = {
sizeof(ubigint),
sizeof(ubigint),
sizeof(ubigint),
sizeof(ubigint)
};
const int f[] = {1, 1, 1, 1};
res = PQexecPrepared(dbs, "TblPlnrMBlock_updateRec", 4, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
throw DbsException("DbsException / PgSQL: error executing statement! (TblPlnrMBlock_updateRec)\n");
PQclear(res);
};
void PgTblPlnrMBlock::updateRst(
ListPlnrMBlock& rst
, bool transact
) {
// IP pgUpdateRst.transact --- BEGIN
if (transact) begin();
for (unsigned int i=0;i<rst.nodes.size();i++) updateRec(rst.nodes[i]);
if (transact) if (!commit()) for (unsigned int i=0;i<rst.nodes.size();i++) updateRec(rst.nodes[i]);
// IP pgUpdateRst.transact --- END
};
void PgTblPlnrMBlock::removeRecByRef(
ubigint ref
) {
PGresult* res;
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
res = PQexecPrepared(dbs, "TblPlnrMBlock_removeRecByRef", 1, vals, l, f, 0);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
throw DbsException("DbsException / PgSQL: error executing statement! (TblPlnrMBlock_removeRecByRef)\n");
PQclear(res);
};
bool PgTblPlnrMBlock::loadRecByRef(
ubigint ref
, PlnrMBlock** rec
) {
ubigint _ref = htonl64(ref);
const char* vals[] = {
(char*) &_ref
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
return loadRecByStmt("TblPlnrMBlock_loadRecByRef", 1, vals, l, f, rec);
};
ubigint PgTblPlnrMBlock::loadRstByDsn(
ubigint refPlnrMDesign
, const bool append
, ListPlnrMBlock& rst
) {
ubigint _refPlnrMDesign = htonl64(refPlnrMDesign);
const char* vals[] = {
(char*) &_refPlnrMDesign
};
const int l[] = {
sizeof(ubigint)
};
const int f[] = {1};
return loadRstByStmt("TblPlnrMBlock_loadRstByDsn", 1, vals, l, f, append, rst);
};
ubigint PgTblPlnrMBlock::loadRstByDsnLyr(
ubigint refPlnrMDesign
, ubigint refPlnrMLayer
, const bool append
, ListPlnrMBlock& rst
) {
ubigint _refPlnrMDesign = htonl64(refPlnrMDesign);
ubigint _refPlnrMLayer = htonl64(refPlnrMLayer);
const char* vals[] = {
(char*) &_refPlnrMDesign,
(char*) &_refPlnrMLayer
};
const int l[] = {
sizeof(ubigint),
sizeof(ubigint)
};
const int f[] = {1,1};
return loadRstByStmt("TblPlnrMBlock_loadRstByDsnLyr", 2, vals, l, f, append, rst);
};
// IP pgTbl --- END
|
1fb05fc8df621777bc59e373fbbc7b4e01b8839e
|
8c92baa9eb58de359dec00a785c7648b31076b03
|
/infoarena_campion/arb_rad.cpp
|
8d952332527a107f179354f97b98b2ef9a149971
|
[] |
no_license
|
george-popoiu/infoarena_campion
|
2e5f2433c4fe4252d11765411cb0ff4ed4eb941a
|
22569d32ac87f8031d9fdaf123da4adf4a7b2a9e
|
refs/heads/master
| 2021-01-19T14:59:04.887725
| 2012-08-08T12:42:30
| 2012-08-08T12:42:30
| 5,341,237
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 551
|
cpp
|
arb_rad.cpp
|
#include<fstream>
#define inf "arb_rad.in"
#define outf "arb_rad.out"
using namespace std;
fstream f(inf,ios::in),g(outf,ios::out);
int n,k;
int A[100][100],T[100],s[100];
void read()
{
int a,b;
f>>n>>k;
for(int i=1; i<n; i++) f>>a>>b , A[a][b]=A[b][a]=1;
}
void dfs(int nod)
{
s[nod]=1;
for(int k=1; k<=n; k++)
if( A[nod][k] && !s[k] )
{
T[k]=nod;
dfs(k);
}
}
void solve()
{
dfs(k);
for(int i=1; i<=n; i++) g<<T[i]<<" ";
}
int main()
{
read();
solve();
f.close();
g.close();
return 0;
}
|
3816cdd1a642b46abf6a1347eb7376609ed1a6fb
|
84506a2cdca98277924f921f34c2583020bf0434
|
/DieTogether/Source/DieTogether/DieTogetherGameMode.cpp
|
0d0ae76adcf8187ce5c81b4452eb0722c8160e16
|
[
"MIT"
] |
permissive
|
AndreasRoither/die-together
|
fe15e37409434ac3927affde5eb7fcc9cc06b8b5
|
efc5d06fdb5a094bc2e5fd3f45441912fc913b9f
|
refs/heads/master
| 2023-07-16T11:41:33.841949
| 2021-08-30T07:50:48
| 2021-08-30T07:50:48
| 248,736,334
| 0
| 1
| null | 2021-08-30T07:50:20
| 2020-03-20T11:13:44
|
CMake
|
UTF-8
|
C++
| false
| false
| 339
|
cpp
|
DieTogetherGameMode.cpp
|
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
#include "DieTogetherGameMode.h"
#include "character/GodCharacter.h"
ADieTogetherGameMode::ADieTogetherGameMode()
{
// Set default pawn class to our character
DefaultPawnClass = AGodCharacter::StaticClass();
//PlayerControllerClass = AGodPlayerController::StaticClass();
}
|
9e543d3d0d3681156381dbca4c5f3a5be46f9d1c
|
5bcdcdded8ff12f4b6c5e94a776cef19c517d3f9
|
/DHT11/DHT11.ino
|
575952cebba5d1178586163d838572812f3f3a6d
|
[] |
no_license
|
nkj06/StudyArduino
|
5c4b161d8a00c87535770b43b018dec4141dd588
|
965977d2e3cac787cc350658bd206ac89c0e15d3
|
refs/heads/master
| 2022-12-02T06:34:02.330627
| 2020-08-19T01:03:19
| 2020-08-19T01:03:19
| 288,596,707
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 672
|
ino
|
DHT11.ino
|
// 온습도 센서
// 툴 - 라이브러리 관리에서 DHT 검색해서 설치
#include <DHT.h>
#define DHTTYPE DHT11
int dhtPin = 8;
int vcc = 9;
int ground = 10;
DHT dht(dhtPin, DHTTYPE);
void setup() {
Serial.begin(9600);
pinMode(dhtPin, INPUT);
pinMode(vcc, OUTPUT);
pinMode(ground, OUTPUT);
digitalWrite(vcc, HIGH);
digitalWrite(ground, LOW);
dht.begin();
}
void loop() {
delay(1500);
float h = dht.readHumidity(); // 습도데이터
float t = dht.readTemperature(); // 온도 데이터
Serial.print("습도 : ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("온도 : ");
Serial.print(t);
Serial.println(" C");
}
|
9f3176c68fcca5d462ed1c5e3db510e07a89bdef
|
8b46bcd539b39927689cfa7dedf6313cee3a6aca
|
/CGLUTInterface.h
|
0ce30a9902e2f315d022a380ab6668c7e1e2ce90
|
[] |
no_license
|
3buson/ioncon
|
66d96234db7cc8770d8e3dc3ceccd9a00e296c5d
|
84b3a55100875e942b90844d2e18ddd9b60798d6
|
refs/heads/master
| 2020-02-26T17:27:56.386954
| 2014-01-12T20:39:41
| 2014-01-12T20:39:41
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,758
|
h
|
CGLUTInterface.h
|
#ifndef CGLUT_INTERFACE_H_INCL
#define CGLUT_INTERFACE_H_INCL
#include "opengl.h"
#include "CEventReceiver.h"
class CGLUTInterface
{
public:
static void connect(CEventReceiver* er)
{
printf("Connecting application interface...\n");
EventReceiver = er;
glutDisplayFunc(displayFunc);
glutIdleFunc(idleFunc);
glutReshapeFunc(reshapeFunc);
glutKeyboardFunc(keyboardFunc);
glutKeyboardUpFunc(keyboardUpFunc);
glutSpecialFunc(specialFunc);
glutMouseFunc(mouseFunc);
glutMotionFunc(motionFunc);
glutPassiveMotionFunc(passiveMotionFunc);
}
static void disconnect()
{
EventReceiver = 0;
}
static void displayFunc()
{
if (EventReceiver)
EventReceiver->displayFunc();
}
static void idleFunc()
{
if (EventReceiver)
EventReceiver->idleFunc();
}
static void mouseFunc(int button, int state, int x, int y)
{
if (EventReceiver)
EventReceiver->mouseFunc(button, state, x, y);
}
static void reshapeFunc(int w, int h)
{
if (EventReceiver)
EventReceiver->reshapeFunc(w, h);
}
static void keyboardFunc(unsigned char c, int x, int y)
{
if (EventReceiver)
EventReceiver->keyboardFunc(c, x, y);
}
static void keyboardUpFunc(unsigned char c, int x, int y)
{
if (EventReceiver)
EventReceiver->keyboardUpFunc(c, x, y);
}
static void specialFunc(int c, int x, int y)
{
if (EventReceiver)
EventReceiver->specialFunc(c, x, y);
}
static void motionFunc(int x, int y)
{
if (EventReceiver)
EventReceiver->motionFunc(x, y);
}
static void passiveMotionFunc(int x, int y)
{
if (EventReceiver)
EventReceiver->passiveMotionFunc(x, y);
}
private:
static CEventReceiver* EventReceiver;
};
// TODO yes i know, this is bad.
CEventReceiver* CGLUTInterface::EventReceiver = 0;
#endif
|
bad65b3bcfc080045e2a8155831eec8078326bc7
|
b61aea9dfd5463d1d43440e18eddf3e65a12af63
|
/CSGOSimple/autostrafe.cpp
|
53d833b0897f29f2e79f9ee9ad20a3713ebbaf20
|
[] |
no_license
|
asdlei99/sssssssss
|
757dd177bab85bd2ee8e491a730b73501f6049a3
|
c311736c694b02d5604ce756bc943f54777f3f50
|
refs/heads/master
| 2020-12-24T03:52:33.067209
| 2017-12-14T03:25:23
| 2017-12-14T03:25:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 597
|
cpp
|
autostrafe.cpp
|
#include "autostrafe.hpp"
#include "valve_sdk/csgostructs.hpp"
void AutoStrafe::OnCreateMove(CUserCmd* cmd)
{
if (!g_LocalPlayer || !g_LocalPlayer->IsAlive())
return;
if ((GetAsyncKeyState(VK_SPACE) && !(g_LocalPlayer->m_fFlags() & FL_ONGROUND)))
{
if (cmd->mousedx > 1 || cmd->mousedx < -1)
{
cmd->sidemove = cmd->mousedx < 0.f ? -450.f : 450.f;
}
else {
cmd->forwardmove = (1800.f * 4.f) / g_LocalPlayer->m_vecVelocity().Length2D();
cmd->sidemove = (cmd->command_number % 2) == 0 ? -450.f : 450.f;
if (cmd->forwardmove > 450.f)
cmd->forwardmove = 450.f;
}
}
}
|
a117b4a56fec7a810be66f669a3adbc8add8ccee
|
c9042c65d6c7a632cfd903a56e52a42903464467
|
/FsGame/NpcBaseModule/AI/Rule/ChaseTarget/AIRChaseTargetBase.cpp
|
0fdf3b5c048fce19df1813d9e2c9680fe9efd4a6
|
[] |
no_license
|
cnsuhao/myown
|
4048a2a878b744636a88a2090739e39698904964
|
50dab74b9ab32cba8b0eb6cf23cf9f95a5d7f3e4
|
refs/heads/master
| 2021-09-10T23:48:25.187878
| 2018-04-04T09:33:30
| 2018-04-04T09:33:30
| 140,817,274
| 2
| 2
| null | null | null | null |
GB18030
|
C++
| false
| false
| 3,900
|
cpp
|
AIRChaseTargetBase.cpp
|
//--------------------------------------------------------------------
// 文件名: AIRChaseTargetBase.h
// 内 容: 基本追击规则
// 说 明:
// 创建日期: 2014年12月31日
// 创建人:
// 修改人:
// :
//--------------------------------------------------------------------
#include "AIRChaseTargetBase.h"
#include "FsGame/NpcBaseModule/AI/AISystem.h"
#include "utils/util_func.h"
#include <math.h>
#include "FsGame/Interface/FightInterface.h"
#include "FsGame/SystemFunctionModule/MotionModule.h"
#include "FsGame/Define/Fields.h"
#include "FsGame/CommonModule/EnvirValueModule.h"
AIRChaseTargetBase::AIRChaseTargetBase()
{
m_ruleType = AI_RULE_CHASE_TARGET;
m_subRuleCode = AIRS_CHASE_TARGET_BASE;
}
//是不是在技能范围内
int AIRChaseTargetBase::InSkillRange(IKernel * pKernel, const PERSISTID & self, const PERSISTID & sender)
{
IGameObj* pSelfObj = pKernel->GetGameObj(self);
if (pSelfObj == NULL)
{
return 0;
}
float dist = pKernel->Distance2D(self, sender);
//碰撞半径
if (dist < pSelfObj->QueryFloat("MinAttackDist"))
{
return AI_RANGE_NEAR;
}
else if (dist > pSelfObj->QueryFloat("MaxAttackDist"))
{
return AI_RANGE_OVER;
}
return AI_RANGE_OK;
}
int AIRChaseTargetBase::DoRule(IKernel * pKernel, const PERSISTID & self, const PERSISTID & sender, const IVarList & args, AITemplateBase &templateWrap)
{
IGameObj *pSelf = pKernel->GetGameObj(self);
if(pSelf == NULL)
{
return AI_RT_IGNORE;
}
//是不是还在战斗
if (pSelf->QueryInt("CurState") != AI_STATE_FIGHT)
{
return AI_RT_IGNORE;
}
//如果不可行走
if ( pSelf->QueryInt("CantMove") > 0)
{
return AI_RT_IGNORE;
}
//得到当前攻击目标
PERSISTID curTarget = pSelf->QueryObject("AITargetObejct");
if (!pKernel->Exists(curTarget))
{
return AI_RT_IGNORE;
}
if (!IsCanChasePlayer(pKernel, curTarget))
{
return AI_RT_IGNORE;
}
// 正在释放技能
// if (USESKILL_RESULT_SUCCEED != FightInterfaceInstance->IsSkillUseBusy(pKernel, self))
// {
// // 持续施法的要处理追击
// if(USESKILL_RESULT_ERR_LEADING_BUSY == FightInterfaceInstance->IsSkillUseBusy(pKernel, self))
// {
// USOperationState type = USOperationState(FightInterfaceInstance->GetCurUSOperationState(pKernel, self));
// if(type == USO_CHANGE_ORIENT)
// {
// pKernel->Rotate(self, pKernel->Angle(self, curTarget), PI2);
// }
// else if(type == USO_CAN_MOTION)
// {
// //在技能攻击中追击
// AIFunction::StartMoveToObject(pKernel, self, curTarget, 0, 2);
// }
// }
// return AI_RT_IGNORE;
// }
//是否在攻击范围内
int iIn = InSkillRange(pKernel, self, curTarget);
float runSpeed = pSelf->QueryFloat("RunSpeed");
if(iIn == AI_RANGE_OK || iIn == AI_RANGE_NEAR)
{
//正好
if (!FloatEqual(runSpeed, 0.0f))
{
MotionModule::MotionStop(pKernel, self);
}
return AI_RT_SUCCESS;
}
//不能移动,塔类
if (FloatEqual(runSpeed, 0.0f))
{
return AI_RT_IGNORE;
}
float minDistance = pSelf->QueryFloat("MinAttackDist");
float maxDistance = pSelf->QueryFloat("MaxAttackDist");
////距离太远,跑向目标
if (AIFunction::StartMoveToObject(pKernel, self, curTarget, minDistance, maxDistance) == AI_RT_FAIL)
{
return AI_RT_END_FIGHT;
}
return AI_RT_IGNORE;
}
// 是否能追击玩家
bool AIRChaseTargetBase::IsCanChasePlayer(IKernel * pKernel, const PERSISTID& target)
{
IGameObj* pTargetObj = pKernel->GetGameObj(target);
if (NULL == pTargetObj)
{
return false;
}
// 不是玩家肯定能追击
if (pTargetObj->GetClassType() != TYPE_PLAYER)
{
return true;
}
#ifndef FSROOMLOGIC_EXPORTS
// 玩家使用轻功不能追击
// if (FightInterfaceInstance->IsInFlySkill(pKernel, target))
// {
// return false;
// }
#endif // !FSROOMLOGIC_EXPORTS
return true;
}
|
3654188d791e848756d19c56805bd6e0c498a458
|
91f1e7fd3451ec7a83307cc935a305fc1a1bfed4
|
/last_ver/retdir/import.cpp
|
a13f02508edcd1ad95b4dd022e567be32e5d9615
|
[] |
no_license
|
ernesto341/ais-research
|
dd903666c6e3bce7d635d5506c811b5a24ac1ef8
|
38873f1ea43314094e35ef0a9046ddc3bbe2c15a
|
refs/heads/master
| 2020-06-29T05:55:56.313548
| 2015-06-18T00:51:05
| 2015-06-18T00:51:05
| 25,174,178
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,024
|
cpp
|
import.cpp
|
#include <import.hpp>
using namespace std;
struct stat buf;
void onDemandImport (int sign)
{
if (DEBUG)
{
cerr << "recieved import signal!\n" << flush;
}
if (sign != SIGUSR1)
{
if (DEBUG)
{
cerr << "onDemandImport signaled by invalid signal!\n" << flush;
}
return;
}
do_import = 1;
}
inline static void resizeChar(char ** a = 0, unsigned int * s = 0)
{
if (a == 0)
{
return;
}
int32_t size = strlen(*a);
char * tmp = (char *)malloc(sizeof(char) * size * 2);
memcpy(tmp, *a, size);
free(*a);
*a = tmp;
if (s != 0)
{
*s = (size * 2);
}
}
unsigned int arr_size = 100;
static bool checked = false;
inline static bool Exists (const char * n)
{
return((bool)(stat(n, &buf) == 0));
}
Antibody ** importChamps (char * fin)
{
if (fin == (char *)0)
{
fin = (char *)"./ais/champions.abs\0";
}
if (DEBUG)
{
cerr << "importChamps: filename = " << fin << endl << flush;
}
ifstream in(fin);
if (in.fail())
{
fin = (char *)"./../ais/champions.abs\0";
cerr << "importChamps: filename = " << fin << endl << flush;
ifstream in(fin);
if (in.fail())
{
cerr << "Unable to open champs file\nAttempting to generate...\n" << flush;
/* HERE */
if (!checked)
{
system(Exists((const char *)("./../ais/lifetime.25\0")) ? (char *)("cd ./../ais/ && ./lifetime.25 && cd ../retdir/\0") : (Exists((const char *)("./ais/lifetime.25\0")) ? (char *)("cd ./ais/ && ./lifetime.25 && cd ../\0") : (char *)("")));
checked = true;
//while(!Exists((const char *)("./../ais/champions.abs\0")) && !Exists((const char *)("./ais/champions.abs\0")));
return(importChamps((char *)(0)));
}
else
{
cerr << "Unable to generate champs file. Aborting.\n" << flush;
return (0);
}
}
}
char * data = 0;
data = (char *)malloc(sizeof(char) * arr_size);
if (!data)
{
return (0);
}
int i = 0;
ab_count = 0;
alen = 0;
class_count = 0;
/* maybe check read/calculated values below against what they should be? */
while (in.get(data[i]))
{
cerr << data[i] << flush;
if (ab_count == 0)
{
if (data[i] == ',')
{
alen++;
}
else if (data[i] == ';')
{
class_count++;
}
}
if (data[i] == '\n')
{
ab_count++;
}
i++;
if ((unsigned int)i == arr_size - 1)
{
resizeChar(&data, &arr_size);
}
}
cerr << endl << flush;
in.close();
if (DEBUG)
{
cerr << "Got alen: " << alen << endl;
cerr << "Got class_count: " << class_count << endl;
}
ab_count /= class_count;
int data_size = strlen(data);
if (DEBUG)
{
cerr << "Got ab_count: " << ab_count << endl;
cerr << "Got data_size: " << data_size << endl << flush;
}
Antibody ** pop = 0;
pop = new Antibody *[class_count];
for (int k = 0; k < class_count; k++)
{
pop[k] = new Antibody [ab_count];
}
int j = 0, k = 0, l = 0, tmp = 0, begin = 0;
i = 0;
while (i < class_count && l < data_size)
{
j = 0;
while (j < ab_count && l < data_size)
{
k = 0;
/* first val: flag[i] (i < alen) */
/* second val: a[i] - attribute */
/* third val: offset[i] */
/* fourth val: max[i] */
/* comma separates value set, iterate iterator */
while (k < alen && l < data_size)
{
begin = l;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setFlag(k, tmp);
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setAttr(k, tmp);
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setOffset(k, tmp);
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setMax(k, tmp);
while (data[l] != 32)
{
l++;
}
l++;
k++;
}
/* tab to stats */
while (data[l] != 9)
{
l++;
}
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setTests(tmp);
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setPos(tmp);
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setFalsePos(tmp);
begin = l;
l++;
while (data[l] != 32)
{
l++;
}
tmp = atoi(&data[begin]);
pop[i][j].setNeg(tmp);
begin = l;
tmp = atoi(&data[begin]);
pop[i][j].setFalseNeg(tmp);
while (data[l] != 9)
{
l++;
}
k = 0;
while (k < class_count)
{
begin = l;
tmp = atoi(&data[begin]);
l++;
while (data[l] != 32)
{
l++;
}
pop[i][j].setCat(k, tmp);
k++;
}
while (data[l] != 10)
{
l++;
}
l++;
j++;
}
i++;
}
cerr << endl << flush;
/* Excessive output
*/
fprintf(stderr, "\n\nDone importing. Got the following:\n");
for (int i = 0; i < class_count; i++)
{
fprintf(stderr, "Class %d :\n", i + 1);
for (int j = 0; j < ab_count; j++)
{
cerr << "\t" << pop[i][j] << "\n";
}
cerr << endl;
}
cerr << endl << endl << flush;
return (pop);
}
void * importManager (void * v)
{
if (DEBUG)
{
cerr << "start import manager\n" << flush;
}
char * fname = (char *)v;
while (!quit)
{
if (do_import == 1)
{
if (DEBUG)
{
cerr << "import initiated!\n" << flush;
}
/* lock access to champs */
pthread_mutex_lock(&champs_mutex);
champs = importChamps(fname);
/* log import success/failure */
if (DEBUG)
{
cerr << "In onDemandImport. Got the following:\n";
for (int i = 0; i < class_count; i++)
{
cerr << "Class " << i+1 << ":\n";
for (int j = 0; j < ab_count; j++)
{
cerr << "\t" << champs[i][j] << "\n";
}
cerr << endl;
}
cerr << endl << flush;
}
/* unlock access to champs */
pthread_mutex_unlock(&champs_mutex);
do_import = 0;
}
}
return ((void *)0);
}
|
ec0cf75524c45742d4ff952a476fdce7e6e910ad
|
cc88f042da9e65aad45d9b09cf43de4f8c255849
|
/src/Pruebas/PruebasSolicitud.cpp
|
49956be6970b8e5808dc4dc0aa62c0e16274b2c5
|
[] |
no_license
|
frojomar/edi2015-16
|
20370c21cb3cb1fba5414c4cb87879531a1ab327
|
104d19034fcf6845a4506aaddeb1f0e5d144ddb9
|
refs/heads/master
| 2020-03-29T23:40:24.116938
| 2018-09-26T20:08:53
| 2018-09-26T20:08:53
| 150,483,297
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,592
|
cpp
|
PruebasSolicitud.cpp
|
/*
* PruebasSolicitud.cpp
*
* Created on: 04/04/2016
* Author: FRANCISCO JAVIER ROJO MARTÍN DNI:76042262-F
*/
#include <iostream>
//#include "../Solicitud.h"
#include "Pruebas.h"
using namespace std;
void pr_Solicitud(){
cout<<" --Inicio pruebas de los constructores de Solicitud"<<endl;
Solicitud s;
if(s.getCodtit()!=0)
cout<<" Error para constructor por defecto"<<endl;
Solicitud s2(1);
if(s2.getCodtit()!=1)
cout<<" Error para constructor parametrizado"<<endl;
cout<<" --Fin pruebas de los contructores de Solicitud"<<endl;
}
void pr_set_getCodtit(){
cout<<" --Inicio pruebas de los get_setCodtit de Solicitud"<<endl;
Solicitud s1(1);
if(s1.getCodtit()!=1)
cout<<" Error para metodo getCodtit(1)"<<endl;
Solicitud s2(2);
if(s2.getCodtit()!=2)
cout<<" Error para metodo getCodtit(2)"<<endl;
Solicitud s3(3);
if(s3.getCodtit()!=3)
cout<<" Error para metodo getCodtit(3)"<<endl;
s1.setCodtit(4);
if(s1.getCodtit()!=4)
cout<<" Error para metodo setCodtit(4)"<<endl;
s2.setCodtit(5);
if(s2.getCodtit()!=5)
cout<<" Error para metodo setCodtit(5)"<<endl;
s3.setCodtit(6);
if(s3.getCodtit()!=6)
cout<<" Error para metodo setCodtit(6)"<<endl;
cout<<" --Fin pruebas de los get_setCodtit de Solicitud"<<endl;
}
void pruebas_Solicitud(){
cout<<"INICIO PRUEBAS SOLICITUD"<<endl;
pr_Solicitud();
cout<<endl;
pr_set_getCodtit();
cout<<"FIN PRUEBAS SOLICITUD"<<endl;
}
/*
int main(){
cout<<"INICIO PRUEBAS SOLICITUD"<<endl;
pr_Solicitud();
cout<<endl;
pr_set_getCodtit();
cout<<"FIN PRUEBAS SOLICITUD"<<endl;
return 0;
}
*/
|
d8d68c6c9bc8bcea8eac7ae20d130ba49db14e4c
|
f678d3a6d93f949eaf286d41a3270f430726b615
|
/read_n_chars_given_read4_2/main.cpp
|
7680fea1f8e62a0a4903f3f67e21acecc0cf350b
|
[] |
no_license
|
yinxx/leetcode
|
aa1eac1b513c4ed44613cc55de3daa67e1760c65
|
8a6954928acb0961ec3b65d7b7882305c0e617cf
|
refs/heads/master
| 2020-03-20T16:45:12.669033
| 2017-12-25T03:35:34
| 2017-12-25T03:35:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,173
|
cpp
|
main.cpp
|
#include <iostream>
// Forward declaration of the read4 API.
int read4(char *buf);
class Solution {
private:
static const int BUFFER_SIZE = 4;
char cache[BUFFER_SIZE];
int size;
int offset;
bool done;
public:
Solution(){
size = 0;
offset = 0;
done = false;
}
/**
* @param buf Destination buffer
* @param n Maximum number of characters to read
* @return The number of characters read
*/
int read(char *buf, int n) {
int total = n;
int idx = 0;
while(n > 0){
// First read whatever is left from the cache:
int to_read = std::min(n, size);
memcpy(buf + idx, cache + offset, to_read);
n -= to_read;
idx += to_read;
offset += to_read;
size -= to_read;
if(done) return idx;
if(size) continue;
// Otherwise, we need to load another batch via read4.
size = read4(cache);
offset = 0;
if(size < 4) // we've reached an end.
done = true;
}
return total;
}
};
|
3de1016c3c0087cccf96d422aa095180b994050c
|
5d0165a2b2a5115b52d5769af3a64c12385e6132
|
/MatrixGenerator.cpp
|
71640b62028d54f816620092ab4cb165c9729dfe
|
[] |
no_license
|
KokBaiSheng/InterviewProject
|
c61a385e9fe94ed7b84b49bb89dea3e408bbefd4
|
7edaae5fe170b59fb9e3ca1e2140802583cd1105
|
refs/heads/master
| 2020-03-20T21:38:24.981288
| 2018-07-08T13:26:47
| 2018-07-08T13:26:47
| 137,751,763
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,223
|
cpp
|
MatrixGenerator.cpp
|
#include<iostream>
#include<fstream>
#include<vector>
void printMatrix(std::vector<std::vector<int>> const & inMatrix, std::string const & fileName)
{
//open outputfilestream
std::fstream ofs;
ofs.open (fileName, std::fstream::out | std::fstream::trunc | std::fstream::binary);
if(ofs.is_open())
{
// get row and columns
int row = inMatrix.size();
int column = 0;
if(row > 0)
{
column = inMatrix[0].size();
}
//first two numbers represent the row and column of the matrix
ofs.write(reinterpret_cast<char *>(&row),sizeof(row));
ofs.write(reinterpret_cast<char *>(&column),sizeof(column));
//print out the rest of the matrix.
for(std::vector<int> row : inMatrix)
{
for(int it : row)
{
ofs.write(reinterpret_cast<char *>(&it),sizeof(it));
}
}
//close ofs
ofs.close();
}
else
{
std::cout <<" Error opening outputfile handle"<<std::endl;
}
}
void printIntVec (std::vector<int> const & inVec)
{
for (int it : inVec )
{
std::cout << it << " ";
}
std::cout << std::endl;
}
std::vector<std::vector<int>> readCSVParams(int const & row, int const & column,std::ifstream& ifs)
{
std::vector<std::vector<int>> ret = std::vector<std::vector<int>>();
//check if input file stream is open
if(ifs.is_open())
{
std::string line;
int y =0;
//while there is a new line and y is smaller than row count
while(getline(ifs,line) && y< row)
{
int it = 0;
int x = 0;
std::vector<int> row = std::vector<int>();
// while it is not at the end of line and x is smaller than the column count
while(it < line.length() && x <column)
{
//get the positition of the comma
int end = line.find(",",it);
if(end == -1)
{
//if a comma cannot be found skip to the end of the line
end = line.length();
}
//get the string of where the iterator is at
std::string currentInput = line.substr(it,end - it);
//push back int
row.push_back(atoi(currentInput.c_str()));
//increment the iterator past the comma
it = end+1;
//increment x
++x;
}
// push the row into the return matrix
ret.push_back(row);
++y;
}
}
else
{
std::cout <<"Error" <<std::endl;
}
ifs.close();
return ret;
}
std::vector<int> XORCipher (std::vector<int> const & inVec, int key)
{
std::vector<int> ret = std::vector<int>();
for(int it : inVec )
{
ret.push_back(it ^ key);
}
return ret;
}
std::vector<std::vector<int>> XORCipherTwoDimension (std::vector<std::vector<int>> const & in2DVec, int key)
{
std::vector<std::vector<int>> ret = std::vector<std::vector<int>>();
for(std::vector<int> row : in2DVec)
{
ret.push_back(XORCipher(row, key));
}
return ret;
}
std::vector<std::vector<int>> CreateRandomMatrix(int const& row, int const& column)
{
std::vector<std::vector<int>> matrixRet = std::vector<std::vector<int>> ();
for (int y=0; y < row ; ++y)
{
std::vector<int> vecRow = std::vector<int>();
for(int y =0; y < column;++y)
{
vecRow.push_back(std::rand() %1000);
}
matrixRet.push_back(vecRow);
}
return matrixRet;
}
int main(int argc, char ** argv)
{
if(argc < 4)
{
std::cout <<"Use case : ./matrixgenerator row column filename.dat" <<std::endl;
return -1;
}
int row = atoi(argv[1]);
int column = atoi(argv[2]);
if(row ==0 || column == 0)
{
std::cout <<"Please specify valid row or column" << std::endl;
return -1;
}
std::string outputName(argv[3]);
if(outputName.find(".dat") == -1)
{
std::cout <<"Please specify valid .dat file" << std::endl;
return -1;
}
std::vector<std::vector<int>>matrixRet = std::vector<std::vector<int>>();
//if there's 5th option
if(argc > 4)
{
//Check for csv
std::string check (argv[4]);
if(check.find(".csv") == -1)
{
std::cout <<"Please specify a csv file" << std::endl;
return -1;
}
std::ifstream fs;
fs.open (argv[4], std::fstream::app);
if( !fs.is_open())
{
std::cout <<"Please specify a csv file" << std::endl;
return -1;
}
matrixRet = readCSVParams(row,column,fs);
}
else
{
matrixRet = CreateRandomMatrix(row,column);
}
//12345 is the key for the xorcipher
matrixRet = XORCipherTwoDimension(matrixRet,12345);
printMatrix(matrixRet, outputName);
return 0;
}
|
dd1db7f1f16dc58d2f531228aa6ded33274a2d21
|
fd88bf8bf77affc30af4fbd9b2e3916bdaa0789b
|
/test/com/ComModTestAAF/ModuleTests/CAAFContentStorageTest.cpp
|
d440887886c9b5a5bfb9a8e2142228f50b8c29eb
|
[] |
no_license
|
jhliberty/AAF
|
6e6a7d898d42e6e91690c76afbc4cf581cc716fc
|
af8c9d43461ab556bd6cf8d98b0f001eb7b87cfe
|
refs/heads/master
| 2021-01-08T11:37:10.299319
| 2016-08-16T02:49:39
| 2016-08-16T02:49:39
| 65,782,219
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 18,590
|
cpp
|
CAAFContentStorageTest.cpp
|
// @doc INTERNAL
// @com This file implements the module test for CAAFContentStorage
//=---------------------------------------------------------------------=
//
// $Id: CAAFContentStorageTest.cpp,v 1.37 2009/06/01 11:47:11 stuart_hc Exp $ $Name: V116 $
//
// The contents of this file are subject to the AAF SDK Public Source
// License Agreement Version 2.0 (the "License"); You may not use this
// file except in compliance with the License. The License is available
// in AAFSDKPSL.TXT, or you may obtain a copy of the License from the
// Advanced Media Workflow Association, Inc., or its successor.
//
// Software distributed under the License is distributed on an "AS IS"
// basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
// the License for the specific language governing rights and limitations
// under the License. Refer to Section 3.3 of the License for proper use
// of this Exhibit.
//
// WARNING: Please contact the Advanced Media Workflow Association,
// Inc., for more information about any additional licenses to
// intellectual property covering the AAF Standard that may be required
// to create and distribute AAF compliant products.
// (http://www.amwa.tv/policies).
//
// Copyright Notices:
// The Original Code of this file is Copyright 1998-2009, licensor of the
// Advanced Media Workflow Association. All rights reserved.
//
// The Initial Developer of the Original Code of this file and the
// licensor of the Advanced Media Workflow Association is
// Avid Technology.
// All rights reserved.
//
//=---------------------------------------------------------------------=
#include "AAF.h"
#include <iostream>
using namespace std;
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "AAFStoredObjectIDs.h"
#include "AAFResult.h"
#include "ModuleTest.h"
#include "AAFDefUIDs.h"
#include "CAAFBuiltinDefs.h"
const aafMobID_t kTestMobID1 = { { 0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x04, 0x02 }, 0x13, 0x00, 0x00, 0x00,
{ 0x464AA9D8, 0x34AC, 0x11d3, { 0x80, 0xB4, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F } } };
const aafMobID_t kTestMobID2 = { { 0x06, 0x0E, 0x2B, 0x34, 0x01, 0x01, 0x01, 0x01,
0x01, 0x01, 0x04, 0x02 }, 0x13, 0x00, 0x00, 0x00,
{ 0x464AA9D9, 0x34AC, 0x11d3, { 0x80, 0xB4, 0x00, 0x60, 0x08, 0x14, 0x3E, 0x6F } } };
// Utility class to implement the test.
struct ContentStorageTest
{
ContentStorageTest(aafProductIdentification_constref productID);
~ContentStorageTest();
void createFile(wchar_t *pFileName,
aafUID_constref fileKind,
testRawStorageType_t rawStorageType);
void openFile(wchar_t *pFileName);
void createFileMob(aafMobID_constref newMobID);
void createEssenceData(IAAFSourceMob *pSourceMob);
void openEssenceData();
void writeEssenceData(IAAFPlainEssenceData *pEssenceData,
const aafDataBuffer_t data,
aafUInt32 dataSize);
void readEssenceData(IAAFPlainEssenceData *pEssenceData,
const aafDataBuffer_t data,
aafUInt32 dataSize);
void cleanupReferences();
void setBufferSize(aafUInt32 bufferSize);
inline void check(HRESULT hr);
inline void checkExpression(bool expression, HRESULT hr);
const char * convert(const wchar_t* pwcName);
// Shared member data:
HRESULT _hr;
aafProductVersion_t _productVersion;
aafProductIdentification_t _productInfo;
IAAFFile *_pFile;
bool _bFileOpen;
IAAFHeader *_pHeader;
IAAFContentStorage *_pStorage;
IAAFDictionary *_pDictionary;
IAAFMob *_pMob;
IAAFSourceMob *_pSourceMob;
IAAFEssenceDescriptor *_pEssenceDescriptor;
IAAFFileDescriptor *_pFileDescriptor;
IEnumAAFEssenceData *_pEnumEssenceData;
IAAFPlainEssenceData *_pEssenceData;
aafDataBuffer_t _buffer;
aafUInt32 _bufferSize;
static const char _smiley[];
static const char _frowney[];
};
extern "C" HRESULT CAAFContentStorage_test(
testMode_t mode,
aafUID_t fileKind,
testRawStorageType_t rawStorageType,
aafProductIdentification_t productID);
extern "C" HRESULT CAAFContentStorage_test(
testMode_t mode,
aafUID_t fileKind,
testRawStorageType_t rawStorageType,
aafProductIdentification_t productID)
{
HRESULT hr = AAFRESULT_SUCCESS;
const size_t fileNameBufLen = 128;
aafWChar fileName[ fileNameBufLen ] = L"";
GenerateTestFileName( productID.productName, fileKind, fileNameBufLen, fileName );
ContentStorageTest edt(productID);
try
{
if(mode == kAAFUnitTestReadWrite)
{
edt.createFile(fileName, fileKind, rawStorageType);
}
edt.openFile(fileName);
}
catch (HRESULT& ehr)
{
// thrown by ContentStorageTest_check() method.
hr = ehr;
}
catch (...)
{
cerr << "CAAFContentStorage_test...Caught general C++"
<< " exception!" << endl;
hr = AAFRESULT_TEST_FAILED;
}
// Cleanup our object if it exists.
// if (SUCCEEDED(hr))
// {
// cout << "The following IAAFContentStorage methods have not been tested:" << endl;
// cout << " GetMobs" << endl;
// hr = AAFRESULT_TEST_PARTIAL_SUCCESS;
// }
return hr;
}
const char ContentStorageTest::_smiley[] = /* 16x16 smiley face */
" **** "
" ******** "
" ********** "
" ************ "
" *** **** *** "
" *** **** *** "
"****************"
"****************"
"****************"
"****************"
" ** ******** ** "
" *** ****** *** "
" *** ** *** "
" **** **** "
" ******** "
" **** ";
const char ContentStorageTest::_frowney[] = /* 16x16 frowney face */
" **** "
" ******** "
" ********** "
" ************ "
" *** **** *** "
" *** **** *** "
"****************"
"****************"
"******* *******"
"***** ** *****"
" *** ****** *** "
" ** ******** ** "
" ************ "
" ********** "
" ******** "
" **** ";
ContentStorageTest::ContentStorageTest(aafProductIdentification_constref productID):
_hr(AAFRESULT_SUCCESS),
_productInfo(productID),
_pFile(NULL),
_bFileOpen(false),
_pHeader(NULL),
_pStorage(NULL),
_pDictionary(NULL),
_pMob(NULL),
_pSourceMob(NULL),
_pEssenceDescriptor(NULL),
_pFileDescriptor(NULL),
_pEnumEssenceData(NULL),
_pEssenceData(NULL),
_buffer(NULL),
_bufferSize(0)
{
}
ContentStorageTest::~ContentStorageTest()
{
cleanupReferences();
}
void ContentStorageTest::cleanupReferences()
{
if (NULL != _buffer)
{
delete [] _buffer;
_buffer = NULL;
}
if (NULL != _pEssenceData)
{
_pEssenceData->Release();
_pEssenceData = NULL;
}
if (NULL != _pEnumEssenceData)
{
_pEnumEssenceData->Release();
_pEnumEssenceData = NULL;
}
if (NULL != _pFileDescriptor)
{
_pFileDescriptor->Release();
_pFileDescriptor = NULL;
}
if (NULL != _pEssenceDescriptor)
{
_pEssenceDescriptor->Release();
_pEssenceDescriptor = NULL;
}
if (NULL != _pSourceMob)
{
_pSourceMob->Release();
_pSourceMob = NULL;
}
if (NULL != _pMob)
{
_pMob->Release();
_pMob = NULL;
}
if (NULL != _pDictionary)
{
_pDictionary->Release();
_pDictionary = NULL;
}
if (NULL != _pStorage)
{
_pStorage->Release();
_pStorage = NULL;
}
if (NULL != _pHeader)
{
_pHeader->Release();
_pHeader = NULL;
}
if (NULL != _pFile)
{
if (_bFileOpen)
_pFile->Close();
_pFile->Release();
_pFile = NULL;
}
}
void ContentStorageTest::setBufferSize(aafUInt32 bufferSize)
{
// Allocate the buffer.
if (NULL != _buffer && bufferSize > _bufferSize)
{
delete [] _buffer;
_buffer = NULL;
}
// Allocate the buffer.
if (NULL == _buffer)
{
_bufferSize = bufferSize;
_buffer = (aafDataBuffer_t)new char[ _bufferSize ];
checkExpression(NULL != _buffer, AAFRESULT_NOMEMORY);
}
}
inline void ContentStorageTest::check(HRESULT hr)
{
if (AAFRESULT_SUCCESS != (_hr = hr))
throw hr;
}
inline void ContentStorageTest::checkExpression(bool expression, HRESULT hr)
{
if (!expression)
throw hr;
}
// local conversion utility.
const char * ContentStorageTest::convert(const wchar_t* pwcName)
{
checkExpression(NULL != pwcName, E_INVALIDARG);
const size_t kBufferSize = 256;
static char ansiName[kBufferSize];
size_t convertedBytes = wcstombs(ansiName, pwcName, kBufferSize);
checkExpression(0 < convertedBytes, E_INVALIDARG);
return ansiName;
}
void ContentStorageTest::createFile(
wchar_t *pFileName,
aafUID_constref fileKind,
testRawStorageType_t rawStorageType)
{
// Delete the test file if it already exists.
remove(convert(pFileName));
check(CreateTestFile( pFileName, fileKind, rawStorageType, _productInfo, &_pFile ));
_bFileOpen = true;
check(_pFile->GetHeader(&_pHeader));
check(_pHeader->GetDictionary(&_pDictionary));
check(_pHeader->GetContentStorage(&_pStorage));
createFileMob(kTestMobID1);
createFileMob(kTestMobID2);
check(_pFile->Save());
cleanupReferences();
}
void ContentStorageTest::openFile(wchar_t *pFileName)
{
aafUInt32 readNumEssenceData;
aafNumSlots_t readNumMobs;
IAAFMob *testMob = NULL;
IEnumAAFMobs *pEnum = NULL;
aafMobID_t uid, readID;
aafBool testBool;
check(AAFFileOpenExistingRead(pFileName, 0, &_pFile));
_bFileOpen = true;
check(_pFile->GetHeader(&_pHeader));
check(_pHeader->GetContentStorage(&_pStorage));
openEssenceData();
check(_pStorage->CountEssenceData(&readNumEssenceData));
checkExpression(2 == readNumEssenceData, AAFRESULT_TEST_FAILED);
/***/
uid = kTestMobID1;
check(_pStorage->LookupMob(uid, &testMob));
check(testMob->GetMobID(&readID));
checkExpression(memcmp(&uid, &readID, sizeof(readID)) == 0, AAFRESULT_TEST_FAILED);
testMob->Release();
testMob = NULL;
/***/
uid = kTestMobID2;
check(_pStorage->LookupMob(uid, &testMob));
check(testMob->GetMobID(&readID));
checkExpression(memcmp(&uid, &readID, sizeof(readID)) == 0, AAFRESULT_TEST_FAILED);
testMob->Release();
testMob = NULL;
/***/
uid.material.Data1 = 0; // Invalidate the mobID
uid.material.Data2 = 0;
uid.material.Data3 = 0;
checkExpression(_pStorage->LookupMob(uid, &testMob) != AAFRESULT_SUCCESS, AAFRESULT_TEST_FAILED);
/***/
check(_pStorage->CountMobs(kAAFFileMob, &readNumMobs));
checkExpression(2 == readNumMobs, AAFRESULT_TEST_FAILED);
check(_pStorage->CountMobs(kAAFMasterMob, &readNumMobs));
checkExpression(0 == readNumMobs, AAFRESULT_TEST_FAILED);
/***/
uid = kTestMobID1;
check(_pStorage->GetMobs(NULL, &pEnum)); // !! Add tests for criteria
check(pEnum->NextOne(&testMob));
check(testMob->GetMobID(&readID));
checkExpression(memcmp(&uid, &readID, sizeof(readID)) == 0, AAFRESULT_TEST_FAILED);
testMob->Release();
testMob = NULL;
/***/
uid = kTestMobID2;
check(_pStorage->IsEssenceDataPresent (uid, kAAFEssence, &testBool));
checkExpression(kAAFTrue == testBool, AAFRESULT_TEST_FAILED);
/***/
uid = kTestMobID2;
uid.material.Data1 = 0; // Invalidate the mobID
uid.material.Data2 = 0;
uid.material.Data3 = 0;
check(_pStorage->IsEssenceDataPresent (uid, kAAFEssence, &testBool));
checkExpression(kAAFFalse == testBool, AAFRESULT_TEST_FAILED);
/***/
pEnum->Release();
pEnum = NULL;
cleanupReferences();
}
void ContentStorageTest::createFileMob(aafMobID_constref newMobID)
{
assert(_pFile && _pStorage && _pDictionary);
assert(NULL == _pSourceMob);
assert(NULL == _pMob);
assert(NULL == _pFileDescriptor);
assert(NULL == _pEssenceDescriptor);
assert(NULL == _pSourceMob);
CAAFBuiltinDefs defs (_pDictionary);
// Create a Mob
check(defs.cdSourceMob()->
CreateInstance(IID_IAAFSourceMob,
(IUnknown **)&_pSourceMob));
check(_pSourceMob->QueryInterface (IID_IAAFMob, (void **)&_pMob));
check(_pMob->SetMobID(newMobID));
check(_pMob->SetName(L"ContentStorageTest File Mob"));
// instantiate a concrete subclass of FileDescriptor
check(defs.cdAIFCDescriptor()->
CreateInstance(IID_IAAFFileDescriptor,
(IUnknown **)&_pFileDescriptor));
IAAFAIFCDescriptor* pAIFCDesc = NULL;
check(_pFileDescriptor->QueryInterface (IID_IAAFAIFCDescriptor, (void **)&pAIFCDesc));
check(pAIFCDesc->SetSummary (5, (unsigned char*)"TEST"));
pAIFCDesc->Release();
pAIFCDesc = NULL;
check(_pFileDescriptor->QueryInterface (IID_IAAFEssenceDescriptor,
(void **)&_pEssenceDescriptor));
check(_pSourceMob->SetEssenceDescriptor (_pEssenceDescriptor));
check(_pStorage->AddMob(_pMob));
createEssenceData(_pSourceMob);
// Cleanup instance data for reuse...
_pEssenceDescriptor->Release();
_pEssenceDescriptor = NULL;
_pFileDescriptor->Release();
_pFileDescriptor = NULL;
_pMob->Release();
_pMob = NULL;
_pSourceMob->Release();
_pSourceMob = NULL;
}
void ContentStorageTest::createEssenceData(IAAFSourceMob *pSourceMob)
{
assert(_pFile && _pStorage && _pDictionary);
assert(pSourceMob);
assert(NULL == _pEssenceData);
CAAFBuiltinDefs defs (_pDictionary);
// Attempt to create an AAFEssenceData.
IAAFEssenceData* pRawEssenceData = NULL;
check(defs.cdEssenceData()->
CreateInstance(IID_IAAFEssenceData,
(IUnknown **)&pRawEssenceData));
check(pRawEssenceData->SetFileMob(pSourceMob));
check(_pStorage->AddEssenceData(pRawEssenceData));
IAAFEssenceData2* pEssenceData2 = NULL;
check(pRawEssenceData->QueryInterface(IID_IAAFEssenceData2, (void**)&pEssenceData2));
check(pEssenceData2->GetPlainEssenceData(0, &_pEssenceData));
writeEssenceData(_pEssenceData, (aafDataBuffer_t)_smiley, sizeof(_smiley));
writeEssenceData(_pEssenceData, (aafDataBuffer_t)_frowney, sizeof(_frowney));
// Read back the data before saving and/or closing the file
check(_pEssenceData->SetPosition(0));
aafPosition_t dataPosition = 0;
check(_pEssenceData->GetPosition(&dataPosition));
checkExpression(dataPosition == 0, AAFRESULT_TEST_FAILED);
// Validate the current essence size.
aafLength_t essenceSize = 0;
aafLength_t expectedEssenceSize = sizeof(_smiley) + sizeof(_frowney);
check(_pEssenceData->GetSize(&essenceSize));
checkExpression(essenceSize == expectedEssenceSize, AAFRESULT_TEST_FAILED);
readEssenceData(_pEssenceData, (aafDataBuffer_t)_smiley, sizeof(_smiley));
readEssenceData(_pEssenceData, (aafDataBuffer_t)_frowney, sizeof(_frowney));
pRawEssenceData->Release();
pRawEssenceData = NULL;
pEssenceData2->Release();
pEssenceData2 = NULL;
_pEssenceData->Release();
_pEssenceData = NULL;
}
void ContentStorageTest::openEssenceData()
{
assert(_pFile && _pStorage);
assert(NULL == _pEnumEssenceData);
assert(NULL == _pEssenceData);
assert(NULL == _pSourceMob);
check(_pStorage->EnumEssenceData(&_pEnumEssenceData));
IAAFEssenceData* pNextEssenceData = NULL;
while (AAFRESULT_SUCCESS == (_hr = _pEnumEssenceData->NextOne(&pNextEssenceData)))
{
IAAFEssenceData2* pEssenceData2 = NULL;
check(pNextEssenceData->QueryInterface(IID_IAAFEssenceData2, (void**)&pEssenceData2));
check(pEssenceData2->GetPlainEssenceData(0, &_pEssenceData));
// Validate the essence.
// Validate the current essence size.
aafLength_t essenceSize = 0;
aafLength_t expectedEssenceSize = sizeof(_smiley) + sizeof(_frowney);
check(_pEssenceData->GetSize(&essenceSize));
checkExpression(essenceSize == expectedEssenceSize, AAFRESULT_TEST_FAILED);
// Validate that the correct data can be read back.
readEssenceData(_pEssenceData, (aafDataBuffer_t)_smiley, sizeof(_smiley));
readEssenceData(_pEssenceData, (aafDataBuffer_t)_frowney, sizeof(_frowney));
// Make sure that the essence data still references
// a valid mob.
check(_pEssenceData->GetFileMob(&_pSourceMob));
_pSourceMob->Release();
_pSourceMob = NULL;
_pEssenceData->Release();
_pEssenceData = NULL;
pEssenceData2->Release();
pEssenceData2 = NULL;
pNextEssenceData->Release();
pNextEssenceData = NULL;
}
// It is ok to run out of objects.
checkExpression (AAFRESULT_NO_MORE_OBJECTS == _hr, _hr);
_hr = AAFRESULT_SUCCESS;
_pEnumEssenceData->Release();
_pEnumEssenceData = NULL;
}
void ContentStorageTest::writeEssenceData(IAAFPlainEssenceData *pEssenceData,
const aafDataBuffer_t data,
aafUInt32 dataSize)
{
assert(NULL != pEssenceData);
// NOTE: The following code assumes that the compiler supports 64 bit
// numbers.
aafPosition_t startingPosition = 0;
aafPosition_t expectedPosition = 0;
aafPosition_t dataPosition = 0;
aafUInt32 bytesWritten = 0;
aafUInt32 offset = 0;
// Save the starting position.
check(pEssenceData->GetPosition(&startingPosition));
for (offset = 0; offset < dataSize; ++offset)
{
// Reset the position to test SetPosition.
dataPosition = startingPosition + offset;
check(pEssenceData->SetPosition(dataPosition));
bytesWritten = 0;
check(pEssenceData->Write(dataSize - offset, data + offset, &bytesWritten));
// Make sure that we wrote the expected number of bytes.
checkExpression(bytesWritten == (dataSize - offset), AAFRESULT_TEST_FAILED);
// Make sure the position is supported correctly.
expectedPosition = startingPosition + dataSize;
dataPosition = 0;
check(pEssenceData->GetPosition(&dataPosition));
checkExpression(dataPosition == expectedPosition, AAFRESULT_TEST_FAILED);
}
}
void ContentStorageTest::readEssenceData(IAAFPlainEssenceData *pEssenceData,
const aafDataBuffer_t data,
aafUInt32 dataSize)
{
assert(NULL != pEssenceData);
// NOTE: The following code assumes that the compiler supports 64 bit
// numbers.
aafPosition_t startingPosition = 0;
aafPosition_t expectedPosition = 0;
aafPosition_t dataPosition = 0;
aafUInt32 bytesRead = 0;
aafUInt32 offset = 0;
// Save the starting position.
check(pEssenceData->GetPosition(&startingPosition));
// Make sure the buffer is large enough to hold the data.
setBufferSize(dataSize);
for (offset = 0; offset < dataSize; ++offset)
{
// Reset the position to test SetPosition.
dataPosition = startingPosition + offset;
check(pEssenceData->SetPosition(dataPosition));
// Read dataSize bytes from the essence data.
bytesRead = 0;
check(pEssenceData->Read(dataSize - offset, _buffer, &bytesRead));
// Make sure that we read the expected number of bytes.
checkExpression(bytesRead == (dataSize - offset), AAFRESULT_TEST_FAILED);
// Make sure the position is supported correctly.
expectedPosition = startingPosition + dataSize;
dataPosition = 0;
check(pEssenceData->GetPosition(&dataPosition));
checkExpression(dataPosition == expectedPosition, AAFRESULT_TEST_FAILED);
// Compare the bytes we read to the given input data.
// (this is assumed to match the original data written
// to the essence data)
checkExpression (0 == memcmp(data + offset, (char *)_buffer, dataSize - offset), AAFRESULT_TEST_FAILED);
}
}
|
8a41970a083a55ac4543b836e68a56a851641b3c
|
2d314658588ed72f399365fb1e8ad85b0e795c75
|
/src/Game/PathManager.h
|
1092a34ee793f513ed97279be4f01d0723ead570
|
[] |
no_license
|
NBK/NBK
|
b82f7c720241032bb086c5436c34caadc121141d
|
c46498c6dac032f2bf8d3819f5277aef239e525e
|
refs/heads/master
| 2016-09-15T17:14:37.473185
| 2013-11-29T00:11:47
| 2013-11-29T00:11:47
| 2,650,959
| 12
| 4
| null | 2012-11-04T21:10:23
| 2011-10-26T13:20:32
|
C
|
UTF-8
|
C++
| false
| false
| 2,568
|
h
|
PathManager.h
|
#ifndef PATH_MANAGER_H
#define PATH_MANAGER_H
#include "Manager.h"
#include "RenderManager.h"
#include "ConsoleListener.h"
#include "BinaryHeap.h"
/* In charge of finding paths between squares */
#define inNeither 0
#define inOpened 1
#define inClosed 2
namespace game_utils
{
namespace managers
{
class CPathManager: public CManager, public control::CConsoleListener
{
public:
CPathManager();
virtual ~CPathManager();
// from CManager
virtual bool init();
virtual bool update();
virtual bool shutdown();
// from CConsoleListener
virtual std::string onAction(std::string keyword, std::string params);
virtual bool findPath(int startX, int startY, int endX, int endY, std::vector<cml::vector2i> *path);
virtual bool findPath(cml::vector2i start, cml::vector2i end, std::vector<cml::vector2i> *path);
enum HeuristicFormula
{
Manhattan = 1,
MaxDXDY = 2,
DiagonalShortcut = 3,
Euclidean = 4,
EuclideanNoSQR = 5,
Custom1 = 6,
None = 7
};
void setFormula(HeuristicFormula formula);
void setHeuristicEstimate(int heuristicEstimate);
void setPunishDirectionChange(bool punishDirectionChange);
void setDirectionChangePenalty(int directionChangePenalty);
void setDiagonalMoves(bool diagonalMoves);
void setHeavyDiagonals(bool heavyDiagonals);
void setDiagonalPenalty(int diagonalPenalty);
void setTieBreaker(bool tieBreaker);
void setTieBreakerValue(float tieBreakerValue);
void setSearchLimit(int searchLimit);
void setAllowWalkOnLava(bool allowWalkOnLava);
void setAllowEndDiagonal(bool allowEndDiagonal);
HeuristicFormula getFormula();
int getHeuristicEstimate();
bool getPunishDirectionChange();
int getDirectionChangePenalty();
bool getDiagonalMoves();
bool getHeavyDiagonals();
int getDiagonalPenalty();
bool getTieBreaker();
float getTieBreakerValue();
int getSearchLimit();
bool getAllowWalkOnLava();
bool getAllowEndDiagonal();
private:
BinaryHeap heap;
HeuristicFormula formula;
int heuristicEstimate;
bool punishDirectionChange;
int directionChangePenalty;
bool diagonalMoves;
bool heavyDiagonals;
int diagonalPenalty;
bool tieBreaker;
float tieBreakerValue;
int searchLimit;
bool allowWalkOnLava;
bool allowEndDiagonal;
static const int directions[8][2];
struct cellData
{
int OCList;
int GCost;
int FCost;
cml::vector2i Parent;
};
};
};
};
#endif // PATH_MANAGER_H
|
ec02700f9ddb5bc45bd5cb13f73edc88f70c157c
|
1e1a877949621fd6ae6353c4814f165b5e220388
|
/DYNAMIC PROGRAMMING/zeroNknapsack.cpp
|
7501db2fa285cd4d8bb059266a2808373aa099a0
|
[] |
no_license
|
aman212yadav/PRACTICE
|
b7f930fe010f72678e6bff9f2c98cf9a0c2c3fff
|
1cd25d1e3d1436fa3ee0747c561f3982289fc6b7
|
refs/heads/master
| 2020-04-12T23:57:25.251011
| 2020-01-17T17:50:29
| 2020-01-17T17:50:29
| 162,834,586
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 546
|
cpp
|
zeroNknapsack.cpp
|
// https://hack.codingblocks.com/practice/p/346/922
#include<bits/stdc++.h>
using namespace std;
int main(){
int n,s,i,j;
cin>>n>>s;
int sizee[n+1],cost[n+1];
for(i=1;i<=n;i++)
cin>>sizee[i];
for(i=1;i<=n;i++)
cin>>cost[i];
long long dp[n+1][s+1];
for(i=0;i<=s;i++)
dp[0][i]=0;
for(i=0;i<=n;i++)
dp[i][0]=0;
for(i=1;i<=n;i++)
{
for(j=1;j<=s;j++)
{
dp[i][j]=dp[i-1][j];
if(j-sizee[i]>=0)
dp[i][j]=max(dp[i][j],cost[i]+dp[i][j-sizee[i]]);
}
}
cout<<dp[n][s];
}
|
b03233a7fcc8300591681441e7f263795ec78673
|
9b7fde4cace1e2fad65490ab620212c131894a0d
|
/InterfaceKit/ext/Haiku/CustomTextView.h
|
da97b05f950ce99b188a36d74541195278dd78c1
|
[] |
no_license
|
gitpan/HaikuKits
|
e27f2b065a6d1dc88fd2fdd565d3da8e4e6b8ef6
|
3dd1ba7d66892e8e18bdb0ade19b059ec0846814
|
refs/heads/master
| 2021-01-19T02:41:22.867459
| 2011-08-20T15:38:18
| 2014-10-26T03:44:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,053
|
h
|
CustomTextView.h
|
/*
* Automatically generated file
*/
class Custom_BTextView : public BTextView {
public:
Custom_BTextView(BRect frame, const char* name, BRect textRect, uint32 resizingMode, uint32 flags);
Custom_BTextView(BRect frame, const char* name, BRect textRect, BFont* font, rgb_color* color, uint32 resizingMode, uint32 flags);
Custom_BTextView(const char* name, uint32 flags);
Custom_BTextView(const char* name, BFont* font, rgb_color* color, uint32 flags);
Custom_BTextView(BMessage* archive);
virtual ~Custom_BTextView();
void AttachedToWindow();
void DetachedFromWindow();
void Draw(BRect updateRect);
void MouseDown(BPoint point);
void MouseUp(BPoint point);
void MouseMoved(BPoint point, uint32 transit, BMessage* message);
void WindowActivated(bool state);
void KeyDown(const char* bytes, int32 numBytes);
void Pulse();
void FrameResized(float newWidth, float newHeight);
void MessageReceived(BMessage* message);
void AllAttached();
void AllDetached();
object_link_data* perl_link_data;
}; // Custom_BTextView
|
b533a61913fbd6fef338b1d83f38291c1013e656
|
1dbb60db92072801e3e7eaf6645ef776e2a26b29
|
/server/src/so_sharedb/market_pro.cpp
|
38465d2b3910988906c3d4a97d56bad683296030
|
[] |
no_license
|
atom-chen/phone-code
|
5a05472fcf2852d1943ad869b37603a4901749d5
|
c0c0f112c9a2570cc0390703b1bff56d67508e89
|
refs/heads/master
| 2020-07-05T01:15:00.585018
| 2015-06-17T08:52:21
| 2015-06-17T08:52:21
| 202,480,234
| 0
| 1
| null | 2019-08-15T05:36:11
| 2019-08-15T05:36:09
| null |
UTF-8
|
C++
| false
| false
| 2,742
|
cpp
|
market_pro.cpp
|
#include "pro.h"
#include "proto/market.h"
#include "proto/constant.h"
MSG_FUNC( PQMarketList )
{
wd::CSql* sql = sql::get( "share" );
if ( sql == NULL )
return;
QuerySql( "select cargo_id, sid, role_id, cate, objid, val, percent, start_time, down_time, buy_name, buy_count, money from market_sell" );
PRMarketList rep;
{
SMarketSellCargo cargo;
for ( sql->first(); !sql->empty(); sql->next() )
{
int32 i = 0;
cargo.cargo_id = sql->getInteger(i++);
cargo.sid = sql->getInteger(i++);
cargo.role_id = sql->getInteger(i++);
cargo.coin.cate = sql->getInteger(i++);
cargo.coin.objid = sql->getInteger(i++);
cargo.coin.val = sql->getInteger(i++);
cargo.percent = sql->getInteger(i++);
cargo.start_time = sql->getInteger(i++);
cargo.down_time = sql->getInteger(i++);
cargo.buy_name = sql->getString(i++);
cargo.buy_count = sql->getInteger(i++);
cargo.money = sql->getInteger(i++);
rep.list.push_back( cargo );
if ( rep.list.size() > 512 )
{
local::write( local::social, rep );
rep.list.clear();
}
}
}
if ( !rep.list.empty() )
{
local::write( local::social, rep );
rep.list.clear();
}
local::write( local::social, rep );
}
MSG_FUNC( PRMarketSellData )
{
wd::CSql* sql = sql::get( "share" );
if ( sql == NULL )
return;
switch ( msg.set_type )
{
case kObjectAdd:
{
ExecuteSql( "insert into market_sell values( %u, %u, %u, %u, %u, %u, %hhu, %u, %u, '%s', %u, %u )",
msg.data.cargo_id, msg.data.sid, msg.data.role_id,
msg.data.coin.cate, msg.data.coin.objid, msg.data.coin.val,
msg.data.percent, msg.data.start_time, msg.data.down_time,
sql->escape(msg.data.buy_name).c_str(), msg.data.buy_count, msg.data.money );
}
break;
case kObjectDel:
{
ExecuteSql( "delete from market_sell where cargo_id = %u", msg.data.cargo_id );
}
break;
case kObjectUpdate:
{
ExecuteSql( "update market_sell set val = %u, percent = %hhu where cargo_id = %u",
msg.data.coin.val, msg.data.percent,
msg.data.cargo_id );
}
break;
}
}
MSG_FUNC( PQMarketSocialReset )
{
wd::CSql* sql = sql::get( "share" );
if ( sql == NULL )
return;
ExecuteSql( "update market_sell set sid = 0 where sid = %u", msg.sid );
}
|
5cafcb5d558253f739c335ae1e9a770c336bd30c
|
aa56d3921a55f307743b58f91f214ddacb93e02a
|
/Engine/src/Engine/Graphics/buffers/VertexArray.cpp
|
56913aef91ebbc1c58cc31b96ca302cebd7ef867
|
[
"Apache-2.0"
] |
permissive
|
AustinLynes/Arcana-Tools
|
3b4da2e40e52f062e42c512bb838281ee542f717
|
ce585d552e30174c4c629a9ea05e7f83947499a5
|
refs/heads/master
| 2023-07-13T10:40:59.200943
| 2021-08-02T01:27:55
| 2021-08-02T01:27:55
| 389,682,422
| 0
| 0
|
Apache-2.0
| 2021-08-02T01:27:56
| 2021-07-26T15:32:39
|
C++
|
UTF-8
|
C++
| false
| false
| 316
|
cpp
|
VertexArray.cpp
|
#include "VertexArray.h"
#include "Engine/Graphics/renderers/Renderer3D.h"
#include "Platform/OpenGL/OpenGLVertexArray.h"
namespace ArcanaTools {
VertexArray* VertexArray::Create()
{
switch (Renderer3D::GetAPI()) {
case RenderAPI::API::OPENGL:
return new OpenGLVertexArray();
}
return nullptr;
}
}
|
959bcad0c49ef116e769095fd0563e7b9e462cec
|
498f5629f15083ac5dbbb3ba73f90bf59067f2e5
|
/codeforces/A. Panoramix's Prediction.cpp
|
845114ceff2d669c90ebfdb923788ec959c191f4
|
[] |
no_license
|
priyanshuN/Algorithms
|
b3103722fd6657d6507d72d73ba80b35e3a196dd
|
22559ffc50939256f2324afd313d4a32bb63f6ac
|
refs/heads/master
| 2022-01-31T06:17:52.577691
| 2022-01-08T14:33:56
| 2022-01-08T14:33:56
| 244,685,281
| 1
| 0
| null | 2022-01-08T14:33:57
| 2020-03-03T16:24:45
|
C++
|
UTF-8
|
C++
| false
| false
| 353
|
cpp
|
A. Panoramix's Prediction.cpp
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,m,z,i,j;
cin>>n>>m;
for(i=n+1;i>0;++i)
{
for(j=2;j<=i;++j)
{
if(i%j==0)
break;
}
if(j==i)
break;
}
if(j==m)
cout<<"YES";
else
cout<<"NO";
return 0;
}
|
d665f82b0c8def3a038abcf1db7859b464dfacfa
|
07fba37300811ce470313379d9a6e0faffaf90ef
|
/Processes.hh
|
7f297184e973a9b024bb690b42331f7cb0bc39f8
|
[
"MIT"
] |
permissive
|
Pseudomanifold/Pump
|
b37e9c56476e1f24a11b3688c553f43b5f5f16d7
|
c7cdc1e7c8acd2e568a1d2925313507e5bb391dd
|
refs/heads/master
| 2021-06-14T11:09:23.535474
| 2017-02-09T08:14:00
| 2017-02-09T08:14:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 343
|
hh
|
Processes.hh
|
#ifndef PUMP_PROCESSES_HH__
#define PUMP_PROCESSES_HH__
#include <string>
namespace pump
{
/*
Executes the given command and returns its output, i.e. everything
that is written to STDOUT. An empty string is not necessarily
indicative of an error.
*/
std::string get_stdout( const std::string& command );
} // namespace pump
#endif
|
11ab51810e4a3c8c5815911119c448f383d213c4
|
3d4ba7ae1b5e197f77dd7934f9fa136b1ea4cc63
|
/GeeksFoGeeks/WaterThePlants.cpp
|
3273211139da53d7160548c31569da744caa0e5a
|
[] |
no_license
|
Debashish-hub/Problems-Of-The-Day
|
9fc0dc86299875c38262d55c3d62b12f84df1d6f
|
3a28a8b186ad2431dc4a89b4a7a0f51a3def67a6
|
refs/heads/main
| 2023-07-02T20:19:59.576008
| 2021-08-06T07:18:33
| 2021-08-06T07:18:33
| 376,271,621
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,844
|
cpp
|
WaterThePlants.cpp
|
// Water the plants
// A gallery with plants is divided into n parts, numbered : 0,1,2,3...n-1. There are provisions for
// attaching water sprinklers at every partition. A sprinkler with range x at partition i can water all
// partitions from i-x to i+x.
// Given an array gallery[ ] consisting of n integers, where gallery[i] is the range of sprinkler
// at partition i (power==-1 indicates no sprinkler attached), return the minimum number of sprinklers
// that need to be turned on to water the complete gallery.
// If there is no possible way to water the full length using the given sprinklers, print -1.
// { Driver Code Starts
// driver code
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution{
public:
int min_sprinklers(int gallery[], int n)
{
// code here
int temp[n];
memset(temp,-1,sizeof(temp));
for(int i=0; i<n; i++){
if(gallery[i] == 0){
temp[i] = max(i, temp[i]);
}else if(gallery[i] != -1){
int end = i+gallery[i];
int start = max(0, i-gallery[i]);
for(int x = start; x <= min(n,end); x++){
temp[x] = max(end, temp[x]);
}
}
}
int ans = 0, i =0 ;
while(i < n){
if(i == -1 || temp[i] == -1)
return -1;
ans++;
i = temp[i] + 1;
}
return ans;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int gallery[n];
for(int i=0; i<n; i++)
cin>> gallery[i];
Solution obj;
cout<< obj.min_sprinklers(gallery,n) << endl;
}
return 1;
}
// } Driver Code Ends
|
f604421cb246aeebe5a50fe9e1234537cb6e2a50
|
e00bb8614664a45a5863dbbd1af0706b4fbdc5c9
|
/9.表达式求值.cpp
|
9ef2a56eb6ffc3968a60fee4ee7476e857cb2a1e
|
[] |
no_license
|
ArgentumHook/BITSS-Data-Structure
|
4ab84724622720f8d2b6f62f48b8f48cd8bae23a
|
efc4d5b0b68fed979e9307e095be9ec5300b7b29
|
refs/heads/master
| 2022-04-22T20:07:04.374144
| 2020-04-23T06:00:33
| 2020-04-23T06:00:33
| 256,190,955
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,714
|
cpp
|
9.表达式求值.cpp
|
#include<cstdio>
#include<cstring>
#include<stack>
#include<iostream>
using namespace std;
stack<char> OP;
stack<int> Number;
char str[100005];
int errorType;
int fpow(int a, int b)
{
int ans = 1;
while (b>0)
{
if (b % 2 == 1)
ans *= a;
b /= 2;
a *= a;
}
return ans;
}
int isp(char ch)
{
switch (ch)
{
case('+'):
return 3;
case('-'):
return 3;
case('*'):
return 5;
case('/'):
return 5;
case('%'):
return 5;
case('('):
return 10;
case('^'):
return 8;
}
}
int icp(char ch)
{
switch (ch)
{
case('+'):
return 4;
case('-'):
return 4;
case('*'):
return 6;
case('/'):
return 6;
case('%'):
return 6;
case('('):
return 1;
case('^'):
return 7;
}
}
int calculate(char op, int a, int b)
{
switch (op)
{
case('+'):
return a + b;
case('-'):
return a - b;
case('*'):
return a * b;
case('/'):
return a / b;
case('%'):
return a % b;
case('^'):
return fpow(a, b);
}
}
int solve(char *s)
{
int num = 0;
errorType = 0;
int numleft = 0;
int numright = 0;
for (int i = 0; s[i]; i++)
{
if (s[i] >= '0'&&s[i] <= '9')
{
if (i>0 && s[i - 1] == ')')
{
errorType = 1;
return -1;
}
num = num * 10 + s[i] - '0';
}
else if (!(s[i] >= '0'&&s[i] <= '9'))
{
if (i > 0 && s[i - 1] == '(' && (s[i] == '%' || s[i] == '*' || s[i] == '/' || s[i] == '^'))
{
errorType = 1;
return -1;
}
if (i>0 && (s[i - 1] >= '0'&&s[i - 1] <= '9'))
{
Number.push(num);
num = 0;
}
else if (i == 0 && (s[i] == '+' || s[i] == '-') && (s[i + 1] >= '0'&&s[i + 1] <= '9'))
{
i++;
int k = i;
while (s[k] && (s[k] >= '0'&&s[k] <= '9'))
{
num = num * 10 + s[k] - '0';
k++;
}
if (s[i - 1] == '-') num *= -1;
i = k - 1;
continue;
}
else if (i == 0 && (s[i] == '%' || s[i] == '*' || s[i] == '/' || s[i] == '^'))
{
errorType = 1;
return -1;
}
else if (i>0 && !(s[i - 1] >= '0'&&s[i - 1] <= '9') && (s[i] == '+' || s[i] == '-') && (s[i + 1] >= '0'&&s[i + 1] <= '9'))
{
i++;
int k = i;
while (s[k] && (s[k] >= '0'&&s[k] <= '9'))
{
num = num * 10 + s[k] - '0';
k++;
}
if (s[i - 1] == '-') num *= -1;
i = k - 1;
continue;
}
if (OP.empty() || s[i] == '(')
{
if (s[i] == '(')
{
if (i > 0 && (s[i - 1] >= '0'&&s[i - 1] <= '9' || s[i - 1] == ')'))
{
errorType = 1;
return -1;
}
}
OP.push(s[i]);
if (s[i] == '(')
numleft++;
continue;
}
else if (s[i] == ')')
{
numright++;
if (numright > numleft)
{
errorType = 1;
return -1;
}
char op;
while (!OP.empty() && (op = OP.top()) != '(')
{
int b = Number.top();
Number.pop();
int a = Number.top();
Number.pop();
if (b == 0 && op == '/')
{
errorType = 2;
return -1;
}
else if (b < 0 && op == '^')
{
errorType = 1;
return -1;
}
else
Number.push(calculate(op, a, b));
OP.pop();
}
OP.pop();
}
else
{
char op;
while (!OP.empty() && icp(OP.top()) > isp(s[i]))
{
op = OP.top();
int b = Number.top();
Number.pop();
int a = Number.top();
Number.pop();
if (b == 0 && op == '/')
{
errorType = 2;
return -1;
}
else if (b < 0 && op == '^')
{
errorType = 1;
return -1;
}
else
Number.push(calculate(op, a, b));
OP.pop();
}
OP.push(s[i]);
}
}
}
if (s[strlen(s) - 1] >= '0'&&s[strlen(s) - 1] <= '9')
Number.push(num);
if (!OP.empty() || !Number.empty())
{
while (!OP.empty())
{
char op = OP.top();
if (op == '(')
{
errorType = 1;
return -1;
}
int b = Number.top();
Number.pop();
int a = Number.top();
Number.pop();
if (b == 0 && op == '/')
{
errorType = 2;
return -1;
}
else if (b < 0 && op == '^')
{
errorType = 1;
return -1;
}
else
Number.push(calculate(op, a, b));
OP.pop();
}
return Number.top();
}
else return num;
}
int main()
{
int T;
cin >> T;
while (T--)
{
while (!OP.empty())
OP.pop();
while (!Number.empty())
Number.pop();
cin >> str;
int ans = solve(str);
if (errorType == 1)
cout << "error." << endl;
else if (errorType == 2)
cout << "Divide 0." << endl;
else
cout << ans << endl;
}
return 0;
}
|
808a16c85a8a796bd6b09959cf4beed3265b0fad
|
412c58404a2937f180838a0d436ea77a1e88aa50
|
/src/common/tm_assert.inc
|
54be483dfaf257d7eb1fb36209f03dd441bb7f58
|
[
"Unlicense",
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
ExternalRepositories/tm
|
6f54b0e6db0a90f27ba67027a538faec216e1187
|
c97a3c14aa769b5a8f94b394b4535cd42eeb31d2
|
refs/heads/master
| 2023-01-23T18:24:51.311720
| 2020-12-05T11:29:24
| 2020-12-05T11:29:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 116
|
inc
|
tm_assert.inc
|
/* assert */
#ifndef TM_ASSERT
#include <assert.h>
#define TM_ASSERT assert
#endif /* !defined(TM_ASSERT) */
|
1b131b8e82f7fb5cf3170b1634f3f9d243514ac2
|
3fbd72ac75213181a7b792f1575fbba9638888ae
|
/3D Engine/src/Renderer/Modules/SkyboxPass.cpp
|
78d61f76a3ab652de1561fa4f1bee9ef644d9fb5
|
[
"Apache-2.0"
] |
permissive
|
BobDeng1974/SaturnEngine
|
b40f4d4e8d1da10d3d31fb5422ea578ac4360a3f
|
0c4db261f5453c4caf75c08bf26a0d2a13f4be69
|
refs/heads/master
| 2020-09-22T06:52:30.973463
| 2019-11-16T19:29:27
| 2019-11-16T19:29:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,199
|
cpp
|
SkyboxPass.cpp
|
#include "Renderer/Modules/SkyboxPass.hpp"
#include "AssetManager/AssetManager.hpp"
#include "ECS/Components/Camera.hpp"
namespace Saturn::RenderModules {
namespace impl {
std::vector<float> skybox_vertices = {
// positions only
-1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f};
}
SkyboxPass::SkyboxPass() : RenderModule(100) {}
void SkyboxPass::init() {
VertexArray::CreateInfo info;
info.vertices = impl::skybox_vertices;
info.dynamic = false;
info.attributes.push_back({0, 3}); // Only positions
skybox_vao.assign(info);
skybox_shader = AssetManager<Shader>::get_resource(
"config/resources/shaders/skybox.sh", true);
}
void SkyboxPass::process(Scene& scene,
Viewport& viewport,
Framebuffer& target) {
using namespace Components;
glDepthMask(GL_FALSE);
Framebuffer::bind(target);
Shader::bind(*skybox_shader);
VertexArray::bind(skybox_vao);
auto& cam = scene.get_ecs().get_with_id<Camera>(viewport.get_camera());
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
if (cam.skybox.is_loaded()) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, cam.skybox->handle);
skybox_shader->set_int(0, 0);
glDrawElements(GL_TRIANGLES, skybox_vao.index_size(), GL_UNSIGNED_INT, nullptr);
}
glDisable(GL_BLEND);
glDepthMask(GL_TRUE);
}
} // namespace Saturn::RenderModules
|
4ea7334859d8078943031cc0fab958ce47131b66
|
9f852b53477cb50b20585eb6e798d5cabeae797a
|
/Source/MathLab/CoordinateSystem/LineBase.cpp
|
ba0afd5619c66fd4060d20970848cd15fd8b3d6b
|
[] |
no_license
|
Spook2U/MathLab
|
57864366675487635040ec6b6c1220b831bc6b05
|
8f457194593453249bf8858fc3d60a0084c82889
|
refs/heads/master
| 2021-01-12T01:05:40.563496
| 2017-03-16T16:55:02
| 2017-03-16T16:55:02
| 78,344,232
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,942
|
cpp
|
LineBase.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "MathLab.h"
#include "LineBase.h"
#include "CoordinateSystemBase.h"
#include "CVectorBase.h"
#include "Lib/MathLabLibrary.h"
// Math Line Structure -------------------------------------------------------------------------------------------------------------------------------
FMathLine::FMathLine() {}
FMathLine::FMathLine(FVector inPosition, FVector inDirection) : position(inPosition), direction(inDirection) {}
FMathLine &FMathLine::operator=(const FMathLine &Other)
{
this->position = Other.position;
this->direction = Other.direction;
return *this;
}
bool FMathLine::operator==(const FMathLine &Other) const
{
MathLabLibrary m;
return ((m.MakeUnitVector(this->direction) == m.MakeUnitVector(Other.direction)) && m.IsPointInLine(*this, FMathPoint(Other.position)));
}
bool FMathLine::operator!=(const FMathLine &Other) const
{
return !(this == &Other);
}
FString FMathLine::ToString()
{
return FString::Printf(TEXT("Position %s, Direction: %s"), *position.ToString(), *direction.ToString());
}
FString FMathLine::ToStringShort()
{
return FString::Printf(TEXT("(%s, %s, %s), (%s, %s, %s)"), *FString::SanitizeFloat(position.X), *FString::SanitizeFloat(position.Y), *FString::SanitizeFloat(position.Z),
*FString::SanitizeFloat(direction.X), *FString::SanitizeFloat(direction.Y), *FString::SanitizeFloat(direction.Z));
}
// Line Class ----------------------------------------------------------------------------------------------------------------------------------------
ALineBase::ALineBase()
{
line = FMathLine();
lineMesh = nullptr;
arrowheadMesh = nullptr;
}
// Unreal Events -------------------------------------------------------------------------------------------------------------------------------------
void ALineBase::BeginPlay()
{
Super::BeginPlay();
}
// Line Setup ----------------------------------------------------------------------------------------------------------------------------------------
void ALineBase::Init(ACoordinateSystemBase *inCoordinateSystem, LaserColors inColor, FMathLine inLine, LineMode inMode, FName inName)
{
if(!MLD_PTR_CHECK(inCoordinateSystem)) return;
type = GeometryType::line;
line = inLine;
mode = inMode;
switch(mode)
{
case LineMode::line: nameMathData = FName(*inLine.ToStringShort()); break;
case LineMode::segment: nameMathData = FName(*inLine.ToStringShort()); break;
case LineMode::vector: nameMathData = FName(*FString::Printf(TEXT("(%s, %s, %s)"), *FString::SanitizeFloat(inLine.direction.X), *FString::SanitizeFloat(inLine.direction.Y), *FString::SanitizeFloat(inLine.direction.Z))); break;
}
Super::Init(inCoordinateSystem, inColor, inName);
switch(mode)
{
case LineMode::line: CreateCVector(inColor); break;
case LineMode::segment: break;
case LineMode::vector: arrowheadMesh->SetVisibility(true); break;
}
InitName(inName);
}
void ALineBase::SetComponents(TArray<UStaticMeshComponent*> components, UTextRenderComponent *inText)
{
for(UStaticMeshComponent *c : components)
{
if(!MLD_PTR_CHECK(c)) continue;
if(c->GetName().Equals("LineMesh")) { this->lineMesh = c; }
if(c->GetName().Equals("ArrowheadMesh")) { this->arrowheadMesh = c; }
}
;
;
if(!(MLD_PTR_CHECK(lineMesh) && MLD_PTR_CHECK(arrowheadMesh) && MLD_PTR_CHECK(inText))) return;
InitScaleLine(lineMesh);
InitScaleArrowhead(arrowheadMesh);
AddLaserComponent(lineMesh);
AddLaserComponent(arrowheadMesh);
arrowheadMesh->SetVisibility(false);
nameRender = inText;
}
// Update Functions ----------------------------------------------------------------------------------------------------------------------------------
void ALineBase::Update()
{
Super::Update();
Move(line.position);
BuildLine();
}
void ALineBase::BuildLine()
{
if(mode == LineMode::segment) { RotateLaserLookAt(line.position, line.direction); }
else { RotateLine(line.direction); }
if (mode == LineMode::line) { SetLaserScale(lineMesh, FVector(NULL, NULL, coordinateSystem->MaxVisibleLength())); }
else if(mode == LineMode::segment) { ScaleLine(lineMesh, UKismetMathLibrary::VSize(line.direction - line.position)); }
else { ScaleVector(lineMesh, arrowheadMesh, UKismetMathLibrary::VSize(line.direction)); }
if (mode == LineMode::segment) { MoveText(nameRender, (line.position + line.direction) / 2); }
else if(mode == LineMode::vector) { MoveText(nameRender, line.position + line.direction/2); }
}
// Setting Functions ---------------------------------------------------------------------------------------------------------------------------------
ALineBase *ALineBase::SetLine(FMathLine inLine)
{
line = inLine;
nameMathData = FName(*inLine.ToStringShort());
if(!(MLD_PTR_CHECK(constVectors[0]) && MLD_PTR_CHECK(constVectors[1]))) return nullptr;
switch(mode)
{
case LineMode::line:
constVectors[0]->SetCVector(FVector::ZeroVector, line.position);
constVectors[1]->SetCVector(line.position, line.direction);
break;
case LineMode::segment:
constVectors[0]->SetCVector(FVector::ZeroVector, line.position);
constVectors[1]->SetCVector(FVector::ZeroVector, line.direction);
break;
case LineMode::vector:
break;
default:
break;
}
Update();
return this;
}
// Utility Functions----------------------------------------------------------------------------------------------------------------------------------
FString ALineBase::ToString()
{
return FString::Printf(TEXT("%s; %s"), *Super::ToString(), *line.ToString());
}
// Constructing Vector Functions ---------------------------------------------------------------------------------------------------------------------
void ALineBase::CreateCVector(LaserColors inColor)
{
if(!MLD_PTR_CHECK(coordinateSystem)) return;
switch(mode)
{
case LineMode::line:
AddCVector(coordinateSystem->AddCVector(coordinateSystem, inColor, FVector::ZeroVector, line.position, CVectorMode::vector, "Position"));
AddCVector(coordinateSystem->AddCVector(coordinateSystem, inColor, line.position, line.direction, CVectorMode::vector, "Direction"));
break;
case LineMode::segment:
AddCVector(coordinateSystem->AddCVector(coordinateSystem, inColor, FVector::ZeroVector, line.position, CVectorMode::vectorPoint, "Point A"));
AddCVector(coordinateSystem->AddCVector(coordinateSystem, inColor, FVector::ZeroVector, line.direction, CVectorMode::vectorPoint, "Point B"));
break;
case LineMode::vector:
break;
default:
break;
}
}
|
8c079c53a6db8fccd09060830870e54f5df7cb07
|
1c8c7a9f8453680f1e477ce7db1923531b35b065
|
/AddressBook.h
|
6fdae9b1e0c9aa987c9a3eb7349de94cf4639f5e
|
[
"BSD-3-Clause"
] |
permissive
|
kytvi2p/i2pd
|
dbe8c6228c0117317d6daadf4de549817fa73ccb
|
73d402525636276ac78aa92ea88535911e21928c
|
refs/heads/master
| 2020-05-31T00:09:45.198691
| 2015-07-06T16:11:17
| 2015-07-06T16:11:17
| 16,423,305
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,248
|
h
|
AddressBook.h
|
#ifndef ADDRESS_BOOK_H__
#define ADDRESS_BOOK_H__
#include <string.h>
#include <string>
#include <map>
#include <vector>
#include <iostream>
#include <mutex>
#include <boost/asio.hpp>
#include "base64.h"
#include "util.h"
#include "Identity.h"
#include "Log.h"
namespace i2p
{
namespace client
{
const char DEFAULT_SUBSCRIPTION_ADDRESS[] = "http://udhdrtrcetjm5sxzskjyr5ztpeszydbh4dpl3pl4utgqqw2v4jna.b32.i2p/hosts.txt";
const int INITIAL_SUBSCRIPTION_UPDATE_TIMEOUT = 3; // in minutes
const int INITIAL_SUBSCRIPTION_RETRY_TIMEOUT = 1; // in minutes
const int CONTINIOUS_SUBSCRIPTION_UPDATE_TIMEOUT = 720; // in minutes (12 hours)
const int CONTINIOUS_SUBSCRIPTION_RETRY_TIMEOUT = 5; // in minutes
const int SUBSCRIPTION_REQUEST_TIMEOUT = 60; //in second
inline std::string GetB32Address(const i2p::data::IdentHash& ident) { return ident.ToBase32().append(".b32.i2p"); }
class AddressBookStorage // interface for storage
{
public:
virtual ~AddressBookStorage () {};
virtual bool GetAddress (const i2p::data::IdentHash& ident, i2p::data::IdentityEx& address) const = 0;
virtual void AddAddress (const i2p::data::IdentityEx& address) = 0;
virtual void RemoveAddress (const i2p::data::IdentHash& ident) = 0;
virtual int Load (std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
virtual int Save (const std::map<std::string, i2p::data::IdentHash>& addresses) = 0;
};
class AddressBookSubscription;
class AddressBook
{
public:
AddressBook ();
~AddressBook ();
void Start ();
void Stop ();
bool GetIdentHash (const std::string& address, i2p::data::IdentHash& ident);
bool GetAddress (const std::string& address, i2p::data::IdentityEx& identity);
const i2p::data::IdentHash * FindAddress (const std::string& address);
void InsertAddress (const std::string& address, const std::string& base64); // for jump service
void InsertAddress (const i2p::data::IdentityEx& address);
void LoadHostsFromStream (std::istream& f);
void DownloadComplete (bool success);
//This method returns the ".b32.i2p" address
std::string ToAddress(const i2p::data::IdentHash& ident) { return GetB32Address(ident); }
std::string ToAddress(const i2p::data::IdentityEx& ident) { return ToAddress(ident.GetIdentHash ()); }
private:
void StartSubscriptions ();
void StopSubscriptions ();
AddressBookStorage * CreateStorage ();
void LoadHosts ();
void LoadSubscriptions ();
void HandleSubscriptionsUpdateTimer (const boost::system::error_code& ecode);
private:
std::mutex m_AddressBookMutex;
std::map<std::string, i2p::data::IdentHash> m_Addresses;
AddressBookStorage * m_Storage;
volatile bool m_IsLoaded, m_IsDownloading;
std::vector<AddressBookSubscription *> m_Subscriptions;
AddressBookSubscription * m_DefaultSubscription; // in case if we don't know any addresses yet
boost::asio::deadline_timer * m_SubscriptionsUpdateTimer;
};
class AddressBookSubscription
{
public:
AddressBookSubscription (AddressBook& book, const std::string& link);
void CheckSubscription ();
private:
void Request ();
private:
AddressBook& m_Book;
std::string m_Link, m_Etag, m_LastModified;
};
}
}
#endif
|
66d65e4962cc1d7f89f24334a8b95a6dc4010980
|
ae956d4076e4fc03b632a8c0e987e9ea5ca89f56
|
/SDK/TBP_UI_LobbyMenu_parameters.h
|
6e1c8f192be54ed7044332995eafd32f57cf0e9a
|
[] |
no_license
|
BrownBison/Bloodhunt-BASE
|
5c79c00917fcd43c4e1932bee3b94e85c89b6bc7
|
8ae1104b748dd4b294609717142404066b6bc1e6
|
refs/heads/main
| 2023-08-07T12:04:49.234272
| 2021-10-02T15:13:42
| 2021-10-02T15:13:42
| 638,649,990
| 1
| 0
| null | 2023-05-09T20:02:24
| 2023-05-09T20:02:23
| null |
UTF-8
|
C++
| false
| false
| 4,239
|
h
|
TBP_UI_LobbyMenu_parameters.h
|
#pragma once
// Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.ShowQuitConfirmation
struct UTBP_UI_LobbyMenu_C_ShowQuitConfirmation_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.ShowLobbyMenu
struct UTBP_UI_LobbyMenu_C_ShowLobbyMenu_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.Get_FindButton_bIsEnabled_1
struct UTBP_UI_LobbyMenu_C_Get_FindButton_bIsEnabled_1_Params
{
bool ReturnValue; // 0x0000(0x0001) (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor)
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.Get_LeaveGroup_Visibility_1
struct UTBP_UI_LobbyMenu_C_Get_LeaveGroup_Visibility_1_Params
{
UMG_ESlateVisibility ReturnValue; // 0x0000(0x0001) (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.Construct
struct UTBP_UI_LobbyMenu_C_Construct_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__HostButton_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__HostButton_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__TBP_UI_MenuButton_C_0_K2Node_ComponentBoundEvent_444_OnClicked__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__TBP_UI_MenuButton_C_0_K2Node_ComponentBoundEvent_444_OnClicked__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__TBP_UI_MenuButton_C_2_K2Node_ComponentBoundEvent_609_OnClicked__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__TBP_UI_MenuButton_C_2_K2Node_ComponentBoundEvent_609_OnClicked__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__TBP_UI_MenuButton_C_3_K2Node_ComponentBoundEvent_620_OnClicked__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__TBP_UI_MenuButton_C_3_K2Node_ComponentBoundEvent_620_OnClicked__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__TBP_UI_ConfirmMenu_K2Node_ComponentBoundEvent_25_Confirm__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__TBP_UI_ConfirmMenu_K2Node_ComponentBoundEvent_25_Confirm__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__QuitConfirmation_K2Node_ComponentBoundEvent_81_Decline__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__QuitConfirmation_K2Node_ComponentBoundEvent_81_Decline__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.BndEvt__ResumeButton_K2Node_ComponentBoundEvent_113_OnClicked__DelegateSignature
struct UTBP_UI_LobbyMenu_C_BndEvt__ResumeButton_K2Node_ComponentBoundEvent_113_OnClicked__DelegateSignature_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.Resume
struct UTBP_UI_LobbyMenu_C_Resume_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.OnOpen
struct UTBP_UI_LobbyMenu_C_OnOpen_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.OnClose
struct UTBP_UI_LobbyMenu_C_OnClose_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.SelectCharacter
struct UTBP_UI_LobbyMenu_C_SelectCharacter_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.LeaveGroup
struct UTBP_UI_LobbyMenu_C_LeaveGroup_Params
{
};
// Function TBP_UI_LobbyMenu.TBP_UI_LobbyMenu_C.ExecuteUbergraph_TBP_UI_LobbyMenu
struct UTBP_UI_LobbyMenu_C_ExecuteUbergraph_TBP_UI_LobbyMenu_Params
{
int EntryPoint; // 0x0000(0x0004) (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
5d667afefd5b6a5dbb175a31c3c9f3bf4d1133e2
|
3ef99240a541f699d71d676db514a4f3001b0c4b
|
/UVa Online Judge/v101/10102.cpp
|
deb80665fa402d426677ff9d63c190282f48458c
|
[
"MIT"
] |
permissive
|
mjenrungrot/competitive_programming
|
36bfdc0e573ea2f8656b66403c15e46044b9818a
|
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
|
refs/heads/master
| 2022-03-26T04:44:50.396871
| 2022-02-10T11:44:13
| 2022-02-10T11:44:13
| 46,323,679
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,129
|
cpp
|
10102.cpp
|
/*=============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 10102.cpp
# Description: UVa Online Judge - 10102
=============================================================================*/
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;
char A[205][205];
int N;
int abs(int x) { return x < 0 ? -x : x; }
int main() {
// freopen("in","r",stdin);
while (scanf("%d", &N) == 1) {
for (int i = 1; i <= N; i++) scanf("%s", &A[i][1]);
int ans = 0;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
if (A[i][j] == '1') {
int tmp = 1e9;
for (int x = 1; x <= N; x++)
for (int y = 1; y <= N; y++) {
if (A[x][y] == '3')
tmp = min(tmp, abs(x - i) + abs(y - j));
}
ans = max(ans, tmp);
}
printf("%d\n", ans);
}
return 0;
}
|
c17acd69f4e8ade8f210f4e54a6b349c89cea6cf
|
0f2b5bc88765b067541736692a4c13fd0555b25d
|
/Grader/RangeInsert.h
|
e499b672183d20607bef3fa418db174a94055edb
|
[] |
no_license
|
Omeracan/cpp_datastruct
|
dd9da3f7e814216569dc80947f15b286221a10c5
|
db1528a1411963638ca56e28fcb25b819bca6627
|
refs/heads/master
| 2020-04-05T20:55:44.638481
| 2018-11-07T11:45:43
| 2018-11-07T11:45:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 386
|
h
|
RangeInsert.h
|
#ifndef __STUDENT_H_
#define __STUDENT_H_
template <typename T>
void CP::vector<T>::insert(iterator position,iterator first,iterator last)
{
std::vector<T> insertVector(first,last),temporaryVector(position,end());
resize(position-begin());
for(auto obj : insertVector)push_back(obj);
for(auto obj : temporaryVector)push_back(obj);
//write your code here
}
#endif
|
f8cc9108a8b9438273a3dad53f56e6107f331d38
|
dfd413672b1736044ae6ca2e288a69bf9de3cfda
|
/chrome/browser/history/top_sites.cc
|
1206843b0fb9858f999a777f4f76809aa474e082
|
[
"BSD-3-Clause"
] |
permissive
|
cha63506/chromium-capsicum
|
fb71128ba218fec097265908c2f41086cdb99892
|
b03da8e897f897c6ad2cda03ceda217b760fd528
|
HEAD
| 2017-10-03T02:40:24.085668
| 2010-02-01T15:24:05
| 2010-02-01T15:24:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,830
|
cc
|
top_sites.cc
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/history/top_sites.h"
#include "app/gfx/codec/jpeg_codec.h"
#include "base/logging.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace history {
TopSites::TopSites() {
}
TopSites::~TopSites() {
}
bool TopSites::Init() {
// TODO(brettw) read the database here.
return true;
}
bool TopSites::SetPageThumbnail(const GURL& url,
const SkBitmap& thumbnail,
const ThumbnailScore& score) {
AutoLock lock(lock_);
std::map<GURL, size_t>::iterator found = canonical_urls_.find(url);
if (found == canonical_urls_.end())
return false; // This URL is not known to us.
MostVisitedURL& most_visited = top_sites_[found->second];
Images& image = top_images_[most_visited.url];
// When comparing the thumbnail scores, we need to take into account the
// redirect hops, which are not generated when the thumbnail is becuase the
// redirects weren't known. We fill that in here since we know the redirects.
ThumbnailScore new_score_with_redirects(score);
new_score_with_redirects.redirect_hops_from_dest =
GetRedirectDistanceForURL(most_visited, url);
if (!ShouldReplaceThumbnailWith(image.thumbnail_score,
new_score_with_redirects))
return false; // The one we already have is better.
image.thumbnail = new RefCountedBytes;
SkAutoLockPixels thumbnail_lock(thumbnail);
bool encoded = gfx::JPEGCodec::Encode(
reinterpret_cast<unsigned char*>(thumbnail.getAddr32(0, 0)),
gfx::JPEGCodec::FORMAT_BGRA, thumbnail.width(),
thumbnail.height(),
static_cast<int>(thumbnail.rowBytes()), 90,
&image.thumbnail->data);
if (!encoded)
return false;
image.thumbnail_score = new_score_with_redirects;
return true;
}
void TopSites::StoreMostVisited(std::vector<MostVisitedURL>* most_visited) {
lock_.AssertAcquired();
// TODO(brettw) filter for blacklist!
if (!top_sites_.empty()) {
std::vector<size_t> added;
std::vector<size_t> deleted;
std::vector<size_t> moved;
DiffMostVisited(top_sites_, *most_visited, &added, &deleted, &moved);
// Delete all the thumbnails associated with URLs that were deleted.
for (size_t i = 0; i < deleted.size(); i++) {
std::map<GURL, Images>::iterator found =
top_images_.find(top_sites_[deleted[i]].url);
if (found != top_images_.end())
top_images_.erase(found);
}
// TODO(brettw) write the new data to disk.
}
// Take ownership of the most visited data.
top_sites_.clear();
top_sites_.swap(*most_visited);
// Save the redirect information for quickly mapping to the canonical URLs.
canonical_urls_.clear();
for (size_t i = 0; i < top_sites_.size(); i++)
StoreRedirectChain(top_sites_[i].redirects, i);
}
void TopSites::StoreRedirectChain(const RedirectList& redirects,
size_t destination) {
lock_.AssertAcquired();
if (redirects.empty()) {
NOTREACHED();
return;
}
// We shouldn't get any duplicates.
DCHECK(canonical_urls_.find(redirects[0]) == canonical_urls_.end());
// Map all the redirected URLs to the destination.
for (size_t i = 0; i < redirects.size(); i++)
canonical_urls_[redirects[i]] = destination;
}
GURL TopSites::GetCanonicalURL(const GURL& url) const {
lock_.AssertAcquired();
std::map<GURL, size_t>::const_iterator found = canonical_urls_.find(url);
if (found == canonical_urls_.end())
return GURL(); // Don't know anything about this URL.
return top_sites_[found->second].url;
}
// static
int TopSites::GetRedirectDistanceForURL(const MostVisitedURL& most_visited,
const GURL& url) {
for (size_t i = 0; i < most_visited.redirects.size(); i++) {
if (most_visited.redirects[i] == url)
return static_cast<int>(most_visited.redirects.size() - i - 1);
}
NOTREACHED() << "URL should always be found.";
return 0;
}
// static
void TopSites::DiffMostVisited(const std::vector<MostVisitedURL>& old_list,
const std::vector<MostVisitedURL>& new_list,
std::vector<size_t>* added_urls,
std::vector<size_t>* deleted_urls,
std::vector<size_t>* moved_urls) {
added_urls->clear();
deleted_urls->clear();
moved_urls->clear();
// Add all the old URLs for quick lookup. This maps URLs to the corresponding
// index in the input.
std::map<GURL, size_t> all_old_urls;
for (size_t i = 0; i < old_list.size(); i++)
all_old_urls[old_list[i].url] = i;
// Check all the URLs in the new set to see which ones are new or just moved.
// When we find a match in the old set, we'll reset its index to our special
// marker. This allows us to quickly identify the deleted ones in a later
// pass.
const size_t kAlreadyFoundMarker = static_cast<size_t>(-1);
for (size_t i = 0; i < new_list.size(); i++) {
std::map<GURL, size_t>::iterator found = all_old_urls.find(new_list[i].url);
if (found == all_old_urls.end()) {
added_urls->push_back(i);
} else {
if (found->second != i)
moved_urls->push_back(i);
found->second = kAlreadyFoundMarker;
}
}
// Any member without the special marker in the all_old_urls list means that
// there wasn't a "new" URL that mapped to it, so it was deleted.
for (std::map<GURL, size_t>::const_iterator i = all_old_urls.begin();
i != all_old_urls.end(); ++i) {
if (i->second != kAlreadyFoundMarker)
deleted_urls->push_back(i->second);
}
}
} // namespace history
|
adfe8fd638852ceebe670435035712a398ce9aff
|
a4a221e9c6a0dd775c8122f51d5bce9cae2e16a6
|
/bora/Usuario.cpp
|
1f229f004db091f10b29012df01c2373747c98b4
|
[] |
no_license
|
AkatoshiVictor/Projeto-TC-AirPlane
|
48cd20cd6ea1dd1a2e304440c547c762ca1f929b
|
3f38a536e005df2b05a6d5964270322836785c7d
|
refs/heads/main
| 2023-08-28T02:56:16.017572
| 2021-10-12T18:58:17
| 2021-10-12T18:58:17
| 405,777,715
| 0
| 1
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 4,174
|
cpp
|
Usuario.cpp
|
#include "Usuario.h"
Usuario::Usuario(){
}
Usuario::Usuario(string email, string senha, string nome_completo, string data_nascimento,
string endereco, string telefone, string telefone_familiar, string documento,
int classe_do_funcionario, float orcamento, string acompanhante, float gastos_totais
, float salario){
this-> email = email;
this-> senha = senha;
this-> nome_completo = nome_completo;
this-> data_nascimento = data_nascimento;
this-> endereco = endereco;
this-> telefone = telefone;
this-> telefone_familiar = telefone_familiar;
this-> documento = documento;
this-> classe_do_funcionario = classe_do_funcionario;
this-> orcamento = orcamento;
this-> acompanhante = acompanhante;
this-> gastos_totais = gastos_totais;
this-> salario = salario;
}
void Usuario::set_email(string email){
this-> email = email;
}
void Usuario::set_senha(string senha){
this-> senha = senha;
}
void Usuario::set_nome_completo(string nome_completo){
this-> nome_completo = nome_completo;
}
void Usuario::set_data_nascimento(string data_nascimento){
this-> data_nascimento = data_nascimento;
}
void Usuario::set_endereco(string endereco){
this-> endereco = endereco;
}
void Usuario::set_telefone(string telefone){
this-> telefone = telefone;
}
void Usuario::set_telefone_familiar(string telefone_familiar){
this-> telefone_familiar = telefone_familiar;
}
void Usuario::set_documento(string documento){
this-> documento = documento;
}
void Usuario::set_classe_do_funcionario(int classe_do_funcionario){
this-> classe_do_funcionario = classe_do_funcionario;
}
void Usuario::set_orcamento(float orcamento){
this-> orcamento = orcamento;
}
void Usuario::set_acompanhante(string acompanhante){
this-> acompanhante = acompanhante;
}
void Usuario::set_gastos_totais(float gastos_totais){
this-> gastos_totais = gastos_totais;
}
void Usuario::set_salario(float salario){
this-> salario = salario;
}
string Usuario::get_email() const{
return email;
}
string Usuario::get_senha() const{
return senha;
}
string Usuario::get_nome_completo() const{
return nome_completo;
}
string Usuario::get_data_nascimento() const{
return data_nascimento;
}
string Usuario::get_endereco() const{
return endereco;
}
string Usuario::get_telefone() const{
return telefone;
}
string Usuario::get_telefone_familiar() const{
return telefone_familiar;
}
string Usuario::get_documento() const{
return documento;
}
int Usuario::get_classe_do_funcionario() const{
return classe_do_funcionario;
}
float Usuario::get_orcamento() const{
return orcamento;
}
string Usuario::get_acompanhante() const{
return acompanhante;
}
float Usuario::get_gastos_totais() const{
return gastos_totais;
}
float Usuario::get_salario() const{
return salario;
}
void Usuario::testar_classe(){ //Será excluída no projeto!
cout << "Email: " << get_email() << endl << "Senha: " << get_senha() << endl << "Nome completo: "
<< get_nome_completo() << endl << "Data de nascimento: " << get_data_nascimento() << endl
<< "Endereço: " << get_endereco() << endl << "Telefone: " << get_telefone() << endl << "Telefone familiar: "
<< get_telefone_familiar() << endl << "Documento: " << get_documento() << endl << "Classe do funcionário: "
<< get_classe_do_funcionario() << endl << "Orçamento: " << get_orcamento() << endl << "Acompanhante: "
<< get_acompanhante() << endl << "Gastos totais: " << get_gastos_totais() << endl;
}
void Usuario::set_tag(string A){
Tag = Tag + " " + A + " ";
}
string Usuario::get_Tag() const{
return Tag;
}
Usuario::Usuario(string Email, string Senha, string Nome, string Data, string Endereco, string Telefone, string TelefoneF,
string Documento, int Salario){
set_email(Email);
set_senha(Senha);
set_nome_completo(Nome);
set_data_nascimento(Data);
set_endereco(Endereco);
set_telefone(Telefone);
set_telefone_familiar(TelefoneF);
set_documento(Documento);
set_salario(Salario);
}
|
6e3db8bcb9a6bacad3ce67b2fa06c4295be41275
|
cad04bb71f3afd50c4df3b2f321cd378d3ad8cb9
|
/Book practices/《C++primer》 5th 练习代码/chapter2/Exercise2.35.cpp
|
43041e4169b03b3dd9fd213e7cc82d6907b417bf
|
[] |
no_license
|
SourDumplings/CodeSolutions
|
9033de38005b1d90488e64ccbb99f91c7e7b71ec
|
5f9eca3fe5701a8fca234343fde31cfcba94cf27
|
refs/heads/master
| 2023-08-16T17:23:34.977471
| 2023-08-07T13:14:47
| 2023-08-07T13:14:47
| 110,331,879
| 10
| 8
| null | 2023-06-14T22:25:16
| 2017-11-11T08:59:11
|
C
|
UTF-8
|
C++
| false
| false
| 683
|
cpp
|
Exercise2.35.cpp
|
/*
@Date : 2017-12-14 16:10:21
@Author : 酸饺子 (changzheng300@foxmail.com)
@Link : https://github.com/SourDumplings
@Version : $Id$
*/
/*
p70
运行结果:
i
i
i
PKi
i
i
*/
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <typeinfo>
using namespace std;
int main()
{
const int i = 42;
auto j = i;
const auto &k = i;
auto *p = &i;
const auto j2 = i, &k2 = i;
cout << typeid(i).name() << endl;
cout << typeid(j).name() << endl;
cout << typeid(k).name() << endl;
cout << typeid(p).name() << endl;
cout << typeid(j2).name() << endl;
cout << typeid(k2).name() << endl;
return 0;
}
|
b988cde6fd331a85fbea928baea21fb84f86f146
|
bb9d814e83303e4740e3c30bc6137c6ec99791c5
|
/evaluate_odometry.cpp
|
29d02537f43f0397eeba3d9151ad1050e4c406e5
|
[] |
no_license
|
cds-mipt/kitti-eval-itl
|
991b8c10c329e5483ccee670d5c228e7a1be7327
|
93bb748ee72a8ef62f158078e70add30adef8e50
|
refs/heads/master
| 2021-02-15T22:30:16.776592
| 2020-09-10T10:26:22
| 2020-09-10T10:26:22
| 244,939,059
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 19,791
|
cpp
|
evaluate_odometry.cpp
|
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <limits>
#include <string.h>
#include "mail.h"
#include "matrix.h"
using namespace std;
#define M_PI 3.14159265358979323846
// static parameter
// float lengths[] = ;
int sets_of_lengths_num = 2;
float all_sets_of_lengths[][10] = {{100,200,300,400,500,600,700,800},
{5,10,25,50,75,100,150,200}};
int32_t num_lengths_of_all_sets[] = {8,8};
float *lengths;
int32_t num_lengths = -1;
int coord_1_idx = -1, coord_2_idx = -1;
char *axis_names[] = {"x", "y", "z"};
int view = -1;
struct errors {
int32_t first_frame;
float r_err;
float t_err;
float len;
float speed;
errors (int32_t first_frame,float r_err,float t_err,float len,float speed) :
first_frame(first_frame),r_err(r_err),t_err(t_err),len(len),speed(speed) {}
};
vector<Matrix> loadPoses(string file_name) {
vector<Matrix> poses;
FILE *fp = fopen(file_name.c_str(),"r");
if (!fp)
return poses;
while (!feof(fp)) {
Matrix P = Matrix::eye(4);
if (fscanf(fp, "%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf",
&P.val[0][0], &P.val[0][1], &P.val[0][2], &P.val[0][3],
&P.val[1][0], &P.val[1][1], &P.val[1][2], &P.val[1][3],
&P.val[2][0], &P.val[2][1], &P.val[2][2], &P.val[2][3] )==12) {
poses.push_back(P);
}
}
fclose(fp);
return poses;
}
vector<float> trajectoryDistances (vector<Matrix> &poses) {
vector<float> dist;
dist.push_back(0);
for (int32_t i=1; i<poses.size(); i++) {
Matrix P1 = poses[i-1];
Matrix P2 = poses[i];
float dx = P1.val[0][3]-P2.val[0][3];
float dy = P1.val[1][3]-P2.val[1][3];
float dz = P1.val[2][3]-P2.val[2][3];
dist.push_back(dist[i-1]+sqrt(dx*dx+dy*dy+dz*dz));
}
return dist;
}
int32_t lastFrameFromSegmentLength(vector<float> &dist,int32_t first_frame,float len) {
for (int32_t i=first_frame; i<dist.size(); i++)
if (dist[i]>dist[first_frame]+len)
return i;
return -1;
}
inline float rotationError(Matrix &pose_error) {
float a = pose_error.val[0][0];
float b = pose_error.val[1][1];
float c = pose_error.val[2][2];
float d = 0.5*(a+b+c-1.0);
return acos(max(min(d,1.0f),-1.0f));
}
inline float translationError(Matrix &pose_error) {
float dx = pose_error.val[0][3];
float dy = pose_error.val[1][3];
float dz = pose_error.val[2][3];
return sqrt(dx*dx+dy*dy+dz*dz);
}
vector<errors> calcSequenceErrors (vector<Matrix> &poses_gt,vector<Matrix> &poses_result) {
// error vector
vector<errors> err;
// parameters
int32_t step_size = 10; // every second
// pre-compute distances (from ground truth as reference)
vector<float> dist = trajectoryDistances(poses_gt);
// for all start positions do
for (int32_t first_frame=0; first_frame<poses_gt.size(); first_frame+=step_size) {
// for all segment lengths do
for (int32_t i=0; i<num_lengths; i++) {
// current length
float len = lengths[i];
// compute last frame
int32_t last_frame = lastFrameFromSegmentLength(dist,first_frame,len);
// continue, if sequence not long enough
if (last_frame==-1)
continue;
// compute rotational and translational errors
Matrix pose_delta_gt = Matrix::inv(poses_gt[first_frame])*poses_gt[last_frame];
Matrix pose_delta_result = Matrix::inv(poses_result[first_frame])*poses_result[last_frame];
Matrix pose_error = Matrix::inv(pose_delta_result)*pose_delta_gt;
float r_err = rotationError(pose_error);
float t_err = translationError(pose_error);
// compute speed
float num_frames = (float)(last_frame-first_frame+1);
float speed = len/(0.1*num_frames);
// write to file
err.push_back(errors(first_frame,r_err/len,t_err/len,len,speed));
}
}
// return error vector
return err;
}
float calcAbsoluteTranslationError(vector<Matrix> &poses_gt, vector<Matrix> &poses_result) {
float sum_of_squares = 0;
for (int32_t frame=0; frame<poses_gt.size(); frame+=1) {
Matrix pose_gt = Matrix::inv(poses_gt[0])*poses_gt[frame];
Matrix pose_result = Matrix::inv(poses_result[0])*poses_result[frame];
float x_gt=pose_gt.val[0][3], y_gt=pose_gt.val[1][3], z_gt=pose_gt.val[2][3];
float x_result=pose_result.val[0][3], y_result=pose_result.val[1][3], z_result=pose_result.val[2][3];
float dx=x_gt-x_result, dy=y_gt-y_result, dz=z_gt-z_result;
sum_of_squares += dx*dx + dy*dy + dz*dz;
}
return sqrt(sum_of_squares / poses_gt.size());
}
void saveSequenceErrors (vector<errors> &err,string file_name) {
// open file
FILE *fp;
fp = fopen(file_name.c_str(),"w");
// write to file
for (vector<errors>::iterator it=err.begin(); it!=err.end(); it++)
fprintf(fp,"%d %f %f %f %f\n",it->first_frame,it->r_err,it->t_err,it->len,it->speed);
// close file
fclose(fp);
}
void savePathPlot (vector<Matrix> &poses_gt,vector<Matrix> &poses_result,string file_name) {
// parameters
int32_t step_size = 3;
// open file
FILE *fp = fopen(file_name.c_str(),"w");
// save x/z coordinates of all frames to file
for (int32_t i=0; i<poses_gt.size(); i+=step_size)
fprintf(fp,"%f %f %f %f %f %f\n",poses_gt[i].val[0][3],poses_gt[i].val[1][3],poses_gt[i].val[2][3],
poses_result[i].val[0][3],poses_result[i].val[1][3],poses_result[i].val[2][3]);
// close file
fclose(fp);
}
vector<float> computeRoi (vector<Matrix> &poses_gt,vector<Matrix> &poses_result) {
float coord_1_min = numeric_limits<int32_t>::max();
float coord_1_max = numeric_limits<int32_t>::min();
float coord_2_min = numeric_limits<int32_t>::max();
float coord_2_max = numeric_limits<int32_t>::min();
for (vector<Matrix>::iterator it=poses_gt.begin(); it!=poses_gt.end(); it++) {
float coord_1 = it->val[coord_1_idx][3];
float coord_2 = it->val[coord_2_idx][3];
if (coord_1<coord_1_min) coord_1_min = coord_1; if (coord_1>coord_1_max) coord_1_max = coord_1;
if (coord_2<coord_2_min) coord_2_min = coord_2; if (coord_2>coord_2_max) coord_2_max = coord_2;
}
for (vector<Matrix>::iterator it=poses_result.begin(); it!=poses_result.end(); it++) {
float coord_1 = it->val[coord_1_idx][3];
float coord_2 = it->val[coord_2_idx][3];
if (coord_1<coord_1_min) coord_1_min = coord_1; if (coord_1>coord_1_max) coord_1_max = coord_1;
if (coord_2<coord_2_min) coord_2_min = coord_2; if (coord_2>coord_2_max) coord_2_max = coord_2;
}
float dcoord_1 = 1.1*(coord_1_max-coord_1_min);
float dcoord_2 = 1.1*(coord_2_max-coord_2_min);
float mcoord_1 = 0.5*(coord_1_max+coord_1_min);
float mcoord_2 = 0.5*(coord_2_max+coord_2_min);
float r = 0.5*max(dcoord_1,dcoord_2);
vector<float> roi;
roi.push_back(mcoord_1-r);
roi.push_back(mcoord_1+r);
roi.push_back(mcoord_2-r);
roi.push_back(mcoord_2+r);
return roi;
}
void plotPathPlot (string dir,vector<float> &roi,int32_t idx) {
// gnuplot file name
char command[1024];
char file_name[256];
sprintf(file_name,"%02d.gp",idx);
string full_name = dir + "/" + file_name;
// create png + eps
for (int32_t i=0; i<2; i++) {
// open file
FILE *fp = fopen(full_name.c_str(),"w");
// save gnuplot instructions
if (i==0) {
fprintf(fp,"set term png size 900,900\n");
fprintf(fp,"set output \"%02d.png\"\n",idx);
} else {
fprintf(fp,"set term postscript eps enhanced color\n");
fprintf(fp,"set output \"%02d.eps\"\n",idx);
}
fprintf(fp,"set size ratio -1\n");
fprintf(fp,"set xrange [%f:%f]\n",roi[0],roi[1]);
fprintf(fp,"set yrange [%f:%f]\n",roi[2],roi[3]);
fprintf(fp,"set xlabel \"%s [m]\"\n", axis_names[coord_1_idx]);
fprintf(fp,"set ylabel \"%s [m]\"\n", axis_names[coord_2_idx]);
fprintf(fp,"plot \"%02d.txt\" using %d:%d lc rgb \"#FF0000\" title 'Ground Truth' w lines,",idx,coord_1_idx+1,coord_2_idx+1);
fprintf(fp,"\"%02d.txt\" using %d:%d lc rgb \"#0000FF\" title 'Visual Odometry' w lines,",idx,coord_1_idx+1+3,coord_2_idx+1+3);
fprintf(fp,"\"< head -1 %02d.txt\" using %d:%d lc rgb \"#000000\" pt 4 ps 1 lw 2 title 'Sequence Start' w points\n",idx,coord_1_idx+1,coord_2_idx+1);
// close file
fclose(fp);
// run gnuplot => create png + eps
sprintf(command,"cd %s; gnuplot %s",dir.c_str(),file_name);
system(command);
}
// create pdf and crop
sprintf(command,"cd %s; ps2pdf %02d.eps %02d_large.pdf",dir.c_str(),idx,idx);
system(command);
sprintf(command,"cd %s; pdfcrop %02d_large.pdf %02d.pdf",dir.c_str(),idx,idx);
system(command);
sprintf(command,"cd %s; rm %02d_large.pdf",dir.c_str(),idx);
system(command);
}
void saveErrorPlots(vector<errors> &seq_err,string plot_error_dir,char* prefix) {
// file names
char file_name_tl[1024]; sprintf(file_name_tl,"%s/%s_tl.txt",plot_error_dir.c_str(),prefix);
char file_name_rl[1024]; sprintf(file_name_rl,"%s/%s_rl.txt",plot_error_dir.c_str(),prefix);
char file_name_ts[1024]; sprintf(file_name_ts,"%s/%s_ts.txt",plot_error_dir.c_str(),prefix);
char file_name_rs[1024]; sprintf(file_name_rs,"%s/%s_rs.txt",plot_error_dir.c_str(),prefix);
// open files
FILE *fp_tl = fopen(file_name_tl,"w");
FILE *fp_rl = fopen(file_name_rl,"w");
FILE *fp_ts = fopen(file_name_ts,"w");
FILE *fp_rs = fopen(file_name_rs,"w");
// for each segment length do
for (int32_t i=0; i<num_lengths; i++) {
float t_err = 0;
float r_err = 0;
float num = 0;
// for all errors do
for (vector<errors>::iterator it=seq_err.begin(); it!=seq_err.end(); it++) {
if (fabs(it->len-lengths[i])<1.0) {
t_err += it->t_err;
r_err += it->r_err;
num++;
}
}
// we require at least 3 values
if (num>2.5) {
fprintf(fp_tl,"%f %f\n",lengths[i],t_err/num);
fprintf(fp_rl,"%f %f\n",lengths[i],r_err/num);
}
}
// for each driving speed do (in m/s)
for (float speed=2; speed<25; speed+=2) {
float t_err = 0;
float r_err = 0;
float num = 0;
// for all errors do
for (vector<errors>::iterator it=seq_err.begin(); it!=seq_err.end(); it++) {
if (fabs(it->speed-speed)<2.0) {
t_err += it->t_err;
r_err += it->r_err;
num++;
}
}
// we require at least 3 values
if (num>2.5) {
fprintf(fp_ts,"%f %f\n",speed,t_err/num);
fprintf(fp_rs,"%f %f\n",speed,r_err/num);
}
}
// close files
fclose(fp_tl);
fclose(fp_rl);
fclose(fp_ts);
fclose(fp_rs);
}
void plotErrorPlots (string dir,char* prefix) {
char command[1024];
// for all four error plots do
for (int32_t i=0; i<4; i++) {
// create suffix
char suffix[16];
switch (i) {
case 0: sprintf(suffix,"tl"); break;
case 1: sprintf(suffix,"rl"); break;
case 2: sprintf(suffix,"ts"); break;
case 3: sprintf(suffix,"rs"); break;
}
// gnuplot file name
char file_name[1024]; char full_name[1024];
sprintf(file_name,"%s_%s.gp",prefix,suffix);
sprintf(full_name,"%s/%s",dir.c_str(),file_name);
// create png + eps
for (int32_t j=0; j<2; j++) {
// open file
FILE *fp = fopen(full_name,"w");
// save gnuplot instructions
if (j==0) {
fprintf(fp,"set term png size 500,250 font \"Helvetica\" 11\n");
fprintf(fp,"set output \"%s_%s.png\"\n",prefix,suffix);
} else {
fprintf(fp,"set term postscript eps enhanced color\n");
fprintf(fp,"set output \"%s_%s.eps\"\n",prefix,suffix);
}
// start plot at 0
fprintf(fp,"set size ratio 0.5\n");
fprintf(fp,"set yrange [0:*]\n");
// x label
if (i<=1) fprintf(fp,"set xlabel \"Path Length [m]\"\n");
else fprintf(fp,"set xlabel \"Speed [km/h]\"\n");
// y label
if (i==0 || i==2) fprintf(fp,"set ylabel \"Translation Error [%%]\"\n");
else fprintf(fp,"set ylabel \"Rotation Error [deg/m]\"\n");
// plot error curve
fprintf(fp,"plot \"%s_%s.txt\" using ",prefix,suffix);
switch (i) {
case 0: fprintf(fp,"1:($2*100) title 'Translation Error'"); break;
case 1: fprintf(fp,"1:($2*57.3) title 'Rotation Error'"); break;
case 2: fprintf(fp,"($1*3.6):($2*100) title 'Translation Error'"); break;
case 3: fprintf(fp,"($1*3.6):($2*57.3) title 'Rotation Error'"); break;
}
fprintf(fp," lc rgb \"#0000FF\" pt 4 w linespoints\n");
// close file
fclose(fp);
// run gnuplot => create png + eps
sprintf(command,"cd %s; gnuplot %s",dir.c_str(),file_name);
system(command);
}
// create pdf and crop
sprintf(command,"cd %s; ps2pdf %s_%s.eps %s_%s_large.pdf",dir.c_str(),prefix,suffix,prefix,suffix);
system(command);
sprintf(command,"cd %s; pdfcrop %s_%s_large.pdf %s_%s.pdf",dir.c_str(),prefix,suffix,prefix,suffix);
system(command);
sprintf(command,"cd %s; rm %s_%s_large.pdf",dir.c_str(),prefix,suffix);
system(command);
}
}
void saveStats (vector<errors> err,string dir) {
float t_err = 0;
float r_err = 0;
// for all errors do => compute sum of t_err, r_err
for (vector<errors>::iterator it=err.begin(); it!=err.end(); it++) {
t_err += it->t_err;
r_err += it->r_err;
}
// open file
FILE *fp = fopen((dir + "/stats.txt").c_str(),"w");
// save errors
float num = err.size();
fprintf(fp,"%f %f\n",t_err/num,r_err/num);
// close file
fclose(fp);
}
void getStats (vector<errors> err,float& _t_err,float& _r_err) {
float t_err = 0;
float r_err = 0;
// for all errors do => compute sum of t_err, r_err
for (vector<errors>::iterator it=err.begin(); it!=err.end(); it++) {
t_err += it->t_err;
r_err += it->r_err;
}
// save errors
float num = err.size();
_t_err = t_err/num;
_r_err = r_err/num;
}
void saveResults(float seq_t_err[],float seq_r_err[],float seq_ate[],vector<errors> total_err,int seq_nums[],int seq_nums_end,string dir) {
int i;
FILE *fp = fopen((dir + "/results.txt").c_str(),"w");
fprintf(fp, "translation_error(%) rotation_error(deg/m) ATE(m)\n");
for (i = 0; i < seq_nums_end; i++) {
fprintf(fp,"%2d: %f %f %f\n",seq_nums[i],seq_t_err[i]*100,seq_r_err[i]/M_PI*180, seq_ate[i]);
}
fprintf(fp,"\n");
float t_err = 0;
float r_err = 0;
for (i = 0; i < seq_nums_end; i++) {
t_err += seq_t_err[i];
r_err += seq_r_err[i];
}
fprintf(fp,"Mean errors: %f %f\n",t_err/seq_nums_end*100,r_err/seq_nums_end/M_PI*180);
t_err = 0;
r_err = 0;
for (vector<errors>::iterator it=total_err.begin(); it!=total_err.end(); it++) {
t_err += it->t_err;
r_err += it->r_err;
}
float num = total_err.size();
fprintf(fp,"In total: %f %f\n",t_err/num*100,r_err/num/M_PI*180);
fclose(fp);
}
bool eval (string result_sha,Mail* mail) {
// ground truth and result directories
string gt_dir = "data/odometry/poses";
string result_dir = result_sha;
string error_dir = result_dir + "/errors";
string plot_path_dir = result_dir + "/plot_path";
string plot_error_dir = result_dir + "/plot_error";
// create output directories
system(("mkdir " + error_dir).c_str());
system(("mkdir " + plot_path_dir).c_str());
system(("mkdir " + plot_error_dir).c_str());
// total errors
vector<errors> total_err;
float seq_t_err[22];
float seq_r_err[22];
float seq_ate[22];
int seq_nums[22];
int seq_nums_ptr = 0;
// for all sequences do
for (int32_t i=0; i<22; i++) {
// file name
char file_name[256];
sprintf(file_name,"%02d.txt",i);
// read ground truth and result poses
vector<Matrix> poses_gt = loadPoses(gt_dir + "/" + file_name);
if (poses_gt.size() == 0) {
continue;
}
vector<Matrix> poses_result = loadPoses(result_dir + "/data/" + file_name);
if (poses_result.size() == 0) {
continue;
}
// plot status
mail->msg("Processing: %s, poses: %d/%d",file_name,poses_result.size(),poses_gt.size());
// check for errors
if (poses_gt.size()==0 || poses_result.size()!=poses_gt.size()) {
mail->msg("ERROR: Couldn't read (all) poses of: %s", file_name);
continue;
}
// compute sequence errors
vector<errors> seq_err = calcSequenceErrors(poses_gt,poses_result);
saveSequenceErrors(seq_err,error_dir + "/" + file_name);
getStats(seq_err,seq_t_err[seq_nums_ptr],seq_r_err[seq_nums_ptr]);
seq_nums[seq_nums_ptr] = i;
// compute trajectory errors
seq_ate[seq_nums_ptr] = calcAbsoluteTranslationError(poses_gt, poses_result);
// add to total errors
total_err.insert(total_err.end(),seq_err.begin(),seq_err.end());
// for all => plot trajectory and compute individual stats
if ((i<=15) or true) {
// save + plot bird's eye view trajectories
savePathPlot(poses_gt,poses_result,plot_path_dir + "/" + file_name);
vector<float> roi = computeRoi(poses_gt,poses_result);
plotPathPlot(plot_path_dir,roi,i);
// save + plot individual errors
char prefix[16];
sprintf(prefix,"%02d",i);
saveErrorPlots(seq_err,plot_error_dir,prefix);
plotErrorPlots(plot_error_dir,prefix);
}
seq_nums_ptr++;
}
// save + plot total errors + summary statistics
if (total_err.size()>0) {
char prefix[16];
sprintf(prefix,"avg");
saveErrorPlots(total_err,plot_error_dir,prefix);
plotErrorPlots(plot_error_dir,prefix);
saveStats(total_err,result_dir);
saveResults(seq_t_err,seq_r_err,seq_ate,total_err,seq_nums,seq_nums_ptr,result_dir);
}
// success
return true;
}
void print_help() {
cout << "Usage: ./evaluate_odometry results_folder lengths_set=[0, 1] view=[x/z, x/y] [user_sha email]" << endl;
int i;
cout << "lengths_set:" << endl;
for (i = 0; i < sets_of_lengths_num; i++) {
cout << " " << i << ": {";
lengths = all_sets_of_lengths[i];
num_lengths = num_lengths_of_all_sets[i];
int j;
for (j = 0; j < num_lengths; j++) {
printf("%.1f", lengths[j]);
if (j != num_lengths-1) {
cout << ", ";
}
}
cout << "}" << endl;
}
cout << "view:" << endl;
cout << " x/z - top view" << endl;
cout << " x/y - side view" << endl;
}
int32_t main (int32_t argc,char *argv[]) {
// we need 2 or 4 arguments!
if (argc!=4 && argc!=6) {
print_help();
return 1;
}
// read arguments
string result_sha = argv[1];
int lengths_set = atoi(argv[2]);
if ((lengths_set >= 2) or (lengths_set < 0)){
cout << "lengths_set must be 0 or 1" << endl;
return 1;
}
lengths = all_sets_of_lengths[lengths_set];
num_lengths = num_lengths_of_all_sets[lengths_set];
cout << "Used lengths:" << endl << " ";
int i = 0;
for (i = 0; i < num_lengths; i++){
printf("%.1f ", lengths[i]);
}
cout << endl;
if (strcmp(argv[3], "x/z") == 0) {
coord_1_idx = 0; //x
coord_2_idx = 2; //z
view = 0;
} else if (strcmp(argv[3], "x/y") == 0) {
coord_1_idx = 0; //x
coord_2_idx = 1; //y
view = 1;
} else {
cout << "view must be top or side" << endl;
return 1;
}
cout << "Used view:" << endl << " " << argv[3] << endl;
// init notification mail
Mail *mail;
if (argc==5) mail = new Mail(argv[5]);
else mail = new Mail();
mail->msg("Thank you for participating in our evaluation!");
// run evaluation
bool success = eval(result_sha,mail);
// if (argc==5) mail->finalize(success,"odometry",result_sha,argv[4]);
// else mail->finalize(success,"odometry",result_sha);
// send mail and exit
delete mail;
return 0;
}
|
4ea535ee4230a858c301b63dec46ca43ce36279a
|
dc7c0d331953787810fe8ab63d0e1c6dbfb1e2bb
|
/Temperature_Humidity_Arduino.ino
|
cf011dbdf1b19fddf3f21991b3dc9db16e1fabcf
|
[] |
no_license
|
Siladrok/Processing3_GUI_DHT11
|
7e8a7021bb58bacae611ba969c4d909e18ecd9f5
|
0d33e4d84f9a770286cadde3307b87777f19dea6
|
refs/heads/master
| 2020-06-22T23:07:17.843015
| 2019-07-23T13:30:13
| 2019-07-23T13:30:13
| 198,425,782
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 886
|
ino
|
Temperature_Humidity_Arduino.ino
|
// Written by ladyada, public domain
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include "DHT.h"
//Define the data pin
#define DHTPIN 2
//Define the sensor type
#define DHTTYPE DHT11
// Initialize DHT sensor.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
dht.begin();
}
void loop() {
//Delay time between measurements
delay(5000);
//Read Humidity
float h = dht.readHumidity();
// Read temperature as Celsius
float t = dht.readTemperature();
// Check if any reads failed and exit early
if (isnan(h) || isnan(t)) {
return;
}
//Write on serial humidity , temperature
Serial.print(h);
Serial.print(",");
Serial.print(t);
}
|
03e9a528299cd17763b695ab286da1723482f7b7
|
872770c5323aa17120f2f708a1f0be09e663c9a8
|
/Elastos/Framework/Droid/eco/inc/core/webkit/CookieSyncManager.h
|
d7ffeef7975135f12aa0afd10140df02651d9365
|
[] |
no_license
|
xianjimli/Elastos
|
76a12b58db23dbf32ecbcefdaf6179510362dd21
|
f9f019d266a7e685544596b365cfbc05bda9cb70
|
refs/heads/master
| 2021-01-11T08:26:17.180908
| 2013-08-21T02:31:17
| 2013-08-21T02:31:17
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,353
|
h
|
CookieSyncManager.h
|
#ifndef __COOKIESYNCMANAGER_H__
#define __COOKIESYNCMANAGER_H__
#include "ext/frameworkext.h"
#include <elastos/AutoPtr.h>
#include <elastos/Vector.h>
#include "WebSyncManager.h"
#include "CCookieManager.h"
/**
* The CookieSyncManager is used to synchronize the browser cookie store
* between RAM and permanent storage. To get the best performance, browser cookies are
* saved in RAM. A separate thread saves the cookies between, driven by a timer.
* <p>
*
* To use the CookieSyncManager, the host application has to call the following
* when the application starts:
* <p>
*
* <pre class="prettyprint">CookieSyncManager.createInstance(context)</pre><p>
*
* To set up for sync, the host application has to call<p>
* <pre class="prettyprint">CookieSyncManager.getInstance().startSync()</pre><p>
*
* in Activity.onResume(), and call
* <p>
*
* <pre class="prettyprint">
* CookieSyncManager.getInstance().stopSync()
* </pre><p>
*
* in Activity.onPause().<p>
*
* To get instant sync instead of waiting for the timer to trigger, the host can
* call
* <p>
* <pre class="prettyprint">CookieSyncManager.getInstance().sync()</pre><p>
*
* The sync interval is 5 minutes, so you will want to force syncs
* manually anyway, for instance in {@link
* WebViewClient#onPageFinished}. Note that even sync() happens
* asynchronously, so don't do it just as your activity is shutting
* down.
*/
class CookieSyncManager : public WebSyncManager
{
public:
/**
* Singleton access to a {@link CookieSyncManager}. An
* IllegalStateException will be thrown if
* {@link CookieSyncManager#createInstance(Context)} is not called before.
*
* @return CookieSyncManager
*/
static CARAPI_(CookieSyncManager*) GetInstance();
/**
* Create a singleton CookieSyncManager within a context
* @param context
* @return CookieSyncManager
*/
static CARAPI_(CookieSyncManager*) CreateInstance(
/* [in] */ IContext* context);
public:
/**
* Package level api, called from CookieManager. Get all the cookies which
* matches a given base domain.
* @param domain
* @return A list of Cookie
*/
CARAPI_(void) GetCookiesForDomain(
/* [in] */ const String& domain,
/* [out] */ Vector<AutoPtr<CCookieManager::Cookie> >& cookielist);
/**
* Package level api, called from CookieManager Clear all cookies in the
* database
*/
CARAPI_(void) ClearAllCookies();
/**
* Returns true if there are any saved cookies.
*/
CARAPI_(Boolean) HasCookies();
/**
* Package level api, called from CookieManager Clear all session cookies in
* the database
*/
CARAPI_(void) ClearSessionCookies();
/**
* Package level api, called from CookieManager Clear all expired cookies in
* the database
*/
CARAPI_(void) ClearExpiredCookies(
/* [in] */ Int64 now);
protected:
CARAPI_(void) SyncFromRamToFlash();
protected:
static Mutex sSyncLock;
private:
CookieSyncManager(
/* [in] */ IContext* context);
CARAPI_(void) SyncFromRamToFlash(
/* [in] */ Vector<AutoPtr<CCookieManager::Cookie> >& list);
private:
static CookieSyncManager* sRef;
// time when last update happened
Int64 mLastUpdate;
};
#endif //__COOKIESYNCMANAGER_H__
|
46a9e596be842564fc6d512ea32c012fba4cc0d7
|
afc8b47a1c7accb58989d608376e4a0b1e8343fa
|
/GAP/HubCluster/bitmap.h
|
bc43910425169d07f5065d3af87324fcaf02e8b3
|
[
"MIT"
] |
permissive
|
CMUAbstract/Graph-Reordering-IISWC18
|
f9472d6d689b01aa53eafd81f5b74b20487223da
|
41b6208a06155fb334e882a995d647a369b25bc5
|
refs/heads/master
| 2022-03-24T10:33:15.958860
| 2022-03-11T00:13:34
| 2022-03-11T00:13:34
| 146,941,861
| 17
| 5
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,778
|
h
|
bitmap.h
|
// Copyright (c) 2015, The Regents of the University of California (Regents)
// See LICENSE.txt for license details
#ifndef BITMAP_H_
#define BITMAP_H_
#include <algorithm>
#include <cinttypes>
#include <cassert>
#include "platform_atomics.h"
/*
GAP Benchmark Suite
Class: Bitmap
Author: Scott Beamer
Parallel bitmap that is thread-safe
- Can set bits in parallel (set_bit_atomic) unlike std::vector<bool>
Modification to original bitmap (uses posix_memalign for memory allocation)
*/
class Bitmap {
public:
explicit Bitmap(size_t size) {
uint64_t num_words = (size + kBitsPerWord - 1) / kBitsPerWord;
//start_ = new uint64_t[num_words];
int ret = posix_memalign((void**) &start_, 64, num_words * sizeof(uint64_t));
assert(ret == 0 && "Memory allocation failure\n");
end_ = start_ + num_words;
}
~Bitmap() {
//delete[] start_;
free(start_);
}
void reset() {
std::fill(start_, end_, 0);
}
void set_bit(size_t pos) {
start_[word_offset(pos)] |= ((uint64_t) 1l << bit_offset(pos));
}
void set_bit_atomic(size_t pos) {
uint64_t old_val, new_val;
do {
old_val = start_[word_offset(pos)];
new_val = old_val | ((uint64_t) 1l << bit_offset(pos));
} while (!compare_and_swap(start_[word_offset(pos)], old_val, new_val));
}
bool get_bit(size_t pos) const {
return (start_[word_offset(pos)] >> bit_offset(pos)) & 1l;
}
void swap(Bitmap &other) {
std::swap(start_, other.start_);
std::swap(end_, other.end_);
}
private:
uint64_t *start_;
uint64_t *end_;
static const uint64_t kBitsPerWord = 64;
static uint64_t word_offset(size_t n) { return n / kBitsPerWord; }
static uint64_t bit_offset(size_t n) { return n & (kBitsPerWord - 1); }
};
#endif // BITMAP_H_
|
4f8a7b00e3e9bc10e6eef3c2cb41f389977461b0
|
dd433de3daea2843440f97cea16e974f57b64629
|
/libyul/ControlFlowSideEffects.h
|
5621a122b1dfb1080b741d73dac3de1ca23e05bc
|
[
"GPL-3.0-only"
] |
permissive
|
step21/solidity
|
a867d555a9bdab2d94b453acd43b94c7a9806061
|
2a0d701f709673162e8417d2f388b8171a34e892
|
refs/heads/develop
| 2021-01-24T21:10:56.649056
| 2020-06-17T14:31:22
| 2020-06-18T08:29:06
| 45,851,195
| 0
| 0
|
MIT
| 2020-06-17T14:28:37
| 2015-11-09T16:33:47
|
C++
|
UTF-8
|
C++
| false
| false
| 1,117
|
h
|
ControlFlowSideEffects.h
|
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <set>
namespace solidity::yul
{
/**
* Side effects of code related to control flow.
*/
struct ControlFlowSideEffects
{
/// If true, this code terminates the control flow.
/// State may or may not be reverted as indicated by the ``reverts`` flag.
bool terminates = false;
/// If true, this code reverts all state changes in the transaction.
/// Whenever this is true, ``terminates`` has to be true as well.
bool reverts = false;
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.