text
stringlengths 8
6.88M
|
|---|
#include "child.h"
const char * Child::getName() {return "Child";}
|
#include<iostream>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<getopt.h>
#include<errno.h>
#include<string.h>
#include<limits.h>
using namespace std;
void print_helpinfo(){
//ๆๅฐๅธฎๅฉไฟกๆฏ
cout<<"copy the content of src file to dst file, dst can be a new file or an existent file.\n";
cout<<"SYNPSIS"<<endl;
cout<<"\tfile_tool [option] src dst"<<endl;
cout<<"OPTION\n";
cout<<"-f --force if dst is an existent file, add this flag will overwrite the content of dst with src\n";
cout<<"-a --append if dst is an existent file, add this flag will append the content of src the the tail of dst\n";
cout<<"-h --help print help info\n";
return;
}
void copy_file( char* src, char* dst , const short flag){
//ๆฃๆฅ src ๆฏๅฆไธบๆฎ้ๆไปถ
struct stat sb ;
stat(src,&sb);
if (!S_ISREG(sb.st_mode)){
printf("bad src! %s\n",strerror(errno));
return ;
}
int src_fd = open(src,O_RDONLY);
int dst_fd = open(dst,O_CREAT|O_EXCL|O_RDWR,S_IRWXU);
//ๅฐ่ฏๅๅปบ dst
if(dst_fd<0){
// ๅฆๆๆไปถๅทฒ็ปๅญๅจ
if(flag ==-1){
printf("dst is alwrady exist , please give additional argument ! use file_tools -h for help!\n");
return ;
}
dst_fd = ( flag == 1) ? open(dst, O_RDWR|O_APPEND) : open(dst,O_RDWR|O_TRUNC);
if(dst_fd < 0){
printf("some error happen! %s\n",strerror(errno));
return ;
}
}
// ๅคๆญ src ๅ dst ๆฏไธๆฏๅไธไธชๆไปถ ้ฒๆญข ๆ ้ๅคๅถ
char abs_path_src[PATH_MAX] , abs_path_dst[PATH_MAX];
realpath(src,abs_path_src);
realpath(dst,abs_path_dst);
if ( strcmp(abs_path_src, abs_path_dst) == 0){
printf("the src and dst are the same!\n");
return ;
}
// ๅผๅง่ฟ่กๆไปถๆไฝ, ไธๆฌก่ฏปๅ 1k byte
char buffer[1024]={0};
while(1){
int count = read(src_fd, &buffer , 1024 ); // ไฝฟ็จ linux ็ณป็ป่ฐ็จ่ฏปๅ 1024ไธชๅญ่
if(count ==0 ){
printf("copy successful\n");
return ;
}else if(count < 0){
printf("some error happen! %s\n", strerror(errno));
return ;
}else{
// ๅdstๅๅญ่
int wcount = write(dst_fd , &buffer , count);
if(wcount < 0){
printf("some error happen! %s\n", strerror(errno));
return;
}
}
}
return ;
}
extern int optind; // ่งฃๆๅๆฐ้่ฆ็ๅ้
int main(int argc, char** argv){
//่งฃๆๅฝไปค่กๅๆฐ
short flag = -1; // flag ๆ นๆฎ่งฃๆๅๆฐ็็ปๆ -1ๅๅงๅผ๏ผ0 force, 1 append
while(1){
int option_index = 0;
int c;
static struct option long_options[] = {
{"force",0,NULL,'f' },
{"append",0,NULL,'a'},
{"help",0,NULL,'h'},
};
c = getopt_long(argc,argv,"fah",long_options,&option_index);
if(c==-1){
// ๅๆฐ่งฃๆๅฎๆ
break;
}
switch(c){
case('?'): //่งฃๆๅฐๆช็ฅๅๆฐ
return 1 ;
case('a'):
flag = 1; break;
case('f'):
flag = 0; break;
case('h'):
print_helpinfo(); return 0;
default:
printf("some unknown error!\n");
return 1 ;
}
}
//่ทๅพ src ๅ dst
if (argc - optind <2 ){
// ๅคๆญๅๆฐ็ไธชๆฐๆฏๅฆ่ถณๅค๏ผๆๅไธคไธชๅๆฐ้่ฆๆฏ src ๅ dst
cout<<"please enter the path of both src and dst\n";
}
char* src = argv[optind],*dst = argv[optind+1];
copy_file(src, dst ,flag);
return 0;
}
|
#include <iostream.h>
#include <conio.h>
void main() {
clrscr();
int a,b,t,i;
cout <<"\n\nEnter the Table no: ";
cin >>t;
cout <<"\n\nEnter the starting range for table: ";
cin >>a;
cout <<"\n\nEnter the Ending range for table: ";
cin >>b;
for (i=a; i<=b; i++)
cout <<"\n\n" <<t << " X " <<i << " = " << i*t;
getch();
}
|
/*
* stampTrait.h
*
* Created on: Dec 1, 2012
* Author: chjd
*/
#ifndef STAMPTRAIT_H_
#define STAMPTRAIT_H_
/*
* Trait design
*/
/*
* Policy may be more appropriate than Trait
*/
template<typename _DcSup,typename _DcLoad,
typename _AcSup,typename _AcLoad
typename _TranSup,typename _TranLoad
>
class TpStampTrait
{
public:
template<StampType type,typename _Sup,typename _Load>
class TpStamp
{
public:
typedef _Sup sup;
typedef _Load load;
};
public:
typedef TpStamp<_DcSup,_DcLoad> DcStamp;
typedef TpStamp<_AcSup,_AcLoad> AcStamp;
typedef TpStamp<_TranSup,_TranLoad> TranStamp;
};
typedef TpStampTrait<EmptySup2,dNormalLoad,EmptySup2,cNormalLoad,EmptySup2,tNormalLoad> ResStamp;
typedef TpStampTrait<EmptySup2,dEmptyLoad2,EmptySup2,cNormalLoad,CLSupK,tCLoad> CapStamp;
typedef TpStampTrait<ShortSup,dEmptyLoad2,EmptySup2,cNormalLoad,CLSupK,tLLoad> IndStamp;
typedef TpStampTrait<ESup,dELoad,ESup,cELoad,ESup,tELoad> EStamp;
typedef TpStampTrait<FSup,dFLoad,FSup,cFLoad,FSup,tFLoad> FStamp;
typedef TpStampTrait<EmptySup4,dGLoad,EmptySup4,cGLoad,EmptySup4,tGLoad> GStamp;
typedef TpStampTrait<HSup,dHLoad,HSup,cHLoad,HSup,tHLoad> HStamp;
typedef TpStampTrait<VSupK,dVLoad,VSupK,cVLoad,VSupK,tVLoad> VStamp;
typedef TpStampTrait<EmptySup2,dILoad,EmptySup2,cILoad,EmptySup2,tILoad> IStamp;
typedef TpStampTrait<OpampSup,dEmptyLoad4,OpampSup,cEmptyLoad4,OpampSup,tEmptyLoad4> OpampStamp;
#endif /* STAMPTRAIT_H_ */
|
class Solution {//BFS with common if() X 4
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.size() == 0 || grid[0].size() == 0) {
return 0;
}
int res = 0;
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[0].size(); j++) {
if(grid[i][j] == '1') {
++res;
BFS(grid, i, j);
}
}
}
return res;
}
private:
void BFS(vector<vector<char>>& grid, int x, int y) {
queue<vector<int>> q;
q.push({x, y});
grid[x][y] = '0';
while(!q.empty()) {
x = q.front()[0], y = q.front()[1];
q.pop();
if(x > 0 && grid[x - 1][y] == '1') {
q.push({x - 1, y});
grid[x - 1][y] = '0';
}
if(x < grid.size() - 1 && grid[x + 1][y] == '1') {
q.push({x + 1, y});
grid[x + 1][y] = '0';
}
if(y > 0 && grid[x][y - 1] == '1') {
q.push({x, y - 1});
grid[x][y - 1] = '0';
}
if(y < grid[0].size() - 1 && grid[x][y + 1] == '1') {
q.push({x, y + 1});
grid[x][y + 1] = '0';
}
}
}
};
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
typedef long long ll;
int main()
{
int n;
cin >> n;
string s; cin >> s;
char bef = 0;
int ans = 0;
rep(i, n){
if (bef != s[i]) ans++;
bef = s[i];
}
cout << ans << endl;
}
|
#ifndef _LIST_H_
#define _LIST_H_
/* Include Headers */
#include "Headers.h"
/* Define Data type for list */
typedef char * ListDataType;
/* Defining structure for list */
struct ListStructure{
ListDataType dataPointer;
struct ListStructure *next;
};
/* Define type for pointer for ListStructure */
typedef ListStructure * ListStructurePointer;
/* Class definition for LIST */
class List_{
private:
bool isEmpty( ListStructurePointer head ){
if( NULL == head )
return 1;
return 0;
}
public:
static unsigned int length( ListStructurePointer *head );
#pragma warning(disable : 4996)
bool addItem( ListStructurePointer * head, ListDataType data, unsigned int dataLength, bool position=false );
bool removeItem( ListStructurePointer * head, bool position=false );
void display( ListStructurePointer * head );
void diplayReverse( ListStructurePointer * head );
bool deleteList( ListStructurePointer *head );
bool reverse( ListStructurePointer *head );
};
#endif /* List.h */
|
#include "SimpleDENFAC.hpp"
#include <vector>
#include <string>
#include <iostream>
#include <boost/serialization/list.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/deque.hpp>
#include "nn/MLP.hpp"
#include "arch/AACAgent.hpp"
#include "bib/Seed.hpp"
#include "bib/Utils.hpp"
#include <bib/MetropolisHasting.hpp>
#include <bib/XMLEngine.hpp>
#include "bib/IniParser.hpp"
#define DOUBLE_COMPARE_PRECISION 1e-9
typedef MLP PolicyImpl;
SimpleDENFAC::SimpleDENFAC(unsigned int _nb_motors, unsigned int _nb_sensors): arch::AACAgent<PolicyImpl, AgentGPUProgOptions>(_nb_motors), nb_sensors(_nb_sensors) {
}
SimpleDENFAC::~SimpleDENFAC() {
delete qnn;
delete ann;
delete hidden_unit_q;
delete hidden_unit_a;
}
/***
* Compute next action with an exploration strategy
* Update last action and last state and best reward
* Fill replay buffer
*/
const std::vector<double>& SimpleDENFAC::_run(double reward, const std::vector<double>& sensors, bool learning, bool goal_reached, bool) {
// Store previous sample into the replay buffer
if (last_action.get() != nullptr && learning) {
double p0 = 1.f;
for(uint i=0; i < nb_motors; i++) {
p0 *= bib::Proba<double>::truncatedGaussianDensity(last_action->at(i), last_pure_action->at(i), noise);
}
sample sa = {last_state, *last_pure_action, *last_action, sensors, reward, goal_reached, p0};
insertSample(sa);
}
// Compute next action
vector<double>* next_action = ann->computeOut(sensors);
// Update last action
last_pure_action.reset(new vector<double>(*next_action));
// Add exploration strategy
if(learning) {
if(gaussian_policy) {
// Gaussian noise
vector<double>* randomized_action = bib::Proba<double>::multidimentionnalTruncatedGaussian(*next_action, noise);
delete next_action;
next_action = randomized_action;
} else if(bib::Utils::rand01() < noise) {
//e-greedy
for (uint i = 0; i < next_action->size(); i++)
next_action->at(i) = bib::Utils::randin(-1.f, 1.f);
}
}
// Update last action
last_action.reset(next_action);
// Update last state
last_state.clear();
for (uint i = 0; i < sensors.size(); i++)
last_state.push_back(sensors[i]);
return *next_action;
}
/***
* Insert a sample into the replay buffer
* Save trajectories
* Called from _run()
* Optionnaly do on-line updates
*/
void SimpleDENFAC::insertSample(const sample& sa) {
if(trajectory.size() >= replay_memory)
trajectory.pop_front();
trajectory.push_back(sa);
}
/***
* Get parameters from config.ini (located in the current build directory or provided with the --config option)
* Initialize actor and critic networks
*/
void SimpleDENFAC::_unique_invoke(boost::property_tree::ptree* pt, boost::program_options::variables_map* command_args) {
//bib::Seed::setFixedSeedUTest();
hidden_unit_q = bib::to_array<uint>(pt->get<std::string>("agent.hidden_unit_q"));
hidden_unit_a = bib::to_array<uint>(pt->get<std::string>("agent.hidden_unit_a"));
noise = pt->get<double>("agent.noise");
gaussian_policy = pt->get<bool>("agent.gaussian_policy");
mini_batch_size = pt->get<uint>("agent.mini_batch_size");
replay_memory = pt->get<uint>("agent.replay_memory");
reset_qnn = pt->get<bool>("agent.reset_qnn");
nb_actor_updates = pt->get<uint>("agent.nb_actor_updates");
nb_critic_updates = pt->get<uint>("agent.nb_critic_updates");
nb_fitted_updates = pt->get<uint>("agent.nb_fitted_updates");
nb_internal_critic_updates = pt->get<uint>("agent.nb_internal_critic_updates");
alpha_a = pt->get<double>("agent.alpha_a");
alpha_v = pt->get<double>("agent.alpha_v");
batch_norm = pt->get<uint>("agent.batch_norm");
inverting_grad = pt->get<bool>("agent.inverting_grad");
decay_v = pt->get<double>("agent.decay_v");
weighting_strategy = pt->get<uint>("agent.weighting_strategy");
last_layer_actor = pt->get<uint>("agent.last_layer_actor");
reset_ann = pt->get<bool>("agent.reset_ann");
hidden_layer_type = pt->get<uint>("agent.hidden_layer_type");
#ifdef CAFFE_CPU_ONLY
LOG_INFO("CPU mode");
(void) command_args;
#else
if(command_args->count("gpu") == 0 || command_args->count("cpu") > 0) {
caffe::Caffe::set_mode(caffe::Caffe::Brew::CPU);
LOG_INFO("CPU mode");
} else {
caffe::Caffe::set_mode(caffe::Caffe::Brew::GPU);
caffe::Caffe::SetDevice(0);
LOG_INFO("GPU mode");
}
#endif
qnn = new MLP(nb_sensors + nb_motors, nb_sensors, *hidden_unit_q,
alpha_v,
mini_batch_size,
decay_v,
hidden_layer_type, batch_norm,
weighting_strategy > 0);
ann = new MLP(nb_sensors, *hidden_unit_a, nb_motors, alpha_a, mini_batch_size, hidden_layer_type, last_layer_actor,
batch_norm);
}
/***
* Load previous run to resume in case of interruption
*/
void SimpleDENFAC::load_previous_run() {
ann->load("continue.actor");
qnn->load("continue.critic");
auto p1 = bib::XMLEngine::load<std::deque<sample>>("trajectory", "continue.trajectory.data");
trajectory = *p1;
delete p1;
auto p3 = bib::XMLEngine::load<struct algo_state>("algo_state", "continue.algo_state.data");
mini_batch_size = p3->mini_batch_size;
replay_memory = p3->replay_memory;
delete p3;
ann->increase_batchsize(mini_batch_size);
qnn->increase_batchsize(mini_batch_size);
}
/***
* Save current state
*/
void SimpleDENFAC::save_run() {
ann->save("continue.actor");
qnn->save("continue.critic");
bib::XMLEngine::save(trajectory, "trajectory", "continue.trajectory.data");
struct algo_state st = {mini_batch_size, replay_memory};
bib::XMLEngine::save(st, "algo_state", "continue.algo_state.data");
}
/***
* Episode initialization
*/
void SimpleDENFAC::_start_episode(const std::vector<double>& sensors, bool _learning) {
last_state.clear();
for (uint i = 0; i < sensors.size(); i++)
last_state.push_back(sensors[i]);
last_action = nullptr;
last_pure_action = nullptr;
trajectory.clear();
learning = _learning;
step = 0;
}
/***
* Compute importance sampling
*/
void SimpleDENFAC::computePThetaBatch(const std::deque< sample >& vtraj, double *ptheta, const std::vector<double>* all_next_actions) {
uint i=0;
for(auto it : vtraj) {
double p0 = 1.f;
for(uint j=0; j < nb_motors; j++) {
p0 *= bib::Proba<double>::truncatedGaussianDensity(it.a[j], all_next_actions->at(i*nb_motors+j), noise);
}
ptheta[i] = p0;
i++;
}
}
/***
* Update the critic using a batch sampled from the replay buffer
*/
void SimpleDENFAC::critic_update(uint iter) {
// Get Replay buffer
std::deque<sample>* traj = &trajectory;
// ******* Compute q_k (q_targets here) *******
// Compute \pi(s_{t+1})
// Get batch data (s_t, s_{t+1} and a)
std::vector<double> all_next_states(traj->size() * nb_sensors);
std::vector<double> all_states(traj->size() * nb_sensors);
std::vector<double> all_actions(traj->size() * nb_motors);
uint i=0;
for (auto it : *traj) {
std::copy(it.next_s.begin(), it.next_s.end(), all_next_states.begin() + i * nb_sensors);
std::copy(it.s.begin(), it.s.end(), all_states.begin() + i * nb_sensors);
std::copy(it.a.begin(), it.a.end(), all_actions.begin() + i * nb_motors);
i++;
}
// Compute all next action
std::vector<double>* all_next_actions;
all_next_actions = ann->computeOutBatch(all_next_states);
// Compute next Q value
std::vector<double>* q_targets;
std::vector<double>* q_targets_weights = nullptr;
double* ptheta = nullptr;
q_targets = qnn->computeOutVFBatch(all_next_states, *all_next_actions);
// Importance sampling
if(weighting_strategy != 0) {
q_targets_weights = new std::vector<double>(q_targets->size(), 1.0f);
if(weighting_strategy > 1) {
ptheta = new double[traj->size()];
computePThetaBatch(*traj, ptheta, all_next_actions);
}
}
delete all_next_actions;
// Adjust q_targets
i=0;
for (auto it : *traj) {
if(it.goal_reached)
q_targets->at(i) = it.r;
else {
q_targets->at(i) = it.r + gamma * q_targets->at(i);
//std::cout<< " Reward = " << it.r << " QV = " << q_targets->at(i) << std::endl;
}
if(weighting_strategy==1)
q_targets_weights->at(i)=1.0f/it.p0;
else if(weighting_strategy==2)
q_targets_weights->at(i)=ptheta[i]/it.p0;
else if(weighting_strategy==3)
q_targets_weights->at(i)=std::min((double)1.0f, ptheta[i]/it.p0);
i++;
}
// for(int j = traj->size()-1; j >= 0; j--) {
// std::cout << "q_target at " << j << " = " << q_targets->at(j) << std::endl;
// };
// Optionnaly reset the network
if(reset_qnn && episode < 1000 ) {
delete qnn;
qnn = new MLP(nb_sensors + nb_motors, nb_sensors, *hidden_unit_q,
alpha_v,
mini_batch_size,
decay_v,
hidden_layer_type, batch_norm,
weighting_strategy > 0);
}
/*
LOG_DEBUG(sum_weighted_reward);
for (int i=0; i < q_targets->size(); i++) {
std::cout << std::setprecision(9) << "Q_target " << i << " : " << q_targets->at(i) << " Reward : " << traj->at(i).r << std::endl;
}
if (q_targets->size() < 198) {
exit(1);
}
*/
// Update critic
if(weighting_strategy != 0)
qnn->stepCritic(all_states, all_actions, *q_targets, iter, q_targets_weights);
else
qnn->stepCritic(all_states, all_actions, *q_targets, iter);
delete q_targets;
if(weighting_strategy != 0) {
delete q_targets_weights;
if(weighting_strategy > 1)
delete[] ptheta;
}
qnn->ZeroGradParameters();
}
/***
* Compute the critic's gradient wrt the actor's actions
* Update the actor using this gradient and the inverting gradient strategy
*/
void SimpleDENFAC::actor_update_grad() {
std::deque<sample>* traj = &trajectory;
std::vector<double> all_states(traj->size() * nb_sensors);
uint i=0;
for (auto it : *traj) {
std::copy(it.s.begin(), it.s.end(), all_states.begin() + i * nb_sensors);
i++;
}
//Update actor
qnn->ZeroGradParameters();
ann->ZeroGradParameters();
// Compute a
auto all_actions_outputs = ann->computeOutBatch(all_states);
// Compute q
delete qnn->computeOutVFBatch(all_states, *all_actions_outputs);
const auto q_values_blob = qnn->getNN()->blob_by_name(MLP::q_values_blob_name);
double* q_values_diff = q_values_blob->mutable_cpu_diff();
// Compute \nabla_a Q(s_t,a)
i=0;
for (auto it : *traj)
q_values_diff[q_values_blob->offset(i++,0,0,0)] = -1.0f;
// Compute s and a toward an increase of Q
qnn->critic_backward();
// Get a
const auto critic_action_blob = qnn->getNN()->blob_by_name(MLP::actions_blob_name);
// Inverting gradient strategy
if(inverting_grad) {
// QTM
double* action_diff = critic_action_blob->mutable_cpu_diff();
double sum_diff = 0;
i=0;
for (auto it : *traj)
sum_diff += action_diff[i++];
//std::cout << sum_diff << std::endl;
for (uint n = 0; n < traj->size(); ++n) {
for (uint h = 0; h < nb_motors; ++h) {
int offset = critic_action_blob->offset(n,0,h,0);
double diff = action_diff[offset];
double output = all_actions_outputs->at(offset);
double min = -1.0;
double max = 1.0;
if (diff < 0) {
diff *= (max - output) / (max - min);
} else if (diff > 0) {
diff *= (output - min) / (max - min);
}
action_diff[offset] = diff;
}
}
//bib::Logger::PRINT_ELEMENTS(action_diff, critic_action_blob->count());
}
// Transfer input-level diffs from Critic to Actor
// Get actor's output
const auto actor_actions_blob = ann->getNN()->blob_by_name(MLP::actions_blob_name);
// Set the actor's output to the action value computed by the critic through the backward pass
actor_actions_blob->ShareDiff(*critic_action_blob);
// Propagate the difference
ann->actor_backward();
// Update QTM
ann->getSolver()->ApplyUpdate();
ann->getSolver()->set_iter(ann->getSolver()->iter() + 1);
delete all_actions_outputs;
}
/***
* Performs fitted updates of the actor and the critic
*/
void SimpleDENFAC::update_actor_critic() {
if(!learning)
return;
if(trajectory.size() != mini_batch_size) {
mini_batch_size = trajectory.size();
qnn->increase_batchsize(mini_batch_size);
ann->increase_batchsize(mini_batch_size);
}
// Fitted updates
for(uint n=0; n<nb_fitted_updates; n++) {
// Fitted critic updates
for(uint i=0; i<nb_critic_updates ; i++)
critic_update(nb_internal_critic_updates);
if(reset_ann && episode < 1000) {
delete ann;
ann = new MLP(nb_sensors, *hidden_unit_a, nb_motors, alpha_a, mini_batch_size, hidden_layer_type, last_layer_actor, batch_norm);
}
// Fitted actor updates
for(uint i=0; i<nb_actor_updates ; i++)
actor_update_grad();
}
}
/***
* Start update
*/
void SimpleDENFAC::end_episode(bool) {
episode++;
update_actor_critic();
}
void SimpleDENFAC::save(const std::string& path, bool) {
ann->save(path+".actor");
qnn->save(path+".critic");
LOG_INFO("Saved as " + path+ ".actor");
// bib::XMLEngine::save<>(trajectory, "trajectory", "trajectory.data");
}
void SimpleDENFAC::load(const std::string& path) {
ann->load(path+".actor");
qnn->load(path+".critic");
}
void SimpleDENFAC::_display(std::ostream& out) const {
out << std::setw(12) << std::fixed << std::setprecision(10) << sum_weighted_reward
#ifndef NDEBUG
<< " " << std::setw(8) << std::fixed << std::setprecision(5) << noise
<< " " << trajectory.size()
<< " " << ann->weight_l1_norm()
<< " " << std::fixed << " E " << std::setprecision(7) << qnn->error()
<< " " << qnn->weight_l1_norm()
#endif
;
}
void SimpleDENFAC::_dump(std::ostream& out) const {
out <<" " << std::setw(25) << std::fixed << std::setprecision(22) <<
sum_weighted_reward << " " << std::setw(8) << std::fixed <<
std::setprecision(5) << trajectory.size() ;
}
double SimpleDENFAC::criticEval(const std::vector<double>& perceptions, const std::vector<double>& actions){
return qnn->computeOutVF(perceptions, actions);
}
arch::Policy<MLP>* SimpleDENFAC::getCopyCurrentPolicy() {
return new arch::Policy<MLP>(new MLP(*ann, true) , gaussian_policy ? arch::policy_type::GAUSSIAN :
arch::policy_type::GREEDY,
noise, decision_each);
}
|
//
// TextBox.cpp
// OpenGL_Timer_CPP
//
// Created by Ran Bao on 4/27/13.
// Copyright (c) 2013 Ran Bao. All rights reserved.
//
#include "TextBox.h"
NewTextBox::NewTextBox(){
x_axis = y_axis = 0;
font = NULL;
}
NewTextBox::NewTextBox(float x, float y, const float *fontColor, void *f){
for (int i = 0; i < 3; i++) {
color[i] = fontColor[i];
}
x_axis = x;
y_axis = y;
font = f;
}
NewTextBox::~NewTextBox(){
}
void NewTextBox::update(const std::string &text_to_display){
text = text_to_display;
}
void NewTextBox::draw(){
glPushMatrix();
glColor3fv(color);
glRasterPos2f(x_axis, y_axis);
for (std::string::iterator it = text.begin(); it != text.end(); it++) {
glutBitmapCharacter(font, *it);
}
glFlush();
glPopMatrix();
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
LL f[2222][2222];
short p[2222][2222];
unsigned char alf[255], alfp[255], a[4444], b[4444], ansa[4444], ansb[4444];
int lalf, la, lb, d[255][255], mina[255], minb[255], an, bn;
int main() {
freopen("dissim.in", "r", stdin);
freopen("dissim.out", "w", stdout);
gets((char*)alf);
lalf = strlen((char*)alf);
for (int i = 0; i < lalf; ++i) alfp[alf[i]] = i;
gets((char*)a);
la = strlen((char*)a);
gets((char*)b);
lb = strlen((char*)b);
for (int i = 0; i < la; ++i) a[i] = alfp[a[i]];
for (int i = 0; i < lb; ++i) b[i] = alfp[b[i]];
for (int i = 0; i < lalf; ++i) {
int& mi = mina[i] = 0;
int minv = 2e9;
for (int j = 0; j< lalf; ++j) {
scanf("%d", &d[i][j]);
if (d[i][j] < minv) {
minv = d[i][j];
mi = j;
}
}
}
for (int i = 0; i < lalf; ++i) {
int& mi = minb[i] = 0;
int minv = 2e9;
for (int j = 0; j < lalf; ++j) {
if (d[j][i] < minv) {
minv = d[j][i];
mi = j;
}
}
}
memset(f, 127, sizeof(f));
f[0][0] = 0;
for (int i = 0; i <= la; ++i)
for (int j = 0; j <= lb; ++j)
if (f[i][j] < 1e18) {
if (i < la && f[i + 1][j] > f[i][j] + d[ a[i] ][ mina[a[i]] ]) {
f[i + 1][j] = f[i][j] + d[ a[i] ][ mina[a[i]] ];
p[i + 1][j] = 1;
}
if (j < lb && f[i][j + 1] > f[i][j] + d[ minb[b[j]] ][ b[j] ]) {
f[i][j + 1] = f[i][j] + d[ minb[b[j]] ][ b[j] ];
p[i][j + 1] = 2;
}
if (i < la && j < lb && f[i + 1][j + 1] > f[i][j] + d[ a[i] ][ b[j] ]) {
f[i + 1][j + 1] = f[i][j] + d[ a[i] ][ b[j] ];
p[i + 1][j + 1] = 3;
}
}
cout << f[la][lb] << endl;
int i = la, j = lb;
while (i > 0 || j > 0) {
if (p[i][j] == 3) {
--i;
--j;
ansa[an++] = a[i];
ansb[bn++] = b[j];
} else
if (p[i][j] == 2) {
--j;
ansa[an++] = minb[b[j]];
ansb[bn++] = b[j];
} else {
--i;
ansa[an++] = a[i];
ansb[bn++] = mina[a[i]];
}
}
for (int i = an - 1; i >= 0; --i) putchar(alf[ansa[i]]);
putchar('\n');
for (int i = bn - 1; i >= 0; --i) putchar(alf[ansb[i]]);
putchar('\n');
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#include "modules/dom/src/domcore/domstaticnodelist.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domcore/domdoc.h"
#include "modules/dom/domutils.h"
#include "modules/doc/frm_doc.h"
#include "modules/logdoc/htm_elm.h"
/* static */ OP_STATUS
DOM_StaticNodeList::Make(DOM_StaticNodeList *&dom_list, OpVector<HTML_Element>& elements, DOM_Document *document)
{
DOM_Runtime *runtime = document->GetRuntime();
DOM_EnvironmentImpl* environment = runtime->GetEnvironment();
RETURN_IF_ERROR(DOM_Object::DOMSetObjectRuntime(dom_list = OP_NEW(DOM_StaticNodeList, ()), runtime, runtime->GetPrototype(DOM_Runtime::NODELIST_PROTOTYPE), "NodeList"));
OP_STATUS status = OpStatus::OK;
for(unsigned i = 0; i < elements.GetCount(); i++)
{
DOM_Node* node;
if (OpStatus::IsError(status = environment->ConstructNode(node, elements.Get(i), document)))
break;
if (OpStatus::IsError(status = dom_list->m_dom_nodes.Add(node)))
break;
}
return status;
}
/* virtual */
DOM_StaticNodeList::~DOM_StaticNodeList()
{
m_dom_nodes.Clear();
/* the list is optionally linked into a cache holding querySelector() results; remove. */
Out();
}
/* virtual */ void
DOM_StaticNodeList::GCTrace()
{
for (unsigned i = 0; i < m_dom_nodes.GetCount(); ++i)
GCMark(m_dom_nodes.Get(i));
}
/* virtual */ void
DOM_StaticNodeList::DOMChangeRuntime(DOM_Runtime *new_runtime)
{
for (unsigned i = 0; i < m_dom_nodes.GetCount(); ++i)
m_dom_nodes.Get(i)->DOMChangeRuntime(new_runtime);
}
/* virtual */ ES_GetState
DOM_StaticNodeList::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_name == OP_ATOM_length)
{
DOMSetNumber(value, m_dom_nodes.GetCount());
return GET_SUCCESS;
}
return DOM_Object::GetName(property_name, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_StaticNodeList::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
if (property_index >= 0 && static_cast<unsigned>(property_index) < m_dom_nodes.GetCount())
{
DOMSetObject(value, m_dom_nodes.Get(property_index));
return GET_SUCCESS;
}
else
return GET_FAILED;
}
/* virtual */ ES_PutState
DOM_StaticNodeList::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
if (property_name == OP_ATOM_length)
return PUT_READ_ONLY;
else
return DOM_Object::PutName(property_name, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_StaticNodeList::GetIndexedPropertiesLength(unsigned &count, ES_Runtime *origining_runtime)
{
count = m_dom_nodes.GetCount();
return GET_SUCCESS;
}
/* static */ int
DOM_StaticNodeList::getItem(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(list, DOM_TYPE_STATIC_NODE_LIST, DOM_StaticNodeList);
DOM_CHECK_ARGUMENTS("n");
DOMSetNull(return_value);
double index = argv[0].value.number;
if (index < 0 || index > UINT_MAX)
return ES_VALUE;
unsigned property_index = static_cast<unsigned>(index);
if (property_index < list->m_dom_nodes.GetCount())
DOMSetObject(return_value, list->m_dom_nodes.Get(property_index));
return ES_VALUE;
}
|
#include "Spark.h"
#include "SparkComms.h"
#include "BluetoothSerial.h"
// NEW CODE ------------------------------------------
void notifyCB_sp(BLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify){
int i;
byte b;
Serial.print("Spark: ");
for (i = 0; i < length; i++) {
b = pData[i];
Serial.print(b, HEX);
Serial.print(" ");
ble_in.add(b);
}
Serial.println();
ble_in.commit();
// triggered_to_app = true;
}
void notifyCB_pedal(NimBLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify){
int i;
Serial.print("Pedal: ");
for (i = 0; i < length; i++) {
Serial.print(pData[i], HEX);
Serial.print(" ");
}
Serial.println();
// In mode B the BB gives 0x80 0x80 0x90 0xNN 0x64 or 0x80 0x80 0x80 0xNN 0x00 for on and off
// In mode C the BB gives 0x80 0x80 0xB0 0xNN 0x7F or 0x80 0x80 0xB0 0xNN 0x00 for on and off
/*
if (pData[2] == 0x90 || (pData[2] == 0xB0 && pData[4] == 0x7F)) {
switch (pData[3]) {
case 0x3C:
case 0x14:
curr_preset = 0;
break;
case 0x3E:
case 0x15:
curr_preset = 1;
break;
case 0x40:
case 0x16:
curr_preset = 2;
break;
case 0x41:
case 0x17:
curr_preset = 3;
break;
}
// triggered_pedal = true;
}
*/
}
/** Handler class for characteristic actions */
class CharacteristicCallbacks: public NimBLECharacteristicCallbacks {
void onRead(NimBLECharacteristic* pCharacteristic){
int j, l;
const char *p;
byte b;
Serial.print(pCharacteristic->getUUID().toString().c_str());
Serial.print(": onRead, value: ");
l = pCharacteristic->getValue().length();
p = pCharacteristic->getValue().c_str();
for (j=0; j < l; j++) {
b = p[j];
Serial.print(" ");
Serial.print(b, HEX);
};
Serial.println();
};
void onWrite(NimBLECharacteristic* pCharacteristic) {
Serial.print(pCharacteristic->getUUID().toString().c_str());
Serial.print(": onWrite(), value: ");
int j, l;
const char *p;
byte b;
l = pCharacteristic->getValue().length();
p = pCharacteristic->getValue().c_str();
for (j=0; j < l; j++) {
b = p[j];
ble_app_in.add(b);
Serial.print(" ");
Serial.print(b, HEX);
// pass_amp[j] = b;
}
Serial.println();
ble_app_in.commit();
// pass_size_amp = j;
// triggered_to_amp = true;
};
/** Called before notification or indication is sent,
* the value can be changed here before sending if desired.
*/
void onNotify(NimBLECharacteristic* pCharacteristic) {
Serial.println("Sending notification to clients");
};
/** The status returned in status is defined in NimBLECharacteristic.h.
* The value returned in code is the NimBLE host return code.
*/
void onStatus(NimBLECharacteristic* pCharacteristic, Status status, int code) {
String str = ("Notification/Indication status code: ");
str += status;
str += ", return code: ";
str += code;
str += ", ";
str += NimBLEUtils::returnCodeToString(code);
Serial.println(str);
};
void onSubscribe(NimBLECharacteristic* pCharacteristic, ble_gap_conn_desc* desc, uint16_t subValue) {
String str = "Client ID: ";
str += desc->conn_handle;
str += " Address: ";
str += std::string(NimBLEAddress(desc->peer_ota_addr)).c_str();
if(subValue == 0) {
str += " Unsubscribed to ";
}else if(subValue == 1) {
str += " Subscribed to notfications for ";
} else if(subValue == 2) {
str += " Subscribed to indications for ";
} else if(subValue == 3) {
str += " Subscribed to notifications and indications for ";
}
str += std::string(pCharacteristic->getUUID()).c_str();
if (subValue == 1 && strcmp(std::string(pCharacteristic->getUUID()).c_str(), S_CHAR2) == 0) {
M5.Lcd.println("App active");
Serial.println("App active");
}
Serial.println(str);
};
};
static CharacteristicCallbacks chrCallbacks_s, chrCallbacks_r;
bool connected_pedal, connected_sp;
void connect_to_all(bool isBLE) {
int i;
is_ble = isBLE;
// Create server to act as Spark
NimBLEDevice::init("Spark 40 BLE");
pClient_sp = NimBLEDevice::createClient();
pScan = NimBLEDevice::getScan();
if (is_ble) {
// Set up server
pServer = NimBLEDevice::createServer();
pService = pServer->createService(S_SERVICE);
pCharacteristic_receive = pService->createCharacteristic(S_CHAR1, NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::WRITE | NIMBLE_PROPERTY::WRITE_NR);
pCharacteristic_send = pService->createCharacteristic(S_CHAR2, NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::NOTIFY);
pCharacteristic_receive->setCallbacks(&chrCallbacks_r);
pCharacteristic_send->setCallbacks(&chrCallbacks_s);
pService->start();
pServer->start();
pAdvertising = NimBLEDevice::getAdvertising(); // create advertising instance
pAdvertising->addServiceUUID(pService->getUUID()); // tell advertising the UUID of our service
pAdvertising->setScanResponse(true);
Serial.println("Service set up");
}
// Connect to Spark
connected_sp = false;
connected_pedal = false;
while (!connected_sp /* || !connected_pedal*/ ) {
pResults = pScan->start(4);
NimBLEUUID SpServiceUuid(C_SERVICE);
NimBLEUUID PedalServiceUuid(PEDAL_SERVICE);
Serial.println("------------------------------");
for(i = 0; i < pResults.getCount() && (!connected_sp /* || !connected_pedal */); i++) {
device = pResults.getDevice(i);
// Print info
Serial.print("Name ");
Serial.println(device.getName().c_str());
if (device.isAdvertisingService(SpServiceUuid)) {
Serial.println("Found Spark - trying to connect....");
if(pClient_sp->connect(&device)) {
connected_sp = true;
Serial.println("Spark connected");
M5.Lcd.println("Spark connected");
}
}
if (strcmp(device.getName().c_str(),"iRig BlueBoard") == 0) {
Serial.println("Found pedal by name - trying to connect....");
pClient_pedal = NimBLEDevice::createClient();
if(pClient_pedal->connect(&device)) {
connected_pedal = true;
Serial.println("Pedal connected");
M5.Lcd.println("Pedal connected");
}
}
}
// Set up client
if (connected_sp) {
pService_sp = pClient_sp->getService(SpServiceUuid);
if (pService_sp != nullptr) {
pSender_sp = pService_sp->getCharacteristic(C_CHAR1);
pReceiver_sp = pService_sp->getCharacteristic(C_CHAR2);
if (pReceiver_sp && pReceiver_sp->canNotify()) {
if (!pReceiver_sp->subscribe(true, notifyCB_sp, true)) {
connected_sp = false;
Serial.println("Spark disconnected");
//pClient_sp->disconnect();
NimBLEDevice::deleteClient(pClient_sp);
}
}
}
}
if (connected_pedal) {
pService_pedal = pClient_pedal->getService(PedalServiceUuid);
if (pService_pedal != nullptr) {
pReceiver_pedal = pService_pedal->getCharacteristic(PEDAL_CHAR);
if (pReceiver_pedal && pReceiver_pedal->canNotify()) {
if (!pReceiver_pedal->subscribe(true, notifyCB_pedal, true)) {
connected_pedal = false;
pClient_pedal->disconnect();
}
}
}
}
}
Serial.println("Available for app to connect...");
// start advertising
if (is_ble) {
pAdvertising->start();
}
}
// NEW CODE ENDS ------------------------------------------
/*
// Callbacks for client events
class ClientCallbacks : public NimBLEClientCallbacks {
void onConnect(NimBLEClient* pClient) {
isBTConnected = true;
}
void onDisconnect(NimBLEClient* pClient) {
isBTConnected = false;
}
};
static ClientCallbacks clientCB;
void start_bt(bool isBLE) {
bt = new BluetoothSerial();
if (!bt->begin (MY_NAME, true)) {
DEBUG("Bluetooth init fail");
while (true);
}
void connect_to_spark() {
while (!connected) {
connected = bt->connect(SPARK_NAME);
if (!(connected && bt->hasClient())) {
connected = false;
DEBUG("Not connected");
delay(2000);
}
}
// flush anything read from Spark - just in case
while (bt->available())
b = bt->read();
}
*/
bool app_available() {
// return ser->available();
return !ble_app_in.is_empty();
}
bool sp_available() {
if (!is_ble) {
return bt->available();
}
else {
return !ble_in.is_empty();
}
}
uint8_t app_read() {
//return ser->read();
uint8_t b;
ble_app_in.get(&b);
return b;
}
uint8_t sp_read() {
if (!is_ble) {
return bt->read();
}
else {
uint8_t b;
ble_in.get(&b);
return b;
}
}
void app_write(byte *buf, int len) {
// ser->write(buf, len);
pCharacteristic_send->setValue(buf, len);
pCharacteristic_send->notify(true);
}
void sp_write(byte *buf, int len) {
if (!is_ble)
bt->write(buf, len);
else
pSender_sp->writeValue(buf, len, false);
}
int ble_getRSSI() {
return pClient_sp->getRssi();
}
|
๏ปฟ// API_06_Dialog.cpp : ์ ํ๋ฆฌ์ผ์ด์
์ ๋ํ ์ง์
์ ์ ์ ์ํฉ๋๋ค.
//
#include "framework.h"
#include "API_06_Dialog.h"
#define MAX_LOADSTRING 100
// ์ ์ญ ๋ณ์:
TCHAR output[200];
HWND hWnd;
HINSTANCE hInst; // ํ์ฌ ์ธ์คํด์ค์
๋๋ค.
WCHAR szTitle[MAX_LOADSTRING]; // ์ ๋ชฉ ํ์์ค ํ
์คํธ์
๋๋ค.
WCHAR szWindowClass[MAX_LOADSTRING]; // ๊ธฐ๋ณธ ์ฐฝ ํด๋์ค ์ด๋ฆ์
๋๋ค.
// ์ด ์ฝ๋ ๋ชจ๋์ ํฌํจ๋ ํจ์์ ์ ์ธ์ ์ ๋ฌํฉ๋๋ค:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK TestDlgProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: ์ฌ๊ธฐ์ ์ฝ๋๋ฅผ ์
๋ ฅํฉ๋๋ค.
// ์ ์ญ ๋ฌธ์์ด์ ์ด๊ธฐํํฉ๋๋ค.
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadStringW(hInstance, IDC_API06DIALOG, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// ์ ํ๋ฆฌ์ผ์ด์
์ด๊ธฐํ๋ฅผ ์ํํฉ๋๋ค:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_API06DIALOG));
MSG msg;
// ๊ธฐ๋ณธ ๋ฉ์์ง ๋ฃจํ์
๋๋ค:
while (GetMessage(&msg, nullptr, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
//
// ํจ์: MyRegisterClass()
//
// ์ฉ๋: ์ฐฝ ํด๋์ค๋ฅผ ๋ฑ๋กํฉ๋๋ค.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_API06DIALOG));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_API06DIALOG);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));
return RegisterClassExW(&wcex);
}
//
// ํจ์: InitInstance(HINSTANCE, int)
//
// ์ฉ๋: ์ธ์คํด์ค ํธ๋ค์ ์ ์ฅํ๊ณ ์ฃผ ์ฐฝ์ ๋ง๋ญ๋๋ค.
//
// ์ฃผ์:
//
// ์ด ํจ์๋ฅผ ํตํด ์ธ์คํด์ค ํธ๋ค์ ์ ์ญ ๋ณ์์ ์ ์ฅํ๊ณ
// ์ฃผ ํ๋ก๊ทธ๋จ ์ฐฝ์ ๋ง๋ ๋ค์ ํ์ํฉ๋๋ค.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // ์ธ์คํด์ค ํธ๋ค์ ์ ์ญ ๋ณ์์ ์ ์ฅํฉ๋๋ค.
hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
//
// ํจ์: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// ์ฉ๋: ์ฃผ ์ฐฝ์ ๋ฉ์์ง๋ฅผ ์ฒ๋ฆฌํฉ๋๋ค.
//
// WM_COMMAND - ์ ํ๋ฆฌ์ผ์ด์
๋ฉ๋ด๋ฅผ ์ฒ๋ฆฌํฉ๋๋ค.
// WM_PAINT - ์ฃผ ์ฐฝ์ ๊ทธ๋ฆฝ๋๋ค.
// WM_DESTROY - ์ข
๋ฃ ๋ฉ์์ง๋ฅผ ๊ฒ์ํ๊ณ ๋ฐํํฉ๋๋ค.
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
break;
case WM_COMMAND:
{
int wmId = LOWORD(wParam);
// ๋ฉ๋ด ์ ํ์ ๊ตฌ๋ฌธ ๋ถ์ํฉ๋๋ค:
switch (wmId)
{
case IDM_EXAMPLE_01:
DialogBox(hInst, MAKEINTRESOURCE(IDD_DIALOG_TEST), hWnd, TestDlgProc);
InvalidateRgn(hWnd, NULL, TRUE);
break;
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
// TODO: ์ฌ๊ธฐ์ hdc๋ฅผ ์ฌ์ฉํ๋ ๊ทธ๋ฆฌ๊ธฐ ์ฝ๋๋ฅผ ์ถ๊ฐํฉ๋๋ค...
FILE* fp = nullptr;
_tfopen_s(&fp, _T("test.txt"), _T("r ccs = UNICODE"));
if (fp == nullptr) EndPaint(hWnd, &ps);
else {
// ์ฝ์ ๋ค ์ถ๋ ฅ
TextOut(hdc, 0, 0, output, _tcslen(output));
EndPaint(hWnd, &ps);
}
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
//[ '\r','\n']
INT_PTR CALLBACK TestDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
static bool hobby[3];
static bool gender;
static TCHAR szGender[2][10] = { _T("๋จ"),_T("์ฌ") };
static TCHAR szHobby[3][20] = { _T("์ํ๊ฐ์"), _T("๋
์"), _T("๊ฒ์") };
TCHAR tmpName[50];
TCHAR tmpAddr[50];
FILE* fp;
switch (message) {
case WM_INITDIALOG:
// ํ๋ฉด ์ด๊ธฐ ๊ฐ
hobby[0] = hobby[1] = hobby[2] = gender = false;
SetDlgItemText(hDlg, IDC_EDIT_NAME, _T("์ด๋ฆ"));
SetDlgItemText(hDlg, IDC_EDIT_ADDR, _T("์ฃผ์"));
CheckRadioButton(hDlg, IDC_RADIO_MALE, IDC_RADIO_FEMALE, IDC_RADIO_MALE);
return 1;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_RADIO_MALE: gender = false; break;
case IDC_RADIO_FEMALE: gender = true; break;
case IDC_CHECK_MOVIE: hobby[0] = !hobby[0];break;
case IDC_CHECK_READING: hobby[1] = !hobby[1];break;
case IDC_CHECK_GAME: hobby[2] = !hobby[2];break;
case IDC_BUTTON_OK :
_tfopen_s(&fp, _T("test.txt"), _T("w, ccs = UNICODE"));
GetDlgItemText(hDlg, IDC_EDIT_NAME, tmpName, 30);
GetDlgItemText(hDlg, IDC_EDIT_ADDR, tmpAddr, 50);
_stprintf_s(output, _T("์ด๋ฆ: %s\r\n์ฃผ์: %s\r\n์ฑ๋ณ: %s์ฑ\r\n์ทจ๋ฏธ: %s %s %s\r\n"),
tmpName, tmpAddr,
gender ? szGender[1] : szGender[0],
hobby[0] ? szHobby[0] : _T(""),
hobby[1] ? szHobby[1] : _T(""),
hobby[2] ? szHobby[2] : _T("")
);
_fputts(output, fp);
SetDlgItemText(hDlg, IDC_EDIT_RESULT, output);
fclose(fp);
break;
case IDCANCEL : case IDC_BUTTON_CANCEL :
EndDialog(hDlg, 0);
break;
}
break;
}
return 0;
}
// ์ ๋ณด ๋ํ ์์์ ๋ฉ์์ง ์ฒ๋ฆฌ๊ธฐ์
๋๋ค.
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
|
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <semaphore.h>
#include <string>
#include <cstring>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <fcntl.h>
#define RWRR (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
using namespace std;
//Roman Sobolenko
//CSD415 Assignment
//Inter process communication through shared memory.
//parentProc ismywriter - takes input from user
//1. Start create, attach to shared memory
//2. create semaphore
//3. Fork and start child process
//4. Loop prompting the user for input
//5. In that loop aquire semphare and write usr inout to shared memory
//6. Release semaphore
sem_t *sem;
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
char *myStr = (char*) shmat(shmid,(void*)0,0);
char * mySem = "/tmpsen";
sem_unlink(mySem); //destroy sem if exists
sem = sem_open(mySem, O_CREAT|O_EXCL, RWRR, 1); //create sem
//fork to the child
if(fork() == 0){
//use gnome to open another terminal
// string s = "gnome-terminal -- ./childProc";
system("gnome-terminal -- ./childProc");
}
else{
while(true){
//array to store user input
char *userInput = new char[256];
cout<<"\nWrite Data : ";
cin >> userInput;
// cin >> myStr; //consolue_input
//aquire sempaphore from the user input
sem_wait(sem); // wait for sem
//add user input to shared mem
strcat(myStr, userInput);
strcat(myStr, "\n");
//realease the semaphore
sem_post(sem);
printf("Data written in memory: %s\n",myStr);
printf(userInput);
}
//detach from shared memory
shmdt(myStr);
}
return 0;
}
|
/* $Id$ */
/* Symbol table data structure.
Each identifier structure refers to a list of possible meanings of this
identifier. Each of these meanings is represented by a "symbol" structure.
*/
typedef union constant { /* depends on type */
long co_ival;
double co_rval;
char *co_sval;
char *co_setval;
} t_const, *p_const;
typedef struct name {
long nm_value; /* address or offset */
struct scope *nm_scope; /* for names that define a scope */
} t_name, *p_name;
typedef struct symbol {
struct symbol *sy_next; /* link to next meaning */
struct symbol *sy_prev_sc; /* link to previous decl in scope */
struct type *sy_type; /* type of symbol */
int sy_class;
#define CONST 0x0001
#define TYPE 0x0002
#define TAG 0x0004
#define MODULE 0x0008
#define PROC 0x0010
#define FUNCTION 0x0020
#define VAR 0x0040
#define REGVAR 0x0080
#define LOCVAR 0x0100
#define VARPAR 0x0200
#define FIELD 0x0400
#define FILESYM 0x0800 /* a filename */
#define FILELINK 0x1000 /* a filename without its suffix */
#define LBOUND 0x2000 /* lower bound of array descriptor */
#define UBOUND 0x4000 /* upper bound of array descriptor */
struct idf *sy_idf; /* reference back to its idf structure */
struct scope *sy_scope; /* scope in which this symbol resides */
union {
t_const syv_const; /* CONST */
t_name syv_name;
struct file *syv_file; /* for FILESYM */
struct symbol *syv_fllink; /* for FILELINK */
struct symbol *syv_descr; /* for LBOUND and UBOUND */
struct fields *syv_field;
} sy_v;
#define sy_const sy_v.syv_const
#define sy_name sy_v.syv_name
#define sy_file sy_v.syv_file
#define sy_filelink sy_v.syv_fllink
#define sy_field sy_v.syv_field
#define sy_descr sy_v.syv_descr
} t_symbol, *p_symbol;
/* ALLOCDEF "symbol" 50 */
extern p_symbol NewSymbol(), Lookup(), Lookfromscope(), add_file();
extern p_symbol identify();
extern p_symbol currfile, listfile;
|
/*
* Created by Peng Qixiang on 2018/8/9.
*/
/*
* ๆฐๅญๅจๆๅบๆฐ็ปไธญๅบ็ฐ็ๆฌกๆฐ
* ็ป่ฎกไธไธชๆฐๅญๅจๆๅบๆฐ็ปไธญๅบ็ฐ็ๆฌกๆฐใ
*
*/
# include <iostream>
# include <vector>
using namespace std;
class Solution {
public:
// binary search
int GetNumberOfK(vector<int> data ,int k) {
if(data.empty()) return 0;
int firstIndex = biSearchFirst(data, k);
int lastIndex = biSearchLast(data, k);
if(firstIndex != -1 && lastIndex != -1) return lastIndex - firstIndex + 1;
else return 0;
}
int biSearchFirst(vector<int> data, int k){
int start = 0, end = data.size() - 1;
while(start <= end){
int mid = (start + end) / 2;
if(data[mid] < k) start = mid + 1;
else if(data[mid] > k) end = mid - 1;
else if(mid - 1 >= 0 && data[mid - 1] == k) end = mid - 1;
else return mid;
}
return -1;
}
int biSearchLast(vector<int> data, int k){
int start = 0, end = data.size() - 1;
while(start <= end){
int mid = (start + end) / 2;
if(data[mid] < k) start = mid + 1;
else if(data[mid] > k) end = mid - 1;
else if(mid + 1 < data.size() && data[mid + 1] == k) start = mid + 1;
else return mid;
}
return -1;
}
};
int main(){
vector<int> test;
test.push_back(1);
test.push_back(2);
test.push_back(2);
test.push_back(3);
test.push_back(4);
Solution s = Solution();
cout << s.GetNumberOfK(test, 2) << endl;
return 0;
}
|
#include "core/pch.h"
#if defined _NEED_LIBSSL_VERIFY_SIGNED_FILE_
#include "modules/libssl/sslv3.h"
#include "modules/libssl/sslopt.h"
#include "modules/url/url2.h"
#include "adjunct/desktop_util/string/stringutils.h"
unsigned long GeneralDecodeBase64(const unsigned char *source, unsigned long len, unsigned long &read_pos, unsigned char *target, BOOL &warning, unsigned long max_write_len=0, unsigned char *decode_buf=NULL, unsigned int *decode_len=NULL);
/** Verify signed file
* The function will return FALSE if signature fails or if any errors occur,
*
* @param signed_file URL containing the file to be verified. MUST be loaded,
* which can be accomplished with signed_file.QuickLoad(TRUE)
* @param signature Base64 encoded signature
*
* @param key Pointer to buffer containing the DER encoded public key associated
* with the private key used to generate the signature, MUST be an
* X509_PUBKEY structure (openssl rsa -pubout ... command result)
* @param key_len Length of the public key buffer
*
* @param alg Algorithm used to calculate signature. Default SSL_SHA
*
* @return TRUE if the verification succeded, FALSE if there was any error.
*/
BOOL VerifySignedFile(URL &signed_file, const OpStringC8 &signature, const unsigned char *key, unsigned long key_len, SSL_HashAlgorithmType alg)
{
if(signed_file.IsEmpty() || (URLStatus) signed_file.GetAttribute(URL::KLoadStatus) != URL_LOADED || key == NULL || key_len == 0)
return FALSE;
// Get The raw data
OpAutoPtr<URL_DataDescriptor> desc(signed_file.GetDescriptor(NULL, TRUE, TRUE, TRUE));
if(!desc.get())
return FALSE;
BOOL more = FALSE;
unsigned long buf_len;
if(desc->RetrieveData(more) == 0 || desc->GetBuffer() == NULL)
return FALSE;
if(desc->GetBufSize() == 0)
return FALSE;
if(signature.Length() <= 0)
return FALSE;
unsigned long signature_len = signature.Length();
SSL_varvector32 signature_in;
signature_in.Resize(signature_len);
if(signature_in.Error())
return FALSE;
unsigned long read_len=0;
BOOL warning= FALSE;
buf_len = GeneralDecodeBase64((unsigned char *)signature.CStr(), signature_len, read_len, signature_in.GetDirect(), warning);
if(warning || read_len != signature_len || buf_len == 0)
return FALSE;
signature_in.Resize(buf_len);
SSL_Hash_Pointer digester(alg);
if(digester.Error())
return FALSE;
digester->InitHash();
do{
more = FALSE;
buf_len = desc->RetrieveData(more);
digester->CalculateHash((unsigned char *)desc->GetBuffer(), buf_len);
desc->ConsumeData(buf_len);
}while(more);
SSL_varvector32 signature_out;
digester->ExtractHash(signature_out);
if(digester->Error() || signature_out.Error())
return FALSE;
OpAutoPtr<SSL_PublicKeyCipher> signature_checker;
OP_STATUS op_err = OpStatus::OK;
signature_checker.reset(g_ssl_api->CreatePublicKeyCipher(SSL_RSA, op_err));
if(OpStatus::IsError(op_err) || signature_checker.get() == NULL)
return FALSE;
SSL_varvector32 pubkey_bin_ex;
pubkey_bin_ex.SetExternal((unsigned char *) key);
pubkey_bin_ex.Resize(key_len);
signature_checker->LoadAllKeys(pubkey_bin_ex);
if(signature_checker->Error())
return FALSE;
if(alg == SSL_SHA)
{
if(!signature_checker->Verify(signature_out.GetDirect(), signature_out.GetLength(), signature_in.GetDirect(), signature_in.GetLength()))
return FALSE;
}
#ifdef USE_SSL_ASN1_SIGNING
else
{
if(!signature_checker->VerifyASN1(digester, signature_in.GetDirect(), signature_in.GetLength()))
return FALSE;
}
#endif
if(signature_checker->Error())
return FALSE;
return TRUE;
}
/** Verify checksum
* The function will return FALSE if verification fails or if any errors occur,
*
* @param signed_file URL containing the file to be verified. MUST be loaded,
* which can be accomplished with signed_file.QuickLoad(TRUE)
* @param checksum Base64 encoded checksum
*
* @param alg Algorithm used to calculate checksum. Default SSL_SHA
*
* @return TRUE if the verification succeded, FALSE if there was any error.
*/
BOOL VerifyChecksum(URL &signed_file, const OpStringC8 &checksum, SSL_HashAlgorithmType alg)
{
if(signed_file.IsEmpty() || (URLStatus) signed_file.GetAttribute(URL::KLoadStatus) != URL_LOADED)
return FALSE;
// Get The raw data
OpAutoPtr<URL_DataDescriptor> desc(signed_file.GetDescriptor(NULL, TRUE, TRUE, TRUE));
if(!desc.get())
return FALSE;
BOOL more = FALSE;
unsigned long buf_len;
if(desc->RetrieveData(more) == 0 || desc->GetBuffer() == NULL)
return FALSE;
if(desc->GetBufSize() == 0)
return FALSE;
SSL_Hash_Pointer digester(alg);
if(digester.Error())
return FALSE;
digester->InitHash();
do{
more = FALSE;
buf_len = desc->RetrieveData(more);
digester->CalculateHash((unsigned char *)desc->GetBuffer(), buf_len);
desc->ConsumeData(buf_len);
}while(more);
SSL_varvector32 signature_out;
digester->ExtractHash(signature_out);
if(digester->Error() || signature_out.Error())
return FALSE;
#ifdef _DEBUG
OpString8 s8;
OP_STATUS retval = ByteToHexStr(signature_out.GetDirect(), signature_out.GetLength(), s8);
OP_ASSERT(retval == OpStatus::OK);
#endif
byte* byte_buffer = NULL;
unsigned int buffer_len = 0;
OP_STATUS ret = HexStrToByte(checksum, byte_buffer, buffer_len);
if(OpStatus::IsError(ret))
return FALSE;
SSL_varvector32 signature_in;
signature_in.Set(byte_buffer, buffer_len);
OP_DELETEA(byte_buffer);
return signature_in == signature_out;
}
/** Check file signature (SHA 256 algorithm)
* The function will return ERR if verification fails or if any errors occur,
*
* @param full_path Full path of file to be checked
*
* @param signature Base64 encoded checksum
*
* @return OK if the verification succeded, ERR if there was any error.
*/
OP_STATUS CheckFileSignature(const OpString &full_path, const OpString8& signature)
{
OpString resolved;
OpString path;
OP_MEMORY_VAR BOOL successful;
RETURN_IF_ERROR(path.Append("file:"));
RETURN_IF_ERROR(path.Append(full_path));
RETURN_IF_LEAVE(successful = g_url_api->ResolveUrlNameL(path, resolved));
if (!successful || resolved.Find("file://") != 0)
return OpStatus::ERR;
URL url = g_url_api->GetURL(resolved.CStr());
if (!url.QuickLoad(TRUE))
return OpStatus::ERR;
// Verify hash
if (VerifyChecksum(url, signature, SSL_SHA_256))
return OpStatus::OK;
else
return OpStatus::ERR;
/*
if (VerifySignedFile(url, signature, AUTOUPDATE_KEY, sizeof(AUTOUPDATE_KEY), SSL_SHA_256))
return OpStatus::OK;
else
return OpStatus::ERR;
*/
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#if defined(INTERNAL_XBM_SUPPORT) || defined(ASYNC_IMAGE_DECODERS_EMULATION)
#include "modules/img/src/imagedecoderxbm.h"
#include "modules/util/str.h"
ImageDecoderXbm::ImageDecoderXbm()
{
image_decoder_listener = NULL;
header_loaded = FALSE;
start_pixel = 0;
last_decoded_line = 0;
width = 0;
height = 0;
row_BGRA = NULL;
}
ImageDecoderXbm::~ImageDecoderXbm()
{
if (row_BGRA)
OP_DELETEA(row_BGRA);
}
OP_STATUS ImageDecoderXbm::DecodeData(const BYTE* data, INT32 numBytes, BOOL more, int& resendBytes, BOOL/* load_all = FALSE*/)
{
resendBytes = 0;
int buf_used = 0;
while (!header_loaded)
{
int line_len = GetNextLine((const unsigned char*)data + buf_used, numBytes - buf_used);
if (!line_len)
{
if (more)
{
resendBytes = numBytes - buf_used;
}
return OpStatus::OK;
}
const unsigned char* start_dim = strnstr((const unsigned char*)data + buf_used, line_len-1, (const unsigned char*) WidthString);
if (start_dim)
{
start_dim += op_strlen(WidthString);
width = op_atoi((const char*) start_dim);
}
else
{
start_dim = strnstr((const unsigned char*)data + buf_used, line_len-1, (const unsigned char*) HeightString);
if (start_dim)
{
start_dim += op_strlen(HeightString);
height = op_atoi((const char*) start_dim);
}
}
buf_used += line_len;
if (width && height)
{
header_loaded = TRUE;
if (image_decoder_listener != NULL)
{
if (width <= 0 || width >= 65536 || height <= 0 || height >= 65536)
{
return OpStatus::ERR;
}
if (!image_decoder_listener->OnInitMainFrame(width, height))
return OpStatus::OK;
ImageFrameData image_frame_data;
image_frame_data.rect.width = width;
image_frame_data.rect.height = height;
image_frame_data.interlaced = TRUE;
image_frame_data.bits_per_pixel = 1;
image_frame_data.transparent = TRUE;
image_decoder_listener->OnNewFrame(image_frame_data);
}
// alloc a line to write line data into
row_BGRA = OP_NEWA(UINT32, width);
if (!row_BGRA)
{
return OpStatus::ERR_NO_MEMORY;
}
}
}
// Load bitmap data
// start_pixel indicates where to start in last_decoded_line
BYTE src_bit = 0;
UINT32 target_pixel = start_pixel;
UINT32 current_line = last_decoded_line;
while (current_line < height)
{
BYTE next_byte;
while ((target_pixel < width) && GetNextInt((const unsigned char*)data, numBytes, buf_used, next_byte))
{
for (src_bit = 0; (src_bit < 8) && (target_pixel < width); src_bit++)
{
UINT8 *dest_row = (UINT8*)&row_BGRA[target_pixel];
if ((next_byte>>src_bit)&0x01)
{
*((UINT32*)dest_row) = 0xFF000000;
}
else
{
// transparent
dest_row[0] = dest_row[1] = dest_row[2] = dest_row[3] = 0x00;
}
target_pixel++;
}
}
if (target_pixel < width)
{
// need more data
start_pixel = target_pixel;
last_decoded_line = current_line;
resendBytes = numBytes - buf_used;
return OpStatus::OK;
}
else
{
target_pixel = 0;
if (image_decoder_listener)
image_decoder_listener->OnLineDecoded(row_BGRA, current_line, 1);
current_line++;
}
}
if (current_line == height || !more)
{
// Tells us that we are ready parsing.
if (image_decoder_listener != NULL)
image_decoder_listener->OnDecodingFinished();
}
return OpStatus::OK;
}
int ImageDecoderXbm::GetNextLine(const unsigned char* buf, int buf_len)
{
const unsigned char* tmp = buf;
int i;
for (i=0; i<buf_len; i++)
{
if (*tmp == '\r' || *tmp == '\n')
break;
tmp++;
}
if (i < buf_len)
{
// fount '\r' or '\n'
return i+1;
}
else
return 0;
}
BOOL ImageDecoderXbm::GetNextInt(const unsigned char* buf, int buf_len, int& buf_used, BYTE& next_byte)
{
BOOL ok = FALSE;
// check if enough data
if ((buf_len - buf_used) < 5)
return FALSE;
const unsigned char* tmp = strnstr(buf + buf_used, (buf_len - buf_used - 1), (unsigned char*) "0x");
if (tmp)
{
if ((buf_len - (tmp - buf)) < 5)
return FALSE;
buf_used = tmp - buf;
tmp += 2;
if (op_isxdigit(*tmp) && op_isxdigit(*(tmp+1)))
{
next_byte = (op_isdigit(*tmp)) ? *tmp-'0' : (op_isupper(*tmp)) ? *tmp-'A'+10 : *tmp-'a'+10;
next_byte *= 16;
tmp++;
next_byte += (op_isdigit(*tmp)) ? *tmp-'0' : (op_isupper(*tmp)) ? *tmp-'A'+10 : *tmp-'a'+10;
ok = TRUE;
}
buf_used += 4;
}
else if (buf_len-buf_used > 4)
buf_used = buf_len-4;
return ok;
}
void ImageDecoderXbm::SetImageDecoderListener(ImageDecoderListener* imageDecoderListener)
{
image_decoder_listener = imageDecoderListener;
}
#endif // INTERNAL_XBM_SUPPORT
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
vector<int> nums{0,3,7,2,5,8,4,6,0,1};
int n = nums.size();
unordered_set <int> hash;
for(auto num: nums) {
hash.insert(num);
}
int longestStreak = 0;
for(auto num: nums) {
if(hash.find(num-1) == hash.end()) {
int cur_num = num;
int currentStreak = 1;
while(hash.find(cur_num + 1) != hash.end()) {
cur_num++;
currentStreak++;
}
longestStreak = max(longestStreak, currentStreak);
}
}
cout << longestStreak << endl;
return 0;
}
|
// Client side C/C++ program to demonstrate Socket programming
// Project #1 :: RealTime ::<< endl
// Project #1 :: RealTime ::<< endl
// Project #1 :: RealTime ::<< endl
// Project #1 :: RealTime ::<< endl
// Project #1 :: RealTime ::<< endl
// cout << Yahya Shqair :: 1160699 :: << Firas maali ::
// cout << Yahya Shqair :: 1160699 :: << Firas maali ::
// cout << Yahya Shqair :: 1160699 :: << Firas maali ::
// cout << Yahya Shqair :: 1160699 :: << Firas maali ::
#include <bits/stdc++.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
#define all(v) (v).begin(), (v).end()
#define lp(i, n) for (int i = 0; i < (n) ; ++i)
#define lpp(i, n) for (int i = 1; i <= (n) ; ++i)
#define lpi(i, j, n) for(int i=(j);i<(int)(n);++i)
#define lpd(i, j, n) for(int i=(j);i>=(int)(n);--i)
#define sz(v) (int)(v).size()
#define clr(v, d) memset(v, d, sizeof(v))
#define mod 100000007
#define PORT 8000
// Client id and msg ID :
int cID , msgID;
int makeRequest();
void lock() {
char type[] = "1:";
char buffer[1024] = {0};
// open new socket for this request
int sock = makeRequest();
int ready = 0 ;// flag is true or false .
cout << "Wait for lock"<<endl;
send(sock , type , strlen(type) , 0 );
read( sock , buffer, 1024);
ready = atoi(buffer);
cout << "Locked successfully"<<endl;
}
void unlock() {
char type[] = "2:";
char buffer[1024] = {0};
int sock = makeRequest();
int ready = 0 ;
// loop is not important but
send(sock , type , strlen(type) , 0 );
read( sock , buffer, 1024);
ready = atoi(buffer);
if(ready != 1){
cout << " you must lock before unlock "<<endl;
return ;
}
cout << "Unlocked Successfully " << endl;
}
void remove() {
char type[] = "6:";
char buffer[1024] = {0};
int sock = makeRequest();
int ready = 0 ;
// loop is not important but
send(sock , type , strlen(type) , 0 );
read( sock , buffer, 1024);
ready = atoi(buffer);
if(ready != 1){
cout << " Fail "<<endl;
return ;
}
cout << "Removed Successfully " << endl;
}
void read() {
char type[] = "3:";
char buffer[1024];
buffer[0] = '0';
int sock = makeRequest();
int ready = 0 ;
send(sock , type , strlen(type) , 0 );
read( sock , buffer, 1024);
ready = atoi(buffer);
if (buffer[0] == '0') {
cout << "You must lock before read " << endl;
return ;
}
cout << buffer << endl;
cout << "Read Successfully " << endl;
}
void write() {
char type[] = "4:";
char buffer[1024];
buffer[0] = '0';
// open new Socket
int sock = makeRequest();
int ready = 0 ;
send(sock , type , strlen(type) , 0 );
read( sock , buffer, 1024);
ready = atoi(buffer);
if (buffer[0] == '0') {
cout << "You must lock before read " << endl;
return ;
}
// Read Data
cout << "Print the msg you want to sent ,, enter # to stop reading" << endl;
string x="",y;
while(cin >> y &&y[0]!='#'){
x+=y+" ";
}
// Move Date from std:string to char[] ;
lp(i, x.size()) {buffer[i] = x[i]; buffer[i + 1] = '\0';}
// send the buffer
send(sock , buffer , strlen(buffer) , 0 );
read( sock , buffer, 1024);
// if response = 1 is ture else failed ;
if (buffer[0] == '1') {
cout << "written Successfully " << endl;
} else {
cout << "Failed " << endl;
}
}
int makeRequest() {
int sock = 0, valread;
struct sockaddr_in serv_addr;
char hello[1100];
// each request has the first tcp msg is like 'web cookies'
// to tell the server client id and msg id .
// implement the cookie
string helloShakehand = std::to_string(cID) + ":" + std::to_string(msgID) + ":";
lp(i, helloShakehand.size()) {hello[i] = helloShakehand[i]; hello[i + 1] = '\0';}
cout << helloShakehand << endl;
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
read( sock , buffer, 1024);
if (atoi(buffer) != 1) {
cout << "error in connection" << endl;
return 0 ;
} else {
cout << "Connected ..." << endl;
return sock ;
}
return sock ;
}
int main()
{
while (1) {
readId :
cout << "Please Enter Client ID : ";
cin >> cID ;
readMID:
cout << endl << "Please Enter sheard Memory you want to access : ";
cin >> msgID ;
while (1) {
cout << endl << "Enter type of you Request : " << endl;
cout << "1- Lock " << endl;
cout << "2- unLock " << endl;
cout << "3- Read " << endl;
cout << "4- Write " << endl;
cout << "5- Change msg id " << endl;
cout << "6- Change Client session " << endl;
cout << "7- Remove me from msg client list " << endl;
int type ; cin >> type ;
if (type == 1) {
lock();
} else if (type == 2 ) {
unlock();
} else if (type == 3) {
read();
} else if (type == 4 ) {
write();
} else if (type == 5) {
goto readMID;
} else if (type == 6 ) {
goto readId;
}else if(type == 7){
remove();
goto readMID ;
} else {
cout << "this option not implemeted yet ." << endl;
}
}
}
return 0;
}
|
#include <iostream>
using namespace std;
long long f(long long v) {
long long b, n, t;
//Init
b = 15;
n = 21;
while(n < v) {
t = (2 * n) + (3 * b) - 2;
n = (3 * n) + (4 * b) - 3;
b = t;
}
return b;
}
int main() {
cout << "Result:" << f(1000000000000) << endl;
return 0;
}
|
#include <cstdio>
void verificaIntervalo(double n);
int main() {
double valor[4];;
scanf("%lf %lf %lf %lf", &valor[0],&valor[1],&valor[2],&valor[3]);
double media = (2*valor[0] + 3*valor[1]+ 4*valor[2]+valor[3])/10;
printf("Media: %.1lf\n", media);
if(media>=7.0){
printf("Aluno aprovado.\n");
}
if(media< 5.0){
printf("Aluno reprovado.\n");
}
if(media >= 5.0 && media <= 6.9) {
printf("Aluno em exame.\n");
double final;
scanf("%lf", &final);
printf("Nota do exame: %.1lf\n", final);
media = (media+final)/2;
if(media>=5.0){
printf("Aluno aprovado.\n");
} else{
printf("Aluno reprovado.\n");
}
printf("Media final: %.1lf\n", media);
}
}
|
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#define LED_WIFI LED_BUILTIN
#define INPUT_ADC A0
#define ssid "YOUR-SSID"
#define password "YOUR-SECRET-PASSWORD"
#define SERVER_URL "SERVER-URL"
void setup_wifi(void);
void read_data(void);
void upload_data(void);
float temperature;
HTTPClient http;
void setup()
{
pinMode(LED_WIFI, OUTPUT);
Serial.begin(115200);
setup_wifi();
}
void loop()
{
read_data();
upload_data();
delay(5e3);
}
void setup_wifi()
{
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
bool wifi_state = LOW;
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
digitalWrite(LED_WIFI, wifi_state);
wifi_state ^= HIGH;
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Show that device is connected
digitalWrite(LED_WIFI, HIGH);
}
void read_data()
{
volatile float Vout = analogRead(INPUT_ADC) * 3.3f / 1024;
/*
* TMP35 Temperature curve:
* Vout = 0.01 [V/Celsius] * Temp
* ~~
* Temp = 100 * Vout
*/
temperature = 100 * Vout;
}
void upload_data()
{
http.begin(SERVER_URL);
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST("\{\"data\": " + String(temperature) + "\}");
if (httpCode > 0)
{
Serial.printf("[HTTP] POST... code: %d\n", httpCode);
// if (httpCode == HTTP_CODE_OK)
// {
// String payload = http.getString();
// Serial.println(payload);
// }
String payload = http.getString();
Serial.println(payload);
}
else
{
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
|
//FOR CYCLE
int main(){
for(int i = 1; i < 10; i++){
cout << i << endl;
}
return 0;
}
// ีีกีทีพีฅีฌ (0;50) ีจีถีฏีกีฎ ีฐีกีฟีพีกีฎีธึีด ีจีถีฏีกีฎ ีฆีธึีตีฃ ีฉีพีฅึีซ ีฃีธึีดีกึีจ
//1-ีซีถ ีฅีฒีกีถีกีฏ
int main(){
int sum=0;
for(int i = 0; i <= 50; i++){
if(i % 2 == 0){
sum += i;
}
}
cout << sum << endl;
return 0;
}
//2-ึีค ีฅีฒีกีถีกีฏ
int main(){
int sum=0;
for(int i = 0; i <= 50; i+=2){
sum += i;
cout << i<< endl;
}
cout << sum << endl;
return 0;
}
// ีดีซีถีนีง n ีจีถีฏีกีฎ ีฉีพีฅึีซ ีฃีธึีดีกึีจ
int main(){
int n;
cin >> n;
int j=n;
int sum=0;
while(j){
sum+=j%10;
j/=10;
}
cout<<sum;
return 0;
}
|
#pragma once
#include "elog/appenders/appender.hpp"
#include <string>
namespace elog
{
class RawAppender: public BaseAppender
{
public:
RawAppender(Formatter& formatter);
~RawAppender();
void append(const Record& record) override;
protected:
virtual void write(const std::string&) = 0;
};
}
|
// Created on: 1996-10-11
// Created by: Christian CAILLET
// Copyright (c) 1996-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESSelect_SelectSubordinate_HeaderFile
#define _IGESSelect_SelectSubordinate_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <IFSelect_SelectExtract.hxx>
class Standard_Transient;
class Interface_InterfaceModel;
class TCollection_AsciiString;
// resolve name collisions with X11 headers
#ifdef Status
#undef Status
#endif
class IGESSelect_SelectSubordinate;
DEFINE_STANDARD_HANDLE(IGESSelect_SelectSubordinate, IFSelect_SelectExtract)
//! This selections uses Subordinate Status as sort criterium
//! It is an integer number which can be :
//! 0 Independent
//! 1 Physically Dependent
//! 2 Logically Dependent
//! 3 Both (recorded)
//! + to sort :
//! 4 : 1 or 3 -> at least Physically
//! 5 : 2 or 3 -> at least Logically
//! 6 : 1 or 2 or 3 -> any kind of dependence
//! (corresponds to 0 reversed)
class IGESSelect_SelectSubordinate : public IFSelect_SelectExtract
{
public:
//! Creates a SelectSubordinate with a status to be sorted
Standard_EXPORT IGESSelect_SelectSubordinate(const Standard_Integer status);
//! Returns the status used for sorting
Standard_EXPORT Standard_Integer Status() const;
//! Returns True if <ent> is an IGES Entity with Subordinate
//! Status matching the criterium
Standard_EXPORT Standard_Boolean Sort (const Standard_Integer rank, const Handle(Standard_Transient)& ent, const Handle(Interface_InterfaceModel)& model) const Standard_OVERRIDE;
//! Returns the Selection criterium : "IGES Entity, Independent"
//! etc...
Standard_EXPORT TCollection_AsciiString ExtractLabel() const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(IGESSelect_SelectSubordinate,IFSelect_SelectExtract)
protected:
private:
Standard_Integer thestatus;
};
#endif // _IGESSelect_SelectSubordinate_HeaderFile
|
#ifdef QT_QML_DEBUG
#include <QtQuick>
#endif
#include <sailfishapp.h>
int main (int argc, char * argv []) {
return SailfishApp::main (argc, argv);
}
|
#ifndef INCLUDE_PROCESSORSTATE_H_
#define INCLUDE_PROCESSORSTATE_H_
class ParserState
{
public :
virtual ~ParserState(){};
virtual void receiveChar(char received) = 0;
};
#endif /* INCLUDE_PROCESSORSTATE_H_ */
|
// Hardware: https://www.tindie.com/products/AllAboutEE/esp8266-analog-inputs-expander/
#include <AllAboutEE_MCP3021.h>
/**
* @brief Sets the pin and fixed address bits for I2C
*
* @author Carlos (4/12/2015)
*
* @param sda The SDA pin number
* @param scl The SCL pin number
*/
void AllAboutEE::MCP3021::begin(int sda, int scl)
{
Wire.pins(sda,scl);
Wire.begin(MCP3021_I2C_ADDRESS);
}
/**
* @brief Gives a conversion's result as a digital value between
* 0 and 1023
*
* @author Carlos (4/12/2015)
*
* @param deviceId The last three bits in the device's I2C
* address. This would be the last number in
* device's name e.g. for an MCP3021A5 deviceId
* = 5, for an MCP3021A3 deviceId = 3.
*
* @return uint16_t The 10-bit conversion result, a value from 0
* to 1023
*/
uint16_t AllAboutEE::MCP3021::read(int deviceId)
{
// we'll read the bytes from the I2C bus into this array
uint8_t data[2];
data[0] = 0x00;
data[1] = 0x00;
// the array is a 10-bit result, the smallest type that can contain it is uint16_t
uint16_t result = 0x0000;
// The device's address is binary [1][0][0][1][A0][A1][A2] where [A0][A1][A2] is the device's unique id
Wire.requestFrom(MCP3021_I2C_ADDRESS|deviceId, 2);
for(int i =0; Wire.available() > 0;i++)
{
data[i] = Wire.read();
}
// The converter's 10-bit result is two bytes that looks like this:
// [0][0][0][0][D9][D8][D7][D6] [D5][D4][D3][D1][D0][x][x]
// so to put them in one variable ...
result = (result | data[0]) << 6; // we take the MSB and shift it left 6 times
data[1] = data[1] >> 2; // we take the LSB and shift it right two times
result = result | data[1]; // we OR both bytes
return result;
}
/**
* @brief Gives a converter's result as an analog value between
* 0 and VDD
*
* @author Carlos (4/12/2015)
*
* @param deviceId The last three bits in the device's I2C
* address. This would be the last number in
* device's name e.g. for an MCP3021A5 deviceId
* = 5, for an MCP3021A3 deviceId = 3.
*
* @param vdd The output of the power supply used to power the
* converter.
*
* @return float The conversion result from 0 to VDD
*/
float AllAboutEE::MCP3021::read(int deviceId, float vdd)
{
uint16_t result = read(deviceId);
return ((float)result * (vdd / 1023));
}
|
/*
ID: stevenh6
TASK: barn1
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
ofstream fout("barn1.out");
ifstream fin("barn1.in");
int M, S, C;
class Gap
{
public:
int dist, pos;
};
bool comppos(Gap first, Gap second)
{
return first.pos < second.pos;
}
bool compdist(Gap first, Gap second)
{
return first.dist > second.dist;
}
void printgap(Gap item[]) {
for (int i = 0; i < C; i++) {
cout << item[i].pos << " " << item[i].dist << endl;
}
cout << "End list";
}
int main()
{
fin >> M >> S >> C;
if (M > C)
{
fout << C << endl;
}
else
{
Gap doors[C];
for (int i = 0; i < C; i++)
{
fin >> doors[i].pos;
}
sort(doors, doors + C, comppos);
int last = 0;
for (int k = 0; k < C; k++) {
doors[k].dist = doors[k].pos - last;
if (last == 0)
{
doors[k].dist = 0;
}
last = doors[k].pos;
}
printgap(doors);
int range = doors[C - 1].pos - doors[0].pos + 1;
sort(doors, doors + C, compdist);
for (int j = 1; j < M; j++)
{
range -= doors[j - 1].dist - 1;
}
fout << range << endl;
}
return 0;
}
|
#pragma once
#if AE_COMPILER == AE_COMPILER_MSVC
#undef __PRETTY_FUNCTION__
#define __PRETTY_FUNCTION__ __FUNCSIG__
#endif
namespace aeEngineSDK
{
#if AE_COMPILER == AE_COMPILER_MSVC
#pragma warning( push )
#pragma warning(disable : 4275)
#endif
class AE_UTILITY_EXPORT aeException : public std::exception
{
public:
aeException() throw() : std::exception()
{
}
explicit aeException(char const* const _Message) throw() : std::exception(_Message)
{
}
aeException(char const* const _Message, int) throw() : std::exception(_Message,1)
{
}
aeException(aeException const& _Other) throw() : std::exception(_Other)
{
}
virtual ~aeException() throw()
{
}
};
class AE_UTILITY_EXPORT InternalErrorException : public aeException
{
public:
InternalErrorException() throw() : aeException("Internal error exception", 1)
{
}
};
}
#if defined(_DEBUG)
#define AE_EXCEPT(Except,Msg) \
MULTI_LINE_MACRO_BEGIN \
Except(); \
MULTI_LINE_MACRO_END
#else
#define AE_EXCEPT(Except,Msg) MULTI_LINE_MACRO_BEGIN Except(); MULTI_LINE_MACRO_END
#endif
|
#include "world.h"
World::World(btScalar averageFPS,btScalar lowestFPS,btVector3 gravity):mWorld(NULL)
{
initNormal(averageFPS,lowestFPS,gravity);
}
void World::stepDebug()
{
mWorld->stepDebug();
}
void World::initNormal(btScalar averageFPS,btScalar lowestFPS,btVector3& gravity)
{
mWorld = new worldsinglethread(averageFPS, lowestFPS);
mWorld->init(gravity);
}
void World::step(btScalar timeStep)
{
mWorld->step(timeStep);
}
RigidBody* World::addRigidBody(btScalar mass, Ogre::Entity* entity ,int shapeType, int group,int mask,btTransform offset)
{
BtOgre::StaticMeshToShapeConverter converter(entity);
btCollisionShape * mShape = Shapez::setupShape(shapeType,converter);
btVector3 localInertia(0,0,0);
mShape->calculateLocalInertia(mass,localInertia);
Ogre::SceneNode *parentNode = entity->getParentSceneNode();
BtOgre::RigidBodyState *state=NULL;
if(offset==btTransform::getIdentity())
state = new BtOgre::RigidBodyState(parentNode);
else
state = new BtOgre::RigidBodyState(parentNode,nodeToBullet(parentNode),offset);
RigidBody* xBody = new RigidBody(mass,state,mShape,localInertia,group,mask);
collisionShapes.push_back(mShape);
return xBody;
}
btTransform World::nodeToBullet(Ogre::SceneNode* node)
{
btVector3 pos = BtOgre::Convert::toBullet(node->getPosition() );
btQuaternion rot = BtOgre::Convert::toBullet(node->getOrientation());
btTransform trz; trz.setIdentity();
trz.setOrigin(pos*2.0);
trz.setRotation(rot);
return trz;
}
ThirdPersonController* World::addThirdPersonController(int resolutionX, int resolutionY,Ogre::Entity* entity ,int shapeType,int group,int mask, btScalar contactProcessingTreshold
,Ogre::Vector3 posOffset, Ogre::Quaternion rotOffset)
{
btTransform startTransform;
startTransform.setIdentity ();
Ogre::Node* cPrntNode = entity->getParentNode();
const Ogre::Vector3& nodePos = cPrntNode->getPosition();
const Ogre::Quaternion& nodeOrient = cPrntNode->getOrientation();
startTransform.setOrigin (btVector3(nodePos.x, nodePos.y, nodePos.z));
startTransform.setRotation(BtOgre::Convert::toBullet(nodeOrient));
btPairCachingGhostObject* m_ghostObject = new btPairCachingGhostObject();
m_ghostObject->setWorldTransform(startTransform);
mWorld->getWorld()->getPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
BtOgre::StaticMeshToShapeConverter converter(entity);
btConvexShape * mShape = ConvexShapez::setupShape(shapeType,converter);
btVector3 cScale = mShape->getLocalScaling();
m_ghostObject->setCollisionShape (mShape);
m_ghostObject->setCollisionFlags (btCollisionObject::CF_CHARACTER_OBJECT);
btScalar stepHeight = btScalar(0.35);
btKinematicCharacterController* m_character = new btKinematicCharacterController (m_ghostObject,mShape,stepHeight);
mWorld->getWorld()->addCollisionObject(m_ghostObject,group, mask);
mWorld->getWorld()->addAction(m_character);
ThirdPersonController* tpc = new ThirdPersonController(posOffset,rotOffset,m_character,m_ghostObject,cPrntNode,resolutionX
,resolutionY,mWorld->getWorld());
collisionShapes.push_back(mShape);
return tpc;
}
RigidBody* World::addAnimatedRigidBody(btScalar mass, Ogre::Entity* entity ,int shapeType,int group,int mask, btScalar contactProcessingTreshold)
{
BtOgre::AnimatedMeshToShapeConverter converter(entity);
btCollisionShape * mShape = Shapez::setupShapeAnimated(shapeType,converter);
btVector3 localInertia(0,0,0);
mShape->calculateLocalInertia(mass,localInertia);
RigidBodyStateAnimated *state = new RigidBodyStateAnimated(entity->getParentSceneNode());
RigidBody* xBody = new RigidBody(mass,state,mShape,localInertia,group,mask);
xBody->setActivationState(DISABLE_DEACTIVATION);
state->setRigidBody(xBody,shapeType);
state->setEntity(entity);
if(contactProcessingTreshold != 0)
xBody->setContactProcessingThreshold(contactProcessingTreshold);
collisionShapes.push_back(mShape);
return xBody;
}
RigidBody* World::addStaticRigidBody(Ogre::Entity* entity ,int shapeType,int group,int mask, btScalar contactProcessingTreshold)
{
BtOgre::StaticMeshToShapeConverter converter(entity);
btCollisionShape * mShape = Shapez::setupShape(shapeType,converter);
btVector3 localInertia(0,0,0);
BtOgre::RigidBodyState *state = new BtOgre::RigidBodyState(entity->getParentSceneNode());
RigidBody* xBody = new RigidBody(0,state,mShape,localInertia,group,mask);
if(contactProcessingTreshold != 0)
xBody->setContactProcessingThreshold(contactProcessingTreshold);
collisionShapes.push_back(mShape);
return xBody;
}
RigidBody* World::addKinematicRigidBody(Ogre::Entity* entity ,int shapeType,int group,int mask, btScalar contactProcessingTreshold)
{
BtOgre::StaticMeshToShapeConverter converter(entity);
btCollisionShape * mShape = Shapez::setupShape(shapeType,converter);
btVector3 localInertia(0,0,0);
BtOgre::RigidBodyState *state = new BtOgre::RigidBodyState(entity->getParentSceneNode());
RigidBody* xBody = new RigidBody(0,state,mShape,localInertia,group,mask);
xBody->setCollisionFlags( xBody->getCollisionFlags() | btCollisionObject::CF_KINEMATIC_OBJECT);
xBody->setActivationState(DISABLE_DEACTIVATION);
if(contactProcessingTreshold != 0)
xBody->setContactProcessingThreshold(contactProcessingTreshold);
collisionShapes.push_back(mShape);
return xBody;
}
btPoint2PointConstraint* World::addPointToPointConstraint(btRigidBody& rbA,btRigidBody& rbB, const btVector3& pivotInA,const btVector3& pivotInB)
{
btPoint2PointConstraint* constraint= new btPoint2PointConstraint(rbA,rbB,pivotInA,pivotInB);
mWorld->getWorld()->addConstraint(constraint);
return constraint;
}
void World::enableDebugging(Ogre::SceneNode* rootSceneNode)
{
mWorld->enableDebugging(rootSceneNode);
}
btDiscreteDynamicsWorld* World::getWorld()
{
return mWorld->getWorld();
}
World::~World()
{
for (int i=getWorld()->getNumCollisionObjects()-1; i>=0 ;i--)
{
btCollisionObject* obj = getWorld()->getCollisionObjectArray()[i];
btRigidBody* body = btRigidBody::upcast(obj);
btMotionState* motState = NULL;
if(body&&body->getMotionState())
{
motState = body->getMotionState();
delete motState;
motState=NULL;
body->setMotionState(NULL);
}
getWorld()->removeCollisionObject( obj );
delete obj;
}
for(int i=0; i<collisionShapes.size(); i++)
delete collisionShapes[i];
collisionShapes.clear();
delete mWorld;
}
|
#ifndef B_MC_HPP
#define B_MC_HPP
namespace b_mc {
extern char const* mocs_compilation();
}
#endif
|
/**
* Copyright (C) Omar Thor, Aurora Hernandez - All Rights Reserved
* Unauthorized copying of this file, via any medium is strictly prohibited
* Proprietary and confidential
*
* Written by
* Omar Thor <omar@thorigin.com>, 2018
* Aurora Hernandez <aurora@aurorahernandez.com>, 2018
*/
#ifndef DMTK_ELEMENT_OPERATIONS_HPP
#define DMTK_ELEMENT_OPERATIONS_HPP
#include <tuple>
#include <type_traits>
#include <vector>
DMTK_NAMESPACE_BEGIN
/**
* @file Provides for basic arithmetic operations on the pseudo type Element
* The implementation is incomplete and only provides the basic operations used
*/
template<typename T>
void find_min_max_atom(const T& value, T& min, T& max) {
find_min_max_atom(value, min, max, select_atom_tag_t<T>{});
}
template<typename T>
void find_min_max_atom(const T&, T&, T&, skip_atom_tag) {}
template<typename T>
void find_min_max_atom(const T& value, T& min, T& max, arithmetic_atom_tag) {
if(value > max) {
max = value;
}
if(value < min) {
min = value;
}
}
template<typename T>
void find_min_max(const T& value, T& min, T& max) {
find_min_max_atom(value, min, max);
}
namespace detail {
template<typename ... T, size_t ... Indexes>
void find_min_max_tuple(const std::tuple<T...>& value, std::tuple<T...>& min, std::tuple<T...>& max, std::index_sequence<Indexes...>) {
(find_min_max_atom(std::get<Indexes>(value), std::get<Indexes>(min), std::get<Indexes>(max)), ...);
}
template<typename T, typename ... Rest>
void find_min_max_vector(const std::vector<T, Rest...>& value, std::vector<T, Rest...>& min, std::vector<T, Rest...>& max) {
for( auto it = value.begin(), end = value.end(),
min_it = min.begin(), min_end = min.end(),
max_it = max.begin(), max_end = max.end();
it != end && min_it != min_end && max_it != max_end;
++it,
++min_it,
++max_it
) {
find_min_max_atom(*it, *min_it, *max_it);
}
}
}
/**
* find_min_max overload for tuple
*
* @param value
* @param min
* @param max
*/
template<size_t SkipLastN, typename ... T>
void find_min_max(const std::tuple<T...>& value, std::tuple<T...>& min, std::tuple<T...>& max) {
detail::find_min_max_tuple(value, min, max, std::make_index_sequence<sizeof...(T) - SkipLastN>{});
}
template<typename T>
void element_add_atom(T& value, const T& add) {
element_add_atom(value, add, select_atom_tag_t<T>{});
}
template<typename T>
void element_add_atom(T& value, const T& add, arithmetic_atom_tag) {
value += add;
}
template<typename T>
void element_add_atom(T& value, const T& add, skip_atom_tag) {}
namespace detail {
template<typename ...T, size_t ... Indexes>
void element_add_helper(std::tuple<T...>& value, const std::tuple<T...>& add, std::index_sequence<Indexes...>) {
((std::get<Indexes>(value) += std::get<Indexes>(add)), ...);
}
}
template<typename ...T>
void element_add(std::tuple<T...>& value, const std::tuple<T...>& add) {
detail::element_add_helper(value, add, std::make_index_sequence<sizeof...(T)>{});
}
template<typename Container, typename std::enable_if_t<is_container_v<Container>>>
void element_add(const Container& value, Container& add) {
//ensure size of sum container
if(value.size() < value.size()) {
value.resize(add.size());
}
for(auto value_it = std::begin(add),
end = std::end(add),
add_it = add.begin();
value_it != end;
++value_it, ++add_it) {
(*value_it) += *add_it;
}
}
template<typename ...T>
void element_div(std::tuple<T...>& value, const std::tuple<T...>& divider) {
detail::element_add_helper(value, divider, std::index_sequence_for<T...>{});
}
template<typename Container>
void element_div(Container& value, const Container& divider) {
for(auto value_it = std::begin(value),
end = std::end(value),
divider_it = divider.begin();
value_it != end;
++value_it, ++divider_it) {
(*value_it) /= divider_it;
}
}
namespace detail {
template<typename ...T, size_t ... Indexes, typename Divider>
void element_div_helper(std::tuple<T...>& value, const Divider& divider, std::index_sequence<Indexes...>) {
((std::get<Indexes>(value) /= divider), ...);
}
}
template<typename ...T, typename Divider>
void element_div(std::tuple<T...>& value, const Divider& divider) {
detail::element_div_helper(value, divider, std::index_sequence_for<T...>{});
}
template<typename Container, typename Divider>
void element_div(Container& value, const Divider& divider) {
for(auto value_it = std::begin(value),
end = std::end(value);
value_it != end;
++value_it) {
(*value_it) /= divider;
}
}
DMTK_NAMESPACE_END
#endif /* DMTK_ELEMENT_OPERATIONST_HPP */
|
#include <iberbar/Base/Lua/LuaStateRef.h>
iberbar::CLuaStateRef::CLuaStateRef( void )
: m_pLuaState( NULL )
{
}
iberbar::CLuaStateRef::~CLuaStateRef()
{
if ( m_pLuaState )
{
lua_close( m_pLuaState );
m_pLuaState = NULL;
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAXN 100
#define INF 0x3f3f3f3f
#define DEVIATION 0.00000005
int main(int argc, char const *argv[])
{
int kase;
scanf("%d\n",&kase);
char kind;
int m,n;
while( kase-- ){
scanf("%c %d %d\n", &kind, &m, &n);
if( kind == 'r' )
printf("%d\n",min(m,n));
if( kind == 'k')
printf("%d\n",(m*n+1)/2);
if( kind == 'Q' )
printf("%d\n",min(m,n));
if( kind == 'K' )
printf("%d\n",((m+1)/2)*((n+1)/2));
}
return 0;
}
|
#pragma once
#include "../../Toolbox/Toolbox.h"
#include "../Vector/Vector3.h"
namespace ae
{
/// \ingroup math
/// <summary>
/// 3D plane represented by a point (on the plane) and a normal vector.
/// </summary>
class AERO_CORE_EXPORT Plane
{
public:
/// <summary>
/// Plane constructor.
/// </summary>
/// <param name="_Point">Point on the plane.</param>
/// <param name="_Normal">Normal of the plane.</param>
Plane( const Vector3& _Point = Vector3::Zero, const Vector3& _Normal = Vector3::AxeY );
/// <summary>Set the point that define the plane position.</summary>
/// <param name="_Point">The point that define the new plane position.</param>
void SetPoint( const Vector3& _Point );
/// <summary>Retrieve the point on the plane.</summary>
/// <returns>The point on the plane.</returns>
const Vector3& GetPoint() const;
/// <summary>Set the normal of the plane.</summary>
/// <param name="_Normal">The new normal of the plane.</param>
void SetNormal( const Vector3& _Normal );
/// <summary>Retrieve the normal of the plane.</summary>
/// <returns>The normal of the plane.</returns>
const Vector3& GetNormal() const;
/// <summary>Process the shortest distance between <paramref name="_Point"/> and the plane.</summary>
/// <param name="_Point">The point to process the distance between it and the plane.</param>
/// <returns>The shortest distance between the point and the plane.</returns>
float GetDistanceToPlane( const Vector3& _Point ) const;
/// <summary>
/// Process the shortest signed distance between <paramref name="_Point"/> and the plane.<para/>
/// It will be positive if the point is above the plane, negative if it is below.
/// </summary>
/// <param name="_Point">The point to process the distance between it and the plane.</param>
/// <returns>
/// The shortest signed distance between the point and the plane.<para/>
/// It will be positive if the point is above the plane, negative if it is below.
/// </returns>
float GetSignedDistanceToPlane( const Vector3& _Point ) const;
private:
/// <summary>
/// A point on the plane. <para/>
/// It's define the plane position.
/// </summary>
Vector3 m_Point;
/// <summary>
/// Normal of the plane.<para/>
/// It's define the plane orientation.
/// </summary>
Vector3 m_Normal;
};
} // ae
|
// Copyright (c) 2015 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StdObjMgt_ReadData_HeaderFile
#define _StdObjMgt_ReadData_HeaderFile
#include <Standard.hxx>
#include <Storage_BaseDriver.hxx>
#include <NCollection_Array1.hxx>
class StdObjMgt_Persistent;
class Standard_GUID;
//! Auxiliary data used to read persistent objects from a file.
class StdObjMgt_ReadData
{
public:
//! Auxiliary class used to automate begin and end of
//! reading object (eating opening and closing parenthesis)
//! at constructor and destructor
class ObjectSentry
{
public:
explicit ObjectSentry (StdObjMgt_ReadData& theData) : myReadData (&theData)
{ myReadData->myDriver->BeginReadObjectData(); }
~ObjectSentry ()
{ myReadData->myDriver->EndReadObjectData(); }
private:
StdObjMgt_ReadData* myReadData;
ObjectSentry (const ObjectSentry&);
ObjectSentry& operator = (const ObjectSentry&);
};
Standard_EXPORT StdObjMgt_ReadData
(const Handle(Storage_BaseDriver)& theDriver, const Standard_Integer theNumberOfObjects);
template <class Instantiator>
void CreatePersistentObject
(const Standard_Integer theRef, Instantiator theInstantiator)
{ myPersistentObjects (theRef) = theInstantiator(); }
Standard_EXPORT void ReadPersistentObject
(const Standard_Integer theRef);
Handle(StdObjMgt_Persistent) PersistentObject
(const Standard_Integer theRef) const
{ return myPersistentObjects (theRef); }
Standard_EXPORT Handle(StdObjMgt_Persistent) ReadReference();
template <class Persistent>
StdObjMgt_ReadData& operator >> (Handle(Persistent)& theTarget)
{
theTarget = Handle(Persistent)::DownCast (ReadReference());
return *this;
}
StdObjMgt_ReadData& operator >> (Handle(StdObjMgt_Persistent)& theTarget)
{
theTarget = ReadReference();
return *this;
}
template <class Type>
StdObjMgt_ReadData& ReadValue (Type& theValue)
{
*myDriver >> theValue;
return *this;
}
StdObjMgt_ReadData& operator >> (Standard_Character& theValue)
{ return ReadValue (theValue); }
StdObjMgt_ReadData& operator >> (Standard_ExtCharacter& theValue)
{ return ReadValue (theValue); }
StdObjMgt_ReadData& operator >> (Standard_Integer& theValue)
{ return ReadValue (theValue); }
StdObjMgt_ReadData& operator >> (Standard_Boolean& theValue)
{ return ReadValue (theValue); }
StdObjMgt_ReadData& operator >> (Standard_Real& theValue)
{ return ReadValue (theValue); }
StdObjMgt_ReadData& operator >> (Standard_ShortReal& theValue)
{ return ReadValue (theValue); }
private:
Handle(Storage_BaseDriver) myDriver;
NCollection_Array1<Handle(StdObjMgt_Persistent)> myPersistentObjects;
};
Standard_EXPORT StdObjMgt_ReadData& operator >>
(StdObjMgt_ReadData& theReadData, Standard_GUID& theGUID);
#endif // _StdObjMgt_ReadData_HeaderFile
|
#include <iostream>
#include <vector>
#include <cmath>
int main()
{
long long int number = 600851475143LL;
long long int highestPrimeFactor = 0LL;
long long int currentFactor = 2LL;
while (number > highestPrimeFactor)
{
if (
(number % currentFactor == 0) &&
(currentFactor > highestPrimeFactor)
) // If the number we are on is a factor of the number and larger than previous factors
{
highestPrimeFactor = currentFactor;
number /= currentFactor; // Make the number smaller, so it is easier to work with
}
else
{
++currentFactor; // Increase the factor
}
}
std::cout << highestPrimeFactor << "\n";
}
|
๏ปฟ#pragma once
#include <memory>
#include <QVector>
#include <QPointF>
#include "item/item.h"
using std::unique_ptr;
class broken_line : public item
{
Q_OBJECT
public:
static std::unique_ptr<broken_line> make (json data, QPointF pos, item* parent);
QRectF boundingRect () const override;
void paint (QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) override;
QPainterPath shape () const override;
private:
broken_line (QVector<QPointF> points);
broken_line (json data, QPointF pos, item* parent = nullptr);
bool init ();
QVector<QPointF> points_;
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#include "modules/scope/src/scope_transport.h"
#include "adjunct/desktop_scope/src/scope_desktop_utils.h"
#include "adjunct/desktop_pi/DesktopOpSystemInfo.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/locale/locale-enum.h"
/* OpScopeDesktopUtils */
OpScopeDesktopUtils::OpScopeDesktopUtils()
{
}
/* virtual */
OpScopeDesktopUtils::~OpScopeDesktopUtils()
{
}
OP_STATUS OpScopeDesktopUtils::DoGetString(const DesktopStringID &in, DesktopStringText &out)
{
// Calculate the enum using the hash
int enum_value = Str::LocaleString(in.GetEnumText().CStr());
OpString text_string;
g_languageManager->GetString((Str::LocaleString)enum_value, text_string);
if (text_string.IsEmpty())
return SetCommandError(OpScopeTPHeader::InternalError, UNI_L("String not found"));
RETURN_IF_ERROR(out.SetText(text_string.CStr()));
return OpStatus::OK;
}
OP_STATUS OpScopeDesktopUtils::DoGetOperaPath(DesktopPath &out)
{
OpString exec_path;
if (OpStatus::IsError(g_op_system_info->GetBinaryPath(&exec_path)) || exec_path.IsEmpty())
return SetCommandError(OpScopeTPHeader::InternalError, UNI_L("Exec path not found"));
RETURN_IF_ERROR(out.SetPath(exec_path.CStr()));
return OpStatus::OK;
}
OP_STATUS OpScopeDesktopUtils::DoGetLargePreferencesPath(DesktopPath &out)
{
OpString home_path;
RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_LOCAL_HOME_FOLDER, home_path));
return out.SetPath(home_path.CStr());
}
OP_STATUS OpScopeDesktopUtils::DoGetSmallPreferencesPath(DesktopPath &out)
{
OpString home_path;
RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_HOME_FOLDER, home_path));
return out.SetPath(home_path.CStr());
}
OP_STATUS OpScopeDesktopUtils::DoGetCachePreferencesPath(DesktopPath &out)
{
OpString home_path;
RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_CACHE_HOME_FOLDER, home_path));
return out.SetPath(home_path.CStr());
}
OP_STATUS OpScopeDesktopUtils::DoGetCurrentProcessId(DesktopPid &out)
{
out.SetPid(g_op_system_info->GetCurrentProcessId());
return OpStatus::OK;
}
|
////////////////////////////////////////////////////////////////////////////////
#include "delaunay.h"
#include <geogram/mesh/mesh.h>
#include <geogram/delaunay/delaunay.h>
#include <igl/adjacency_matrix.h>
#include <igl/sum.h>
#include <igl/diag.h>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
// -----------------------------------------------------------------------------
void laplace_energy(const Eigen::MatrixXd &V, const Eigen::MatrixXi &F, Eigen::VectorXd &E){
assert(V.cols() == 2 || V.cols() == 3);
assert(F.cols() == 3);
int n = (int)V.rows();
// Compute the uniform laplacian
Eigen::SparseMatrix<double> A;
igl::adjacency_matrix(F, A);
// sum each row
Eigen::SparseVector<double> Asum;
igl::sum(A, 1, Asum);
// Convert row sums into diagonal of sparse matrix
Eigen::SparseMatrix<double> Adiag;
igl::diag(Asum, Adiag);
// Build uniform laplacian
Eigen::SparseMatrix<double> L;
L = A - Adiag;
{
Eigen::VectorXd Ex = L * V.col(0);
Eigen::VectorXd Ey = L * V.col(1);
E = Ex.array().abs() + Ey.array().abs();
}
double Emean = E.array().mean();
// Normalize Laplacian Energy from 0 to 2 * average, and set everything above to 1
Eigen::VectorXd Enorm = Eigen::VectorXd::Zero(n);
for (size_t i = 0; i < n; i++)
{
if (E(i) < (2 * Emean))
Enorm(i) = E(i) / (2 * Emean);
else
Enorm(i) = 1;
}
E = Enorm;
}
// -----------------------------------------------------------------------------
} // namespace cellogram
|
#ifndef COUNTERWIDGET_HPP_
#define COUNTERWIDGET_HPP_
#include <QWidget>
#include <QTimer>
#include <QtCharts>
#include "LogModel.hpp"
#include "PlayerStatsModel.hpp"
#include "GameStatsModel.hpp"
namespace Ui {
class CounterWidget;
}
/**
A widget with a treeview to display and manipulate a LogModel.
*/
class CounterWidget : public QWidget {
Q_OBJECT
Ui::CounterWidget* form_;
LogModel* model_;
PlayerStatsModel playerStats_;
GameStatsModel gameStats_;
QString filename_;
QChart playerValueChart_;
/**
order to not spam the disk with saving after every single little change,
every single little change starts/resets the timer (single-shot), and
only when the timer event is triggert the game will be saved.
*/
QTimer saveDelayTimer_;
void setModel(LogModel* model, const QString& filename);
public:
CounterWidget(QWidget* parent = nullptr);
~CounterWidget();
public slots:
void playerNameChanged();
void playerCountChanged();
void displayCumSumChanged();
void newGame();
void loadGame();
void save();
void delayedSave();
void updateStatistics();
void changeFont();
};
#endif /* include guard: COUNTERWIDGET_HPP_ */
|
/**
* Project: ows-qt-console
* File name: main_window.h
* Description: this header describes the program's main window
*
* @author Mathieu Grzybek on 2012-04-30
* @copyright 2012 Mathieu Grzybek. All rights reserved.
* @version $Id: code-gpl-license.txt,v 1.2 2004/05/04 13:19:30 garry Exp $
*
* @see The GNU Public License (GPL) version 3 or higher
*
*
* ows-qt-console 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.
*
* This program 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 this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MAIN_WINDOW_H
#define MAIN_WINDOW_H
#include <QMainWindow>
#include <QSettings>
#include <QErrorMessage>
#include <QTreeWidgetItem>
#include <QDateTime>
#include "convertions.h"
#include "connect.h"
#include "domains_manager.h"
#include "edit_node_dialog.h"
#include "edit_job_dialog.h"
#include "rpc_client.h"
namespace Ui {
class Main_Window;
}
class Connect;
class Main_Window : public QMainWindow
{
Q_OBJECT
public:
explicit Main_Window(QWidget *parent = 0);
~Main_Window();
QStandardItemModel servers_model;
QStandardItemModel template_jobs_model;
QStandardItemModel current_jobs_model;
QStandardItemModel nodes_model;
// bool rpc_connect(const QString& hostname, const int& port, const QString& username, const QString& password);
private slots:
void on_actionManage_triggered();
void on_actionConnect_triggered();
void on_actionDisconnect_triggered();
void on_nodes_tree_doubleClicked(const QModelIndex &index);
void on_add_template_job_button_clicked();
void on_add_current_job_button_clicked();
void on_add_template_node_button_clicked();
void on_get_current_nodes_button_clicked();
void on_get_template_nodes_button_clicked();
private:
/*
* Windows
*/
Ui::Main_Window* ui;
Domains_Manager* dm_dialog;
Connect* connect_dialog;
/*
* Settings objects
*
* QSettings::QSettings ( Scope scope, const QString & organization, const QString & application = QString(), QObject * parent = 0 )
*/
QSettings settings;
char* config_file;
/*
* RPC objects
*/
Rpc_Client* rpc_client;
rpc::t_node local_node;
rpc::t_node remote_node;
rpc::t_routing_data routing;
std::string current_planning_name;
void load_settings();
void save_settings();
/*
* RPC methods
*/
bool populate_domain_models();
void insert_nodes_model(const rpc::t_node& n);
bool populate_jobs_models(const rpc::v_jobs* template_jobs, const rpc::v_jobs* current_jobs);
/*
* Models
*/
void prepare_models();
void prepare_jobs_model();
void prepare_nodes_model();
};
#endif // MAIN_WINDOW_H
|
#include "StaticGameObject.h"
StaticGameObject::StaticGameObject(SDL_Rect *r, SDL_Surface *s,double x,double y,double a):GameObject(r,s)
{
worldX = x;
worldY = y;
angle = a;
//collisionRadius = (rect->w + rect->h)/2/2;
}
double StaticGameObject::getWorldX()
{
return worldX;
}
double StaticGameObject::getWorldY()
{
return worldY;
}
double StaticGameObject::getAngle()
{
return angle;
}
void StaticGameObject::setWorldX(double x)
{
worldX = x;
}
void StaticGameObject::setWorldY(double y)
{
worldY = y;
}
void StaticGameObject::rotate(double a)
{
angle += a;
}
|
#include <string.h>
const unsigned int line1Y = 5;
const unsigned int line2Y = 20;
const unsigned int col1X = 5;
const unsigned int col2X = 20;
const unsigned int col3X = 85;
const unsigned int wordSize = 8;
const unsigned int blinkPeriod = 600;
static enum State{
mainMenu = 0,
playerMove = 1,
movingMotors = 2,
doneUI = 3
} displayState = mainMenu;
struct button{
int pin;
bool state;
bool prevState;
};
struct button Ubutton={UbuttonPin,false,false};
void changeUIState(int n){
//resets the button states just in case they were down when the state was previously changed
Ubutton.state = false;
Ubutton.prevState = false;
switch (n){
case 0:
displayState = mainMenu;
break;
case 1:
displayState = playerMove;
break;
case 2:
displayState = movingMotors;
break;
}
}
bool UIUpdate(){
flushBuffer(); //clears the serial buffer as it messes up the OLED
switch (displayState){
case mainMenu:
updateMainMenu();
break;
case playerMove:
updateMoveSelect();
break;
case movingMotors:
movingMotorsDisplay();
break;
case doneUI:
return true;
}
Ubutton.prevState = Ubutton.state;
Ubutton.state = digitalRead(Ubutton.pin);
OrbitOledUpdate();
return false;
}
void updateMainMenu(){
char txt[] = "Press BTN2";
int n = sizeof(txt)/sizeof(txt[0]);
OrbitOledMoveTo(col1X,line1Y);
OrbitOledDrawString("Checkersbot9000");
OrbitOledMoveTo(col2X,line2Y);
OrbitOledDrawString("Press BTN 2");
if(!Ubutton.state && Ubutton.prevState){ //once the button is pressed changes the state
displayState = playerMove;
OrbitOledClear();
OrbitOledClearBuffer();
OrbitOledInit();
Ubutton.prevState = false;
delay(100);
}
}
void updateMoveSelect(){
OrbitOledMoveTo(col1X, line1Y);
OrbitOledDrawString("Press B2 to");
OrbitOledMoveTo(col1X, line2Y);
OrbitOledDrawString("end your turn");
if(Ubutton.state == false && Ubutton.prevState == true){ //if one of the buttons has been pressed down
displayState = movingMotors;
Ubutton.prevState = false; //sets it back to on
OrbitOledClear();
OrbitOledClearBuffer();
OrbitOledInit();
}
}
void movingMotorsDisplay(){
OrbitOledMoveTo(col1X, line1Y);
OrbitOledDrawString("It's My Turn");
OrbitOledMoveTo(col2X,line2Y);
OrbitOledDrawString("Now");
displayState = doneUI;
}
|
#pragma once
class AI_CarrierReleaseEnemies : public hg::IAction
{
public:
void LoadFromXML( tinyxml2::XMLElement* data );
void Init( hg::Entity* entity ) override;
hg::IBehavior::Result Update( hg::Entity* entity ) override;
hg::IBehavior* MakeCopy() const;
private:
float m_Timer;
float m_Duration;
uint32_t m_CurrRow;
static const int kRows = 3;
static const int kCols = 4;
hg::Entity* m_Enemies[kRows * kCols];
hg::Transform* m_Carrier;
};
|
#pragma once
#ifndef __SURVEY_H__
#define __SURVEY_H__
#include <cmath>
#include <iomanip>
#include <Windows.h>
#include "GamingStudent.h"
class Survey
{
private:
int numOfStudents; // This will hold the amount of students in the survey
// Non-gamer related variables
int numOfNonGamers; // This will hold the amount of non-gaming students in the survey
int favouriteServicePos[14]; // This will hold the amount of students that prefer a specific streaming service
double averageAgeNonGamer; // This will hold the average age of the non gaming students
double averageHoursEntertainment; // This will hold the average amount of hours spent consuming non-gaming entertainment
std::string favouriteService; // This will hold the name of the streaming service that was the most popular
// Gamer related variables
int numOfGamers; // This will hold the amount of gaming students in the survey
int favouriteDevicePos[8]; // This will hold the amount of students that prefer a specific console
double averageAgeGamer; // This will hold the average age of the gaming students
double averageHoursGaming; // This will hold the average amount of hours spent gaming
std::string favouriteDevice; // This will hold the name of the console that was the most popular
Person** participants;
public:
Survey(int participants);
void addParticipant(int spot, Student* student);
void processData();
// getters
int getNumOfStudents();
int getNumOfNonGamers();
int getFavouriteServicePos();
double getAverageAgeNonGamer();
double getAverageHoursEntertainment();
std::string getFavouriteService();
int getNumOfGamers();
int getFavouriteDevicePos();
double getAverageAgeGamer();
double getAverageHoursGaming();
std::string getFavouriteDevice();
std::string getName(int spot);
Student* getStudent(int spot);
// Overloaded cout operator
friend std::ostream& operator<<(std::ostream& out, Survey survey);
};
#endif
|
/**
* The n-queens puzzle is the problem of placing n queens on
* an nยกรn chessboard such that no two queens attack each other.
*
* Given an integer n, return all distinct solutions
* to the n-queens puzzle.
*
* Each solution contains a distinct board configuration of the
* n-queens' placement, where 'Q' and '.' both indicate a queen
* and an empty space respectively.
*
* For example,
* There exist two distinct solutions to the 4-queens puzzle:
*
* [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
*
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
*/
class Solution {
vector<string> generate(vector<int> &placement) {
int N = placement.size();
vector<string> ret;
for (int i = 0; i < N; i++) {
string s;
for (int j = 0; j < N; j++) {
s += (placement[i] == j) ? 'Q' : '.';
}
ret.push_back(s);
}
return ret;
}
bool valid(vector<int> &placement, int row, int col) {
for (int i = 0; i < row; i++) {
int j = placement[i];
if (j == col || i - row == j - col || i - row == col - j) {
return false;
}
}
return true;
}
void solve(vector<vector<string> > &ret, vector<int> &placement, int cur_row, const int N) {
if (cur_row == N) {
ret.push_back(generate(placement));
return;
}
for (int col = 0; col < N; col++) {
if (valid(placement, cur_row, col)) {
placement[cur_row] = col;
solve(ret, placement, cur_row + 1, N);
}
}
}
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > ret;
if (n <= 0) {
return ret;
}
vector<int> placement(n);
solve(ret, placement, 0, n);
return ret;
}
};
|
// $Id$
//
// (C) Copyright Mateusz Loskot 2008, mateusz@loskot.net
// Distributed under the BSD License
// (See accompanying file LICENSE.txt or copy at
// http://www.opensource.org/licenses/bsd-license.php)
//
#if defined(_MSC_VER) && defined(USE_VLD)
#include <vld.h>
#endif
// liblas
#include <liblas/liblas.hpp>
#include <liblas/laspoint.hpp>
#include <liblas/lasfile.hpp>
//std
#include <algorithm>
#include <exception>
#include <list>
#include <iostream>
#include <cassert>
// Reports object of LASFile
void print_file(liblas::LASFile& f)
{
if (f.IsNull())
{
std::cout << "{ null file }\n";
}
else
{
std::cout << "{ name: " << f.GetName() << "; mode: " << f.GetMode() << "; signature: ";
if (f.GetMode() == liblas::LASFile::eRead)
std::cout << f.GetReader().GetHeader().GetFileSignature();
else
std::cout << f.GetWriter().GetHeader().GetFileSignature();
std::cout << " }\n";
}
}
int main()
{
using liblas::LASFile;
try
{
{
LASFile f;
{
LASFile f0;
LASFile f1("test2.las", liblas::LASHeader(), liblas::LASFile::eWrite);
LASFile f2("test.las"); // throws if file missing
std::list<LASFile> files;
files.push_back(f0);
files.push_back(f1);
files.push_back(f2);
std::for_each(files.begin(), files.end(), print_file);
f = f1; // save
liblas::LASPoint p;
p.SetCoordinates(10, 20, 30);
f.GetWriter().WritePoint(p);
files.clear(); // get rid of all but f1 (now f)
}
print_file(f); // f (previously f1) is still alive
} // f goes to hell and header gots updated here
}
catch (std::exception const& e)
{
std::cout << "Error: " << e.what() << std::endl;
}
catch (...)
{
std::cerr << "Unknown error\n";
}
return 0;
}
|
#pragma once
#include <Component.h>
#include <OGLML/Sprite.h>
namespace breakout
{
class SpriteComponent : public BaseComponent
{
public:
static EComponentType GetType()
{
return EComponentType::Sprite;
};
SpriteComponent();
~SpriteComponent();
oglml::Sprite& Sprite();
private:
oglml::Sprite m_sprite;
};
}
|
#pragma once
#include "GnSignal.h"
#include "GcPropertyGridProperty.h"
class GcPropertyGridCtrl : public CMFCPropertyGridCtrl
{
DECLARE_DYNAMIC(GcPropertyGridCtrl)
public:
GcPropertyGridCtrl();
virtual ~GcPropertyGridCtrl();
public:
virtual int OnDrawProperty(CDC* pDC, CMFCPropertyGridProperty* pProp) const;
virtual BOOL EditItem(CMFCPropertyGridProperty* pProp, LPPOINT lptClick = NULL);
virtual BOOL RemoveProperty(CMFCPropertyGridProperty*& pProp, BOOL bRedraw = true, BOOL bAdjustLayout = true);
protected:
DECLARE_MESSAGE_MAP();
public:
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
};
|
/***********************************************/
/*************** IPv6 Server ******************/
/***********************************************/
#include "winsock2.h"
#include "iostream.h"
#include "ws2tcpip.h"
#include "tpipv6.h"
#pragma comment(lib,"WS2_32.lib")
//
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define DEFAULT_FAMILY PF_UNSPEC
#define DEFAULT_SOCKTYPE SOCK_STREAM //TCP
#define DEFAULT_PORT "5001"
#define BUFFER_SIZE 4
int main(int argc, char **argv)
{
char Buffer[BUFFER_SIZE];
int Family = DEFAULT_FAMILY;
int SocketType = DEFAULT_SOCKTYPE;
char *Port = DEFAULT_PORT;
char *Address = NULL;
int i, NumSocks, RetVal, FromLen, AmountRead;
SOCKADDR_STORAGE From;
WSADATA wsaData;
ADDRINFO Hints, *AddrInfo, *AI;
SOCKET ServSock[FD_SETSIZE];
fd_set SockSet;
//ๅ ่ฝฝwinsockๅบ๏ผๅๅงๅ
if ((RetVal = WSAStartup(MAKEWORD(2, 2), &wsaData)) != 0)
{
cout<<"WSAStartup error";
WSACleanup();
return -1;
}
//ๆๆฌๅฐๅฐๅไฟกๆฏ่ต็ปAddrInfo
memset(&Hints, 0, sizeof(Hints));
Hints.ai_family = Family;
Hints.ai_socktype = SocketType;
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
RetVal = getaddrinfo(Address, Port, &Hints, &AddrInfo);
if (RetVal != 0)
{
cout<<"getaddrinfo error";
WSACleanup();
return -1;
}
//ๅฏนๆฏไธช่ฟๅ็ๅฐๅๅๅปบไธไธชๅฅๆฅๅญ๏ผๅนถ็ปๅฎ
for (i = 0, AI = AddrInfo; AI != NULL; AI = AI->ai_next, i++)
{
if (i == FD_SETSIZE)
{
cout<<"getaddrinfo returned more addresses than we could use.\n";
break;
}
if ((AI->ai_family != PF_INET) && (AI->ai_family != PF_INET6))
continue;
//ๅๅปบๅฅๆฅๅญ
ServSock[i] = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
if (ServSock[i] == INVALID_SOCKET)
{
cout<<"socket error";
continue;
}
//bind
if (bind(ServSock[i], AI->ai_addr, AI->ai_addrlen) == SOCKET_ERROR)
{
cout<<"bind error";
continue;
}
//listen
if (listen(ServSock[i], 2) == SOCKET_ERROR)
{
cout<<"listen error";
continue;
}
printf("'Listening' on port %s, protocol %s, protocol family %s\n",
Port, (SocketType == SOCK_STREAM) ? "TCP" : "UDP",
(AI->ai_family == PF_INET) ? "PF_INET" : "PF_INET6");
}
freeaddrinfo(AddrInfo);
NumSocks = i;
//
FD_ZERO(&SockSet);
while(1)
{
FromLen = sizeof(From);
for (i = 0; i < NumSocks; i++)
{
if (FD_ISSET(ServSock[i], &SockSet))
break;
}
if (i == NumSocks)
{
for (i = 0; i < NumSocks; i++)
FD_SET(ServSock[i], &SockSet);
if (select(NumSocks, &SockSet, 0, 0, 0) == SOCKET_ERROR)
{
cout<<"select() fail";
WSACleanup();
return -1;
}
}//ๆญคๆถSockSetไธญไธบๅฏ่ฏป็ๅฅๆฅๅญ็ป
for (i = 0; i < NumSocks; i++)
{
if (FD_ISSET(ServSock[i], &SockSet))
{
FD_CLR(ServSock[i], &SockSet);
break;
}
}
SOCKET ConnSock;
//accept
ConnSock = accept(ServSock[i], (LPSOCKADDR)&From, &FromLen);
if (ConnSock == INVALID_SOCKET)
{
cout<<"accept error";
WSACleanup();
return -1;
}
/*
if (getnameinfo((LPSOCKADDR)&From, FromLen, Hostname,
sizeof(Hostname), NULL, 0, NI_NUMERICHOST) != 0)
strcpy(Hostname, "<unknown>");
printf("\nAccepted connection from %s\n", Hostname);
*/
while (1)
{
AmountRead = recv(ConnSock, Buffer, 4, 0);
if (AmountRead == SOCKET_ERROR)
{
cout<<"receive error";
closesocket(ConnSock);
break;
}
if (AmountRead == 0)
{
cout<<"Client closed connection\n";
closesocket(ConnSock);
break;
}
for(int j=0;j<=3;j++)
{
printf("%c",(Buffer[j]));
}
}
}
return 0;
}
|
#include "utils/time_utils.hpp"
#include "utils/service_thread.hpp"
#include <cppunit/extensions/HelperMacros.h>
#include <atomic>
#include <thread>
using namespace std;
namespace nora {
namespace test {
class time_utils_test : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(time_utils_test);
CPPUNIT_TEST(test);
CPPUNIT_TEST_SUITE_END();
public:
void test();
void time_part_test();
};
CPPUNIT_TEST_SUITE_REGISTRATION(time_utils_test);
void time_utils_test::test() {
atomic<int> done_num{0};
vector<shared_ptr<service_thread>> sts;
for (int i = 0; i < 8; ++i) {
sts.push_back(make_shared<service_thread>("time_utils"));
}
for_each(sts.begin(), sts.end(), [] (const auto& st) {
st->start();
});
for_each(sts.begin(), sts.end(), [&done_num] (const auto& st){
st->async_call(
[&done_num] {
for (int i = 0; i < 3000; ++i) {
clock::instance().now_time_str();
}
done_num++;
});
});
while (done_num.load() < 8) {
continue;
}
for_each(sts.begin(), sts.end(),
[] (auto& st) {
st->stop();
});
sts.clear();
}
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) Opera Software ASA 1995 - 2006
*/
#include "core/pch.h"
#include "modules/regexp/include/regexp_api.h"
#include "modules/regexp/include/regexp_advanced_api.h"
#include "modules/regexp/src/regexp_private.h"
OP_STATUS
OpRegExp::CreateRegExp( OpRegExp **re, const uni_char *pattern, OpREFlags *inflags )
{
RegExp *regex = OP_NEW(RegExp, ());
if (regex == NULL)
return OpStatus::ERR_NO_MEMORY;
RegExpFlags flags;
flags.ignore_case = inflags->case_insensitive ? YES : NO;
flags.multi_line = inflags->multi_line ? YES : NO;
flags.ignore_whitespace = inflags->ignore_whitespace;
OP_STATUS res = regex->Init(pattern, uni_strlen(pattern), NULL, &flags);
if (OpStatus::IsMemoryError(res))
{
regex->DecRef();
return res;
}
if (OpStatus::IsError(res))
{
regex->DecRef();
return OpStatus::ERR;
}
*re = OP_NEW(OpRegExp, (regex));
if (*re == NULL)
{
regex->DecRef();
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
OpRegExp::OpRegExp(RegExp *regex)
: regex(regex)
{
}
OpRegExp::~OpRegExp()
{
if (regex)
regex->DecRef();
regex = NULL;
}
OP_STATUS
OpRegExp::Match( const uni_char *string, OpREMatchLoc *match )
{
RegExpMatch* matchlocs;
int OP_MEMORY_VAR nmatches = 0;
OP_STATUS res = OpStatus::OK;
TRAP( res, nmatches = regex->ExecL(string, uni_strlen(string), 0, &matchlocs));
if (OpStatus::IsError(res))
return res;
if (nmatches == 0)
{
match->matchloc = (unsigned int)-1;
match->matchlen = (unsigned int)-1;
}
else
{
match->matchloc = matchlocs[0].start;
match->matchlen = matchlocs[0].length;
}
return OpStatus::OK;
}
OP_STATUS
OpRegExp::Match( const uni_char *string, int *nmatches, OpREMatchLoc **matches )
{
RegExpMatch* matchlocs;
OP_STATUS res;
int i;
BOOL matched = FALSE;
TRAP( res, matched = regex->ExecL(string, uni_strlen(string), 0, &matchlocs));
if (OpStatus::IsError(res))
return res;
if (!matched)
{
*nmatches = 0;
*matches = NULL;
return OpStatus::OK;
}
*nmatches = regex->GetNumberOfCaptures() + 1;
*matches = OP_NEWA(OpREMatchLoc, *nmatches);
if (*matches == NULL)
return OpStatus::ERR_NO_MEMORY;
for ( i=0 ; i < *nmatches ; i++ )
{
(*matches)[i].matchloc = matchlocs[i].start;
(*matches)[i].matchlen = matchlocs[i].length;
}
return OpStatus::OK;
}
|
#include <reactor/base/SimpleLogger.h>
#include <reactor/net/EventLoop.h>
using namespace reactor;
using namespace reactor::base;
using namespace reactor::net;
void f1() {
LOG(Info) << "f1";
}
void f2() {
LOG(Info) << "f2";
}
void f3() {
LOG(Info) << "f3";
}
int main() {
EventLoop loop;
loop.run_after(1, f1);
loop.run_at(Timestamp::current().add_seconds(2), f2);
loop.run_every(2, f3);
loop.loop();
}
|
#ifndef SHOC_UTIL_H
#define SHOC_UTIL_H
#include "utl/bit.h"
#include "utl/str.h"
namespace shoc {
/**
* @brief Alias for underlying byte type.
*
*/
using byte = uint8_t;
/**
* @brief Input (const) span.
*
* @tparam N Size
* @tparam T Type
*/
template<size_t N = std::dynamic_extent, class T = byte>
using span_i = std::span<const T, N>;
/**
* @brief Output (non-const) span.
*
* @tparam N Size
* @tparam T Type
*/
template<size_t N = std::dynamic_extent, class T = byte>
using span_o = std::span<T, N>;
/**
* @brief Wrapper for swap function.
*
* @param x
* @param y
*/
constexpr void swap(auto &x, auto &y)
{
std::swap(x, y);
}
/**
* @brief Rotate bits of an integer to left.
*
* @param x Integer to rotate
* @param s Shift
* @return Result
*/
constexpr auto rol(auto x, int s)
{
return std::rotl(x, s);
}
/**
* @brief Rotate bits of an integer to right.
*
* @param x Integer to rotate
* @param s Shift
* @return Result
*/
constexpr auto ror(auto x, int s)
{
return std::rotr(x, s);
}
/**
* @brief Check if platform little endian.
*
* @return true if little endian
*/
constexpr bool little_endian()
{
return std::endian::native == std::endian::little;
}
/**
* @brief Copy from one memory region to another.
*
* @param dst Destination
* @param src Source
* @param cnt Number of bytes
*/
constexpr void copy(void* dst, const void *src, size_t cnt)
{
std::copy(static_cast<const byte*>(src), static_cast<const byte*>(src) + cnt, static_cast<byte*>(dst));
}
/**
* @brief Fill memory with given byte value.
*
* @param dst Memory to fill
* @param val Byte value
* @param cnt Number of bytes
*/
constexpr void fill(void* dst, byte val, size_t cnt)
{
std::fill_n(static_cast<byte*>(dst), cnt, val);
}
/**
* @brief Reliably zero out memory region.
*
* @param dst Memory to zero out
* @param cnt Number of bytes
*/
constexpr void zero(void* dst, size_t cnt)
{
// if (std::is_constant_evaluated()) {
// std::fill_n(static_cast<byte*>(dst), cnt, 0);
// } else {
std::fill_n(static_cast<volatile byte*>(dst), cnt, 0);
// }
}
/**
* @brief XOR block of bytes with another. Arrays must be of equal
* length and valid pointers!
*
* @param x Destination array
* @param y Another array
* @param len Length of a block in bytes, default if 16
*/
constexpr void xorb(byte *x, const byte *y, size_t len = 16)
{
for (size_t i = 0; i < len; ++i)
x[i] ^= y[i];
}
/**
* @brief Reverse bits in the given integer.
*
* @tparam T Integer type
* @param x Integer to reverse
* @return Result
*/
template<class T>
constexpr T bitswap(T x)
{
auto bits = sizeof(T) * 8;
auto mask = ~T(0);
while (bits >>= 1) {
mask ^= mask << bits;
x = (x & ~mask) >> bits | (x & mask) << bits;
}
return x;
}
/**
* @brief Reverse bytes in the given integer.
*
* @tparam T Integer type
* @param x Integer to reverse
* @return Result
*/
template<class T>
constexpr T byteswap(T x)
{
return 0; // TODO
}
/**
* @brief Put integer into array in little endian order.
*
* @tparam T Integer type
* @param val Input integer
* @param out Output array
*/
template<class T>
constexpr void putle(T val, byte *out)
{
for (int i = 0; i < sizeof(T) * 8; i += 8)
*out++ = val >> i;
}
/**
* @brief Put integer into array in big endian order.
*
* @tparam T Integer type
* @param val Input integer
* @param out Output array
*/
template<class T>
constexpr void putbe(T val, byte *out)
{
for (int i = sizeof(T) * 8 - 8; i >= 0; i -= 8)
*out++ = val >> i;
}
/**
* @brief Choose function, used in SHA and MD.
*/
template <class T>
constexpr T ch(T x, T y, T z)
{
return (x & y) ^ (~x & z);
}
/**
* @brief Major function, used in SHA and MD.
*/
template <class T>
constexpr T maj(T x, T y, T z)
{
return (x & y) ^ (x & z) ^ (y & z);
}
/**
* @brief Parity function, used in SHA and MD.
*/
template <class T>
constexpr T parity(T x, T y, T z)
{
return x ^ y ^ z;
}
/**
* @brief Increment counter bytes in a block, used in block-cipher mode
* such as CTR and GCM.
*
* @tparam L Length of counter in bytes, default is 4
* @tparam B Total block length in bytes, default is 16
* @param block Pointer to the beginning of a block, not counter
*/
template<size_t L = 4, size_t B = 16>
constexpr void incc(byte *block)
{
size_t i = B;
while (++block[--i] == 0 && i >= B - L);
}
template<class H>
struct Eater {
void operator()(const void *in, size_t len, byte *out)
{
auto &impl = static_cast<H&>(*this);
impl.init();
impl.feed(in, len);
impl.stop(out);
}
private:
friend H;
};
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-file-style: "stroustrup" -*-
**
** Copyright (C) 1995-2003 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef OPELEMENTCALLBACK_SUPPORT
#include "modules/logdoc/opelementcallback.h"
#include "modules/logdoc/src/xmlsupport.h"
#include "modules/logdoc/logdoc.h"
/* static */ OP_STATUS
OpElementCallback::MakeTokenHandler(XMLTokenHandler *&tokenhandler, LogicalDocument *logdoc, OpElementCallback *callback)
{
tokenhandler = OP_NEW(LogdocXMLTokenHandler, (logdoc));
if (!tokenhandler)
return OpStatus::ERR_NO_MEMORY;
((LogdocXMLTokenHandler *) tokenhandler)->SetElementCallback(callback);
return OpStatus::OK;
}
/* virtual */
OpElementCallback::~OpElementCallback()
{
}
#endif // OPELEMENTCALLBACK_SUPPORT
|
/*
* @author : imkaka
* @date : 31/1/2019
*/
#include<iostream>
#include<cstdio>
using namespace std;
int binary_search_itr(int arr[], int size, int val){
int l = 0, r = size-1;
int mid = (l + r) / 2;
while(arr[mid] != val && l <= r){
if(val < arr[mid]){
r = mid - 1;
}
else{
l = mid +1;
}
mid = (l + r) / 2;
}
if(arr[mid] == val)
return mid;
return -1;
}
int binary_search_rec(int arr[], int left, int right, int val){
if(right >= left){
int mid = left + (right - left) / 2;
if(arr[mid] == val) return mid;
if(arr[mid] > val)
return binary_search_rec(arr, left, mid-1, val);
return binary_search_rec(arr, mid+1, right, val);
}
return -1;
}
int main(){
int arr[] = {1, 2, 3, 6, 9, 15, 16, 14};
int val = 9;
int size = sizeof(arr)/sizeof(arr[0]);
cout << "Iterative: " << binary_search_itr(arr, size, val) << endl;
cout << "Recursive: " << binary_search_rec(arr, 0, size-1, val) << endl;
return 0;
}
|
////////////////////////////////////////////////////////////////////////////////
#include "load_points.h"
#include "MeshUtils.h"
#include <geogram/mesh/mesh_io.h>
////////////////////////////////////////////////////////////////////////////////
namespace cellogram {
void load_points(const std::string &filename, Eigen::MatrixXd &V) {
GEO::Mesh M;
if(!GEO::mesh_load(filename, M)) {
return;
}
Eigen::MatrixXi F, T;
from_geogram_mesh(M, V, F, T);
}
} // namespace cellogram
|
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*-
*
* Copyright (C) 1995-2005 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef XPATH_SUPPORT
#include "modules/xpath/src/xplogicalexpr.h"
#include "modules/xpath/src/xpparser.h"
XPath_LogicalExpression::XPath_LogicalExpression (XPath_Parser *parser, XPath_BooleanExpression *lhs, XPath_BooleanExpression *rhs, XPath_ExpressionType type)
: XPath_BooleanExpression (parser),
lhs (lhs),
rhs (rhs),
type (type),
state_index (parser->GetStateIndex ())
{
}
/* virtual */
XPath_LogicalExpression::~XPath_LogicalExpression ()
{
OP_DELETE (lhs);
OP_DELETE (rhs);
}
/* static */ XPath_BooleanExpression *
XPath_LogicalExpression::MakeL (XPath_Parser *parser, XPath_Expression *lhs, XPath_Expression *rhs, XPath_ExpressionType type)
{
OpStackAutoPtr<XPath_Expression> rhs_anchor (rhs);
XPath_BooleanExpression *lhs_boolean, *rhs_boolean;
lhs_boolean = XPath_BooleanExpression::MakeL (parser, lhs);
OpStackAutoPtr<XPath_BooleanExpression> lhs_boolean_anchor (lhs_boolean);
rhs_anchor.release ();
rhs_boolean = XPath_BooleanExpression::MakeL (parser, rhs);
OpStackAutoPtr<XPath_BooleanExpression> rhs_boolean_anchor (rhs_boolean);
XPath_LogicalExpression *expression = OP_NEW_L (XPath_LogicalExpression, (parser, lhs_boolean, rhs_boolean, type));
lhs_boolean_anchor.release ();
rhs_boolean_anchor.release ();
return expression;
}
/* virtual */ unsigned
XPath_LogicalExpression::GetExpressionFlags ()
{
return ((lhs->GetExpressionFlags () | rhs->GetExpressionFlags ()) & MASK_INHERITED) | FLAG_BOOLEAN;
}
/* virtual */ BOOL
XPath_LogicalExpression::EvaluateToBooleanL (XPath_Context *context, BOOL initial)
{
unsigned &state = context->states[state_index];
/* States: 0 = initial
1 = continue evaluation of lhs
2 = continue evaluation of rhs */
if (initial)
state = 0;
BOOL lhs_initial = state < 1, rhs_initial = state < 2;
if (state < 2)
{
if (lhs_initial)
state = 1;
if (!lhs->EvaluateToBooleanL (context, lhs_initial) == (type == XP_EXPR_AND))
return type == XP_EXPR_OR;
state = 2;
}
return rhs->EvaluateToBooleanL (context, rhs_initial);
}
#endif // XPATH_SUPPORT
|
#pragma once
namespace BroodWar
{
namespace Loader
{
private ref class AIManaged abstract sealed
{
private:
static AiBase^ aiBase;
internal:
static AIManaged();
static void Reload();
static void Start();
static void End(bool isWinner);
static void Frame();
static void SendText(System::String^ text);
static void ReceiveText(BWAPI::Player player, System::String^ text);
static void PlayerLeft(BWAPI::Player player);
static void NukeDetect(BWAPI::Position target);
static void UnitDiscover(BWAPI::Unit unit);
static void UnitEvade(BWAPI::Unit unit);
static void UnitShow(BWAPI::Unit unit);
static void UnitHide(BWAPI::Unit unit);
static void UnitCreate(BWAPI::Unit unit);
static void UnitDestroy(BWAPI::Unit unit);
static void UnitMorph(BWAPI::Unit unit);
static void UnitRenegade(BWAPI::Unit unit);
static void SaveGame(System::String^ gameName);
static void UnitComplete(BWAPI::Unit unit);
static void PlayerDropped(BWAPI::Player player);
};
}
}
|
//
// Created by Benoit Hamon on 10/4/2017.
//
#include <iostream>
#include <fstream>
#include <regex>
#include <exception>
#include <boost/dll/import.hpp>
#include <boost/range/iterator_range.hpp>
#include "ModuleManager.hpp"
#include "ssl/Base64.hpp"
ModuleManager::ModuleManager(IModuleCommunication *moduleCommunication,
std::string const &dirname)
: _dirname(dirname), _moduleCommunication(moduleCommunication) {}
ModuleManager::~ModuleManager() {}
std::vector<std::string> ModuleManager::readDirectory() {
boost::filesystem::path p(this->_dirname);
std::vector<std::string> res;
std::regex regex(".+\\.so");
if (is_directory(p)) {
for (auto &entry : boost::make_iterator_range(boost::filesystem::directory_iterator(p), {})) {
std::string tmp(entry.path().string());
if (std::regex_match(tmp, regex))
res.push_back(tmp);
}
}
return res;
}
void ModuleManager::runLibrary(std::string const &libraryName) {
boost::filesystem::path shared_library_path(libraryName);
boost::function<module_t > creator;
std::cout << libraryName << std::endl;
try {
creator = boost::dll::import_alias<module_t>(shared_library_path, "create_module");
boost::shared_ptr<IModule> plugin = creator(this->_moduleCommunication);
this->_threads.create_thread(boost::bind(&IModule::start, plugin.get()));
this->_libraries.push_back({libraryName, plugin, creator});
} catch (std::exception) {
this->_libraries.push_back({libraryName, nullptr, creator});
}
}
void ModuleManager::runLibraries() {
std::vector<std::string> librariesNames = this->readDirectory();
for (auto &libraryName : librariesNames) {
if (std::find_if(this->_libraries.begin(),
this->_libraries.end(),
[libraryName](Library &lib) {return lib.name == libraryName;}) == this->_libraries.end()) {
runLibrary(libraryName);
}
}
}
void ModuleManager::run() {
while (true) {
this->runLibraries();
boost::this_thread::sleep_for(boost::chrono::milliseconds(100));
}
this->_threads.join_all();
}
void ModuleManager::addModuleCommunication(IModuleCommunication *moduleCommunication) {
this->_moduleCommunication = moduleCommunication;
}
void ModuleManager::addLibrary(boost::property_tree::ptree const &ptree) {
try {
std::ofstream file(this->_dirname
+ ptree.get<std::string>("filename"));
file << Base64::decrypt(ptree.get<std::string>("data"));
file.close();
} catch (std::exception) {}
}
|
#ifndef SYNERGIST_H_
#define SYNERGIST_H_
#include "Skill.h"
#include "CharacterEntity.h"
class Synergist : public CharacterEntity
{
public:
Synergist();
~Synergist();
virtual void Init(int Level);
virtual void LevelUp(bool);
void Update(double dt);
// OffensiveSkill* skill_1;
};
#endif
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x, y, z, T;
scanf("%d", &T);
while(T--){
scanf("%d %d %d", &x, &y, &z);
printf("%d\n", z*(2*x-y) / (x+y));
}
return 0;
}
|
#ifndef _MAC_SERVICES_HANDLER_H_
#define _MAC_SERVICES_HANDLER_H_
#ifdef SUPPORT_OSX_SERVICES
#ifndef NO_CARBON
const CFStringRef kOperaOpenURLString = CFSTR("openURL");
const CFStringRef kOperaMailToString = CFSTR("mailTo");
const CFStringRef kOperaSendFilesString = CFSTR("sendFiles");
const CFStringRef kOperaOpenFilesString = CFSTR("openFiles");
#endif // NO_CARBON
class MacOpServices
{
public:
static void Free();
static void InstallServicesHandler();
private:
MacOpServices();
#ifndef NO_CARBON
enum OperaServiceProviderKind
{
kOperaServiceKindUnknown = 0,
kOperaServiceKindOpenURL = 1,
kOperaServiceKindMailTo = 2,
kOperaServiceKindSendFiles = 3,
kOperaServiceKindOpenFiles = 4
};
static OperaServiceProviderKind GetServiceKind(CFStringRef cfstr);
static pascal OSStatus ServicesHandler(EventHandlerCallRef nextHandler, EventRef inEvent, void *inUserData);
static EventHandlerRef sServicesHandler;
static EventHandlerUPP sServicesUPP;
#endif // NO_CARBON
};
#endif // SUPPORT_OSX_SERVICES
#endif // _MAC_SERVICES_HANDLER_H_
|
/*
* Copyright (c) 2015-2021 Morwenn
* SPDX-License-Identifier: MIT
*/
#ifndef CPPSORT_FIXED_LOW_MOVES_SORTER_H_
#define CPPSORT_FIXED_LOW_MOVES_SORTER_H_
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <cstddef>
#include <functional>
#include <iterator>
#include <tuple>
#include <type_traits>
#include <utility>
#include <cpp-sort/sorter_facade.h>
#include <cpp-sort/sorter_traits.h>
#include <cpp-sort/utility/functional.h>
#include <cpp-sort/utility/iter_move.h>
#include "../detail/empty_sorter.h"
#include "../detail/minmax_element.h"
namespace cppsort
{
////////////////////////////////////////////////////////////
// Adapter
template<std::size_t N>
struct low_moves_sorter;
namespace detail
{
template<std::size_t N>
struct low_moves_sorter_impl
{
template<
typename RandomAccessIterator,
typename Compare = std::less<>,
typename Projection = utility::identity,
typename = std::enable_if_t<is_projection_iterator_v<
Projection, RandomAccessIterator, Compare
>>
>
auto operator()(RandomAccessIterator first, RandomAccessIterator last,
Compare compare={}, Projection projection={}) const
-> void
{
using utility::iter_swap;
// There are specializations for N < 5, so unchecked_minmax_element
// will always be passed at least 2 elements
RandomAccessIterator min, max;
std::tie(min, max) = unchecked_minmax_element(first, last, compare, projection);
--last;
if (max == first && min == last) {
if (min == max) return;
iter_swap(min, max);
} else if (max == first) {
if (last != max) {
iter_swap(last, max);
}
if (first != min) {
iter_swap(first, min);
}
} else {
if (first != min) {
iter_swap(first, min);
}
if (last != max) {
iter_swap(last, max);
}
}
++first;
low_moves_sorter<N-2u>{}(std::move(first), std::move(last),
std::move(compare), std::move(projection));
}
};
template<>
struct low_moves_sorter_impl<0u>:
cppsort::detail::empty_sorter_impl
{};
template<>
struct low_moves_sorter_impl<1u>:
cppsort::detail::empty_sorter_impl
{};
}
template<std::size_t N>
struct low_moves_sorter:
sorter_facade<detail::low_moves_sorter_impl<N>>
{};
////////////////////////////////////////////////////////////
// Sorter traits
template<std::size_t N>
struct sorter_traits<low_moves_sorter<N>>
{
using iterator_category = std::random_access_iterator_tag;
// Some of the algorithms are stable, some other are not,
// the stability *could* be documented depending on which
// fixed-size algorithms are used, but it would be lots of
// work...
using is_always_stable = std::false_type;
};
template<>
struct fixed_sorter_traits<low_moves_sorter>
{
using iterator_category = std::random_access_iterator_tag;
using is_always_stable = std::false_type;
};
}
// Specializations of low_moves_sorter for some values of N
#include "../detail/low_moves/sort2.h"
#include "../detail/low_moves/sort3.h"
#include "../detail/low_moves/sort4.h"
#endif // CPPSORT_FIXED_LOW_MOVES_SORTER_H_
|
//
// Created by carte on 11/7/2019.
//
#include "LinkedList.h"
#ifndef PROJECT7_QUEUE_H
#define PROJECT7_QUEUE_H
#endif //PROJECT7_QUEUE_H
class Queue: public LinkedList{
public:
Queue();
void enqueue_tail(Data stat);
bool dequeue_head();
private:
Node* tail;
};
|
// SubDoc.h : interface of the CSubDoc class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_SUBDOC_H__D55C4369_FDD2_11D2_8800_00A0C9062EBA__INCLUDED_)
#define AFX_SUBDOC_H__D55C4369_FDD2_11D2_8800_00A0C9062EBA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class Cell;
class Average;
class CSubDoc : public CDocument
{
protected: // create from serialization only
CSubDoc();
DECLARE_DYNCREATE(CSubDoc)
// Attributes
public:
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CSubDoc)
public:
virtual BOOL OnNewDocument();
virtual void Serialize(CArchive& ar);
virtual BOOL OnOpenDocument(LPCTSTR lpszPathName);
virtual BOOL OnSaveDocument(LPCTSTR lpszPathName);
//}}AFX_VIRTUAL
// Implementation
private:
int level;
public:
Cell *editCell, *saveCell;
Average *average;
void Resubdivide();
void SetLevel( int level );
void SetAverage( Average *a );
public:
virtual ~CSubDoc();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CSubDoc)
// NOTE - the ClassWizard will add and remove member functions here.
// DO NOT EDIT what you see in these blocks of generated code !
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_SUBDOC_H__D55C4369_FDD2_11D2_8800_00A0C9062EBA__INCLUDED_)
|
#include "bullet.h"
#include "gamemanager.h"
void Bullet::handleCollisions()
{
hurtElements();
if (_is_damage_dealed) {
_game->deleteElement(this);
}
}
void Bullet::hurtElements()
{
for (int i=0; i<_elements->size(); i++)
{
//czyli jesli nie sprawdza samego siebie, oraz jesli jest kolizja
if ( (*_elements)[i] != this
&& isCollisionWithElement((*_elements)[i])
&& _aggressor_team->isElementInThisTeam((*_elements)[i]) == false) {
_is_damage_dealed = true;
(*_elements)[i]->getHurt(_power);
}
}
}
Bullet::Bullet(XY pos, XY velo, int bullet_power, Team *aggressor_team, GameManager *game) :
Movable(pos, XY(10,10), 1, velo, game)
{
_power = bullet_power;
_aggressor_team = aggressor_team;
_elements = _game->getElements();
_hp = 1;
_is_damage_dealed = false;
}
bool Bullet::isInContactWithMe(Element *e)
{
return false;
//inne obiekty nie moga sie odbijac od pocisku
}
void Bullet::getHurt(int damage)
{
//cannot be hurt
}
#include <QDebug>
void Bullet::updateElement()
{
move();
}
|
#include "pch.h"
// Ship - length, hp, x, y, rotation,
// Field - 10x10 '~'
// Animation '*' 'o' 'O' x, y, end_char
// Player
// Enemy
int main()
{
game G;
G.menu();
system("pause");
// Phase 1: Menu
// Phase 2: Ship placement
// Phase 3: Turn based gameplay
// Phase 4: SOSAT
return 0;
}
|
#pragma once
#include "ofMain.h"
#include "StopMotionController.h"
#include "ofxGui.h"
class ofApp : public ofBaseApp
{
shared_ptr<StopMotionController> mAnimation;
ofxPanel mGui;
ofParameterGroup mParams;
ofParameter<float> mLevel;
ofParameter<float> mGain;
ofParameter<float> mDecay;
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void audioIn(ofSoundBuffer& buffer);
};
|
//Faรงa um programa que solicite 10 (dez) nรบmeros inteiros do usuรกrio. Informe os nรบmeros, a soma e a mรฉdia.
#include<stdlib.h>
#include<stdio.h>
main(){
int num1, num2, num3, num4, num5, num6, num7, num8, num9, num10;
float soma, media;
printf("Digite o primeiro numero: ");
scanf("%d",&num1);
printf("Digite o segundo numero: ");
scanf("%d",&num2);
printf("Digite o terceiro numero: ");
scanf("%d",&num3);
printf("Digite o quarto numero: ");
scanf("%d",&num4);
printf("Digite o quinto numero: ");
scanf("%d",&num5);
printf("Digite o sexto numero: ");
scanf("%d",&num6);
printf("Digite o setimo numero: ");
scanf("%d",&num7);
printf("Digite o oitavo numero: ");
scanf("%d",&num8);
printf("Digite o nono numero: ");
scanf("%d",&num9);
printf("Digite o decimo numero: ");
scanf("%d",&num10);
soma= num1+num2+num3+num4+num5+num6+num7+num8+num9+num10;
media= soma/10;
printf("\nSoma dos numeros: %.1f", soma);
printf("\nMedia dos numeros: %.1f", media);
}
|
#include "Galois/Galois.h"
#include "Galois/Accumulator.h"
#include "Galois/Bag.h"
#include "Galois/Statistic.h"
#include "Galois/UnionFind.h"
#include "Galois/Graphs/LCGraph.h"
#include "Galois/ParallelSTL/ParallelSTL.h"
#include "llvm/Support/CommandLine.h"
#include "Galois/Runtime/WorkList.h"
#include "Lonestar/BoilerPlate.h"
#include<sys/time.h>
#include <utility>
#include <algorithm>
#include <iostream>
#include "Galois/Statistic.h"
struct SNode{
unsigned int dist;
};
typedef Galois::Graph::LC_CSR_Graph<SNode,void> Graph;
typedef Graph::GraphNode GNode;
Graph graph;
unsigned int number_of_threads;
struct GNodeIndexer: public std::unary_function<GNode,unsigned int> {
unsigned int operator()(const GNode& val) const {
return (graph.getData(val, Galois::NONE).dist % 64);
}
};
struct AsyncAlgo {
std::string name() const { return "Parallel (Async)"; }
void operator()(GNode& source) const {
using namespace GaloisRuntime::WorkList;
std::deque<GNode> initial;
for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {
GNode src = *ii;
graph.getData(src, Galois::NONE).dist = src;
initial.push_back(src);
}
//set the number of active threads
Galois::setActiveThreads(number_of_threads);
std::cout << "graph size: " << graph.size() << std::endl;
std::cout << "workset size: " << initial.size() << std::endl;
Galois::for_each< FIFO<> >(initial.begin(), initial.end(), *this);
}
void operator()(GNode& n, Galois::UserContext<GNode>& ctx) const {
//std::cout << Galois::getActiveThreads() << std::endl;
SNode& data = graph.getData(n, Galois::NONE);
unsigned int newDist = data.dist;
for (Graph::edge_iterator ii = graph.edge_begin(n, Galois::NONE),
ei = graph.edge_end(n, Galois::NONE); ii != ei; ++ii) {
GNode dst = graph.getEdgeDst(ii);
SNode& ddata = graph.getData(dst, Galois::NONE);
if(ddata.dist > newDist){
graph.getData(dst, Galois::NONE).dist= newDist;
ctx.push(dst);
}
}
}
};
void print_componentIds(){
for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {
Graph::GraphNode src = *ii;
std::cout << src << " " << graph.getData(src, Galois::NONE).dist << std::endl;
}
}
/*Extremely slow for large graphs*/
void print_edges_in_graph(){
for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {
Graph::GraphNode src = *ii;
for (Graph::edge_iterator jj = graph.edge_begin(src), ej = graph.edge_end(src); jj != ej; ++jj) {
Graph::GraphNode dst = graph.getEdgeDst(jj);
std::cout << "Edge: " << src << " " << dst << std::endl;
}
}
}
struct timeval start, end;
int main(int argc, char **argv){
char *filename;
bool output = false;
if(argc > 2){
filename = argv[1];
number_of_threads = atoi(argv[2]);
}else{
std::cout << "You need to give filename and number of threads to run on" << std::endl;
}
if(argc > 3){
output = true;
}
graph.structureFromFile(filename);
std::cout << "in main graph loaded" << std::endl;
//Initialize the component ids of the nodes with the node number
for (Graph::iterator ii = graph.begin(), ei = graph.end(); ii != ei; ++ii) {
Graph::GraphNode src = *ii;
graph.getData(src, Galois::NONE).dist = src;
}
Galois::preAlloc((16 + (graph.size() * sizeof(SNode) * 2) / GaloisRuntime::MM::pageSize)*8);
Galois::Statistic("MeminfoPre", GaloisRuntime::MM::pageAllocInfo());
Galois::StatTimer T;
T.start();
GNode gn1;
gettimeofday(&start, NULL);
AsyncAlgo a;
a(gn1);
gettimeofday(&end, NULL);
T.stop();
Galois::Statistic("MeminfoPost", GaloisRuntime::MM::pageAllocInfo());
if(output)
print_componentIds();
std::cout << "Time taken by parallel galois fifo implementation on " << graph.size() << " nodes is " << (((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6) << std::endl;
return 0;
}
|
#include "CppUnitTest.h"
#include "CppUnitTestAssert.h"
#include "../3XD_Lib/geometry/transform.h"
#include <math.h>
#include <vector>
#include <array>
#define M_PI 3.14159265358979323846
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Z_3D_LIB_FOR_EGE;
namespace My3D_Lib_for_ege_UnitTest
{
TEST_CLASS(_transform_test)
{
typedef _square < 4, double > MATRIX;
typedef _affine_vector VECTOR;
typedef _affine_vector DOT;
typedef _line LINE;
typedef _plane PLANE;
public:
TEST_METHOD(transform__X_I_T)
{
_vector < 3, double > t1 { 1.0, 2.0, 3.0 };
_matrix < 3, 3, double > t2{
{ 0.0, 3.0, -2.0 },
{ -3.0, 0.0, 1.0 },
{ 2.0, -1.0, 0.0 },
};
_matrix < 3, 3, double > t3 = _transform::_X(t1);
Assert::IsTrue(t2 == t3);
_square < 3, double > t4(IDENTITY_MATRIX);
_square < 3, double > t5 = _transform::_I();
Assert::IsTrue(t4 == t5);
_matrix < 3, 3, double > t6{
{ 1.0, 2.0, 3.0 },
{ 2.0, 4.0, 6.0 },
{ 3.0, 6.0, 9.0 },
};
_matrix < 3, 3, double > t7 = _transform::_T(t1);
Assert::IsTrue(t6 == t7);
}
TEST_METHOD(transform_exec) {
MATRIX _m;
MATRIX _t = _transform::_J({ _m });
Assert::IsTrue(_m == _t);
VECTOR v{ 0, 0, 0, 1 };
std::vector< VECTOR > v2 = { { 1, 2, 3, 0 },{ 3, 4, 5, 0 } };
_transform::exec({ _m }, v2);
}
TEST_METHOD(transform__join) {
double _t11[3][3] = {
{ 1, 2, 3 },
{ 2, 3, 4 },
{ 3, 4, 5 },
};
double _t12[3][1] = {
{ 0 }, { 0 }, { 0 },
};
double _t21[1][3] = {
{ -1, -2, -3 }
};
double _t22[1][1] = { { 1 } };
double _tj[4][4] = {
{ 1, 2, 3, 0 },
{ 2, 3, 4, 0 },
{ 3, 4, 5, 0 },
{ -1, -2, -3, 1 },
};
_matrix< 3, 3, double > t11(_t11);
_matrix< 3, 1, double > t12(_t12);
_matrix< 1, 3, double> t21(_t21);
_matrix< 1, 1, double > t22(_t22);
_matrix< 4, 4, double > tj(_tj);
_matrix< 4, 4, double > t = _transform::_join(t11, t12, t21, t22);
Assert::IsTrue(t == tj);
}
TEST_METHOD(transform_trans) {
double _t1[4] = { 1, 2, 3, 0 };
double _tt[4] = { 1, 3, -2, 0 };
VECTOR t1(_t1);
VECTOR tt(_tt);
VECTOR t2 = _transform::trans(t1, tt);
Assert::IsTrue(t1 == t2);
double _t3[4] = { 1, 2, 3, 1 };
double _t4[4] = { 2, 5, 1, 1 };
DOT t3(_t3);
VECTOR t4(_t4);
DOT t5 = _transform::trans(t3, tt);
Assert::IsTrue(t4 == t5);
}
TEST_METHOD(transform_rot) {
double _t1[4] = { 1, 1, 1, 0 };
DOT _p{ 0, 0, 0, 1 };
VECTOR _v{ 0, 0, 1, 0 };
LINE _l(_p, _v);
VECTOR t1(_t1);
VECTOR tt{ cos(M_PI / 2) - sin(M_PI / 2), sin(M_PI / 2) + cos(M_PI / 2), 1, 0 };
VECTOR t2 = _transform::rot(t1, _l, M_PI / 2);
Assert::IsTrue(t2 == tt);
VECTOR _v2{ 0, 1, 0, 0 };
LINE _l2(_p, _v2);
VECTOR tt2{ cos( M_PI / 2 ) + sin( M_PI / 2 ), 1, cos( M_PI / 2 ) - sin( M_PI / 2 ), 0 };
VECTOR t3 = _transform::rot(t1, _l2, M_PI / 2);
Assert::IsTrue(t3 == tt2);
VECTOR _v3{ 1, 0, 0, 0 };
LINE _l3(_p, _v3);
VECTOR tt3{ 1, cos(M_PI / 2) - sin(M_PI / 2), sin(M_PI / 2) - cos(M_PI / 2), 0 };
VECTOR t4 = _transform::rot(t1, _l3, M_PI / 2);
Assert::IsFalse(t4 == tt3);
}
TEST_METHOD(transform_mirror) {
DOT t1{ 1, 2, 3, 4 };
VECTOR _p{ 0, 0, 0, 1 };
VECTOR _v{ 0, 0, 1, 0 };
DOT t2{ 1, 2, -3, 4 };
PLANE _l(_p, _v);
DOT tt = _transform::mirror(t1, _l);
Assert::IsTrue(t2 == tt);
DOT t3{ 1, -2, 3, 4 };
VECTOR _v2{ 0, 1, 0, 0 };
PLANE _l2(_p, _v2);
DOT tt2 = _transform::mirror(t1, _l2);
Assert::IsTrue(t3 == tt2);
DOT t4{ -1, 2, 3, 4 };
VECTOR _v3{ 1, 0, 0, 0 };
PLANE _l3(_p, _v3);
DOT tt3 = _transform::mirror(t1, _l3);
Assert::IsTrue(t4 == tt3);
}
TEST_METHOD(transform_scale) {
DOT t1{ 1, 2, 3, 4 };
DOT tt{ 3, 6, 9, 4 };
DOT o{ 0, 0, 0, 1 };
DOT t2 = _transform::scale(t1, 3.0, o);
Assert::IsTrue(t2 == tt);
VECTOR w{ 0, 0, 1, 0 };
DOT tt2{ 1, 2, 9, 4 };
DOT t3 = _transform::scale(t1, 3.0, o, w);
Assert::IsTrue(t3 == tt2);
VECTOR w2{ 1, 0, 0, 0 };
DOT tt3{ 3, 2, 3, 4 };
DOT t4 = _transform::scale(t1, 3.0, o, w2);
Assert::IsTrue(t4 == tt3);
VECTOR w3{ 0, 1, 0, 0 };
DOT tt4{ 1, 6, 3, 4 };
DOT t5 = _transform::scale(t1, 3.0, o, w3);
Assert::IsTrue(t5 == tt4);
}
TEST_METHOD(transform_ortho) {
DOT t1{ 1, 2, 3, 4 };
DOT tt{ 1, 2, 0, 4 };
DOT _p{ 0, 0, 0, 1 };
VECTOR _n{ 0, 0, 1, 0 };
PLANE _l(_p, _n);
DOT t2 = _transform::ortho(t1, _l);
Assert::IsTrue(t2 == tt);
VECTOR _n2{ 0, 1, 0, 0 };
PLANE _l2(_p, _n2);
DOT tt2{ 1, 0, 3, 4 };
DOT t3 = _transform::ortho(t1, _l2);
Assert::IsTrue(t3 == tt2);
VECTOR _n3{ 1, 0, 0, 0 };
PLANE _l3(_p, _n3);
DOT tt3{ 0, 2, 3, 4 };
DOT t4 = _transform::ortho(t1, _l3);
Assert::IsTrue(t4 == tt3);
}
TEST_METHOD(transform_persp) {
DOT t1{ 1, 2, 3, 4 };
DOT tt{ 10.0 / 37.0, 20.0 / 37.0, 0, 1 };
DOT v{ 0, 0, 10, 1 }; // view pointer
DOT _p{ 0, 0, 0, 1 };
VECTOR _n{ 0, 0, 1, 0 };
PLANE _l(_p, _n);
DOT t2 = _transform::persp(t1, _l, v);
t2.normalize();
Assert::IsTrue(tt == t2);
}
TEST_METHOD(transform_shear) {
DOT t1{ 1, 1, 5, 1 };
DOT tt{ 1, 1, (tan(M_PI / 2) + 1) * 5, 1 };
PLANE _l({ 0, 0, 0, 1 }, { 0, 0, 1, 0 });
DOT _w{ 0, 0, 1, 0 };
DOT t2 = _transform::shear(t1, _l, _w, M_PI / 2);
Assert::IsTrue(tt == t2);
}
};
}
|
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "serialadapter.h"
#include "rgbdapter.h"
#include "myconicalgradient.h"
#include "avaservice.h"
#include "gateadapter.h"
#include "buttonadapter.h"
#include "bme280adapter.h"
#include "compressoradapter.h"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
app.setOrganizationName("Shagalin A.M.");
app.setOrganizationDomain("shagalinam@gmail.com");
app.setApplicationName("Home Application");
QQmlApplicationEngine engine;
SerialAdapter::declareQML();
GateAdapter::declareQML();
ButtonAdapter::declareQML();
RGBAdapter::declareQML();
BME280Adapter::declareQML();
CompressorAdapter::declareQML();
MyConicalGradient::declareQML();
AvaService::declareQML();
DataAdapter::declareQML();
engine.load(QUrl(QStringLiteral("qrc:/AvaInterface.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
|
/*
This file is part of the VRender library.
Copyright (C) 2005 Cyril Soler (Cyril.Soler@imag.fr)
Version 1.0.0, released on June 27, 2005.
http://artis.imag.fr/Members/Cyril.Soler/VRender
VRender is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
VRender 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 VRender; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.3.
http://www.libqglviewer.com - contact@libqglviewer.com
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#ifndef _VRENDER_EXPORTER_H
#define _VRENDER_EXPORTER_H
// Set of classes for exporting in various formats, like EPS, XFig3.2, SVG.
#include "Primitive.h"
#include "../config.h"
#include <QTextStream>
#include <QString>
namespace vrender
{
class VRenderParams ;
class Exporter
{
public:
Exporter() ;
virtual ~Exporter() {};
virtual void exportToFile(const QString& filename,const std::vector<PtrPrimitive>&,VRenderParams&) ;
void setBoundingBox(float xmin,float ymin,float xmax,float ymax) ;
void setClearColor(float r,float g,float b) ;
void setClearBackground(bool b) ;
void setBlackAndWhite(bool b) ;
protected:
virtual void spewPoint(const Point *, QTextStream& out) = 0 ;
virtual void spewSegment(const Segment *, QTextStream& out) = 0 ;
virtual void spewPolygone(const Polygone *, QTextStream& out) = 0 ;
virtual void writeHeader(QTextStream& out) const = 0 ;
virtual void writeFooter(QTextStream& out) const = 0 ;
float _clearR,_clearG,_clearB ;
float _pointSize ;
float _lineWidth ;
GLfloat _xmin,_xmax,_ymin,_ymax,_zmin,_zmax ;
bool _clearBG,_blackAndWhite ;
};
// Exports to encapsulated postscript.
class EPSExporter: public Exporter
{
public:
EPSExporter() ;
virtual ~EPSExporter() {};
protected:
virtual void spewPoint(const Point *, QTextStream& out) ;
virtual void spewSegment(const Segment *, QTextStream& out) ;
virtual void spewPolygone(const Polygone *, QTextStream& out) ;
virtual void writeHeader(QTextStream& out) const ;
virtual void writeFooter(QTextStream& out) const ;
private:
void setColor(QTextStream& out,float,float,float) ;
static const double EPS_GOURAUD_THRESHOLD ;
static const char *GOURAUD_TRIANGLE_EPS[] ;
static const char *CREATOR ;
static float last_r ;
static float last_g ;
static float last_b ;
};
// Exports to postscript. The only difference is the filename extension and
// the showpage at the end.
class PSExporter: public EPSExporter
{
public:
virtual ~PSExporter() {};
protected:
virtual void writeFooter(QTextStream& out) const ;
};
class FIGExporter: public Exporter
{
public:
FIGExporter() ;
virtual ~FIGExporter() {};
protected:
virtual void spewPoint(const Point *, QTextStream& out) ;
virtual void spewSegment(const Segment *, QTextStream& out) ;
virtual void spewPolygone(const Polygone *, QTextStream& out) ;
virtual void writeHeader(QTextStream& out) const ;
virtual void writeFooter(QTextStream& out) const ;
private:
mutable int _sizeX ;
mutable int _sizeY ;
mutable int _depth ;
int FigCoordX(double) const ;
int FigCoordY(double) const ;
int FigGrayScaleIndex(float red, float green, float blue) const ;
};
#ifdef A_FAIRE
class SVGExporter: public Exporter
{
protected:
virtual void spewPoint(const Point *, QTextStream& out) ;
virtual void spewSegment(const Segment *, QTextStream& out) ;
virtual void spewPolygone(const Polygone *, QTextStream& out) ;
virtual void writeHeader(QTextStream& out) const ;
virtual void writeFooter(QTextStream& out) const ;
};
#endif
}
#endif
|
#ifndef RENDERMANAGER_H
#define RENDERMANAGER_H
#include "renderer/quadrenderer.h"
#include "renderer/cuberenderer.h"
#include "renderer/chunkrenderer.h"
#include "renderer/uirenderer.h"
class Camera;
class ChunkMesh;
class Ui;
class RenderManager
{
public:
RenderManager();
void addQuad(const Vector3 &pos);
void addCube(const Vector3 &pos);
void addChunk(const ChunkMesh &chunkMesh);
void addUi(const Ui &ui);
void render(const Camera &camera);
private:
QuadRenderer _quadRenderer;
CubeRenderer _cubeRenderer;
ChunkRenderer _chunkRenderer;
UiRenderer _uiRenderer;
};
#endif // RENDERMANAGER_H
|
#include "CameraModel.h"
#include <ComputerVisionLib/CameraModel/ProjectionModel/PinholeModel.h>
Cvl::CameraModel::CameraModel(DistortionModel::Uptr pDistortionModel, ProjectionModel::Uptr pProjectionModel) :
mpDistortionModel(std::move(pDistortionModel)),
mpProjectionModel(std::move(pProjectionModel))
{
}
Cvl::CameraModel::CameraModel(ProjectionModel::Uptr pProjectionModel) :
mpDistortionModel(nullptr),
mpProjectionModel(std::move(pProjectionModel))
{
}
Cvl::CameraModel::CameraModel(CameraModel const & other) :
mpDistortionModel(other.mpDistortionModel ? other.mpDistortionModel->clone() : nullptr),
mpProjectionModel(other.mpProjectionModel->clone())
{
}
Cvl::CameraModel::~CameraModel()
{
}
Eigen::Array2Xd Cvl::CameraModel::distortAndProject(Eigen::Array2Xd const & normalizedCameraPoints) const
{
return mpProjectionModel->project(mpDistortionModel ? mpDistortionModel->distort(normalizedCameraPoints) : normalizedCameraPoints);
}
Eigen::Array2d Cvl::CameraModel::distortAndProject(Eigen::Array2d const & normalizedCameraPoint) const
{
return distortAndProject((Eigen::Array2Xd(2, 1) << normalizedCameraPoint).finished()).col(0);
}
Eigen::Array2Xd Cvl::CameraModel::unprojectAndUndistort(Eigen::Array2Xd const & imagePoints) const
{
if (mpDistortionModel)
return mpDistortionModel->undistort(mpProjectionModel->unproject(imagePoints));
return mpProjectionModel->unproject(imagePoints);
}
Eigen::Array2d Cvl::CameraModel::unprojectAndUndistort(Eigen::Array2d const & imagePoint) const
{
return unprojectAndUndistort((Eigen::Array2Xd(2, 1) << imagePoint).finished()).col(0);
}
Eigen::Array2Xd Cvl::CameraModel::transformTo(CameraModel const & other, Eigen::Array2Xd const & imagePoints) const
{
return other.distortAndProject(this->unprojectAndUndistort(imagePoints));
}
Eigen::Array2d Cvl::CameraModel::transformTo(CameraModel const & other, Eigen::Array2d const & imagePoint) const
{
return transformTo(other, (Eigen::Array2Xd(2, 1) << imagePoint).finished()).col(0);
}
Eigen::Array2Xd Cvl::CameraModel::transformToPinhole(Eigen::Array2Xd const & imagePoints) const
{
Eigen::Vector4d projectionParameters = this->getProjectionParameters();
CameraModel pinholeModel = CameraModel::create<PinholeModel>(projectionParameters(0), projectionParameters(1), projectionParameters(2), projectionParameters(3));
return this->transformTo(pinholeModel, imagePoints);
}
Eigen::Array2d Cvl::CameraModel::transformToPinhole(Eigen::Array2d const & imagePoint) const
{
return transformToPinhole((Eigen::Array2Xd(2, 1) << imagePoint).finished()).col(0);
}
bool Cvl::CameraModel::isPinholeModel() const
{
return (dynamic_cast<Cvl::PinholeModel*>(mpProjectionModel.get()) != nullptr);
}
Eigen::Matrix3d Cvl::CameraModel::getPinholeCameraMatrix() const
{
return mpProjectionModel->getPinholeCameraMatrix();
}
Eigen::Matrix3d Cvl::CameraModel::getInversePinholeCameraMatrix() const
{
return mpProjectionModel->getInversePinholeCameraMatrix();
}
Eigen::Vector4d Cvl::CameraModel::getProjectionParameters() const
{
return mpProjectionModel->getParameters();
}
Eigen::VectorXd Cvl::CameraModel::getDistortionParameters() const
{
return mpDistortionModel ? mpDistortionModel->getParameters() : Eigen::VectorXd();
}
Eigen::VectorXd Cvl::CameraModel::getAllParameters() const
{
Eigen::VectorXd distortionParameters = mpDistortionModel ? mpDistortionModel->getParameters() : Eigen::VectorXd();
return (Eigen::VectorXd(4 + distortionParameters.size()) << mpProjectionModel->getParameters(), distortionParameters).finished();
}
void Cvl::CameraModel::setProjectionParameters(double focalLengthX, double focalLengthY, double principalPointX, double principalPointY)
{
mpProjectionModel->setParameters(focalLengthX, focalLengthY, principalPointX, principalPointY);
}
void Cvl::CameraModel::setProjectionParameters(Eigen::Vector4d const & parameters)
{
mpProjectionModel->setParameters(parameters);
}
void Cvl::CameraModel::setDistortionParameters(Eigen::VectorXd const & parameters)
{
if (mpDistortionModel)
mpDistortionModel->setParameters(parameters);
}
void Cvl::CameraModel::resetDistortionParameters()
{
if (mpDistortionModel)
mpDistortionModel->resetParameters();
}
void Cvl::CameraModel::setAllParameters(Eigen::VectorXd const & parameters)
{
mpProjectionModel->setParameters(parameters.head(4));
if (mpDistortionModel)
mpDistortionModel->setParameters(parameters.tail(parameters.rows() - 4));
}
Cvl::CameraModel& Cvl::CameraModel::operator=(CameraModel const & other)
{
if (this != &other)
{
mpDistortionModel = other.mpDistortionModel ? other.mpDistortionModel->clone() : nullptr;
mpProjectionModel = other.mpProjectionModel->clone();
}
return *this;
}
|
//้ฆๅ
ๆณๅฐไบhash่กจ,็ถๅๆฏไบๅๆฅๆพ,ไฝๆฏๆฒก็ป่ๅด,hash็จ่ตทๆฅๆ็นๆ
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
for(int i=0;i<numbers.size();++i){
if(numbers[i]*2==target){ //3.่ฟ็งๆ
ๅตๆฒก่่ๅฐ
vector<int> result;
result.push_back(i+1);
result.push_back(i+2);
return result;
}
int temp = binary_search(numbers,0,numbers.size(),target-numbers[i]);
if(temp!=-100){
vector<int> result;
result.push_back(i+1); //1.ไบบๅฎถ่ฆ็ๆฏindexไธๆฏvalue 2.Please note that your returned answers (both index1 and index2) are not zero-based.ไปไน็ฉๆ
result.push_back(temp+1);
return result;
}
}
}
//ไบๅๆฅๆพvector็
int binary_search(vector<int>& numbers,int low,int high,int be_searched){
for(;low<high;){
int middle=(low+high)>>1;
if(be_searched<numbers[middle]){
high=middle;
}
else if(be_searched>numbers[middle]){
low=middle+1;
}
else{
for(;be_searched==numbers[middle];middle=middle-1);
middle=middle+1;
return middle;
}
}
return -100;
}
};
|
#include <bits/stdc++.h>
using namespace std;
int n = 100, l, r, x;
int main() {
srand(time(0));
printf("%d %d\n", n, n);
for (int i = 1; i <= n; i++) {
x = rand() % 2, l = (rand() - 1) % n + 1, r = (rand() - 1) % n + 1;
if (l > r) swap(l, r);
printf("%d %d %d\n", x, l, r);
}
}
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder 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.
**
** FlatSiteBuilder 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 FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#ifndef MENUELIST_H
#define MENUELIST_H
#include <QWidget>
#include <QPushButton>
#include <QTableWidget>
#include "site.h"
#include "undoableeditor.h"
class QUndoStack;
class MainWindow;
class MenuEditor;
class FlatButton;
class MenuList : public UndoableEditor
{
Q_OBJECT
public:
MenuList(MainWindow *win, Site *site);
void load() override;
void save() override;
void registerMenuEditor(MenuEditor *editor);
void unregisterMenuEditor();
private slots:
void buttonClicked();
void tableDoubleClicked(int, int);
void deleteMenu(QObject *menu);
void editMenu(QObject *menu);
void menuChanged(QString text);
signals:
void editContent(QTableWidgetItem *item);
void editedItemChanged(QTableWidgetItem *item);
private:
Site *m_site;
QTableWidget *m_list;
MainWindow *m_win;
MenuEditor *m_editor;
Menu *m_menuInEditor;
QTableWidgetItem *addListItem(Menu *menu);
};
#endif // MENUELIST_H
|
// https://practice.geeksforgeeks.org/problems/fixed-two-nodes-of-a-bst/1/?track=md-tree&batchId=144
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *left, *right;
Node(int x)
{
int data = x;
left = right = NULL;
}
};
void swap(int *a, int *b)
{
int t = *a;
*a = *b;
*b = t;
}
struct Node *NewNode(int data)
{
struct Node *Node = (struct Node *)malloc(sizeof(struct Node));
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);
}
struct Node *correctBST(struct Node *root);
void Inorder(struct Node *root)
{
if (root == NULL)
{
return;
}
Inorder(root->left);
cout << root->data << " ";
Inorder(root->right);
}
int flag = 1;
int c = 0;
void inorder(struct Node *temp, struct Node *root)
{
if (flag == 0)
{
return;
}
if (temp == NULL && root == NULL)
return;
if (root == NULL)
{
flag = 0;
return;
}
if (temp == NULL)
{
flag = 0;
return;
}
if (temp->data == root->data)
{
c++;
}
inorder(temp->left, root->left);
inorder(temp->right, root->right);
}
void insert(struct Node *root, int a1, int a2, char lr)
{
if (root == NULL)
return;
if (root->data == a1)
{
switch (lr)
{
case 'L':
root->left = NewNode(a2);
break;
case 'R':
root->right = NewNode(a2);
break;
}
}
insert(root->left, a1, a2, lr);
insert(root->right, a1, a2, lr);
}
int main()
{
int t;
cin >> t;
while (t--)
{
struct Node *root = NULL;
struct Node *temp = NULL;
int n;
cin >> n;
int m = n;
while (n--)
{
int a1, a2;
char lr;
cin >> a1 >> a2 >> lr;
if (root == NULL)
{
temp = NewNode(a1);
root = NewNode(a1);
switch (lr)
{
case 'L':
root->left = NewNode(a2);
temp->left = NewNode(a2);
break;
case 'R':
root->right = NewNode(a2);
temp->right = NewNode(a2);
break;
}
}
else
{
insert(root, a1, a2, lr);
insert(temp, a1, a2, lr);
}
}
flag = 1;
c = 0;
root = correctBST(root);
inorder(temp, root);
if (c + 1 == m)
{
cout << flag << endl;
}
else
{
cout << "0";
}
}
return 0;
}
/*This is a function problem.You only need to complete the function given below*/
/*Complete the function
Node is as follows:
struct Node
{
int data;
struct Node *left, *right;
Node(int x){
int data = x;
left = right = NULL;
}
};
*/
void findNodes(Node *root, Node *prev, Node *first, Node *adjacent, Node *second)
{
if (!root)
return;
// cout << root->data << " ";
findNodes(root->left, prev, first, adjacent, second);
if (prev)
{
if (prev->data > root->data)
{
if (!first)
{
*first = *prev;
*adjacent = *root;
cout << first->data << " " << adjacent->data << endl;
}
else
*second = *root;
}
}
*prev = *root;
findNodes(root->right, prev, first, adjacent, second);
}
struct Node *correctBST(struct Node *root)
{
struct Node *first, *second, *adjacent, *prev;
first = second = adjacent = prev = NULL;
findNodes(root, prev, first, adjacent, second);
if (first && second)
{
int temp = first->data;
first->data = second->data;
second->data = temp;
}
else if (first && adjacent)
{
int temp = adjacent->data;
adjacent->data = first->data;
first->data = temp;
}
return root;
}
|
#ifndef _ss_math_H_
#define _ss_math_H_
#include "ssVector2.h"
#include "ssVector3.h"
#include "ssVector4.h"
#include "ssBBox.h"
#include "ssMatrix3.h"
#include "ssMatrix4.h"
#include "ssPlane.h"
#include "ssPoint3.h"
#include "ssQuaternion.h"
#include "ssRay.h"
#include "ssSphere.h"
using std::min;
using std::max;
// global functions for fast use.
inline void CoordinateSystem0(const ssMath::Vector3 &v1, ssMath::Vector3 &v2, ssMath::Vector3 &v3)
{
if(v1.y != 1 && v1.y != -1)
{
v2 = ssMath::Vector3(v1.z, 0, -v1.x).hat();
v3 = v1.crossProduct(v2);//Cross(v1, *v2);
}
else
{
v2 = ssMath::Vector3(1, 0, 0);
v3 = ssMath::Vector3(0, 0, 1);
}
}
inline void CoordinateSystem1(const ssMath::Vector3 &v1, ssMath::Vector3 &v2, ssMath::Vector3 &v3)
{
if (fabsf(v1.x) > fabsf(v1.y)) {
float invLen = 1.f / sqrtf(v1.x*v1.x + v1.z*v1.z);
v2 = ssMath::Vector3(-v1.z * invLen, 0.f, v1.x * invLen);
}
else {
float invLen = 1.f / sqrtf(v1.y*v1.y + v1.z*v1.z);
v2 = ssMath::Vector3(0.f, v1.z * invLen, -v1.y * invLen);
}
v3 = v1.crossProduct(v2);//Cross(v1, *v2);
}
inline void CoordinateSystem(const ssMath::Vector3 &v1, ssMath::Vector3 &v2, ssMath::Vector3 &v3) {
/* using stereographi projection parametrization */
/* notice it could be the singular point (0, -1, 0) */
if((v1.y + 1.f) < 1.0e-8)
v2 = ssMath::Vector3(0, 0, 0);
else
v2 = ssMath::Vector3((v1.y + 1.f) * (v1.y + 1.f) + v1.z * v1.z - v1.x * v1.x,
-2.f * v1.x * (v1.y + 1.f),
-2.f * v1.x * v1.z).hat();
v3 = v1.crossProduct(v2);//Cross(v1, *v2);
}
inline float Distance(const ssMath::Point3 &p1, const ssMath::Point3 &p2) {
return (p1 - p2).length();
}
inline float Clamp(const float &x, const float &minval, const float &maxval) {
if (x < minval) return minval;
if (x > maxval) return maxval;
return x;
}
inline float DistanceSquared(const ssMath::Point3 &p1, const ssMath::Point3 &p2) {
return (p1 - p2).squaredLength();
}
inline ssMath::Vector3 SphericalDirection(float sintheta, float costheta,
float phi) {
return ssMath::Vector3(sintheta * cosf(phi),
sintheta * sinf(phi), costheta);
}
inline ssMath::Vector3 SphericalDirection(float sintheta, float costheta,
float phi, const ssMath::Vector3 &x, const ssMath::Vector3 &y,
const ssMath::Vector3 &z) {
return sintheta * cosf(phi) * x +
sintheta * sinf(phi) * y + costheta * z;
}
inline float SphericalTheta(const ssMath::Vector3 &v) {
return acosf(v.z);
}
inline float SphericalPhi(const ssMath::Vector3 &v) {
return atan2f(v.y, v.x) + (float)M_PI;
}
#endif
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
bool cmp(const P &a, const P &b){
if (a.second == b.second){
return a.first < b.first;
} else {
return a.second < b.second;
}
}
int main()
{
int n, m;
cin >> n >> m;
vector<P> war(m);
rep(i, m){ cin >> war[i].first >> war[i].second;}
sort(war.begin(), war.end(), cmp);
// rep(i, m){
// cout << war[i].first << ":" << war[i].second << endl;
// }
int point = 0;
int ans = 0;
rep(i, m){
if (war[i].first >= point){
point = war[i].second;
ans++;
}
}
cout << ans << endl;
}
|
// Created on: 1993-04-07
// Created by: Laurent BUCHARD
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IntCurveSurface_ThePolyhedronToolOfHInter_HeaderFile
#define _IntCurveSurface_ThePolyhedronToolOfHInter_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Bnd_HArray1OfBox.hxx>
#include <Standard_Integer.hxx>
class Standard_OutOfRange;
class IntCurveSurface_ThePolyhedronOfHInter;
class Bnd_Box;
class gp_Pnt;
class IntCurveSurface_ThePolyhedronToolOfHInter
{
public:
DEFINE_STANDARD_ALLOC
//! Give the bounding box of the PolyhedronTool.
static const Bnd_Box& Bounding (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh);
//! Give the array of boxes. The box <n> corresponding
//! to the triangle <n>.
static const Handle(Bnd_HArray1OfBox)& ComponentsBounding (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh);
//! Give the tolerance of the polygon.
static Standard_Real DeflectionOverEstimation (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh);
//! Give the number of triangles in this polyhedral surface.
static Standard_Integer NbTriangles (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh);
//! Give the indices of the 3 points of the triangle of
//! address Index in the PolyhedronTool.
static void Triangle (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh, const Standard_Integer Index, Standard_Integer& P1, Standard_Integer& P2, Standard_Integer& P3);
//! Give the point of index i in the polyhedral surface.
static const gp_Pnt& Point (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh, const Standard_Integer Index);
//! Give the address Tricon of the triangle connexe to
//! the triangle of address Triang by the edge Pivot Pedge
//! and the third point of this connexe triangle. When we
//! are on a free edge TriCon==0 but the function return
//! the value of the triangle in the other side of Pivot
//! on the free edge. Used to turn around a vertex.
static Standard_Integer TriConnex (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh, const Standard_Integer Triang, const Standard_Integer Pivot, const Standard_Integer Pedge, Standard_Integer& TriCon, Standard_Integer& OtherP);
//! This method returns true if the edge based on points with
//! indices Index1 and Index2 represents a boundary edge. It is
//! necessary to take into account the boundary deflection for
//! this edge.
static Standard_Boolean IsOnBound (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh, const Standard_Integer Index1, const Standard_Integer Index2);
//! This method returns a border deflection of the polyhedron.
static Standard_Real GetBorderDeflection (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh);
Standard_EXPORT static void Dump (const IntCurveSurface_ThePolyhedronOfHInter& thePolyh);
protected:
private:
};
#define ThePolyhedron IntCurveSurface_ThePolyhedronOfHInter
#define ThePolyhedron_hxx <IntCurveSurface_ThePolyhedronOfHInter.hxx>
#define IntCurveSurface_PolyhedronTool IntCurveSurface_ThePolyhedronToolOfHInter
#define IntCurveSurface_PolyhedronTool_hxx <IntCurveSurface_ThePolyhedronToolOfHInter.hxx>
#include <IntCurveSurface_PolyhedronTool.lxx>
#undef ThePolyhedron
#undef ThePolyhedron_hxx
#undef IntCurveSurface_PolyhedronTool
#undef IntCurveSurface_PolyhedronTool_hxx
#endif // _IntCurveSurface_ThePolyhedronToolOfHInter_HeaderFile
|
#pragma once
#include "Epoch.h"
namespace ga
{
class GeneticAlgorithm
{
public:
GeneticAlgorithm(std::vector<size_t> config, int population_size);
virtual ~GeneticAlgorithm();
pEpoch epoch;
pEpoch Selection(double unchange_perc, double mutation_perc, double crossover_perc);
private:
int GetIndex(float val);
};
}
|
// Grouping Vanilla Mod specific items together because they have limited use in Epoch and should be called sporadically.
// DayZ Mod base building is not enabled in Epoch so there is no reason to spawn many of these items.
// skigoggles posted a list of unused (junk) items here: https://helpthedeadreturn.wordpress.com/2015/12/08/items-of-dubious-value-junk/
VanillaSurvival[] =
{
// {Loot_MAGAZINE, 1, equip_pvc_box}, // Unused
// {Loot_MAGAZINE, 1, ItemBookBible}, // Novelty church item - added directly to church loot
{Loot_MAGAZINE, 1, equip_rope}, //Used for upgrade tents
{Loot_MAGAZINE, 1, equip_rag}, // Used to craft bandages
{Loot_MAGAZINE, 1, equip_string}, // Used in multiple crafting recipes
{Loot_MAGAZINE, 1, equip_duct_tape}, // Repair broken stuff - craft a sling
{Loot_MAGAZINE, 1, equip_herb_box}, // Combine with ItemWaterBottle to make Herbal Tea
{Loot_MAGAZINE, 1, equip_nails}, // Combine with baseball bat, upgrade storage buildings
{Loot_MAGAZINE, 1, equip_hose} // Need this to siphon gas with fuel container - very useful
};
VanillaConstruction[] =
{
// {Loot_MAGAZINE, 2, equip_1inch_metal_pipe}, // Unused
// {Loot_MAGAZINE, 2, equip_2inch_metal_pipe}, // Unused
// {Loot_VEHICLE, 2, WeaponHolder_ItemPickaxeBroken},
// {Loot_MAGAZINE, 5, ItemStone}, // Epoch(Dayz Mod) fences, does not need to be spawned, can be harvested with pickaxes
// {Loot_WEAPON, 1, ItemDIY_wood}, // Vanilla base building
// {Loot_WEAPON, 1, ItemDIY_Gate} // Vanilla base building
// {Loot_MAGAZINE, 9, equip_metal_sheet_rusted}, // Unused
{Loot_MAGAZINE, 1, equip_scrapelectronics}, // Vehicle upgrade
{Loot_MAGAZINE, 1, equip_floppywire}, // Vehicle upgrade
{Loot_VEHICLE, 4, WeaponHolder_ItemPickaxe}, // Get ItemStone from rocks on the map for fence foundations.
{Loot_MAGAZINE, 9, ItemMetalSheet}, //Used for upgrade storage buildings and metal fences, vehicle upgrade
{Loot_MAGAZINE, 9, equip_metal_sheet}, //Used for upgrade storage buildings
{Loot_MAGAZINE, 4, ItemScrews}, //Used for upgrade storage buildings, vehicle upgrade
{Loot_MAGAZINE, 1, equip_hose}, // Need this to siphon gas with fuel container - very useful
{Loot_MAGAZINE, 1, equip_lever}, // Repair broken handles if dayz_toolBreaking enabled
{Loot_MAGAZINE, 1, ItemPlank}, // Used for upgrade storage buildings, craft a sling
{Loot_MAGAZINE, 1, equip_nails}, // Combine with baseball bat, upgrade storage buildings
{Loot_MAGAZINE, 1, equip_brick} // Used to sharpen tools if dayz_knifeDulling enabled
};
|
#pragma once
#include <bits/stdc++.h>
#include "expression.h"
class AbstractDispatcher;
class Var_decl {
public:
std::string type, id;
int *shapex;
int *shapey;
Expression *initial_value;
Var_decl(std::string, std::string, Expression *);
Var_decl(std::string, std::string, int, Expression *);
Var_decl(std::string, std::string, int, int, Expression *);
void Accept(AbstractDispatcher& dispatcher);
std::string getType();
~Var_decl();
};
class Multivar_decl {
public:
std::vector<Var_decl*> decls;
Multivar_decl(Var_decl*);
void add_var_decl(std::string, Expression*);
void add_var_decl(std::string, int, Expression*);
void add_var_decl(std::string, int, int, Expression*);
void Accept(AbstractDispatcher& dispatcher);
~Multivar_decl();
};
|
#include "RequestHandler.hpp"
#include "SysrepoListener.hpp"
#include <unistd.h>
int main(int, char **) {
SysrepoListener l;
l.listen();
RequestHandler handler(l);
while (true) {
pause();
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
bool compare(int x, int y)
{
return abs(x) < abs(y);
}
void findMinSum(int arr[], int n)
{
sort(arr, arr + n, compare);
int min = INT_MAX, x, y;
for (int i = 1; i < n; i++) {
// Absolute value shows how close it is to zero
if (abs(arr[i - 1] + arr[i]) <= min) {
// if found an even close value
// update min and store the index
min = abs(arr[i - 1] + arr[i]);
x = i - 1;
y = i;
}
}
cout << "The two elements whose sum is minimum are "
<< arr[x] << " and " << arr[y];
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
findMinSum(arr, n);
return 0;
}
|
// USBOutput.h
#ifndef _USBOUTPUT_h
#define _USBOUTPUT_h
#include "Config.h"
#include "Output.h"
#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif
#ifndef TEENSY
#include <HID-Project.h>
#endif
class USBOutput : public Output
{
private:
float lastPosition;
int lowestPosition = -1;
int highestPosition = -1;
int lowestActivePosition;
int highestActivePosition;
bool wasAirHeld;
void writeKey(uint16_t key);
void pressKey(uint16_t key);
void releaseKey(uint16_t key);
public:
void sendKeyEvent(int key, bool pressed, bool doublePressed) override;
void sendKeyEvent(int key, KeyState keyState) override;
void sendSensorEvent(float position) override;
void sendSensorEvent2(int sensor, bool unused) override;
void sendSensor(int sensor) override;
void sendUpdate() override;
USBOutput();
};
#endif
|
/*
* Copyright (c) 2016, The Regents of the University of California (Regents).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Please contact the author(s) of this library if you have any questions.
* Author: Erik Nelson ( eanelson@eecs.berkeley.edu )
*/
#ifndef RAYTRACING_LENS_RAYTRACER_H
#define RAYTRACING_LENS_RAYTRACER_H
#include <cmath>
#include <raytracing/scene.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
class LensRaytracer {
public:
LensRaytracer();
~LensRaytracer();
bool Initialize(int window_width, int window_height);
void Update(GLFWwindow* window, double elapsed, double total_elapsed);
void Render(double elapsed, double total_elapsed);
private:
// Rendering functions.
void LinkShader();
void ResetModel();
void ModelTransform();
void ViewTransform();
void ProjectionTransform();
void SetMaterial();
// Variables for tracking mouse position.
double mx0_, my0_, mx1_, my1_, mdx_, mdy_;
// Camera variables.
double vertical_angle_;
double horizontal_angle_;
// Transform variables.
glm::vec3 eye_, lookat_, up_;
// Window width and height.
int window_width_;
int window_height_;
// Shader handles.
GLuint model_matrix_;
GLuint view_matrix_;
GLuint proj_matrix_;
GLuint camera_pos_;
// Rendering options.
bool draw_axes_;
bool update_mouse_;
// A scene that we will add lenses to.
Scene scene_;
// Maximum viewing angle so that a user can't look straight up or down.
static constexpr double max_angle_ = 85.0 * M_PI / 180.0;
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Manuela Hutter (manuelah)
*/
#ifndef WEBSERVER_SERVICE_SETTINGS_DIALOG
#define WEBSERVER_SERVICE_SETTINGS_DIALOG
#ifdef GADGET_SUPPORT
#ifdef WEBSERVER_SUPPORT
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/quick/webserver/controller/WebServerServiceSettingsContext.h"
class WebServerServiceController;
/***********************************************************************************
** @class WebServerServiceSettingsDialog
** @brief Dialog to change the settings of a Unite service.
************************************************************************************/
class WebServerServiceSettingsDialog : public Dialog
{
public:
WebServerServiceSettingsDialog(WebServerServiceController * service_controller, WebServerServiceSettingsContext* service_context);
~WebServerServiceSettingsDialog();
//===== OpInputContext implementations =====
virtual Type GetType();
virtual BOOL OnInputAction(OpInputAction* action);
//===== Dialog implementations =====
virtual void OnInit();
virtual UINT32 OnOk();
//===== DesktopWindow implementations =====
virtual const char* GetWindowName();
//===== OpWidgetListener implementations ====
virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse);
protected:
virtual BOOL HasRequiredFieldsFilled();
BOOL HasSharedFolderFilled();
BOOL HasValidSharedFolder();
void SaveSettingsToContext();
protected:
enum ServiceSettingsError
{
NoError,
InvalidServiceNameInURL,
ServiceNameAlreadyInUse,
InvalidSharedFolderPath
};
WebServerServiceController * m_service_controller; //< the controller who performs service actions. not owned by this class
WebServerServiceSettingsContext * m_service_context; //< the context of the widget to be installed. owned by this class
void ShowError(ServiceSettingsError error);
void HideError();
private:
BOOL IsAbsolutePath(const OpStringC & shared_folder);
void UpdateURL(const OpStringC & service_address);
private:
OpWidget * m_incorrect_input_field;
};
#endif // WEBSERVER_SUPPORT
#endif // GADGET_SUPPORT
#endif // WEBSERVER_SERVICE_SETTINGS_DIALOG
|
#include <Poco/AutoPtr.h>
#include <Poco/Timespan.h>
#include <Poco/Util/XMLConfiguration.h>
#include <cppunit/extensions/HelperMacros.h>
#include "di/DependencyInjector.h"
#include "cppunit/BetterAssert.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
namespace BeeeOn {
class DependencyInjectorTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(DependencyInjectorTest);
CPPUNIT_TEST(testSimple);
CPPUNIT_TEST(testConstant);
CPPUNIT_TEST(testCastToBase);
CPPUNIT_TEST(testAlias);
CPPUNIT_TEST(testAliasLoop);
CPPUNIT_TEST(testAliasToAliasFails);
CPPUNIT_TEST(testExternalVariables);
CPPUNIT_TEST(testEarly);
CPPUNIT_TEST(testCircularDependency);
CPPUNIT_TEST_SUITE_END();
public:
DependencyInjectorTest():
m_config(new XMLConfiguration())
{
}
void setUp();
void tearDown();
void testSimple();
void testConstant();
void testCastToBase();
void testAlias();
void testAliasLoop();
void testAliasToAliasFails();
void testExternalVariables();
void testEarly();
void testCircularDependency();
private:
AutoPtr<XMLConfiguration> m_config;
};
CPPUNIT_TEST_SUITE_REGISTRATION(DependencyInjectorTest);
class FakeParent {
public:
virtual ~FakeParent()
{
}
};
class FakeObject : public FakeParent {
public:
FakeObject():
m_self(NULL),
m_index(0)
{
}
virtual ~FakeObject()
{
}
void setSelf(FakeObject *self)
{
m_self = self;
}
void setName(const string &name)
{
m_name = name;
}
void setOther(const string &other)
{
m_other = other;
}
void setIndex(int n)
{
m_index = n;
}
void setTimespan(const Timespan &time)
{
m_timespan = time;
}
void setList(const list<string> &l)
{
m_list.clear();
for (auto &s : l)
m_list.push_back(s);
}
void setMap(const map<string, string> &m)
{
m_map = m;
}
public:
FakeObject *m_self;
string m_name;
string m_other;
int m_index;
Timespan m_timespan;
vector<string> m_list;
map<string, string> m_map;
};
}
BEEEON_OBJECT_BEGIN(BeeeOn, FakeObject)
BEEEON_OBJECT_CASTABLE(FakeParent)
BEEEON_OBJECT_PROPERTY("self", &FakeObject::setSelf)
BEEEON_OBJECT_PROPERTY("name", &FakeObject::setName)
BEEEON_OBJECT_PROPERTY("index", &FakeObject::setIndex)
BEEEON_OBJECT_PROPERTY("other", &FakeObject::setOther)
BEEEON_OBJECT_PROPERTY("timespan", &FakeObject::setTimespan)
BEEEON_OBJECT_PROPERTY("list", &FakeObject::setList)
BEEEON_OBJECT_PROPERTY("map", &FakeObject::setMap)
BEEEON_OBJECT_END(BeeeOn, FakeObject)
namespace BeeeOn {
void DependencyInjectorTest::setUp()
{
m_config->loadEmpty("empty");
m_config->setString("constant[1][@name]", "label");
m_config->setString("constant[1][@text]", "Some text");
m_config->setString("constant[2][@name]", "sum");
m_config->setString("constant[2][@number]", "1 + ${FakeNumber}"); // 43
m_config->setString("constant[3][@name]", "time");
m_config->setString("constant[3][@time]", "${sum} s"); // 43000000
m_config->setString("constant[4][@name]", "enabled");
m_config->setString("constant[4][@yes-when]", "${sum} == 43"); // yes
m_config->setString("alias[1][@name]", "simpleAlias");
m_config->setString("alias[1][@ref]", "simple");
m_config->setString("alias[2][@name]", "secondAlias");
m_config->setString("alias[2][@ref]", "secondAlias");
m_config->setString("alias[3][@name]", "aliasToAlias");
m_config->setString("alias[3][@ref]", "simpleAlias");
m_config->setString("instance[1][@name]", "simple");
m_config->setString("instance[1][@class]", "BeeeOn::FakeObject");
m_config->setString("instance[1].set[1][@name]", "self");
m_config->setString("instance[1].set[1][@ref]", "simple");
m_config->setString("instance[1].set[2][@name]", "name");
m_config->setString("instance[1].set[2][@text]", "fake");
m_config->setString("instance[1].set[3][@name]", "index");
m_config->setString("instance[1].set[3][@number]", "5");
m_config->setString("instance[1].set[4][@name]", "list");
m_config->setString("instance[1].set[4][@list]", "a,b,c");
m_config->setString("instance[1].set[5][@name]", "map");
m_config->setString("instance[1].set[5].pair[1][@key]", "a");
m_config->setString("instance[1].set[5].pair[1][@text]", "1");
m_config->setString("instance[1].set[5].pair[2][@key]", "b");
m_config->setString("instance[1].set[5].pair[2][@text]", "2");
m_config->setString("instance[1].set[5].pair[3][@key]", "c");
m_config->setString("instance[1].set[5].pair[3][@text]", "3");
m_config->setString("instance[1].set[6][@name]", "timespan");
m_config->setString("instance[1].set[6][@time]", "5 s");
m_config->setString("instance[2][@name]", "variable");
m_config->setString("instance[2][@class]", "BeeeOn::FakeObject");
m_config->setString("instance[2].set[1][@name]", "name");
m_config->setString("instance[2].set[1][@text]", "${FakeText}");
m_config->setString("instance[2].set[2][@name]", "index");
m_config->setString("instance[2].set[2][@number]", "${FakeNumber} + 6");
m_config->setString("instance[2].set[3][@name]", "other");
m_config->setString("instance[2].set[3][@text]", "${NotExisting}");
m_config->setString("instance[3][@name]", "earlyInit0");
m_config->setString("instance[3][@class]", "BeeeOn::FakeObject");
m_config->setString("instance[3][@init]", "early");
m_config->setString("instance[3].set[1][@name]", "name");
m_config->setString("instance[3].set[1][@text]", "early0");
m_config->setString("instance[4][@name]", "earlyInit1");
m_config->setString("instance[4][@class]", "BeeeOn::FakeObject");
m_config->setString("instance[4][@init]", "early");
m_config->setString("instance[4].set[1][@name]", "name");
m_config->setString("instance[4].set[1][@text]", "early1");
m_config->setString("FakeText", "any string");
m_config->setInt("FakeNumber", 42);
if (Logger::get("Test").debug())
m_config->save(cerr);
}
void DependencyInjectorTest::tearDown()
{
}
/**
* Simple test of the most important properties of DependencyInjector.
* It creates an instance of the FakeObject and sets ref, text and
* number on it.
*/
void DependencyInjectorTest::testSimple()
{
DependencyInjector injector(m_config);
SharedPtr<FakeObject> fake = injector.find<FakeObject>("simple");
CPPUNIT_ASSERT(fake.isNull());
fake = injector.create<FakeObject>("simple");
CPPUNIT_ASSERT(!fake.isNull());
CPPUNIT_ASSERT(fake->m_self == fake);
CPPUNIT_ASSERT(fake->m_name.compare("fake") == 0);
CPPUNIT_ASSERT(fake->m_index == 5);
CPPUNIT_ASSERT(Timespan(5 * Timespan::SECONDS) == fake->m_timespan);
CPPUNIT_ASSERT_EQUAL(3, fake->m_list.size());
CPPUNIT_ASSERT_EQUAL("a", fake->m_list[0]);
CPPUNIT_ASSERT_EQUAL("b", fake->m_list[1]);
CPPUNIT_ASSERT_EQUAL("c", fake->m_list[2]);
CPPUNIT_ASSERT_EQUAL("1", fake->m_map["a"]);
CPPUNIT_ASSERT_EQUAL("2", fake->m_map["b"]);
CPPUNIT_ASSERT_EQUAL("3", fake->m_map["c"]);
}
void DependencyInjectorTest::testConstant()
{
DependencyInjector injector(m_config);
CPPUNIT_ASSERT(m_config->has("label"));
CPPUNIT_ASSERT_EQUAL("Some text", m_config->getString("label"));
CPPUNIT_ASSERT(m_config->has("sum"));
CPPUNIT_ASSERT_EQUAL("43", m_config->getString("sum"));
CPPUNIT_ASSERT(m_config->has("time"));
CPPUNIT_ASSERT_EQUAL("43000000", m_config->getString("time"));
CPPUNIT_ASSERT(m_config->has("enabled"));
CPPUNIT_ASSERT_EQUAL("yes", m_config->getString("enabled"));
}
void DependencyInjectorTest::testCastToBase()
{
DependencyInjector injector(m_config);
SharedPtr<FakeParent> parent;
parent = injector.find<FakeParent>("simple");
CPPUNIT_ASSERT(parent.isNull());
parent = injector.create<FakeParent>("simple");
CPPUNIT_ASSERT(!parent.isNull());
SharedPtr<FakeObject> object = parent.cast<FakeObject>();
CPPUNIT_ASSERT(!object.isNull());
}
/**
* Test refering to an alias pointing to an instance.
* An alias points to an instance so it just uses a different name.
*/
void DependencyInjectorTest::testAlias()
{
DependencyInjector injector(m_config);
SharedPtr<FakeObject> fakeAlias = injector.find<FakeObject>("simpleAlias");
CPPUNIT_ASSERT(fakeAlias.isNull());
fakeAlias = injector.create<FakeObject>("simpleAlias");
CPPUNIT_ASSERT(!fakeAlias.isNull());
SharedPtr<FakeObject> fake = injector.find<FakeObject>("simple");
CPPUNIT_ASSERT(!fake.isNull());
SharedPtr<FakeObject> fakeCreated = injector.create<FakeObject>("simple");
CPPUNIT_ASSERT(!fakeCreated.isNull());
CPPUNIT_ASSERT(fake == fakeAlias);
CPPUNIT_ASSERT(fakeAlias == fakeCreated);
}
/**
* Test alias points to itself throws an exception.
*/
void DependencyInjectorTest::testAliasLoop()
{
DependencyInjector injector(m_config);
CPPUNIT_ASSERT_THROW(injector.create<FakeObject>("secondAlias"),
IllegalStateException);
}
/**
* Alias cannot point to an alias.
* The NotFoundException is thrown because the DependencyInjector
* does not search the alias namespace recursively.
*/
void DependencyInjectorTest::testAliasToAliasFails()
{
DependencyInjector injector(m_config);
CPPUNIT_ASSERT_THROW(injector.create<FakeObject>("aliasToAlias"),
NotFoundException);
}
/**
* Test that ${VAR} constructs are expanded when constructing objects.
*/
void DependencyInjectorTest::testExternalVariables()
{
DependencyInjector injector(m_config);
SharedPtr<FakeObject> fake = injector.create<FakeObject>("variable");
CPPUNIT_ASSERT(!fake.isNull());
CPPUNIT_ASSERT(fake->m_name.compare("any string") == 0);
CPPUNIT_ASSERT(fake->m_other.compare("${NotExisting}") == 0);
CPPUNIT_ASSERT(fake->m_index == (42 + 6));
}
/**
* Test whether the init="early" instances are created automatically
* during DependencyInjector construction.
*/
void DependencyInjectorTest::testEarly()
{
DependencyInjector injector(m_config);
SharedPtr<FakeObject> early0 = injector.find<FakeObject>("earlyInit0");
CPPUNIT_ASSERT(!early0.isNull());
SharedPtr<FakeObject> early1 = injector.find<FakeObject>("earlyInit1");
CPPUNIT_ASSERT(!early1.isNull());
CPPUNIT_ASSERT(early0 != early1);
}
class CircularDependencyObject {
public:
CircularDependencyObject():
m_other(NULL),
m_destroyed(NULL)
{
}
virtual ~CircularDependencyObject()
{
if (m_destroyed)
*m_destroyed = true;
}
void setOther(SharedPtr<CircularDependencyObject> other)
{
m_other = other;
}
void cleanup()
{
m_other = NULL;
}
SharedPtr<CircularDependencyObject> m_other;
bool *m_destroyed;
};
}
BEEEON_OBJECT_BEGIN(BeeeOn, CircularDependencyObject)
BEEEON_OBJECT_PROPERTY("other", &CircularDependencyObject::setOther)
BEEEON_OBJECT_HOOK("cleanup", &CircularDependencyObject::cleanup)
BEEEON_OBJECT_END(BeeeOn, CircularDependencyObject)
namespace BeeeOn {
/**
* Show that two objects that holds a shared pointer to each other
* blocks each other's destruction. The solution is to avoid using
* shared pointer or to define the cleanup hook. The cleanup hook
* is used in this test to make sure that the objects do not block
* each other from destruction.
*/
void DependencyInjectorTest::testCircularDependency()
{
AutoPtr<XMLConfiguration> m_config(new XMLConfiguration);
m_config->loadEmpty("empty");
m_config->setString("instance[1][@name]", "first");
m_config->setString("instance[1][@class]", "BeeeOn::CircularDependencyObject");
m_config->setString("instance[1].set[1][@name]", "other");
m_config->setString("instance[1].set[1][@ref]", "second");
m_config->setString("instance[2][@name]", "second");
m_config->setString("instance[2][@class]", "BeeeOn::CircularDependencyObject");
m_config->setString("instance[2].set[1][@name]", "other");
m_config->setString("instance[2].set[1][@ref]", "first");
SharedPtr<CircularDependencyObject> first;
SharedPtr<CircularDependencyObject> second;
bool firstDestroyed = false;
bool secondDestroyed = false;
{
DependencyInjector injector(m_config);
first = injector.create<CircularDependencyObject>("first");
// 3 references: DependencyInjector, second, and this method
CPPUNIT_ASSERT_EQUAL(3, first.referenceCount());
second = injector.create<CircularDependencyObject>("second");
// 3 references: DependencyInjector, first, and this method
CPPUNIT_ASSERT_EQUAL(3, second.referenceCount());
first->m_destroyed = &firstDestroyed;
second->m_destroyed = &secondDestroyed;
}
CPPUNIT_ASSERT(!firstDestroyed);
CPPUNIT_ASSERT(!secondDestroyed);
// DependencyInjector has dropped references
// "cleanup" hook dropped the circular ones
CPPUNIT_ASSERT_EQUAL(1, first.referenceCount());
CPPUNIT_ASSERT_EQUAL(1, second.referenceCount());
first = NULL;
CPPUNIT_ASSERT(firstDestroyed);
second = NULL;
CPPUNIT_ASSERT(secondDestroyed);
}
}
|
#include <iostream>
#include <string>
#include <sstream>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
string envVar[50];
void parseEnv(char* inp)
{
string input(inp);
string delimiter = ":";
size_t pos = 0;
int i=0;
while((pos=input.find(delimiter)) != string::npos){
envVar[i++] = input.substr(0,pos);
input.erase(0,pos+delimiter.length());
}
}
int getLength(string array[])
{
int i = 0;
while(array[i] != "")
i++;
return i;
}
string findPath(string command)
{
for(int i = 0; i < getLength(envVar); i++)
{
if(access((envVar[i] + "/" + command).c_str(), F_OK) == 0)
return envVar[i] + "/" + command;
}
return "";
}
int main()
{
/*parseEnv(getenv("PATH"));
char *argv[] = { "ls", NULL };
execv(findPath("ls").c_str(), argv);
cout << "Starting..." << endl;
sleep(20);*/
sleep(10);
cout << "ending" << endl;
return 0;
}
|
#include <iostream>
using namespace std;
int p[11] = {0};
int c[11] = {0};
int calcScore(int score, int t, int goal) {
if (score >= goal) {
return t;
} else {
}
}
int main()
{
int d, g; cin >> d >> g;
for (int i = 1; i <= d; i++) {
cin >> p[i] >> c[i];
}
calcScore(0, 0, g);
return 0;
}
|
#ifndef _MSG_0X3F_PARTICLE_STC_H_
#define _MSG_0X3F_PARTICLE_STC_H_
#include "mcprotocol_base.h"
namespace MC
{
namespace Protocol
{
namespace Msg
{
class Particle : public BaseMessage
{
public:
Particle();
Particle(const String16& _particleName, float _x, float _y, float _z, float _offsetX, float _offsetY, float _offsetZ, float _particleSpeed, int32_t _numOfParticles);
size_t serialize(Buffer& _dst, size_t _offset);
size_t deserialize(const Buffer& _src, size_t _offset);
const String16& getParticleName() const;
float getX() const;
float getY() const;
float getZ() const;
float getOffsetX() const;
float getOffsetY() const;
float getOffsetZ() const;
float getParticleSpeed() const;
int32_t getNumOfParticles() const;
void setParticleName(const String16& _val);
void setX(float _val);
void setY(float _val);
void setZ(float _val);
void setOffsetX(float _val);
void setOffsetY(float _val);
void setOffsetZ(float _val);
void setParticleSpeed(float _val);
void setNumOfParticles(int32_t _val);
private:
String16 _pf_particleName;
float _pf_x;
float _pf_y;
float _pf_z;
float _pf_offsetX;
float _pf_offsetY;
float _pf_offsetZ;
float _pf_particleSpeed;
int32_t _pf_numOfParticles;
};
} // namespace Msg
} // namespace Protocol
} // namespace MC
#endif // _MSG_0X3F_PARTICLE_STC_H_
|
#include <signal.h>
#include <math.h>
#include "CDLReactor.h"
#include "Configure.h"
#include "ClientHandler.h"
#include "Despatch.h"
#include "Logger.h"
#include "Version.h"
#include "SvrConfig_.h"
#include "RedisAccess.h"
#include "ErrorMsg.h"
//#include "UdpManager.h"
#include "TrumptConnect.h"
#include "Packet.h"
#include "Util.h"
//#include "ErrorMessage.h"
#include "Protocol.h"
//#include "ErrorMessage.h"
#include "ServerManager.h"
#include "Packet.h"
#include "BackConnect.h"
RedisAccess *RedisConnector = NULL;
int initBackServerConnect()
{
SvrConfig_& svf = SvrConfig_::getInstance();
svf.initWithAddr(Configure::instance()->m_sUserAddr.c_str());
for (int i = 0; i<svf.getBackNodes(); ++i)
{
Nodes* nodes = svf.getNodes(i);
BackNodes* backnodes = new BackNodes(nodes->id);
for(int j=0; j<nodes->count();++j)
{
Node* node = nodes->get(j);
int ret = backnodes->addNode(node);
if(ret==-1)
{
_LOG_ERROR_("Nodes[%d] node[%d][%s:%d] Connected Fault\n", nodes->id, node->id, node->ip, node->port);
return -1;
}
else
_LOG_INFO_("Nodes[%d] node[%d][%s:%d] Connected OK\n", nodes->id, node->id, node->ip, node->port);
}
BackConnectManager::addNodes( nodes->id, backnodes );
}
_LOG_INFO_("Init Back Server Connect OK \n");
return 0;
}
int main(int argc, char* argv[])
{
srand((unsigned int)time(0));
CDLReactor::Instance()->Init();
Util::registerSignal();
if (!Configure::instance()->LoadConfig(argc, argv))
{
_LOG_ERROR_("Read Cfg fault,System exit\n");
return -1;
}
AddressInfo addrLog;
Util::parseAddress(Configure::instance()->m_sLogAddr.c_str(), addrLog);
CLogger::InitLogger(
Configure::instance()->m_nLogLevel,
Configure::instance()->GetGameTag(),
Configure::instance()->m_nServerId,
addrLog.ip,
addrLog.port
);
//ๅฏๅจServer
AllocServer server(Configure::instance()->m_sListenIp.c_str(), Configure::instance()->m_nPort);
if (CDLReactor::Instance()->RegistServer(&server) == -1)
return -1;
else
_LOG_DEBUG_("%s[%s.%s] have been started,listen port:%d...\n",Configure::instance()->ServerName(),VERSION,SUBVER,Configure::instance()->m_nPort);
RedisConnector = new RedisAccess();
bool ret = RedisConnector->connect(Configure::instance()->m_sServerRedisAddr[READ_REDIS_CONF].c_str());
if(!ret)
{
_LOG_ERROR_("Connect Redis Fault\n");
}
else
{
_LOG_INFO_("Connect Redis Success\n");
}
if(initBackServerConnect()<0)
{
_LOG_ERROR_("Init Back Server Connector fault,System exit\n");
return -1;
}
AddressInfo addrTrumpt;
Util::parseAddress(Configure::instance()->m_sTrumptAddr.c_str(), addrTrumpt);
if(TrumptConnect::getInstance()->connect(addrTrumpt.ip.c_str(), addrTrumpt.port)==-1)
{
_LOG_ERROR_("Connect TrumptServer Error,[%s:%d]\n", addrTrumpt.ip.c_str(), addrTrumpt.port);
return -1;
}
return CDLReactor::Instance()->RunEventLoop();
}
|
#pragma once
#include <bitstream.h>
#include <json/Document.h>
#include "RWLockable.h"
#include "Page.h"
#include "credb/defines.h"
namespace credb
{
namespace trusted
{
class BufferManager;
class ObjectEventHandle;
/**
* All objects are stored in blocks
* Blocks hold a single buffer that can easily be written to disk
* All writes are append-only
*/
class Block : public Page
{
public:
using int_type = uint32_t;
private:
bitstream m_data;
int_type m_file_pos;
struct header_t
{
bool sealed;
int_type num_files;
};
header_t& header()
{
return *reinterpret_cast<header_t*>(m_data.data());
}
const header_t& header() const
{
return *reinterpret_cast<const header_t*>(m_data.data());
}
size_t index_size() const;
const int_type* index() const
{
return reinterpret_cast<const int_type*>(m_data.data()+sizeof(header_t));
}
int_type* index()
{
return reinterpret_cast<int_type*>(m_data.data()+sizeof(header_t));
}
public:
Block(BufferManager &buffer, page_no_t page_no, bool init);
Block(BufferManager &buffer, page_no_t page_no, bitstream &bstream);
Block(const Block &other) = delete;
bitstream serialize() const override;
/**
* Get the amount of memory that is occupied by this datastructure
*
* @note this might contain memory that has been reserved but not written to yet
*/
size_t byte_size() const override;
/**
* Get the number of bytes that are actual stored data
*/
size_t get_data_size() const { return m_data.size(); }
bool is_pending() const;
event_index_t insert(json::Document &event);
ObjectEventHandle get_event(event_index_t pos) const;
block_id_t identifier() const;
void seal();
void unseal(); // for debug purpose
/**
* How many entries are stored in this block?
*/
int_type num_events() const
{
return m_file_pos+1;
}
};
} // namespace trusted
} // namespace credb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.