text
stringlengths
8
6.88M
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; LL a[20],b[20]; LL gcd(LL a,LL b) { while (b) { LL t = a;a = b;b = t%b; } return a; } int main() { int t,n,ca = 0; scanf("%d",&t); while (t--) { scanf("%d",&n); for (int i = 1;i <= n; i++) scanf("%I64d",&a[i]); for (int i = 1;i <= n; i++) scanf("%I64d",&b[i]); LL p = b[n],q = a[n]; for (int i = n-1;i >= 1; i--) { LL p1 = p,q1 = q; p = q1*b[i];q = a[i]*q1 + p1; LL d = gcd(p,q); p /= d;q /= d; } LL d = gcd(p,q); p /= d;q /= d; printf("Case #%d: %I64d %I64d\n",++ca,p,q); } return 0; }
// (C) 1992-2016 Intel Corporation. // Intel, the Intel logo, Intel, MegaCore, NIOS II, Quartus and TalkBack words // and logos are trademarks of Intel Corporation or its subsidiaries in the U.S. // and/or other countries. Other marks and brands may be claimed as the property // of others. See Trademarks on intel.com for full list of Intel trademarks or // the Trademarks & Brands Names Database (if Intel) or See www.Intel.com/legal (if Altera) // Your use of Intel Corporation's design tools, logic functions and other // software and tools, and its AMPP partner logic functions, and any output // files any of the foregoing (including device programming or simulation // files), and any associated documentation or information are expressly subject // to the terms and conditions of the Altera Program License Subscription // Agreement, Intel MegaCore Function License Agreement, or other applicable // license agreement, including, without limitation, that your use is for the // sole purpose of programming logic devices manufactured by Intel and sold by // Intel or its authorized distributors. Please refer to the applicable // agreement for further details. /******** * Measure PCIe bandwidth: * * Fastest: Max speed of any one Enqueue call * Slowest: Min speed of any one Enqueue call * Average: Sum of transfer times from Queued-End of each request divided * by total bytes * Total: Queue time of first Enqueue call to End time of last Enqueue call * divided by total bytes * * Final "Thoughput" value is average of max read and max write speeds. ********/ #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <time.h> #include "aclutil.h" #include "hostspeed_ocl.h" // WARNING: host runs out of events if MAXNUMBYTES is much greater than // MINNUMBYTES!!! #define DEFAULT_MAXNUMBYTES (2097152*4) #define DEFAULT_MINNUMBYTES (32768) bool check_results(unsigned int * buf, unsigned int * output, int n) { bool result=true; int prints=0; for (int j=0; j<n; j++) if (buf[j]!=output[j]) { if (prints++ < 512) printf("Error! Mismatch at element %d: %8x != %8x, xor = %08x\n", j,buf[j],output[j], buf[j]^output[j]); result=false; } return result; } int hostspeed (cl_platform_id platform, cl_device_id device, cl_context context, cl_command_queue queue) { srand ( time(NULL) ); size_t maxbytes = DEFAULT_MAXNUMBYTES; size_t maxints = maxbytes/sizeof(int); size_t iterations=1; for (size_t i=maxbytes/DEFAULT_MINNUMBYTES; i>>1 ; i=i>>1) iterations++; struct speed *readspeed = new struct speed[iterations]; struct speed *writespeed = new struct speed[iterations]; bool result=true; unsigned int *buf = (unsigned int*) acl_aligned_malloc (maxints * sizeof(unsigned int)); unsigned int *output = (unsigned int*) acl_aligned_malloc (maxints * sizeof(unsigned int)); // Create sequence: 0 rand1 ~2 rand2 4 ... for (size_t j=0; j<maxints; j++) if (j%2==0) buf[j]=(j&2) ? ~j : j; else buf[j]=rand()*rand(); hostspeed_ocl_device_init(platform, device, context, queue, maxbytes); size_t block_bytes=DEFAULT_MINNUMBYTES; // Warm up ocl_writespeed((char*)buf,block_bytes,maxbytes); ocl_readspeed((char*)output,block_bytes,maxbytes); for (size_t i=0; i<iterations; i++, block_bytes*=2) { printf("Transferring %d KBs in %d %d KB blocks ...\n",maxbytes/1024,maxbytes/block_bytes,block_bytes/1024); writespeed[i] = ocl_writespeed((char*)buf,block_bytes,maxbytes); readspeed[i] = ocl_readspeed((char*)output,block_bytes,maxbytes); result &= check_results(buf,output,maxints); } printf("\nPCIe Gen2.0 peak speed: 500MB/s/lane\n"); printf("\nBlock_Size Avg Max Min End-End (MB/s)\n"); float write_topspeed = 0; block_bytes=DEFAULT_MINNUMBYTES; printf("Writing %d KBs with block size (in bytes) below:\n",maxbytes/1024); for (size_t i=0; i<iterations; i++, block_bytes*=2) { printf("%8d %.2f %.2f %.2f %.2f\n", block_bytes, writespeed[i].average, writespeed[i].fastest, writespeed[i].slowest, writespeed[i].total); if (writespeed[i].fastest > write_topspeed) write_topspeed = writespeed[i].fastest; if (writespeed[i].total > write_topspeed) write_topspeed = writespeed[i].total; } float read_topspeed = 0; block_bytes=DEFAULT_MINNUMBYTES; printf("Reading %d KBs with block size (in bytes) below:\n",maxbytes/1024); for (size_t i=0; i<iterations; i++, block_bytes*=2) { printf("%8d %.2f %.2f %.2f %.2f\n", block_bytes, readspeed[i].average, readspeed[i].fastest, readspeed[i].slowest, readspeed[i].total); if (readspeed[i].fastest > read_topspeed) read_topspeed = readspeed[i].fastest; if (readspeed[i].total > read_topspeed) read_topspeed = readspeed[i].total; } printf("\nHost write top speed = %.2f MB/s\n",write_topspeed); printf("Host read top speed = %.2f MB/s\n",read_topspeed); //printf("Throughput = %.2f MB/s\n",(read_topspeed+write_topspeed)/2); printf("\n"); printf("\nHOST-TO-MEMORY BANDWIDTH = %.0f MB/s\n",(read_topspeed+write_topspeed)/2); printf("\n"); if (!result) printf("\nFAILURE!\n"); acl_aligned_free (buf); acl_aligned_free (output); freeDeviceMemory(); return (result) ? 0 : -1; }
#include<iostream> #include<algorithm> #include<vector> #include<map> using namespace std; class MinStack { public: //基本思想:辅助栈 MinStack() { minElem.push_back(INT_MAX); } void push(int x) { st.push_back(x); minElem.push_back(min(minElem[minElem.size() - 1], x)); } void pop() { st.pop_back(); minElem.pop_back(); } int top() { return st[st.size() - 1]; } int getMin() { return minElem[minElem.size() - 1]; } private: vector<int> st; vector<int> minElem; }; class MinStack1 { public: //基本思想:栈+HashMap MinStack1() { } void push(int x) { ++minElem[x]; st.push_back(x); } void pop() { --minElem[top()]; if (minElem[top()] <= 0) minElem.erase(top()); st.pop_back(); } int top() { return st[st.size() - 1]; } int getMin() { return (*minElem.begin()).first; } private: map<int,int> minElem; vector<int> st; }; int main() { MinStack* minStack = new MinStack(); minStack->push(-2); minStack->push(0); minStack->push(-3); cout << minStack->getMin() << endl; minStack->pop(); cout << minStack->top() << endl; cout << minStack->getMin() << endl; return 0; }
#include <ionir/passes/pass.h> namespace ionir { StringLiteral::StringLiteral(std::string value) : Value(ValueKind::String, TypeFactory::typeString()), value(std::move(value)) { // } void StringLiteral::accept(Pass &visitor) { visitor.visitStringLiteral(this->dynamicCast<StringLiteral>()); } }
/** * Uses the "character cast" to retreive * the sprites name */ #pragma once #include "ref_count.h" #include <string> #include <vector> class CartFile; class SpriteProperty; class StockSprite { public: bool Load(CartFile& cart); typedef struct { WORD palette_id; WORD animation_id; WORD sprite_id; std::string name; } SceneCast; bool GetName(std::string& in_name, WORD animation_id, WORD sprite_id); bool GetName(std::string& in_name, Ref<SpriteProperty> prop); std::vector<SceneCast> characters; };
#include <iostream> #include <vector> #include <map> using namespace std; class Perception{ bool location; bool isDirty; public: Perception(bool _location = true, bool _isDirty = true){ this->location = _location; this->isDirty = _isDirty; } bool getLocation(){ return location; } void setLocation(bool value){ location = value; } bool getIsDirty(){ return isDirty; } void setIsDirty(bool value){ isDirty = value; } }; class Enviromment{ bool isDirtyA; bool isDirtyB; bool agentLocation; public: Enviromment(bool _isDirtyA = true, bool _isDirtyB = true, bool _agentLocation = true) { this->isDirtyA = _isDirtyA; this->isDirtyB = _isDirtyB; this->agentLocation = _agentLocation; } bool getIsDirtyA(){ return isDirtyA; } void setisDirtyA(bool value){ isDirtyA = value; } bool getIsDirtyB(){ return isDirtyB; } void setisDirtyB(bool value){ isDirtyB = value; } bool getAgentLocation(){ return agentLocation; } void setAgentLocation(bool value){ agentLocation = value; } Perception getPerception(){ return Perception(agentLocation, agentLocation ? isDirtyA : isDirtyB); } void updateEnvironment(Perception p){ p.getLocation() ? isDirtyA = p.getIsDirty() : isDirtyB = p.getIsDirty(); this->agentLocation = p.getLocation(); } }; class Action{ string name; public: Action(string _name = ""){ this->name = _name; } string getName(){ return name; } }; class Agent{ protected: Perception perception; vector<Action> actions; public: Agent() {} void setPerception(Perception perception){ this->perception = perception; } Perception getPerception(){ return this->perception; } }; class TableDriveAgent : Agent{ vector<Perception> perceptions; map<Perception*,Action*> table; public: TableDriveAgent(){} void setTable(){ this->table.insert(make_pair(new Perception(true,false), new Action("Right"))); this->table.insert(make_pair(new Perception(true,true), new Action("Aspire"))); this->table.insert(make_pair(new Perception(false,false), new Action("Left"))); this->table.insert(make_pair(new Perception(false,true), new Action("Aspire"))); } Action SelectAction(Perception _perception){ perceptions.push_back(_perception); map<Perception*,Action*>::iterator it; for (it = table.begin(); it != table.end(); it++) { if((it->first->getLocation()== _perception.getLocation()) && (it->first->getIsDirty() == _perception.getIsDirty())){ return *(it->second); } } return Action("Erro"); } }; class SimpleReflexAgent : Agent{ private: public: Action SelectAction(Perception _perception){ this->perception = _perception; if(perception.getIsDirty()){ this->actions.push_back(Action("Aspire")); this->perception.setIsDirty(false); return Action("Aspire"); } else if(perception.getLocation()){ this->actions.push_back(Action("Right")); this->perception.setLocation(false); return Action("Right"); } else if(!perception.getLocation()){ this->actions.push_back(Action("Left")); this->perception.setLocation(true); return Action("Left"); } return Action("ERRO!"); } void setPerception(Perception perception){ this->perception = perception; } Perception getPerception(){ return this->perception; } }; void mainTable(TableDriveAgent& agent){ Action action; Enviromment enviromment(false, true, true); agent.setTable(); cout << "\n------------------------------\nGetting Started:\n"; cout << "Loc: "; enviromment.getAgentLocation() ? cout << "A" : cout << "B"; cout<< " isDirtyA: " << enviromment.getIsDirtyA() << " isDirtyB: " << enviromment.getIsDirtyB() << endl; cout << "------------------------------\n\n"; int x; cout << "Number of steps: "; cin >> x; for(int i = 0; i < x; i++){ cout << "Loc: "; enviromment.getAgentLocation() ? cout << "A" : cout << "B"; cout << " isDirtyA: "; enviromment.getIsDirtyA() ? cout << "True" : cout << "False"; cout << " | isDirtyB: "; enviromment.getIsDirtyB() ? cout << "True" : cout << "False"; bool isDirty; if(enviromment.getAgentLocation()){ isDirty = enviromment.getIsDirtyA(); }else{ isDirty = enviromment.getIsDirtyB(); } action = agent.SelectAction(Perception(enviromment.getAgentLocation(), isDirty)); cout << "\nAction: " << action.getName() << endl << endl; if(action.getName() == "Aspire"){ enviromment.getAgentLocation() ? enviromment.setisDirtyA(false) : enviromment.setisDirtyB(false); } if(action.getName() == "Left"){ enviromment.setAgentLocation(1); } if(action.getName() == "Right"){ enviromment.setAgentLocation(0); } } } void mainReflex(SimpleReflexAgent& _reflex){ Enviromment enviromment(true,true,true); SimpleReflexAgent reflex = _reflex; cout << "\n------------------------------\nGetting Started:\n"; cout << "Loc: "; enviromment.getAgentLocation() ? cout << "A" : cout << "B"; cout<< " isDirtyA: " << enviromment.getIsDirtyA() << " isDirtyB: " << enviromment.getIsDirtyB() << endl; cout << "------------------------------\n\n"; int x; cout << "Number of steps: "; cin >> x; for(int i = 0; i < x; i++){ reflex.setPerception(enviromment.getPerception()); cout << "Loc: "; cout << (enviromment.getAgentLocation() ? "A" : "B"); cout << " | Is Dirty: "; cout << (enviromment.getAgentLocation() ? (enviromment.getIsDirtyA() ? "Y" : "N") : (enviromment.getIsDirtyB() ? "S" : "N")) << endl; cout << "Action: "; cout << reflex.SelectAction(reflex.getPerception()).getName() << endl << endl; enviromment.updateEnvironment(reflex.getPerception()); } } int main(){ TableDriveAgent agent; SimpleReflexAgent reflex; //mainTable(agent); int x; cout << "0 to Agent Table, 1 to Agent Reflex: "; cin >> x; if(x == 0){ mainTable(agent); }else if (x == 1) { mainReflex(reflex); }else{ cout << "\n\n ERROR \n\n"; } return 0; }
#pragma once #include "proto/data_base.pb.h" #include "proto/data_rank.pb.h" #include "proto/data_battle.pb.h" #include "proto/data_tower.pb.h" #include "proto/data_mansion.pb.h" #include "proto/data_child.pb.h" #include "proto/data_league.pb.h" #include "proto/data_activity.pb.h" #include "proto/data_route.pb.h" #include "proto/config_mansion.pb.h" #include "proto/config_quest.pb.h" #include "utils/assert.hpp" #include <iostream> using namespace std; namespace pd = proto::data; namespace pc = proto::config; namespace nora { const pc::mansion_craft_drop& pick_craft_drop(const pc::mansion_craft_drop_array& drops, pd::actor::craft_type craft); inline bool operator>(const pd::rank_entity& a, const pd::rank_entity& b) { ASSERT(a.values_size() >= 0); ASSERT(a.values_size() == b.values_size()); for (auto i = 0; i < a.values_size(); ++i) { if (a.values(i) == b.values(i)) { continue; } if (a.values(i) > b.values(i)) { return true; } else { return false; } } return false; } inline bool operator==(const pd::rank_entity& a, const pd::rank_entity& b) { ASSERT(a.values_size() >= 0); for (auto i = 0; i < a.values_size(); ++i) { if (a.values(i) != b.values(i)) { return false; } } return true; } inline bool operator>(const pd::city_battle_damage_record& a, const pd::city_battle_damage_record& b) { return a.damage() > b.damage(); } inline bool operator==(const pd::city_battle_damage_record& a, const pd::city_battle_damage_record& b) { return a.damage() == b.damage(); } inline bool operator==(const pd::grid& a, const pd::grid& b) { if(a.row() == b.row() && a.col() == b.col()) { return true; } else { return false; } } inline bool operator==(const pd::voice& a, const pd::voice& b) { return a.id() == b.id(); } inline bool operator!=(const pd::voice& a, const pd::voice& b) { return a.id() != b.id(); } inline bool pos_in_area(const pd::position& pos, const pc::mansion_area& area) { return pos.x() >= area.left_down().x() && pos.y() >= area.left_down().y() && pos.x() <= area.up_right().x() && pos.y() <= area.up_right().y(); } inline pd::position operator+(const pd::position& a, const pd::position& b) { pd::position ret; ret.set_x(a.x() + b.x()); ret.set_y(a.y() + b.y()); return ret; } inline pd::position operator*(const pd::position& a, double scale) { pd::position ret; ret.set_x(a.x() * scale); ret.set_y(a.y() * scale); return ret; } inline pc::mansion_area operator+(const pc::mansion_area& a, const pd::position& b) { pc::mansion_area ret; ret.mutable_left_down()->set_x(a.left_down().x() + b.x()); ret.mutable_left_down()->set_y(a.left_down().y() + b.y()); ret.mutable_up_right()->set_x(a.up_right().x() + b.x()); ret.mutable_up_right()->set_y(a.up_right().y() + b.y()); return ret; } inline pc::mansion_area operator*(const pc::mansion_area& a, double scale) { pc::mansion_area ret; ret.mutable_left_down()->set_x(a.left_down().x()); ret.mutable_left_down()->set_y(a.left_down().y()); ret.mutable_up_right()->set_x(a.up_right().x() * scale); ret.mutable_up_right()->set_y(a.up_right().y() * scale); return ret; } inline bool operator!=(const pd::position& a, const pd::position& b){ return a.x() != b.x() || a.y() != b.y(); } inline bool areas_overlapped(const pc::mansion_area& a, const pc::mansion_area& b) { if (a.left_down().x() > b.up_right().x()) { return false; } if (a.up_right().x() < b.left_down().x()) { return false; } if (a.left_down().y() > b.up_right().y()) { return false; } if (a.up_right().y() < b.up_right().y()) { return false; } return true; } inline bool gid_array_has_duplicate(const pd::gid_array& gids) { set<uint64_t> exists; for (auto i : gids.gids()) { if (exists.count(i) > 0) { return true; } exists.insert(i); } return false; } inline bool operator<(const pd::tower_record& a, const pd::tower_record& b) { if (a.role_level() < b.role_level()) { return true; } else if (a.role_level() == b.role_level()) { if (a.zhanli() < b.zhanli()) { return true; } else { return false; } } else { return false; } } inline bool operator>(const pd::tower_record& a, const pd::tower_record& b) { if (a.role_level() > b.role_level()) { return true; } else if (a.role_level() == b.role_level()) { if (a.zhanli() > b.zhanli()) { return true; } else { return false; } } else { return false; } } inline bool operator>(pd::child_phase a, pd::child_phase b) { return static_cast<int>(a) > static_cast<int>(b); } inline bool operator<(pd::child_phase a, pd::child_phase b) { return static_cast<int>(a) < static_cast<int>(b); } void merge_mansion_furniture(pd::mansion_all_furniture& a, const pd::mansion_all_furniture& b); inline bool operator!=(const pd::activity_mgr_prize_wheel& a, const pd::activity_mgr_prize_wheel& b) { return a.start_day() != b.start_day() || a.duration() != b.duration() || a.pttid() != b.pttid(); } inline bool operator!=(const pd::ipport& a, const pd::ipport& b) { return a.ip() != b.ip() || a.port() != b.port(); } inline bool operator!=(const pd::route_info& a, const pd::route_info& b) { return a.scened_ipport() != b.scened_ipport() || a.gmd_ipport() != b.gmd_ipport(); } inline bool operator!=(const pd::route_client& a, const pd::route_client& b) { return a.type() != b.type() || a.id() != b.id() || a.route_info() != b.route_info(); } inline bool operator!=(const pd::route_table& a, const pd::route_table& b) { if (a.clients_size() != b.clients_size()) { return true; } for (auto i = 0; i < a.clients_size(); ++i) { if (a.clients(i) != b.clients(i)) { return true; } } return false; } }
//https://www.reddit.com/r/dailyprogrammer/comments/4so25w/20160713_challenge_275_intermediate_splurthian/ #include <iostream> // std::cout #include <string> // std::string #include <vector> #include <iterator> #include <algorithm> #include <fstream> void isValidName(std::string ele, std::string sym) { signed short index = ele.find(sym[0]); if (index != std::string::npos) { //if the first letter of the given symbol name is present if (index < ele.size() && ele.substr(index + 1, ele.size()).find(sym[1]) != std::string::npos)//if the second letter of the symbol name is present in the remaining substring { std::cout << "Valid." << std::endl; } else { std::cout << "not a valid symbol name" << std::endl; } } else { std::cout << "not a valid symbol name" << std::endl; } } void findValidName(std::string ele) { std::string symbol; std::vector<std::string> combinations; //using a vector to store our string combinations for (unsigned int i = 0; i < ele.size()-1; i++) { for (unsigned int j = i + 1; j < ele.size(); j++) { symbol = ele[i]; symbol += ele[j]; //combine the symbols into one string combinations.push_back(symbol); //throw it on the vector } } std::sort(combinations.begin(), combinations.end()); //alphabetize combinations.erase(std::unique(combinations.begin(), combinations.end()), combinations.end()); //remove duplicates std::cout << "All combinations" << std::endl; for (std::vector<std::string>::iterator iter = combinations.begin(); iter != combinations.end(); ++iter) { std::cout << *iter << std::endl; } std::cout << "Alphabetically First: " + combinations.front() << std::endl; std::cout << "Number of combinations: "; std::cout << combinations.size() << std::endl; } void findAllPreferredNames(std::vector<std::string> elements) { std::vector<std::string> symbols; std::string symbol; for (std::vector<std::string>::iterator iter = elements.begin(); iter != elements.end(); ++iter) { std::cout << *iter; for (unsigned int i = 0; i < iter->size() - 1; i++) { for (unsigned int j = i + 1; j < iter->size(); j++) { symbol = (*iter)[i]; symbol += (*iter)[j]; //combine the symbols into one string if (!(std::find(symbols.begin(), symbols.end(), symbol) != symbols.end()))//check if it is already in the list { symbols.push_back(symbol); //throw it on the vector symbol[0] = toupper(symbol[0]); std::cout << ": "; std::cout << symbol<< std::endl; goto loopbreak; } else if (i == (*iter).size()-2 && j == (*iter).size() -1){ symbol = ": No Valid Symbol"; symbols.push_back(symbol); std::cout << symbol << std::endl; }// Do nothing if it finds it in the list already } } loopbreak:; } std::cout << symbols.size() << std::endl; } int main() { std::string elementName, symbolName; //std::cin >> elementName; //std::cin >> symbolName; std::vector<std::string> ElementArray; std::string line; std::ifstream ElementNames("ElementNames.txt"); while (std::getline(ElementNames, line)) { ElementArray.push_back(line); } findAllPreferredNames(ElementArray); //isValidName(elementName, symbolName); //findValidName(elementName); return 0; }
#pragma once namespace Game { struct ShaderData { ShaderData() { } GLuint programId; GLuint matrixId; GLuint modelSpaceId; GLuint vertexUVID; GLuint viewMatrixID; GLuint modelMatrixID; GLuint normalModelSpaceId; }; }
class Solution { public: int compareVersion(string version1, string version2) { int a, b, i, j; i = j = 0; while (i<version1.length() || j<version2.length()) { a = b = 0; while(i<version1.length() && version1[i] != '.') a = 10*a + version1[i++]-'0'; if (version1[i] == '.') i++; while(j<version2.length() && version2[j] != '.') b = 10*b + version2[j++]-'0'; if (version2[j] == '.') j++; if (a > b) return 1; if (a < b) return -1; } return 0; } };
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/app18.unoproj.g.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.UX.PropertyAccessor.h> namespace g{namespace Uno{namespace UX{struct PropertyObject;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{struct app18_accessor_List_Title;} namespace g{ // internal sealed class app18_accessor_List_Title :21 // { ::g::Uno::UX::PropertyAccessor_type* app18_accessor_List_Title_typeof(); void app18_accessor_List_Title__ctor_1_fn(app18_accessor_List_Title* __this); void app18_accessor_List_Title__GetAsObject_fn(app18_accessor_List_Title* __this, ::g::Uno::UX::PropertyObject* obj, uObject** __retval); void app18_accessor_List_Title__get_Name_fn(app18_accessor_List_Title* __this, ::g::Uno::UX::Selector* __retval); void app18_accessor_List_Title__New1_fn(app18_accessor_List_Title** __retval); void app18_accessor_List_Title__get_PropertyType_fn(app18_accessor_List_Title* __this, uType** __retval); void app18_accessor_List_Title__SetAsObject_fn(app18_accessor_List_Title* __this, ::g::Uno::UX::PropertyObject* obj, uObject* v, uObject* origin); void app18_accessor_List_Title__get_SupportsOriginSetter_fn(app18_accessor_List_Title* __this, bool* __retval); struct app18_accessor_List_Title : ::g::Uno::UX::PropertyAccessor { static ::g::Uno::UX::Selector _name_; static ::g::Uno::UX::Selector& _name() { return _name_; } static uSStrong< ::g::Uno::UX::PropertyAccessor*> Singleton_; static uSStrong< ::g::Uno::UX::PropertyAccessor*>& Singleton() { return Singleton_; } void ctor_1(); static app18_accessor_List_Title* New1(); }; // } } // ::g
#include <iostream> #include <opencv2/core/mat.hpp> #include <opencv/cxmisc.h> cv::Mat calcIntegralImage_naive(cv::Mat &image){ cv::Mat IntegralImage = cv::Mat::zeros(image.rows, image.cols, CV_64FC1); for(int h = 0; h < image.rows; h++){ for(int w = 0; w < image.cols; w++){ for (int j = 0; j<=h; j++){ for (int i = 0; i<=w; i++){ IntegralImage.at<double>(h, w) += image.at<double>(j, i); } } } } return IntegralImage; } cv::Mat calcIntegralImage_useprev(cv::Mat &image){ cv::Mat IntegralImage = cv::Mat::zeros(image.rows, image.cols,CV_64FC1); int integral_stride=IntegralImage.cols; int src_stride=image.cols; //1 channel double *integral = IntegralImage.ptr<double>(0); double *src = image.ptr<double>(0); for(int h = 0; h < image.rows; h++){ int nh = h - 1; double row_sum=0; for(int w = 0; w < image.cols; w++){ int nw = w - 1; if (nh >= 0){ integral[w] += integral[w - integral_stride]; } row_sum+= src[w]; integral[w] += row_sum; } integral += integral_stride; src += src_stride; } return IntegralImage; } cv::Mat calcIntegralImage_padding(cv::Mat &image){ cv::Mat IntegralImage = cv::Mat::zeros(image.rows+1, image.cols+1,CV_64FC1); double *integral = IntegralImage.ptr<double>(1)+1; //Start from (1,1) double *src = image.ptr<double>(0); int integral_stride=IntegralImage.cols; int src_stride=image.cols; for(int h = 0; h < image.rows; h++){ int row_sum = 0; for(int w = 0; w < image.cols; w++){ row_sum += src[w]; integral[w] = row_sum + integral[w - integral_stride]; } src += src_stride; integral += integral_stride; } IntegralImage = IntegralImage(cv::Rect(1,1,image.cols,image.rows)); return IntegralImage; } int main() { cv::TickMeter meter; cv::Mat sample = cv::Mat::eye(200, 200, CV_64FC1); meter.start(); calcIntegralImage_naive(sample); meter.stop(); std::cout << "calcIntegralImage_naive (200*200): "<< meter << std::endl; meter.reset(); meter.start(); calcIntegralImage_useprev(sample); meter.stop(); std::cout << "calcIntegralImage_useprev (200*200): "<< meter << std::endl; meter.reset(); meter.start(); calcIntegralImage_padding(sample); meter.stop(); std::cout << "calcIntegralImage_padding (200*200): "<< meter << std::endl; sample = cv::Mat::eye(5000, 5000, CV_64FC1); meter.reset(); meter.start(); calcIntegralImage_useprev(sample); meter.stop(); std::cout << "calcIntegralImage_useprev (5000*5000): "<< meter << std::endl; meter.reset(); meter.start(); calcIntegralImage_padding(sample); meter.stop(); std::cout << "calcIntegralImage_padding (5000*5000): "<< meter << std::endl; return 0; }
#include "Mesh.h" Mesh::Mesh() { } Mesh::~Mesh() { } void Mesh::initaliseQuad() { //assert(VAO == 0); //checks that the mesh is not initalized already //generate buffers glGenBuffers(1, &VBO); glGenBuffers(1, &IBO); glGenVertexArrays(1, &VAO); //shoudlnt this go befor the vbo since the vao contains it //bind vertex array (mesh wrapper) glBindVertexArray(VAO); // is this what makes it contains the other two? //bind vertex buffer glBindBuffer(GL_ARRAY_BUFFER, VBO); //this creats a unit quad the sides have the length of one //define verts Vertex verties[4]; verties[0].positon = { -0.5f, 0.0f, 0.5f, 1.0f }; //xyzt verties[1].positon = { 0.5f, 0.0f, 0.5f, 1.0f }; verties[2].positon = { -0.5f, 0.0f, -0.5f, 1.0f }; //verties[4].positon = { 0.5f, 0.0f, 0.5f, 1.0f }; verties[3].positon = { 0.5f, 0.0f, -0.5f, 1.0f }; //verties[5].positon = { -0.5f, 0.0f, -0.5f, 1.0f }; verties[0].normal = {0,1,0,0}; verties[1].normal = {0,1,0,0}; verties[2].normal = {0,1,0,0}; verties[3].normal = {0,1,0,0}; //check if this is right verties[0].UV = {0,1}; verties[1].UV = {1,1}; verties[2].UV = {0,0}; //verties[4].UV = {0,0}; verties[3].UV = {1,0}; //verties[5].UV = {0,0}; verties[0].tangent = {1,0,0,1}; verties[1].tangent = {1,0,0,1}; verties[2].tangent = {1,0,0,1}; verties[3].tangent = {1,0,0,1}; //triCount = 2; //--------------------------------------------- int index_buffer[]{ 0,1,2,1,3,2 }; // abcbdc triCount = 6; glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(Vertex), &verties[0], GL_STATIC_DRAW); // needs to be fixed-- if the other vectors are in the struct it doesnt work glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, triCount * sizeof(int), &index_buffer[0], GL_STATIC_DRAW); //fill vertex buffer //glBufferData(GL_ARRAY_BUFFER, 6 * sizeof(Vertex), &verties[0], GL_STATIC_DRAW); //enable first element as position glEnableVertexAttribArray(0); //enables the generic vertex attribute array specified by index glVertexAttribPointer(0, 4 , GL_FLOAT, GL_FALSE, sizeof(Vertex), 0); //normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)sizeof(glm::vec4)); // needs to have tyhe correct stride //UV enable glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(8 * sizeof(float))); //kill this guy ------^ //tangent glEnableVertexAttribArray(3); glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)(10 * sizeof(float))); //unbind buffers glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); //binds the buffer to 0 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); /*auto window = glfwGetCurrentContext(); if(glfwGetKey(window,GLFW_KEY_X)) { for(int i = 0; i < 0 ; i++) { verties[i].positon; } }*/ //quad has 2 triangles } void Mesh::draw() { glBindVertexArray(VAO); //glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO); //checks to see if your using indices or just verticies if(IBO != 0) // indices { glDrawElements(GL_TRIANGLES, triCount, GL_UNSIGNED_INT, 0); } else // verticies { glDrawArrays(GL_TRIANGLES, 0, 3 * triCount); } ////bind //for(auto) //{ // if(m_) //} glBindVertexArray(0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } //void Mesh::draw(bool usePatches) //{ // //} //bool Mesh::load(const char*, bool loadTextures, bool flipTextureV ) //{ // return false; //}
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@tiliae.eu * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef ICONTROLLER_H_ #define ICONTROLLER_H_ #include "Pointer.h" #include "IModelAware.h" #include "ITreeController.h" class IWidget; /** * Interfejs kontrolerów. Ten interfejs dziedziczy z Base::ITreeController, czyli wszystkie * kontrolery w bajce mają możliwość zagnieżdżania jednego w drugim. Prócz tego w tym podstawowym * interfejsie są metody do pobierania modelu i widgetu. * * IController i Base::ITreeController są oddzielone od siebie, żeby zachować prostotę interfejsu * IController i nie zaciemniac jej metodami drzewiastymi. * \ingroup Kontroler */ struct T_IController : public Controller::ITreeController { virtual ~T_IController () {} virtual Ptr <View::IWidget> const &getWidget () = 0; virtual void setWidget (Ptr <View::IWidget> w) = 0; /*--------------------------------------------------------------------------*/ // Testowa virtual std::string const &getName () const = 0; }; # endif /* ICONTROLLER_H_ */
/*-------------------------------------------------------------------- Name: Michael Martin and Jeremiah Cantu Date: 12/6/2020 Course: CSCE 236 Embedded Systems (Spring 2020) File: lab2_button_count.ino HW/Lab: Lab 2, Button Count Code Purp: Testing timers and counters Doc: Jeremiah Cantu was my lab partner Academic Integrity Statement: I certify that, while others may have assisted me in brain storming, debugging and validating this program, the program itself is my own work. I understand that submitting code which is the work of other individuals is a violation of the honor code. I also understand that if I knowingly give my original work to another individual is also a violation of the honor code. --------------------------------------------------------------------*/ #include <Arduino.h> //#include <avr/io.h> // Definitions for Port B & D registors #define PINB_Reg (*((volatile uint8_t *) 0x23)) #define DDRB_Reg (*((volatile uint8_t *) 0x24)) #define PORTB_Reg (*((volatile uint8_t *) 0x25)) #define PIND_Reg (*((volatile uint8_t *) 0x29)) #define DDRD_Reg (*((volatile uint8_t *) 0x2a)) #define PORTD_Reg (*((volatile uint8_t *) 0x2b)) // Definitions for LED assignments: #define BOARD_LED 5 //pin 13 is PortB bit 5 #define RED_LED 1 //pin 9 is PortB bit 1 #define GREEN_LED 2 //pin 10 is PortB bit 2 #define BLUE_LED 3 //pin 11 is PortB bit 3 #define BUTTON 5 /** * Init all of the LEDs and test them **/ void LEDInit(){ //Set pinmode for LEDs to output DDRB_Reg |= (1 << BOARD_LED); DDRB_Reg |= (1 << RED_LED); DDRB_Reg |= (1 << GREEN_LED); DDRB_Reg |= (1 << BLUE_LED); //Turn all off PORTB_Reg &= ~(1 << BOARD_LED); //clear output PORTB_Reg &= ~(1 << RED_LED); //clear output PORTB_Reg &= ~(1 << GREEN_LED); //clear output PORTB_Reg &= ~(1 << BLUE_LED); //clear output //Test LEDs Serial.println("Testing LEDs..."); PORTB_Reg |= (1 << BOARD_LED); //set output PORTB_Reg |= (1 << RED_LED); //set output delay(400); PORTB_Reg &= ~(1 << RED_LED); //clear output PORTB_Reg |= (1 << GREEN_LED); //set output delay(400); PORTB_Reg &= ~(1 << GREEN_LED); //clear output PORTB_Reg |= (1 << BLUE_LED); //set output delay(400); PORTB_Reg &= ~(1 << BLUE_LED); //clear output PORTB_Reg &= ~(1 << BOARD_LED); //clear output Serial.println("Finished LED testing!"); } ///////////////////////////////////////////// void setup() { Serial.begin(9600); Serial.println("Starting up..."); LEDInit(); //Set pinmode for Button as input //DDRD_Reg &= ~(1 << BUTTON); //Enable pullup //PORTD_Reg |= (1 << BUTTON); //set output to enable pullup resistor DDRB_Reg &= ~(1<<0); PORTB_Reg |= (1<<0); //Init counter1 TCCR1A = 0; //Normal mode 0xffff top, rolls over TCCR1B &= ~(7); TCCR1B |= (1 << CS12) | (1 << CS11) | (1 << CS10); //Pre-scaler 64 TCCR1C = 0; //Set counter to zero, high byte first TCNT1H = 0; TCNT1L = 0; //Make sure interrupts are disabled TIMSK1 = 0; TIFR1 = 0; Serial.println("Finished setup!"); } ///////////////////////////////////////////// int prev_count = 0; void updateCount(){ if(prev_count != TCNT1){ Serial.print("TCNT1: "); Serial.println(TCNT1); if(TCNT1 - prev_count > 1){ Serial.println("Bounce detected!!!!"); } prev_count = TCNT1; delay(100); } } ///////////////////////////////////////////// int buttonPresses = 0; void checkForBounceCount(){ if(digitalRead(8) == 0){ Serial.println("Button!"); TCNT1 = 0; ICR1 = 0; buttonPresses ++; while(TCNT1 != 0xfff){ if(ICR1 != 0){ Serial.println("Bounce detected!!!!"); Serial.println(TCNT1); } else{ Serial.println("Number of presses: "); Serial.println(buttonPresses); } } } } void checkForReleaseBounce(){ if(digitalRead(8) == 0){ delay(50); while(digitalRead(8) == 0){} TCNT1H = 0; TCNT1L = 0; ICR1 = 0; while(TCNT1 < 0xfff){ if(ICR1 != 0){ Serial.println("Bounce detected!!!!"); Serial.println(TCNT1); } } Serial.println("done bouncing!"); } } void timeButtonHold(){ if(digitalRead(8) == 0){ TCNT1 = 0; delay(50); while(digitalRead(8) == 0){} Serial.println("Button Held"); Serial.println(TCNT1/10000.0); } } ///////////////////////////////////////////// void loop() { /* Serial.print("TCNT1: "); Serial.println(TCNT1); */ //updateCount(); //timeButtonHold(); //checkForReleaseBounce(); //checkForBounceCount(); } /////////////////////////////////////////////
// Copyright 2012 Yandex #ifndef LTR_LEARNERS_DECISION_TREE_DECISION_TREE_LEARNER_H_ #define LTR_LEARNERS_DECISION_TREE_DECISION_TREE_LEARNER_H_ #include <vector> #include <string> #include <functional> #include "logog/logog.h" #include "ltr/learners/learner.h" #include "ltr/learners/decision_tree/utility/utility.h" #include "ltr/learners/decision_tree/decision_vertex.h" #include "ltr/learners/decision_tree/leaf_vertex.h" #include "ltr/learners/decision_tree/splitting_quality.h" #include "ltr/learners/decision_tree/conditions_learner.h" #include "ltr/scorers/decision_tree_scorer.h" using std::string; using std::vector; namespace ltr { namespace decision_tree { /** * The Vertex with corresponding part of DataSet. */ struct VertexWithData { VertexWithData(Vertex<double>::Ptr vertex, const DataSet<Object>& data) : vertex(vertex), data(data) {} VertexWithData(const VertexWithData& other) : vertex(other.vertex), data(other.data) {} Vertex<double>::Ptr vertex; DataSet<Object> data; }; /** * \class DecisionTreeLearner * Builds decision tree for given data. */ class DecisionTreeLearner : public BaseLearner<Object, DecisionTreeScorer> { public: void setDefaultParameters(); void checkParameters() const; GET_SET(ConditionsLearner::Ptr, conditions_learner); GET_SET(SplittingQuality::Ptr, splitting_quality); GET_SET(int, min_vertex_size); GET_SET(double, label_eps); explicit DecisionTreeLearner(const ParametersContainer& parameters); string toString() const; explicit DecisionTreeLearner( int min_vertex_size = 3, double label_eps = 0.001); private: virtual void setParametersImpl(const ParametersContainer& parameters); bool needToGenerateLeaf(const DataSet<Object>& data) const; LeafVertex<double>::Ptr generateLeaf(const DataSet<Object>& data) const; virtual void buildNextLayer(const vector<VertexWithData>& current_layer, vector<VertexWithData>* next_layer); /** * Function creates decision tree for given data. * Uses ConditionsLearner and SplittingQuality to create it. */ Vertex<double>::Ptr buildTree(const DataSet<Object>& data); void learnImpl(const DataSet<Object>& data, DecisionTreeScorer* scorer); virtual string getDefaultAlias() const; int min_vertex_size_; double label_eps_; /** * Object, used to generate different conditions for splitting data set */ ConditionsLearner::Ptr conditions_learner_; /** * Object, used to select the best split of the data set */ SplittingQuality::Ptr splitting_quality_; }; }; }; #endif // LTR_LEARNERS_DECISION_TREE_DECISION_TREE_LEARNER_H_
#include <algorithm> #include <fstream> #include <iostream> #include <regex> #include <sstream> #include <stdexcept> #include <vector> #include "hash.h" using namespace std; typedef pair<string, uchar_vector> t_handlehashpair; // These values are just an example. Do not get too excited if you "win" using these values. // The real values will be revealed after Bitcoin block 502961. uchar_vector secret("50D858E0985ECC7F60418AAF0CC5AB587F42C2570A884095A9E8CCACD0F6545C"); uchar_vector blockHash("00000000000000000024fb37364cbf81fd49cc2d51c09c75c35433c3a1945d04"); string getLowercase(const string& s) { string s_lower(s); transform(s_lower.begin(), s_lower.end(), s_lower.begin(), ::tolower); return s_lower; } string getHandleFromUrl(const string& url) { regex e("https://twitter.com/([^/]*)"); smatch m; if (!regex_search(url, m, e)) { stringstream ss; ss << "Invalid url encountered: " << url; throw runtime_error(ss.str()); } return m[1]; } uchar_vector getHandleHash(const string& handle, const uchar_vector& nonce) { uchar_vector hash; string handle_lower = getLowercase(handle); for (auto c: handle_lower) { hash.push_back((unsigned char)c); } hash << nonce; return sha256_2(hash); } bool sortByHandleHash(const t_handlehashpair& h1, const t_handlehashpair& h2) { return h1.second < h2.second; } int main(int argc, char* argv[]) { if (argc != 3) { cerr << "#Usage: " << argv[0] << " <source file> <destination file>" << endl; return -1; } try { string line; vector<t_handlehashpair> handlehashpairs; uchar_vector nonce = secret ^ blockHash; ifstream inputFile(argv[1]); while (getline(inputFile, line)) { string handle = getHandleFromUrl(line); handlehashpairs.push_back(make_pair(handle, getHandleHash(handle, nonce))); } sort(handlehashpairs.begin(), handlehashpairs.end(), sortByHandleHash); ofstream outputFile(argv[2], ofstream::trunc); for (auto handlehashpair: handlehashpairs) { outputFile << handlehashpair.second.getHex() << " " << handlehashpair.first << endl; } } catch (exception& e) { cerr << e.what() << endl; return -2; } return 0; }
/* Copyright (c) 2015, M. Kerber, D. Morozov, A. Nigmetov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. You are under no obligation whatsoever to provide any bug fixes, patches, or upgrades to the features, functionality or performance of the source code (Enhancements) to anyone; however, if you choose to make your Enhancements available either publicly, or directly to copyright holder, without imposing a separate written license agreement for such Enhancements, then you hereby grant the following license: a non-exclusive, royalty-free perpetual license to install, use, modify, prepare derivative works, incorporate into other computer software, distribute, and sublicense such enhancements or derivative works thereof, in binary and source code form. */ #ifndef AUCTION_ORACLE_KDTREE_RESTRICTED_H #define AUCTION_ORACLE_KDTREE_RESTRICTED_H //#define USE_BOOST_HEAP #include <map> #include <memory> #include <set> #include "basic_defs_ws.h" #include "diagonal_heap.h" #include "auction_oracle_base.h" #include <hera/dnn/geometry/euclidean-fixed.h> #include <hera/dnn/local/kd-tree.h> namespace hera { namespace ws { template <class Real_ = double, class PointContainer_ = std::vector<DiagramPoint<Real_>>> struct AuctionOracleKDTreeRestricted : AuctionOracleBase<Real_, PointContainer_> { using PointContainer = PointContainer_; using Real = Real_; using LossesHeapR = typename ws::LossesHeapOld<Real>; using LossesHeapRHandle = typename ws::LossesHeapOld<Real>::handle_type; using DiagramPointR = typename hera::DiagramPoint<Real>; using DebugOptimalBidR = typename ws::DebugOptimalBid<Real>; using DnnPoint = dnn::Point<2, Real>; using DnnTraits = dnn::PointTraits<DnnPoint>; AuctionOracleKDTreeRestricted(const PointContainer& bidders, const PointContainer& items, const AuctionParams<Real>& params); ~AuctionOracleKDTreeRestricted(); // data members // temporarily make everything public Real max_val_; Real weight_adj_const_; dnn::KDTree<DnnTraits>* kdtree_; std::vector<DnnPoint> dnn_points_; std::vector<DnnPoint*> dnn_point_handles_; LossesHeapR diag_items_heap_; std::vector<LossesHeapRHandle> diag_heap_handles_; std::vector<size_t> heap_handles_indices_; std::vector<size_t> kdtree_items_; std::vector<size_t> top_diag_indices_; std::vector<size_t> top_diag_lookup_; size_t top_diag_counter_ { 0 }; bool best_diagonal_items_computed_ { false }; Real best_diagonal_item_value_; size_t second_best_diagonal_item_idx_ { k_invalid_index }; Real second_best_diagonal_item_value_ { std::numeric_limits<Real>::max() }; // methods void set_price(const IdxType items_idx, const Real new_price, const bool update_diag = true); void set_prices(const std::vector<Real>& new_prices); IdxValPair<Real> get_optimal_bid(const IdxType bidder_idx); void adjust_prices(); void adjust_prices(const Real delta); // debug routines DebugOptimalBidR get_optimal_bid_debug(IdxType bidder_idx) const; void sanity_check(); // heap top vector size_t get_heap_top_size() const; void recompute_top_diag_items(bool hard = false); void recompute_second_best_diag(); void reset_top_diag_counter(); void increment_top_diag_counter(); void add_top_diag_index(const size_t item_idx); void remove_top_diag_index(const size_t item_idx); bool is_in_top_diag_indices(const size_t item_idx) const; std::pair<Real, Real> get_minmax_price() const; }; template<class Real> std::ostream& operator<< (std::ostream& output, const DebugOptimalBid<Real>& db); } // ws } // hera #include "auction_oracle_kdtree_restricted.hpp" #endif
/* * Copyright (c) 2020 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_TESTSUITE_WRAPPER_H_ #define CPPSORT_TESTSUITE_WRAPPER_H_ //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <utility> //////////////////////////////////////////////////////////// // Wrapper around a simple type // // This wrapper with a public value is mostly used to test // pointer to data members used a projections throughout // the test suite template<typename T> struct generic_wrapper { T value; generic_wrapper() = default; generic_wrapper(const generic_wrapper&) = default; generic_wrapper(generic_wrapper&&) = default; constexpr generic_wrapper(const T& other_value): value(other_value) {} constexpr generic_wrapper(T&& other_value): value(std::move(other_value)) {} generic_wrapper& operator=(const generic_wrapper&) = default; generic_wrapper& operator=(generic_wrapper&&) = default; constexpr auto operator=(const T& other_value) -> generic_wrapper& { value = other_value; return *this; } constexpr auto operator=(T&& other_value) -> generic_wrapper& { value = std::move(other_value); return *this; } }; //////////////////////////////////////////////////////////// // Wrapper with an "order" // // This wrapper has an additional integral field meant to // attach more information to it than the value it wraps, // information which can be used to try to detect issues in // stable sorting algorithms template<typename T> struct generic_stable_wrapper { T value; int order; generic_stable_wrapper() = default; generic_stable_wrapper(const generic_stable_wrapper&) = default; generic_stable_wrapper(generic_stable_wrapper&&) = default; constexpr generic_stable_wrapper(const T& other_value): value(other_value) {} constexpr generic_stable_wrapper(T&& other_value): value(std::move(other_value)) {} generic_stable_wrapper& operator=(const generic_stable_wrapper&) = default; generic_stable_wrapper& operator=(generic_stable_wrapper&&) = default; constexpr auto operator=(const T& other_value) -> generic_stable_wrapper& { value = other_value; return *this; } constexpr auto operator=(T&& other_value) -> generic_stable_wrapper& { value = std::move(other_value); return *this; } friend constexpr auto operator==(const generic_stable_wrapper& lhs, const generic_stable_wrapper& rhs) -> bool { return lhs.value == rhs.value && lhs.order == rhs.order; } friend constexpr auto operator<(const generic_stable_wrapper& lhs, const generic_stable_wrapper& rhs) -> bool { if (lhs.value < rhs.value) { return true; } if (rhs.value < lhs.value) { return false; } return lhs.order < rhs.order; } }; #endif // CPPSORT_TESTSUITE_WRAPPER_H_
#ifndef ABOUTBOOKCRICKET_H #define ABOUTBOOKCRICKET_H #include <QDialog> namespace Ui { class aboutbookcricket; } class aboutbookcricket : public QDialog { Q_OBJECT public: explicit aboutbookcricket(QWidget *parent = 0); ~aboutbookcricket(); private slots: void on_pushButton_clicked(); private: Ui::aboutbookcricket *ui; }; #endif // ABOUTBOOKCRICKET_H
#include <iostream> #include "ListaST.h" #include "stdlib.h" using namespace std; int main() { ListaST<int> A; A.inserta(5); A.inserta(1); A.inserta(2); A.inserta(4); A.inserta(3); A.inserta(-2); system("cls"); cout << "Lista:" << endl; A.muestraTusDatos(); cout << endl << "Promedio: " << A.promedio() << endl; return 0; }
#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; struct cell { int val, tag, ctag; bool operator<(const cell& A) const { if (val != A.val) return val > A.val; return tag < A.tag; } }; priority_queue<cell> q; int main() { int n, M, T; scanf("%d%d%d", &n, &M, &T); for (int i = 0; i < n; ++i) { int h, m, s; scanf("%d:%d:%d", &h, &m, &s); int pos = ((h * 60) + m) * 60 + s; cell a; a.val = pos; a.tag = 1; q.push(a); } vector<int> ans; int k = 0; map<int, int> un; bool cool = false; while (!q.empty()) { int pos = q.top().val; int tag = q.top().tag; int ctag = q.top().ctag; q.pop(); if (tag == 1) { if (int(un.size()) < M) { ++k; } ans.push_back(k); un[k]++; cell A; A.val = pos + T - 1; A.tag = -1; A.ctag = k; q.push(A); } else { auto it = un.find(ctag); it->second--; if (it->second == 0) { un.erase(it); } } if (int(un.size()) == M) cool = true; } if (!cool) { puts("No solution"); return 0; } printf("%d\n", k); for (size_t i = 0; i < ans.size(); ++i) printf("%d\n", ans[i]); return 0; }
#include "stdafx.h" #include "DelegateWinThreadPool.h" DelegateWinThreadPool::DelegateWinThreadPool(const tstring &csThreadName, int iNumOfThreads) : m_csThreadName(csThreadName) , m_iNumOfThreads(iNumOfThreads) , m_Event(true, false) { } DelegateWinThreadPool::~DelegateWinThreadPool() { } void DelegateWinThreadPool::Start() { for (int i = 0; i < m_iNumOfThreads; ++i) { DelegateWinThread *pThread = new DelegateWinThread(m_csThreadName, this); pThread->Start(); m_vecDelegateThread.push_back(pThread); } } void DelegateWinThreadPool::JoinAll() { for (int i = 0; i < m_iNumOfThreads; ++i) { AddWork(NULL); } for (auto iter = m_vecDelegateThread.begin(); iter != m_vecDelegateThread.end(); ++iter) { DelegateWinThread *pThread = *iter; pThread->Stop(); delete pThread; } } void DelegateWinThreadPool::Run() { for (;;) { m_Event.Wait(); Delegate *pDelegate = NULL; { AutoLock autoLock(m_Lock); if (m_WorkQueue.empty()) { m_Event.Reset(); continue; } pDelegate = m_WorkQueue.front(); m_WorkQueue.pop(); } if (pDelegate == NULL) { break; } pDelegate->Run(); } } void DelegateWinThreadPool::AddWork(Delegate *pDelegate) { AutoLock autoLock(m_Lock); m_WorkQueue.push(pDelegate); if (!m_Event.IsSignaled()) { m_Event.Signal(); } }
#include"conio.h" #include"stdio.h" void main(void) { clrscr(); int radius; float area; printf("Enter Radius of cicle = "); scanf("%d",&radius); area=3.14*radius*radius; printf("\n\nArea of a Cirle is %.2f",area); getch(); }
// // AcidAudioBuffer.hpp // SRXvert // // Created by Dennis Lapchenko on 04/05/2016. // // #ifndef ACIDAUDIOBUFFER_H_ #define ACIDAUDIOBUFFER_H_ #include "../JuceLibraryCode/JuceHeader.h" namespace AcidR { class AcidAudioBuffer : public AudioSampleBuffer { public: AcidAudioBuffer(); ~AcidAudioBuffer(); void setSampleRate(double newSampleRate); double getSampleRate(); void PeakNormalise(float maxPeak, float threshold); void WriteFromReader(AudioFormatReader *reader); private: double sampleRate; }; } #endif /* AcidAudioBuffer_h */
// Created on : Sat May 02 12:41:15 2020 // Created by: Irina KRYLOVA // Generator: Express (EXPRESS -> CASCADE/XSTEP Translator) V3.0 // Copyright (c) Open CASCADE 2020 // // 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 _StepKinematics_PlanarPairValue_HeaderFile_ #define _StepKinematics_PlanarPairValue_HeaderFile_ #include <Standard.hxx> #include <StepKinematics_PairValue.hxx> #include <TCollection_HAsciiString.hxx> #include <StepKinematics_KinematicPair.hxx> DEFINE_STANDARD_HANDLE(StepKinematics_PlanarPairValue, StepKinematics_PairValue) //! Representation of STEP entity PlanarPairValue class StepKinematics_PlanarPairValue : public StepKinematics_PairValue { public : //! default constructor Standard_EXPORT StepKinematics_PlanarPairValue(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init(const Handle(TCollection_HAsciiString)& theRepresentationItem_Name, const Handle(StepKinematics_KinematicPair)& thePairValue_AppliesToPair, const Standard_Real theActualRotation, const Standard_Real theActualTranslationX, const Standard_Real theActualTranslationY); //! Returns field ActualRotation Standard_EXPORT Standard_Real ActualRotation() const; //! Sets field ActualRotation Standard_EXPORT void SetActualRotation (const Standard_Real theActualRotation); //! Returns field ActualTranslationX Standard_EXPORT Standard_Real ActualTranslationX() const; //! Sets field ActualTranslationX Standard_EXPORT void SetActualTranslationX (const Standard_Real theActualTranslationX); //! Returns field ActualTranslationY Standard_EXPORT Standard_Real ActualTranslationY() const; //! Sets field ActualTranslationY Standard_EXPORT void SetActualTranslationY (const Standard_Real theActualTranslationY); DEFINE_STANDARD_RTTIEXT(StepKinematics_PlanarPairValue, StepKinematics_PairValue) private: Standard_Real myActualRotation; Standard_Real myActualTranslationX; Standard_Real myActualTranslationY; }; #endif // _StepKinematics_PlanarPairValue_HeaderFile_
#include <stdio.h> #include <math.h> #include <PortAudio/portaudio.h> #include <sndfile.hh> #ifdef WIN32 #include <windows.h> #if PA_USE_ASIO #include <PortAudio/pa_asio.h> #endif #endif #define NUM_SECONDS (180) #define SAMPLE_RATE (44100) //Hz #define FRAMES_PER_BUFFER (64) #ifndef M_PI #define M_PI 4*atan(1) #endif
/* ID: washirv1 PROG: ariprog LANG: C++ */ #include <fstream> using namespace std; #define INFILE "ariprog.in" #define OUTFILE "ariprog.out" int square(int i) { return i * i; } int main() { int N, M; ifstream fin(INFILE); fin >> N >> M; fin.close(); const int NUM = square(M) * 2 + 1; // Generate bisquares bool bisquares[NUM]; for (int i = 0; i < NUM; i++) bisquares[i] = false; for (int p = 0; p <= M; p++) for (int q = 0; q <= M; q++) bisquares[square(p) + square(q)] = true; ofstream fout(OUTFILE); // 1 <= b <= 2M^2 / (N - 1) bool none = true; for (int b = 1, bInc = 1; b <= 2 * square(M) / (N - 1); b += bInc) { // 0 <= a <= 2M^2 - (N - 1) * b for (int a = 0; a <= 2 * square(M) - (N - 1) * b; a++) { int n = 0; while (n < N) { if (bisquares[a + n * b]) n++; else break; } if (n == N) // valid sequence found { if (none) { bInc = b; none = false; } fout << a << " " << b << endl; } } } if (none) fout << "NONE" << endl; fout.close(); return 0; }
#include "../include/Command.h" using namespace std; Command::Command():title("") {} const string& Command::operator[](const string& key) const { for(int i(0); i!=keys.size(); i++) { if(keys[i] == key) { return value[i]; } } } string& Command::operator[](const string& key) { for(int i(0); i!=keys.size(); i++) { if(keys[i] == key) { return value[i]; } } //if key is not exist, create it keys.push_back(key); value.push_back(""); return value.back(); }
#include "CSoftwareListWidget.h" #include "CTableWidget.h" #include <QTabWidget> #include <QHBoxLayout> CSoftwareListWidget::CSoftwareListWidget(QWidget *parent) : QWidget(parent) { m_pTabWidget = new QTabWidget(this); QHBoxLayout* hboxLayout = new QHBoxLayout(this); hboxLayout->addWidget(m_pTabWidget); connect(CXmlParse::Instance(), &CXmlParse::dataChangedNotify, this, &CSoftwareListWidget::updateUi); } CSoftwareListWidget::~CSoftwareListWidget() { } void CSoftwareListWidget::updateUi(const QMap<QString, SoftData>& data) { QMapIterator<QString, SoftData> iter(data); while(iter.hasNext()) { iter.next(); //本地安装程序 if(iter.value().bUpgrade && m_pTabMap.contains(iter.key())) { m_pTabMap.value(iter.key())->updateTable(iter.value()); } else if(iter.value().bInstall) { CTableWidget* table = new CTableWidget(iter.value(), this); m_pTabWidget->addTab(table,iter.key()); m_pTabMap.insert(iter.key(), table); } } m_pTabWidget->setCurrentIndex(0); }
#ifndef _NEGATIVE_EXPRESSION_HPP_ #define _NEGATIVE_EXPRESSION_HPP_ #include "Expression.hpp" // Di bawah ini, kelas NegativeExpression menginherit Expression // Namun, sekarang Expression merupakan interface, bukan kelas. class NegativeExpression : public Expression { protected: // Di Java, tidak ada konsep pointer. Polymorphism dapat dilakukan // pada reference, bukan pointer. Expression* x; public: NegativeExpression(Expression* x) { this->x = x; } int solve() { return -1 * this->x->solve(); } }; #endif
// // debug.cpp // utilities // // Created by Six on 2/23/2018. // Copyright 2/23/2018 Six. All rights reserved. // #include <stdarg.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <memory> #include <string> #include <time.h> #include <ctype.h> #include <libgen.h> #include "string_utils.hpp" #include "buffer.hpp" /// @brief A memory-safe pointer to a c string typedef std::unique_ptr< std::string::value_type, std::default_delete<std::string::value_type[]> > safe_c_string; //////////////////////////////////////////////////////////////////////////////// // make_time_str //////////////////////////////////////////////////////////////////////////////// static std::string make_time_str(void) { time_t rawtime; struct tm *tme; time (&rawtime); tme = localtime(&rawtime); return util_sprintf("<%02d/%02d/%4d %02d:%02d:%02d>",tme->tm_mon+1,tme->tm_mday,tme->tm_year+1900, tme->tm_hour,tme->tm_min,tme->tm_sec); } // end time_str //////////////////////////////////////////////////////////////////////////////// // make_unformatted_string - for when you have a message already formatted //////////////////////////////////////////////////////////////////////////////// static std::string make_unformatted_string(const char *file, int line, const char *func, const char *msg) { const std::string time_str = make_time_str(); std::shared_ptr<char> file_base = util_strdup(file); return util_sprintf("%s %s:%d:[%s]: %s", time_str.c_str(), basename(file_base.get()), line, func, msg); } // end make_unformatted_string //////////////////////////////////////////////////////////////////////////////// // vmake_formatted_string - for when you have sprintf-like formatting // IMPORTANT NOTES: // call va_start() first before calling this function // call va_end() after calling this function //////////////////////////////////////////////////////////////////////////////// static std::string vmake_formatted_string(const char *file, int line, const char *func, const char *fmt, int fmt_len, va_list args) { safe_c_string fmt_str(new std::string::value_type[fmt_len+1]); (void)vsnprintf(fmt_str.get(),fmt_len+1,fmt,args); return make_unformatted_string(file, line, func, fmt_str.get()); } // end vmake_formatted_string //////////////////////////////////////////////////////////////////////////////// // formatted_print -- for when you need to log stuff a-la fprintf //////////////////////////////////////////////////////////////////////////////// void formatted_print(const char *file, int line, const char *func, const char *fmt, ...) { va_list args; va_start(args,fmt); const int fmt_len = vsnprintf(NULL, 0, fmt, args); va_end(args); va_start(args,fmt); fprintf(stderr, "%s", vmake_formatted_string(file, line, func, fmt, fmt_len, args).c_str()); va_end(args); } // end formatted_print //////////////////////////////////////////////////////////////////////////////// // debug_print_io //////////////////////////////////////////////////////////////////////////////// void debug_print_io(const char *file, int line, const char *func, bool in, const void *msg, size_t len) { const char *dir = (in ? "<--" : "-->"); Buffer<uint8_t> buf; buf.wrap(msg, len); size_t offset = 0; std::string chars; std::string hex; std::string tmp; std::string log_msg; const std::string time_string(make_time_str()); // do 4 byte chunks while we can while(offset < len) { const uint8_t u = *buf.alias<uint8_t>(offset, &offset); hex += util_sprintf("%02X", u); if(isprint(u)) { chars.push_back(char(u)); } else { chars.push_back('.'); } } // end while util_sprintf(log_msg, "%s %s %s %s\n", time_string.c_str(), dir, hex.c_str(), chars.c_str()); fprintf(stderr, "%s", log_msg.c_str()); } // end debug_print_io
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef DESKTOP_EXTENSIONS_MANAGER_H #define DESKTOP_EXTENSIONS_MANAGER_H #include "adjunct/quick/extensions/ExtensionInstaller.h" #include "adjunct/quick/extensions/ExtensionUIListener.h" #include "adjunct/quick/extensions/ExtensionSpeedDialHandler.h" #include "adjunct/quick/extensions/TabAPIListener.h" #include "adjunct/quick/managers/DesktopManager.h" #include "adjunct/quick/models/ExtensionsModel.h" #include "adjunct/quick/windows/OpRichMenuWindow.h" #include "adjunct/quick_toolkit/contexts/DialogContextListener.h" #include "modules/windowcommander/OpWindowCommanderManager.h" #define g_desktop_extensions_manager (DesktopExtensionsManager::GetInstance()) class ExtensionPrefsController; class ExtensionPopupController; class OpExtensionButton; class OpGadgetClass; class OpWindowCommander; class OpWorkspace; /** * @brief Desktop Manager for Desktop Extensions. * * Provides functions for installation/deinstallation, updates * of desktop extensions. Handles actions from Extensions Manager * panel (@see ExtensionsPanel). */ class DesktopExtensionsManager : public DesktopManager<DesktopExtensionsManager>, public OpRichMenuWindow::Listener, public OpPageListener, public DialogContextListener, public OpTimerListener { public: DesktopExtensionsManager(); virtual ~DesktopExtensionsManager(); virtual OP_STATUS Init(); void StartAutoStartServices(); BOOL HandleAction(OpInputAction* action); /** * @see ExtensionsModel */ OP_STATUS AddExtensionsModelListener(ExtensionsModel::Listener* listener); OP_STATUS RemoveExtensionsModelListener(ExtensionsModel::Listener* listener); OP_STATUS SetExtensionDataListener(const OpStringC& extension_id, ExtensionDataListener* listener); OP_STATUS RefreshModel(); BOOL CanShowOptionsPage(const OpStringC& extension_id); /** * Open an extension's options page in a DocumentDesktopWindow. * * @param extension_id extension WUID * @return status */ OP_STATUS OpenExtensionOptionsPage(const OpStringC& extension_id); /** * Open an extension's options page in a call-out dialog. * * @param extension_id extension WUID * @param controller the dialog's controller * @return status */ OP_STATUS OpenExtensionOptionsPage(const OpStringC& extension_id, ExtensionPrefsController& controller); OP_STATUS SetExtensionSecurity(const OpStringC& extension_id, BOOL ssl_access, BOOL private_access); OP_STATUS GetExtensionSecurity(const OpStringC& extension_id, BOOL& ssl_access, BOOL& private_access); OP_STATUS UninstallExtension(const OpStringC& extension_id); OP_STATUS EnableExtension(const OpStringC& extension_id); OP_STATUS DisableExtension(const OpStringC& extension_id, BOOL user_requested = TRUE, BOOL notify_listeners = TRUE); ExtensionButtonComposite* GetButtonFromModel(INT32 id); OP_STATUS CreateButtonInModel(INT32 id); OP_STATUS DeleteButtonInModel(INT32 id); /** * @param extension_id Extension id. * @return Status. */ OP_STATUS ShowExtensionUninstallDialog(const uni_char* extension_id); /** * Called after OpExtensionButton has been removed from composite. * * @param id Extension id. */ void OnButtonRemovedFromComposite(INT32 id); /** * @see ExtensionInstaller::Install* */ OP_STATUS InstallFromExternalURL(const OpStringC& url_name, BOOL silent_installation = FALSE, BOOL temp_mode = FALSE); OP_STATUS InstallFromLocalPath(const OpStringC& extension_path); /** * Create a UI window for an extension. * * Called when handling OpUiWindowListener::CreateUiWindow() coming * from Core. * * @param commander the extension's OpWindowCommander * @param args describes the kind of window to be created * @return status */ OP_STATUS CreateExtensionWindow(OpWindowCommander* commander, const OpUiWindowListener::CreateUiWindowArgs& args); /** * Update functionality. */ OP_STATUS AskForExtensionUpdate(const OpStringC& extension_id); void UpdateExtension(const OpStringC& extension_id); OP_STATUS ShowUpdateAvailable(const OpStringC& extension_id); OP_STATUS CheckForDelayedUpdate(OpGadget* gadget,BOOL &updated); OP_STATUS CheckForDelayedUpdates(); void CheckForUpdate(); void ShowUpdateNotification(); void ShowUpdateNotification(OpGadget* last_updated, OpGadget* next_to_last_updated, int number_of_updates_made); /** * Checks if update of extension given by id was downloaded from a trusted host. * When update is downloaded we create file update_url.dat in extension's profile * directory where we put update's download url. This method checks if the host * located in this file is located on a list of trusted hosts. * * @param extension_id id of the extension which we want to check * @return true if host from which update was downloaded is a trusted host, false otherwise */ bool IsUpdateFromTrustedHost(const OpStringC& extension_id); /** * Checks if update of extension represented by instance of class OpGadget was downloaded * from a trusted host. For more details @see IsUpdateFromTrustedHost(const OpStringC&). */ bool IsUpdateFromTrustedHost(OpGadget& gadget); /** * Shows dialog which informs user that extension's update was blocked * as it was downloaded from untrusted repository. * * @param repository URL of the untrusted repository. */ void ShowUntrustedRepositoryWarningDialog(OpStringC repository) const; void StartListeningTo(OpWorkspace* workspace); void StopListeningTo(OpWorkspace* workspace); OP_STATUS RemoveDuplicatedSDExtensions(OpGadget* gadget); OP_STATUS UpdateExtension(GadgetUpdateInfo* data,OpStringC& update_source); void CloseDevExtensionPopup(); /** * Regular extension popup, platform popup, * is closed autmaticly when user changes focus to something else. * Only time, when there is a need to manually close popup, * is when new tab from extension popup is created. */ void CloseRegExtensionPopup(); // // OpPageListener // virtual void OnPageClose(OpWindowCommander* commander); virtual BOOL OnPagePopupMenu(OpWindowCommander* commander, OpDocumentContext& context) { return TRUE; } // // OpRichMenuWindow::Listener // virtual void OnMenuClosed(); /** * By usage of this function you can open any url, including internal gadget url * which is not working via g_application->GoToPage(..) */ OP_STATUS OpenExtensionUrl(const OpStringC& url,const OpStringC& wuid); /** * Retrive from extension pointed by extension_id fallback url from config.xml * * @param extension_id Extension wuid. * @param fallback_url - here fallback url will be returned, * if extension with extension_id exist * @return Status. */ OP_STATUS GetExtensionFallbackUrl(const OpStringC& extension_id, OpString& fallback_url); /** * SD feature */ void ExtensionDataUpdated(const OpStringC& extension_id); /** Install all extensions from custom folder. It should be called after * SpeedDialManager is initialized and after it loaded speed dials from ini file. */ OP_STATUS InstallCustomExtensions(); /** * Returns number of installed extensions (including extensions in dev mode). */ unsigned GetExtensionsCount() const { return m_extensions_model.GetCount(); } /** * Cancel download started by InstallRemote * @param download_url address, must be the same as passed to InstallRemote */ void CancelInstallationDownload(const OpStringC& download_url) { m_extension_installer.AbortDownload(download_url); }; /** * Marks extensions as temporary * Extension installed via SD add dialog might be considered as a temporary (until it is confirmed) * which results in blocking some regular actions handling (see ExtensionSpeedDialHandler) */ OP_STATUS SetExtensionTemporary(const OpStringC& extension_id, BOOL temporary); BOOL IsExtensionTemporary(const OpStringC& extension_id); OP_STATUS AddInstallListener(ExtensionInstaller::Listener* listener) {return m_extension_installer.AddListener(listener);} OP_STATUS RemoveInstallListener(ExtensionInstaller::Listener* listener) {return m_extension_installer.RemoveListener(listener);} /** * Retrieve all installed speed dial extensions. * * @param[out] extensions vector of all installed speed dial extensions * @return status of operation. If any error is returned @a extensions should not be used */ OP_STATUS GetAllSpeedDialExtensions(OpVector<OpGadget>& extensions) { return m_extensions_model.GetAllSpeedDialExtensions(extensions); } /** * Adds extension's speed dial represented by instance of class gadget * to the end of all speed dials. * * @parameter gadget gadget which represents extension's speed dial * @return status */ OP_STATUS AddSpeedDial(OpGadget& gadget) { return m_speeddial_handler.AddSpeedDial(gadget); } /** * Reloads the specified extension. Shorthand for both reload the extension and refresh the model. * It's used in extension view, as well as context menu of LSDs and extention button. * * @parameter id the gadget id of the extension to reload * @return BOOL return value that can be used in HandleAction */ BOOL ReloadExtension(const OpStringC& id) { RETURN_VALUE_IF_ERROR(m_extensions_model.ReloadExtension(id), FALSE); RETURN_VALUE_IF_ERROR(m_extensions_model.Refresh(), FALSE); return TRUE; } //pass-through, for doc see ExtensionInstaller::CheckUIButtonForInstallNotification void CheckUIButtonForInstallNotification(class OpExtensionButton* button,BOOL show) { m_extension_installer.CheckUIButtonForInstallNotification(button,show); } void ShowPopup(OpWidget* opener, INT32 composite_id); void SetPopupURL(INT32 composite_id, const OpStringC& url); void SetPopupSize(INT32 composite_id,UINT32 width, UINT32 height); BOOL HandlePopupAction(OpInputAction* action); virtual void OnDialogClosing(DialogContext* context); ExtensionUIListener* GetExtensionUIListener() { return &m_extension_ui_listener; } TabAPIListener* GetTabAPIListener() { return &m_tab_api_listener; } /** * Returns true if new extensions should be installed in silent mode (i.e. should * not be focused after installation). */ bool IsSilentInstall() const { return m_silent_install; } // OpTimerListener interface void OnTimeOut(OpTimer* time) { CheckForUpdate(); } private: /** * Create a window for an extension's main script. */ OP_STATUS CreateDummyExtensionWindow(OpWindowCommander* commander); /** * Create a window for a Speed Dial extension. */ OP_STATUS CreateSpeedDialExtensionWindow(OpWindowCommander* commander); /** * Create a window for an extension's options page. */ OP_STATUS CreateExtensionOptionsWindow(OpWindowCommander* commander, const OpStringC& url); /** * Create a window for an extension's options page. */ OP_STATUS CreateExtensionPopupWindow(OpWindowCommander* commander, const OpStringC& url); /** * Gets extension URL. * * @param extension_id Id of extension from which host will be taken. * @param url Will be filed with extension URL. * * @param return OK if host has been filled, ERR when extension was not found, * ERR_FILE_NOT_FOUND when extension file does not exist, * OOM in case of out of memomry. */ OP_STATUS GetURL(const OpStringC& extension_id, OpString& url) const; /** * Gets gadget URL. * * @param gadget Gadget from which host will be taken. * @param url Will be filed with gadget URL. * * @param return OK if host has been filled, ERR_FILE_NOT_FOUND when gadget * file does not exist, OOM in case of out of memomry. */ OP_STATUS GetURL(OpGadget& gadget, OpString& url) const; ExtensionInstaller m_extension_installer; ExtensionUIListener m_extension_ui_listener; TabAPIListener m_tab_api_listener; OpStringHashTable<ExtensionDataListener> m_extension_data_listeners; OpGadget* m_last_updated; OpGadget* m_next_to_last_updated; int m_number_of_updates_made; ExtensionsModel m_extensions_model; OpRichMenuWindow* m_popup_window; BOOL m_popup_active; ExtensionSpeedDialHandler m_speeddial_handler; ExtensionPrefsController* m_extension_prefs_controller; ExtensionPopupController* m_popup_controller; // extension popup dialog for developer mode INT32 m_popup_composite_id; OpExtensionButton* m_extension_popup_btn; // pointer to opener of the popup dialog, in case opened via button OpString m_last_popup_url; bool m_silent_install; // when true new extensions should not be focused after installation OpTimer m_uid_retrieval_retry_timer; enum { MAX_UUID_RETRIEVAL_RETRIES = 5 }; unsigned m_uid_retrieval_retry_count; }; #endif // DESKTOP_EXTENSIONS_MANAGER_H
#ifndef CPUCORE_H #define CPUCORE_H #include <QObject> #include "processslot.h" #include <QGraphicsRectItem> #include <QGraphicsTextItem> #include <QTimer> #include <QFont> class CpuCore: public QObject, public QGraphicsRectItem { Q_OBJECT public: CpuCore(QObject* parent=0, int playerNumber=0); ProcessSlot* slot1; ProcessSlot* slot2; ProcessSlot* slot3; ProcessSlot* slot4; bool slot1Occupied=false; bool slot2Occupied=false; bool slot3Occupied=false; bool slot4Occupied=false; int scoreCount; QGraphicsTextItem* info; QGraphicsTextItem* Pscore; QGraphicsTextItem* P; QGraphicsRectItem* border; QGraphicsRectItem* blocker; QTimer* fadeText_timer; public slots: void slotIsOccupied(int slot); void slotIsFree(int slot); void fadeInfoText(); void process_was_terminated(int process_id); void process_starved(int process_id); void decrease(); void increase(); }; #endif // CPUCORE_H
#include <iostream> #include <sstream> #include <fstream> #include <map> #include <bitset> #include <string> #include <algorithm> #include <cmath> using namespace std; string decimal_to_binary(int num); // Convert decimal value to binary value int main (int argc, char* argv[]){ // store the encoded list to a map ifstream encodedFile(argv[1]); map<string, string> mapOfEncodedAscii; string line1; while (getline(encodedFile, line1)) { istringstream iss(line1); string ascii_value; string huffman_value; iss >> ascii_value; iss >> huffman_value; mapOfEncodedAscii[huffman_value] = ascii_value; // key is huffman value & value is ascii } string binary_string = ""; int bit_count = 0; unsigned char c; unsigned char d; c = cin.get(); int i =1; while (!cin.eof()) { d = cin.get(); if(cin.peek()!=EOF) { binary_string += decimal_to_binary(int(c)); bit_count += 8; while(bit_count>0 && binary_string != ""){ if(i > bit_count) break; if(mapOfEncodedAscii.count(binary_string.substr(0, i)) == 1){ int asciiVal = stoi(mapOfEncodedAscii[binary_string.substr(0,i)]); char asciiChar = asciiVal; cout << asciiChar; bit_count -= i; binary_string = binary_string.substr(i, bit_count); i = 1; } else{ i++; } } c = d; } } binary_string += decimal_to_binary(int(c)).substr(0,8-int(d)); bit_count = binary_string.length(); i=1; while(bit_count>0 && binary_string != ""){ if(mapOfEncodedAscii.count(binary_string.substr(0, i)) == 1){ int asciiVal = stoi(mapOfEncodedAscii[binary_string.substr(0,i)]); char asciiChar = asciiVal; cout << asciiChar; bit_count -= i; binary_string = binary_string.substr(i, bit_count); i = 1; } else{ i++; } } return 0; } // Convert decimal value to binary value string decimal_to_binary(int num) { string result = ""; if(num < 0) num += 256; for(int i=0; i<8; i++){ int bit = pow(2, 8-1-i); if(num >= bit){ result += "1"; num -= bit; } else { result += "0"; } } return result; }
// // Copyright (c) 2013 Mikko Mononen memon@inside.org // Port of _gl3.c to _DE.cpp by dtcxzyw // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // // SHA=2bead03bea43b2418060aaa154f972829995e663 #ifndef NOMINMAX #define NOMINMAX #endif #include "demo.h" #include "perf.h" #include <Windows.h> #include <nanovg.h> #include <nanovg_DE.hpp> #define ENGINE_DLL 1 #define D3D11_SUPPORTED 1 #define D3D12_SUPPORTED 1 #define GL_SUPPORTED 1 #define VULKAN_SUPPORTED 1 #include <DiligentCore/Common/interface/FileWrapper.hpp> #include <DiligentCore/Graphics/GraphicsEngineD3D11/interface/EngineFactoryD3D11.h> #include <DiligentCore/Graphics/GraphicsEngineD3D12/interface/EngineFactoryD3D12.h> #include <DiligentCore/Graphics/GraphicsEngineOpenGL/interface/EngineFactoryOpenGL.h> #include <DiligentCore/Graphics/GraphicsEngineVulkan/interface/EngineFactoryVk.h> #include <DiligentCore/Graphics/GraphicsTools/interface/DurationQueryHelper.hpp> #include <DiligentCore/Graphics/GraphicsTools/interface/ScreenCapture.hpp> #include <DiligentTools/TextureLoader/interface/Image.h> #include <chrono> #include <sstream> using Clock = std::chrono::high_resolution_clock; #ifdef _DEBUG #define DILIGENT_DEBUG #endif // _DEBUG #define NANOVG_MSAA static void callback(DE::DEBUG_MESSAGE_SEVERITY severity, const char* message, const char* function, const char* file, int line) { if(severity != DE::DEBUG_MESSAGE_SEVERITY_INFO) { DebugBreak(); } else OutputDebugStringA(message); } class Engine final { public: Engine(void* hWnd, DE::RENDER_DEVICE_TYPE type) { DE::SwapChainDesc SCDesc; SCDesc.DefaultDepthValue = 1.0f; SCDesc.DefaultStencilValue = 0; SCDesc.ColorBufferFormat = DE::TEX_FORMAT_RGBA8_UNORM; SCDesc.DepthBufferFormat = DE::TEX_FORMAT_D24_UNORM_S8_UINT; SCDesc.Usage = DE::SWAP_CHAIN_USAGE_RENDER_TARGET | DE::SWAP_CHAIN_USAGE_COPY_SOURCE; switch(type) { #if D3D11_SUPPORTED case DE::RENDER_DEVICE_TYPE_D3D11: { DE::EngineD3D11CreateInfo EngineCI; EngineCI.DebugMessageCallback = callback; #ifdef DILIGENT_DEBUG EngineCI.DebugFlags |= DE::D3D11_DEBUG_FLAG_CREATE_DEBUG_DEVICE | DE::D3D11_DEBUG_FLAG_VERIFY_COMMITTED_SHADER_RESOURCES; #endif #if ENGINE_DLL // Load the dll and import GetEngineFactoryD3D11() function auto GetEngineFactoryD3D11 = DE::LoadGraphicsEngineD3D11(); #endif auto* pFactoryD3D11 = GetEngineFactoryD3D11(); pFactoryD3D11->CreateDeviceAndContextsD3D11(EngineCI, &device, &immediateContext); DE::Win32NativeWindow window{ hWnd }; pFactoryD3D11->CreateSwapChainD3D11( device, immediateContext, SCDesc, DE::FullScreenModeDesc{}, window, &swapChain); } break; #endif #if D3D12_SUPPORTED case DE::RENDER_DEVICE_TYPE_D3D12: { #if ENGINE_DLL // Load the dll and import GetEngineFactoryD3D12() function auto GetEngineFactoryD3D12 = DE::LoadGraphicsEngineD3D12(); #endif DE::EngineD3D12CreateInfo EngineCI; EngineCI.DebugMessageCallback = callback; #ifdef DILIGENT_DEBUG EngineCI.EnableDebugLayer = true; #endif auto* pFactoryD3D12 = GetEngineFactoryD3D12(); pFactoryD3D12->CreateDeviceAndContextsD3D12(EngineCI, &device, &immediateContext); DE::Win32NativeWindow window{ hWnd }; pFactoryD3D12->CreateSwapChainD3D12( device, immediateContext, SCDesc, DE::FullScreenModeDesc{}, window, &swapChain); } break; #endif #if GL_SUPPORTED case DE::RENDER_DEVICE_TYPE_GL: { #if EXPLICITLY_LOAD_ENGINE_GL_DLL // Load the dll and import GetEngineFactoryOpenGL() function auto GetEngineFactoryOpenGL = DE::LoadGraphicsEngineOpenGL(); #endif auto* pFactoryOpenGL = GetEngineFactoryOpenGL(); DE::EngineGLCreateInfo EngineCI; EngineCI.Window.hWnd = hWnd; EngineCI.DebugMessageCallback = callback; #ifdef DILIGENT_DEBUG EngineCI.CreateDebugContext = true; #endif pFactoryOpenGL->CreateDeviceAndSwapChainGL( EngineCI, &device, &immediateContext, SCDesc, &swapChain); } break; #endif #if VULKAN_SUPPORTED case DE::RENDER_DEVICE_TYPE_VULKAN: { #if EXPLICITLY_LOAD_ENGINE_VK_DLL // Load the dll and import GetEngineFactoryVk() function auto GetEngineFactoryVk = DE::LoadGraphicsEngineVk(); #endif DE::EngineVkCreateInfo EngineCI; EngineCI.DebugMessageCallback = callback; #ifdef DILIGENT_DEBUG EngineCI.EnableValidation = true; #endif auto* pFactoryVk = GetEngineFactoryVk(); pFactoryVk->CreateDeviceAndContextsVk(EngineCI, &device, &immediateContext); if(!swapChain && hWnd != nullptr) { DE::Win32NativeWindow window{ hWnd }; pFactoryVk->CreateSwapChainVk(device, immediateContext, SCDesc, window, &swapChain); } } break; #endif default: throw std::logic_error("Unknown/unsupported device type"); break; } } ~Engine() { immediateContext->Flush(); } void updateTarget(const float* clearColor) { auto* pRTV = swapChain->GetCurrentBackBufferRTV(); auto* pDSV = swapChain->GetDepthBufferDSV(); if(sampleCount) { pRTV = msaaColorRTV; pDSV = msaaDepthDSV; } immediateContext->SetRenderTargets( 1, &pRTV, pDSV, DE::RESOURCE_STATE_TRANSITION_MODE_TRANSITION); // Clear the back buffer // Let the engine perform required state transitions immediateContext->ClearRenderTarget( pRTV, clearColor, DE::RESOURCE_STATE_TRANSITION_MODE_TRANSITION); immediateContext->ClearDepthStencil( pDSV, DE::CLEAR_DEPTH_FLAG | DE::CLEAR_STENCIL_FLAG, 1.0f, 0, DE::RESOURCE_STATE_TRANSITION_MODE_TRANSITION); } void resetRenderTarget() { if(sampleCount == 1) return; const auto& SCDesc = swapChain->GetDesc(); // Create window-size multi-sampled offscreen render target DE::TextureDesc colTexDesc = {}; colTexDesc.Name = "Color RTV"; colTexDesc.Type = DE::RESOURCE_DIM_TEX_2D; colTexDesc.BindFlags = DE::BIND_RENDER_TARGET; colTexDesc.Width = SCDesc.Width; colTexDesc.Height = SCDesc.Height; colTexDesc.MipLevels = 1; colTexDesc.Format = SCDesc.ColorBufferFormat; bool needSRGBConversion = device->GetDeviceCaps().IsD3DDevice() && (colTexDesc.Format == DE::TEX_FORMAT_RGBA8_UNORM_SRGB || colTexDesc.Format == DE::TEX_FORMAT_BGRA8_UNORM_SRGB); if(needSRGBConversion) { // Internally Direct3D swap chain images are not SRGB, and // ResolveSubresource requires source and destination formats to // match exactly or be typeless. So we will have to create a // typeless texture and use SRGB render target view with it. colTexDesc.Format = colTexDesc.Format == DE::TEX_FORMAT_RGBA8_UNORM_SRGB ? DE::TEX_FORMAT_RGBA8_TYPELESS : DE::TEX_FORMAT_BGRA8_TYPELESS; } // Set the desired number of samples colTexDesc.SampleCount = sampleCount; // Define optimal clear value float col[4] = { 0.3f, 0.3f, 0.32f, 1.0f }; memcpy(colTexDesc.ClearValue.Color, col, sizeof(col)); colTexDesc.ClearValue.Format = SCDesc.ColorBufferFormat; DE::RefCntAutoPtr<DE::ITexture> pColor; device->CreateTexture(colTexDesc, nullptr, &pColor); // Store the render target view msaaColorRTV.Release(); if(needSRGBConversion) { DE::TextureViewDesc RTVDesc; RTVDesc.ViewType = DE::TEXTURE_VIEW_RENDER_TARGET; RTVDesc.Format = SCDesc.ColorBufferFormat; pColor->CreateView(RTVDesc, &msaaColorRTV); } else { msaaColorRTV = pColor->GetDefaultView(DE::TEXTURE_VIEW_RENDER_TARGET); } // Create window-size multi-sampled depth buffer DE::TextureDesc depthDesc = colTexDesc; depthDesc.Name = "depth DSV"; depthDesc.Format = SCDesc.DepthBufferFormat; depthDesc.BindFlags = DE::BIND_DEPTH_STENCIL; // Define optimal clear value depthDesc.ClearValue.Format = depthDesc.Format; DE::RefCntAutoPtr<DE::ITexture> pDepth; device->CreateTexture(depthDesc, nullptr, &pDepth); // Store the depth-stencil view msaaDepthDSV = pDepth->GetDefaultView(DE::TEXTURE_VIEW_DEPTH_STENCIL); } DE::RefCntAutoPtr<DE::IRenderDevice> device; DE::RefCntAutoPtr<DE::IDeviceContext> immediateContext; DE::RefCntAutoPtr<DE::ISwapChain> swapChain; DE::Uint32 sampleCount = 1; DE::RefCntAutoPtr<DE::ITextureView> msaaColorRTV; DE::RefCntAutoPtr<DE::ITextureView> msaaDepthDSV; }; std::unique_ptr<Engine> gEngine; bool blowup = false, screenshot = false, premult = false, escape = false; void SaveScreenCapture(const std::string& FileName, DE::ScreenCapture::CaptureInfo& Capture) { DE::MappedTextureSubresource texData; gEngine->immediateContext->MapTextureSubresource( Capture.pTexture, 0, 0, DE::MAP_READ, DE::MAP_FLAG_DO_NOT_WAIT, nullptr, texData); const auto& texDesc = Capture.pTexture->GetDesc(); DE::Image::EncodeInfo Info; Info.Width = texDesc.Width; Info.Height = texDesc.Height; Info.TexFormat = texDesc.Format; Info.KeepAlpha = !premult; Info.pData = texData.pData; Info.Stride = texData.Stride; Info.FileFormat = DE::IMAGE_FILE_FORMAT_PNG; DE::RefCntAutoPtr<DE::IDataBlob> pEncodedImage; DE::Image::Encode(Info, &pEncodedImage); gEngine->immediateContext->UnmapTextureSubresource(Capture.pTexture, 0, 0); DE::FileWrapper pFile(FileName.c_str(), EFileAccessMode::Overwrite); if(pFile) { auto res = pFile->Write(pEncodedImage->GetDataPtr(), pEncodedImage->GetSize()); pFile.Close(); } } void saveScreenShot() { gEngine->immediateContext->SetRenderTargets( 0, nullptr, nullptr, DE::RESOURCE_STATE_TRANSITION_MODE_NONE); DE::ScreenCapture sc(gEngine->device); sc.Capture(gEngine->swapChain, gEngine->immediateContext, 0); while(!sc.HasCapture()) gEngine->device->IdleGPU(); auto cap = sc.GetCapture(); SaveScreenCapture("dump.png", cap); } std::unique_ptr<DE::DurationQueryHelper> query; void initGPUTimer(GPUtimer* timer) { memset(timer, 0, sizeof(GPUtimer)); timer->supported = gEngine->device->GetDeviceCaps().Features.TimestampQueries; if(timer->supported) query = std::make_unique<DE::DurationQueryHelper>(gEngine->device, 100); } void startGPUTimer(GPUtimer* timer) { if(!timer->supported) return; query->Begin(gEngine->immediateContext); } bool stopGPUTimer(GPUtimer* timer, float* time) { if(!timer->supported) return 0; double res; if(query->End(gEngine->immediateContext, res)) { *time = static_cast<float>(res); return true; } return false; } #ifdef D3D11_SUPPORTED #include <d3d11.h> #endif // D3D11_SUPPORTED #ifdef D3D12_SUPPORTED #include <d3d12.h> #endif // D3D12_SUPPORTED DE::Uint8 getQualityLevel() { auto dev = gEngine->device->GetDeviceCaps().DevType; void* nativeHandle = gEngine->swapChain->GetCurrentBackBufferRTV() ->GetTexture() ->GetNativeHandle(); #ifdef D3D11_SUPPORTED if(dev == DE::RENDER_DEVICE_TYPE_D3D11) { auto res = reinterpret_cast<ID3D11Resource*>(nativeHandle); ID3D11Device* device = nullptr; res->GetDevice(&device); UINT level = 0; device->CheckMultisampleQualityLevels(DXGI_FORMAT_R8G8B8A8_UNORM, gEngine->sampleCount, &level); return static_cast<DE::Uint8>(level - 1); } #endif // D3D11_SUPPORTED #ifdef D3D12_SUPPORTED if(dev == DE::RENDER_DEVICE_TYPE_D3D12) { auto res = reinterpret_cast<ID3D12Resource*>(nativeHandle); void* device = nullptr; res->GetDevice(__uuidof(ID3D12Device), &device); D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS data = {}; data.Format = DXGI_FORMAT_R8G8B8A8_UNORM; data.SampleCount = gEngine->sampleCount; data.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE; reinterpret_cast<ID3D12Device*>(device)->CheckFeatureSupport( D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &data, sizeof(data)); return static_cast<DE::Uint8>(data.NumQualityLevels - 1); } #endif // D3D12_SUPPORTED return 0; } LRESULT CALLBACK MessageProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam); int WINAPI WinMain(HINSTANCE instance, HINSTANCE, LPSTR, int cmdShow) { WNDCLASSEX wcex = { sizeof(WNDCLASSEX), CS_HREDRAW | CS_VREDRAW, MessageProc, 0L, 0L, instance, NULL, NULL, NULL, NULL, L"NanoVG", NULL }; RegisterClassExW(&wcex); RECT rc = { 0, 0, 1000, 600 }; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); HWND hwnd = CreateWindowW(L"NanoVG", L"NanoVG", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, instance, NULL); if(!hwnd) { return -1; } ShowWindow(hwnd, cmdShow); UpdateWindow(hwnd); gEngine = std::make_unique<Engine>(hwnd, DE::RENDER_DEVICE_TYPE_VULKAN); DemoData data; NVGcontext* vg = NULL; GPUtimer gpuTimer; PerfGraph fps, cpuGraph, gpuGraph; float cpuTime = 0; initGraph(&fps, GRAPH_RENDER_FPS, "Frame Time"); initGraph(&cpuGraph, GRAPH_RENDER_MS, "CPU Time"); initGraph(&gpuGraph, GRAPH_RENDER_MS, "GPU Time"); auto&& SDesc = gEngine->swapChain->GetDesc(); #ifdef NANOVG_MSAA const auto& colorFmtInfo = gEngine->device->GetTextureFormatInfoExt(SDesc.ColorBufferFormat); const auto& depthFmtInfo = gEngine->device->GetTextureFormatInfoExt(SDesc.DepthBufferFormat); DE::Uint32 supportedSampleCounts = colorFmtInfo.SampleCounts & depthFmtInfo.SampleCounts; while(supportedSampleCounts & (gEngine->sampleCount << 1)) gEngine->sampleCount <<= 1; #endif // NANOVG_MSAA if(gEngine->sampleCount > 1) gEngine->resetRenderTarget(); DE::SampleDesc msaa = {}; msaa.Count = gEngine->sampleCount; msaa.Quality = getQualityLevel(); vg = nvgCreateDE( gEngine->device, gEngine->immediateContext, msaa, SDesc.ColorBufferFormat, SDesc.DepthBufferFormat, static_cast<int>((msaa.Count == 1 ? NVGCreateFlags::NVG_ANTIALIAS : 0) | NVG_ALLOW_INDIRECT_RENDERING | NVGCreateFlags::NVG_STENCIL_STROKES #ifdef _DEBUG | NVGCreateFlags::NVG_DEBUG #endif )); if(loadDemoData(vg, &data) == -1) return -1; initGPUTimer(&gpuTimer); auto lastTime = Clock::now(); float sum = 0.0f; MSG msg = { 0 }; while(WM_QUIT != msg.message && !escape) { if(PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } else { auto cur = Clock::now(); constexpr auto den = Clock::period::den; float delta = static_cast<float>((cur - lastTime).count()) / den; sum += delta; lastTime = cur; int winWidth, winHeight, mx, my, fbWidth, fbHeight; { RECT rect; GetClientRect(hwnd, &rect); winWidth = rect.right - rect.left; winHeight = rect.bottom - rect.top; } { POINT point; GetCursorPos(&point); ScreenToClient(hwnd, &point); mx = point.x; my = point.y; } { auto&& SDesc = gEngine->swapChain->GetDesc(); fbWidth = SDesc.Width; fbHeight = SDesc.Height; } float pxRatio = static_cast<float>(fbWidth) / winWidth; startGPUTimer(&gpuTimer); const float clearA[] = { 0.0f, 0.0f, 0.0f, 1.0f }; const float clearB[] = { 0.3f, 0.3f, 0.32f, 1.0f }; gEngine->updateTarget(premult ? clearA : clearB); nvgBeginFrame(vg, static_cast<float>(winWidth), static_cast<float>(winHeight), pxRatio); renderDemo(vg, static_cast<float>(mx), static_cast<float>(my), static_cast<float>(winWidth), static_cast<float>(winHeight), sum, blowup, &data); renderGraph(vg, 5, 5, &fps); renderGraph(vg, 5 + 200 + 5, 5, &cpuGraph); if(gpuTimer.supported) renderGraph(vg, 5 + 200 + 5 + 200 + 5, 5, &gpuGraph); nvgEndFrame(vg); auto ct = Clock::now(); cpuTime = static_cast<float>((ct - cur).count()) / den; updateGraph(&fps, delta); updateGraph(&cpuGraph, cpuTime); float gpuTime; if(stopGPUTimer(&gpuTimer, &gpuTime)) updateGraph(&gpuGraph, gpuTime); if(gEngine->sampleCount > 1) { // Resolve multi-sampled render taget into the current swap // chain back buffer. auto pCurrentBackBuffer = gEngine->swapChain->GetCurrentBackBufferRTV()->GetTexture(); DE::ResolveTextureSubresourceAttribs RA = {}; RA.SrcTextureTransitionMode = DE::RESOURCE_STATE_TRANSITION_MODE_TRANSITION; RA.DstTextureTransitionMode = DE::RESOURCE_STATE_TRANSITION_MODE_TRANSITION; gEngine->immediateContext->ResolveTextureSubresource( gEngine->msaaColorRTV->GetTexture(), pCurrentBackBuffer, RA); } if(screenshot) { screenshot = false; saveScreenShot(); } gEngine->swapChain->Present(0U); } } freeDemoData(vg, &data); nvgDeleteDE(vg); { std::stringstream ss; ss.precision(5); ss << "Average Frame Time: " << (getGraphAverage(&fps) * 1000.0f) << " ms\n"; ss << " CPU Time: " << (getGraphAverage(&cpuGraph) * 1000.0f) << " ms\n"; ss << " GPU Time: " << (getGraphAverage(&gpuGraph) * 1000.0f) << " ms\n"; std::string str = ss.str(); OutputDebugStringA(str.c_str()); } gEngine.reset(); DestroyWindow(hwnd); UnregisterClassW(wcex.lpszClassName, wcex.hInstance); return 0; } LRESULT CALLBACK MessageProc(HWND wnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_KEYDOWN: { if(wParam == VK_ESCAPE) escape = true; if(wParam == VK_SPACE) { blowup = !blowup; return true; } if(wParam == 'S') { screenshot = 1; return true; } if(wParam == 'P') { premult = !premult; return true; } return false; } case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(wnd, &ps); EndPaint(wnd, &ps); return 0; } case WM_SIZE: if(gEngine) { gEngine->swapChain->Resize(LOWORD(lParam), HIWORD(lParam)); gEngine->resetRenderTarget(); } return 0; case WM_CHAR: if(wParam == VK_ESCAPE) PostQuitMessage(0); return 0; case WM_DESTROY: PostQuitMessage(0); return 0; case WM_GETMINMAXINFO: { LPMINMAXINFO lpMMI = (LPMINMAXINFO)lParam; lpMMI->ptMinTrackSize.x = 320; lpMMI->ptMinTrackSize.y = 240; return 0; } default: return DefWindowProcW(wnd, message, wParam, lParam); } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2004 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef WINDOWSOPFOLDERLISTER_H #define WINDOWSOPFOLDERLISTER_H #include "modules/pi/system/OpFolderLister.h" class WindowsOpFolderLister : public OpFolderLister { public: WindowsOpFolderLister(); ~WindowsOpFolderLister(); OP_STATUS Construct(const uni_char* path, const uni_char* pattern); BOOL Next(); const uni_char* GetFileName() const; const uni_char* GetFullPath() const; OpFileLength GetFileLength() const; BOOL IsFolder() const; private: void UpdateFullPath(); /** * Function that uses the supplied pattern to search for files and directories * * @param handle [out] Gives the status of the search handle. * @param path_pattern [in] The supplied pattern to search for. * @param data [out] The data for the found element. * @return True if there is another file to get, false if all files have been visited. */ BOOL SearchForFirst(HANDLE &handle, const OpString &path_pattern, WIN32_FIND_DATA &data); /** * Function that uses the supplied pattern to search for files and directories * * @param handle [in] Gives the status of the search handle. * @param data [out] The data for the found element. * @return True if there is another file to get, false if all files have been visited. */ BOOL SearchForNext(const HANDLE &handle, WIN32_FIND_DATA &data); WIN32_FIND_DATA m_find_data; HANDLE m_find_handle; OpString m_path_pattern; uni_char* m_path; int m_path_length; DWORD m_drives; int m_drive; }; #endif // !WINDOWSOPFOLDERLISTER_H
// ========================================================================== // $Id: TriangleMesh.h 3765 2013-03-15 19:25:00Z jlang $ // Wrapper code to interface TriangleMesh // TriangleMesh implementation must support VRML reading, normal // generation, setting of normals, vertex (node) access. // ========================================================================== // (C)opyright: // // Jochen Lang // SITE, University of Ottawa // 800 King Edward Ave. // Ottawa, On., K1N 6N5 // Canada. // http://www.site.uottawa.ca // // Creator: Jochen Lang // Email: jlang@site.uottawa.ca // ========================================================================== // $Rev: 3765 $ // $LastChangedBy: jlang $ // $LastChangedDate: 2013-03-15 15:25:00 -0400 (Fri, 15 Mar 2013) $ // ========================================================================== #ifndef WRAPPER_TRIANGLE_MESH_H #define WRAPPER_TRIANGLE_MESH_H #include "TriMeshSimple.h" #include <vector> using std::vector; #include <set> using std::set; using std::multiset; #include <iostream> using std::cout; using std::endl; #include <fstream> using std::ifstream; using std::ofstream; #include <string> #include "g_Part.h" #include "g_Vector.h" #include "geodesic_algorithm_exact.h" // typedef g_Container<g_PEdge *> g_PEdgeContainer; // typedef g_Container<g_Node *> g_NodeContainer; template <class T> struct svector:vector<T> { inline svector() : vector<T>() {} inline svector(int n) : vector<T>(n) {} // already in vector // T operator[](int); }; // Should use a namespace class Coordinate : public TriMeshSimple::Point { // point is really a vec3f which is a typedef from VectorT // geometry subpackage public: inline double x() { return (*this)[0]; } inline double y() { return (*this)[1]; } inline double z() { return (*this)[2]; } inline double DistanceTo(const g_Vector& _oVec) const { return g_Vector(*this).DistanceTo(_oVec); } /* should just work inline Coordinate operator-(Coordinate&) { } */ }; // Should this be a g_Node? /* class Node { */ /* public: */ /* Coordinate coordinate(); */ /* }; */ class Color : public TriMeshSimple::Color { public: inline Color() : TriMeshSimple::Color() {}; inline Color( float _r, float _g, float _b ) : TriMeshSimple::Color( _r, _g, _b ) {} inline Color( const TriMeshSimple::Color& _oCol ) : TriMeshSimple::Color( _oCol ) {} }; class TriangleMesh : public g_Part { private: geodesic::Mesh d_geo_mesh; TriMeshSimple* d_tms; TriMeshSimple::VertexHandle* d_vhandleA; void calcTriMeshSimple(bool addColor=false, bool addNormals=false); svector<g_Vector> d_normals; svector<Color> d_color; public: TriangleMesh(); TriangleMesh( const g_Part& ); TriangleMesh( const TriangleMesh& ); ~TriangleMesh(); TriangleMesh& operator=( const TriangleMesh& ); void init( ifstream&, const std::string& _ext = ".PLY" ); void exportVRML( ofstream&, const std::string& _ext = ".PLY"); void setColorToMesh(svector<Color>&); void calculateVertexNormals( bool _keep = true ); void initGeodesicDistanceCalculation(); double getGeodesicDistance(int, double&, svector<double>&); size_t getNumberOfTriangles(); double getMeshResolution(); void SetNormals(int _id, int _dim, double _val ); void Normals_Resize(); // get normal at node with id g_Vector getNormalAtNode(int _id); }; #endif
// // mainclass.h // GreedyTung // // Created by Helen on 10/13/14. // Copyright (c) 2014 ___IWINLAB___. All rights reserved. // // git test #ifndef GreedyTung_mainclass_h #define GreedyTung_mainclass_h #include <iostream> #include <vector> #include <string> //#include "MapManager.hpp" using namespace std; class Subnet; class Router; class Link; struct traffic_demand{ int source; int destination; float t_d; traffic_demand(int s, int d, float td) : source(s), destination(d), t_d(td*8) {} bool operator < (const traffic_demand& str) const { return (t_d > str.t_d); } }; class Subnet{ int Subnet_ID; int Router_num; int* Router_ID_Arr; public: void set_Subnet_ID(int ID){ Subnet_ID = ID; } int get_Subnet_ID(){ return Subnet_ID; } void increment_Router_num(){ Router_num += 1; } void decrement_Router_num(); }; class Router{ int Router_ID; int address_x, address_y; Subnet* subnet; vector<Link*> Link_vec; public: void set_Router_ID(int r_ID){ Router_ID = r_ID; } int get_Router_ID(){ return Router_ID; } void set_address_x(int add_x){ address_x = add_x; } void set_address_y(int add_y){ address_y = add_y; } int get_address_x(){ return address_x; } int get_address_y(){ return address_y; } void add_Link(Link *lk); vector<Link*> get_Link_vec(){ return Link_vec; } Link *get_inter_Link(int R_ID); }; class Link{ string Link_type; int Link_ID; float capacity, utilized_capacity; vector<Router*> port_router_vec; public: void set_Link_type(string L_type){ Link_type = L_type; } string get_Link_type(){ return Link_type; } void set_Link_ID(int l_id){ Link_ID = l_id; } int get_Link_ID(){ return Link_ID; } float get_capacity(){ return capacity; } float get_utilized_capasity(){ return utilized_capacity; } void set_capacity(float cpt){ capacity = cpt; utilized_capacity = 0; } void add_capacity_utilization(float ult); void minus_capacity_utilization(float ult); bool set_router(Router *port_router); vector<Router*> get_router_arr(){ return port_router_vec; } Router *get_another_router(Router *ori_router); }; struct check_result{ bool result; float unutilized_capa; int r_left, r_right; }; check_result check_route(vector<int> route_vec, float t_d, vector<Router*> routers_vec); void update_routelinks(vector<int> route_vec, float t_d, vector<Router*> routers_vec); void create_longlink(int source, int dest, float t_d, vector<Router*> routers_vec, vector<Link*> &links_vec); #endif
#include "Light.h" Light::Light() { direction = Vector3(0.0f, 0.0f, 0.0f); color = Vector3(1.0f, 1.0f, 1.0f); intensity = 1.0f; } void Light::SetDirection(float x, float y, float z) { direction = Vector3(x, y, z); } void Light::SetColor(float r, float g, float b) { if (r > 1.0f) { r = 1.0f; } else if (r < 0.0f) { r = 0.0f; } if (g > 1.0f) { g = 1.0f; } else if (g < 0.0f) { g = 0.0f; } if (b > 1.0f) { b = 1.0f; } else if (b < 0.0f) { b = 0.0f; } color = Vector3(r, g, b); } void Light::SetIntensity(float value) { intensity = value; } Vector3 & Light::GetDirection() { return direction; } Vector3 & Light::GetColor() { return color; } float & Light::GetIntensity() { return intensity; }
#ifndef AVL_HPP #define AVL_HPP 1 #include "BSTree.hpp" namespace cs202 { template<class Key, class Value> class AVLNode : public BinaryNode<Key, Value> { public: int height; AVLNode() { height = 1; } AVLNode(Key in_key, Value in_value, BinaryNode<Key, Value>* r, BinaryNode<Key, Value>* p) : BinaryNode<Key, Value> (in_key, in_value, r, p) { height = 1; } AVLNode<Key, Value>* get_parent() {return dynamic_cast<AVLNode<Key, Value>*> (this->parent);} AVLNode<Key, Value>* get_root() {return dynamic_cast<AVLNode<Key, Value>*> (this->root);} AVLNode<Key, Value>* get_left() {return dynamic_cast<AVLNode<Key, Value>*> (this->left);} AVLNode<Key, Value>* get_right() {return dynamic_cast<AVLNode<Key, Value>*> (this->right);} }; template <class Key, class Value> class AVL : public BSTree<Key, Value> { private: int max(int a, int b) { return a > b ? a : b; } int get_height_of(AVLNode<Key, Value>* node) { if (node) { if (node->get_left() && node->get_right()) { return 1 + max(node->get_left()->height, node->get_left()->height); } else if (node->get_left()) { return 1 + node->get_left()->height; } else if (node->get_right()) { return 1 + node->get_right()->height; } else { return 1; } } else { return 0; } } // fixes the height of a node, assuming the height of it's subtrees is correct void fix_height_of_node(AVLNode<Key, Value>* node) { node->height = 1 + max(get_height_of(node->get_left()), get_height_of(node->get_right())); } void increase_height_up_tree(AVLNode<Key, Value>* node) { while (node->parent) { AVLNode<Key, Value>* parent = dynamic_cast<AVLNode<Key, Value>* > (node->parent); parent->height = get_height_of(parent); node = parent; } } protected: // AVLNode<Key, Value>* root; virtual AVLNode<Key, Value>* put_under_node(BinaryNode<Key, Value>* node, const Key& key, const Value& value) override { if (key == node->key) { node->val = value; return dynamic_cast<AVLNode<Key, Value>*> (node); } else if (key > node->key) { if (node->right) { return put_under_node(node->right, key, value); } else { node->right = new AVLNode<Key, Value> (key, value, this->root, node); return dynamic_cast<AVLNode<Key, Value>*> (node->right); } } else if (key < node->key) { if (node->left) { return put_under_node(node->left, key, value); } else { node->left = new AVLNode<Key, Value> (key, value, this->root, node); return dynamic_cast<AVLNode<Key,Value>*> (node->left); } } else { return nullptr; // something has gone wrong if this happens } } int compute_balance_factor(AVLNode<Key, Value>* node) { if (node->left && node->right) { return get_height_of(node->get_left()) - get_height_of(node->get_right()); } else if (node->get_left()) { return get_height_of(node->get_left()); } else { return - get_height_of(node->get_right()); } } void fixup_at(AVLNode<Key, Value>* inserted_node) { AVLNode<Key, Value>* cur = inserted_node; if (!cur) { return; } while (cur->parent) { cur = cur->get_parent(); int bf = compute_balance_factor(cur); if (bf == 2) { AVLNode<Key, Value>* left = cur->get_left(); if (compute_balance_factor(left) == 1) { this->right_rotation_at(cur); fix_height_of_node(cur); fix_height_of_node(left); } else { if (compute_balance_factor(left) == -1) { this->left_rotation_at(left); } this->right_rotation_at(cur); fix_height_of_node(cur); fix_height_of_node(left); fix_height_of_node(cur->get_parent()); } } else if (bf == -2) { AVLNode<Key, Value>* right = cur->get_right(); if (compute_balance_factor(right) == -1) { this->left_rotation_at(cur); fix_height_of_node(cur); fix_height_of_node(right); } else { if (compute_balance_factor(right) == 1) { this->right_rotation_at(right); } this->left_rotation_at(cur); fix_height_of_node(cur); fix_height_of_node(right); fix_height_of_node(cur->get_parent()); } } else { fix_height_of_node(cur); } } } public: virtual void put(const Key& key, const Value& value) override { if (!this->root) { this->root = new AVLNode<Key, Value>(key, value, nullptr, nullptr); this->root->root = this->root; dynamic_cast<AVLNode<Key, Value>* > (this->root)->height = 1; // BinaryTree<Key, Value>::root = dynamic_cast<BinaryNode<Key, Value>* > (root); } else { AVLNode<Key, Value>* inserted_node = put_under_node(this->root, key, value); increase_height_up_tree(inserted_node); fixup_at(inserted_node); } } virtual void remove(const Key& key) override { auto node_to_remove = this->has_child_with_key(this->root, key); auto parent = node_to_remove->parent; if (!node_to_remove) { throw std::runtime_error("Can't remove a nonexisting key"); } if (!node_to_remove->left && !node_to_remove->right) { // node is leaf if (node_to_remove->parent) { if (node_to_remove->parent->left == node_to_remove) { node_to_remove->parent->left = nullptr; } else if (node_to_remove->parent->right == node_to_remove) { node_to_remove->parent->right = nullptr; } } else { // node_to_remove must be the root this->root = nullptr; } parent = node_to_remove->parent; delete node_to_remove; } else if (node_to_remove->left && node_to_remove->right) { // node has two children auto successor = this->find_descendant_just_larger_than_key(this->root, node_to_remove->key); node_to_remove->key = successor->key; node_to_remove->val = successor->val; if (successor->parent->left == successor) { successor->parent->left = nullptr; } else { successor->parent->right = nullptr; } parent = successor->parent; delete successor; } else { // node has one child BinaryNode<Key, Value>* child; if (node_to_remove->left) { child = node_to_remove->left; } else { child = node_to_remove->right; } if (node_to_remove->parent) { if (node_to_remove->parent->left == node_to_remove) { node_to_remove->parent->left = child; } else { node_to_remove->parent->right = child; } } else { this->root = child; child->root = child; } parent = node_to_remove->parent; delete node_to_remove; } auto avl_parent = dynamic_cast<AVLNode<Key, Value>*> (parent); fixup_at(avl_parent); } virtual int getHeight() override { AVLNode<Key, Value>* avl_root = dynamic_cast<AVLNode<Key, Value>* > (this->root); return avl_root->height; } }; } #endif /* ifndef AVL_HPP */
#define BUILDING_NODE_EXTENSION #include <node.h> #include <v8.h> #include <Znode.h> using namespace v8; using namespace node; void InitAll(Handle<Object> target) { HandleScope scope; Znode::Init(target); } NODE_MODULE(znode,InitAll)
// // Created by Deepak Ramalingam on 12/6/20. // #include <SDL.h> #include <SDL_image.h> #include "../headers/graphics.h" #include "../headers/globals.h" /* * Graphics class * Holds all information dealing with graphics */ Graphics::Graphics() { SDL_CreateWindowAndRenderer(globals::SCREEN_WIDTH, globals::SCREEN_HEIGHT, 0, &this->_window, &this->_renderer); SDL_SetWindowTitle(this->_window, "MMZ++"); SDL_ShowCursor(0); if(globals::FULLSCREEN) { toggleFullScreenMode(); } else { toggleWindowedMode(); } } Graphics::~Graphics() { SDL_DestroyWindow(this->_window); } SDL_Surface* Graphics::loadImage(const std::string &filePath) { if(this->_spriteSheets.count(filePath) == 0) { this->_spriteSheets[filePath] = IMG_Load(filePath.c_str()); } return this->_spriteSheets[filePath]; } void Graphics::blitSurface(SDL_Texture *source, SDL_Rect *sourceRectangle, SDL_Rect *destinationRectangle) { SDL_RenderCopy(this->_renderer, source, sourceRectangle, destinationRectangle); } void Graphics::flip() { SDL_RenderPresent(this->_renderer); } void Graphics::clear() { SDL_RenderClear(this->_renderer); } SDL_Renderer* Graphics::getRenderer() const { return this->_renderer; } void Graphics::toggleWindowedMode() { SDL_SetWindowFullscreen(this->_window, 0); SDL_SetWindowSize(this->_window, globals::SCREEN_WIDTH, globals::SCREEN_HEIGHT); } void Graphics::toggleFullScreenMode() { SDL_SetWindowFullscreen(this->_window, 1); }
#include <iostream> #include <algorithm> using namespace std; #define MOD 1000000007 // 10^9 + 7 typedef long long ll; // 階乗を計算 (MODなし) ll factorial(ll n) { if (n == 1) return 1; return n * factorial(n-1); } // 階乗を計算 (MODあり) ※問題のMODと合致しているかチェック! ll factorial_mod(ll n) { ll ans = 1; for (ll i = n; i > 0; --i) { ans = (ans % MOD) * (i % MOD) % MOD; } return ans; } int main() { ll a; cin >> a; cout << factorial_mod(a) << endl; }
#include <iostream> #include <string> #include "smart_bag.h" using namespace std; int main(){ SmartBag<string> b1; b1.add("Hello"); b1.add("World1"); cout << b1 << endl; return 0; }
#include <conio.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <string.h> #include <math.h> #include <locale.h> #include <ctype.h> float valor1,valor2; int main() { ret1: printf("\nInsira um valor\n"); scanf("%f",&valor1); printf("\nInsira mais um valor\n"); ret: scanf("%f",&valor2); if(valor1>valor2) { printf("\nInsira novamente o segundo valor\n"); goto ret; } goto ret1; }
#pragma once #include "..//ACTEffect.h" #include "IAct.h" class CAct_Dist : public IAct { public : void Fire( Monster* me, Monster* target, const wchar_t* beamEffectPath, const wchar_t* soundPath, float range, float baseDamage, CVector3 effectScale = { 3.5,3.5,3.5 } ); //ダメージを与え終わったらtrueを返します bool DamageCalc(); private: bool IsHitting(Monster* mon, Monster* me); CEffect* m_beamefk = nullptr; CVector3 crs = CVector3::Zero(); CVector3 m_targetPosition = CVector3::Zero(); Monster* m_me = nullptr; CVector3 efs = CVector3::One(); };
#pragma once #include "Tool.h" #include "AnimationAsset.h" #include "AppColors.h" namespace CAE { class SelectionTool : public Tool { private: // sf::FloatRect selectionRect; sf::FloatRect second_draw; sf::RectangleShape shape; bool ButtonPressed; bool once; // bool Selection; sf::IntRect rect; void assetUpdated() override {} void calcRect(sf::Rect<int> selectionRect) { if(selectionRect.width < 0) { selectionRect.left += selectionRect.width; selectionRect.width = abs(selectionRect.width); } if(selectionRect.height < 0) { selectionRect.top += selectionRect.height; selectionRect.height = abs(selectionRect.height); } sf::FloatRect selection; bool f = false; for(auto& g : *asset) { g->setSelected(false); for(auto& part : *g) { part->setSelected(false); if(auto r = part->getRect(); selectionRect.left <= r.left && selectionRect.top <= r.top && (selectionRect.left + selectionRect.width) >= (r.left + r.width) && (selectionRect.top + selectionRect.height) >= (r.top + r.height)) { part->setSelected(true); g->setSelected(true); selection.width = std::max(r.left + r.width, selection.left + selection.width); selection.height = std::max(r.top + r.height, selection.top + selection.height); if(!f) { selection.left = r.left; selection.top = r.top; f = true; } else { selection.left = std::min(r.left, selection.left); selection.top = std::min(r.top, selection.top); } if(selection.left < 0) selection.width += abs(selection.left); else selection.width -= selection.left; if(selection.top < 0) selection.height += abs(selection.top); else selection.height -= selection.top; } } } shape.setPosition(sf::Vector2f(selection.left, selection.top)); shape.setSize(sf::Vector2f(selection.width, selection.height)); } public: SelectionTool(EMHolder& m, const sf::Texture& t, sf::RenderWindow& window) : Tool(m, t, window) { shape.setFillColor(sf::Color::Transparent); shape.setOutlineColor(CAE::Colors::OutLine_r); shape.setOutlineThickness(1); } void Enable() override { EventsHolder["SelectionTool"].setEnable(true); } void Disable() override { EventsHolder["SelectionTool"].setEnable(false); } void Init() override { auto& eManager = EventsHolder.addEM("SelectionTool", false); eManager.addEvent(KBoardEvent::KeyPressed(sf::Keyboard::Escape), [this](sf::Event&) { for(auto& g : *asset) for(auto& part : *g) part->setSelected(false); shape.setPosition(sf::Vector2f(0, 0)); shape.setSize(sf::Vector2f(0, 0)); }); // eManager.addEvent(KBoardEvent::KeyPressed(sf::Keyboard::LControl), [this](sf::Event&) // { // Selection = true; // }); // eManager.addEvent(KBoardEvent::KeyReleased(sf::Keyboard::LControl), [this](sf::Event&) // { // Selection = false; // }); eManager.addEvent(MouseEvent::ButtonPressed(sf::Mouse::Left), [this](sf::Event&) { ButtonPressed = true; }); eManager.addEvent(MouseEvent::ButtonReleased(sf::Mouse::Left), [this](sf::Event&) { if(once) { calcRect(rect); once = false; // Selection = false; rect = {}; History_data::NeedSnapshot(); } ButtonPressed = false; shape.setPosition(sf::Vector2f(0, 0)); shape.setSize(sf::Vector2f(0, 0)); }); eManager.addEvent(MouseEvent(sf::Event::MouseMoved), [this](sf::Event&) { if(!EventsHolder.isCtrlPressed() && ButtonPressed) { if(!once) { once = true; rect.left = EventsHolder.currMousePos().x; rect.top = EventsHolder.currMousePos().y; } else { auto delta = sf::Vector2f(rect.left, rect.top) - EventsHolder.currMousePos(); rect.width = -delta.x; rect.height = -delta.y; } shape.setPosition(sf::Vector2f(rect.left, rect.top)); shape.setSize(sf::Vector2f(rect.width, rect.height)); } }); eManager.addEvent(MouseEvent::ButtonPressed(sf::Mouse::Left), [this](sf::Event&) { if(EventsHolder.isCtrlPressed()) for(auto& g : *asset) for(auto& part : *g) { if(part->getRect().contains(EventsHolder.currMousePos())) { part->setSelected(!part->isSelected()); g->setSelected(part->isSelected()); return; } } }); } void update() override { if(ImGui::IsAnyWindowHovered()) { //rect = {}; // shape.setPosition(sf::Vector2f(0, 0)); //shape.setSize(sf::Vector2f(0, 0)); once = ButtonPressed = false; } } void draw(sf::RenderWindow& w) override { w.draw(shape); } }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright 2002-2006 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Peter Karlsson */ #ifndef OPPREFSLISTENER_H #define OPPREFSLISTENER_H #include "modules/prefs/prefsmanager/opprefscollection.h" /** * Interface implemented by all classes that wish to listen to * changes in an OpPrefsCollection. * * To do that, make your class inherit this one, and call * OpPrefsCollection::RegisterListenerL(this) on the collection(s) you * wish to listen to. */ class OpPrefsListener { public: /** Standard destructor. Needs to be virtual due to inheritance. */ virtual ~OpPrefsListener() {} /** Signals a change in an integer preference. * * @param id Identity of the collection that has changed the value. * @param pref Identity of the preference. This is the integer * representation of the enumeration value used by the * associated OpPrefsCollection. * @param newvalue The new value of the preference. */ virtual void PrefChanged(OpPrefsCollection::Collections /* id */, int /* pref */, int /* newvalue */) {} /** Signals a change in a string preference. * * @param id Identity of the collection that has changed the value. * @param pref Identity of the preference. This is the integer * representation of the enumeration value used by the * associated OpPrefsCollection. * @param newvalue The new value of the preference. */ virtual void PrefChanged(OpPrefsCollection::Collections /* id */, int /* pref */, const OpStringC & /* newvalue */) {} #ifdef PREFS_HOSTOVERRIDE /** Signals the addition, change or removal of a host override. * * @param id Identity of the collection that has changed the value. * @param hostname The affected host name. */ virtual void HostOverrideChanged(OpPrefsCollection::Collections /* id */, const uni_char * /* hostname */) {} #endif }; #endif // OPPREFSLISTENER_H
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define REP(i,n) for(int i=0; i<n; i++) #define REP_R(i,n,m) for(int i=m; i<n; i++) #define MAX 100 int main() { int a, b; cin >> a >> b; if (a*b == 15) { cout << "*" << endl; } else if (a+b == 15) { cout << "+" << endl; } else { cout << "x" << endl; } }
#pragma once #include "object\GameObject.h" #include "Bomb.h" class Player : public GameObject { Bomb bomb; Vector2 lastPos; int lifeNum; int bombNum; int power; int point; int graze; bool isSlowMode; bool lockSlowMode; int shotCount; int muki; public: Player(); Player(Vector2 position); ~Player() = default; void Init() override; void Fin() override; void Update() override; void Draw() const override; void OnCollide(GameObject* obj) override; void Move(Vector2 vec); void Shot(); void SlowMode(); void Bomb(); void DrawPlayerInfo(Vector2 pos) const; };
/* * * Copyright 2015-2016, Google Inc. * 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <map> #include "acoross_generator.h" #include "src/compiler/cpp_generator_helpers.h" #include "src/compiler/config.h" #include <sstream> namespace acoross_rpc_cpp_generator { namespace { template <class T> grpc::string as_string(T x) { std::ostringstream out; out << x; return out.str(); } bool NoStreaming(const grpc::protobuf::MethodDescriptor *method) { return !method->client_streaming() && !method->server_streaming(); } bool ClientOnlyStreaming(const grpc::protobuf::MethodDescriptor *method) { return method->client_streaming() && !method->server_streaming(); } bool ServerOnlyStreaming(const grpc::protobuf::MethodDescriptor *method) { return !method->client_streaming() && method->server_streaming(); } bool BidiStreaming(const grpc::protobuf::MethodDescriptor *method) { return method->client_streaming() && method->server_streaming(); } grpc::string FilenameIdentifier(const grpc::string &filename) { grpc::string result; for (unsigned i = 0; i < filename.size(); i++) { char c = filename[i]; if (isalnum(c)) { result.push_back(c); } else { static char hex[] = "0123456789abcdef"; result.push_back('_'); result.push_back(hex[(c >> 4) & 0xf]); result.push_back(hex[c & 0xf]); } } return result; } } // namespace //acoross changed grpc::string GetHeaderPrologue(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); grpc::protobuf::io::Printer printer(&output_stream, '$'); std::map<grpc::string, grpc::string> vars; vars["filename"] = file->name(); vars["filename_identifier"] = FilenameIdentifier(file->name()); vars["filename_base"] = grpc_generator::StripProto(file->name()); printer.Print(vars, "// Generated by the acoross-rpc protobuf plugin.\n"); printer.Print(vars, "// If you make any local change, they will be lost.\n"); printer.Print(vars, "// source: $filename$\n"); printer.Print(vars, "#ifndef ACOROSS_RPC_$filename_identifier$__INCLUDED\n"); printer.Print(vars, "#define ACOROSS_RPC_$filename_identifier$__INCLUDED\n"); printer.Print(vars, "\n"); printer.Print(vars, "#include \"$filename_base$.pb.h\"\n"); printer.Print(vars, "\n"); } return output; } //acoross changed grpc::string GetHeaderIncludes(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string temp = "#include <SDKDDKVer.h>\n" "#include <boost/asio.hpp>\n" "#include <acoross/rpc/rpc_service.h>\n" "#include <acoross/rpc/rpc_stub.h>\n" "#include <acoross/rpc/rpc_macros.h>\n" "\n"; if (!file->package().empty()) { std::vector<grpc::string> parts = grpc_generator::tokenize(file->package(), "."); for (auto part = parts.begin(); part != parts.end(); part++) { temp.append("namespace "); temp.append(*part); temp.append(" {\n"); } temp.append("\n"); } return temp; } void PrintHeaderService(grpc::protobuf::io::Printer *printer, const grpc::protobuf::ServiceDescriptor *service, std::map<grpc::string, grpc::string> *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, "class $Service$ final {\n" " public:\n"); printer->Indent(); // enum printer->Print("enum Protocol\n{\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { printer->Print(service->method(i)->name().c_str()); printer->Print(",\n"); } printer->Outdent(); printer->Print("};\n\n"); // Server side printer->Print( "class Service : public ::acoross::rpc::RpcService \n" "{\n" "public:\n"); printer->Indent(); printer->Print("Service(::boost::asio::io_service& io_service, ::boost::asio::ip::tcp::socket&& socket);\n"); printer->Print("virtual ~Service() {}\n"); //TODO: doing here!! printer->Print("\n"); printer->Outdent(); printer->Print("private:\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Method"] = service->method(i)->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(service->method(i)->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(service->method(i)->output_type(), true); printer->Print(*vars, "DEF_SERVICE($Method$, $Request$, $Response$)\n"); } printer->Print("\n"); printer->Outdent(); printer->Print("};\n\n"); // Client side printer->Print( "class Stub : public ::acoross::rpc::RpcStub\n" "{\n" "public:\n"); printer->Indent(); printer->Print("Stub(::boost::asio::io_service& io_service, ::boost::asio::ip::tcp::socket&& socket);\n"); printer->Print("virtual ~Stub() {}\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Method"] = service->method(i)->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(service->method(i)->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(service->method(i)->output_type(), true); printer->Print(*vars, "DEF_STUB($Method$, $Request$, $Response$)\n"); } printer->Outdent(); printer->Print("};\n\n"); printer->Outdent(); printer->Print("};\n\n"); } grpc::string GetHeaderServices(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); grpc::protobuf::io::Printer printer(&output_stream, '$'); std::map<grpc::string, grpc::string> vars; // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); if (!file->package().empty()) { vars["Package"].append("."); } if (!params.services_namespace.empty()) { vars["services_namespace"] = params.services_namespace; printer.Print(vars, "\nnamespace $services_namespace$ {\n\n"); } for (int i = 0; i < file->service_count(); ++i) { PrintHeaderService(&printer, file->service(i), &vars); printer.Print("\n"); } if (!params.services_namespace.empty()) { printer.Print(vars, "} // namespace $services_namespace$\n\n"); } } return output; } grpc::string GetHeaderEpilogue(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); grpc::protobuf::io::Printer printer(&output_stream, '$'); std::map<grpc::string, grpc::string> vars; vars["filename"] = file->name(); vars["filename_identifier"] = FilenameIdentifier(file->name()); if (!file->package().empty()) { std::vector<grpc::string> parts = grpc_generator::tokenize(file->package(), "."); for (auto part = parts.rbegin(); part != parts.rend(); part++) { vars["part"] = *part; printer.Print(vars, "} // namespace $part$\n"); } printer.Print(vars, "\n"); } printer.Print(vars, "\n"); printer.Print(vars, "#endif // ACOROSS_RPC_$filename_identifier$__INCLUDED\n"); } return output; } //done by acoross grpc::string GetSourcePrologue(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); grpc::protobuf::io::Printer printer(&output_stream, '$'); std::map<grpc::string, grpc::string> vars; vars["filename"] = file->name(); vars["filename_base"] = grpc_generator::StripProto(file->name()); printer.Print(vars, "// Generated by the acoross-rpc protobuf plugin.\n"); printer.Print(vars, "// If you make any local change, they will be lost.\n"); printer.Print(vars, "// source: $filename$\n\n"); printer.Print(vars, "#include \"$filename_base$.pb.h\"\n"); printer.Print(vars, "#include \"$filename_base$.rpc.h\"\n"); printer.Print(vars, "\n"); } return output; } grpc::string GetSourceIncludes(const grpc::protobuf::FileDescriptor *file, const Parameters &param) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); grpc::protobuf::io::Printer printer(&output_stream, '$'); std::map<grpc::string, grpc::string> vars; //printer.Print(vars, "#include <grpc++/impl/codegen/sync_stream.h>\n"); //printer.Print("\n"); if (!file->package().empty()) { std::vector<grpc::string> parts = grpc_generator::tokenize(file->package(), "."); for (auto part = parts.begin(); part != parts.end(); part++) { vars["part"] = *part; printer.Print(vars, "namespace $part$ {\n"); } } printer.Print(vars, "\n"); } return output; } void PrintSourceService(grpc::protobuf::io::Printer *printer, const grpc::protobuf::ServiceDescriptor *service, std::map<grpc::string, grpc::string> *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, "$Service$::Service::Service(" "::boost::asio::io_service& io_service, ::boost::asio::ip::tcp::socket&& socket)\n" "\t: ::acoross::rpc::RpcService(io_service, std::move(socket))\n"); printer->Print("{\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { const grpc::protobuf::MethodDescriptor *method = service->method(i); (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); printer->Print(*vars, "REGISTER_SERVICE($Method$, $Request$, $Response$)\n"); } printer->Outdent(); printer->Print("}\n"); printer->Print("\n"); printer->Print(*vars, "$Service$::Stub::Stub(::boost::asio::io_service& io_service, ::boost::asio::ip::tcp::socket&& socket)\n" "\t: ::acoross::rpc::RpcStub(io_service, std::move(socket))\n" "{}\n\n"); } grpc::string GetSourceServices(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string output; { // Scope the output stream so it closes and finalizes output to the string. grpc::protobuf::io::StringOutputStream output_stream(&output); grpc::protobuf::io::Printer printer(&output_stream, '$'); std::map<grpc::string, grpc::string> vars; // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); if (!file->package().empty()) { vars["Package"].append("."); } if (!params.services_namespace.empty()) { vars["ns"] = params.services_namespace + "::"; vars["prefix"] = params.services_namespace; } else { vars["ns"] = ""; vars["prefix"] = ""; } for (int i = 0; i < file->service_count(); ++i) { PrintSourceService(&printer, file->service(i), &vars); printer.Print("\n"); } } return output; } //done by acoross grpc::string GetSourceEpilogue(const grpc::protobuf::FileDescriptor *file, const Parameters &params) { grpc::string temp; if (!file->package().empty()) { std::vector<grpc::string> parts = grpc_generator::tokenize(file->package(), "."); for (auto part = parts.begin(); part != parts.end(); part++) { temp.append("} // namespace "); temp.append(*part); temp.append("\n"); } temp.append("\n"); } return temp; } } // namespace acoross_rpc_cpp_generator
#ifndef RENDERER_H #define RENDERER_H #include <vector> #include <GL/gl.h> #include <GL/glext.h> class App; extern App* a; class Model; class Entity; class Renderer { public: Renderer(); void registerEntity(Entity* e); void render(GLuint); ~Renderer(); protected: private: std::vector<Entity*> _es; GLuint registerBuffer(int sz, const GLvoid* data, GLenum usage=GL_STATIC_DRAW); void registerModel(Model* m); }; #endif // RENDERER_H
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "CCWebView.h" USING_NS_CC; USING_NS_CC_WEBVIEW; class HelloWorld : public cocos2d::CCLayer, public cocos2d::webview_plugin::CCWebViewDelegate { public: // Method 'init' in cocos2d-x returns bool, instead of 'id' in cocos2d-iphone (an object pointer) virtual bool init(); // there's no 'id' in cpp, so we recommend to return the class instance pointer static cocos2d::CCScene* scene(); // a selector callback void menuCloseCallback(CCObject* pSender); // preprocessor macro for "static create()" constructor ( node() deprecated ) CREATE_FUNC(HelloWorld); void showResult(std::string* str1, std::string* str2); void callbackFromJS(CCWebView *webview, CCString *message); }; #endif // __HELLOWORLD_SCENE_H__
// // Copyright (C) BlockWorks Consulting Ltd - All Rights Reserved. // Unauthorized copying of this file, via any medium is strictly prohibited. // Proprietary and confidential. // Written by Steve Tickle <Steve@BlockWorks.co>, September 2014. // #include <stdio.h> #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include <unistd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> #include <stddef.h> #include <pthread.h> #include "Reactor.h" //#include "GeneratedScheduler.hpp" #include "Scheduler.hpp" #include "PulseWidthModulator.hpp" #include "UARTTransmitter8N1.hpp" #include "UARTReceiver8N1.hpp" #include "NoOperation.hpp" #include "I2CMaster.hpp" extern "C" { #include "Timestamp.h" #include "DebugText.h" #include "SharedMemory.h" #include "ErrorHandling.h" #include "Utilities.h" //#include "MessageBox.h" } uint8_t* counter64Base = 0; volatile uint8_t* counterControl; volatile uint32_t* counterValue; void SetupCounter64() { const uint32_t BASE = 0x01F01C00; // CPUCFG const uint32_t PAGE_SIZE = 4096; const uint32_t BASEPage = BASE & ~(PAGE_SIZE-1); uint32_t BASEOffsetIntoPage = BASE - BASEPage; int mem_fd = 0; uint8_t* regAddrMap = NULL; if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) { perror("can't open /dev/mem"); exit (1); } regAddrMap = (uint8_t*)mmap( NULL, BASEOffsetIntoPage+(PAGE_SIZE*2), PROT_READ|PROT_WRITE|PROT_EXEC,// Enable reading & writting to mapped memory MAP_SHARED, //Shared with other processes mem_fd, BASEPage); if (regAddrMap == NULL) { perror("mmap error"); close(mem_fd); exit (1); } uint32_t* pvalue = (uint32_t*)(regAddrMap + BASEOffsetIntoPage); counter64Base = (uint8_t*)pvalue; //counterValue = (volatile uint64_t*)(counter64Base+0x0284); counterValue = (volatile uint32_t*)(counter64Base+0x0284); counterControl = (uint8_t*)(counter64Base+0x0280); //uint32_t* counterControl = (uint32_t*)(counter64Base+0x0280); } uint64_t GetCounter64() { *counterControl = 2; uint32_t value = *counterValue; return (uint64_t)value; } SharedMemoryLayout* sharedMemory; void* entryPoint(void*) { while(true) { #if 0 sharedMemory->channel0In.Put( 0x01 ); sharedMemory->channel0In.Put( 0x02 ); sharedMemory->channel0In.Put( 0x04 ); sharedMemory->channel0In.Put( 0x08 ); sharedMemory->channel0In.Put( 0x10 ); sharedMemory->channel0In.Put( 0x20 ); sharedMemory->channel0In.Put( 0x40 ); sharedMemory->channel0In.Put( 0x80 ); #endif #if 0 i2cMaster.InsertIntoTxFIFO( 0x01 ); i2cMaster.InsertIntoTxFIFO( 0x02 ); i2cMaster.InsertIntoTxFIFO( 0x04 ); i2cMaster.InsertIntoTxFIFO( 0xff ); i2cMaster.InsertIntoTxFIFO( 0xff ); i2cMaster.InsertIntoTxFIFO( 0x20 ); i2cMaster.InsertIntoTxFIFO( 0x40 ); i2cMaster.InsertIntoTxFIFO( 0x80 ); i2cMaster.Transmit(); #endif #if 0 static uint64_t previousValue = 0; uint64_t thisValue = GetTimestamp(); uint64_t delta; if(thisValue > previousValue) { delta = thisValue - previousValue; } else { delta = thisValue + (0xffffffff-previousValue); } //DebugPrintf("%lld.\n",delta); previousValue = thisValue; #endif #if 0 // // // for(uint32_t i=0; i<256; i++) { DebugPrintf("%d\n",pwm.deltas[i]); } #endif #if 0 { static uint32_t period; static int32_t delta = 1; if(period < 1) { delta = 1; } if(period >= 500) { delta = -1; } period += delta; //pwm.SetPeriod(period); } #endif usleep(100000); //sleep(1); } } // // // int main() { DebugPrintf("\nReactorControl.\n"); SetupCounter64(); // // // sharedMemory = (SharedMemoryLayout*)SharedMemoryMasterInitialise(0x00000001); sharedMemory->inletToControl.InitialiseAsReader(); sharedMemory->controlToOutlet.InitialiseAsWriter(); // // // //MessageBoxInitialise(); // // Wait until we are fully connected. // DebugPrintf("Waiting for connections.\n"); while( (sharedMemory->inletToControl.numberOfWriters == 0) ) { //printf("%llx\n",GetCounter64()); } DebugPrintf("Connected.\n"); // // // typedef UARTTransmitter8N1<10,3, 0x01, 1024> TxType; typedef UARTReceiver8N1<8,3, 0x02, 1024> RxType; typedef PWM<1, 0, 0x02, ChannelBufferType> PWMType1; typedef PWM<1, 0, 0x10, ChannelBufferType> PWMType2; typedef I2CMaster<10, 0x01,0x10, ChannelBufferType> I2CMasterType2; typedef I2CMaster<100, 0x04,0x08, ChannelBufferType> I2CMasterType; //TxType one; //RxType two; NoOperation nop; PWMType1 pwm(sharedMemory->channel1In); PWMType2 pwm2(sharedMemory->channel2In); I2CMasterType i2cMaster(sharedMemory->channel0In, sharedMemory->channel0Out, sharedMemory->channel0Command ); I2CMasterType2 i2cMaster2(sharedMemory->channel2In, sharedMemory->channel2Out, sharedMemory->channel2Command ); Scheduler< 100, PWMType1, I2CMasterType, I2CMasterType2, I2CMasterType2, I2CMasterType2, I2CMasterType2, PWMType2, PWMType2 > scheduler(pwm, i2cMaster, i2cMaster2, i2cMaster2, i2cMaster2,i2cMaster2, pwm2, pwm2); // // // //pthread_t threadId; //pthread_create(&threadId, NULL, entryPoint, NULL); // // // while(true) { static uint8_t outputValue; // // Get the current input values. // uint8_t value = sharedMemory->inletToControl.Get(); //uint32_t value32 = 0; //MessageBoxRead(1, &value32); //uint8_t value = value32&0xff; //DebugPrintf("rx %02x\n",value); // // Process the input. // scheduler.PeriodicProcessing( value, outputValue ); // // Set the outputs. // sharedMemory->controlToOutlet.Put( outputValue ); } }
#ifndef CHECKER_H #define CHECKER_H #include <string> #include <vector> #include <map> using namespace std; class Checker{ protected: map<string, int> Dictionary; vector<string> Matches; string wordWithHigestOcurrence; public: Checker(); Checker(map<string, int> Dic); void setDictionary(map<string, int> Dic); void functionAlteration(string word); void functionDeletion(string word); void functionInsertion(string word); void functionTransposition(string word); vector<string> getMatches(); vector<string> getMatches(string word); string wordWithHighestOccurence(); string getWordWithHighestOccurence(); ~Checker(); }; #endif
# include<iostream> # include<cmath> using namespace std; int main(void) { int grid[10][55]; int sol[10][55]; int rows = 0; cin >> rows; for(int i = 0; i < rows; i++) { for(int j = 0; j <= i; j++) { cin >> grid[i][j]; sol[i][j] = grid[i][j]; } } for(int i = rows-1; i >= 1; i--) { for(int j = 0; j <= i; j++) { sol[i-1][j] += max(sol[i][j],sol[i][j+1]); } } cout << "Enter number of rows: Enter values for array: " << endl; cout << "Maximum path value = " << sol[0][0] << endl; }
#ifndef __OPERATION_H__ #define __OPERATION_H__ #include <iostream> #include "component.h" class Operation : public Base { protected: Base* value1; Base* value2; public: virtual double evaluate() = 0; Operation(); }; #endif
#ifndef SUPPORT_VECTOR_MACHINE_H #define SUPPORT_VECTOR_MACHINE_H #include "Common.h" #include "Feature.h" #include "PascalImageDatabase.h" //! Support Vector Machine Class /*! This class is a wrapper for LIBSVM that allows the SVM training from the image database. It creates a primal form of the weights so it can be used along with the OPENCV framework. */ class SupportVectorMachine { private: struct svm_parameter _param; // set by parse_command_line struct svm_problem _prob; // set by read_problem struct svm_model *_model; struct svm_node *_x_space; svm_node *_data; private: //! De allocate memory void _deinit(); public: //! Constructor SupportVectorMachine(); //! Loads SVM with user-defined parameters /*! \param params ParameterMap containing the SVM configuration */ SupportVectorMachine(const ParametersMap &params); //! Loads SVM model from file /*! \param modelFName Path to a file containing the SVM configuration */ SupportVectorMachine(const std::string &modelFName); //! Destructor ~SupportVectorMachine(); //! Train the SVM model void train(const std::vector<float> &labels, FeatureCollection &features, std::string svmModelFName); //! Predict the decision value of a feature /*! Run classifier on feature, size of feature must match one used for model training. \param feature HOG calculated features from an image */ float predict(const Feature &feature) const; //! Predict the decision value of a feature /*! Run classifier on feature, size of feature must match one used for model training. \param feature HOG calculated features from an image */ //float predict(const vector<float> &feature) const; //! Predict the label of a feature /*! Run classifier on feature, size of feature must match one used for model training. \param feature HOG calculated features from an image */ float predictLabel(const Feature &feature) const; //! Predict the label of a feature /*! Run classifier on feature, size of feature must match one used for model training. \param feature HOG calculated features from an image */ float predictLabel(const vector<float> &feature, double& decisionValue) const; //! Gets a collection of predictions given a collection of features std::vector<float> predict(const FeatureCollection &fset); std::vector<float> predictLabel(const FeatureCollection &fset) const; //! Get the primal form for the svm std::vector<float> getDetector() const; //! Print the parameters chosen for the SVM void printSVMParameters(); //! Get SVM weights in the shape of the original features //vector<float> getWeights() const; double getBiasTerm() const; //! Get default parameters static ParametersMap getDefaultParameters(); ParametersMap getParameters(); //Mat renderSVMWeights(const FeatureExtractor *featExtractor); //! Load model to file /*! \param filename Path where the configuration file is located. */ svm_model * load(const std::string &filename); //! Save model to file /*! \param filename Path where the configuration file will be located. */ void save(const std::string &filename) const; //! Verify if the svm is initiallized bool initialized() const { return _model != NULL; } }; #endif // SUPPORT_VECTOR_MACHINE_H
#ifndef CONNECTIONCOMMANDS_HH #define CONNECTIONCOMMANDS_HH #include "nanodbc/nanodbc.h" #include <sql.h> #include <sqlext.h> #include "errors.hh" #include "fetch.hh" #include "UVMonitor.hh" #include "odbcutil.hh" #include "arguments.hh" namespace NC { enum struct ConnectionCommands { dbms_name, is_connected, dbms_version, catalog_name, database_name, driver_name, connect, disconnect, query, execute, set_auto_commit }; template<ConnectionCommands c> struct ConnectionCommand { }; template<> struct ConnectionCommand<ConnectionCommands::dbms_name> { static nc_string_t Execute( UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { return owner->Synchronized([&](nanodbc::connection& connection) { return connection.dbms_name(); }); } }; template<> struct ConnectionCommand<ConnectionCommands::is_connected> { static bool Execute( UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { return owner->Synchronized([&](nanodbc::connection& connection) { return connection.connected(); }); } }; template<> struct ConnectionCommand<ConnectionCommands::dbms_version> { static nc_string_t Execute( UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { return owner->Synchronized([&](nanodbc::connection& connection) { return connection.dbms_version(); }); } }; template<> struct ConnectionCommand<ConnectionCommands::catalog_name> { static nc_string_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { return owner->Synchronized([&](nanodbc::connection& connection) { return connection.catalog_name(); }); } }; template<> struct ConnectionCommand<ConnectionCommands::database_name> { static nc_string_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { return owner->Synchronized([&](nanodbc::connection& connection) { return connection.database_name(); }); } }; template<> struct ConnectionCommand<ConnectionCommands::driver_name> { static nc_string_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { return owner->Synchronized([&](nanodbc::connection& connection) { return connection.driver_name(); }); } }; template<> struct ConnectionCommand<ConnectionCommands::connect> { static nc_null_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<nc_string_t, TimeoutArg>& args) { owner->Synchronized([&](nanodbc::connection& connection) { connection.connect(std::get<0>(args), std::get<1>(args)); }); return nc_null_t {}; } static nc_null_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<nc_string_t>& args) { owner->Synchronized([&](nanodbc::connection& connection) { connection.connect(std::get<0>(args)); }); return nc_null_t {}; } static nc_null_t Execute(UVMonitor<nanodbc::connection>* owner, std::tuple<nc_string_t, nc_string_t, nc_string_t> args) { owner->Synchronized([&](nanodbc::connection& connection) { connection.connect(std::get<0>(args), std::get<1>(args), std::get<2>(args)); }); return nc_null_t {}; } static nc_null_t Execute(UVMonitor<nanodbc::connection>* owner, std::tuple<nc_string_t, nc_string_t, nc_string_t, TimeoutArg> args) { owner->Synchronized([&](nanodbc::connection& connection) { connection.connect(std::get<0>(args), std::get<1>(args), std::get<2>(args), std::get<3>(args)); }); return nc_null_t {}; } }; template<> struct ConnectionCommand<ConnectionCommands::disconnect> { static nc_null_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<>&) { owner->Synchronized([&](nanodbc::connection& connection) { connection.disconnect(); }); return nc_null_t {}; } }; template<> struct ConnectionCommand<ConnectionCommands::set_auto_commit> { static nc_null_t Execute( UVMonitor<nanodbc::connection>* owner, const std::tuple<bool>& args) { using NC::success; auto enable = std::get<0>(args); owner->Synchronized([&](nanodbc::connection& connection) { auto* handle = connection.native_dbc_handle(); auto retcode = SQLSetConnectAttr( handle, SQL_ATTR_AUTOCOMMIT, (SQLPOINTER) (enable ? SQL_AUTOCOMMIT_ON : SQL_AUTOCOMMIT_OFF), SQL_NTS); if (!success(retcode)) { throw nanodbc::database_error(handle, SQL_HANDLE_DBC, std::string("Unable to set auto commit mode")); } }); return nc_null_t {}; } }; template<> struct ConnectionCommand<ConnectionCommands::query> { static nc_result_t Execute(UVMonitor<nanodbc::connection>* owner, const std::tuple<QueryArguments>& args) { return owner->Synchronized([&](nanodbc::connection& connection) { const QueryArguments& qargs = std::get<0>(args); nanodbc::result result = nanodbc::execute(connection, qargs.GetQuery(), qargs.GetBatchSize(), qargs.GetTimeout()); return fetch_result_eagerly(&result); }); } }; template<> struct ConnectionCommand<ConnectionCommands::execute> { static nc_null_t Execute( UVMonitor<nanodbc::connection>* owner, const std::tuple<QueryArguments>& args) { owner->Synchronized([&](nanodbc::connection& connection) { const QueryArguments& qargs = std::get<0>(args); nanodbc::just_execute(connection, qargs.GetQuery(), qargs.GetBatchSize(), qargs.GetTimeout()); }); return nc_null_t {}; } }; } // namespace NC #endif /* CONNECTIONCOMMANDS_HH */
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; set<string> S; vector<string> V; string st[200100]; int main() { int n; scanf("%d",&n); for (int i = 1;i <= n; i++) cin >> st[i]; for (int i = n;i >= 1; i--) { if (!S.count(st[i])) { S.insert(st[i]); cout << st[i] << endl; } } return 0; }
#include <iostream> #include <vector> using namespace std; int main () { vector<int>::size_type sz; vector<int> foo; sz = foo.capacity(); cout << "making foo grow:\n"; for (int i=0; i<100; ++i) { foo.push_back(i); if (sz!=foo.capacity()) { sz = foo.capacity(); cout << "capacity changed: " << sz << '\n'; } } vector<int> bar; sz = bar.capacity(); bar.reserve(100); // this is the only difference with foo above that it will directly reserve the capacity for 100size . cout << "making bar grow:\n"; for (int i=0; i<100; ++i) { bar.push_back(i); if (sz!=bar.capacity()) { sz = bar.capacity(); cout << "capacity changed: " << sz << '\n'; } } return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * Morten Rolland, mortenro@opera.com */ #include "core/pch.h" #if defined(SELFTEST) && defined(OPMEMORY_EXECUTABLE_SEGMENT) // // This simple function is used to test executable memory. It is // assumed that it can be copied into an executable memory segment, // and still execute the same function (smallest fibonacci number // larger or equal to the argument). // extern "C" int OpMemory_Test_ExecutableMemory(int arg) { int n1 = 0; int n2 = 1; for (;;) { int sum = n1 + n2; if ( sum >= arg ) return sum; n1 = n2; n2 = sum; } } extern "C" int OpMemory_Test_ExecutableMemory2(int arg) { return arg + 100; } #endif // SELFTEST && OPMEMORY_EXECUTABLE_SEGMENT
#include <iostream> #include <sstream> #include <fstream> #include <iomanip> // std::setprecision #include "../include/command_interface.h" #include "../include/constants.h" #include "../lib/rapidxml/rapidxml.hpp" #include "../lib/rapidxml/rapidxml_print.hpp" using namespace rapidxml; using namespace std; string command_interface::doubleString(double value) { stringstream ss; ss.setf(ios::scientific); ss << setprecision(3); ss << value; return ss.str(); } void command_interface::save_device_params(string config_dir_name) { ofstream file_stored(config_dir_name); xml_document<> doc; xml_node <> * pRoot = doc.allocate_node(node_element, "document"); /* Save device data */ xml_node <> * pNode_device = doc.allocate_node(node_element, "Device"); // T string T = doubleString(layers_params.device.T); const char* p_T = T.c_str(); pNode_device->append_attribute(doc.allocate_attribute("T", p_T)); // dt string dt = doubleString(layers_params.device.dt); const char* p_dt = dt.c_str(); pNode_device->append_attribute(doc.allocate_attribute("dt", p_dt)); // V_a string V_a = doubleString(layers_params.device.V_a); const char* p_V_a = V_a.c_str(); pNode_device->append_attribute(doc.allocate_attribute("V_a", p_V_a)); // V_build string V_build = doubleString(layers_params.device.V_build); const char* p_V_build = V_build.c_str(); pNode_device->append_attribute(doc.allocate_attribute("V_build", p_V_build)); // G_suns string G_suns = doubleString(layers_params.device.G_suns); const char* p_G_suns = G_suns.c_str(); pNode_device->append_attribute(doc.allocate_attribute("G_suns", p_G_suns)); // W_a string W_a = doubleString(layers_params.device.W_a / C_q); const char* p_W_a = W_a.c_str(); pNode_device->append_attribute(doc.allocate_attribute("W_a", p_W_a)); // W_c string W_c = doubleString(layers_params.device.W_c / C_q); const char* p_W_c = W_c.c_str(); pNode_device->append_attribute(doc.allocate_attribute("W_c", p_W_c)); // epsilon string epsilon = doubleString(layers_params.device.epsilon); const char* p_epsilon = epsilon.c_str(); pNode_device->append_attribute(doc.allocate_attribute("epsilon", p_epsilon)); pRoot->append_node(pNode_device); doc.append_node(pRoot); file_stored << doc; file_stored.close(); doc.clear(); } void command_interface::save_setting(string config_dir_name) { xml_document<> doc; // Load file ifstream file(config_dir_name); stringstream buffer; buffer << file.rdbuf(); file.close(); string content(buffer.str()); doc.parse<0>(&content[0]); xml_node<> *pRoot = doc.first_node(); xml_node<> *pNode_settings = doc.clone_node( pRoot ); pNode_settings = doc.allocate_node(node_element, "Settings"); // first_pulse_time string first_pulse = doubleString(settings.first_pulse); const char* p_first_pulse = first_pulse.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("first_pulse_time", p_first_pulse)); // second_pulse_time string second_pulse = doubleString(settings.second_pulse); const char* p_sec_pulse = second_pulse.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("second_pulse_time", p_sec_pulse)); // third_pulse_time string third_pulse = doubleString(settings.third_pulse); const char* p_third_pulse = third_pulse.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("third_pulse_time", p_third_pulse)); // V_min string V_min = doubleString(settings.V_min); const char* p_V_min = V_min.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("V_min", p_V_min)); // V_max string V_max = doubleString(settings.V_max); const char* p_V_max = V_max.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("V_max", p_V_max)); // V_rate string V_rate = doubleString(settings.V_rate); const char* p_V_rate = V_rate.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("V_rate", p_V_rate)); // V_step string V_step = doubleString(settings.V_step); const char* p_V_step = V_step.c_str(); pNode_settings->append_attribute(doc.allocate_attribute("V_step", p_V_step)); doc.first_node("document")->append_node( pNode_settings ); /* Appending node a to the tree in src */ // Save file ofstream file_stored(config_dir_name); file_stored << "<? Solar Cell Simulation ?>" << endl; file_stored << doc; file_stored.close(); doc.clear(); } void command_interface::save_layer_params(string config_dir_name, unscaled_layer_params * layer_params) { xml_document<> doc; const char * tmp_layer_name = layer_params->name.c_str();; // Load file ifstream file(config_dir_name); stringstream buffer; buffer << file.rdbuf(); file.close(); string content(buffer.str()); doc.parse<0>(&content[0]); xml_node<> *pRoot = doc.first_node(); /* Node to append */ xml_node<> *pNode_layer = doc.clone_node( pRoot ); /* Save layer data */ pNode_layer = doc.allocate_node(node_element, tmp_layer_name); // name const char* p_name = layer_params->name.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("name", p_name)); // ID string ID = to_string(layer_params->ID); const char* p_ID = ID.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("ID", p_ID)); // E_r string E_r = doubleString(layer_params->E_r); const char* p_E_r = E_r.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("E_r", p_E_r)); // u_n string u_n = doubleString(layer_params->u_n); const char* p_u_n = u_n.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("u_n", p_u_n)); // u_p string u_p = doubleString(layer_params->u_p); const char* p_u_p = u_p.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("u_p", p_u_p)); // u_s string u_s = doubleString(layer_params->u_s); const char* p_u_s = u_s.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("u_s", p_u_s)); // E_b string E_b = doubleString(layer_params->E_b / C_q); const char* p_E_b = E_b.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("E_b", p_E_b)); // y_ns string y_ns = doubleString(layer_params->y_ns); const char* p_y_ns = y_ns.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("y_ns", p_y_ns)); // y_ps string y_ps = doubleString(layer_params->y_ps); const char* p_y_ps = y_ps.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("y_ps", p_y_ps)); // t_s string t_s = doubleString(layer_params->t_s); const char* p_t_s = t_s.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("t_s", p_t_s)); // L string L = doubleString(layer_params->L); const char* p_L = L.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("L", p_L)); // N_points string N_points = doubleString(layer_params->N_points); const char* p_N_points = N_points.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("N_points", p_N_points)); // E_c string E_c = doubleString(layer_params->E_c / C_q); const char* p_E_c = E_c.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("E_c", p_E_c)); // E_v string E_v = doubleString(layer_params->E_v / C_q); const char* p_E_v = E_v.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("E_v", p_E_v)); // N_D string N_D = doubleString(layer_params->N_D); const char* p_N_D = N_D.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("N_D", p_N_D)); // N_A string N_A = doubleString(layer_params->N_A); const char* p_N_A = N_A.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("N_A", p_N_A)); // N_c string N_c = doubleString(layer_params->N_c); const char* p_N_c = N_c.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("N_c", p_N_c)); // N_v string N_v = doubleString(layer_params->N_v); const char* p_N_v = N_v.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("N_v", p_N_v)); // ksi string ksi = doubleString(layer_params->ksi); const char* p_ksi = ksi.c_str(); pNode_layer->append_attribute(doc.allocate_attribute("ksi", p_ksi)); doc.first_node("document")->append_node( pNode_layer ); /* Appending node a to the tree in src */ // Save file ofstream file_stored(config_dir_name); file_stored << doc; file_stored.close(); doc.clear(); }
#include<ctime> #include<iostream> #include<conio.h> #include<stdio.h> using namespace std; void takeInput(int a[],int n) { for(int i = 0; i < n; i++) { cin>>a[i]; } } int linearSearch(int a[], int num, int size) { for(int i = 0; i < size; i++) { if(a[i] == num) { return i; } } return -1; } int main() { clock_t c_start = clock(); int n,m; int a[30]; cout<<"Enter the number of elements: "; cin>>n; cout<<"Enter the elements : "; takeInput(a,n); //takeInput function calling cout<<"Enter the number to be searched: "; cin>>m; int ans = linearSearch(a,m,n); cout<<"Element is present at index : "<< ans; clock_t c_end = clock(); long double time_elapsed_ms = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC; cout << "\nCPU time used in Linear Search: " << time_elapsed_ms << " ms\n"; return 0; }
#include <iostream> #include <cmath> #include <iomanip> using namespace std; long double fun(long double x){ long double a = sin(10*x-20)/exp(pow(x-2,2)/5)+0.25-x; return a; } int main() { double x,y; x = 0; y = 0; while (y>=0){ y = fun(x); x += 0.00000001; } while (x<6){ if (y<0) { y = fun(x); x += 0.00000001; } else { y = fun(x); break; } } cout << fixed << showpoint << setprecision(10); cout << y << endl; cout << x; }
#include<bits/stdc++.h> using namespace std; int timu[1500]; bool vis[1500]; int main(){ int T; cin>>T; while(T--){ for(int i=1000;i<=1015;i++){ timu[i]=0; vis[i]=0; } int cnt=0; int ans=0; int n,m; cin>>n>>m; for(int i=0;i<m;i++){ int x; cin>>x; int t1,t2; cin>>t1; getchar(); cin>>t2; string b; cin>>b; if(vis[x]==true) continue; if(b=="AC"){ ans+=timu[x]; ans+=t1*60+t2; vis[x]=true; cnt++; }else{ timu[x]+=20; } } cout<<cnt<<" "<<ans<<"\n"; } return 0; }
#include <iostream> using namespace std; int main(){ int t; string s; cin >> t; while(t--){ cin >> s; if(!s.compare("1") || !s.compare("4") || !s.compare("78")){ cout << "+" << endl; }else if(!s.substr(s.length() - 2, 2).compare("35")){ cout << "-" << endl; }else if(s[0] == '9' && s[s.length()-1] == '4'){ cout << "*" << endl; }else{ cout << "?" << endl; } } return 0; }
//算法:模拟,归并排序 //先按照初始分数排一遍序 //之后开始模拟比赛. //将胜利的人加入win数组,将输的人加入los数组 //根据题意,可以得知: //由于原序列中的人是按照 先分数降序 再编号升序 的顺序排列的 //由于只有胜者才加分 //所以在win数组与los数组中,也保证了 先分数降序 再编号升序 的有序性质 //根据归并排序,是将两个有序序列合并的原理 //则可以用O(n)的复杂度完成每次排序 //根据此性质模拟即可 #include<cstdio> #include<algorithm> using namespace std; struct person { int s,w,num; }a[200010]; int n,r,q; int s[200010],w[200010]; person win[200010],los[200010]; bool cmp(person aa,person bb)//初始排序 { if(aa.s==bb.s) return aa.num<bb.num; return aa.s>bb.s; } void merge()//归并排序 { int i=1,j=1,k=1; while(i<=n && j<=n) { if(win[i].s>los[j].s) a[k++]=win[i++];//先按分数降序排 else if(win[i].s==los[j].s && win[i].num<los[j].num) a[k++]=win[i++];//分数相同按编号 else a[k++]=los[j++];//分数降序 } while(i<=n) a[k++]=win[i++];//归并排序,将剩余的加入到序列中 while(j<=n) a[k++]=los[j++]; } int main() { scanf("%d%d%d",&n,&r,&q); for(int i=1;i<=2*n;i++)//输入 { scanf("%d",&a[i].s); a[i].num=i; } for(int j=1;j<=2*n;j++) scanf("%d",&a[j].w); sort(a+1,a+2*n+1,cmp); while(r--)//进行r轮 { for(int i=1;i<=2*n-1;i+=2)//模拟比赛 ,并将胜负者加入win,los数组中 if(a[i].w>a[i+1].w) a[i].s+=1,win[i/2+1]=a[i],los[i/2+1]=a[i+1]; else a[i+1].s+=1,win[i/2+1]=a[i+1],los[i/2+1]=a[i]; merge();//归并 } printf("%d",a[q].num);//输出 }
#include <iostream> using namespace std; int Sum_Of_Maximum_SubArray(int arr[], int size_of_arr,int neg_max) { if (neg_max > 0) { int max_sum = 0; for (int x = 0; x < size_of_arr; x++) { int sum = 0; for (int y = x; y < size_of_arr; y++) { sum = sum + arr[y]; if (sum > max_sum) { max_sum = sum; } } } return max_sum; } else { return neg_max; } } int main() { int size; cout << "Enter size" << endl; cin >> size; int nums[size]; for (int x = 0; x < size; x++) { cout << "Enter element" << endl; cin >> nums[x]; } int neg_max=nums[0]; for(int x=1;x<size;x++) { if(nums[x]>neg_max) { neg_max=nums[x]; } } cout << Sum_Of_Maximum_SubArray(nums, size,neg_max); return 0; }
/* * File: main.cpp * Author: Daniel Canales * * Created on June 24, 2014, 9:34 PM */ #include <cstdlib> #include <iostream> using namespace std; /* * */ int main(int argc, char** argv) { int payamt = 1700; int payper = 26; int annual = payamt*payper; cout << "Employee's Annual Pay is: $" << annual << endl; return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef WIDGET_RUNTIME_SUPPORT #include "adjunct/widgetruntime/hotlist/GadgetsHotlistView.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/menus/DesktopMenuHandler.h" #include "adjunct/quick/hotlist/HotlistManager.h" #include "modules/util/opfile/opfolder.h" const char* const GadgetsHotlistView::GADGET_MENU_NAME = "Widget Item Popup Menu"; OP_STATUS GadgetsHotlistView::Init() { m_sort_column = NAME_COLUMN; m_controller = OP_NEW(GadgetsHotlistController, (*m_hotlist_view)); RETURN_OOM_IF_NULL(m_controller.get()); RETURN_IF_ERROR(InitModel()); m_hotlist_view->SetTreeModel(m_gadgets_model.get(), m_sort_column, TRUE); m_hotlist_view->SetPaintBackgroundLine(FALSE); m_hotlist_view->SetHaveWeakAssociatedText(TRUE); m_hotlist_view->SetRestrictImageSize(FALSE); m_hotlist_view->SetShowThreadImage(FALSE); m_hotlist_view->SetAllowMultiLineIcons(TRUE); m_hotlist_view->SetColumnImageFixedDrawArea(ICON_COLUMN, GADGET_HOTLIST_ICON_SIZE + 2); m_hotlist_view->SetColumnFixedWidth(ICON_COLUMN, GADGET_HOTLIST_ICON_SIZE + 2); m_hotlist_view->SetColumnFixedWidth(SEPARATOR_COLUMN, SEPARATOR_COLUMN_WIDTH); m_hotlist_view->SetExtraLineHeight(2); m_hotlist_view->SetVerticalAlign(WIDGET_V_ALIGN_TOP); m_hotlist_view->SetMultiselectable(FALSE); SetPrefsmanFlags(); return OpHotlistTreeView::Init(); } OP_STATUS GadgetsHotlistView::InitModel() { m_gadgets_model.reset(OP_NEW(GadgetsTreeModel, ())); RETURN_OOM_IF_NULL(m_gadgets_model.get()); RETURN_IF_ERROR(m_gadgets_model->Init()); return OpStatus::OK; } OP_STATUS GadgetsHotlistView::DeleteModel() { m_hotlist_view->SetTreeModel(NULL, m_sort_column, TRUE); m_gadgets_model.reset(); return OpStatus::OK; } void GadgetsHotlistView::OnDeleted() { // As strange as it is, we have to delete the model before g_gadget_manager // is destroyed, or we crash on deleting OpGadgetClass objects. OpStatus::Ignore(DeleteModel()); OpHotlistTreeView::OnDeleted(); } void GadgetsHotlistView::OnShow(BOOL show) { m_gadgets_model->SetActive(show); OpHotlistTreeView::OnShow(show); } BOOL GadgetsHotlistView::ShowContextMenu(const OpPoint& point, BOOL center, OpTreeView* view, BOOL use_keyboard_context) { BOOL shown = FALSE; if (NULL == view) { } else if (NULL != view->GetSelectedItem()) { // Inside the context of an installed gadget. const OpPoint translated_point = point + GetScreenRect().TopLeft(); g_application->GetMenuHandler()->ShowPopupMenu(GADGET_MENU_NAME, PopupPlacement::AnchorAt(translated_point, center), 0, use_keyboard_context); shown = TRUE; } // TODO: Inside the context of an "unupgraded" gadget. return shown; } INT32 GadgetsHotlistView::GetRootID() { return -1; } void GadgetsHotlistView::OnSetDetailed(BOOL detailed) { // This method body intentionally left blank. } INT32 GadgetsHotlistView::OnDropItem(HotlistModelItem* hmi_target, DesktopDragObject* drag_object, INT32 i, DropType drop_type, DesktopDragObject::InsertType insert_type, INT32 *first_id, BOOL force_delete) { // This method body intentionally left blank. return 0; } BOOL GadgetsHotlistView::OnInputAction(OpInputAction* action) { return m_controller->HandleAction(*action); } void GadgetsHotlistView::OnMouseEvent(OpWidget* widget, INT32 pos, INT32 x, INT32 y, MouseButton button, BOOL down, UINT8 nclicks) { // Context menu triggering more or less copied from OpHotlistTreeView. if (!down && 1 == nclicks && MOUSE_BUTTON_2 == button) { if (NULL != widget && WIDGET_TYPE_TREEVIEW == widget->GetType()) { // Needed for split view layout x += widget->GetRect(FALSE).x; y += widget->GetRect(FALSE).y; ShowContextMenu(OpPoint(x,y), FALSE, static_cast<OpTreeView*>(widget), FALSE); } return; } if (MOUSE_BUTTON_1 == button && 2 == nclicks) { OpInputAction action(OpInputAction::ACTION_OPEN_WIDGET); g_input_manager->InvokeAction(&action, GetParentInputContext()); } } #endif // WIDGET_RUNTIME_SUPPORT
#include "CEmployee.h" int main() { char choice = '0'; CEmployee* cemployee = nullptr; CWageEmployee wemp; while (choice != '8') { cout << "\t\t***** Menu *****" << endl; cout << "1) Set Employee Data" << endl; cout << "2) Display Employee Data" << endl; cout << "3) Update Employee Basic Salary" << endl; cout << "4) Calculate Total Salary" << endl; cout << "5) Set Employee Data using Parent Class pointer " << endl; cout << "6) Display Employee Data using Parent Class pointer " << endl; cout << "7) Create New CWageEmployee Object" << endl; cout << "8) Exit" << endl; cin >> choice; switch (choice) { case '1': { wemp.set_emp_details(); break; } case '2': { wemp.display_emp_details(); break; } case '3': { int sal; cout << "Enter Updated Salary amount: "; cin >> sal; wemp.set_emp_salary(sal); break; } case '4': { cout<< "Employee Salary is "<< wemp.compute_salary() << endl; break; } case '5': { cemployee = new CWageEmployee(); //Changes: cemployee->set_emp_details(); cemployee->display_emp_details(); break; } case '6': { if(cemployee != nullptr) { cemployee->display_emp_details(); } else { cout << "No Employee Created to display, so make one"<<endl; cemployee = new CWageEmployee(); //Changes: cemployee->set_emp_details(); cemployee->display_emp_details(); } break; } case '7': { CWageEmployee wemp2; //wemp2.set_emp_details(); wemp2.display_emp_details(); break; } case '8': { delete cemployee; // Resolved memory leak cout << "BYE" << endl; break; } default: break; } } return 0; }
#include <iostream> using namespace std; class punto{ public: int x; int y; punto(){ x=0; y=0; } punto(int w, int z){ x=w; y=z; } void print(){ cout<< x << " " << y << endl; } int getx(){ return x; } int gety(){ return y; } int setx(int i){ x=i; } int sety(int j){ y=j; } void suma(int a, int b){ x += a; y += b; } }; class vectorx { public: punto px1; punto px2; void suma(int a, int b){ px1.suma(a,b); px2.suma(a,b); } void imprimir(){ px1.print(); px2.print(); } }; main(){ punto p1(5,2); punto p2(6,7); vectorx vex; vex.px1=p1; vex.px2=p2; vex.imprimir(); vex.suma(10,10); vex.imprimir(); }
/** * Copyright (c) 2013, 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. * * @file lnav_config.cc */ #include <chrono> #include <iostream> #include <regex> #include <stdexcept> #include "lnav_config.hh" #include <fcntl.h> #include <fmt/format.h> #include <glob.h> #include <libgen.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <unistd.h> #include "base/auto_fd.hh" #include "base/auto_mem.hh" #include "base/auto_pid.hh" #include "base/fs_util.hh" #include "base/injector.bind.hh" #include "base/injector.hh" #include "base/lnav_log.hh" #include "base/paths.hh" #include "base/string_util.hh" #include "bin2c.hh" #include "config.h" #include "default-config.h" #include "styling.hh" #include "view_curses.hh" #include "yajlpp/yajlpp.hh" #include "yajlpp/yajlpp_def.hh" using namespace std::chrono_literals; static const int MAX_CRASH_LOG_COUNT = 16; static const auto STDIN_CAPTURE_RETENTION = 24h; static auto intern_lifetime = intern_string::get_table_lifetime(); struct _lnav_config lnav_config; struct _lnav_config rollback_lnav_config; static struct _lnav_config lnav_default_config; std::map<intern_string_t, source_location> lnav_config_locations; lnav_config_listener* lnav_config_listener::LISTENER_LIST; static auto a = injector::bind<archive_manager::config>::to_instance( +[]() { return &lnav_config.lc_archive_manager; }); static auto dtc = injector::bind<date_time_scanner_ns::config>::to_instance( +[]() { return &lnav_config.lc_log_date_time; }); static auto fvc = injector::bind<file_vtab::config>::to_instance( +[]() { return &lnav_config.lc_file_vtab; }); static auto lc = injector::bind<lnav::logfile::config>::to_instance( +[]() { return &lnav_config.lc_logfile; }); static auto p = injector::bind<lnav::piper::config>::to_instance( +[]() { return &lnav_config.lc_piper; }); static auto tc = injector::bind<tailer::config>::to_instance( +[]() { return &lnav_config.lc_tailer; }); static auto scc = injector::bind<sysclip::config>::to_instance( +[]() { return &lnav_config.lc_sysclip; }); static auto uh = injector::bind<lnav::url_handler::config>::to_instance( +[]() { return &lnav_config.lc_url_handlers; }); static auto lsc = injector::bind<logfile_sub_source_ns::config>::to_instance( +[]() { return &lnav_config.lc_log_source; }); static auto annoc = injector::bind<lnav::log::annotate::config>::to_instance( +[]() { return &lnav_config.lc_log_annotations; }); static auto tssc = injector::bind<top_status_source_cfg>::to_instance( +[]() { return &lnav_config.lc_top_status_cfg; }); bool check_experimental(const char* feature_name) { const char* env_value = getenv("LNAV_EXP"); require(feature_name != nullptr); if (env_value && strcasestr(env_value, feature_name)) { return true; } return false; } void ensure_dotlnav() { static const char* subdirs[] = { "", "configs", "configs/default", "configs/installed", "formats", "formats/default", "formats/installed", "staging", "stdin-captures", "crash", }; auto path = lnav::paths::dotlnav(); for (const auto* sub_path : subdirs) { auto full_path = path / sub_path; if (mkdir(full_path.c_str(), 0755) == -1 && errno != EEXIST) { log_error("unable to make directory: %s -- %s", full_path.c_str(), strerror(errno)); } } auto crash_dir_path = path / "crash"; lnav_log_crash_dir = strdup(crash_dir_path.c_str()); { static_root_mem<glob_t, globfree> gl; auto crash_glob = path / "crash-*"; if (glob(crash_glob.c_str(), GLOB_NOCHECK, nullptr, gl.inout()) == 0) { std::error_code ec; for (size_t lpc = 0; lpc < gl->gl_pathc; lpc++) { auto crash_file = ghc::filesystem::path(gl->gl_pathv[lpc]); ghc::filesystem::rename( crash_file, crash_dir_path / crash_file.filename(), ec); } } } { static_root_mem<glob_t, globfree> gl; auto crash_glob = path / "crash/*"; if (glob(crash_glob.c_str(), GLOB_NOCHECK, nullptr, gl.inout()) == 0) { for (int lpc = 0; lpc < ((int) gl->gl_pathc - MAX_CRASH_LOG_COUNT); lpc++) { log_perror(remove(gl->gl_pathv[lpc])); } } } { static_root_mem<glob_t, globfree> gl; auto cap_glob = path / "stdin-captures/*"; if (glob(cap_glob.c_str(), GLOB_NOCHECK, nullptr, gl.inout()) == 0) { auto old_time = std::chrono::system_clock::now() - STDIN_CAPTURE_RETENTION; for (size_t lpc = 0; lpc < gl->gl_pathc; lpc++) { struct stat st; if (stat(gl->gl_pathv[lpc], &st) == -1) { continue; } if (std::chrono::system_clock::from_time_t(st.st_mtime) > old_time) { continue; } log_info("Removing old stdin capture: %s", gl->gl_pathv[lpc]); log_perror(remove(gl->gl_pathv[lpc])); } } } } bool install_from_git(const std::string& repo) { static const std::regex repo_name_converter("[^\\w]"); auto formats_path = lnav::paths::dotlnav() / "formats"; auto configs_path = lnav::paths::dotlnav() / "configs"; auto staging_path = lnav::paths::dotlnav() / "staging"; auto local_name = std::regex_replace(repo, repo_name_converter, "_"); auto local_formats_path = formats_path / local_name; auto local_configs_path = configs_path / local_name; auto local_staging_path = staging_path / local_name; auto fork_res = lnav::pid::from_fork(); if (fork_res.isErr()) { fprintf(stderr, "error: cannot fork() to run git: %s\n", fork_res.unwrapErr().c_str()); _exit(1); } auto git_cmd = fork_res.unwrap(); if (git_cmd.in_child()) { if (ghc::filesystem::is_directory(local_formats_path)) { fmt::print("Updating format repo: {}\n", repo); log_perror(chdir(local_formats_path.c_str())); execlp("git", "git", "pull", nullptr); } else if (ghc::filesystem::is_directory(local_configs_path)) { fmt::print("Updating config repo: {}\n", repo); log_perror(chdir(local_configs_path.c_str())); execlp("git", "git", "pull", nullptr); } else { execlp("git", "git", "clone", repo.c_str(), local_staging_path.c_str(), nullptr); } _exit(1); } auto finished_child = std::move(git_cmd).wait_for_child(); if (!finished_child.was_normal_exit() || finished_child.exit_status() != 0) { return false; } if (!ghc::filesystem::is_directory(local_staging_path)) { auto um = lnav::console::user_message::error( attr_line_t("failed to install git repo: ") .append(lnav::roles::file(repo))) .with_reason( attr_line_t("git failed to create the local directory") .append( lnav::roles::file(local_staging_path.string()))); lnav::console::print(stderr, um); return false; } auto config_path = local_staging_path / "*"; static_root_mem<glob_t, globfree> gl; int found_config_file = 0; int found_format_file = 0; int found_sql_file = 0; int found_lnav_file = 0; if (glob(config_path.c_str(), 0, nullptr, gl.inout()) == 0) { for (size_t lpc = 0; lpc < gl->gl_pathc; lpc++) { auto file_path = ghc::filesystem::path{gl->gl_pathv[lpc]}; if (file_path.extension() == ".lnav") { found_lnav_file += 1; continue; } if (file_path.extension() == ".sql") { found_sql_file += 1; continue; } if (file_path.extension() != ".json") { found_sql_file += 1; continue; } auto file_type_result = detect_config_file_type(file_path); if (file_type_result.isErr()) { fprintf(stderr, "error: %s\n", file_type_result.unwrapErr().c_str()); return false; } if (file_type_result.unwrap() == config_file_type::CONFIG) { found_config_file += 1; } else { found_format_file += 1; } } } if (found_config_file == 0 && found_format_file == 0 && found_sql_file == 0 && found_lnav_file == 0) { auto um = lnav::console::user_message::error( attr_line_t("invalid lnav repo: ") .append(lnav::roles::file(repo))) .with_reason("no .json, .sql, or .lnav files were found"); lnav::console::print(stderr, um); return false; } auto dest_path = local_formats_path; attr_line_t notes; if (found_format_file > 0) { notes.append("found ") .append(lnav::roles::number(fmt::to_string(found_format_file))) .append(" format file(s)\n"); } if (found_config_file > 0) { if (found_format_file == 0) { dest_path = local_configs_path; } notes.append("found ") .append(lnav::roles::number(fmt::to_string(found_config_file))) .append(" configuration file(s)\n"); } if (found_sql_file > 0) { notes.append("found ") .append(lnav::roles::number(fmt::to_string(found_sql_file))) .append(" SQL file(s)\n"); } if (found_lnav_file > 0) { notes.append("found ") .append(lnav::roles::number(fmt::to_string(found_lnav_file))) .append(" lnav-script file(s)\n"); } rename(local_staging_path.c_str(), dest_path.c_str()); auto um = lnav::console::user_message::ok( attr_line_t("installed lnav repo at: ") .append(lnav::roles::file(local_configs_path.string()))) .with_note(notes); lnav::console::print(stdout, um); return true; } bool update_installs_from_git() { static_root_mem<glob_t, globfree> gl; auto git_formats = lnav::paths::dotlnav() / "formats/*/.git"; bool found = false, retval = true; if (glob(git_formats.c_str(), 0, nullptr, gl.inout()) == 0) { for (int lpc = 0; lpc < (int) gl->gl_pathc; lpc++) { auto git_dir = ghc::filesystem::path(gl->gl_pathv[lpc]).parent_path(); printf("Updating formats in %s\n", git_dir.c_str()); auto pull_cmd = fmt::format(FMT_STRING("cd '{}' && git pull"), git_dir.string()); int ret = system(pull_cmd.c_str()); if (ret == -1) { std::cerr << "Failed to spawn command " << "\"" << pull_cmd << "\": " << strerror(errno) << std::endl; retval = false; } else if (ret > 0) { std::cerr << "Command " << "\"" << pull_cmd << "\" failed: " << strerror(errno) << std::endl; retval = false; } found = true; } } if (!found) { printf( "No formats from git repositories found, " "use 'lnav -i extra' to install third-party foramts\n"); } return retval; } static int read_repo_path(yajlpp_parse_context* ypc, const unsigned char* str, size_t len) { auto path = std::string((const char*) str, len); install_from_git(path.c_str()); return 1; } static const struct json_path_container format_handlers = { json_path_handler("format-repos#", read_repo_path), }; void install_extra_formats() { auto config_root = lnav::paths::dotlnav() / "remote-config"; auto_fd fd; if (access(config_root.c_str(), R_OK) == 0) { printf("Updating lnav remote config repo...\n"); auto pull_cmd = fmt::format(FMT_STRING("cd '{}' && git pull"), config_root.string()); log_perror(system(pull_cmd.c_str())); } else { printf("Cloning lnav remote config repo...\n"); auto clone_cmd = fmt::format( FMT_STRING( "git clone https://github.com/tstack/lnav-config.git {}"), config_root.string()); log_perror(system(clone_cmd.c_str())); } auto config_json = config_root / "remote-config.json"; if ((fd = lnav::filesystem::openp(config_json, O_RDONLY)) == -1) { perror("Unable to open remote-config.json"); } else { yajlpp_parse_context ypc_config( intern_string::lookup(config_root.string()), &format_handlers); auto_mem<yajl_handle_t> jhandle(yajl_free); unsigned char buffer[4096]; ssize_t rc; jhandle = yajl_alloc(&ypc_config.ypc_callbacks, nullptr, &ypc_config); yajl_config(jhandle, yajl_allow_comments, 1); while ((rc = read(fd, buffer, sizeof(buffer))) > 0) { if (yajl_parse(jhandle, buffer, rc) != yajl_status_ok) { auto* msg = yajl_get_error(jhandle, 1, buffer, rc); fprintf( stderr, "Unable to parse remote-config.json -- %s", msg); yajl_free_error(jhandle, msg); return; } } if (yajl_complete_parse(jhandle) != yajl_status_ok) { auto* msg = yajl_get_error(jhandle, 1, buffer, rc); fprintf(stderr, "Unable to parse remote-config.json -- %s", msg); yajl_free_error(jhandle, msg); } } } struct config_userdata { explicit config_userdata(std::vector<lnav::console::user_message>& errors) : ud_errors(errors) { } std::vector<lnav::console::user_message>& ud_errors; }; static void config_error_reporter(const yajlpp_parse_context& ypc, const lnav::console::user_message& msg) { auto* ud = (config_userdata*) ypc.ypc_userdata; ud->ud_errors.emplace_back(msg); } static const struct json_path_container key_command_handlers = { yajlpp::property_handler("command") .with_synopsis("<command>") .with_description( "The command to execute for the given key sequence. Use a script " "to execute more complicated operations.") .with_pattern("^[:|;].*") .with_example(":goto next hour") .for_field(&key_command::kc_cmd), yajlpp::property_handler("alt-msg") .with_synopsis("<msg>") .with_description( "The help message to display after the key is pressed.") .for_field<>(&key_command::kc_alt_msg), }; static const struct json_path_container keymap_def_handlers = { yajlpp::pattern_property_handler("(?<key_seq>(?:x[0-9a-f]{2})+)") .with_synopsis("<utf8-key-code-in-hex>") .with_description( "Map of key codes to commands to execute. The field names are " "the keys to be mapped using as a hexadecimal representation of " "the UTF-8 encoding. Each byte of the UTF-8 should start with " "an 'x' followed by the hexadecimal representation of the byte.") .with_obj_provider<key_command, key_map>( [](const yajlpp_provider_context& ypc, key_map* km) { auto& retval = km->km_seq_to_cmd[ypc.get_substr("key_seq")]; return &retval; }) .with_path_provider<key_map>( [](key_map* km, std::vector<std::string>& paths_out) { for (const auto& iter : km->km_seq_to_cmd) { paths_out.emplace_back(iter.first); } }) .with_children(key_command_handlers), }; static const struct json_path_container keymap_defs_handlers = { yajlpp::pattern_property_handler("(?<keymap_name>[\\w\\-]+)") .with_description("The keymap definitions") .with_obj_provider<key_map, _lnav_config>( [](const yajlpp_provider_context& ypc, _lnav_config* root) { key_map& retval = root->lc_ui_keymaps[ypc.get_substr("keymap_name")]; return &retval; }) .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_ui_keymaps) { paths_out.emplace_back(iter.first); } }) .with_children(keymap_def_handlers), }; static const json_path_handler_base::enum_value_t _movement_values[] = { {"top", config_movement_mode::TOP}, {"cursor", config_movement_mode::CURSOR}, json_path_handler_base::ENUM_TERMINATOR, }; static const struct json_path_container movement_handlers = { yajlpp::property_handler("mode") .with_synopsis("top|cursor") .with_enum_values(_movement_values) .with_example("top") .with_example("cursor") .with_description("The mode of cursor movement to use.") .for_field<>(&_lnav_config::lc_ui_movement, &movement_config::mode), }; static const struct json_path_container global_var_handlers = { yajlpp::pattern_property_handler("(?<var_name>\\w+)") .with_synopsis("<name>") .with_description( "A global variable definition. Global variables can be referenced " "in scripts, SQL statements, or commands.") .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_global_vars) { paths_out.emplace_back(iter.first); } }) .for_field(&_lnav_config::lc_global_vars), }; static const struct json_path_container style_config_handlers = json_path_container{ yajlpp::property_handler("color") .with_synopsis("#hex|color_name") .with_description( "The foreground color value for this style. The value can be " "the name of an xterm color, the hexadecimal value, or a theme " "variable reference.") .with_example("#fff") .with_example("Green") .with_example("$black") .for_field(&style_config::sc_color), yajlpp::property_handler("background-color") .with_synopsis("#hex|color_name") .with_description( "The background color value for this style. The value can be " "the name of an xterm color, the hexadecimal value, or a theme " "variable reference.") .with_example("#2d2a2e") .with_example("Green") .for_field(&style_config::sc_background_color), yajlpp::property_handler("underline") .with_description("Indicates that the text should be underlined.") .for_field(&style_config::sc_underline), yajlpp::property_handler("bold") .with_description("Indicates that the text should be bolded.") .for_field(&style_config::sc_bold), } .with_definition_id("style"); static const struct json_path_container theme_styles_handlers = { yajlpp::property_handler("identifier") .with_description("Styling for identifiers in logs") .for_child(&lnav_theme::lt_style_identifier) .with_children(style_config_handlers), yajlpp::property_handler("text") .with_description("Styling for plain text") .for_child(&lnav_theme::lt_style_text) .with_children(style_config_handlers), yajlpp::property_handler("alt-text") .with_description("Styling for plain text when alternating") .for_child(&lnav_theme::lt_style_alt_text) .with_children(style_config_handlers), yajlpp::property_handler("error") .with_description("Styling for error messages") .for_child(&lnav_theme::lt_style_error) .with_children(style_config_handlers), yajlpp::property_handler("ok") .with_description("Styling for success messages") .for_child(&lnav_theme::lt_style_ok) .with_children(style_config_handlers), yajlpp::property_handler("info") .with_description("Styling for informational messages") .for_child(&lnav_theme::lt_style_info) .with_children(style_config_handlers), yajlpp::property_handler("warning") .with_description("Styling for warning messages") .for_child(&lnav_theme::lt_style_warning) .with_children(style_config_handlers), yajlpp::property_handler("hidden") .with_description("Styling for hidden fields in logs") .for_child(&lnav_theme::lt_style_hidden) .with_children(style_config_handlers), yajlpp::property_handler("cursor-line") .with_description("Styling for the cursor line in the main view") .for_child(&lnav_theme::lt_style_cursor_line) .with_children(style_config_handlers), yajlpp::property_handler("disabled-cursor-line") .with_description("Styling for the cursor line when it is disabled") .for_child(&lnav_theme::lt_style_disabled_cursor_line) .with_children(style_config_handlers), yajlpp::property_handler("adjusted-time") .with_description("Styling for timestamps that have been adjusted") .for_child(&lnav_theme::lt_style_adjusted_time) .with_children(style_config_handlers), yajlpp::property_handler("skewed-time") .with_description( "Styling for timestamps that are different from the received time") .for_child(&lnav_theme::lt_style_skewed_time) .with_children(style_config_handlers), yajlpp::property_handler("offset-time") .with_description("Styling for hidden fields") .for_child(&lnav_theme::lt_style_offset_time) .with_children(style_config_handlers), yajlpp::property_handler("invalid-msg") .with_description("Styling for invalid log messages") .for_child(&lnav_theme::lt_style_invalid_msg) .with_children(style_config_handlers), yajlpp::property_handler("popup") .with_description("Styling for popup windows") .for_child(&lnav_theme::lt_style_popup) .with_children(style_config_handlers), yajlpp::property_handler("focused") .with_description("Styling for a focused row in a list view") .for_child(&lnav_theme::lt_style_focused) .with_children(style_config_handlers), yajlpp::property_handler("disabled-focused") .with_description("Styling for a disabled focused row in a list view") .for_child(&lnav_theme::lt_style_disabled_focused) .with_children(style_config_handlers), yajlpp::property_handler("scrollbar") .with_description("Styling for scrollbars") .for_child(&lnav_theme::lt_style_scrollbar) .with_children(style_config_handlers), yajlpp::property_handler("h1") .with_description("Styling for top-level headers") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { return &root->lt_style_header[0].pp_value; }) .with_children(style_config_handlers), yajlpp::property_handler("h2") .with_description("Styling for 2nd-level headers") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { return &root->lt_style_header[1].pp_value; }) .with_children(style_config_handlers), yajlpp::property_handler("h3") .with_description("Styling for 3rd-level headers") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { return &root->lt_style_header[2].pp_value; }) .with_children(style_config_handlers), yajlpp::property_handler("h4") .with_description("Styling for 4th-level headers") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { return &root->lt_style_header[3].pp_value; }) .with_children(style_config_handlers), yajlpp::property_handler("h5") .with_description("Styling for 5th-level headers") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { return &root->lt_style_header[4].pp_value; }) .with_children(style_config_handlers), yajlpp::property_handler("h6") .with_description("Styling for 6th-level headers") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { return &root->lt_style_header[5].pp_value; }) .with_children(style_config_handlers), yajlpp::property_handler("hr") .with_description("Styling for horizontal rules") .for_child(&lnav_theme::lt_style_hr) .with_children(style_config_handlers), yajlpp::property_handler("hyperlink") .with_description("Styling for hyperlinks") .for_child(&lnav_theme::lt_style_hyperlink) .with_children(style_config_handlers), yajlpp::property_handler("list-glyph") .with_description("Styling for glyphs that prefix a list item") .for_child(&lnav_theme::lt_style_list_glyph) .with_children(style_config_handlers), yajlpp::property_handler("breadcrumb") .with_description("Styling for the separator between breadcrumbs") .for_child(&lnav_theme::lt_style_breadcrumb) .with_children(style_config_handlers), yajlpp::property_handler("table-border") .with_description("Styling for table borders") .for_child(&lnav_theme::lt_style_table_border) .with_children(style_config_handlers), yajlpp::property_handler("table-header") .with_description("Styling for table headers") .for_child(&lnav_theme::lt_style_table_header) .with_children(style_config_handlers), yajlpp::property_handler("quote-border") .with_description("Styling for quoted-block borders") .for_child(&lnav_theme::lt_style_quote_border) .with_children(style_config_handlers), yajlpp::property_handler("quoted-text") .with_description("Styling for quoted text blocks") .for_child(&lnav_theme::lt_style_quoted_text) .with_children(style_config_handlers), yajlpp::property_handler("footnote-border") .with_description("Styling for footnote borders") .for_child(&lnav_theme::lt_style_footnote_border) .with_children(style_config_handlers), yajlpp::property_handler("footnote-text") .with_description("Styling for footnote text") .for_child(&lnav_theme::lt_style_footnote_text) .with_children(style_config_handlers), yajlpp::property_handler("snippet-border") .with_description("Styling for snippet borders") .for_child(&lnav_theme::lt_style_snippet_border) .with_children(style_config_handlers), yajlpp::property_handler("indent-guide") .with_description("Styling for indent guide lines") .for_child(&lnav_theme::lt_style_indent_guide) .with_children(style_config_handlers), }; static const struct json_path_container theme_syntax_styles_handlers = { yajlpp::property_handler("inline-code") .with_description("Styling for inline code blocks") .for_child(&lnav_theme::lt_style_inline_code) .with_children(style_config_handlers), yajlpp::property_handler("quoted-code") .with_description("Styling for quoted code blocks") .for_child(&lnav_theme::lt_style_quoted_code) .with_children(style_config_handlers), yajlpp::property_handler("code-border") .with_description("Styling for quoted-code borders") .for_child(&lnav_theme::lt_style_code_border) .with_children(style_config_handlers), yajlpp::property_handler("keyword") .with_description("Styling for keywords in source files") .for_child(&lnav_theme::lt_style_keyword) .with_children(style_config_handlers), yajlpp::property_handler("string") .with_description("Styling for single/double-quoted strings in text") .for_child(&lnav_theme::lt_style_string) .with_children(style_config_handlers), yajlpp::property_handler("comment") .with_description("Styling for comments in source files") .for_child(&lnav_theme::lt_style_comment) .with_children(style_config_handlers), yajlpp::property_handler("doc-directive") .with_description( "Styling for documentation directives in source files") .for_child(&lnav_theme::lt_style_doc_directive) .with_children(style_config_handlers), yajlpp::property_handler("variable") .with_description("Styling for variables in text") .for_child(&lnav_theme::lt_style_variable) .with_children(style_config_handlers), yajlpp::property_handler("symbol") .with_description("Styling for symbols in source files") .for_child(&lnav_theme::lt_style_symbol) .with_children(style_config_handlers), yajlpp::property_handler("number") .with_description("Styling for numbers in source files") .for_child(&lnav_theme::lt_style_number) .with_children(style_config_handlers), yajlpp::property_handler("type") .with_description("Styling for types in source files") .for_child(&lnav_theme::lt_style_type) .with_children(style_config_handlers), yajlpp::property_handler("function") .with_description("Styling for functions in source files") .for_child(&lnav_theme::lt_style_function) .with_children(style_config_handlers), yajlpp::property_handler("separators-references-accessors") .with_description("Styling for sigils in source files") .for_child(&lnav_theme::lt_style_sep_ref_acc) .with_children(style_config_handlers), yajlpp::property_handler("re-special") .with_description( "Styling for special characters in regular expressions") .for_child(&lnav_theme::lt_style_re_special) .with_children(style_config_handlers), yajlpp::property_handler("re-repeat") .with_description("Styling for repeats in regular expressions") .for_child(&lnav_theme::lt_style_re_repeat) .with_children(style_config_handlers), yajlpp::property_handler("diff-delete") .with_description("Styling for deleted lines in diffs") .for_child(&lnav_theme::lt_style_diff_delete) .with_children(style_config_handlers), yajlpp::property_handler("diff-add") .with_description("Styling for added lines in diffs") .for_child(&lnav_theme::lt_style_diff_add) .with_children(style_config_handlers), yajlpp::property_handler("diff-section") .with_description("Styling for diffs") .for_child(&lnav_theme::lt_style_diff_section) .with_children(style_config_handlers), yajlpp::property_handler("spectrogram-low") .with_description( "Styling for the lower threshold values in the spectrogram view") .for_child(&lnav_theme::lt_style_low_threshold) .with_children(style_config_handlers), yajlpp::property_handler("spectrogram-medium") .with_description( "Styling for the medium threshold values in the spectrogram view") .for_child(&lnav_theme::lt_style_med_threshold) .with_children(style_config_handlers), yajlpp::property_handler("spectrogram-high") .with_description( "Styling for the high threshold values in the spectrogram view") .for_child(&lnav_theme::lt_style_high_threshold) .with_children(style_config_handlers), yajlpp::property_handler("file") .with_description("Styling for file names in source files") .for_child(&lnav_theme::lt_style_file) .with_children(style_config_handlers), }; static const struct json_path_container theme_status_styles_handlers = { yajlpp::property_handler("text") .with_description("Styling for status bars") .for_child(&lnav_theme::lt_style_status) .with_children(style_config_handlers), yajlpp::property_handler("warn") .with_description("Styling for warnings in status bars") .for_child(&lnav_theme::lt_style_warn_status) .with_children(style_config_handlers), yajlpp::property_handler("alert") .with_description("Styling for alerts in status bars") .for_child(&lnav_theme::lt_style_alert_status) .with_children(style_config_handlers), yajlpp::property_handler("active") .with_description("Styling for activity in status bars") .for_child(&lnav_theme::lt_style_active_status) .with_children(style_config_handlers), yajlpp::property_handler("inactive-alert") .with_description("Styling for inactive alert status bars") .for_child(&lnav_theme::lt_style_inactive_alert_status) .with_children(style_config_handlers), yajlpp::property_handler("inactive") .with_description("Styling for inactive status bars") .for_child(&lnav_theme::lt_style_inactive_status) .with_children(style_config_handlers), yajlpp::property_handler("title-hotkey") .with_description("Styling for hotkey highlights in titles") .for_child(&lnav_theme::lt_style_status_title_hotkey) .with_children(style_config_handlers), yajlpp::property_handler("title") .with_description("Styling for title sections of status bars") .for_child(&lnav_theme::lt_style_status_title) .with_children(style_config_handlers), yajlpp::property_handler("disabled-title") .with_description("Styling for title sections of status bars") .for_child(&lnav_theme::lt_style_status_disabled_title) .with_children(style_config_handlers), yajlpp::property_handler("subtitle") .with_description("Styling for subtitle sections of status bars") .for_child(&lnav_theme::lt_style_status_subtitle) .with_children(style_config_handlers), yajlpp::property_handler("info") .with_description("Styling for informational messages in status bars") .for_child(&lnav_theme::lt_style_status_info) .with_children(style_config_handlers), yajlpp::property_handler("hotkey") .with_description("Styling for hotkey highlights of status bars") .for_child(&lnav_theme::lt_style_status_hotkey) .with_children(style_config_handlers), }; static const struct json_path_container theme_log_level_styles_handlers = { yajlpp::pattern_property_handler( "(?<level>trace|debug5|debug4|debug3|debug2|debug|info|stats|notice|" "warning|error|critical|fatal|invalid)") .with_obj_provider<style_config, lnav_theme>( [](const yajlpp_provider_context& ypc, lnav_theme* root) { auto& sc = root->lt_level_styles[string2level( ypc.get_substr_i("level").get())]; if (ypc.ypc_parse_context != nullptr && sc.pp_path.empty()) { sc.pp_path = ypc.ypc_parse_context->get_full_path(); } return &sc.pp_value; }) .with_path_provider<lnav_theme>( [](struct lnav_theme* cfg, std::vector<std::string>& paths_out) { for (int lpc = LEVEL_TRACE; lpc < LEVEL__MAX; lpc++) { paths_out.emplace_back(level_names[lpc]); } }) .with_children(style_config_handlers), }; static const struct json_path_container highlighter_handlers = { yajlpp::property_handler("pattern") .with_synopsis("regular expression") .with_description("The regular expression to highlight") .for_field(&highlighter_config::hc_regex), yajlpp::property_handler("style") .with_description( "The styling for the text that matches the associated pattern") .for_child(&highlighter_config::hc_style) .with_children(style_config_handlers), }; static const struct json_path_container theme_highlights_handlers = { yajlpp::pattern_property_handler("(?<highlight_name>[\\w\\-]+)") .with_obj_provider<highlighter_config, lnav_theme>([](const yajlpp_provider_context& ypc, lnav_theme* root) { highlighter_config& hc = root->lt_highlights[ypc.get_substr_i("highlight_name").get()]; return &hc; }) .with_path_provider<lnav_theme>( [](struct lnav_theme* cfg, std::vector<std::string>& paths_out) { for (const auto& pair : cfg->lt_highlights) { paths_out.emplace_back(pair.first); } }) .with_children(highlighter_handlers), }; static const struct json_path_container theme_vars_handlers = { yajlpp::pattern_property_handler("(?<var_name>\\w+)") .with_synopsis("name") .with_description("A theme variable definition") .with_path_provider<lnav_theme>( [](struct lnav_theme* lt, std::vector<std::string>& paths_out) { for (const auto& iter : lt->lt_vars) { paths_out.emplace_back(iter.first); } }) .for_field(&lnav_theme::lt_vars), }; static const struct json_path_container theme_def_handlers = { yajlpp::property_handler("vars") .with_description("Variables definitions that are used in this theme.") .with_children(theme_vars_handlers), yajlpp::property_handler("styles") .with_description("Styles for log messages.") .with_children(theme_styles_handlers), yajlpp::property_handler("syntax-styles") .with_description("Styles for syntax highlighting in text files.") .with_children(theme_syntax_styles_handlers), yajlpp::property_handler("status-styles") .with_description("Styles for the user-interface components.") .with_children(theme_status_styles_handlers), yajlpp::property_handler("log-level-styles") .with_description("Styles for each log message level.") .with_children(theme_log_level_styles_handlers), yajlpp::property_handler("highlights") .with_description("Styles for text highlights.") .with_children(theme_highlights_handlers), }; static const struct json_path_container theme_defs_handlers = { yajlpp::pattern_property_handler("(?<theme_name>[\\w\\-]+)") .with_description("Theme definitions") .with_obj_provider<lnav_theme, _lnav_config>( [](const yajlpp_provider_context& ypc, _lnav_config* root) { lnav_theme& lt = root->lc_ui_theme_defs[ypc.get_substr("theme_name")]; return &lt; }) .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_ui_theme_defs) { paths_out.emplace_back(iter.first); } }) .with_obj_deleter( +[](const yajlpp_provider_context& ypc, _lnav_config* root) { root->lc_ui_theme_defs.erase(ypc.get_substr("theme_name")); }) .with_children(theme_def_handlers), }; static const struct json_path_container ui_handlers = { yajlpp::property_handler("clock-format") .with_synopsis("format") .with_description("The format for the clock displayed in " "the top-left corner using strftime(3) conversions") .with_example("%a %b %d %H:%M:%S %Z") .for_field(&_lnav_config::lc_top_status_cfg, &top_status_source_cfg::tssc_clock_format), yajlpp::property_handler("dim-text") .with_synopsis("bool") .with_description("Reduce the brightness of text (useful for xterms). " "This setting can be useful when running in an xterm " "where the white color is very bright.") .for_field(&_lnav_config::lc_ui_dim_text), yajlpp::property_handler("default-colors") .with_synopsis("bool") .with_description( "Use default terminal background and foreground colors " "instead of black and white for all text coloring. This setting " "can be useful when transparent background or alternate color " "theme terminal is used.") .for_field(&_lnav_config::lc_ui_default_colors), yajlpp::property_handler("keymap") .with_synopsis("keymap_name") .with_description("The name of the keymap to use.") .for_field(&_lnav_config::lc_ui_keymap), yajlpp::property_handler("theme") .with_synopsis("theme_name") .with_description("The name of the theme to use.") .for_field(&_lnav_config::lc_ui_theme), yajlpp::property_handler("theme-defs") .with_description("Theme definitions.") .with_children(theme_defs_handlers), yajlpp::property_handler("movement") .with_description("Log file cursor movement mode settings") .with_children(movement_handlers), yajlpp::property_handler("keymap-defs") .with_description("Keymap definitions.") .with_children(keymap_defs_handlers), }; static const struct json_path_container archive_handlers = { yajlpp::property_handler("min-free-space") .with_synopsis("<bytes>") .with_description( "The minimum free space, in bytes, to maintain when unpacking " "archives") .with_min_value(0) .for_field(&_lnav_config::lc_archive_manager, &archive_manager::config::amc_min_free_space), yajlpp::property_handler("cache-ttl") .with_synopsis("<duration>") .with_description( "The time-to-live for unpacked archives, expressed as a duration " "(e.g. '3d' for three days)") .with_example("3d") .with_example("12h") .for_field(&_lnav_config::lc_archive_manager, &archive_manager::config::amc_cache_ttl), }; static const struct json_path_container piper_handlers = { yajlpp::property_handler("max-size") .with_synopsis("<bytes>") .with_description("The maximum size of a capture file") .with_min_value(128) .for_field(&_lnav_config::lc_piper, &lnav::piper::config::c_max_size), yajlpp::property_handler("rotations") .with_synopsis("<count>") .with_min_value(2) .with_description("The number of rotated files to keep") .for_field(&_lnav_config::lc_piper, &lnav::piper::config::c_rotations), yajlpp::property_handler("ttl") .with_synopsis("<duration>") .with_description( "The time-to-live for captured data, expressed as a duration " "(e.g. '3d' for three days)") .with_example("3d") .with_example("12h") .for_field(&_lnav_config::lc_piper, &lnav::piper::config::c_ttl), }; static const struct json_path_container file_vtab_handlers = { yajlpp::property_handler("max-content-size") .with_synopsis("<bytes>") .with_description( "The maximum allowed file size for the content column") .with_min_value(0) .for_field(&_lnav_config::lc_file_vtab, &file_vtab::config::fvc_max_content_size), }; static const struct json_path_container logfile_handlers = { yajlpp::property_handler("max-unrecognized-lines") .with_synopsis("<lines>") .with_description("The maximum number of lines in a file to use when " "detecting the format") .with_min_value(1) .for_field(&_lnav_config::lc_logfile, &lnav::logfile::config::lc_max_unrecognized_lines), }; static const struct json_path_container ssh_config_handlers = { yajlpp::pattern_property_handler("(?<config_name>\\w+)") .with_synopsis("name") .with_description("Set an SSH configuration value") .with_path_provider<_lnav_config>( [](auto* m, std::vector<std::string>& paths_out) { for (const auto& pair : m->lc_tailer.c_ssh_config) { paths_out.emplace_back(pair.first); } }) .for_field(&_lnav_config::lc_tailer, &tailer::config::c_ssh_config), }; static const struct json_path_container ssh_option_handlers = { yajlpp::pattern_property_handler("(?<option_name>\\w+)") .with_synopsis("name") .with_description("Set an option to be passed to the SSH command") .for_field(&_lnav_config::lc_tailer, &tailer::config::c_ssh_options), }; static const struct json_path_container ssh_handlers = { yajlpp::property_handler("command") .with_synopsis("ssh-command") .with_description("The SSH command to execute") .for_field(&_lnav_config::lc_tailer, &tailer::config::c_ssh_cmd), yajlpp::property_handler("transfer-command") .with_synopsis("command") .with_description( "Command executed on the remote host when transferring the file") .for_field(&_lnav_config::lc_tailer, &tailer::config::c_transfer_cmd), yajlpp::property_handler("start-command") .with_synopsis("command") .with_description( "Command executed on the remote host to start the tailer") .for_field(&_lnav_config::lc_tailer, &tailer::config::c_start_cmd), yajlpp::property_handler("flags") .with_description("The flags to pass to the SSH command") .for_field(&_lnav_config::lc_tailer, &tailer::config::c_ssh_flags), yajlpp::property_handler("options") .with_description("The options to pass to the SSH command") .with_children(ssh_option_handlers), yajlpp::property_handler("config") .with_description( "The ssh_config options to pass to SSH with the -o option") .with_children(ssh_config_handlers), }; static const struct json_path_container remote_handlers = { yajlpp::property_handler("cache-ttl") .with_synopsis("<duration>") .with_description("The time-to-live for files copied from remote " "hosts, expressed as a duration " "(e.g. '3d' for three days)") .with_example("3d") .with_example("12h") .for_field(&_lnav_config::lc_tailer, &tailer::config::c_cache_ttl), yajlpp::property_handler("ssh") .with_description( "Settings related to the ssh command used to contact remote " "machines") .with_children(ssh_handlers), }; static const struct json_path_container sysclip_impl_cmd_handlers = json_path_container{ yajlpp::property_handler("write") .with_synopsis("<command>") .with_description("The command used to write to the clipboard") .with_example("pbcopy") .for_field(&sysclip::clip_commands::cc_write), yajlpp::property_handler("read") .with_synopsis("<command>") .with_description("The command used to read from the clipboard") .with_example("pbpaste") .for_field(&sysclip::clip_commands::cc_read), } .with_description("Container for the commands used to read from and write to the system clipboard") .with_definition_id("clip-commands"); static const struct json_path_container sysclip_impl_handlers = { yajlpp::property_handler("test") .with_synopsis("<command>") .with_description("The command that checks") .with_example("command -v pbcopy") .for_field(&sysclip::clipboard::c_test_command), yajlpp::property_handler("general") .with_description("Commands to work with the general clipboard") .for_child(&sysclip::clipboard::c_general) .with_children(sysclip_impl_cmd_handlers), yajlpp::property_handler("find") .with_description("Commands to work with the find clipboard") .for_child(&sysclip::clipboard::c_find) .with_children(sysclip_impl_cmd_handlers), }; static const struct json_path_container sysclip_impls_handlers = { yajlpp::pattern_property_handler("(?<clipboard_impl_name>[\\w\\-]+)") .with_synopsis("<name>") .with_description("Clipboard implementation") .with_obj_provider<sysclip::clipboard, _lnav_config>( [](const yajlpp_provider_context& ypc, _lnav_config* root) { auto& retval = root->lc_sysclip.c_clipboard_impls[ypc.get_substr( "clipboard_impl_name")]; return &retval; }) .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_sysclip.c_clipboard_impls) { paths_out.emplace_back(iter.first); } }) .with_children(sysclip_impl_handlers), }; static const struct json_path_container sysclip_handlers = { yajlpp::property_handler("impls") .with_description("Clipboard implementations") .with_children(sysclip_impls_handlers), }; static const struct json_path_container log_source_watch_expr_handlers = { yajlpp::property_handler("expr") .with_synopsis("<SQL-expression>") .with_description("The SQL expression to execute for each input line. " "If expression evaluates to true, a 'log message " "detected' event will be published.") .for_field(&logfile_sub_source_ns::watch_expression::we_expr), yajlpp::property_handler("enabled") .with_description("Indicates whether or not this expression should be " "evaluated during log processing.") .for_field(&logfile_sub_source_ns::watch_expression::we_enabled), }; static const struct json_path_container log_source_watch_handlers = { yajlpp::pattern_property_handler("(?<watch_name>[\\w\\.\\-]+)") .with_synopsis("<name>") .with_description("A log message watch expression") .with_obj_provider<logfile_sub_source_ns::watch_expression, _lnav_config>( [](const yajlpp_provider_context& ypc, _lnav_config* root) { auto& retval = root->lc_log_source .c_watch_exprs[ypc.get_substr("watch_name")]; return &retval; }) .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_log_source.c_watch_exprs) { paths_out.emplace_back(iter.first); } }) .with_obj_deleter( +[](const yajlpp_provider_context& ypc, _lnav_config* root) { root->lc_log_source.c_watch_exprs.erase( ypc.get_substr("watch_name")); }) .with_children(log_source_watch_expr_handlers), }; static const struct json_path_container annotation_handlers = { yajlpp::property_handler("description") .with_synopsis("<text>") .with_description("A description of this annotation") .for_field(&lnav::log::annotate::annotation_def::a_description), yajlpp::property_handler("condition") .with_synopsis("<SQL-expression>") .with_description( "The SQLite expression to execute for a log message that " "determines whether or not this annotation is applicable. The " "expression is evaluated the same way as a filter expression") .with_min_length(1) .for_field(&lnav::log::annotate::annotation_def::a_condition), yajlpp::property_handler("handler") .with_synopsis("<script>") .with_description("The script to execute to generate the annotation " "content. A JSON object with the log message content " "will be sent to the script on the standard input") .with_min_length(1) .for_field(&lnav::log::annotate::annotation_def::a_handler), }; static const struct json_path_container annotations_handlers = { yajlpp::pattern_property_handler(R"((?<annotation_name>[\w\.\-]+))") .with_obj_provider<lnav::log::annotate::annotation_def, _lnav_config>( [](const yajlpp_provider_context& ypc, _lnav_config* root) { auto* retval = &(root->lc_log_annotations .a_definitions[ypc.get_substr_i(0)]); return retval; }) .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_log_annotations.a_definitions) { paths_out.emplace_back(iter.first.to_string()); } }) .with_children(annotation_handlers), }; static const struct json_path_container log_date_time_handlers = { yajlpp::property_handler("convert-zoned-to-local") .with_description("Convert timestamps with ") .with_pattern(R"(^[\w\-]+(?!\.lnav)$)") .for_field(&_lnav_config::lc_log_date_time, &date_time_scanner_ns::config::c_zoned_to_local), }; static const struct json_path_container log_source_handlers = { yajlpp::property_handler("date-time") .with_description("Settings related to log message dates and times") .with_children(log_date_time_handlers), yajlpp::property_handler("watch-expressions") .with_description("Log message watch expressions") .with_children(log_source_watch_handlers), yajlpp::property_handler("annotations").with_children(annotations_handlers), }; static const struct json_path_container url_scheme_handlers = { yajlpp::property_handler("handler") .with_description( "The name of the lnav script that can handle URLs " "with of this scheme. This should not include the '.lnav' suffix.") .with_pattern(R"(^[\w\-]+(?!\.lnav)$)") .for_field(&lnav::url_handler::scheme::p_handler), }; static const struct json_path_container url_handlers = { yajlpp::pattern_property_handler(R"((?<url_scheme>[a-z][\w\-\+\.]+))") .with_description("Definition of a custom URL scheme") .with_obj_provider<lnav::url_handler::scheme, _lnav_config>( [](const yajlpp_provider_context& ypc, _lnav_config* root) { auto& retval = root->lc_url_handlers .c_schemes[ypc.get_substr("url_scheme")]; return &retval; }) .with_path_provider<_lnav_config>( [](struct _lnav_config* cfg, std::vector<std::string>& paths_out) { for (const auto& iter : cfg->lc_url_handlers.c_schemes) { paths_out.emplace_back(iter.first); } }) .with_children(url_scheme_handlers), }; static const struct json_path_container tuning_handlers = { yajlpp::property_handler("archive-manager") .with_description("Settings related to opening archive files") .with_children(archive_handlers), yajlpp::property_handler("piper") .with_description("Settings related to capturing piped data") .with_children(piper_handlers), yajlpp::property_handler("file-vtab") .with_description("Settings related to the lnav_file virtual-table") .with_children(file_vtab_handlers), yajlpp::property_handler("logfile") .with_description("Settings related to log files") .with_children(logfile_handlers), yajlpp::property_handler("remote") .with_description("Settings related to remote file support") .with_children(remote_handlers), yajlpp::property_handler("clipboard") .with_description("Settings related to the clipboard") .with_children(sysclip_handlers), yajlpp::property_handler("url-scheme") .with_description("Settings related to custom URL handling") .with_children(url_handlers), }; const char* DEFAULT_CONFIG_SCHEMA = "https://lnav.org/schemas/config-v1.schema.json"; static const std::set<std::string> SUPPORTED_CONFIG_SCHEMAS = { DEFAULT_CONFIG_SCHEMA, }; const char* DEFAULT_FORMAT_SCHEMA = "https://lnav.org/schemas/format-v1.schema.json"; const std::set<std::string> SUPPORTED_FORMAT_SCHEMAS = { DEFAULT_FORMAT_SCHEMA, }; static int read_id(yajlpp_parse_context* ypc, const unsigned char* str, size_t len) { auto file_id = std::string((const char*) str, len); if (SUPPORTED_CONFIG_SCHEMAS.count(file_id) == 0) { const auto* handler = ypc->ypc_current_handler; attr_line_t notes{"expecting one of the following $schema values:"}; for (const auto& schema : SUPPORTED_CONFIG_SCHEMAS) { notes.append("\n").append( lnav::roles::symbol(fmt::format(FMT_STRING(" {}"), schema))); } ypc->report_error( lnav::console::user_message::error( attr_line_t() .append_quoted(lnav::roles::symbol(file_id)) .append( " is not a supported configuration $schema version")) .with_snippet(ypc->get_snippet()) .with_note(notes) .with_help(handler->get_help_text(ypc))); } return 1; } const json_path_container lnav_config_handlers = json_path_container { json_path_handler("$schema", read_id) .with_synopsis("<schema-uri>") .with_description("The URI that specifies the schema that describes this type of file") .with_example(DEFAULT_CONFIG_SCHEMA), yajlpp::property_handler("tuning") .with_description("Internal settings") .with_children(tuning_handlers), yajlpp::property_handler("ui") .with_description("User-interface settings") .with_children(ui_handlers), yajlpp::property_handler("log") .with_description("Log message settings") .with_children(log_source_handlers), yajlpp::property_handler("global") .with_description("Global variable definitions") .with_children(global_var_handlers), } .with_schema_id(*SUPPORTED_CONFIG_SCHEMAS.cbegin()); class active_key_map_listener : public lnav_config_listener { public: active_key_map_listener() : lnav_config_listener(__FILE__) {} void reload_config(error_reporter& reporter) override { lnav_config.lc_active_keymap = lnav_config.lc_ui_keymaps["default"]; for (const auto& pair : lnav_config.lc_ui_keymaps[lnav_config.lc_ui_keymap].km_seq_to_cmd) { lnav_config.lc_active_keymap.km_seq_to_cmd[pair.first] = pair.second; } } }; static active_key_map_listener KEYMAP_LISTENER; Result<config_file_type, std::string> detect_config_file_type(const ghc::filesystem::path& path) { static const char* id_path[] = {"$schema", nullptr}; auto content = TRY(lnav::filesystem::read_file(path)); if (startswith(content, "#")) { content.insert(0, "//"); } char error_buffer[1024]; auto content_tree = std::unique_ptr<yajl_val_s, decltype(&yajl_tree_free)>( yajl_tree_parse(content.c_str(), error_buffer, sizeof(error_buffer)), yajl_tree_free); if (content_tree == nullptr) { return Err( fmt::format(FMT_STRING("JSON parsing failed -- {}"), error_buffer)); } auto* id_val = yajl_tree_get(content_tree.get(), id_path, yajl_t_string); if (id_val != nullptr) { if (SUPPORTED_CONFIG_SCHEMAS.count(id_val->u.string)) { return Ok(config_file_type::CONFIG); } if (SUPPORTED_FORMAT_SCHEMAS.count(id_val->u.string)) { return Ok(config_file_type::FORMAT); } return Err(fmt::format( FMT_STRING("unsupported configuration version in file -- {}"), id_val->u.string)); } return Ok(config_file_type::FORMAT); } static void load_config_from(_lnav_config& lconfig, const ghc::filesystem::path& path, std::vector<lnav::console::user_message>& errors) { yajlpp_parse_context ypc(intern_string::lookup(path.string()), &lnav_config_handlers); struct config_userdata ud(errors); auto_fd fd; log_info("loading configuration from %s", path.c_str()); ypc.ypc_locations = &lnav_config_locations; ypc.with_obj(lconfig); ypc.ypc_userdata = &ud; ypc.with_error_reporter(config_error_reporter); if ((fd = lnav::filesystem::openp(path, O_RDONLY)) == -1) { if (errno != ENOENT) { errors.emplace_back( lnav::console::user_message::error( attr_line_t("unable to open configuration file: ") .append(lnav::roles::file(path))) .with_errno_reason()); } } else { char buffer[2048]; ssize_t rc = -1; auto handle = yajlpp::alloc_handle(&ypc.ypc_callbacks, &ypc); yajl_config(handle, yajl_allow_comments, 1); yajl_config(handle, yajl_allow_multiple_values, 1); ypc.ypc_handle = handle; while (true) { rc = read(fd, buffer, sizeof(buffer)); if (rc == 0) { break; } if (rc == -1) { errors.emplace_back( lnav::console::user_message::error( attr_line_t("unable to read format file: ") .append(lnav::roles::file(path))) .with_errno_reason()); break; } if (ypc.parse((const unsigned char*) buffer, rc) != yajl_status_ok) { break; } } if (rc == 0) { ypc.complete_parse(); } } } static bool load_default_config(struct _lnav_config& config_obj, const std::string& path, const bin_src_file& bsf, std::vector<lnav::console::user_message>& errors) { yajlpp_parse_context ypc_builtin(intern_string::lookup(bsf.get_name()), &lnav_config_handlers); struct config_userdata ud(errors); auto handle = yajlpp::alloc_handle(&ypc_builtin.ypc_callbacks, &ypc_builtin); ypc_builtin.ypc_locations = &lnav_config_locations; ypc_builtin.with_handle(handle); ypc_builtin.with_obj(config_obj); ypc_builtin.with_error_reporter(config_error_reporter); ypc_builtin.ypc_userdata = &ud; if (path != "*") { ypc_builtin.ypc_ignore_unused = true; ypc_builtin.ypc_active_paths.insert(path); } yajl_config(handle, yajl_allow_comments, 1); yajl_config(handle, yajl_allow_multiple_values, 1); ypc_builtin.parse_doc(bsf.to_string_fragment()); return path == "*" || ypc_builtin.ypc_active_paths.empty(); } static bool load_default_configs(struct _lnav_config& config_obj, const std::string& path, std::vector<lnav::console::user_message>& errors) { auto retval = false; for (auto& bsf : lnav_config_json) { retval = load_default_config(config_obj, path, bsf, errors) || retval; } return retval; } void load_config(const std::vector<ghc::filesystem::path>& extra_paths, std::vector<lnav::console::user_message>& errors) { auto user_config = lnav::paths::dotlnav() / "config.json"; for (auto& bsf : lnav_config_json) { auto sample_path = lnav::paths::dotlnav() / "configs" / "default" / fmt::format(FMT_STRING("{}.sample"), bsf.get_name()); auto write_res = lnav::filesystem::write_file(sample_path, bsf.to_string_fragment()); if (write_res.isErr()) { fprintf(stderr, "error:unable to write default config file: %s -- %s\n", sample_path.c_str(), write_res.unwrapErr().c_str()); } } { log_info("loading builtin configuration into default"); load_default_configs(lnav_default_config, "*", errors); log_info("loading builtin configuration into base"); load_default_configs(lnav_config, "*", errors); log_info("loading installed configuration files"); for (const auto& extra_path : extra_paths) { auto config_path = extra_path / "configs/*/*.json"; static_root_mem<glob_t, globfree> gl; if (glob(config_path.c_str(), 0, nullptr, gl.inout()) == 0) { for (size_t lpc = 0; lpc < gl->gl_pathc; lpc++) { load_config_from(lnav_config, gl->gl_pathv[lpc], errors); if (errors.empty()) { load_config_from( lnav_default_config, gl->gl_pathv[lpc], errors); } } } } for (const auto& extra_path : extra_paths) { auto config_path = extra_path / "formats/*/config.*.json"; static_root_mem<glob_t, globfree> gl; if (glob(config_path.c_str(), 0, nullptr, gl.inout()) == 0) { for (size_t lpc = 0; lpc < gl->gl_pathc; lpc++) { load_config_from(lnav_config, gl->gl_pathv[lpc], errors); if (errors.empty()) { load_config_from( lnav_default_config, gl->gl_pathv[lpc], errors); } } } } log_info("loading user configuration"); load_config_from(lnav_config, user_config, errors); } reload_config(errors); rollback_lnav_config = lnav_config; } std::string dump_config() { yajlpp_gen gen; yajlpp_gen_context ygc(gen, lnav_config_handlers); yajl_gen_config(gen, yajl_gen_beautify, true); ygc.with_obj(lnav_config); ygc.gen(); return gen.to_string_fragment().to_string(); } void reset_config(const std::string& path) { std::vector<lnav::console::user_message> errors; load_default_configs(lnav_config, path, errors); if (path != "*") { static const auto INPUT_SRC = intern_string::lookup("input"); yajlpp_parse_context ypc(INPUT_SRC, &lnav_config_handlers); ypc.set_path(path) .with_obj(lnav_config) .with_error_reporter([&errors](const auto& ypc, auto msg) { errors.push_back(msg); }); ypc.ypc_active_paths.insert(path); ypc.update_callbacks(); const json_path_handler_base* jph = ypc.ypc_current_handler; if (!ypc.ypc_handler_stack.empty()) { jph = ypc.ypc_handler_stack.back(); } if (jph != nullptr && jph->jph_children && jph->jph_obj_deleter) { auto key_start = ypc.ypc_path_index_stack.back(); auto path_frag = string_fragment::from_byte_range( ypc.ypc_path.data(), key_start + 1, ypc.ypc_path.size()); auto md = jph->jph_regex->create_match_data(); yajlpp_provider_context provider_ctx{&md, static_cast<size_t>(-1)}; jph->jph_regex->capture_from(path_frag).into(md).matches(); jph->jph_obj_deleter(provider_ctx, ypc.ypc_obj_stack.top()); } } reload_config(errors); for (const auto& err : errors) { log_debug("reset %s", err.um_message.get_string().c_str()); } } std::string save_config() { auto user_config = lnav::paths::dotlnav() / "config.json"; yajlpp_gen gen; yajlpp_gen_context ygc(gen, lnav_config_handlers); ygc.with_default_obj(lnav_default_config).with_obj(lnav_config); ygc.gen(); auto config_str = gen.to_string_fragment().to_string(); char errbuf[1024]; auto_mem<yajl_val_s> tree(yajl_tree_free); tree = yajl_tree_parse(config_str.c_str(), errbuf, sizeof(errbuf)); if (tree == nullptr) { return fmt::format( FMT_STRING("error: unable to save configuration -- {}"), errbuf); } yajl_cleanup_tree(tree); yajlpp_gen clean_gen; yajl_gen_config(clean_gen, yajl_gen_beautify, true); yajl_gen_tree(clean_gen, tree); auto write_res = lnav::filesystem::write_file( user_config, clean_gen.to_string_fragment()); if (write_res.isErr()) { return fmt::format( FMT_STRING("error: unable to write configuration file: {} -- {}"), user_config.string(), write_res.unwrapErr()); } return "info: configuration saved"; } void reload_config(std::vector<lnav::console::user_message>& errors) { lnav_config_listener* curr = lnav_config_listener::LISTENER_LIST; while (curr != nullptr) { auto reporter = [&errors](const void* cfg_value, const lnav::console::user_message& errmsg) { log_error("configuration error: %s", errmsg.to_attr_line().get_string().c_str()); auto cb = [&cfg_value, &errors, &errmsg]( const json_path_handler_base& jph, const std::string& path, const void* mem) { if (mem != cfg_value) { return; } auto loc_iter = lnav_config_locations.find(intern_string::lookup(path)); auto has_loc = loc_iter != lnav_config_locations.end(); auto um = lnav::console::user_message::error( attr_line_t() .append(has_loc ? "invalid value for property " : "missing value for property ") .append_quoted(lnav::roles::symbol(path))) .with_reason(errmsg) .with_help(jph.get_help_text(path)); if (has_loc) { um.with_snippet( lnav::console::snippet::from(loc_iter->second.sl_source, "") .with_line(loc_iter->second.sl_line_number)); } errors.emplace_back(um); }; for (const auto& jph : lnav_config_handlers.jpc_children) { jph.walk(cb, &lnav_config); } }; curr->reload_config(reporter); curr = curr->lcl_next; } }
#ifndef MATAUXILIAR_H #define MATAUXILIAR_H #include <iostream> #include <QString> #include <opencv2/opencv.hpp> /* Funciones para dibujar/escribir en matrices de opencv */ void writeText(cv::Mat img, std::string text, int x, int y, cv::Scalar color, double fontscale=0.4); void drawRec(cv::Mat &frame); void drawMovBar(cv::Mat &image, int mov_percent); void writeAlert(cv::Mat &frame, QString alert_msg); #endif // MATAUXILIAR_H
/* Copyright (c) 2012 <benemorius@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef OBCLCD_H #define OBCLCD_H #include "SPI.h" #include "IO.h" #define LCD_MAX_CHARACTERS (20) #define CLOCK_MAX_CHARACTERS (4) namespace ObcLcdSymbolMasks { const uint8_t symbol[] = {0x4, 0x4, 0x4, 0x8, 0x8, 0xc, 0x4, 0x4, 0x4}; } namespace ObcLcdSymbolOffsets { const uint8_t symbol[] = {0x0, 0x3, 0x4, 0x2, 0x4, 0x6, 0x1, 0x7, 0x5}; } namespace ObcLcdSymbols { enum symbol { LeftArrow = 0x0, RightArrow = 0x1, Plus = 0x2, TopDot = 0x3, BottomDot = 0x4, Periods = 0x5, Memo = 0x6, AM = 0x7, PM = 0x8, }; } class ObcLcd { public: ObcLcd(SPI& spi, IO& cs, IO& refresh, IO& unk0, IO& unk1, uint32_t spiClockrateHz = 1000000); void printf(char* format, ...); void printfClock(char* format, ...); void clear(); void clearClock(); void setSymbol(ObcLcdSymbols::symbol symbol, bool isOn); private: void update(); void testSymbols(); void sendSymbols(); SPI& spi; IO& cs; IO& refresh; IO& unk0; IO& unk1; uint32_t spiClockrate; uint8_t symbolBytes[8]; static const uint8_t constBytes[8]; char lcdBuffer[LCD_MAX_CHARACTERS+1]; char clockBuffer[CLOCK_MAX_CHARACTERS+1]; }; #endif // OBCLCD_H
#include<iostream> using namespace std; int main() { int i,n,j,k,m; j=0; int index[100], nums[100], output[100]; cout<<"Enter length of array\n"; cin>>n; for(i=0;i<n;i++) { cout<<"Enter elements of nums array\n"; cin>>nums[i]; cout<<endl; output[i]=-1; } for(i=0;i<n;i++) { cout<<"Enter elements of index array\n"; cin>>index[i]; cout<<endl; } for(i=0;i<n;i++) { k=index[i]; if(output[k]==-1) { output[k]=nums[j]; j++; } else { for(m=n-1;m>=k;m--) output[m]=output[m-1]; output[k]=nums[j]; j++; } } for(i=0;i<n;i++) {cout<<output[i]<<",";} return 0; }
#include "AllJoynBase.h" #include "alljoyn\AuthListener.h" //static volatile sig_atomic_t s_interrupt = false; // //static void CDECL_CALL SigIntHandler(int sig) //{ // QCC_UNUSED(sig); // s_interrupt = true; //} volatile sig_atomic_t AllJoynBase::mInterrupt = false; void CDECL_CALL AllJoynBase::SigIntHandler(int sig) { QCC_UNUSED(sig); AllJoynBase::mInterrupt = true; } AllJoynBase::AllJoynBase() { mBus = NULL; mObjectInterface = NULL; } QStatus AllJoynBase::CreateInterface() { /* Create org.alljoyn.bus.samples.chat interface */ mObjectInterface = NULL; QStatus status = mBus->CreateInterface(CHAT_SERVICE_INTERFACE_NAME, mObjectInterface); if (ER_OK == status) { mCreateInterfaceManaged(); mObjectInterface->Activate(); return status; } else { printf("Failed to create interface \"%s\" (%s)\n", CHAT_SERVICE_INTERFACE_NAME, QCC_StatusText(status)); } return status; } /* void AllJoynBase::Invoke(const InterfaceDescription::Member* member, Message& msg) { const MsgArg * pArgs; size_t numArgs = 0; msg->GetArgs(numArgs, pArgs); mStartInvokeManaged(member->name.c_str(), numArgs); for (size_t i = 0; i < numArgs; i++) { switch (pArgs[i].typeId) { case AllJoynTypeId::ALLJOYN_STRING: ((SendStringArg)handlers[AllJoynTypeId::ALLJOYN_STRING])(pArgs[i].v_string.str); break; default: // Throw an error break; } } mFinishInvokeManaged(); } */ QStatus AllJoynBase::StartMessageBus(void) { QStatus status = mBus->Start(); if (ER_OK == status) { printf("BusAttachment started.\n"); } else { printf("Start of BusAttachment failed (%s).\n", QCC_StatusText(status)); } return status; } bool AllJoynBase::AddInterfaceMember( const char* name, const char* inputSig, const char* outSig, const char* argNames, int memberType) // 0 signal, 1 method { std::string args = argNames; std::string input; if (!args.empty()) args += ","; if (outSig != "") args += "reply"; printf("Interface name = %s.\n", mObjectInterface->GetName()); switch (memberType) { case 0: printf("Adding Signal %s \n", name); return mObjectInterface->AddSignal(name, inputSig, argNames, 0) == ER_OK; case 1: input = inputSig; printf("Adding method \"%s\" \"%s\" \"%s\" \"%s\" %d \n", name, input.c_str(), outSig, args.c_str(), 0); return mObjectInterface->AddMethod(name, input.c_str(), outSig, args.c_str(), 0) == ER_OK; default: return false; } } /** Connect, report the result to stdout, and return the status code. */ QStatus AllJoynBase::ConnectBusAttachment(void) { QStatus status = mBus->Connect(); if (ER_OK == status) { printf("Connect to '%s' succeeded.\n", mBus->GetConnectSpec().c_str()); } else { printf("Failed to connect to '%s' (%s).\n", mBus->GetConnectSpec().c_str(), QCC_StatusText(status)); } return status; } QStatus AllJoynBase::Initialize() { QStatus status; if ((status = AllJoynInit()) != ER_OK) { return status; } #ifdef ROUTER if ((status = AllJoynRouterInit()) != ER_OK) { AllJoynShutdown(); return status; } #endif /* Install SIGINT handler. */ signal(SIGINT, AllJoynBase::SigIntHandler); status = ER_OK; /* Create message bus */ mBus = new BusAttachment("chat", true); if (mBus) { if (ER_OK == status) { status = CreateInterface(); } if (ER_OK == status) { RegisterBusListener(); } if (ER_OK == status) { status = StartMessageBus(); } if (ER_OK == status) { CreateBusObject(); } return status; } else { status = ER_OUT_OF_MEMORY; } return status; } QStatus AllJoynBase::Start() { QStatus status; status = RegisterBusObject(); if (ER_OK == status) { status = ConnectBusAttachment(); } return status; } QStatus AllJoynBase::Stop() { printf("Alljoyn stop in\n"); if (mBus) { delete mBus; mBus = NULL; } #ifdef ROUTER QStatus status; status = AllJoynRouterShutdown(); #endif return AllJoynShutdown(); }
#include <iostream> #include <cstdio> using namespace std; int main(){ int n; cin >> n; while(n--){ string str; cin >> str; for(int i = 0; i < str.length(); i++){ if(str[i]!= str[i+1]){ cout << str[i]; } } cout << "\n"; } return 0; }
#include "IProcess.h" #include "Configure.h" #include "BaseClientHandler.h" #include "HallManager.h" #include "Logger.h" #include "ErrorMsg.h" #include "AllocSvrConnect.h" #include "Room.h" #include "RedisLogic.h" #include "ProtocolClientId.h" #include "ProtocolServerId.h" #include "Util.h" #include "GameUtil.h" #include "GameApp.h" #include "MoneyAgent.h" #include "RoundAgent.h" #include "MySqlAgent.h" int IProcess::sendToRobotCard(Player* player, Table* table) { if(player==NULL || table == NULL) return 0; if(player->source != 30) return 0; int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; OutputPacket response; response.Begin(SERVER_MSG_ROBOT, player->id); response.WriteShort(0); response.WriteString("ok"); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteByte(table->m_nCountPlayer); int i = 0; for(i = 0; i < table->m_bMaxNum; ++i) { Player* otherplayer = table->player_array[i]; if(otherplayer) { response.WriteInt(otherplayer->id); for(int j = 0; j < MAX_COUNT; j++) response.WriteByte(otherplayer->card_array[j]); } } response.End(); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[sendToRobotCard] Send To Uid[%d] Error!\n", player->id); return 0; } int IProcess::GameStart(Table* table) { if(table == NULL) return -1; table->gameStart(); for(int i = 0; i < table->m_bMaxNum; ++i) { Player* player = table->player_array[i]; if(player) sendGameStartInfo(player, table); } return 0; } int IProcess::sendGameStartInfo(Player* player, Table* table) { int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; int i = 0; OutputPacket response; response.Begin(GMSERVER_GAME_START, player->id); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteInt(table->m_nAnte); response.WriteInt(table->m_nTax); response.WriteInt(table->player_array[table->m_nDealerIndex]->id); response.WriteInt(table->player_array[table->m_nFirstIndex]->id); response.WriteInt64(table->m_lSumPool); response.WriteByte(table->m_nCountPlayer); for(i = 0; i < table->m_bMaxNum; ++i) { short index = (table->m_nDealerIndex+i) % table->m_bMaxNum; if(table->player_array[index]) { response.WriteInt(table->player_array[index]->id); response.WriteInt64(table->player_array[index]->m_lMoney); } } response.WriteShort(player->optype); if (player->m_bCardStatus == CARD_UNKNOWN) { response.WriteInt(table->m_nRase1); response.WriteInt(table->m_nRase2); response.WriteInt(table->m_nRase3); response.WriteInt(table->m_nRase4); response.WriteInt(table->m_nMaxLimit); } else { response.WriteInt(table->m_nRase2); response.WriteInt(table->m_nRase3); response.WriteInt(table->m_nRase4); response.WriteInt(table->m_nMaxLimit); response.WriteInt(table->m_nMaxLimit * 2); } response.WriteByte(Configure::getInstance()->max_round); response.WriteByte(Configure::getInstance()->betcointime - 3); response.WriteByte(player->m_bCardStatus); response.WriteShort(0); response.WriteString(""); response.WriteByte(player->m_nChangeNum); response.End(); _LOG_DEBUG_("<==[sendGameStartInfo] Push [0x%04x] to uid=[%d]\n", GMSERVER_GAME_START, player->id); _LOG_DEBUG_("[Data Response] err=[0], errmsg[ok]\n"); _LOG_DEBUG_("[Data Response] uid[%d]\n",player->id); _LOG_DEBUG_("[Data Response] m_nStatus[%d]\n",player->m_nStatus); _LOG_DEBUG_("[Data Response] tid=[%d]\n", tid); _LOG_DEBUG_("[Data Response] tm_nStatus=[%d]\n", table->m_nStatus); _LOG_DEBUG_("[Data Response] optype=[%d]\n", player->optype); _LOG_DEBUG_("[Data Response] money=[%ld]\n", player->m_lMoney); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[sendGameStartInfo] Send To Uid[%d] Error!\n", player->id); return 0; } int IProcess::pushForbidinfo(Table* table) { if(table == NULL) return -1; if(!table->isActive()) return -1; int j = 0; int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; for(j = 0; j < table->m_bMaxNum; ++j) { Player* player = table->player_array[j]; if(player) { OutputPacket response; response.Begin(PUSH_MSG_FORBID, player->id); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteByte(table->m_nCountPlayer); for(int i = 0; i < table->m_bMaxNum; ++i) { Player* otherplayer = table->player_array[i]; if(otherplayer) { response.WriteInt(otherplayer->id); response.WriteByte(otherplayer->m_nUseForbidNum); } } response.End(); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[sendPoolinfo] Send To Uid[%d] Error!\n", player->id); } } _LOG_DEBUG_("<==[pushForbidinfo] Push [0x%04x] \n", PUSH_MSG_FORBID); _LOG_DEBUG_("[Data Response] err=[0], errmsg[ok]\n"); _LOG_DEBUG_("[Data Response] tid=[%d]\n", tid); _LOG_DEBUG_("[Data Response] tm_nStatus=[%d]\n", table->m_nStatus); return 0; } int IProcess::RecordWinLoser(int winUid, vector<int>& losers, vector<int64_t>& loseCoin, int loserCount, Table* table) { for (int i = 0; i < loserCount; ++i) { OutputPacket outputPacket; outputPacket.Begin(S2S_MYSQL_LOG_WIN_LOSE); outputPacket.WriteShort(Configure::getInstance()->m_nLevel); outputPacket.WriteInt(table->id); outputPacket.WriteInt(table->getStartTime()); outputPacket.WriteInt(table->getEndTime()); outputPacket.WriteShort(Configure::getInstance()->m_nServerId); outputPacket.WriteInt(GAME_ID); outputPacket.WriteInt(winUid); outputPacket.WriteInt(losers[i]); outputPacket.WriteInt64(loseCoin[i]); outputPacket.End(); if (MySqlServer()->Send(&outputPacket) != 0) { _LOG_ERROR_("Send record win and loser info request to mysql server Error\n"); return -1; } } return 0; } int IProcess::GameOver( Table* table) { if(table == NULL) { _LOG_ERROR_("[GameOver] table[%p]\n", table); return -1; } int i = 0; //int sendNum = 0; Json::Value game_play_anaysis; game_play_anaysis["rlevel"] = Configure::getInstance()->m_nLevel; game_play_anaysis["tid"] = table->id; game_play_anaysis["starttime"] = (int)table->getStartTime(); game_play_anaysis["endtime"] = (int)table->getEndTime(); game_play_anaysis["svid"] = Configure::getInstance()->m_nServerId; int winUid = 0; vector<int> losersUid; vector<int64_t> losersCoin; std::string endtime = Util::formatGMTTimeS(); for(i = 0; i < table->m_bMaxNum; ++i) { Player* player = table->player_array[i]; if(player && player->isGameOver()) { if (player->m_lFinallGetCoin > 0) { if (winUid > 0) { LOGGER(E_LOG_ERROR) << "Too more winer , " << winUid << " and " << player->id << " all are winer"; } else { winUid = player->id; //LOGGER(E_LOG_DEBUG) << " winer " << winUid ; } table->m_nPreWinIndex = player->m_nTabIndex; player->m_nWin++; ULOGGER(E_LOG_DEBUG, player->id) << "player->m_lFinallGetCoin:" << player->m_lFinallGetCoin; GameUtil::CalcSysWinMoney(player->m_lFinallGetCoin, player->m_nTax, table->m_nTax); ULOGGER(E_LOG_DEBUG, player->id) << " player->m_nTax:" << player->m_nTax << " table->m_nTax:" << table->m_nTax; if (!RedisLogic::UpdateTaxRank(Tax(), player->pid, Configure::getInstance()->m_nServerId, GAME_ID, Configure::getInstance()->m_nLevel, player->tid, player->id, player->m_nTax)) LOGGER(E_LOG_DEBUG) << "OperationRedis::GenerateTip Error, pid=" << player->pid << ", m_nServerId=" << Configure::getInstance()->m_nServerId << ", gameid=" << GAME_ID << ", level=" << Configure::getInstance()->m_nLevel << ", id=" << player->id << ", Tax=" << player->m_nTax; } else if (player->m_lFinallGetCoin < 0) { player->m_nLose++; player->m_nTax = 0; //LOGGER(E_LOG_DEBUG) << "loser :" << player->id << " , lose money: " << player->m_lFinallGetCoin; losersUid.push_back(player->id); losersCoin.push_back(-player->m_lFinallGetCoin); } player->m_lMoney += player->m_lFinallGetCoin; player->recordWin(player->m_lFinallGetCoin); if (player->isdropline) { RedisLogic::setPlayerOffline(Offline(), GAME_ID, Configure::getInstance()->m_nLevel, player->id, player->m_lFinallGetCoin, endtime); } char uidKey[128] = { 0 }; sprintf(uidKey , "%d" , player->id); game_play_anaysis[uidKey] = player->gameRecordAnalysisInfo(); player->clearRecordAnalysisInfo(); char statistic_info[128] = { 0 }; sprintf(statistic_info , ", money=%ld, FinallGetCoin=%ld, tax=%d" , player->m_lMoney , player->m_lFinallGetCoin , player->m_nTax); //ULOGGER(E_LOG_DEBUG, player->id) << "money=" << player->m_lMoney << " FinallGetCoin=" << player->m_lFinallGetCoin << " tax=" << player->m_nTax; player->calcMaxWin(); if(player->m_lFinallGetCoin != 0 || player->hasUseCoin()) updateDB_UserCoin(player, table); int64_t winmoney = player->m_lFinallGetCoin; std::string strTrumpt; if (GameUtil::getDisplayMessage(strTrumpt, GAME_ID, Configure::getInstance()->m_nLevel, player->name, winmoney, Configure::getInstance()->wincoin1, Configure::getInstance()->wincoin2, Configure::getInstance()->wincoin3, Configure::getInstance()->wincoin4)) { AllocSvrConnect::getInstance()->trumptToUser(PRODUCT_TRUMPET, strTrumpt.c_str(), player->pid); } } } Json::FastWriter jWriter; std::string analysisInfo = jWriter.write(game_play_anaysis); LOGGER(E_LOG_DEBUG)<< "flowergameanalysis: "<< analysisInfo; RecordWinLoser(winUid, losersUid, losersCoin, losersUid.size(), table); Json::Value data; data["BID"] = string(table->getGameID()); data["Time"]=(int)(time(NULL) - table->getStartTime()); data["num"] = table->m_bMaxNum; for(i = 0; i < table->m_bMaxNum; ++i) { char szplayer[16] = {0}; sprintf(szplayer, "uid%d",i); Player* otherplayer = table->player_array[i]; if(otherplayer) { sendGameOverinfo(otherplayer, table); data[szplayer] = otherplayer->id; sprintf(szplayer, "fvalue%d",i); data[szplayer] = otherplayer->m_nEndCardType; sprintf(szplayer, "fcoin%d",i); data[szplayer] = (double)otherplayer->m_lFinallGetCoin; sprintf(szplayer, "money%d",i); data[szplayer] = (double)otherplayer->m_lMoney; } else data[szplayer] = 0; } for(i = 0; i < table->m_bMaxNum; ++i) { Player* otherplayer = table->player_array[i]; //当前这个用户已经掉线 if(otherplayer && otherplayer->isdropline) { serverPushLeaveInfo(table, otherplayer); table->playerLeave(otherplayer); } //用户下低注超时超过几次直接踢出用户 if(otherplayer && (otherplayer->timeoutCount >= Configure::getInstance()->timeoutCount)) { serverPushLeaveInfo(table, otherplayer, 3); table->playerLeave(otherplayer); } } return 0; } int IProcess::sendGameOverinfo(Player* player, Table* table) { int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; int i = 0; //int j = 0; OutputPacket response; response.Begin(GMSERVER_MSG_GAMEOVER,player->id); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteByte(table->m_nCountPlayer); for(i = 0; i < table->m_bMaxNum; ++i) { Player* otherplayer = table->player_array[i]; if(otherplayer) { response.WriteInt(otherplayer->id); response.WriteShort(otherplayer->m_nStatus); response.WriteByte(otherplayer->m_nTabIndex); response.WriteByte(otherplayer->m_bCardStatus); //printf("otherplayer:%d m_bCardStatus:%d\n", otherplayer->id, otherplayer->m_bCardStatus); if(otherplayer->id == player->id) { response.WriteByte(otherplayer->card_array[0]); response.WriteByte(otherplayer->card_array[1]); response.WriteByte(otherplayer->card_array[2]); response.WriteByte(otherplayer->m_nEndCardType); } else { set<int>::iterator iter = player->m_setCompare.find(otherplayer->id); if(iter != player->m_setCompare.end()) { response.WriteByte(otherplayer->card_array[0]); response.WriteByte(otherplayer->card_array[1]); response.WriteByte(otherplayer->card_array[2]); response.WriteByte(otherplayer->m_nEndCardType); } else { response.WriteByte(0); response.WriteByte(0); response.WriteByte(0); response.WriteByte(0); } } response.WriteInt64(otherplayer->m_lFinallGetCoin); response.WriteInt64(otherplayer->m_lMoney); response.WriteInt(otherplayer->m_nWin); response.WriteInt(otherplayer->m_nLose); response.WriteInt(otherplayer->m_nRoll); } } response.WriteByte(player->m_bCompleteTask ? 1 : 0); response.WriteShort(player->m_bCompleteTask ? player->m_nGetRoll : 0); response.End(); _LOG_INFO_("[GameOverinfo] Push [0x%04x] to uid=[%d] m_lFinallGetCoin[%ld] m_lMoney[%ld] CompleteTask[%d]\n", GMSERVER_MSG_GAMEOVER, player->id,player->m_lFinallGetCoin, player->m_lMoney, player->m_bCompleteTask ? 1 : 0); _LOG_DEBUG_("[Data Response] err=[0], errmsg[ok]\n"); _LOG_DEBUG_("[Data Response] uid[%d]\n",player->id); _LOG_DEBUG_("[Data Response] m_nStatus[%d]\n",player->m_nStatus); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[sendGameOverinfo] Send To Uid[%d] Error!\n", player->id); return 0; } int IProcess::serverPushLeaveInfo(Table* table, Player* leavePlayer,short retno) { if(table == NULL || leavePlayer == NULL) return -1; int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; _LOG_INFO_("<==[serverPushLeaveInfo] Push [0x%04x] leaver[%d] retno[%d]\n", SERVER_MSG_KICKOUT, leavePlayer->id, retno); _LOG_DEBUG_("[Data Response] err=[0], errmsg[]\n"); int i = 0; for(i = 0; i < table->m_bMaxNum; ++i) { if(table->player_array[i]) { OutputPacket response; response.Begin(SERVER_MSG_KICKOUT,table->player_array[i]->id); response.SetSource(E_MSG_SOURCE_GAME_SERVER); response.WriteShort(retno); response.WriteString(_EMSG_(retno)); response.WriteInt(table->player_array[i]->id); response.WriteShort(table->player_array[i]->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteInt(leavePlayer->id); response.End(); HallManager::getInstance()->sendToHall(table->player_array[i]->m_nHallid, &response, false); } } _LOG_DEBUG_("[Data Response] tid=[%d]\n", tid); _LOG_DEBUG_("[Data Response] tm_nStatus=[%d]\n", table->m_nStatus); _LOG_DEBUG_("[Data Response] leavePlayer=[%d]\n", leavePlayer->id); _LOG_DEBUG_("[Data Response] leavePlayerstatus=[%d]\n", leavePlayer->m_nStatus); return 0; } int IProcess::serverWarnPlayerKick(Table* table, Player* warnner, short timeCount) { if(table == NULL || warnner == NULL) return -1; int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; _LOG_DEBUG_("<==[serverWarnPlayerKick] Push [0x%04x]\n", GMSERVER_WARN_KICK); // int sendnum = 0; // int i = 0; OutputPacket response; response.Begin(GMSERVER_WARN_KICK,warnner->id); response.WriteShort(0); response.WriteString("ok"); response.WriteInt(warnner->id); response.WriteShort(warnner->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteShort(timeCount); response.End(); HallManager::getInstance()->sendToHall(warnner->m_nHallid, &response, false); _LOG_DEBUG_("[Data Response] tid=[%d]\n", tid); _LOG_DEBUG_("[Data Response] tm_nStatus=[%d]\n", table->m_nStatus); _LOG_DEBUG_("[Data Response] warnner=[%d]\n", warnner->id); _LOG_DEBUG_("[Data Response] timeCount=[%d]\n", timeCount); return 0; } int IProcess::updateDB_UserCoin(Player* player, Table* table) { if(table->isAllRobot()) return 0; if(player->source != 30) { ULOGGER(E_LOG_INFO, player->id) << "before m_nMagicCoinCount:" << player->m_nMagicCoinCount << " m_lMoney:" << player->m_lMoney << " m_nMagicNum:" << player->m_nMagicNum; MoneyAgent* connect = MoneyServer(); OutputPacket respone; respone.Begin(CMD_MONEY_UPDATE_MONEY); respone.WriteInt(player->id); respone.WriteByte(1); respone.WriteInt64(player->m_lFinallGetCoin); respone.End(); if(connect->Send(&respone) < 0) _LOG_ERROR_("Send request to MoneyServer Error\n" ); OutputPacket outPacket; outPacket.Begin(ROUND_SET_INFO); outPacket.WriteInt(player->id); outPacket.WriteInt(player->m_nWin); outPacket.WriteInt(player->m_nLose); outPacket.WriteInt(player->m_nTie); outPacket.WriteInt(player->m_nRunAway); outPacket.WriteInt64(player->m_lMaxWinMoney); outPacket.WriteInt64(player->m_lMaxCardValue); outPacket.End(); if(RoundServer()->Send(&outPacket) < 0) _LOG_ERROR_("Send request to RoundServerConnect Error\n" ); } int32_t round_end_type = GAME_END_NORMAL; if (player->is_discard == true) { round_end_type = GAME_END_DISCARD; } else if (player->isdropline) { round_end_type = GAME_END_DISCONNECT; } int cmd = 0x0120; OutputPacket outputPacket; outputPacket.Begin(cmd); outputPacket.WriteInt(player->id); outputPacket.WriteInt64(player->m_lFinallGetCoin - table->m_nTax); outputPacket.WriteInt(player->source); outputPacket.WriteInt(player->cid); outputPacket.WriteInt(player->sid); outputPacket.WriteInt(player->pid); outputPacket.WriteInt(player->m_nTax); outputPacket.WriteInt(table->m_nAnte); outputPacket.WriteInt(Configure::getInstance()->m_nServerId); outputPacket.WriteInt(table->id); short m_nType = table->m_nType; outputPacket.WriteInt(m_nType); outputPacket.WriteString(table->getGameID()); //outputPacket.WriteInt(table->getEndType()); outputPacket.WriteInt(round_end_type); outputPacket.WriteInt64(player->m_lMoney); outputPacket.WriteInt(table->getStartTime()); outputPacket.WriteInt(table->getEndTime()); outputPacket.WriteInt(player->m_nEndCardType); // outputPacket.WriteInt(0); //taskcoin // outputPacket.WriteInt(player->m_nMagicNum); // outputPacket.WriteInt(player->m_nMagicCoinCount); // outputPacket.WriteInt(player->m_nUseMulCoin); // outputPacket.WriteInt(player->m_nUseForbidCoin); // outputPacket.WriteInt(player->m_nUseChangeCoin); outputPacket.End(); if(MySqlServer()->Send( &outputPacket )==0) { return 0; } else { _LOG_ERROR_("Send request to BackServer Error\n" ); return -1; } return 0; } int IProcess::updateDB_UserCoin(LeaverInfo* player, Table* table) { if(table->isAllRobot()) return 0; if(player->source != 30) { LOGGER(E_LOG_INFO) << "before m_nMagicCoinCount:" << player->m_nMagicCoinCount << " m_lMoney:" << player->m_lMoney << " m_nMagicNum:" << player->m_nMagicNum; if(player->m_lMoney - player->m_nMagicCoinCount < 0) { player->m_nMagicCoinCount = player->m_lMoney; player->m_lMoney = 0; } OutputPacket respone; respone.Begin(CMD_MONEY_UPDATE_MONEY); respone.WriteInt(player->uid); respone.WriteByte(1); int64_t tempmoney = -player->m_lSumBetCoin - table->m_nTax - player->m_nMagicCoinCount - player->m_nUseMulCoin - player->m_nUseForbidCoin - player->m_nUseChangeCoin; respone.WriteInt64(tempmoney); respone.End(); if(MoneyServer()->Send(&respone) < 0) _LOG_ERROR_("Send request to MoneyServer Error\n" ); OutputPacket outPacket; outPacket.Begin(ROUND_SET_INFO); outPacket.WriteInt(player->uid); outPacket.WriteInt(player->m_nWin); outPacket.WriteInt(player->m_nLose + 1); outPacket.WriteInt(player->m_nTie); outPacket.WriteInt(player->m_nRunAway); outPacket.WriteInt64(player->m_lMaxWinMoney); outPacket.WriteInt64(player->m_lMaxCardValue); outPacket.End(); if(RoundServer()->Send( &outPacket ) < 0) _LOG_ERROR_("Send request to RoundServerConnect Error\n" ); _LOG_DEBUG_("after m_nMagicCoinCount:%d m_lMoney:%d m_nMagicNum:%d \n", player->m_nMagicCoinCount, player->m_lMoney, player->m_nMagicNum); } int sedcmd = 0x0120; OutputPacket outputPacket; outputPacket.Begin(sedcmd); outputPacket.WriteInt(player->uid); outputPacket.WriteInt64(-player->m_lSumBetCoin - table->m_nTax); outputPacket.WriteInt(player->source); outputPacket.WriteInt(player->cid); outputPacket.WriteInt(player->sid); outputPacket.WriteInt(player->pid); outputPacket.WriteInt(table->m_nTax); outputPacket.WriteInt(table->m_nAnte); outputPacket.WriteInt(Configure::getInstance()->m_nServerId); outputPacket.WriteInt(table->id); short m_nType = table->m_nType; outputPacket.WriteInt(m_nType); outputPacket.WriteString(table->getGameID()); //outputPacket.WriteInt(table->getEndType()); outputPacket.WriteInt(GAME_END_DISCONNECT); outputPacket.WriteInt64(player->m_lMoney); outputPacket.WriteInt(table->getStartTime()); //outputPacket.WriteInt(table->getEndTime()); outputPacket.WriteInt(time(NULL)); outputPacket.WriteInt(-1); // outputPacket.WriteInt(0); // outputPacket.WriteInt(player->m_nMagicNum); // outputPacket.WriteInt(player->m_nMagicCoinCount); // outputPacket.WriteInt(player->m_nUseMulCoin); // outputPacket.WriteInt(player->m_nUseForbidCoin); // outputPacket.WriteInt(player->m_nUseChangeCoin); outputPacket.End(); if(MySqlServer()->Send( &outputPacket )==0) { return 0; } else { _LOG_ERROR_("Send request to BackServer Error\n" ); return -1; } return 0; } int IProcess::UpdateDBActiveTime(Player* player) { if(player->source == 30) return 0; if(time(NULL) - player->getEnterTime() > 36000) return 0; OutputPacket outputPacket; outputPacket.Begin(ROUND_SET_ONLINETIME); outputPacket.WriteInt(player->id); outputPacket.WriteInt(time(NULL) - player->getEnterTime()); outputPacket.End(); _LOG_DEBUG_("==>[updateDB] [0x%04x] [UpdateDBActiveTime]\n", ROUND_SET_ONLINETIME); if(RoundServer()->Send( &outputPacket )<0) _LOG_ERROR_("Send request to RoundServerConnect Error\n" ); return 0; } int IProcess::NotifyPlayerNetStatus(Table* table, int uid, int signal, int type) { OutputPacket response; response.Begin(CLIENT_MSG_NETWORK_STATUS); response.WriteShort(0); response.WriteString("ok"); response.WriteInt(uid); response.WriteInt(signal); response.WriteInt(type); response.End(); for (int i = 0; i < GAME_PLAYER; ++i) //转发网络状态给同桌的其他玩家 { Player* p = table->player_array[i]; if (p && p->id != uid) { response.SetUid(p->id); HallManager::getInstance()->sendToHall(p->m_nHallid, &response, false); } } return 0; } int IProcess::sendCompareInfoToPlayers(Player* player , Table* table , Player* compareplayer , Player* opponent , short compareRet , Player* nextplayer , int64_t comparecoin , short seq) { int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16) | table->id; OutputPacket response; response.Begin(CLIENT_MSG_COMPARE_CARD , player->id); //if (player->id == compareplayer->id) // response.SetSeqNum(seq); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteByte(table->m_bCurrRound); response.WriteInt64(comparecoin); response.WriteByte(compareRet); response.WriteInt(compareplayer->id); response.WriteInt64(compareplayer->m_lSumBetCoin); response.WriteInt64(compareplayer->m_lMoney); response.WriteInt(opponent->id); response.WriteInt64(table->m_lCurrBetMax); response.WriteInt(nextplayer ? nextplayer->id : 0); response.WriteInt64(player->m_lSumBetCoin); response.WriteInt64(player->m_lMoney); response.WriteShort(player->optype); response.WriteInt64(table->m_lSumPool); response.WriteInt64(player->m_AllinCoin); response.WriteByte(player->m_bCardStatus); response.End(); _LOG_DEBUG_("<==[CompareCardProc] Push [0x%04x] to uid=[%d]" "[Data Response] err=[0], errmsg[], uid=[%d],m_nStatus=[%d],m_lCurrBetMax=[%d], compareplayer=[%d]," "m_bCurrRound=[%d], compareRet=[%d],m_lSumBetCoin=[%d], m_lSumPool=[%d], nextplayer=[%d]\n" , CLIENT_MSG_COMPARE_CARD , player->id , player->id , player->m_nStatus , table->m_lCurrBetMax , compareplayer->id , table->m_bCurrRound , compareRet , player->m_lSumBetCoin , table->m_lSumPool , nextplayer ? nextplayer->id : 0); if (HallManager::getInstance()->sendToHall(player->m_nHallid , &response , false) < 0) _LOG_ERROR_("[CompareCardProc] Send To Uid[%d] Error!\n" , player->id); return 0; } // 剩余两个玩家时,一个玩家只够跟注一次时,在玩家跟注时,强制进行比牌 int IProcess::ForceCampareCard(Table* table , Player* p1 , Player* p2, short seq, bool isDelayNotify) { if (!table || !p1 || !p2) { _LOG_ERROR_("table:%d, campare card, peoples ptr(p1:%d, p2:%d) Error!\n" , table, p1, p2); return -1; } short compareRet = table->compareCard(p1 , p2); if (compareRet < 0) { _LOG_ERROR_("Compare Card Error, players[%d, %d], tid:%d !\n" , p1->id , p2->id, table->id ); return -1; } // 玩家的钱全部扣除 用于比牌 int64_t compareMoney = p1->m_lMoney; table->playerBetCoin(p1, compareMoney); // 记录比牌到游戏回放日志中 p1->recordCompareCard(table->m_bCurrRound , p2->id , compareMoney , compareRet); Json::Value data; data["BID"] = string(table->getGameID()); data["Time"] = (int)(time(NULL) - table->getStartTime()); data["currd"] = table->m_bCurrRound; data["UID"] = p1->id; data["ccoin"] = (double)compareMoney; data["opponet"] = p2->id; data["count"] = (double)p1->m_lSumBetCoin; if (!table->isAllRobot()) _LOG_REPORT_(player->id , RECORD_COMPARE_CARD , "%s" , data.toStyledString().c_str()); data["errcode"] = 0; if (isDelayNotify && table->setCompareResultInfo(compareRet , p1 , p2, compareMoney)) // 保存比牌结果,并延迟3秒通知客户端 { table->startCompareResultNotifyTimer(COMPARE_NOTIFY_DELAY_TIME); return 0; } p1->m_bCompare = true; if (compareRet == 1) { p2->m_bCardStatus = CARD_DISCARD; } if (compareRet == 0 || compareRet == DRAW) { p1->m_bCardStatus = CARD_DISCARD; compareRet = 0; } for (int i = 0; i < table->m_bMaxNum; ++i) { if (table->player_array[i]) { _LOG_ERROR_("Send compare card result %d of %d and %d to player %d:" , compareRet , p1->id , p2->id , table->player_array[i]->id); sendCompareInfoToPlayers(table->player_array[i] , table , p1 , p2 , compareRet , NULL , compareMoney , seq); } } return table->gameOver(true); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ /** \file * * \brief Implement fundamental functions for the memory module. * * These are either called directly, or through inlined new operators etc. * * \author Morten Rolland, mortenro@opera.com */ #include "core/pch.h" #ifdef ENABLE_MEMORY_OOM_EMULATION # include "modules/lea_malloc/lea_monoblock.h" #endif #include "modules/memory/src/memory_debug.h" #include "modules/memory/src/memory_opallocinfo.h" #include "modules/memory/src/memory_memguard.h" #include "modules/memory/src/memory_opallocinfo.h" #include "modules/memory/src/memory_reporting.h" #ifdef MEMORY_USE_LOCKING # include "modules/pi/system/OpMemory.h" # define MUTEX_LOCK() OpMemory::MemdebugLock() # define MUTEX_UNLOCK() OpMemory::MemdebugUnlock() #else # define MUTEX_LOCK() do {} while (0) # define MUTEX_UNLOCK() do {} while (0) #endif #if MEMORY_INLINED_OP_NEW || MEMORY_INLINED_NEW_ELEAVE || MEMORY_INLINED_ARRAY_ELEAVE void* op_meminternal_malloc_leave(size_t size) { void* ptr = op_meminternal_malloc(size); if ( ptr == 0 ) LEAVE(OpStatus::ERR_NO_MEMORY); return ptr; } #endif void* op_meminternal_always_leave(void) { LEAVE(OpStatus::ERR_NO_MEMORY); return NULL; } #ifdef ENABLE_MEMORY_DEBUGGING extern "C" void* OpMemDebug_OpMalloc(size_t size, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, "bytes[]", MEMORY_FLAG_ALLOCATED_OP_MALLOC); return g_mem_debug->OpMalloc(size, &info); } extern "C" void* OpMemDebug_OpCalloc(size_t num, size_t size, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, "bytes[]", MEMORY_FLAG_ALLOCATED_OP_CALLOC); return g_mem_debug->OpCalloc(num, size, &info); } extern "C" void* OpMemDebug_OpRealloc(void* ptr, size_t size, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, 0, 0); return g_mem_debug->OpRealloc(ptr, size, &info); } extern "C" void OpMemDebug_OpFree(void* ptr, void** pptr, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, 0, MEMORY_FLAG_RELEASED_OP_FREE); g_mem_debug->OpFree(ptr, pptr, &info); } extern "C" void OpMemDebug_OpFreeExpr(void* ptr, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, 0, MEMORY_FLAG_RELEASED_OP_FREE); g_mem_debug->OpFreeExpr(ptr, &info); } void* OpMemDebug_NewSMOD(size_t size) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_OP_NEW_SMOD); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewSMOD(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEW_SMOD); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewSMOD_L(size_t size) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_OP_NEW_SMOD); return g_mem_debug->OpMalloc_L(size, &info); } void* OpMemDebug_NewSMOD_L(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEW_SMOD); return g_mem_debug->OpMalloc_L(size, &info); } void* OpMemDebug_NewSMOT(size_t size) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_OP_NEWSMOT); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewSMOT(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWSMOT); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewSMOT_L(size_t size) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_OP_NEWSMOT); return g_mem_debug->OpMalloc_L(size, &info); } void* OpMemDebug_NewSMOT_L(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWSMOT); return g_mem_debug->OpMalloc_L(size, &info); } void* OpMemDebug_NewSMOP(size_t size) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_OP_NEWSMOP); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewSMOP(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWSMOP); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewSMOP_L(size_t size) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_OP_NEWSMOP); return g_mem_debug->OpMalloc_L(size, &info); } void* OpMemDebug_NewSMOP_L(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWSMOP); return g_mem_debug->OpMalloc_L(size, &info); } void OpMemDebug_PooledDelete(void* ptr) { OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_RELEASED_POOLED_DELETE); g_mem_debug->OpFreeExpr(ptr, &info); } extern "C" char* OpMemDebug_OpStrdup(const char* str, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, "char", MEMORY_FLAG_ALLOCATED_OP_STRDUP); return g_mem_debug->OpStrdup(str, &info); } extern "C" uni_char* OpMemDebug_UniStrdup(const uni_char* str, const char* file, int line) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, "uni_char", MEMORY_FLAG_ALLOCATED_UNI_STRDUP); return g_mem_debug->UniStrdup(str, &info); } extern "C" void OpMemDebug_ReportLeaks(void) { if (g_mem_guard) g_mem_guard->ReportLeaks(); } #if MEMORY_INLINED_OP_NEW void* OpMemDebug_New(size_t size, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEW); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_NewA(size_t size, const char* file, int line, const char* obj, unsigned int count1, unsigned int count2, size_t objsize) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWA); info.SetArrayElementCount(count1); info.SetArrayElementSize(objsize); OP_ASSERT(count1 == count2); return g_mem_debug->OpMalloc(size, &info); } #endif // MEMORY_INLINED_OP_NEW #if MEMORY_INLINED_GLOBAL_NEW void* OpMemDebug_GlobalNew(size_t size) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEW); return g_mem_debug->OpMalloc(size, &info); } void* OpMemDebug_GlobalNewA(size_t size) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEWA); return g_mem_debug->OpMalloc(size, &info); } #endif // MEMORY_INLINED_GLOBAL_NEW #if MEMORY_INLINED_GLOBAL_DELETE void OpMemDebug_GlobalDelete(void* ptr) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_RELEASED_DELETE); g_mem_debug->OpFreeExpr(ptr, &info); } void OpMemDebug_GlobalDeleteA(void* ptr) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_RELEASED_DELETEA); g_mem_debug->OpFreeExpr(ptr, &info); } #endif // MEMORY_INLINED_GLOBAL_DELETE #if MEMORY_INLINED_NEW_ELEAVE void* OpMemDebug_GlobalNew_L(size_t size) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEW); return g_mem_debug->OpMalloc_L(size, &info); } #endif // MEMORY_INLINED_NEW_ELEAVE #if MEMORY_INLINED_ARRAY_ELEAVE void* OpMemDebug_GlobalNewA_L(size_t size) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEWA); return g_mem_debug->OpMalloc_L(size, &info); } #endif // MEMORY_INLINED_ARRAY_ELEAVE void* OpMemDebug_NewELO(size_t size, OpMemLife &life, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWELO); return g_mem_debug->NewELO(size, life, &info); } void* OpMemDebug_NewELO_L(size_t size, OpMemLife &life, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWELO); return g_mem_debug->NewELO_L(size, life, &info); } void* OpMemDebug_NewELSA(size_t size, OpMemLife &life, const char* file, int line, const char* obj, unsigned int count1, unsigned int count2, size_t objsize) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWELSA); info.SetArrayElementCount(count1); info.SetArrayElementSize(objsize); OP_ASSERT(count1 == count2); return g_mem_debug->NewELSA(size, life, &info); } void OpMemDebug_TrackDelete(const void* ptr, const char* file, int line) { #if MEMORY_KEEP_FREESITE g_mem_guard->TrackDelete(ptr, file, line); #endif } void OpMemDebug_TrackDeleteA(const void* ptr, const char* file, int line) { #if MEMORY_KEEP_FREESITE g_mem_guard->TrackDeleteA(ptr, file, line); #endif } #if MEMORY_IMPLEMENT_OP_NEW void* operator new(size_t size, TOpAllocNewDefault, const char* file, int line, const char* obj) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEW); return g_mem_debug->OpMalloc(size, &info); } void* operator new(size_t size, TOpAllocNewDefault_L, const char* file, int line, const char* obj) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEW); return g_mem_debug->OpMalloc_L(size, &info); } void* operator new[](size_t size, TOpAllocNewDefaultA, const char* file, int line, const char* obj, unsigned int count1, unsigned int count2, size_t objsize) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWA); info.SetArrayElementCount(count1); info.SetArrayElementSize(objsize); OP_ASSERT(count1 == count2); return g_mem_debug->OpMalloc(size, &info); } void* operator new[](size_t size, TOpAllocNewDefaultA_L, const char* file, int line, const char* obj, unsigned int count1, unsigned int count2, size_t objsize) { OpMemoryStateInit(); OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWA); info.SetArrayElementCount(count1); info.SetArrayElementSize(objsize); OP_ASSERT(count1 == count2); return g_mem_debug->OpMalloc_L(size, &info); } #if 0 #ifdef MEMORY_SMOPOOL_ALLOCATOR void* operator new(size_t size, TOpAllocNewSMO, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWSMO); return g_mem_debug->NewSMO(size, &info); } #endif // MEMORY_SMOPOOL_ALLOCATOR #ifdef MEMORY_ELOPOOL_ALLOCATOR void* operator new(size_t size, TOpAllocNewELO, OpMemLife &life, const char* file, int line, const char* obj) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWELO); return g_mem_debug->NewELO(size, life, &info); } void* operator new[](size_t size, TOpAllocNewELSA, OpMemLife &life, const char* file, int line, const char* obj, unsigned int count1, unsigned int count2, unsigned int objsize) { OPALLOCINFO(info, file, line, obj, MEMORY_FLAG_ALLOCATED_OP_NEWELSA); info.SetArrayElementCount(count1); info.SetArrayElementSize(objsize); OP_ASSERT(count1 == count2); return g_mem_debug->NewELSA(size, life, &info); } #endif // MEMORY_ELOPOOL_ALLOCATOR #endif // 0 #endif // MEMORY_IMPLEMENT_OP_NEW #if MEMORY_IMPLEMENT_GLOBAL_NEW void* operator new(size_t size) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEW); return g_mem_debug->OpMalloc(size, &info); } void* operator new[](size_t size) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEWA); return g_mem_debug->OpMalloc(size, &info); } #endif // MEMORY_IMPLEMENT_GLOBAL_NEW #if MEMORY_IMPLEMENT_NEW_ELEAVE void* operator new(size_t size, TLeave /* cookie */) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEW); return g_mem_debug->OpMalloc_L(size, &info); } #endif // MEMORY_IMPLEMENT_NEW_ELEAVE #if MEMORY_IMPLEMENT_ARRAY_ELEAVE void* operator new[](size_t size, TLeave /* cookie */) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_ALLOCATED_GLOBAL_NEWA); info.SetArrayElementCount(size); info.SetArrayElementSize(1); return g_mem_debug->OpMalloc_L(size, &info); } #endif // MEMORY_IMPLEMENT_ARRAY_ELEAVE #if MEMORY_IMPLEMENT_GLOBAL_DELETE void operator delete(void* ptr) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_RELEASED_DELETE); g_mem_debug->OpFreeExpr(ptr, &info); } void operator delete[](void* ptr) { OpMemoryStateInit(); OPALLOCINFO(info, 0, 0, 0, MEMORY_FLAG_RELEASED_DELETEA); g_mem_debug->OpFreeExpr(ptr, &info); } #endif // MEMORY_IMPLEMENT_GLOBAL_DELETE extern "C" void OpMemDebug_OOM(int countdown) { g_mem_debug->Action(MEMORY_ACTION_SET_OOM_COUNT, countdown); } #else // ENABLE_MEMORY_DEBUGGING #if MEMORY_IMPLEMENT_OP_NEW #if MEMORY_NAMESPACE_OP_NEW void* operator new(size_t size, TOpAllocNewDefault) { return op_meminternal_malloc(size); } void* operator new[](size_t size, TOpAllocNewDefaultA) { return op_meminternal_malloc(size); } void* operator new(size_t size, TOpAllocNewDefault_L) { void* ptr = op_meminternal_malloc(size); if ( ptr == 0 ) LEAVE(OpStatus::ERR_NO_MEMORY); return ptr; } void* operator new[](size_t size, TOpAllocNewDefaultA_L) { void* ptr = op_meminternal_malloc(size); if ( ptr == 0 ) LEAVE(OpStatus::ERR_NO_MEMORY); return ptr; } #endif // MEMORY_NAMESPACE_OP_NEW #if 0 #ifdef MEMORY_SMOPOOL_ALLOCATOR void* operator new(size_t size, TOpAllocNewSMO) { return g_mem_pools.AllocSMO(size); } #endif // MEMORY_SMOPOOL_ALLOCATOR #ifdef MEMORY_ELOPOOL_ALLOCATOR void* operator new(size_t size, TOpAllocNewELO, OpMemLife &life) { return life.IntAllocELO(size, MEMORY_ALIGNMENT-1); } void* operator new[](size_t size, TOpAllocNewELSA, OpMemLife &life) { return life.IntAllocELO(size, 1); } #endif // MEMORY_ELOPOOL_ALLOCATOR #endif // 0 #endif // MEMORY_IMPLEMENT_OP_NEW #if MEMORY_IMPLEMENT_GLOBAL_NEW void* operator new(size_t size) { return op_meminternal_malloc(size); } void* operator new[](size_t size) { return op_meminternal_malloc(size); } #endif // MEMORY_IMPLEMENT_GLOBAL_NEW #if MEMORY_IMPLEMENT_NEW_ELEAVE void* operator new(size_t size, TLeave /* cookie */) { #ifdef VALGRIND void* ptr = operator new(size); #else void* ptr = op_meminternal_malloc(size); #endif if ( ptr == 0 ) LEAVE(OpStatus::ERR_NO_MEMORY); return ptr; } #endif // MEMORY_IMPLEMENT_NEW_ELEAVE #if MEMORY_IMPLEMENT_ARRAY_ELEAVE void* operator new[](size_t size, TLeave /* cookie */) { #ifdef VALGRIND void* ptr = operator new[](size); #else void* ptr = op_meminternal_malloc(size); #endif if ( ptr == 0 ) LEAVE(OpStatus::ERR_NO_MEMORY); return ptr; } #endif // MEMORY_IMPLEMENT_ARRAY_ELEAVE #if MEMORY_IMPLEMENT_GLOBAL_DELETE void operator delete(void* ptr) { op_meminternal_free(ptr); } void operator delete[](void* ptr) { op_meminternal_free(ptr); } #endif // MEMORY_IMPLEMENT_GLOBAL_DELETE #endif // ENABLE_MEMORY_DEBUGGING #if defined(ENABLE_MEMORY_OOM_EMULATION) && !defined(ENABLE_MEMORY_DEBUGGING) // // When memory debugging is not enabled, but OOM emulation is enabled, this // set of functions are used to allocate on the general heap. If the limited // heap is not available, the platform allocator is used (when not configured // for Desktop with -mem option, or not yet available) // void* op_limited_heap_malloc(size_t size) { if ( g_mem_limited_heap == 0 ) return op_lowlevel_malloc(size); void* mem = g_mem_limited_heap->malloc(size); #ifdef MEMORY_ASSERT_ON_OOM if(!mem) { OP_ASSERT(!"oom_assert"); } #endif // MEMORY_ASSERT_ON_OOM return mem; } void* op_limited_heap_calloc(size_t num, size_t size) { if ( g_mem_limited_heap == 0 ) return op_lowlevel_calloc(num, size); void* mem = g_mem_limited_heap->calloc(num, size); #ifdef MEMORY_ASSERT_ON_OOM if(!mem) { OP_ASSERT(!"oom_assert"); } #endif // MEMORY_ASSERT_ON_OOM return mem; } void* op_limited_heap_realloc(void* ptr, size_t size) { if ( g_mem_limited_heap == 0 || ! g_mem_limited_heap->Contains(ptr) ) return op_lowlevel_realloc(ptr, size); void* mem = g_mem_limited_heap->realloc(ptr, size); #ifdef MEMORY_ASSERT_ON_OOM if(!mem) { OP_ASSERT(!"oom_assert"); } #endif // MEMORY_ASSERT_ON_OOM return mem; } void op_limited_heap_free(void* ptr) { if ( g_mem_limited_heap == 0 || ! g_mem_limited_heap->Contains(ptr) ) op_lowlevel_free(ptr); else g_mem_limited_heap->free(ptr); } #endif // ENABLE_MEMORY_OOM_EMULATION && !ENABLE_MEMORY_DEBUGGING #ifdef SELFTEST void* OpMemGuard_Real2Shadow(void* ptr) { #ifdef ENABLE_MEMORY_DEBUGGING return g_mem_guard->Real2Shadow(ptr); #else return ptr; #endif } #endif // SELFTEST #ifdef MEMORY_DEBUGGING_ALLOCATOR extern "C" void* op_debug_malloc(size_t size) { return op_lowlevel_malloc(size); } extern "C" void op_debug_free(void* ptr) { op_lowlevel_free(ptr); } char* op_debug_strdup(const char* str) { int len = op_strlen(str); char* copy = (char*)op_debug_malloc(len + 1); if ( copy != 0 ) { op_strncpy(copy, str, len); copy[len] = 0; } return copy; } #endif // MEMORY_DEBUGGING_ALLOCATOR #ifdef OPMEMORY_VIRTUAL_MEMORY size_t op_get_mempagesize(void) { return OpMemory::GetPageSize(); } #endif // OPMEMORY_VIRTUAL_MEMORY #ifdef MEMORY_FAIL_ALLOCATION_ONCE BOOL OpMemDebug_SetOOMFailEnabled(BOOL b) { return (g_mem_guard->SetOOMFailEnabled(b!=FALSE)?TRUE:FALSE); } void OpMemDebug_SetOOMFailThreshold(int oom_threshold) { g_mem_guard->SetOOMFailThreshold(oom_threshold); } int OpMemDebug_GetOOMFailThreshold() { return g_mem_guard->GetOOMFailThreshold(); } void OpMemDebug_SetTagNumber(int tag) { g_mem_guard->SetCurrentTag(tag); } void OpMemDebug_ClearCallCounts() { g_mem_guard->ClearCallCounts(); } void OpMemDebug_SetBreakAtCallNumber(int callnumber) { g_mem_guard->SetBreakAtCallNumber(callnumber); } #endif // MEMORY_FAIL_ALLOCATION_ONCE
#ifndef _SORTING_BY_BUBBLE_H #define _SORTING_BY_BUBBLE_H #include "adt.h" namespace cs2420 { template<typename T> class SortByBubble : public SortBy<T> { public: SortByBubble(Bag<T>& bag) : SortBy<T>(bag) {} void sort(bool reversed = false){ for(int i = 0; i < this->elements.getSize() - 1; i++){ for(int j = 0; j < this->elements.getSize() - i - 1; j++){ if(this->lessOrGreaterThan(j+1, j, reversed)){ this->swap(j+1, j); } } } } }; } #endif
#pragma once #include "bibliotecas.h" template <typename T> struct NoArvore{ T conteudo; NoArvore * esq; NoArvore * dir; NoArvore(){ this->conteudo=0; this->esq=0; this->dir=0; } NoArvore(T conteudo){ this->conteudo=conteudo; this->esq=0; this->dir=0; } NoArvore(T conteudo, NoArvore * esquerdo, NoArvore * direito){ this->conteudo=conteudo; this->esq=esquerdo; this->dir=direito; } ~NoArvore(){ delete this; } void imprime(){ cout << conteudo << endl; } }; template <typename T> struct Arvore{ NoArvore<T> * raiz=new NoArvore<T>; /** * Cria arvore vazia */ Arvore(){ } ~Arvore(){ } void inicializaRaiz(T conteudo){ if(raiz->conteudo == 0) raiz->conteudo=conteudo; } void insere_ArvoreDeBusca(T conteudo){ if(estaVazia()) raiz->conteudo=conteudo; else insere(new NoArvore<T>(conteudo), raiz, raiz, true); } void insere_ArvoreDeBusca(NoArvore<T> * no){ insere(no, raiz, raiz, true); } /** * Tentar inserir numa posicao que não existe consiste em falha */ void insere(T filho, T pai){ NoArvore<T> * temp=pega_Pre(pai, raiz); if(temp->esq == 0)temp->esq=new NoArvore<T>(filho); else if(temp->dir == 0) temp->dir=new NoArvore<T>(filho); } NoArvore<T> * pega_Pre(T conteudo, NoArvore<T> * temp){ NoArvore<T> * resultado; if(temp != 0){ if(temp->conteudo == conteudo) return temp; resultado=pega_Pre(conteudo, temp->esq); if(resultado != 0) return resultado; resultado=pega_Pre(conteudo, temp->dir); if(resultado != 0) return resultado; } return 0; } NoArvore<T> * pega_Em(T conteudo, NoArvore<T> * temp){ NoArvore<T> * resultado; if(temp != 0){ resultado=pega_Pos(conteudo, temp->esq); if(resultado != 0) return resultado; if(temp->conteudo == conteudo) return temp; resultado=pega_Pos(conteudo, temp->dir); if(resultado != 0) return resultado; } return 0; } NoArvore<T> * pega_Pos(T conteudo, NoArvore<T> * temp){ NoArvore<T> * resultado; if(temp != 0){ resultado=pega_Pos(conteudo, temp->esq); if(resultado != 0) return resultado; resultado=pega_Pos(conteudo, temp->dir); if(resultado != 0) return resultado; if(temp->conteudo == conteudo) return temp; } return 0; } NoArvore<T> * pegaPai_Pre(T conteudo, NoArvore<T> * atual, NoArvore<T> * pai){ NoArvore<T> * resultado; if(atual != 0){ if(atual->conteudo == conteudo) return pai; // resultado=pegaPai_Pre(conteudo, atual->esq, atual); if(resultado != 0) return resultado; // resultado=pegaPai_Pre(conteudo, atual->dir, atual); if(resultado != 0) return resultado; } return 0; } NoArvore<T> * pegaPai_Em(T conteudo, NoArvore<T> * atual, NoArvore<T> * pai){ NoArvore<T> * resultado; if(atual != 0){ resultado=pegaPai_Em(conteudo, atual->esq, atual); if(resultado != 0) return resultado; // if(atual->conteudo == conteudo) return pai; // resultado=pegaPai_Em(conteudo, atual->dir, atual); if(resultado != 0) return resultado; } return 0; } NoArvore<T> * pegaPai_Pos(T conteudo, NoArvore<T> * atual, NoArvore<T> * pai){ NoArvore<T> * resultado; if(atual != 0){ resultado=pegaPai_Pos(conteudo, atual->esq, atual); if(resultado != 0) return resultado; // resultado=pegaPai_Pos(conteudo, atual->dir, atual); if(resultado != 0) return resultado; // if(atual->conteudo == conteudo) return pai; } return 0; } void limpa(){ apagaRecursivamente(raiz); } void apagaRecursivamente(NoArvore<T> * raiz){ ListaEncadeada<int> * lista=listaEnderecos_Pre(raiz); raiz=new NoArvore<T>; for(int i=0; i < lista->tamanho; i++)delete lista->pega(i); } bool estaVazia(){ return raiz->conteudo == 0; } void imprime_Pre(){ ListaEncadeada<T> * lista=new ListaEncadeada<T>; lista_Pre(raiz, lista); imprime("\n\n"); lista->imprime(); } void imprime_Em(){ ListaEncadeada<T> * lista=new ListaEncadeada<T>; lista_Em(raiz); lista->imprime(); } void imprime_Pos(){ ListaEncadeada<T> * lista=new ListaEncadeada<T>; lista_Pos(raiz); lista->imprime(); } // ListaEncadeada<int> * listaEnderecos_Pre(NoArvore<T> * raiz){ // ListaEncadeada<(NoArvore<T> *)> * lista=new ListaEncadeada<(NoArvore<T> *)>; // listaEnderecos_Pre(raiz, lista); // return lista; // } ListaEncadeada<T> * lista_Pre(NoArvore<T> * raiz){ ListaEncadeada<T> * lista=new ListaEncadeada<T>; lista_Pre(raiz, lista); return lista; } ListaEncadeada<T> * lista_Em(NoArvore<T> * raiz){ ListaEncadeada<T> * lista=new ListaEncadeada<T>; lista_Em(raiz, lista); return lista; } ListaEncadeada<T> * lista_Pos(NoArvore<T> * raiz){ ListaEncadeada<T> * lista=new ListaEncadeada<T>; lista_Pos(raiz, lista); return lista; } void remove_ArvoreDeBusca(T conteudo){ NoArvore<T> * ponteiroPai=0, * ponteiroFilho=0; if(raiz->conteudo == conteudo){ ponteiroFilho=raiz; raiz=new NoArvore<T>; }else{ ponteiroPai=pegaPai_Pre(conteudo, raiz, raiz); ponteiroFilho=pega_Pre(conteudo, ponteiroPai); if(ponteiroFilho == 0 || ponteiroPai == 0) return; ponteiroPai->esq == ponteiroFilho ? ponteiroPai->esq=0 : ponteiroPai->dir=0; } ListaEncadeada<T> * lista=lista_Pre(ponteiroFilho); for(int i=1; i < lista->tamanho; i++)this->insere_ArvoreDeBusca(lista->pega(i)); // pula a primeira entrada e insere o resto //apagaRecursivamente(ponteiroFilho); //deleteponteiroFIlho; } private: void insere(NoArvore<T> * no, NoArvore<T> * temp, NoArvore<T> * tempAnterior, bool esquerdo){ if(temp == 0) esquerdo ? tempAnterior->esq=no : tempAnterior->dir=no; else no->conteudo < temp->conteudo ? insere(no, temp->esq, temp, true) : insere(no, temp->dir, temp, false); } // void listaEnderecos_Pre(NoArvore<T> * temp, ListaEncadeada<(NoArvore<T> *)> * lista){ // if(temp != 0){ // lista->adicionaAoFinal(temp); // lista_Pre(temp->esq, lista); // lista_Pre(temp->dir, lista); // } // } void lista_Pre(NoArvore<T> * temp, ListaEncadeada<T> * lista){ if(temp != 0){ lista->adicionaAoFinal(temp->conteudo); //printf("Ponteiro: %10p Conteudo: %5i Esquerda: %10p Direita: %10p \n", temp, temp->conteudo, temp->esq, temp->dir ); lista_Pre(temp->esq, lista); lista_Pre(temp->dir, lista); } } void lista_Em(NoArvore<T> * temp, ListaEncadeada<T> * lista){ if(temp != 0){ lista_Em(temp->esq, lista); lista->adicionaAoFinal(temp->conteudo); //printf("Ponteiro: %10p Conteudo: %5i Esquerda: %10p Direita: %10p \n", temp, temp->conteudo, temp->esq, temp->dir ); lista_Em(temp->dir, lista); } } void lista_Pos(NoArvore<T> * temp, ListaEncadeada<T> * lista){ if(temp != 0){ lista_Pos(temp->esq); lista_Pos(temp->dir); //printf("Ponteiro: %10p Conteudo: %5i Esquerda: %10p Direita: %10p \n", temp, temp->conteudo, temp->esq, temp->dir ); lista->adicionaAoFinal(temp->conteudo); } } };
#include <iostream> #include <cstdio> using namespace std; int main(){ int M,N; cin >> M >> N; cout << (M * N) / 2<<"\n"; return 0; }
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef IOGDCMQT_DICOMDIREDITOR_HPP #define IOGDCMQT_DICOMDIREDITOR_HPP #include <QDialog> #include <QWidget> #include <QPointer> #include <QTreeWidget> #include <QPushButton> #include <QComboBox> #include <QLineEdit> #include <boost/filesystem/path.hpp> #include <fwRuntime/ConfigurationElement.hpp> #include <fwServices/IService.hpp> #include <gui/editor/IDialogEditor.hpp> #include <fwData/location/ILocation.hpp> #include <ioGdcmQt/Types.hpp> #include "ioGdcmQt/config.hpp" namespace ioGdcm { namespace ui { /** * @class DicomdirEditor * @brief Display the DICOMDIR files content with a tree widget and allows to select a reader to view the selected patient, study or serie. * @author IRCAD (Research and Development Team). * @date 2011. */ class IOGDCMQT_CLASS_API DicomdirEditor : public QDialog { Q_OBJECT public: IOGDCMQT_API DicomdirEditor(QWidget* parent, ::boost::filesystem::path& dicomdirPath) throw(); IOGDCMQT_API virtual ~DicomdirEditor() throw(); IOGDCMQT_API void setReader(const std::map < ::ioGdcm::DicomReader, std::string >& readerList); IOGDCMQT_API std::pair< ::ioGdcm::DicomReader, std::vector< ::boost::filesystem::path > > show(); IOGDCMQT_API void setPath (::boost::filesystem::path& path) {m_dicomdirPath = path;} private : /** * @brief create the content of the dialog box (Add a tree widget and a combo box for reader). */ void createContent() throw(::fwTools::Failed); std::vector< ::boost::filesystem::path> getDicomFiles(QTreeWidgetItem *item); private: typedef std::map<std::string, std::string> DatasetType; typedef std::map< std::string, DatasetType > PatientMapType; typedef std::map< std::string, DatasetType > StudyMapType; typedef std::map< std::string, DatasetType > SeriesMapType; typedef std::list <std::string> FileListType; typedef std::map< std::string, FileListType > PatientFilesMapType; typedef std::map< std::string, FileListType > StudyFilesMapType; typedef std::map< std::string, FileListType > SerieFilessMapType; typedef std::map< std::string, FileListType > SelectionMapType; typedef std::pair < ::ioGdcm::DicomReader, std::string > readerListType; QPointer< QTreeWidget > m_DicomdirStructure; QPointer< QComboBox > m_readers; QPointer< QPushButton > m_open; ::boost::filesystem::path m_dicomdirPath; bool m_bServiceIsConfigured; private Q_SLOTS: void onSelection(); }; } //namespace ui } //namespace ioGdcm #endif // IOGDCMQT_DICOMDIREDITOR_HPP
// 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. #include <ctime> #include <future> #include <fstream> #include <sstream> #include <string> #include <boost/filesystem.hpp> #include "ClientHelper.h" #include "CryptoNoteConfig.h" #include "Common/JsonValue.h" #include "Common/StringTools.h" #include "CryptoNoteCore/TransactionExtra.h" #include "Wallet/LegacyKeysImporter.h" #include "WalletLegacy/WalletHelper.h" #include <Logging/LoggerRef.h> using namespace common; namespace cn { uint32_t client_helper::deposit_term(const cn::Deposit &deposit) const { return deposit.term; } std::string client_helper::deposit_amount(const cn::Deposit &deposit, const Currency &currency) const { return currency.formatAmount(deposit.amount); } std::string client_helper::deposit_interest(const cn::Deposit &deposit, const Currency &currency) const { return currency.formatAmount(deposit.interest); } std::string client_helper::deposit_status(const cn::Deposit &deposit) const { std::string status_str = ""; if (deposit.locked) status_str = "Locked"; else if (deposit.spendingTransactionId == cn::WALLET_LEGACY_INVALID_TRANSACTION_ID) status_str = "Unlocked"; else status_str = "Withdrawn"; return status_str; } size_t client_helper::deposit_creating_tx_id(const cn::Deposit &deposit) const { return deposit.creatingTransactionId; } size_t client_helper::deposit_spending_tx_id(const cn::Deposit &deposit) const { return deposit.spendingTransactionId; } std::string client_helper::deposit_unlock_height(const cn::Deposit &deposit, const cn::WalletLegacyTransaction &txInfo) const { std::string unlock_str = ""; if (txInfo.blockHeight > cn::parameters::CRYPTONOTE_MAX_BLOCK_NUMBER) { unlock_str = "Please wait."; } else { unlock_str = std::to_string(txInfo.blockHeight + deposit_term(deposit)); } bool bad_unlock2 = unlock_str == "0"; if (bad_unlock2) { unlock_str = "ERROR"; } return unlock_str; } std::string client_helper::deposit_height(const cn::WalletLegacyTransaction &txInfo) const { std::string height_str = ""; uint64_t deposit_height = txInfo.blockHeight; bool bad_unlock = deposit_height > cn::parameters::CRYPTONOTE_MAX_BLOCK_NUMBER; if (bad_unlock) { height_str = "Please wait."; } else { height_str = std::to_string(deposit_height); } bool bad_unlock2 = height_str == "0"; if (bad_unlock2) { height_str = "ERROR"; } return height_str; } std::string client_helper::get_deposit_info(const cn::Deposit &deposit, cn::DepositId did, const Currency &currency, const cn::WalletLegacyTransaction &txInfo) const { std::stringstream full_info; full_info << std::left << std::setw(8) << makeCenteredString(8, std::to_string(did)) << " | " << std::setw(20) << makeCenteredString(20, deposit_amount(deposit, currency)) << " | " << std::setw(20) << makeCenteredString(20, deposit_interest(deposit, currency)) << " | " << std::setw(16) << makeCenteredString(16, deposit_unlock_height(deposit, txInfo)) << " | " << std::setw(12) << makeCenteredString(12, deposit_status(deposit)); std::string as_str = full_info.str(); return as_str; } std::string client_helper::get_full_deposit_info(const cn::Deposit &deposit, cn::DepositId did, const Currency &currency, const cn::WalletLegacyTransaction &txInfo) const { std::stringstream full_info; full_info << "ID: " << std::to_string(did) << "\n" << "Amount: " << deposit_amount(deposit, currency) << "\n" << "Interest: " << deposit_interest(deposit, currency) << "\n" << "Height: " << deposit_height(txInfo) << "\n" << "Unlock Height: " << deposit_unlock_height(deposit, txInfo) << "\n" << "Status: " << deposit_status(deposit) << "\n"; std::string as_str = full_info.str(); return as_str; } std::string client_helper::list_deposit_item(const WalletLegacyTransaction& txInfo, Deposit deposit, std::string listed_deposit, DepositId id, const Currency &currency) { std::string format_amount = currency.formatAmount(deposit.amount); std::string format_interest = currency.formatAmount(deposit.interest); std::string format_total = currency.formatAmount(deposit.amount + deposit.interest); std::stringstream ss_id(makeCenteredString(8, std::to_string(id))); std::stringstream ss_amount(makeCenteredString(20, format_amount)); std::stringstream ss_interest(makeCenteredString(20, format_interest)); std::stringstream ss_height(makeCenteredString(16, deposit_height(txInfo))); std::stringstream ss_unlockheight(makeCenteredString(16, deposit_unlock_height(deposit, txInfo))); std::stringstream ss_status(makeCenteredString(12, deposit_status(deposit))); ss_id >> std::setw(8); ss_amount >> std::setw(20); ss_interest >> std::setw(20); ss_height >> std::setw(16); ss_unlockheight >> std::setw(16); ss_status >> std::setw(12); listed_deposit = ss_id.str() + " | " + ss_amount.str() + " | " + ss_interest.str() + " | " + ss_height.str() + " | " + ss_unlockheight.str() + " | " + ss_status.str() + "\n"; return listed_deposit; } std::string client_helper::list_tx_item(const WalletLegacyTransaction& txInfo, std::string listed_tx, const Currency &currency) { std::vector<uint8_t> extraVec = asBinaryArray(txInfo.extra); crypto::Hash paymentId; std::string paymentIdStr = (cn::getPaymentIdFromTxExtra(extraVec, paymentId) && paymentId != NULL_HASH ? podToHex(paymentId) : ""); char timeString[32 + 1]; time_t timestamp = static_cast<time_t>(txInfo.timestamp); struct tm time; #ifdef _WIN32 gmtime_s(&time, &timestamp); #else gmtime_r(&timestamp, &time); #endif if (!std::strftime(timeString, sizeof(timeString), "%c", &time)) { throw std::runtime_error("time buffer is too small"); } std::string format_amount = currency.formatAmount(txInfo.totalAmount); std::stringstream ss_time(makeCenteredString(32, timeString)); std::stringstream ss_hash(makeCenteredString(64, podToHex(txInfo.hash))); std::stringstream ss_amount(makeCenteredString(20, currency.formatAmount(txInfo.totalAmount))); std::stringstream ss_fee(makeCenteredString(14, currency.formatAmount(txInfo.fee))); std::stringstream ss_blockheight(makeCenteredString(8, std::to_string(txInfo.blockHeight))); std::stringstream ss_unlocktime(makeCenteredString(12, std::to_string(txInfo.unlockTime))); ss_time >> std::setw(32); ss_hash >> std::setw(64); ss_amount >> std::setw(20); ss_fee >> std::setw(14); ss_blockheight >> std::setw(8); ss_unlocktime >> std::setw(12); listed_tx = ss_time.str() + " | " + ss_hash.str() + " | " + ss_amount.str() + " | " + ss_fee.str() + " | " + ss_blockheight.str() + " | " + ss_unlocktime.str() + "\n"; return listed_tx; } bool client_helper::confirm_deposit(uint64_t term, uint64_t amount, bool is_testnet, const Currency& currency, logging::LoggerRef logger) { uint64_t interest = currency.calculateInterestV3(amount, term); uint64_t min_term = is_testnet ? parameters::TESTNET_DEPOSIT_MIN_TERM_V3 : parameters::DEPOSIT_MIN_TERM_V3; logger(logging::INFO) << "Confirm deposit details:\n" << "\tAmount: " << currency.formatAmount(amount) << "\n" << "\tMonths: " << term / min_term << "\n" << "\tInterest: " << currency.formatAmount(interest) << "\n"; logger(logging::INFO) << "Is this correct? (Y/N): \n"; char c; std::cin >> c; c = std::tolower(c); if (c == 'y') { return true; } else if (c == 'n') { return false; } else { logger(logging::ERROR) << "Bad input, please enter either Y or N."; } return false; } JsonValue client_helper::buildLoggerConfiguration(logging::Level level, const std::string& logfile) { using common::JsonValue; JsonValue loggerConfiguration(JsonValue::OBJECT); loggerConfiguration.insert("globalLevel", static_cast<int64_t>(level)); JsonValue& cfgLoggers = loggerConfiguration.insert("loggers", JsonValue::ARRAY); JsonValue& consoleLogger = cfgLoggers.pushBack(JsonValue::OBJECT); consoleLogger.insert("type", "console"); consoleLogger.insert("level", static_cast<int64_t>(logging::TRACE)); consoleLogger.insert("pattern", ""); JsonValue& fileLogger = cfgLoggers.pushBack(JsonValue::OBJECT); fileLogger.insert("type", "file"); fileLogger.insert("filename", logfile); fileLogger.insert("level", static_cast<int64_t>(logging::TRACE)); return loggerConfiguration; } bool client_helper::parseUrlAddress(const std::string& url, std::string& address, uint16_t& port) { auto pos = url.find("://"); size_t addrStart = 0; if (pos != std::string::npos) addrStart = pos + 3; auto addrEnd = url.find(':', addrStart); if (addrEnd != std::string::npos) { auto portEnd = url.find('/', addrEnd); port = common::fromString<uint16_t>(url.substr( addrEnd + 1, portEnd == std::string::npos ? std::string::npos : portEnd - addrEnd - 1)); } else { addrEnd = url.find('/'); port = 80; } address = url.substr(addrStart, addrEnd - addrStart); return true; } std::error_code client_helper::initAndLoadWallet(cn::IWalletLegacy& wallet, std::istream& walletFile, const std::string& password) { WalletHelper::InitWalletResultObserver initObserver; std::future<std::error_code> f_initError = initObserver.initResult.get_future(); WalletHelper::IWalletRemoveObserverGuard removeGuard(wallet, initObserver); wallet.initAndLoad(walletFile, password); auto initError = f_initError.get(); return initError; } std::string client_helper::tryToOpenWalletOrLoadKeysOrThrow(logging::LoggerRef& logger, std::unique_ptr<cn::IWalletLegacy>& wallet, const std::string& walletFile, const std::string& password) { std::string keys_file, walletFileName; WalletHelper::prepareFileNames(walletFile, keys_file, walletFileName); boost::system::error_code ignore; bool keysExists = boost::filesystem::exists(keys_file, ignore); bool walletExists = boost::filesystem::exists(walletFileName, ignore); if (!walletExists && !keysExists && boost::filesystem::exists(walletFile, ignore)) { boost::system::error_code renameEc; boost::filesystem::rename(walletFile, walletFileName, renameEc); if (renameEc) throw std::runtime_error("failed to rename file '" + walletFile + "' to '" + walletFileName + "': " + renameEc.message()); walletExists = true; } if (walletExists) { logger(logging::INFO) << "Loading wallet..."; std::ifstream walletFile; walletFile.open(walletFileName, std::ios_base::binary | std::ios_base::in); if (walletFile.fail()) throw std::runtime_error("error opening wallet file '" + walletFileName + "'"); auto initError = initAndLoadWallet(*wallet, walletFile, password); walletFile.close(); if (initError) { //bad password, or legacy format if (keysExists) { std::stringstream ss; cn::importLegacyKeys(keys_file, password, ss); boost::filesystem::rename(keys_file, keys_file + ".back"); boost::filesystem::rename(walletFileName, walletFileName + ".back"); initError = initAndLoadWallet(*wallet, ss, password); if (initError) throw std::runtime_error("failed to load wallet: " + initError.message()); logger(logging::INFO) << "Saving wallet..."; save_wallet(*wallet, walletFileName, logger); logger(logging::INFO, logging::BRIGHT_GREEN) << "Saving successful"; return walletFileName; } else { // no keys, wallet error loading throw std::runtime_error("can't load wallet file '" + walletFileName + "', check password"); } } else { //new wallet ok return walletFileName; } } else if (keysExists) { //wallet not exists but keys presented std::stringstream ss; cn::importLegacyKeys(keys_file, password, ss); boost::filesystem::rename(keys_file, keys_file + ".back"); WalletHelper::InitWalletResultObserver initObserver; std::future<std::error_code> f_initError = initObserver.initResult.get_future(); WalletHelper::IWalletRemoveObserverGuard removeGuard(*wallet, initObserver); wallet->initAndLoad(ss, password); auto initError = f_initError.get(); removeGuard.removeObserver(); if (initError) { throw std::runtime_error("failed to load wallet: " + initError.message()); } logger(logging::INFO) << "Saving wallet..."; save_wallet(*wallet, walletFileName, logger); logger(logging::INFO, logging::BRIGHT_GREEN) << "Saved successful"; return walletFileName; } else { //no wallet no keys throw std::runtime_error("wallet file '" + walletFileName + "' is not found"); } } void client_helper::save_wallet(cn::IWalletLegacy& wallet, const std::string& walletFilename, logging::LoggerRef& logger) { logger(logging::INFO) << "Saving wallet..."; try { cn::WalletHelper::storeWallet(wallet, walletFilename); logger(logging::INFO, logging::BRIGHT_GREEN) << "Saved successful"; } catch (std::exception& e) { logger(logging::ERROR, logging::BRIGHT_RED) << "Failed to store wallet: " << e.what(); throw std::runtime_error("error saving wallet file '" + walletFilename + "'"); } } std::stringstream client_helper::balances(std::unique_ptr<cn::IWalletLegacy>& wallet, const Currency& currency) { std::stringstream balances; uint64_t full_balance = wallet->actualBalance() + wallet->pendingBalance() + wallet->actualDepositBalance() + wallet->pendingDepositBalance(); std::string full_balance_text = "Total Balance: " + currency.formatAmount(full_balance) + "\n"; uint64_t non_deposit_unlocked_balance = wallet->actualBalance(); std::string non_deposit_unlocked_balance_text = "Available: " + currency.formatAmount(non_deposit_unlocked_balance) + "\n"; uint64_t non_deposit_locked_balance = wallet->pendingBalance(); std::string non_deposit_locked_balance_text = "Locked: " + currency.formatAmount(non_deposit_locked_balance) + "\n"; uint64_t deposit_unlocked_balance = wallet->actualDepositBalance(); std::string deposit_locked_balance_text = "Unlocked Balance: " + currency.formatAmount(deposit_unlocked_balance) + "\n"; uint64_t deposit_locked_balance = wallet->pendingDepositBalance(); std::string deposit_unlocked_balance_text = "Locked Deposits: " + currency.formatAmount(deposit_locked_balance) + "\n"; balances << full_balance_text << non_deposit_unlocked_balance_text << non_deposit_locked_balance_text << deposit_unlocked_balance_text << deposit_locked_balance_text; return balances; } }
#ifndef Ocean_H #define Ocean_H #include "Height.h" #include "WaveModel.h" #include "Dvector.h" class Ocean { private : double lx; double ly; int nx; int ny; int t; Height hr; WaveModel* model; Dvector vertices; public : Ocean(Height h, WaveModel* wM); Ocean(const Ocean & ocean2); ~Ocean(); void generateHeight(); void main_computation(); int getNx() const {return nx;} int getNy() const {return ny;} double get_ly() const{return ly;} double get_lx() const {return lx;} WaveModel* getWaveModel() const{return model;} Dvector getVertices() const{return vertices;} Height getHeight()const {return hr;} int getTime() const {return t;} void setTime(int time); Ocean& operator=(const Ocean & ocean2); void init_gl_VertexArrayX(const int y, double* const vertices) const; void init_gl_VertexArrayY(const int x, double* const vertices) const; void gl_vertexArrayX(const int y, double* const vertices) const ; void gl_vertexArrayY(const int x, double* const vertices) const ; }; #endif
/* Copyright (c) 2014 Mircea Daniel Ispas This file is part of "Push Game Engine" released under zlib license For conditions of distribution and use, see copyright notice in Push.hpp */ #pragma once #include "Core/Hash.hpp" #include "Core/Path.hpp" #include "Core/TypeID.hpp" #include <memory> #include <cstdint> #include <cassert> namespace Push { class Resource { public: enum class State : uint32_t { Initialized, Loading, Loaded, Releasing, Released }; public: template<typename T> T* Get(); template<typename T> T const* Get() const; const Path& GetPath() const; Resource::State GetState() const; protected: Resource(const Path& resource, size_t type); virtual ~Resource(); virtual void SyncLoad() = 0; virtual void AsyncLoad() = 0; virtual void SyncRelease() = 0; virtual void AsyncRelease() = 0; private: Path m_resource; State m_state; uint32_t m_uses; Hash m_hash; size_t m_type; friend class ResourceManager; }; template<typename T> T* Resource::Get() { assert(m_type == TypeID<T>::value()); return static_cast<T*>(this); } template<typename T> T const* Resource::Get() const { assert(m_type == TypeID<T>::value()); return static_cast<T const*>(this); } }
#pragma once #include "DynamicObjectModel.h" #include "DynamicObjectView.h" #include "DynamicObjectLogicCalculator.h" class DynamicObjectController { public: DynamicObjectController(); virtual ~DynamicObjectController(); public: //the implementation of the update public and private methods is given and inherited virtual void update(const float elapsedTime); protected: virtual void updateBasicDynamicObjectMeasurements(); private: virtual void updateState(); virtual void updateMove(const float elapsedTime); virtual void updateImpact(const float elapsedTime); virtual void updateVanish(const float elapsedTime); //start to be given (requires sound management) virtual void startMove(DynamicObjectModel::DynamicObjectState)= 0; virtual void startImpact()= 0; virtual void startVanish()= 0; protected: DynamicObjectModel* m_dynamicObjectModel; DynamicObjectView* m_dynamicObjectView; DynamicObjectLogicCalculator* m_dynamicObjectLogicCalculator; };
#pragma once #include <qobject.h> #include <qdebug.h> #include <qpointer.h> class test : public QObject { Q_OBJECT public: explicit test(QObject * parent = nullptr); QPointer<QObject> widget; void useWidget(); signals: public slots: };
#include "commons.h" #include "my_signal.h" #include <string.h> #include <cstdio> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <fcntl.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/shm.h> #include <syslog.h> const char* const THE_FILE = "\\tmp\\fls_file_example"; char *theFile; void signal_handler(int signal) { syslog (LOG_NOTICE, "CHILD: SIGUSR1 received.\n"); syslog (LOG_NOTICE, "PARENT: Reading strings from maped memory:\n"); int offset = 0; const char* strings[3]; for (int i = 0; i < 3; ++i) { strings[i] = theFile + offset; offset += strlen(strings[i]) + 1; syslog (LOG_NOTICE, "[%d] %s\n", i, strings[i]); } syslog (LOG_NOTICE, "CHILD: Result: %d \n", target_func(strings[0], strings[1], strings[2])); syslog (LOG_NOTICE, "CHILD: the work is done.\n"); closelog(); exit(EXIT_SUCCESS); } void child_job() { openlog ("CHILD", LOG_PID, LOG_DAEMON); syslog (LOG_NOTICE, "CHILD: registering signal SIGUSR1\n"); register_signal(SIGUSR1, signal_handler); syslog (LOG_NOTICE, "CHILD: signal SIGUSR1 registered\n"); for (;;); } int main() { /* Open the log file */ openlog ("PARENT", LOG_PID, LOG_DAEMON); std::string str[] = {generate_str(), generate_str(), generate_str()}; syslog(LOG_NOTICE, "PARENT: creating file %s\n", THE_FILE); int fd; if ((fd = open(THE_FILE, O_CREAT | O_RDWR, 0666)) < 0) { syslog(LOG_ERR, "PARENT: failed to create the file %s\n", THE_FILE); exit(EXIT_FAILURE); } syslog (LOG_NOTICE, "PARENT: Writing strings to the file:\n"); for (int i = 0; i < 3; ++i) { syslog (LOG_NOTICE, "[%d] %s\n", i, str[i].c_str()); write(fd, str[i].c_str(), str[i].length() + 1); } struct stat buf; if ((theFile = (char *)mmap(0, (size_t)buf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == (void *)-1) { syslog(LOG_ERR, "mmap failure"); exit(EXIT_FAILURE); } pid_t pid; /* Fork off the parent process */ pid = fork(); /* An error occurred */ if (pid < 0) { exit(EXIT_FAILURE); } /* Success: Let the parent terminate */ if (pid > 0) { syslog(LOG_NOTICE, "PARENT: child proccess %i created\n", (int)pid); wait(0); syslog (LOG_NOTICE, "PARENT: the work is done.\n"); closelog(); exit(EXIT_SUCCESS); } else { child_job(); } }
// Copyright (c) 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 _Aspect_ScrollDelta_HeaderFile #define _Aspect_ScrollDelta_HeaderFile #include <Aspect_VKeyFlags.hxx> #include <NCollection_Vec2.hxx> //! Parameters for mouse scroll action. struct Aspect_ScrollDelta { NCollection_Vec2<int> Point; //!< scale position Standard_Real Delta; //!< delta in pixels Aspect_VKeyFlags Flags; //!< key flags //! Return true if action has point defined. bool HasPoint() const { return Point.x() >= 0 && Point.y() >= 0; } //! Reset at point. void ResetPoint() { Point.SetValues (-1, -1); } //! Empty constructor. Aspect_ScrollDelta() : Point (-1, -1), Delta (0.0), Flags (Aspect_VKeyFlags_NONE) {} //! Constructor. Aspect_ScrollDelta (const NCollection_Vec2<int>& thePnt, Standard_Real theValue, Aspect_VKeyFlags theFlags = Aspect_VKeyFlags_NONE) : Point (thePnt), Delta (theValue), Flags (theFlags) {} //! Constructor with undefined point. Aspect_ScrollDelta (Standard_Real theValue, Aspect_VKeyFlags theFlags = Aspect_VKeyFlags_NONE) : Point (-1, -1), Delta (theValue), Flags (theFlags) {} }; #endif // _Aspect_ScrollDelta_HeaderFile
/*! \file */ //Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #ifndef STFY_APP_ADC_HPP_ #define STFY_APP_ADC_HPP_ #include <iface/dev/adc.h> #include "Periph.hpp" namespace hal { /*! \brief ADC Peripheral Class * \details This class implements ADC device peripherals. * * \code * #include <stfy/hal.hpp> * * int main(int argc, char * argv[]){ * Adc adc(0); //create an instance of ADC to access port 0 * adc_sample_t samples[16]; * adc.init((1<<0)|(1<<1)); //open() and set_attr() enabling channels 0 and 1 * adc.read(0, samples, 16*sizeof(adc_sample_t)); //read 16 samples from channel 0 * adc.read(1, samples, 16*sizeof(adc_sample_t)); //read 16 samples from channel 1 * adc.close(); //close the ADC * } * \endcode * */ class Adc : public Periph { public: /*! \details Initialize the instance with \a port */ Adc(port_t port); /*! \details Get the ADC attributes */ int get_attr(adc_attr_t & attr); /*! \details Set the ADC attributes */ int set_attr(const adc_attr_t & attr); /*! \details Set the ADC attributes */ int set_attr(u16 enabled_channels /*! Enabled Channels */, u32 freq = ADC_MAX_FREQ /*! ADC clock frequency (use ADC_MAX_FREQ for maximum speed) */, u8 pin_assign = 0 /*! Pin assignment value */){ adc_attr_t attr; attr.enabled_channels = enabled_channels; attr.freq = freq; attr.pin_assign = pin_assign; return set_attr(attr); } /*! \details This method opens the ADC then sets the ADC * attributes as specified. */ int init(u16 enabled_channels /*! Enabled Channels */, u32 freq = ADC_MAX_FREQ /*! ADC clock frequency (use ADC_MAX_FREQ for maximum speed) */, u8 pin_assign = 0 /*! Pin assignment value */){ if( open() < 0 ){ return -1; } return set_attr(enabled_channels, freq, pin_assign); } #ifdef __MCU_ONLY__ using Pblock::read; int read(void * buf, int nbyte); int close(); #endif private: }; }; #endif /* STFY_APP_ADC_HPP_ */
#include <stdio.h> #include <math.h> #include <windows.h> #include <vector> int main(){ }
#include "../src/BakeryLock.hpp" #include "../src/FixnumLockException.hpp" #include <thread> #include <iostream> #include <string> const int THREADS = 7; const size_t N = 6; int count = 0; lab::BakeryLock<N> bl; void change(const bool add) { try { for (int i = 0; i < 5; ++i) { bl.lock(); if (add) { ++count; std::cout << "Thread " << bl.get_id().value() << " added 1 and count is " << count << '\n'; } else { --count; std::cout << "Thread " << bl.get_id().value() << " subtracted 1 and count is " << count << '\n'; } bl.unlock(); } } catch (lab::MaxThreadReachedException e) { std::cout << e.what() << '\n'; } } auto main(int argc, char** argv) -> int { std::thread thr[THREADS]; for (int i = 0; i < THREADS; ++i) { if (i % 2 == 0) thr[i] = std::thread(change, true); else thr[i] = std::thread(change, false); } for (int i = 0; i < THREADS; ++i) thr[i].join(); return 0; }
#ifndef STATICGAMEOBJECT_H_ #define STATICGAMEOBJECT_H_ #include "GameObject.h" class StaticGameObject : public GameObject { protected: double worldX, worldY; double angle; public: StaticGameObject(SDL_Rect *r, SDL_Surface *s,double x, double y,double a); double getWorldX(); double getWorldY(); double getAngle(); void setWorldX(double); void setWorldY(double); void rotate(double a); }; #endif
#include "../include/histogram.h" #include "LightImage.h" namespace li { Histogram::Histogram() : channles(0), data(NULL) { } Histogram::Histogram(Image &_im) { channles = _im.channels; data = new int[channles * 256]; for (int j = 0; j < 256 * channles; ++j) { data[j] = 0; } int pix_cnt = _im.width * _im.height; for (int i = 0; i < pix_cnt; ++i) { for (int j = 0; j < _im.channels; ++j) { LI_U8 _v = _im.data[i * channles + j]; data[j * 256 + _v] += 1; } } } Histogram::~Histogram() { delete[] data; } Image Histogram::Render(int _width = 256, int _height = 180) { LI_U8 *dat = new LI_U8[_width * _height * channles]; int max = 0; for (int j = 0; j < 256 * channles; ++j) { if (data[j] > max) max = data[j]; } int cnt_per_pix = (max / _height) + 1; for (int i = 0; i < _height; ++i) { for (int j = 0; j < _width; ++j) { for (int k = 0; k < channles; ++k) { int _v = data[k * 256 + j]; auto h = _height - _v / cnt_per_pix; if (i > h) dat[(i * _width + j) * channles + k] = 255; else dat[(i * _width + j) * channles + k] = 0; } } } return Image(_width, _height, channles, dat); } double hist_simi(Image &_im1, Image &_im2) { Image temp1 = rgb2gray(_im1); Image temp2 = rgb2gray(_im2); Histogram h1(_im1); Histogram h2(_im2); int max1 = 0; int max2 = 0; double p1[255] = {0.0}; double p2[255] = {0.0}; for (int i = 1; i < 255; ++i) { if (h1.data[i] > max1) max1 = h1.data[i]; if (h2.data[i] > max2) max2 = h2.data[i]; } for (int j = 1; j < 255; ++j) { p1[j] = (double) h1.data[j] / (double) max1; p2[j] = (double) h2.data[j] / (double) max2; } double res = 0.0; for (int k = 1; k < 255; ++k) { res += abs(p1[k] - p2[k]); } return 1.0 / res; } Image histogram_eq(Image &_im) { Histogram h(_im); for (int i = 1; i < 256; ++i) { for (int j = 0; j < h.channles; ++j) { h.data[j * 256 + i] = h.data[j * 256 + i] + h.data[j * 256 + i - 1]; } } int pix_per_level = (_im.width * _im.height) / 256; LI_U8 *map = new LI_U8[h.channles * 256]; for (int i = 0; i < 256; ++i) { for (int j = 0; j < h.channles; ++j) { map[j * 256 + i] = h.data[j * 256 + i] / pix_per_level; } } LI_U8 *dat = new LI_U8[_im.width * _im.height * _im.channels]; for (int i = 0; i < _im.height; ++i) { for (int j = 0; j < _im.width; ++j) { for (int k = 0; k < _im.channels; ++k) { dat[(i * _im.width + j) * _im.channels + k] = map[k * 256 + _im.data[(i * _im.width + j) * _im.channels + k]]; } } } delete[](map); return Image(_im.width, _im.height, _im.channels, dat); } }
#include <iostream> #include "LaminateOrthotropic.h" using namespace std; int main() { MaterialOrthotropic material; LaminateOrthotropic laminate; material.E11 = 27000000.; material.E22 = 1500000.; material.nu12 = 0.35; material.G12 = 1100000.; laminate.stackup.resize(4); laminate.stackup[0].material = material; laminate.stackup[0].thickness = 0.008; laminate.stackup[0].orientation = 0.; laminate.stackup[1].material = material; laminate.stackup[1].thickness = 0.008; laminate.stackup[1].orientation = 45.; laminate.stackup[2].material = material; laminate.stackup[2].thickness = 0.008; laminate.stackup[2].orientation = -45.; laminate.stackup[3].material = material; laminate.stackup[3].thickness = 0.008; laminate.stackup[3].orientation = 90.; //laminate.stackup[4].material = material; //laminate.stackup[4].thickness = 0.008; //laminate.stackup[4].orientation = 90.; //laminate.stackup[5].material = material; //laminate.stackup[5].thickness = 0.008; //laminate.stackup[5].orientation = -45.; //laminate.stackup[6].material = material; //laminate.stackup[6].thickness = 0.008; //laminate.stackup[6].orientation = 45.; //laminate.stackup[7].material = material; //laminate.stackup[7].thickness = 0.008; //laminate.stackup[7].orientation = 0.; laminate.calculate_laminate_properties(); int k = 4; for(int i = 0; i < 4; i++) { cout << laminate.local_ply_strain[k][i].data[0]*1000000. << ","; cout << laminate.local_ply_strain[k][i].data[1]*1000000. << ","; cout << laminate.local_ply_strain[k][i].data[2]*1000000.; cout << "\n"; } for(int i = 0; i < 4; i++) { cout << laminate.local_ply_stress[k][i].data[0] << ","; cout << laminate.local_ply_stress[k][i].data[1] << ","; cout << laminate.local_ply_stress[k][i].data[2]; cout << "\n"; } }
#include <iostream> using namespace std; template <typename T, typename U> class multi{ public: T x; U y; multi(T a , U b) :x(a),y(b){} ~multi(){} T multi_out(){ return(x*y); } }; int main(){ multi<double,double> obj(5.3,4.34); cout << "Multiplied values :" << obj.multi_out() << endl; }