text
stringlengths 8
6.88M
|
|---|
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Schedule{
public:
Schedule(string Tit,string Loc,string Det,string Y,string M,string D,string BH,string BM,string EH,string EM)
:title{Tit},location{Loc},detail{Det},year{Y},month{M},day{D},begin{BH,BM},end{EH,EM}
{}
string year, month, day;
string begin [2];
string end [2];
string title,location, detail;
};
void AddSchedule(vector<Schedule>&);
void ModifySchedule(vector<Schedule>&);
void DeleteSchedule(vector<Schedule>&);
void ViewSchedule(vector<Schedule>);
void Viewing(Schedule);
void running();
void InputAndSplit(string*,char);
int main(){
running();
return 0;
}
void running(){
vector<Schedule> ScList;
cout<<endl;
while(true){
cout<<"Scheduler Program"<<endl;
cout<<"Mode 1: Add Schedule"<<endl;
cout<<"Mode 2: Modify Schedule"<<endl;
cout<<"Mode 3: Delete Schedule"<<endl;
cout<<"Mode 4: View Schedule"<<endl;
cout<<"Mode 5: Exit"<<endl<<endl;
cout<<"Select a Mode Number: ";
int a;
cin>>a;
if(a==1)
AddSchedule(ScList);
else if(a==2)
ModifySchedule(ScList);
else if(a==3)
DeleteSchedule(ScList);
else if(a==4)
ViewSchedule(ScList);
else if(a==5){
cout<<"Closing Scheduler"<<endl;
break;
}
}
}
void AddSchedule(vector<Schedule>& v){
string title, location, detail;
string date[3], begin[2],end[2];
cin.ignore();
cout<<"Add Schdule"<<endl;
cout<<"Enter Title: ";
getline(cin, title, '\n');
cout<<"Enter Date(YYYY-MM-DD): ";
InputAndSplit(date,'-');
cout<<"Enter Begin Time(HH:MM): ";
InputAndSplit(begin,':');
cout<<"Enter End Time(HH:MM): ";
InputAndSplit(end,':');
cout<<"Enter Location: ";
getline(cin, location, '\n');
cout<<"Enter Detail: ";
getline(cin, detail, '\n');
v.push_back(Schedule(title,location,detail,date[0],date[1],date[2],begin[0],begin[1],end[0],end[1]));
cout<<"A schedule has been added!"<<endl<<endl;
}
void ModifySchedule(vector<Schedule>& v){
string date[3],begin[2];
cin.ignore();
cout<<endl;
cout<<"Modify Schedule"<<endl;
cout<<"Enter the Schedule Date(YYYY-MM-DD): ";
InputAndSplit(date,'-');
cout<<"Enter th Begin Time(HH:MM): ";
InputAndSplit(begin,':');
for(Schedule& s:v){
if(s.year==date[0]&&s.month==date[1]&&s.day==date[2]&&
s.begin[0]==begin[0]&&s.begin[1]==begin[1]){
string title="", location="", detail="";
for(string& d:date)
d="";
for (string& b:begin)
b="";
string end[]={"",""};
cout<<endl<<"Current Schedule: "<<endl;
Viewing(s);
cout<<endl;
cout<<"Enter New Title (If not changing, press Enter): ";
getline(cin, title,'\n');
cout<<"Enter New Date(YYYY-MM-DD) (If unchanged, press Enter): ";
InputAndSplit(date,'-');
cout<<"Enter New Begin Time(HH:MM) (If unchanged, press Enter): ";
InputAndSplit(begin,':');
cout<<"Enter New End Time(HH:MM) (If unchanged, press Enter): ";
InputAndSplit(end,':');
cout<<"Enter New Location (If unchanged, press Enter): ";
getline(cin, location,'\n');
cout<<"Enter New Detail (If unchanged, press Enter): ";
getline(cin, detail, '\n');
if(title!="")
s.title=title;
if(date[0]!=""&&date[1]!=""&&date[2]!=""){
s.year=date[0];
s.month=date[1];
s.day=date[2];
}
if(begin[0]!=""&&begin[1]!=""){
s.begin[0]=begin[0];
s.begin[1]=begin[1];
}
if(end[0]!=""&&end[1]!=""){
s.end[0]=end[0];
s.end[1]=end[1];
}
if(location!="")
s.location=location;
if(detail!="")
s.detail=detail;
break;
}
}
cout<<endl;
}
void DeleteSchedule(vector<Schedule>& v){
string date[3],begin[2];
int index=0;
cin.ignore();
cout<<endl;
cout<<"Remove Schedule"<<endl;
cout<<"Enter the Schedule Date (YYYY-MM-DD): ";
InputAndSplit(date,'-');
cout<<"Enter the Begin Time (HH:MM): ";
InputAndSplit(begin,':');
for(Schedule& s:v){
if(s.year==date[0]&&s.month==date[1]&&s.day==date[2]&&
s.begin[0]==begin[0]&&s.begin[1]==begin[1]){
v.erase(v.begin()+index,v.begin()+index+1);
break;
}
index++;
}
cout<<"The schedule has been removed."<<endl<<endl;
}
void ViewSchedule(vector<Schedule> v){
int opt;
cout<<endl;
cout<<"Option 1: View All Schedules"<<endl;
cout<<"Option 2: View Schedules by Date"<<endl;
cout<<"Option 3: View Schedules by Title"<<endl;
cout<<"Enter an Option Number: ";
cin>>opt;
if(opt==1){ // view all schedules
cout<<endl<<"Displaying All Schedules"<<endl;
for(Schedule s:v){
Viewing(s);
cout<<endl;
}
}
else if(opt==2){ // view schedules by date
string date[3];
cin.ignore();
cout<<"Enter the date(YYYY-MM-DD): ";
InputAndSplit(date,'-');
cout<<endl<<"Displaying Schedules on "<<date[0]<<"-"<<date[1]<<"-"<<date[2]<<endl;
for(Schedule s:v){
if(s.year==date[0]&&s.month==date[1]&&s.day==date[2]){
Viewing(s);
cout<<endl;
}
}
}
else if(opt==3){ // view schedules by title
string title;
cout<<"Enter the title: ";
cin>>title;
cout<<endl<<"Displaying Schedules of "<<title<<endl;
for(Schedule s:v){
if(s.title.find(title)!=string::npos){
Viewing(s);
cout<<endl;
}
}
}
}
void InputAndSplit(string* arr,char delimiter){
string inp="";
getline(cin, inp,'\n');
for(int i=0,j=0;inp[i];i++){
if(inp[i]!=delimiter){
arr[j]+=inp[i];
}
else
j++;
}
}
void Viewing(Schedule s){
cout<<"Title: "<<s.title<<endl;
cout<<"Date: "<<s.year<<"-"<<s.month<<"-"<<s.day<<endl;
cout<<"Time: "<<s.begin[0]<<":"<<s.begin[1]<<"-"<<s.end[0]<<":"<<s.end[1]<<endl;
cout<<"Location: "<<s.location<<endl;
cout<<"Detail: "<<s.detail<<endl;
}
|
/**
* @file test/test_stop.cc
* @brief
* @version 0.1
* @date 2021-01-14
*
* @copyright Copyright (c) 2021 Tencent. All rights reserved.
*
*/
#include <cstdio>
#include "mini_sdp.h"
void printx(const char* buff, size_t len) {
for (int i = 0; i < len; i++) {
printf("%02X ", (uint8_t)buff[i]);
}
printf("\n");
}
int main(int argc, char ** argv) {
uint32_t ssrc = 0x12345678;
char pack[1200];
mini_sdp::StopStreamAttr attr;
attr.svrsig = "127.0.0.1:abcd:efgh";
attr.status = 0;
attr.seq = 0;
size_t len = mini_sdp::BuildStopStreamPacket(pack, 1200, attr);
printx(pack, len);
printf("check pack: %d\n", mini_sdp::IsMiniSdpStopPack(pack, len));
mini_sdp::StopStreamAttr attr2;
len = mini_sdp::LoadStopStreamPacket(pack, len, attr2);
printf("svrsig: %s\nstatus: %hu\nseq: %hu\n", attr2.svrsig.c_str(), attr2.status, attr2.seq);
}
|
#ifndef ICsquare_H_
#define ICsquare_H_
//Class for storing a square initial condition Riemann problem, where each quadrant has its own initial values
#include <math.h>
#include <iostream>
#include <cassert>
#include <vector>
#define PI 3.1415926535897932384626433832795
class ICsinus{
public:
ICsinus(float xmin = 0, float xmax = 1, float ymin = 0, float ymax = 1);
void setIC(cpu_ptr_2D &rho, cpu_ptr_2D &rho_u, cpu_ptr_2D &rho_v, cpu_ptr_2D &E);
void exactSolution(cpu_ptr_2D &rho, float time);
private:
float xmin, ymin, xmax, ymax;
float u,v,p,gamNew;
};
ICsinus::ICsinus(float xmin, float xmax, float ymin, float ymax):xmin(xmin),ymin(ymin), xmax(xmax), ymax(ymax), u(1.0), v(-0.5f), p(1.0f), gamNew(1.4f){}
void ICsinus::setIC(cpu_ptr_2D &rho, cpu_ptr_2D &rho_u, cpu_ptr_2D &rho_v, cpu_ptr_2D &E){
int nx = rho.get_nx();
int ny = rho.get_ny();
float dx = (xmax-xmin)/(float) nx;
float dy = (ymax-ymin)/(float) ny;
float x, y;
rho.xmin = xmin;
rho.xmax = xmax;
rho.ymin = ymin;
rho.ymax = ymax;
rho_u.xmin = xmin;
rho_u.xmin = xmin;
rho_u.xmax = xmax;
rho_u.ymin = ymin;
rho_v.ymax = ymax;
rho_v.xmax = xmax;
rho_v.ymin = ymin;
rho_v.ymax = ymax;
E.xmin = xmin;
E.xmax = xmax;
E.ymin = ymin;
E.ymax = ymax;
for (int i = 0; i < nx; i++){
x = dx*i+dx*0.5f + xmin ;
for (int j=0; j < ny; j++){
y = dy*j+dy*0.5f+ ymin;
rho(i,j) = 1.0f + 0.2f*sinf(PI*(x+y));
rho_u(i,j) = u*rho(i,j);
rho_v(i,j) = v*rho(i,j);
E(i,j) = p/(gamNew -1.0f) + 0.5f*rho(i,j)*(u*u + v*v);
}
}
}
void ICsinus::exactSolution(cpu_ptr_2D &rho, float time){
int nx = rho.get_nx();
int ny = rho.get_ny();
float dx = (xmax-xmin)/(float) nx;
float dy = (ymax-ymin)/(float) ny;
float x, y;
for (int i = 0; i < nx; i++){
x = dx*i + dx*0.5;
for (int j=0; j < ny; j++){
y = dy*j+dy*0.5;
rho(i,j) = 1.0f + 0.2f*sinf(PI*(x+y-time*(u+v)));
}
}
}
class ICsquare{
public:
// Constructor, assumes we are dealing with the positive unit sqaure, but this is optional
ICsquare(float x_intersect, float y_intersect,float gam, float xmin = 0,float xmax = 1,float ymin = 0,float ymax = 1);
void set_rho(float* rho);
void set_pressure(float* pressure);
void set_u(float* u);
void set_v(float* v);
void set_gam(float gam);
void setIC(cpu_ptr_2D &rho, cpu_ptr_2D &rho_u, cpu_ptr_2D &rho_v, cpu_ptr_2D &E);
private:
// Where quadrant division lines intersect
float x_intersect, y_intersect;
// Initial pressure and density
float pressure_array[4];
float rho_array[4];
// Initial speeds in x and y-directions
float u_array[4];
float v_array[4];
//x and y limits for the sqaure
float xmin, ymin, xmax, ymax, gam;
};
ICsquare::ICsquare(float x_intersect, float y_intersect, float gam, float xmin, float xmax, float ymin, float ymax):x_intersect(x_intersect), y_intersect(y_intersect),gam(gam),\
xmin(xmin),ymin(ymin), xmax(xmax), ymax(ymax){
}
void ICsquare::set_gam(float gam){
gam = gam;
}
void ICsquare::set_rho(float* rho){
for (int i=0; i<4; i++)
rho_array[i] = rho[i];
}
void ICsquare::set_u(float* u){
for (int i=0; i<4; i++)
u_array[i] = u[i];
}
void ICsquare::set_v(float* v){
for (int i=0; i<4; i++)
v_array[i] = v[i];
}
void ICsquare::set_pressure(float* pressure){
for (int i=0; i<4; i++)
pressure_array[i] = pressure[i];
}
void ICsquare::setIC(cpu_ptr_2D &rho, cpu_ptr_2D &rho_u, cpu_ptr_2D &rho_v, cpu_ptr_2D &E){
int nx = rho.get_nx();
int ny = rho.get_ny();
float dx = (xmax-xmin)/(float) nx;
float dy = (ymax-ymin)/(float) ny;
rho.xmin = xmin;
rho.xmax = xmax;
rho.ymin = ymin;
rho.ymax = ymax;
rho_u.xmin = xmin;
rho_u.xmin = xmin;
rho_u.xmax = xmax;
rho_u.ymin = ymin;
rho_v.ymax = ymax;
rho_v.xmax = xmax;
rho_v.ymin = ymin;
rho_v.ymax = ymax;
E.xmin = xmin;
E.xmax = xmax;
E.ymin = ymin;
E.ymax = ymax;
float x, y;
int quad;
for (int i = 0; i < nx; i++){
x = dx*i;
for (int j=0; j < ny; j++){
y = dy*j;
// Quadrant 1
if (x >= x_intersect && y >= y_intersect)
quad = 0;
// Quadrant 2
else if (x < x_intersect && y >= y_intersect)
quad = 1;
// Quadrant 3
else if ( x < x_intersect && y < y_intersect)
quad = 2;
// Quadrant 4
else
quad = 3;
// Set initial values
rho(i,j) = rho_array[quad];
//printf("%.3f ", rho(i,j));
rho_u(i,j) = rho_array[quad]*u_array[quad];
rho_v(i,j) = rho_array[quad]*v_array[quad];
E(i,j) = pressure_array[quad]/(gam -1.0) + 0.5*rho_array[quad]*(u_array[quad]*u_array[quad] + v_array[quad]*v_array[quad]);
}
}
}
#endif
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <boost/utility/value_init.hpp>
#include <CryptoNote.h>
#include "CryptoNoteBasic.h"
#include "CryptoNoteSerialization.h"
#include "Serialization/BinaryOutputStreamSerializer.h"
#include "Serialization/BinaryInputStreamSerializer.h"
namespace logging {
class ILogger;
}
namespace cn {
bool parseAndValidateTransactionFromBinaryArray(const BinaryArray& transactionBinaryArray, Transaction& transaction, crypto::Hash& transactionHash, crypto::Hash& transactionPrefixHash);
struct TransactionSourceEntry {
typedef std::pair<uint32_t, crypto::PublicKey> OutputEntry;
std::vector<OutputEntry> outputs; //index + key
size_t realOutput; //index in outputs vector of real output_entry
crypto::PublicKey realTransactionPublicKey; //incoming real tx public key
size_t realOutputIndexInTransaction; //index in transaction outputs vector
uint64_t amount; //money
};
struct TransactionDestinationEntry {
uint64_t amount; //money
AccountPublicAddress addr; //destination address
TransactionDestinationEntry() : amount(0), addr(boost::value_initialized<AccountPublicAddress>()) {}
TransactionDestinationEntry(uint64_t amount, const AccountPublicAddress &addr) : amount(amount), addr(addr) {}
};
struct tx_message_entry
{
std::string message;
bool encrypt;
AccountPublicAddress addr;
};
bool generateDeterministicTransactionKeys(const crypto::Hash &inputsHash, const crypto::SecretKey &viewSecretKey, KeyPair &generatedKeys);
bool generateDeterministicTransactionKeys(const Transaction &tx, const crypto::SecretKey &viewSecretKey, KeyPair &generatedKeys);
bool constructTransaction(
const AccountKeys& senderAccountKeys,
const std::vector<TransactionSourceEntry>& sources,
const std::vector<TransactionDestinationEntry>& destinations,
const std::vector<tx_message_entry>& messages,
uint64_t ttl, std::vector<uint8_t> extra, Transaction& transaction, uint64_t unlock_time, logging::ILogger& log, crypto::SecretKey& transactionSK);
inline bool constructTransaction(
const AccountKeys& sender_account_keys,
const std::vector<TransactionSourceEntry>& sources,
const std::vector<TransactionDestinationEntry>& destinations,
std::vector<uint8_t> extra, Transaction& tx, uint64_t unlock_time, logging::ILogger& log, crypto::SecretKey& transactionSK) {
return constructTransaction(sender_account_keys, sources, destinations, std::vector<tx_message_entry>(), 0, extra, tx, unlock_time, log, transactionSK);
}
bool is_out_to_acc(const AccountKeys& acc, const KeyOutput& out_key, const crypto::PublicKey& tx_pub_key, size_t keyIndex);
bool is_out_to_acc(const AccountKeys& acc, const KeyOutput& out_key, const crypto::KeyDerivation& derivation, size_t keyIndex);
bool lookup_acc_outs(const AccountKeys& acc, const Transaction& tx, const crypto::PublicKey& tx_pub_key, std::vector<size_t>& outs, uint64_t& money_transfered);
bool lookup_acc_outs(const AccountKeys& acc, const Transaction& tx, std::vector<size_t>& outs, uint64_t& money_transfered);
bool generate_key_image_helper(const AccountKeys& ack, const crypto::PublicKey& tx_public_key, size_t real_output_index, KeyPair& in_ephemeral, crypto::KeyImage& ki);
std::string short_hash_str(const crypto::Hash& h);
bool get_block_hashing_blob(const Block& b, BinaryArray& blob);
bool get_aux_block_header_hash(const Block& b, crypto::Hash& res);
bool get_block_hash(const Block& b, crypto::Hash& res);
crypto::Hash get_block_hash(const Block& b);
bool get_block_longhash(crypto::cn_context &context, const Block& b, crypto::Hash& res);
bool get_inputs_money_amount(const Transaction& tx, uint64_t& money);
uint64_t get_outs_money_amount(const Transaction& tx);
bool check_inputs_types_supported(const TransactionPrefix& tx);
bool check_outs_valid(const TransactionPrefix& tx, std::string* error = 0);
bool checkMultisignatureInputsDiff(const TransactionPrefix& tx);
bool check_money_overflow(const TransactionPrefix& tx);
bool check_outs_overflow(const TransactionPrefix& tx);
bool check_inputs_overflow(const TransactionPrefix& tx);
uint32_t get_block_height(const Block& b);
std::vector<uint32_t> relative_output_offsets_to_absolute(const std::vector<uint32_t>& off);
std::vector<uint32_t> absolute_output_offsets_to_relative(const std::vector<uint32_t>& off);
// 62387455827 -> 455827 + 7000000 + 80000000 + 300000000 + 2000000000 + 60000000000, where 455827 <= dust_threshold
template<typename chunk_handler_t, typename dust_handler_t>
void decompose_amount_into_digits(uint64_t amount, uint64_t dust_threshold, const chunk_handler_t& chunk_handler, const dust_handler_t& dust_handler) {
if (0 == amount) {
return;
}
bool is_dust_handled = false;
uint64_t dust = 0;
uint64_t order = 1;
while (0 != amount) {
uint64_t chunk = (amount % 10) * order;
amount /= 10;
order *= 10;
if (dust + chunk <= dust_threshold) {
dust += chunk;
} else {
if (!is_dust_handled && 0 != dust) {
dust_handler(dust);
is_dust_handled = true;
}
if (0 != chunk) {
chunk_handler(chunk);
}
}
}
if (!is_dust_handled && 0 != dust) {
dust_handler(dust);
}
}
void get_tx_tree_hash(const std::vector<crypto::Hash>& tx_hashes, crypto::Hash& h);
crypto::Hash get_tx_tree_hash(const std::vector<crypto::Hash>& tx_hashes);
crypto::Hash get_tx_tree_hash(const Block& b);
bool is_valid_decomposed_amount(uint64_t amount);
}
|
/*
* contour_format.cpp
*
* Created on: 8 Jul 2012
* Author: sashman
*
* File to translate the heightmap into a grid of tile types found in TILE_CASE (terrian_generator.hpp) enum
*/
#include "terrain_generator.hpp"
extern int crop_height;
extern int crop_width;
extern int** tmap;
int sub_map_h = 0;
int sub_map_w = 0;
int max = 0;
int threshhold_increment = 40;
int threshold = 0;
int nearest_round = 5;
extern int sea_level;
int** cmap;
int convex_case_ids[] =
{ 1 };
int straight_case_ids[] =
{ 2, 3, 6, 7 };
int concave_case_ids[] =
{ 10, 11, 14, 15, 42, 43, 46, 47 };
int bad_case_ids[] =
{ 12, 17, 34, 48, 68, 130, 136 };
std::set<int> convex_set(convex_case_ids, convex_case_ids + 1);
std::set<int> straight_set(straight_case_ids, straight_case_ids + 4);
std::set<int> concave_set(concave_case_ids, concave_case_ids + 8);
std::set<int> bad_set(bad_case_ids, bad_case_ids + 7);
void round_tmap()
{
for (int i = 0; i < crop_height; ++i)
{
for (int j = 0; j < crop_width; ++j)
{
//nearest 10
//tmap[i][j] = (int) (tmap[i][j] / 10 * 10);
tmap[i][j] = (int) (tmap[i][j] / nearest_round * nearest_round);
}
}
}
bool above_threshold(int height)
{
return height > threshold;
}
/*
void print_neighbour_case_id(char case_id)
{
//read bits in
std::vector<char> n_case(8);
for (int i = n_case.size() - 1; i >= 0; --i)
{
char t = (char)((case_id >> i) & 1);
std::cout<<(int)t<<std::endl;
n_case.push_back(t);
}
//print out
int c = 0;
for (std::vector<char>::iterator it = n_case.begin(); it != n_case.end();
it++)
{
//skip middle
if(c == 4){
c++;
std::cout<<"x";
} else {
std::cout<< (int)*it ;
}
if(c == 2 || c == 6 || c == 8) std::cout<<std::endl;
c++;
}
}
*/
//-1 invalid
char get_neighbour_case(std::vector<int> *n_case, bool verbose)
{
if (n_case->size() != 8
// && n_case->size() != 5 &&
// n_case->size() != 3
)
{
return -1;
}
unsigned char case_id = 0;
for (int i = n_case->size() - 1; i >= 0; --i)
{
case_id |= above_threshold((int) n_case->at(i)) ? 1 << i : 0;
}
if (case_id == 255 || case_id == 0)
return 0;
if (verbose)
std::cout << (int) case_id << std::endl;
if (verbose)
{
for (unsigned int i = 0; i < n_case->size(); ++i)
{
if (i == 4)
std::cout << " ";
above_threshold((int) n_case->at(i)) ?
std::cout << ". " : std::cout << "~ ";
if (i == 2 || i == 4)
std::cout << std::endl;
}
}
if (verbose)
std::cout << std::endl;
return case_id;
}
void reset_grass()
{
for (int i = 0; i < crop_height; ++i)
{
for (int j = 0; j < crop_width; ++j)
{
if (cmap[i][j] == HIGH_GRASS)
cmap[i][j] = GRASS;
}
}
}
/**
*
* int t - current threshold
*
*/
void fill_one_tile_gaps(int t)
{
//horizontal gaps
for (int i = 0; i < crop_height; ++i)
{
for (int j = 0; j < crop_width - 3; ++j)
{
if (!above_threshold(tmap[i][j + 1]) && above_threshold(tmap[i][j])
&& above_threshold(tmap[i][j + 2]))
{
//if (tmap[i][j + 1] <= t && tmap[i][j] > t && tmap[i][j + 2] > t) {
tmap[i][j + 1] = t + nearest_round;
}
}
}
//vertical gaps
for (int i = 0; i < crop_height - 3; ++i)
{
for (int j = 0; j < crop_width; ++j)
{
if (!above_threshold(tmap[i + 1][j]) && above_threshold(tmap[i][j])
&& above_threshold(tmap[i + 2][j]))
{
tmap[i + 1][j] = t + nearest_round;
}
}
}
//diagonal gaps
for (int i = 0; i < crop_height - 3; ++i)
{
for (int j = 0; j < crop_width - 3; ++j)
{
//2 rotational cases
/*
*
* ^ v v
* v v v
* v v ^
*
* and
*
* v v ^
* v v v
* ^ v v
*
*/
if ((above_threshold(tmap[i][j])
&& !above_threshold(tmap[i + 1][j + 1])
&& above_threshold(tmap[i + 2][j + 2]))
|| (above_threshold(tmap[i + 2][j])
&& !above_threshold(tmap[i + 1][j + 1])
&& above_threshold(tmap[i][j + 2])))
{
tmap[i + 1][j + 1] = t + nearest_round;
}
}
}
}
/**
*
* int t - current threshold
* int n - size of gap to fill in
*
*/
void fill_n_tile_gaps(int t, int n)
{
//horizontal gaps
for (int i = 0; i < crop_height; ++i)
{
for (int j = 0; j < crop_width - (n + 2); ++j)
{
//if both sides are above threshold
if (above_threshold(tmap[i][j])
&& above_threshold(tmap[i][j + n + 1]))
{
//check the in between tiles
bool gap = false;
for (int k = j + 1; k < j + n + 1; ++k)
{
//detect gap
if (!gap && !above_threshold(tmap[i][k]))
gap = true;
//if gap detected, fill in tiles
if (gap)
{
tmap[i][k] = t + nearest_round;
}
}
}
}
}
//vertical gaps
for (int i = 0; i < crop_height - (n + 2); ++i)
{
for (int j = 0; j < crop_width; ++j)
{
//if both sides are above threshold
if (above_threshold(tmap[i][j])
&& above_threshold(tmap[i + n + 1][j]))
{
//check the in between tiles
bool gap = false;
for (int k = i + 1; k < i + n + 1; ++k)
{
//detect gap
if (!gap && !above_threshold(tmap[k][j]))
gap = true;
//if gap detected, fill in tiles
if (gap)
{
tmap[k][j] = t + nearest_round;
}
}
}
}
}
/*
* Not filling diagonals
*
//diagonal gaps
for (int i = 0; i < crop_height - (n + 2); ++i) {
for (int j = 0; j < crop_width - (n + 2); ++j) {
//n=2 examples
// *
// *
// * ^ v v v
// * v v v v
// * v v v v
// * v v v ^
// *
// * and
// *
// * v v v ^
// * v v v v
// * v v v v
// * ^ v v v
// *
// *
//check edges
if (above_threshold(tmap[i][j]) && above_threshold(tmap[i + n + 1][j + n + 1])) {
bool gap = false;
std::cout<<"\t"<< "x " << j << " y "<< i <<
" by "<< "x " << j+n+1 << " y "<< i+n+1 <<std::endl;
for (int k = j + 1; k < j + n + 1; ++k) {
std::cout<<"\t"<< "k=" << k <<std::endl;
//detect gap
if (!gap && !above_threshold(tmap[k][k]))
gap = true;
//if gap detected, fill in tiles
if (gap) {
tmap[k][k] = t + nearest_round;
}
}
}
if (above_threshold(tmap[i][j + n + 1])
&& above_threshold(tmap[i + n + 1][j])) {
bool gap = false;
for (int k = j + 1; k < j + n; ++k) {
//detect gap
if (!gap && !above_threshold(tmap[n - k + 1][k]))
gap = true;
//if gap detected, fill in tiles
if (gap) {
tmap[n - k + 1][k] = t + nearest_round;
}
}
}
}
}
*/
}
void verify_one_tile_gaps(int t, bool verbose)
{
//horizontal gaps
for (int i = 0; i < crop_height; ++i)
{
for (int j = 0; j < crop_width - 3; ++j)
{
if (!above_threshold(tmap[i][j + 1]) && above_threshold(tmap[i][j])
&& above_threshold(tmap[i][j + 2]))
{
if (verbose)
{
std::cout << "===" << j << ", " << i
<< " horizontal gap (threshold = " << t << ")"
<< std::endl;
std::cout << "===" << "\t-----" << std::endl;
for (int k = (i) - 2; k < (i) + 3; k++)
{
std::cout << "===";
for (int l = (j + 1) - 2; l < (j + 1) + 3; l++)
{
if ((k >= 0 && k < crop_height)
&& (l >= 0 && l < crop_width))
{
above_threshold(tmap[k][l]) ?
std::cout << " ." : std::cout << " ~";
}
}
std::cout << std::endl;
}
std::cout << "===" << "\t-----" << std::endl;
}
}
}
}
//vertical gaps
for (int i = 0; i < crop_height - 3; ++i)
{
for (int j = 0; j < crop_width; ++j)
{
if (!above_threshold(tmap[i + 1][j]) && above_threshold(tmap[i][j])
&& above_threshold(tmap[i + 2][j]))
{
if (verbose)
{
std::cout << "===" << j << ", " << i
<< " vertical gap (threshold = " << t << ")"
<< std::endl;
std::cout << "===" << "\t-----" << std::endl;
for (int k = (i + 1) - 2; k < (i + 1) + 3; k++)
{
std::cout << "===";
for (int l = (j) - 2; l < (j) + 3; l++)
{
if ((k >= 0 && k < crop_height)
&& (l >= 0 && l < crop_width))
{
above_threshold(tmap[k][l]) ?
std::cout << " ." : std::cout << " ~";
}
}
std::cout << std::endl;
}
std::cout << "===" << "\t-----" << std::endl;
}
}
}
}
}
unsigned char rotate_case(std::vector<int> *n_case, bool verbose)
{
int t5 = (*n_case)[5];
int t3 = (*n_case)[3];
(*n_case)[5] = (*n_case)[0];
(*n_case)[3] = (*n_case)[1];
(*n_case)[0] = (*n_case)[2];
(*n_case)[1] = (*n_case)[4];
(*n_case)[2] = (*n_case)[7];
(*n_case)[4] = (*n_case)[6];
(*n_case)[7] = t5; //(*n_case)[5];
(*n_case)[6] = t3;
return get_neighbour_case(n_case, verbose);
}
int undo_rotation(int id, int r, bool verbose)
{
TILE_CASE convex_cliff_start = CLIFF_NW_SN;
TILE_CASE straight_cliff_start = CLIFF_WE_SN;
TILE_CASE concave_cliff_start = CLIFF_SE_SN;
if (r > 3)
{
if (verbose)
std::cout << "***BAD ROTATE r = " << r << std::endl;
return -1;
}
if (convex_set.count(id) > 0)
return convex_cliff_start + r;
else if (straight_set.count(id) > 0)
return straight_cliff_start + r;
else if (concave_set.count(id) > 0)
return concave_cliff_start + r;
else
{
if (verbose)
std::cout << "***BAD ROTATE id = " << id << std::endl;
return -1;
}
}
//return coords to go back to
std::pair<int, int> fix_tile_case(int i, int j, std::vector<int> *n_case,
int id)
{
bool found = false;
std::pair<int, int> backtrack(i, j);
//Hardcoded gap fixes
if (bad_set.count(id) > 0)
{
found = true;
tmap[i][j + 1] = threshold + nearest_round;
backtrack.first = i - 1;
backtrack.second = j - 1;
}
//find gap between tiles
if (above_threshold(tmap[i - 1][j + 1]) && !above_threshold(tmap[i][j + 1])
&& above_threshold(tmap[i + 1][j + 1]))
{
found = true;
tmap[i][j + 1] = threshold + nearest_round;
}
if (above_threshold(tmap[i + 1][j - 1]) && !above_threshold(tmap[i + 1][j])
&& above_threshold(tmap[i + 1][j + 1]))
{
found = true;
tmap[i + 1][j] = threshold + nearest_round;
}
if (above_threshold(tmap[i - 1][j]) && !above_threshold(tmap[i][j])
&& above_threshold(tmap[i + 1][j]))
{
found = true;
tmap[i][j] = threshold + nearest_round;
backtrack.first = i - 1;
backtrack.second = j - 1;
}
if (above_threshold(tmap[i][j - 1]) && !above_threshold(tmap[i][j])
&& above_threshold(tmap[i][j + 1]))
{
found = true;
tmap[i][j] = threshold + nearest_round;
backtrack.first = i - 1;
backtrack.second = j - 1;
}
if (above_threshold(tmap[i - 1][j - 1]) && !above_threshold(tmap[i][j - 1])
&& above_threshold(tmap[i + 1][j - 1]))
{
found = true;
tmap[i][j - 1] = threshold + nearest_round;
backtrack.first = i - 1;
backtrack.second = j - 2;
}
if (above_threshold(tmap[i - 1][j - 1]) && !above_threshold(tmap[i - 1][j])
&& above_threshold(tmap[i - 1][j + 1]))
{
found = true;
tmap[i - 1][j] = threshold + nearest_round;
backtrack.first = i - 2;
backtrack.second = j - 1;
}
if (!found)
{
for (int k = i - 1; k <= i + 1; ++k)
{
for (int l = j - 1; l <= j + 1; ++l)
{
if (k == i && j == l)
std::cout << " ";
else
above_threshold(tmap[k][l]) ?
std::cout << ". " : std::cout << "~ ";
}
std::cout << std::endl;
}
std::cout << std::endl;
exit(0);
}
// std::cout << "Going back to " << backtrack.second << "," << backtrack.first
// << std::endl;
return backtrack;
}
void set_contour_values(bool verbose)
{
for (int i = 0; i < crop_height; i += 1)
{
for (int j = 0; j < crop_width; j += 1)
{
if (above_threshold(tmap[i][j]))
{
cmap[i][j] = GRASS;
}
else
{
std::vector<int> *n_case = new std::vector<int>;
for (int k = i - 1; k <= i + 1; ++k)
{
for (int l = j - 1; l <= j + 1; ++l)
{
if ((k >= 0 && k < crop_height)
&& (l >= 0 && l < crop_width)
&& (k != i || l != j))
{
//std::cout << i << ","<< j << " pushing back " << tmap[k][l] << " " << k << ","<< l << std::endl;
//std::cout << l << "," << k << ":::";
n_case->push_back(tmap[k][l]);
}
}
}
unsigned char id = get_neighbour_case(n_case, verbose);
if (id != 0 && id != 255 && id != -1)
{
if (verbose)
std::cout << "Looking at " << j << "," << i
<< std::endl;
if (verbose)
std::cout << "---------" << std::endl;
int r = 0;
/*
while (id != 1 // convex cliff
&& id != 2 && id != 3 && id != 6 && id != 7 // straight cliff
&& id != 10 && id != 11 && id != 15 && id != 43
&& id != 47)
*/
while (convex_set.count(id) == 0 && // convex cliffs
straight_set.count(id) == 0 && // straight cliffs
concave_set.count(id) == 0) // concave cliffs
{
if (verbose)
std::cout << (int) id << " shifting " << std::endl;
id = rotate_case(n_case, verbose);
r++;
if (r > 3)
{
if (verbose)
{
std::cout << "***BAD CASE! id = " << (int) id
<< " on threshold = " << threshold
<< std::endl;
std::cout << "Fixing case " << (int) id
<< std::endl;
//#define EXIT_ON_BAD_CASE
#ifdef EXIT_ON_BAD_CASE
std::cout << "EXITING!" << std::endl;
exit(0);
#endif
}
std::pair<int, int> backtrack = fix_tile_case(i, j,
n_case, id);
i = backtrack.first;
j = backtrack.second;
break;
}
}
if (verbose)
{
std::cout << "-> " << (int) id << std::endl;
if (convex_set.count(id) != 0)
{
std::cout << "Part of convex set" << std::endl;
for (std::set<int>::iterator iter =
convex_set.begin();
iter != convex_set.end(); ++iter)
std::cout << *iter << " ";
std::cout << std::endl;
}
if (straight_set.count(id) != 0)
{
std::cout << "Part of straight set " << std::endl;
for (std::set<int>::iterator iter =
straight_set.begin();
iter != straight_set.end(); ++iter)
std::cout << *iter << " ";
std::cout << std::endl;
}
if (concave_set.count(id) != 0)
{
std::cout << "Part of concave set " << std::endl;
for (std::set<int>::iterator iter =
concave_set.begin();
iter != concave_set.end(); ++iter)
std::cout << *iter << " ";
std::cout << std::endl;
}
}
cmap[i][j] = undo_rotation(id, r, verbose);
//add random gaps in straights
//old way
// if (rand() % 10 == 0) cmap[i][j] = GRASS;
//for a series of 3 straights
//1 in x chance to create a gap
int chance = 10;
//3 in a row indicies must be measured backwards
if (cmap[i][j] >= CLIFF_WE_SN && cmap[i][j] <= CLIFF_NS_EW)
{
switch (cmap[i][j])
{
case CLIFF_WE_SN:
if (cmap[i][j - 1] == CLIFF_WE_SN
&& cmap[i][j - 2] == CLIFF_WE_SN
&& (rand() % chance == 0))
{
cmap[i][j - 2] = CLIFF_NW_SN;
cmap[i][j - 1] = GRASS;
cmap[i][j] = CLIFF_NE_SN;
}
break;
case CLIFF_WE_NS:
if (cmap[i][j - 1] == CLIFF_WE_NS
&& cmap[i][j - 2] == CLIFF_WE_NS
&& (rand() % chance == 0))
{
cmap[i][j - 2] = CLIFF_SW_NS;
cmap[i][j - 1] = GRASS;
cmap[i][j] = CLIFF_SE_NS;
}
break;
case CLIFF_NS_WE:
if (cmap[i-1][j] == CLIFF_NS_WE
&& cmap[i-2][j] == CLIFF_NS_WE
&& (rand() % chance == 0))
{
cmap[i-2][j] = CLIFF_NE_SN;
cmap[i-1][j] = GRASS;
cmap[i][j] = CLIFF_SE_NS;
}
break;
case CLIFF_NS_EW:
if (cmap[i-1][j] == CLIFF_NS_EW
&& cmap[i-2][j] == CLIFF_NS_EW
&& (rand() % chance == 0))
{
cmap[i-2][j] = CLIFF_NW_SN;
cmap[i-1][j] = GRASS;
cmap[i][j] = CLIFF_SW_NS;
}
break;
default:
break;
}
}
// cmap[i][j] = WATER;
if (cmap[i][j] == -1)
{
if (point_above_sealevel(j, i))
cmap[i][j] = GRASS;
else
cmap[i][j] = WATER;
}
}
else
{
if (cmap[i][j] == -1)
{
if (point_above_sealevel(j, i))
cmap[i][j] = GRASS;
else
cmap[i][j] = WATER;
}
}
}
}
}
}
void contour_map(int _sub_map_h, int _sub_map_w, bool verbose)
{
sub_map_h = _sub_map_h;
sub_map_w = _sub_map_w;
round_tmap();
max = tmap[0][0];
//set up contour map array
cmap = new int*[crop_height];
for (int i = 0; i < crop_height; ++i)
{
cmap[i] = new int[crop_width];
for (int j = 0; j < crop_width; ++j)
{
cmap[i][j] = -1;
}
}
for (int i = 0; i < crop_height; ++i)
{
for (int j = 0; j < crop_width; ++j)
{
if (tmap[i][j] > max)
max = tmap[i][j];
}
}
std::cout << "\n" << std::endl;
for (threshold = sea_level; threshold < max; threshold +=
threshhold_increment)
{
std::cout << "T= " << threshold << std::endl;
//needs to be ran twice to get rid of some cases
fill_one_tile_gaps(threshold);
fill_one_tile_gaps(threshold);
fill_one_tile_gaps(threshold);
//fill in gaps of 2
fill_n_tile_gaps(threshold, 4);
fill_n_tile_gaps(threshold, 4);
verify_one_tile_gaps(threshold, verbose);
//fill_one_tile_gaps(threshold);
//threshold = 65;
set_contour_values(verbose);
reset_grass();
}
}
void print_contour(FILE* stream)
{
if (stream == 0)
{
stream = fopen(DEFAULT_CONTOUR_FILE, "w");
}
if (stream == NULL)
perror("Error opening file");
else
{
fprintf(stream, "%i %i %i\n\n", crop_width, crop_height, max);
fprintf(stream, " ");
for (int i = 0; i < crop_height; ++i)
fprintf(stream, "%.2i", i);
fprintf(stream, "\n");
for (int i = 0; i < crop_height; ++i)
{
fprintf(stream, "%02i ", i);
for (int j = 0; j < crop_width; ++j)
{
int t = cmap[i][j];
if (t == GRASS || t == HIGH_GRASS)
fprintf(stream, ". ");
else if (t == CLIFF_NS_EW || t == CLIFF_NS_WE)
fprintf(stream, "| ");
else if (t == CLIFF_WE_NS || t == CLIFF_WE_SN)
fprintf(stream, "- ");
else if (t == WATER)
fprintf(stream, "~ ");
else if (t == CLIFF_NE_NS || t == CLIFF_NE_SN
|| t == CLIFF_SW_NS || t == CLIFF_SW_SN)
fprintf(stream, "\\ ");
else if (t == CLIFF_SE_NS || t == CLIFF_SE_SN
|| t == CLIFF_NW_NS || t == CLIFF_NW_SN)
fprintf(stream, "/ ");
else
fprintf(stream, "%i ", t);
}
fprintf(stream, "\n");
}
fprintf(stream, "\n");
fprintf(stream, " ");
for (int i = 0; i < crop_height; ++i)
fprintf(stream, "%03i ", i);
fprintf(stream, "\n");
for (int i = 0; i < crop_height; ++i)
{
fprintf(stream, "%02i ", i);
for (int j = 0; j < crop_width; ++j)
{
int t = tmap[i][j];
fprintf(stream, "%03i ", t);
}
fprintf(stream, "\n");
}
}
}
|
#ifndef COLORS_H
#define COLORS_H
namespace MC {
struct Color {
unsigned char RED;
unsigned char GREEN;
unsigned char BLUE;
float R() { return RED/256.0f; }
float G() { return GREEN/256.0f; }
float B() { return BLUE/256.0f; }
};
}
#endif
|
#include <iostream>
#include <bitset>
using namespace std;
// 11分43秒
const size_t INT_SIZE = sizeof(int) * 8;
class Bit{
public:
Bit();
int changeBit(int num);
private:
bitset<INT_SIZE> b;
};
Bit::Bit(){
for(int i=0; i<INT_SIZE; i++){
if(!(i % 2)){
b.set(i);
}
}
}
int Bit::changeBit(int num){
int b_int = b.to_ulong();
int even = num & b_int;
int odd = num & (b_int << 1);
return (even << 1) | (odd >> 1);
}
int main(void){
Bit bit;
cout << bit.changeBit(5) << endl; // 10
cout << bit.changeBit(13) << endl; // 14
cout << bit.changeBit(21) << endl; // 42
cout << bit.changeBit(30) << endl; // 45
return 0;
}
|
#include <stdio.h>
#include "SDL2_net.h"
using namespace SDL2;
#pragma comment(linker, "/subsystem:console")
int main(int argc, char **argv)
{
SDL sdl;
Net net;
TCP server(9999);
if (!server)
{
printf("server:%s\n", net.GetError());
return 1;
}
//TCP tcp = server.WaitForAccept(100);
SocketSet set(2);
set.Add(server);
if (set.Check(10000))
{
TCP tcp = server.Accept();
if (!tcp)
{
printf("tcp:%s\n", net.GetError());
}
else
{
tcp.Send("message", 7);
}
}
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
main()
{
int a,b,c;
while(cin>>a>>b>>c)
{
int sum1, sum2, sum3, sum4, sum5;
sum1= a + (b * c);
sum2= a * (b + c);
sum3= a * b * c;
sum4= (a + b) * c;
sum5= a + b + c;
int res = max(sum5, max(sum1, max(sum2, max(sum3, sum4))));
cout<<res<<endl;
}
return 0;
}
|
#pragma once
#include "StochProc.h"
StochProc::StochProc(const StochProc& init){
if (PHI_STATES == 1){
phiTrans[0][0] = init.phiTrans[0][0];
phiTransCDF[0][0] = init.phiTransCDF[0][0];
}
else if (PHI_STATES == 2){
phiTrans[0][0] = init.phiTrans[0][0];
phiTrans[0][1] = init.phiTrans[0][1];
phiTrans[1][0] = init.phiTrans[1][0];
phiTrans[1][1] = init.phiTrans[1][1];
phiTransCDF[0][0] = init.phiTransCDF[0][0];
phiTransCDF[0][1] = init.phiTransCDF[0][1];
phiTransCDF[1][0] = init.phiTransCDF[1][0];
phiTransCDF[1][1] = init.phiTransCDF[1][1];
}
else{
std::cout << "expect only two phi states" << std::endl;
exit(-1);
}
assets.resize(ASSET_SIZE);
aggAssets.resize(AGG_ASSET_SIZE);
transition.resize(PHI_STATES);
cdf.resize(PHI_STATES);
shocks.resize(PHI_STATES);
for (int h = 0; h < PHI_STATES; h++){
transition[h].resize(AGG_SHOCK_SIZE);
cdf[h].resize(AGG_SHOCK_SIZE);
shocks[h].resize(AGG_SHOCK_SIZE);
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
transition[h][i].resize(CAP_SHOCK_SIZE);
cdf[h][i].resize(CAP_SHOCK_SIZE);
shocks[h][i].resize(CAP_SHOCK_SIZE);
for (int ii = 0; ii < CAP_SHOCK_SIZE; ii++) {
transition[h][i][ii].resize(CAP_SHOCK_SIZE);
cdf[h][i][ii].resize(CAP_SHOCK_SIZE);
shocks[h][i][ii].resize(CAP_SHOCK_SIZE);
for (int j = 0; j < CAP_SHOCK_SIZE; j++) {
transition[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
cdf[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
shocks[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
for (int k = 0; k < WAGE_SHOCK_SIZE; k++) {
shocks[h][i][ii][j][k].resize(NUM_SHOCK_VARS);
}
}
}
}
}
for (int h = 0; h < PHI_STATES; h++) {
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
for (int j = 0; j < CAP_SHOCK_SIZE; j++) {
for (int jj = 0; jj < CAP_SHOCK_SIZE; jj++) {
for (int l = 0; l < WAGE_SHOCK_SIZE; l++) {
shocks[h][i][j][jj][l][EF_K1] = init.shocks[h][i][j][jj][l][EF_K1];
shocks[h][i][j][jj][l][EF_K2] = init.shocks[h][i][j][jj][l][EF_K2];
shocks[h][i][j][jj][l][EF_W] = init.shocks[h][i][j][jj][l][EF_W];
shocks[h][i][j][jj][l][EF_A] = init.shocks[h][i][j][jj][l][EF_A];
shocks[h][i][j][jj][l][EF_PHI] = init.shocks[h][i][j][jj][l][EF_PHI];
for (int mm1 = 0; mm1 < PHI_STATES; mm1++) {
for (int m = 0; m < AGG_SHOCK_SIZE; m++) {
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
transition[h][i][j][jj][l][mm1][m][n][nn][o] = init.transition[h][i][j][jj][l][mm1][m][n][nn][o];
cdf[h][i][j][jj][l][mm1][m][n][nn][o] = init.cdf[h][i][j][jj][l][mm1][m][n][nn][o];
}
}
}
}
}
}
}
}
}
}
for (int i = 0; i < ASSET_SIZE; i++) {
assets[i] = init.assets[i];
}
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
aggAssets[i] = init.aggAssets[i];
}
}
StochProc::StochProc(VecDoub phis) {
if (phis.size() != PHI_STATES){
std::cerr << "StochProc(VecDoub): phis parameter is not of size PHI_STATES" << std::endl;
exit(-1);
}
if (PHI_STATES == 1){
phiTrans[0][0] = 1;
phiTransCDF[0][0] = 1;
}
else if (PHI_STATES == 2){
#if 1
#if 1
phiTrans[0][0] = 0.5;
phiTrans[0][1] = 0.5;
phiTrans[1][0] = 0.125;
phiTrans[1][1] = 0.875;
phiTransCDF[0][0] = 0.5;
phiTransCDF[0][1] = 1;
phiTransCDF[1][0] = 0.125;
phiTransCDF[1][1] = 1;
#else
phiTrans[0][0] = 0.99999;
phiTrans[0][1] = 0.00001;
phiTrans[1][0] = 0.00001;
phiTrans[1][1] = 0.99999;
phiTransCDF[0][0] = 0.99999;
phiTransCDF[0][1] = 1;
phiTransCDF[1][0] = 0.00001;
phiTransCDF[1][1] = 1;
#endif
#else
phiTrans[0][0] = 0.5;
phiTrans[0][1] = 0.5;
phiTrans[1][0] = 0.5;
phiTrans[1][1] = 0.5;
phiTransCDF[0][0] = 0.5;
phiTransCDF[0][1] = 1;
phiTransCDF[1][0] = 0.5;
phiTransCDF[1][1] = 1;
#endif
}
else{
std::cout << "expect only two phi states" << std::endl;
exit(-1);
}
assets.resize(ASSET_SIZE);
aggAssets.resize(AGG_ASSET_SIZE);
transition.resize(PHI_STATES);
cdf.resize(PHI_STATES);
shocks.resize(PHI_STATES);
for (int h = 0; h < PHI_STATES; h++){
transition[h].resize(AGG_SHOCK_SIZE);
cdf[h].resize(AGG_SHOCK_SIZE);
shocks[h].resize(AGG_SHOCK_SIZE);
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
transition[h][i].resize(CAP_SHOCK_SIZE);
cdf[h][i].resize(CAP_SHOCK_SIZE);
shocks[h][i].resize(CAP_SHOCK_SIZE);
for (int ii = 0; ii < CAP_SHOCK_SIZE; ii++) {
transition[h][i][ii].resize(CAP_SHOCK_SIZE);
cdf[h][i][ii].resize(CAP_SHOCK_SIZE);
shocks[h][i][ii].resize(CAP_SHOCK_SIZE);
for (int j = 0; j < CAP_SHOCK_SIZE; j++) {
transition[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
cdf[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
shocks[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
for (int k = 0; k < WAGE_SHOCK_SIZE; k++) {
shocks[h][i][ii][j][k].resize(NUM_SHOCK_VARS);
}
}
}
}
}
for (int i = 0; i < ASSET_SIZE; i++) {
assets[i] = 1.0 / (ASSET_SIZE - 1) * i;
assets[i] = pow(assets[i], CURVATURE);
assets[i] = assets[i] * (MAX_ASSETS - MIN_ASSETS) + MIN_ASSETS;
}
for (int i = 0; i < AGG_ASSET_SIZE; i++) {
if (AGG_ASSET_SIZE == 1){
aggAssets[0] = (MAX_AGG_ASSETS + MIN_AGG_ASSETS) / 2;
}else{
aggAssets[i] = 1.0 / (MAX(1,AGG_ASSET_SIZE - 1)) * i;
aggAssets[i] = pow(aggAssets[i], AGG_CURVATURE);
aggAssets[i] = aggAssets[i] * (MAX_AGG_ASSETS - MIN_AGG_ASSETS) + MIN_AGG_ASSETS;
}
}
for (int h = 0; h < PHI_STATES; h++) {
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
for (int j = 0; j < CAP_SHOCK_SIZE; j++) {
for (int jj = 0; jj < CAP_SHOCK_SIZE; jj++) {
for (int l = 0; l < WAGE_SHOCK_SIZE; l++) {
double shocks1[CAP_SHOCK_SIZE];
double shocks2[CAP_SHOCK_SIZE];
double wageShocks[WAGE_SHOCK_SIZE];
double transition1[CAP_SHOCK_SIZE][CAP_SHOCK_SIZE];
double transition2[CAP_SHOCK_SIZE][CAP_SHOCK_SIZE];
double wageTrans[WAGE_SHOCK_SIZE][WAGE_SHOCK_SIZE];
if (CAP_SHOCK_SIZE == 1) {
shocks1[j] = 0;
shocks2[jj] = 0;
transition1[j][jj] = 1;
transition2[j][jj] = 1;
}
else {
#if 0
extern void tauchen(double mean, double rho,
double sigma, double m,
double(&z)[CAP_SHOCK_SIZE],
double(&zprob)[CAP_SHOCK_SIZE][CAP_SHOCK_SIZE]);
tauchen(CAP1_SHOCK_MEAN, CAP1_SHOCK_PERSISTENCE,
CAP1_SHOCK_STD, CAP1_SHOCK_SPREAD, shocks1,
transition1);
tauchen(CAP2_SHOCK_MEAN, CAP2_SHOCK_PERSISTENCE,
CAP2_SHOCK_STD, CAP2_SHOCK_SPREAD, shocks2,
transition2);
#else
shocks1[0] = -0.225;
shocks1[1] = 0.525;
transition1[0][0] = 0.5;
transition1[0][1] = 0.5;
transition1[1][0] = 0.5;
transition1[1][1] = 0.5;
shocks2[0] = -0.225;
shocks2[1] = 0.525;
transition2[0][0] = 0.5;
transition2[0][1] = 0.5;
transition2[1][0] = 0.5;
transition2[1][1] = 0.5;
#endif
}
if (WAGE_SHOCK_SIZE == 1) {
wageShocks[l] = 0;
wageTrans[l][l] = 1;
}
else {
#if 0
extern void tauchen2(double mean, double rho,
double sigma, double m,
double(&z)[WAGE_SHOCK_SIZE],
double(&zprob)[WAGE_SHOCK_SIZE][WAGE_SHOCK_SIZE]);
tauchen2(WAGE_SHOCK_MEAN, WAGE_SHOCK_PERSISTENCE,
WAGE_SHOCK_STD, WAGE_SHOCK_SPREAD,
wageShocks, wageTrans);
#else
if (WAGE_SHOCK_SIZE != 2){
std::cout << "expect only two wage shocks" << std::endl;
exit(-1);
}
wageShocks[0] = 0.34;
wageShocks[1] = 1.36;
wageTrans[0][0] = 0.95;
wageTrans[0][1] = 0.05;
wageTrans[1][0] = 0.05;
wageTrans[1][1] = 0.95;
#endif
}
shocks[h][i][j][jj][l][EF_K1] = shocks1[j];
shocks[h][i][j][jj][l][EF_K2] = shocks2[jj];
shocks[h][i][j][jj][l][EF_W] = wageShocks[l];
shocks[h][i][j][jj][l][EF_A] = 1;
shocks[h][i][j][jj][l][EF_PHI] = phis[h];
for (int mm1 = 0; mm1 < PHI_STATES; mm1++) {
for (int m = 0; m < AGG_SHOCK_SIZE; m++) {
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
transition[h][i][j][jj][l][mm1][m][n][nn][o] =
transition1[j][n]
* transition2[jj][nn]
* wageTrans[l][o]
* phiTrans[h][mm1];
}
}
}
}
}
for (int mm1 = 0; mm1 < PHI_STATES; mm1++) {
for (int m = 0; m < AGG_SHOCK_SIZE; m++) {
double prevValue = 0;
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
cdf[h][i][j][jj][l][mm1][m][n][nn][o] =
prevValue +
transition[h][i][j][jj][l][mm1][m][n][nn][o];
prevValue = cdf[h][i][j][jj][l][mm1][m][n][nn][o];
}
}
}
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
cdf[h][i][j][jj][l][mm1][m][n][nn][o] = cdf[h][i][j][jj][l][mm1][m][n][nn][o] /
cdf[h][i][j][jj][l][mm1][m][CAP_SHOCK_SIZE - 1][CAP_SHOCK_SIZE - 1][WAGE_SHOCK_SIZE - 1];
}
}
}
}
}
}
}
}
}
}
}
StochProc::~StochProc() {
}
int StochProc::getCondNewPhi(const int curSt, const double randNum) const{
for (int i = 0; i < PHI_STATES; i++){
if (randNum < phiTransCDF[curSt][i]){
return i;
}
}
std::cerr << "StochProc:getCondNewPhi - Should not reach here. rand="<<randNum << std::endl;
std::cerr << "Transition CDF"<<std::endl;
for (int i = 0; i < PHI_STATES; i++){
std::cout << phiTransCDF[curSt][i] << " ";
}
exit(-1);
return PHI_STATES - 1;
}
VecInt StochProc::getCondNewState(const VecInt& currentState, const int newAggState, const int newPhi, const double randNum) const{
int h = currentState[EF_PHI];
int i = currentState[EF_A];
int j = currentState[EF_K1];
int jj = currentState[EF_K2];
int l = currentState[EF_W];
VecInt newState = VecInt(NUM_SHOCK_VARS);
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
if (randNum < cdf[h][i][j][jj][l][newPhi][newAggState][n][nn][o]){
newState[EF_A] = newAggState;
newState[EF_PHI] = newPhi;
newState[EF_K1] = n;
newState[EF_K2] = nn;
newState[EF_W] = o;
return newState;
}
}
}
}
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
if (randNum < cdf[newPhi][i][j][jj][l][newPhi][newAggState][n][nn][o]){
newState[EF_A] = newAggState;
newState[EF_PHI] = newPhi;
newState[EF_K1] = n;
newState[EF_K2] = nn;
newState[EF_W] = o;
return newState;
}
}
}
}
std::cerr << "Could not transition to new phi and new state." << std::endl;
exit(-1);
return newState;
}
StochProc& StochProc::operator=(const StochProc& init) {
if (PHI_STATES == 1){
phiTrans[0][0] = init.phiTrans[0][0];
phiTransCDF[0][0] = init.phiTransCDF[0][0];
}
else if (PHI_STATES == 2){
phiTrans[0][0] = init.phiTrans[0][0];
phiTrans[0][1] = init.phiTrans[0][1];
phiTrans[1][0] = init.phiTrans[1][0];
phiTrans[1][1] = init.phiTrans[1][1];
phiTransCDF[0][0] = init.phiTransCDF[0][0];
phiTransCDF[0][1] = init.phiTransCDF[0][1];
phiTransCDF[1][0] = init.phiTransCDF[1][0];
phiTransCDF[1][1] = init.phiTransCDF[1][1];
}
else{
std::cout << "expect only two phi states" << std::endl;
exit(-1);
}
assets.resize(ASSET_SIZE);
aggAssets.resize(AGG_ASSET_SIZE);
transition.resize(PHI_STATES);
cdf.resize(PHI_STATES);
shocks.resize(PHI_STATES);
for (int h = 0; h < PHI_STATES; h++){
transition[h].resize(AGG_SHOCK_SIZE);
cdf[h].resize(AGG_SHOCK_SIZE);
shocks[h].resize(AGG_SHOCK_SIZE);
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
transition[h][i].resize(CAP_SHOCK_SIZE);
cdf[h][i].resize(CAP_SHOCK_SIZE);
shocks[h][i].resize(CAP_SHOCK_SIZE);
for (int ii = 0; ii < CAP_SHOCK_SIZE; ii++) {
transition[h][i][ii].resize(CAP_SHOCK_SIZE);
cdf[h][i][ii].resize(CAP_SHOCK_SIZE);
shocks[h][i][ii].resize(CAP_SHOCK_SIZE);
for (int j = 0; j < CAP_SHOCK_SIZE; j++) {
transition[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
cdf[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
shocks[h][i][ii][j].resize(WAGE_SHOCK_SIZE);
for (int k = 0; k < WAGE_SHOCK_SIZE; k++) {
shocks[h][i][ii][j][k].resize(NUM_SHOCK_VARS);
}
}
}
}
}
for (int h = 0; h < PHI_STATES; h++) {
for (int i = 0; i < AGG_SHOCK_SIZE; i++) {
for (int j = 0; j < CAP_SHOCK_SIZE; j++) {
for (int jj = 0; jj < CAP_SHOCK_SIZE; jj++) {
for (int l = 0; l < WAGE_SHOCK_SIZE; l++) {
shocks[h][i][j][jj][l][EF_K1] = init.shocks[h][i][j][jj][l][EF_K1];
shocks[h][i][j][jj][l][EF_K2] = init.shocks[h][i][j][jj][l][EF_K2];
shocks[h][i][j][jj][l][EF_W] = init.shocks[h][i][j][jj][l][EF_W];
shocks[h][i][j][jj][l][EF_A] = init.shocks[h][i][j][jj][l][EF_A];
shocks[h][i][j][jj][l][EF_PHI] = init.shocks[h][i][j][jj][l][EF_PHI];
for (int mm1 = 0; mm1 < PHI_STATES; mm1++) {
for (int m = 0; m < AGG_SHOCK_SIZE; m++) {
for (int n = 0; n < CAP_SHOCK_SIZE; n++) {
for (int nn = 0; nn < CAP_SHOCK_SIZE; nn++) {
for (int o = 0; o < WAGE_SHOCK_SIZE; o++) {
transition[h][i][j][jj][l][mm1][m][n][nn][o] = init.transition[h][i][j][jj][l][mm1][m][n][nn][o];
cdf[h][i][j][jj][l][mm1][m][n][nn][o] = init.cdf[h][i][j][jj][l][mm1][m][n][nn][o];
}
}
}
}
}
}
}
}
}
}
for (int i = 0; i < ASSET_SIZE; i++) {
assets[i] = init.assets[i];
}
for (int i = 0; i < AGG_ASSET_SIZE; i++) {
aggAssets[i] = init.aggAssets[i];
}
return *this;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* This file is used as PRODUCT_SYSTEM_FILE by Desktop on Unix.
*/
#ifndef UNIX_SYSTEM_H
#define UNIX_SYSTEM_H __FILE__
#include "platforms/posix/sys/include_early.h"
#include <assert.h>
#include <sys/types.h>
#include "platforms/unix/base/common/preamble.h"
#include "platforms/posix/sys/posix_choice.h"
#include "adjunct/quick/quick-version.h"
#define NATIVE_BOOL
#ifndef BYTE_ORDER
# if defined(_BYTE_ORDER)
# define BYTE_ORDER _BYTE_ORDER
# elif defined(__BYTE_ORDER)
# define BYTE_ORDER __BYTE_ORDER
# elif defined(__BYTE_ORDER__)
# define BYTE_ORDER __BYTE_ORDER__
# else
# error Undefined BYTE_ORDER
# endif
#endif
#ifndef BIG_ENDIAN
# if defined(_BIG_ENDIAN)
# define BIG_ENDIAN _BIG_ENDIAN
# elif defined(__BIG_ENDIAN)
# define BIG_ENDIAN __BIG_ENDIAN
# elif defined(__BIG_ENDIAN__)
# define BIG_ENDIAN __BIG_ENDIAN__
# else
# error Undefined BIG_ENDIAN
# endif
#endif
#ifndef LITTLE_ENDIAN
# if defined(_LITTLE_ENDIAN)
# define LITTLE_ENDIAN _LITTLE_ENDIAN
# elif defined(__LITTLE_ENDIAN)
# define LITTLE_ENDIAN __LITTLE_ENDIAN
# elif defined(__LITTLE_ENDIAN__)
# define LITTLE_ENDIAN __LITTLE_ENDIAN__
# else
# error Undefined LITTLE_ENDIAN
# endif
#endif
#ifndef FLOAT_WORD_ORDER
# if defined(_FLOAT_WORD_ORDER)
# define FLOAT_WORD_ORDER _FLOAT_WORD_ORDER
# elif defined(__FLOAT_WORD_ORDER)
# define FLOAT_WORD_ORDER __FLOAT_WORD_ORDER
# elif defined(__FLOAT_WORD_ORDER__)
# define FLOAT_WORD_ORDER __FLOAT_WORD_ORDER__
# else
# define FLOAT_WORD_ORDER BYTE_ORDER
# endif
#endif
#if BYTE_ORDER == BIG_ENDIAN
#define SYSTEM_BIG_ENDIAN YES
#elif BYTE_ORDER == LITTLE_ENDIAN
#define SYSTEM_BIG_ENDIAN NO
#else
#error Unsupported BYTE_ORDER
#endif
#if FLOAT_WORD_ORDER == BIG_ENDIAN
#define SYSTEM_IEEE_8087 NO
#define SYSTEM_IEEE_MC68K YES
#elif FLOAT_WORD_ORDER == LITTLE_ENDIAN
#define SYSTEM_IEEE_8087 YES
#define SYSTEM_IEEE_MC68K NO
#else
#error Unsupported FLOAT_WORD_ORDER
#endif
#define SYSTEM_NAMESPACE YES
#undef SYSTEM_STRTOD /* does not conform to specification, should be locale-independent */
#define SYSTEM_STRTOD NO
#undef SYSTEM_GETPHYSMEM
#define SYSTEM_GETPHYSMEM YES /* SYS_GETPHYSMEM */
#undef SYSTEM_OPFILELENGTH_IS_SIGNED
#define SYSTEM_OPFILELENGTH_IS_SIGNED NO /* core has issues with this, assumes OpFileLength is unsigned - see DSK-295495 */
#undef SYSTEM_VSNPRINTF
#define SYSTEM_VSNPRINTF NO /* preventing locale settings to make PS printing output commas in PS code */
#undef SYSTEM_LOCAL_TYPE_AS_TEMPLATE_ARG
#define SYSTEM_LOCAL_TYPE_AS_TEMPLATE_ARG NO
#include "platforms/posix/sys/posix_declare.h" /* *after* fixing up SYSTEM_* defines. */
#ifndef _NO_THREADS_ /* desktop_pi's threading: */
typedef pthread_t OpThreadId;
typedef pthread_mutex_t OpMutexId;
typedef struct sema_struct_t* OpSemaphoreId;
#endif /* _NO_THREADS_ */
#ifndef max /* Deprecated in the system system, in favour of MAX, MIN. */
#ifdef __cplusplus
template<class T,class T2> static inline T min(T a, T2 b) { if( a < b ) return a; else return b; }
template<class T,class T2> static inline T max(T a, T2 b) { if( a > b ) return a; else return b; }
#define max max
#define min min
#else /* __cplusplus */
# define min(a,b) (((a) < (b)) ? (a) : (b))
# define max(a,b) (((a) > (b)) ? (a) : (b))
#endif /* __cplusplus */
#endif /* max */
#define IN
#define OUT
#define IO
#define OPT
#define far
#define MAX_PATH PATH_MAX
#define huge
#define IGNORE_SZ_PARAM NULL
#define __export
#ifndef NEWLINE
# define NEWLINE "\n"
#endif /* NEWLINE */
#define USED_IN_BITFIELD /* Enums are unsigned by default in gcc */
#define PATH_CASE_INSENSITIVE FALSE
/* we use non-signal-mask saving versions for performance reasons;
* signal masks are assumed to not change inside leaving funcions */
#undef op_setjmp
#undef op_longjmp
#define op_setjmp(e) _setjmp(e)
#define op_longjmp(e, v) _longjmp(e, v)
/* op_* defines not actually specified by the system system: */
#define op_offsetof(s,f) offsetof(s,f)
#define op_sleep(s) sleep(s)
/* The system system doesn't define op_stristr; but util/str.cpp does ! In
* fact, stristr isn't defined on Linux, but we always got away with some calls
* to it because we defined op_stristr to stristr, causing util_str.cpp to
* define stristr, so various calls to stristr worked ! This (reversing the
* direction of the define) doesn't really belong in !TYPE_SYSTEMATIC, but is
* here so that normal builds should still work, while those trying to enforce
* standards still get errors over this. */
#define stristr(s,f) op_stristr(s,f)
/* The following two macros are used to catch call-stack information. These are
* implemented as macros to work in more environments, i.e. provide useful
* information where stack-frames are not available and only one return-address
* can be provided.
*
* This API for call-stack information is currently used by the memory module.
*/
#ifdef __GNUC__ /* TODO: what does the size parameter mean ? */
#define OPGETCALLSTACK(size) \
void* opx_ret_address_hidden = __builtin_return_address(0); \
void* opx_frm_address_hidden = __builtin_frame_address(0)
#endif /* else: you need to implement an equivalent ! */
#define OPCOPYCALLSTACK(ptr, size) \
OpCopyCallStack(reinterpret_cast<UINTPTR*>(ptr), opx_ret_address_hidden, opx_frm_address_hidden, size)
#ifdef __cplusplus
extern "C"
#endif
void OpCopyCallStack(UINTPTR* dst, void* pc, void* fp, int size);
#ifdef __cplusplus
extern __thread class OpComponentManager* g_component_manager;
extern class CoreComponent* g_opera;
extern class OpThreadTools* g_thread_tools;
extern __thread class CleanupItem* g_cleanup_stack;
#endif // __cplusplus
#endif /* !UNIX_SYSTEM_H */
|
#include "global.h"
const float t = 14;
|
/* -*- 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.
*/
#ifndef IMAGEDECODERICO_H
#define IMAGEDECODERICO_H
#include "modules/img/image.h"
typedef struct
{
UINT8 bWidth; // Width, in pixels, of the image
UINT8 bHeight; // Height, in pixels, of the image
UINT8 bColorCount; // Number of colors in image (0 if >=8bpp)
UINT8 bReserved; // Reserved ( must be 0)
UINT16 wPlanes; // Color Planes
UINT16 wBitCount; // Bits per pixel
UINT32 dwBytesInRes; // How many bytes in this resource?
UINT32 dwImageOffset; // Where in the file is this image?
} ICO_DIRENTRY;
typedef struct
{
UINT16 idReserved; // Reserved (must be 0)
UINT16 idType; // Resource Type (1 for icons)
UINT16 idCount; // How many images?
} ICO_HEADER;
class ImageDecoderIco : public ImageDecoder
{
typedef struct _BMP_INFOHEADER{ // bmih
UINT32 biSize;
UINT32 biWidth;
UINT32 biHeight;
UINT16 biPlanes;
UINT16 biBitCount;
UINT32 biCompression;
UINT32 biSizeImage;
UINT32 biXPelsPerMeter;
UINT32 biYPelsPerMeter;
UINT32 biClrUsed;
UINT32 biClrImportant;
} BMP_INFOHEADER;
typedef struct _RGBQ { // rgbq
UINT8 rgbBlue;
UINT8 rgbGreen;
UINT8 rgbRed;
UINT8 rgbReserved;
} RGBQ;
typedef struct ImageIcoDecodeInfo
{
ICO_HEADER header;
ICO_DIRENTRY* icEntries;
BOOL header_loaded;
BOOL entries_loaded;
BOOL reached_offset;
} ImageIcoDecodeInfo;
public:
ImageDecoderIco();
~ImageDecoderIco();
virtual OP_STATUS DecodeData(const BYTE* data, INT32 numBytes, BOOL more, int& resendBytes, BOOL load_all = FALSE);
virtual void SetImageDecoderListener(ImageDecoderListener* imageDecoderListener);
private:
void CleanDecoder();
/**
* Reads the fileheader and stores it in internal decode-structure
* @param data A pointer to current data
* @param num_bytes The number of bytes that is remaining in current data-chunk
*/
UINT32 ReadIcoFileHeader(const BYTE* data, UINT32 num_bytes);
/**
* Read all ICO-entries in current data
* @param data A pointer to current data
* @param num_bytes The number of bytes that is remaining in current data-chunk
*/
UINT32 ReadIcoEntries(const BYTE* data, UINT32 num_bytes);
ImageDecoderListener* image_decoder_listener; ///> current listener -- whereto information is sent
UINT32 width, ///> the total width of the picture
height; ///> the total height of the picture
UINT32 bits_per_pixel; ///> number of bits/pixel
UINT32 col_mapsize; ///> the size of the color map
ImageIcoDecodeInfo* decode; ///> here goes all header information
UINT32 img_to_decode; ///> which image we are supposed to decode
BOOL decoding_finished; ///> Have we decoded everything that we were interested in?
BOOL is_alpha;
OP_STATUS ReadIndexed (const unsigned char* src, UINT32 bytes_in_image);
OP_STATUS ReadRaw (const unsigned char* src, UINT32 bytes_in_image);
OP_STATUS ReadRaw32 (const unsigned char* src, UINT32 bytes_in_image);
};
#endif // IMAGEDECODERICO_H
|
#include "SvcTimer.h"
#include "protocol.h"
//毫秒级定时器, 每隔30毫秒触发一次, 更新玩家的位置信息
SvcTimer::SvcTimer(io_service& ios, PlayerManager*& playerMgr)
: mTimer(ios, boost::posix_time::milliseconds(30)), mPlayMgr(playerMgr)
{
mTimer.async_wait(boost::bind(&SvcTimer::handler, this));
}
SvcTimer::~SvcTimer()
{
}
//void SvcTimer::handler()
//{
// //为了防止在发送数据包时有玩家退出引起程序崩溃, 从这个地方加锁
// boost::mutex::scoped_lock lock(mPlayMgr->mMutex);
//
// memset(buffer, 0, sizeof(buffer));
// char*p = buffer;
// int count = 0;
//
// for (PlayerManager::iterator i = mPlayMgr->begin(); i != mPlayMgr->end(); i++)
// {
// if ((sizeof(buffer) - count * sizeof(TransformInfo)) < sizeof(TransformInfo))
// {
// break;
// }
// Player* ply = (Player*)(*i);
// if (NULL != ply && ply->transInfo.update)
// {
// memcpy(p, (const void*)&ply->transInfo, sizeof(TransformInfo));
// ply->transInfo.update = false;
//
// p += sizeof(TransformInfo);
// count++;
// }
// }
//
// if(count > 0)
// {
// for (PlayerManager::iterator j = mPlayMgr->begin(); j != mPlayMgr->end(); j++)
// {
// Player* ply1 = (Player*)(*j);
// if (NULL != ply1)
// {
// mPlayMgr->SendCmd(ply1->GetLinkID(), ID_User_Transform, 0, &buffer, sizeof(TransformInfo)* count);
// }
// }
//
// //if (mPlayMgr->GetUserVisibilityExternal())
// //{
// // mPlayMgr->GetCenterSvrConnection()->Send(ID_Global_Transform, 0, (char*)&buffer, sizeof(TransformInfo)* count);
// //}
//
// }
//
// mTimer.expires_at(mTimer.expires_at() + boost::posix_time::milliseconds(30));
// mTimer.async_wait(boost::bind(&SvcTimer::handler, this));
//}
void SvcTimer::handler()
{
//为了防止在发送数据包时有玩家退出引起程序崩溃, 从这个地方加锁
boost::mutex::scoped_lock lock(mPlayMgr->GetMutex());
SendTransformDataByUserType(VIP);
SendTransformDataByUserType(ExternalVIP);
mTimer.expires_at(mTimer.expires_at() + boost::posix_time::milliseconds(30));
mTimer.async_wait(boost::bind(&SvcTimer::handler, this));
}
void SvcTimer::SendTransformDataByUserType(UserType usrType)
{
memset(buffer, 0, sizeof(buffer));
char*p = buffer;
int count = 0;
for (PlayerManager::iterator i = mPlayMgr->begin(); i != mPlayMgr->end(); i++)
{
if ((sizeof(buffer) - count * sizeof(TransformInfo)) < sizeof(TransformInfo))
{
break;
}
Player* ply = (Player*)(*i);
if (NULL != ply && ply->GetTransformInfo().update && (ply->GetUserType() == usrType))
{
memcpy(p, (const void*)&ply->GetTransformInfo(), sizeof(TransformInfo));
ply->GetTransformInfo().update = false;
p += sizeof(TransformInfo);
count++;
}
}
if (count > 0)
{
int len = sizeof(TransformInfo)* count;
for (PlayerManager::iterator j = mPlayMgr->begin(); j != mPlayMgr->end(); j++)
{
Player* ply1 = (Player*)(*j);
if (NULL != ply1)
{
mPlayMgr->SendCmd(ply1->GetLinkID(), ID_User_Transform, 0, &buffer, len);
}
}
if (usrType == ExternalVIP)
{
NetEvtClient* pCenterSvrClient = mPlayMgr->GetCenterSvrConnection();
if (pCenterSvrClient)
{
pCenterSvrClient->Send(ID_Global_Transform, 0, (char*)&buffer, len);
}
}
}
}
|
#include<stdio.h>
#include<conio.h>
#define MAX 6
using namespace std;
int arr[100],head,tail;
void enqueue(int arr[],int a)
{
int temp = (tail+1)%MAX;
if(head==temp)
{
printf("\n queue overflow");
}
else
{
arr[tail] = a;
tail = temp;
}
}
void dequeue()
{
if(head == tail)
printf("\n queue underflow");
else
{
printf("dequeued ele:::%d\n",arr[head]);
head = (head+1)%MAX;
}
}
int main()
{
head=tail=0;
enqueue(arr,10);
enqueue(arr,20);
enqueue(arr,30);
enqueue(arr,40);
enqueue(arr,50);
for(int i=0;i<MAX-1;i++)
printf("%d",arr[i]);
dequeue();
dequeue();
getch();
}
|
#ifndef GLMCFG_H
#define GLMCFG_H
// TODO appropriate defines for glm
#include <glm/fwd.hpp>
#include <glm/vec3.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/quaternion.hpp>
#include <vector>
namespace pb
{
typedef glm::vec3 Vec3;
typedef glm::quat Quat;
typedef glm::mat4x4 Mat4;
typedef uint32_t ColorRGBA;
typedef std::vector<uint32_t> Indices;
typedef std::vector<glm::vec3> Positions;
typedef std::vector<ColorRGBA> ColorsRGBA;
typedef std::vector<Mat4> Transforms;
};
#endif // GLMCFG_H
|
//
// PostgreSQLTypes.h
//
// $Id: //poco/1.4/Data/PostgreSQL/include/_Db/PostgreSQL/SessionHandle.h#1 $
//
// Library: Data
// Package: PostgreSQL
//
// Definition of the SessionHandle class.
//
// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef Data_PostgreSQL_Types_INCLUDED
#define Data_PostgreSQL_Types_INCLUDED
#include "_Db/MetaColumn.h"
#include <vector>
#include <libpq-fe.h>
namespace _Db {
namespace PostgreSQL {
/// Oid constants duplicated from PostgreSQL "include/postgresql/server/catalog/pg_type.h"
/// because PostgreSQL compile time definitions are too onerous to reproduce for this module
const Oid BOOLOID = 16;
const Oid INT2OID = 21;
const Oid INT4OID = 23;
const Oid INT8OID = 20;
const Oid FLOAT8OID = 701; // double
const Oid FLOAT4OID = 700;
const Oid NUMERICOID = 1700;
const Oid CHAROID = 18;
const Oid BPCHAROID = 1042; // fixed length char
const Oid VARCHAROID = 1043;
const Oid BYTEAOID = 17; // BLOB
const Oid TEXTOID = 25; // CLOB
const Oid DATEOID = 1082;
const Oid TIMEOID = 1083;
const Oid TIMETZOID = 1266;
const Oid TIMESTAMPOID = 1114;
const Oid TIMESTAMPZOID = 1184;
// future use
const Oid BITOID = 1560;
const Oid VARYBITOID = 1562;
const Oid CASHOID = 790;
const Oid MACADDROID = 829;
const Oid UUIDOID = 2950;
Poco::Data::MetaColumn::ColumnDataType oidToColumnDataType(const Oid anOID);
class InputParameter
/// PostgreSQL class to record values for input parameters to SQL statements
{
public:
explicit InputParameter(Poco::Data::MetaColumn::ColumnDataType aFieldType,
const void* aDataPtr,
std::size_t theDataLength);
explicit InputParameter();
~InputParameter();
Poco::Data::MetaColumn::ColumnDataType fieldType() const;
const void* pData() const;
std::size_t size() const;
bool isBinary() const;
void setStringVersionRepresentation(const std::string& aString);
void setNonStringVersionRepresentation(const void* aPtr, std::size_t theSize);
const void* pInternalRepresentation() const;
private:
Poco::Data::MetaColumn::ColumnDataType _fieldType;
const void* _pData;
std::size_t _size;
bool _isBinary;
std::string _stringVersionRepresentation;
void* _pNonStringVersionRepresentation;
};
typedef std::vector <InputParameter> InputParameterVector;
class OutputParameter
/// PostgreSQL class to record values for output parameters to capture the results
{
public:
explicit OutputParameter(Poco::Data::MetaColumn::ColumnDataType aFieldType,
Oid anInternalFieldType,
std::size_t aRowNumber,
const char* aDataPtr,
std::size_t theSize,
bool anIsNull);
explicit OutputParameter();
~OutputParameter();
void setValues(Poco::Data::MetaColumn::ColumnDataType aFieldType,
Oid anInternalFieldType,
std::size_t aRowNumber,
const char* aDataPtr,
std::size_t theSize,
bool anIsNull);
Poco::Data::MetaColumn::ColumnDataType fieldType() const;
Oid internalFieldType() const;
std::size_t rowNumber() const;
const char* pData() const;
std::size_t size() const;
bool isNull() const;
private:
Poco::Data::MetaColumn::ColumnDataType _fieldType;
Oid _internalFieldType;
std::size_t _rowNumber;
const char* _pData;
std::size_t _size;
bool _isNull;
};
typedef std::vector <OutputParameter> OutputParameterVector;
class PQConnectionInfoOptionsFree
/// PostgreSQL connection Info Options free (RAII)
{
public:
explicit PQConnectionInfoOptionsFree(PQconninfoOption* aConnectionInfoOptionPtr);
~PQConnectionInfoOptionsFree();
private:
PQConnectionInfoOptionsFree (const PQConnectionInfoOptionsFree&);
PQConnectionInfoOptionsFree& operator= (const PQConnectionInfoOptionsFree&);
private:
PQconninfoOption* _pConnectionInfoOption;
};
class PQResultClear
/// PostgreSQL statement result free (RAII)
{
public:
explicit PQResultClear(PGresult * aPQResultPtr);
~PQResultClear();
private:
PQResultClear (const PQResultClear&);
PQResultClear& operator= (const PQResultClear&);
private:
PGresult* _pPQResult;
};
class PGCancelFree
/// PostgreSQL Cancel Info Options free (RAII)
{
public:
explicit PGCancelFree(PGcancel * aStatementCancelPtr);
~PGCancelFree();
private:
PGCancelFree (const PGCancelFree&);
PGCancelFree& operator= (const PGCancelFree&);
private:
PGcancel* _pPGCancel;
};
//
// inlines
//
// InputParameter
inline
InputParameter::InputParameter(Poco::Data::MetaColumn::ColumnDataType aFieldType,
const void* aDataPtr,
std::size_t theSize)
: _fieldType (aFieldType),
_pData (aDataPtr),
_size (theSize),
_isBinary (false),
_pNonStringVersionRepresentation (0)
{
if ( Poco::Data::MetaColumn::FDT_BLOB == _fieldType
|| Poco::Data::MetaColumn::FDT_CLOB == _fieldType) {
_isBinary = true;
}
}
inline
InputParameter::InputParameter()
: _fieldType (Poco::Data::MetaColumn::FDT_UNKNOWN),
_pData (0),
_size (0),
_isBinary (false),
_pNonStringVersionRepresentation (0)
{
}
inline
InputParameter::~InputParameter()
{
}
inline
const void*
InputParameter::pData() const
{
return _pData;
}
inline
Poco::Data::MetaColumn::ColumnDataType
InputParameter::fieldType() const
{
return _fieldType;
}
inline
std::size_t
InputParameter::size() const
{
return _size;
}
inline
bool
InputParameter::isBinary() const
{
return _isBinary;
}
inline
void
InputParameter::setStringVersionRepresentation(const std::string& aString)
{
_pNonStringVersionRepresentation = 0;
_stringVersionRepresentation = aString;
_size = _stringVersionRepresentation.size();
}
inline
void
InputParameter::setNonStringVersionRepresentation(const void* aPtr, std::size_t theDataLength)
{
_stringVersionRepresentation = std::string();
_pNonStringVersionRepresentation = const_cast<void *> (aPtr);
_size = theDataLength;
}
inline
const void*
InputParameter::pInternalRepresentation() const
{
switch (_fieldType) {
case Poco::Data::MetaColumn::FDT_BOOL:
case Poco::Data::MetaColumn::FDT_INT8:
case Poco::Data::MetaColumn::FDT_UINT8:
case Poco::Data::MetaColumn::FDT_INT16:
case Poco::Data::MetaColumn::FDT_UINT16:
case Poco::Data::MetaColumn::FDT_INT32:
case Poco::Data::MetaColumn::FDT_UINT32:
case Poco::Data::MetaColumn::FDT_INT64:
case Poco::Data::MetaColumn::FDT_UINT64:
case Poco::Data::MetaColumn::FDT_FLOAT:
case Poco::Data::MetaColumn::FDT_DOUBLE:
case Poco::Data::MetaColumn::FDT_STRING:
case Poco::Data::MetaColumn::FDT_DATE:
case Poco::Data::MetaColumn::FDT_TIME:
case Poco::Data::MetaColumn::FDT_TIMESTAMP:
return _stringVersionRepresentation.c_str();
case Poco::Data::MetaColumn::FDT_BLOB:
case Poco::Data::MetaColumn::FDT_CLOB:
return _pNonStringVersionRepresentation;
case Poco::Data::MetaColumn::FDT_UNKNOWN:
default:
return 0;
}
}
// OutputParameter
inline
OutputParameter::OutputParameter(Poco::Data::MetaColumn::ColumnDataType aFieldType,
Oid anInternalFieldType,
std::size_t aRowNumber,
const char* aDataPtr,
std::size_t theSize,
bool anIsNull)
: _fieldType (aFieldType),
_internalFieldType (anInternalFieldType),
_rowNumber (aRowNumber),
_pData (aDataPtr),
_size (theSize),
_isNull (anIsNull)
{
}
inline
OutputParameter::OutputParameter()
: _fieldType (Poco::Data::MetaColumn::FDT_UNKNOWN),
_internalFieldType (-1),
_rowNumber (0),
_pData (0),
_size (0),
_isNull (true)
{
}
inline
OutputParameter::~OutputParameter()
{
}
inline
void
OutputParameter::setValues(Poco::Data::MetaColumn::ColumnDataType aFieldType,
Oid anInternalFieldType,
std::size_t aRowNumber,
const char* aDataPtr,
std::size_t theSize,
bool anIsNull)
{
_fieldType = aFieldType;
_internalFieldType = anInternalFieldType;
_rowNumber = aRowNumber;
_pData = aDataPtr;
_size = theSize;
_isNull = anIsNull;
}
inline
Poco::Data::MetaColumn::ColumnDataType
OutputParameter::fieldType() const
{
return _fieldType;
}
inline
Oid
OutputParameter::internalFieldType() const
{
return _internalFieldType;
}
inline
std::size_t
OutputParameter::rowNumber() const
{
return _rowNumber;
}
inline
const char*
OutputParameter::pData() const
{
return _pData;
}
inline
std::size_t
OutputParameter::size() const
{
return _size;
}
inline
bool
OutputParameter::isNull() const
{
return _isNull;
}
// PQConnectionInfoOptionsFree
inline
PQConnectionInfoOptionsFree::PQConnectionInfoOptionsFree(PQconninfoOption* aConnectionInfoOptionPtr)
: _pConnectionInfoOption(aConnectionInfoOptionPtr)
{
}
inline
PQConnectionInfoOptionsFree::~PQConnectionInfoOptionsFree()
{
if (_pConnectionInfoOption)
{
PQconninfoFree(_pConnectionInfoOption);
_pConnectionInfoOption = 0;
}
}
// PQResultClear
inline
PQResultClear::PQResultClear(PGresult* aPQResultPtr)
: _pPQResult(aPQResultPtr)
{
}
inline
PQResultClear::~PQResultClear()
{
if (_pPQResult)
{
PQclear(_pPQResult);
_pPQResult = 0;
}
}
// PGCancelFree
inline
PGCancelFree::PGCancelFree(PGcancel* aStatementCancelPtr)
: _pPGCancel(aStatementCancelPtr)
{
}
inline
PGCancelFree::~PGCancelFree()
{
if (_pPGCancel)
{
PQfreeCancel(_pPGCancel);
_pPGCancel = 0;
}
}
}}}
#endif // Data_PostgreSQL_Types_INCLUDED
|
#include "moc_IncA.cpp"
/// AUTOMOC moc_ include on the first line of the file!
#include "IncA.hpp"
/// @brief Source local QObject
///
class IncAPrivate : public QObject
{
Q_OBJECT
public:
IncAPrivate(){};
};
IncA::IncA()
{
IncAPrivate priv;
}
#include "IncA.moc"
|
//
// BoatBList.cpp
// GAME2
//
// Created by ruby on 2017. 11. 11..
// Copyright © 2017년 ruby. All rights reserved.
//
#include "BoatBList.hpp"
#include "BoatB.hpp"
void BoatBList::add(BoatB * new_BoatB){
if (head == NULL) { // BoatB가 아직 없는 경우
head = new_BoatB;
size++;
} else {
BoatB * t = head;
for (int i = 0; i < size - 1; i++)
t = t->get_next();
t->set_next(new_BoatB);
size++;
}
}
|
#include <iostream>
constexpr void SafeDeleteArray(bool* arr) noexcept
{
if (arr)
{
delete[] arr;
arr = nullptr;
}
}
void solution(int start, int end)
{
bool* arr = new bool[end + 1];
for (int i = 0; i < end + 1; i++)
arr[i] = false;
arr[1] = true;
for (int i = 2; i * i <= end; i++)
{
if (!arr[i])
{
for (int j = 2; j * i <= end; j++)
arr[j * i] = true;
}
}
for (int i = start; i <= end; i++)
{
if (!arr[i])
printf("%d\n", i);
}
SafeDeleteArray(arr);
}
int main(void)
{
int start, end;
scanf("%d %d", &start, &end);
solution(start, end);
return 0;
}
|
#include <iostream>
#include "rsdgMission.h"
#include <vector>
#include <stack>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
bool verbose;
bool local;
//derive your own rsdgMission class
//where you can reimplement the updateFunction
//each time when reconfig() is called, this function would be used to set the new budget
class robotRSDG: public rsdgMission{
public:
virtual void updateBudget(){
setBudget(getBudget()-10);
}
};
bool coke;
bool pepsi;
int cokePref;
int pepsiPref;
int budget;
string inputFile;
string outputFile;
map<string,string> path;
stack<string> finished; // a stack where the top() is the latest finished target
bool done;//when robot returns to the starting point, the 'fakerobot' will return
string currentJob; //current target
rsdgMission* setupRSDG();
rsdgPara* paraCoke;
rsdgPara* paraPepsi;
//5 functions for 4 balls(cans) and 1 starting point
void* ball1Fun (void*);
void* ball2Fun (void*);
void* ball3Fun (void*);
void* ball4Fun (void*);
void* start (void*);
//robot
void* robot(void*);
rsdgMission* rsdg;
int main(int argc, char* argv[]){
local = false;
if(argc<2){
cokePref=1;
pepsiPref=1;
}else{
for(int i = 1; i<argc; i++){
string arg = argv[i];
if(arg=="-coke"){
cokePref=atoi(argv[++i]);
}
if(arg=="-pepsi"){
pepsiPref=atoi(argv[++i]);
}
if(arg=="-xml"){
inputFile = argv[++i];
}
if(arg=="-b"){
budget = atoi(argv[++i]);
}
if(arg=="-v"){
verbose = true;
}
if(arg=="-l"){
local = true;
}
}
}
done = false;
outputFile = "./problem.lp";
//push starting point to the finished stack
finished.push("s");
currentJob="s";
//setup RSDG
rsdg = setupRSDG();
rsdg->setBudget(budget);
//since we will not let RSDG reconfig automatically, we only need to do 'reconfig'
rsdg -> reconfig();
sleep(1);//wait a second for the reconfiguration to finish
//simulating the robot behavior
pthread_t fakerobot;
pthread_create(&fakerobot,NULL,&robot,NULL);
pthread_join(fakerobot,NULL);
rsdg -> stopSolver();
rsdg -> cancel();
return 1;;
}
//fake robot
/*
read the flags to generate command to robot
sleep(2): assuming after 2 seconds the robot came back from the first target
setBudget(): it should set the budget to current budget, i.e. 30(could be any number, depends on the inital budget and the cost in the first pick)
udpateWeight: update the weight of the balls that have been picked up, here I assumes it picked up Pepsi
so it updates the weight for 'pickPepsi' and 'pepsiCan' to 0.
by doing the updateWeight, it will enable the solver to keep selecting 'pickPeipsi'.
Your robot should know that even the flag for pepsi is still true in the second solver consulting, you don't have to pick it up again. So you should have a logic of determing which can have I already picked up.
The reason of doing so:
We want to keep the solution consistent through out the entire mission. If it chooses 'pickPepsi' at the begining, it will always choose this if nothing goes wrong. The correct interpretion of 'pickPepsi' is 'getting the user a pepsi at the end'
thanks
example call-line:
./test -xml sample.xml -coke 10 -pepsi 20 -b 60
*/
// a function that uses "finished" to generate command
// it will not generate command to re-pick anything
void cmdGenerator(){
string cur = finished.top();
string nextStep = path[cur];
cout<<"*******CMD:GO AND FETCH "<<nextStep<<"***********"<<endl;
}
// the actual job that the robot going and fetching the ball(can)
void* robotJob(void* arg){
string pre = currentJob;
currentJob = path[currentJob];
if(currentJob=="s"){//next step is to go home
done = true;
sleep(5);//spending 5 seconds to go home
return NULL;
}
cout<<"*******GRABING...********"<<endl;
sleep(5);//assuming it takes 5 seconds to go to target and grab
finished.push(currentJob);
if(verbose)cout<<"pre:"<<pre<<" cur:"<<currentJob<<endl;
// after finished the current job, robot sets the weight of this node and the edge to it to be 0
// to ensure the next solution will also choose this
rsdg->updateWeight(currentJob,pre,0);//path cost = 0
rsdg->updateWeight(currentJob,0);//current destination = 0
return NULL;
}
// a master robot thread that acts as controller
void* robot (void* arg){
while(!done){
cmdGenerator();//generate the command
//start the thread to go and fetch the ball
pthread_t goNfetch;
pthread_create(&goNfetch, NULL,&robotJob, NULL);
pthread_join(goNfetch,NULL);
rsdg->reconfig();//everytime when finished a task, it does a reconfiguration
sleep(1);
}
cout<<"*******MISSION ACCOMPLISHED******"<<endl;
return NULL;
}
//init RSDG
//for a result like a$b, it means 'a' depends on 'b', in the robot case, go from 'b' to 'a'
rsdgMission* setupRSDG(){
paraCoke = new rsdgPara();
paraPepsi = new rsdgPara();
rsdgMission* res = new robotRSDG();
res->regService("ball1","b1",&ball1Fun);
res->regService("ball2","b2",&ball2Fun);
res->regService("ball3","b3",&ball3Fun);
res->regService("ball4","b4",&ball4Fun);
res->regService("start","s",&start);
res->generateProb(inputFile);
res->setBudget(budget);
res->addConstraint("s",true);//tell the RSDG that the starting point has to be chosen
res->updateMV("ball1",pepsiPref,false);//ball1 is a pepsi
res->updateMV("ball2",cokePref,false);//ball2 is a coke
res->updateMV("ball3",pepsiPref,false);//ball3 is a pepsi
res->updateMV("ball4",cokePref,false);//ball4 is a coke
res->updateMV("start",0,false);
res->setSolver(local);
res->printProb(outputFile);//for validating
res->setupSolverFreq(0);//check solver manually
return res;
}
//run functions for nodes
void* start(void* arg){
if(currentJob=="s")cout<<"*******STARTING...*******"<<endl;
vector<string> dep = rsdg->getDep("s");
if(dep.size()==0){
if(verbose)cout<<"no dependence"<<endl;
return NULL;
}
string from = dep[0];
if("s"==path[from])return NULL;
path[from]="s";
if(verbose)cout<<"from"<<from<<"to s"<<endl;
return NULL;
}
void* ball1Fun (void* arg){
vector<string> dep = rsdg->getDep("b1");
if(dep.size()==0){
if(verbose)cout<<"no dependence"<<endl;
return NULL;
}
string from = dep[0];
if("b1"==path[from])return NULL;
path[from]="b1";
if(verbose)cout<<"from "<<from<<"to b1"<<endl;
return NULL;
}
void* ball2Fun (void* arg){
vector<string> dep = rsdg->getDep("b2");
if(dep.size()==0){
if(verbose)cout<<"no dependence"<<endl;
return NULL;
}
string from = dep[0];
if("b2"==path[from])return NULL;
path[from]="b2";
if(verbose)cout<<"from "<<from<<"to b2"<<endl;
return NULL;
}
void* ball3Fun (void* arg){
vector<string> dep = rsdg->getDep("b3");
if(dep.size()==0){
if(verbose)cout<<"no dependence"<<endl;
return NULL;
}
string from = dep[0];
if("b3"==path[from])return NULL;
path[from]="b3";
if(verbose)cout<<"from "<<from<<"to b3"<<endl;
return NULL;
}
void* ball4Fun (void* arg){
vector<string> dep = rsdg->getDep("b4");
if(dep.size()==0){
if(verbose)cout<<"no dependence"<<endl;
return NULL;
}
string from = dep[0];
if("b4"==path[from])return NULL;
path[from]="b4";
if(verbose)cout<<"from "<<from<<"to b4"<<endl;
return NULL;
}
|
#include<string>
#include<iostream>
using namespace std;
class address{
private:
char name[10];
char city[10];
public:
address(char *p,char *q){
//return 1;
strcpy(name,p);
strcpy(city,q);
}
};
class date{
private:
int day,month,year;
date(){
day=7;month=9;year=1996;
}
};
class triplets{
private :
int t1,t2,t3;
public:
triplets(int x,int y, int z){
t1=x;t2=y;t3=z;
}
void display(){
cout<<endl<<t1<<t2<<t3;
}
};
class list{
private:
class node{
public:
int data;
node *link;
}*p;
public:
void create(){
p=new node;
p->data=10;
p->data=10;
}
};
int main(){
address my("mac","london");
printf("\ns\n");
// date today;
triplets r(2,3,4),s(0,0,0);;
r.display();
s.display();
list l1;
l1.create();
return 0;
}
|
#ifndef LogVol_PCBs_Cyl_h
#define LogVol_PCBs_Cyl_h 1
/*! @file LogVol_PCBs_Cyl.hh
@brief Defines mandatory user class LogVol_PCBs_Cyl.
@date August, 2015
@author Flechas (D. C. Flechas dcflechasg@unal.edu.co)
@version 2.0
In this header file, the 'physical' setup is defined: materials, geometries and positions.
This class defines the experimental hall used in the toolkit.
*/
#include "globals.hh"
#include "G4VSolid.hh"
#include "G4LogicalVolume.hh"
/* units and constants */
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
class G4Material;
/*! @brief This mandatory user class defines the geometry.
It is responsible for
@li Construction of geometry
\sa Construct()
*/
class LogVol_PCBs_Cyl : public G4LogicalVolume
{
public:
//! Constructor
LogVol_PCBs_Cyl(G4String fname="PCBs_Cyl_log", G4double frad=1.0*cm, G4double flen=1.0*cm);
//! Destructor
~LogVol_PCBs_Cyl();
public:
inline void SetRadius(G4double val) {Radius = val;};
inline void SetLength(G4double val) {Length = val;};
inline void SetThickness(G4double val) {Thickness = val;};
inline void SetName(G4String pname) {Name = pname;};
inline G4double GetRadius(void) {return Radius;};
inline G4double GetLength(void) {return Length;};
inline G4double GetThickness(void) {return Thickness;};
private:
void ConstructSolidVol_PCBs_Cyl(void);
void SetSolidVol_PCBs_Cyl(void);
private:
// General solid volume
G4VSolid* PCBs_Cyl_solid;
//! Name
G4String Name;
//! Dimensions and material
G4double Radius;
G4double Thickness;
G4double Length;
G4Material* Material;
};
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#endif
|
int motor_one1=9;
int motor_one2=10;
int motor_two1=5;
int motor_two2=3;
void setup() {
// put your setup code here, to run once:
pinMode(6,INPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,INPUT);
pinMode(5,OUTPUT);
pinMode(3,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int sensorstate1= digitalRead(6);
int sensorstate2= digitalRead(11);
if(sensorstate1==HIGH && sensorstate2==HIGH)
{analogWrite(9,0);
analogWrite(10,100);
analogWrite(5,0);
analogWrite(3,100);
delay(2000);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(5,0);
analogWrite(3,100);
delay(2000);
analogWrite(9,100);
analogWrite(10,0);
analogWrite(5,100);
analogWrite(3,0);
}
if(sensorstate1==LOW && sensorstate2==HIGH)
{analogWrite(9,0);
analogWrite(10,100);
analogWrite(5,0);
analogWrite(3,100);
delay(2000);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(5,0);
analogWrite(3,100);
delay(2000);
analogWrite(9,100);
analogWrite(10,0);
analogWrite(5,100);
analogWrite(3,0);
if(sensorstate1==HIGH && sensorstate2==LOW)
{analogWrite(9,0);
analogWrite(10,100);
analogWrite(5,0);
analogWrite(3,100);
delay(2000);
analogWrite(9,0);
analogWrite(10,0);
analogWrite(5,0);
analogWrite(3,100);
delay(2000);
analogWrite(9,100);
analogWrite(10,0);
analogWrite(5,100);
analogWrite(3,0);
}
}
else
analogWrite(9,100);
analogWrite(10,0);
analogWrite(5,100);
analogWrite(3,0);
}
|
#ifndef PRODUCT_H
#define PRODUCT_H
class Product {
public:
virtual ~Product() = 0;
protected:
Product();
};
class ConcreteProduct :public Product {
public:
~ConcreteProduct();
ConcreteProduct();
};
#endif
|
#ifndef AI_BATTLEPLANNER_H
#define AI_BATTLEPLANNER_H
#include <string>
#include "../Objects/Characters/Skill.h"
using std::string;
class AIBattlePlanner
{
Skill* m_SkillUsed;
size_t m_Attacker;
size_t m_Target;
public:
AIBattlePlanner();
AIBattlePlanner(Skill* SkillUsed, size_t Attacker, size_t Target);
~AIBattlePlanner();
void SetSkill(Skill* skill);
void SetAttacker(size_t attacker);
void SetTarget(size_t target);
Skill* GetSkill();
size_t GetAttacker();
size_t GetTarget();
};
#endif
|
#ifndef SIGHT_H
#define SIGHT_H
#include <GL/glu.h>
#include <QOpenGLWidget>
#include "Vector.h"
class Object;
class PlayerNeo;
class UniversalForce;
class UniversalTorque;
class QKeyEvent;
class Sight : public QOpenGLWidget
{
Q_OBJECT
public:
Sight(PlayerNeo*, UniversalForce*, UniversalTorque*);
signals:
void timeCall(void);
private:
void initializeGL(void);
void resizeGL(int, int);
void paintGL(void);
void setGluLookAt(const Vector&, const Vector&);
void paintObject(Object*);
// void paintCrashSpot(void);
void keyPressEvent(QKeyEvent*);
void keyReleaseEvent(QKeyEvent*);
Vector lookAtF;
Vector lookAtB;
Vector lookAtL;
Vector lookAtR;
Vector lookAtD;
Vector sightPointF;
Vector sightPointB;
Vector sightPointL;
Vector sightPointR;
Vector sightPointD;
short channel;
float speedHorizontal;
float speedVertical;
PlayerNeo* playerNeo;
UniversalForce* accel;
UniversalTorque* torque;
};
#endif
|
#pragma once
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <sys/random.h>
using namespace std;
namespace randomize
{
uint32_t rangeInt(uint32_t min, uint32_t max);
string queryString(uint32_t min, uint32_t max);
string cookie(uint32_t min, uint32_t max);
string path(uint32_t min, uint32_t max);
string paramName(uint32_t min, uint32_t max);
string json(uint32_t min, uint32_t max);
string escapedValue(uint32_t min, uint32_t max);
};
|
#include "ring.h"
Ring::Ring()
{
this->ringWidth = 30;
this->objectId = 5;
}
Ring::Ring(int width)
{
this->ringWidth = width;
this->objectId=5;
}
void Ring::paintShape()
{
glColor4f(0.75,0.75,0.75,0.85);
glBlendFunc(GL_SRC_ALPHA,GL_ONE);
glEnable(GL_BLEND);
glutSolidTorus(5.0,this->ringWidth,5,20);
glDisable(GL_BLEND);
}
void Ring::showTextures(bool *i){
showTexturesForObject = i;
}
|
// Copyright (c) 2022 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 _ShapeAnalysis_CanonicalRecognition_HeaderFile
#define _ShapeAnalysis_CanonicalRecognition_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Boolean.hxx>
#include <Standard_Integer.hxx>
#include <TopAbs_ShapeEnum.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Edge.hxx>
#include <GeomAbs_SurfaceType.hxx>
#include <GeomAbs_CurveType.hxx>
#include <GeomConvert_ConvType.hxx>
#include <TColStd_Array1OfReal.hxx>
class gp_Pln;
class gp_Cone;
class gp_Cylinder;
class gp_Sphere;
class gp_Lin;
class gp_Circ;
class gp_Elips;
class Geom_Curve;
class Geom_Surface;
//! This class provides operators for analysis surfaces and curves of shapes
//! in order to find out more simple geometry entities, which could replace
//! existing complex (for exampe, BSpline) geometry objects with given tolerance.
class ShapeAnalysis_CanonicalRecognition
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT ShapeAnalysis_CanonicalRecognition();
//! constructor with shape initialisation
Standard_EXPORT ShapeAnalysis_CanonicalRecognition(const TopoDS_Shape& theShape);
//! Sets shape
Standard_EXPORT void SetShape(const TopoDS_Shape& theShape);
//! Returns input shape
const TopoDS_Shape& GetShape() const
{
return myShape;
}
//! Returns deviation between input geometry entity and analytical entity
Standard_Real GetGap() const
{
return myGap;
}
//! Returns status of operation.
//! Current meaning of possible values of status:
//! -1 - algorithm is not initalazed by shape
//! 0 - no errors
//! 1 - error during any operation (usually - because of wrong input data)
//! Any operation (calling any methods like IsPlane(...), ...) can be performed
//! when current staue is equal 0.
//! If after any operation status != 0, it is necessary to set it 0 by method ClearStatus()
//! before calling other operation.
Standard_Integer GetStatus() const
{
return myStatus;
}
//! Returns status to be equal 0.
void ClearStatus()
{
myStatus = 0;
}
//! Returns true if the underlined surface can be represent by plane with tolerance theTol
//! and sets in thePln the result plane.
Standard_EXPORT Standard_Boolean IsPlane(const Standard_Real theTol, gp_Pln& thePln);
//! Returns true if the underlined surface can be represent by cylindrical one with tolerance theTol
//! and sets in theCyl the result cylinrical surface.
Standard_EXPORT Standard_Boolean IsCylinder(const Standard_Real theTol, gp_Cylinder& theCyl);
//! Returns true if the underlined surface can be represent by conical one with tolerance theTol
//! and sets in theCone the result conical surface.
Standard_EXPORT Standard_Boolean IsCone(const Standard_Real theTol, gp_Cone& theCone);
//! Returns true if the underlined surface can be represent by spherical one with tolerance theTol
//! and sets in theSphere the result spherical surface.
Standard_EXPORT Standard_Boolean IsSphere(const Standard_Real theTol, gp_Sphere& theSphere);
//! Returns true if the underlined curve can be represent by line with tolerance theTol
//! and sets in theLin the result line.
Standard_EXPORT Standard_Boolean IsLine(const Standard_Real theTol, gp_Lin& theLin);
//! Returns true if the underlined curve can be represent by circle with tolerance theTol
//! and sets in theCirc the result circle.
Standard_EXPORT Standard_Boolean IsCircle(const Standard_Real theTol, gp_Circ& theCirc);
//! Returns true if the underlined curve can be represent by ellipse with tolerance theTol
//! and sets in theCirc the result ellipse.
Standard_EXPORT Standard_Boolean IsEllipse(const Standard_Real theTol, gp_Elips& theElips);
private:
Standard_Boolean IsElementarySurf(const GeomAbs_SurfaceType theTarget, const Standard_Real theTol,
gp_Ax3& thePos, TColStd_Array1OfReal& theParams);
Standard_Boolean IsConic(const GeomAbs_CurveType theTarget, const Standard_Real theTol,
gp_Ax2& thePos, TColStd_Array1OfReal& theParams);
static Handle(Geom_Surface) GetSurface(const TopoDS_Face& theFace, const Standard_Real theTol,
const GeomConvert_ConvType theType, const GeomAbs_SurfaceType theTarget,
Standard_Real& theGap, Standard_Integer& theStatus);
static Handle(Geom_Surface) GetSurface(const TopoDS_Shell& theShell, const Standard_Real theTol,
const GeomConvert_ConvType theType, const GeomAbs_SurfaceType theTarget,
Standard_Real& theGap, Standard_Integer& theStatus);
static Handle(Geom_Surface) GetSurface(const TopoDS_Edge& theEdge, const Standard_Real theTol,
const GeomConvert_ConvType theType, const GeomAbs_SurfaceType theTarget,
gp_Ax3& thePos, TColStd_Array1OfReal& theParams,
Standard_Real& theGap, Standard_Integer& theStatus);
static Handle(Geom_Surface) GetSurface(const TopoDS_Wire& theWire, const Standard_Real theTol,
const GeomConvert_ConvType theType, const GeomAbs_SurfaceType theTarget,
gp_Ax3& thePos, TColStd_Array1OfReal& theParams,
Standard_Real& theGap, Standard_Integer& theStatus);
static Handle(Geom_Curve) GetCurve(const TopoDS_Edge& theEdge, const Standard_Real theTol,
const GeomConvert_ConvType theType, const GeomAbs_CurveType theTarget,
Standard_Real& theGap, Standard_Integer& theStatus);
static Standard_Boolean GetSurfaceByLS(const TopoDS_Wire& theWire, const Standard_Real theTol,
const GeomAbs_SurfaceType theTarget,
gp_Ax3& thePos, TColStd_Array1OfReal& theParams,
Standard_Real& theGap, Standard_Integer& theStatus);
void Init(const TopoDS_Shape& theShape);
private:
TopoDS_Shape myShape;
TopAbs_ShapeEnum mySType;
Standard_Real myGap;
Standard_Integer myStatus;
};
#endif // _ShapeAnalysis_CanonicalRecognition_HeaderFile
|
#ifndef MOTOR_HPP
#define MOTOR_HPP
class Motor {
private:
int pin1;
int pin2;
bool isDirType;
bool isInverted;
public:
Motor(int _pin1, int _pin2, bool _isDirType=true, bool _isInverted=false);
void write(int _spd);
void invert();
};
#endif
|
#include "simulation.hpp"
#include "profile/profile.hpp"
#include <kalman/kalman1d.hpp>
Simulation::Simulation(): m_realAccelerationX(1), m_basicSpeedX(1), m_basicPositionX(1), m_gpsPositionX(1), m_kalmanAccelerationX(1), m_kalmanBiasX(1), m_kalmanSpeedX(1), m_kalmanPositionX(1)
{}
const Signal& Simulation::realAccelerationX() const
{
return m_realAccelerationX;
}
const Signal& Simulation::basicSpeedX() const
{
return m_basicSpeedX;
}
const Signal& Simulation::basicPositionX() const
{
return m_basicPositionX;
}
const Signal& Simulation::gpsPositionX() const
{
return m_gpsPositionX;
}
void Simulation::run(boost::weak_ptr<Profile> profile_wk)
{
boost::shared_ptr<Profile> profile = profile_wk.lock();
if(!profile) return;
size_t N = profile->N();
m_realAccelerationX = profile->accelerationX() + Signal::noise(profile->te(), N, 0.2, 0.1);
m_basicSpeedX = m_realAccelerationX.integrate();
m_basicPositionX = m_basicSpeedX.integrate();
size_t gpsn = profile->gpsN();
size_t ratio = N / gpsn;
m_gpsPositionX = Signal(profile->gpsTe(), gpsn);
for(size_t i = 0; i < gpsn; i++)
m_gpsPositionX[i] = profile->positionX()[i*ratio];
if(profile->noisyGPS())
{
m_gpsPositionX += Signal::noise(profile->gpsTe(), gpsn, 0, 100);
}
//run Kalman filter
m_kalmanAccelerationX = Signal(profile->te(), N);
m_kalmanBiasX = Signal(profile->te(), N);
m_kalmanSpeedX = Signal(profile->te(), N);
m_kalmanPositionX = Signal(profile->te(), N);
Kalman1D kf;
size_t j = 0;
for(size_t i = 0; i < N; i++)
{
Matrix<1, 1> input(m_realAccelerationX[i]);
kf.predict(input);
if(i % ratio == 0)
{
Matrix<1, 1> measurement = m_gpsPositionX[j];
kf.update(measurement);
j++;
}
const Matrix<4,1>& state = kf.state();
m_kalmanAccelerationX[i] = state(0, 0);
m_kalmanBiasX[i] = state(1, 0);
m_kalmanSpeedX[i] = state(2, 0);
m_kalmanPositionX[i] = state(3, 0);
}
}
|
#include "../inc/SEMD2Mesh.h"
#include <cstdio>
template <class T>
bool SEMD2Mesh<T>::loadBufferFromFile(std::string f, uint32_t i)
{
FILE *fp; // ponteiro de arquivo
tMD2 *header; // header do modelo
char *buffer; // buffer dos frames
tMD2Frame<T> *frame; // frame temporário
tMD2Vertex *ptrverts; // ponteiro para vértices
int *ptrnormals; // ponteiro para normais
// tenta abrir arquivo
if( (fp = fopen( f.c_str(), "rb" )) == NULL )
{
//printf("\nErro ao abrir arquivo %s", f.c_str());
return false;
}
// aloca memória para o header do modelo
if( !(header = new tMD2) )
{
//printf("\nErro de alocacao do MD2");
return false;
}
// lê o cabeçalho
fread( header, sizeof( tMD2 ), 1, fp );
// verifica o número mágico e a versão do arquivo
if( (header->ident != MD2_IDENT) && (header->version != MD2_VERSION) )
{
delete header;
fclose( fp );
return false;
}
// guarda as variáveis do cabeçalho localmente
numFrames = header->num_frames;
numXYZ = header->num_xyz;
numGlCmds = header->num_glcmds;
skinW = header->skinwidth;
skinH = header->skinheight;
// alocação de memória para os dados da geometria
vertices = new tMD2Vertex[ numXYZ * numFrames ];
lightnormals = new int[ numXYZ * numFrames ];
buffer = new char[ numFrames * header->framesize ];
glcmds = new int[ numGlCmds ];
// leitura do arquivo
fseek( fp, header->ofs_frames, SEEK_SET ); // le frames
fread( buffer, numFrames * header->framesize, 1, fp );
fseek( fp, header->ofs_glcmds, SEEK_SET ); // le diretivas opengl
fread( glcmds, numGlCmds, sizeof( int ), fp );
// inicializa o vertexbuffer
SEMesh<T>::vb_[i]=new SEVertexBuffer<T>();
// inicializa tabela de vértices
for( int j = 0; j < numFrames; j++ )
{
frame = (tMD2Frame<T>*)&buffer[ header->framesize * j ];
ptrverts = &vertices[ numXYZ * j ];
ptrnormals = &lightnormals[ numXYZ * j ];
for( int k = 0; k < numXYZ; ++k )
{
static SEVertex<T> v_;
// coordenadas do vértice
v_[0] = (frame->scale[1] * frame->verts[k].v[1] + frame->translate[1]);
v_[1] = (frame->scale[2] * frame->verts[k].v[2] + frame->translate[2]);
v_[2] = (frame->scale[0] * frame->verts[k].v[0] + frame->translate[0]);
// normal do vértice
v_[3] = vertexNormals[frame->verts[k].lightnormalindex].v[0];
v_[4] = vertexNormals[frame->verts[k].lightnormalindex].v[1];
v_[5] = vertexNormals[frame->verts[k].lightnormalindex].v[2];
v_.l =
SEMesh<T>::vb_[i].append(v_);
}
}
// fecha o arquivo
fclose( fp );
// limpeza da memória temporária
delete header;
delete [] buffer;
//calculateBoundBox();
return true;
}
|
#include <iostream>
#include <fstream>
#include <string>
#include "wordfinder.h"
using namespace std;
int main()
{
WordFinder wf;
ifstream file("in.txt");
cout<<(file.is_open()?"opened in.txt file":"input file doesn't open")<<endl;
ofstream out("out.txt");
cout<<(out.is_open()?"opened out.txt file":"output file doesn't open")<<endl;
string textIn;
getline(file, textIn);
wf.addText(textIn);
int cWords;
file >> cWords;
string wordToFind;
while((file >> wordToFind) && cWords--)
out << wf.findWord(wordToFind);
file.close();
out.close();
return 0;
}
|
#ifndef COMMANDS_H_
#define COMMANDS_H_
#include <string>
#include "Triggers.h"
using namespace std;
class Commands: public Triggers{
public:
Commands();
string getCommand();
void setCommand(string);
private:
string command;
};
#endif
|
#include "login_form.h"
#include "complex_form.h"
using namespace mmcomplex;
void login_form::auth_do()
{
String^ login = L"admin\n";
String^ password = L"admin\n";
bool auth = true;
if (edit_login->Text == L"" || edit_password->Text == L"")
{
edit_login->Text = L"Введите логин и пароль!";
auth = false;
}
if (!auth)
{
return;
}
if (edit_password->Text == L"admin" && edit_login->Text == L"admin")
{
complex_form^ form = gcnew complex_form();
form->Show();
this->Hide();
}
else
{
edit_password->Clear();
edit_login->Text = L"Неправильный логин или пароль!";
}
}
void login_form::button_go_Click(System::Object^ sender, System::EventArgs^ e)
{
auth_do();
}
void login_form::login_form_KeyDown(System::Object^ sender, System::Windows::Forms::KeyEventArgs^ e)
{
if (e->KeyCode == System::Windows::Forms::Keys::Enter)
{
auth_do();
}
}
|
//
// Created by 송지원 on 2019-11-13.
//
#include "iostream"
using namespace std;
int main() {
int i,j, N;
long long D[91][2];
D[1][0] = 0;
D[1][1] = 1;
cin >> N;
for (i=2; i<=N; i++) {
D[i][0] = D[i-1][0] + D[i-1][1];
D[i][1] = D[i-1][0];
}
cout << D[N][0] + D[N][1] << endl;
}
|
#pragma once
#include <vector>
// 需要尽量高效的插入和删除
// 需要方便的找到最大元素
#include <set>
#include <string>
#include <functional>
#include <sys/select.h>
#include "tcp_socket.hpp"
bool operator<(const TcpSocket& lhs, const TcpSocket& rhs)
{
return lhs.GetFd() < rhs.GetFd();
}
class Selector
{
public:
void Add (const TcpSocket& sock)
{
printf("[Selector::Add] %d\n", sock.GetFd());
socket_set_.insert(sock);
}
void Del (const TcpSocket& sock)
{
printf("[Selector::Del] %d\n", sock.GetFd());
socket_set_.erase(sock);
}
// Wait 返回的时候要告诉用户哪个文件描述符就绪了
void Wait(std::vector<TcpSocket>* output)
{
// 调用 Wait 就相当于调用 select 进行等待
// 先获取到最大文件描述符
if (socket_set_.empty())
{
printf("[Selector::Wait] socket_set_ is empty\n");
return;
}
int max_fd = socket_set_.rbegin()->GetFd();
fd_set readfds;
FD_ZERO(&readfds);
// 把每个关注的 fd 都添加到 readfds 中
for (const auto& sock : socket_set_)
{
FD_SET(sock.GetFd(), &readfds);
}
// 默认是阻塞等待, 有文件描述符就绪的时候,才会返回
// 当函数返回后,根据函数的返回情况构造输出参数,告诉调用者哪些描述符就绪了
int nfds = select(max_fd + 1, &readfds, nullptr, nullptr, nullptr);
if (nfds < 0)
{
perror("Select");
return;
}
for (int fd = 0; fd < max_fd + 1; fd++)
{
if (FD_ISSET(fd, &readfds))
{
output->push_back(TcpSocket(fd));
}
}
}
private:
// 用一个数据结构把文件描述符存起来
// 要求 TCPSocket 类能支持比较操作 operator<
std::set<TcpSocket> socket_set_;
};
typedef std::function<void (const std::string&, std::string*)> Handler;
#define CHECK_RET(exp) \
if (!exp) \
{\
return false;\
}
// 实现一个 Select 版本的 TCP server
class TcpSelectServer
{
public:
bool Start(const std::string& ip, uint16_t port,
Handler handler)
{
// 创建 socket
TcpSocket listen_socket;
CHECK_RET(listen_socket.Socket());
CHECK_RET(listen_socket.Bind(ip, port));
CHECK_RET(listen_socket.Listen());
// 创建一个 select 对象把 listen_socket 管理起来
Selector selector;
selector.Add(listen_socket);
// 后续进行等待都是靠 selector 对象完成
// 进入主循环
while (true)
{
// 不再是直接调用 accept
// 而是用 seletor 进行多路复用
std::vector<TcpSocket> output;
selector.Wait(&output);
// 遍历返回结果,一次处理每个就绪的 socket
for (auto& tcp_socket : output)
{
// 分成两种情况讨论
// a) 如果就绪的是 listen_socket 调用 accept
if (tcp_socket.GetFd() == listen_socket.GetFd())
{
TcpSocket client_socket;
std::string ip;
uint16_t port;
tcp_socket.Accept(&client_socket, &ip, &port);
printf("[client %s:%d] connected\n", ip.c_str(), port);
selector.Add(client_socket);
}
// b) 如果就绪的 socket 不是 listen_socket 调用 recv
else
{
std::string req;
int ret = tcp_socket.Recv(&req);
if (ret < 0)
{
continue;
}
else if (0 == ret)
{
printf("对端关闭!\n");
selector.Del(tcp_socket);
tcp_socket.Close();
continue;
}
printf("[client] %s\n", req.c_str());
std::string resp;
// 根据请求完成响应的过程
handler(req, &resp);
tcp_socket.Send(resp);
}
}
}
}
private:
};
|
#include "ResultScene.h"
#include "DxLib.h"
#include "Game.h"
#include "Peripheral.h"
#include "TitleScene.h"
#include <cmath>
const float waitTime = 30.0f;
const int defInterval = 60;
const int ShortInterval = 10;
void ResultScene::FadeinUpdate(const Peripheral & p)
{
_wait = max((_wait - 1), 0);
SetDrawBlendMode(DX_BLENDGRAPHTYPE_ALPHA, 255 - 255 * (_wait / waitTime));
Draw();
if (_wait == 0) {
_updater = &ResultScene::NormalUpdate;
}
}
void ResultScene::NormalUpdate(const Peripheral & p)
{
Draw();
if (p.IsTrigger(PAD_INPUT_10)) {
_Interval = ShortInterval;
_updater = &ResultScene::FadeoutUpdate;
_wait = waitTime;
}
}
void ResultScene::FadeoutUpdate(const Peripheral & p)
{
_wait = max((_wait - 1), 0);
Draw();
SetDrawBlendMode(DX_BLENDGRAPHTYPE_ALPHA, 255 * (_wait / waitTime));
if (_wait == 0) {
Game::Instance().ChangeScene(new TitleScene());
}
}
ResultScene::ResultScene()
{
_resultImgH1 = LoadGraph("image/Result1.png");
_resultImgH2 = LoadGraph("image/Result2.png");
_wait = waitTime;
_count = 0;
_Interval = defInterval;
_updater = &ResultScene::FadeinUpdate;
}
ResultScene::~ResultScene()
{
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
}
void ResultScene::Update(const Peripheral & p)
{
_count++;
(this->*_updater)(p);
}
void ResultScene::Draw()
{
DxLib::DrawRotaGraph(512 / 2, 480 / 2, 2, 0, _resultImgH1, true);
}
|
#include <bits/stdc++.h>
using namespace std;
void solve () {
int n;
cin >> n;
vector<int> s(n);
for (auto& it: s) cin >> it;
sort(s.begin(), s.end());
int ans = 1000;
for (int i=1; i<n; ++i) {
ans = min(ans, abs(s[i] - s[i-1]));
}
cout << ans << endl;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* The idea for this class is arjanl's (arjanl@opera.com), faithfully executed
* by psmaas (psmaas@opera.com) and later cleaned up by Eddy.
*/
#ifndef MODULES_UTIL_ADT_OP_FILTERED_VECTOR_H
#define MODULES_UTIL_ADT_OP_FILTERED_VECTOR_H
# ifdef UTIL_OP_FILTERED_VECTOR
#include "modules/util/adt/opvector.h"
template<class T>
class OpFilteredVectorItem;
/** Indexing mode.
*
* Where OpFilteredVector's methods take or return an index into the vector, it
* is always given relative to one of these modes, each of which selects a
* subset of the vector's members. The index of an entry in the array, with
* respect to a given indexing mode, is the number of earlier entries in the
* array that are included in that indexing mode's subset.
*/
enum FilteredVectorIndex
{
CompleteVector, //< All entries are included
VisibleVector, //< Only the visible entries are counted; used by default
InvisibleVector //< Only the invisible entries are counted
};
/** A vector with entries selectively visible.
*
* The OpFilteredVector class creates a layer of abstraction over the vector
* containing the items to be able to efficiently look up and insert into the
* vector. This layer of abstraction is necessary to support a concept of
* "hidden" or filtered items. The presence of these filtered items can be
* transparent by the user having a virtual index into the vector.
*
* This is done by keeping an external sorted vector with the indexes of the
* filtered items.
*
* This external vector makes it possible to calculate the real index of items
* which makes lookups and inserts more efficient.
*
* @tparam T Type of entries in the vector: must have OpFilteredVectorItem<T> as
* one of its public bases.
*/
template<class T>
class OpFilteredVector
{
public:
/** Add item to (the end of) a vector.
*
* @param item to be added
* @return OpStatus::OK if successful
*/
OP_STATUS Add(T* item) { return Insert(GetCount(CompleteVector), item, CompleteVector); }
/** Insert item at specified index in vector.
*
* @param index Where item should be inserted.
* @param item What to insert.
* @param mode Indexing mode; see FilteredVectorIndex.
* @return OpStatus::OK if successful
*/
OP_STATUS Insert(UINT32 index, T* item, FilteredVectorIndex mode = VisibleVector)
{
if (!item)
return OpStatus::ERR;
// Make sure the index is into the complete vector
index = GetIndex(index, mode, CompleteVector);
// Update invisible items
UINT32 invisible_count = m_filtered_indices.GetCount();
for (UINT32 i = m_filtered_indices.Search(index); i < invisible_count; i++)
{
INT32 value = m_filtered_indices.Get(i);
if (value >= static_cast<INT32>(index))
m_filtered_indices.Replace(i, value + 1);
}
if (item->IsFiltered())
{
// Add index to m_filtered_indices
UINT32 idx = m_filtered_indices.Search(index);
if (idx == m_filtered_indices.GetCount() || // Insert last
static_cast<INT32>(index) != m_filtered_indices.Get(idx))
// Not already there
m_filtered_indices.Insert(idx, index);
else
OP_ASSERT(!"Either an item was readded or I failed to insert it");
}
return m_items.Insert(index, item);
}
/** Remove item at specified index from the vector.
*
* @param index Index of the item to be removed.
* @param mode Indexing mode; see FilteredVectorIndex.
* @return Pointer to the item removed.
*/
T* Remove(UINT32 index, FilteredVectorIndex mode = VisibleVector)
{
// Make sure the index is into the complete vector
index = GetIndex(index, mode, CompleteVector);
// Update invisible items
for (UINT32 i = m_filtered_indices.GetCount();
m_filtered_indices.Get(--i) >= (int) index + 1; )
m_filtered_indices.Replace(i, m_filtered_indices.Get(i) - 1);
T* item = m_items.Remove(index);
if (item && item->IsFiltered())
{
// Remove index from m_filtered_indices
UINT32 idx = m_filtered_indices.Search(index);
if (idx < m_filtered_indices.GetCount() && // in range
(int) index == m_filtered_indices.Get(idx)) // present
m_filtered_indices.Remove(idx);
else
OP_ASSERT(!"Item was not there");
}
return item;
}
/** Remove an item, specified by its value, from the vector.
*
* @note Has the same limitation as Find(). In particular, if there is a
* copy of the given item, at an index suppressed in the given mode, before
* a later copy at an index visible in the given mode, the former shall
* prevent the latter from being noticed, hence from being removed.
*
* @param item The item to remove (identified using Find(item, mode)).
* @param mode Indexing mode; item is only removed if visible in this mode.
* @return OpStatus::OK if successful, OpStatus::ERR on failure.
*/
OP_STATUS RemoveByItem(T* item, FilteredVectorIndex mode = VisibleVector)
{
INT32 index = Find(item, mode);
return index >= 0 && Remove(index, mode) ? OpStatus::OK : OpStatus::ERR;
}
/** Look up item at a specified index in the vector.
*
* @param index of the desired item
* @param mode Indexing mode; see FilteredVectorIndex.
* @return pointer to the item if present else NULL
*/
T* Get(UINT32 index, FilteredVectorIndex mode = VisibleVector) const
{
return m_items.Get(mode == CompleteVector ? index :
static_cast<UINT32>(GetIndex(index, mode, CompleteVector)));
}
/**
* @param mode Indexing mode; see FilteredVectorIndex.
* @return The number of items visible in this mode.
*/
INT32 GetCount(FilteredVectorIndex mode = VisibleVector)
{
switch (mode)
{
case CompleteVector: return m_items.GetCount();
case VisibleVector: return m_items.GetCount() - m_filtered_indices.GetCount();
case InvisibleVector: return m_filtered_indices.GetCount();
}
OP_ASSERT(!"Bad indexing mode");
return 0;
}
/** Clear the vector.
*
* Deletes all the items (including the filtered items) and
* clears the filtered index array.
*/
void DeleteAll() { m_items.DeleteAll(); m_filtered_indices.Clear(); }
/** Finds the index of a given item.
*
* Locates the first instance of the given item in the vector; if this index
* is valid for the given indexing mode, its index in that mode is returned;
* else -1 is returned.
*
* @note If the vector includes a later instance of the item at an index
* visible in the desired mode, this will be hidden by any earlier instance
* at an index suppressed by the mode.
*
* @param item The item to find.
* @param mode Indexing mode; see FilteredVectorIndex.
* @return The item's index in the given mode, or -1.
*/
INT32 Find(T* item, FilteredVectorIndex mode = VisibleVector) const
{
INT32 index = m_items.Find(item);
switch (mode)
{
case CompleteVector: return index;
case VisibleVector:
{
UINT32 idx = m_filtered_indices.Search(index);
return (idx < m_filtered_indices.GetCount() &&
index == m_filtered_indices.Get(idx))
? -1 : GetIndex(index, CompleteVector, mode);
}
case InvisibleVector:
{
UINT32 idx = m_filtered_indices.Search(index);
return (idx < m_filtered_indices.GetCount() &&
index == m_filtered_indices.Get(idx))
? GetIndex(index, CompleteVector, mode) : -1;
}
}
OP_ASSERT(!"Bad indexing mode");
return 0;
}
/** Duplicate another filtered vector.
*
* @param vec to be copied
* @return See OpStatus.
*/
OP_STATUS DuplicateOf(OpFilteredVector& vec)
{
RETURN_IF_ERROR(m_items.DuplicateOf(vec.GetItems()));
return m_filtered_indices.DuplicateOf(vec.GetFilteredIndexes());
}
/** Translates an index between modes.
*
* Note that translating from visible to invisible (and vice versa) does not
* make sense and will cause an assertion. Cases where neither in or out
* mode is CompleteVector do not make sense and will return index.
*
* @param index The index to be translated
* @param in_mode Indexing mode in which to interpret index.
* @param out_mode Indexing mode to use for returned value.
* @return The specified output index.
*/
INT32 GetIndex(INT32 index,
FilteredVectorIndex in_mode,
FilteredVectorIndex out_mode) const
{
if (in_mode == out_mode) // pointless request - but harmless
return index;
if (out_mode == CompleteVector)
return GetCompleteIndex(index, in_mode);
if (in_mode == CompleteVector)
return GetFilteredIndex(index, out_mode);
OP_ASSERT(!"Incoherent index conversion request");
return index;
}
/** Control visibility of a given index's contents.
*
* @param index Index of the entry whose visibility is to be modified.
* @param visible TRUE to make the entry visible, FALSE to make it invisible.
*/
void SetVisibility(INT32 index, BOOL visible)
{
if (index < 0)
return;
T* item = m_items.Get(index);
if (item)
{
item->m_filtered = !visible;
if (visible)
m_filtered_indices.RemoveByItem(index);
else
{
// Add index to m_filtered_indices
UINT32 idx = m_filtered_indices.Search(index);
if (idx == m_filtered_indices.GetCount() || // Insert last
index != m_filtered_indices.Get(idx)) // Not already there
m_filtered_indices.Insert(idx, index);
}
}
}
private:
/**
* @param index into the filtered vector
* @return the actual index into the vector
*/
INT32 GetCompleteIndex(INT32 index, FilteredVectorIndex out_index = VisibleVector) const
{
if (index < 0)
return -1;
INT32 invisible_count = m_filtered_indices.GetCount();
switch (out_index)
{
// Included for completeness, despite making little sense:
case CompleteVector: return index;
case VisibleVector:
{
INT32 pos = index;
for (INT32 i = 0; i < invisible_count && m_filtered_indices.Get(i) <= pos; i++)
pos++;
return pos;
}
case InvisibleVector:
if (index >= invisible_count)
return m_items.GetCount();
return m_filtered_indices.Get(index);
}
OP_ASSERT(!"Bad indexing mode");
return -1;
}
/**
* @param index into the actual vector
* @return the index among the filter items
*/
INT32 GetFilteredIndex(INT32 index, FilteredVectorIndex mode = VisibleVector) const
{
switch (mode)
{
// Included for completeness, despite making little sense:
case CompleteVector: return index;
case VisibleVector:
{
UINT32 nearest_index = m_filtered_indices.Search(index);
// Check if they are all smaller than index:
if (nearest_index == m_filtered_indices.GetCount())
return index - m_filtered_indices.GetCount();
INT32 nearest_item_pos = m_filtered_indices.Get(nearest_index);
if (nearest_item_pos < index)
return index - (nearest_index + 1);
else if (nearest_item_pos > index)
return index - nearest_index;
else
return -1; // Item is invisible
}
case InvisibleVector:
{
UINT32 idx = m_filtered_indices.Search(index);
if (idx < m_filtered_indices.GetCount() && // in range
index == m_filtered_indices.Get(idx)) // present
return idx;
return -1; // Item is visible
}
}
OP_ASSERT(!"Bad indexing mode");
return 0;
}
OpVector<T>& GetItems() { return m_items; }
OpINT32Vector& GetFilteredIndexes() { return m_filtered_indices; }
OpVector<T> m_items;
OpINT32Vector m_filtered_indices;
};
template<class T>
class OpFilteredVectorItem
{
public:
virtual ~OpFilteredVectorItem() {} // we expect to be sub-classed
friend class OpFilteredVector<T>; // SetVisibility modifies m_filtered
OpFilteredVectorItem(BOOL filtered) : m_filtered(filtered) {}
BOOL IsFiltered() { return m_filtered; }
private:
BOOL m_filtered;
};
# endif // UTIL_OP_FILTERED_VECTOR
#endif // MODULES_UTIL_ADT_OP_FILTERED_VECTOR_H
|
/**
* Copyright (c) 2022, Timothy Stack
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of Timothy Stack 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 REGENTS 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 REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <algorithm>
#include "pollable.hh"
#include "base/itertools.hh"
#include "base/lnav_log.hh"
pollable::pollable(std::shared_ptr<pollable_supervisor> supervisor,
category cat)
: p_supervisor(supervisor), p_category(cat)
{
log_debug("pollable attach %p to %p", this, this->p_supervisor.get());
this->p_supervisor->attach(this);
}
pollable::~pollable()
{
log_debug("pollable detach %p from %p", this, this->p_supervisor.get());
this->p_supervisor->detach(this);
}
pollable_supervisor::update_result
pollable_supervisor::update_poll_set(std::vector<struct pollfd>& pollfds)
{
update_result retval;
size_t old_size = pollfds.size();
for (auto& pol : this->b_components) {
pol->update_poll_set(pollfds);
switch (pol->get_category()) {
case pollable::category::background:
retval.ur_background += pollfds.size() - old_size;
break;
case pollable::category::interactive:
retval.ur_interactive += pollfds.size() - old_size;
break;
}
old_size = pollfds.size();
}
return retval;
}
void
pollable_supervisor::check_poll_set(const std::vector<struct pollfd>& pollfds)
{
std::vector<pollable*> visited;
auto found_new = false;
// TODO move this loop into the superclass
do {
found_new = false;
for (auto* pol : this->b_components) {
if (std::find(visited.begin(), visited.end(), pol) == visited.end())
{
visited.emplace_back(pol);
pol->check_poll_set(pollfds);
found_new = true;
break;
}
}
} while (found_new);
}
size_t
pollable_supervisor::count(pollable::category cat)
{
size_t retval = 0;
for (const auto* pol : this->b_components) {
if (pol->get_category() == cat) {
retval += 1;
}
}
return retval;
}
short
pollfd_revents(const std::vector<struct pollfd>& pollfds, int fd)
{
return pollfds | lnav::itertools::find_if([fd](const auto& entry) {
return entry.fd == fd;
})
| lnav::itertools::deref() | lnav::itertools::map(&pollfd::revents)
| lnav::itertools::unwrap_or((short) 0);
}
bool
pollfd_ready(const std::vector<struct pollfd>& pollfds, int fd, short events)
{
return std::any_of(
pollfds.begin(), pollfds.end(), [fd, events](const auto& entry) {
return entry.fd == fd && entry.revents & events;
});
}
|
/*
* Array-based Stack
*
*/
#ifndef STACK_H
#define STACK_H
template <typename E>
class Stack {
public:
Stack(int maxsize = 0);
void push(E e);
bool isEmpty() const { return size == 0; }
E pop();
E last() const { return stack[size-1]; }
private:
E* stack;
int size;
int maxSize;
void resize(int newSize);
};
template <typename E>
Stack<E>::Stack(int maxsize) {
maxSize = maxsize;
size = 0;
first = last = 0;
if (maxSize <= 0)
stack = NULL;
else
stack = new E[maxSize];
}
template <typename E>
void Stack<E>::push(E e) {
if (maxSize == 0) {
stack = new E[1];
stack[0] = e;
maxSize = 1;
size = 1;
return;
}
if (size == maxSize)
resize(2*maxSize);
stack[size++] = e;
return;
}
template <typename E>
void Stack<E>::resize(int newSize) {
E* temp = stack;
stack = new E[newSize];
for (int i = 0; i < size; ++i)
stack[i] = temp[i];
maxSize = newSize;
delete [] temp;
}
template <typename E>
E Stack<E>::pop() {
if (size == 0)
std::cout << "The Stack was empty.\n";
if (size <= maxSize/4)
resize(maxSize/2);
return stack[--size];
}
#endif
|
#pragma once
#include "proto/ss_base.pb.h"
#include "proto/processor.hpp"
#include "utils/server_process_base.hpp"
namespace ps = proto::ss;
namespace nora {
namespace scene {
class common_resource : public proto::processor<common_resource, ps::base>,
public server_process_base,
public enable_shared_from_this<common_resource> {
public:
common_resource(const string& name);
static void static_init();
friend ostream& operator<<(ostream& os, const common_resource& m) {
return os << m.name_;
}
static string base_name();
private:
void process_lock_fanli_rsp(const ps::base *msg);
void process_lock_come_back_rsp(const ps::base *msg);
const string name_;
};
}
}
|
#include <iostream>
using namespace std;
int main()
{
int i,j,max=1;
for(i=1; i<=5; i++)
{
cout<<""<<endl;
for(j=1;j<=max; j++)
{
cout << "*"<<endl;
}
max++;
}
return 0;
}
|
#include <memory>
#include "base/scheduling/scheduling_handles.h"
#include "base/scheduling/task_loop.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker.h"
#include "gtest/gtest.h"
namespace base {
class ThreadCheckerTest: public testing::Test {
public:
ThreadCheckerTest() = default;
virtual void SetUp() override {
task_loop_ = TaskLoop::Create(ThreadType::UI);
worker_1_.Start();
worker_2_.Start();
WaitForAllThreadsToStart();
}
void WaitForAllThreadsToStart() {
GetWorker1TaskRunner()->PostTask(task_loop_->QuitClosure());
task_loop_->Run();
GetWorker2TaskRunner()->PostTask(task_loop_->QuitClosure());
task_loop_->Run();
}
virtual void TearDown() override {
printf("TearDown() ------\n");
task_loop_.reset();
worker_1_.Stop();
worker_2_.Stop();
}
std::shared_ptr<TaskRunner> GetWorker1TaskRunner() {
return worker_1_.GetTaskRunner();
}
std::shared_ptr<TaskRunner> GetWorker2TaskRunner() {
return worker_2_.GetTaskRunner();
}
void UnblockMainThread() {
return task_loop_->Quit();
}
void Wait() {
task_loop_->Run();
}
private:
std::shared_ptr<TaskLoop> task_loop_;
base::Thread worker_1_;
base::Thread worker_2_;
};
TEST_F(ThreadCheckerTest, ConstructedOnMainThread) {
std::unique_ptr<ThreadChecker> checker(new ThreadChecker());
EXPECT_TRUE(checker->CalledOnConstructedThread());
GetWorker1TaskRunner()->PostTask([&](){
EXPECT_FALSE(checker->CalledOnConstructedThread());
UnblockMainThread();
});
Wait();
GetWorker2TaskRunner()->PostTask([&](){
EXPECT_FALSE(checker->CalledOnConstructedThread());
UnblockMainThread();
});
Wait();
}
TEST_F(ThreadCheckerTest, ConstructedOnWorkerThread) {
std::unique_ptr<ThreadChecker> checker;
GetWorker1TaskRunner()->PostTask([&](){
checker = std::unique_ptr<ThreadChecker>(new ThreadChecker());
EXPECT_TRUE(checker->CalledOnConstructedThread());
UnblockMainThread();
});
Wait();
EXPECT_FALSE(checker->CalledOnConstructedThread());
GetWorker2TaskRunner()->PostTask([&](){
EXPECT_FALSE(checker->CalledOnConstructedThread());
UnblockMainThread();
});
Wait();
}
}; // namespace base
|
//====================================================================================
// @Title: STRING
//------------------------------------------------------------------------------------
// @Location: /prolix/common/include/xString.h
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//------------------------------------------------------------------------------------
// @Description:
//
// Simple string tools to manipulate string data types and enhance aesthetic for
// logging inFormation, conversion from numerical types, and the RPG component of
// the project.
//
//====================================================================================
#ifndef __PROLIX_BASE_COMMON_STRING_H__
#define __PROLIX_BASE_COMMON_STRING_H__
#include <string>
#include <sstream>
//====================================================================================
// String
//====================================================================================
class String : public std::string
{
friend extern std::ostream &operator<<(std::ostream &os, String str);
friend extern String operator+(String str1, String str2);
friend extern String operator+(std::string str1, String str2);
friend extern String operator+(String str1, std::string str2);
friend extern bool operator==(String str1, String str2);
friend extern bool operator!=(String str1, String str2);
bool IsWhitespace(char c);
std::string mSource;
public:
String UpperCase(); // converts String to all uppercase characters
String LowerCase(); // converts String to all lowercase characters
String Capitalize(); // capitalizes the first word
String CamelCase(); // capitalizes every word
float ToNumber(); // converts the String equivalent to a number (float)
unsigned int length(); // returns length of the String
std::string Source(); // returns source of the native C++ string
void SetSource(std::string str); // sets a string value to mSource
// replaces a substring of a String
String replace(String query, String replacement);
String replace(std::string query, std::string replacement);
// removes a substring from String
String remove(String query);
String remove(std::string query);
// trims off leading and trailing whitespace
String trim();
// removes any consective instances of whitespace + trims
String format();
// returns a String index if query exists in String else -1
int find(String query);
int find(std::string query);
// returns true if query exists in string; else false
bool exists(String query);
bool exists(std::string query);
// Constructors
String();
String(std::string str);
String operator=(std::string str);
String operator=(char *str);
};
//====================================================================================
// External
//====================================================================================
// operations
extern std::ostream &operator<<(std::ostream &os, String str);
extern String operator+(String str1, String str2);
extern String operator+(std::string str1, String str2);
extern String operator+(String str1, std::string str2);
extern bool operator==(String str1, String str2);
extern bool operator!=(String str1, String str2);
// converts a char array to string
std::string toString(char *char_array);
// trim outlying whitespace characters
std::string Trim(std::string str);
// converts a number to type string
template <typename T> std::string toString(T n)
{
std::stringstream s;
s << n;
return s.str();
}
float ToNumber(std::string s);
#endif
|
#include "ParallelPrimeFinder.h"
void ParallelPrimeFinder::test(int min, int max)
{
omp_set_num_threads(MAX_THREAD_NUM);
try {
std::stringstream ss;
ss << name() << " (" << MAX_THREAD_NUM << " threads)";
printResult(ss.str(), measureTime(min, max));
}
catch (std::exception e) {
std::cerr << e.what() << std::endl;
}
}
|
#include "MxAudioSource.h"
#include "../../GameObject/MxGameObject.h"
#include "../RigidBody/MxRigidBody.h"
#include "../../Time/MxTime.h"
#include <fmod/fmod.hpp>
namespace Mix {
MX_IMPLEMENT_RTTI(AudioSource, Component);
void AudioSource::setMute(const bool _mute) {
if (mChannel)
mChannel->setMute(_mute);
else
mChannelParam.mute = _mute;
}
bool AudioSource::getMute() const {
if (mChannel)
mChannel->getMute(&mChannelParam.mute);
return mChannelParam.mute;
}
bool AudioSource::getPaused() const {
if (mChannel)
mChannel->getPaused(&mChannelParam.paused);
return mChannelParam.paused;
}
void AudioSource::setPaused(const bool _paused) {
if (mChannel)
mChannel->setPaused(_paused);
else
mChannelParam.paused = _paused;
}
float AudioSource::getVolume() const {
if (mChannel)
mChannel->getVolume(&mChannelParam.volume);
return mChannelParam.volume;
}
void AudioSource::setVolume(const float _volume) {
if (mChannel)
mChannel->setVolume(_volume);
else
mChannelParam.volume = _volume;
}
bool AudioSource::getVolumeRamp() const {
if (mChannel)
mChannel->getVolumeRamp(&mChannelParam.volumRamp);
return mChannelParam.volumRamp;
}
void AudioSource::setVolumeRamp(const bool _volumeRamp) {
if (mChannel)
mChannel->setVolumeRamp(_volumeRamp);
else
mChannelParam.volumRamp = _volumeRamp;
}
float AudioSource::getPitch() const {
if (mChannel)
mChannel->getPitch(&mChannelParam.pitch);
return mChannelParam.pitch;
}
void AudioSource::setPitch(const float _pitch) {
if (mChannel)
mChannel->setPitch(_pitch);
else
mChannelParam.pitch = _pitch;
}
Vector2f AudioSource::get3DMinMaxDistance() const {
if (mChannel)
mChannel->get3DMinMaxDistance(&mChannelParam.distance.x, &mChannelParam.distance.y);
return mChannelParam.distance;
}
void AudioSource::set3DMinMaxDistance(const Vector2f& _distance) {
if (mChannel)
mChannel->set3DMinMaxDistance(_distance.x, _distance.y);
else
mChannelParam.distance = _distance;
}
float AudioSource::get3DDopplerLevel() const {
if (mChannel)
mChannel->get3DDopplerLevel(&mChannelParam.level);
return mChannelParam.level;
}
void AudioSource::set3DDopplerLevel(const float _level) {
if (mChannel)
mChannel->set3DDopplerLevel(_level);
else
mChannelParam.level = _level;
}
float AudioSource::getFrequency() const {
if (mChannel)
mChannel->getFrequency(&mChannelParam.Frequency);
return mChannelParam.Frequency;
}
void AudioSource::setFrequency(const float _frequency) {
if (mChannel)
mChannel->setFrequency(_frequency);
else
mChannelParam.Frequency = _frequency;
}
int AudioSource::getPriority() const {
if (mChannel)
mChannel->getPriority(&mChannelParam.Priority);
return mChannelParam.Priority;
}
void AudioSource::setPriority(const int _priority) {
if (mChannel)
mChannel->setPriority(_priority);
else
mChannelParam.Priority = _priority;
}
void FMODChannelParam::importChannel(FMOD::Channel& _Channel) {
_Channel.getMute(&mute);
_Channel.getPaused(&paused);
_Channel.getVolume(&volume);
_Channel.getVolumeRamp(&volumRamp);
_Channel.getPitch(&pitch);
_Channel.get3DMinMaxDistance(&distance.x, &distance.y);
_Channel.get3DLevel(&level);
_Channel.getFrequency(&Frequency);
_Channel.getPriority(&Priority);
}
void FMODChannelParam::exportChannel(FMOD::Channel& _Channel) {
_Channel.setMute(mute);
_Channel.setPaused(paused);
_Channel.setVolume(volume);
_Channel.setVolumeRamp(volumRamp);
_Channel.setPitch(pitch);
_Channel.set3DMinMaxDistance(distance.x, distance.y);
_Channel.set3DLevel(level);
_Channel.setFrequency(Frequency);
_Channel.setPriority(Priority);
}
}
|
#ifndef MODELPARAMETERS_H
#define MODELPARAMETERS_H
/**
* @brief The ModelParameters class
*/
class ModelParameters
{
public:
/// The slope of the ground (radians)
double slope;
/// Our gravitational constant (or is it?)
double g;
/// These lengths represent the mass distribution of the leg segments. a1,b1 for shank, a2,b2 for thigh
double a_1,b_1,a_2,b_2;
/// The lengths of the shank, thigh and leg (derived from the values given above)
double l_s, l_t, L;
/// The mass of the hips (upper body), thigh and shank respectively
double m_h, m_t, m_s;
/// Construct some default model parameters
ModelParameters() {
// A slope of -0.05 is about as stable as the passive walker can achieve - we need to
// make sure that in this position the neural oscillator input is reduced to a minimum.
slope = -0.05;
// A reasonable choice for the effects of gravity
g = -9.81;
m_h = 1.0; // The mass of the hips
m_t = 1.0; // The mass of the thigh
// Note that the shank mass seems to have a very large impact on stability
// especially during knee and heel strike events. To improve stability, a
// simple solution could be to tone it down to about 0.02.
m_s = 0.2;
a_1 = 0.3750;
b_1 = 0.1250;
a_2 = 0.1750;
b_2 = 0.3250;
l_s = a_1+b_1;
l_t = a_2+b_2;
L = l_s+l_t;
}
};
#endif // MODELPARAMETERS_H
|
#ifndef EXEC_HOLDER_HPP_INCLUDED
#define EXEC_HOLDER_HPP_INCLUDED
#include <elfio/elfio.hpp>
#include <cstdint>
class ExeHolder {
// begin of aligned storage
void *AllocPtr;
uint64_t Base;
int PageSize;
int RetCode;
void memoryInitSegment(const ELFIO::segment &S, int AllocSize);
public:
ExeHolder():
AllocPtr(nullptr), Base(0), PageSize(0), RetCode(0) {}
void memoryInit(ELFIO::elfio &Reader);
void transferControl(ELFIO::elfio &Reader);
int getRetCode() { return RetCode; }
~ExeHolder();
};
#endif
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
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;
#define N 11111
int n, k, cnt1 = 0, cnt2 = 0;
char s[555];
map<string, int> mp1;
map<string, int> mp2;
vector<int> g[N];
vector<int> lst[N];
vector<int> ans;
int pr[N], nx[N];
int was[N];
int IT = 0;
int getid1(const char * s) {
int& t = mp1[s];
if (!t) t = ++cnt1;
return t;
}
int getid2(const char * s) {
int& t = mp2[s];
if (!t) t = ++cnt2;
return t;
}
bool kuhn(int x) {
if (was[x] == IT) return false;
was[x] = IT;
for (int i = 0; i < g[x].size(); ++i)
if (pr[g[x][i]] == -1 || kuhn(pr[g[x][i]])) {
pr[g[x][i]] = x;
nx[x] = g[x][i];
return true;
}
return false;
}
int main() {
freopen("heavy.in", "r", stdin);
freopen("heavy.out", "w", stdout);
scanf("%d%d\n", &n, &k);
for (int i = 0; i < n; ++i) {
gets(s);
char ch = 0;
swap(ch, s[k]);
int l = getid1(s) - 1;
swap(ch, s[k]);
int r = getid2(s + strlen(s) - k) + n - 1;
lst[l].push_back(i + 1);
lst[r].push_back(i + 1);
g[l].push_back(r);
g[r].push_back(l);
}
int q = 0;
memset(pr, -1, sizeof(pr));
memset(nx, -1, sizeof(nx));
for (int i = 0; i < n; ++i) {
++IT;
q += kuhn(i);
}
++IT;
for (int i = 0; i < n; ++i)
if (nx[i] == -1 && lst[i].size() != 0)
for (int j = 0; j < g[i].size(); ++j)
if (was[ g[i][j] ] != IT) {
was[ g[i][j] ] = IT;
ans.push_back(g[i][j]);
}
for (int i = 0; i < n; ++i)
if (pr[i + n] == -1 && lst[i + n].size() != 0)
for (int j = 0; j < g[i + n].size(); ++j)
if (was[ g[i + n][j] ] != IT) {
was[ g[i + n][j] ] = IT;
ans.push_back(g[i + n][j]);
}
for (int i = 0; i < n; ++i)
if (nx[i] != -1 && was[i] != IT && was[nx[i]] != IT) {
was[i] = IT;
//was[nx[i]] = IT;
ans.push_back(i);
}
if (q != ans.size())
throw 1;
++IT;
printf("%d\n", (int)ans.size());
for (int i = 0; i < ans.size(); ++i) {
int x = ans[i];
int sz = 0;
for (int j = 0; j < lst[x].size(); ++j)
if (was[lst[x][j]] != IT)
++sz;
printf("%d", sz);
for (int j = 0; j < lst[x].size(); ++j)
if (was[lst[x][j]] != IT) {
printf(" %d", lst[x][j]);
was[lst[x][j]] = IT;
}
puts("");
}
for (int i = 1; i <= n; ++i) if (was[i] != IT) throw 1;
return 0;
}
|
//算法:DP(单调队列维护)
/*
简单的转移方程式: f[i]= max (f[i-r,i-r])+a[i]
但是n方复杂度对200000的数据量来说,就是送命的
优化:
要找到区间[i-r,i-l]内的最大值,
可以用优先队列,但是(nlogn)还是慢了些
这时候复杂度为(n)的单调队列登场了
将f数组先初始化为极小值
因为琪露诺可以移动到[i+l,i+r]区间内的点
则除[1,l-1]外,其他任何点都可到达
则计算f[i]时,从l开始枚举即可,不需要考虑到不了的点
(因为他们不会被更新,f永远是极小值)
每次都将i-l放入单调队列,并进行维护
并依次删去队首k+r<i的,即到达不了i点的
此时队首元素即为要求的max (f[i-r,i-r]);
全扫一遍后,再从能够到达河对岸的点
即属于[n-r+1,n]的点中找最大的f
得到的就是答案
*/
#include<cstdio>
#include<algorithm>
#include<cstring>
const int MARX=0xf;
const int MAXX = 3e5+10;
//============================================================
int n,l,r,ans;
int a[MAXX],f[MAXX];
int queue[MAXX],head[MAXX];
int h=1,t=1;
//============================================================
int maxx(int i)//获取最大的f[i],单调队列模板
{
while(queue[t]<=f[i] && t>=h) t--;
queue[++t]=f[i];//放入
head[t]=i;
while(queue[h]+r<i) h++; //删掉不能到达的
return head[h];//返回
}
//============================================================
int main()
{
memset(f,-MARX,sizeof(f));//初始化极小值
ans=-2147483640 , f[0]=0;//初始化各值.
scanf("%d%d%d",&n,&l,&r);
for(int i=0;i<=n;i++) scanf("%d",&a[i]);
for(int i=l;i<=n;i++)//DP过程
{
int k=maxx(i-l);
f[i]=f[k]+a[i];
if(i>=n-r+1) ans=std::max(ans,f[i]);//找到能到达河对岸的,即答案
}
printf("%d",ans);
}
|
/**
* Copyright 2015 ViajeFacil
* @author Hugo Ferrando Seage
*/
#ifndef DIALOGINFORME_H
#define DIALOGINFORME_H
#include <QDialog>
#include <string>
#include "./pelVector.hpp"
#include "./owner.hpp"
#include "./entradaHistorial.hpp"
namespace Ui {
class dialogInforme;
}
struct rank {
std::string name = "";
int num = 0;
};
class dialogInforme : public QDialog {
Q_OBJECT
public:
explicit dialogInforme(QWidget *parent = 0);
~dialogInforme();
void cargar(pel::Vector<Owner>* own);
void cargarH(pel::Vector<entradaHistorial>* his);
void quickSort(rank arr[], int left, int right);
std::string crearString(entradaHistorial h);
void setRadio(int opcion);
private slots: // NOLINT - https://github.com/google/styleguide/issues/30
void on_radioButton_5_clicked();
void on_radioButton_clicked();
private:
Ui::dialogInforme *ui;
pel::Vector<Owner> *ow;
pel::Vector<entradaHistorial> *hi;
};
#endif // DIALOGINFORME_H
|
#include "_pch.h"
#include "MoveObjPresenter.h"
using namespace wh;
//-----------------------------------------------------------------------------
CtrlMoveExecWindow::CtrlMoveExecWindow(
const std::shared_ptr<IMoveObjView>& view
, const std::shared_ptr<ModelMoveExecWindow>& model)
: CtrlWindowBase(view, model)
{
mCtrlObjBrowser = std::make_shared<CtrlTableObjBrowser_RO>
(view->GetViewObjBrowser(), model->mModelObjBrowser);
if (!mView)
return;
namespace ph = std::placeholders;
connModel_SelectPage = mModel->sigSelectPage
.connect(std::bind(&T_View::SetSelectPage, mView.get(), ph::_1));
connModel_EnableRecent = mModel->sigEnableRecent
.connect(std::bind(&T_View::EnableRecent , mView.get(), ph::_1));
connModel_UpdateRecent = mModel->sigUpdateRecent
.connect(std::bind(&T_View::UpdateRecent, mView.get(), ph::_1));
connModel_UpdateDst = mModel->sigUpdateDst
.connect(std::bind(&T_View::UpdateDst, mView.get(), ph::_1));
connModel_GetSelect = mModel->sigGetSelection
.connect(std::bind(&T_View::GetSelection, mView.get(), ph::_1));
connViewCmd_Unlock = mView->sigUnlock
.connect(std::bind(&CtrlMoveExecWindow::Unlock, this));
connViewCmd_Execute = mView->sigExecute
.connect(std::bind(&CtrlMoveExecWindow::Execute, this));
connViewCmd_EnableRecent = mView->sigEnableRecent
.connect(std::bind(&CtrlMoveExecWindow::OnViewEnableRecent, this, ph::_1));
}
//-----------------------------------------------------------------------------
CtrlMoveExecWindow::~CtrlMoveExecWindow()
{
}
//-----------------------------------------------------------------------------
void CtrlMoveExecWindow::SetObjects(const std::set<ObjectKey>& obj)
{
mModel->LockObjects(obj);
//OnModelUpdate();
}
//-----------------------------------------------------------------------------
void CtrlMoveExecWindow::Execute()
{
mModel->DoExecute();
}
//---------------------------------------------------------------------------
void CtrlMoveExecWindow::Unlock()
{
mModel->UnlockObjects();
}
//-----------------------------------------------------------------------------
void CtrlMoveExecWindow::OnViewEnableRecent(bool enable)
{
mModel->SetRecentEnable(enable);
//OnModelUpdate();
}
//-----------------------------------------------------------------------------
|
#pragma once
class DBUserManager : public CMultiThreadSync<DBUserManager>
{
public:
DBUserManager();
~DBUserManager();
private:
std::vector<DBUser*> m_UserSessionVector;
SOCKET m_ListenSocket;
public:
BOOL Begin(DWORD maxUserCount, SOCKET listenSocket);
BOOL End(VOID);
BOOL AcceptAll(VOID);
BOOL WriteAll(DWORD protocol, BYTE *data, DWORD dataLength);
DBUser* GetSession(CPacketSession* pPacketSession);
};
|
#pragma once
#include <string>
namespace dot_pp {
struct NullConstructionPolicy
{
void createGraph(const std::string&) {}
void createDigraph(const std::string&) {}
void createVertex(const std::string&) {}
void createEdge(const std::string&, const std::string&){}
void applyGraphAttribute(const std::string&, const std::string&){}
void applyDefaultVertexAttribute(const std::string&, const std::string&) {}
void applyVertexAttribute(const std::string&, const std::string&, const std::string&) {}
void applyDefaultEdgeAttribute(const std::string&, const std::string) {}
void applyEdgeAttribute(const std::string&, const std::string&, const std::string&, const std::string&) {}
void finalize() {}
};
}
|
#include<bits/stdc++.h>
using namespace std;
#define maxn 10005
int n;
int t[maxn];
int ans[maxn];
int ind;
void solve(int l,int r){
if(r-l<2)
return;
ind=l;
for(int i=l;i<=r;i+=2){
t[ind++]=ans[i];
}
for(int i=l+1;i<=r;i+=2){
t[ind++]=ans[i];
}
for(int i=l;i<=r;i++){
ans[i]=t[i];
}
int mid=(l+r)>>1;
solve(l,mid);
solve(mid,r);
return;
}
int main(){
while(cin>>n&&n){
for(int i=0;i<n;i++)
ans[i]=i;
solve(0,n-1);
cout<<n<<":";
for(int i=0;i<n;i++){
cout<<" "<<ans[i];
}
cout<<"\n";
}
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
int main()
{
int curfl = 0, destfl, floor;
float high, speed;
float time1;
high = 3.0; // Height of the floor
speed = 5.0; // Speed of the elevator per second
while(1)
{
printf("Currently the elevator is at floor number = %d\n", curfl);
printf("Enter the floor number between 0-25 : ");
// printf("%d %d", &curfl, &time1);
scanf("%d", &destfl);
if(destfl > curfl)
{
floor = destfl - curfl;
time1 = (floor * (high / speed));
printf("Elevator will take %.2f second to reach %d (st, nd, rd) floor \n", time1, destfl);
while(curfl != destfl)
{
Sleep((1000 * 3) / 5);
curfl++;
printf("You are at floor number %d \n", curfl);
}
printf("Door opening \n"); printf ("\7") ;
Sleep(10000);
printf("Door Closed\n \n");
}
else if(destfl < curfl)
{
floor = curfl - destfl;
time1 = (floor * (high / speed));
printf("Elevator will take %.2f second to reach %d (st, nd, rd) floor \n", time1, destfl);
while(curfl != destfl)
{
Sleep((1000 * 3) / 5);
curfl--;
printf("You are at floor number %d \n", curfl);
}
printf("Door opening \n");
Sleep(10000);
printf("Door Closed\n \n");
}
else{
printf("You are the same floor. Please getout from the elevator \n");
}
}
// printf("Hello world!\n");
return 0;
}
|
#ifndef REL_OP_H
#define REL_OP_H
#include "Pipe.h"
#include "DBFile.h"
#include "Record.h"
#include "Function.h"
#include <sstream>
class RelationalOpThreadMemberHolder{
public:
Schema *mySchema;
Pipe *inPipe;
Pipe *outPipe;
CNF *selOp;
DBFile *inFile;
Record *literal;
int numAttsInput;
int numAttsOutput;
int *keepMe;
int runLength;
Function *function;
OrderMaker *groupAtts;
Pipe *inPipeR;
FILE *outFile;
RelationalOpThreadMemberHolder(Schema *mySchema, Pipe *inPipe, DBFile *inFile, Pipe *outPipe, FILE *outFile, CNF *selOp, Record *literal, int numAttsInput, int numAttsOutput, int *keepMe, int runLength, Function *function, OrderMaker *groupAtts, Pipe *inPipeR){
this->mySchema = mySchema;
this->inPipe = inPipe;
this->inFile = inFile;
this->outPipe = outPipe;
this->outFile = outFile;
this->selOp = selOp;
this->literal = literal;
this->numAttsInput = numAttsInput;
this->numAttsOutput = numAttsOutput;
this->keepMe = keepMe;
this->runLength = runLength;
this->function = function;
this->groupAtts = groupAtts;
this->inPipeR = inPipeR;
}
};
class RelationalOp {
public:
// blocks the caller until the particular relational operator
// has run to completion
virtual void WaitUntilDone ();
// tell us how much internal memory the operation can use
virtual void Use_n_Pages (int n=100);
int runLength = 100; //default runlength
int GetRunLength (void) {return runLength;}
protected:
pthread_t operatorThread;
};
/**************************************************************************************************
SELECT FILE
**************************************************************************************************/
class SelectFile : public RelationalOp {
public:
void Run (DBFile &inFile, Pipe &outPipe, CNF &selOp, Record &literal);
static void* Operate(void* arg);
};
/**************************************************************************************************
SELECT PIPE
**************************************************************************************************/
class SelectPipe : public RelationalOp {
public:
void Run (Pipe &inPipe, Pipe &outPipe, CNF &selOp, Record &literal);
static void* Operate(void* arg);
};
/**************************************************************************************************
PROJECT
**************************************************************************************************/
class Project : public RelationalOp {
public:
void Run (Pipe &inPipe, Pipe &outPipe, int *keepMe, int numAttsInput, int numAttsOutput);
static void* Operate(void* arg);
};
/**************************************************************************************************
JOIN
**************************************************************************************************/
class FixedSizeRecordBuffer;
class Join : public RelationalOp {
public:
void Run (Pipe &inPipeL, Pipe &inPipeR, Pipe &outPipe, CNF &selOp, Record &literal);
private:
static void* Operate(void* param);
static void SortMergeJoin(Pipe* leftPipe, OrderMaker* leftOrderMaker, Pipe* rightPipe, OrderMaker* rightOrderMaker, Pipe* pout, CNF* selOp, Record* literal, int runLength, RelationalOpThreadMemberHolder* params);
static void NestedLoopJoin(Pipe* leftPipe, Pipe* rightPipe, Pipe* pout, CNF* selOp, Record* literal, int runLength);
static void JoinBufferWithFile(FixedSizeRecordBuffer& buffer, DBFile& file, Pipe& out, Record& literal, CNF& selOp);
static void PipeToFile(Pipe& inPipe, DBFile& outFile);
};
class FixedSizeRecordBuffer {
friend class Join;
public:
FixedSizeRecordBuffer(int runLength);
~FixedSizeRecordBuffer();
private:
Record* buffer;
int numRecords;
int size;
int capacity;
bool Add (Record& addme);
void Clear ();
};
/**************************************************************************************************
DUPLICATE REMOVAL
**************************************************************************************************/
class DuplicateRemoval : public RelationalOp {
public:
void Run (Pipe &inPipe, Pipe &outPipe, Schema &mySchema);
static void* Operate(void* arg);
};
/**************************************************************************************************
SUM
**************************************************************************************************/
class Sum : public RelationalOp {
public:
void Run (Pipe &inPipe, Pipe &outPipe, Function &computeMe);
static void* Operate(void* arg);
template <class T> static void CalculateSum(Pipe* in, Pipe* out, Function* function);
};
/**************************************************************************************************
GROUPBY
**************************************************************************************************/
class GroupBy : public RelationalOp {
private:
public:
void Run (Pipe &inPipe, Pipe &outPipe, OrderMaker &groupAtts, Function &computeMe);
static void* Operate(void* arg);
template <class T>
static void MakeGroups(Pipe* inPipe, Pipe* outPipe, OrderMaker* orderMaker, Function* function, int runLength);
template <class T>
static void AddGroup(Record& record, const T& sum, Pipe* outPipe, OrderMaker* orderMaker, Function* function);
};
/**************************************************************************************************
WRITEOUT
**************************************************************************************************/
class WriteOut : public RelationalOp {
public:
void Run (Pipe &inPipe, FILE *outFile, Schema &mySchema);
static void* Operate(void* arg);
};
#endif
|
#include <TMRpcm.h>
#include <SD.h>
#include <SPI.h>
TMRpcm tmrpcm;
long k = 0;
int skipDay = 0;
int shamash = 2;
int candle1 = A0;
int candle2 = A1;
int candle3 = A2;
int candle4 = A3;
int candle5 = A4;
int candle6 = A5;
int candle7 = 8;
int candle8 = 3;
int dayUp = 5;
int dayDown = 6;
int day = 1;
int tempRead = 1;
void setup()
{
Serial.begin(9600);
tmrpcm.speakerPin = 9; //Set speaker output pin to 9
pinMode(9, INPUT);
if (!SD.begin(10)) {
Serial.println("SD card initialization failed!");
return;
}
pinMode(candle1, OUTPUT);
pinMode(candle2, OUTPUT);
pinMode(candle3, OUTPUT);
pinMode(candle4, OUTPUT);
pinMode(candle5, OUTPUT);
pinMode(candle6, OUTPUT);
pinMode(candle7, OUTPUT);
pinMode(candle8, OUTPUT);
pinMode(shamash, OUTPUT);
pinMode(dayUp, INPUT);
pinMode(dayDown, INPUT);
digitalWrite(candle1, LOW);
digitalWrite(candle2, LOW);
digitalWrite(candle3, LOW);
digitalWrite(candle4, LOW);
digitalWrite(candle5, LOW);
digitalWrite(candle6, LOW);
digitalWrite(candle7, LOW);
digitalWrite(candle8, LOW);
digitalWrite(shamash, LOW);
digitalWrite(dayUp, LOW);
digitalWrite(dayDown, LOW);
Serial.println('setup done');
}
void loop()
{
while (day < 9)
{
burnout(day);
day = day +1;
}
}
|
//
// RockManage.h
// GetFish
//
// Created by zhusu on 15/3/11.
//
//
#ifndef __GetFish__RockManage__
#define __GetFish__RockManage__
#include "cocos2d.h"
#include "Rock.h"
#include "ActorManage.h"
USING_NS_CC;
class RockManage : public ActorManage
{
public:
CREATE_FUNC(RockManage);
RockManage();
virtual bool init();
virtual ~RockManage();
void addRock(const char* name,int hp,CCPoint pos);
};
#endif /* defined(__GetFish__RockManage__) */
|
#include <string>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sstream>
#include <list>
#include <algorithm>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <numeric>
#include <bitset>
#include <deque>
//#include <random>
#include <string.h>
#include <stdlib.h>
#include <vector>
#include <unordered_map>
#include <thread>
const long long LINF = (5e18);
const int INF = (1<<30);
const int sINF = (1<<23);
const int MOD = 1000000009;
const double EPS = 1e-6;
using namespace std;
class CandidatesSelection {
public:
typedef pair<int, int> P;
string possible(vector <string> score, vector <int> result) {
vector<P> conds;
for (int i=0; i<result.size()-1; ++i)
conds.push_back(P(result[i], result[i+1]));
int m = (int)score[0].size();
vector<bool> used(m, false);
while (!conds.empty()) {
bool canend = true;
for (auto p: conds)
canend &= (p.first < p.second);
if (canend)
break;
bool removed = false;
for (int i=0; i<m; ++i) {
if (used[i])
continue;
bool can = true;
for (auto p: conds) {
int a = p.first;
int b = p.second;
can &= ( score[a][i] <= score[b][i] );
}
if (!can)
continue;
removed = true;
used[i] = true;
vector<P> newconds;
for (auto p: conds) {
int a = p.first;
int b = p.second;
if (score[a][i] == score[b][i])
newconds.push_back(P(a, b));
}
conds = newconds;
}
if (!removed)
return "Impossible";
}
return "Possible";
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"CC", "AA", "BB"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1,2,0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Possible"; verify_case(0, Arg2, possible(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {"BAB", "ABB", "AAB", "ABA"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2,0,1,3}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Possible"; verify_case(1, Arg2, possible(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {"BAB", "ABB", "AAB", "ABA"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 1, 3, 2}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Impossible"; verify_case(2, Arg2, possible(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {"AAA", "ZZZ"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1, 0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Impossible"; verify_case(3, Arg2, possible(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {"ZZZ", "AAA"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Possible"; verify_case(4, Arg2, possible(Arg0, Arg1)); }
void test_case_5() { string Arr0[] = {"ZYYYYX","YXZYXY","ZZZZXX","XZXYYX","ZZZYYZ","ZZXXYZ","ZYZZXZ","XZYYZX"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3,7,1,0,2,5,6,4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); string Arg2 = "Possible"; verify_case(5, Arg2, possible(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
CandidatesSelection ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "mopology.hpp"
cv::Mat rectSE( const int size )
{
return cv::Mat( size, size, CV_8UC1, cv::Scalar( 255 ) );
}
cv::Mat rectSE( const int x, const int y )
{
return cv::Mat( x, y, CV_8UC1, cv::Scalar( 255 ) );
}
cv::Mat crossSE()
{
return ( cv::Mat_<uchar>( 3, 3 ) << 0, 255, 0, 255, 255, 255, 0, 255, 0 );
}
std::function<void( Pixel&, const int* )> singleerosion( cv::Mat& A,
cv::Mat& B )
{
return [&]( Pixel& p, const int* position ) -> void {
for ( int k = -( B.rows / 2 ); k <= ( B.rows / 2 ); k++ )
for ( int l = -( B.cols / 2 ); l <= ( B.cols / 2 ); l++ )
if ( position[0] + k >= 0 && position[0] + k < A.rows &&
position[1] + l >= 0 && position[1] + l < A.cols &&
B.at<uchar>( ( B.rows / 2 ) - k, ( B.cols / 2 ) - l ) ==
255 &&
A.at<uchar>( position[0] + k, position[1] + l ) == 0 )
{
p = 0;
return;
}
p = 255;
return;
};
}
// A (-) B
cv::Mat erosion( cv::Mat A, cv::Mat B )
{
cv::Mat C = cv::Mat_<uchar>( A.size() );
const int nRows = C.rows;
const int nCols = C.cols;
int p[2];
auto f = singleerosion( A, B );
for ( int i = 0; i < nRows; i++ )
for ( int j = 0; j < nCols; j++ )
{
// C.at<uchar>( i, j ) = singleerosion( A, B, i, j );
p[0] = i;
p[1] = j;
f( C.at<uchar>( i, j ), p );
}
return C;
}
std::function<void( Pixel&, const int* )> singledilation( cv::Mat& A,
cv::Mat& B )
{
return [&]( Pixel& p, const int* position ) -> void {
for ( int k = -( B.rows / 2 ); k <= ( B.rows / 2 ); k++ )
for ( int l = -( B.cols / 2 ); l <= ( B.cols / 2 ); l++ )
if ( position[0] + k >= 0 && position[0] + k < A.rows &&
position[1] + l >= 0 && position[1] + l < A.cols &&
B.at<uchar>( ( B.rows / 2 ) - k, ( B.cols / 2 ) - l ) ==
255 &&
A.at<uchar>( position[0] + k, position[1] + l ) == 255 )
{
p = 255;
return;
}
p = 0;
return;
};
}
// A (+) B
cv::Mat dilation( cv::Mat A, cv::Mat B )
{
cv::Mat C = cv::Mat_<uchar>( A.size() );
const int nRows = C.rows;
const int nCols = C.cols;
C.forEach<Pixel>( singledilation( A, B ) );
return C;
}
cv::Mat opening( cv::Mat A, cv::Mat B )
{
return dilation( erosion( A, B ), B );
}
cv::Mat closing( cv::Mat A, cv::Mat B )
{
return erosion( dilation( A, B ), B );
}
cv::Mat geodesic_dilation_1( cv::Mat F, cv::Mat G, cv::Mat B )
{
auto dil = dilation( F, B );
dil.forEach<uchar>( [&]( Pixel& p, const int* i ) {
p = p && G.at<uchar>( i[0], i[1] ) ? 255 : 0;
} );
return dil;
}
cv::Mat geodesic_dilation( cv::Mat F, cv::Mat G, cv::Mat B, int n )
{
for ( int i = 0; i < n; i++ )
F = geodesic_dilation_1( F, G, B );
return F;
}
cv::Mat geodesic_erosion_1( cv::Mat F, cv::Mat G, cv::Mat B )
{
auto eros = erosion( F, B );
eros.forEach<uchar>( [&]( Pixel& p, const int* i ) {
p = p | G.at<uchar>( i[0], i[1] ) ? 255 : 0;
} );
return eros;
}
cv::Mat geodesic_reconst_D( cv::Mat F, cv::Mat G, cv::Mat B )
{
cv::Mat D;
bool isSame = true;
for ( int i = 0; i < 1000; i++ )
{
D = geodesic_dilation_1( F, G, B );
D.forEach<uchar>( [&]( Pixel& p, const int* i ) {
if ( p != F.at<uchar>( i[0], i[1] ) )
isSame = false;
} );
if ( isSame == true )
break;
isSame = true;
F = D;
}
return D;
}
cv::Mat geodesic_reconst_E( cv::Mat F, cv::Mat G, cv::Mat B )
{
cv::Mat E;
bool isSame = true;
for ( int i = 0; i < 1000; i++ )
{
E = geodesic_erosion_1( F, G, B );
E.forEach<uchar>( [&]( Pixel& p, const int* i ) {
if ( p != F.at<uchar>( i[0], i[1] ) )
isSame = false;
} );
if ( isSame == true )
break;
isSame = true;
F = E;
}
return E;
}
cv::Mat auto_hole( cv::Mat I )
{
cv::Mat I_c = 255 - I;
auto F = I_c.clone();
const int nRow = F.rows;
const int nCol = F.cols;
F.forEach<uchar>( [&]( Pixel& p, const int* i ) {
p = ( ( i[0] == 0 || i[0] == nRow - 1 || i[1] == 0 ||
i[1] == nCol - 1 ) )
? p
: 0;
} );
auto R = geodesic_reconst_D( F, I_c, rectSE( 3 ) );
cv::Mat H = 255 - R;
return H;
}
cv::Mat border_clean( cv::Mat I )
{
auto F = I.clone();
const int nRow = F.rows;
const int nCol = F.cols;
F.forEach<uchar>( [&]( Pixel& p, const int* i ) {
p = ( ( i[0] == 0 || i[0] == nRow - 1 || i[1] == 0 ||
i[1] == nCol - 1 ) )
? p
: 0;
} );
return I - geodesic_reconst_D( F, I, rectSE( 3 ) );
}
|
#pragma once
#include "constants.h"
#include "Model.h"
#include "constants.h"
#include <string>
#include <vector>
class Fish :public Model {
public:
Fish::Fish(std::string path, float radius, float offset_x, float offset_y , float offset_z, bool R_direction, int max_deviation);
Fish::Fish();
float radius;
int max_deviation;
int current_deviation;
bool R_diretion;
float offset_x;
float offset_y;
float offset_z;
float x_trans;
float y_trans;
float z_trans;
void Fish::updateMatrix(int angle);
glm::mat4 translate_matrix;
glm::mat4 rotate_matrix;
void Fish::sendMatrix(glm::mat4 view_matrix, glm::mat4 perspective_matrix);
void Fish::getUniform();
int Fish::swim();
};
|
//
// main.cpp
// GardenOfEden
//
// Created by Russell Lowry on 12/5/17.
// Copyright © 2017 Russell Lowry. All rights reserved.
//
#include <iostream>
#include <stdio.h>
using namespace std;
int func[8];
int target[50], origin[50];
int ID, n, found;
char s[50];
void depthFirstSearch(int var) {
if(found) {
return;
}
int x, y;
if(var == n-1) {
x = (origin[n-2]<<2) | (origin[n-1]<<1) | (origin[0]<<0);
y = (origin[n-1]<<2) | (origin[0]<<1) | (origin[1]<<0);
if(target[var] == func[x] && target[0] == func[y]) {
found = 1;
}
return;
}
for(int x = 0; x < 8; x++) {
if(func[x] == target[var] && ((x>>2)&1) == origin[var-1] && ((x>>1)&1) == origin[var]) {
origin[var+1] = (x>>0)&1;
depthFirstSearch(var+1);
if(found) {
return;
}
}
}
}
int main(int argc, const char * argv[]) {
while(scanf("%d%d%s", &ID, &n, s) == 3) {
for(int x = 0; x < n; x++) {
target[x] = s[x]-'0';
}
for(int x = 0; x < 8; x++) {
func[x] = (ID>>x)&1;
}
found = 0;
for(int x = 0; x < 8; x++) {
if(func[x] == target[0]) {
origin[0] = (x>>1)&1;
origin[1] = (x>>0)&1;
depthFirstSearch(1);
}
}
if(found) {
cout << "REACHABLE" << endl;
}
else {
cout << "GARDEN OF EDEN" << endl;
}
}
return 0;
}
|
// Auduino Grain oscillator
//
// by Peter Knight, Tinker.it http://tinker.it,
// Ilja Everilä <saarni@gmail.com>
//
// ChangeLog:
// 18 Oct 2012: Attempt at optimizing 8bit multiplications
#include <avr/pgmspace.h>
#include "asm.h"
// Sine!
//
// _--_
// - - -
// -__-
//
static const uint8_t sine_lookup[256] PROGMEM = {
128, 131, 134, 137, 140, 143, 146, 149, 152, 155, 158, 162, 165, 167, 170, 173,
176, 179, 182, 185, 188, 190, 193, 196, 198, 201, 203, 206, 208, 211, 213, 215,
218, 220, 222, 224, 226, 228, 230, 232, 234, 235, 237, 238, 240, 241, 243, 244,
245, 246, 248, 249, 250, 250, 251, 252, 253, 253, 254, 254, 254, 255, 255, 255,
255, 255, 255, 255, 254, 254, 254, 253, 253, 252, 251, 250, 250, 249, 248, 246,
245, 244, 243, 241, 240, 238, 237, 235, 234, 232, 230, 228, 226, 224, 222, 220,
218, 215, 213, 211, 208, 206, 203, 201, 198, 196, 193, 190, 188, 185, 182, 179,
176, 173, 170, 167, 165, 162, 158, 155, 152, 149, 146, 143, 140, 137, 134, 131,
128, 124, 121, 118, 115, 112, 109, 106, 103, 100, 97, 93, 90, 88, 85, 82,
79, 76, 73, 70, 67, 65, 62, 59, 57, 54, 52, 49, 47, 44, 42, 40,
37, 35, 33, 31, 29, 27, 25, 23, 21, 20, 18, 17, 15, 14, 12, 11,
10, 9, 7, 6, 5, 5, 4, 3, 2, 2, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 9,
10, 11, 12, 14, 15, 17, 18, 20, 21, 23, 25, 27, 29, 31, 33, 35,
37, 40, 42, 44, 47, 49, 52, 54, 57, 59, 62, 65, 67, 70, 73, 76,
79, 82, 85, 88, 90, 93, 97, 100, 103, 106, 109, 112, 115, 118, 121, 124
};
inline void Env::tick() {
// Make the grain amplitude decay by a factor every sample (exponential decay)
uint16_t tmp = mul(value(), decay);
if (divider) {
tmp >>= divider;
}
if (tmp) {
amp -= tmp;
} else if (divider) {
amp = 0;
}
}
inline uint8_t Env::value() const {
return static_cast<uint8_t>(amp >> 8);
}
inline void Env::reset() {
amp = 0x7fff;
}
inline void Grain::reset() {
phase.reset();
env.reset();
}
inline uint16_t Grain::getSample() const {
//return mul(pgm_read_byte(&sine_lookup[phase.acc >> 8]), env.value());
// Convert phase into a triangle wave
uint8_t value = phase.acc >> 7;
if (phase.acc & 0x8000) value = ~value;
// Multiply by current grain amplitude to get sample
return mul(value, env.value());
}
|
// Created on: 1995-09-18
// Created by: Bruno DUMORTIER
// Copyright (c) 1995-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 _BRepOffsetAPI_MakeEvolved_HeaderFile
#define _BRepOffsetAPI_MakeEvolved_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <BRepFill_Evolved.hxx>
#include <BRepFill_AdvancedEvolved.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
#include <GeomAbs_JoinType.hxx>
#include <TopTools_ListOfShape.hxx>
class TopoDS_Wire;
class TopoDS_Shape;
//! Describes functions to build evolved shapes.
//! An evolved shape is built from a planar spine (face or
//! wire) and a profile (wire). The evolved shape is the
//! unlooped sweep (pipe) of the profile along the spine.
//! Self-intersections are removed.
//! A MakeEvolved object provides a framework for:
//! - defining the construction of an evolved shape,
//! - implementing the construction algorithm, and
//! - consulting the result.
//! Computes an Evolved by
//! 1 - sweeping a profile along a spine.
//! 2 - removing the self-intersections.
//!
//! The Profile is expected to be planar and can be a line
//! (which lies in infinite number of planes).
//!
//! The profile is defined in a Referential R. The position of
//! the profile at the current point of the spine is given by
//! confusing R and the local referential given by ( D0, D1
//! and the normal of the Spine).
//!
//! The coordinate system is determined by theIsAxeProf argument:
//! - if theIsAxeProf is true, R is the global coordinate system,
//! - if theIsAxeProf is false, R is computed so that:
//! * its origin is given by the point on the spine which is
//! closest to the profile,
//! * its "X Axis" is given by the tangent to the spine at this point, and
//! * its "Z Axis" is the normal to the plane which contains the spine.
//!
//! theJoinType defines the type of pipe generated by the salient
//! vertices of the spine. The default type is GeomAbs_Arc
//! where the vertices generate revolved pipes about the
//! axis passing along the vertex and the normal to the
//! plane of the spine. At present, this is the only
//! construction type implemented.
//!
//! if <theIsSolid> is TRUE the Shape result is completed to be a
//! solid or a compound of solids.
//!
//! If theIsProfOnSpine == TRUE then the profile must connect with the spine.
//!
//! If theIsVolume option is switched on then self-intersections
//! in the result of Pipe-algorithm will be removed by
//! BOPAlgo_MakerVolume algorithm. At that the arguments
//! "theJoinType", "theIsAxeProf", "theIsProfOnSpine" are not used.
class BRepOffsetAPI_MakeEvolved : public BRepBuilderAPI_MakeShape
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BRepOffsetAPI_MakeEvolved();
//! Constructs an evolved shape by sweeping the profile
//! (theProfile) along the spine (theSpine).
//! theSpine can be shape only of type wire or face.
//! See description to this class for detailed information.
Standard_EXPORT BRepOffsetAPI_MakeEvolved(const TopoDS_Shape& theSpine,
const TopoDS_Wire& theProfile,
const GeomAbs_JoinType theJoinType = GeomAbs_Arc,
const Standard_Boolean theIsAxeProf = Standard_True,
const Standard_Boolean theIsSolid = Standard_False,
const Standard_Boolean theIsProfOnSpine = Standard_False,
const Standard_Real theTol = 0.0000001,
const Standard_Boolean theIsVolume = Standard_False,
const Standard_Boolean theRunInParallel = Standard_False);
Standard_EXPORT const BRepFill_Evolved& Evolved() const;
//! Builds the resulting shape (redefined from MakeShape).
Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
//! Returns the shapes created from a subshape
//! <SpineShape> of the spine and a subshape
//! <ProfShape> on the profile.
Standard_EXPORT const TopTools_ListOfShape& GeneratedShapes (const TopoDS_Shape& SpineShape, const TopoDS_Shape& ProfShape) const;
//! Return the face Top if <Solid> is True in the constructor.
Standard_EXPORT const TopoDS_Shape& Top() const;
//! Return the face Bottom if <Solid> is True in the constructor.
Standard_EXPORT const TopoDS_Shape& Bottom() const;
protected:
private:
BRepFill_Evolved myEvolved;
BRepFill_AdvancedEvolved myVolume;
Standard_Boolean myIsVolume;
};
#endif // _BRepOffsetAPI_MakeEvolved_HeaderFile
|
#include<iostream>
#include<string>
using namespace std;
void myFunction1(int, char);
void breakDown(string, int);
|
#include "_pch.h"
#include "globaldata.h"
#include "ViewActBrowser.h"
//#include "wxDataViewIconMLTextRenderer.h"
//#include "wxComboBtn.h"
//#include "config.h"
//#include <wx/uiaction.h>
using namespace wh;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
ViewActBrowser::ViewActBrowser(const std::shared_ptr<IViewWindow>& parent)
:ViewActBrowser(parent->GetWnd())
{}
//-----------------------------------------------------------------------------
ViewActBrowser::ViewActBrowser(wxWindow* parent)
{
mTable = nullptr;
mDvModel = nullptr;
mTable = new wxDataViewCtrl(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize
, wxDV_ROW_LINES
| wxDV_VERT_RULES
//| wxDV_HORIZ_RULES
//| wxDV_MULTIPLE
);
wxDataViewCtrl* table = mTable;
mDvModel = new wxDVTableActBrowser();
table->AssociateModel(mDvModel);
mDvModel->DecRef();
#define ICON_HEIGHT 24+2
int row_height = table->GetCharHeight() + 2;// + 1px in bottom and top
if (ICON_HEIGHT > row_height)
row_height = ICON_HEIGHT;
table->SetRowHeight(row_height);
ResetColumns();
table->Bind(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK
, [this](wxDataViewEvent& evt) { StoreSelect(); evt.Skip(); });
table->Bind(wxEVT_DATAVIEW_COLUMN_SORTED
, [this](wxDataViewEvent& evt) { RestoreSelect(); });
table->Bind(wxEVT_DATAVIEW_ITEM_ACTIVATED
, &ViewActBrowser::OnCmd_Activate, this);
table->Bind(wxEVT_DATAVIEW_SELECTION_CHANGED
, &ViewActBrowser::OnCmd_SelectionChanged, this);
table->GetTargetWindow()->Bind(wxEVT_MOTION
, &ViewActBrowser::OnCmd_MouseMove, this);
table->Bind(wxEVT_COMMAND_MENU_SELECTED
, [this](wxCommandEvent&) { sigRefresh(); }, wxID_REFRESH);
mToolTipTimer.Bind(wxEVT_TIMER
, [this](wxTimerEvent& evt) { ShowToolTip(); });
table->Bind(wxEVT_DESTROY, [this](wxWindowDestroyEvent& evt)
{
if (evt.GetWindow() != mTable)
return;
mTable = nullptr;
mDvModel = nullptr;
});
wxAcceleratorEntry entries[2];
char i = 0;
entries[i++].Set(wxACCEL_CTRL, (int) 'R', wxID_REFRESH);
entries[i++].Set(wxACCEL_NORMAL, WXK_F5, wxID_REFRESH);
wxAcceleratorTable accel(i + 1, entries);
table->SetAcceleratorTable(accel);
}
//-----------------------------------------------------------------------------
ViewActBrowser::~ViewActBrowser()
{
//mToolTipTimer.Stop();
}
//-----------------------------------------------------------------------------
void ViewActBrowser::StoreSelect()
{
}
//-----------------------------------------------------------------------------
void ViewActBrowser::RestoreSelect()
{
}
//-----------------------------------------------------------------------------
void ViewActBrowser::AutosizeColumns()
{
if (!mColAutosize)
return;
TEST_FUNC_TIME;
wxBusyCursor busyCursor;
for (size_t i = 0; i < mTable->GetColumnCount(); i++)
{
auto col_pos = mTable->GetModelColumnIndex(i);
auto col = mTable->GetColumn(col_pos);
if (col)
{
auto bs = mTable->GetBestColumnWidth(i);
if (bs > 300)
bs = 300;
col->SetWidth(bs);
}
}
}
//-----------------------------------------------------------------------------
void ViewActBrowser::ResetColumns()
{
wxWindowUpdateLocker lock(mTable);
mTable->ClearColumns();
//auto renderer1 = new wxDataViewIconTextRenderer();
auto col0 = mTable->AppendTextColumn("Имя", 0, wxDATAVIEW_CELL_INERT, -1
, wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
auto col1 = mTable->AppendTextColumn("Описание", 1, wxDATAVIEW_CELL_INERT, 150
, wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
/*
auto col2 = mTable->AppendTextColumn("Цвет", 2, wxDATAVIEW_CELL_INERT, -1
, wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
auto col3 = mTable->AppendTextColumn("#", 3, wxDATAVIEW_CELL_INERT, -1
, wxALIGN_NOT, wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
*/
}
//-----------------------------------------------------------------------------
void ViewActBrowser::RebuildColumns()
{
}
//-----------------------------------------------------------------------------
wxDataViewColumn * ViewActBrowser::AppendTableColumn(const wxString & title, int model_id)
{
auto col = mTable->AppendTextColumn(title, model_id
, wxDATAVIEW_CELL_INERT
, GetTitleWidth(title)
, wxALIGN_NOT
, wxDATAVIEW_COL_REORDERABLE | wxDATAVIEW_COL_RESIZABLE | wxDATAVIEW_COL_SORTABLE);
col->SetMinWidth(80);
return col;
}
//-----------------------------------------------------------------------------
int ViewActBrowser::GetTitleWidth(const wxString& title)const
{
const int spw = mTable->GetTextExtent(" ").GetWidth();
int hw = mTable->GetTextExtent(title).GetWidth() + spw * 4 + 24;
if (hw < 80)
hw = -1; // default width
else if (hw > 300)
hw = 300;
return hw;
}
//-----------------------------------------------------------------------------
bool ViewActBrowser::IsSelectedItem(const wxDataViewItem& item)const
{
if (!item.IsOk())
return false;
const IIdent64* ident = static_cast<const IIdent64*> (item.GetID());
if (!ident)
return false;
const auto& act = dynamic_cast<const IAct64*>(ident);
if (act)
{
return act->IsSelected();
}
return false;
}
//-----------------------------------------------------------------------------
void ViewActBrowser::SetSelected(const wxDataViewItem & item, bool select) const
{
if (!item.IsOk())
return;
const IIdent64* ident = static_cast<const IIdent64*> (item.GetID());
if (!ident)
return;
const auto& act = dynamic_cast<const IAct64*>(ident);
if (act)
{
int64_t aid = act->GetId();
sigSelect(aid, select);
}
}
//-----------------------------------------------------------------------------
void ViewActBrowser::SetSelected() const
{
bool select = !IsSelectedItem(mTable->GetCurrentItem());
SetSelected(mTable->GetCurrentItem(), select);
}
//-----------------------------------------------------------------------------
void ViewActBrowser::OnCmd_Activate(wxDataViewEvent & evt)
{
sigActivate();
}
//-----------------------------------------------------------------------------
void ViewActBrowser::OnCmd_SelectionChanged(wxDataViewEvent & evt)
{
}
//-----------------------------------------------------------------------------
void ViewActBrowser::SetBeforeRefresh(std::shared_ptr<const ModelActTable> table)
{
}
//-----------------------------------------------------------------------------
void ViewActBrowser::SetAfterRefresh(std::shared_ptr<const ModelActTable> table)
{
if (!mDvModel)
return;
TEST_FUNC_TIME;
wxBusyCursor busyCursor;
wxWindowUpdateLocker lock(mTable);
mDvModel->SetData(table);
AutosizeColumns();
RestoreSelect();
}
//-----------------------------------------------------------------------------
void ViewActBrowser::GetSelection(std::set<int64_t>& sel)const
{
auto item = mTable->GetCurrentItem();
if (!item.IsOk())
return;
const IIdent64* ident = static_cast<const IIdent64*> (item.GetID());
if (!ident)
return;
const auto& act = dynamic_cast<const IAct64*>(ident);
if (!act)
return;
sel.emplace(act->GetId());
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void ViewActBrowser::ShowToolTip()
{
if (!mTable || !mTable->GetMainWindow()->IsMouseInWindow())
return;
wxPoint pos = wxGetMousePosition();
pos = mTable->ScreenToClient(pos);
wxDataViewItem item(nullptr);
wxDataViewColumn* col = nullptr;
mTable->HitTest(pos, item, col);
if (!col || !item.IsOk())
return;
wxString val;
wxVariant var;
mDvModel->GetValue(var, item, col->GetModelColumn());
val = var.GetString();
const auto* ident = static_cast<const IAct64*> (item.GetID());
if (!ident)
return;
wxString item_str = wxString::Format("#[%s]\t%s"
, ident->GetIdAsString(), ident->GetColour());
mTable->GetTargetWindow()->SetToolTip(val + "\n\n" + item_str);
}
//-----------------------------------------------------------------------------
void ViewActBrowser::OnCmd_MouseMove(wxMouseEvent& evt)
{
mTable->GetTargetWindow()->SetToolTip(wxEmptyString);
mToolTipTimer.StartOnce(15000);
}
|
#include "Patrol.h"
#include <iostream>
Patrol::Patrol()
= default;
Patrol::~Patrol()
= default;
void Patrol::Execute()
{
std::cout << "Performing Patrol Action" << std::endl;
}
|
// Created on: 1992-04-06
// Created by: Christian CAILLET
// Copyright (c) 1992-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 _IGESData_ParamReader_HeaderFile
#define _IGESData_ParamReader_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <IGESData_ReadStage.hxx>
#include <Interface_ParamType.hxx>
#include <Standard_CString.hxx>
#include <IGESData_Status.hxx>
#include <IGESData_ParamCursor.hxx>
#include <Standard_Type.hxx>
#include <TColStd_HArray1OfInteger.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <Interface_HArray1OfHAsciiString.hxx>
#include <IGESData_HArray1OfIGESEntity.hxx>
class Interface_ParamList;
class Interface_Check;
class IGESData_IGESEntity;
class IGESData_IGESReaderData;
class Message_Msg;
class gp_XY;
class gp_XYZ;
class TCollection_HAsciiString;
class Interface_EntityList;
//! access to a list of parameters, with management of read stage
//! (owned parameters, properties, associativities) and current
//! parameter number, read errors (which feed a Check), plus
//! convenient facilities to read parameters, in particular :
//! - first parameter is ignored (it repeats entity type), hence
//! number 1 gives 2nd parameter, etc...
//! - lists are not explicit, list-reading methods are provided
//! which manage a current param. number
//! - interpretation is made as possible (texts, reals, entities ...)
//! (in particular, Reading a Real accepts an Integer)
class IGESData_ParamReader
{
public:
DEFINE_STANDARD_ALLOC
//! Prepares a ParamReader, stage "Own", current param = 1
//! It considers a part of the list, from <base> (excluded) for
//! <nbpar> parameters; <nbpar> = 0 commands to take list length.
//! Default is (1 to skip type)
Standard_EXPORT IGESData_ParamReader(const Handle(Interface_ParamList)& list, const Handle(Interface_Check)& ach, const Standard_Integer base = 1, const Standard_Integer nbpar = 0, const Standard_Integer num = 0);
//! Returns the entity number in the file
Standard_EXPORT Standard_Integer EntityNumber() const;
//! resets state (stage, current param number, check with no fail)
Standard_EXPORT void Clear();
//! returns the current parameter number
//! This notion is involved by the organisation of an IGES list of
//! parameter : it can be ended by two lists (Associativities and
//! Properties), which can be empty, or even absent. Hence, it is
//! necessary to know, at the end of specific reading, how many
//! parameters have been read : the optional lists follow
Standard_EXPORT Standard_Integer CurrentNumber() const;
//! sets current parameter number to a new value
//! must be done at end of each step : set on first parameter
//! following last read one; is done by some Read... methods
//! (must be done directly if these method are not used)
//! num greater than NbParams means that following lists are empty
//! If current num is not managed, it remains at 1, which probably
//! will cause error when successive steps of reading are made
Standard_EXPORT void SetCurrentNumber (const Standard_Integer num);
//! gives current stage (Own-Props-Assocs-End, begins at Own)
Standard_EXPORT IGESData_ReadStage Stage() const;
//! passes to next stage (must be linked with setting Current)
Standard_EXPORT void NextStage();
//! passes directly to the end of reading process
Standard_EXPORT void EndAll();
//! returns number of parameters (minus the first one)
//! following method skip the first parameter (1 gives the 2nd)
Standard_EXPORT Standard_Integer NbParams() const;
//! returns type of parameter; note that "Ident" or "Sub" cannot
//! be encountered, they correspond to "Integer", see also below
Standard_EXPORT Interface_ParamType ParamType (const Standard_Integer num) const;
//! returns literal value of a parameter, as it was in file
Standard_EXPORT Standard_CString ParamValue (const Standard_Integer num) const;
//! says if a parameter is defined (not void)
//! See also DefinedElseSkip
Standard_EXPORT Standard_Boolean IsParamDefined (const Standard_Integer num) const;
//! says if a parameter can be regarded as an entity reference
//! (see Prepare from IGESReaderData for more explanation)
//! Note that such a parameter can seen as be a plain Integer too
Standard_EXPORT Standard_Boolean IsParamEntity (const Standard_Integer num) const;
//! returns entity number corresponding to a parameter if there is
//! otherwise zero (according criterium IsParamEntity)
Standard_EXPORT Standard_Integer ParamNumber (const Standard_Integer num) const;
//! directly returns entity referenced by a parameter
Standard_EXPORT Handle(IGESData_IGESEntity) ParamEntity (const Handle(IGESData_IGESReaderData)& IR, const Standard_Integer num);
//! Creates a ParamCursor from the Current Number, to read one
//! parameter, and to advance Current Number after reading
Standard_EXPORT IGESData_ParamCursor Current() const;
//! Creates a ParamCursor from the Current Number, to read a list
//! of "nb" items, and to advance Current Number after reading
//! By default, each item is made of one parameter
//! If size is given, it precises the number of params per item
Standard_EXPORT IGESData_ParamCursor CurrentList (const Standard_Integer nb, const Standard_Integer size = 1) const;
//! Allows to simply process a parameter which can be defaulted.
//! Waits on the Current Number a defined parameter or skips it :
//! If the parameter <num> is defined, changes nothing and returns True
//! Hence, the next reading with current cursor will concern <num>
//! If it is void, advances Current Position by one, and returns False
//! The next reading will concern <num+1> (except if <num> = NbParams)
//!
//! This allows to process Default values as follows (C++) :
//! if (PR.DefinedElseSkip()) {
//! .. PR.Read... (current parameter);
//! } else {
//! <current parameter> = default value
//! .. nothing else to do with ParamReader
//! }
//! For Message
Standard_EXPORT Standard_Boolean DefinedElseSkip();
Standard_EXPORT Standard_Boolean ReadInteger (const IGESData_ParamCursor& PC, Standard_Integer& val);
//! Reads an Integer value designated by PC
//! The method Current designates the current parameter and
//! advances the Current Number by one after reading
//! Note that if a count (not 1) is given, it is ignored
//! If it is not an Integer, fills Check with a Fail (using mess)
//! and returns False
Standard_EXPORT Standard_Boolean ReadInteger (const IGESData_ParamCursor& PC, const Standard_CString mess, Standard_Integer& val);
Standard_EXPORT Standard_Boolean ReadBoolean (const IGESData_ParamCursor& PC, const Message_Msg& amsg, Standard_Boolean& val, const Standard_Boolean exact = Standard_True);
//! Reads a Boolean value from parameter "num"
//! A Boolean is given as an Integer value 0 (False) or 1 (True)
//! Anyway, an Integer is demanded (else, Check is filled)
//! If exact is given True, those precise values are demanded
//! Else, Correction is done, as False for 0 or <0, True for >0
//! (with a Warning error message, and return is True)
//! In case of error (not an Integer, or not 0/1 and exact True),
//! Check is filled with a Fail (using mess) and return is False
Standard_EXPORT Standard_Boolean ReadBoolean (const IGESData_ParamCursor& PC, const Standard_CString mess, Standard_Boolean& val, const Standard_Boolean exact = Standard_True);
Standard_EXPORT Standard_Boolean ReadReal (const IGESData_ParamCursor& PC, Standard_Real& val);
//! Reads a Real value from parameter "num"
//! An Integer is accepted (Check is filled with a Warning
//! message) and causes return to be True (as normal case)
//! In other cases, Check is filled with a Fail and return is False
Standard_EXPORT Standard_Boolean ReadReal (const IGESData_ParamCursor& PC, const Standard_CString mess, Standard_Real& val);
Standard_EXPORT Standard_Boolean ReadXY (const IGESData_ParamCursor& PC, Message_Msg& amsg, gp_XY& val);
//! Reads a couple of Real values (X,Y) from parameter "num"
//! Integers are accepted (Check is filled with a Warning
//! message) and cause return to be True (as normal case)
//! In other cases, Check is filled with a Fail and return is False
Standard_EXPORT Standard_Boolean ReadXY (const IGESData_ParamCursor& PC, const Standard_CString mess, gp_XY& val);
Standard_EXPORT Standard_Boolean ReadXYZ (const IGESData_ParamCursor& PC, Message_Msg& amsg, gp_XYZ& val);
//! Reads a triplet of Real values (X,Y,Z) from parameter "num"
//! Integers are accepted (Check is filled with a Warning
//! message) and cause return to be True (as normal case)
//! In other cases, Check is filled with a Fail and return is False
//! For Message
Standard_EXPORT Standard_Boolean ReadXYZ (const IGESData_ParamCursor& PC, const Standard_CString mess, gp_XYZ& val);
Standard_EXPORT Standard_Boolean ReadText (const IGESData_ParamCursor& thePC, const Message_Msg& theMsg, Handle(TCollection_HAsciiString)& theVal);
//! Reads a Text value from parameter "num", as a String from
//! Collection, that is, Hollerith text without leading "nnnH"
//! If it is not a String, fills Check with a Fail (using mess)
//! and returns False
Standard_EXPORT Standard_Boolean ReadText (const IGESData_ParamCursor& PC, const Standard_CString mess, Handle(TCollection_HAsciiString)& val);
Standard_EXPORT Standard_Boolean ReadEntity (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, IGESData_Status& aStatus, Handle(IGESData_IGESEntity)& val, const Standard_Boolean canbenul = Standard_False);
//! Reads an IGES entity from parameter "num"
//! An Entity is known by its reference, which has the form of an
//! odd Integer Value (a number in the Directory)
//! If <canbenul> is given True, a Reference can also be Null :
//! in this case, the result is a Null Handle with no Error
//! If <canbenul> is False, a Null Reference causes an Error
//! If the parameter cannot refer to an entity (or null), fills
//! Check with a Fail (using mess) and returns False
Standard_EXPORT Standard_Boolean ReadEntity (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, const Standard_CString mess, Handle(IGESData_IGESEntity)& val, const Standard_Boolean canbenul = Standard_False);
Standard_EXPORT Standard_Boolean ReadEntity (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, IGESData_Status& aStatus, const Handle(Standard_Type)& type, Handle(IGESData_IGESEntity)& val, const Standard_Boolean canbenul = Standard_False);
//! Safe variant for arbitrary type of argument
template <class T>
Standard_Boolean ReadEntity (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, IGESData_Status& aStatus, const Handle(Standard_Type)& type, Handle(T)& val, const Standard_Boolean canbenul = Standard_False)
{
Handle(IGESData_IGESEntity) aVal = val;
Standard_Boolean aRes = ReadEntity (IR, PC, aStatus, type, aVal, canbenul);
val = Handle(T)::DownCast(aVal);
return aRes && (canbenul || ! val.IsNull());
}
//! Works as ReadEntity without Type, but in addition checks the
//! Type of the Entity, which must be "kind of" a given <type>
//! Then, gives the same fail cases as ReadEntity without Type,
//! plus the case "Incorrect Type"
//! (in such a case, returns False and givel <val> = Null)
Standard_EXPORT Standard_Boolean ReadEntity (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, const Standard_CString mess, const Handle(Standard_Type)& type, Handle(IGESData_IGESEntity)& val, const Standard_Boolean canbenul = Standard_False);
//! Safe variant for arbitrary type of argument
template <class T>
Standard_Boolean ReadEntity (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, const Standard_CString mess, const Handle(Standard_Type)& type, Handle(T)& val, const Standard_Boolean canbenul = Standard_False)
{
Handle(IGESData_IGESEntity) aVal = val;
Standard_Boolean aRes = ReadEntity (IR, PC, mess, type, aVal, canbenul);
val = Handle(T)::DownCast(aVal);
return aRes && (canbenul || ! val.IsNull());
}
Standard_EXPORT Standard_Boolean ReadInts (const IGESData_ParamCursor& PC, const Message_Msg& amsg, Handle(TColStd_HArray1OfInteger)& val, const Standard_Integer index = 1);
//! Reads a list of Integer values, defined by PC (with a count of
//! parameters). PC can start from Current Number and command it
//! to advance after reading (use method CurrentList to do this)
//! The list is given as a HArray1, numered from "index"
//! If all params are not Integer, Check is filled (using mess)
//! and return value is False
Standard_EXPORT Standard_Boolean ReadInts (const IGESData_ParamCursor& PC, const Standard_CString mess, Handle(TColStd_HArray1OfInteger)& val, const Standard_Integer index = 1);
Standard_EXPORT Standard_Boolean ReadReals (const IGESData_ParamCursor& PC, Message_Msg& amsg, Handle(TColStd_HArray1OfReal)& val, const Standard_Integer index = 1);
//! Reads a list of Real values defined by PC
//! Same conditions as for ReadInts, for PC and index
//! An Integer parameter is accepted, if at least one parameter is
//! Integer, Check is filled with a "Warning" message
//! If all params are neither Real nor Integer, Check is filled
//! (using mess) and return value is False
Standard_EXPORT Standard_Boolean ReadReals (const IGESData_ParamCursor& PC, const Standard_CString mess, Handle(TColStd_HArray1OfReal)& val, const Standard_Integer index = 1);
Standard_EXPORT Standard_Boolean ReadTexts (const IGESData_ParamCursor& PC, const Message_Msg& amsg, Handle(Interface_HArray1OfHAsciiString)& val, const Standard_Integer index = 1);
//! Reads a list of Hollerith Texts, defined by PC
//! Texts are read as Hollerith texts without leading "nnnH"
//! Same conditions as for ReadInts, for PC and index
//! If all params are not Text, Check is filled (using mess)
//! and return value is False
Standard_EXPORT Standard_Boolean ReadTexts (const IGESData_ParamCursor& PC, const Standard_CString mess, Handle(Interface_HArray1OfHAsciiString)& val, const Standard_Integer index = 1);
Standard_EXPORT Standard_Boolean ReadEnts (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, const Message_Msg& amsg, Handle(IGESData_HArray1OfIGESEntity)& val, const Standard_Integer index = 1);
//! Reads a list of Entities defined by PC
//! Same conditions as for ReadInts, for PC and index
//! The list is given as a HArray1, numered from "index"
//! If all params cannot be read as Entities, Check is filled
//! (using mess) and return value is False
//! Remark : Null references are accepted, they are ignored
//! (negative pointers too : they provoke a Warning message)
//! If the caller wants to check them, a loop on ReadEntity should
//! be used
Standard_EXPORT Standard_Boolean ReadEnts (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, const Standard_CString mess, Handle(IGESData_HArray1OfIGESEntity)& val, const Standard_Integer index = 1);
Standard_EXPORT Standard_Boolean ReadEntList (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, Message_Msg& amsg, Interface_EntityList& val, const Standard_Boolean ord = Standard_True);
//! Reads a list of Entities defined by PC
//! Same conditions as for ReadEnts, for PC
//! The list is given as an EntityList
//! (index has no meaning; the EntityList starts from clear)
//! If "ord" is given True (default), entities will be added to
//! the list in their original order
//! Remark : Negative or Null Pointers are ignored
//! Else ("ord" False), order is not guaranteed (faster mode)
//! If all params cannot be read as Entities, same as above
//! Warning Give "ord" to False ONLY if order is not significant
Standard_EXPORT Standard_Boolean ReadEntList (const Handle(IGESData_IGESReaderData)& IR, const IGESData_ParamCursor& PC, const Standard_CString mess, Interface_EntityList& val, const Standard_Boolean ord = Standard_True);
Standard_EXPORT Standard_Boolean ReadingReal (const Standard_Integer num, Standard_Real& val);
//! Routine which reads a Real parameter, given its number
//! Same conditions as ReadReal for mess, val, and return value
Standard_EXPORT Standard_Boolean ReadingReal (const Standard_Integer num, const Standard_CString mess, Standard_Real& val);
Standard_EXPORT Standard_Boolean ReadingEntityNumber (const Standard_Integer num, Standard_Integer& val);
//! Routine which reads an Entity Number (which allows to read the
//! Entity in the IGESReaderData by BoundEntity), given its number
//! in the list of Parameters
//! Same conditions as ReadEntity for mess, val, and return value
//! In particular, returns True and val to zero means Null Entity,
//! and val not zero means Entity read by BoundEntity
Standard_EXPORT Standard_Boolean ReadingEntityNumber (const Standard_Integer num, const Standard_CString mess, Standard_Integer& val);
Standard_EXPORT void SendFail (const Message_Msg& amsg);
Standard_EXPORT void SendWarning (const Message_Msg& amsg);
Standard_EXPORT void AddFail (const Standard_CString afail, const Standard_CString bfail = "");
//! feeds the Check with a new fail (as a String or as a CString)
Standard_EXPORT void AddFail (const Handle(TCollection_HAsciiString)& af, const Handle(TCollection_HAsciiString)& bf);
Standard_EXPORT void AddWarning (const Standard_CString awarn, const Standard_CString bwarn = "");
//! feeds the Check with a new Warning message
Standard_EXPORT void AddWarning (const Handle(TCollection_HAsciiString)& aw, const Handle(TCollection_HAsciiString)& bw);
Standard_EXPORT void Mend (const Standard_CString pref = "");
//! says if fails have been recorded into the Check
Standard_EXPORT Standard_Boolean HasFailed() const;
//! returns the Check
//! Note that any error signaled above is also recorded into it
Standard_EXPORT const Handle(Interface_Check)& Check() const;
//! returns the check in a way which allows to work on it directly
//! (i.e. messages added to the Check are added to ParamReader too)
Standard_EXPORT Handle(Interface_Check)& CCheck();
//! Returns True if the Check is Empty
//! Else, it has to be recorded with the Read Entity
Standard_EXPORT Standard_Boolean IsCheckEmpty() const;
protected:
private:
Standard_EXPORT Standard_Boolean PrepareRead (const IGESData_ParamCursor& PC, const Standard_Boolean several, const Standard_Integer size = 1);
//! Prepares work for Read... methods which call it to begin
//! The required count of parameters must not overpass NbParams.
//! If several is given False, PC count must be one.
//! If size is given, the TermSize from ParmCursor must be a
//! multiple count of this size.
//! If one of above condition is not satisfied, a Fail Message is
//! recorded into Check, using the root "mess" and return is False
Standard_EXPORT Standard_Boolean PrepareRead (const IGESData_ParamCursor& PC, const Standard_CString mess, const Standard_Boolean several, const Standard_Integer size = 1);
//! Gets the first parameter number to be read, determined from
//! ParamCursor data read by PrepareRead (Start + Offset)
//! Then commands to skip 1 parameter (default) or nb if given
Standard_EXPORT Standard_Integer FirstRead (const Standard_Integer nb = 1);
//! Gets the next parameter number to be read. Skips to next Item
//! if TermSize has been read.
//! Then commands to skip 1 parameter (default) or nb if given
Standard_EXPORT Standard_Integer NextRead (const Standard_Integer nb = 1);
//! internal method which builds a Fail message from an
//! identification "idm" and a diagnostic ("afail")
//! Also feeds LastReadStatus
//! <af> for final message, bf (can be different) for original
Standard_EXPORT void AddFail (const Standard_CString idm, const Handle(TCollection_HAsciiString)& af, const Handle(TCollection_HAsciiString)& bf);
//! Same as above but with CString
//! <bf> empty means = <af>
Standard_EXPORT void AddFail (const Standard_CString idm, const Standard_CString afail, const Standard_CString bfail);
//! internal method which builds a Warning message from an
//! identification "idm" and a diagnostic
//! <aw> is final message, bw is original (can be different)
//! Also feeds LastReadStatus
Standard_EXPORT void AddWarning (const Standard_CString idm, const Handle(TCollection_HAsciiString)& aw, const Handle(TCollection_HAsciiString)& bw);
//! Same as above but with CString
//! <bw> empty means = <aw>
Standard_EXPORT void AddWarning (const Standard_CString idm, const Standard_CString aw, const Standard_CString bw);
Handle(Interface_ParamList) theparams;
Handle(Interface_Check) thecheck;
Standard_Integer thebase;
Standard_Integer thenbpar;
Standard_Integer thecurr;
IGESData_ReadStage thestage;
Standard_Boolean thelast;
Standard_Integer theindex;
Standard_Integer thenbitem;
Standard_Integer theitemsz;
Standard_Integer theoffset;
Standard_Integer thetermsz;
Standard_Integer themaxind;
Standard_Integer thenbterm;
Standard_Integer pbrealint;
Standard_Integer pbrealform;
Standard_Integer thenum;
};
#endif // _IGESData_ParamReader_HeaderFile
|
// Example 6.4 : std::string, std::string_view
// Created by Oleksiy Grechnyev 2020
#include <iostream>
#include <string>
#include <string_view>
//==============================
int main(){
using namespace std;
{
cout << "std::string :\n\n";
// Create string from C-string literal
string s1("Big [REDACTED]");
// Concatenate
s1 += " Gun";
cout << "s1 = " << s1 << endl;
cout << "s1.size() = " << s1.size() << endl;
// Create a 0-terminated C-string (const char *) from it
const char * c1 = s1.c_str();
cout << "c1 = " << c1 << endl;
// Find a substring, then remove it
string s2 = "[REDACTED] ";
int pos = s1.find(s2);
cout << "pos = " << pos << endl;
if (pos != string::npos){
// Remove the substring
s1.erase(pos, s2.size());
}
cout << "s1 = " << s1 << endl;
// iteral with suffix s is std::string, not const char * !
cout << "std::string literal"s << endl;
}
{
cout << "std::string_view :\n\n";
// From C-string
const char * c1 = "Take a look to the sky just before you die";
string_view sv1(c1); // Whole 0-terminated string
string_view sv2(c1 + 12, 10); // Substring
// From std::string
string s3{"It is the last time you will"};
string_view sv3(s3); // Whole string
string_view sv4 = string_view(s3).substr(10, 9); // Substring
// WRONG !!! Dangling pointer, as string temporary dies !!!
// string_view sv(string("Error !!!"));
cout << "sv1 = " << sv1 << endl;
cout << "sv2 = " << sv2 << endl;
cout << "sv3 = " << sv3 << endl;
cout << "sv4 = " << sv4 << endl;
}
return 0;
}
|
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;
class Solution {
public:
string largestNumber(vector<int>& nums) {
//基本思想:排序,将先将nums中数字转为字符串保存到ans,然后对ans排序
//排序算法是将两个字符串正反拼接后比较大小,这正好是题目所要求的返回最大拼接的字符串
string res;
vector<string> ans;
for (auto num : nums)
ans.push_back(to_string(num));
sort(ans.begin(), ans.end(), [](const string& a, const string& b) {return a + b > b + a; });
for (int i = 0; i < ans.size(); i++)
res.append(ans[i]);
if (res[0] == '0')
return "0";
return res;
}
};
class Solution1 {
public:
string largestNumber(vector<int>& nums) {
//基本思想:暴力,用二维数组vec保存nums中每个数字的每一位
//然后进行排序比如3,31,34的顺序是34,3,31,比较每一位数字如果vec[i][k]<vec[j][k]直接交换
//如果vec[i][k]==vec[j][k],这个时候如果vec[i]到最后一位数字了,那就比较vec[j]当前位数字和vec[i]第一位数字的大小如果小于交换
//如果vec[i][0]==vec[j][k+1]且k+1是vec[j]最后一位数字,对于830,8308和898,89的情况如果vec[i][temp]>vec[i][temp + 1]交换
string res;
vector<vector<int>> vec;
for (auto num : nums)
{
vector<int> cur;
while (num / 10 != 0)
{
cur.push_back(num % 10);
num = num / 10;
}
cur.push_back(num);
reverse(cur.begin(), cur.end());
vec.push_back(cur);
}
for (int i = 0; i < vec.size() - 1; i++)
{
for (int j = i + 1; j < vec.size(); j++)
{
int k = 0;
while (k < vec[i].size() && k < vec[j].size())
{
if (vec[i][k] < vec[j][k])
{
swap(vec[i], vec[j]);
break;
}
else if (vec[i][k] > vec[j][k])
{
break;
}
else
{
if (k == vec[i].size() - 1 && k < vec[j].size() - 1)
{
while (k < vec[j].size() - 1)
{
if (vec[i][0] < vec[j][k + 1])
{
swap(vec[i], vec[j]);
break;
}
else if (vec[i][0] == vec[j][k + 1])
{
if (k + 1 == vec[j].size() - 1)
{
int temp = 0;
while (temp < vec[i].size() - 1)
{
if (vec[i][temp] > vec[i][temp + 1])
{
swap(vec[i], vec[j]);
break;
}
else if (vec[i][temp] < vec[i][temp + 1])
break;
else
temp++;
}
}
k++;
}
else
break;
}
break;
}
else if (k == vec[j].size() - 1 && k < vec[i].size() - 1)
{
while (k < vec[i].size() - 1)
{
if (vec[j][0] > vec[i][k + 1])
{
swap(vec[i], vec[j]);
break;
}
else if (vec[j][0] == vec[i][k + 1])
{
if (k + 1 == vec[i].size()-1)
{
int temp = 0;
while (temp < vec[j].size() - 1)
{
if (vec[j][temp] < vec[j][temp + 1])
{
swap(vec[i], vec[j]);
break;
}
else if (vec[j][temp] > vec[j][temp + 1])
break;
else
temp++;
}
}
k++;
}
else
break;
}
break;
}
}
k++;
}
}
}
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
res.push_back('0' + vec[i][j]);
}
if (res[0] == '0')
return "0";
else
return res;
}
};
int main()
{
Solution solute;
vector<int> nums = { 824,8248 };
cout << solute.largestNumber(nums) << endl;
return 0;
}
|
#ifndef CMESSAGEDATAMEDIATOR_H
#define CMESSAGEDATAMEDIATOR_H
#include <QObject>
#include <QMap>
#include <QMutex>
#include "../SMonitorServer/CNetMessage.h"
class CMessageDataMediator : public QObject
{
Q_OBJECT
public:
CMessageDataMediator(QObject *parent = 0);
~CMessageDataMediator();
static CMessageDataMediator* Instance();
QString m_strOldId; //旧的门店编号
QString m_strNewId; //新的门店编号
QString m_strSoftname; //安装好的软件名称
QString m_strVersion; //软件版本号
//全局标志位
bool m_bIsCanConnectedTime; //当前是否处于可连接服务器时段
QString m_strSvrUpdateXmlUrl; //服务器升级XML
QString m_strHelpInfoXmlUrl; //帮助信息XML
QString m_strVersionCheckFile; //客户端版本号比较文件URL
QString m_strClientVersion; //客户端版本号
bool m_bClientStartOver; //客户端启动完毕
bool m_bTextMode; //测试模式
bool m_bLocalCrossLinkIsInstalled; //本地CrossLink是否已安装
bool m_bCrossLinkIsInstalled;
//门店信息
QString m_strShopId; //门店编号
QString m_strUnitNum; //组织编号
QString m_strUnitName; //组织名称
public:
//设置连接消息MAP属性值
void setConnectMsgMapProperty(MsgHead msgHead, bool bRecved);
//初始化连接消息MAP
void initConnectMsgMap();
//添加消息
void addConnectMsgProperty(MsgHead msgHead, bool bRecved);
//获取消息属性
bool getConnectMsg(MsgHead msgHead, bool& bRecved);
//判断所有消息是否全都收到
bool isAllMsgRecved(bool bNeedHasMsg);
//清空消息MAP
void clearConnectMsgMap();
//查询门店信息
void QueryShopInfo(bool bRefreshRead);
//是否需要上传CrossLinkRun安装信息
bool NeedUploadCrossLinkRunState();
private:
bool GetAccessDataPath(QString& strDataPath);
private:
static CMessageDataMediator* m_Instance;
QMutex m_ConnectMsgMapMutex; //上传信息MAP锁
QMap<MsgHead, bool> m_ConnectMsgMap;
};
#define MessageDataMediator CMessageDataMediator::Instance()
#endif // CMESSAGEDATAMEDIATOR_H
|
#include <iostream>
int serch(int* arr, int num, int begin, int end) {
if (num > arr[end]) {
std::cout << "number is not element of array: " << std::endl;
return 1;
}
if (num == arr[begin]) {
std::cout << "number is a element of array: " << begin + 1 << std::endl;
return 0;
}
if (num == arr[end]) {
std::cout << "number is a element of array: " << end + 1 << std::endl;
return 0;
}
if (num == arr[(end - begin) / 2]) {
std::cout << "number is a element of array: " << (end - begin) / 2 + 1 << std::endl;
return 0;
}
if ((1 == end - begin) || (0 == end - begin)) {
std::cout << "number is not element of array" << std::endl;
return 1;
}
if (num < arr[(end - begin) / 2]) {
end = (end - begin) / 2;
return serch(arr, num, begin, end);
} else {
begin = begin + (end - begin) / 2;
return serch(arr, num, begin, end);
}
}
void validnumber(int& number) {
while (std::cin.fail()) {
std::cout << "Invalid Value: Try again!" << std::endl;
std::cin.clear();
std::cin.ignore(256,'\n');
std::cout << "Please enter the intager number: ";
std::cin>> number;
}
}
int main () {
int arr [10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
std::cout << "array is : ";
for(int i = 0; i < 10; ++i) {
std::cout << arr[i] << ", ";
}
std::cout << std::endl << "enter serch number" << std::endl;
int begin = 0;
int end = 9;
int num = 0;
std::cin >> num;
validnumber(num);
serch(arr, num, begin, end);
return 0;
}
|
#ifndef _CancleBankerProc_H_
#define _CancleBankerProc_H_
#include "BaseProcess.h"
#include "Player.h"
#include "Table.h"
class CancleBankerProc : public BaseProcess {
public:
CancleBankerProc();
virtual ~CancleBankerProc();
virtual int doRequest(CDLSocketHandler *clientHandler, InputPacket *inputPacket, Context *pt);
private:
int sendTabePlayersInfo(Player *player, Table *table, Player *applyer, short seq);
};
#endif
|
#include "stdafx.h"
#include "specmath.h"
#include <math.h>
#include <random>
#include <functional>
specrand specmath::sprand = specrand();
vec3 specmath::random_inside_unit_sphere()
{
float x = 2 * sprand.pull() - 1;
float y = 2 * sprand.pull() - 1;
float z = 2 * sprand.pull() - 1;
while (x*x + y * y + z * z > 1)
{
x = 2 * sprand.pull() - 1;
y = 2 * sprand.pull() - 1;
z = 2 * sprand.pull() - 1;
}
return vec3(x, y, z);
}
vec3 specmath::random_inside_unit_disk()
{
float x = 2 * sprand.pull() - 1;
float y = 2 * sprand.pull() - 1;
float z = 0;
vec3 disk = vec3(x, y, z);
while (disk * disk >= 1)
{
x = 2 * sprand.pull() - 1;
y = 2 * sprand.pull() - 1;
disk = vec3(x, y, z);
}
return disk;
}
float specmath::randFloat()
{
return sprand.pull();
}
specmath::specmath()
{
}
specmath::~specmath()
{
}
specrand::specrand()
{
std::random_device rd; //Will be used to obtain a seed for the random number engine
gen = std::mt19937(rd()); //Standard mersenne_twister_engine seeded with rd()
dis = std::uniform_real_distribution<float>(0.0f, 1.0f);
}
float specrand::pull()
{
return dis(gen);
}
|
#pragma once
#include <vector>
#include <Windows.h>
namespace physmeme
{
NTSTATUS __cdecl map_driver(std::vector<std::uint8_t>& raw_driver);
NTSTATUS __cdecl map_driver(std::uint8_t * image, std::size_t size);
}
|
#include <iostream>
#include <vector>
#include <ctime>
#include <ios>
#include <iomanip>
using namespace std;
int validar( string , vector<string> ) ;
string soliRegistro( vector<string> ) ;
vector<int> calificaciones() ;
int promedioNotas( vector<int> ) ;
void mostrarRegistro( vector<int> , vector<string> ) ;
int main()
{
vector<string> nombreCampos = { "TC1" , "TC2" , "TC3" , "TC4" , "TC5" , "Promedio" } ,
codigos ; // almacena los 10 codigos de los alumnos
vector< vector<int> > notas( 10 , vector<int>(5) ) ; // almacena las notas de los alumnos
int indice = 0 ;
while( true )
{
if( indice == 10 ) break ;
cout << "Solicitamos codigo del alumno" << endl ;
codigos.push_back( soliRegistro( codigos ) ) ;
notas[ indice ] = calificaciones() ;
mostrarRegistro( notas.at( indice ) , nombreCampos ) ;
indice++ ;
}
return 0 ;
} // fin main
int validar( string codigo , vector<string> codigos )
{
int resultado = 0 ;
for( int i = 0 ; i < codigos.size() ; i++ )
{
if( codigo == codigos.at(i) ) resultado = 1 ;
}
return resultado ;
} // fin validar
string soliRegistro( vector<string> codigos )
{
string codigo ;
while( true )
{
cout << "Ingrese codigo del estudiante: " ; cin >> codigo ;
if( validar( codigo , codigos ) == 0 ) break ;
else cout << "Codigo ya registrado" << endl ;
}
return codigo ;
} // fin soliRegistro
vector<int> calificaciones()
{
vector<int> notas ;
int valor = 0 ;
srand( time(NULL) ) ;
for( int i = 0 ; i < 5 ; i++ )
{
valor = rand() % (20-5+1)+5 ;
notas.push_back( valor ) ;
}
return notas ;
} // fin calificaciones
int promedioNotas( vector<int> notas )
{
int promedio = 0 ;
for( int i = 0 ; i < notas.size() ; i++ )
{
promedio += notas.at(i) ;
}
return promedio / notas.size() ;
} // fin promedioNotas
void mostrarRegistro( vector<int> notas , vector<string> nombreCampos )
{
cout << "Registro" << endl ;
for( int i = 0 ; i < nombreCampos.size() ; i++ )
{
cout << setw( 5 ) ;
i == nombreCampos.size()-1 ? cout << nombreCampos.at(i) << endl : cout << nombreCampos.at(i) << " " ;
}
for( int i = 0 ; i < notas.size() ; i++ )
{
cout << setw( 5 ) ;
cout << notas.at(i) << " " ;
if( i == notas.size() - 1 )
{
cout << setw( 5 ) ;
cout << promedioNotas( notas ) << endl ;
}
}
} // fin mostrarRegistro
|
int pin = 3;
char instruction;
int action = 0;
void setup(){
Serial.begin( 9600);
pinMode( pin, OUTPUT);
}
void loop(){
if ( Serial.available() > 0){
instruction = Serial.read();
if ( instruction == '1'){
digitalWrite( pin, HIGH);
}
else if ( instruction == '0'){
digitalWrite( pin, LOW);
}
}
}
|
// Author: Kirill Gavrilov
// Copyright (c) 2018-2019 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 _RWGltf_GltfPrimArrayData_HeaderFile
#define _RWGltf_GltfPrimArrayData_HeaderFile
#include <NCollection_Buffer.hxx>
#include <RWGltf_GltfAccessor.hxx>
#include <RWGltf_GltfArrayType.hxx>
#include <TCollection_AsciiString.hxx>
//! An element within primitive array - vertex attribute or element indexes.
class RWGltf_GltfPrimArrayData
{
public:
Handle(NCollection_Buffer) StreamData;
TCollection_AsciiString StreamUri;
int64_t StreamOffset;
int64_t StreamLength;
RWGltf_GltfAccessor Accessor;
RWGltf_GltfArrayType Type;
RWGltf_GltfPrimArrayData()
: StreamOffset (0), StreamLength (0), Type (RWGltf_GltfArrayType_UNKNOWN) {}
RWGltf_GltfPrimArrayData (RWGltf_GltfArrayType theType)
: StreamOffset (0), StreamLength (0), Type (theType) {}
};
#endif // _RWGltf_GltfPrimArrayData_HeaderFile
|
/*Contains the Arduino Uno/atmega328 code for the board which controls the photogate and personnel gate open/closed sensors on the tower.
* This board has support for 6 photogate sensors that are high when open, and low when blocked. The following sensors are defined:
* SENSORS0 Register:
* TOP_TRIP_SENSOR - indicates when the trolley is docked at the top of the tower
* GRIP_RELEASE_SENSOR - Tripped when the trolley passes through approximately the midpoint of the tower during a drop - provides feedback to other systems so that the bucket-holding magnet can be released at the appropriate time
* MISC_1_SENSOR - unused
* MISC_2_SENSOR - unused
* TOP_VEL_SENSOR - Top velocity chronograph sensor/first to be tripped
* BTM_VEL_SENSOR - Bottom velocity chronograph sensor/second to be tripped
*
* The personnel gate open/closed sensor is defined as follows
* GATE_SWITCH_SIG - high when gate is closed; low when open. Test shouldn't be allowed to commence with this gate open
*
* Relevant status bits provide state information of the system, and are listed as follows:
* STATUS:
* TIMER_ACTIVE - high when the chronograph is active and ready to take a velocity measurement
* TEST_READY - high when all sensors are good for a drop test and that the the system state is ready to start a drop test
* TIMER_TRIPPED - high when the timer has moved from an active/ready state to a "tripped" state, or a measurement complete state
*
* Relevant control bits provide commands to the module, and are listed as follows:
* CTRL
* TIMER_RST - Set to 1 to reset and/or set the timer to its active state. Before setting this bit, ensure that the previous time measurement has been successfully recovered by the master device
*
* Time data is in microseconds and is stored in the TIMEA (MSB) and TIMEB (LSB) registers
*
* The recommended master-side sequence for running the module in a test setting is as follows:
* 0) User ensures that no sensors are blocked, and that trolley is docked and ready to go
* 1) Master device sets the TIMER_RST bit to activate the timer
* 2) Master device checks the TEST_READY bit to ensure that all sensors are blocked/unblocked appropriately, and that the timer has been activated
* 3) Master runs test and waits approximate time it takes for drop test to complete, plus 1 second to give the microcontroller time to save data to memory
* 4) Master checks TIMER_TRIPPED bit to ensure that timer was tripped succesfully
* 5) Master retrieves data from registers TIMEA and TIMEB, and re-assembles the time value; checks value to ensure it makes sense
* 6) Start again at (0) for repeated tests
*
*/
#include <SimpleModbusSlave.h>
//Pins of interest
enum { //PINB
P_PB0,
P_PB1,
P_PB2,
P_MOSI,
P_MISO,
P_SCK,
P_XTAL1,
P_XTAL2
};
enum { //PINC
P_TOP_TRIP_SENSOR,
P_GRIP_RELEASE_SENSOR,
P_MISC_1_SENSOR,
P_MISC_2_SENSOR,
P_PC4,
P_PC5,
P_RST
};
enum { //PIND
P_RX,
P_TX,
P_TOP_VEL_SENSOR,
P_BTM_VEL_SENSOR,
P_DE_RE,
P_PD5,
P_GATE_SWITCH_SIG,
P_PD7
};
enum { //SENSORS0
R_TOP_TRIP_SENSOR,
R_GRIP_RELEASE_SENSOR,
R_MISC_1_SENSOR,
R_MISC_2_SENSOR,
R_TOP_VEL_SENSOR,
R_BTM_VEL_SENSOR,
R_GATE_SWITCH_SIG
};
//TIMEA - MSBs
//TIMEB - LSBs
enum { //STATUS
R_TIMER_ACTIVE,
R_TEST_READY,
R_TIMER_TRIPPED
};
enum { //CTRL
R_TIMER_RST
};
//Arduino Pin Numbers (Redundant)
#define STARTPIN 2
#define STOPPIN 3
#define DE_REPIN 4
#define MODBUS_BAUD_RATE 115200
#define MODBUS_ADDR 0x03
enum
{
SENSORS0,
TIMEA,
TIMEB,
STATUS,
CTRL,
HOLDING_REGS_SIZE // leave this one
// total number of registers for function 3 and 16 share the same register array
// i.e. the same address space
};
unsigned int holdingRegs[HOLDING_REGS_SIZE]; // function 3 and 16 register array
//Timer Variables
volatile unsigned long startTime, stopTime, dt;
volatile unsigned long tripFlag = 0;
volatile unsigned int startFlag, stopFlag = 0;
//Timer Interrupt Vectors
const uint8_t startInt = digitalPinToInterrupt(STARTPIN);
const uint8_t stopInt = digitalPinToInterrupt(STOPPIN);
/**Pulls in sensor values and puts them in SENSORS0 register
*
*/
void UpdateSENSORS0(void)
{
holdingRegs[SENSORS0] = (PINC & 0b00001111) | ((PIND & 0b00001100) << 2) | ((PIND & 0b01000000) << 0);
//holdingRegs[SENSORS0] = 0b11000011;
//holdingRegs[SENSORS0] = PIND & 0b01000000;
}
/** Checks if ctrl bits have been reset and acts accordingly - requires UpdateSENSORS0() to be run first for accurate results
* TIMER_RST - ensures all sensor values are in correct states for starting test and resets and activates timer
*/
void CheckCTRL(void)
{
//Check TIMER_RST
if (((holdingRegs[SENSORS0] & 0b00110000) == 0b00110000) && (holdingRegs[CTRL] & 0b00000001)) { //Top/Btm Velocity sensors unblocked, Top trip sensor blocked and TIMER_RST flag high
//Reset and enable timer
startFlag = 0;
stopFlag = 0;
tripFlag = 0;
holdingRegs[TIMEA] = 0;
holdingRegs[TIMEB] = 0;
EIFR |= bit(startInt); //clear start interrupt flag if it has been triggered
attachInterrupt(startInt, StartISR, FALLING);
holdingRegs[CTRL] = (holdingRegs[CTRL] & ~0b00000001); //Clear TIMER_RST CTRL bit
holdingRegs[STATUS] = (holdingRegs[STATUS] | 0b00000001); //Set TIMER_ACTIVE STATUS bit
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~0b00000100); //Clear TIMER_TRIPPED STATUS bit
}
}
/** Updates status registers according to current sensor states - requires UpdateSENSORS() routine first for accurate results
* TEST_READY - high when all parameters are set for test to begin; appropriate sensors must be blocked/unblocked, timer must be active but not tripped
*/
void CheckSTATUS(void)
{
//Update TEST_READY
/* Registers must be:
* SENSORS0: GATE_SWITCH_SIG 1, BTM_VEL_SENSOR 1, TOP_VEL_SENSOR 1, GRIP_RELEASE_SENSOR 1, TOP_TRIP_SENSOR 0
* STATUS: TIMER_ACTIVE 1, TIMER_TRIPPED 0
*/
if ( ((holdingRegs[SENSORS0] & 0b01110011) == 0b01110010) && ((holdingRegs[STATUS] & 0b00000101) == 0b00000001) ) {
holdingRegs[STATUS] = holdingRegs[STATUS] | (0b00000010); //Test is ready
}
else {
holdingRegs[STATUS] = holdingRegs[STATUS] & ~(0b00000010); //Test is not ready - plz don't start test
}
}
void UpdateTIMER(void)
{
if (tripFlag) {
dt = stopTime - startTime;
holdingRegs[TIMEA] = (uint16_t )(dt >> 16); //places MSBs
holdingRegs[TIMEB] = (uint16_t)(dt); //places LSBs
}
}
void StartISR()
{
startTime = micros();
detachInterrupt(startInt);
startFlag = 1;
EIFR |= bit(stopInt); //clear stop interrupt flag if it has been triggered
attachInterrupt(stopInt, StopISR, FALLING);
}
void StopISR()
{
stopTime = micros();
detachInterrupt(stopInt);
//dt = stopTime - startTime;
stopFlag = 1;
tripFlag = 1;
holdingRegs[STATUS] = (holdingRegs[STATUS] | 0b00000100); //Set TIMER_TRIPPED STATUS bit
holdingRegs[STATUS] = (holdingRegs[STATUS] & ~0b00000001); //Clear TIMER_ACTIVE STATUS bit
}
void setup() {
//Set pinmodes:
DDRC = 0x00; //All inputs
DDRD = 0b00000010; //All inputs except TX
//Setup Timer interrupts
//EIFR |= bit(startInt); //clear start interrupt flag if it has been triggered (unecessary at first attach)
//attachInterrupt(startInt, StartISR, FALLING);
//Setup Serial protocol
modbus_configure(&Serial, MODBUS_BAUD_RATE, SERIAL_8N2, MODBUS_ADDR, DE_REPIN, HOLDING_REGS_SIZE, holdingRegs);
holdingRegs[STATUS] = 0b00000000; //Clear holdingRegs...
}
void loop() {
/*Run register update functions in following sequence:
* UpdateSENSORS0(); - updates the SENSORS0 register, which contains values of all photogate sensors and the personel entry gate
* CheckCTRL(); - updates the arduino status based on CTRL register status, including resetting timer
* CheckSTATUS(); - updates the status of the STATUS register bit TEST_READY to determine whether test is ready to run
* UpdateTIMER(); - if the timer has been tripped, computes the dt and updates the TIMEA and TIMEB registers with that time
*/
UpdateSENSORS0();
CheckCTRL();
CheckSTATUS();
UpdateTIMER();
modbus_update();
//delay(1);
}
|
// Copyright (c) 2021 Hartmut Kaiser
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/config.hpp>
#include <pika/iterator_support/counting_iterator.hpp>
#include <pika/iterator_support/iterator_range.hpp>
#include <pika/iterator_support/range.hpp>
#include <pika/iterator_support/traits/is_range.hpp>
namespace pika::util::detail {
///////////////////////////////////////////////////////////////////////////
template <typename Incrementable>
using counting_shape_type =
pika::util::iterator_range<pika::util::counting_iterator<Incrementable>>;
PIKA_NVCC_PRAGMA_HD_WARNING_DISABLE
template <typename Incrementable>
PIKA_HOST_DEVICE inline counting_shape_type<Incrementable> make_counting_shape(Incrementable n)
{
return pika::util::make_iterator_range(pika::util::make_counting_iterator(Incrementable(0)),
pika::util::make_counting_iterator(n));
}
} // namespace pika::util::detail
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "InteractorComponent.h"
#include "InteractableActor.h"
// Sets default values for this component's properties
UInteractorComponent::UInteractorComponent()
{
// Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features
// off to improve performance if you don't need them.
PrimaryComponentTick.bCanEverTick = false;
// ...
}
bool UInteractorComponent::Interact(UObjectInfo* info)
{
// You have to ovrride from this
if (GEngine) {
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Yellow, TEXT("You must override from this class"));
}
return false;
}
bool UInteractorComponent::InteractWith(UObjectInfo* info)
{
if (bIsInteractable) {
return Interact(info);
}
// Add something to say we can't interact (like a sound)
return false;
}
bool UInteractorComponent::PickUp()
{
if (bIsPickable) {
AInteractableActor* owner = Cast<AInteractableActor>(GetOwner());
if (owner->Info->ObjectId.Contains("key")) {
owner->PlaySound("pickup", owner->GetActorLocation());
}
return true;
}
// Add something to say we can't pickup (like a sound)
return false;
}
|
#pragma once
#include "components/component.hpp"
#include "utilities/global_set.hpp"
#include "point.hpp"
#include <unordered_set>
#include <cassert>
#include <string>
namespace item {
/// Properties of an item -- name of item, mass of item, material of item, etc.
struct ItemProperties {
std::string name;
float mass;
};
/// Component to describe an item which has properties, can be locked, and can be nested with other items.
///
///@invariant If container is not null, then parent does not have a Position Component or a Furniture Component.
///@invariant If container is null, then parent has a Position Component or a Furniture Component.
struct Item : ecs::ComponentCRTP<ecs::Component::Item, Item>, private global_set<Item> {
Item(const ItemProperties& p) : prop(p), locked(false), container(nullptr) { }
virtual void on_remove() override;
/// Attempt to lock the item. If the lock fails, return a default-initialized `ItemLock`.
struct ItemLock try_lock();
inline void insert(Item* i) { items.insert(i); }
inline void erase(Item* i) { items.erase(i); }
/// Unsafe function. Should not be called if you do not have both `this` and `container` locked.
///@warning UNSAFE
inline void remove_from() {
assert(container);
container->erase(this);
container = nullptr;
}
/// Unsafe function. Should not be called if you do not have both `this` and `i` locked.
///@warning UNSAFE
inline void insert_into(Item* i) {
assert(container == nullptr);
container = i;
container->insert(this);
}
/// Walk up the containment tree and find the top parent's location. Slow O(D) where D is tree depth.
Point pos() const;
ItemProperties const& prop;
bool locked;
Item* container;
using set_t = std::unordered_set<struct Item*>;
set_t items;
friend struct global_set<Item>;
};
}
|
#ifndef BLUETANK_H
#define BLUETANK_H
class BlueTank
{
public:
BlueTank();
};
#endif // BLUETANK_H
|
#include <stdio.h>
#include <iostream>
#include <math.h>
void selectionSort(int a[], int n) {
int i, j, min, temp;
for (i = 0; i < n - 1; i++) {
min = i;
for (j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
int** createMatrix(int rows, int cols, int initValue){
//alloc matrix
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i){
matrix[i] = new int[cols];
}
//Init matrix
for(int i =0; i<rows; i++){
for(int j = 0; j<cols; j++){
matrix[i][j] = initValue;
}
}
return matrix;
}
bool** createMatrix(int rows, int cols, bool initValue){
//alloc matrix
bool** matrix = new bool*[rows];
for (int i = 0; i < rows; ++i){
matrix[i] = new bool[cols];
}
//Init matrix
for(int i = 0; i<rows; i++){
for(int j = 0; j<cols; j++){
matrix[i][j] = initValue;
}
}
return matrix;
}
double** createMatrix(int rows, int cols, double initValue){
//alloc matrix
double** matrix = new double*[rows];
for (int i = 0; i < rows; ++i){
matrix[i] = new double[cols];
}
//Init matrix
for(int i =0; i<rows; i++){
for(int j = 0; j<cols; j++){
matrix[i][j] = initValue;
}
}
return matrix;
}
void deleteMatrix(int** matrix, int rows){
for (int i = 0; i < rows; ++i)
{delete [] matrix[i];}
delete [] matrix;
}
void printmatrix(int** matrix, int rows, int cols){
for(int i =0; i<rows; i++){
for(int j = 0; j<cols; j++){
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
void printmatrix(bool** matrix, int rows, int cols){
for(int i =0; i<rows; i++){
for(int j = 0; j<cols; j++){
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
void printmatrix(double** matrix, int rows, int cols){
for(int i =0; i<rows; i++){
for(int j = 0; j<cols; j++){
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
void printpaddedmatrix(int** matrix, int rows, int cols){
for(int i =1; i<=rows; i++){
for(int j = 1; j<=cols; j++){
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
void biner(int** A, bool** B, int T, int N, int M)
/* Membuat citra biner dari citra A berdasarkan nilai ambang
(threshold) T yang dispesifikasikan. Ukuran citra adalah N M.
citra_biner adalah tipe data untuk citra biner).
*/
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
if (A[i][j] < T)
B[i][j] = 0;
else
B[i][j] = 1;
}
}
void negatif(int** A, int** B, int N, int M)
/* Membuat citra negatif dari citra A. Hasilnya disimpan di
dalam citra B. Ukuran citra adalah N M.
*/
{
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
B[i][j] = 255 - A[i][j];
}
}
void image_brightening(int** A, int b, int** B, int N, int M)
/* Pencerahan citra dengan menjumlahkan setiap pixel di dalam citra A dengan
sebuah skalar b. Hasil disimpan di dalam citra B. Citra berukuran N M. */
{
int i, j, temp;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
std::cout<< A[i][j] <<" "<< B[i][j] <<std::endl;
temp = A[i][j] + b;
std::cout<< temp <<std::endl;
/* clipping */
if (temp < 0)
B[i][j] = 0;
else
if (temp > 255)
B[i][j] = 255;
else
B[i][j] = temp;
}
}
void grayscale(int** R, int** G, int** B, int** Gray, int N, int M) {
int i, j;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
Gray[i][j] = 0.299 * R[i][j] + 0.587 * G[i][j] + 0.144 * B[i][j];
}
}
void addvalues(int** A, int** B, int** C, int N, int M) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
int temp = A[i][j] + B[i][j];
if (temp > 255) {
C[i][j] = 255;
}
else {
C[i][j] = temp;
}
temp = 0;
}
}
}
void substractvalues(int** A, int** B, int** C, int N, int M) {
int i, j;
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
int temp = A[i][j] - B[i][j];
if (temp <= 0) {
C[i][j] = 0;
}
else {
C[i][j] = temp;
}
temp=0;
}
}
}
void addvalues(int** A, int B, int** C, int N, int M) {
int i, j, temp;
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
int temp = B + A[i][j];
if (temp > 255) {
C[i][j] = 255;
}
else {
C[i][j] = temp;
}
temp = 0;
}
}
}
void substractvalues(int** A, int B, int** C, int N, int M) {
int i, j, temp;
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
int temp = A[i][j] - B;
if (temp <= 0) {
C[i][j] = 255;
}
else {
C[i][j] = temp;
}
temp=0;
}
}
}
void multiplication(int** A, float** B, int** C, int N)
/* Mengalikan buah citra A dengan matriks koreksi B menjadi citra C.
Citra A, matriks B, dan hasil perkalian C berukuran N N.
*/
{
int i, j, k, temp;
for (i = 0; i <= N - 1; i++)
for (j = 0; j <= N - 1; j++)
{
temp = 0;
for (k = 0; k <= N - 1; k++)
{
temp = temp + A[i][k] * B[k][j];
/* clipping */
if (temp < 0)
C[i][j] = 0;
else
if (temp > 255)
C[i][j] = 255;
else
C[i][j] = temp;
}
}
}
void multiplication(int** A, float B, int** C, int N)
/* Mengalikan buah citra A dengan matriks koreksi B menjadi citra C.
Citra A, matriks B, dan hasil perkalian C berukuran N N.
*/
{
int i, j, temp;
for (i = 0; i <= N - 1; i++)
for (j = 0; j <= N - 1; j++)
{
temp = A[i][j] * B;
if (temp < 0) {
C[i][j] = 0;
}
else {
if (temp > 255) {
C[i][j] = 255;
}
else {
C[i][j] = (int)temp;
}
}
}
}
void not_operation(bool** A, bool** B, int N, int M)
/* Membuat citra komplemen dari citra biner A.
Komplemennya disimpan di dalam B. Ukuran citra A
adalah N M.
*/
{
int i, j;
for (i = 0; i <= N - 1; i++)
for (j = 0; j <= M - 1; j++)
{
B[i][j] = !A[i][j];
}
}
void translation(int** A, int** B, int N, int M, int m, int n)
/* Mentranslasi citra A sejauh m, n menjadi citra B. Ukuran citra N M. */
// CUMA BISA POSITIF VALUE
{
int i, j;
for (i = 0; i < m; i++) {
for (j = 0; j < M; j++)
{
B[i][j] = 0;
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < N; j++)
{
B[j][i] = 0;
}
}
for (i = m; i <= N - 1; i++) {
for (j = n; j <= M - 1; j++)
{
B[i][j] = A[i][j];//NOTDONE
}
}
}
void rotation90CCW(int** A, int** B, int N, int M)
/* Rotasi citra A sejauh 90 berlawanan arah jarum jam (CCW = Clock Counterwise). Ukuran citra adalah N M. Hasil rotasi disimpan di dalam citra B.
*/
{
int i, j, k;
for (i=0; i<=N-1; i++)
{
k=M-1;
for (j=0; j<=M-1; j++)
{
B[k][i]=A[i][j];
k--;
}
}
}
void rotation90CW(int** A, int** B, int N, int M)
/* Rotasi citra A sejauh 90 searah jarum jam (CW = Clock-wise).
Ukuran citra adalah N M. Hasil rotasi disimpan di dalam cira B.
*/
{
int i, j, k;
k=M-1;
for (i=0; i<=N-1; i++)
{
for (j=0; j<=M-1; j++)
{
B[j][k]=A[i][j];
}
k--;
}
}
void horizontal_flip(int** A, int** B, int N, int M)
/* Flipping vertikal (pencerminan terhadap sumbu-X) terhadap citar A.
Ukuran citra adalah N M. Hasil flipping disimpan di dalam citra B.
*/
{
int i, j, k;
for (i=0; i<=N-1; i++)
{
k= M-1;
for (j=0; j<=M-1; j++)
{
B[i][k]=A[i][j];
k--;
}
}
}
void vertical_flip(int** A, int** B, int N, int M)
/* Flipping vertikal (pencerminan terhadap sumbu-X) terhadap citar A.
Ukuran citra adalah N M. Hasil flipping disimpan di dalam citra B.
*/
{
int i, j, k;
k=N-1;
for (i=0; i<=N-1; i++)
{
for (j=0; j<=M-1; j++)
{
B[k][j]=A[i][j];
}
k--;
}
}
void zoom_in(int** A, int** B, int N, int M)
/* perbesaran citra A dengan faktor skala 2
Ukuran citra adalah N M. Hasil perbesaran disimpan dalam citra B.
*/
// B ukurannya dua kali dari A
{
int i, j, k, m, n;
m=0; n=0;
for (i=0; i<=N-1; i++)
{
for (j=0; j<=M-1; j++)
{
B[m][n]= A[i][j];
B[m][n+1]= A[i][j];
B[m+1][n]= A[i][j];
B[m+1][n+1]= A[i][j];
n=n+2;
}
m=m+2;
n=0;
}
}
void zoom_out(int** A, int** B, int N, int M)
/* perbesaran citra A dengan faktor skala 1/2
Ukuran citra adalah N M. Hasil perbesaran disimpa d dalam citra B.
*/
// N dan M Ukuran A, B sebisa mungkin ukurannya setengah dari A
{
int i, j, k, m, n;
m=0;
for (i=0; i<=N-1; i+=2)
{
n=0;
int temp = 0;
for (j=0; j<=M-1; j+=2)
{
temp = 0;
temp += A[i][j];
temp += A[i][j+1];
temp += A[i+1][j];
temp += A[i+1][j+1];
B[m][n] = temp/4 ;
n+=1;
}
m+=1;
}
}
void log_operation(int** A, int c, int** B, int N, int M)
{
int i, j, temp;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
temp = c*log(A[i][j]+1) ;
/* clipping */
if (temp < 0)
B[i][j] = 0;
else
if (temp > 255)
B[i][j] = 255;
else
B[i][j] = temp;
}
}
void invlog_operation(int** A, int c, int** B, int N, int M)
{
int i, j, temp;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
temp = c*exp(A[i][j]+1) ;
/* clipping */
if (temp < 0)
B[i][j] = 0;
else
if (temp > 255)
B[i][j] = 255;
else
B[i][j] = temp;
}
}
void power(int** A, int c, float y, int** B, int N, int M)
{
int i, j, temp;
for (i = 0; i < N; i++)
for (j = 0; j < M; j++)
{
temp = c*(pow(A[i][j],y)) ;
/* clipping */
if (temp < 0)
B[i][j] = 0;
else
if (temp > 255)
B[i][j] = 255;
else
B[i][j] = temp;
}
}
void median_filter(int **input, int **output, int rows, int cols){
// This holds the convolution results for an index.
int x, y; // Used for input matrix index
// Fill output matrix: rows and columns are i and j respectively
for (int i = 1; i < rows-1; i++)
{
for (int j = 1; j < cols-1; j++)
{
x = i-1;
y = j-1;
int convolute[9] = {0};
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute[k*3+l] = input[x][y];
// std::cout<<input[x][y]<<std::endl;
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
// std::cout<<convolute<<std::endl;
selectionSort(convolute,9);
// for (int z = 0; z < 9; z++){
// std::cout<< convolute[z] <<" ";
// }
// std::cout<<std::endl;
output[i][j] = (convolute[3]+convolute[4])/2;
// Add result to output matrix.
}
}
}
void convolute(int **input, int **output, double **kernel, int rows, int cols){
int convolute = 0; // This holds the convolution results for an index.
int x, y; // Used for input matrix index
// Fill output matrix: rows and columns are i and j respectively
for (int i = 1; i < rows-1; i++)
{
for (int j = 1; j < cols-1; j++)
{
x = i-1;
y = j-1;
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute += kernel[k][l] * input[x][y];
// std::cout<<input[x][y]<<std::endl;
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
// std::cout<<convolute<<std::endl;
if (convolute < 0)
output[i][j] = 0;
else
if (convolute > 255)
output[i][j] = 255;
else
output[i][j] = convolute;
// Add result to output matrix.
convolute = 0; // Needed before we move on to the next index.
}
}
}
void highpass1(int **input, int **output, int rows, int cols){
//detects edge
double** kernel = createMatrix(3,3,1.0);
kernel[0][0]=-1;
kernel[0][1]=-1;
kernel[0][2]=-1;
kernel[1][0]=-1;
kernel[1][1]=8;
kernel[1][2]=-1;
kernel[2][0]=-1;
kernel[2][1]=-1;
kernel[2][2]=-1;
// printmatrix(kernel,3,3);
convolute(input,output,kernel,rows,cols);
}
void highpass2(int **input, int **output, int rows, int cols){
double** kernel = createMatrix(3,3,1.0);
kernel[0][0]=-1;
kernel[0][1]=-1;
kernel[0][2]=-1;
kernel[1][0]=-1;
kernel[1][1]=9;
kernel[1][2]=-1;
kernel[2][0]=-1;
kernel[2][1]=-1;
kernel[2][2]=-1;
// printmatrix(kernel,3,3);
convolute(input,output,kernel,rows,cols);
}
void highpass3(int **input, int **output, int rows, int cols){
double** kernel = createMatrix(3,3,1.0);
kernel[0][0]=0;
kernel[0][1]=-1;
kernel[0][2]=0;
kernel[1][0]=-1;
kernel[1][1]=5;
kernel[1][2]=-1;
kernel[2][0]=0;
kernel[2][1]=-1;
kernel[2][2]=0;
// printmatrix(kernel,3,3);
convolute(input,output,kernel,rows,cols);
}
void unsharp_masking(int **input, int **output, int rows, int cols){
int** temp = createMatrix(rows,cols,0);
gaussian_blur(input, temp, rows, cols);
int** highpass = createMatrix(rows,cols,0);
substractvalues(input, temp, highpass, rows, cols);
addvalues(input,highpass,output,rows,cols);
}
void highboost_filter(int **input, int **output, int rows, int cols, float alpha){
int** temp = createMatrix(rows,cols,0);
gaussian_blur(input, temp, rows, cols);
int** highpass = createMatrix(rows,cols,0);
substractvalues(input, temp, highpass, rows, cols);
multiplication(input,alpha-1,temp,rows);
addvalues(temp,highpass,output,rows,cols);
}
void edge_gradient(int **input, int **output, float Threshold, int rows, int cols){
int convolute_x = 0; // This holds the convolution results for an index.
int convolute_y= 0;
int convoluted = 0;
int x, y; // Used for input matrix index
int** kernel_x = createMatrix(2,2,1);
kernel_x[0][0]=-1;kernel_x[1][0]=-1;kernel_x[0][1]=1;kernel_x[1][1]=1;
int** kernel_y = createMatrix(2,2,1);
kernel_y[0][0]=1;kernel_y[1][0]=-1;kernel_y[0][1]=1;kernel_y[1][1]=-1;
// Fill output matrix: rows and columns are i and j respectively
for (int i = 1; i < rows-1; i++)
{
for (int j = 1; j < cols-1; j++)
{
x = i-1;
y = j-1;
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 2; k++)
{
for (int l = 0; l < 2; l++)
{
// Convolute here.
convolute_x += kernel_x[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
x = i-1;
y = j-1;
for (int k = 0; k < 2; k++)
{
for (int l = 0; l < 2; l++)
{
// Convolute here.
convolute_y += kernel_y[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
convoluted = abs(convolute_x) + abs(convolute_y);
if(convoluted>=Threshold){
output[i][j] = 255;
}
else{
output[i][j]= 0;
}
convolute_x = 0;
convolute_y = 0;
convoluted = 0; // Needed before we move on to the next index.
}
}
}
void gaussian_blur(int **input, int **output, int rows, int cols){
double** kernel = createMatrix(3,3,1.0);
kernel[0][0]=1.0/16;
kernel[0][1]=1.0/8;
kernel[0][2]=1.0/16;
kernel[1][0]=1.0/8;
kernel[1][1]=1.0/4;
kernel[1][2]=1.0/8;
kernel[2][0]=1.0/16;
kernel[2][1]=1.0/8;
kernel[2][2]=1.0/16;
// printmatrix(kernel,3,3);
convolute(input,output,kernel,rows,cols);
}
void edge_laplace(int **input, int **output, int rows, int cols){
double** kernel = createMatrix(3,3,1.0);
kernel[0][0]=0;
kernel[0][1]=1;
kernel[0][2]=0;
kernel[1][0]=1;
kernel[1][1]=-4;
kernel[1][2]=1;
kernel[2][0]=0;
kernel[2][1]=1;
kernel[2][2]=0;
// printmatrix(kernel,3,3);
convolute(input,output,kernel,rows,cols);
}
void LoG(int **input, int **output, int rows, int cols){
int** temp = createMatrix(rows,cols,0);
gaussian_blur(input, temp, rows, cols);
edge_laplace(temp ,output,rows,cols);
}
void edge_sobel(int **input, int **output, float Threshold, int rows, int cols){
int convolute_x = 0; // This holds the convolution results for an index.
int convolute_y= 0;
int convoluted = 0;
int x, y; // Used for input matrix index
double** kernel_x = createMatrix(3,3,1.0);
kernel_x[0][0]=-1;
kernel_x[0][1]=0;
kernel_x[0][2]=1;
kernel_x[1][0]=-2;
kernel_x[1][1]=0;
kernel_x[1][2]=2;
kernel_x[2][0]=-1;
kernel_x[2][1]=0;
kernel_x[2][2]=1;
double** kernel_y = createMatrix(3,3,1.0);
kernel_y[0][0]=1;
kernel_y[0][1]=2;
kernel_y[0][2]=1;
kernel_y[1][0]=0;
kernel_y[1][1]=0;
kernel_y[1][2]=0;
kernel_y[2][0]=-1;
kernel_y[2][1]=-2;
kernel_y[2][2]=-1;
// Fill output matrix: rows and columns are i and j respectively
for (int i = 1; i < rows-1; i++)
{
for (int j = 1; j < cols-1; j++)
{
x = i-1;
y = j-1;
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute_x += kernel_x[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
x = i-1;
y = j-1;
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute_y += kernel_y[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
convoluted = abs(convolute_x) + abs(convolute_y);
if(convoluted>=Threshold){
output[i][j] = 255;
}
else{
output[i][j]= 0;
}
convolute_x = 0;
convolute_y = 0;
convoluted = 0; // Needed before we move on to the next index.
}
}
}
void edge_prewitt(int **input, int **output, float Threshold, int rows, int cols){
int convolute_x = 0; // This holds the convolution results for an index.
int convolute_y= 0;
int convoluted = 0;
int x, y; // Used for input matrix index
double** kernel_x = createMatrix(3,3,1.0);
kernel_x[0][0]=-1;
kernel_x[0][1]=0;
kernel_x[0][2]=1;
kernel_x[1][0]=-1;
kernel_x[1][1]=0;
kernel_x[1][2]=1;
kernel_x[2][0]=-1;
kernel_x[2][1]=0;
kernel_x[2][2]=1;
double** kernel_y = createMatrix(3,3,1.0);
kernel_y[0][0]=1;
kernel_y[0][1]=1;
kernel_y[0][2]=1;
kernel_y[1][0]=0;
kernel_y[1][1]=0;
kernel_y[1][2]=0;
kernel_y[2][0]=-1;
kernel_y[2][1]=-1;
kernel_y[2][2]=-1;
// Fill output matrix: rows and columns are i and j respectively
for (int i = 1; i < rows-1; i++)
{
for (int j = 1; j < cols-1; j++)
{
x = i-1;
y = j-1;
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute_x += kernel_x[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
x = i-1;
y = j-1;
for (int k = 0; k < 3; k++)
{
for (int l = 0; l < 3; l++)
{
// Convolute here.
convolute_y += kernel_y[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
convoluted = abs(convolute_x) + abs(convolute_y);
if(convoluted>=Threshold){
output[i][j] = 255;
}
else{
output[i][j]= 0;
}
convolute_x = 0;
convolute_y = 0;
convoluted = 0; // Needed before we move on to the next index.
}
}
}
void edge_roberts(int **input, int **output, float Threshold, int rows, int cols){
int convolute_x = 0; // This holds the convolution results for an index.
int convolute_y= 0;
int convoluted = 0;
int x, y; // Used for input matrix index
int** kernel_x = createMatrix(2,2,1);
kernel_x[0][0]=1;kernel_x[1][0]=0;kernel_x[0][1]=0;kernel_x[1][1]=-1;
int** kernel_y = createMatrix(2,2,1);
kernel_y[0][0]=0;kernel_y[1][0]=-1;kernel_y[0][1]=1;kernel_y[1][1]=0;
// Fill output matrix: rows and columns are i and j respectively
for (int i = 1; i < rows-1; i++)
{
for (int j = 1; j < cols-1; j++)
{
x = i-1;
y = j-1;
// Kernel rows and columns are k and l respectively
for (int k = 0; k < 2; k++)
{
for (int l = 0; l < 2; l++)
{
// Convolute here.
convolute_x += kernel_x[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
x = i-1;
y = j-1;
for (int k = 0; k < 2; k++)
{
for (int l = 0; l < 2; l++)
{
// Convolute here.
convolute_y += kernel_y[k][l] * input[x][y];
y++; // Move right.
}
x++; // Move down.
y = j-1; // Restart column position
}
convoluted = abs(convolute_x) + abs(convolute_y);
if(convoluted>=Threshold){
output[i][j] = 255;
}
else{
output[i][j]= 0;
}
convolute_x = 0;
convolute_y = 0;
convoluted = 0; // Needed before we move on to the next index.
}
}
}
void edge_canny(int **input, int **output, float Gradient_T, float Canny_T, int rows, int cols){
int** temp1 = createMatrix(rows,cols,0);
int** temp2 = createMatrix(rows,cols,0);
gaussian_blur(input, temp1, rows, cols);
edge_roberts(temp1 ,temp2 , Gradient_T, rows, cols);
for(int i =1; i<rows-1; i++){
for(int j =1; j<cols-1; j++){
if(temp2[i][j] >= Canny_T){
output[i][j] = 255;
}
else{
output[i][j]= 0;
}
}
}
}
|
#include <gtest/gtest.h>
#include "utl/bit_window.h"
#include "utl/log.h"
using namespace utl;
// TEST(BitWindow, Default)
// {
// bit_window bw;
// ASSERT_EQ(bw.check_and_update(0), true);
// ASSERT_EQ(bw.check_and_update(0), false);
// ASSERT_EQ(bw.check_and_update(31), true);
// ASSERT_EQ(bw.check_and_update(31), false);
// ASSERT_EQ(bw.check_and_update(1), true);
// ASSERT_EQ(bw.check_and_update(30), true);
// ASSERT_EQ(bw.check_and_update(32), true);
// ASSERT_EQ(bw.check_and_update(0), false);
// ASSERT_EQ(bw.check_and_update(1), false);
// ASSERT_EQ(bw.check_and_update(2), true);
// bit_window bw2;
// ASSERT_EQ(bw2.check_and_update(32), true);
// ASSERT_EQ(bw2.check_and_update(32), false);
// ASSERT_EQ(bw2.check_and_update(0), false);
// ASSERT_EQ(bw2.check_and_update(1), true);
// ASSERT_EQ(bw2.check_and_update(2), true);
// uint32_t a = 0 - uint32_t(-1);
// printf("a %lu 0x%08x \n", a, a);
// }
TEST(BitWindow, Default)
{
bit_window bw;
EXPECT_EQ(bw.latest(), 0);
EXPECT_EQ(bw.check(0), false);
EXPECT_EQ(bw.check(1), true);
EXPECT_EQ(bw.check(32), true);
bw.update(33);
EXPECT_EQ(bw.check(0), false);
EXPECT_EQ(bw.check(1), true);
EXPECT_EQ(bw.check(32), true);
// bit_window bw;
// EXPECT_EQ(bw.latest(), -1);
// EXPECT_EQ(bw.check(0), true);
// EXPECT_EQ(bw.check(32), true);
// EXPECT_EQ(bw.check(512), true);
// EXPECT_EQ(bw.check(-1), false);
// EXPECT_EQ(bw.check(-32), false);
// EXPECT_EQ(bw.check(-33), true);
}
|
/**
widget.h
@author Dmytro Haponov
@version 1.2 3/08/15
*/
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_CreateDBbutt_clicked();
void on_OpenDBbutt_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
|
#include "GameObject.h"
GameObject::GameObject(): x(0), y(0) {
}
GameObject::~GameObject() {
}
void GameObject::update(int keyCode) {
}
void GameObject::render(Graphics& graphics) {
}
|
/*
kamalsam
*/
#include<iostream>
#include<stack>
#include<string.h>
#include<ctype.h>
using namespace std;
int priority(char a)
{
switch(a)
{
case '+': return 1;
case '-': return 2;
case '*': return 3;
case '/': return 4;
case '^': return 5;
}
}
int main()
{
stack<char>a;
int size,i,j;
cin>>size;
char exp[size][400];
char ans[size][400];
for(i=0;i<size;i++)
{
int count=0;
cin>>exp[i];
int len=strlen(exp[i]);
for(j=0;j<len;j++)
{
char ch=exp[i][j];
if(isalpha(ch))
{
ans[i][count++]=ch;
}
else if(ch=='(')
{
a.push(ch);
}
else if(ch==')')
{
while(a.top()!='(')
{
ans[i][count++]=a.top();
a.pop();
}
a.pop();
}
else
{
if(priority(ch)>priority(a.top()))
{
a.push(ch);
}
else
{
while(priority(ch)<priority(a.top()))
{
ans[i][count++]=a.top();
a.pop();
}
}
}
}
while(a.empty()==0)
{
ans[i][count++]=a.top();
}
ans[i][count]='\0';
}
for(i=0;i<size;i++)
{
cout<<ans[i]<<endl;
}
return 0;
}
|
/*
** EPITECH PROJECT, 2019
** OOP_indie_studio_2018
** File description:
** FileNotFoundException
*/
#ifndef FILENOTFOUNDEXCEPTION_HPP_
#define FILENOTFOUNDEXCEPTION_HPP_
#include <string>
#include "Exception.hpp"
class FileNotFoundException : public Exception {
public:
FileNotFoundException(const std::string &message);
~FileNotFoundException();
const char *what() const throw() override;
};
#endif /* !FILENOTFOUNDEXCEPTION_HPP_ */
|
#include "processor.h"
#include "linux_parser.h"
// TODO: Return the aggregate CPU utilization
float Processor::Utilization() {
// idea from https://stackoverflow.com/questions/23367857/accurate-calculation-of-cpu-usage-given-in-percentage-in-linux
long long Idle = LinuxParser::IdleJiffies();
long long Non_Idle = LinuxParser::ActiveJiffies();
long Total = Non_Idle + Idle;
float CPU_Percentage = (Total - Idle)/(float)Total;
return CPU_Percentage;
}
|
#include "web_message_handler.h"
WebMessageHandler::WebMessageHandler()
{
}
WebMessageHandler::~WebMessageHandler()
{
}
void WebMessageHandler::startup(GameController* _game_controller)
{
pGameController = _game_controller;
}
void WebMessageHandler::processWebMessages(Document* document)
{
// Document* document = pGameController->socketServer()->getNextIncomingMessage();
if(0 != document){
// cout << "Got document " << document;
string message = document->FindMember("message")->value.GetString();
// cout << "Got message " << document;
if(message.compare("get_buttons") == 0){
pGameController->sendWebMessage(pGameController->buttonController()->getInfoString());
}else if(message.compare("get_lamps") == 0){
pGameController->sendWebMessage(pGameController->lampController()->getInfoString());
}else if(message.compare("get_coils") == 0){
pGameController->sendWebMessage(pGameController->coilController()->getInfoString());
}else if(message.compare("set_lamp_state") == 0){
string name = document->FindMember("name")->value.GetString();
LampState state = (LampState)document->FindMember("value")->value.GetInt();
pGameController->lampController()->setLampState(name, state);
}else if(message.compare("set_coil_state") == 0){
string name = document->FindMember("name")->value.GetString();
int state = document->FindMember("value")->value.GetInt();
pGameController->coilController()->setCoilState(name, state);
}/*else if(message.compare("get_game_state") == 0){
pGameState->sendToWeb();
}else if(message.compare("set_game_state") == 0){
GameState state = (GameState)document->FindMember("value")->value.GetInt();
setGameState(state);
}*/
}
}
|
#pragma once
#include "PhysicsInclude.h"
class Physics
{
public:
Physics();
~Physics();
//シミュレーション系
//bool PhysicsInit();
void PhysicsRelease();
void PhysicsUpdate(Vector3 Force, Vector3 Torque);
//Integrate系=========================
void Integrate(RigidbodyState &states, unsigned int numRigidbodys, float timestep);
//====================================
//Apply系=============================
void ApplyExternalForce(RigidbodyState &state, const RigidBodyElements &bodyelements, const Vector3 &externalForce, const Vector3 &externalTorque, float timeStep);
//====================================
//Broadphase系======================
bool IntersectAABB(const Vector3 ¢erA, const Vector3 &halfA, const Vector3 ¢erB, const Vector3 &halfB);
/// ブロードフェーズコールバック<br>
/// epxBroadPhase()の引数として渡すと、AABB交差判定前に呼ばれる
/// もどり値のtrueで判定を続行 , falseで判定をキャンセル
typedef bool(*BroadPhaseCallback)(unsigned int rigidBodyIdA, unsigned int rigidBodyIdB, void *userData);
//ブロードフェーズ
void BroadPhase(RigidbodyState* states, Collider* colliders,unsigned int numRigidbodies,
const Pair *oldPairs,const unsigned int numOldPairs,Pair *newPairs,unsigned int &numNewPairs,const unsigned int maxPairs,
DefaultAllocator* allocator, void *userData, BroadPhaseCallback callback
);
//==================================
//衝突検出系==========================
void GetClosestPointTriangle(const Vector3 &point,
const Vector3 &trianglePoint0,const Vector3 &trianglePoint1,const Vector3 &trianglePoint2,
const Vector3 &triangleNormal,Vector3 &closestPoint);
void GetClosestTwoSegments(const Vector3 &segmentPointA0, const Vector3 &segmentPointA1,
const Vector3 &segmentPointB0, const Vector3 &segmentPointB1,
Vector3 &closestPointA, Vector3 &closestPointB);
//
bool ConvexConvexContact_Local(const ConvexMesh &convexA, const Transform3 &transformA,
const ConvexMesh &convexB, const Transform3 &transformB, Vector3 &normal, float &penetrationDepth,
Vector3 &contactPointA, Vector3 &contactPointB);
bool ConvexConvexContact(const ConvexMesh &convexA, const Transform3 &transformA,
const ConvexMesh &convexB, const Transform3 &transformB,
Vector3 &normal, float &penetrationDepth,
Vector3 &contactPointA, Vector3 &contactPointB);
//検出
void DetectCollision(const RigidbodyState *states,const Collider *colliders,unsigned int numRigidBodies,const Pair *pairs,unsigned int numPairs);
//====================================
//拘束ソルバー系========================
void SolveConstraints(RigidbodyState *states, const RigidBodyElements *bodies,
unsigned int numRigidBodies, const Pair *pairs, unsigned int numPairs,
BallJoint *joints,
unsigned int numJoints, unsigned int iteration,
float bias, float slop,
float timeStep,
Allocator *allocator);
//======================================
//オブジェクト作成
int CreateRigidBody(float* vertices, float numvertices,
GLuint* indices, unsigned int numIndices,
Vector3 scale = Vector3(1.0f,1.0f,1.0f), MotionType type = MotionType::TypeActive,
Vector3 pos = Vector3(0), float mass = 1.0f, bool sphere = false);
//現在の物理シミュレーションのシーンを取得
const char *PhysicsGetSceneTitle(int i);
void SetRigidBodyPos(int i, Vector3 pos);
void SetRigidBodyRotate(int i, Quat q);
//オブジェクトの姿勢を変更
void PlusRigidBodyOrientation(int i, Matrix3 rotate);
//剛体情報の取得
int GetNumRigidbodies();
const RigidbodyState GetRigidBodyState(int i);
const RigidBodyElements GetRigidBodyElements(int i);
const Collider GetCollider(int i);
//衝突情報の取得
};
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* LispC FuncExpression
* Represents a function call in the AST.
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#pragma once
#include <vector>
#include "Expression.h"
namespace lispc
{
class FuncExpression : public Expression
{
public:
FuncExpression(Func func);
virtual ~FuncExpression() override;
virtual bool is_atom() const override;
virtual bool is_func() const override;
virtual std::string get_type() const override;
Expression* invoke(std::vector<Expression*>& args);
private:
Func func;
};
}
|
//
// 7576.cpp
// baekjoon
//
// Created by 최희연 on 2021/07/13.
//
#include <iostream>
#include <queue>
using namespace std;
int dx[4]={0, 0, 1, -1};
int dy[4]={1, -1, 0, 0};
int m, n, result = 0;
int tomato[1001][1001];
queue<pair<int, int>> q;
bool isIn(int x, int y){
if(x>=0&&x<n&&y>=0&&y<m)
return true;
else
return false;
}
void bfs(){
while(!q.empty()){
int oriY=q.front().first;
int oriX=q.front().second;
q.pop();
for(int i=0;i<4;i++){
int newX = oriX+dx[i];
int newY = oriY+dy[i];
if(isIn(newY, newX)==1 && tomato[newY][newX]==0){
tomato[newY][newX]=tomato[oriY][oriX]+1;
q.push(make_pair(newY, newX));
}
}
}
}
int main(){
scanf("%d %d", &m, &n);
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%d", &tomato[i][j]);
if(tomato[i][j]==1)
q.push(make_pair(i, j));
}
}
bfs();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(tomato[i][j]==0){
printf("-1\n");
return 0;
}
if(result<tomato[i][j]){
result = tomato[i][j];
}
}
}
printf("%d\n", result-1);
return 0;
}
|
/*
* TDrawingView.h
*
* Created on: Apr 11, 2017
* Author: Alex
*/
#ifndef TDRAWINGVIEW_H_
#define TDRAWINGVIEW_H_
#include "TView.h"
#include <cairo.h>
#include "TGraphics.h"
class TDrawingView: public TView {
public:
TDrawingView();
virtual ~TDrawingView();
public:
TCairoGraphics graphics;
Evas_Object *image;
Evas_Coord width;
Evas_Coord height;
//cairo_t *cairo;
//cairo_surface_t *surface;
//unsigned char *pixels;
virtual void OnResize(int width, int height);
virtual void CairoDrawing();
virtual void OnClick(int x, int y) {};
virtual void OnLineStart(int x, int y) {};
virtual void OnLineMove(int x1, int y1, int x2, int y2) {};
virtual void OnLineEnd(int x, int y) {};
virtual void OnLineAbort(int x, int y) {};
virtual void OnMomentumStart(int x, int y) {};
virtual void OnMomentumMove(int x1, int y1) {};
virtual void OnMomentumEnd(int x, int y) {};
private:
protected:
virtual void CreateContent();
int myWidth, myHeight;
};
#endif /* TDRAWINGVIEW_H_ */
|
#include "Snowflakes.h"
#include <cstdlib>
#include <ctime>
SnowflakeGenerator::SnowflakeGenerator(gfx::Canvas* canvasToSet, int nSnowflakes) :
Primitive (canvasToSet, 0, Color(255,255,255)),
_snowflakes(nSnowflakes)
{
srand(time(0));
{
int x, y;
for (int i = 0; i < nSnowflakes; ++i) {
x = (rand() % (int)(canvasToSet->width() * 3)) - canvasToSet->width();
y = (rand() % (int)(canvasToSet->height() * 1.5)) - canvasToSet->height();
_snowflakes[i] = new Snowflake(canvasToSet, 1.f, (rand()%100)/100.f, rand() % 1000);
_snowflakes[i]->location(x, y);
}
}
}
void SnowflakeGenerator::draw() {
int x;
for (int i = 0; i< _snowflakes.size(); ++i) {
_snowflakes[i]->draw();
if (_snowflakes[i]->location().y() > _canvas->height()) {
x = (rand() % (int)(_canvas->width() * 3)) - _canvas->width();
_snowflakes[i]->location(x, -8);
}
}
}
void SnowflakeGenerator::move(float dt, float x, float y, unsigned long long timestamp) {
for (int i = 0; i< _snowflakes.size(); ++i) {
_snowflakes[i]->move(dt, x, y, timestamp);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.