blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
c37ad0fb8c54b7a3015d149625dadcc20422db66
314d0b2f0c4687a61e9ee4ecbd5a6823903a2678
/src/support/pagelocker.cpp
6e6272f3bb4f4388106fef5e3792bd8741e88ea5
[ "MIT" ]
permissive
pelermu/zaap
e956f6ff2f89e02d86054f70ba32e9b3ad871b6b
58363ba5c14fc04e4439aa7cc9a18d7870270e43
refs/heads/master
2020-03-27T06:36:59.900631
2018-08-25T18:38:38
2018-08-25T18:38:38
146,120,318
0
0
MIT
2018-08-25T18:35:56
2018-08-25T18:35:56
null
UTF-8
C++
false
false
1,890
cpp
// Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "support/pagelocker.h" #if defined(HAVE_CONFIG_H) #include "config/zaap-config.h" #endif #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <windows.h> // This is used to attempt to keep keying material out of swap // Note that VirtualLock does not provide this as a guarantee on Windows, // but, in practice, memory that has been VirtualLock'd almost never gets written to // the pagefile except in rare circumstances where memory is extremely low. #else #include <sys/mman.h> #include <limits.h> // for PAGESIZE #include <unistd.h> // for sysconf #endif LockedPageManager* LockedPageManager::_instance = NULL; boost::once_flag LockedPageManager::init_flag = BOOST_ONCE_INIT; /** Determine system page size in bytes */ static inline size_t GetSystemPageSize() { size_t page_size; #if defined(WIN32) SYSTEM_INFO sSysInfo; GetSystemInfo(&sSysInfo); page_size = sSysInfo.dwPageSize; #elif defined(PAGESIZE) // defined in limits.h page_size = PAGESIZE; #else // assume some POSIX OS page_size = sysconf(_SC_PAGESIZE); #endif return page_size; } bool MemoryPageLocker::Lock(const void* addr, size_t len) { #ifdef WIN32 return VirtualLock(const_cast<void*>(addr), len) != 0; #else return mlock(addr, len) == 0; #endif } bool MemoryPageLocker::Unlock(const void* addr, size_t len) { #ifdef WIN32 return VirtualUnlock(const_cast<void*>(addr), len) != 0; #else return munlock(addr, len) == 0; #endif } LockedPageManager::LockedPageManager() : LockedPageManagerBase<MemoryPageLocker>(GetSystemPageSize()) { }
[ "37992703+zaapnetwork@users.noreply.github.com" ]
37992703+zaapnetwork@users.noreply.github.com
58fe43400f8def80a8f259a46e64b29e59f802c7
9b2f86a8ce31d512e82c091157066094df4e59cb
/PROJECT.CPP
33b8efde108464d0b4cade4f9a6309258e4e8937
[]
no_license
vishuchhabra/Turbo_programming
0c1e32071754ce6254d40fb50c67963bcfd5600a
8aa7aa900922cb0fd31003508baed4659f626dc1
refs/heads/master
2023-02-04T00:07:33.125087
2020-12-25T11:48:14
2020-12-25T11:48:14
278,798,873
0
0
null
null
null
null
UTF-8
C++
false
false
3,062
cpp
#include<iostream.h> #include<graphics.h> #include<conio.h> #include<dos.h> #include<stdlib.h> #include<stdio.h> #include<ctype.h> #include<fstream.h> #include<process.h> #include<string.h> #include<iomanip.h> class student { private: char uid[20]; char dob[10]; char father[15]; char bg[2]; char sex[1]; char mob[10]; char add[40]; char marks[15]; char branch[20]; char rf; char f[30]; unsigned long int fee; public: void adddata() { cout<<"REGISTRATION ID (name):"; gets(uid);//cin.getline(uid,19); fstream fout; fout.open(uid,ios::out); fout<<"REGISTRATION ID (name):"<<uid<<endl; cout<<"DATE OF BIRTH(dd\\mm\\yyyy):";cin>>dob; fout<<"DATE OF BIRTH(dd\mm\yyyy):"<<dob<<endl; cout<<"FATHER NAME :";gets(father); fout<<"FATHER NAME :"<<father<<endl; cout<<"BLOOD GROUP :";cin>>bg; fout<<"BLOOD GROUP :"<<bg<<endl; cout<<"SEX(m\\f):";cin>>sex; fout<<"SEX(m\\f):"<<sex<<endl; cout<<"MOBILE NO:";cin>>mob; fout<<"MOBILE NO:"<<mob<<endl; cout<<"ADDRESS:";gets(add); fout<<"ADDRESS:"<<add<<endl; cout<<"+2 MARKS:";gets(marks); fout<<"+2 MARKS:"<<marks<<endl; cout<<"BRANCH:";gets(branch); fout<<"BRANCH:"<<branch<<endl; cout<<"HAD STUDENT SUBMITTED TUITION FESS (y\\n):"; cin>>rf; if(rf=='y') { cout<<"BALANCE:0"<<endl; fout<<"BALANCE:0"<<endl; } else { cout<<"BALANCE=50000 "<<endl; fout<<"BALANCE=50000 "<<endl; } fout<<"***********************************"<<endl; cout<<"REGISTRATION COMPLETED......."<<endl; cout<<endl; for(int u=0;u<30;u++) { cout<<"<"; delay(20); } getch(); fout.close(); } void update() { cout<<"ENTER THE REGISTRATION ID:"; gets(uid); FILE *file; if(file =fopen(uid,"r")) { clrscr(); cout<<"PLEASE SELECT THE OPTION FOR UPDATES:"<<endl; cout<<"1.UPDATES AFTER REGISTRATION"<<endl; cout<<"2.UPDATES AFTER COMPLETING THE COURSE"<<endl; int k; cin>>k; switch(k) { case 1: { clrscr(); cout<<"ENTER ANY EXTRA WORK IN FIELD OF MEDICAL:"; gets(add); ofstream fout; fout.open(uid,ios::app); fout<<"UPDATES:"<<endl; fout<<"EXTRA WORK IN FIELD OF MEDICAL:"<<add<<endl; cout<<"ENTER THE PENDING TUITION FEE OF INSTITUTE:"; cin>>fee; fout<<"PENDING TUITION FEE AMMOUNT :"<<fee<<endl; cout<<"ENTER THE HOSTEL ROOM NO. IF ALLOTTED (otherwise nill):"; gets(branch); fout<<"HOSTEL ROOM ALLOTED:"<<branch<<endl; fout<<"***********************************"<<endl; fout.close(); cout<<"UPDATED SUCCESSFULLY !!!!!"<<endl; } break; case 2: clrscr(); cout<<"ENTER YOUR SPECIALIZATION :"; gets(f); ofstream j; j<<"ANOTHER UPDATE:"<<endl<<"SPECIALIZATION:"<<f<<endl; j<<"***********************************"<<endl; j.close(); cout<<"UPDATED SUCCESSFULLY !!!!!"<<endl; break; } } else cout<<"PLEASE ENTER THE VALID USER ID...... "<<endl; for(int u=0;u<30;u++) { cout<<"<<"; delay(20); } getch(); } }; void main() { clrscr(); student y; y.update(); }
[ "vishuchhabra1016@gmail.com" ]
vishuchhabra1016@gmail.com
658c354f2cd8a29272f0ab06e16e9ace05d7b8f4
da1aa824deb8d7d7416151601e662629765780f0
/Seg3D/src/Core/Skinner/VisibilityGroup.cc
384eab2049f7f2b0b6f7df39c2876cc009755484
[ "MIT" ]
permissive
viscenter/educe
69b5402782a4455af6d4009cb69f0d9a47042095
2dca76e7def3e0620896f155af64f6ba84163d77
refs/heads/master
2021-01-02T22:44:36.560170
2009-06-12T15:16:15
2009-06-12T15:16:15
5,413,435
1
0
null
null
null
null
UTF-8
C++
false
false
3,725
cc
// // For more information, please see: http://software.sci.utah.edu // // The MIT License // // Copyright (c) 2006 Scientific Computing and Imaging Institute, // University of Utah. // // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // File : VisibilityGroup.cc // Author : McKay Davis // Date : Tue Oct 3 23:17:07 2006 #include <Core/Skinner/Variables.h> #include <Core/Skinner/VisibilityGroup.h> #include <Core/Util/Assert.h> #include <Core/Containers/StringUtil.h> namespace SCIRun { namespace Skinner { VisibilityGroup::VisibilityGroup(Variables *variables) : Parent(variables), current_(variables,"VisibilityGroup::current","") { REGISTER_CATCHER_TARGET(VisibilityGroup::show_VisibleItem); REGISTER_CATCHER_TARGET(VisibilityGroup::VisibleItem_Maker); } BaseTool::propagation_state_e VisibilityGroup::VisibleItem_Maker(event_handle_t &maker_signal) { VisibleItem *child = construct_child_from_maker_signal<VisibleItem>(maker_signal); visible_items_.push_back(child); if (!current_().empty()) { child->visible_ = ends_with(child->get_id(), current_()); } return STOP_E; } VisibilityGroup::~VisibilityGroup() { } MinMax VisibilityGroup::get_minmax(unsigned int ltype) { return SPRING_MINMAX; } BaseTool::propagation_state_e VisibilityGroup::show_VisibleItem(event_handle_t &event) { Signal *signal = dynamic_cast<Signal *>(event.get_rep()); string id = "/"+signal->get_vars()->get_string("id"); Var<string> group(signal->get_vars(),"group",""); for (unsigned int i = 0; i < visible_items_.size(); ++i) { if (group() == visible_items_[i]->group_()) { bool wasvisible = visible_items_[i]->visible_(); bool isvisible = ends_with(visible_items_[i]->get_id(), id); if (wasvisible && !isvisible) { visible_items_[i]->throw_made_invisible(); visible_items_[i]->visible_ = false; } else if (!wasvisible && isvisible) { visible_items_[i]->visible_ = true; visible_items_[i]->throw_made_visible(); current_ = signal->get_vars()->get_string("id"); } } } return CONTINUE_E; } VisibleItem::VisibleItem(Variables *variables) : Parent(variables), group_(variables,"group","") { } VisibleItem::~VisibleItem() { } void VisibleItem::throw_made_visible() { throw_signal("VisibleItem::made_visible"); } void VisibleItem::throw_made_invisible() { throw_signal("VisibleItem::made_invisible"); } int VisibleItem::get_signal_id(const string &signalname) const { if (signalname == "VisibleItem::made_visible") return 1; if (signalname == "VisibleItem::made_invisible") return 2; return Parent::get_signal_id(signalname); } } }
[ "ryan.baumann@gmail.com" ]
ryan.baumann@gmail.com
40017dc26003180803f659b370acbcf8417b849d
9eca997425ba09c6878dd2b56d851abfc07083d6
/fboss/agent/hw/test/HwLinkStateToggler.cpp
f3dbadc3305b102bb069bc7c4327fa9c9c223f9a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
5GApp/fboss
7ee319d2446b0fbf31aaf35780cdd33ae16d397b
b038fabc5e7d762095aaf4ea576e1e2a025a9ba1
refs/heads/master
2023-02-22T10:30:10.836655
2021-01-28T23:50:42
2021-01-28T23:52:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,402
cpp
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/hw/test/HwLinkStateToggler.h" #include "fboss/agent/ApplyThriftConfig.h" #include "fboss/agent/HwSwitch.h" #include "fboss/agent/Platform.h" #include "fboss/agent/hw/switch_asics/HwAsic.h" #include "fboss/agent/state/Port.h" #include <boost/container/flat_map.hpp> #include <folly/gen/Base.h> namespace facebook::fboss { void HwLinkStateToggler::linkStateChanged(PortID port, bool up) noexcept { { std::lock_guard<std::mutex> lk(linkEventMutex_); if (!portIdToWaitFor_ || port != portIdToWaitFor_ || up != waitForPortUp_) { return; } desiredPortEventOccurred_ = true; portIdToWaitFor_ = std::nullopt; } linkEventCV_.notify_one(); } void HwLinkStateToggler::setPortIDAndStateToWaitFor( PortID port, bool waitForPortUp) { std::lock_guard<std::mutex> lk(linkEventMutex_); portIdToWaitFor_ = port; waitForPortUp_ = waitForPortUp; desiredPortEventOccurred_ = false; } void HwLinkStateToggler::portStateChangeImpl( std::shared_ptr<SwitchState> switchState, const std::vector<PortID>& ports, bool up) { auto newState = switchState; auto desiredLoopbackMode = up ? desiredLoopbackMode_ : cfg::PortLoopbackMode::NONE; for (auto port : ports) { if (newState->getPorts()->getPort(port)->getLoopbackMode() == desiredLoopbackMode) { continue; } newState = newState->clone(); auto newPort = newState->getPorts()->getPort(port)->modify(&newState); setPortIDAndStateToWaitFor(port, up); newPort->setLoopbackMode(desiredLoopbackMode); stateUpdateFn_(newState); invokeLinkScanIfNeeded(port, up); std::unique_lock<std::mutex> lock{linkEventMutex_}; linkEventCV_.wait(lock, [this] { return desiredPortEventOccurred_; }); /* toggle the oper state */ newState = newState->clone(); newPort = newState->getPorts()->getPort(port)->modify(&newState); newPort->setOperState(up); stateUpdateFn_(newState); } } void HwLinkStateToggler::applyInitialConfig( const std::shared_ptr<SwitchState>& curState, const Platform* platform, const cfg::SwitchConfig& initCfg) { auto newState = applyInitialConfigWithPortsDown(curState, platform, initCfg); bringUpPorts(newState, initCfg); } std::shared_ptr<SwitchState> HwLinkStateToggler::applyInitialConfigWithPortsDown( const std::shared_ptr<SwitchState>& curState, const Platform* platform, const cfg::SwitchConfig& initCfg) { // Goal of this function is twofold // - Apply initial config. // - Set preemphasis on all ports to 0 // We do this in 2 steps // i) Apply initial config, but with ports disabled. This is done to cater // for platforms where ports only show up after first config application // ii) Set preempahsis for all ports to 0 // iii) Apply initial config with the correct port state. // Coupled with preempahsis set to 0 and lbmode=NONE, this will keep ports // down. We will then set the enabled ports to desired loopback mode in // bringUpPorts API auto cfg = initCfg; boost::container::flat_map<int, cfg::PortState> portId2DesiredState; for (auto& port : *cfg.ports_ref()) { portId2DesiredState[*port.logicalID_ref()] = *port.state_ref(); // Keep ports down by disabling them and setting loopback mode to NONE *port.state_ref() = cfg::PortState::DISABLED; *port.loopbackMode_ref() = cfg::PortLoopbackMode::NONE; } // i) Set preempahsis to 0, so ports state can be manipulated by just setting // loopback mode (lopbackMode::NONE == down), loopbackMode::{MAC, PHY} == up) // ii) Apply first config with all ports set to loopback mode as NONE // iii) Synchronously bring ports up. By doing this we are guaranteed to have // tided over, over the first set of linkscan events that come as a result of // init (since there are no portup events in init + initial config // application). iii) Start tests. auto newState = applyThriftConfig(curState, &cfg, platform); stateUpdateFn_(newState); for (auto& port : *cfg.ports_ref()) { // Set all port preemphasis values to 0 so that we can bring ports up and // down by setting their loopback mode to PHY and NONE respectively. setPortPreemphasis( newState->getPorts()->getPort(PortID(*port.logicalID_ref())), 0); *port.state_ref() = portId2DesiredState[*port.logicalID_ref()]; } newState = applyThriftConfig(newState, &cfg, platform); stateUpdateFn_(newState); platform->getHwSwitch()->switchRunStateChanged(SwitchRunState::CONFIGURED); return newState; } void HwLinkStateToggler::bringUpPorts( const std::shared_ptr<SwitchState>& newState, const cfg::SwitchConfig& initCfg) { std::vector<PortID> portsToBringUp; folly::gen::from(*initCfg.ports_ref()) | folly::gen::filter([](const auto& port) { return *port.state_ref() == cfg::PortState::ENABLED; }) | folly::gen::map( [](const auto& port) { return PortID(*port.logicalID_ref()); }) | folly::gen::appendTo(portsToBringUp); bringUpPorts(newState, portsToBringUp); } } // namespace facebook::fboss
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
7d92c2b9008cfe2dd05181bcc1a7119684c8b263
5e7e51e706eeeaed51c1e82d97cff480c6347fb2
/myGraph/Graph.cpp
541c68d4442dca34dfc1a70cb534589a005cfea9
[]
no_license
ZMarsh20/DataStructures
27bf060fa36ccd48222ec7a36d19d9a94c8572eb
e7e9f7ce267286906f55edbef1c1a4d953cb7790
refs/heads/main
2023-01-08T21:20:37.215112
2020-11-02T00:55:47
2020-11-02T00:55:47
309,218,899
0
0
null
null
null
null
UTF-8
C++
false
false
6,881
cpp
#include "Graph.h" Graph::Graph() { top = nullptr; graph; size = 0; total = 0; } void Graph::load(string s) { ifstream infile(s); if (infile) { string line; while (getline(infile, line)) { string word, num = ""; vector<string> new_line; int counter = 0; line += ' '; for (char c : line) { if (counter % 2 == 1 || counter == 0) { if (c == ' ') { if (word != "") { add(word); new_line.push_back(word); word = ""; counter++; } } else if (c == '=' || c == '>') { continue; } else { word += c; } } else { if (c == ' ') { counter++; new_line.push_back(num); num = ""; } else { num += c; } } } update(new_line); } infile.close(); } } void Graph::add(string s) { Node* runner = top; while (runner != nullptr) { if (runner->name == s) return; runner = runner->next; } if (size == 0) { Node* p = new Node; p->name = s; p->pos = size; p->next = top; top = p; } else if (runner == nullptr) { Node* r = top; while (r->next != nullptr) r = r->next; Node* p = new Node; p->name = s; p->pos = size; p->next = nullptr; r->next = p; } size++; vector<int> new_vector(size); graph.push_back(new_vector); for (int i = 0; i < size - 1; i++) { graph[i].push_back(0); } } void Graph::update(vector<string> s) { Node* runner = top; while (runner->name != s.at(0)) runner = runner->next; int spot = runner->pos; int num = 0; for (int i = s.size(); i > 1; i--) { if (i % 2 == 0) { runner = top; while (runner->name != s[i - 1]) runner = runner->next; graph[spot][runner->pos] = num; } else { num = stoi(s[i - 1]); total += num; } } } void Graph::display() { Node* runner = top; cout << '\t'; while (runner != nullptr) { cout << runner->name << '\t'; runner = runner->next; } cout << endl << endl; runner = top; for (int i = 0; i < size; i++) { cout << " " << runner->name << "\t"; for (int j = 0; j < size; j++) { cout << graph[i][j] << "\t"; } cout << endl << endl; runner = runner->next; } } void Graph::adjacent(string s) { Node* runner = top; while (runner != nullptr && runner->name != s) runner = runner->next; if (runner == nullptr) { cout << "There is no " << s << " name in the digraph\n\n"; return; } Node* run = top; cout << runner->name << ": "; for (int i = 0; i < size; i++) { if (graph[runner->pos][i] > 0) { cout << run->name << " "; } run = run->next; } cout << endl << endl; } void Graph::dfs(string s) { Node* runner = top; while (runner != nullptr && runner->name != s) runner = runner->next; Node* run = top; for (int i = 0; i < size; i++) { if (graph[runner->pos][i] > 0 && run->mark == false) { run->mark = true; cout << " -> " << run->name; dfs(run->name); cout << "\nBack to " << s; run->mark = false; } run = run->next; } } void Graph::DFS(string s) { Node* runner = top; while (runner != nullptr && runner->name != s) runner = runner->next; if (runner == nullptr) { cout << "There is no " << s << " word in the digraph\n\n"; return; } runner->mark = true; cout << s; dfs(s); cout << endl << endl; runner->mark = false; } void Graph::bfs(string s) { cout << s << " -> "; Node* runner = top; while (runner != nullptr && runner->name != s) runner = runner->next; Node* run = top; for (int i = 0; i < size; i++) { if (graph[runner->pos][i] > 0) { cout << " " << run->name; } run = run->next; } cout << endl; run = top; for (int i = 0; i < size; i++) { if (graph[runner->pos][i] > 0 && run->mark == false) { run->mark = true; bfs(run->name); } run = run->next; } } void Graph::BFS(string s) { Node* runner = top; int depth, total = 0; while (runner != nullptr && runner->name != s) runner = runner->next; if (runner == nullptr) { cout << "There is no " << s << " word in the digraph\n\n"; return; } runner->mark = true; bfs(s); cleanup(); cout << endl; } void Graph::connected(Node* r, Node* n) { Node* runner = top; for (int i = 0; i < size; i++) { if (graph[n->pos][i] > 0 && runner->mark == false) { if (runner->connected == true) { r->connected = true; return; } else { runner->mark = true; r->connect++; } } runner = runner->next; } if (r->connect != size - 1) { int j = n->pos; n = top; for (int i = 0; i < size; i++) { if (graph[j][i] > 0) connected(r, n); n = n->next; if (r->connected == true) { break; } } } else { r->connected = true; return; } } bool Graph::Connected() { Node* runner = top; Node* r = top; while (runner != nullptr) { connected(runner, runner); while (r != nullptr) { r->mark = false; r = r->next; } r = top; runner = runner->next; } runner = top; while (runner != nullptr) { if (runner->connected != true) { cleanup(); return false; } runner = runner->next; } cleanup(); return true; } void Graph::dike(Node* s, Node* e, int t, int& curr, int run, vector<Node*>& order) { Node* r = top; for (int i = 0; i < size; i++) { if (graph[s->pos][i] > 0 && r == e && (t + graph[s->pos][i]) < curr) { order[run] = r; curr = t + graph[s->pos][i]; e->connected = true; break; } r = r->next; } r = top; for (int i = 0; i < size; i++) { if (graph[s->pos][i] > 0 && r->mark == false && r != e && t + graph[s->pos][i] < curr) { r->mark = true; bool hold = false; if (e->connected) { e->connected = false; hold = true; } dike(r, e, t + graph[s->pos][i], curr, run + 1, order); if (e->connected) order[run] = r; if (hold) e->connected = hold; r->mark = false; } r = r->next; } } void Graph::path(vector<Node*> order, Node* e) { if (order[1] == nullptr) { cout << "The two are not connected in any way\n\n"; return; } int i = 0; while (i < size) { if (order[i] == e) break; cout << order[i]->name << " -" << graph[order[i]->pos][order[i + 1]->pos] << "-> "; i++; } cout << order[i]->name << endl << endl; } void Graph::Dijkstra(string start, string end) { Node* s = top; Node* e = top; while (s != nullptr && s->name != start) { s = s->next; } while (e != nullptr && e->name != end) { e = e->next; } if (s == nullptr) { cout << start << " does not exist in the digraph\n\n"; return; } if (e == nullptr) { cout << end << " does not exist in the digraph\n\n"; return; } if (start == end) { cout << "They are the same place\n\n"; return; } int curr = total; vector<Node*> order(size); order[0] = s; s->mark = true; dike(s, e, 0, curr, 1, order); s->mark = false; path(order, e); cleanup(); } void Graph::cleanup() { Node* r = top; while (r != nullptr) { r->connect = 0; r->connected = false; r->mark = false; r = r->next; } }
[ "marshallz2018@gmail.com" ]
marshallz2018@gmail.com
525b079a163e55e1badf3a1a3b3e88f1a3ac9209
d9e1dfe0f69cb0913de74d142bdc53e481fc4a02
/oopL2/main.cpp
3bcf18395047fa63b62919eb82fa9654e3b9674c
[]
no_license
castlesofplacebo/object-oriented-programming-labs
4ecc23be5fc812192e59f57196d803f164ef1274
5f61541fb5c49db60f9dadbe9395fad82883ad04
refs/heads/master
2023-03-31T21:10:37.323883
2021-04-11T21:05:09
2021-04-11T21:05:09
304,923,916
0
1
null
null
null
null
UTF-8
C++
false
false
3,189
cpp
#include <iostream> #include "AbstractProduct.h" #include "Product.h" #include "Shop.h" #include "Dispatcher.h" using namespace std; int main() { try { AbstractProduct product1("1", "apple"); AbstractProduct product2("2", "apple"); AbstractProduct product3("3", "apple"); AbstractProduct product4("4", "apple"); AbstractProduct product5("5", "apple"); AbstractProduct product6("6", "apple"); AbstractProduct product7("7", "apple"); AbstractProduct product8("8", "apple"); AbstractProduct product9("9", "apple"); AbstractProduct product10("10", "apple"); //tests for 3-rd statement -> passed Shop shop1("01", "7-eleven", "Alpiysky per"); shop1.addProductsInTheShop(product1, 2, 450.0); shop1.addProductsInTheShop(product2, 3, 200.0); shop1.addProductsInTheShop(product2, 3, 100.0); shop1.addProductsInTheShop(product9, 1, 1200.91); //shop1.setPrice(product1, 30.1); Shop shop2("02", "Metro", "Belorusskaya st"); shop2.addProductsInTheShop(product1, 7, 70.1); shop2.addProductsInTheShop(product2, 9, 10.0); shop2.addProductsInTheShop(product5, 4, 30.9); Shop shop3("03", "Ashan", "Vyazemsky per"); shop3.addProductsInTheShop(product1, 1, 50.1); shop3.addProductsInTheShop(product3, 2, 230.0); shop3.addProductsInTheShop(product9, 78, 1200.9); Dispatcher city("saint-product_list"); city.addShop(&shop1); city.addShop(&shop2); city.addShop(&shop3); //test for 4-th statement -> passed /* Shop result = city.theCheapestProduct(product4); cout << "Shop code, name and address : " << result.getCode() << " " << result.getName() << " " << result.getAddress() << endl; */ //test for 5-th statement -> passed /*vector<pair<size_t, AbstractProduct>> currentList = shop1.forTheAmount(100005000.0); for (auto i : currentList) { cout << "Count : " << i.first << "; Product code and name : " << i.second.getCode() << " " << i.second.getName() << endl; }*/ //test for 6-th statement -> passed /*vector<pair<int, AbstractProduct>> currentList; currentList.emplace_back(make_pair(2, product1)); currentList.emplace_back(make_pair(4, product2)); cout << shop1.buyProducts(currentList) << endl;*/ //test for 7-th statement -> passed /* vector<pair<int, AbstractProduct>> currentList; currentList.emplace_back(make_pair(2, product1)); currentList.emplace_back(make_pair(3, product2)); Shop result = city.theCheapestList(currentList); cout << "Shop code, name and address : " << result.getCode() << " " << result.getName() << " " << result.getAddress() << endl; */ //to see what shop contains /*vector<Product> curr = shop1.getProducts(); for (auto i : curr) cout << i.getCode() << " " << i.getCount() << endl;*/ } catch (exception &err) { cout << err.what() << endl; return EXIT_FAILURE; } return 0; }
[ "castlesofplacebo@gmail.com" ]
castlesofplacebo@gmail.com
86d96c855cb2f6c900442659c13091b19b0972a9
a44a5766fdc2f2a5544ef828e78b3d0f6c25cb52
/m_3sum_closest.cpp
ce92cde7703c4926ef6ee848ffe94c15dcfb34ee
[ "MIT" ]
permissive
skyera/myleetcode
79d85d8ac1a4483da0aba4252aad960c5d77b246
c3524e73b320afb863d0c04d40b1b660ff9fec8c
refs/heads/master
2021-01-12T12:12:50.943934
2017-10-22T18:31:05
2017-10-22T18:31:05
72,364,302
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
// 3sum closest // Medium // 9/12/2017 #include <iostream> #include <vector> #include <cstdlib> #include <algorithm> #include <iterator> #include <climits> using namespace std; int threesumclosest(vector<int> &nums, int target) { int result = 0; int min_gap = INT_MAX; sort(nums.begin(), nums.end()); for (auto a = nums.begin(); a != prev(nums.end(), 2); ++a) { auto b = next(a); auto c = prev(nums.end()); while (b < c) { const int sum = *a + *b + *c; const int gap = abs(sum - target); if (gap < min_gap) { result = sum; min_gap = gap; } if (sum < target) ++b; else --c; } } return result; } int main() { return 0; }
[ "zgliu71@gmail.com" ]
zgliu71@gmail.com
501695a8eef77a70f07ae096b8db5a96fbdf9b2f
8105c30b6a950f4e7d64986f8b8f7950999d6c51
/unitTest/TaskTest.cpp
3ea35b6714387a48064d88dddac54b3bc4100989
[]
no_license
dario-DI/DistributedCompute
fb690b7ab7a8c00ed7503a1025d5004da99a2fcc
db97c7463bc1b86f3aa1e81657edd0be7aa4cad5
refs/heads/master
2021-01-19T16:25:15.224669
2014-09-28T03:09:09
2014-09-28T03:09:09
7,122,729
15
11
null
null
null
null
UTF-8
C++
false
false
1,823
cpp
// test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <assert.h> #include <fstream> #include <zmq.h> #include <DCompute/zmqEx.h> #include <DCompute/joberServer.h> #include <DCompute/worker.h> #include <DCompute/client.h> #include <DCompute/task.h> #include <DCompute/util.h> using namespace DCompute; class Task1 : public cex::Interface { public: Task1() { result=0; book = "you are ok, hello!"; } GF_DECL_SERIALIZABLE(Task1) int result; std::string book; void Do() { int* kk=new int; delete kk; for(size_t i=0; i<book.length(); ++i) { if (book.at(i)=='e') { ++result; } } printf("result:%d.\n", result); } }; GF_BEGIN_SERIALIZE_IMPL_NOW(Task1, 1) //GF_SERIALIZE_BASE(BaseS) GF_SERIALIZE_MEMBER(book) GF_END_SERIALIZE_IMPL GF_CLASS_VERSION(Task1, 1) REGIST_DELTA_CREATOR(Task1, TDCTaskProxy<Task1>) using namespace DCompute; #define WORKERSIZE 4 #define TASKSIZE 40 CEX_TEST(TaskTest) { int cpu = Util::DetectNumberOfProcessor(); auto server = cex::DeltaCreateRef<IJoberServer>(); server->create(); server->start(); { std::shared_ptr<IWorker> worker[WORKERSIZE]; for (int i=0; i<WORKERSIZE; ++i) { worker[i] = cex::DeltaCreateRef<IWorker>(); } for (int i=0; i<WORKERSIZE; ++i) { worker[i]->setID(i); worker[i]->create(); worker[i]->start(); } size_t workerSize = Util::GetWorkerSize(); assert(workerSize==WORKERSIZE); Task1 tasks[TASKSIZE]; DoMultiTask(tasks, TASKSIZE, 5000); int allResult=0; for (int i=0;i<TASKSIZE;++i) { allResult+=tasks[i].result; } printf("result reduced: %d.\n", allResult); assert(allResult==2*TASKSIZE); system("pause"); for (int i=0; i<WORKERSIZE; ++i) { worker[i]->join(); } } //Sleep(1000000000); server->join(); }
[ "dx2120@163.com" ]
dx2120@163.com
835a8bfa8b60f46bbb5e6185cdce15a95337d83b
03f9fc20b63e7c7b494cc29f54a16f57be062e98
/Computers/Computer.cpp
f6bb58b23f51d7444ca21c9ca8f213085bb05068
[]
no_license
imnikitaokunev/ComputerComponents
f9b12b6f0e5d2ca761018cc665d171306fc88684
fc681c906f79f314b7d28c62148742f12c0fcc70
refs/heads/master
2022-01-10T12:02:15.729181
2019-05-15T21:31:41
2019-05-16T12:08:44
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
12,575
cpp
#include "Computer.h" void Computer::setDrive(int dr) { drive = dr; } int Computer::getDrive() const { return drive; } void Computer::title() { cout << setw(67) << "---Компьютеры---" << endl << endl; } void Computer::header() { ElectronicDevice::header(); cout << setw(4) << "|" << setw(8) << "Cores" << setw(4) << "|" << setw(8) << "Freq." << setw(4) << "|" << setw(7) << "VRAM" << setw(4) << "|" << setw(6) << "RAM" << setw(4) << "|" << setw(11) << "Capacity" << setw(4) << "|" << setw(8) << "Drive" << endl; cout << setw(105) << "----------|----------|-----------|-----------|----------|---------|--------------|----------" << endl; } void Computer::change() { char choice; do { system("cls"); this->title(); cout << endl; cout << " Какие поля вы желаете изменить?" << endl; cout << "\t1. Модель." << endl << "\t2. Стоимость." << endl << "\t3. Тип ОЗУ." << endl << "\t4. Объем ОЗУ." << endl << "\t5. Объем видеопамяти." << endl << "\t6. Количество ядер процессора." << endl << "\t7. Базовая частота процессора." << endl << "\t8. Объем винчестера." << endl << "\t0. Назад." << endl << endl << "\t >> "; choice = _getch(); cout << choice << endl << endl; switch (choice) { case '1': cout << "Новая модель: "; this->model = inputStringWithNums(); break; case '2': cout << "Новая стоимость: "; this->cost = inputNumber(MIN, MAX); break; case '3': cout << "Новый тип ОЗУ: "; this->memoryType = inputStringWithNums(); break; case '4': cout << "Новый объем ОЗУ: "; this->capacity = inputNumber(MIN, MAXCAPACITY); break; case '5': cout << "Новый объем видеопамяти: "; this->memorySize = inputNumber(MIN, MAXVRAM); break; case '6': cout << "Новое количество ядер процессора: "; this->countOfCores = inputNumber(MIN, MAXCORES); break; case '7': cout << "Новая базовая частота процесора: "; this->baseFrequency = inputNumber(MIN, MAXFREQUENCY); break; case '8': cout << "Новый объем винчестера: "; this->drive = inputNumber(MIN, MAXDRIVE); break; case '0': break; default: cout << endl; cout << "Некорректный ввод." << endl;; system("pause"); break; } cout << "Желаете изменить что-то еще?(1 - да/0 - нет) "; choice = _getch(); cout << choice << endl; } while (choice != '0'); } void Computer::search(bool* flag) { Computer temp; char choice; do { system("cls"); this->title(); cout << endl; cout << " По каким полям вы желаете совершить поиск?" << endl; cout << "\t1. Модель." << endl << "\t2. Стоимость." << endl << "\t3. Тип ОЗУ." << endl << "\t4. Объем ОЗУ." << endl << "\t5. Объем видеопамяти." << endl << "\t6. Количество ядер процессора." << endl << "\t7. Базовая частота процессора." << endl << "\t8. Объем винчестера." << endl << "\t0. Назад." << endl << endl << "\t >> "; choice = _getch(); cout << choice << endl << endl; switch (choice) { case '1': cout << "Модель: "; flag[MODEL] = true; this->model = inputStringWithNums(); break; case '2': cout << "Стоимость: "; flag[COST] = true; this->cost = inputNumber(MIN, MAX); break; case '3': cout << "Тип ОЗУ: "; flag[MEMORYTYPE] = true; this->memoryType = inputStringWithNums(); break; case '4': cout << "Объем ОЗУ: "; flag[CAPACITY] = true; this->capacity = inputNumber(MIN, MAXCAPACITY); break; case '5': cout << "Объем видеопамяти: "; flag[MEMORYSIZE] = true; this->memorySize = inputNumber(MIN, MAXVRAM); break; case '6': cout << "Количество ядер процессора: "; flag[COUNTOFCORES] = true; this->countOfCores = inputNumber(MIN, MAXCORES); break; case '7': cout << "Базовая частота процесора: "; flag[BASEFREQUENCY] = true; this->baseFrequency = inputNumber(MIN, MAXFREQUENCY); break; case '8': cout << "Объем винчестера: "; flag[DRIVE] = true; this->drive = inputNumber(MIN, MAXDRIVE); break; case '0': break; default: cout << endl; cout << "Некорректный ввод." << endl;; system("pause"); break; } cout << "Желаете добавить что-то еще?(1 - да/0 - нет) "; choice = _getch(); cout << choice << endl; } while (choice != '0'); } void Computer::changeField() { char choice; system("cls"); this->title(); cout << endl; cout << " По какому полю построить дерево?" << endl; cout << "\t1. Модель." << endl << "\t2. Стоимость." << endl << "\t3. Тип ОЗУ." << endl << "\t4. Объем ОЗУ." << endl << "\t5. Объем видеопамяти." << endl << "\t6. Количество ядер процессора." << endl << "\t7. Базовая частота процессора." << endl << "\t8. Объем винчестера." << endl << "\t0. Назад." << endl << endl << "\t >> "; choice = _getch(); cout << choice << endl << endl; switch (choice) { case '1': field = MODEL; break; case '2': field = COST; break; case '3': field = MEMORYTYPE; break; case '4': field = CAPACITY; break; case '5': field = MEMORYSIZE; break; case '6': field = COUNTOFCORES; break; case '7': field = BASEFREQUENCY; break; case '8': field = DRIVE; break; case '0': break; default: cout << endl; cout << "Некорректный ввод." << endl;; system("pause"); break; } } bool Computer::isEqual(Computer& other) { if (field == COST) if (this->cost == other.cost) return true; if (field == MODEL) if (this->model == other.model) return true; if (field == CAPACITY) if (this->capacity == other.capacity) return true; if (field == MEMORYTYPE) if (this->memoryType == other.memoryType) return true; if (field == MEMORYSIZE) if (this->memorySize == other.memorySize) return true; if (field == BASEFREQUENCY) if (this->baseFrequency == other.baseFrequency) return true; if (field == COUNTOFCORES) if (this->countOfCores == other.countOfCores) return true; if (field == DRIVE) if (this->drive == other.drive) return true; return false; } bool Computer::isEqual(Computer& other, bool* flag) { if (flag[COST] == true) if (this->cost != other.cost) return false; if (flag[MODEL] == true) if (this->model != other.model) return false; if (flag[CAPACITY] == true) if (this->capacity != other.capacity) return false; if (flag[MEMORYTYPE] == true) if (this->memoryType != other.memoryType) return false; if (flag[MEMORYSIZE] == true) if (this->memorySize != other.memorySize) return false; if (flag[BASEFREQUENCY] == true) if (this->baseFrequency != other.baseFrequency) return false; if (flag[COUNTOFCORES] == true) if (this->countOfCores != other.countOfCores) return false; if (flag[DRIVE] == true) if (this->drive != other.drive) return false; return true; } bool Computer::operator==(Computer& other) { if (this->cost != other.cost) return false; if (this->model != other.model) return false; if (this->capacity != other.capacity) return false; if (this->memoryType != other.memoryType) return false; if (this->memorySize != other.memorySize) return false; if (this->baseFrequency != other.baseFrequency) return false; if (this->countOfCores != other.countOfCores) return false; if (this->drive != other.drive) return false; return true; } bool Computer::operator>(Computer& other) { if (field == COST) if (this->cost > other.cost) return true; if (field == MODEL) if (this->model > other.model) return true; if (field == CAPACITY) if (this->capacity > other.capacity) return true; if (field == MEMORYTYPE) if (this->memoryType > other.memoryType) return true; if (field == MEMORYSIZE) if (this->memorySize > other.memorySize) return true; if (field == BASEFREQUENCY) if (this->baseFrequency > other.baseFrequency) return true; if (field == COUNTOFCORES) if (this->countOfCores > other.countOfCores) return true; if (field == DRIVE) if (this->drive > other.drive) return true; return false; } bool Computer::operator<(Computer& other) { if (field == COST) if (this->cost < other.cost) return true; if (field == MODEL) if (this->model < other.model) return true; if (field == CAPACITY) if (this->capacity < other.capacity) return true; if (field == MEMORYTYPE) if (this->memoryType < other.memoryType) return true; if (field == MEMORYSIZE) if (this->memorySize < other.memorySize) return true; if (field == BASEFREQUENCY) if (this->baseFrequency < other.baseFrequency) return true; if (field == COUNTOFCORES) if (this->countOfCores < other.countOfCores) return true; if (field == DRIVE) if (this->drive < other.drive) return true; return false; } istream& operator >>(istream& in, Computer& obj) { in >> dynamic_cast<CPU&> (obj); cout << "Объем видеопамяти: "; obj.memorySize = inputNumber(MIN, MAXVRAM); cout << "Тип ОЗУ: "; obj.memoryType = inputStringWithNums(); cout << "Емкость ОЗУ: "; obj.capacity = inputNumber(MIN, MAXCAPACITY); cout << "Винчестер: "; obj.drive = inputNumber(MIN, MAXDRIVE); return in; } ostream& operator <<(ostream& out, Computer& obj) { out << dynamic_cast <CPU&> (obj); out << setw(4) << "|" << setw(7) << obj.memorySize << setw(4) << "|" << setw(6) << obj.memoryType << setw(4) << "|" << setw(11) << obj.capacity << setw(4) << "|" << setw(8) << obj.drive; return out; } ifstream& operator >> (ifstream &fin, Computer& obj) { fin >> dynamic_cast<ElectronicDevice&>(obj); fin >> obj.countOfCores; fin >> obj.baseFrequency; fin >> obj.capacity; fin.get(); getline(fin, obj.memoryType, '*'); fin >> obj.memorySize; fin >> obj.drive; fin.get(); return fin; } ofstream& operator << (ofstream& fout, Computer& obj) { fout << dynamic_cast<ElectronicDevice&> (obj); fout << ' ' << obj.countOfCores << ' ' << obj.baseFrequency << ' ' << obj.memorySize << ' ' << obj.memoryType << "*" << ' ' << obj.capacity << ' ' << obj.drive; return fout; } void Computer::writeToBinary(ofstream& out, Computer& obj) { out.write(obj.model.c_str(), sizeof(obj.model)); out.write(reinterpret_cast<char*>(&obj.cost), sizeof(obj.cost)); out.write(reinterpret_cast<char*>(&obj.countOfCores), sizeof(obj.countOfCores)); out.write(reinterpret_cast<char*>(&obj.baseFrequency), sizeof(obj.baseFrequency)); out.write(reinterpret_cast<char*>(&obj.capacity), sizeof(obj.capacity)); out.write(obj.memoryType.c_str(), sizeof(obj.memoryType)); out.write(reinterpret_cast<char*>(&obj.memorySize), sizeof(obj.memorySize)); out.write(reinterpret_cast<char*>(&obj.drive), sizeof(obj.drive)); out.write("\n", sizeof("\n")); } void Computer::readFromBinary(ifstream& in, Computer& obj) { in.read(const_cast<char*>(obj.model.c_str()), sizeof(obj.model)); in.read(reinterpret_cast<char*>(&obj.cost), sizeof(obj.cost)); in.read(reinterpret_cast<char*>(&obj.countOfCores), sizeof(obj.countOfCores)); in.read(reinterpret_cast<char*>(&obj.baseFrequency), sizeof(obj.baseFrequency)); in.read(reinterpret_cast<char*>(&obj.capacity), sizeof(obj.capacity)); in.read(const_cast<char*>(obj.memoryType.c_str()), sizeof(obj.memoryType)); in.read(reinterpret_cast<char*>(&obj.memorySize), sizeof(obj.memorySize)); in.read(reinterpret_cast<char*>(&obj.drive), sizeof(obj.drive)); string buf; getline(in, buf, '\n'); in.get(); }
[ "nikitosinos1@gmail.com" ]
nikitosinos1@gmail.com
07e43a18c815a4310d26f171e94401d45e0011c2
934620766e762e270024febb0d78924070a01230
/sec2-2/소스3.cpp
8eabf3b0106d1e644f75eb6717a1826d1bba7a40
[]
no_license
whwofla/sec2-2
391e949a099616a38ca8a6ee2b08755578c9d6f4
9400cd257c6237d23d1e4e2eb4df06a371374547
refs/heads/master
2023-01-23T18:50:48.305137
2020-11-27T02:40:58
2020-11-27T02:40:58
298,446,991
0
0
null
null
null
null
UHC
C++
false
false
996
cpp
#include <stdio.h> #include "소스1.cpp" int main(void) { IntStack s; if (Initialize(&s, 64) == -1) { puts("스택 생성에 실패하였습니다"); return 1; } while (1) { int menu, x; printf("현재 데이터수 : %d / %d\n", Size(&s), Capacity(&s)); printf("(1)푸시 (2)팝 (3)피크 (4)출력 (0)종료 "); scanf_s("%d", menu); if (menu == 0) break; switch (menu) { case 1: printf("데이터 : "); scanf_s("%d", &x); if (push(&s, x) == -1) puts("\a오류:푸시에 실패하였습니다."); break; case 2: if (Pop(&s, &x) == -1) puts("\a오류:팝에 실패하였습니다."); else printf("팝 데이터는 %d 입니다\n", x); break; case 3: if (Peek(&s, &x) == -1) puts("\a오류 : 피크에 실패하였습니다."); else printf("피크 데이터는 %d 입니다. \n", x); break; case 4: print(&s); break; } } Terminate(&s); return 0; }
[ "whwo2142@naver.com" ]
whwo2142@naver.com
a237ba95fb1136d0a6a21dc5a90270fd97921e3c
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Shared/src/TileFeature.cpp
94d2fb1453aab210b122e894524721b257f5d468
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,954
cpp
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd 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 the Vodafone Group Services Ltd 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. */ #include "TileMapConfig.h" #include "TileFeature.h" #include "TileMapFormatDesc.h" using namespace std; // ------------------------------- TilePrimitiveFeature ------------------- // ------------------------------- TileFeature ---------------------------- TileFeature::TileFeature(int32 type) : TilePrimitiveFeature(type) { } TileFeature::~TileFeature() { for ( vector<TileFeatureArg*>::iterator it = m_args.begin(); it != m_args.end(); ++it ) { delete *it; } } // This copy constructor may be used in vector. TileFeature::TileFeature(const TileFeature& other) : TilePrimitiveFeature(other) { m_args.clear(); } const TileFeature& TileFeature::operator=(const TileFeature& other) { if ( this != &other ) { m_args.clear(); } return *this; } #ifdef MC2_SYSTEM bool TileFeature::save( BitBuffer& buf, const TileMap& tileMap, const TileFeature* prevFeature ) const { bool sameType = false; if ( ( prevFeature == NULL ) || ( getType() != prevFeature->getType() ) ) { // Not same as previous. buf.writeNextBits( 0, 1 ); // Write the type. buf.writeNextBits( m_type, 8 ); prevFeature = NULL; mc2dbg8 << "TileFeature::save Explicitly saving the type" << endl; } else { sameType = true; // Same as previous. buf.writeNextBits( 1, 1 ); mc2dbg8 << "TileFeature::save Implicitly saving the type" << endl; } if ( sameType ) { // Submit the previous feature into the save method for the // arguments. vector<TileFeatureArg*>::const_iterator prevIt = prevFeature->m_args.begin(); for ( vector<TileFeatureArg*>::const_iterator it = m_args.begin(); it != m_args.end(); ++it ) { (*it)->save( buf, tileMap, *prevIt ); ++prevIt; } } else { // No previous feature of same type. for ( vector<TileFeatureArg*>::const_iterator it = m_args.begin(); it != m_args.end(); ++it ) { (*it)->save( buf, tileMap, NULL ); } } return true; } void TileFeature::dump( ostream& stream ) const { stream << "Feature type " << (int) m_type << endl; for ( vector<TileFeatureArg*>::const_iterator it = m_args.begin(); it != m_args.end(); ++it ) { (*it)->dump( stream ); } } #endif bool TilePrimitiveFeature::internalLoad( BitBuffer& buf, TileMap& tileMap, const TilePrimitiveFeature* prevFeature ) { if ( prevFeature != NULL ) { // Use previous arguments vector<TileFeatureArg*>::const_iterator prevIt = prevFeature->m_args.begin(); for ( vector<TileFeatureArg*>::const_iterator it = m_args.begin(); it != m_args.end(); ++it ) { (*it)->load( buf, tileMap, *prevIt ); ++prevIt; } } else { // Don't use previous arguments. for ( vector<TileFeatureArg*>::const_iterator it = m_args.begin(); it != m_args.end(); ++it ) { (*it)->load( buf, tileMap, NULL ); } } return true; } bool TilePrimitiveFeature::createFromStream( TilePrimitiveFeature& target, BitBuffer& buf, const TileMapFormatDesc& desc, TileMap& tileMap, const TilePrimitiveFeature* prevFeature ) { // Create TileFeature of correct dynamic type. bool sameAsPrevious = buf.readNextBits( 1 ) != 0; int16 type; if ( sameAsPrevious ) { // Same as previous. type = prevFeature->getType(); } else { // Not same as previous. // Read the actual type. type = int16( buf.readNextSignedBits( 8 ) ); } target.setType( type ); if ( ! desc.getArgsForFeatureType( type, target.m_args ) ) { mc2log << "TileFeature::createFromStream - Could not find args " << "for feature of type " << type << endl; return false; } // Load the feature with internalLoad. // Supply the previous feature if it is of the same type. target.internalLoad( buf, tileMap, sameAsPrevious ? prevFeature : NULL ); return true; }
[ "hlars@sema-ovpn-morpheus.itinerary.com" ]
hlars@sema-ovpn-morpheus.itinerary.com
be60edf2692d5116ce0e8d90a755d7205fb1af61
984873a2c70b7224a9f779d5ff2c3eb9b3958eea
/Project/lua_library/ltable.cpp
a8aa5e1d1792ae8875a48a690eb7da6ee0668b27
[]
no_license
nanguazhude/MyLearnLua
0c347d6a8f8f38fb78b6264068fca6ffad6a494f
f2012130898079d1ed78a6d2ff6d55fd9e6dde1f
refs/heads/master
2020-03-10T17:39:54.108047
2018-04-26T08:41:42
2018-04-26T08:41:42
129,505,359
0
0
null
null
null
null
UTF-8
C++
false
false
19,829
cpp
/* ** $Id: ltable.c,v 2.118 2016/11/07 12:38:35 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ #define ltable_c #ifndef LUA_CORE #define LUA_CORE #endif #include "lprefix.hpp" /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array ** part. The actual size of the array is the largest 'n' such that ** more than half the slots between 1 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not ** in its main position (i.e. the 'original' position that its hash gives ** to it), then the colliding element is in its own main position. ** Hence even when the load factor reaches 100%, performance remains good. */ #include <cmath> #include <climits> #include "lua.hpp" #include "ldebug.hpp" #include "ldo.hpp" #include "lgc.hpp" #include "lmem.hpp" #include "lobject.hpp" #include "lstate.hpp" #include "lstring.hpp" #include "ltable.hpp" #include "lvm.hpp" /* ** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is ** the largest integer such that MAXASIZE fits in an unsigned int. */ #define MAXABITS cast_int(sizeof(int) * CHAR_BIT - 1) #define MAXASIZE (1u << MAXABITS) /* ** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest ** integer such that 2^MAXHBITS fits in a signed int. (Note that the ** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still ** fits comfortably in an unsigned int.) */ #define MAXHBITS (MAXABITS - 1) #define hashpow2(t,n) (gnode(t, lmod((n), sizenode(t)))) #define hashstr(t,str) hashpow2(t, (str)->hash) #define hashboolean(t,p) hashpow2(t, p) #define hashint(t,i) hashpow2(t, i) /* ** for some types, it is better to avoid modulus by power of 2, as ** they tend to have many 2 factors. */ #define hashmod(t,n) (gnode(t, ((n) % ((sizenode(t)-1)|1)))) #define hashpointer(t,p) hashmod(t, point2uint(p)) #define dummynode (&dummynode_) static const Node dummynode_ = { {NILCONSTANT}, /* value */ {{NILCONSTANT, 0}} /* key */ }; /* ** Hash for floating-point numbers. ** The main computation should be just ** n = frexp(n, &i); return (n * INT_MAX) + i ** but there are some numerical subtleties. ** In a two-complement representation, INT_MAX does not has an exact ** representation as a float, but INT_MIN does; because the absolute ** value of 'frexp' is smaller than 1 (unless 'n' is inf/NaN), the ** absolute value of the product 'frexp * -INT_MIN' is smaller or equal ** to INT_MAX. Next, the use of 'unsigned int' avoids overflows when ** adding 'i'; the use of '~u' (instead of '-u') avoids problems with ** INT_MIN. */ #if !defined(l_hashfloat) static int l_hashfloat (lua_Number n) { int i; lua_Integer ni; n = l_mathop(frexp)(n, &i) * -cast_num(INT_MIN); if (!lua_numbertointeger(n, &ni)) { /* is 'n' inf/-inf/NaN? */ lua_assert(luai_numisnan(n) || l_mathop(fabs)(n) == cast_num(HUGE_VAL)); return 0; } else { /* normal case */ unsigned int u = cast(unsigned int, i) + cast(unsigned int, ni); return cast_int(u <= cast(unsigned int, INT_MAX) ? u : ~u); } } #endif /* ** returns the 'main' position of an element in a table (that is, the index ** of its hash value) */ static Node *mainposition (const Table *t, const TValue *key) { switch (ttype(key)) { case LUA_TNUMINT: return hashint(t, ivalue(key)); case LUA_TNUMFLT: return hashmod(t, l_hashfloat(fltvalue(key))); case LUA_TSHRSTR: return hashstr(t, tsvalue(key)); case LUA_TLNGSTR: return hashpow2(t, luaS_hashlongstr(tsvalue(key))); case LUA_TBOOLEAN: return hashboolean(t, bvalue(key)); case LUA_TLIGHTUSERDATA: return hashpointer(t, pvalue(key)); case LUA_TLCF: return hashpointer(t, fvalue(key)); default: lua_assert(!ttisdeadkey(key)); return hashpointer(t, gcvalue(key)); } } /* ** returns the index for 'key' if 'key' is an appropriate key to live in ** the array part of the table, 0 otherwise. */ static unsigned int arrayindex (const TValue *key) { if (ttisinteger(key)) { lua_Integer k = ivalue(key); if (0 < k && (lua_Unsigned)k <= MAXASIZE) return cast(unsigned int, k); /* 'key' is an appropriate array index */ } return 0; /* 'key' did not match some condition */ } /* ** returns the index of a 'key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning of a traversal is signaled by 0. */ static unsigned int findindex (lua_State *L, Table *t, StkId key) { unsigned int i; if (ttisnil(key)) return 0; /* first iteration */ i = arrayindex(key); if (i != 0 && i <= t->sizearray) /* is 'key' inside array part? */ return i; /* yes; that's the index */ else { int nx; Node *n = mainposition(t, key); for (;;) { /* check whether 'key' is somewhere in the chain */ /* key may be dead already, but it is ok to use it in 'next' */ if (luaV_rawequalobj(gkey(n), key) || (ttisdeadkey(gkey(n)) && iscollectable(key) && deadvalue(gkey(n)) == gcvalue(key))) { i = cast_int(n - gnode(t, 0)); /* key index in hash table */ /* hash elements are numbered after array ones */ return (i + 1) + t->sizearray; } nx = gnext(n); if (nx == 0) luaG_runerror(L, "invalid key to 'next'"); /* key not found */ else n += nx; } } } int luaH_next (lua_State *L, Table *t, StkId key) { unsigned int i = findindex(L, t, key); /* find original element */ for (; i < t->sizearray; i++) { /* try first array part */ if (!ttisnil(&t->array[i])) { /* a non-nil value? */ setivalue(key, i + 1); setobj2s(L, key+1, &t->array[i]); return 1; } } for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) { /* hash part */ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ setobj2s(L, key, gkey(gnode(t, i))); setobj2s(L, key+1, gval(gnode(t, i))); return 1; } } return 0; /* no more elements */ } /* ** {============================================================= ** Rehash ** ============================================================== */ /* ** Compute the optimal size for the array part of table 't'. 'nums' is a ** "count array" where 'nums[i]' is the number of integers in the table ** between 2^(i - 1) + 1 and 2^i. 'pna' enters with the total number of ** integer keys in the table and leaves with the number of keys that ** will go to the array part; return the optimal size. */ static unsigned int computesizes (unsigned int nums[], unsigned int *pna) { int i; unsigned int twotoi; /* 2^i (candidate for optimal size) */ unsigned int a = 0; /* number of elements smaller than 2^i */ unsigned int na = 0; /* number of elements to go to array part */ unsigned int optimal = 0; /* optimal size for array part */ /* loop while keys can fill more than half of total size */ for (i = 0, twotoi = 1; *pna > twotoi / 2; i++, twotoi *= 2) { if (nums[i] > 0) { a += nums[i]; if (a > twotoi/2) { /* more than half elements present? */ optimal = twotoi; /* optimal size (till now) */ na = a; /* all elements up to 'optimal' will go to array part */ } } } lua_assert((optimal == 0 || optimal / 2 < na) && na <= optimal); *pna = na; return optimal; } static int countint (const TValue *key, unsigned int *nums) { unsigned int k = arrayindex(key); if (k != 0) { /* is 'key' an appropriate array index? */ nums[luaO_ceillog2(k)]++; /* count as such */ return 1; } else return 0; } /* ** Count keys in array part of table 't': Fill 'nums[i]' with ** number of keys that will go into corresponding slice and return ** total number of non-nil keys. */ static unsigned int numusearray (const Table *t, unsigned int *nums) { int lg; unsigned int ttlg; /* 2^lg */ unsigned int ause = 0; /* summation of 'nums' */ unsigned int i = 1; /* count to traverse all array keys */ /* traverse each slice */ for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) { unsigned int lc = 0; /* counter */ unsigned int lim = ttlg; if (lim > t->sizearray) { lim = t->sizearray; /* adjust upper limit */ if (i > lim) break; /* no more elements to count */ } /* count elements in range (2^(lg - 1), 2^lg] */ for (; i <= lim; i++) { if (!ttisnil(&t->array[i-1])) lc++; } nums[lg] += lc; ause += lc; } return ause; } static int numusehash (const Table *t, unsigned int *nums, unsigned int *pna) { int totaluse = 0; /* total number of elements */ int ause = 0; /* elements added to 'nums' (can go to array part) */ int i = sizenode(t); while (i--) { Node *n = &t->node[i]; if (!ttisnil(gval(n))) { ause += countint(gkey(n), nums); totaluse++; } } *pna += ause; return totaluse; } static void setarrayvector (lua_State *L, Table *t, unsigned int size) { unsigned int i; luaM_reallocvector(L, t->array, t->sizearray, size, TValue); for (i=t->sizearray; i<size; i++) setnilvalue(&t->array[i]); t->sizearray = size; } static void setnodevector (lua_State *L, Table *t, unsigned int size) { if (size == 0) { /* no elements to hash part? */ t->node = cast(Node *, dummynode); /* use common 'dummynode' */ t->lsizenode = 0; t->lastfree = nullptr; /* signal that it is using dummy node */ } else { int i; int lsize = luaO_ceillog2(size); if (lsize > MAXHBITS) luaG_runerror(L, "table overflow"); size = twoto(lsize); t->node = luaM_newvector(L, size, Node); for (i = 0; i < (int)size; i++) { Node *n = gnode(t, i); gnext(n) = 0; setnilvalue(wgkey(n)); setnilvalue(gval(n)); } t->lsizenode = cast_byte(lsize); t->lastfree = gnode(t, size); /* all positions are free */ } } void luaH_resize (lua_State *L, Table *t, unsigned int nasize, unsigned int nhsize) { unsigned int i; int j; unsigned int oldasize = t->sizearray; int oldhsize = allocsizenode(t); Node *nold = t->node; /* save old hash ... */ if (nasize > oldasize) /* array part must grow? */ setarrayvector(L, t, nasize); /* create new hash part with appropriate size */ setnodevector(L, t, nhsize); if (nasize < oldasize) { /* array part must shrink? */ t->sizearray = nasize; /* re-insert elements from vanishing slice */ for (i=nasize; i<oldasize; i++) { if (!ttisnil(&t->array[i])) luaH_setint(L, t, i + 1, &t->array[i]); } /* shrink array */ luaM_reallocvector(L, t->array, oldasize, nasize, TValue); } /* re-insert elements from hash part */ for (j = oldhsize - 1; j >= 0; j--) { Node *old = nold + j; if (!ttisnil(gval(old))) { /* doesn't need barrier/invalidate cache, as entry was already present in the table */ setobjt2t(L, luaH_set(L, t, gkey(old)), gval(old)); } } if (oldhsize > 0) /* not the dummy node? */ luaM_freearray(L, nold, cast(size_t, oldhsize)); /* free old hash */ } void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) { int nsize = allocsizenode(t); luaH_resize(L, t, nasize, nsize); } /* ** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i */ static void rehash (lua_State *L, Table *t, const TValue *ek) { unsigned int asize; /* optimal size for array part */ unsigned int na; /* number of keys in the array part */ unsigned int nums[MAXABITS + 1]; int i; int totaluse; for (i = 0; i <= MAXABITS; i++) nums[i] = 0; /* reset counts */ na = numusearray(t, nums); /* count keys in array part */ totaluse = na; /* all those keys are integer keys */ totaluse += numusehash(t, nums, &na); /* count keys in hash part */ /* count extra key */ na += countint(ek, nums); totaluse++; /* compute new size for array part */ asize = computesizes(nums, &na); /* resize the table to new computed sizes */ luaH_resize(L, t, asize, totaluse - na); } /* ** }============================================================= */ Table *luaH_new (lua_State *L) { GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table)); Table *t = gco2t(o); t->metatable = nullptr; t->flags = cast_byte(~0); t->array = nullptr; t->sizearray = 0; setnodevector(L, t, 0); return t; } void luaH_free (lua_State *L, Table *t) { if (!isdummy(t)) luaM_freearray(L, t->node, cast(size_t, sizenode(t))); luaM_freearray(L, t->array, t->sizearray); luaM_free(L, t); } static Node *getfreepos (Table *t) { if (!isdummy(t)) { while (t->lastfree > t->node) { t->lastfree--; if (ttisnil(gkey(t->lastfree))) return t->lastfree; } } return nullptr; /* could not find a free place */ } /* ** inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main ** position or not: if it is not, move colliding node to an empty place and ** put new key in its main position; otherwise (colliding node is in its main ** position), new key goes to an empty position. */ TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) { Node *mp; TValue aux; if (ttisnil(key)) luaG_runerror(L, "table index is nil"); else if (ttisfloat(key)) { lua_Integer k; if (luaV_tointeger(key, &k, 0)) { /* does index fit in an integer? */ setivalue(&aux, k); key = &aux; /* insert it as an integer */ } else if (luai_numisnan(fltvalue(key))) luaG_runerror(L, "table index is NaN"); } mp = mainposition(t, key); if (!ttisnil(gval(mp)) || isdummy(t)) { /* main position is taken? */ Node *othern; Node *f = getfreepos(t); /* get a free place */ if (f == nullptr) { /* cannot find a free place? */ rehash(L, t, key); /* grow table */ /* whatever called 'newkey' takes care of TM cache */ return luaH_set(L, t, key); /* insert key into grown table */ } lua_assert(!isdummy(t)); othern = mainposition(t, gkey(mp)); if (othern != mp) { /* is colliding node out of its main position? */ /* yes; move colliding node into free position */ while (othern + gnext(othern) != mp) /* find previous */ othern += gnext(othern); gnext(othern) = cast_int(f - othern); /* rechain to point to 'f' */ *f = *mp; /* copy colliding node into free pos. (mp->next also goes) */ if (gnext(mp) != 0) { gnext(f) += cast_int(mp - f); /* correct 'next' */ gnext(mp) = 0; /* now 'mp' is free */ } setnilvalue(gval(mp)); } else { /* colliding node is in its own main position */ /* new node will go into free position */ if (gnext(mp) != 0) gnext(f) = cast_int((mp + gnext(mp)) - f); /* chain new position */ else lua_assert(gnext(f) == 0); gnext(mp) = cast_int(f - mp); mp = f; } } setnodekey(L, &mp->i_key, key); luaC_barrierback(L, t, key); lua_assert(ttisnil(gval(mp))); return gval(mp); } /* ** search function for integers */ const TValue *luaH_getint (Table *t, lua_Integer key) { /* (1 <= key && key <= t->sizearray) */ if (l_castS2U(key) - 1 < t->sizearray) return &t->array[key - 1]; else { Node *n = hashint(t, key); for (;;) { /* check whether 'key' is somewhere in the chain */ if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) break; n += nx; } } return luaO_nilobject; } } /* ** search function for short strings */ const TValue *luaH_getshortstr (Table *t, TString *key) { Node *n = hashstr(t, key); lua_assert(key->tt == LUA_TSHRSTR); for (;;) { /* check whether 'key' is somewhere in the chain */ const TValue *k = gkey(n); if (ttisshrstring(k) && eqshrstr(tsvalue(k), key)) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) return luaO_nilobject; /* not found */ n += nx; } } } /* ** "Generic" get version. (Not that generic: not valid for integers, ** which may be in array part, nor for floats with integral values.) */ static const TValue *getgeneric (Table *t, const TValue *key) { Node *n = mainposition(t, key); for (;;) { /* check whether 'key' is somewhere in the chain */ if (luaV_rawequalobj(gkey(n), key)) return gval(n); /* that's it */ else { int nx = gnext(n); if (nx == 0) return luaO_nilobject; /* not found */ n += nx; } } } const TValue *luaH_getstr (Table *t, TString *key) { if (key->tt == LUA_TSHRSTR) return luaH_getshortstr(t, key); else { /* for long strings, use generic case */ TValue ko; setsvalue(cast(lua_State *, nullptr), &ko, key); return getgeneric(t, &ko); } } /* ** main search function */ const TValue *luaH_get (Table *t, const TValue *key) { switch (ttype(key)) { case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key)); case LUA_TNUMINT: return luaH_getint(t, ivalue(key)); case LUA_TNIL: return luaO_nilobject; case LUA_TNUMFLT: { lua_Integer k; if (luaV_tointeger(key, &k, 0)) /* index is int? */ return luaH_getint(t, k); /* use specialized version */ /* else... */ } /* FALLTHROUGH */ default: return getgeneric(t, key); } } /* ** beware: when using this function you probably need to check a GC ** barrier and invalidate the TM cache. */ TValue *luaH_set (lua_State *L, Table *t, const TValue *key) { const TValue *p = luaH_get(t, key); if (p != luaO_nilobject) return cast(TValue *, p); else return luaH_newkey(L, t, key); } void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) { const TValue *p = luaH_getint(t, key); TValue *cell; if (p != luaO_nilobject) cell = cast(TValue *, p); else { TValue k; setivalue(&k, key); cell = luaH_newkey(L, t, &k); } setobj2t(L, cell, value); } static int unbound_search (Table *t, unsigned int j) { unsigned int i = j; /* i is zero or a present index */ j++; /* find 'i' and 'j' such that i is present and j is not */ while (!ttisnil(luaH_getint(t, j))) { i = j; if (j > cast(unsigned int, MAX_INT)/2) { /* overflow? */ /* table was built with bad purposes: resort to linear search */ i = 1; while (!ttisnil(luaH_getint(t, i))) i++; return i - 1; } j *= 2; } /* now do a binary search between them */ while (j - i > 1) { unsigned int m = (i+j)/2; if (ttisnil(luaH_getint(t, m))) j = m; else i = m; } return i; } /* ** Try to find a boundary in table 't'. A 'boundary' is an integer index ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). */ int luaH_getn (Table *t) { unsigned int j = t->sizearray; if (j > 0 && ttisnil(&t->array[j - 1])) { /* there is a boundary in the array part: (binary) search for it */ unsigned int i = 0; while (j - i > 1) { unsigned int m = (i+j)/2; if (ttisnil(&t->array[m - 1])) j = m; else i = m; } return i; } /* else must find a boundary in hash part */ else if (isdummy(t)) /* hash part is empty? */ return j; /* that is easy... */ else return unbound_search(t, j); } #if defined(LUA_DEBUG) Node *luaH_mainposition (const Table *t, const TValue *key) { return mainposition(t, key); } int luaH_isdummy (const Table *t) { return isdummy(t); } #endif
[ "nanguazhude@vip.qq.com" ]
nanguazhude@vip.qq.com
815724a6ec6d0192b60275de509ba4211dc5f71a
e1bafb9c94db3a6cfd86ce4b3a641e79583220b3
/leetcode-clion/leetcode-problems/cpp/882.reachable-nodes-in-subdivided-graph.cpp
270c9271908a5220fd5665b0d1033a39286051ad
[]
no_license
lightjameslyy/lt-cpp
055b0245ba9cc4608db6a0d08dc081d1c2766ba2
525c3f0fbeb4b112361a6650bf3ef445fdb61e2c
refs/heads/master
2021-07-09T08:32:24.405308
2020-06-08T08:45:10
2020-06-08T08:45:10
128,907,003
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
cpp
/* * @lc app=leetcode id=882 lang=cpp * * [882] Reachable Nodes In Subdivided Graph * * https://leetcode.com/problems/reachable-nodes-in-subdivided-graph/description/ * * algorithms * Hard (39.00%) * Total Accepted: 4.1K * Total Submissions: 10.5K * Testcase Example: '[[0,1,10],[0,2,1],[1,2,2]]\n6\n3' * * Starting with an undirected graph (the "original graph") with nodes from 0 * to N-1, subdivisions are made to some of the edges. * * The graph is given as follows: edges[k] is a list of integer pairs (i, j, n) * such that (i, j) is an edge of the original graph, * * and n is the total number of new nodes on that edge.  * * Then, the edge (i, j) is deleted from the original graph, n new nodes (x_1, * x_2, ..., x_n) are added to the original graph, * * and n+1 new edges (i, x_1), (x_1, x_2), (x_2, x_3), ..., (x_{n-1}, x_n), * (x_n, j) are added to the original graph. * * Now, you start at node 0 from the original graph, and in each move, you * travel along one edge.  * * Return how many nodes you can reach in at most M moves. * * * * Example 1: * * * Input: edges = [[0,1,10],[0,2,1],[1,2,2]], M = 6, N = 3 * Output: 13 * Explanation: * The nodes that are reachable in the final graph after M = 6 moves are * indicated below. * * * * * Example 2: * * * Input: edges = [[0,1,4],[1,2,6],[0,2,8],[1,3,1]], M = 10, N = 4 * Output: 23 * * * * * Note: * * * 0 <= edges.length <= 10000 * 0 <= edges[i][0] < edges[i][1] < N * There does not exist any i != j for which edges[i][0] == edges[j][0] and * edges[i][1] == edges[j][1]. * The original graph has no parallel edges. * 0 <= edges[i][2] <= 10000 * 0 <= M <= 10^9 * 1 <= N <= 3000 * A reachable node is a node that can be travelled to using at most M moves * starting from node 0. * * * * * * */ class Solution { public: int reachableNodes(vector<vector<int>>& edges, int M, int N) { } };
[ "lightjameslyy@gmail.com" ]
lightjameslyy@gmail.com
9fd3824f993a8c59229df292edeca0139ff0f940
8c66d1fe6ecde6f66f3eaf5b5db220da3930c7ab
/codeforces/1471/B.cpp
ca5619b0ee3128143c041a91df71540a02c834f4
[]
no_license
Hasanul-Bari/codeforces
0af70eda9dee3e7ddefc63560538e986dda0c141
1a074980ccdc2cd97a0a6a85f1f89da0343407b3
refs/heads/master
2023-06-03T07:52:28.584598
2021-04-12T14:39:00
2021-06-17T18:08:03
334,670,088
2
0
null
null
null
null
UTF-8
C++
false
false
1,409
cpp
#include<bits/stdc++.h> #define faster ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ll long long #define ull unsigned long long #define pb push_back const double PI = acos(-1.0); using namespace std; class info { public: ll v,c; }; int main() { faster ll t,n,x; cin>>t; while(t--) { cin>>n>>x; queue<info> q; int a[n]; for(int i=0; i<n; i++) { cin>>a[i]; } ll s=0; bool hp=true; for(int i=0; i<n; i++) { if(a[i]%x==0 && hp==true) { info d; d.v=a[i]/x; d.c=x; q.push(d); } else hp=false; s=s+a[i]; } while(!q.empty() && hp==true) { info d=q.front(); q.pop(); s=s+(d.v*d.c); if(d.v%x==0) { d.v=d.v/x; d.c=d.c*x; q.push(d); } else { break; } } while(!q.empty()) { info d=q.front(); q.pop(); s=s+(d.v*d.c); } cout<<s<<endl; } return 0; }
[ "hasanul.bari.hasan96@gmail.com" ]
hasanul.bari.hasan96@gmail.com
5f79d89832164222ff2c556e5552e1720eaf51e8
468ea57135c20749ef682c701ccaf3b193139c41
/source/fwe_evds_object_csection.cpp
bef90bda75ae62f58cbf0d131cd89286c2cf899a
[ "BSD-3-Clause" ]
permissive
HunterNL/FWE
27c3464b8738744c67bbe6b9982d51b7d21d96ff
cbb752fcc910ee1eaa09b71ea696408a5d75c495
refs/heads/master
2020-12-25T10:42:13.124447
2013-10-12T13:56:32
2013-10-12T13:56:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,791
cpp
//////////////////////////////////////////////////////////////////////////////// /// @file //////////////////////////////////////////////////////////////////////////////// /// Copyright (C) 2012-2013, Black Phoenix /// 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 the author nor the names of the 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 COPYRIGHT HOLDERS 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 <QStackedWidget> #include <QVBoxLayout> #include <QTabBar> #include <math.h> #include "fwe_evds.h" #include "fwe_evds_object.h" #include "fwe_evds_object_csection.h" #include "fwe_prop_sheet.h" using namespace EVDS; //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// CrossSectionEditor::CrossSectionEditor(Object* in_object) { object = in_object; editor = object->getEVDSEditor(); //Create cross-section editor layout = new QVBoxLayout; setLayout(layout); layout->setSpacing(0); layout->setMargin(0); //Create section selection bar tab = new QTabBar(this); tab->setTabsClosable(true); tab->setMovable(true); //tab->setShape(QTabBar::RoundedNorth); layout->addWidget(tab); //Setup tab signals connect(tab,SIGNAL(currentChanged(int)),this,SLOT(sectionSelected(int))); connect(tab,SIGNAL(tabCloseRequested(int)),this,SLOT(sectionDeleted(int))); connect(tab,SIGNAL(tabMoved(int,int)),this,SLOT(sectionMoved(int,int))); //Create section interface sections = new QStackedWidget(this); layout->addWidget(sections); //Initialize cross-section information SIMC_LIST_ENTRY* entry; SIMC_LIST* csections_list; EVDS_VARIABLE* csection; geometry = 0; if (EVDS_Object_GetVariable(object->getEVDSObject(),"geometry.cross_sections",&geometry) != EVDS_OK) { EVDS_Object_AddVariable(object->getEVDSObject(),"geometry.cross_sections",EVDS_VARIABLE_TYPE_NESTED,&geometry); } EVDS_Variable_GetList(geometry,&csections_list); //Traverse list for initial cross-section information int index = 0; entry = SIMC_List_GetFirst(csections_list); while (entry) { csection = (EVDS_VARIABLE*)SIMC_List_GetData(csections_list,entry); //Create widget CrossSection* csection_widget = new CrossSection(csection,this); csectionWidgetByIndex[index] = csection_widget; indexByCSectionWidget[csection_widget] = index; sections->addWidget(csection_widget); tab->addTab(tr("%1").arg(index+1)); index++; entry = SIMC_List_GetNext(csections_list,entry); } tab->addTab(""); //object->update(true); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// CrossSectionEditor::~CrossSectionEditor() { } int CrossSectionEditor::getSelectedIndex() { return sections->currentIndex(); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSectionEditor::sectionSelected(int index) { if (index == sections->count()) { //Create new section EVDS_VARIABLE* csection; EVDS_VARIABLE* type; EVDS_Variable_AddNested(geometry,"section",EVDS_VARIABLE_TYPE_NESTED,&csection); //FIXME crash here EVDS_Variable_AddAttribute(csection,"type",EVDS_VARIABLE_TYPE_STRING,&type); EVDS_Variable_SetString(type,"ellipse",8); EVDS_Variable_AddAttribute(csection,"offset",EVDS_VARIABLE_TYPE_FLOAT,&type); EVDS_Variable_SetReal(type,0.0); //Create widget CrossSection* csection_widget = new CrossSection(csection,this); csectionWidgetByIndex[index] = csection_widget; indexByCSectionWidget[csection_widget] = index; sections->addWidget(csection_widget); tab->setTabText(index,tr("%1").arg(index+1)); tab->addTab(""); //Update geometry, unless this is the first cross-section to be created if (index != 0) { object->update(true); object->getEVDSEditor()->setModified(); } } sections->setCurrentIndex(index); object->update(false); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSectionEditor::sectionDeleted(int index) { if (index == sections->count()) return; if (sections->count() == 1) return; CrossSection* csection_widget = csectionWidgetByIndex[index]; csectionWidgetByIndex.remove(index); for (int i = index; i < sections->count()-1; i++) { csectionWidgetByIndex[i] = csectionWidgetByIndex[i+1]; indexByCSectionWidget[csectionWidgetByIndex[i]] = i; tab->setTabText(i,tr("%1").arg(i+1)); } EVDS_VARIABLE* csection = csection_widget->getEVDSCrossSection(); EVDS_Variable_Destroy(csection); tab->removeTab(index); sections->removeWidget(sections->widget(index)); if ((index == sections->count()) && (index > 1)) { tab->setCurrentIndex(index-1); } //Update geometry object->update(true); object->getEVDSEditor()->setModified(); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSectionEditor::sectionMoved(int from, int to) { if (to == sections->count()) sectionSelected(to); if (from == sections->count()) sectionSelected(from); CrossSection* csection_widget_from = csectionWidgetByIndex[from]; CrossSection* csection_widget_to = csectionWidgetByIndex[to]; csectionWidgetByIndex[to] = csection_widget_from; csectionWidgetByIndex[from] = csection_widget_to; indexByCSectionWidget[csection_widget_from] = to; indexByCSectionWidget[csection_widget_to] = from; EVDS_VARIABLE* csection_to = csection_widget_to->getEVDSCrossSection(); EVDS_VARIABLE* csection_from = csection_widget_from->getEVDSCrossSection(); if (from > to) { sections->removeWidget(csection_widget_from); sections->insertWidget(to,csection_widget_from); EVDS_Variable_MoveInList(csection_to,csection_from); } else { sections->removeWidget(csection_widget_from); sections->insertWidget(to,csection_widget_from); EVDS_Variable_MoveInList(csection_from,csection_to); } tab->setTabText(from,tr("%1").arg(from+1)); tab->setTabText(to,tr("%1").arg(to+1)); //Update geometry object->update(true); object->getEVDSEditor()->setModified(); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// CrossSection::CrossSection(EVDS_VARIABLE* in_cross_section, CrossSectionEditor* in_editor) { cross_section = in_cross_section; editor = in_editor; //Create layout layout = new QVBoxLayout; layout->setMargin(0); setLayout(layout); //Create property sheet createPropertySheet(); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// CrossSection::~CrossSection() { } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSection::createPropertySheet() { property_sheet = new FWEPropertySheet(this); layout->addWidget(property_sheet); //Connect up signals and slots connect(property_sheet, SIGNAL(doubleChanged(const QString&, double)), this, SLOT(doubleChanged(const QString&, double))); connect(property_sheet, SIGNAL(stringChanged(const QString&, const QString&)), this, SLOT(stringChanged(const QString&, const QString&))); connect(property_sheet, SIGNAL(propertyUpdate(const QString&)), this, SLOT(propertyUpdate(const QString&))); //Create default set of properties property_sheet->setProperties(editor->getEVDSEditor()->csectionVariables[""]); property_sheet->setProperties(editor->getEVDSEditor()->csectionVariables[getType()]); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// QString CrossSection::getType() { EVDS_VARIABLE* type_var = 0; char type[257] = { 0 }; if (EVDS_Variable_GetAttribute(cross_section,"type",&type_var) == EVDS_OK) { EVDS_Variable_GetString(type_var,type,256,0); return QString(type); } else { return ""; } } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSection::setVariable(const QString &name, double value) { if (name[0] == '@') { int specialIndex = name.right(1).toInt(); EVDS_VARIABLE* pv = 0; EVDS_VARIABLE* mv = 0; //if (value == 0.0) return; switch (specialIndex) { case 1: { EVDS_Variable_AddAttribute(cross_section,"tangent.offset.pos",EVDS_VARIABLE_TYPE_FLOAT,&pv); EVDS_Variable_AddAttribute(cross_section,"tangent.offset.neg",EVDS_VARIABLE_TYPE_FLOAT,&mv); EVDS_Variable_SetReal(pv,value); EVDS_Variable_SetReal(mv,value); property_sheet->updateProperty("tangent.offset.pos"); property_sheet->updateProperty("tangent.offset.neg"); } break; case 2: { EVDS_Variable_AddAttribute(cross_section,"tangent.radial.pos",EVDS_VARIABLE_TYPE_FLOAT,&pv); EVDS_Variable_AddAttribute(cross_section,"tangent.radial.neg",EVDS_VARIABLE_TYPE_FLOAT,&mv); EVDS_Variable_SetReal(pv,value); EVDS_Variable_SetReal(mv,value); property_sheet->updateProperty("tangent.radial.pos"); property_sheet->updateProperty("tangent.radial.neg"); } break; } } else { //Ordinary logic EVDS_VARIABLE* v; EVDS_REAL prev_value; if (EVDS_Variable_AddAttribute(cross_section,name.toAscii().data(),EVDS_VARIABLE_TYPE_FLOAT,&v) == EVDS_OK) { EVDS_Variable_GetReal(v,&prev_value); EVDS_Variable_SetReal(v,value); } //Special logic if (name == "tangent.offset.pos") property_sheet->updateProperty("\x01"); if (name == "tangent.offset.neg") property_sheet->updateProperty("\x01"); if (name == "tangent.radial.pos") property_sheet->updateProperty("\x02"); if (name == "tangent.radial.neg") property_sheet->updateProperty("\x02"); if (name == "rx") { EVDS_REAL ry; if (EVDS_Variable_AddAttribute(cross_section,"ry",EVDS_VARIABLE_TYPE_FLOAT,&v) == EVDS_OK) { EVDS_Variable_GetReal(v,&ry); if (prev_value == ry) EVDS_Variable_SetReal(v,value); property_sheet->updateProperty("ry"); } } } editor->getObject()->update(true); editor->getObject()->getEVDSEditor()->setModified(); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSection::setVariable(const QString &name, const QString &value) { if (name[0] == '@') { int specialIndex = name.right(1).toInt(); if (specialIndex == 3) { EVDS_VARIABLE* v; //Change type if (EVDS_Variable_AddAttribute(cross_section,"type",EVDS_VARIABLE_TYPE_STRING,&v) == EVDS_OK) { EVDS_Variable_SetString(v,value.toAscii().data(),strlen(value.toAscii().data())+1); } //Update property sheet if (property_sheet) { //QWidget* prev_sheet = property_sheet; //prev_sheet->deleteLater(); property_sheet->deleteLater(); createPropertySheet(); //editor->propertySheetUpdated(prev_sheet,property_sheet); } editor->getObject()->update(true); return; } } else { //FIXME } editor->getObject()->update(true); editor->getObject()->getEVDSEditor()->setModified(); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// double CrossSection::getVariable(const QString &name) { if (name[0] == '@') { int specialIndex = name.right(1).toInt(); EVDS_VARIABLE* pv = 0; EVDS_VARIABLE* mv = 0; EVDS_REAL p = 0.0; EVDS_REAL m = 0.0; switch (specialIndex) { case 1: { EVDS_Variable_GetAttribute(cross_section,"tangent_p_offset",&pv); EVDS_Variable_GetAttribute(cross_section,"tangent_m_offset",&mv); } break; case 2: { EVDS_Variable_GetAttribute(cross_section,"tangent_p_radial",&pv); EVDS_Variable_GetAttribute(cross_section,"tangent_m_radial",&mv); } break; } EVDS_Variable_GetReal(pv,&p); EVDS_Variable_GetReal(mv,&m); if (fabs(p-m) < 1e-9) { return p; } else { return 0.0; } } else { EVDS_VARIABLE* variable; int error_code = EVDS_Variable_GetAttribute(cross_section,name.toAscii().data(),&variable); if (error_code == EVDS_OK) { //Special hack for rx/ry if ((error_code == EVDS_ERROR_NOT_FOUND) && (name == "ry")) EVDS_Variable_AddAttribute(cross_section,"rx",EVDS_VARIABLE_TYPE_FLOAT,&variable); //Special hack for tangent_p_offset/tangent_m_offset //if ((error_code == EVDS_ERROR_NOT_FOUND) && (name == "tangent_m_offset")) //EVDS_Variable_AddAttribute(cross_section,"tangent_p_offset",EVDS_VARIABLE_TYPE_FLOAT,&variable); //Special hack for tangent_p_radial/tangent_m_radial //if ((error_code == EVDS_ERROR_NOT_FOUND) && (name == "tangent_m_radial")) //EVDS_Variable_AddAttribute(cross_section,"tangent_p_radial",EVDS_VARIABLE_TYPE_FLOAT,&variable); EVDS_REAL value; EVDS_Variable_GetReal(variable,&value); return value; } } return 0.0; } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSection::doubleChanged(const QString& name, double value) { setVariable(name,value); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSection::stringChanged(const QString& name, const QString& value) { setVariable(name,value); } //////////////////////////////////////////////////////////////////////////////// /// @brief //////////////////////////////////////////////////////////////////////////////// void CrossSection::propertyUpdate(const QString& name) { if (name == "@3") { //Special: type property_sheet->setString(name,getType()); } else { //Other variable property_sheet->setDouble(name,getVariable(name)); } }
[ "phoenix@uol.ua" ]
phoenix@uol.ua
59932587e358d76757a3ff75aad4987a7850e7c0
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/9f/f67de6aef1d54f/main.cpp
ac3afeec880e233f3512c6ca91087e46629c2f19
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,112
cpp
#include <iostream> #include <cstdint> struct MyStruct { const uint16_t index; MyStruct(uint16_t in) : index(in) { } } ; static const MyStruct array[] = { MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), MyStruct(__COUNTER__), } ; int main() { for( size_t i = 0; i < sizeof( array )/sizeof(MyStruct); ++i ) { std::cout << i << ":" << array[i].index << ":" << std::boolalpha << ( i == array[i].index ? true : false ) << std::endl ; } }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
e346bdfedf2b7fa43f91872ab857e1396b492e51
a9306217d01b27d76adfd200513fbf4f86070ad4
/include/CppAwait/impl/Compatibility.h
272c219f2617bb568795f0415e5fc4fab4728ef5
[ "Apache-2.0" ]
permissive
alarouche/CppAwait
ecaa00d31cb828cd3e67de66cb9b8857911d0a0b
af40711c233cbadcb4d40d571a2fb24dab07753b
refs/heads/master
2021-01-16T21:36:34.142034
2015-07-09T07:46:12
2015-07-09T07:47:56
42,529,493
1
0
null
2015-09-15T15:48:27
2015-09-15T15:48:25
C++
UTF-8
C++
false
false
3,079
h
/* * Copyright 2012-2015 Valentin Milea * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "../Config.h" #include "Assert.h" #include <exception> #include <memory> namespace ut { // MSVC10 workaround -- no std::make_exception_ptr() // template <typename T> std::exception_ptr make_exception_ptr(const T& e) { ut_assert_(!std::uncaught_exception() && "disallowed while an exception is propagating"); std::exception_ptr eptr; try { throw e; } catch(...) { // MSVC10+ issue - std::current_exception returns empty here if // another exception is currently propagating eptr = std::current_exception(); } return eptr; } // MSVC10 workaround -- no conversion from std::exception_ptr to bool // inline bool is(const std::exception_ptr& eptr) { return !(eptr == std::exception_ptr()); } // MSVC10 workaround -- no std::declval() // template <typename T> T&& declval(); // make_unique missing in C++ 11 // template<typename T> std::unique_ptr<T> make_unique() { return std::unique_ptr<T>(new T()); } template<typename T, typename Arg1> std::unique_ptr<T> make_unique(Arg1&& arg1) { return std::unique_ptr<T>(new T( std::forward<Arg1>(arg1))); } template<typename T, typename Arg1, typename Arg2> std::unique_ptr<T> make_unique(Arg1&& arg1, Arg2&& arg2) { return std::unique_ptr<T>(new T( std::forward<Arg1>(arg1), std::forward<Arg2>(arg2))); } template<typename T, typename Arg1, typename Arg2, typename Arg3> std::unique_ptr<T> make_unique(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3) { return std::unique_ptr<T>(new T( std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3))); } template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4> std::unique_ptr<T> make_unique(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4) { return std::unique_ptr<T>(new T( std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4))); } template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> std::unique_ptr<T> make_unique(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5) { return std::unique_ptr<T>(new T( std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5))); } // // misc // template<typename T> std::unique_ptr<T> asUniquePtr(T&& value) { return ut::make_unique<T>(std::move(value)); } }
[ "valentin.milea@gmail.com" ]
valentin.milea@gmail.com
0b06079676cf4f37013447beef4210ae767d1582
2d745800357af60f01885cebbdb2552505a2c73a
/src/walletdb.cpp
9e3a43f60fa2df9dcc9dd92b50d3512464ea9a0d
[ "MIT" ]
permissive
Ace-Of-Fades/HOST
ac469d4347bd04e02ffbcd933c68640c6f4c9dfd
e704fa8e5f1a3a0bd9eaea14bf39aa77bd01d430
refs/heads/master
2020-06-27T20:05:35.197796
2016-12-12T18:29:20
2016-12-12T18:29:20
76,279,404
1
0
null
null
null
null
UTF-8
C++
false
false
23,866
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin developers // Copyright (c) 2016 The HOST developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "walletdb.h" #include "wallet.h" #include <boost/version.hpp> #include <boost/filesystem.hpp> using namespace std; using namespace boost; static uint64_t nAccountingEntryNumber = 0; extern bool fWalletUnlockStakingOnly; // // CWalletDB // bool CWalletDB::WriteName(const string& strAddress, const string& strName) { nWalletDBUpdated++; return Write(make_pair(string("name"), strAddress), strName); } bool CWalletDB::EraseName(const string& strAddress) { // This should only be used for sending addresses, never for receiving addresses, // receiving addresses must always have an address book entry if they're not change return. nWalletDBUpdated++; return Erase(make_pair(string("name"), strAddress)); } bool CWalletDB::ReadAccount(const string& strAccount, CAccount& account) { account.SetNull(); return Read(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccount(const string& strAccount, const CAccount& account) { return Write(make_pair(string("acc"), strAccount), account); } bool CWalletDB::WriteAccountingEntry(const uint64_t nAccEntryNum, const CAccountingEntry& acentry) { return Write(boost::make_tuple(string("acentry"), acentry.strAccount, nAccEntryNum), acentry); } bool CWalletDB::WriteAccountingEntry(const CAccountingEntry& acentry) { return WriteAccountingEntry(++nAccountingEntryNumber, acentry); } int64_t CWalletDB::GetAccountCreditDebit(const string& strAccount) { list<CAccountingEntry> entries; ListAccountCreditDebit(strAccount, entries); int64_t nCreditDebit = 0; BOOST_FOREACH (const CAccountingEntry& entry, entries) nCreditDebit += entry.nCreditDebit; return nCreditDebit; } void CWalletDB::ListAccountCreditDebit(const string& strAccount, list<CAccountingEntry>& entries) { bool fAllAccounts = (strAccount == "*"); Dbc* pcursor = GetCursor(); if (!pcursor) throw runtime_error("CWalletDB::ListAccountCreditDebit() : cannot create DB cursor"); unsigned int fFlags = DB_SET_RANGE; while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); if (fFlags == DB_SET_RANGE) ssKey << boost::make_tuple(string("acentry"), (fAllAccounts? string("") : strAccount), uint64_t(0)); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue, fFlags); fFlags = DB_NEXT; if (ret == DB_NOTFOUND) break; else if (ret != 0) { pcursor->close(); throw runtime_error("CWalletDB::ListAccountCreditDebit() : error scanning DB"); } // Unserialize string strType; ssKey >> strType; if (strType != "acentry") break; CAccountingEntry acentry; ssKey >> acentry.strAccount; if (!fAllAccounts && acentry.strAccount != strAccount) break; ssValue >> acentry; ssKey >> acentry.nEntryNo; entries.push_back(acentry); } pcursor->close(); } DBErrors CWalletDB::ReorderTransactions(CWallet* pwallet) { LOCK(pwallet->cs_wallet); // Old wallets didn't have any defined order for transactions // Probably a bad idea to change the output of this // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap. typedef pair<CWalletTx*, CAccountingEntry*> TxPair; typedef multimap<int64_t, TxPair > TxItems; TxItems txByTime; for (map<uint256, CWalletTx>::iterator it = pwallet->mapWallet.begin(); it != pwallet->mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0))); } list<CAccountingEntry> acentries; ListAccountCreditDebit("", acentries); BOOST_FOREACH(CAccountingEntry& entry, acentries) { txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry))); } int64_t& nOrderPosNext = pwallet->nOrderPosNext; nOrderPosNext = 0; std::vector<int64_t> nOrderPosOffsets; for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it) { CWalletTx *const pwtx = (*it).second.first; CAccountingEntry *const pacentry = (*it).second.second; int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos; if (nOrderPos == -1) { nOrderPos = nOrderPosNext++; nOrderPosOffsets.push_back(nOrderPos); if (pacentry) // Have to write accounting regardless, since we don't keep it in memory if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } else { int64_t nOrderPosOff = 0; BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets) { if (nOrderPos >= nOffsetStart) ++nOrderPosOff; } nOrderPos += nOrderPosOff; nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1); if (!nOrderPosOff) continue; // Since we're changing the order, write it back if (pwtx) { if (!WriteTx(pwtx->GetHash(), *pwtx)) return DB_LOAD_FAIL; } else if (!WriteAccountingEntry(pacentry->nEntryNo, *pacentry)) return DB_LOAD_FAIL; } } return DB_LOAD_OK; } class CWalletScanState { public: unsigned int nKeys; unsigned int nCKeys; unsigned int nKeyMeta; bool fIsEncrypted; bool fAnyUnordered; int nFileVersion; vector<uint256> vWalletUpgrade; CWalletScanState() { nKeys = nCKeys = nKeyMeta = 0; fIsEncrypted = false; fAnyUnordered = false; nFileVersion = 0; } }; bool ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, CWalletScanState &wss, string& strType, string& strErr) { try { // Unserialize // Taking advantage of the fact that pair serialization // is just the two items serialized one after the other ssKey >> strType; if (strType == "name") { string strAddress; ssKey >> strAddress; ssValue >> pwallet->mapAddressBook[CBitcoinAddress(strAddress).Get()]; } else if (strType == "tx") { uint256 hash; ssKey >> hash; CWalletTx& wtx = pwallet->mapWallet[hash]; ssValue >> wtx; if (wtx.CheckTransaction() && (wtx.GetHash() == hash)) wtx.BindWallet(pwallet); else { pwallet->mapWallet.erase(hash); return false; } // Undo serialize changes in 31600 if (31404 <= wtx.fTimeReceivedIsTxTime && wtx.fTimeReceivedIsTxTime <= 31703) { if (!ssValue.empty()) { char fTmp; char fUnused; ssValue >> fTmp >> fUnused >> wtx.strFromAccount; strErr = strprintf("LoadWallet() upgrading tx ver=%d %d '%s' %s", wtx.fTimeReceivedIsTxTime, fTmp, wtx.strFromAccount.c_str(), hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = fTmp; } else { strErr = strprintf("LoadWallet() repairing tx ver=%d %s", wtx.fTimeReceivedIsTxTime, hash.ToString().c_str()); wtx.fTimeReceivedIsTxTime = 0; } wss.vWalletUpgrade.push_back(hash); } if (wtx.nOrderPos == -1) wss.fAnyUnordered = true; //// debug print //printf("LoadWallet %s\n", wtx.GetHash().ToString().c_str()); //printf(" %12"PRId64" %s %s %s\n", // wtx.vout[0].nValue, // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()).c_str(), // wtx.hashBlock.ToString().substr(0,20).c_str(), // wtx.mapValue["message"].c_str()); } else if (strType == "acentry") { string strAccount; ssKey >> strAccount; uint64_t nNumber; ssKey >> nNumber; if (nNumber > nAccountingEntryNumber) nAccountingEntryNumber = nNumber; if (!wss.fAnyUnordered) { CAccountingEntry acentry; ssValue >> acentry; if (acentry.nOrderPos == -1) wss.fAnyUnordered = true; } } else if (strType == "key" || strType == "wkey") { vector<unsigned char> vchPubKey; ssKey >> vchPubKey; CKey key; if (strType == "key") { wss.nKeys++; CPrivKey pkey; ssValue >> pkey; key.SetPubKey(vchPubKey); if (!key.SetPrivKey(pkey)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (key.GetPubKey() != vchPubKey) { strErr = "Error reading wallet database: CPrivKey pubkey inconsistency"; return false; } if (!key.IsValid()) { strErr = "Error reading wallet database: invalid CPrivKey"; return false; } } else { CWalletKey wkey; ssValue >> wkey; key.SetPubKey(vchPubKey); if (!key.SetPrivKey(wkey.vchPrivKey)) { strErr = "Error reading wallet database: CPrivKey corrupt"; return false; } if (key.GetPubKey() != vchPubKey) { strErr = "Error reading wallet database: CWalletKey pubkey inconsistency"; return false; } if (!key.IsValid()) { strErr = "Error reading wallet database: invalid CWalletKey"; return false; } } if (!pwallet->LoadKey(key)) { strErr = "Error reading wallet database: LoadKey failed"; return false; } } else if (strType == "mkey") { unsigned int nID; ssKey >> nID; CMasterKey kMasterKey; ssValue >> kMasterKey; if(pwallet->mapMasterKeys.count(nID) != 0) { strErr = strprintf("Error reading wallet database: duplicate CMasterKey id %u", nID); return false; } pwallet->mapMasterKeys[nID] = kMasterKey; if (pwallet->nMasterKeyMaxID < nID) pwallet->nMasterKeyMaxID = nID; } else if (strType == "ckey") { wss.nCKeys++; vector<unsigned char> vchPubKey; ssKey >> vchPubKey; vector<unsigned char> vchPrivKey; ssValue >> vchPrivKey; if (!pwallet->LoadCryptedKey(vchPubKey, vchPrivKey)) { strErr = "Error reading wallet database: LoadCryptedKey failed"; return false; } wss.fIsEncrypted = true; } else if (strType == "keymeta") { CPubKey vchPubKey; ssKey >> vchPubKey; CKeyMetadata keyMeta; ssValue >> keyMeta; wss.nKeyMeta++; pwallet->LoadKeyMetadata(vchPubKey, keyMeta); // find earliest key creation time, as wallet birthday if (!pwallet->nTimeFirstKey || (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; } else if (strType == "pool") { int64_t nIndex; ssKey >> nIndex; CKeyPool keypool; ssValue >> keypool; pwallet->setKeyPool.insert(nIndex); // If no metadata exists yet, create a default with the pool key's // creation time. Note that this may be overwritten by actually // stored metadata for that key later, which is fine. CKeyID keyid = keypool.vchPubKey.GetID(); if (pwallet->mapKeyMetadata.count(keyid) == 0) pwallet->mapKeyMetadata[keyid] = CKeyMetadata(keypool.nTime); } else if (strType == "version") { ssValue >> wss.nFileVersion; if (wss.nFileVersion == 10300) wss.nFileVersion = 300; } else if (strType == "cscript") { uint160 hash; ssKey >> hash; CScript script; ssValue >> script; if (!pwallet->LoadCScript(script)) { strErr = "Error reading wallet database: LoadCScript failed"; return false; } } else if (strType == "orderposnext") { ssValue >> pwallet->nOrderPosNext; } } catch (...) { return false; } return true; } static bool IsKeyType(string strType) { return (strType== "key" || strType == "wkey" || strType == "mkey" || strType == "ckey"); } DBErrors CWalletDB::LoadWallet(CWallet* pwallet) { pwallet->vchDefaultKey = CPubKey(); CWalletScanState wss; bool fNoncriticalErrors = false; DBErrors result = DB_LOAD_OK; try { LOCK(pwallet->cs_wallet); int nMinVersion = 0; if (Read((string)"minversion", nMinVersion)) { if (nMinVersion > CLIENT_VERSION) return DB_TOO_NEW; pwallet->LoadMinVersion(nMinVersion); } // Get cursor Dbc* pcursor = GetCursor(); if (!pcursor) { printf("Error getting wallet database cursor\n"); return DB_CORRUPT; } while (true) { // Read next record CDataStream ssKey(SER_DISK, CLIENT_VERSION); CDataStream ssValue(SER_DISK, CLIENT_VERSION); int ret = ReadAtCursor(pcursor, ssKey, ssValue); if (ret == DB_NOTFOUND) break; else if (ret != 0) { printf("Error reading next record from wallet database\n"); return DB_CORRUPT; } // Try to be tolerant of single corrupt records: string strType, strErr; if (!ReadKeyValue(pwallet, ssKey, ssValue, wss, strType, strErr)) { // losing keys is considered a catastrophic error, anything else // we assume the user can live with: if (IsKeyType(strType)) result = DB_CORRUPT; else { // Leave other errors alone, if we try to fix them we might make things worse. fNoncriticalErrors = true; // ... but do warn the user there is something wrong. if (strType == "tx") // Rescan if there is a bad transaction record: SoftSetBoolArg("-rescan", true); } } if (!strErr.empty()) printf("%s\n", strErr.c_str()); } pcursor->close(); } catch (...) { result = DB_CORRUPT; } if (fNoncriticalErrors && result == DB_LOAD_OK) result = DB_NONCRITICAL_ERROR; // Any wallet corruption at all: skip any rewriting or // upgrading, we don't want to make it worse. if (result != DB_LOAD_OK) return result; printf("nFileVersion = %d\n", wss.nFileVersion); printf("Keys: %u plaintext, %u encrypted, %u w/ metadata, %u total\n", wss.nKeys, wss.nCKeys, wss.nKeyMeta, wss.nKeys + wss.nCKeys); // nTimeFirstKey is only reliable if all keys have metadata if ((wss.nKeys + wss.nCKeys) != wss.nKeyMeta) pwallet->nTimeFirstKey = 1; // 0 would be considered 'no value' BOOST_FOREACH(uint256 hash, wss.vWalletUpgrade) WriteTx(hash, pwallet->mapWallet[hash]); // Rewrite encrypted wallets of versions 0.4.0 and 0.5.0rc: if (wss.fIsEncrypted && (wss.nFileVersion == 40000 || wss.nFileVersion == 50000)) return DB_NEED_REWRITE; if (wss.nFileVersion < CLIENT_VERSION) // Update WriteVersion(CLIENT_VERSION); if (wss.fAnyUnordered) result = ReorderTransactions(pwallet); return result; } void ThreadFlushWalletDB(void* parg) { // Make this thread recognisable as the wallet flushing thread RenameThread("HOST-wallet"); const string& strFile = ((const string*)parg)[0]; static bool fOneThread; if (fOneThread) return; fOneThread = true; if (!GetBoolArg("-flushwallet", true)) return; unsigned int nLastSeen = nWalletDBUpdated; unsigned int nLastFlushed = nWalletDBUpdated; int64_t nLastWalletUpdate = GetTime(); while (!fShutdown) { MilliSleep(500); if (nLastSeen != nWalletDBUpdated) { nLastSeen = nWalletDBUpdated; nLastWalletUpdate = GetTime(); } if (nLastFlushed != nWalletDBUpdated && GetTime() - nLastWalletUpdate >= 2) { TRY_LOCK(bitdb.cs_db,lockDb); if (lockDb) { // Don't do this if any databases are in use int nRefCount = 0; map<string, int>::iterator mi = bitdb.mapFileUseCount.begin(); while (mi != bitdb.mapFileUseCount.end()) { nRefCount += (*mi).second; mi++; } if (nRefCount == 0 && !fShutdown) { map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile); if (mi != bitdb.mapFileUseCount.end()) { printf("Flushing wallet.dat\n"); nLastFlushed = nWalletDBUpdated; int64_t nStart = GetTimeMillis(); // Flush wallet.dat so it's self contained bitdb.CloseDb(strFile); bitdb.CheckpointLSN(strFile); bitdb.mapFileUseCount.erase(mi++); printf("Flushed wallet.dat %"PRId64"ms\n", GetTimeMillis() - nStart); } } } } } } bool BackupWallet(const CWallet& wallet, const string& strDest) { if (!wallet.fFileBacked) return false; while (!fShutdown) { { LOCK(bitdb.cs_db); if (!bitdb.mapFileUseCount.count(wallet.strWalletFile) || bitdb.mapFileUseCount[wallet.strWalletFile] == 0) { // Flush log data to the dat file bitdb.CloseDb(wallet.strWalletFile); bitdb.CheckpointLSN(wallet.strWalletFile); bitdb.mapFileUseCount.erase(wallet.strWalletFile); // Copy wallet.dat filesystem::path pathSrc = GetDataDir() / wallet.strWalletFile; filesystem::path pathDest(strDest); if (filesystem::is_directory(pathDest)) pathDest /= wallet.strWalletFile; try { #if BOOST_VERSION >= 104000 filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists); #else filesystem::copy_file(pathSrc, pathDest); #endif printf("copied wallet.dat to %s\n", pathDest.string().c_str()); return true; } catch(const filesystem::filesystem_error &e) { printf("error copying wallet.dat to %s - %s\n", pathDest.string().c_str(), e.what()); return false; } } } MilliSleep(100); } return false; } // // Try to (very carefully!) recover wallet.dat if there is a problem. // bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys) { // Recovery procedure: // move wallet.dat to wallet.timestamp.bak // Call Salvage with fAggressive=true to // get as much data as possible. // Rewrite salvaged data to wallet.dat // Set -rescan so any missing transactions will be // found. int64_t now = GetTime(); std::string newFilename = strprintf("wallet.%"PRId64".bak", now); int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL, newFilename.c_str(), DB_AUTO_COMMIT); if (result == 0) printf("Renamed %s to %s\n", filename.c_str(), newFilename.c_str()); else { printf("Failed to rename %s to %s\n", filename.c_str(), newFilename.c_str()); return false; } std::vector<CDBEnv::KeyValPair> salvagedData; bool allOK = dbenv.Salvage(newFilename, true, salvagedData); if (salvagedData.empty()) { printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str()); return false; } printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size()); bool fSuccess = allOK; Db* pdbCopy = new Db(&dbenv.dbenv, 0); int ret = pdbCopy->open(NULL, // Txn pointer filename.c_str(), // Filename "main", // Logical db name DB_BTREE, // Database type DB_CREATE, // Flags 0); if (ret > 0) { printf("Cannot create database file %s\n", filename.c_str()); return false; } CWallet dummyWallet; CWalletScanState wss; DbTxn* ptxn = dbenv.TxnBegin(); BOOST_FOREACH(CDBEnv::KeyValPair& row, salvagedData) { if (fOnlyKeys) { CDataStream ssKey(row.first, SER_DISK, CLIENT_VERSION); CDataStream ssValue(row.second, SER_DISK, CLIENT_VERSION); string strType, strErr; bool fReadOK = ReadKeyValue(&dummyWallet, ssKey, ssValue, wss, strType, strErr); if (!IsKeyType(strType)) continue; if (!fReadOK) { printf("WARNING: CWalletDB::Recover skipping %s: %s\n", strType.c_str(), strErr.c_str()); continue; } } Dbt datKey(&row.first[0], row.first.size()); Dbt datValue(&row.second[0], row.second.size()); int ret2 = pdbCopy->put(ptxn, &datKey, &datValue, DB_NOOVERWRITE); if (ret2 > 0) fSuccess = false; } ptxn->commit(0); pdbCopy->close(0); delete pdbCopy; return fSuccess; } bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename) { return CWalletDB::Recover(dbenv, filename, false); }
[ "alexandercharbonneau95@gmail.com" ]
alexandercharbonneau95@gmail.com
719006e3c55b33c32be666fe0ccc12807d5419ea
1ba46d45a09abc75aea3f6fe5a078b4245fe00e1
/Duibrowser/src/EAWebkit/EAWebKitSupportPackages/EASTLEAWebKit/local/source/assert.cpp
a9d5c32b335390b9a5bbbfa7c926d3f73fbac136
[]
no_license
visi/DuiBrowser
a81bace2b8a3ebb665d349f56fba4ed1201d5f7f
03db25634fe8696ee060e1c01bff8fa0911fcba8
refs/heads/master
2020-06-04T22:10:13.882734
2014-08-17T00:12:40
2014-08-17T00:12:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,887
cpp
/* Copyright (C) 2009-2010 Electronic Arts, 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: 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 Electronic Arts, Inc. ("EA") 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 ELECTRONIC ARTS AND ITS 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 ELECTRONIC ARTS OR ITS 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. */ /////////////////////////////////////////////////////////////////////////////// // EASTL/assert.cpp // // Copyright (c) 2005, Electronic Arts. All rights reserved. // Written and maintained by Paul Pedriana. /////////////////////////////////////////////////////////////////////////////// #include <EASTL/internal/config.h> #include <EASTL/string.h> #include <EABase/eabase.h> #if defined(EA_PLATFORM_MICROSOFT) #pragma warning(push, 0) #if defined _MSC_VER #include <crtdbg.h> #endif #if defined(EA_PLATFORM_WINDOWS) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #elif defined(EA_PLATFORM_WINCE) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #elif defined(EA_PLATFORM_XENON) #include <comdecl.h> #endif #pragma warning(pop) #else #include <stdio.h> #endif namespace eastl { /// gpAssertionFailureFunction /// /// Global assertion failure function pointer. Set by SetAssertionFailureFunction. /// EASTL_API EASTL_AssertionFailureFunction gpAssertionFailureFunction = AssertionFailureFunctionDefault; EASTL_API void* gpAssertionFailureFunctionContext = NULL; /// SetAssertionFailureFunction /// /// Sets the function called when an assertion fails. If this function is not called /// by the user, a default function will be used. The user may supply a context parameter /// which will be passed back to the user in the function call. This is typically used /// to store a C++ 'this' pointer, though other things are possible. /// /// There is no thread safety here, so the user needs to externally make sure that /// this function is not called in a thread-unsafe way. The easiest way to do this is /// to just call this function once from the main thread on application startup. /// EASTL_API void SetAssertionFailureFunction(EASTL_AssertionFailureFunction pAssertionFailureFunction, void* pContext) { gpAssertionFailureFunction = pAssertionFailureFunction; gpAssertionFailureFunctionContext = pContext; } /// AssertionFailureFunctionDefault /// EASTL_API void AssertionFailureFunctionDefault(const char* pExpression, void* /*pContext*/) { #if defined(EA_DEBUG) || defined(_DEBUG) // We cannot use puts() because it appends a newline. // We cannot use printf(pExpression) because pExpression might have formatting statements. #if defined(EA_PLATFORM_MICROSOFT) OutputDebugStringA(pExpression); (void)pExpression; #else printf("%s", pExpression); // Write the message to stdout, which happens to be the trace view for many console debug machines. #endif #endif EASTL_DEBUG_BREAK(); } /// AssertionFailure /// EASTL_API void AssertionFailure(const char* pExpression) { if(gpAssertionFailureFunction) gpAssertionFailureFunction(pExpression, gpAssertionFailureFunctionContext); } } // namespace eastl
[ "achellies@163.com" ]
achellies@163.com
73ca0d44c573bbef754325d6f2cf88a335c0a330
7be0ebdddb09cf6813e1c075c1ac51b59157dd7f
/Oving3_2/Oppgave1/circle.hpp
aa370514180a9b92e44d05de1a4db6a2c324d07e
[]
no_license
ianevangelista/IINI4003-CPP-for-programmerere
680d513ed9d26eb289de6c2f74a218deeb0b25bd
cac4a3b7a69369f66f8acb91fd622c1ca2fed737
refs/heads/master
2022-12-20T00:52:42.307316
2020-09-21T20:12:11
2020-09-21T20:12:11
292,862,395
0
0
null
null
null
null
UTF-8
C++
false
false
422
hpp
#pragma once const double pi = 3.141592; class Circle { public: Circle(double radius_); double get_area() const; double get_circumference() const; private: double radius; }; // ==> Implementasjon av klassen Circle Circle::Circle(double radius_) : radius(radius_) { } double Circle::get_area() const { return pi * radius * radius; } double Circle::get_circumference() const { return 2.0 * pi * radius; }
[ "ianevangelista1999@gmail.com" ]
ianevangelista1999@gmail.com
267c4a127ce272321ef4c8fab2a126f8d1f12006
f503c616cb40d94ed622e27aad0b55ad627e92d5
/source/mainwindow.h
448645935fbe9058e779ee3c95e3be2063ff5008
[]
no_license
skibindings/common-words-counter
6221e60bde0090f0b9a5092542dad90ed64cc1d3
c7e7ecd7090f658d05d6fc31ced5fc45f8b13f02
refs/heads/master
2022-11-12T00:30:40.216363
2020-06-28T13:57:42
2020-06-28T13:57:42
275,594,304
0
0
null
null
null
null
UTF-8
C++
false
false
940
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QListWidgetItem> #include <QFutureWatcher> #include <QMap> #include <QList> #include <QProgressBar> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_load_file_button_clicked(); void on_file_list_itemClicked(QListWidgetItem *item); void on_remove_selected_button_clicked(); void on_analyze_all_button_clicked(); void finished_analyze(); void on_analyze_selected_button_clicked(); private: Ui::MainWindow *ui; static int analyze(int items_number, int set_size, QProgressBar *pb); QFutureWatcher<int> watcher; static QList<QString> files_to_analyze; static QMap<QString, int> analyze_result; bool analyze_work; }; #endif // MAINWINDOW_H
[ "mineanimatior@gmail.com" ]
mineanimatior@gmail.com
a9f65b89c546423652f10e34d872a0d446e31065
c8e922ad0073cf3c0f32920f5d04611a1e28b255
/48.旋转图像.cpp
de0625d7781f805acc08cd2c7e15d6ecf72e1cd3
[]
no_license
yohaohge/leecode
5f619f1989d3e98a3db31f982c06b55ebab73bf5
7083d26bc04a8a9836fa86c9aaa1bc7f8902adbb
refs/heads/master
2023-07-30T23:38:54.483133
2021-10-06T04:57:07
2021-10-06T04:57:07
331,861,162
0
0
null
null
null
null
UTF-8
C++
false
false
857
cpp
/* * @lc app=leetcode.cn id=48 lang=cpp * * [48] 旋转图像 */ // @lc code=start class Solution { public: void rotate(vector<vector<int>>& matrix) { // 按圈旋转 int n = matrix.size(); for(int i = 0; i < n/2; i++ ) { int start = i; int end = n-i-1; for(int j = 0; j < n-2*i - 1; j++) { int x1 = i, y1 = i+j; int x2 = i+j, y2 = end; int x3 = end, y3 = end-j; int x4 = end-j , y4 = i ; int tmp = matrix[x4][y4]; matrix[x4][y4] = matrix[x3][y3]; matrix[x3][y3] = matrix[x2][y2]; matrix[x2][y2] = matrix[x1][y1]; matrix[x1][y1] = tmp; } } } }; // @lc code=end
[ "noreply@github.com" ]
noreply@github.com
566f66c30124866e26dd8a9468f3eea9e258c958
c695fefd2d733901d5dd17e26688c58770aaee5d
/springmass.h
6cd54c8c9528de1f41733cf409b92b5072113319
[]
no_license
jdiogenes/B16-Software-Engineering-Laboratory
d2d6b97fcf29aad268936787d2911e39eeed2445
92778e1a36594e4b931c6adb7d076fdef5b13927
refs/heads/master
2021-01-19T19:35:19.395786
2017-05-23T23:09:26
2017-05-23T23:09:26
88,425,152
0
0
null
null
null
null
UTF-8
C++
false
false
3,145
h
/** file: springmass.h ** brief: SpringMass simulation ** author: Andrea Vedaldi **/ #ifndef __springmass__ #define __springmass__ #include "simulation.h" #include <cmath> #include <vector> #define MOON_GRAVITY 1.62 #define EARTH_GRAVITY 9.82 /* ---------------------------------------------------------------- */ // class Vector2 /* ---------------------------------------------------------------- */ class Vector2 { public: double x ; double y ; Vector2() : x(0), y(0) { } Vector2(double _x, double _y) : x(_x), y(_y) { } double norm2() const { return x*x + y*y ; } double norm() const { return std::sqrt(norm2()) ; } } ; inline Vector2 operator+ (Vector2 a, Vector2 b) { return Vector2(a.x+b.x, a.y+b.y) ; } inline Vector2 operator- (Vector2 a, Vector2 b) { return Vector2(a.x-b.x, a.y-b.y) ; } inline Vector2 operator* (double a, Vector2 b) { return Vector2(a*b.x, a*b.y) ; } inline Vector2 operator* (Vector2 a, double b) { return Vector2(a.x*b, a.y*b) ; } inline Vector2 operator/ (Vector2 a, double b) { return Vector2(a.x/b, a.y/b) ; } inline double dot(Vector2 a, Vector2 b) { return a.x*b.x + a.y*b.y ; } /* ---------------------------------------------------------------- */ // class Mass /* ---------------------------------------------------------------- */ class Mass { public: Mass() ; Mass(Vector2 position, Vector2 velocity, double mass, double radius) ; void setForce(Vector2 f) ; void addForce(Vector2 f) ; Vector2 getForce() const ; Vector2 getPosition() const ; Vector2 getVelocity() const ; double getMass() const ; double getRadius() const ; double getEnergy(double gravity) const ; void step(double dt) ; protected: Vector2 position ; Vector2 velocity ; Vector2 force ; double mass ; double radius ; double xmin ; double xmax ; double ymin ; double ymax ; } ; /* ---------------------------------------------------------------- */ // class Spring /* ---------------------------------------------------------------- */ class Spring { public: Spring(Mass * mass1, Mass * mass2, double naturalLength, double stiffness, double damping = 0.01) ; Mass * getMass1() const ; Mass * getMass2() const ; Vector2 getForce() const ; double getLength() const ; double getEnergy() const ; protected: /* begin remove */ double naturalLength ; double stiffness ; double damping ; Mass * mass1 ; Mass * mass2 ; /* end remove */ } ; /* ---------------------------------------------------------------- */ // class SpringMass : public Simulation /* ---------------------------------------------------------------- */ class SpringMass : public Simulation { public: SpringMass(double gravity = MOON_GRAVITY) ; void step(double dt) ; void display() ; double getEnergy() const ; /* begin remove */ int addMass(Mass m) ; void addSpring(int i, int j, double length, double stiffness) ; /* end remove */ protected: double gravity ; /* begin remove */ typedef std::vector<Mass> masses_t ; typedef std::vector<Spring> springs_t ; masses_t masses ; springs_t springs ; /* end remove */ } ; #endif /* defined(__springmass__) */
[ "jdsantana0@gmail.com" ]
jdsantana0@gmail.com
86a13f9849d763878cf0b3b64232fcbdc0c523f2
9a3ec3eb5371a0e719b50bbf832a732e829b1ce4
/T4C Server/SimpleMonster.h
feb41f3a2e449f02b35096dc878e0a1b4086250c
[]
no_license
elestranobaron/T4C-Serveur-Multiplateformes
5cb4dac8b8bd79bfd2bbd2be2da6914992fa7364
f4a5ed21db1cd21415825cc0e72ddb57beee053e
refs/heads/master
2022-10-01T20:13:36.217655
2022-09-22T02:43:33
2022-09-22T02:43:33
96,352,559
12
8
null
null
null
null
UTF-8
C++
false
false
848
h
// SimpleMonster.h: interface for the SimpleMonster class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_SIMPLEMONSTER_H__8745E2D3_0F4C_11D1_BCDB_00E029058623__INCLUDED_) #define AFX_SIMPLEMONSTER_H__8745E2D3_0F4C_11D1_BCDB_00E029058623__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 #include "NPCstructure.h" class __declspec( dllexport ) SimpleMonster : public NPCstructure { public: SimpleMonster(); virtual ~SimpleMonster(); void Create( ); virtual void OnInitialise( UNIT_FUNC_PROTOTYPE ); virtual void OnPopup( UNIT_FUNC_PROTOTYPE ); virtual void OnServerInitialisation( UNIT_FUNC_PROTOTYPE, WORD wBaseReferenceID ); MonsterStructure *GetMonsterStructure( void ); }; #endif // !defined(AFX_SIMPLEMONSTER_H__8745E2D3_0F4C_11D1_BCDB_00E029058623__INCLUDED_)
[ "lloancythomas@hotmail.co" ]
lloancythomas@hotmail.co
9a5d5e877f1e7744e2ee1892bc1d46119a65f7da
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/third_party/blink/renderer/bindings/core/v8/v8_html_options_collection.cc
61b9ff143047b2d7d9b8aa4ce805a2a64e6b005e
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,838
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.cc.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #include "third_party/blink/renderer/bindings/core/v8/v8_html_options_collection.h" #include <algorithm> #include "base/memory/scoped_refptr.h" #include "third_party/blink/renderer/bindings/core/v8/idl_types.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h" #include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h" #include "third_party/blink/renderer/bindings/core/v8/v8_element.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_element.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_opt_group_element.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_option_element.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/html/custom/ce_reactions_scope.h" #include "third_party/blink/renderer/platform/bindings/exception_messages.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h" #include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h" #include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h" #include "third_party/blink/renderer/platform/wtf/get_ptr.h" namespace blink { // Suppress warning: global constructors, because struct WrapperTypeInfo is trivial // and does not depend on another global objects. #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif const WrapperTypeInfo v8_html_options_collection_wrapper_type_info = { gin::kEmbedderBlink, V8HTMLOptionsCollection::DomTemplate, nullptr, "HTMLOptionsCollection", V8HTMLCollection::GetWrapperTypeInfo(), WrapperTypeInfo::kWrapperTypeObjectPrototype, WrapperTypeInfo::kObjectClassId, WrapperTypeInfo::kNotInheritFromActiveScriptWrappable, }; #if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__) #pragma clang diagnostic pop #endif // This static member must be declared by DEFINE_WRAPPERTYPEINFO in HTMLOptionsCollection.h. // For details, see the comment of DEFINE_WRAPPERTYPEINFO in // platform/bindings/ScriptWrappable.h. const WrapperTypeInfo& HTMLOptionsCollection::wrapper_type_info_ = v8_html_options_collection_wrapper_type_info; // not [ActiveScriptWrappable] static_assert( !std::is_base_of<ActiveScriptWrappableBase, HTMLOptionsCollection>::value, "HTMLOptionsCollection inherits from ActiveScriptWrappable<>, but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); static_assert( std::is_same<decltype(&HTMLOptionsCollection::HasPendingActivity), decltype(&ScriptWrappable::HasPendingActivity)>::value, "HTMLOptionsCollection is overriding hasPendingActivity(), but is not specifying " "[ActiveScriptWrappable] extended attribute in the IDL file. " "Be consistent."); namespace html_options_collection_v8_internal { static void LengthAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(holder); V8SetReturnValueUnsigned(info, impl->length()); } static void LengthAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(holder); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "HTMLOptionsCollection", "length"); CEReactionsScope ce_reactions_scope; // Prepare the value to be set. uint32_t cpp_value = NativeValueTraits<IDLUnsignedLong>::NativeValue(info.GetIsolate(), v8_value, exception_state); if (exception_state.HadException()) return; impl->setLength(cpp_value, exception_state); } static void SelectedIndexAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Object> holder = info.Holder(); HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(holder); V8SetReturnValueInt(info, impl->selectedIndex()); } static void SelectedIndexAttributeSetter( v8::Local<v8::Value> v8_value, const v8::FunctionCallbackInfo<v8::Value>& info) { v8::Isolate* isolate = info.GetIsolate(); ALLOW_UNUSED_LOCAL(isolate); v8::Local<v8::Object> holder = info.Holder(); ALLOW_UNUSED_LOCAL(holder); HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(holder); ExceptionState exception_state(isolate, ExceptionState::kSetterContext, "HTMLOptionsCollection", "selectedIndex"); // Prepare the value to be set. int32_t cpp_value = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), v8_value, exception_state); if (exception_state.HadException()) return; impl->setSelectedIndex(cpp_value); } static void AddMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "HTMLOptionsCollection", "add"); CEReactionsScope ce_reactions_scope; HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } HTMLOptionElementOrHTMLOptGroupElement element; HTMLElementOrLong before; V8HTMLOptionElementOrHTMLOptGroupElement::ToImpl(info.GetIsolate(), info[0], element, UnionTypeConversionMode::kNotNullable, exception_state); if (exception_state.HadException()) return; if (!info[1]->IsUndefined()) { V8HTMLElementOrLong::ToImpl(info.GetIsolate(), info[1], before, UnionTypeConversionMode::kNullable, exception_state); if (exception_state.HadException()) return; } else { /* null default value */; } impl->add(element, before, exception_state); if (exception_state.HadException()) { return; } } static void RemoveMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exception_state(info.GetIsolate(), ExceptionState::kExecutionContext, "HTMLOptionsCollection", "remove"); CEReactionsScope ce_reactions_scope; HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); if (UNLIKELY(info.Length() < 1)) { exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length())); return; } int32_t index; index = NativeValueTraits<IDLLong>::NativeValue(info.GetIsolate(), info[0], exception_state); if (exception_state.HadException()) return; impl->remove(index); } static void NamedPropertyGetter(const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); Element* result = impl->namedItem(name); if (!result) return; V8SetReturnValueFast(info, result, impl); } static void NamedPropertyQuery( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Integer>& info) { const CString& name_in_utf8 = name.Utf8(); ExceptionState exception_state( info.GetIsolate(), ExceptionState::kGetterContext, "HTMLOptionsCollection", name_in_utf8.data()); HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); bool result = impl->NamedPropertyQuery(name, exception_state); if (!result) return; // https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty // 2.7. If |O| implements an interface with a named property setter, then set // desc.[[Writable]] to true, otherwise set it to false. // 2.8. If |O| implements an interface with the // [LegacyUnenumerableNamedProperties] extended attribute, then set // desc.[[Enumerable]] to false, otherwise set it to true. V8SetReturnValueInt(info, v8::DontEnum | v8::ReadOnly); } static void NamedPropertyEnumerator(const v8::PropertyCallbackInfo<v8::Array>& info) { ExceptionState exception_state( info.GetIsolate(), ExceptionState::kEnumerationContext, "HTMLOptionsCollection"); HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); Vector<String> names; impl->NamedPropertyEnumerator(names, exception_state); if (exception_state.HadException()) return; V8SetReturnValue(info, ToV8(names, info.Holder(), info.GetIsolate()).As<v8::Array>()); } static void IndexedPropertyGetter( uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) { HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); // We assume that all the implementations support length() method, although // the spec doesn't require that length() must exist. It's okay that // the interface does not have length attribute as long as the // implementation supports length() member function. if (index >= impl->length()) return; // Returns undefined due to out-of-range. Element* result = impl->item(index); V8SetReturnValueFast(info, result, impl); } static void IndexedPropertyDescriptor( uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) { // https://heycam.github.io/webidl/#LegacyPlatformObjectGetOwnProperty // Steps 1.1 to 1.2.4 are covered here: we rely on indexedPropertyGetter() to // call the getter function and check that |index| is a valid property index, // in which case it will have set info.GetReturnValue() to something other // than undefined. V8HTMLOptionsCollection::IndexedPropertyGetterCallback(index, info); v8::Local<v8::Value> getter_value = info.GetReturnValue().Get(); if (!getter_value->IsUndefined()) { // 1.2.5. Let |desc| be a newly created Property Descriptor with no fields. // 1.2.6. Set desc.[[Value]] to the result of converting value to an // ECMAScript value. // 1.2.7. If O implements an interface with an indexed property setter, // then set desc.[[Writable]] to true, otherwise set it to false. v8::PropertyDescriptor desc(getter_value, true); // 1.2.8. Set desc.[[Enumerable]] and desc.[[Configurable]] to true. desc.set_enumerable(true); desc.set_configurable(true); // 1.2.9. Return |desc|. V8SetReturnValue(info, desc); } } static void IndexedPropertySetter( uint32_t index, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<v8::Value>& info) { ExceptionState exception_state( info.GetIsolate(), ExceptionState::kIndexedSetterContext, "HTMLOptionsCollection"); CEReactionsScope ce_reactions_scope; HTMLOptionsCollection* impl = V8HTMLOptionsCollection::ToImpl(info.Holder()); HTMLOptionElement* property_value = V8HTMLOptionElement::ToImplWithTypeCheck(info.GetIsolate(), v8_value); if (!property_value && !IsUndefinedOrNull(v8_value)) { exception_state.ThrowTypeError("The provided value is not of type 'HTMLOptionElement'."); return; } bool result = impl->AnonymousIndexedSetter(index, property_value, exception_state); if (exception_state.HadException()) return; if (!result) return; V8SetReturnValue(info, v8_value); } } // namespace html_options_collection_v8_internal void V8HTMLOptionsCollection::LengthAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_length_Getter"); html_options_collection_v8_internal::LengthAttributeGetter(info); } void V8HTMLOptionsCollection::LengthAttributeSetterCallback( const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_length_Setter"); v8::Local<v8::Value> v8_value = info[0]; html_options_collection_v8_internal::LengthAttributeSetter(v8_value, info); } void V8HTMLOptionsCollection::SelectedIndexAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_selectedIndex_Getter"); html_options_collection_v8_internal::SelectedIndexAttributeGetter(info); } void V8HTMLOptionsCollection::SelectedIndexAttributeSetterCallback( const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_selectedIndex_Setter"); v8::Local<v8::Value> v8_value = info[0]; html_options_collection_v8_internal::SelectedIndexAttributeSetter(v8_value, info); } void V8HTMLOptionsCollection::AddMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_add"); html_options_collection_v8_internal::AddMethod(info); } void V8HTMLOptionsCollection::RemoveMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_remove"); html_options_collection_v8_internal::RemoveMethod(info); } void V8HTMLOptionsCollection::NamedPropertyGetterCallback( v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_NamedPropertyGetter"); if (!name->IsString()) return; const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>()); html_options_collection_v8_internal::NamedPropertyGetter(property_name, info); } void V8HTMLOptionsCollection::NamedPropertyQueryCallback( v8::Local<v8::Name> name, const v8::PropertyCallbackInfo<v8::Integer>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_NamedPropertyQuery"); if (!name->IsString()) return; const AtomicString& property_name = ToCoreAtomicString(name.As<v8::String>()); html_options_collection_v8_internal::NamedPropertyQuery(property_name, info); } void V8HTMLOptionsCollection::NamedPropertyEnumeratorCallback( const v8::PropertyCallbackInfo<v8::Array>& info) { html_options_collection_v8_internal::NamedPropertyEnumerator(info); } void V8HTMLOptionsCollection::IndexedPropertyGetterCallback( uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) { RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HTMLOptionsCollection_IndexedPropertyGetter"); html_options_collection_v8_internal::IndexedPropertyGetter(index, info); } void V8HTMLOptionsCollection::IndexedPropertyDescriptorCallback( uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& info) { html_options_collection_v8_internal::IndexedPropertyDescriptor(index, info); } void V8HTMLOptionsCollection::IndexedPropertySetterCallback( uint32_t index, v8::Local<v8::Value> v8_value, const v8::PropertyCallbackInfo<v8::Value>& info) { html_options_collection_v8_internal::IndexedPropertySetter(index, v8_value, info); } void V8HTMLOptionsCollection::IndexedPropertyDefinerCallback( uint32_t index, const v8::PropertyDescriptor& desc, const v8::PropertyCallbackInfo<v8::Value>& info) { // https://heycam.github.io/webidl/#legacy-platform-object-defineownproperty // 3.9.3. [[DefineOwnProperty]] // step 1.1. If the result of calling IsDataDescriptor(Desc) is false, then // return false. if (desc.has_get() || desc.has_set()) { V8SetReturnValue(info, v8::Null(info.GetIsolate())); if (info.ShouldThrowOnError()) { ExceptionState exception_state(info.GetIsolate(), ExceptionState::kIndexedSetterContext, "HTMLOptionsCollection"); exception_state.ThrowTypeError("Accessor properties are not allowed."); } return; } // Return nothing and fall back to indexedPropertySetterCallback. } static constexpr V8DOMConfiguration::AccessorConfiguration kV8HTMLOptionsCollectionAccessors[] = { { "length", V8HTMLOptionsCollection::LengthAttributeGetterCallback, V8HTMLOptionsCollection::LengthAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, { "selectedIndex", V8HTMLOptionsCollection::SelectedIndexAttributeGetterCallback, V8HTMLOptionsCollection::SelectedIndexAttributeSetterCallback, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds }, }; static constexpr V8DOMConfiguration::MethodConfiguration kV8HTMLOptionsCollectionMethods[] = { {"add", V8HTMLOptionsCollection::AddMethodCallback, 1, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds}, {"remove", V8HTMLOptionsCollection::RemoveMethodCallback, 1, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds}, }; static void InstallV8HTMLOptionsCollectionTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { // Initialize the interface object's template. V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8HTMLOptionsCollection::GetWrapperTypeInfo()->interface_name, V8HTMLCollection::DomTemplate(isolate, world), V8HTMLOptionsCollection::kInternalFieldCount); v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. V8DOMConfiguration::InstallAccessors( isolate, world, instance_template, prototype_template, interface_template, signature, kV8HTMLOptionsCollectionAccessors, base::size(kV8HTMLOptionsCollectionAccessors)); V8DOMConfiguration::InstallMethods( isolate, world, instance_template, prototype_template, interface_template, signature, kV8HTMLOptionsCollectionMethods, base::size(kV8HTMLOptionsCollectionMethods)); // Indexed properties v8::IndexedPropertyHandlerConfiguration indexedPropertyHandlerConfig( V8HTMLOptionsCollection::IndexedPropertyGetterCallback, V8HTMLOptionsCollection::IndexedPropertySetterCallback, V8HTMLOptionsCollection::IndexedPropertyDescriptorCallback, nullptr, IndexedPropertyEnumerator<HTMLOptionsCollection>, V8HTMLOptionsCollection::IndexedPropertyDefinerCallback, v8::Local<v8::Value>(), v8::PropertyHandlerFlags::kNone); instance_template->SetHandler(indexedPropertyHandlerConfig); // Named properties v8::NamedPropertyHandlerConfiguration namedPropertyHandlerConfig(V8HTMLOptionsCollection::NamedPropertyGetterCallback, nullptr, V8HTMLOptionsCollection::NamedPropertyQueryCallback, nullptr, V8HTMLOptionsCollection::NamedPropertyEnumeratorCallback, v8::Local<v8::Value>(), static_cast<v8::PropertyHandlerFlags>(int(v8::PropertyHandlerFlags::kOnlyInterceptStrings) | int(v8::PropertyHandlerFlags::kNonMasking))); instance_template->SetHandler(namedPropertyHandlerConfig); // Array iterator (@@iterator) prototype_template->SetIntrinsicDataProperty(v8::Symbol::GetIterator(isolate), v8::kArrayProto_values, v8::DontEnum); // Custom signature V8HTMLOptionsCollection::InstallRuntimeEnabledFeaturesOnTemplate( isolate, world, interface_template); } void V8HTMLOptionsCollection::InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world, v8::Local<v8::FunctionTemplate> interface_template) { v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template); ALLOW_UNUSED_LOCAL(signature); v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate(); ALLOW_UNUSED_LOCAL(instance_template); v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate(); ALLOW_UNUSED_LOCAL(prototype_template); // Register IDL constants, attributes and operations. // Custom signature } v8::Local<v8::FunctionTemplate> V8HTMLOptionsCollection::DomTemplate( v8::Isolate* isolate, const DOMWrapperWorld& world) { return V8DOMConfiguration::DomClassTemplate( isolate, world, const_cast<WrapperTypeInfo*>(V8HTMLOptionsCollection::GetWrapperTypeInfo()), InstallV8HTMLOptionsCollectionTemplate); } bool V8HTMLOptionsCollection::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->HasInstance(V8HTMLOptionsCollection::GetWrapperTypeInfo(), v8_value); } v8::Local<v8::Object> V8HTMLOptionsCollection::FindInstanceInPrototypeChain( v8::Local<v8::Value> v8_value, v8::Isolate* isolate) { return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain( V8HTMLOptionsCollection::GetWrapperTypeInfo(), v8_value); } HTMLOptionsCollection* V8HTMLOptionsCollection::ToImplWithTypeCheck( v8::Isolate* isolate, v8::Local<v8::Value> value) { return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr; } HTMLOptionsCollection* NativeValueTraits<HTMLOptionsCollection>::NativeValue( v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) { HTMLOptionsCollection* native_value = V8HTMLOptionsCollection::ToImplWithTypeCheck(isolate, value); if (!native_value) { exception_state.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue( "HTMLOptionsCollection")); } return native_value; } } // namespace blink
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
72887ff680f2c3eebbc292d4bc2de54bbe9c7f10
b2f0d5774b9d510f637b41864fcd24dd7661903d
/200_Number_of_Islands.cpp
848537021c32d0887d01ea3516cf551c947cd9ed
[]
no_license
utsavsingh899/LeetCode_Solutions
a04876dde85865035bcc312fc40eb586ed0b1fa1
ae9b72b576f7d04d3ed9bee0bc3b9d6f8f1dd3fa
refs/heads/master
2023-05-21T08:05:51.174655
2021-06-09T22:51:57
2021-06-09T22:51:57
225,664,872
3
1
null
null
null
null
UTF-8
C++
false
false
852
cpp
class Solution { void dfs(int x, int y, vector<vector<char>>& grid) { grid[x][y] = '0'; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int tx, ty, n = grid.size(), m = grid[0].size(); for (int i = 0; i < 4; ++i) { tx = x + dx[i]; ty = y + dy[i]; if (0 <= tx && tx < n && 0 <= ty && ty < m && grid[tx][ty] == '1') dfs(tx, ty, grid); } } public: int numIslands(vector<vector<char>>& grid) { if (grid.size() == 0 || grid[0].size() == 0) return 0; int res = 0; for (int i = 0; i < grid.size(); ++i) for (int j = 0; j < grid[i].size(); ++j) if (grid[i][j] == '1') { ++res; dfs(i, j, grid); } return res; } };
[ "utsavsingh899@gmail.com" ]
utsavsingh899@gmail.com
5049198d5974677fcbb4b355772b400f51219c75
1c7666f732856924c1de74cf4b1183a05f564ea1
/trunk/vtOS/Shell/Desktop/vtDesktop.cpp
0722f7280b011f31dfac24b2732679d2a85c838c
[]
no_license
BGCX067/facepad-svn-to-git
438a9d1c2da6be2a607d0e278c023390a63d1f86
46b57814576757dc01bb6364bf2eae5e6a96c40c
refs/heads/master
2021-01-13T00:56:28.273577
2015-12-28T14:49:48
2015-12-28T14:49:48
48,837,247
0
0
null
null
null
null
GB18030
C++
false
false
8,398
cpp
#include "..\..\..\FacePad\stdafx.h" #include "vtDesktop.h" #include "..\..\Kernel\Memory\cache_aligned.h" #include "..\..\Kernel\MultiThreading\atomic_t.h" vtDesktop::vtDesktop(void) { initDesktop(NULL, WIN_DESKTOP_DEFAULT_WIDTH, WIN_DESKTOP_DEFAULT_HEIGHT); cache_aligned_t a1(50, 63, false); a1.Malloc(127); cache_aligned_t a2(31, 128); cache_aligned_t a3; cache_aligned_t a4(1999); cache_aligned_t a5(a1); a2.Malloc(63); a2.Realloc(0); a1.Realloc(1); a1.Realloc(2); a2.Realloc(128); void *pBuffer = a2.GetPtr(); a2.MemSet(0); a3 = a2; a1.Free(); //a5.Free(true); pBuffer = a1.AllocPtr(); if (pBuffer != NULL) free(pBuffer); pBuffer = a5.GetPtr(); if (pBuffer != NULL) cache_aligned_t::FreeBlock(pBuffer); //if (pBuffer != NULL) // cache_aligned_t::FreeBlock(pBuffer); atomic_t atomic; atomic_init(&atomic, 0); atomic_inc(&atomic); atomic_set_return(&atomic, 8); atomic_sub_return(3, &atomic); pBuffer = _aligned_malloc(54, 64); if (pBuffer != NULL) _aligned_free(pBuffer); } vtDesktop::vtDesktop( HWND hwnd ) { initDesktop(hwnd); } vtDesktop::vtDesktop( CWnd *pWnd ) { if (pWnd != NULL) initDesktop(pWnd->GetSafeHwnd()); } vtDesktop::~vtDesktop(void) { Detach(); } void vtDesktop::initDesktop( HWND hwnd, int _width, int _height ) { m_hWnd = hwnd; if (_width < 0) _width = WIN_DESKTOP_DEFAULT_WIDTH; if (_height < 0) _height = WIN_DESKTOP_DEFAULT_HEIGHT; initDesktopData(_width, _height); m_pbmpBGBuf = NULL; m_pbmpBG = NULL; m_pbmpWallPaper = NULL; } void vtDesktop::initDesktopData( int _width, int _height ) { width = _width; height = _height; align = VT_ALIGN_CENTER; paddingLeft = 0; paddingRight = 0; paddingTop = 0; paddingBottom = 0; clientWidth = 0; clientHeight = 0; clientAlignH = 0; clientAlignV = 0; cellSpacingX = 0; cellSpacingY = 0; iconWidth = WIN_DESKTOP_ICON_DEFAULT_WIDTH; iconHeight = WIN_DESKTOP_ICON_DEFAULT_HEIGHT; iconSpacingLeft = 0; iconSpacingRight = 0; iconSpacingTop = 0; iconSpacingBottom = 0; iconTextWidth = 0; iconTextHeight = 0; iconTextSpacingX = 0; iconTextSpacingY = 0; iconTextLines = 2; iconArrangement = VT_CELL_LEFT2RIGHT_UP2DOWN; iconAutoAlign = TRUE; iconAlignToGrid = TRUE; bgcolor = WIN_2003_DESKTOP_DEFAULT_BGCOLOR; initWallPaperData(_width, _height); } void vtDesktop::initWallPaperData( int _width, int _height ) { wallPaper.width = _width; wallPaper.height = _height; wallPaper.align = VT_ALIGN_CENTER; wallPaper.bgcolor = bgcolor; _tcscpy_s(wallPaper.cPictureFile, _countof(wallPaper.cPictureFile), _T("")); } BOOL vtDesktop::Attach( HWND hwnd ) { if (hwnd == NULL) return FALSE; m_hWnd = hwnd; LoadDesktopBitmaps(hwnd); return ::IsWindow(hwnd); } BOOL vtDesktop::Attach( CWnd *pWnd ) { if (pWnd != NULL) { return Attach(pWnd->GetSafeHwnd()); } else return FALSE; } HWND vtDesktop::Detach( void ) { HWND hOldWnd = m_hWnd; DeleteObject(); m_hWnd = NULL; return hOldWnd; } void vtDesktop::DeleteObject( void ) { FreeDesktopBitmaps(); } int vtDesktop::initShortCutList( void ) { vtShortCut shortCut; shortCut.SetLinkName(_T("我的电脑")); shortCutList.Add(&shortCut); shortCut.SetLinkName(_T("我的文档")); shortCutList.Add(&shortCut); shortCut.SetLinkName(_T("网上邻居")); shortCutList.Add(&shortCut); shortCut.SetLinkName(_T("回收站")); shortCutList.Add(&shortCut); return shortCutList.SizeOf(); } void vtDesktop::LoadDesktopBitmaps( HWND hwnd, int _width, int _height ) { FreeDesktopBitmaps(); CDC *pDC = NULL; if (hwnd == NULL) hwnd = GetDesktopWindow(); ASSERT(::IsWindow(hwnd)); pDC = CDC::FromHandle(::GetDC(hwnd)); ASSERT(pDC != NULL); if (pDC == NULL) return; CBitmap *pOldBmp = NULL; CDC dcMem; dcMem.CreateCompatibleDC(pDC); m_pbmpBGBuf = new CBitmap; if (m_pbmpBGBuf != NULL) { m_pbmpBGBuf->CreateCompatibleBitmap(pDC, _width, _height); pOldBmp = dcMem.SelectObject((CBitmap *)m_pbmpBGBuf); dcMem.FillSolidRect(0, 0, _width, _height, RGB(0, 0, 0)); if (pOldBmp != NULL) { dcMem.SelectObject(pOldBmp); pOldBmp = NULL; } } m_pbmpBG = new CBitmap; if (m_pbmpBG != NULL) { m_pbmpBG->CreateCompatibleBitmap(pDC, _width, _height); pOldBmp = dcMem.SelectObject((CBitmap *)m_pbmpBG); dcMem.FillSolidRect(0, 0, _width, _height, bgcolor); if (pOldBmp != NULL) { dcMem.SelectObject(pOldBmp); pOldBmp = NULL; } } m_pbmpWallPaper = new CBitmap; if (m_pbmpWallPaper != NULL) { m_pbmpWallPaper->CreateCompatibleBitmap(pDC, _width, _height); pOldBmp = dcMem.SelectObject((CBitmap *)m_pbmpWallPaper); dcMem.FillSolidRect(0, 0, _width, _height, bgcolor); if (pOldBmp != NULL) { dcMem.SelectObject(pOldBmp); pOldBmp = NULL; } } dcMem.DeleteDC(); ::ReleaseDC(hwnd, pDC->m_hDC); pDC->DeleteDC(); } void vtDesktop::LoadDesktopBitmaps( HWND hwnd /*= NULL*/ ) { LoadDesktopBitmaps(hwnd, width, height); } void vtDesktop::FreeDesktopBitmaps( void ) { if (m_pbmpWallPaper != NULL) { m_pbmpWallPaper->DeleteObject(); delete m_pbmpWallPaper; m_pbmpWallPaper = NULL; } if (m_pbmpBG != NULL) { m_pbmpBG->DeleteObject(); delete m_pbmpBG; m_pbmpBG = NULL; } if (m_pbmpBGBuf != NULL) { m_pbmpBGBuf->DeleteObject(); delete m_pbmpBGBuf; m_pbmpBGBuf = NULL; } } void vtDesktop::PaintDesktop( CDC *pDC, CRect *lpRect, UINT flags ) { ASSERT(pDC != NULL); if (pDC != NULL) { CBitmap *pOldBmp = NULL; CDC dcMem; dcMem.CreateCompatibleDC(pDC); pOldBmp = dcMem.SelectObject((CBitmap *)m_pbmpBGBuf); #if 1 PaintDesktopBackground(&dcMem, lpRect, flags); PaintDesktopIconList(&dcMem, lpRect, flags); pDC->BitBlt(lpRect->left, lpRect->top, lpRect->Width(), lpRect->Height(), &dcMem, lpRect->left, lpRect->top, SRCCOPY); #else PaintDesktopBackground(pDC, lpRect, flags); PaintDesktopIconList(pDC, lpRect, flags); #endif if (pOldBmp != NULL) { dcMem.SelectObject(pOldBmp); pOldBmp = NULL; } dcMem.DeleteDC(); } } void vtDesktop::PaintDesktopBackground( CDC *pDC, CRect *lpRect, UINT flags ) { ASSERT(pDC != NULL); if (pDC != NULL) { if (m_pbmpBG != NULL) { CBitmap *pOldBmp = NULL; CDC dcMem; dcMem.CreateCompatibleDC(pDC); pOldBmp = dcMem.SelectObject((CBitmap *)m_pbmpBG); pDC->BitBlt(lpRect->left, lpRect->top, lpRect->Width(), lpRect->Height(), &dcMem, lpRect->left, lpRect->top, SRCCOPY); if (pOldBmp != NULL) { dcMem.SelectObject(pOldBmp); pOldBmp = NULL; } dcMem.DeleteDC(); } } } void vtDesktop::PaintDesktopIconList( CDC *pDC, CRect *lpRect, UINT flags ) { ASSERT(pDC != NULL); if (pDC != NULL) { list<vtShortCut *>::iterator itList; vtShortCut *shortcut; CRect rcIcon; int index = 0; for (itList = shortCutList.begin(); itList != shortCutList.end(); itList++) { shortcut = (vtShortCut *)*itList; ASSERT(shortcut != NULL); if (shortcut != NULL) { PaintDesktopIcon(pDC, &rcIcon, shortcut, index, flags); index++; } } } } void vtDesktop::PaintDesktopIcon( CDC *pDC, CRect *lpRect, vtShortCut *shortcut, int index, UINT flags ) { ASSERT(pDC != NULL); if (pDC != NULL) { // } }
[ "you@example.com" ]
you@example.com
9980df5903c7e295947d87b9cfbb321e68367433
6d219186265a5555059e08f7f1915c2534270f6d
/ros/src/gpar_nanook/src/gpar_nanook_gps.cpp
d5a7b46feceedc73e9e8d449892c6c8c3e75ef6b
[]
no_license
Marcus-Davi/gpar-robotics
f54b65f61d99a399267cfca8ff0fb14f5a929ec8
4caa454aceff4cc9d7aebe40d9abf934da89eebc
refs/heads/master
2023-08-25T15:57:01.494363
2021-10-15T16:07:12
2021-10-15T16:07:12
275,730,946
1
0
null
null
null
null
UTF-8
C++
false
false
6,361
cpp
/* * Copyright (C) 2008, Morgan Quigley and Willow Garage, Inc. * * 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 names of Stanford University or Willow Garage, 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 "ros/ros.h" #include "geometry_msgs/Twist.h" #include "std_msgs/String.h" #include <sstream> #include <serial/serial.h> #include <sensor_msgs/NavSatFix.h> //TODO Add exception catch when disconnected sensor_msgs::NavSatFix ParseGPS(const std::string& msg); const unsigned char AlwaysLocateMode[]={"$PMTK225,8*23\r\n"}; const unsigned char StandbyMode[] = {"$PMTK161,0*28\x0D\x0A"}; const unsigned char SetHertz[] = {"$PMTK220,100*2F\r\n"}; const unsigned char GGAMode[] = {"$PMTK314,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n"}; const unsigned char GLLMode[] = {"$PMTK314,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n"}; const unsigned char RMCMode[] = {"$PMTK314,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0*29\r\n"}; /** * This tutorial demonstrates simple sending of messages over the ROS system. */ int main(int argc, char **argv) { /** * The ros::init() function needs to see argc and argv so that it can perform * any ROS arguments and name remapping that were provided at the command line. * For programmatic remappings you can use a different version of init() which takes * remappings directly, but for most command-line programs, passing argc and argv is * the easiest way to do it. The third argument to init() is the name of the node. * * You must call one of the versions of ros::init() before using any other * part of the ROS system. */ ros::init(argc, argv, "mcuserial_node"); /** * NodeHandle is the main access point to communications with the ROS system. * The first NodeHandle constructed will fully initialize this node, and the last * NodeHandle destructed will close down the node. */ ros::NodeHandle nh; ros::NodeHandle private_nh("~"); //ros::NodeHandle n("~"); std::string porta_serial = "/dev/ttyUSB0"; sensor_msgs::NavSatFix GpsData; if ( !private_nh.getParam("serial_port",porta_serial) ) { ROS_WARN("Setting default serial port -> %s",porta_serial.c_str()); } serial::Serial mcu_serial(porta_serial,57600,serial::Timeout::simpleTimeout(1000)); if(mcu_serial.isOpen()){ ROS_INFO("Porta Serial aberta!"); } else { ROS_INFO("Problema ao abrir a porta %s ! ela existe?",porta_serial.c_str()); return -1; } ros::Publisher pub = nh.advertise< sensor_msgs::NavSatFix>("gps",100); mcu_serial.write(AlwaysLocateMode,sizeof(AlwaysLocateMode)); ros::Duration(0.1).sleep(); // mcu_serial.write(GLLMode,sizeof(GLLMode)); mcu_serial.write(RMCMode,sizeof(RMCMode)); ros::Duration(0.1).sleep(); mcu_serial.write(SetHertz,sizeof(SetHertz)); std::string data; ros::Rate r(20); //Escrever algum código que verifique se o Nanook tá ok! while(ros::ok()){ // ROS_INFO("getting data"); data = mcu_serial.readline(200,"\r"); //Le ate 100 bytes // ROS_INFO("got data!"); // ROS_INFO("parsing"); GpsData = ParseGPS(data); //ROS_INFO("parsed... publishing"); pub.publish(GpsData); //ROS_INFO("published"); ros::spinOnce(); r.sleep(); } return 0; } sensor_msgs::NavSatFix ParseGPS(const std::string& msg){ sensor_msgs::NavSatFix GPS; // ROS_INFO("msg = %s",msg.c_str()); GPS.header.stamp = ros::Time::now(); char* ptr; double lat,lat_d,lat_m; double lon,lon_d,lon_m; int lat_signal = 1; int lon_signal = 1; // ROS_INFO("getting GPGLL"); ptr = strstr((char*)msg.c_str(),"GPRMC"); if(!ptr){ ROS_INFO("GPGLL not found!"); return GPS; } ROS_INFO("Sentence : %s",ptr); ptr = strchr((char*)msg.c_str(),','); // look for first comma ptr = strchr((char*)++ptr,','); // look for 2nd comma ptr = strchr((char*)++ptr,','); // look for 3rd comma // ROS_INFO("ptr OK %s.. atofing",ptr); lat = atof(++ptr); // ROS_INFO("atof ok",ptr); if(lat == 0){ GPS.latitude = 0; GPS.longitude = 0; GPS.status.status = -1; //NO FIX! } else { ptr = strchr((char*)ptr,','); //procura 2a virgula ddmm.mmmm if (*(ptr+1) == 'S') lat_signal = -1; ptr = strchr((char*)++ptr,','); //procura 3a virgula dddmm.mmmm lon = atof(++ptr); lat_d = floorf(lat/100); //graus lat_m = (lat/100.0 - lat_d)*1.66666666666666; //isola os minutos, converte para décimos de graus (1 min = 1/60 grau) // //exemplo : min = 44.6567. 44.6567/60 = 0.744 lon_d = floorf(lon/100); //graus lon_m = (lon/100.0 - lon_d)*1.6666666666666;//isola os minutos, converte para décimos de graus ptr = strchr((char*)ptr,','); if(*(ptr+1) == 'W') lon_signal = -1; GPS.latitude = lat_signal * (lat_d + lat_m); GPS.longitude = lon_signal *(lon_d + lon_m); GPS.status.status = 0; } // TODO converter e publichar velocidades // ROS_INFO("4:: RETURNING GPS.."); return GPS; }
[ "davi2812@dee.ufc.br" ]
davi2812@dee.ufc.br
dd364e9eb4e56377f03359e5854e22100eec15d8
0990f8898c00077ff97b41a147a1cae8f32a380a
/src/qt/sendcoinsdialog.h
d829df7b29019902966ce77698682ad14697f1ee
[ "MIT" ]
permissive
TheUCoin/theucoin
12ddf35d29cd89e1b34afa4ca974383d85334967
886ed0cff8758e6e625ade8d52597d4cb03ec73a
refs/heads/master
2020-06-14T10:26:15.640967
2019-07-03T04:53:01
2019-07-03T04:53:01
194,981,049
0
0
null
null
null
null
UTF-8
C++
false
false
3,438
h
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef TUCOIN_QT_SENDCOINSDIALOG_H #define TUCOIN_QT_SENDCOINSDIALOG_H #include "walletmodel.h" #include <QDialog> #include <QString> static const int MAX_SEND_POPUP_ENTRIES = 10; class ClientModel; class OptionsModel; class SendCoinsEntry; class SendCoinsRecipient; namespace Ui { class SendCoinsDialog; } QT_BEGIN_NAMESPACE class QUrl; QT_END_NAMESPACE /** Dialog for sending tucoins */ class SendCoinsDialog : public QDialog { Q_OBJECT public: explicit SendCoinsDialog(QWidget* parent = 0); ~SendCoinsDialog(); void setClientModel(ClientModel* clientModel); void setModel(WalletModel* model); /** Set up the tab chain manually, as Qt messes up the tab chain by default in some cases (issue https://bugreports.qt-project.org/browse/QTBUG-10907). */ QWidget* setupTabChain(QWidget* prev); void setAddress(const QString& address); void pasteEntry(const SendCoinsRecipient& rv); bool handlePaymentRequest(const SendCoinsRecipient& recipient); bool fSplitBlock; public slots: void clear(); void reject(); void accept(); SendCoinsEntry* addEntry(); void updateTabsAndLabels(); void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance); private: Ui::SendCoinsDialog* ui; ClientModel* clientModel; WalletModel* model; bool fNewRecipientAllowed; void send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted); bool fFeeMinimized; // Process WalletModel::SendCoinsReturn and generate a pair consisting // of a message and message flags for use in emit message(). // Additional parameter msgArg can be used via .arg(msgArg). void processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg = QString(), bool fPrepare = false); void minimizeFeeSection(bool fMinimize); void updateFeeMinimizedLabel(); private slots: void on_sendButton_clicked(); void on_buttonChooseFee_clicked(); void on_buttonMinimizeFee_clicked(); void removeEntry(SendCoinsEntry* entry); void updateDisplayUnit(); void updateSwiftTX(); void coinControlFeatureChanged(bool); void coinControlButtonClicked(); void coinControlChangeChecked(int); void coinControlChangeEdited(const QString&); void coinControlUpdateLabels(); void coinControlClipboardQuantity(); void coinControlClipboardAmount(); void coinControlClipboardFee(); void coinControlClipboardAfterFee(); void coinControlClipboardBytes(); void coinControlClipboardPriority(); void coinControlClipboardLowOutput(); void coinControlClipboardChange(); void splitBlockChecked(int); void splitBlockLineEditChanged(const QString& text); void setMinimumFee(); void updateFeeSectionControls(); void updateMinFeeLabel(); void updateSmartFeeLabel(); void updateGlobalFeeVariables(); signals: // Fired when a message should be reported to the user void message(const QString& title, const QString& message, unsigned int style); }; #endif // TUCOIN_QT_SENDCOINSDIALOG_H
[ "vric.team@gmail.com" ]
vric.team@gmail.com
d84e82da27dac1c18c0562e9faee37a53f9526f1
3eced30e5499038d489dd09e58e4441ba812d546
/MindMapGUI/MindMapPainter.h
3730a37dac9c8c210abcbf11c5d1df728c2b1a81
[]
no_license
KemingChen/POSD
e1999eb73517fb26992e410f53dc0fbd27db247f
493e4de38a469d032a6703ff7b57b3113c33de6f
refs/heads/master
2020-05-17T18:41:08.117150
2015-01-12T15:53:09
2015-01-12T15:53:09
30,136,294
0
0
null
null
null
null
UTF-8
C++
false
false
695
h
#pragma once #include "IGraphic.h" #include "Component.h" #include <QGraphicsScene> class MindMapGUI; class GUIPresentModel; class MindMapPainter : public IGraphic { private: QGraphicsScene* _scene; MindMapGUI* _guiWindow; GUIPresentModel* _presentModel; QFont getFont() const; QPen getPen() const; public: MindMapPainter(QGraphicsScene* scene, MindMapGUI* guiWindow, GUIPresentModel* presentModel); void calculateTextRectSize(Component* node); void drawNode(Component* node); void drawRectangle(Rect rect); void drawTriangle(Rect rect); void drawEllipse(Rect rect); ~MindMapPainter(); };
[ "believe75467@gmail.com" ]
believe75467@gmail.com
359c835e2271bc3acef4ac26a586215a4566d503
cbf187c628e9aef224c6cc432a3c63401567d6c7
/homework/test.cpp
5fe0d51f8817b9b8254acca2022818ab92e179b5
[]
no_license
WayKwin/WD_backup
64bbddcd1fc8b64dd5d941766f9f66636aef5c5a
e2e0005b9f0e06bb20d4b9d0c86106e9e8842148
refs/heads/master
2020-03-10T03:56:44.044819
2018-08-30T15:30:54
2018-08-30T15:30:54
129,179,507
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
#include<unordered_map> #include<iostream> #include<map> #include<vector> #include<string.h> using namespace std; int main() { int num1 = 1; int num2 = 2; char str[]= "1,2"; if(sscanf(str,"%d ,%d",&num1,&num2) != 2 ) cout << "Sdsad\n"; cout << num1 << " "<<num2 <<endl; }
[ "543235396@qq.com" ]
543235396@qq.com
dcd4a01bbd1ae89e8961144dfde7b2168afae4f0
69ed1447b867b11b3ff841aeb10550fe138a2246
/Implementation/LibMCData/libmcdata_buildjobdata.hpp
d7d68a68c268b9beba4500c760b61ecfded119c8
[ "BSD-3-Clause" ]
permissive
jakeread/AutodeskMachineControlFramework
926d492390773b57b64aee910412ee29db13a055
288b07db3df7b72b67f98040ccf6da9889123469
refs/heads/master
2023-08-23T03:07:07.311759
2021-08-06T17:35:16
2021-08-06T17:35:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,420
hpp
/*++ Copyright (C) 2020 Autodesk 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 the Autodesk 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 AUTODESK INC. 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. Abstract: This is the class declaration of CBuildJobData */ #ifndef __LIBMCDATA_BUILDJOBDATA #define __LIBMCDATA_BUILDJOBDATA #include "libmcdata_interfaces.hpp" // Parent classes #include "libmcdata_base.hpp" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4250) #endif // Include custom headers here. #include "amcdata_storagepath.hpp" #include "amcdata_sqlhandler.hpp" namespace LibMCData { namespace Impl { /************************************************************************************************************************* Class declaration of CBuildJobData **************************************************************************************************************************/ class CBuildJobData; typedef std::shared_ptr<CBuildJobData> PBuildJobData; class CBuildJobData : public virtual IBuildJobData, public virtual CBase { private: std::string m_sDataUUID; std::string m_sName; LibMCData::eBuildJobDataType m_eDataType; std::string m_sTimeStamp; std::string m_sStorageStreamUUID; std::string m_sUserID; std::string m_sJobUUID; std::string m_sSHA256; uint64_t m_nStreamSize; AMCData::PSQLHandler m_pSQLHandler; AMCData::PStoragePath m_pStoragePath; protected: CBuildJobData(const std::string& sDataUUID, const std::string & sName, const std::string& sJobUUID, LibMCData::eBuildJobDataType eDataType, std::string & sTimeStamp, std::string & sStorageStreamUUID, std::string & sUserID, std::string & sSHA2, uint64_t nStreamSize, AMCData::PSQLHandler pSQLHandler, AMCData::PStoragePath pStoragePath); public: ~CBuildJobData(); static CBuildJobData* make(const std::string& sDataUUID, const std::string& sName, const std::string& sJobUUID, LibMCData::eBuildJobDataType eDataType, std::string& sTimeStamp, std::string& sStorageStreamUUID, std::string& sUserID, std::string& sSHA2, uint64_t nStreamSize, AMCData::PSQLHandler pSQLHandler, AMCData::PStoragePath pStoragePath); static CBuildJobData* makeFrom(CBuildJobData* pBuildJob); static PBuildJobData makeShared(const std::string& sDataUUID, const std::string& sName, const std::string& sJobUUID, LibMCData::eBuildJobDataType eDataType, std::string& sTimeStamp, std::string& sStorageStreamUUID, std::string& sUserID, std::string& sSHA2, uint64_t nStreamSize, AMCData::PSQLHandler pSQLHandler, AMCData::PStoragePath pStoragePath); static PBuildJobData makeSharedFrom(CBuildJobData* pBuildJobData); static CBuildJobData* createInDatabase(const std::string sName, const std::string & sJobUUID, LibMCData::eBuildJobDataType eDataType, std::string sTimeStamp, std::string sStorageStreamUUID, std::string sUserID, std::string& sSHA2, uint64_t nStreamSize, AMCData::PSQLHandler pSQLHandler, AMCData::PStoragePath pStoragePath); static PBuildJobData createSharedInDatabase(const std::string sName, const std::string & sJobUUID, LibMCData::eBuildJobDataType eDataType, std::string sTimeStamp, std::string sStorageStreamUUID, std::string sUserID, std::string& sSHA2, uint64_t nStreamSize, AMCData::PSQLHandler pSQLHandler, AMCData::PStoragePath pStoragePath); std::string GetDataUUID() override; std::string GetJobUUID() override; std::string GetName() override; std::string GetTimeStamp() override; IStorageStream * GetStorageStream() override; std::string GetStorageStreamSHA2() override; LibMCData_uint64 GetStorageStreamSize() override; LibMCData::eBuildJobDataType GetDataType() override; std::string GetDataTypeAsString() override; std::string GetMIMEType() override; static std::string convertBuildJobDataTypeToString(const LibMCData::eBuildJobDataType dataType); static LibMCData::eBuildJobDataType convertStringToBuildJobDataType(const std::string& sValue); }; } // namespace Impl } // namespace LibMCData #ifdef _MSC_VER #pragma warning(pop) #endif #endif // __LIBMCDATA_BUILDJOBDATA
[ "Alexander.Oster@autodesk.com" ]
Alexander.Oster@autodesk.com
cfb6863422cc22db1397e221795213de6da81f7e
497db4b4bebd9456641d4d2efc377d7349f02ac8
/Response.h
929a0cb58192cc9b63d1579ac26e71ae8a44858f
[]
no_license
ideawu/cpp-redis
8aba3b157ec19282d02a65d1b07983771ff15c4f
95860614d546e8b52fed7801ae3edb46fe082bb2
refs/heads/master
2023-07-02T23:57:31.787544
2021-08-01T09:19:46
2021-08-01T09:19:46
391,581,485
0
3
null
null
null
null
UTF-8
C++
false
false
1,238
h
#include <vector> #include <string> #ifndef REDIS_RESPONSE_H_ #define REDIS_RESPONSE_H_ namespace redis { class Response { public: enum { STATUS = 0, INT, NOT_FOUND, BULK, ARRAY }; Response() { } Response(int clientId) { _clientId = clientId; } int ClientId() const { return _clientId; } void ReplyOK() { _type = STATUS; } void ReplyError(const std::string msg) { _type = STATUS; _vals.push_back(msg); } void ReplyInt(int64_t num) { _type = INT; _vals.push_back(std::to_string(num)); } void ReplyNotFound() { _type = NOT_FOUND; } void ReplyBulk(const std::string data) { _type = BULK; _vals.push_back(data); } void ReplyArray(const std::vector<std::string>& vals) { _type = ARRAY; this->_vals = vals; } void ReplyArray(const std::vector<bool>& exists, const std::vector<std::string>& vals) { _type = ARRAY; _exists = exists; _vals = vals; } std::string Encode() const; private: int _clientId; int _type = STATUS; std::vector<bool> _exists; std::vector<std::string> _vals; }; }; // namespace redis #endif
[ "3202758+ideawu@users.noreply.github.com" ]
3202758+ideawu@users.noreply.github.com
1932b5b52afc36c2a9f74a4bd6517220cff181fa
82cc4eea98806f3024b5b16696a7af258e2a24a4
/src/xapian/api/result.h
b4e1a9666d64726ad30667802b1c075bbb62ffaa
[ "MIT", "GPL-2.0-only", "Apache-2.0", "GPL-1.0-or-later", "BSD-3-Clause" ]
permissive
puer99miss/Xapiand
72e7497f37f315c354ae12b360ea8b14bc31ee00
480f312709d40e2b1deb244ff0761b79846ed608
refs/heads/master
2020-05-18T23:33:48.464001
2019-05-02T18:29:01
2019-05-02T18:29:01
184,714,481
1
0
MIT
2019-05-03T07:21:22
2019-05-03T07:21:22
null
UTF-8
C++
false
false
2,635
h
/** @file result.h * @brief A result in an MSet */ /* Copyright 2017,2019 Olly Betts * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef XAPIAN_INCLUDED_RESULT_H #define XAPIAN_INCLUDED_RESULT_H #include "xapian/backends/multi.h" #include "xapian/types.h" #include <string> /** A result in an MSet. */ class Result { double weight; Xapian::docid did; Xapian::doccount collapse_count = 0; std::string collapse_key; std::string sort_key; public: Result& operator=(const Result&) = delete; Result(const Result&) = delete; /// Move constructor. Result(Result&&) = default; /// Move assignment. Result& operator=(Result&&) = default; /// Constructor. Result(double weight_, Xapian::docid did_) : weight(weight_), did(did_) {} /// Constructor used by MSet::Internal::unserialise(). Result(double weight_, Xapian::docid did_, std::string&& collapse_key_, Xapian::doccount collapse_count_, std::string&& sort_key_) : weight(weight_), did(did_), collapse_count(collapse_count_), collapse_key(std::move(collapse_key_)), sort_key(std::move(sort_key_)) {} void swap(Result& o); Xapian::docid get_docid() const { return did; } double get_weight() const { return weight; } Xapian::doccount get_collapse_count() const { return collapse_count; } const std::string& get_collapse_key() const { return collapse_key; } const std::string& get_sort_key() const { return sort_key; } void set_weight(double weight_) { weight = weight_; } void set_collapse_count(Xapian::doccount c) { collapse_count = c; } void set_collapse_key(const std::string& k) { collapse_key = k; } void set_sort_key(const std::string& k) { sort_key = k; } void unshard_docid(Xapian::doccount shard, Xapian::doccount n_shards) { did = unshard(did, shard, n_shards); } std::string get_description() const; }; #endif // XAPIAN_INCLUDED_RESULT_H
[ "german.mb@gmail.com" ]
german.mb@gmail.com
93d9caefbb6d25c809053a9dcfbf8a07da274c1b
2b1436cec45b64a877a3e5ac077eb134a1fa3bd2
/shell/Command.h
d77861a5e99eff41a3dfb3a8390c4a9a7fee4600
[]
no_license
hkruisselbrink/HansJoostGeheugen
ed5149b3e857c1fc7216360ac9902a9050822415
0a9bc263aa344f06f1adf5d0f8c019a8e25cabf7
refs/heads/master
2020-04-07T16:36:52.760982
2014-07-01T10:04:53
2014-07-01T10:04:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,033
h
#ifndef _Command_h_ #define _Command_h_ /** @file Command.h * Definition of class Command. */ #include <string> // std::string #include <vector> // std::vector /** @class Command * The program to be executed. */ class Command { private: // The words that make up the command. std::vector<std::string> words; // IO redirection information std::string input; // name of input file std::string output; // name of output file bool append; // use output append mode bool cdCommand; bool exitCommand; public: /// Initialize Command(); /// Add a word to the command void addWord(std::string& word); /// Set the name of the standard input file /// @pre There may only be one input file specification void setInput(std::string& input); /// Set the name of the standard output file /// @pre There may only be one output file specification void setOutput(std::string& output); /// Set the name of the standard output file in append mode /// @pre There may only be one output file specification void setAppend(std::string& output); /// Does this command have some input redirection? bool hasInput() const { return !input.empty(); } /// Does this command have some output redirection? bool hasOutput() const { return !output.empty(); } /// Is this an do-nothing-at-all command? bool isEmpty() const; bool hasCd(); bool hasExit(); /// Execute the command. /// All words are passed to the new process as the program's argument list. /// /// The first word is taken to be the name of the program to be executed. /// If the name begins with '/' it is an absolute name. /// If the name begins with "./" it is relative to the current directory. /// Otherwise it is to be searched for using the PATH environment variable. /// (Also see getenv(3), getcwd(3), access(2), execv(3)). void execute(); // TODO: Add any other methods you need }; // vim:ai:aw:ts=4:sw=4: #endif /*_Command_h_*/
[ "hans@localhost.localdomain" ]
hans@localhost.localdomain
4dfaa82a2629a1d81b12cc7bd291a97031d8b5e2
dd3f4d317a0e363a866fa06e8a8fd4bc29d86805
/RakNet/cat/crypt/hash/Skein.hpp
36acffabc2fc86e5bbc9cac2cbc101d22b090413
[ "BSD-3-Clause" ]
permissive
Xaretius/vaultmp
23c0b3a5a5e623d5ac7ab70eab11a0142ff9edad
28f83a7068441a4120b086a1355462d2f26eaa3a
refs/heads/master
2021-01-10T14:40:34.980883
2011-05-18T13:09:30
2011-05-18T13:09:30
50,698,651
0
0
null
null
null
null
UTF-8
C++
false
false
4,443
hpp
/* Copyright (c) 2009-2010 Christopher A. Taylor. 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 LibCat 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. */ /* Bruce Schneier's SHA-3 candidate Skein hash function http://www.skein-hash.info/ */ #ifndef CAT_SKEIN_HPP #define CAT_SKEIN_HPP #include <cat/crypt/hash/ICryptHash.hpp> namespace cat { // Base class for various versions of Skein class Skein : public ICryptHash { protected: // Tweak word 1 bit field starting positions static const int T1_POS_TREE_LVL = 112-64; // bits 112..118 : level in hash tree static const int T1_POS_BIT_PAD = 119-64; // bit 119 : partial final input byte static const int T1_POS_BLK_TYPE = 120-64; // bits 120..125 : type field static const int T1_POS_FIRST = 126-64; // bits 126 : first block flag static const int T1_POS_FINAL = 127-64; // bit 127 : final block flag // Tweak word 1 bit field masks static const u64 T1_MASK_FIRST = (u64)1 << T1_POS_FIRST; static const u64 T1_MASK_FINAL = (u64)1 << T1_POS_FINAL; static const u64 T1_MASK_BIT_PAD = (u64)1 << T1_POS_BIT_PAD; static const u64 T1_MASK_TREE_LVL = (u64)0x7F << T1_POS_TREE_LVL; static const u64 T1_MASK_BLK_TYPE = (u64)63 << T1_POS_BLK_TYPE; static const int BLK_TYPE_KEY = 0; // key, for MAC and KDF static const int BLK_TYPE_CFG = 4; // configuration block static const int BLK_TYPE_PERS = 8; // personalization string static const int BLK_TYPE_PK = 12; // public key (for digital signature hashing) static const int BLK_TYPE_KDF = 16; // key identifier for KDF static const int BLK_TYPE_NONCE = 20; // nonce for PRNG static const int BLK_TYPE_MSG = 48; // message processing static const int BLK_TYPE_OUT = 63; // output stage static const u32 ID_STRING_LE = 0x33414853; static const u32 VERSION = 1; static const u64 SCHEMA_VER = ((u64)VERSION << 32) | ID_STRING_LE; static const int MAX_BITS = 512; static const int MAX_WORDS = MAX_BITS / 64; static const int MAX_BYTES = MAX_BITS / 8; u64 Tweak[2]; u64 State[MAX_WORDS]; u8 Work[MAX_BYTES]; int used_bytes, digest_words; u64 output_block_counter; bool output_prng_mode; typedef void (Skein::*HashComputation)(const void *message, int blocks, u32 byte_count, u64 *NextState); void HashComputation256(const void *message, int blocks, u32 byte_count, u64 *NextState); void HashComputation512(const void *message, int blocks, u32 byte_count, u64 *NextState); HashComputation hash_func; void GenerateInitialState(int bits); public: ~Skein(); bool BeginKey(int bits); bool SetKey(ICryptHash *parent); bool BeginMAC(); bool BeginKDF(); bool BeginPRNG(); void Crunch(const void *message, int bytes); void End(); void Generate(void *out, int bytes, int strengthening_rounds = 0); }; } // namespace cat #endif // CAT_SKEIN_HPP
[ "recycler1993@t-online.de" ]
recycler1993@t-online.de
2dd6ebcfc0aad03c5489322d5a13875fe3e78ed8
c057e033602e465adfa3d84d80331a3a21cef609
/C/testcases/CWE415_Double_Free/s01/CWE415_Double_Free__new_delete_array_char_73b.cpp
ac4fc3dc20921660808d210da8dd0515dca33ed4
[]
no_license
Anzsley/My_Juliet_Test_Suite_v1.3_for_C_Cpp
12c2796ae7e580d89e4e7b8274dddf920361c41c
f278f1464588ffb763b7d06e2650fda01702148f
refs/heads/main
2023-04-11T08:29:22.597042
2021-04-09T11:53:16
2021-04-09T11:53:16
356,251,613
1
0
null
null
null
null
UTF-8
C++
false
false
1,468
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE415_Double_Free__new_delete_array_char_73b.cpp Label Definition File: CWE415_Double_Free__new_delete_array.label.xml Template File: sources-sinks-73b.tmpl.cpp */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files * * */ #include "std_testcase.h" #include <list> #include <wchar.h> using namespace std; namespace CWE415_Double_Free__new_delete_array_char_73 { #ifndef OMITBAD void badSink(list<char *> dataList) { /* copy data out of dataList */ char * data = dataList.back(); /* POTENTIAL FLAW: Possibly deleting memory twice */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(list<char *> dataList) { char * data = dataList.back(); /* POTENTIAL FLAW: Possibly deleting memory twice */ delete [] data; } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(list<char *> dataList) { char * data = dataList.back(); /* do nothing */ /* FIX: Don't attempt to delete the memory */ ; /* empty statement needed for some flow variants */ } #endif /* OMITGOOD */ } /* close namespace */
[ "65642214+Anzsley@users.noreply.github.com" ]
65642214+Anzsley@users.noreply.github.com
f7c134e31240634081a7b8e30f73e44d0ed3a65d
92d6a696e8008f8dcad8b5098ab1722acf6b5f60
/src/wxprintgp.h
c92b155cfcdea33fa78a470eed12299636ce8890
[]
no_license
graciposser/astran
8687fe2700a6e94905aa16f5907076647c1ead9b
4ae62bdf664aa36e62fee243f9bfa20cd2602d9a
refs/heads/master
2020-04-05T22:50:47.871247
2012-08-28T15:34:27
2012-08-28T15:34:27
32,224,823
0
0
null
null
null
null
UTF-8
C++
false
false
756
h
#ifndef __wxprintgp__ #define __wxprintgp__ /** @file Subclass of View_PrintGP, which is generated by wxFormBuilder. */ #include "wxinterface.h" #include "icpdfrm.h" #include <string> using std::string; #include <iomanip> class IcpdFrm; /** Implementing View_PrintGP */ class WxPrintGP : public View_PrintGP { private: IcpdFrm* currentFrmwork; protected: // Handlers for View_PrintGP events. void PressedKey( wxKeyEvent& event ); //void applyButtonEvt( wxCommandEvent& event ); void okButtonEvt( wxCommandEvent& event ); void cancelButtonEvt( wxCommandEvent& event ); void ok(); void cancel(); public: /** Constructor */ WxPrintGP( IcpdFrm* frmwork ); void refresh(); string doubleToString(double val); }; #endif // __wxprintgp__
[ "graciposser@6dc9b86d-86e5-d22b-864f-d61d89bde513" ]
graciposser@6dc9b86d-86e5-d22b-864f-d61d89bde513
2fc8ebd9e8567497bceb0534b32207f69f7818f5
5638be520c7794e028a864abac29f51c88c07f27
/Leetcode/c102_A.cpp
5be63544632d615c5809f58282a0c7fdefc62ca0
[]
no_license
CcChangJF/AlgoCodes
eb8af69764ff4042819bafd15abc0d573b80f9c9
737ae8f6aed4d43386c08ca1b007c03d698e042c
refs/heads/master
2020-04-26T11:23:03.166366
2019-03-17T02:11:01
2019-03-17T02:11:01
173,514,478
0
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
//Description //TestCase /* */ //Wrong case /* */ /* how to solve */ #include <iostream> #include <vector> #include <string> #include <algorithm> using namespace std; class Solution { public: vector<int> sortArrayByParity(vector<int>& A) { if (0 == A.size()) {return vector<int>();} vector<int> res(A.begin(), A.end()); int start = 0; int end = res.size() - 1; while(start < end) { while (start < res.size() && start < end && 0 == res[start] % 2) { start = start + 1; } while ( end >= 0 && start < end && 1 == res[end] % 2 ) { end = end - 1; } if ( start < end ) { swap(res[start], res[end]); start = start + 1; end = end - 1; } } return res; } }; int main() { Solution s; return 0; }
[ "changjunfeng2018@gmail.com" ]
changjunfeng2018@gmail.com
1f78e421fca7868acfd6e8ea32ebf3affe14aabe
9736e73ddb97fdc40ecd12c57915722ce01b78ed
/borody_task_4/func_sim/func_instr/disasm.cpp
e77cf930b81afa2cccbb1c4a6d9403cc1277df14
[ "MIT" ]
permissive
MIPT-ILab/mipt-mips-old-branches
2f1a96c90234f1cf21341b949fc105dcdbd18454
a4e17025999b15d423601cf38a84234c5c037b33
refs/heads/master
2021-03-12T18:00:25.684770
2017-05-17T21:13:56
2017-05-17T21:13:56
91,449,696
1
0
null
null
null
null
UTF-8
C++
false
false
1,818
cpp
// Generci C #include <string.h> #include <stdlib.h> #include <assert.h> // Generic C++ #include <iostream> #include <iomanip> // uArchSim modules #include <elf_parser.h> #include <func_instr.h> using namespace std; int main ( int argc, char* argv[]) { // Constants used for pretty-printing const string indent_offset_string = " "; const string indent_disasm_string = " "; const int indent_offset = indent_offset_string.length(); const int table_width = 40; const int min_num_of_args = 3; if ( argc >= min_num_of_args && strcmp( argv[1], "--help")) { for ( size_t i = 2; i < argc; ++i) { // TODO: refactor it! ElfSection section( argv[ 1], argv[ i]); cout << "Disassembly of the section " << argv[ i] << ":" << endl << endl; uint64 instr_addr = section.startAddr(); for ( ; section.isInside( instr_addr, 4); instr_addr += 4) { uint32 instr_bits = section.read( instr_addr); FuncInstr instr( instr_bits); cout << indent_offset_string << setw( 8); cout.fill( '0'); cout << right << hex << instr_addr << instr.dump( indent_disasm_string) << endl; } cout << endl; } } else if ( argc == 2 && !strcmp( argv[ 1], "--help")) { cout << "MIPS disassembler." << endl << endl << "Usage: \"" << argv[0] << " <ELF binary file> <section name> [<section_name>, ...]\"" << endl; } else { cerr << "ERROR: wrong number of arguments!" << endl << "Type \"" << argv[ 0] << " --help\" for usage." << endl; exit( EXIT_FAILURE); } return 0; }
[ "dmitriy.borodiy@gmail.com@8191d7f6-0415-6e15-5cfd-e6cccd3c4e6a" ]
dmitriy.borodiy@gmail.com@8191d7f6-0415-6e15-5cfd-e6cccd3c4e6a
108a1b4cc54300c23430d7ceedb05490075a1405
9425b49470913fb7d6df65f1e1e23076938628c0
/04_week/nest_for_test_2.cpp
1dddc262bf4bd8f15aff72297088d4460ebc18a3
[]
no_license
ramanqul/pp1-2019-fall
a3a456681b6aac322eaaf5d0d69405af798e6632
55b5701ece13563629d1088dc9fe8f08a953a158
refs/heads/master
2020-07-15T06:13:51.266168
2019-11-17T11:54:40
2019-11-17T11:54:40
205,497,935
2
4
null
null
null
null
UTF-8
C++
false
false
299
cpp
#include <iostream> using namespace std; /* 2 6 8 4 16 32 8 24 64 */ int main() { //How many times it will iterate? A: 10*10 = 100 for (int row=1;row<=10;row++) { for (int col=1;col<=10;col++) { int product = row * col; cout << product << " "; } cout << endl; } return 0; }
[ "buzaubakov.raman@gmail.com" ]
buzaubakov.raman@gmail.com
0304264724a68ab134a2783ee554f5c9e8340e61
6680f8d317de48876d4176d443bfd580ec7a5aef
/Header/Pacs/widgets/wpan.h
52ef098758650d5b7da5c16955a9e1616fabcf26
[]
no_license
AlirezaMojtabavi/misInteractiveSegmentation
1b51b0babb0c6f9601330fafc5c15ca560d6af31
4630a8c614f6421042636a2adc47ed6b5d960a2b
refs/heads/master
2020-12-10T11:09:19.345393
2020-03-04T11:34:26
2020-03-04T11:34:26
233,574,482
3
0
null
null
null
null
UTF-8
C++
false
false
1,470
h
/* * * $Id: wpan.h $ * Ginkgo CADx Project * * Copyright 2008-14 MetaEmotion S.L. All rights reserved. * http://ginkgo-cadx.com * * This file is licensed under LGPL v3 license. * See License.txt for details * * */ #pragma once #include <vector> #include <export/tools/itoolslider.h> #include <api/iwidgets.h> #include <api/math/geometry3d.h> namespace GNC { namespace GCS { namespace Widgets { //--------------------------------------------------------------------- class WPanBuilder : public GNC::GCS::Widgets::IWidgetBuilder { public: typedef GNC::GCS::Vector TVector; typedef GNC::GCS::Vector3D TVector3D; typedef GNC::GCS::Events::EventoRaton TEventoRaton; typedef GNC::GCS::Events::EventoTeclado TEventoTeclado; typedef GNC::GCS::IWidgetsManager TWidgetsManager; typedef GNC::GCS::Widgets::IWidget TWidget; WPanBuilder(TWidgetsManager* pManager, const GNC::GCS::TriggerButton& buttonMask, long gid); ~WPanBuilder(); virtual void OnMouseEvents(TEventoRaton& event); virtual void OnKeyEvents(TEventoTeclado& event); virtual void Render(GNC::GCS::Contexto3D* c); virtual GNC::GCS::Widgets::TipoCursor GetCursor(); //region "Helpers" bool m_Dentro; //endregion protected: TVector m_NodoMoviendose; // Cursor bool m_MouseDown; Estado m_Estado; }; } } }
[ "alireza_mojtabavi@yahoo.com" ]
alireza_mojtabavi@yahoo.com
286b929ab1323597ebe03923b1e11b3bad8392cb
0813ee5e3dd0ae14be05d10ebb005fc6d8cce002
/____Documents____/2_Display/uml_tmp_file/include/binder/LinkedList.cpp
dbca84dcc7ddfb40845ed1711a604fb7acc022fa
[]
no_license
listentodella/Android
d59e81c7be1c63c2e936614703b3c16a2927bde4
9c4134fe4bbaf16cf5a45079887029a423351a68
refs/heads/master
2021-06-28T16:51:04.196832
2019-03-12T13:12:20
2019-03-12T13:12:20
109,273,649
3
0
null
null
null
null
UTF-8
C++
false
false
71
cpp
#include "LinkedList.h" namespace android { } // namespace android
[ "937138688@qq.com" ]
937138688@qq.com
c57d115af30018e53fc908ee97ae2aef110ff047
0bc8635f52a77bf23668320ab9924f5b90ff147d
/QPushButton/widget.h
da65ea6f4fe2cc515c7757d21964df7113dfd189
[]
no_license
vicfer89/Qt-CodeRepo_Learning
b5c547313bb6ea568e2ca7485db67a3aa8459f5b
4fd1398da64220579bfbcbb39396791050193d11
refs/heads/master
2020-04-21T12:00:20.108699
2019-02-07T11:29:30
2019-02-07T11:29:30
169,547,841
0
0
null
null
null
null
UTF-8
C++
false
false
314
h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = nullptr); ~Widget(); private slots: void on_pushButton_Quitar_clicked(); private: Ui::Widget *ui; }; #endif // WIDGET_H
[ "vicfer89@gmail.com" ]
vicfer89@gmail.com
b4b7ef1f4dbebbf943ea68addb1cd213a4d2f5c5
33707649a50d8b03f477a2fcfab3b33b8de868a0
/examples/distributed-primitives/idgenerator/FlakeIdGenerator.cpp
27ac1b980f486ed8b23d5c707b575af8eb3af193
[ "Apache-2.0" ]
permissive
vladoschreiner/hazelcast-cpp-client
266bbbcb03d35d4c191f62e3eb93b7b5e4670880
22e381448b83ad80cf336cef4a30c4387841fba6
refs/heads/master
2020-04-29T09:35:40.837000
2019-03-16T22:27:26
2019-03-16T22:27:26
176,030,583
0
0
Apache-2.0
2019-03-16T22:14:36
2019-03-16T22:14:36
null
UTF-8
C++
false
false
1,160
cpp
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <hazelcast/client/HazelcastClient.h> #include <hazelcast/client/FlakeIdGenerator.h> int main() { hazelcast::client::ClientConfig config; hazelcast::client::HazelcastClient hz(config); hazelcast::client::FlakeIdGenerator generator = hz.getFlakeIdGenerator("flakeIdGenerator"); for (int i = 0; i < 10000; ++i) { hazelcast::util::sleep(1); int64_t newId = generator.newId(); std::cout << "Id : " << newId << std::endl; } std::cout << "Finished" << std::endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
3f8c356da8f61084494fa383e295db13cb3fca0e
92a9582a8e4f8ff459b1809373a24bf8cf1ad2fa
/Homeworks/Homework 3/linear.cpp
4cc98895bc4341643080fbe37930b7f76d55d2fe
[]
no_license
stovsky/CS32
433b28ff0963600e1ff5b9df40034bd844f7cbc6
08465c02bb70885d3915fe04c91cc391745a4317
refs/heads/main
2023-09-03T15:31:42.997294
2021-10-28T04:13:16
2021-10-28T04:13:16
422,056,300
0
0
null
null
null
null
UTF-8
C++
false
false
1,149
cpp
bool allTrue(const string a[], int n) { if (n <= 0) return true; if (n == 1) return somePredicate(a[0]); return somePredicate(a[0]) && allTrue(a + 1, n - 1); } int countFalse(const string a[], int n) { int counter = 0; if (n <= 0) return 0; if (n == 1) { if (somePredicate(a[0])) return 0; else return 1; } if (!somePredicate(a[0])) counter++; return counter + countFalse(a + 1, n - 1); } int firstFalse(const string a[], int n) { if (n <= 0) return -1; if (!somePredicate(a[0])) return 0; int i = firstFalse(a + 1, n - 1); if (i == -1) return -1; return i + 1; } int indexOfLeast(const string a[], int n) { if (n <= 0) return -1; if (n == 1) return 0; int i = indexOfLeast(a, n - 1); if (a[i] <= a[n - 1]) return i; else return n - 1; } bool includes(const string a1[], int n1, const string a2[], int n2) { if (n2 <= 0) return true; if (n1 <= 0 || n1 < n2) return false; if (a1[0] == a2[0]) return includes(a1 + 1, n1 - 1, a2 + 1, n2 - 1); else return includes(a1 + 1, n1 - 1, a2, n2); }
[ "noreply@github.com" ]
noreply@github.com
ff9265f61026d7503bc7d484b38c0675a9788a5b
7a17d90d655482898c6777c101d3ab6578ccc6ba
/SDK/PUBG_ActorSequence_classes.hpp
fd37690efd3e9b755243fd2be46d5a9c8e006d2a
[]
no_license
Chordp/PUBG-SDK
7625f4a419d5b028f7ff5afa5db49e18fcee5de6
1b23c750ec97cb842bf5bc2b827da557e4ff828f
refs/heads/master
2022-08-25T10:07:15.641579
2022-08-14T14:12:48
2022-08-14T14:12:48
245,409,493
17
7
null
null
null
null
UTF-8
C++
false
false
3,146
hpp
#pragma once // PUBG (9.1.5.3) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_ActorSequence_structs.hpp" namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class ActorSequence.ActorSequence // 0x0030 (0x0370 - 0x0340) class UActorSequence : public UMovieSceneSequence { public: class UMovieScene* MovieScene; // 0x0340(0x0008) (ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData) struct FActorSequenceObjectReferenceMap ObjectReferences; // 0x0348(0x0020) unsigned char UnknownData00[0x8]; // 0x0368(0x0008) MISSED OFFSET static UClass* StaticClass() { static UClass* ptr; if(!ptr) ptr = UObject::FindClass(_xor_("Class ActorSequence.ActorSequence")); return ptr; } }; // Class ActorSequence.ActorSequenceComponent // 0x0040 (0x0250 - 0x0210) class UActorSequenceComponent : public UActorComponent { public: struct FMovieSceneSequencePlaybackSettings PlaybackSettings; // 0x0210(0x0028) (Edit) class UActorSequence* Sequence; // 0x0238(0x0008) (Edit, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData) class UActorSequencePlayer* SequencePlayer; // 0x0240(0x0008) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, IsPlainOldData) bool bAutoPlay; // 0x0248(0x0001) (Edit, ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x7]; // 0x0249(0x0007) MISSED OFFSET static UClass* StaticClass() { static UClass* ptr; if(!ptr) ptr = UObject::FindClass(_xor_("Class ActorSequence.ActorSequenceComponent")); return ptr; } }; // Class ActorSequence.ActorSequencePlayer // 0x0000 (0x0710 - 0x0710) class UActorSequencePlayer : public UMovieSceneSequencePlayer { public: static UClass* StaticClass() { static UClass* ptr; if(!ptr) ptr = UObject::FindClass(_xor_("Class ActorSequence.ActorSequencePlayer")); return ptr; } void Stop(); void StartPlayingNextTick(); void SetPlayRate(float PlayRate); void SetPlaybackRange(float NewStartTime, float NewEndTime); void SetPlaybackPosition(float NewPlaybackPosition); void PlayReverse(); void PlayLooping(int NumLoops); void Play(); void Pause(); bool IsPlaying(); float GetPlayRate(); float GetPlaybackStart(); float GetPlaybackPosition(); float GetPlaybackEnd(); float GetLength(); TArray<class UObject*> GetBoundObjects(const struct FMovieSceneObjectBindingID& ObjectBinding); void ChangePlaybackDirection(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "1263178881@qq.com" ]
1263178881@qq.com
aaf5b1b9c6ab4021e6f6769975210002d588421d
03d30a4d27cb5a07cb83494e53e9ccf625746f9b
/src/engine/IO/mouse.h
bab5217683aab0c746767b27547a783de11d5ad3
[]
no_license
villeholopainen/airplane
d579aeb29ef59ff2434c134965844edd431de05a
bcf48f07c556787086c27e9d645f4b52b8205984
refs/heads/master
2021-05-06T17:07:07.165901
2017-11-23T10:59:19
2017-11-23T10:59:19
111,791,157
0
0
null
null
null
null
UTF-8
C++
false
false
755
h
#ifndef MOUSE_H #define MOUSE_H #include <GLFW/glfw3.h> class Mouse { public: static void MousePosCallback(GLFWwindow *window, double x, double y); static void mouseButtonCallback(GLFWwindow *window, int button, int action, int mods); static double GetMouseX(); static double GetMouseY(); static bool ButtonDown(int button); static bool ButtonUp(int button); static bool Button(int button); private: static double m_x; static double m_y; static bool buttons[]; static bool buttonsDown[]; static bool buttonsUp[]; static int m_mousebutton; }; #endif // MOUSE_H
[ "holopainen.ville@elisanet.fi" ]
holopainen.ville@elisanet.fi
f00a0dc9f57c06c18b5f02993ec1bf9788d9a5ca
e5ef1df4b8ad35ce664895fbfe2d5833e588c853
/computer_entry.h
f74089bad7336ee42460b1ceed6b0028c7fa28f0
[]
no_license
Zeph-T/Cyber-Cafe-Management-System
63f7b53a53efc316d98f84327e8ee30a859b73d4
c1c2b5cfcc298a2f0a01fc81bcc04d0d556f06d5
refs/heads/main
2023-01-22T07:25:29.150484
2020-11-30T07:39:22
2020-11-30T07:39:22
317,145,708
0
0
null
null
null
null
UTF-8
C++
false
false
2,024
h
#include<string.h> using namespace std; class computer_entry { public: char *name,*model,*processor,*purchase_date; int ram; float *price; computer_entry() { name=new char[20]; model=new char[20]; processor=new char[20]; purchase_date=new char[10]; price=new float; } void add(); void show(); void del(); void update(); int search(char n[20]); void display(computer_entry com[],int cn); }; void computer_entry::display(computer_entry com[],int cn) { cout<<"Computer Name\t\tModel\t\tProcessor\t\tRam\t\tPrice\t\tPurchase date\n"; for(int i=0;i<cn;i++) { if(com[i].name!=" ") { float *t=com[i].price; cout<<" "<<com[i].name<<" \t\t "<<com[i].model<<"\t\t "<<com[i].processor<<" \t\t "<<com[i].ram<<" \t\t "; cout<<*t<<" \t\t"<<com[i].purchase_date<<endl; } } } void computer_entry::add() { cout<<"Enter computer name: "; cin>>name; cout<<"Enter model: "; cin>>model; cout<<"Enter processor type: "; cin>>processor; cout<<"Ram: "; cin>>ram; cout<<"Price of computer: "; cin>>*price; cout<<"Purchase date of computer: "; cin>>purchase_date; } void computer_entry::show() { cout<<"computer name: "<<name<<endl; cout<<"model: "<<model<<endl; cout<<"Enter processor type: "<<processor<<endl; cout<<"Ram: "<<ram<<endl; cout<<"Price of computer: "<<*price<<endl; cout<<"Purchase date of computer: "<<purchase_date<<endl; } void computer_entry::update() { cout<<"Enter computer name: "; cin>>name; cout<<"Enter model: "; cin>>model; cout<<"Enter processor type: "; cin>>processor; cout<<"Ram: "; cin>>ram; cout<<"Price of computer: "; cin>>*price; cout<<"Purchase date of computer: "; cin>>purchase_date; } int computer_entry::search(char n[20]) { if(strcmp(n,name)==0) return 1; else return 0; } void computer_entry::del() { name=" "; model=" "; processor=" "; purchase_date=" "; price=NULL ; ram=NULL; }
[ "noreply@github.com" ]
noreply@github.com
bebe20d25f784d46adc2278af63528fb8de2d0f8
62b5c8e7164a25432719892a5d96475843350fc6
/UnitTest1/UnitTest1.cpp
83fd23a521365e3c8f222a4ca6ea12a32da416d3
[]
no_license
StanislavSorochak/oop_laba6.7
9946313178a6d2c23b9d22eaa338e8ae1b3a33ca
a61fc374769f699c089ce5b22bc5c414ff094ec4
refs/heads/master
2023-04-27T09:01:09.300983
2021-05-24T08:41:31
2021-05-24T08:41:31
370,283,311
0
0
null
null
null
null
UTF-8
C++
false
false
724
cpp
#include "pch.h" #include "CppUnitTest.h" #include "../oop_laba6.7/Array.cpp" #include "../oop_laba6.7/Source.cpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTest1 { TEST_CLASS(UnitTest1) { public: TEST_METHOD(TestMethod1) { int arr[] = { 0, 1, 2, 3, -4 }; Array result = Array(1); Array dynamicArray = returnDynamicArray(arr, 5); int zeroDuplicated[] = { 0, 0, 1, 2, 3, -4 }; Predicate<double>* zero = new Zero<double>(); //functor: "zero elements" result = duplicate_if<Array>(dynamicArray.begin(), dynamicArray.end(), dynamicArray, *zero); for (int i = 0; i < result.size(); i++) Assert::AreEqual((int)result[i], zeroDuplicated[i]); } }; }
[ "75738611+StanislavSorochak@users.noreply.github.com" ]
75738611+StanislavSorochak@users.noreply.github.com
095dea4e1769234ce01f46455abfc04ef29d8a90
5161f17e5eb4483f9b0b57a42a5565bd32654e02
/src/components/mesh_renderer.h
8a7bd3218ee4ffc970235ae43ae7fd13d64d6510
[ "MIT" ]
permissive
ScottTodd/GraphicsPractice
1fa022143b6fd1c71b3a2cdfe3e3bebb0ebbc7cf
31691d5fd0b674627e41362772737168c57ec698
refs/heads/master
2021-01-20T07:13:57.633646
2015-08-09T21:03:51
2015-08-09T21:03:51
40,450,460
2
0
null
null
null
null
UTF-8
C++
false
false
416
h
#ifndef MESH_RENDERER_H #define MESH_RENDERER_H #include "component.h" #include "material.h" #include "mesh.h" class MeshRenderer : public Component { public: MeshRenderer(); MeshRenderer(Mesh &mesh, Material &material); ~MeshRenderer() {} void Update(float delta_time); void Render() const; void Cleanup(); private: Mesh mesh_; Material material_; }; #endif // MESH_RENDERER_H
[ "scott.todd0@gmail.com" ]
scott.todd0@gmail.com
e951ac8090f00d7a07ce9c9049836d5f05780297
98fb6a5b345e81907363c666b817f0c69f604d24
/Projet-ATM_Java/data/RAW/cluster_15ac_1err_1.cp
f3343680eccbe09026fe88f36faa9050d66436fe
[]
no_license
CedricBaillif/Projet-ATM_Repo
57b82474f88d4c42677206988cbd3fb1ebca0965
fb12d2d35e68e641ae35c4796b14581fde4f8ff8
refs/heads/master
2020-05-26T07:46:10.704800
2015-06-30T14:47:00
2015-06-30T14:47:00
34,018,337
0
0
null
null
null
null
UTF-8
C++
false
false
92
cp
0 106 1 150 2 137 3 40 4 123 5 150 6 150 7 127 8 150 9 150 10 8 11 150 12 150 13 150 14 150
[ "cedric.baillif@gmail.com" ]
cedric.baillif@gmail.com
5ca9dbd5fa2ef764de5d0d133f06139f2acd5e2a
a8e5517df264ca12e84c377270574a3cc378f0c1
/BOJ/3964/solution.cpp
cc551514fdb692c6eef3a70f87d0a48afabda22b
[]
no_license
wowoto9772/Hungry-Algorithm
cb94edc0d8a4a3518dd1996feafada9774767ff0
4be3d0e2f07d01e55653c277870d93b73ec917de
refs/heads/master
2021-05-04T23:28:12.443915
2019-08-11T08:11:39
2019-08-11T08:11:39
64,544,872
1
1
null
null
null
null
UTF-8
C++
false
false
805
cpp
#include <stdio.h> #include <limits.h> #include <vector> #include <algorithm> using namespace std; #define ll long long int main(){ int t; scanf("%d", &t); while (t--){ ll n, k; scanf("%lld %lld", &n, &k); vector <ll> p; vector <int> c; for (ll i = 2; i*i <= k; i++){ if (k%i)continue; p.push_back(i); int d = 0; while (!(k%i)){ k /= i; d++; } c.push_back(d); } if (k != 1){ p.push_back(k); c.push_back(1); } ll ans = 0; ans = LLONG_MAX; for (int i = 0; i < p.size(); i++){ int r = c[i]; ll d = 0; ll cur = p[i]; while (cur <= n){ d += n / cur; if (cur > n / p[i]){ // prevent overflow break; } cur *= p[i]; } ans = min(ans, d / r); } if (ans == LLONG_MAX)ans = 0; printf("%lld\n", ans); } }
[ "csjaj9772@gmail.com" ]
csjaj9772@gmail.com
f47ec7505e2eac1ea945afdc5e7db37cf31d36bc
b5d3d6895a7f67647d9288df54b4fb8a6edcc77e
/rootfinding.cpp
4fa06060dea5e806842dd707804c1faded99ad52
[]
no_license
paro8929/etaON
520f8c2e89e302124541cd488c2ebc804141089c
e17fbc76043976f55eb459bf352e6d9d7a2690e3
refs/heads/main
2023-06-01T09:57:02.181708
2021-06-21T15:05:12
2021-06-21T15:05:12
357,631,309
1
0
null
null
null
null
UTF-8
C++
false
false
1,806
cpp
double est_root(double xa,double xb, double ya, double yb) { double res=(xb*ya-xa*yb)/(ya-yb); return res; } double convergeroot1(double (*fun)(double *),double *args) { double xa,xb,ya,yb,res; //initial gues: xa=args[0]; int IT=round(args[1]); double strength=args[2]; double brek=args[3]; int verbose=round(args[4]); double mult; for (int i=0;i<IT;i++) { args[0]=xa; ya=(*fun)(args); mult=-ya*strength; xb=xa+mult; args[0]=xb; yb=(*fun)(args); res=est_root(xa,xb,ya,yb); if (verbose) printf("i=%i res=%f y(%f)=%f y(%f)=%f\n",i,res,xa,ya,xb,yb); xa=xb+(res-xb)*brek; } return res; } int sign(double x) { if (x > 0) return 1; if (x < 0) return -1; return 0; } double convergeroot2(double (*fun)(double *),double *args) { int IT=round(args[1]); double low=args[2]; double high=args[3]; int verbose=round(args[4]); if (low>high) { printf("converge root 2 WARNING: low>high!\n"); //ABORT=1; } args[0]=low; double ylow=(*fun)(args); args[0]=high; double yhigh=(*fun)(args); if (sign(ylow)==sign(yhigh)) { printf("converge root 2 WARNING: root not bracketed!\n"); printf("low=%f: ylow%f high=%f yhigh %f\n",low,ylow,high,yhigh); //ABORT=1; } double middle; for (int i=0;i<IT;i++) { middle=0.5*(low+high); args[0]=middle; double ym=(*fun)(args); if (sign(ym)==sign(ylow)) { low=middle; ylow=ym; } else if (sign(ym)==sign(yhigh)) { high=middle; yhigh=ym; } if (verbose) printf("i=%i %f %f %f %f\n",i,low,ylow,high,yhigh); } return middle; } double testf(double *args) { double x=args[0]; return (x-0.144)*(x-0.144); }
[ "paul.romatschke@colorado.edu" ]
paul.romatschke@colorado.edu
86a5267890a120ce687b009a6025c53e82184b29
725930880df2293e956e654741f5ed72d7d3bc22
/include/SceneMgr.hpp
2bb57222925bee2febff7c9e1453fdadf5b77069
[]
no_license
nitorionedan/Ohajiki
595bddcbb49af2df228c9362d87db461ba085161
a86ba2aa0ccbe0a663176d5c2f2c84e3871717e6
refs/heads/master
2021-01-12T10:15:45.315315
2016-12-24T02:56:55
2016-12-24T02:56:55
76,400,912
1
0
null
null
null
null
UTF-8
C++
false
false
255
hpp
#pragma once #include "Task.hpp" #include "Game.hpp" class SceneMgrClass : public Task { public: SceneMgrClass(); ~SceneMgrClass(); virtual void Update() override; virtual void Draw() override; private: void Initialize(); GameClass* m_game; };
[ "b1444263@planet.kanazawa-it.ac.jp" ]
b1444263@planet.kanazawa-it.ac.jp
d7d6feaaf8043ef67f630de1502cf10ff4cdcad4
58e2b1d22f33170b9b89ce84e2dea84cfa97bfca
/RayTracing/Primitives.h
c55467d8cf4dbc10d8062ef6d57fb39d89aa630f
[ "MIT" ]
permissive
msembinelli/mjs-gl
a0ac4eb35d7b2093f254ad3a7c0a25f54b48229c
8f900787405d7249456e469a032b32793540ec61
refs/heads/master
2021-01-19T03:56:47.926946
2017-01-23T06:35:22
2017-01-23T06:35:22
49,688,336
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
h
#ifndef PRIMITIVES_H #define PRIMITIVES_H #include <glm/glm.hpp> #include <GLFW/glfw3.h> #include "Ray.h" using namespace glm; class Object { public: Object(vec3 diffuse_colour_, vec3 specular_colour_, GLfloat phong_exponent_, GLfloat reflectance_); vec3 diffuse_colour; vec3 specular_colour; GLfloat reflectance; GLfloat phong_exponent; virtual bool intersect(const Ray &ray, vec3 *point, GLfloat *t_val) = 0; virtual vec3 normal(const vec3 &intersection_point) = 0; }; class Sphere : public Object { public: Sphere(vec3 center_, GLfloat radius_, vec3 diffuse_colour_, vec3 specular_colour_, GLfloat phong_exponent_, GLfloat reflectance_); bool intersect(const Ray &ray, vec3 *point, GLfloat *t_val); vec3 normal(const vec3 &intersection_point); private: vec3 center; GLfloat radius; }; class Plane : public Object { public: Plane(vec3 normal_, vec3 point_, vec3 diffuse_colour_, vec3 specular_colour_, GLfloat phong_exponent_, GLfloat reflectance_); bool intersect(const Ray &ray, vec3 *point, GLfloat *t_val); vec3 normal(const vec3 &intersection_point); private: vec3 p_normal; vec3 point; }; class Triangle : public Object { public: Triangle(vec3 p0_, vec3 p1_, vec3 p2_, vec3 diffuse_colour_, vec3 specular_colour_, GLfloat phong_exponent_, GLfloat reflectance_); bool intersect(const Ray &ray, vec3 *point, GLfloat *t_val); vec3 normal(const vec3 &intersection_point); private: vec3 p0, p1, p2; }; #endif
[ "matthew.sembinelli@gmail.com" ]
matthew.sembinelli@gmail.com
f75480d1c0c44b9f30ea1d76bdc5901679b7b808
aaad2e2d740df7aec21ce3c8f12778ffeb068781
/Exp3Drone/src/GamePadHandler.cpp
ec3a7e61adae405ef04cb0ee123a3c4c833cdf78
[]
no_license
lsale/BizarreExperiments
80bd3a263d76f0af7f2a5cff31448098c7ae6fad
972edb5114ed047b64a7f5368a22b011a62f29be
refs/heads/master
2020-04-06T05:47:54.249116
2013-11-27T09:43:00
2013-11-27T09:43:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,003
cpp
/* * GamePadHandler.cpp * * Created on: 27 Aug 2013 * Author: doturner */ #include "GamePadHandler.h" #include <QDebug> #include <screen/screen.h> #include <errno.h> // This macro provides error checking for all calls to libscreen APIs. static int rc; #define SCREEN_API(x, y) rc = x; \ if (rc) fprintf(stderr, "\n%s in %s: %d", y, __FUNCTION__, errno) #define MAX_CONTROLLERS 2 GamePadHandler::GamePadHandler(screen_context_t* screen_context) : shouldRun(true), mScreenContext(*screen_context) { qDebug() << "[GamePadHandler] Constructor start"; qDebug() << "[GamePadHandler] Constructor end"; } GamePadHandler::~GamePadHandler() { qDebug() << "[GamePadHandler] Destructor start"; qDebug() << "[GamePadHandler] Destructor end"; } void GamePadHandler::run() { qDebug() << "[GamePadHandler] run() - start"; shouldRun = true; // Initialize BPS library. bps_initialize(); // Initialize the controllers int i; for (i = 0; i < MAX_CONTROLLERS; ++i) { initController(&mControllers[i], i); } // Request screen events screen_request_events(mScreenContext); // Look for attached gamepads discoverControllers(); //Main event loop while (shouldRun) { //do some stuff //qDebug() << "[GamePadHandler] Polling for gamepad events"; //sleep(1); handleEvents(); //update(); //render(); } // Clean up resources and shut everything down. // Stop requesting events from libscreen. screen_stop_events(mScreenContext); // Shut down BPS library for this process. bps_shutdown(); qDebug() << "[GamePadHandler] run() - end"; } void GamePadHandler::initController(GameController* controller, int player) { // Initialize controller values. controller->handle = 0; controller->type = 0; controller->analogCount = 0; controller->buttonCount = 0; controller->buttons = 0; controller->analog0[0] = controller->analog0[1] = controller->analog0[2] = 0; controller->analog1[0] = controller->analog1[1] = controller->analog1[2] = 0; sprintf(controller->deviceString, "Player %d: No device detected.", player + 1); } void GamePadHandler::discoverControllers() { // Get an array of all available devices. int deviceCount; SCREEN_API(screen_get_context_property_iv(mScreenContext, SCREEN_PROPERTY_DEVICE_COUNT, &deviceCount), "SCREEN_PROPERTY_DEVICE_COUNT"); screen_device_t* devices = (screen_device_t*) calloc(deviceCount, sizeof(screen_device_t)); SCREEN_API(screen_get_context_property_pv(mScreenContext, SCREEN_PROPERTY_DEVICES, (void** )devices), "SCREEN_PROPERTY_DEVICES"); // Scan the list for gamepad and joystick devices. int i; int controllerIndex = 0; for (i = 0; i < deviceCount; i++) { int type; SCREEN_API(screen_get_device_property_iv(devices[i], SCREEN_PROPERTY_TYPE, &type), "SCREEN_PROPERTY_TYPE"); if (!rc && (type == SCREEN_EVENT_GAMEPAD || type == SCREEN_EVENT_JOYSTICK)) { // Assign this device to control Player 1 or Player 2. GameController* controller = &mControllers[controllerIndex]; controller->handle = devices[i]; loadController(controller); qDebug() << "[GamePadHandler] discoverControllers - Device already connected, index: " << controllerIndex << " name: " << controller->deviceString; emit gamePadConnected(controllerIndex); // We'll just use the first compatible devices we find. controllerIndex++; if (controllerIndex == MAX_CONTROLLERS) { break; } } } free(devices); } void GamePadHandler::loadController(GameController* controller) { // Query libscreen for information about this device. SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_TYPE, &controller->type), "SCREEN_PROPERTY_TYPE"); SCREEN_API(screen_get_device_property_cv(controller->handle, SCREEN_PROPERTY_ID_STRING, sizeof(controller->id), controller->id), "SCREEN_PROPERTY_ID_STRING"); SCREEN_API(screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_BUTTON_COUNT, &controller->buttonCount), "SCREEN_PROPERTY_BUTTON_COUNT"); // Check for the existence of analog sticks. if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG0, controller->analog0)) { ++controller->analogCount; } if (!screen_get_device_property_iv(controller->handle, SCREEN_PROPERTY_ANALOG1, controller->analog1)) { ++controller->analogCount; } if (controller->type == SCREEN_EVENT_GAMEPAD) { sprintf(controller->deviceString, "Gamepad device ID: %s", controller->id); } else { sprintf(controller->deviceString, "Joystick device: %s", controller->id); } qDebug() << "[GamePadHandler] loadController() - Loaded device ID: " << controller->id; } void GamePadHandler::handleEvents() { // Get the first event in the queue. bps_event_t *event = NULL; if (BPS_SUCCESS != bps_get_event(&event, 0)) { qDebug() << "[GamePadHandler] handleEvents() - bps_get_event() failed"; return; } // Handle all events in the queue. // If we don't do this in a loop, we'll only handle one event per frame. // If many events are triggered quickly, e.g. by spinning the analog sticks, // the queue will grow and the user will see the analog sticks lag. while (event) { handleScreenEvent(event); if (BPS_SUCCESS != bps_get_event(&event, 0)) { qDebug() << "[GamePadHandler] handleEvents() - bps_get_event() failed"; return; } } } void GamePadHandler::handleScreenEvent(bps_event_t *event) { int eventType; screen_event_t screen_event = screen_event_get_event(event); screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_TYPE, &eventType); switch (eventType) { case SCREEN_EVENT_GAMEPAD: case SCREEN_EVENT_JOYSTICK: { //qDebug() << "[GamePadHandler] handleScreenEvent() - Got gamepad event"; // Determine which controller this is. screen_device_t device; SCREEN_API(screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DEVICE, (void** )&device), "SCREEN_PROPERTY_DEVICE"); GameController* controller = NULL; int i; for (i = 0; i < MAX_CONTROLLERS; ++i) { if (device == mControllers[i].handle) { controller = &mControllers[i]; break; } } if (!controller) { break; } // Store the controller's new state. int oldButtonState = controller->buttons; SCREEN_API(screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_BUTTONS, &controller->buttons), "SCREEN_PROPERTY_BUTTONS"); if (oldButtonState != controller->buttons){ qDebug() << "[GamePadHandler] button state changed to: " << controller->buttons; emit buttonStateChanged(i, controller->buttons); } if (controller->analogCount > 0) { int oldAnalog0XValue = controller->analog0[0]; int oldAnalog0YValue = controller->analog0[1]; SCREEN_API(screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ANALOG0, controller->analog0), "SCREEN_PROPERTY_ANALOG0"); if (oldAnalog0XValue != controller->analog0[0] || oldAnalog0YValue != controller->analog0[1]){ emit analog0StateChanged(i, controller->analog0[0], controller->analog0[1]); } } if (controller->analogCount == 2) { int oldAnalog1XValue = controller->analog1[0]; int oldAnalog1YValue = controller->analog1[1]; SCREEN_API(screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ANALOG1, controller->analog1), "SCREEN_PROPERTY_ANALOG1"); if (oldAnalog1XValue != controller->analog1[0] || oldAnalog1YValue != controller->analog1[1]){ emit analog1StateChanged(i, controller->analog1[0], controller->analog1[1]); } } break; } case SCREEN_EVENT_DEVICE: { qDebug() << "[GamePadHandler] handleScreenEvent() - Got device event"; // A device was attached or removed. screen_device_t device; int attached; int type; SCREEN_API(screen_get_event_property_pv(screen_event, SCREEN_PROPERTY_DEVICE, (void** )&device), "SCREEN_PROPERTY_DEVICE"); SCREEN_API(screen_get_event_property_iv(screen_event, SCREEN_PROPERTY_ATTACHED, &attached), "SCREEN_PROPERTY_ATTACHED"); if (attached) { SCREEN_API(screen_get_device_property_iv(device, SCREEN_PROPERTY_TYPE, &type), "SCREEN_PROPERTY_TYPE"); } qDebug() << "[GamePadHandler] handleScreenEvent() - Got device event for: " << device; int i; if (attached && (type == SCREEN_EVENT_GAMEPAD || type == SCREEN_EVENT_JOYSTICK)) { for (i = 0; i < MAX_CONTROLLERS; ++i) { if (!mControllers[i].handle) { mControllers[i].handle = device; loadController(&mControllers[i]); qDebug() << "[GamePadHandler] handleScreenEvent - Device connected, index: " << i; emit gamePadConnected(i); break; } } } else { for (i = 0; i < MAX_CONTROLLERS; ++i) { if (device == mControllers[i].handle) { initController(&mControllers[i], i); qDebug() << "[GamePadHandler] handleScreenEvent - Device disconnected, index: " << i; emit gamePadDisconnected(i); break; } } } break; } } } void GamePadHandler::stop() { qDebug() << "[GamePadHandler] stop() - start"; shouldRun = false; qDebug() << "[GamePadHandler] stop() - end"; }
[ "doturner@rim.com" ]
doturner@rim.com
084c08bfa3505a0f508698b4701296dd66d91338
dbbf11a647ad4c53a7d6e66786c9f10b34d48105
/Morepractices/李白打酒问题/dfs/main.cpp
fd6c4a84d54d1641232106ab1bd1c17579541377
[]
no_license
a1991221/AlgorithmTraining
62472044d4890fa3216e79ba30b97d167bc7aaca
70d227ad910cc3245ecb9b707794f4128a6eb769
refs/heads/master
2021-01-22T11:04:50.166088
2017-03-27T12:10:36
2017-03-27T12:10:36
92,669,623
1
0
null
2017-05-28T15:27:44
2017-05-28T15:27:44
null
GB18030
C++
false
false
1,149
cpp
//题目描述: //话说大诗人李白,一生好饮。幸好他从不开车。 //一天,他提着酒壶,从家里出来,酒壶中有酒2斗。他边走边唱: // //无事街上走,提壶去打酒。 //逢店加一倍,遇花喝一斗。 // //这一路上,他一共遇到店5次,遇到花10次,已知最后一次遇到的是花,他正好把酒喝光了。 // //请你计算李白遇到店和花的次序,可以把遇店记为a,遇花记为b。则:babaabbabbabbbb 就是合理的次序。 //像这样的答案一共有多少呢?请你计算出所有可能方案的个数(包含题目给出的)。 #include <iostream> using namespace std; int count=0; void dfs(int,int,int); int main() { dfs(0,0,2); cout<<count<<endl; return 0; } //遇到了多少店,遇到了多少花,还有多少酒 void dfs(int store,int flow,int acho) { if(store>5||flow>9)return; //注意不符合条件的情况的排除 if(store==5&&flow==9) { if(acho==1) { count++; return; } else return; } //每次或者遇到酒店或者遇到花,两种选择 dfs(store+1,flow,acho*2); dfs(store,flow+1,acho-1); }
[ "1790617178@qq.com" ]
1790617178@qq.com
a8e0c053baf11d6c052d8f562422a84b2bdda927
9ad4d7be4f4fe75e9640e9733c52496a8541ede0
/RoboterSoftware.ino
d27459baf87408a8dd876c9fd1fc51eb20bdc85e
[]
no_license
matyas1995/Adveisor_Software
f9212d2e8cb7f0a7f4c4024252e97cb0be47b4c1
e408c2329416beeb30dceb1b7c366081a55e1309
refs/heads/master
2021-01-22T12:07:28.012425
2015-06-16T20:29:28
2015-06-16T20:29:28
37,156,282
0
0
null
null
null
null
UTF-8
C++
false
false
550
ino
#include <AFMotor.h> #include <Arduino.h> #include "subroutinen.h" #include "hardware.h" void setup() { hardware_setup(); pinMode(43, OUTPUT); pinMode(37, OUTPUT); digitalWrite(43, HIGH); digitalWrite(37, LOW); //Serial.begin(9600); } void loop() { //drive_straight(100, LEFT_SIDE, 255); /*struct side_info Seite = get_side_info(RIGHT_SIDE); Serial.println(Seite.average_distance); Serial.println(Seite.angle); Serial.println(get_dist(sensor1)); Serial.println(get_dist(sensor2)); delay(1000);*/ drive(1, 255, 255); }
[ "matyas.mehn@hotmail.com" ]
matyas.mehn@hotmail.com
8e4a6dbfebd8cd9d1292e44525d6274c80d6f294
0b4cab24e8e2df80cd9a8889018cfd19a60e834c
/LibCore/Test/Coroutine_Test.cpp
2fbb68d62b87472a1c5afbee9e9b2e4c7a3e7bcc
[]
no_license
woopengcheng/LibCore
77b2afb917edb4f5fd7b173e88d39a7114030379
e3ebdc70f2429b9deafe387cecd505900ca7ac69
refs/heads/master
2021-06-13T04:05:29.411325
2017-06-05T05:26:39
2017-06-05T05:26:39
28,578,832
3
0
null
null
null
null
UTF-8
C++
false
false
1,332
cpp
#include "Coroutine/Coroutine.h" #include "UnitTest++/UnitTestPP.h" #include "CUtil/inc/CUtil.h" const INT64 CO_NUM = 5; static INT64 g_curIndex = 0; static INT64 g_randIndex = 0; static INT64 g_randIndexRecord[CO_NUM] = { 0 }; struct CoTask { void * pCoID; void * pArg; }; static void fiberProc(void * pArg) { CoTask * pTask = (CoTask *)pArg; { INT64 nIndex; while (1) { nIndex = (INT64)(pTask->pArg); CHECK_EQUAL(nIndex, g_curIndex); INT64 nPrevIndex = g_randIndex; g_randIndexRecord[nIndex] = g_randIndex; Coroutine::CoYieldCur(); CHECK_EQUAL(nPrevIndex, g_randIndexRecord[nIndex]); } } } TEST(Coroutine) { typedef std::map<INT64, CoTask*> MapCoTasksT; MapCoTasksT mapCoTasks; Coroutine::CoInit(); for (INT64 i = 0; i < CO_NUM; i++) { CoTask * pTask = new CoTask; pTask->pArg = (void*)(i); Coroutine::CoCreate(&(pTask->pCoID), fiberProc, pTask); mapCoTasks.insert(std::make_pair(i, pTask)); } for (INT64 j = 0; j < 2; ++j) { for (INT64 i = 0;i < CO_NUM;++i) { g_curIndex = i; g_randIndex = CUtil::random(); Coroutine::CoResume(mapCoTasks[i]->pCoID); } } for (INT64 i = 0; i < CO_NUM; i++) { CoTask * pTask = mapCoTasks[i]; if (pTask) { Coroutine::CoRelease(pTask->pCoID); } delete pTask; } mapCoTasks.clear(); Coroutine::CoCleanup(); }
[ "woopengcheng@163.com" ]
woopengcheng@163.com
a3683437624f19330f1205b950c1997cd362dba7
0fca9387a89ea06383526e34ab2d398f957cba16
/QuidditchApp/terrain.cpp
fe2a7478d5064d060c8cb307233787c83d532811
[]
no_license
yanjiasen4/ComputerGraphics
daabfc5359e9a4e28ac3b8f6da593cff5c1d8318
9434daeea5bad09804074d0e9a6cfb4f51b5120e
refs/heads/master
2021-01-10T01:22:13.504898
2016-01-14T07:16:17
2016-01-14T07:16:35
44,035,085
0
0
null
null
null
null
UTF-8
C++
false
false
330
cpp
#include "terrain.h" Terrain::Terrain() : Object() { } Terrain::Terrain(const char * filename) : Object() { loadFromObj(filename); } Terrain::~Terrain() { } void Terrain::setPos(GLfloat x, GLfloat y, GLfloat z) { position.setX(x); position.setY(y); position.setZ(z); } void Terrain::setAngle(GLfloat ag) { angle = ag; }
[ "1158076176@qq.com" ]
1158076176@qq.com
a686740a839d08e452a6bc13165633e8dac7e99e
53b7cde54d5ef6d92a97a92b725d8ae206fd41f8
/src/main.cpp
28647f7e77c757ea09ecf60264dddfe732289ba2
[ "MIT" ]
permissive
zahidaliayub/BitcoinLite
2f8b522fca564c735cbf4478fdda53edf2e05d5d
75c85ba737610ed893046aa455c91cfe8f8ed062
refs/heads/master
2021-04-03T06:24:47.022745
2017-09-16T22:41:48
2017-09-16T22:41:48
124,633,801
0
0
null
null
null
null
UTF-8
C++
false
false
134,254
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "alert.h" #include "checkpoints.h" #include "db.h" #include "txdb.h" #include "net.h" #include "init.h" #include "ui_interface.h" #include "kernel.h" #include "zerocoin/Zerocoin.h" #include <boost/algorithm/string/replace.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> using namespace std; using namespace boost; // // Global state // CCriticalSection cs_setpwalletRegistered; set<CWallet*> setpwalletRegistered; CCriticalSection cs_main; CTxMemPool mempool; unsigned int nTransactionsUpdated = 0; map<uint256, CBlockIndex*> mapBlockIndex; set<pair<COutPoint, unsigned int> > setStakeSeen; libzerocoin::Params* ZCParams; CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // "standard" scrypt target limit for proof of work, results with 0,000244140625 proof-of-work difficulty CBigNum bnProofOfStakeLimit(~uint256(0) >> 20); CBigNum bnProofOfWorkLimitTestNet(~uint256(0) >> 16); unsigned int nTargetSpacing = 1 * 60; // 1 minute unsigned int nStakeMinAge = 8 * 60 * 60; unsigned int nStakeMaxAge = -1; // unlimited unsigned int nModifierInterval = 10 * 60; // time to elapse before new modifier is computed int nCoinbaseMaturity = 20; CBlockIndex* pindexGenesisBlock = NULL; int nBestHeight = -1; uint256 nBestChainTrust = 0; uint256 nBestInvalidTrust = 0; uint256 hashBestChain = 0; CBlockIndex* pindexBest = NULL; int64_t nTimeBestReceived = 0; CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have map<uint256, CBlock*> mapOrphanBlocks; multimap<uint256, CBlock*> mapOrphanBlocksByPrev; set<pair<COutPoint, unsigned int> > setStakeSeenOrphan; map<uint256, CTransaction> mapOrphanTransactions; map<uint256, set<uint256> > mapOrphanTransactionsByPrev; // Constant stuff for coinbase transactions we create: CScript COINBASE_FLAGS; const string strMessageMagic = "bitcoinlite Signed Message:\n"; // Settings int64_t nTransactionFee = MIN_TX_FEE; int64_t nReserveBalance = 0; int64_t nMinimumInputValue = 0; extern enum Checkpoints::CPMode CheckpointsMode; ////////////////////////////////////////////////////////////////////////////// // // dispatching functions // // These functions dispatch to one or all registered wallets void RegisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.insert(pwalletIn); } } void UnregisterWallet(CWallet* pwalletIn) { { LOCK(cs_setpwalletRegistered); setpwalletRegistered.erase(pwalletIn); } } // check whether the passed transaction is from us bool static IsFromMe(CTransaction& tx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) return true; return false; } // get the wallet transaction with the given hash (if it exists) bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->GetTransaction(hashTx,wtx)) return true; return false; } // erases transaction with the given hash from all wallets void static EraseFromWallets(uint256 hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->EraseFromWallet(hash); } // make sure all wallets know about the given transaction, in the given block void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fConnect) { if (!fConnect) { // ppcoin: wallets need to refund inputs when disconnecting coinstake if (tx.IsCoinStake()) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) if (pwallet->IsFromMe(tx)) pwallet->DisableTransaction(tx); } return; } BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate); } // notify wallets about a new best chain void static SetBestChain(const CBlockLocator& loc) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->SetBestChain(loc); } // notify wallets about an updated transaction void static UpdatedTransaction(const uint256& hashTx) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->UpdatedTransaction(hashTx); } // dump all wallets void static PrintWallets(const CBlock& block) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->PrintWallet(block); } // notify wallets about an incoming inventory (for request counts) void static Inventory(const uint256& hash) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->Inventory(hash); } // ask wallets to resend their transactions void ResendWalletTransactions(bool fForce) { BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered) pwallet->ResendWalletTransactions(fForce); } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // bool AddOrphanTx(const CTransaction& tx) { uint256 hash = tx.GetHash(); if (mapOrphanTransactions.count(hash)) return false; // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 10,000 orphans, each of which is at most 5,000 bytes big is // at most 500 megabytes of orphans: size_t nSize = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (nSize > 5000) { printf("ignoring large orphan tx (size: %"PRIszu", hash: %s)\n", nSize, hash.ToString().substr(0,10).c_str()); return false; } mapOrphanTransactions[hash] = tx; BOOST_FOREACH(const CTxIn& txin, tx.vin) mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash); printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(), mapOrphanTransactions.size()); return true; } void static EraseOrphanTx(uint256 hash) { if (!mapOrphanTransactions.count(hash)) return; const CTransaction& tx = mapOrphanTransactions[hash]; BOOST_FOREACH(const CTxIn& txin, tx.vin) { mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash); if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty()) mapOrphanTransactionsByPrev.erase(txin.prevout.hash); } mapOrphanTransactions.erase(hash); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans) { unsigned int nEvicted = 0; while (mapOrphanTransactions.size() > nMaxOrphans) { // Evict a random orphan: uint256 randomhash = GetRandHash(); map<uint256, CTransaction>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } ////////////////////////////////////////////////////////////////////////////// // // CTransaction and CTxIndex // bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet) { SetNull(); if (!txdb.ReadTxIndex(prevout.hash, txindexRet)) return false; if (!ReadFromDisk(txindexRet.pos)) return false; if (prevout.n >= vout.size()) { SetNull(); return false; } return true; } bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout) { CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool CTransaction::ReadFromDisk(COutPoint prevout) { CTxDB txdb("r"); CTxIndex txindex; return ReadFromDisk(txdb, prevout, txindex); } bool IsStandardTx(const CTransaction& tx) { if (tx.nVersion > CTransaction::CURRENT_VERSION) return false; // Treat non-final transactions as non-standard to prevent a specific type // of double-spend attack, as well as DoS attacks. (if the transaction // can't be mined, the attacker isn't expending resources broadcasting it) // Basically we don't want to propagate transactions that can't included in // the next block. // // However, IsFinalTx() is confusing... Without arguments, it uses // chainActive.Height() to evaluate nLockTime; when a block is accepted, chainActive.Height() // is set to the value of nHeight in the block. However, when IsFinalTx() // is called within CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a transaction can // be part of the *next* block, we need to call IsFinalTx() with one more // than chainActive.Height(). // // Timestamps on the other hand don't get any special treatment, because we // can't know what timestamp the next block will have, and there aren't // timestamp applications where it matters. if (!IsFinalTx(tx, nBestHeight + 1)) { return false; } // nTime has different purpose from nLockTime but can be used in similar attacks if (tx.nTime > FutureDrift(GetAdjustedTime())) { return false; } // Extremely large transactions with lots of inputs can cost the network // almost as much to process as they cost the sender in fees, because // computing signature hashes is O(ninputs*txsize). Limiting transactions // to MAX_STANDARD_TX_SIZE mitigates CPU exhaustion attacks. unsigned int sz = tx.GetSerializeSize(SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz >= MAX_STANDARD_TX_SIZE) return false; BOOST_FOREACH(const CTxIn& txin, tx.vin) { // Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG // pay-to-script-hash, which is 3 ~80-byte signatures, 3 // ~65-byte public keys, plus a few script ops. if (txin.scriptSig.size() > 500) return false; if (!txin.scriptSig.IsPushOnly()) return false; if (fEnforceCanonical && !txin.scriptSig.HasCanonicalPushes()) { return false; } } unsigned int nDataOut = 0; txnouttype whichType; BOOST_FOREACH(const CTxOut& txout, tx.vout) { if (!::IsStandard(txout.scriptPubKey, whichType)) return false; if (whichType == TX_NULL_DATA) nDataOut++; if (txout.nValue == 0) return false; if (fEnforceCanonical && !txout.scriptPubKey.HasCanonicalPushes()) { return false; } } // only one OP_RETURN txout is permitted if (nDataOut > 1) { return false; } return true; } bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime) { AssertLockHeld(cs_main); // Time based nLockTime implemented in 0.1.6 if (tx.nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64_t)tx.nLockTime < ((int64_t)tx.nLockTime < LOCKTIME_THRESHOLD ? (int64_t)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, tx.vin) if (!txin.IsFinal()) return false; return true; } // // Check transaction inputs, and make sure any // pay-to-script-hash transactions are evaluating IsStandard scripts // // Why bother? To avoid denial-of-service attacks; an attacker // can submit a standard HASH... OP_EQUAL transaction, // which will get accepted into blocks. The redemption // script can be anything; an attacker could use a very // expensive-to-check-upon-redemption script like: // DUP CHECKSIG DROP ... repeated 100 times... OP_1 // bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const { if (IsCoinBase()) return true; // Coinbases don't use vin normally for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prev = GetOutputFor(vin[i], mapInputs); vector<vector<unsigned char> > vSolutions; txnouttype whichType; // get the scriptPubKey corresponding to this input: const CScript& prevScript = prev.scriptPubKey; if (!Solver(prevScript, whichType, vSolutions)) return false; int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions); if (nArgsExpected < 0) return false; // Transactions with extra stuff in their scriptSigs are // non-standard. Note that this EvalScript() call will // be quick, because if there are any operations // beside "push data" in the scriptSig the // IsStandard() call returns false vector<vector<unsigned char> > stack; if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0)) return false; if (whichType == TX_SCRIPTHASH) { if (stack.empty()) return false; CScript subscript(stack.back().begin(), stack.back().end()); vector<vector<unsigned char> > vSolutions2; txnouttype whichType2; if (!Solver(subscript, whichType2, vSolutions2)) return false; if (whichType2 == TX_SCRIPTHASH) return false; int tmpExpected; tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2); if (tmpExpected < 0) return false; nArgsExpected += tmpExpected; } if (stack.size() != (unsigned int)nArgsExpected) return false; } return true; } unsigned int CTransaction::GetLegacySigOpCount() const { unsigned int nSigOps = 0; BOOST_FOREACH(const CTxIn& txin, vin) { nSigOps += txin.scriptSig.GetSigOpCount(false); } BOOST_FOREACH(const CTxOut& txout, vout) { nSigOps += txout.scriptPubKey.GetSigOpCount(false); } return nSigOps; } int CMerkleTx::SetMerkleBranch(const CBlock* pblock) { AssertLockHeld(cs_main); CBlock blockTmp; if (pblock == NULL) { // Load the block this tx is in CTxIndex txindex; if (!CTxDB("r").ReadTxIndex(GetHash(), txindex)) return 0; if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos)) return 0; pblock = &blockTmp; } // Update the tx's hashBlock hashBlock = pblock->GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++) if (pblock->vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)pblock->vtx.size()) { vMerkleBranch.clear(); nIndex = -1; printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = pblock->GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return pindexBest->nHeight - pindex->nHeight + 1; } bool CTransaction::CheckTransaction() const { // Basic checks that don't depend on any context if (vin.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vin empty")); if (vout.empty()) return DoS(10, error("CTransaction::CheckTransaction() : vout empty")); // Size limits if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CTransaction::CheckTransaction() : size limits failed")); // Check for negative or overflow output values int64_t nValueOut = 0; for (unsigned int i = 0; i < vout.size(); i++) { const CTxOut& txout = vout[i]; if (txout.IsEmpty() && !IsCoinBase() && !IsCoinStake()) return DoS(100, error("CTransaction::CheckTransaction() : txout empty for user transaction")); if (txout.nValue < 0) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative")); if (txout.nValue > MAX_MONEY) return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high")); nValueOut += txout.nValue; if (!MoneyRange(nValueOut)) return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range")); } // Check for duplicate inputs set<COutPoint> vInOutPoints; BOOST_FOREACH(const CTxIn& txin, vin) { if (vInOutPoints.count(txin.prevout)) return false; vInOutPoints.insert(txin.prevout); } if (IsCoinBase()) { if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100) return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size is invalid")); } else { BOOST_FOREACH(const CTxIn& txin, vin) if (txin.prevout.IsNull()) return DoS(10, error("CTransaction::CheckTransaction() : prevout is null")); } return true; } int64_t CTransaction::GetMinFee(unsigned int nBlockSize, enum GetMinFee_mode mode, unsigned int nBytes) const { // Base fee is either MIN_TX_FEE or MIN_RELAY_TX_FEE int64_t nBaseFee = (mode == GMF_RELAY) ? MIN_RELAY_TX_FEE : MIN_TX_FEE; unsigned int nNewBlockSize = nBlockSize + nBytes; int64_t nMinFee = (1 + (int64_t)nBytes / 1000) * nBaseFee; // To limit dust spam, require MIN_TX_FEE/MIN_RELAY_TX_FEE if any output is less than 0.01 if (nMinFee < nBaseFee) { BOOST_FOREACH(const CTxOut& txout, vout) if (txout.nValue < CENT) nMinFee = nBaseFee; } // Raise the price as the block approaches full if (nBlockSize != 1 && nNewBlockSize >= MAX_BLOCK_SIZE_GEN/2) { if (nNewBlockSize >= MAX_BLOCK_SIZE_GEN) return MAX_MONEY; nMinFee *= MAX_BLOCK_SIZE_GEN / (MAX_BLOCK_SIZE_GEN - nNewBlockSize); } if (!MoneyRange(nMinFee)) nMinFee = MAX_MONEY; return nMinFee; } bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool* pfMissingInputs) { AssertLockHeld(cs_main); if (pfMissingInputs) *pfMissingInputs = false; if (!tx.CheckTransaction()) return error("AcceptToMemoryPool : CheckTransaction failed"); // Coinbase is only valid in a block, not as a loose transaction if (tx.IsCoinBase()) return tx.DoS(100, error("AcceptToMemoryPool : coinbase as individual tx")); // ppcoin: coinstake is also only valid in a block, not as a loose transaction if (tx.IsCoinStake()) return tx.DoS(100, error("AcceptToMemoryPool : coinstake as individual tx")); // Rather not work on nonstandard transactions (unless -testnet) if (!fTestNet && !IsStandardTx(tx)) return error("AcceptToMemoryPool : nonstandard transaction type"); // is it already in the memory pool? uint256 hash = tx.GetHash(); if (pool.exists(hash)) return false; // Check for conflicts with in-memory transactions CTransaction* ptxOld = NULL; { LOCK(pool.cs); // protect pool.mapNextTx for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (pool.mapNextTx.count(outpoint)) { // Disable replacement feature for now return false; // Allow replacing with a newer version of the same transaction if (i != 0) return false; ptxOld = pool.mapNextTx[outpoint].ptx; if (IsFinalTx(*ptxOld)) return false; if (!tx.IsNewerThan(*ptxOld)) return false; for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint outpoint = tx.vin[i].prevout; if (!pool.mapNextTx.count(outpoint) || pool.mapNextTx[outpoint].ptx != ptxOld) return false; } break; } } } { CTxDB txdb("r"); // do we already have it? if (txdb.ContainsTx(hash)) return false; MapPrevTx mapInputs; map<uint256, CTxIndex> mapUnused; bool fInvalid = false; if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) { if (fInvalid) return error("AcceptToMemoryPool : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str()); if (pfMissingInputs) *pfMissingInputs = true; return false; } // Check for non-standard pay-to-script-hash in inputs if (!tx.AreInputsStandard(mapInputs) && !fTestNet) return error("AcceptToMemoryPool : nonstandard transaction input"); // Note: if you modify this code to accept non-standard transactions, then // you should add code here to check that the transaction does a // reasonable number of ECDSA signature verifications. int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Don't accept it if it can't get into a block int64_t txMinFee = tx.GetMinFee(1000, GMF_RELAY, nSize); if (nFees < txMinFee) return error("AcceptToMemoryPool : not enough fees %s, %"PRId64" < %"PRId64, hash.ToString().c_str(), nFees, txMinFee); // Continuously rate-limit free transactions // This mitigates 'penny-flooding' -- sending thousands of free transactions just to // be annoying or make others' transactions take longer to confirm. if (nFees < MIN_RELAY_TX_FEE) { static CCriticalSection cs; static double dFreeCount; static int64_t nLastTime; int64_t nNow = GetTime(); { LOCK(pool.cs); // Use an exponentially decaying ~10-minute window: dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); nLastTime = nNow; // -limitfreerelay unit is thousand-bytes-per-minute // At default rate it would take over a month to fill 1GB if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx)) return error("AcceptToMemoryPool : free transaction rejected by rate limiter"); if (fDebug) printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); dFreeCount += nSize; } } // Check against previous transactions // This is done last to help prevent CPU exhaustion denial-of-service attacks. if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false)) { return error("AcceptToMemoryPool : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str()); } } // Store transaction in memory { LOCK(pool.cs); if (ptxOld) { printf("AcceptToMemoryPool : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str()); pool.remove(*ptxOld); } pool.addUnchecked(hash, tx); } ///// are we sure this is ok when loading transactions or restoring block txes // If updated, erase old tx from wallet if (ptxOld) EraseFromWallets(ptxOld->GetHash()); printf("AcceptToMemoryPool : accepted %s (poolsz %"PRIszu")\n", hash.ToString().substr(0,10).c_str(), pool.mapTx.size()); return true; } bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx) { // Add to memory pool without checking anything. Don't call this directly, // call AcceptToMemoryPool to properly check the transaction first. { mapTx[hash] = tx; for (unsigned int i = 0; i < tx.vin.size(); i++) mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i); nTransactionsUpdated++; } return true; } bool CTxMemPool::remove(const CTransaction &tx, bool fRecursive) { // Remove transaction from memory pool { LOCK(cs); uint256 hash = tx.GetHash(); if (mapTx.count(hash)) { if (fRecursive) { for (unsigned int i = 0; i < tx.vout.size(); i++) { std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i)); if (it != mapNextTx.end()) remove(*it->second.ptx, true); } } BOOST_FOREACH(const CTxIn& txin, tx.vin) mapNextTx.erase(txin.prevout); mapTx.erase(hash); nTransactionsUpdated++; } } return true; } bool CTxMemPool::removeConflicts(const CTransaction &tx) { // Remove transactions which depend on inputs of tx, recursively LOCK(cs); BOOST_FOREACH(const CTxIn &txin, tx.vin) { std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout); if (it != mapNextTx.end()) { const CTransaction &txConflict = *it->second.ptx; if (txConflict != tx) remove(txConflict, true); } } return true; } void CTxMemPool::clear() { LOCK(cs); mapTx.clear(); mapNextTx.clear(); ++nTransactionsUpdated; } void CTxMemPool::queryHashes(std::vector<uint256>& vtxid) { vtxid.clear(); LOCK(cs); vtxid.reserve(mapTx.size()); for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi) vtxid.push_back((*mi).first); } int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return pindexBest->nHeight - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool return nResult; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; return max(0, (nCoinbaseMaturity+0) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool() { return ::AcceptToMemoryPool(mempool, *this, NULL); } bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb) { { // Add previous supporting transactions first BOOST_FOREACH(CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!mempool.exists(hash) && !txdb.ContainsTx(hash)) tx.AcceptToMemoryPool(); } } return AcceptToMemoryPool(); } return false; } bool CWalletTx::AcceptWalletTransaction() { CTxDB txdb("r"); return AcceptWalletTransaction(txdb); } int CTxIndex::GetDepthInMainChain() const { // Read block header CBlock block; if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false)) return 0; // Find the block in the index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !pindex->IsInMainChain()) return 0; return 1 + nBestHeight - pindex->nHeight; } // Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock) { { LOCK(cs_main); { if (mempool.lookup(hash, tx)) { return true; } } CTxDB txdb("r"); CTxIndex txindex; if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex)) { CBlock block; if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) hashBlock = block.GetHash(); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////// // // CBlock and CBlockIndex // static CBlockIndex* pblockindexFBBHLast; CBlockIndex* FindBlockByHeight(int nHeight) { CBlockIndex *pblockindex; if (nHeight < nBestHeight / 2) pblockindex = pindexGenesisBlock; else pblockindex = pindexBest; if (pblockindexFBBHLast && abs(nHeight - pblockindex->nHeight) > abs(nHeight - pblockindexFBBHLast->nHeight)) pblockindex = pblockindexFBBHLast; while (pblockindex->nHeight > nHeight) pblockindex = pblockindex->pprev; while (pblockindex->nHeight < nHeight) pblockindex = pblockindex->pnext; pblockindexFBBHLast = pblockindex; return pblockindex; } bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions) { if (!fReadTransactions) { *this = pindex->GetBlockHeader(); return true; } if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions)) return false; if (GetHash() != pindex->GetBlockHash()) return error("CBlock::ReadFromDisk() : GetHash() doesn't match index"); return true; } uint256 static GetOrphanRoot(const CBlock* pblock) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblock->hashPrevBlock)) pblock = mapOrphanBlocks[pblock->hashPrevBlock]; return pblock->GetHash(); } // ppcoin: find block wanted by given orphan block uint256 WantedByOrphan(const CBlock* pblockOrphan) { // Work back to the first block in the orphan chain while (mapOrphanBlocks.count(pblockOrphan->hashPrevBlock)) pblockOrphan = mapOrphanBlocks[pblockOrphan->hashPrevBlock]; return pblockOrphan->hashPrevBlock; } // miner's coin base reward int64_t GetProofOfWorkReward(int64_t nFees) { int64_t nSubsidy = 150 * COIN; if(nBestHeight == 0) { nSubsidy = 15750000 * COIN; } if (fDebug && GetBoolArg("-printcreation")) printf("GetProofOfWorkReward() : create=%s nSubsidy=%"PRId64"\n", FormatMoney(nSubsidy).c_str(), nSubsidy); return nSubsidy + nFees; } // miner's coin stake reward based on coin age spent (coin-days) int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees) { int64_t nSubsidy = nCoinAge * COIN_YEAR_REWARD * 33 / (365 * 33 + 8); if (fDebug && GetBoolArg("-printcreation")) printf("GetProofOfStakeReward(): create=%s nCoinAge=%"PRId64"\n", FormatMoney(nSubsidy).c_str(), nCoinAge); return nSubsidy + nFees; } static const int64_t nTargetTimespan = 16 * 60; // 16 mins // // maximum nBits value could possible be required nTime after // unsigned int ComputeMaxBits(CBigNum bnTargetLimit, unsigned int nBase, int64_t nTime) { CBigNum bnResult; bnResult.SetCompact(nBase); bnResult *= 2; while (nTime > 0 && bnResult < bnTargetLimit) { // Maximum 200% adjustment per day... bnResult *= 2; nTime -= 24 * 60 * 60; } if (bnResult > bnTargetLimit) bnResult = bnTargetLimit; return bnResult.GetCompact(); } // // minimum amount of work that could possibly be required nTime after // minimum proof-of-work required was nBase // unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime) { return ComputeMaxBits(bnProofOfWorkLimit, nBase, nTime); } // // minimum amount of stake that could possibly be required nTime after // minimum proof-of-stake required was nBase // unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime) { return ComputeMaxBits(bnProofOfStakeLimit, nBase, nTime); } // ppcoin: find last block index up to pindex const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake) { while (pindex && pindex->pprev && (pindex->IsProofOfStake() != fProofOfStake)) pindex = pindex->pprev; return pindex; } static unsigned int GetNextTargetRequiredV1(const CBlockIndex* pindexLast, bool fProofOfStake) { CBigNum bnTargetLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit; if (pindexLast == NULL) return bnTargetLimit.GetCompact(); // genesis block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // first block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // second block int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing CBigNum bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t nInterval = nTargetTimespan / nTargetSpacing; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } static unsigned int GetNextTargetRequiredV2(const CBlockIndex* pindexLast, bool fProofOfStake) { CBigNum bnTargetLimit = fProofOfStake ? bnProofOfStakeLimit : bnProofOfWorkLimit; if (pindexLast == NULL) return bnTargetLimit.GetCompact(); // genesis block const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); if (pindexPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // first block const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); if (pindexPrevPrev->pprev == NULL) return bnTargetLimit.GetCompact(); // second block int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); if (nActualSpacing < 0) nActualSpacing = nTargetSpacing; // ppcoin: target change every block // ppcoin: retarget with exponential moving toward target spacing CBigNum bnNew; bnNew.SetCompact(pindexPrev->nBits); int64_t nInterval = nTargetTimespan / nTargetSpacing; bnNew *= ((nInterval - 1) * nTargetSpacing + nActualSpacing + nActualSpacing); bnNew /= ((nInterval + 1) * nTargetSpacing); if (bnNew <= 0 || bnNew > bnTargetLimit) bnNew = bnTargetLimit; return bnNew.GetCompact(); } unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake) { if (pindexLast->nHeight < 1200) return GetNextTargetRequiredV1(pindexLast, fProofOfStake); else return GetNextTargetRequiredV2(pindexLast, fProofOfStake); } bool CheckProofOfWork(uint256 hash, unsigned int nBits) { CBigNum bnTarget; bnTarget.SetCompact(nBits); // Check range if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit) return error("CheckProofOfWork() : nBits below minimum work"); // Check proof of work matches claimed amount if (hash > bnTarget.getuint256()) return error("CheckProofOfWork() : hash doesn't match nBits"); return true; } // Return maximum amount of blocks that other nodes claim to have int GetNumBlocksOfPeers() { return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate()); } bool IsInitialBlockDownload() { LOCK(cs_main); if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate()) return true; static int64_t nLastUpdate; static CBlockIndex* pindexLastBest; if (pindexBest != pindexLastBest) { pindexLastBest = pindexBest; nLastUpdate = GetTime(); } return (GetTime() - nLastUpdate < 15 && pindexBest->GetBlockTime() < GetTime() - 8 * 60 * 60); } void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->nChainTrust > nBestInvalidTrust) { nBestInvalidTrust = pindexNew->nChainTrust; CTxDB().WriteBestInvalidTrust(CBigNum(nBestInvalidTrust)); uiInterface.NotifyBlocksChanged(); } uint256 nBestInvalidBlockTrust = pindexNew->nChainTrust - pindexNew->pprev->nChainTrust; uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust; printf("InvalidChainFound: invalid block=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n", pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight, CBigNum(pindexNew->nChainTrust).ToString().c_str(), nBestInvalidBlockTrust.Get64(), DateTimeStrFormat("%x %H:%M:%S", pindexNew->GetBlockTime()).c_str()); printf("InvalidChainFound: current best=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(pindexBest->nChainTrust).ToString().c_str(), nBestBlockTrust.Get64(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); } void CBlock::UpdateTime(const CBlockIndex* pindexPrev) { nTime = max(GetBlockTime(), GetAdjustedTime()); } bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers if (!IsCoinBase()) { BOOST_FOREACH(const CTxIn& txin, vin) { COutPoint prevout = txin.prevout; // Get prev txindex from disk CTxIndex txindex; if (!txdb.ReadTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : ReadTxIndex failed"); if (prevout.n >= txindex.vSpent.size()) return error("DisconnectInputs() : prevout.n out of range"); // Mark outpoint as not spent txindex.vSpent[prevout.n].SetNull(); // Write back if (!txdb.UpdateTxIndex(prevout.hash, txindex)) return error("DisconnectInputs() : UpdateTxIndex failed"); } } // Remove transaction from index // This can fail if a duplicate of this transaction was in a chain that got // reorganized away. This is only possible if this transaction was completely // spent, so erasing it would be a no-op anyway. txdb.EraseTxIndex(*this); return true; } bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool, bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid) { // FetchInputs can return false either because we just haven't seen some inputs // (in which case the transaction should be stored as an orphan) // or because the transaction is malformed (in which case the transaction should // be dropped). If tx is definitely invalid, fInvalid will be set to true. fInvalid = false; if (IsCoinBase()) return true; // Coinbase transactions have no inputs to fetch. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; if (inputsRet.count(prevout.hash)) continue; // Got it already // Read txindex CTxIndex& txindex = inputsRet[prevout.hash].first; bool fFound = true; if ((fBlock || fMiner) && mapTestPool.count(prevout.hash)) { // Get txindex from current proposed changes txindex = mapTestPool.find(prevout.hash)->second; } else { // Read txindex from txdb fFound = txdb.ReadTxIndex(prevout.hash, txindex); } if (!fFound && (fBlock || fMiner)) return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); // Read txPrev CTransaction& txPrev = inputsRet[prevout.hash].second; if (!fFound || txindex.pos == CDiskTxPos(1,1,1)) { // Get prev tx from single transactions in memory if (!mempool.lookup(prevout.hash, txPrev)) return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); if (!fFound) txindex.vSpent.resize(txPrev.vout.size()); } else { // Get prev tx from disk if (!txPrev.ReadFromDisk(txindex.pos)) return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str()); } } // Make sure all prevout.n indexes are valid: for (unsigned int i = 0; i < vin.size(); i++) { const COutPoint prevout = vin[i].prevout; assert(inputsRet.count(prevout.hash) != 0); const CTxIndex& txindex = inputsRet[prevout.hash].first; const CTransaction& txPrev = inputsRet[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) { // Revisit this if/when transaction replacement is implemented and allows // adding inputs: fInvalid = true; return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); } } return true; } const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const { MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash); if (mi == inputs.end()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found"); const CTransaction& txPrev = (mi->second).second; if (input.prevout.n >= txPrev.vout.size()) throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range"); return txPrev.vout[input.prevout.n]; } int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; int64_t nResult = 0; for (unsigned int i = 0; i < vin.size(); i++) { nResult += GetOutputFor(vin[i], inputs).nValue; } return nResult; } unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const { if (IsCoinBase()) return 0; unsigned int nSigOps = 0; for (unsigned int i = 0; i < vin.size(); i++) { const CTxOut& prevout = GetOutputFor(vin[i], inputs); if (prevout.scriptPubKey.IsPayToScriptHash()) nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig); } return nSigOps; } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx, const CBlockIndex* pindexBlock, bool fBlock, bool fMiner) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain // fMiner is true when called from the internal bitcoin miner // ... both are false when called from CTransaction::AcceptToMemoryPool if (!IsCoinBase()) { int64_t nValueIn = 0; int64_t nFees = 0; for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size()) return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %"PRIszu" %"PRIszu" prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str())); // If prev is coinbase or coinstake, check that it's matured if (txPrev.IsCoinBase() || txPrev.IsCoinStake()) for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < nCoinbaseMaturity; pindex = pindex->pprev) if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile) return error("ConnectInputs() : tried to spend %s at depth %d", txPrev.IsCoinBase() ? "coinbase" : "coinstake", pindexBlock->nHeight - pindex->nHeight); // ppcoin: check transaction timestamp if (txPrev.nTime > nTime) return DoS(100, error("ConnectInputs() : transaction timestamp earlier than input transaction")); // Check for negative or overflow input values nValueIn += txPrev.vout[prevout.n].nValue; if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn)) return DoS(100, error("ConnectInputs() : txin values out of range")); } // The first loop above does all the inexpensive checks. // Only if ALL inputs pass do we perform expensive ECDSA signature checks. // Helps prevent CPU exhaustion attacks. for (unsigned int i = 0; i < vin.size(); i++) { COutPoint prevout = vin[i].prevout; assert(inputs.count(prevout.hash) > 0); CTxIndex& txindex = inputs[prevout.hash].first; CTransaction& txPrev = inputs[prevout.hash].second; // Check for conflicts (double-spend) // This doesn't trigger the DoS code on purpose; if it did, it would make it easier // for an attacker to attempt to split the network. if (!txindex.vSpent[prevout.n].IsNull()) return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str()); // Skip ECDSA signature verification when connecting blocks (fBlock=true) // before the last blockchain checkpoint. This is safe because block merkle hashes are // still computed and checked, and any change will be caught at the next checkpoint. if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate()))) { // Verify signature if (!VerifySignature(txPrev, *this, i, 0)) { return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str())); } } // Mark outpoints as spent txindex.vSpent[prevout.n] = posThisTx; // Write back if (fBlock || fMiner) { mapTestPool[prevout.hash] = txindex; } } if (!IsCoinStake()) { if (nValueIn < GetValueOut()) return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str())); // Tally transaction fees int64_t nTxFee = nValueIn - GetValueOut(); if (nTxFee < 0) return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str())); // enforce transaction fees for every block if (nTxFee < GetMinFee()) return fBlock? DoS(100, error("ConnectInputs() : %s not paying required fee=%s, paid=%s", GetHash().ToString().substr(0,10).c_str(), FormatMoney(GetMinFee()).c_str(), FormatMoney(nTxFee).c_str())) : false; nFees += nTxFee; if (!MoneyRange(nFees)) return DoS(100, error("ConnectInputs() : nFees out of range")); } } return true; } bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex) { // Disconnect in reverse order for (int i = vtx.size()-1; i >= 0; i--) if (!vtx[i].DisconnectInputs(txdb)) return false; // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = 0; if (!txdb.WriteBlockIndex(blockindexPrev)) return error("DisconnectBlock() : WriteBlockIndex failed"); } // ppcoin: clean up wallet after disconnecting coinstake BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, false, false); return true; } bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck) { // Check it again in case a previous version let a bad block in, but skip BlockSig checking if (!CheckBlock(!fJustCheck, !fJustCheck, false)) return false; //// issue here: it doesn't know the version unsigned int nTxPos; if (fJustCheck) // FetchInputs treats CDiskTxPos(1,1,1) as a special "refer to memorypool" indicator // Since we're just checking the block and not actually connecting it, it might not (and probably shouldn't) be on the disk to get the transaction from nTxPos = 1; else nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(vtx.size()); map<uint256, CTxIndex> mapQueuedChanges; int64_t nFees = 0; int64_t nValueIn = 0; int64_t nValueOut = 0; int64_t nStakeReward = 0; unsigned int nSigOps = 0; BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. // If such overwrites are allowed, coinbases and transactions depending upon those // can be duplicated to remove the ability to spend the first instance -- even after // being sent to another address. // See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information. // This logic is not necessary for memory pool transactions, as AcceptToMemoryPool // already refuses previously-known transaction ids entirely. // This rule was originally applied all blocks whose timestamp was after March 15, 2012, 0:00 UTC. // Now that the whole chain is irreversibly beyond that time it is applied to all blocks except the // two in the chain that violate it. This prevents exploiting the issue against nodes in their // initial block download. CTxIndex txindexOld; if (txdb.ReadTxIndex(hashTx, txindexOld)) { BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent) if (pos.IsNull()) return false; } nSigOps += tx.GetLegacySigOpCount(); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos); if (!fJustCheck) nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION); MapPrevTx mapInputs; if (tx.IsCoinBase()) nValueOut += tx.GetValueOut(); else { bool fInvalid; if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid)) return false; // Add in sigops done by pay-to-script-hash inputs; // this is to prevent a "rogue miner" from creating // an incredibly-expensive-to-validate block. nSigOps += tx.GetP2SHSigOpCount(mapInputs); if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("ConnectBlock() : too many sigops")); int64_t nTxValueIn = tx.GetValueIn(mapInputs); int64_t nTxValueOut = tx.GetValueOut(); nValueIn += nTxValueIn; nValueOut += nTxValueOut; if (!tx.IsCoinStake()) nFees += nTxValueIn - nTxValueOut; if (tx.IsCoinStake()) nStakeReward = nTxValueOut - nTxValueIn; if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } if (IsProofOfWork()) { int64_t nReward = GetProofOfWorkReward(nFees); // Check coinbase reward if (vtx[0].GetValueOut() > nReward) return DoS(50, error("ConnectBlock() : coinbase reward exceeded (actual=%"PRId64" vs calculated=%"PRId64")", vtx[0].GetValueOut(), nReward)); } if (IsProofOfStake()) { // ppcoin: coin stake tx earns reward instead of paying fee uint64_t nCoinAge; if (!vtx[1].GetCoinAge(txdb, nCoinAge)) return error("ConnectBlock() : %s unable to get coin age for coinstake", vtx[1].GetHash().ToString().substr(0,10).c_str()); int64_t nCalculatedStakeReward = GetProofOfStakeReward(nCoinAge, nFees); if (nStakeReward > nCalculatedStakeReward) return DoS(100, error("ConnectBlock() : coinstake pays too much(actual=%"PRId64" vs calculated=%"PRId64")", nStakeReward, nCalculatedStakeReward)); } // ppcoin: track money supply and mint amount info pindex->nMint = nValueOut - nValueIn + nFees; pindex->nMoneySupply = (pindex->pprev? pindex->pprev->nMoneySupply : 0) + nValueOut - nValueIn; if (!txdb.WriteBlockIndex(CDiskBlockIndex(pindex))) return error("Connect() : WriteBlockIndex for pindex failed"); if (fJustCheck) return true; // Write queued txindex changes for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi) { if (!txdb.UpdateTxIndex((*mi).first, (*mi).second)) return error("ConnectBlock() : UpdateTxIndex failed"); } // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) { CDiskBlockIndex blockindexPrev(pindex->pprev); blockindexPrev.hashNext = pindex->GetBlockHash(); if (!txdb.WriteBlockIndex(blockindexPrev)) return error("ConnectBlock() : WriteBlockIndex failed"); } // Watch for transactions paying to me BOOST_FOREACH(CTransaction& tx, vtx) SyncWithWallets(tx, this, true); return true; } bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew) { printf("REORGANIZE\n"); // Find the fork CBlockIndex* pfork = pindexBest; CBlockIndex* plonger = pindexNew; while (pfork != plonger) { while (plonger->nHeight > pfork->nHeight) if (!(plonger = plonger->pprev)) return error("Reorganize() : plonger->pprev is null"); if (pfork == plonger) break; if (!(pfork = pfork->pprev)) return error("Reorganize() : pfork->pprev is null"); } // List of what to disconnect vector<CBlockIndex*> vDisconnect; for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev) vDisconnect.push_back(pindex); // List of what to connect vector<CBlockIndex*> vConnect; for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev) vConnect.push_back(pindex); reverse(vConnect.begin(), vConnect.end()); printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str()); printf("REORGANIZE: Connect %"PRIszu" blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str()); // Disconnect shorter branch list<CTransaction> vResurrect; BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) { CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for disconnect failed"); if (!block.DisconnectBlock(txdb, pindex)) return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); // Queue memory transactions to resurrect. // We only do this for blocks after the last checkpoint (reorganisation before that // point should only happen with -reindex/-loadblock, or a misbehaving peer. BOOST_REVERSE_FOREACH(const CTransaction& tx, block.vtx) if (!(tx.IsCoinBase() || tx.IsCoinStake()) && pindex->nHeight > Checkpoints::GetTotalBlocksEstimate()) vResurrect.push_front(tx); } // Connect longer branch vector<CTransaction> vDelete; for (unsigned int i = 0; i < vConnect.size(); i++) { CBlockIndex* pindex = vConnect[i]; CBlock block; if (!block.ReadFromDisk(pindex)) return error("Reorganize() : ReadFromDisk for connect failed"); if (!block.ConnectBlock(txdb, pindex)) { // Invalid block return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str()); } // Queue memory transactions to delete BOOST_FOREACH(const CTransaction& tx, block.vtx) vDelete.push_back(tx); } if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash())) return error("Reorganize() : WriteHashBestChain failed"); // Make sure it's successfully written to disk before changing memory structure if (!txdb.TxnCommit()) return error("Reorganize() : TxnCommit failed"); // Disconnect shorter branch BOOST_FOREACH(CBlockIndex* pindex, vDisconnect) if (pindex->pprev) pindex->pprev->pnext = NULL; // Connect longer branch BOOST_FOREACH(CBlockIndex* pindex, vConnect) if (pindex->pprev) pindex->pprev->pnext = pindex; // Resurrect memory transactions that were in the disconnected branch BOOST_FOREACH(CTransaction& tx, vResurrect) AcceptToMemoryPool(mempool, tx, NULL); // Delete redundant memory transactions that are in the connected branch BOOST_FOREACH(CTransaction& tx, vDelete) { mempool.remove(tx); mempool.removeConflicts(tx); } printf("REORGANIZE: done\n"); return true; } // Called from inside SetBestChain: attaches a block to the new best chain being built bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew) { uint256 hash = GetHash(); // Adding to current best branch if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return false; } if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); // Add to current best branch pindexNew->pprev->pnext = pindexNew; // Delete redundant memory transactions BOOST_FOREACH(CTransaction& tx, vtx) mempool.remove(tx); return true; } bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew) { uint256 hash = GetHash(); if (!txdb.TxnBegin()) return error("SetBestChain() : TxnBegin failed"); if (pindexGenesisBlock == NULL && hash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)) { txdb.WriteHashBestChain(hash); if (!txdb.TxnCommit()) return error("SetBestChain() : TxnCommit failed"); pindexGenesisBlock = pindexNew; } else if (hashPrevBlock == hashBestChain) { if (!SetBestChainInner(txdb, pindexNew)) return error("SetBestChain() : SetBestChainInner failed"); } else { // the first block in the new chain that will cause it to become the new best chain CBlockIndex *pindexIntermediate = pindexNew; // list of blocks that need to be connected afterwards std::vector<CBlockIndex*> vpindexSecondary; // Reorganize is costly in terms of db load, as it works in a single db transaction. // Try to limit how much needs to be done inside while (pindexIntermediate->pprev && pindexIntermediate->pprev->nChainTrust > pindexBest->nChainTrust) { vpindexSecondary.push_back(pindexIntermediate); pindexIntermediate = pindexIntermediate->pprev; } if (!vpindexSecondary.empty()) printf("Postponing %"PRIszu" reconnects\n", vpindexSecondary.size()); // Switch to new best branch if (!Reorganize(txdb, pindexIntermediate)) { txdb.TxnAbort(); InvalidChainFound(pindexNew); return error("SetBestChain() : Reorganize failed"); } // Connect further blocks BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary) { CBlock block; if (!block.ReadFromDisk(pindex)) { printf("SetBestChain() : ReadFromDisk failed\n"); break; } if (!txdb.TxnBegin()) { printf("SetBestChain() : TxnBegin 2 failed\n"); break; } // errors now are not fatal, we still did a reorganisation to a new chain in a valid way if (!block.SetBestChainInner(txdb, pindex)) break; } } // Update best block in wallet (so we can detect restored wallets) bool fIsInitialDownload = IsInitialBlockDownload(); if (!fIsInitialDownload) { const CBlockLocator locator(pindexNew); ::SetBestChain(locator); } // New best block hashBestChain = hash; pindexBest = pindexNew; pblockindexFBBHLast = NULL; nBestHeight = pindexBest->nHeight; nBestChainTrust = pindexNew->nChainTrust; nTimeBestReceived = GetTime(); nTransactionsUpdated++; uint256 nBestBlockTrust = pindexBest->nHeight != 0 ? (pindexBest->nChainTrust - pindexBest->pprev->nChainTrust) : pindexBest->nChainTrust; printf("SetBestChain: new best=%s height=%d trust=%s blocktrust=%"PRId64" date=%s\n", hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(), nBestBlockTrust.Get64(), DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str()); // Check the version of the last 100 blocks to see if we need to upgrade: if (!fIsInitialDownload) { int nUpgraded = 0; const CBlockIndex* pindex = pindexBest; for (int i = 0; i < 100 && pindex != NULL; i++) { if (pindex->nVersion > CBlock::CURRENT_VERSION) ++nUpgraded; pindex = pindex->pprev; } if (nUpgraded > 0) printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION); if (nUpgraded > 100/2) // strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user: strMiscWarning = _("Warning: This version is obsolete, upgrade required!"); } std::string strCmd = GetArg("-blocknotify", ""); if (!fIsInitialDownload && !strCmd.empty()) { boost::replace_all(strCmd, "%s", hashBestChain.GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } return true; } // ppcoin: total coin age spent in transaction, in the unit of coin-days. // Only those coins meeting minimum age requirement counts. As those // transactions not in main chain are not currently indexed so we // might not find out about their coin age. Older transactions are // guaranteed to be in main chain by sync-checkpoint. This rule is // introduced to help nodes establish a consistent view of the coin // age (trust score) of competing branches. bool CTransaction::GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const { CBigNum bnCentSecond = 0; // coin age in the unit of cent-seconds nCoinAge = 0; if (IsCoinBase()) return true; BOOST_FOREACH(const CTxIn& txin, vin) { // First try finding the previous transaction in database CTransaction txPrev; CTxIndex txindex; if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex)) continue; // previous transaction not in main chain if (nTime < txPrev.nTime) return false; // Transaction timestamp violation // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) return false; // unable to read block of previous transaction if (block.GetBlockTime() + nStakeMinAge > nTime) continue; // only count coins meeting min age requirement int64_t nValueIn = txPrev.vout[txin.prevout.n].nValue; bnCentSecond += CBigNum(nValueIn) * (nTime-txPrev.nTime) / CENT; if (fDebug && GetBoolArg("-printcoinage")) printf("coin age nValueIn=%"PRId64" nTimeDiff=%d bnCentSecond=%s\n", nValueIn, nTime - txPrev.nTime, bnCentSecond.ToString().c_str()); } CBigNum bnCoinDay = bnCentSecond * CENT / COIN / (24 * 60 * 60); if (fDebug && GetBoolArg("-printcoinage")) printf("coin age bnCoinDay=%s\n", bnCoinDay.ToString().c_str()); nCoinAge = bnCoinDay.getuint64(); return true; } // ppcoin: total coin age spent in block, in the unit of coin-days. bool CBlock::GetCoinAge(uint64_t& nCoinAge) const { nCoinAge = 0; CTxDB txdb("r"); BOOST_FOREACH(const CTransaction& tx, vtx) { uint64_t nTxCoinAge; if (tx.GetCoinAge(txdb, nTxCoinAge)) nCoinAge += nTxCoinAge; else return false; } if (nCoinAge == 0) // block coin age minimum 1 coin-day nCoinAge = 1; if (fDebug && GetBoolArg("-printcoinage")) printf("block coin age total nCoinDays=%"PRId64"\n", nCoinAge); return true; } bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof) { // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str()); // Construct new block index object CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this); if (!pindexNew) return error("AddToBlockIndex() : new CBlockIndex failed"); pindexNew->phashBlock = &hash; map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock); if (miPrev != mapBlockIndex.end()) { pindexNew->pprev = (*miPrev).second; pindexNew->nHeight = pindexNew->pprev->nHeight + 1; } // ppcoin: compute chain trust score pindexNew->nChainTrust = (pindexNew->pprev ? pindexNew->pprev->nChainTrust : 0) + pindexNew->GetBlockTrust(); // ppcoin: compute stake entropy bit for stake modifier if (!pindexNew->SetStakeEntropyBit(GetStakeEntropyBit())) return error("AddToBlockIndex() : SetStakeEntropyBit() failed"); // Record proof hash value pindexNew->hashProof = hashProof; // ppcoin: compute stake modifier uint64_t nStakeModifier = 0; bool fGeneratedStakeModifier = false; if (!ComputeNextStakeModifier(pindexNew->pprev, nStakeModifier, fGeneratedStakeModifier)) return error("AddToBlockIndex() : ComputeNextStakeModifier() failed"); pindexNew->SetStakeModifier(nStakeModifier, fGeneratedStakeModifier); pindexNew->nStakeModifierChecksum = GetStakeModifierChecksum(pindexNew); if (!CheckStakeModifierCheckpoints(pindexNew->nHeight, pindexNew->nStakeModifierChecksum)) return error("AddToBlockIndex() : Rejected by stake modifier checkpoint height=%d, modifier=0x%016"PRIx64, pindexNew->nHeight, nStakeModifier); // Add to mapBlockIndex map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first; if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); pindexNew->phashBlock = &((*mi).first); // Write to disk block index CTxDB txdb; if (!txdb.TxnBegin()) return false; txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew)); if (!txdb.TxnCommit()) return false; LOCK(cs_main); // New best if (pindexNew->nChainTrust > nBestChainTrust) if (!SetBestChain(txdb, pindexNew)) return false; if (pindexNew == pindexBest) { // Notify UI to display prev block's coinbase if it was ours static uint256 hashPrevBestCoinBase; UpdatedTransaction(hashPrevBestCoinBase); hashPrevBestCoinBase = vtx[0].GetHash(); } uiInterface.NotifyBlocksChanged(); return true; } bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) const { // These are checks that are independent of context // that can be verified before saving an orphan block. // Size limits if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE) return DoS(100, error("CheckBlock() : size limits failed")); // Check proof of work matches claimed amount if (fCheckPOW && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits)) return DoS(50, error("CheckBlock() : proof of work failed")); // Check timestamp if (GetBlockTime() > FutureDrift(GetAdjustedTime())) return error("CheckBlock() : block timestamp too far in the future"); // First transaction must be coinbase, the rest must not be if (vtx.empty() || !vtx[0].IsCoinBase()) return DoS(100, error("CheckBlock() : first tx is not coinbase")); for (unsigned int i = 1; i < vtx.size(); i++) if (vtx[i].IsCoinBase()) return DoS(100, error("CheckBlock() : more than one coinbase")); // Check coinbase timestamp if (GetBlockTime() > FutureDrift((int64_t)vtx[0].nTime)) return DoS(50, error("CheckBlock() : coinbase timestamp is too early")); if (IsProofOfStake()) { // Coinbase output should be empty if proof-of-stake block if (vtx[0].vout.size() != 1 || !vtx[0].vout[0].IsEmpty()) return DoS(100, error("CheckBlock() : coinbase output not empty for proof-of-stake block")); // Second transaction must be coinstake, the rest must not be if (vtx.empty() || !vtx[1].IsCoinStake()) return DoS(100, error("CheckBlock() : second tx is not coinstake")); for (unsigned int i = 2; i < vtx.size(); i++) if (vtx[i].IsCoinStake()) return DoS(100, error("CheckBlock() : more than one coinstake")); // Check coinstake timestamp if (!CheckCoinStakeTimestamp(GetBlockTime(), (int64_t)vtx[1].nTime)) return DoS(50, error("CheckBlock() : coinstake timestamp violation nTimeBlock=%"PRId64" nTimeTx=%u", GetBlockTime(), vtx[1].nTime)); // NovaCoin: check proof-of-stake block signature if (fCheckSig && !CheckBlockSignature()) return DoS(100, error("CheckBlock() : bad proof-of-stake block signature")); } // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) { if (!tx.CheckTransaction()) return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed")); // ppcoin: check transaction timestamp if (GetBlockTime() < (int64_t)tx.nTime) return DoS(50, error("CheckBlock() : block timestamp earlier than transaction timestamp")); } // Check for duplicate txids. This is caught by ConnectInputs(), // but catching it earlier avoids a potential DoS attack: set<uint256> uniqueTx; BOOST_FOREACH(const CTransaction& tx, vtx) { uniqueTx.insert(tx.GetHash()); } if (uniqueTx.size() != vtx.size()) return DoS(100, error("CheckBlock() : duplicate transaction")); unsigned int nSigOps = 0; BOOST_FOREACH(const CTransaction& tx, vtx) { nSigOps += tx.GetLegacySigOpCount(); } if (nSigOps > MAX_BLOCK_SIGOPS) return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount")); // Check merkle root if (fCheckMerkleRoot && hashMerkleRoot != BuildMerkleTree()) return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch")); return true; } bool CBlock::AcceptBlock() { AssertLockHeld(cs_main); if (nVersion > CURRENT_VERSION) return DoS(100, error("AcceptBlock() : reject unknown block version %d", nVersion)); // Check for duplicate uint256 hash = GetHash(); if (mapBlockIndex.count(hash)) return error("AcceptBlock() : block already in mapBlockIndex"); // Get prev block index map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock); if (mi == mapBlockIndex.end()) return DoS(10, error("AcceptBlock() : prev block not found")); CBlockIndex* pindexPrev = (*mi).second; int nHeight = pindexPrev->nHeight+1; if (IsProofOfWork() && nHeight > LAST_POW_BLOCK) return DoS(100, error("AcceptBlock() : reject proof-of-work at height %d", nHeight)); // Check proof-of-work or proof-of-stake if (nBits != GetNextTargetRequired(pindexPrev, IsProofOfStake())) return DoS(100, error("AcceptBlock() : incorrect %s", IsProofOfWork() ? "proof-of-work" : "proof-of-stake")); // Check timestamp against prev if (GetBlockTime() <= pindexPrev->GetPastTimeLimit() || FutureDrift(GetBlockTime()) < pindexPrev->GetBlockTime()) return error("AcceptBlock() : block's timestamp is too early"); // Check that all transactions are finalized BOOST_FOREACH(const CTransaction& tx, vtx) if (!IsFinalTx(tx, nHeight, GetBlockTime())) return DoS(10, error("AcceptBlock() : contains a non-final transaction")); // Check that the block chain matches the known block chain up to a checkpoint if (!Checkpoints::CheckHardened(nHeight, hash)) return DoS(100, error("AcceptBlock() : rejected by hardened checkpoint lock-in at %d", nHeight)); uint256 hashProof; // Verify hash target and signature of coinstake tx if (IsProofOfStake()) { uint256 targetProofOfStake; if (!CheckProofOfStake(vtx[1], nBits, hashProof, targetProofOfStake)) { printf("WARNING: AcceptBlock(): check proof-of-stake failed for block %s\n", hash.ToString().c_str()); return false; // do not error here as we expect this during initial block download } } // PoW is checked in CheckBlock() if (IsProofOfWork()) { hashProof = GetPoWHash(); } bool cpSatisfies = Checkpoints::CheckSync(hash, pindexPrev); // Check that the block satisfies synchronized checkpoint if (CheckpointsMode == Checkpoints::STRICT && !cpSatisfies) return error("AcceptBlock() : rejected by synchronized checkpoint"); if (CheckpointsMode == Checkpoints::ADVISORY && !cpSatisfies) strMiscWarning = _("WARNING: syncronized checkpoint violation detected, but skipped!"); // Enforce rule that the coinbase starts with serialized block height CScript expect = CScript() << nHeight; if (vtx[0].vin[0].scriptSig.size() < expect.size() || !std::equal(expect.begin(), expect.end(), vtx[0].vin[0].scriptSig.begin())) return DoS(100, error("AcceptBlock() : block height mismatch in coinbase")); // Write block to history file if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION))) return error("AcceptBlock() : out of disk space"); unsigned int nFile = -1; unsigned int nBlockPos = 0; if (!WriteToDisk(nFile, nBlockPos)) return error("AcceptBlock() : WriteToDisk failed"); if (!AddToBlockIndex(nFile, nBlockPos, hashProof)) return error("AcceptBlock() : AddToBlockIndex failed"); // Relay inventory, but don't relay old inventory during initial block download int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate(); if (hashBestChain == hash) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate)) pnode->PushInventory(CInv(MSG_BLOCK, hash)); } // ppcoin: check pending sync-checkpoint Checkpoints::AcceptPendingSyncCheckpoint(); return true; } uint256 CBlockIndex::GetBlockTrust() const { CBigNum bnTarget; bnTarget.SetCompact(nBits); if (bnTarget <= 0) return 0; return ((CBigNum(1)<<256) / (bnTarget+1)).getuint256(); } bool CBlockIndex::IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck) { unsigned int nFound = 0; for (unsigned int i = 0; i < nToCheck && nFound < nRequired && pstart != NULL; i++) { if (pstart->nVersion >= minVersion) ++nFound; pstart = pstart->pprev; } return (nFound >= nRequired); } bool ProcessBlock(CNode* pfrom, CBlock* pblock) { AssertLockHeld(cs_main); // Check for duplicate uint256 hash = pblock->GetHash(); if (mapBlockIndex.count(hash)) return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str()); if (mapOrphanBlocks.count(hash)) return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake // Limited duplicity on stake: prevents block flood attack // Duplicate stake allowed only when there is orphan child block if (pblock->IsProofOfStake() && setStakeSeen.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); // Preliminary checks if (!pblock->CheckBlock()) return error("ProcessBlock() : CheckBlock FAILED"); CBlockIndex* pcheckpoint = Checkpoints::GetLastSyncCheckpoint(); if (pcheckpoint && pblock->hashPrevBlock != hashBestChain && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) { // Extra checks to prevent "fill up memory by spamming with bogus blocks" int64_t deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime; CBigNum bnNewBlock; bnNewBlock.SetCompact(pblock->nBits); CBigNum bnRequired; if (pblock->IsProofOfStake()) bnRequired.SetCompact(ComputeMinStake(GetLastBlockIndex(pcheckpoint, true)->nBits, deltaTime, pblock->nTime)); else bnRequired.SetCompact(ComputeMinWork(GetLastBlockIndex(pcheckpoint, false)->nBits, deltaTime)); if (bnNewBlock > bnRequired) { if (pfrom) pfrom->Misbehaving(100); return error("ProcessBlock() : block with too little %s", pblock->IsProofOfStake()? "proof-of-stake" : "proof-of-work"); } } // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); // If don't already have its previous block, shunt it off to holding area until we get it if (!mapBlockIndex.count(pblock->hashPrevBlock)) { printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str()); // ppcoin: check proof-of-stake if (pblock->IsProofOfStake()) { // Limited duplicity on stake: prevents block flood attack // Duplicate stake allowed only when there is orphan child block if (setStakeSeenOrphan.count(pblock->GetProofOfStake()) && !mapOrphanBlocksByPrev.count(hash) && !Checkpoints::WantedByPendingSyncCheckpoint(hash)) return error("ProcessBlock() : duplicate proof-of-stake (%s, %d) for orphan block %s", pblock->GetProofOfStake().first.ToString().c_str(), pblock->GetProofOfStake().second, hash.ToString().c_str()); else setStakeSeenOrphan.insert(pblock->GetProofOfStake()); } CBlock* pblock2 = new CBlock(*pblock); mapOrphanBlocks.insert(make_pair(hash, pblock2)); mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2)); // Ask this guy to fill in what we're missing if (pfrom) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2)); // ppcoin: getblocks may not obtain the ancestor block rejected // earlier by duplicate-stake check so we ask for it again directly if (!IsInitialBlockDownload()) pfrom->AskFor(CInv(MSG_BLOCK, WantedByOrphan(pblock2))); } return true; } // Store to disk if (!pblock->AcceptBlock()) return error("ProcessBlock() : AcceptBlock FAILED"); // Recursively process any orphan blocks that depended on this one vector<uint256> vWorkQueue; vWorkQueue.push_back(hash); for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev); mi != mapOrphanBlocksByPrev.upper_bound(hashPrev); ++mi) { CBlock* pblockOrphan = (*mi).second; if (pblockOrphan->AcceptBlock()) vWorkQueue.push_back(pblockOrphan->GetHash()); mapOrphanBlocks.erase(pblockOrphan->GetHash()); setStakeSeenOrphan.erase(pblockOrphan->GetProofOfStake()); delete pblockOrphan; } mapOrphanBlocksByPrev.erase(hashPrev); } printf("ProcessBlock: ACCEPTED\n"); // ppcoin: if responsible for sync-checkpoint send it if (pfrom && !CSyncCheckpoint::strMasterPrivKey.empty()) Checkpoints::SendSyncCheckpoint(Checkpoints::AutoSelectSyncCheckpoint()); return true; } // novacoin: attempt to generate suitable proof-of-stake bool CBlock::SignBlock(CWallet& wallet, int64_t nFees) { // if we are trying to sign // something except proof-of-stake block template if (!vtx[0].vout[0].IsEmpty()) return false; // if we are trying to sign // a complete proof-of-stake block if (IsProofOfStake()) return true; static int64_t nLastCoinStakeSearchTime = GetAdjustedTime(); // startup timestamp CKey key; CTransaction txCoinStake; int64_t nSearchTime = txCoinStake.nTime; // search to current time if (nSearchTime > nLastCoinStakeSearchTime) { if (wallet.CreateCoinStake(wallet, nBits, nSearchTime-nLastCoinStakeSearchTime, nFees, txCoinStake, key)) { if (txCoinStake.nTime >= max(pindexBest->GetPastTimeLimit()+1, PastDrift(pindexBest->GetBlockTime()))) { // make sure coinstake would meet timestamp protocol // as it would be the same as the block timestamp vtx[0].nTime = nTime = txCoinStake.nTime; nTime = max(pindexBest->GetPastTimeLimit()+1, GetMaxTransactionTime()); nTime = max(GetBlockTime(), PastDrift(pindexBest->GetBlockTime())); // we have to make sure that we have no future timestamps in // our transactions set for (vector<CTransaction>::iterator it = vtx.begin(); it != vtx.end();) if (it->nTime > nTime) { it = vtx.erase(it); } else { ++it; } vtx.insert(vtx.begin() + 1, txCoinStake); hashMerkleRoot = BuildMerkleTree(); // append a signature to our block return key.Sign(GetHash(), vchBlockSig); } } nLastCoinStakeSearchInterval = nSearchTime - nLastCoinStakeSearchTime; nLastCoinStakeSearchTime = nSearchTime; } return false; } bool CBlock::CheckBlockSignature() const { if (IsProofOfWork()) return vchBlockSig.empty(); vector<valtype> vSolutions; txnouttype whichType; const CTxOut& txout = vtx[1].vout[1]; if (!Solver(txout.scriptPubKey, whichType, vSolutions)) return false; if (whichType == TX_PUBKEY) { valtype& vchPubKey = vSolutions[0]; CKey key; if (!key.SetPubKey(vchPubKey)) return false; if (vchBlockSig.empty()) return false; return key.Verify(GetHash(), vchBlockSig); } return false; } bool CheckDiskSpace(uint64_t nAdditionalBytes) { uint64_t nFreeBytesAvailable = filesystem::space(GetDataDir()).available; // Check for nMinDiskSpace bytes (currently 50MB) if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes) { fShutdown = true; string strMessage = _("Warning: Disk space is low!"); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "bitcoinlite", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL); StartShutdown(); return false; } return true; } static filesystem::path BlockFilePath(unsigned int nFile) { string strBlockFn = strprintf("blk%04u.dat", nFile); return GetDataDir() / strBlockFn; } FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode) { if ((nFile < 1) || (nFile == (unsigned int) -1)) return NULL; FILE* file = fopen(BlockFilePath(nFile).string().c_str(), pszMode); if (!file) return NULL; if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w')) { if (fseek(file, nBlockPos, SEEK_SET) != 0) { fclose(file); return NULL; } } return file; } static unsigned int nCurrentBlockFile = 1; FILE* AppendBlockFile(unsigned int& nFileRet) { nFileRet = 0; while (true) { FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab"); if (!file) return NULL; if (fseek(file, 0, SEEK_END) != 0) return NULL; // FAT32 file size max 4GB, fseek and ftell max 2GB, so we must stay under 2GB if (ftell(file) < (long)(0x7F000000 - MAX_SIZE)) { nFileRet = nCurrentBlockFile; return file; } fclose(file); nCurrentBlockFile++; } } bool LoadBlockIndex(bool fAllowNew) { LOCK(cs_main); CBigNum bnTrustedModulus; if (fTestNet) { pchMessageStart[0] = 0x6e; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xf9; pchMessageStart[3] = 0xfd; bnTrustedModulus.SetHex("f0d14cf72623dacfe738d0892b599be0f31052239cddd95a3f25101c801dc990453b38c9434efe3f372db39a32c2bb44cbaea72d62c8931fa785b0ec44531308df3e46069be5573e49bb29f4d479bfc3d162f57a5965db03810be7636da265bfced9c01a6b0296c77910ebdc8016f70174f0f18a57b3b971ac43a934c6aedbc5c866764a3622b5b7e3f9832b8b3f133c849dbcc0396588abcd1e41048555746e4823fb8aba5b3d23692c6857fccce733d6bb6ec1d5ea0afafecea14a0f6f798b6b27f77dc989c557795cc39a0940ef6bb29a7fc84135193a55bcfc2f01dd73efad1b69f45a55198bd0e6bef4d338e452f6a420f1ae2b1167b923f76633ab6e55"); bnProofOfWorkLimit = bnProofOfWorkLimitTestNet; // 16 bits PoW target limit for testnet nStakeMinAge = 1 * 60 * 60; // test net min age is 1 hour nCoinbaseMaturity = 10; // test maturity is 10 blocks } else { bnTrustedModulus.SetHex("d01f952e1090a5a72a3eda261083256596ccc192935ae1454c2bafd03b09e6ed11811be9f3a69f5783bbbced8c6a0c56621f42c2d19087416facf2f13cc7ed7159d1c5253119612b8449f0c7f54248e382d30ecab1928dbf075c5425dcaee1a819aa13550e0f3227b8c685b14e0eae094d65d8a610a6f49fff8145259d1187e4c6a472fa5868b2b67f957cb74b787f4311dbc13c97a2ca13acdb876ff506ebecbb904548c267d68868e07a32cd9ed461fbc2f920e9940e7788fed2e4817f274df5839c2196c80abe5c486df39795186d7bc86314ae1e8342f3c884b158b4b05b4302754bf351477d35370bad6639b2195d30006b77bf3dbb28b848fd9ecff5662bf39dde0c974e83af51b0d3d642d43834827b8c3b189065514636b8f2a59c42ba9b4fc4975d4827a5d89617a3873e4b377b4d559ad165748632bd928439cfbc5a8ef49bc2220e0b15fb0aa302367d5e99e379a961c1bc8cf89825da5525e3c8f14d7d8acca2fa9c133a2176ae69874d8b1d38b26b9c694e211018005a97b40848681b9dd38feb2de141626fb82591aad20dc629b2b6421cef1227809551a0e4e943ab99841939877f18f2d9c0addc93cf672e26b02ed94da3e6d329e8ac8f3736eebbf37bb1a21e5aadf04ee8e3b542f876aa88b2adf2608bd86329b7f7a56fd0dc1c40b48188731d11082aea360c62a0840c2db3dad7178fd7e359317ae081"); } #if 0 // Set up the Zerocoin Params object ZCParams = new libzerocoin::Params(bnTrustedModulus); #endif // // Load block index // CTxDB txdb("cr+"); if (!txdb.LoadBlockIndex()) return false; // // Init with genesis block // if (mapBlockIndex.empty()) { if (!fAllowNew) return false; // Genesis block // MainNet: //CBlock(hash=000001faef25dec4fbcf906e6242621df2c183bf232f263d0ba5b101911e4563, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1502785513, nBits=1e0fffff, nNonce=164482, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1502785513, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 // TestNet: //CBlock(hash=0000724595fb3b9609d441cbfb9577615c292abf07d996d3edabc48de843642d, ver=1, hashPrevBlock=0000000000000000000000000000000000000000000000000000000000000000, hashMerkleRoot=12630d16a97f24b287c8c2594dda5fb98c9e6c70fc61d44191931ea2aa08dc90, nTime=1502785513, nBits=1f00ffff, nNonce=216178, vtx=1, vchBlockSig=) // Coinbase(hash=12630d16a9, nTime=1502785513, ver=1, vin.size=1, vout.size=1, nLockTime=0) // CTxIn(COutPoint(0000000000, 4294967295), coinbase 00012a24323020466562203230313420426974636f696e2041544d7320636f6d6520746f20555341) // CTxOut(empty) // vMerkleTree: 12630d16a9 const char* pszTimestamp = "August 2017"; CTransaction txNew; txNew.nTime = 1502785513; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 0 << CBigNum(42) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].SetEmpty(); CBlock block; block.vtx.push_back(txNew); block.hashPrevBlock = 0; block.hashMerkleRoot = block.BuildMerkleTree(); block.nVersion = 1; block.nTime = 1502785513; block.nBits = bnProofOfWorkLimit.GetCompact(); block.nNonce = !fTestNet ? 3320926 : 3320926; if (true && (block.GetHash() != hashGenesisBlock)) { // This will figure out a valid hash and Nonce if you're // creating a different genesis block: uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256(); while (block.GetHash() > hashTarget) { ++block.nNonce; if (block.nNonce == 0) { printf("NONCE WRAPPED, incrementing time"); ++block.nTime; } } } //// debug print block.print(); printf("block.GetHash() == %s\n", block.GetHash().ToString().c_str()); printf("block.hashMerkleRoot == %s\n", block.hashMerkleRoot.ToString().c_str()); printf("block.nTime = %u \n", block.nTime); printf("block.nNonce = %u \n", block.nNonce); assert(block.hashMerkleRoot == uint256("0x08fa7ecd85a65701cecae89569b7c2b7b53d1ffbd24b45a1692e8998d6205d9f")); assert(block.GetHash() == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet)); assert(block.CheckBlock()); // Start new block file unsigned int nFile; unsigned int nBlockPos; if (!block.WriteToDisk(nFile, nBlockPos)) return error("LoadBlockIndex() : writing genesis block to disk failed"); if (!block.AddToBlockIndex(nFile, nBlockPos, hashGenesisBlock)) return error("LoadBlockIndex() : genesis block not accepted"); // ppcoin: initialize synchronized checkpoint if (!Checkpoints::WriteSyncCheckpoint((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))) return error("LoadBlockIndex() : failed to init sync checkpoint"); } string strPubKey = ""; // if checkpoint master key changed must reset sync-checkpoint if (!txdb.ReadCheckpointPubKey(strPubKey) || strPubKey != CSyncCheckpoint::strMasterPubKey) { // write checkpoint master key to db txdb.TxnBegin(); if (!txdb.WriteCheckpointPubKey(CSyncCheckpoint::strMasterPubKey)) return error("LoadBlockIndex() : failed to write new checkpoint master key to db"); if (!txdb.TxnCommit()) return error("LoadBlockIndex() : failed to commit new checkpoint master key to db"); if ((!fTestNet) && !Checkpoints::ResetSyncCheckpoint()) return error("LoadBlockIndex() : failed to reset sync-checkpoint"); } return true; } void PrintBlockTree() { AssertLockHeld(cs_main); // pre-compute tree structure map<CBlockIndex*, vector<CBlockIndex*> > mapNext; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { CBlockIndex* pindex = (*mi).second; mapNext[pindex->pprev].push_back(pindex); // test //while (rand() % 3 == 0) // mapNext[pindex->pprev].push_back(pindex); } vector<pair<int, CBlockIndex*> > vStack; vStack.push_back(make_pair(0, pindexGenesisBlock)); int nPrevCol = 0; while (!vStack.empty()) { int nCol = vStack.back().first; CBlockIndex* pindex = vStack.back().second; vStack.pop_back(); // print split or gap if (nCol > nPrevCol) { for (int i = 0; i < nCol-1; i++) printf("| "); printf("|\\\n"); } else if (nCol < nPrevCol) { for (int i = 0; i < nCol; i++) printf("| "); printf("|\n"); } nPrevCol = nCol; // print columns for (int i = 0; i < nCol; i++) printf("| "); // print item CBlock block; block.ReadFromDisk(pindex); printf("%d (%u,%u) %s %08x %s mint %7s tx %"PRIszu"", pindex->nHeight, pindex->nFile, pindex->nBlockPos, block.GetHash().ToString().c_str(), block.nBits, DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(), FormatMoney(pindex->nMint).c_str(), block.vtx.size()); PrintWallets(block); // put the main time-chain first vector<CBlockIndex*>& vNext = mapNext[pindex]; for (unsigned int i = 0; i < vNext.size(); i++) { if (vNext[i]->pnext) { swap(vNext[0], vNext[i]); break; } } // iterate children for (unsigned int i = 0; i < vNext.size(); i++) vStack.push_back(make_pair(nCol+i, vNext[i])); } } bool LoadExternalBlockFile(FILE* fileIn) { int64_t nStart = GetTimeMillis(); int nLoaded = 0; { LOCK(cs_main); try { CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION); unsigned int nPos = 0; while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown) { unsigned char pchData[65536]; do { fseek(blkdat, nPos, SEEK_SET); int nRead = fread(pchData, 1, sizeof(pchData), blkdat); if (nRead <= 8) { nPos = (unsigned int)-1; break; } void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart)); if (nFind) { if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0) { nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart); break; } nPos += ((unsigned char*)nFind - pchData) + 1; } else nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1; } while(!fRequestShutdown); if (nPos == (unsigned int)-1) break; fseek(blkdat, nPos, SEEK_SET); unsigned int nSize; blkdat >> nSize; if (nSize > 0 && nSize <= MAX_BLOCK_SIZE) { CBlock block; blkdat >> block; if (ProcessBlock(NULL,&block)) { nLoaded++; nPos += 4 + nSize; } } } } catch (std::exception &e) { printf("%s() : Deserialize or I/O error caught during load\n", __PRETTY_FUNCTION__); } } printf("Loaded %i blocks from external file in %"PRId64"ms\n", nLoaded, GetTimeMillis() - nStart); return nLoaded > 0; } ////////////////////////////////////////////////////////////////////////////// // // CAlert // extern map<uint256, CAlert> mapAlerts; extern CCriticalSection cs_mapAlerts; string GetWarnings(string strFor) { int nPriority = 0; string strStatusBar; string strRPC; if (GetBoolArg("-testsafemode")) strRPC = "test"; // Misc warnings like out of disk space and clock is wrong if (strMiscWarning != "") { nPriority = 1000; strStatusBar = strMiscWarning; } // if detected invalid checkpoint enter safe mode if (Checkpoints::hashInvalidCheckpoint != 0) { nPriority = 3000; strStatusBar = strRPC = _("WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers."); } // Alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) { const CAlert& alert = item.second; if (alert.AppliesToMe() && alert.nPriority > nPriority) { nPriority = alert.nPriority; strStatusBar = alert.strStatusBar; if (nPriority > 1000) strRPC = strStatusBar; } } } if (strFor == "statusbar") return strStatusBar; else if (strFor == "rpc") return strRPC; assert(!"GetWarnings() : invalid parameter"); return "error"; } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(CTxDB& txdb, const CInv& inv) { switch (inv.type) { case MSG_TX: { bool txInMap = false; txInMap = mempool.exists(inv.hash); return txInMap || mapOrphanTransactions.count(inv.hash) || txdb.ContainsTx(inv.hash); } case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); } // Don't know what it is, just say we already got one return true; } // The message start string is designed to be unlikely to occur in normal data. // The characters are rarely used upper ASCII, not valid as UTF-8, and produce // a large 4-byte int at any alignment. unsigned char pchMessageStart[4] = { 0x06, 0xc6, 0x1f, 0xa7 }; bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv) { static map<CService, CPubKey> mapReuseKey; RandAddSeedPerfmon(); if (fDebug) printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size()); if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0) { printf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (strCommand == "version") { // Each connection can only send one version message if (pfrom->nVersion != 0) { pfrom->Misbehaving(1); return false; } int64_t nTime; CAddress addrMe; CAddress addrFrom; uint64_t nNonce = 1; vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe; if (pfrom->nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion); pfrom->fDisconnect = true; return false; } if (pfrom->nVersion == 10300) pfrom->nVersion = 300; if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) vRecv >> pfrom->strSubVer; if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; if (pfrom->fInbound && addrMe.IsRoutable()) { pfrom->addrLocal = addrMe; SeenLocal(addrMe); } // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str()); pfrom->fDisconnect = true; return true; } // record my external IP reported by peer if (addrFrom.IsRoutable() && addrMe.IsRoutable()) addrSeenByPeer = addrMe; // Be shy and don't send version until we hear if (pfrom->fInbound) pfrom->PushVersion(); pfrom->fClient = !(pfrom->nServices & NODE_NETWORK); if (GetBoolArg("-synctime", true)) AddTimeData(pfrom->addr, nTime); // Change version pfrom->PushMessage("verack"); pfrom->ssSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Advertise our address if (!fNoListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr); if (addr.IsRoutable()) pfrom->PushAddress(addr); } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000) { pfrom->PushMessage("getaddr"); pfrom->fGetAddr = true; } addrman.Good(pfrom->addr); } else { if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom) { addrman.Add(addrFrom, addrFrom); addrman.Good(addrFrom); } } // Ask the first connected node for block updates static int nAskedForBlocks = 0; if (!pfrom->fClient && !pfrom->fOneShot && (pfrom->nStartingHeight > (nBestHeight - 144)) && (pfrom->nVersion < NOBLKS_VERSION_START || pfrom->nVersion >= NOBLKS_VERSION_END) && (nAskedForBlocks < 1 || vNodes.size() <= 1)) { nAskedForBlocks++; pfrom->PushGetBlocks(pindexBest, uint256(0)); } // Relay alerts { LOCK(cs_mapAlerts); BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts) item.second.RelayTo(pfrom); } // Relay sync-checkpoint { LOCK(Checkpoints::cs_hashSyncCheckpoint); if (!Checkpoints::checkpointMessage.IsNull()) Checkpoints::checkpointMessage.RelayTo(pfrom); } pfrom->fSuccessfullyConnected = true; printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str()); cPeerBlockCounts.input(pfrom->nStartingHeight); // ppcoin: ask for pending sync-checkpoint if any if (!IsInitialBlockDownload()) Checkpoints::AskForPendingSyncCheckpoint(pfrom); } else if (pfrom->nVersion == 0) { // Must have a version message before anything else pfrom->Misbehaving(1); return false; } else if (strCommand == "verack") { pfrom->SetRecvVersion(min(pfrom->nVersion, PROTOCOL_VERSION)); } else if (strCommand == "addr") { vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000) return true; if (vAddr.size() > 1000) { pfrom->Misbehaving(20); return error("message addr size() = %"PRIszu"", vAddr.size()); } // Store the new addresses vector<CAddress> vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; BOOST_FOREACH(CAddress& addr, vAddr) { if (fShutdown) return true; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { // Relay to a limited number of other nodes { LOCK(cs_vNodes); // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the setAddrKnowns of the chosen nodes prevent repeats static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint64_t hashAddr = addr.GetHash(); uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60)); hashRand = Hash(BEGIN(hashRand), END(hashRand)); multimap<uint256, CNode*> mapMix; BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->nVersion < CADDR_TIME_VERSION) continue; unsigned int nPointer; memcpy(&nPointer, &pnode, sizeof(nPointer)); uint256 hashKey = hashRand ^ nPointer; hashKey = Hash(BEGIN(hashKey), END(hashKey)); mapMix.insert(make_pair(hashKey, pnode)); } int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi) ((*mi).second)->PushAddress(addr); } } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; } else if (strCommand == "inv") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { pfrom->Misbehaving(20); return error("message inv size() = %"PRIszu"", vInv.size()); } // find last block in inv vector unsigned int nLastBlock = (unsigned int)(-1); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) { nLastBlock = vInv.size() - 1 - nInv; break; } } CTxDB txdb("r"); for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) { const CInv &inv = vInv[nInv]; if (fShutdown) return true; pfrom->AddInventoryKnown(inv); bool fAlreadyHave = AlreadyHave(txdb, inv); if (fDebug) printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new"); if (!fAlreadyHave) pfrom->AskFor(inv); else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) { pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash])); } else if (nInv == nLastBlock) { // In case we are on a very long side-chain, it is possible that we already have // the last block in an inv bundle sent in response to getblocks. Try to detect // this situation and push another getblocks to continue. pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0)); if (fDebug) printf("force request: %s\n", inv.ToString().c_str()); } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getdata") { vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { pfrom->Misbehaving(20); return error("message getdata size() = %"PRIszu"", vInv.size()); } if (fDebugNet || (vInv.size() != 1)) printf("received getdata (%"PRIszu" invsz)\n", vInv.size()); BOOST_FOREACH(const CInv& inv, vInv) { if (fShutdown) return true; if (fDebugNet || (vInv.size() == 1)) printf("received getdata for: %s\n", inv.ToString().c_str()); if (inv.type == MSG_BLOCK) { // Send block from disk map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash); if (mi != mapBlockIndex.end()) { CBlock block; block.ReadFromDisk((*mi).second); pfrom->PushMessage("block", block); // Trigger them to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // ppcoin: send latest proof-of-work block to allow the // download node to accept as orphan (proof-of-stake // block might be rejected by stake connection check) vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, GetLastBlockIndex(pindexBest, false)->GetBlockHash())); pfrom->PushMessage("inv", vInv); pfrom->hashContinue = 0; } } } else if (inv.IsKnownType()) { // Send stream from relay memory bool pushed = false; { LOCK(cs_mapRelay); map<CInv, CDataStream>::iterator mi = mapRelay.find(inv); if (mi != mapRelay.end()) { pfrom->PushMessage(inv.GetCommand(), (*mi).second); pushed = true; } } if (!pushed && inv.type == MSG_TX) { CTransaction tx; if (mempool.lookup(inv.hash, tx)) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); ss << tx; pfrom->PushMessage("tx", ss); } } } // Track requests for our stuff Inventory(inv.hash); } } else if (strCommand == "getblocks") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; // Find the last block the caller has in the main chain CBlockIndex* pindex = locator.GetBlockIndex(); // Send the rest of the chain if (pindex) pindex = pindex->pnext; int nLimit = 500; printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit); for (; pindex; pindex = pindex->pnext) { if (pindex->GetBlockHash() == hashStop) { printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); // ppcoin: tell downloading node about the latest block if it's // without risk being rejected due to stake connection check if (hashStop != hashBestChain && pindex->GetBlockTime() + nStakeMinAge > pindexBest->GetBlockTime()) pfrom->PushInventory(CInv(MSG_BLOCK, hashBestChain)); break; } pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll make them // getblocks the next batch of inventory. printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } } else if (strCommand == "checkpoint") { CSyncCheckpoint checkpoint; vRecv >> checkpoint; if (checkpoint.ProcessSyncCheckpoint(pfrom)) { // Relay pfrom->hashCheckpointKnown = checkpoint.hashCheckpoint; LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) checkpoint.RelayTo(pnode); } } else if (strCommand == "getheaders") { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; CBlockIndex* pindex = NULL; if (locator.IsNull()) { // If locator is null, return the hashStop block map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop); if (mi == mapBlockIndex.end()) return true; pindex = (*mi).second; } else { // Find the last block the caller has in the main chain pindex = locator.GetBlockIndex(); if (pindex) pindex = pindex->pnext; } vector<CBlock> vHeaders; int nLimit = 2000; printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str()); for (; pindex; pindex = pindex->pnext) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } pfrom->PushMessage("headers", vHeaders); } else if (strCommand == "tx") { vector<uint256> vWorkQueue; vector<uint256> vEraseQueue; CTransaction tx; vRecv >> tx; CInv inv(MSG_TX, tx.GetHash()); pfrom->AddInventoryKnown(inv); bool fMissingInputs = false; if (AcceptToMemoryPool(mempool, tx, &fMissingInputs)) { SyncWithWallets(tx, NULL, true); RelayTransaction(tx, inv.hash); mapAlreadyAskedFor.erase(inv); vWorkQueue.push_back(inv.hash); vEraseQueue.push_back(inv.hash); // Recursively process any orphan transactions that depended on this one for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hashPrev = vWorkQueue[i]; for (set<uint256>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin(); mi != mapOrphanTransactionsByPrev[hashPrev].end(); ++mi) { const uint256& orphanTxHash = *mi; CTransaction& orphanTx = mapOrphanTransactions[orphanTxHash]; bool fMissingInputs2 = false; if (AcceptToMemoryPool(mempool, orphanTx, &fMissingInputs2)) { printf(" accepted orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str()); SyncWithWallets(tx, NULL, true); RelayTransaction(orphanTx, orphanTxHash); mapAlreadyAskedFor.erase(CInv(MSG_TX, orphanTxHash)); vWorkQueue.push_back(orphanTxHash); vEraseQueue.push_back(orphanTxHash); } else if (!fMissingInputs2) { // invalid orphan vEraseQueue.push_back(orphanTxHash); printf(" removed invalid orphan tx %s\n", orphanTxHash.ToString().substr(0,10).c_str()); } } } BOOST_FOREACH(uint256 hash, vEraseQueue) EraseOrphanTx(hash); } else if (fMissingInputs) { AddOrphanTx(tx); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS); if (nEvicted > 0) printf("mapOrphan overflow, removed %u tx\n", nEvicted); } if (tx.nDoS) pfrom->Misbehaving(tx.nDoS); } else if (strCommand == "block") { CBlock block; vRecv >> block; uint256 hashBlock = block.GetHash(); printf("received block %s\n", hashBlock.ToString().substr(0,20).c_str()); CInv inv(MSG_BLOCK, hashBlock); pfrom->AddInventoryKnown(inv); if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); } else if (strCommand == "getaddr") { // Don't return addresses older than nCutOff timestamp int64_t nCutOff = GetTime() - (nNodeLifespan * 24 * 60 * 60); pfrom->vAddrToSend.clear(); vector<CAddress> vAddr = addrman.GetAddr(); BOOST_FOREACH(const CAddress &addr, vAddr) if(addr.nTime > nCutOff) pfrom->PushAddress(addr); } else if (strCommand == "mempool") { std::vector<uint256> vtxid; mempool.queryHashes(vtxid); vector<CInv> vInv; for (unsigned int i = 0; i < vtxid.size(); i++) { CInv inv(MSG_TX, vtxid[i]); vInv.push_back(inv); if (i == (MAX_INV_SZ - 1)) break; } if (vInv.size() > 0) pfrom->PushMessage("inv", vInv); } else if (strCommand == "checkorder") { uint256 hashReply; vRecv >> hashReply; if (!GetBoolArg("-allowreceivebyip")) { pfrom->PushMessage("reply", hashReply, (int)2, string("")); return true; } CWalletTx order; vRecv >> order; /// we have a chance to check the order here // Keep giving the same key to the same ip until they use it if (!mapReuseKey.count(pfrom->addr)) pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true); // Send back approval of order and pubkey to use CScript scriptPubKey; scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG; pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey); } else if (strCommand == "reply") { uint256 hashReply; vRecv >> hashReply; CRequestTracker tracker; { LOCK(pfrom->cs_mapRequests); map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply); if (mi != pfrom->mapRequests.end()) { tracker = (*mi).second; pfrom->mapRequests.erase(mi); } } if (!tracker.IsNull()) tracker.fn(tracker.param1, vRecv); } else if (strCommand == "ping") { if (pfrom->nVersion > BIP0031_VERSION) { uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. pfrom->PushMessage("pong", nonce); } } else if (strCommand == "alert") { CAlert alert; vRecv >> alert; uint256 alertHash = alert.GetHash(); if (pfrom->setKnown.count(alertHash) == 0) { if (alert.ProcessAlert()) { // Relay pfrom->setKnown.insert(alertHash); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) alert.RelayTo(pnode); } } else { // Small DoS penalty so peers that send us lots of // duplicate/expired/invalid-signature/whatever alerts // eventually get banned. // This isn't a Misbehaving(100) (immediate ban) because the // peer might be an older or different implementation with // a different signature key, etc. pfrom->Misbehaving(10); } } } else { // Ignore unknown commands for extensibility } // Update the last seen time for this node's address if (pfrom->fNetworkNode) if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping") AddressCurrentlyConnected(pfrom->addr); return true; } // requires LOCK(cs_vRecvMsg) bool ProcessMessages(CNode* pfrom) { //if (fDebug) // printf("ProcessMessages(%zu messages)\n", pfrom->vRecvMsg.size()); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // bool fOk = true; std::deque<CNetMessage>::iterator it = pfrom->vRecvMsg.begin(); while (!pfrom->fDisconnect && it != pfrom->vRecvMsg.end()) { // Don't bother if send buffer is too full to respond anyway if (pfrom->nSendSize >= SendBufferSize()) break; // get next message CNetMessage& msg = *it; //if (fDebug) // printf("ProcessMessages(message %u msgsz, %zu bytes, complete:%s)\n", // msg.hdr.nMessageSize, msg.vRecv.size(), // msg.complete() ? "Y" : "N"); // end, if an incomplete message is found if (!msg.complete()) break; // at this point, any failure means we can delete the current message it++; // Scan for message start if (memcmp(msg.hdr.pchMessageStart, pchMessageStart, sizeof(pchMessageStart)) != 0) { printf("\n\nPROCESSMESSAGE: INVALID MESSAGESTART\n\n"); fOk = false; break; } // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid()) { printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str()); continue; } string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; // Checksum CDataStream& vRecv = msg.vRecv; uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) { printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n", strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum); continue; } // Process message bool fRet = false; try { { LOCK(cs_main); fRet = ProcessMessage(pfrom, strCommand, vRecv); } if (fShutdown) break; } catch (std::ios_base::failure& e) { if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from over-long size printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what()); } else { PrintExceptionContinue(&e, "ProcessMessages()"); } } catch (std::exception& e) { PrintExceptionContinue(&e, "ProcessMessages()"); } catch (...) { PrintExceptionContinue(NULL, "ProcessMessages()"); } if (!fRet) printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize); } // In case the connection got shut down, its receive buffer was wiped if (!pfrom->fDisconnect) pfrom->vRecvMsg.erase(pfrom->vRecvMsg.begin(), it); return fOk; } bool SendMessages(CNode* pto, bool fSendTrickle) { TRY_LOCK(cs_main, lockMain); if (lockMain) { // Don't send anything until we get their version message if (pto->nVersion == 0) return true; // Keep-alive ping. We send a nonce of zero because we don't use it anywhere // right now. if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSendMsg.empty()) { uint64_t nonce = 0; if (pto->nVersion > BIP0031_VERSION) pto->PushMessage("ping", nonce); else pto->PushMessage("ping"); } // Resend wallet transactions that haven't gotten in a block yet ResendWalletTransactions(); // Address refresh broadcast static int64_t nLastRebroadcast; if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60)) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { // Periodically clear setAddrKnown to allow refresh broadcasts if (nLastRebroadcast) pnode->setAddrKnown.clear(); // Rebroadcast our address if (!fNoListen) { CAddress addr = GetLocalAddress(&pnode->addr); if (addr.IsRoutable()) pnode->PushAddress(addr); } } } nLastRebroadcast = GetTime(); } // // Message: addr // if (fSendTrickle) { vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend) { // returns true if wasn't already contained in the set if (pto->setAddrKnown.insert(addr).second) { vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { pto->PushMessage("addr", vAddr); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) pto->PushMessage("addr", vAddr); } // // Message: inventory // vector<CInv> vInv; vector<CInv> vInvWait; { LOCK(pto->cs_inventory); vInv.reserve(pto->vInventoryToSend.size()); vInvWait.reserve(pto->vInventoryToSend.size()); BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend) { if (pto->setInventoryKnown.count(inv)) continue; // trickle out tx inv to protect privacy if (inv.type == MSG_TX && !fSendTrickle) { // 1/4 of tx invs blast to all immediately static uint256 hashSalt; if (hashSalt == 0) hashSalt = GetRandHash(); uint256 hashRand = inv.hash ^ hashSalt; hashRand = Hash(BEGIN(hashRand), END(hashRand)); bool fTrickleWait = ((hashRand & 3) != 0); // always trickle our own transactions if (!fTrickleWait) { CWalletTx wtx; if (GetTransaction(inv.hash, wtx)) if (wtx.fFromMe) fTrickleWait = true; } if (fTrickleWait) { vInvWait.push_back(inv); continue; } } // returns true if wasn't already contained in the set if (pto->setInventoryKnown.insert(inv).second) { vInv.push_back(inv); if (vInv.size() >= 1000) { pto->PushMessage("inv", vInv); vInv.clear(); } } } pto->vInventoryToSend = vInvWait; } if (!vInv.empty()) pto->PushMessage("inv", vInv); // // Message: getdata // vector<CInv> vGetData; int64_t nNow = GetTime() * 1000000; CTxDB txdb("r"); while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow) { const CInv& inv = (*pto->mapAskFor.begin()).second; if (!AlreadyHave(txdb, inv)) { if (fDebugNet) printf("sending getdata: %s\n", inv.ToString().c_str()); vGetData.push_back(inv); if (vGetData.size() >= 1000) { pto->PushMessage("getdata", vGetData); vGetData.clear(); } mapAlreadyAskedFor[inv] = nNow; } pto->mapAskFor.erase(pto->mapAskFor.begin()); } if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); } return true; }
[ "31115677+bitcoin-lite@users.noreply.github.com" ]
31115677+bitcoin-lite@users.noreply.github.com
baf22539cf8bf8b9896389c3344e54f3f596ea3e
b200b00772505ae4d3bf510a60c5a17576c0c34c
/Uncapacitated-Facility-Location/Uncap-Facility-Location/src/main.cpp
2ee53b25defefd6546f58ffb347523c740a03bc9
[]
no_license
joaogsma/Graph-Theory
ddb609d45c173a3f462d42bffaa149c21a1e5228
360a5304a1fe86fec3204a4dc26f68f97373087d
refs/heads/master
2020-09-15T22:27:38.294383
2016-11-29T16:23:35
2016-11-29T16:23:35
67,560,002
0
0
null
null
null
null
ISO-8859-1
C++
false
false
38,324
cpp
#ifndef __GUARD_MAIN__ #define __GUARD_MAIN__ #include <algorithm> #include <climits> #include <chrono> #include <fstream> #include <iterator> #include <map> #include <numeric> #include <vector> #include <random> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "gurobi_c++.h" using std::accumulate; using std::back_inserter; using std::chrono::steady_clock; using std::chrono::duration_cast; using std::copy; using std::cout; using std::endl; using std::ifstream; using std::istream; using std::make_pair; using std::map; using std::min_element; using std::mt19937; using std::ofstream; using std::ostream; using std::pair; using std::random_device; using std::runtime_error; using std::set; using std::string; using std::stringstream; using std::transform; using std::uniform_int_distribution; using std::vector; // ============================================================================ // ============================== CONFIGURATIONS ============================== // ============================================================================ static const int min_distance = 1; static const int max_distance = 10; static const int min_client_demand = 10; static const int max_client_demand = 50; static const int min_opening_cost = 80; static const int max_opening_cost = 300; static const int min_clients_per_facility = 5; static const int max_clients_per_facility = 10; static const int min_facilities_per_client = 3; static const int max_facilities_per_client = 4; static const int artificial_inf = std::max(1000 * max_distance, 99999); // ============================================================================ static random_device rd; static mt19937 mt_engine(rd()); static GRBEnv env; // ============================================================================ // ============================== LINEAR PROGRAM ============================== // ============================================================================ // ============= CLASS DECLARATION ============= class Linear_Program { friend int main(); public: Linear_Program(const vector<double>& objective_vector, const vector<vector<double> >& constraints, const vector<char>& constraint_types) : objective_vector(objective_vector), constraints(constraints), constraint_types(constraint_types) { validate(); } void solve(vector<double>& solution, double& value, bool do_maximize = true, bool relaxed = false) const; private: vector<double> objective_vector; // Coefficients of the objective function to be maximized vector<vector<double> > constraints; // A matrix of the linear program in standard form vector<char> constraint_types; // b vector of the linear program in standard form void validate() const; void gurobi_solve(vector<double>& solution, double& max, bool do_maximize, bool relaxed) const; }; // ============================================= // ============= CLASS DEFINITION ============= void Linear_Program::validate() const { const string& error_message = "Invalid Linear Programming configuration"; // Check if either vector is empty if (objective_vector.empty() || constraints.empty() || constraint_types.empty()) throw runtime_error(error_message); /* Check if objective vector of coefficients contains coefficients for all variables */ if (objective_vector.size() != constraints[0].size() - 1) throw runtime_error(error_message); // Check if there is one type value for each equation if (constraint_types.size() != constraints.size()) throw runtime_error(error_message); // Check if all constraints contain coefficients for all variables vector<double>::size_type eq_size = constraints[0].size(); for (vector<double>::size_type i = 1; i < constraints.size(); ++i) if (constraints[i].size() != eq_size) throw runtime_error(error_message); } void Linear_Program::solve(vector<double>& solution, double& value, bool do_maximize, bool relaxed) const { gurobi_solve(solution, value, do_maximize, relaxed); } void Linear_Program::gurobi_solve(vector<double>& solution, double& value, bool do_maximize, bool relaxed) const { size_t num_variables = objective_vector.size(); // Create the gurobi model GRBModel model(env); // Add the variables to the model vector<GRBVar> variables; for (size_t i = 0; i < num_variables; ++i) { variables.push_back(model.addVar(0., (relaxed ? GRB_INFINITY : 1.), 0., GRB_CONTINUOUS)); } // Add the objective function to the model GRBLinExpr obj_expr; obj_expr.addTerms(&objective_vector[0], &variables[0], num_variables); model.setObjective(obj_expr, (do_maximize ? GRB_MAXIMIZE : GRB_MINIMIZE)); // Add the constraints to the model for (size_t i = 0; i < constraints.size(); ++i) { GRBLinExpr expr; expr.addTerms(&constraints[i][0], &variables[0], num_variables); model.addConstr(expr, (constraint_types[i] == '=' ? GRB_EQUAL : GRB_LESS_EQUAL), constraints[i].back()); } model.optimize(); solution.clear(); for (size_t i = 0; i < num_variables; ++i) solution.push_back(variables[i].get(GRB_DoubleAttr_X)); value = model.get(GRB_DoubleAttr_ObjVal); } // ============================================ // ============================================================================ // ============================================================================ // ================================== GRAPH =================================== // ============================================================================ struct Graph { vector<vector<int> > distance_cost; vector<int> facility_costs; vector<int> client_demands; int facilities() const { return (int)facility_costs.size(); } int clients() const { return (int)client_demands.size(); } }; Graph random_graph(int num_facilities, int num_clients) { Graph problem; // Initially populate the distances with 0 distances problem.distance_cost = vector<vector<int> >(num_facilities, vector<int>(num_clients, 0)); uniform_int_distribution<int> fac_cost_dist(min_opening_cost, max_opening_cost); // Initialize the opening costs with random values from [min_opening_cost, max_opening_cost] for (int facility = 0; facility < num_facilities; ++facility) problem.facility_costs.push_back(fac_cost_dist(mt_engine)); uniform_int_distribution<int> client_dem_dist(min_client_demand, max_client_demand); // Initialize the client demands with random values from [min_client_demand, max_client_demand] for (int client = 0; client < num_clients; ++client) problem.client_demands.push_back(client_dem_dist(mt_engine)); // Assign the minimum number of facilities for each client for (int client = 0; client < num_clients; ++client) { int has_facilities = 0; vector<int> available; for (int i = 0; i < num_facilities; ++i) available.push_back(i); while (has_facilities < min_facilities_per_client) { if (available.empty()) // Failed, try again { std::cout << "Failed to generate random graph, retrying..." << std::endl; return random_graph(num_facilities, num_clients); } uniform_int_distribution<int> facility_dist(0, available.size() - 1); int facility_idx = facility_dist(mt_engine); int facility = available[facility_idx]; // Random facility // Remove facility from the available vector available.erase(available.begin() + facility_idx); /* Mark this client as supported by the facility if it does not already support the maximum number of clients */ if (accumulate(problem.distance_cost[facility].begin(), problem.distance_cost[facility].end(), 0) < max_clients_per_facility) { problem.distance_cost[facility][client] = 1; has_facilities++; } } } // Assign the (remaining) minimum number of clients to each facility for (int facility = 0; facility < num_facilities; ++facility) { int has_clients = accumulate(problem.distance_cost[facility].begin(), problem.distance_cost[facility].end(), 0); vector<int> available; for (int i = 0; i < num_clients; ++i) available.push_back(i); while (has_clients < min_clients_per_facility) { if (available.empty()) // Failed, try again { std::cout << "Failed to generate random graph, retrying..." << std::endl; return random_graph(num_facilities, num_clients); } uniform_int_distribution<int> client_dist(0, available.size() - 1); int client_idx = client_dist(mt_engine); int client = available[client_idx]; // Remove client from the available vector available.erase(available.begin() + client_idx); int client_facilities = 0; for (int i = 0; i < num_facilities; ++i) client_facilities += problem.distance_cost[i][client]; /* Support client with this facility if the client is not yet supported by the max number of facilities */ if (client_facilities < max_facilities_per_client) { problem.distance_cost[facility][client] = 1; has_clients++; } } } int possible_extra_conections = (max_facilities_per_client - min_facilities_per_client) * (max_clients_per_facility - min_clients_per_facility); uniform_int_distribution<int> extra_dist(0, possible_extra_conections); int extra_connections = extra_dist(mt_engine); // Vector containing all positions connections not already chosen vector<pair<int, int> > possible_connections; // Fill the possible_conections vector for (int facility = 0; facility < num_facilities; ++facility) for (int client = 0; client < num_clients; ++client) if (problem.distance_cost[facility][client] == 0) possible_connections.push_back(make_pair(facility, client)); for (int i = 0; i < extra_connections && !possible_connections.empty(); ++i) { uniform_int_distribution<int> position_dist(0, possible_connections.size() - 1); int idx = position_dist(mt_engine); int facility = possible_connections[idx].first; int client = possible_connections[idx].second; possible_connections.erase(possible_connections.begin() + idx); // Count the number of facilities associated with this client int has_facilities = 0; for (int i = 0; i < num_facilities; ++i) has_facilities += problem.distance_cost[i][client]; // Client cannot have more facilities if (has_facilities == max_facilities_per_client) continue; // Count the number of clients associated with this facility int has_clients = 0; for (int i = 0; i < num_clients; ++i) has_clients += problem.distance_cost[facility][i]; // Facility cannot have more clients if (has_clients == max_clients_per_facility) continue; problem.distance_cost[facility][client] = 1; } uniform_int_distribution<int> distance_dist(min_distance, max_distance); // Substitute all 0s by "infinite" (no connection) and all 1s by a random distance for (int facility = 0; facility < num_facilities; ++facility) { for (int client = 0; client < num_clients; ++client) { int& value = problem.distance_cost[facility][client]; value = value ? distance_dist(mt_engine) : artificial_inf; } } return problem; } // ============================================================================ // ============================================================================ // ================================= UTILITY ================================== // ============================================================================ inline int edge_pos_primal(int client, int facility, int num_clients, int num_facilities = 0) { return num_facilities + (facility * num_clients) + client; } inline int edge_pos_dual(int facility, int client, int num_facilities, int num_clients = 0) { return num_clients + (client * num_facilities) + facility; } // ============================================================================ // ============================================================================ // =============================== BRUTE-FORCE ================================ // ============================================================================ inline bool is_open(unsigned long long configuration, int facility) { return ((1ll << facility) & configuration) > 0; } void optimal(const Graph& problem, map<int, int>& client_assignments, map<int, vector<int> >& facility_assignments, double& min_cost) { client_assignments.clear(); facility_assignments.clear(); int num_facilities = problem.facilities(); int num_clients = problem.clients(); int num_variables = num_facilities * num_clients; unsigned long long best_opened; vector<double> best_solution; double best_cost = INT_MAX; unsigned long long out_of_range = 1ll << num_facilities; /* Test all combinations of facilities. Each combination is codified in an unsigned long long variable, where a 1 value in the nth bit signals that the facility in the nth position of the facilities vector is active */ for (unsigned long long combination = 1; combination < out_of_range; ++combination) { /* Objecive function to be minimized. The coefficients will all be negated before they are added, since a LP in standard form requires a function to be maximized */ vector<double> objective_vector(num_variables, 0); // Copy facility-client edges (distance cost * client demand) for (int facility = 0; facility < num_facilities; ++facility) { for (int client = 0; client < num_clients; ++client) { int pos = edge_pos_primal(client, facility, num_clients); objective_vector[pos] = problem.distance_cost.at(facility).at(client) * problem.client_demands[client]; } } vector<vector<double> > constraints; vector<char> constraint_types; /* Constraints guaranteeing that the demands of every client is satified. These specify that the summation of x_ij, through all facilities i, is equal to one, for all clients j */ for (int client = 0; client < num_clients; ++client) { vector<double> constraint(num_variables + 1, 0); for (int facility = 0; facility < num_facilities; ++facility) { int position = edge_pos_primal(client, facility, num_clients); constraint[position] = 1; } constraint.back() = 1; constraints.push_back(constraint); constraint_types.push_back('='); } /* Constraints guaranteeing that clients are supplied only from open facilities. These specify that x_ij <= y_j for all facility i and client j */ for (int facility = 0; facility < num_facilities; ++facility) { for (int client = 0; client < num_clients; ++client) { vector<double> constraint(num_variables + 1, 0); int pos = edge_pos_primal(client, facility, num_clients); constraint[pos] = 1; constraint.back() = is_open(combination, facility); constraints.push_back(constraint); constraint_types.push_back('<'); } } // Create and solve a LP problem in order to find the remaining variables Linear_Program lp(objective_vector, constraints, constraint_types); vector<double> solution; double min; double opening_cost = 0; lp.solve(solution, min, false); for (int i = 0; i < num_facilities; ++i) opening_cost += is_open(combination, i) * problem.facility_costs[i]; double cost = min + opening_cost; if (cost < best_cost) { best_solution = solution; best_opened = combination; best_cost = cost; } } min_cost = best_cost; for (int facility = 0; facility < num_facilities; ++facility) { for (int client = 0; client < num_clients; ++client) { int position = edge_pos_primal(client, facility, num_clients); if (best_solution[position] == 1) { client_assignments[client] = facility; facility_assignments[facility].push_back(client); } } } } // ============================================================================ // ============================================================================ // ================================ HEURISTICS ================================ // ============================================================================ struct Cluster { set<int> clients, facilities; }; inline double objective_fn_contribution(const Graph& problem, int facility, const set<int>& clients) { auto lambda_acc_client_cost = [&](double acc, int client) -> double { int distance = problem.distance_cost.at(facility).at(client); if (distance == artificial_inf) distance = 0; return acc + distance * problem.client_demands[client]; }; return accumulate(clients.begin(), clients.end(), (double)problem.facility_costs[facility], lambda_acc_client_cost); } inline int find_cluster_seed(const map<int, int>& client_assignments, const vector<double>& dual_solution, int num_clients) { double min_val = INT_MAX; int client_seed; for (int client = 0; client < num_clients; ++client) { // Ignore clients that were already assigned to clusters if (client_assignments.find(client) != client_assignments.end()) continue; /* If this is a client with a smaller vj than the best one so far, update the variables */ if (dual_solution[client] < min_val) { min_val = dual_solution[client]; client_seed = client; } } // Signals that no unassigned client exists if (min_val == INT_MAX) return -1; return client_seed; } inline void formulate_primal(const Graph& problem, vector<double>& objective, vector<vector<double> >& constraints, vector<char>& constraint_types) { int num_facilities = problem.facilities(); int num_clients = problem.clients(); int num_variables = num_facilities + num_facilities * num_clients; // ========== Set the objective function ========== objective.resize(num_variables); // Copy the facility costs (coefficients of the first num_facilities variables) copy(problem.facility_costs.begin(), problem.facility_costs.end(), objective.begin()); // Set the coefficients of the xij variables for (int facility = 0; facility < num_facilities; ++facility) { for (int client = 0; client < num_clients; ++client) { int pos = edge_pos_primal(client, facility, num_clients, num_facilities); /* Set the value of xij to be dij*wj, where dij is the cost per product unit and wj is the client demand, in product units */ objective[pos] = problem.distance_cost.at(facility).at(client) * problem.client_demands[client]; } } // ================================================ // ========== Set the sum(xij) = 1 constraints ========== for (int client = 0; client < num_clients; ++client) { vector<double> constraint(num_variables + 1, 0.); for (int facility = 0; facility < num_facilities; ++facility) { int pos = edge_pos_primal(client, facility, num_clients, num_facilities); // xij coefficient is 1 constraint[pos] = 1.; } // Sum of xij, through all facilities i, must be equal to 1 constraint.back() = 1.; constraints.push_back(constraint); constraint_types.push_back('='); } // ====================================================== // ========== Set the xij <= yi constraints ========== for (int facility = 0; facility < num_facilities; ++facility) { for (int client = 0; client < num_clients; ++client) { vector<double> constraint(num_variables + 1, 0.); // yi position is set to -1 constraint[facility] = -1.; // xij position is set to 1 int pos = edge_pos_primal(client, facility, num_clients, num_facilities); constraint[pos] = 1.; constraints.push_back(constraint); constraint_types.push_back('<'); } } // =================================================== } inline void formulate_dual(const Graph& problem, vector<double>& objective, vector<vector<double> >& constraints, vector<char>& constraint_types) { int num_facilities = problem.facilities(); int num_clients = problem.clients(); int num_variables = num_clients + num_facilities * num_clients; // ========== Set the objective function ========== // Initial num_clients positions are set to 1 objective = vector<double>(num_clients, 1.); /* Expand the array to size num_variables. Positions [num_clients, num_variables) are set to 0 */ objective.resize(num_variables); // ================================================ // ========== Set vj - Beta_ij <= cij constraints ========== for (int client = 0; client < num_clients; ++client) { for (int facility = 0; facility < num_facilities; ++facility) { vector<double> constraint(num_variables + 1, 0.); // Set vj variable to 1 constraint[client] = 1.; // Set Beta_ij variable to -1 int pos = edge_pos_dual(facility, client, num_facilities, num_clients); constraint[pos] = -1.; // Set the right-hand-side to dij*wij constraint.back() = problem.distance_cost.at(facility).at(client) * problem.client_demands[client]; constraints.push_back(constraint); constraint_types.push_back('<'); } } // ========================================================= // ========== Set sum(Beta_ij) <= fi constraints ========== for (int facility = 0; facility < num_facilities; ++facility) { vector<double> constraint(num_variables + 1, 0.); for (int client = 0; client < num_clients; ++client) { // Set position Beta_ij to 1 int pos = edge_pos_dual(facility, client, num_facilities, num_clients); constraint[pos] = 1.; } // Set the right-hand-side to fi constraint.back() = problem.facility_costs[facility]; constraints.push_back(constraint); constraint_types.push_back('<'); } // ======================================================== } void lp_rounding(const Graph& problem, map<int, int>& client_assignments, map<int, vector<int> >& facility_assignments, double& min_cost, bool modified = false) { client_assignments.clear(); facility_assignments.clear(); // ========== Solve the primal and dual LP problems ========== vector<double> objective_primal, objective_dual; vector<vector<double> > constraints_primal, constraints_dual; vector<char> constraint_types_primal, constraint_types_dual; // Formulate LP problems formulate_primal(problem, objective_primal, constraints_primal, constraint_types_primal); formulate_dual(problem, objective_dual, constraints_dual, constraint_types_dual); // Create Linear_Program objects Linear_Program primal_lp(objective_primal, constraints_primal, constraint_types_primal); Linear_Program dual_lp(objective_dual, constraints_dual, constraint_types_dual); vector<double> solution_primal, solution_dual; double cost_primal, cost_dual; // Solve LP problems primal_lp.solve(solution_primal, cost_primal, false, true); dual_lp.solve(solution_dual, cost_dual, true, true); // =========================================================== // ========== Divide the clients into clusters ========== int num_facilities = problem.facilities(); int num_clients = problem.clients(); double cost = 0; int client_seed = find_cluster_seed(client_assignments, solution_dual, num_clients); // Continue while there are unassociated clients while (client_seed != -1) { Cluster cluster; // Add to the cluster all facilities that serve the client seed for (int facility = 0; facility < num_facilities; ++facility) { // Add this facility to the cluster if the client seed is fractionally served by it int pos = edge_pos_primal(client_seed, facility, num_clients, num_facilities); if (solution_primal[pos] > 0) cluster.facilities.insert(facility); } // Add to the cluster all clients served by a facility in the cluster for (set<int>::const_iterator facility_it = cluster.facilities.begin(); facility_it != cluster.facilities.end(); ++facility_it) { for (int client = 0; client < num_clients; ++client) { /* Add this client to the cluster if it is fractionally served by the current facility and has not yet been added to any clusters */ int pos = edge_pos_primal(client, *facility_it, num_clients, num_facilities); if (solution_primal[pos] > 0 && client_assignments.find(client) == client_assignments.end()) { cluster.clients.insert(client); } } } int chosen_facility; /* Choose a facility to open. In the standard heuristic, the chosen facility is the cheapest to open. In the modified heuristic, the chosen facility is the one that provides the smallest contribution to the objective function */ if (modified) // Modified heuristic { double smallest_contribution = INT_MAX; auto lambda_cmp_contribution = [&](int f1, int f2) -> bool { return objective_fn_contribution(problem, f1, cluster.clients) < objective_fn_contribution(problem, f2, cluster.clients); }; set<int>::const_iterator position = min_element(cluster.facilities.begin(), cluster.facilities.end(), lambda_cmp_contribution); chosen_facility = *position; } else // Standard heuristic { int smallest_cost = INT_MAX; // Find the facility in the cluster with the smallest opening cost for (set<int>::const_iterator facility_it = cluster.facilities.begin(); facility_it != cluster.facilities.end(); ++facility_it) { if (problem.facility_costs[*facility_it] < smallest_cost) { smallest_cost = problem.facility_costs[*facility_it]; chosen_facility = *facility_it; } } } // Update the mappings facility_assignments[chosen_facility].push_back(client_seed); client_assignments[client_seed] = chosen_facility; // Assign the clients in the cluster to the opened facility for (set<int>::const_iterator client_it = cluster.clients.begin(); client_it != cluster.clients.end(); ++client_it) { // Assign the client if there is service from the facility to it if (problem.distance_cost[chosen_facility][*client_it] != artificial_inf && *client_it != client_seed) { client_assignments[*client_it] = chosen_facility; facility_assignments[chosen_facility].push_back(*client_it); } } // Update the cost of the solution for (set<int>::const_iterator client_it = cluster.clients.begin(); client_it != cluster.clients.end(); ++client_it) { int distance = problem.distance_cost.at(chosen_facility).at(*client_it); if (distance == artificial_inf) distance = 0; cost += distance * problem.client_demands[*client_it]; } cost += problem.facility_costs[chosen_facility]; client_seed = find_cluster_seed(client_assignments, solution_dual, num_clients); } // ====================================================== min_cost = cost; } // ============================================================================ string print_input_format(const Graph& problem) { int num_facilities = problem.facilities(); int num_clients = problem.clients(); stringstream ss; ss << num_facilities << " " << num_clients << endl; for (int facility = 0; facility < num_facilities; ++facility) ss << problem.facility_costs[facility] << ((facility == num_facilities - 1) ? '\n' : ' '); for (int client = 0; client < num_clients; ++client) ss << problem.client_demands[client] << ((client == num_clients - 1) ? '\n' : ' '); for (int facility = 0; facility < num_facilities; ++facility) for (int client = 0; client < num_clients; ++client) ss << problem.distance_cost[facility][client] << ((client == num_clients - 1) ? '\n' : ' '); return ss.str(); } string print_output_format(int instance, const string& algorithm, int num_facilities, const map<int, int> client_assignments, const map<int, vector<int> >& facility_assignments, double cost) { stringstream ss; ss << "INSTÂNCIA " << instance << " - " << algorithm << ": Custo " << cost << endl << "Facilities abertas:"; for (map<int, vector<int> >::const_iterator it = facility_assignments.begin(); it != facility_assignments.end(); ++it) { ss << ' ' << (it->first + 1); } ss << endl; for (map<int, vector<int> >::const_iterator it = facility_assignments.begin(); it != facility_assignments.end(); ++it) { ss << "Facility f" << (it->first + 1) << " atende clientes:"; for (vector<int>::size_type i = 0; i < it->second.size(); ++i) ss << ' ' << ((it->second)[i] + 1 + num_facilities); ss << endl; } return ss.str(); } void read_instance(Graph& problem, istream& in, ostream& out) { int num_facilities, num_clients; if (!(in >> num_facilities >> num_clients)) throw runtime_error("Could not read from file"); int buffer; for (int facility = 0; facility < num_facilities; ++facility) { if (!(in >> buffer)) throw runtime_error("Could not read from file"); problem.facility_costs.push_back(buffer); } for (int client = 0; client < num_clients; ++client) { if (!(in >> buffer)) throw runtime_error("Could not read from file"); problem.client_demands.push_back(buffer); } for (int facility = 0; facility < num_facilities; ++facility) { problem.distance_cost.push_back(vector<int>(num_clients, 0)); for (int client = 0; client < num_clients; ++client) { if (!(in >> problem.distance_cost[facility][client])) throw runtime_error("Could not read from file"); } } } void read_input(istream& in, ostream& out, bool find_cases = false) { int num_instances; if (!(in >> num_instances)) throw runtime_error("Could not read number of instances"); bool standard_found = false, modified_found = false; double h_mean = 0, mh_mean = 0, h_worst = INT_MIN, mh_worst = INT_MIN; double h_success = 0, mh_success = 0; stringstream ss; for (int instance = 0; instance < num_instances; ++instance) { Graph problem; read_instance(problem, in, ss); map<int, vector<int> > facility_assignment; map<int, int> client_assignment; double opt_cost, h_cost, mh_cost; optimal(problem, client_assignment, facility_assignment, opt_cost); ss << print_output_format(instance + 1, "Ótima", problem.facilities(), client_assignment, facility_assignment, opt_cost) << endl; lp_rounding(problem, client_assignment, facility_assignment, h_cost); ss << print_output_format(instance + 1, "Heurística", problem.facilities(), client_assignment, facility_assignment, h_cost) << endl; lp_rounding(problem, client_assignment, facility_assignment, mh_cost, true); ss << print_output_format(instance + 1, "Heurística Melhorada", problem.facilities(), client_assignment, facility_assignment, mh_cost) << endl; ss << "========================================" << endl << endl; if (find_cases && h_cost < mh_cost && !standard_found) { standard_found = true; cout << "*** Standard heuristic is better in this instance ***" << endl; cout << print_output_format(instance + 1, "Heurística", problem.facilities(), client_assignment, facility_assignment, h_cost) << endl; cout << print_input_format(problem) << endl; } else if (find_cases && mh_cost < h_cost && !modified_found) { modified_found = true; cout << "*** Modified heuristic is better in this instance ***" << endl; cout << print_output_format(instance + 1, "Heurística Melhorada", problem.facilities(), client_assignment, facility_assignment, mh_cost) << endl; cout << print_input_format(problem) << endl; } if (h_cost == opt_cost) h_success++; if (mh_cost == opt_cost) mh_success++; double h_ratio = h_cost / opt_cost; double mh_ratio = mh_cost / opt_cost; h_mean += h_ratio; mh_mean += mh_ratio; h_worst = std::max(h_worst, h_ratio); mh_worst = std::max(mh_worst, mh_ratio); } out << "================================" << endl; out << "========== STATISTICS ==========" << endl; out << "================================" << endl << endl; out << "Heuristic mean ratio: " << (h_mean / num_instances) << endl; out << "Modified heuristic mean ratio: " << (mh_mean / num_instances) << endl; out << "Heuristic equals OPT: " << (100 * (h_success / num_instances)) << "%" << endl; out << "Modified heuristic equals OPT: " << (100 * (mh_success / num_instances)) << "%" << endl; out << "Worst heuristic ratio: " << h_worst << endl; out << "Worst modified heuristic ratio: " << mh_worst << endl << endl; out << "================================" << endl; out << "========== INSTANCES ===========" << endl; out << "================================" << endl << endl << ss.str(); } void read_input(const string& input_filename, const string& out_filename, bool find_cases = false) { ifstream input_file(input_filename); ofstream output_file(out_filename); if (!input_file) throw runtime_error("Could not open input file"); if (!output_file) throw runtime_error("Could not open output file"); read_input(input_file, output_file, find_cases); input_file.close(); output_file.close(); } void random_problems(int problems_per_configuration, ostream& out) { out << "=====================================" << endl; out << "========== Configuration 1 ==========" << endl; out << "=====================================" << endl << endl; for (int i = 0; i < problems_per_configuration; i++) out << print_input_format(random_graph(4, 10)) << endl; out << "=====================================" << endl; out << "========== Configuration 2 ==========" << endl; out << "=====================================" << endl << endl; for (int i = 0; i < problems_per_configuration; i++) out << print_input_format(random_graph(5, 12)) << endl; out << "=====================================" << endl; out << "========== Configuration 3 ==========" << endl; out << "=====================================" << endl << endl; for (int i = 0; i < problems_per_configuration; i++) out << print_input_format(random_graph(6, 14)) << endl; out << "=====================================" << endl; out << "========== Configuration 4 ==========" << endl; out << "=====================================" << endl << endl; for (int i = 0; i < problems_per_configuration; i++) out << print_input_format(random_graph(7, 16)) << endl; } int main() { env.set(GRB_IntParam_OutputFlag, 0); try { string choice; cout << "Type \"f\" for file inputs, or \"r\" for random problems:" << endl; do { std::cin >> choice; } while (choice != "r" && choice != "f"); if (choice == "f") read_input("Projeto_UFL_input.txt", "Projeto_UFL_output_jgsma.txt", true); else { ofstream output_file("Projeto_UFL_jgsma_400_inputs.txt"); random_problems(400, output_file); output_file.close(); } } catch (std::exception& e) { cout << "ERROR => " << e.what() << endl; } } #endif
[ "jgsma@cin.ufpe.br" ]
jgsma@cin.ufpe.br
e62067ffd1182e68378988c2603747fe2128da66
c2cb548aaff4c9346bd859cd27ac79068d340d45
/Codeforces/Gym/101744/E.cpp
d4b627bea8bd3b695831b5e8cffa5777bb845883
[]
no_license
arnabxero/online-judges-problem-solutions
28997ab7e14bd1c2861b393e04b093c89f87cce9
506fe0c29742ceeb152f2698a30f7b32994a0e3e
refs/heads/master
2023-09-01T09:42:35.746179
2021-10-04T23:15:11
2021-10-04T23:15:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
// Problem name: MaratonIME rides the university bus // Problem link: https://codeforces.com/gym/101744/problem/E // Submission link: https://codeforces.com/gym/101744/submission/43083190 #include <bits/stdc++.h> #define endl '\n' using namespace std; typedef long long ll; int main(){ ios_base::sync_with_stdio(0), cin.tie(0); int n, m, x, y; cin >> n >> m; vector<ll> sum(n + 1, 0); for(int i = 1 ; i <= n ; i++) cin >> x, sum[ i ] = sum[ i - 1 ] + x; while(m--) cin >> x >> y, cout << ((sum[ y ] - sum[ --x ]) & 1 ? "Nao" : "Sim") << endl; return 0; }
[ "josea132.romero@gmail.com" ]
josea132.romero@gmail.com
891bb392e2fb9dfb8fbf2557d58455a0fef3f75b
f66ca7e6d96638d129c73e4dab57223ee57bd7fe
/p736/p736.cpp
68282bed5407714130141750683fbe2b4891b55c
[ "MIT" ]
permissive
suzyz/leetcode_practice
e4a5ab30b60318dc087452daef7dab51727d396a
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
refs/heads/master
2021-01-19T01:17:49.194902
2019-01-12T13:27:56
2019-01-12T13:27:56
95,619,304
1
0
null
null
null
null
UTF-8
C++
false
false
1,566
cpp
// Recursive. class Solution { public: int evaluate(string s) { unordered_map<string,int> dict; return helper(s, dict); } int helper(string s, unordered_map<string,int>& dict) { if (isdigit(s[0]) || s[0] == '-') return atoi(s.c_str()); if (islower(s[0])) return dict[s]; int n = s.length(); vector<string> exprs; if (s[1] == 'a' || s[1] == 'm') { int st = s[1] == 'a' ? 5 : 6; splitExpr(s.substr(st, n-1-st), exprs); int a = helper(exprs[0], dict); int b = helper(exprs[1], dict); return s[1] == 'a' ? a + b : a * b; } splitExpr(s.substr(5, n-6), exprs); int len = exprs.size(); unordered_map<string,int> newDict = dict; for (int i = 0; i < len-1; i += 2) newDict[exprs[i]] = helper(exprs[i+1], newDict); return helper(exprs[len-1], newDict); } void splitExpr(string s, vector<string>& res) { int i = 0, n = s.length(); while (i < n) { int j = i, count = 0; while (j < n) { if (s[j] == '(') ++count; else if (s[j] == ')') --count; else if (s[j] == ' ' && count == 0) break; ++j; } res.push_back(s.substr(i, j-i)); i = j+1; } } };
[ "suzyzhang0@gmail.com" ]
suzyzhang0@gmail.com
05233c5e5fb143c1b96d45133dbe8783605f1434
5a152b6b7b56b550a5db3b5e5e39e1dc55d9da8f
/CompProgBook/MyDearNeighbors/MyDearNeighbors.cpp
8e8f9cbfe5d5147069e55dbb65ba42984be3f572
[]
no_license
nmackay132/CompetitveProgramming
0db92eb8e5f3210150093202772ac8dffec69939
c01043f113e6e0e87ef015f2d620b80405776814
refs/heads/master
2021-01-20T21:23:46.957565
2016-01-09T21:53:09
2016-01-09T21:53:09
40,418,895
0
0
null
null
null
null
UTF-8
C++
false
false
1,933
cpp
/* */ #include <cstdio> #include <stdlib.h> #include <iostream> #include <vector> #include <string> #include <string.h> #include <math.h> #include <queue> #include <sstream> #include <limits> #include <algorithm> #include <map> #include <bitset> using namespace std; const int MAX_INT = std::numeric_limits<int>::max(); const int MIN_INT = std::numeric_limits<int>::min(); const int INF = 1000000000; const int NEG_INF = -1000000000; #define MAX(a,b)(a>b?a:b) #define MIN(a,b)(a<b?a:b) #define MEM(arr,val)memset(arr,val, sizeof arr) #define REP(n)int decrement = n;while(decrement--) #define PI acos(0)*2.0 #define EPS 1.0e-9 #define are_equal(a,b)fabs(a-b)<EPS #define LS(b)(b& (-b)) // Least significant bit #define DEG_to_RAD(a)((a*PI)/180.0) // convert to radians typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); } int lcm(int a, int b){ return a*(b / gcd(a, b)); } //----------------------------------------------------------------------// int main(){ int N; scanf("%d", &N); while (N--){ int P; scanf("%d", &P); int count; vii nums; string line; stringstream ss; getline(cin, line); for (int i = 1; i <= P; i++) { stringstream ss; string line; getline(cin, line); ss.str(line); int n; count = 0; while (ss >> n){ //printf("t %d\n", n); count++; } nums.push_back(ii(count, i)); } sort(nums.begin(), nums.end()); //for (int i = 0; i < nums.size(); i++) { // printf("test %d %d\n", nums[i].first, nums[i].second); //} //printf("\n"); vi ans; ans.push_back(nums[0].second); int min = nums[0].first; for (int i = 1; i < nums.size(); i++) { if (nums[i].first != min) break; ans.push_back(nums[i].second); } printf("%d", ans[0]); for (int i = 1; i < ans.size(); i++) { printf(" %d", ans[i]); } printf("\n"); } return 0; }
[ "mackaynathan@gmail.com" ]
mackaynathan@gmail.com
236dbda832d186f63d3ef5e1ac1a6194404d16ab
e02a75042ee1f0da2d32996b7cd7269a80c8502e
/AtCoder/abc162/b.cpp
221f5fa85a4c99c4235e08f05b62bc53d4178c7b
[]
no_license
KL-Lru/Competitive-Programming
35131245d630e7b8728e2707066dc871e6363230
d9395043ea439c68bcbdd1ed52fe080444dcc140
refs/heads/master
2021-06-18T03:17:16.583231
2021-04-05T14:09:00
2021-04-05T14:09:00
193,652,887
0
0
null
null
null
null
UTF-8
C++
false
false
236
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; int main(){ int n; cin >> n; ll sm = 0; for(int i=1;i<=n;i++){ if(i%3==0 || i%5 == 0) continue; sm += i; } cout << sm << endl; }
[ "kilattoeruru@outlook.jp" ]
kilattoeruru@outlook.jp
fea49ff92510636a601343903dfba9cf8870d5d8
f018f90d1bec533d274a2fd6f3aedd6e75fdf1cf
/IP_Cam/General_NetSDK_Eng_Linux64_IS_V3.48.1.R.170623/NetSDK_Eng_Bin/Demo_Src/build-PTZControl-Desktop_Qt_5_9_1_GCC_64bit2-Debug/ui_dialog.h
8182bb50411655009ef4f92fab853f2b84125f7a
[]
no_license
MichelRamseier/BT17
8d581d0c77ce31e44f7340570118c21ea80de122
6105143d7170bcdd4c8a839fb5bf1342235c327a
refs/heads/master
2020-12-24T05:39:55.726678
2018-11-12T21:13:13
2018-11-12T21:13:13
92,951,232
4
1
null
2018-11-12T21:13:14
2017-05-31T13:55:48
C++
UTF-8
C++
false
false
61,288
h
/******************************************************************************** ** Form generated from reading UI file 'dialog.ui' ** ** Created by: Qt User Interface Compiler version 5.9.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_DIALOG_H #define UI_DIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QFrame> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QFrame *frame5_2; QLabel *textLabel2; QComboBox *comboxChannel; QFrame *frame6; QLabel *textLabel1_2; QLineEdit *EditPreSetNo; QPushButton *pushButSet; QPushButton *pushButPresetDel; QPushButton *pushButGotoPreset; QFrame *frame3; QLabel *IP; QLabel *Port; QLabel *PassWord; QLabel *UserName; QLineEdit *lineEdit4; QLineEdit *lineEdit3; QLineEdit *lineEdit1; QLineEdit *lineEdit2; QPushButton *Login; QPushButton *Logout; QFrame *frame7; QLabel *textLabel3; QLabel *textLabel2_2; QLineEdit *EditPresetNum; QLineEdit *AutoTourNo; QPushButton *ButStartTour; QPushButton *ButStopTour; QPushButton *ButAddTour; QPushButton *ButDelTourPreset; QPushButton *ButDelTourNo; QFrame *frame12; QLabel *textLabel5; QPushButton *ButLimitLeft; QPushButton *ButLimitRight; QPushButton *ButStartScan; QPushButton *butStopScan; QFrame *frame5; QLabel *textLabel1; QComboBox *comboxCtrlParam; QPushButton *pushButRightUP; QPushButton *pushButRight; QPushButton *pushButRDown; QPushButton *pushButDZoom; QPushButton *pushButDFocus; QPushButton *pushButDAperture; QPushButton *pushButLeft; QPushButton *pushButLeftDown; QPushButton *pushButAZoom; QPushButton *pushButAFocus; QPushButton *pushButAperture; QPushButton *pushButDown; QPushButton *pushButLeftUp; QPushButton *pushButUp; QFrame *frame14; QLabel *textLabel10; QLabel *textLabel9; QLabel *textLabel8; QLabel *textLabel7; QLineEdit *lineEditX; QLineEdit *lineEditY; QLineEdit *lineEditZoom; QPushButton *ButSIT; QFrame *frame13; QLabel *textLabel6; QPushButton *ButStartPan; QPushButton *ButStopPan; QFrame *frame15; QLabel *textLabel11; QComboBox *comboxAuxNo; QPushButton *ButOpenAUX; QPushButton *ButCloseAUX; QFrame *frame10; QLabel *textLabel4; QLineEdit *PattermNo; QPushButton *ButStartProgram; QPushButton *ButStopProgram; QPushButton *ButStartPatterm; QPushButton *ButStopPatterm; QPushButton *ButDelPatterm; QFrame *frame14_2; QLabel *textLabel1_3; QPushButton *ButMenuLeft; QPushButton *ButMenuUP; QPushButton *ButMenuDown; QPushButton *ButMenuRight; QPushButton *ButOpenMenu; QPushButton *ButCloseMenu; QPushButton *ButMenuOK; QPushButton *ButMenuCancel; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QStringLiteral("Dialog")); Dialog->setEnabled(true); Dialog->resize(895, 400); Dialog->setMinimumSize(QSize(895, 400)); Dialog->setMaximumSize(QSize(895, 400)); QPalette palette; QBrush brush(QColor(0, 0, 0, 255)); brush.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::WindowText, brush); QBrush brush1(QColor(85, 170, 255, 255)); brush1.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Button, brush1); QBrush brush2(QColor(212, 234, 255, 255)); brush2.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Light, brush2); QBrush brush3(QColor(148, 202, 255, 255)); brush3.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Midlight, brush3); QBrush brush4(QColor(42, 85, 127, 255)); brush4.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Dark, brush4); QBrush brush5(QColor(57, 113, 170, 255)); brush5.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Mid, brush5); palette.setBrush(QPalette::Active, QPalette::Text, brush); QBrush brush6(QColor(255, 255, 255, 255)); brush6.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette.setBrush(QPalette::Active, QPalette::Base, brush6); QBrush brush7(QColor(212, 228, 255, 255)); brush7.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Window, brush7); palette.setBrush(QPalette::Active, QPalette::Shadow, brush); QBrush brush8(QColor(0, 0, 128, 255)); brush8.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette.setBrush(QPalette::Active, QPalette::Link, brush); palette.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette.setBrush(QPalette::Inactive, QPalette::Light, brush2); QBrush brush9(QColor(123, 189, 255, 255)); brush9.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette.setBrush(QPalette::Inactive, QPalette::Text, brush); palette.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); QBrush brush10(QColor(0, 0, 255, 255)); brush10.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Inactive, QPalette::Link, brush10); QBrush brush11(QColor(255, 0, 255, 255)); brush11.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); QBrush brush12(QColor(128, 128, 128, 255)); brush12.setStyle(Qt::SolidPattern); palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); Dialog->setPalette(palette); frame5_2 = new QFrame(Dialog); frame5_2->setObjectName(QStringLiteral("frame5_2")); frame5_2->setGeometry(QRect(10, 89, 251, 41)); frame5_2->setFrameShape(QFrame::StyledPanel); frame5_2->setFrameShadow(QFrame::Plain); textLabel2 = new QLabel(frame5_2); textLabel2->setObjectName(QStringLiteral("textLabel2")); textLabel2->setGeometry(QRect(10, 10, 91, 21)); textLabel2->setWordWrap(false); comboxChannel = new QComboBox(frame5_2); comboxChannel->setObjectName(QStringLiteral("comboxChannel")); comboxChannel->setGeometry(QRect(103, 10, 140, 22)); QPalette palette1; palette1.setBrush(QPalette::Active, QPalette::WindowText, brush); palette1.setBrush(QPalette::Active, QPalette::Button, brush1); palette1.setBrush(QPalette::Active, QPalette::Light, brush2); palette1.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette1.setBrush(QPalette::Active, QPalette::Dark, brush4); palette1.setBrush(QPalette::Active, QPalette::Mid, brush5); palette1.setBrush(QPalette::Active, QPalette::Text, brush); palette1.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette1.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette1.setBrush(QPalette::Active, QPalette::Base, brush6); palette1.setBrush(QPalette::Active, QPalette::Window, brush7); palette1.setBrush(QPalette::Active, QPalette::Shadow, brush); palette1.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette1.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette1.setBrush(QPalette::Active, QPalette::Link, brush); palette1.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette1.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette1.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette1.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette1.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette1.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette1.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette1.setBrush(QPalette::Inactive, QPalette::Text, brush); palette1.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette1.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette1.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette1.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette1.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette1.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette1.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette1.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette1.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette1.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette1.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette1.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette1.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette1.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette1.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette1.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette1.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette1.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette1.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette1.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette1.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette1.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette1.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette1.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette1.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); comboxChannel->setPalette(palette1); frame6 = new QFrame(Dialog); frame6->setObjectName(QStringLiteral("frame6")); frame6->setGeometry(QRect(259, 89, 240, 80)); frame6->setFrameShape(QFrame::StyledPanel); frame6->setFrameShadow(QFrame::Plain); textLabel1_2 = new QLabel(frame6); textLabel1_2->setObjectName(QStringLiteral("textLabel1_2")); textLabel1_2->setGeometry(QRect(10, 10, 81, 22)); textLabel1_2->setWordWrap(false); EditPreSetNo = new QLineEdit(frame6); EditPreSetNo->setObjectName(QStringLiteral("EditPreSetNo")); EditPreSetNo->setGeometry(QRect(90, 10, 140, 22)); pushButSet = new QPushButton(frame6); pushButSet->setObjectName(QStringLiteral("pushButSet")); pushButSet->setGeometry(QRect(11, 41, 70, 25)); pushButPresetDel = new QPushButton(frame6); pushButPresetDel->setObjectName(QStringLiteral("pushButPresetDel")); pushButPresetDel->setGeometry(QRect(87, 41, 71, 25)); pushButGotoPreset = new QPushButton(frame6); pushButGotoPreset->setObjectName(QStringLiteral("pushButGotoPreset")); pushButGotoPreset->setGeometry(QRect(160, 40, 71, 25)); frame3 = new QFrame(Dialog); frame3->setObjectName(QStringLiteral("frame3")); frame3->setGeometry(QRect(10, 10, 489, 80)); QPalette palette2; palette2.setBrush(QPalette::Active, QPalette::WindowText, brush); palette2.setBrush(QPalette::Active, QPalette::Button, brush1); palette2.setBrush(QPalette::Active, QPalette::Light, brush2); palette2.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette2.setBrush(QPalette::Active, QPalette::Dark, brush4); palette2.setBrush(QPalette::Active, QPalette::Mid, brush5); palette2.setBrush(QPalette::Active, QPalette::Text, brush); palette2.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette2.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette2.setBrush(QPalette::Active, QPalette::Base, brush6); palette2.setBrush(QPalette::Active, QPalette::Window, brush7); palette2.setBrush(QPalette::Active, QPalette::Shadow, brush); palette2.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette2.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette2.setBrush(QPalette::Active, QPalette::Link, brush); palette2.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette2.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette2.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette2.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette2.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette2.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette2.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette2.setBrush(QPalette::Inactive, QPalette::Text, brush); palette2.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette2.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette2.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette2.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette2.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette2.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette2.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette2.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette2.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette2.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette2.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette2.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette2.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette2.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette2.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette2.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette2.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette2.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette2.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette2.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette2.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette2.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette2.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette2.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette2.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); frame3->setPalette(palette2); frame3->setFrameShape(QFrame::StyledPanel); frame3->setFrameShadow(QFrame::Plain); IP = new QLabel(frame3); IP->setObjectName(QStringLiteral("IP")); IP->setGeometry(QRect(12, 10, 18, 22)); IP->setWordWrap(false); Port = new QLabel(frame3); Port->setObjectName(QStringLiteral("Port")); Port->setGeometry(QRect(12, 41, 27, 22)); Port->setWordWrap(false); PassWord = new QLabel(frame3); PassWord->setObjectName(QStringLiteral("PassWord")); PassWord->setGeometry(QRect(159, 41, 81, 22)); PassWord->setWordWrap(false); UserName = new QLabel(frame3); UserName->setObjectName(QStringLiteral("UserName")); UserName->setGeometry(QRect(162, 10, 81, 22)); UserName->setWordWrap(false); lineEdit4 = new QLineEdit(frame3); lineEdit4->setObjectName(QStringLiteral("lineEdit4")); lineEdit4->setGeometry(QRect(250, 10, 100, 22)); lineEdit3 = new QLineEdit(frame3); lineEdit3->setObjectName(QStringLiteral("lineEdit3")); lineEdit3->setGeometry(QRect(250, 41, 100, 22)); lineEdit1 = new QLineEdit(frame3); lineEdit1->setObjectName(QStringLiteral("lineEdit1")); lineEdit1->setGeometry(QRect(46, 10, 100, 22)); lineEdit2 = new QLineEdit(frame3); lineEdit2->setObjectName(QStringLiteral("lineEdit2")); lineEdit2->setGeometry(QRect(45, 41, 100, 22)); Login = new QPushButton(frame3); Login->setObjectName(QStringLiteral("Login")); Login->setGeometry(QRect(360, 10, 80, 25)); QPalette palette3; palette3.setBrush(QPalette::Active, QPalette::WindowText, brush); palette3.setBrush(QPalette::Active, QPalette::Button, brush1); palette3.setBrush(QPalette::Active, QPalette::Light, brush2); palette3.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette3.setBrush(QPalette::Active, QPalette::Dark, brush4); palette3.setBrush(QPalette::Active, QPalette::Mid, brush5); palette3.setBrush(QPalette::Active, QPalette::Text, brush); palette3.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette3.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette3.setBrush(QPalette::Active, QPalette::Base, brush6); palette3.setBrush(QPalette::Active, QPalette::Window, brush7); palette3.setBrush(QPalette::Active, QPalette::Shadow, brush); palette3.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette3.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette3.setBrush(QPalette::Active, QPalette::Link, brush); palette3.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette3.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette3.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette3.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette3.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette3.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette3.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette3.setBrush(QPalette::Inactive, QPalette::Text, brush); palette3.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette3.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette3.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette3.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette3.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette3.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette3.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette3.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette3.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette3.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette3.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette3.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette3.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette3.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette3.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette3.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette3.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette3.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette3.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette3.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette3.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette3.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette3.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette3.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette3.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); Login->setPalette(palette3); Logout = new QPushButton(frame3); Logout->setObjectName(QStringLiteral("Logout")); Logout->setGeometry(QRect(360, 40, 80, 25)); QPalette palette4; palette4.setBrush(QPalette::Active, QPalette::WindowText, brush); palette4.setBrush(QPalette::Active, QPalette::Button, brush1); palette4.setBrush(QPalette::Active, QPalette::Light, brush2); palette4.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette4.setBrush(QPalette::Active, QPalette::Dark, brush4); palette4.setBrush(QPalette::Active, QPalette::Mid, brush5); palette4.setBrush(QPalette::Active, QPalette::Text, brush); palette4.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette4.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette4.setBrush(QPalette::Active, QPalette::Base, brush6); palette4.setBrush(QPalette::Active, QPalette::Window, brush7); palette4.setBrush(QPalette::Active, QPalette::Shadow, brush); palette4.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette4.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette4.setBrush(QPalette::Active, QPalette::Link, brush); palette4.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette4.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette4.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette4.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette4.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette4.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette4.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette4.setBrush(QPalette::Inactive, QPalette::Text, brush); palette4.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette4.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette4.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette4.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette4.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette4.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette4.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette4.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette4.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette4.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette4.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette4.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette4.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette4.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette4.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette4.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette4.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette4.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette4.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette4.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette4.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette4.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette4.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette4.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette4.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); Logout->setPalette(palette4); frame7 = new QFrame(Dialog); frame7->setObjectName(QStringLiteral("frame7")); frame7->setGeometry(QRect(260, 170, 240, 224)); frame7->setFrameShape(QFrame::StyledPanel); frame7->setFrameShadow(QFrame::Plain); frame7->setLineWidth(1); frame7->setMidLineWidth(0); textLabel3 = new QLabel(frame7); textLabel3->setObjectName(QStringLiteral("textLabel3")); textLabel3->setGeometry(QRect(10, 11, 71, 16)); textLabel3->setWordWrap(false); textLabel2_2 = new QLabel(frame7); textLabel2_2->setObjectName(QStringLiteral("textLabel2_2")); textLabel2_2->setGeometry(QRect(10, 43, 81, 16)); textLabel2_2->setWordWrap(false); EditPresetNum = new QLineEdit(frame7); EditPresetNum->setObjectName(QStringLiteral("EditPresetNum")); EditPresetNum->setGeometry(QRect(89, 11, 140, 22)); AutoTourNo = new QLineEdit(frame7); AutoTourNo->setObjectName(QStringLiteral("AutoTourNo")); AutoTourNo->setGeometry(QRect(89, 39, 140, 22)); ButStartTour = new QPushButton(frame7); ButStartTour->setObjectName(QStringLiteral("ButStartTour")); ButStartTour->setGeometry(QRect(79, 65, 150, 25)); ButStopTour = new QPushButton(frame7); ButStopTour->setObjectName(QStringLiteral("ButStopTour")); ButStopTour->setGeometry(QRect(79, 94, 150, 25)); ButAddTour = new QPushButton(frame7); ButAddTour->setObjectName(QStringLiteral("ButAddTour")); ButAddTour->setGeometry(QRect(78, 123, 150, 25)); ButDelTourPreset = new QPushButton(frame7); ButDelTourPreset->setObjectName(QStringLiteral("ButDelTourPreset")); ButDelTourPreset->setGeometry(QRect(57, 152, 171, 25)); ButDelTourNo = new QPushButton(frame7); ButDelTourNo->setObjectName(QStringLiteral("ButDelTourNo")); ButDelTourNo->setGeometry(QRect(78, 183, 150, 25)); frame12 = new QFrame(Dialog); frame12->setObjectName(QStringLiteral("frame12")); frame12->setGeometry(QRect(498, 305, 200, 87)); frame12->setFrameShape(QFrame::StyledPanel); frame12->setFrameShadow(QFrame::Plain); textLabel5 = new QLabel(frame12); textLabel5->setObjectName(QStringLiteral("textLabel5")); textLabel5->setGeometry(QRect(10, 3, 81, 21)); textLabel5->setWordWrap(false); ButLimitLeft = new QPushButton(frame12); ButLimitLeft->setObjectName(QStringLiteral("ButLimitLeft")); ButLimitLeft->setGeometry(QRect(11, 21, 80, 23)); ButLimitRight = new QPushButton(frame12); ButLimitRight->setObjectName(QStringLiteral("ButLimitRight")); ButLimitRight->setGeometry(QRect(98, 21, 91, 23)); ButStartScan = new QPushButton(frame12); ButStartScan->setObjectName(QStringLiteral("ButStartScan")); ButStartScan->setGeometry(QRect(11, 50, 75, 23)); butStopScan = new QPushButton(frame12); butStopScan->setObjectName(QStringLiteral("butStopScan")); butStopScan->setGeometry(QRect(108, 50, 81, 23)); frame5 = new QFrame(Dialog); frame5->setObjectName(QStringLiteral("frame5")); frame5->setGeometry(QRect(10, 129, 250, 263)); frame5->setFrameShape(QFrame::StyledPanel); frame5->setFrameShadow(QFrame::Plain); textLabel1 = new QLabel(frame5); textLabel1->setObjectName(QStringLiteral("textLabel1")); textLabel1->setGeometry(QRect(10, 10, 91, 21)); textLabel1->setWordWrap(false); comboxCtrlParam = new QComboBox(frame5); comboxCtrlParam->setObjectName(QStringLiteral("comboxCtrlParam")); comboxCtrlParam->setGeometry(QRect(102, 10, 140, 22)); QPalette palette5; palette5.setBrush(QPalette::Active, QPalette::WindowText, brush); palette5.setBrush(QPalette::Active, QPalette::Button, brush1); palette5.setBrush(QPalette::Active, QPalette::Light, brush2); palette5.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette5.setBrush(QPalette::Active, QPalette::Dark, brush4); palette5.setBrush(QPalette::Active, QPalette::Mid, brush5); palette5.setBrush(QPalette::Active, QPalette::Text, brush); palette5.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette5.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette5.setBrush(QPalette::Active, QPalette::Base, brush6); palette5.setBrush(QPalette::Active, QPalette::Window, brush7); palette5.setBrush(QPalette::Active, QPalette::Shadow, brush); palette5.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette5.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette5.setBrush(QPalette::Active, QPalette::Link, brush); palette5.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette5.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette5.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette5.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette5.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette5.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette5.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette5.setBrush(QPalette::Inactive, QPalette::Text, brush); palette5.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette5.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette5.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette5.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette5.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette5.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette5.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette5.setBrush(QPalette::Inactive, QPalette::Link, brush); palette5.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush); palette5.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette5.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette5.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette5.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette5.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette5.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette5.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette5.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette5.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette5.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette5.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette5.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette5.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette5.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette5.setBrush(QPalette::Disabled, QPalette::Link, brush); palette5.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush); comboxCtrlParam->setPalette(palette5); pushButRightUP = new QPushButton(frame5); pushButRightUP->setObjectName(QStringLiteral("pushButRightUP")); pushButRightUP->setGeometry(QRect(159, 43, 81, 25)); pushButRight = new QPushButton(frame5); pushButRight->setObjectName(QStringLiteral("pushButRight")); pushButRight->setGeometry(QRect(160, 70, 81, 25)); pushButRDown = new QPushButton(frame5); pushButRDown->setObjectName(QStringLiteral("pushButRDown")); pushButRDown->setGeometry(QRect(160, 102, 95, 25)); pushButDZoom = new QPushButton(frame5); pushButDZoom->setObjectName(QStringLiteral("pushButDZoom")); pushButDZoom->setGeometry(QRect(159, 132, 81, 25)); pushButDFocus = new QPushButton(frame5); pushButDFocus->setObjectName(QStringLiteral("pushButDFocus")); pushButDFocus->setGeometry(QRect(159, 162, 81, 25)); pushButDAperture = new QPushButton(frame5); pushButDAperture->setObjectName(QStringLiteral("pushButDAperture")); pushButDAperture->setGeometry(QRect(159, 192, 81, 25)); pushButLeft = new QPushButton(frame5); pushButLeft->setObjectName(QStringLiteral("pushButLeft")); pushButLeft->setGeometry(QRect(9, 72, 91, 25)); pushButLeftDown = new QPushButton(frame5); pushButLeftDown->setObjectName(QStringLiteral("pushButLeftDown")); pushButLeftDown->setGeometry(QRect(9, 102, 91, 25)); pushButAZoom = new QPushButton(frame5); pushButAZoom->setObjectName(QStringLiteral("pushButAZoom")); pushButAZoom->setGeometry(QRect(9, 132, 91, 25)); pushButAFocus = new QPushButton(frame5); pushButAFocus->setObjectName(QStringLiteral("pushButAFocus")); pushButAFocus->setGeometry(QRect(9, 163, 95, 25)); pushButAperture = new QPushButton(frame5); pushButAperture->setObjectName(QStringLiteral("pushButAperture")); pushButAperture->setGeometry(QRect(9, 193, 95, 25)); pushButDown = new QPushButton(frame5); pushButDown->setObjectName(QStringLiteral("pushButDown")); pushButDown->setGeometry(QRect(100, 102, 60, 25)); pushButLeftUp = new QPushButton(frame5); pushButLeftUp->setObjectName(QStringLiteral("pushButLeftUp")); pushButLeftUp->setGeometry(QRect(9, 43, 91, 25)); pushButUp = new QPushButton(frame5); pushButUp->setObjectName(QStringLiteral("pushButUp")); pushButUp->setGeometry(QRect(100, 43, 60, 25)); frame14 = new QFrame(Dialog); frame14->setObjectName(QStringLiteral("frame14")); frame14->setGeometry(QRect(697, 124, 191, 140)); frame14->setFrameShape(QFrame::StyledPanel); frame14->setFrameShadow(QFrame::Plain); textLabel10 = new QLabel(frame14); textLabel10->setObjectName(QStringLiteral("textLabel10")); textLabel10->setGeometry(QRect(7, 93, 51, 20)); textLabel10->setWordWrap(false); textLabel9 = new QLabel(frame14); textLabel9->setObjectName(QStringLiteral("textLabel9")); textLabel9->setGeometry(QRect(21, 62, 37, 16)); textLabel9->setWordWrap(false); textLabel8 = new QLabel(frame14); textLabel8->setObjectName(QStringLiteral("textLabel8")); textLabel8->setGeometry(QRect(20, 30, 37, 16)); textLabel8->setWordWrap(false); textLabel7 = new QLabel(frame14); textLabel7->setObjectName(QStringLiteral("textLabel7")); textLabel7->setGeometry(QRect(20, 1, 70, 21)); textLabel7->setWordWrap(false); lineEditX = new QLineEdit(frame14); lineEditX->setObjectName(QStringLiteral("lineEditX")); lineEditX->setGeometry(QRect(70, 32, 108, 22)); lineEditY = new QLineEdit(frame14); lineEditY->setObjectName(QStringLiteral("lineEditY")); lineEditY->setGeometry(QRect(70, 57, 108, 22)); lineEditZoom = new QLineEdit(frame14); lineEditZoom->setObjectName(QStringLiteral("lineEditZoom")); lineEditZoom->setGeometry(QRect(70, 82, 108, 22)); ButSIT = new QPushButton(frame14); ButSIT->setObjectName(QStringLiteral("ButSIT")); ButSIT->setGeometry(QRect(70, 107, 108, 25)); frame13 = new QFrame(Dialog); frame13->setObjectName(QStringLiteral("frame13")); frame13->setGeometry(QRect(697, 332, 191, 60)); frame13->setFrameShape(QFrame::StyledPanel); frame13->setFrameShadow(QFrame::Plain); textLabel6 = new QLabel(frame13); textLabel6->setObjectName(QStringLiteral("textLabel6")); textLabel6->setGeometry(QRect(10, 5, 91, 20)); textLabel6->setWordWrap(false); ButStartPan = new QPushButton(frame13); ButStartPan->setObjectName(QStringLiteral("ButStartPan")); ButStartPan->setGeometry(QRect(11, 25, 95, 25)); ButStopPan = new QPushButton(frame13); ButStopPan->setObjectName(QStringLiteral("ButStopPan")); ButStopPan->setGeometry(QRect(102, 25, 85, 25)); frame15 = new QFrame(Dialog); frame15->setObjectName(QStringLiteral("frame15")); frame15->setGeometry(QRect(697, 260, 191, 73)); frame15->setFrameShape(QFrame::StyledPanel); frame15->setFrameShadow(QFrame::Plain); textLabel11 = new QLabel(frame15); textLabel11->setObjectName(QStringLiteral("textLabel11")); textLabel11->setGeometry(QRect(10, 10, 71, 21)); textLabel11->setWordWrap(false); comboxAuxNo = new QComboBox(frame15); comboxAuxNo->setObjectName(QStringLiteral("comboxAuxNo")); comboxAuxNo->setGeometry(QRect(80, 11, 101, 20)); QPalette palette6; palette6.setBrush(QPalette::Active, QPalette::WindowText, brush); palette6.setBrush(QPalette::Active, QPalette::Button, brush1); palette6.setBrush(QPalette::Active, QPalette::Light, brush2); palette6.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette6.setBrush(QPalette::Active, QPalette::Dark, brush4); palette6.setBrush(QPalette::Active, QPalette::Mid, brush5); palette6.setBrush(QPalette::Active, QPalette::Text, brush); palette6.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette6.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette6.setBrush(QPalette::Active, QPalette::Base, brush6); palette6.setBrush(QPalette::Active, QPalette::Window, brush7); palette6.setBrush(QPalette::Active, QPalette::Shadow, brush); palette6.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette6.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette6.setBrush(QPalette::Active, QPalette::Link, brush); palette6.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette6.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette6.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette6.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette6.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette6.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette6.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette6.setBrush(QPalette::Inactive, QPalette::Text, brush); palette6.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette6.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette6.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette6.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette6.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette6.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette6.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette6.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette6.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette6.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette6.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette6.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette6.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette6.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette6.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette6.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette6.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette6.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette6.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette6.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette6.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette6.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette6.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette6.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette6.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); comboxAuxNo->setPalette(palette6); ButOpenAUX = new QPushButton(frame15); ButOpenAUX->setObjectName(QStringLiteral("ButOpenAUX")); ButOpenAUX->setGeometry(QRect(9, 40, 85, 25)); ButCloseAUX = new QPushButton(frame15); ButCloseAUX->setObjectName(QStringLiteral("ButCloseAUX")); ButCloseAUX->setGeometry(QRect(100, 40, 85, 25)); frame10 = new QFrame(Dialog); frame10->setObjectName(QStringLiteral("frame10")); frame10->setGeometry(QRect(498, 124, 200, 182)); frame10->setFrameShape(QFrame::StyledPanel); frame10->setFrameShadow(QFrame::Plain); textLabel4 = new QLabel(frame10); textLabel4->setObjectName(QStringLiteral("textLabel4")); textLabel4->setGeometry(QRect(6, 6, 71, 31)); textLabel4->setWordWrap(false); PattermNo = new QLineEdit(frame10); PattermNo->setObjectName(QStringLiteral("PattermNo")); PattermNo->setGeometry(QRect(75, 11, 120, 22)); ButStartProgram = new QPushButton(frame10); ButStartProgram->setObjectName(QStringLiteral("ButStartProgram")); ButStartProgram->setGeometry(QRect(71, 40, 120, 25)); ButStopProgram = new QPushButton(frame10); ButStopProgram->setObjectName(QStringLiteral("ButStopProgram")); ButStopProgram->setGeometry(QRect(71, 68, 120, 25)); ButStartPatterm = new QPushButton(frame10); ButStartPatterm->setObjectName(QStringLiteral("ButStartPatterm")); ButStartPatterm->setGeometry(QRect(70, 96, 120, 25)); ButStopPatterm = new QPushButton(frame10); ButStopPatterm->setObjectName(QStringLiteral("ButStopPatterm")); ButStopPatterm->setGeometry(QRect(70, 124, 120, 25)); ButDelPatterm = new QPushButton(frame10); ButDelPatterm->setObjectName(QStringLiteral("ButDelPatterm")); ButDelPatterm->setGeometry(QRect(70, 152, 120, 25)); frame14_2 = new QFrame(Dialog); frame14_2->setObjectName(QStringLiteral("frame14_2")); frame14_2->setGeometry(QRect(498, 10, 390, 115)); frame14_2->setFrameShape(QFrame::StyledPanel); frame14_2->setFrameShadow(QFrame::Plain); textLabel1_3 = new QLabel(frame14_2); textLabel1_3->setObjectName(QStringLiteral("textLabel1_3")); textLabel1_3->setGeometry(QRect(10, 10, 81, 31)); textLabel1_3->setWordWrap(false); ButMenuLeft = new QPushButton(frame14_2); ButMenuLeft->setObjectName(QStringLiteral("ButMenuLeft")); ButMenuLeft->setGeometry(QRect(100, 40, 60, 25)); QPalette palette7; palette7.setBrush(QPalette::Active, QPalette::WindowText, brush); palette7.setBrush(QPalette::Active, QPalette::Button, brush1); palette7.setBrush(QPalette::Active, QPalette::Light, brush2); palette7.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette7.setBrush(QPalette::Active, QPalette::Dark, brush4); palette7.setBrush(QPalette::Active, QPalette::Mid, brush5); palette7.setBrush(QPalette::Active, QPalette::Text, brush); palette7.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette7.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette7.setBrush(QPalette::Active, QPalette::Base, brush6); palette7.setBrush(QPalette::Active, QPalette::Window, brush7); palette7.setBrush(QPalette::Active, QPalette::Shadow, brush); palette7.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette7.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette7.setBrush(QPalette::Active, QPalette::Link, brush); palette7.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette7.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette7.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette7.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette7.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette7.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette7.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette7.setBrush(QPalette::Inactive, QPalette::Text, brush); palette7.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette7.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette7.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette7.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette7.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette7.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette7.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette7.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette7.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette7.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette7.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette7.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette7.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette7.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette7.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette7.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette7.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette7.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette7.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette7.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette7.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette7.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette7.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette7.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette7.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); ButMenuLeft->setPalette(palette7); ButMenuUP = new QPushButton(frame14_2); ButMenuUP->setObjectName(QStringLiteral("ButMenuUP")); ButMenuUP->setGeometry(QRect(160, 10, 60, 25)); ButMenuDown = new QPushButton(frame14_2); ButMenuDown->setObjectName(QStringLiteral("ButMenuDown")); ButMenuDown->setGeometry(QRect(160, 70, 60, 25)); ButMenuRight = new QPushButton(frame14_2); ButMenuRight->setObjectName(QStringLiteral("ButMenuRight")); ButMenuRight->setGeometry(QRect(215, 40, 60, 25)); ButOpenMenu = new QPushButton(frame14_2); ButOpenMenu->setObjectName(QStringLiteral("ButOpenMenu")); ButOpenMenu->setGeometry(QRect(289, 4, 98, 25)); ButCloseMenu = new QPushButton(frame14_2); ButCloseMenu->setObjectName(QStringLiteral("ButCloseMenu")); ButCloseMenu->setGeometry(QRect(290, 31, 98, 25)); QPalette palette8; palette8.setBrush(QPalette::Active, QPalette::WindowText, brush); palette8.setBrush(QPalette::Active, QPalette::Button, brush1); palette8.setBrush(QPalette::Active, QPalette::Light, brush2); palette8.setBrush(QPalette::Active, QPalette::Midlight, brush3); palette8.setBrush(QPalette::Active, QPalette::Dark, brush4); palette8.setBrush(QPalette::Active, QPalette::Mid, brush5); palette8.setBrush(QPalette::Active, QPalette::Text, brush); palette8.setBrush(QPalette::Active, QPalette::BrightText, brush6); palette8.setBrush(QPalette::Active, QPalette::ButtonText, brush); palette8.setBrush(QPalette::Active, QPalette::Base, brush6); palette8.setBrush(QPalette::Active, QPalette::Window, brush7); palette8.setBrush(QPalette::Active, QPalette::Shadow, brush); palette8.setBrush(QPalette::Active, QPalette::Highlight, brush8); palette8.setBrush(QPalette::Active, QPalette::HighlightedText, brush6); palette8.setBrush(QPalette::Active, QPalette::Link, brush); palette8.setBrush(QPalette::Active, QPalette::LinkVisited, brush); palette8.setBrush(QPalette::Inactive, QPalette::WindowText, brush); palette8.setBrush(QPalette::Inactive, QPalette::Button, brush1); palette8.setBrush(QPalette::Inactive, QPalette::Light, brush2); palette8.setBrush(QPalette::Inactive, QPalette::Midlight, brush9); palette8.setBrush(QPalette::Inactive, QPalette::Dark, brush4); palette8.setBrush(QPalette::Inactive, QPalette::Mid, brush5); palette8.setBrush(QPalette::Inactive, QPalette::Text, brush); palette8.setBrush(QPalette::Inactive, QPalette::BrightText, brush6); palette8.setBrush(QPalette::Inactive, QPalette::ButtonText, brush); palette8.setBrush(QPalette::Inactive, QPalette::Base, brush6); palette8.setBrush(QPalette::Inactive, QPalette::Window, brush7); palette8.setBrush(QPalette::Inactive, QPalette::Shadow, brush); palette8.setBrush(QPalette::Inactive, QPalette::Highlight, brush8); palette8.setBrush(QPalette::Inactive, QPalette::HighlightedText, brush6); palette8.setBrush(QPalette::Inactive, QPalette::Link, brush10); palette8.setBrush(QPalette::Inactive, QPalette::LinkVisited, brush11); palette8.setBrush(QPalette::Disabled, QPalette::WindowText, brush12); palette8.setBrush(QPalette::Disabled, QPalette::Button, brush1); palette8.setBrush(QPalette::Disabled, QPalette::Light, brush2); palette8.setBrush(QPalette::Disabled, QPalette::Midlight, brush9); palette8.setBrush(QPalette::Disabled, QPalette::Dark, brush4); palette8.setBrush(QPalette::Disabled, QPalette::Mid, brush5); palette8.setBrush(QPalette::Disabled, QPalette::Text, brush12); palette8.setBrush(QPalette::Disabled, QPalette::BrightText, brush6); palette8.setBrush(QPalette::Disabled, QPalette::ButtonText, brush12); palette8.setBrush(QPalette::Disabled, QPalette::Base, brush6); palette8.setBrush(QPalette::Disabled, QPalette::Window, brush7); palette8.setBrush(QPalette::Disabled, QPalette::Shadow, brush); palette8.setBrush(QPalette::Disabled, QPalette::Highlight, brush8); palette8.setBrush(QPalette::Disabled, QPalette::HighlightedText, brush6); palette8.setBrush(QPalette::Disabled, QPalette::Link, brush10); palette8.setBrush(QPalette::Disabled, QPalette::LinkVisited, brush11); ButCloseMenu->setPalette(palette8); ButMenuOK = new QPushButton(frame14_2); ButMenuOK->setObjectName(QStringLiteral("ButMenuOK")); ButMenuOK->setGeometry(QRect(290, 58, 98, 25)); ButMenuCancel = new QPushButton(frame14_2); ButMenuCancel->setObjectName(QStringLiteral("ButMenuCancel")); ButMenuCancel->setGeometry(QRect(291, 85, 98, 25)); retranslateUi(Dialog); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "PTZ", Q_NULLPTR)); textLabel2->setText(QApplication::translate("Dialog", "Channel NO.", Q_NULLPTR)); textLabel1_2->setText(QApplication::translate("Dialog", "Preset NO.", Q_NULLPTR)); pushButSet->setText(QApplication::translate("Dialog", "Set", Q_NULLPTR)); pushButPresetDel->setText(QApplication::translate("Dialog", "Delete", Q_NULLPTR)); pushButGotoPreset->setText(QApplication::translate("Dialog", "Go To", Q_NULLPTR)); IP->setText(QApplication::translate("Dialog", "IP", Q_NULLPTR)); Port->setText(QApplication::translate("Dialog", "Port", Q_NULLPTR)); PassWord->setText(QApplication::translate("Dialog", "PassWord", Q_NULLPTR)); UserName->setText(QApplication::translate("Dialog", "UserName", Q_NULLPTR)); lineEdit4->setText(QApplication::translate("Dialog", "admin", Q_NULLPTR)); lineEdit3->setText(QApplication::translate("Dialog", "admin", Q_NULLPTR)); lineEdit1->setText(QApplication::translate("Dialog", "10.7.4.23", Q_NULLPTR)); lineEdit2->setText(QApplication::translate("Dialog", "37777", Q_NULLPTR)); Login->setText(QApplication::translate("Dialog", "Login", Q_NULLPTR)); Logout->setText(QApplication::translate("Dialog", "Logout", Q_NULLPTR)); textLabel3->setText(QApplication::translate("Dialog", "Preset No", Q_NULLPTR)); textLabel2_2->setText(QApplication::translate("Dialog", "AutoTour", Q_NULLPTR)); ButStartTour->setText(QApplication::translate("Dialog", "Start Tour", Q_NULLPTR)); ButStopTour->setText(QApplication::translate("Dialog", "Stop Tour", Q_NULLPTR)); ButAddTour->setText(QApplication::translate("Dialog", "Add Preset To Tour", Q_NULLPTR)); ButDelTourPreset->setText(QApplication::translate("Dialog", "Del Preset From Tour", Q_NULLPTR)); ButDelTourNo->setText(QApplication::translate("Dialog", "Delete Tour NO.", Q_NULLPTR)); textLabel5->setText(QApplication::translate("Dialog", "Auto Scan :", Q_NULLPTR)); ButLimitLeft->setText(QApplication::translate("Dialog", "Left Limit", Q_NULLPTR)); ButLimitRight->setText(QApplication::translate("Dialog", "Right Limit", Q_NULLPTR)); ButStartScan->setText(QApplication::translate("Dialog", "Start", Q_NULLPTR)); butStopScan->setText(QApplication::translate("Dialog", "Stop", Q_NULLPTR)); textLabel1->setText(QApplication::translate("Dialog", "Ctrol Parm", Q_NULLPTR)); comboxCtrlParam->clear(); comboxCtrlParam->insertItems(0, QStringList() << QApplication::translate("Dialog", "1", Q_NULLPTR) << QApplication::translate("Dialog", "2", Q_NULLPTR) << QApplication::translate("Dialog", "3", Q_NULLPTR) << QApplication::translate("Dialog", "4", Q_NULLPTR) << QApplication::translate("Dialog", "5", Q_NULLPTR) << QApplication::translate("Dialog", "6", Q_NULLPTR) << QApplication::translate("Dialog", "7", Q_NULLPTR) << QApplication::translate("Dialog", "8", Q_NULLPTR) ); pushButRightUP->setText(QApplication::translate("Dialog", "Right up", Q_NULLPTR)); pushButRight->setText(QApplication::translate("Dialog", "Right", Q_NULLPTR)); pushButRDown->setText(QApplication::translate("Dialog", "Right Down", Q_NULLPTR)); pushButDZoom->setText(QApplication::translate("Dialog", "Zoom -", Q_NULLPTR)); pushButDFocus->setText(QApplication::translate("Dialog", "Focus -", Q_NULLPTR)); pushButDAperture->setText(QApplication::translate("Dialog", "Aperture -", Q_NULLPTR)); pushButLeft->setText(QApplication::translate("Dialog", "Left", Q_NULLPTR)); pushButLeftDown->setText(QApplication::translate("Dialog", "Left Down", Q_NULLPTR)); pushButAZoom->setText(QApplication::translate("Dialog", "Zoom +", Q_NULLPTR)); pushButAFocus->setText(QApplication::translate("Dialog", "Focus +", Q_NULLPTR)); pushButAperture->setText(QApplication::translate("Dialog", "Aperture +", Q_NULLPTR)); pushButDown->setText(QApplication::translate("Dialog", "Down", Q_NULLPTR)); pushButLeftUp->setText(QApplication::translate("Dialog", "Left Up", Q_NULLPTR)); pushButUp->setText(QApplication::translate("Dialog", "UP", Q_NULLPTR)); textLabel10->setText(QApplication::translate("Dialog", "Zoom", Q_NULLPTR)); textLabel9->setText(QApplication::translate("Dialog", "Y", Q_NULLPTR)); textLabel8->setText(QApplication::translate("Dialog", "X", Q_NULLPTR)); textLabel7->setText(QApplication::translate("Dialog", "SIT :", Q_NULLPTR)); ButSIT->setText(QApplication::translate("Dialog", "SIT", Q_NULLPTR)); textLabel6->setText(QApplication::translate("Dialog", "Auto Pan :", Q_NULLPTR)); ButStartPan->setText(QApplication::translate("Dialog", "Start", Q_NULLPTR)); ButStopPan->setText(QApplication::translate("Dialog", "Stop", Q_NULLPTR)); textLabel11->setText(QApplication::translate("Dialog", "AUX NO.", Q_NULLPTR)); comboxAuxNo->clear(); comboxAuxNo->insertItems(0, QStringList() << QApplication::translate("Dialog", "23", Q_NULLPTR) << QApplication::translate("Dialog", "24", Q_NULLPTR) << QApplication::translate("Dialog", "27", Q_NULLPTR) << QApplication::translate("Dialog", "41", Q_NULLPTR) << QApplication::translate("Dialog", "43", Q_NULLPTR) ); ButOpenAUX->setText(QApplication::translate("Dialog", "Open", Q_NULLPTR)); ButCloseAUX->setText(QApplication::translate("Dialog", "Close", Q_NULLPTR)); textLabel4->setText(QApplication::translate("Dialog", " Pattern", Q_NULLPTR)); ButStartProgram->setText(QApplication::translate("Dialog", "Program Start", Q_NULLPTR)); ButStopProgram->setText(QApplication::translate("Dialog", "Program Stop", Q_NULLPTR)); ButStartPatterm->setText(QApplication::translate("Dialog", "Pattern Start", Q_NULLPTR)); ButStopPatterm->setText(QApplication::translate("Dialog", "Pattern Stop", Q_NULLPTR)); ButDelPatterm->setText(QApplication::translate("Dialog", "Delete", Q_NULLPTR)); textLabel1_3->setText(QApplication::translate("Dialog", "PTZ Menu", Q_NULLPTR)); ButMenuLeft->setText(QApplication::translate("Dialog", "Left", Q_NULLPTR)); ButMenuUP->setText(QApplication::translate("Dialog", "UP", Q_NULLPTR)); ButMenuDown->setText(QApplication::translate("Dialog", "Down", Q_NULLPTR)); ButMenuRight->setText(QApplication::translate("Dialog", "Right", Q_NULLPTR)); ButOpenMenu->setText(QApplication::translate("Dialog", "Open Menu", Q_NULLPTR)); ButCloseMenu->setText(QApplication::translate("Dialog", "Close Menu", Q_NULLPTR)); ButMenuOK->setText(QApplication::translate("Dialog", "OK", Q_NULLPTR)); ButMenuCancel->setText(QApplication::translate("Dialog", "Cancel", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_DIALOG_H
[ "benjamin.habegger@axiamo.com" ]
benjamin.habegger@axiamo.com
ed7a4aeba0ee3b7e465a783d992e66a15405b317
48d5dbf4475448f5df6955f418d7c42468d2a165
/SDK/SoT_BP_fod_Plentifin_03_AmberRaw_00_a_ItemDesc_functions.cpp
371e6fe49476ba17cda58f5ef5b4b5c4264a93bb
[]
no_license
Outshynd/SoT-SDK-1
80140ba84fe9f2cdfd9a402b868099df4e8b8619
8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4
refs/heads/master
2022-11-21T04:35:29.362290
2020-07-10T14:50:55
2020-07-10T14:50:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
// Sea of Thieves (1.4.16) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_fod_Plentifin_03_AmberRaw_00_a_ItemDesc_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "53855178+Shat-sky@users.noreply.github.com" ]
53855178+Shat-sky@users.noreply.github.com
cfdad73fe4d57e49452705b311dd9070b9314ab4
3466c2193223e00505d7fefaeb0dd51424017a63
/chapter-p/quiz-loops-01.cpp
4f931798fdf0e1ef3dcf3a5d8946f697e9b24b3d
[]
no_license
ohduran/reviewcpp
6c7a9a9cb131eec192f4e9359398dc42faa8f14f
30018d98cd0789791b829c48ff908ccaadfece9b
refs/heads/master
2023-01-19T00:25:38.347885
2020-11-09T06:55:18
2020-11-09T06:55:18
301,610,156
0
0
null
2020-12-11T11:28:00
2020-10-06T04:07:46
C++
UTF-8
C++
false
false
325
cpp
#include <iostream> #include <iterator> int main() { const int scores[] = {4, 6, 7, 3, 8, 2, 1, 9, 5}; const int numStudents = static_cast<int>(sizeof(scores) / sizeof(scores[0])); for (int student = 0; student < numStudents; student++) { std::cout << scores[student] << '\n'; } return 0; }
[ "alvaro.duranb@hotmail.com" ]
alvaro.duranb@hotmail.com
ea2f14b0fd74dd1891f82de86e6ed97f9c06e3e4
60ea8793239386d19298afbd8e101762069830f8
/通用代码/装饰模式(C++)/ConcreteComponent.cpp
50cea9e6808949166e09ad1a496b796ae783c8ea
[]
no_license
szschao/ZenOfDesignPatterns
ff11dc1fdd3220fe74a6b9d8d1ee5f7ef361d859
e83b85c8dbf23178be43ca34c3c7b74b3d730630
refs/heads/master
2021-01-10T03:14:46.425010
2016-04-07T16:50:15
2016-04-07T16:50:15
52,878,757
0
0
null
null
null
null
UTF-8
C++
false
false
357
cpp
#include "ConcreteComponent.h" using namespace std; ConcreteComponent::ConcreteComponent() { cout << "ConcreteComponent Construct" << endl; } ConcreteComponent::~ConcreteComponent() { cout << "~ConcreteComponent" << endl; } //重写父类方法 void ConcreteComponent::Operate() { cout << "原职责:do Something" << endl; }
[ "sc@cuihuadeMacBook-Pro.local" ]
sc@cuihuadeMacBook-Pro.local
0fb8dc61621b339a664f579491c69e21ffad59ff
a1a8b69b2a24fd86e4d260c8c5d4a039b7c06286
/build/iOS/Release/include/Fuse.Triggers.Actions.BringToFront.h
89ceea0bcf6391aab5ed02fae0ec99897fdf5738
[]
no_license
epireve/hikr-tute
df0af11d1cfbdf6e874372b019d30ab0541c09b7
545501fba7044b4cc927baea2edec0674769e22c
refs/heads/master
2021-09-02T13:54:05.359975
2018-01-03T01:21:31
2018-01-03T01:21:31
115,536,756
0
0
null
null
null
null
UTF-8
C++
false
false
1,085
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Controls/1.4.2/Triggers/BringToFront.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Triggers.Actions.TriggerAction.h> namespace g{namespace Fuse{namespace Triggers{namespace Actions{struct BringToFront;}}}} namespace g{namespace Fuse{struct Node;}} namespace g{namespace Fuse{struct Visual;}} namespace g{ namespace Fuse{ namespace Triggers{ namespace Actions{ // public sealed class BringToFront :37 // { ::g::Fuse::Triggers::Actions::TriggerAction_type* BringToFront_typeof(); void BringToFront__Perform_fn(BringToFront* __this, ::g::Fuse::Node* target); void BringToFront__get_Target_fn(BringToFront* __this, ::g::Fuse::Visual** __retval); void BringToFront__set_Target_fn(BringToFront* __this, ::g::Fuse::Visual* value); struct BringToFront : ::g::Fuse::Triggers::Actions::TriggerAction { uStrong< ::g::Fuse::Visual*> _Target; ::g::Fuse::Visual* Target(); void Target(::g::Fuse::Visual* value); }; // } }}}} // ::g::Fuse::Triggers::Actions
[ "i@firdaus.my" ]
i@firdaus.my
a0b71f67cf42c038707a3ddb217a17a466c66faa
3a64d611b73e036ad01d0a84986a2ad56f4505d5
/chrome/browser/ui/views/payments/shipping_address_editor_view_controller.cc
95cf8b8b720dbde754b12ade871c858832880882
[ "BSD-3-Clause" ]
permissive
ISSuh/chromium
d32d1fccc03d7a78cd2fbebbba6685a3e16274a2
e045f43a583f484cc4a9dfcbae3a639bb531cff1
refs/heads/master
2023-03-17T04:03:11.111290
2020-09-26T11:39:44
2020-09-26T11:39:44
298,805,518
0
0
BSD-3-Clause
2020-09-26T12:04:46
2020-09-26T12:04:46
null
UTF-8
C++
false
false
24,062
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/payments/shipping_address_editor_view_controller.h" #include "base/bind.h" #include "base/callback.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/ui/views/payments/payment_request_dialog_view.h" #include "chrome/browser/ui/views/payments/payment_request_dialog_view_ids.h" #include "chrome/browser/ui/views/payments/validating_combobox.h" #include "chrome/browser/ui/views/payments/validating_textfield.h" #include "chrome/grit/generated_resources.h" #include "components/autofill/core/browser/autofill_address_util.h" #include "components/autofill/core/browser/autofill_type.h" #include "components/autofill/core/browser/field_types.h" #include "components/autofill/core/browser/geo/address_i18n.h" #include "components/autofill/core/browser/geo/autofill_country.h" #include "components/autofill/core/browser/geo/phone_number_i18n.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/browser/ui/country_combobox_model.h" #include "components/autofill/core/browser/validation.h" #include "components/autofill/core/common/autofill_constants.h" #include "components/autofill/core/common/autofill_l10n_util.h" #include "components/payments/content/payment_request_state.h" #include "components/payments/core/payment_request_data_util.h" #include "components/payments/core/payments_profile_comparator.h" #include "components/strings/grit/components_strings.h" #include "third_party/libaddressinput/messages.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_data.h" #include "third_party/libaddressinput/src/cpp/include/libaddressinput/address_formatter.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/textfield/textfield.h" namespace payments { namespace { // size_t doesn't have a defined maximum value, so this is a trick to create one // as is done for std::string::npos. // http://www.cplusplus.com/reference/string/string/npos const size_t kInvalidCountryIndex = static_cast<size_t>(-1); } // namespace ShippingAddressEditorViewController::ShippingAddressEditorViewController( PaymentRequestSpec* spec, PaymentRequestState* state, PaymentRequestDialogView* dialog, BackNavigationType back_navigation_type, base::OnceClosure on_edited, base::OnceCallback<void(const autofill::AutofillProfile&)> on_added, autofill::AutofillProfile* profile, bool is_incognito) : EditorViewController(spec, state, dialog, back_navigation_type, is_incognito), on_edited_(std::move(on_edited)), on_added_(std::move(on_added)), profile_to_edit_(profile), chosen_country_index_(kInvalidCountryIndex), failed_to_load_region_data_(false) { if (profile_to_edit_) temporary_profile_ = *profile_to_edit_; UpdateCountries(/*model=*/nullptr); UpdateEditorFields(); } ShippingAddressEditorViewController::~ShippingAddressEditorViewController() {} bool ShippingAddressEditorViewController::IsEditingExistingItem() { return !!profile_to_edit_; } std::vector<EditorField> ShippingAddressEditorViewController::GetFieldDefinitions() { return editor_fields_; } base::string16 ShippingAddressEditorViewController::GetInitialValueForType( autofill::ServerFieldType type) { return GetValueForType(temporary_profile_, type); } bool ShippingAddressEditorViewController::ValidateModelAndSave() { // To validate the profile first, we use a temporary object. autofill::AutofillProfile profile; if (!SaveFieldsToProfile(&profile, /*ignore_errors=*/false)) return false; if (!profile_to_edit_) { // Add the profile (will not add a duplicate). profile.set_origin(autofill::kSettingsOrigin); if (!is_incognito()) state()->GetPersonalDataManager()->AddProfile(profile); std::move(on_added_).Run(profile); on_edited_.Reset(); } else { autofill::ServerFieldTypeSet all_fields; profile_to_edit_->GetSupportedTypes(&all_fields); // Clear all the address data in |profile_to_edit_| except the email field, // in anticipation of adding only the fields present in the editor. Prefer // this method to copying |profile| into |profile_to_edit_|, because the // latter object needs to retain other properties (use count, use date, // guid, etc.). for (autofill::ServerFieldType type : all_fields) { if (type != autofill::ServerFieldType::EMAIL_ADDRESS) { profile_to_edit_->SetRawInfo(type, base::string16()); } } bool success = SaveFieldsToProfile(profile_to_edit_, /*ignore_errors=*/false); DCHECK(success); profile_to_edit_->set_origin(autofill::kSettingsOrigin); if (!is_incognito()) state()->GetPersonalDataManager()->UpdateProfile(*profile_to_edit_); state()->profile_comparator()->Invalidate(*profile_to_edit_); std::move(on_edited_).Run(); on_added_.Reset(); } return true; } std::unique_ptr<ValidationDelegate> ShippingAddressEditorViewController::CreateValidationDelegate( const EditorField& field) { return std::make_unique< ShippingAddressEditorViewController::ShippingAddressValidationDelegate>( this, field); } std::unique_ptr<ui::ComboboxModel> ShippingAddressEditorViewController::GetComboboxModelForType( const autofill::ServerFieldType& type) { switch (type) { case autofill::ADDRESS_HOME_COUNTRY: { auto model = std::make_unique<autofill::CountryComboboxModel>(); model->SetCountries(*state()->GetPersonalDataManager(), base::Callback<bool(const std::string&)>(), state()->GetApplicationLocale()); if (model->countries().size() != countries_.size()) UpdateCountries(model.get()); return model; } case autofill::ADDRESS_HOME_STATE: { auto model = std::make_unique<autofill::RegionComboboxModel>(); region_model_ = model.get(); if (chosen_country_index_ < countries_.size()) { model->LoadRegionData(countries_[chosen_country_index_].first, state()->GetRegionDataLoader(), /*timeout_ms=*/5000); if (!model->IsPendingRegionDataLoad()) { // If the data was already pre-loaded, the observer won't get notified // so we have to check for failure here. failed_to_load_region_data_ = model->failed_to_load_data(); } } else { failed_to_load_region_data_ = true; } if (failed_to_load_region_data_) { // We can't update the view synchronously while building the view. OnDataChanged(/*synchronous=*/false); } return model; } default: NOTREACHED(); break; } return std::unique_ptr<ui::ComboboxModel>(); } void ShippingAddressEditorViewController::OnPerformAction( ValidatingCombobox* sender) { EditorViewController::OnPerformAction(sender); if (sender->GetID() != GetInputFieldViewId(autofill::ADDRESS_HOME_COUNTRY)) return; DCHECK_GE(sender->GetSelectedIndex(), 0); if (chosen_country_index_ != static_cast<size_t>(sender->GetSelectedIndex())) { chosen_country_index_ = sender->GetSelectedIndex(); failed_to_load_region_data_ = false; // View update must be asynchronous to let the combobox finish performing // the action. OnDataChanged(/*synchronous=*/false); } } void ShippingAddressEditorViewController::UpdateEditorView() { region_model_ = nullptr; EditorViewController::UpdateEditorView(); if (chosen_country_index_ > 0UL && chosen_country_index_ < countries_.size()) { views::Combobox* country_combo_box = static_cast<views::Combobox*>(dialog()->GetViewByID( GetInputFieldViewId(autofill::ADDRESS_HOME_COUNTRY))); DCHECK(country_combo_box); DCHECK_EQ(countries_.size(), static_cast<size_t>(country_combo_box->GetRowCount())); country_combo_box->SetSelectedIndex(chosen_country_index_); } else if (countries_.size() > 0UL) { chosen_country_index_ = 0UL; } else { chosen_country_index_ = kInvalidCountryIndex; } } base::string16 ShippingAddressEditorViewController::GetSheetTitle() { // TODO(crbug.com/712074): Editor title should reflect the missing information // in the case that one or more fields are missing. return profile_to_edit_ ? l10n_util::GetStringUTF16(IDS_PAYMENTS_EDIT_ADDRESS) : l10n_util::GetStringUTF16(IDS_PAYMENTS_ADD_ADDRESS); } std::unique_ptr<views::Button> ShippingAddressEditorViewController::CreatePrimaryButton() { std::unique_ptr<views::Button> button( EditorViewController::CreatePrimaryButton()); button->SetID(static_cast<int>(DialogViewID::SAVE_ADDRESS_BUTTON)); return button; } ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: ShippingAddressValidationDelegate( ShippingAddressEditorViewController* controller, const EditorField& field) : field_(field), controller_(controller) {} ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: ~ShippingAddressValidationDelegate() {} bool ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: ShouldFormat() { return field_.type == autofill::PHONE_HOME_WHOLE_NUMBER; } base::string16 ShippingAddressEditorViewController::ShippingAddressValidationDelegate::Format( const base::string16& text) { if (controller_->chosen_country_index_ < controller_->countries_.size()) { return base::UTF8ToUTF16(autofill::i18n::FormatPhoneForDisplay( base::UTF16ToUTF8(text), controller_->countries_[controller_->chosen_country_index_].first)); } else { return text; } } bool ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: IsValidTextfield(views::Textfield* textfield, base::string16* error_message) { return ValidateValue(textfield->GetText(), error_message); } bool ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: IsValidCombobox(ValidatingCombobox* combobox, base::string16* error_message) { return ValidateValue(combobox->GetTextForRow(combobox->GetSelectedIndex()), error_message); } bool ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: TextfieldValueChanged(views::Textfield* textfield, bool was_blurred) { if (!was_blurred) return true; base::string16 error_message; bool is_valid = ValidateValue(textfield->GetText(), &error_message); controller_->DisplayErrorMessageForField(field_.type, error_message); return is_valid; } bool ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: ComboboxValueChanged(ValidatingCombobox* combobox) { base::string16 error_message; bool is_valid = ValidateValue( combobox->GetTextForRow(combobox->GetSelectedIndex()), &error_message); controller_->DisplayErrorMessageForField(field_.type, error_message); return is_valid; } void ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: ComboboxModelChanged(ValidatingCombobox* combobox) { controller_->OnComboboxModelChanged(combobox); } bool ShippingAddressEditorViewController::ShippingAddressValidationDelegate:: ValidateValue(const base::string16& value, base::string16* error_message) { if (!controller_->spec()) return false; // Show errors from merchant's retry() call. Note that changing the selected // shipping address will clear the validation errors from retry(). autofill::AutofillProfile* invalid_shipping_profile = controller_->state()->invalid_shipping_profile(); if (invalid_shipping_profile && error_message && value == controller_->GetValueForType(*invalid_shipping_profile, field_.type)) { *error_message = controller_->spec()->GetShippingAddressError(field_.type); if (!error_message->empty()) return false; } if (!value.empty()) { if (field_.type == autofill::PHONE_HOME_WHOLE_NUMBER && controller_->chosen_country_index_ < controller_->countries_.size() && !autofill::IsPossiblePhoneNumber( value, controller_->countries_[controller_->chosen_country_index_] .first)) { if (error_message) { *error_message = l10n_util::GetStringUTF16( IDS_PAYMENTS_PHONE_INVALID_VALIDATION_MESSAGE); } return false; } if (field_.type == autofill::ADDRESS_HOME_STATE && value == l10n_util::GetStringUTF16(IDS_AUTOFILL_LOADING_REGIONS)) { // Wait for the regions to be loaded or timeout before assessing validity. return false; } // As long as other field types are non-empty, they are valid. return true; } if (error_message && field_.required) { *error_message = l10n_util::GetStringUTF16( IDS_PREF_EDIT_DIALOG_FIELD_REQUIRED_VALIDATION_MESSAGE); } return !field_.required; } base::string16 ShippingAddressEditorViewController::GetValueForType( const autofill::AutofillProfile& profile, autofill::ServerFieldType type) { if (type == autofill::PHONE_HOME_WHOLE_NUMBER) { return autofill::i18n::GetFormattedPhoneNumberForDisplay( profile, state()->GetApplicationLocale()); } if (type == autofill::ADDRESS_HOME_STATE && region_model_) { // For the state, check if the initial value matches either a region code or // a region name. base::string16 initial_region = profile.GetInfo(type, state()->GetApplicationLocale()); autofill::l10n::CaseInsensitiveCompare compare; for (const auto& region : region_model_->GetRegions()) { if (compare.StringsEqual(initial_region, base::UTF8ToUTF16(region.first)) || compare.StringsEqual(initial_region, base::UTF8ToUTF16(region.second))) { return base::UTF8ToUTF16(region.second); } } return initial_region; } if (type == autofill::ADDRESS_HOME_STREET_ADDRESS) { std::string street_address_line; i18n::addressinput::GetStreetAddressLinesAsSingleLine( *autofill::i18n::CreateAddressDataFromAutofillProfile( profile, state()->GetApplicationLocale()), &street_address_line); return base::UTF8ToUTF16(street_address_line); } return profile.GetInfo(type, state()->GetApplicationLocale()); } bool ShippingAddressEditorViewController::GetSheetId(DialogViewID* sheet_id) { *sheet_id = DialogViewID::SHIPPING_ADDRESS_EDITOR_SHEET; return true; } void ShippingAddressEditorViewController::UpdateCountries( autofill::CountryComboboxModel* model) { autofill::CountryComboboxModel local_model; if (!model) { local_model.SetCountries(*state()->GetPersonalDataManager(), base::Callback<bool(const std::string&)>(), state()->GetApplicationLocale()); model = &local_model; } for (size_t i = 0; i < model->countries().size(); ++i) { autofill::AutofillCountry* country(model->countries()[i].get()); if (country) { countries_.push_back( std::make_pair(country->country_code(), country->name())); } else { // Separator, kept to make sure the size of the vector stays the same. countries_.push_back(std::make_pair("", base::UTF8ToUTF16(""))); } } // If there is a profile to edit, make sure to use its country for the initial // |chosen_country_index_|. if (IsEditingExistingItem()) { base::string16 chosen_country(temporary_profile_.GetInfo( autofill::ADDRESS_HOME_COUNTRY, state()->GetApplicationLocale())); for (chosen_country_index_ = 0; chosen_country_index_ < countries_.size(); ++chosen_country_index_) { if (chosen_country == countries_[chosen_country_index_].second) break; } // Make sure the the country was actually found in |countries_| and was not // empty, otherwise set |chosen_country_index_| to index 0, which is the // default country based on the locale. if (chosen_country_index_ >= countries_.size() || chosen_country.empty()) { // But only if there is at least one country. if (!countries_.empty()) { LOG(ERROR) << "Unexpected country: " << chosen_country; chosen_country_index_ = 0; temporary_profile_.SetInfo(autofill::ADDRESS_HOME_COUNTRY, countries_[chosen_country_index_].second, state()->GetApplicationLocale()); } else { LOG(ERROR) << "Unexpected empty country list!"; chosen_country_index_ = kInvalidCountryIndex; } } } else if (!countries_.empty()) { chosen_country_index_ = 0; } } void ShippingAddressEditorViewController::UpdateEditorFields() { editor_fields_.clear(); std::string chosen_country_code; if (chosen_country_index_ < countries_.size()) chosen_country_code = countries_[chosen_country_index_].first; std::unique_ptr<base::ListValue> components(new base::ListValue); autofill::GetAddressComponents(chosen_country_code, state()->GetApplicationLocale(), components.get(), &language_code_); // Insert the Country combobox at the top. editor_fields_.emplace_back( autofill::ADDRESS_HOME_COUNTRY, l10n_util::GetStringUTF16(IDS_LIBADDRESSINPUT_COUNTRY_OR_REGION_LABEL), EditorField::LengthHint::HINT_SHORT, /*required=*/true, EditorField::ControlType::COMBOBOX); for (size_t line_index = 0; line_index < components->GetSize(); ++line_index) { const base::ListValue* line = nullptr; if (!components->GetList(line_index, &line)) { NOTREACHED(); return; } DCHECK_NE(nullptr, line); for (size_t component_index = 0; component_index < line->GetSize(); ++component_index) { const base::DictionaryValue* component = nullptr; if (!line->GetDictionary(component_index, &component)) { NOTREACHED(); return; } std::string field_type; if (!component->GetString(autofill::kFieldTypeKey, &field_type)) { NOTREACHED(); return; } std::string field_name; if (!component->GetString(autofill::kFieldNameKey, &field_name)) { NOTREACHED(); return; } bool field_length; if (!component->GetBoolean(autofill::kFieldLengthKey, &field_length)) { NOTREACHED(); return; } EditorField::LengthHint length_hint = EditorField::LengthHint::HINT_SHORT; if (field_length == autofill::kLongField) length_hint = EditorField::LengthHint::HINT_LONG; else DCHECK_EQ(autofill::kShortField, field_length); autofill::ServerFieldType server_field_type = autofill::GetFieldTypeFromString(field_type); EditorField::ControlType control_type = EditorField::ControlType::TEXTFIELD; if (server_field_type == autofill::ADDRESS_HOME_COUNTRY || (server_field_type == autofill::ADDRESS_HOME_STATE && !failed_to_load_region_data_)) { control_type = EditorField::ControlType::COMBOBOX; } editor_fields_.emplace_back(server_field_type, base::UTF8ToUTF16(field_name), length_hint, autofill::i18n::IsFieldRequired( server_field_type, chosen_country_code) || server_field_type == autofill::NAME_FULL, control_type); } } // Always add phone number at the end. editor_fields_.emplace_back( autofill::PHONE_HOME_WHOLE_NUMBER, l10n_util::GetStringUTF16(IDS_AUTOFILL_FIELD_LABEL_PHONE), EditorField::LengthHint::HINT_SHORT, /*required=*/true, EditorField::ControlType::TEXTFIELD_NUMBER); } void ShippingAddressEditorViewController::OnDataChanged(bool synchronous) { SaveFieldsToProfile(&temporary_profile_, /*ignore_errors*/ true); // Normalization is guaranteed to be synchronous and rules should have been // loaded already. state()->GetAddressNormalizer()->NormalizeAddressSync(&temporary_profile_); UpdateEditorFields(); if (synchronous) { UpdateEditorView(); } else { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&ShippingAddressEditorViewController::UpdateEditorView, weak_ptr_factory_.GetWeakPtr())); } } bool ShippingAddressEditorViewController::SaveFieldsToProfile( autofill::AutofillProfile* profile, bool ignore_errors) { const std::string& locale = state()->GetApplicationLocale(); // The country must be set first, because the profile uses the country to // interpret some of the data (e.g., phone numbers) passed to SetInfo. views::Combobox* combobox = static_cast<views::Combobox*>(dialog()->GetViewByID( GetInputFieldViewId(autofill::ADDRESS_HOME_COUNTRY))); // The combobox can be null when saving to temporary profile while updating // the view. if (combobox) { base::string16 country( combobox->GetTextForRow(combobox->GetSelectedIndex())); bool success = profile->SetInfo(autofill::ADDRESS_HOME_COUNTRY, country, locale); LOG_IF(ERROR, !success && !ignore_errors) << "Can't set profile country to: " << country; if (!success && !ignore_errors) return false; } bool success = true; for (const auto& field : text_fields()) { // ValidatingTextfield* is the key, EditorField is the value. if (field.first->IsValid()) { success = profile->SetInfo(field.second.type, field.first->GetText(), locale); } else { success = false; } LOG_IF(ERROR, !success && !ignore_errors) << "Can't setinfo(" << field.second.type << ", " << field.first->GetText(); if (!success && !ignore_errors) return false; } for (const auto& field : comboboxes()) { // ValidatingCombobox* is the key, EditorField is the value. ValidatingCombobox* combobox = field.first; // The country has already been dealt with. if (combobox->GetID() == GetInputFieldViewId(autofill::ADDRESS_HOME_COUNTRY)) continue; if (combobox->IsValid()) { success = profile->SetInfo( field.second.type, combobox->GetTextForRow(combobox->GetSelectedIndex()), locale); } else { success = false; } LOG_IF(ERROR, !success && !ignore_errors) << "Can't setinfo(" << field.second.type << ", " << combobox->GetTextForRow(combobox->GetSelectedIndex()); if (!success && !ignore_errors) return false; } profile->set_language_code(language_code_); return success; } void ShippingAddressEditorViewController::OnComboboxModelChanged( ValidatingCombobox* combobox) { if (combobox->GetID() != GetInputFieldViewId(autofill::ADDRESS_HOME_STATE)) return; autofill::RegionComboboxModel* model = static_cast<autofill::RegionComboboxModel*>(combobox->model()); if (model->IsPendingRegionDataLoad()) return; if (model->failed_to_load_data()) { failed_to_load_region_data_ = true; // It is safe to update synchronously since the change comes from the model // and not from the UI. OnDataChanged(/*synchronous=*/true); } else { base::string16 state_value = GetInitialValueForType(autofill::ADDRESS_HOME_STATE); if (!state_value.empty()) { combobox->SelectValue(state_value); OnPerformAction(combobox); } } } } // namespace payments
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
98165f60598c56c6c47810163c30864865c59506
4cc8a7f7406f026624a6dcf519450db42ac04712
/circle.h
d23a581c9602b80ebab6388330de2fcc52a3fce7
[]
no_license
csilva25/Shapes
18611842b185f347de885115033f934e959b524b
097a11c033ca2684338df140c3f825e5badca5c4
refs/heads/master
2021-01-11T21:14:36.313721
2017-01-17T22:05:57
2017-01-17T22:05:57
79,276,803
2
1
null
null
null
null
UTF-8
C++
false
false
276
h
//p6 //Cristian Silva //upbeatfish #ifndef CIRCLE_H #define CIRCLE_H #include "circle.h" #include "shape.h" #include <iostream> using namespace std; class Circle : public Shape { public: Circle(int y, int x); void draw(Grid &grid); protected: }; #endif
[ "csilva25@mail.csuchico.edu" ]
csilva25@mail.csuchico.edu
904f7f88aa41a82216161f801b24fe1d67d2fc48
882ec9153b4e1eb36d710ec6bcb410355cfb5910
/nucleus/io/sam_writer.h
bee6262efc085487bedd7d1249ec701a7b6b24da
[ "Apache-2.0" ]
permissive
PulluriRohith/nucleus
ca9be5293e11ee09cd69df3c9e7207f003dc87d1
837325b7f549fe0d71bc42a4d0826d7a084a3c99
refs/heads/master
2020-09-11T06:39:21.517041
2019-11-15T17:52:38
2019-11-15T17:52:38
221,975,035
0
0
Apache-2.0
2019-11-15T17:46:49
2019-11-15T17:46:49
null
UTF-8
C++
false
false
3,912
h
/* * Copyright 2018 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef THIRD_PARTY_NUCLEUS_IO_SAM_WRITER_H_ #define THIRD_PARTY_NUCLEUS_IO_SAM_WRITER_H_ #include <memory> #include <string> #include "htslib/hts.h" #include "htslib/sam.h" #include "nucleus/platform/types.h" #include "nucleus/protos/reads.pb.h" #include "nucleus/util/proto_ptr.h" #include "nucleus/vendor/statusor.h" #include "tensorflow/core/lib/core/status.h" namespace nucleus { // A SAM/BAM/CRAM writer. // // SAM/BAM/CRAM files store information about a biological sequence and its // corresponding quality scores. // // https://samtools.github.io/hts-specs/SAMv1.pdf // https://samtools.github.io/hts-specs/CRAMv3.pdf // This class converts nucleus.genomics.v1.SamHeader and // nucleus.genomics.v1.Read to a file based on the file path passed in. // // This uses the htslib C API for writing NGS reads (BAM, SAM, SAM). For details // of the API, see: // https://github.com/samtools/htslib/tree/develop/htslib // class SamWriter { public: // Creates a new SamWriter writing to the file at |sam_path|, which is // opened and created if needed. Returns either a unique_ptr to the // SamWriter or a Status indicating why an error occurred. static StatusOr<std::unique_ptr<SamWriter>> ToFile( const string& sam_path, const nucleus::genomics::v1::SamHeader& sam_header); // Creates a new SamWriter writing to the file at |sam_path|, which is // opened and created if needed. |ref_path|, which points to an external // reference FASTA file, cannot be empty for CRAM files. If |embed_ref|, the // CRAM output file will embed the references in the output file. Returns // either a unique_ptr to the SamWriter or a Status indicating why an error // occurred. static StatusOr<std::unique_ptr<SamWriter>> ToFile( const string& sam_path, const string& ref_path, bool embed_ref, const nucleus::genomics::v1::SamHeader& sam_header); ~SamWriter(); // Disable copy and assignment operations. SamWriter(const SamWriter& other) = delete; SamWriter& operator=(const SamWriter&) = delete; // Write a Read to the file. // Returns Status::OK() if the write was successful; otherwise the status // provides information about what error occurred. tensorflow::Status Write(const nucleus::genomics::v1::Read& read); tensorflow::Status WritePython( const ConstProtoPtr<const nucleus::genomics::v1::Read>& wrapped) { return Write(*(wrapped.p_)); } // Close the underlying resource descriptors. Returns Status::OK() if the // close was successful; otherwise the status provides information about what // error occurred. tensorflow::Status Close(); // This no-op function is needed only for Python context manager support. Do // not use it! void PythonEnter() const {} private: class NativeHeader; class NativeFile; class NativeBody; // Private constructor; use ToFile to safely create a SamWriter. SamWriter(std::unique_ptr<NativeFile> file, std::unique_ptr<NativeHeader> header); // A pointer to the htslib file used to access the SAM/BAM/CRAM data. std::unique_ptr<NativeFile> native_file_; // A htslib header data structure obtained by parsing the header of this file. std::unique_ptr<NativeHeader> native_header_; }; } // namespace nucleus #endif // THIRD_PARTY_NUCLEUS_IO_SAM_WRITER_H_
[ "copybara-piper@google.com" ]
copybara-piper@google.com
a58e8dcda3b307b89dcca61014c9b9319edba865
035e0f03335c933fe6623d7d8cc3ae5c0962d4e4
/dblpAnalysisApp/listInput.cpp
e32413a4ba7af80038b1d5aa9ca265ce27cb40af
[]
no_license
Crazy0416/Social-Network-Analysis
0c01bd0d8110843a3dd9049b4ce3f19236ea2247
85a3f60826e3c3ac67f4a28a6eb05091fde63f27
refs/heads/master
2021-01-23T06:45:06.244851
2017-06-03T01:58:04
2017-06-03T01:58:04
86,396,020
0
0
null
null
null
null
UHC
C++
false
false
5,422
cpp
#include "listInput.h" #include <qinputdialog.h> /* * GridLayout으로 구성 * Author들의 리스트인 listwidget과 * 선택된 author를 통해 크롤링을 시작하게 만드는 QPushButton으로 구성 */ ListInput::ListInput(QWidget *parent) : QDialog(parent) { // GridLayout 생성 후 listwidget과 버튼 삽입 QGridLayout *topLayout = new QGridLayout(this); listwidget = new QListWidget(this); selectButton = new QPushButton("select",this); topLayout->addWidget(listwidget, 100, 1000); topLayout->addWidget(selectButton, 1200, 100); setLayout(topLayout); setBaseSize(500, 500); //connect QObject::connect(selectButton, SIGNAL(clicked()), this, SLOT(on_PushSelectButton_Clicked())); } /* 소멸자*/ ListInput::~ListInput() { delete listwidget; delete selectButton; } /* * 버튼이 눌렸을 때 실행되는 슬롯 * 버튼이 눌릴 경우 첫 위젯이 실행 됨 -> 2가지 케이스가 존재 * ◇ 1. 선택한 author가 단 하나 존재하여 바로 그 author의 논문 제목 보여주는 URL 받는 경우 http://dblp.uni-trier.de/pers~ 로 된 URL 받음 * -> 제목 바로 크롤링 * ◇ 2. 선택한 author가 비슷한 이름이 여럿 존재하여 비슷한 author들을 보여주는 URL 받는 경우 http://dblp.uni-trier.de/search/author?q=~ 로 된 URL 받음 * -> on_PushSelectButton_Clicked 슬롯 안에서 ListInput 위젯 생성 * -> 비슷한 이름 크롤링하여 QInputDialog::InputItem 에 추가 * -> author를 선택할 때까지 ListInput 실행흐름이 멈춤 * -> 선택한 text의 위치에 존재하는 Element의 href attribute의 URL을 파싱하여 다시 Navigate * -> 선택한 author의 논문 제목 바로 크롤링 */ void ListInput::on_PushSelectButton_Clicked() { // strData : 최근 아이템 text 반환 QString strData = listwidget->currentItem()->text(); // list : strData를 '.' 구분자로 나눈 QStringList QStringList list = strData.split('.'); if (strData != NULL) // 빈칸이 아닌 author를 선택한 경우 { QString strDataName; for (int i = 1; i < list.size(); i++) // 이름에 인덱스 삽입 ex) Alon Y. Levy -> 4.Alon Y. Levy { strDataName.append(list[i]); if(i != list.size() - 1) strDataName.append("."); } qDebug() << strDataName; /////////////// <author 크롤링> WebDriver firefox = Start(Firefox()); string dblpURL = "http://dblp.uni-trier.de/search/author?author="; dblpURL += strDataName.toStdString(); firefox.Navigate(dblpURL); vector<Element> menu; ////////////// </author 크롤링> if ((firefox.GetUrl().find("dblp.uni-trier.de/search") != -1)) // 1. 입력한 author가 여러 사람이 존재하는 경우 { menu = firefox.FindElements(ById("completesearch-authors")); // all_author는 href를 가지는 Element를 다 가져옴으로인해 필요하지 않는 데이터도 크롤링함 -> index를 사용해 해결 vector<Element> all_author = menu[0].FindElements(ByCss("a[href]")); int cnt = 0; // all_author count - 1 int listIndex = 1; // span이 들어간, 즉 index // a[href]를 가지는 Element 배열 중 author를 가지는 element의 인덱스를 저장 // author를 가지지 않는 Element의 위치에는 -1의 값을 가짐 int *authorlistIndex = new int[all_author.size()]; for (int i = 0; i < all_author.size(); i++) authorlistIndex[i] = -1; // 초기화 QStringList authorList; // QInputDialog에 넣을 유사한 author들의 QString List for (Element i : all_author) { if (i.FindElements(ByTag("span")).size() != 0) // i Element가 author 이름 가지고 있다면 조건문 실행 { QString tmp = QString::number(listIndex) + "." + QString::fromStdString(i.GetText()); qDebug() << tmp; authorList << tmp; authorlistIndex[cnt] = listIndex; // authorlistIndex[cnt]에 span의 index 넣는다. listIndex++; } cnt++; } // 검색한 author와 비슷한 이름을 가진 author 고르는 창 QString secontAuthor = QInputDialog::getItem(this, "choose author", "Choose author", authorList); QStringList secondAuthorSplit = secontAuthor.split("."); // secondAuthorIndex : 유사 author를 띄운 InputDialog에서 선택한 author의 인덱스 값 int secondAuthorIndex = secondAuthorSplit[0].toInt(); qDebug() << "similar author index : " << QString::number(secondAuthorIndex); for (int i = 0; i < all_author.size(); i++) { if (authorlistIndex[i] == secondAuthorIndex) // 유사 author의 인덱스 == 그 유사 author를 가진 Element의 인덱스가 같다면 그 URL로 크롤링 { string url = all_author[i].GetAttribute("href"); vector<Element> menu2 = firefox.Navigate(url).FindElements(ByClass("entry")); for (Element i : menu2) { QString tmp = QString::fromStdString(i.FindElement(ByClass("title")).GetText()); // 논문 주제 크롤링 qDebug() << tmp << endl; } } } } else // 2. 입력한 사람이 단 한 사람 존재하는 경우 { menu = firefox.FindElements(ByClass("entry")); for (Element i : menu) { QString tmp = QString::fromStdString(i.FindElement(ByClass("title")).GetText()); // 논문 주제 크롤링 qDebug() << tmp << endl; } } } else // author를 선택하지 못했다면 { qDebug() << "error!!!"; } this->close(); // 이 위젯 종료 }
[ "minmin0416@naver.com" ]
minmin0416@naver.com
0fd9fb4545f7be4b548b0636e53fe0f65235bf56
35182a11c05071524a94ece1f6400716db828e2e
/src/memory.cpp
6df2d533e2a7e10e73a700de437884cb9c251c57
[]
no_license
shrin18/Cpp_practise
054b04a00c76957602316ee77e18f0d78a0f3300
ee1c0ea9c409fc8f3c156ff9a3a6a1a030d578c1
refs/heads/main
2023-01-22T05:25:43.691943
2020-11-19T06:46:57
2020-11-19T06:46:57
305,348,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,586
cpp
#include <iostream> #include <string> #include <vector> #include <array> #define SIZE 5 using namespace std; class Entity{ private: string m_Name; int m_Age; public: Entity(const string& name) : m_Name(name), m_Age(-1) {} Entity(int age) : m_Name("Unknown"), m_Age(age) {} }; void Function() { Entity entity = Entity("Shrinish"); } void PrintEntity(const Entity& entity) { //print } int main(){ int array[5]; int size = 6; int * heaparray = new int [size]; delete[] heaparray; std::array<int, 10> collection; for(int i=0; i<collection.size(); i++) { cout << i << endl; } int num, temp, k = 1, j, r; char hex[50]; cout << "Enter a decimal number"; cin >> num; temp = num; while (temp!=0) { r = temp%16; if (r < 10) hex[k++] = r + 48; else hex[k++] = r + 55; temp = temp/16; } cout << "Hexadecimal equivalent of " << num << "is" ; for(j=1; j>0;j--) { cout << hex[j]; } Entity b = 22; double value = 5.65; double a = (int)value + value; //Static casting //Entity* entity = new Entity(); cout << a << endl; vector<std::string> vector; vector.push_back("Shrinish"); vector.pop_back(); cout << &vector << endl; PrintEntity(Entity("Shrinish")); Entity *e; { Entity entity("Cherno"); e = &entity; } Entity entity = Entity("Shrinish"); cin.get(); }
[ "shrinish@kth.se" ]
shrinish@kth.se
7e62c2a42dc1d9637e6a1eb7ff711a9dac7b2d0b
1e0e777fbb8527a61c7e2861e31134c5fecaed08
/position.cpp
7dd1a48ed02b61a5d39d55c7ba17aa6f8c0fdf00
[]
no_license
bbrokaw55/snake_game_SFML
f150168f79862502585863760e4396700609a42f
fdf65b05978b41a7ab9d55453a5553946a7389c3
refs/heads/master
2020-03-29T00:57:00.985539
2018-09-18T23:35:52
2018-09-18T23:35:52
149,363,626
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
// *** // Author : Ben Brokaw // // CSCI 261 - A // // Definition file for position class // // Date created: 4/20/18 // // *** #include "position.h" //using namespace std; // Initializes to center of window Pos::Pos() { this->x = (500 / 2); this->y = (400 / 2); } // Initializes to X,Y coordinates Pos::Pos(float x, float y) { this->x = x; this->y = y; } // Multiplies coordinates by the scale void Pos::mult(float scl) { this->x = (this->x * scl); this->y = (this->y * scl); }
[ "noreply@github.com" ]
noreply@github.com
649238780da0c9848c1e2a5b495b43c52a5c7c0d
bdbc93d9cc2dbea8b69e7425e1b5d39f659dd08c
/custom_sub/sub_main.cpp
fbf6608248c73c0291f3611f072c80d773e389ae
[]
no_license
kt997/mosquitto
b124fffa9aaf11ff1a9a3c909c87c0162db08ae0
47685d252c80413ad2837da6a0f8ac6f5beae06f
refs/heads/master
2022-11-09T01:59:44.016933
2020-06-17T11:24:19
2020-06-17T11:24:19
260,932,133
1
0
null
null
null
null
UTF-8
C++
false
false
1,496
cpp
#include "sub.h" #include "sub_internals.h" #define client_id1 "sub2" #define pattern "#" #define host "localhost" #define port 1883 #define cafile "ca.crt" using namespace std; // int on_password_check(char *buf, int size, int rwflag, void *userdata) // { // int length = 0; // // if(!buf) // return 0; // } void my_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message) { if(message->payloadlen){ cout<<(char *)userdata<<" "; cout<<message->topic<<endl<<(char*)message->payload<<endl; }else{ cout<<message->topic<<endl; } // fflush(stdout); // return 0; } void my_subscribe_callback(mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos) { int i; printf("Subscribed (mid: %d): %d", mid, granted_qos[0]); for(i=1; i<qos_count; i++){ printf(", %d", granted_qos[i]); } printf("\n"); } int main() { mosquitto *mosq; // mosquitto_lib_init(); int res=0; mosq=mosquitto_new(client_id1, 0, NULL); if(!mosq){ fprintf(stderr, "Error: Instance not made.\n"); exit(1); } else cout<<"passes\n"; mosquitto_loop_start(mosq); mosquitto_connect(mosq, host, port, 60); mosquitto_subscribe(mosq, NULL, pattern, 2); mosquitto_message_callback_set(mosq, my_message_callback); // mosquitto_disconnect(mosq); mosquitto_loop_stop(mosq, false); // mosquitto_lib_cleanup(); return 0; }
[ "kshitijtrivedi@gmail.com" ]
kshitijtrivedi@gmail.com
7e1d0609b4fec643fc3887cf9b83d18f990a21cf
27c872d5c3532d972b4e3eb20e70e82ccda660fc
/chrome/chrome_cleaner/os/system_util_cleaner_unittest.cc
230593112fe7397337ffeda5fedcb30c480f8c14
[ "BSD-3-Clause" ]
permissive
adityavs/chromium-1
1b084f8ba68803bc6ae88ea7bebec3d2e6cbe210
27ae617ee377e19cc5a48c9e80a1863ea03043e3
refs/heads/master
2023-03-05T22:13:58.379272
2018-07-28T22:10:46
2018-07-28T22:10:46
139,341,362
1
0
null
2018-07-28T22:10:47
2018-07-01T15:42:25
null
UTF-8
C++
false
false
4,580
cc
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/chrome_cleaner/os/system_util_cleaner.h" #include <windows.h> #include <shlwapi.h> #include <stdint.h> #include <wincrypt.h> #include <algorithm> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/strings/string16.h" #include "base/strings/string_util.h" #include "base/test/scoped_path_override.h" #include "base/test/test_shortcut_win.h" #include "base/test/test_timeouts.h" #include "base/win/shortcut.h" #include "chrome/chrome_cleaner/os/layered_service_provider_api.h" #include "chrome/chrome_cleaner/os/layered_service_provider_wrapper.h" #include "chrome/chrome_cleaner/strings/string_util.h" #include "chrome/chrome_cleaner/test/test_executables.h" #include "chrome/chrome_cleaner/test/test_scoped_service_handle.h" #include "chrome/chrome_cleaner/test/test_strings.h" #include "chrome/chrome_cleaner/test/test_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace chrome_cleaner { namespace { class ServiceUtilCleanerTest : public testing::Test { public: void SetUp() override { // Cleanup previous run. This may happen when previous execution of unittest // crashed, leaving background processes/services. if (IsProcessRunning(kTestServiceExecutableName)) { StopService(kServiceName); WaitForProcessesStopped(kTestServiceExecutableName); } DeleteService(kServiceName); ASSERT_TRUE(WaitForServiceDeleted(kServiceName)); ASSERT_FALSE(IsProcessRunning(kTestServiceExecutableName)); ASSERT_FALSE(DoesServiceExist(kServiceName)); } }; } // namespace TEST(SystemUtilCleanerTests, AcquireDebugRightsPrivileges) { ASSERT_FALSE(HasDebugRightsPrivileges()); EXPECT_TRUE(AcquireDebugRightsPrivileges()); EXPECT_TRUE(HasDebugRightsPrivileges()); EXPECT_TRUE(ReleaseDebugRightsPrivileges()); EXPECT_FALSE(HasDebugRightsPrivileges()); } TEST(SystemUtilCleanerTests, OpenRegistryKeyWithInvalidParameter) { const RegKeyPath key_path(HKEY_LOCAL_MACHINE, L"non-existing key path"); base::win::RegKey key; EXPECT_FALSE(key_path.Open(KEY_READ, &key)); } TEST_F(ServiceUtilCleanerTest, DeleteService) { TestScopedServiceHandle service_handle; ASSERT_TRUE(service_handle.InstallService()); service_handle.Close(); EXPECT_TRUE(DoesServiceExist(service_handle.service_name())); EXPECT_TRUE(DeleteService(service_handle.service_name())); EXPECT_TRUE(WaitForServiceDeleted(service_handle.service_name())); EXPECT_FALSE(DoesServiceExist(service_handle.service_name())); } TEST_F(ServiceUtilCleanerTest, StopAndDeleteRunningService) { // Install and launch the service. TestScopedServiceHandle service_handle; ASSERT_TRUE(service_handle.InstallService()); ASSERT_TRUE(service_handle.StartService()); EXPECT_TRUE(DoesServiceExist(service_handle.service_name())); EXPECT_TRUE(IsProcessRunning(kTestServiceExecutableName)); service_handle.Close(); // Stop the service. EXPECT_TRUE(StopService(service_handle.service_name())); EXPECT_TRUE(WaitForProcessesStopped(kTestServiceExecutableName)); EXPECT_TRUE(WaitForServiceStopped(service_handle.service_name())); // Delete the service EXPECT_TRUE(DeleteService(service_handle.service_name())); EXPECT_TRUE(WaitForServiceDeleted(service_handle.service_name())); // The service must be fully stopped and deleted. EXPECT_FALSE(DoesServiceExist(service_handle.service_name())); EXPECT_FALSE(IsProcessRunning(kTestServiceExecutableName)); } TEST_F(ServiceUtilCleanerTest, DeleteRunningService) { // Install and launch the service. TestScopedServiceHandle service_handle; ASSERT_TRUE(service_handle.InstallService()); ASSERT_TRUE(service_handle.StartService()); EXPECT_TRUE(DoesServiceExist(service_handle.service_name())); EXPECT_TRUE(IsProcessRunning(kTestServiceExecutableName)); service_handle.Close(); // Delete the service EXPECT_TRUE(DeleteService(service_handle.service_name())); // The service must be fully stopped and deleted. EXPECT_TRUE(WaitForProcessesStopped(kTestServiceExecutableName)); EXPECT_FALSE(DoesServiceExist(service_handle.service_name())); EXPECT_FALSE(IsProcessRunning(kTestServiceExecutableName)); } } // namespace chrome_cleaner
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
9ba3e64ed80916d0e2695ef5bfc9de7df57022a8
1722686f8139aca7d6927ec7a6dfed13a5d319fb
/pc-BigClass/JR-tea/YMAccountManager.h
b3cf708f5c5e6a31197a5a739c6a5202209d18c4
[]
no_license
oamates/clientmy
610ca1c825e503e0b477a9a579248d608435a5d0
b3618b2225da198f338a3f2981c841dde010cd8d
refs/heads/main
2022-12-30T14:53:43.037242
2020-10-21T01:01:12
2020-10-21T01:01:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,916
h
#ifndef YMACCOUNTMANAGER_H #define YMACCOUNTMANAGER_H #include <QObject> #include <QJsonArray> #include <QJsonObject> #include <QFile> #include <QIODevice> #include "YMHttpClient.h" class YMAccountManager : public QObject , public YMHttpResponseHandler { Q_OBJECT public: explicit YMAccountManager(QObject * parent = 0); ~YMAccountManager(); void login(const QString &username, QString &password); void saveUserInfo(QString userName, QString password, int RememberPwd, int autoLogin); QJsonArray getUserLoginInfo(); void getLatestVersion(); void getLatLng();//获取经纬度 void errorLog(QString messge); static YMAccountManager * getInstance(); //获取更新下载的url QString getDownLoadUrl(); public: bool getUpdateFirmware(); void setUpdateFirmware(bool firmwareStatus); void findLogin(QString username, QString password); protected: virtual void onResponse(int reqCode, const QString &data); void onRespLogin(const QString& data); signals: void loginStateChanged(bool loginState); void loginSucceed(QString message); void loginFailed(QString message); void teacherInfoChanged(QJsonObject teacherInfo); void updateSoftWareChanged(int isForce); void sigTokenFail(); private: static YMAccountManager * m_instance; private: YMHttpClient * m_httpClient; QString m_username; QString m_phone; QString m_token; QJsonObject m_firmwareData; // QWebView *m_webView; public: QString m_versinon; bool m_updateStatus; int m_updateValue; typedef void (YMAccountManager::* HttpRespHandler)(const QString& data); QMap<int, HttpRespHandler> m_respHandlers; }; #endif // YMACCOUNTMANAGER_H
[ "shaohua.zhang@yimifudao.com" ]
shaohua.zhang@yimifudao.com
5af1c1529caf93dc83d60f5446039a7db15080d3
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_Ke218172943.h
51ecdd924ba7d065222a521b952c35619c66ac4c
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_ValueType3507792607.h" #include "mscorlib_System_Collections_Generic_Dictionary_2_E3143661503.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/KeyCollection/Enumerator<System.Object,Stm.V1_0.DynamicDispatcher/CallbackAndCallee> struct Enumerator_t218172943 { public: // System.Collections.Generic.Dictionary`2/Enumerator<TKey,TValue> System.Collections.Generic.Dictionary`2/KeyCollection/Enumerator::host_enumerator Enumerator_t3143661503 ___host_enumerator_0; public: inline static int32_t get_offset_of_host_enumerator_0() { return static_cast<int32_t>(offsetof(Enumerator_t218172943, ___host_enumerator_0)); } inline Enumerator_t3143661503 get_host_enumerator_0() const { return ___host_enumerator_0; } inline Enumerator_t3143661503 * get_address_of_host_enumerator_0() { return &___host_enumerator_0; } inline void set_host_enumerator_0(Enumerator_t3143661503 value) { ___host_enumerator_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "gdesmarais@gsngames.com" ]
gdesmarais@gsngames.com
954bc9d9b96b22bfb5bf0aeb8db99d76e3ae8155
055e78502297026a4ca9b340f25ee1c678e6ca9d
/OccTry-vc14-64/Command/ScCmdFace.cpp
d818760eda214ac008ebac58fa99bb1734127224
[]
no_license
ymqhyq/OccTry-vc14
1ceb759720fcd405e7b82de826f80e71a0713b76
a80ffe78211e2c4659e6f7be6be4736997d46417
refs/heads/master
2020-12-22T11:46:22.993613
2020-01-29T01:58:29
2020-01-29T01:58:29
236,754,637
1
0
null
null
null
null
GB18030
C++
false
false
2,483
cpp
#include "StdAfx.h" #include ".\sccmdface.h" ScCmdFace::ScCmdFace(void) { } ScCmdFace::~ScCmdFace(void) { } ///////////////////////////////////////////////////////////////// // Face 修正 //启动和结束命令 int ScCmdFaceFixAll::Begin(Handle(AIS_InteractiveContext) aCtx) { ScCommand::Begin(aCtx); if(HasSelFace()) { if(FixShape()) Done(); else End(); } else { Prompt("选择一个曲面:"); NeedSelect(TRUE); } return 0; } int ScCmdFaceFixAll::End() { return ScCommand::End(); } //点选方式下的消息响应函数 void ScCmdFaceFixAll::InputEvent(const CPoint& point,int nState, const Handle(V3d_View)& aView) { if(nState == MINPUT_RIGHT) { End(); } else { if(HasSelFace()) Done(); else End(); } } BOOL ScCmdFaceFixAll::HasSelFace() { InitSelect(); if(MoreSelect()) { TopoDS_Shape aS = SelectedShape(FALSE); if(!aS.IsNull() && aS.ShapeType() == TopAbs_FACE) { SelObj(0) = SelectedObj(); return TRUE; } } return FALSE; } BOOL ScCmdFaceFixAll::FixShape() { TopoDS_Shape aShape = GetObjShape(SelObj(0)); TopoDS_Face aFace = TopoDS::Face(aShape); //进行修正 Handle(ShapeFix_Face) sff = new ShapeFix_Face; Handle(ShapeBuild_ReShape) ctx = new ShapeBuild_ReShape; ctx->Apply(aFace); sff->SetContext(ctx); sff->Init(aFace); sff->SetPrecision(0.001); sff->Perform(); if(sff->Status(ShapeExtend_DONE)) { TopoDS_Shape aNS = ctx->Apply(aFace); if(!aNS.IsNull() && aNS.ShapeType() == TopAbs_FACE) { TopoDS_Face aNFace = TopoDS::Face(aNS); AfxMessageBox("修正成功."); m_AISContext->Remove(SelObj(0), Standard_True); SelObj(0) = NULL; Display(NewObj(0),aNFace); return TRUE; } } return FALSE; } ////////////////////////////////////////////////////////////////////////// // 修正face的wire的缝隙 BOOL ScCmdFaceFixGaps::FixShape() { TopoDS_Shape aShape = GetObjShape(SelObj(0)); Handle(ShapeFix_Wireframe) SFWF = new ShapeFix_Wireframe(aShape); SFWF->SetPrecision(0.1); if ( SFWF->FixWireGaps() ) { TopoDS_Shape aS = SFWF->Shape(); if(!aS.IsNull() && aS.ShapeType() == TopAbs_FACE) { m_AISContext->Remove(SelObj(0), Standard_True); SelObj(0) = NULL; Display(NewObj(0),aS); AfxMessageBox("修正完成."); return TRUE; } } return FALSE; }
[ "51437649+ymqhyq@users.noreply.github.com" ]
51437649+ymqhyq@users.noreply.github.com
1c210ab2be1b3fe29813e61e08acdf5b87595481
057e61b56f7caeebf00421933db21be12a7cb5ff
/baekjoon/2606.cpp
a4b73ea42ae77cc75da7ca30e0519db99f684fa9
[]
no_license
skdudn321/algorithm
e8c5e0bc1afc12ed27708ccf37532ed5d2177e53
cd7a6d0c95eb34aac3a73e2bc7d7ff7767d87a8e
refs/heads/master
2020-04-06T06:51:21.411572
2017-12-12T12:13:17
2017-12-12T12:13:17
62,157,943
0
0
null
null
null
null
UTF-8
C++
false
false
666
cpp
#include<stdio.h> int find(int num); void merge(int x, int y); int group[101]; int main(void) { int N, K; int temp1, temp2; int sum = 0; scanf("%d %d", &N, &K); for (int i = 1; i <= N; i++) { group[i] = i; } for (int i = 1; i <= K; i++) { scanf("%d %d", &temp1, &temp2); merge(temp1, temp2); } for (int i = 1; i <= N; i++) { if (find(i) == 1) { sum++; } } printf("%d", sum - 1); } int find(int num) { while (group[num] != num) { num = group[num]; } return num; } void merge(int x, int y) { x = find(x); y = find(y); if (x < y) { group[y] = x; } else { group[x] = y; } }
[ "skdudn12378@gmail.com" ]
skdudn12378@gmail.com
c1c890d81908c79df08711d1b6ff268e5c476c0e
d3bdbe3ff6eeb84bd47a7c2318a856690601655b
/Client/Box_Shooter/World.cpp
0d43e260bb87e6670dbccb8b9e50f7be77439572
[]
no_license
Palarra/BoxShooter_v2
6acb17823214951848203c7fcbe2e481c75e4bb1
dd17e30ca36f8660d284fb0e37998b7821408830
refs/heads/master
2020-03-28T13:22:34.046365
2018-09-30T10:02:03
2018-09-30T10:02:03
148,389,708
0
0
null
null
null
null
ISO-8859-1
C++
false
false
5,625
cpp
#include "World.h" World::World(sf::RenderWindow &window) : m_physic_world(b2World(b2Vec2(0.0f, 0.0f))), m_window(window) , m_player(Player(m_physic_world, "Antony", FRIENDLY_PLAYER, FRIENDLY_ARROW)), m_ennemy_player(Player(m_physic_world, "Armen", ENEMY_PLAYER, ENEMY_ARROW)) { bool connected = false; std::cout << "Taper votre ip :" << std::endl; std::cin >> m_ip_adress; initNetwork(m_ip_adress); while (!connected) { enet_host_service(host, &event, 0); do { std::string data; switch (event.type) { std::cout << "Event type" << event.type << std::endl; case ENET_EVENT_TYPE_RECEIVE: for (int i = 0; i < event.packet->dataLength; i++) { data += event.packet->data[i]; } std::cout << "[CLIENT] Mon id : " << std::stoi(data) << std::endl; m_id = std::stoi(data); connected = true; } } while (enet_host_check_events(host, &event) > 0); } /* On initialise le jeu .... */ clock.restart(); velocityIterations = 6; positionIterations = 2; m_physic_world.SetContactListener(&myContactListenerInstance); createEnvironnement(); } void World::initNetwork(std::string ip) { if (enet_initialize() != 0) { fprintf(stderr, "An error occurred while initializing ENet.\n"); } atexit(enet_deinitialize); address.port = 1234; std::cout << "Client initialise" << std::endl; fflush(stdout); host = enet_host_create(NULL, 1, // create a client host 2, // allow only 1 outgoing connection 57600, // use 57600 / 8 for 56K modem with 56 Kbps downstream bandwidth 14400);// use 14400 / 8 for 56K modem with 14 Kbps upstream bandwidth if (!host) { fprintf(stderr, "An error occurred while trying to create an ENet client host.\n"); exit(EXIT_FAILURE); } // connect to server: enet_address_set_host(&address, ip.c_str()); server = enet_host_connect(host, &address, 2, 0); server->data = 0; // use this as mark that connection is not yet acknowledged if (!server) { fprintf(stderr, "No available peers for initiating an ENet connection.\n"); exit(EXIT_FAILURE); } } void World::sendPacket(int Channel, const std::string data) { /* Create a reliable packet of size 7 containing "packet\0" */ ENetPacket * packet = enet_packet_create(data.c_str(), strlen(data.c_str()) + 1, ENET_PACKET_FLAG_RELIABLE); //printf("Je send : %s taille : %d \n", data.c_str(), data.c_str() + 1); /* Send the packet to the peer over channel id 0. */ /* One could also broadcast the packet by */ /* enet_host_broadcast (host, 0, packet); */ enet_peer_send(server, Channel, packet); /* One could just use enet_host_service() instead. */ enet_host_flush(host); } void World::createEnvironnement() { /* ----------------------------------------------------------------- */ b2BodyDef groundBodyDef; groundBodyDef.position.Set(0.0f, 805.0f / 30.0f); b2Body* groundBody = m_physic_world.CreateBody(&groundBodyDef); b2PolygonShape groundBox; groundBox.SetAsBox(2000 / 60.0f, 10.0f / 60.0f); groundBody->CreateFixture(&groundBox, 0.0f); /* -------------- Left wall -------------- */ b2BodyDef leftwallBodyDef; leftwallBodyDef.position.Set(-5.0f / 30.0f, 0.0f); b2Body* leftwallBody = m_physic_world.CreateBody(&leftwallBodyDef); b2PolygonShape leftwallBox; leftwallBox.SetAsBox(10.0f / 60.0f, 2000.0f / 60.0f); leftwallBody->CreateFixture(&leftwallBox, 0.0f); /* -------------- Right wall -------------- */ b2BodyDef rightwallBodyDef; rightwallBodyDef.position.Set(805.0f / 30.0f, 0.0f); b2Body* rightwallBody = m_physic_world.CreateBody(&rightwallBodyDef); b2PolygonShape rightwallBox; rightwallBox.SetAsBox(10.0f / 60.0f, 2000.0f / 60.0f); rightwallBody->CreateFixture(&rightwallBox, 0.0f); /* -------------- Sky -------------- */ b2BodyDef skyBodyDef; skyBodyDef.position.Set(0.0f, -5.0f / 30.0f); b2Body* skyBody = m_physic_world.CreateBody(&skyBodyDef); b2PolygonShape skyBox; skyBox.SetAsBox(2000 / 60.0f, 10.0f / 60.0f); skyBody->CreateFixture(&skyBox, 0.0f); } void World::update() { if (enet_host_service(host, &event, 0) > 0) { std::string data; do { data.clear(); switch (event.type) { case ENET_EVENT_TYPE_RECEIVE: for (int i = 0; i < event.packet->dataLength; i++) { data += event.packet->data[i]; } //std::cout << data << std::endl; treatPacket(data); enet_packet_destroy(event.packet); // clean up the packet now that we're done using it break; case ENET_EVENT_TYPE_DISCONNECT: printf(" host disconnected.\n"); fflush(stdout); free(event.peer->data); event.peer->data = 0; // reset the peer's client information. server = 0; default: break; } } while (enet_host_check_events(host, &event) > 0); } deltaTime = clock.restart().asSeconds(); m_player.getMovement(m_window); m_player.update(); m_player.draw(m_window); m_ennemy_player.update(); m_ennemy_player.draw(m_window); std::string data_to_send; data_to_send = std::to_string(m_id); /* On inscrit en tête du packet l'id du client */ data_to_send += ';'; data_to_send << m_player; /* On extract toutes les données du player que l'on veut envoyer dans le paquet */ sendPacket(0, data_to_send); m_physic_world.Step(deltaTime, velocityIterations, positionIterations); std::string fps; fps += "FPS : "; fps += std::to_string(1 / deltaTime); m_window.setTitle(fps); } void World::treatPacket(std::string data) { int id = data[0] - '0'; if (id == m_id) { m_player.extractDataPlayer(data); } else { m_ennemy_player.extractDataEnnemyPlayer(data); } }
[ "palarradu03@gmail.com" ]
palarradu03@gmail.com
ee22345d163dfaba2b228cc37a7d6349818956ec
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/arc023/A/2168143.cpp
d25b610d5ea14317c4a94e4823a9fb636031247d
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
659
cpp
#include <cmath> #include <iostream> #include <vector> #include <queue> #include <map> #include <set> #include <algorithm> #include <utility> #include <iomanip> #define int long long int #define rep(i, n) for(int i = 0; i < (n); ++i) using namespace std; typedef pair<int, int> P; const int INF = 1e15; const int MOD = 1e9+7; int day(int y, int m, int d){ return 365 * y + y / 4 - y / 100 + y / 400 + 306 * (m + 1) / 10 + d - 429; } signed main(){ int y, m, d; cin >> y >> m >> d; if(m <= 2){ m += 12; y -= 1; } cout << day(2014, 5, 17) - day(y, m, d) << endl; return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
6ff7c71ceb96b1d420b34b7170c474e4b7fe64f2
8d62ff256e83477863f27c15242a2c48c7d4660c
/OrbitTrail/FirstAidShop.h
1cece458e4d8d54835ecfe847036230a7ce73a7e
[]
no_license
MUProgrammingClub/source-code
b19162b86fc53f3a95a6da9518b1d0e149db4c62
8190fe49e60de61486e41a10411c8a371dbe66f6
refs/heads/master
2021-04-29T23:38:47.448625
2018-11-02T19:52:15
2018-11-02T19:52:15
121,559,622
3
0
null
null
null
null
UTF-8
C++
false
false
138
h
#pragma once #include "Shop.h" class FirstAidShop : public Shop { public: FirstAidShop(); void initializeShop(); ~FirstAidShop(); };
[ "ldjamison@marywood.edu" ]
ldjamison@marywood.edu
bd34a61620ce205cf99b817391ebc8cf7b2a800e
55d560fe6678a3edc9232ef14de8fafd7b7ece12
/libs/multiprecision/config/has_gmp.cpp
4cab3d7ac4d90a5b28395f1e9ff3b261a92a3215
[ "BSL-1.0" ]
permissive
stardog-union/boost
ec3abeeef1b45389228df031bf25b470d3d123c5
caa4a540db892caa92e5346e0094c63dea51cbfb
refs/heads/stardog/develop
2021-06-25T02:15:10.697006
2020-11-17T19:50:35
2020-11-17T19:50:35
148,681,713
0
0
BSL-1.0
2020-11-17T19:50:36
2018-09-13T18:38:54
C++
UTF-8
C++
false
false
1,013
cpp
// Copyright John Maddock 2008. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <cstddef> // See https://gcc.gnu.org/gcc-4.9/porting_to.html #include <gmp.h> #include <boost/config.hpp> #ifdef __GNUC__ #pragma message "__GNU_MP_VERSION=" BOOST_STRINGIZE(__GNU_MP_VERSION) #pragma message "__GNU_MP_VERSION_MINOR=" BOOST_STRINGIZE(__GNU_MP_VERSION_MINOR) #endif #if (__GNU_MP_VERSION < 4) || ((__GNU_MP_VERSION == 4) && (__GNU_MP_VERSION_MINOR < 2)) #error "Incompatible GMP version" #endif int main() { void *(*alloc_func_ptr) (size_t); void *(*realloc_func_ptr) (void *, size_t, size_t); void (*free_func_ptr) (void *, size_t); mp_get_memory_functions(&alloc_func_ptr, &realloc_func_ptr, &free_func_ptr); mpz_t integ; mpz_init (integ); if(integ[0]._mp_d) mpz_clear (integ); return 0; }
[ "james.pack@stardog.com" ]
james.pack@stardog.com
bf53f4c3ab8ce5cc0d69adf6216d3585b6635f61
caa830ccd40613a535e5f2b6d87cd05140a30a7c
/dialogstaticscan.cpp
348e4a34fff1e61370eaadb8a0120f4a245378cb
[ "MIT" ]
permissive
bronxc/StaticScan
1a10e932cb56f890bbc8b750e4ce9339c7d084f0
311b6900bb148f74de53e42b87ffcb9c94ed94a3
refs/heads/master
2023-05-11T23:45:00.296989
2023-04-29T09:13:18
2023-04-29T09:13:18
127,593,994
0
0
MIT
2018-04-01T03:38:43
2018-04-01T03:38:43
null
UTF-8
C++
false
false
2,568
cpp
/* Copyright (c) 2017-2023 hors<horsicq@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. */ #include "dialogstaticscan.h" #include "ui_dialogstaticscan.h" DialogStaticScan::DialogStaticScan(QWidget *pParent) : QDialog(pParent), ui(new Ui::DialogStaticScan) { ui->setupUi(this); g_pDevice = nullptr; setWindowFlags(Qt::Window); } DialogStaticScan::~DialogStaticScan() { delete ui; } void DialogStaticScan::setData(QIODevice *pDevice, bool bAuto) { this->g_pDevice = pDevice; if (bAuto) { scan(); } } void DialogStaticScan::on_pushButtonClose_clicked() { this->close(); } void DialogStaticScan::on_pushButtonScan_clicked() { scan(); } void DialogStaticScan::scan() { SpecAbstract::SCAN_RESULT scanResult = {}; SpecAbstract::SCAN_OPTIONS options = {}; options.bRecursiveScan = ui->checkBoxRecursiveScan->isChecked(); options.bDeepScan = ui->checkBoxDeepScan->isChecked(); options.bHeuristicScan = ui->checkBoxHeuristicScan->isChecked(); options.bVerbose = ui->checkBoxVerbose->isChecked(); options.bAllTypesScan = ui->checkBoxAllTypesScan->isChecked(); DialogStaticScanProcess ds(XOptions::getMainWidget(this)); ds.setData(g_pDevice, &options, &scanResult); ds.showDialogDelay(); // TODO const QString sSaveFileName = XBinary::getResultFileName(g_pDevice, QString("%1.txt").arg(tr("Result"))); ui->widgetResult->setData(scanResult, sSaveFileName); }
[ "horsicq@gmail.com" ]
horsicq@gmail.com
e703b0ebc12a8e59fbbbcec5b5d6f6fee1e4de27
eea55a29e3929535c8e7d88a47f102e3e00ad15b
/Larrys_Challenge_C++/Movimentador.h
ecea228c99b38735ac3a37ceffa26f2fdb6e9535
[]
no_license
breno-abreu/LarrysChallengeCpp
10808e9fad71514a76f164ca06e14245cb69010c
ede2ed5f346657030ddd7f6360341956ca40b8ec
refs/heads/master
2020-12-23T02:05:47.450389
2020-03-31T17:37:00
2020-03-31T17:37:00
236,992,746
0
0
null
null
null
null
UTF-8
C++
false
false
425
h
#pragma once #include "bibliotecas.h" #include "SuperficieInterativa.h" class Movimentador : public SuperficieInterativa { private: int direcao; public: Movimentador(); Movimentador(RenderWindow* _window, Texture *_textura, const float cx, const float cy, const int _profundidade, const int _codigo, const int _xTile, const int _yTile, const int _direcao); ~Movimentador(); int getDirecao()const; void existir(); };
[ "breno2601@gmail.com" ]
breno2601@gmail.com
8e71a335c02f7ea05b04d2eef678795b868ff5d3
8f0c19443475e22472e9b6b78eeb14d58523b0d9
/keithley1/keithley1/stdafx.cpp
ebfc3e90568e9ce9278b74d39ee3de7b90a1353e
[]
no_license
asdfhhh/visualstudio-projects-ihep
a27993d9ae568b9ec53ab8998ef54c65565ff655
8e1d936f7db31c3f3b8c182dc2f327c54d471d13
refs/heads/master
2021-01-10T14:10:46.650519
2019-08-12T02:57:32
2019-08-12T02:57:32
46,844,293
0
0
null
null
null
null
GB18030
C++
false
false
163
cpp
// stdafx.cpp : 只包括标准包含文件的源文件 // keithley1.pch 将作为预编译头 // stdafx.obj 将包含预编译类型信息 #include "stdafx.h"
[ "fanrr@ihep.ac.cn" ]
fanrr@ihep.ac.cn
84fd978db589491d68607e14073eea3542543dba
a256d82cb102ae7b8fd75db500dc22b385a5c5eb
/PTA/指针/7-1-冒泡.cpp
c03ef5705e063928f8478e25f68f5ffe99631de2
[]
no_license
Jinxuyang/data-structures-and-algorithms
5827c0da7b31f5d3aedb57e5d82654789124dcba
07fe964944d79c2c289a4ce2446fb8ddbd45e8f8
refs/heads/master
2023-01-31T12:59:24.730025
2020-12-09T13:09:56
2020-12-09T13:09:56
319,959,659
1
0
null
null
null
null
UTF-8
C++
false
false
348
cpp
#include <iostream> #include <algorithm> using namespace std; void bubbleSort(int *p, int c) { sort(p, p + c); } int main(int argc, char const *argv[]) { int T; cin >> T; int x[100000], cnt = 0; for (int i = 0; i < T; i++) { cin >> x[i]; cnt ++; } bubbleSort(x, cnt); for (int i = 0; i < T; i++) { cout << x[i] << " "; } return 0; }
[ "jinxuyang3@gmail.com" ]
jinxuyang3@gmail.com
38fb5e45aba0ae0406d56728819979268e8075fc
c94fae6bc7779ce06e05b60a0753e82430f830b8
/用Create函数创建控件/用Create函数创建控件/用Create函数创建控件Doc.h
95e2b22e600a8fbc94d0d0e72d38b120a44f00ed
[]
no_license
MrsZ/MFC_VS2012
f4bbfc56f2b89c4c99c2ddc55d77e4138d3db4d0
bc623f1d13cf2fa0eb18b4f2b4f20cb5a762ad96
refs/heads/master
2021-05-29T06:00:47.703364
2015-08-19T13:16:52
2015-08-19T13:16:52
110,326,425
0
1
null
2017-11-11T07:19:09
2017-11-11T07:19:09
null
GB18030
C++
false
false
1,019
h
// 用Create函数创建控件Doc.h : C用Create函数创建控件Doc 类的接口 // #pragma once class C用Create函数创建控件Doc : public CDocument { protected: // 仅从序列化创建 C用Create函数创建控件Doc(); DECLARE_DYNCREATE(C用Create函数创建控件Doc) // 特性 public: // 操作 public: // 重写 public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); #ifdef SHARED_HANDLERS virtual void InitializeSearchContent(); virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds); #endif // SHARED_HANDLERS // 实现 public: virtual ~C用Create函数创建控件Doc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 生成的消息映射函数 protected: DECLARE_MESSAGE_MAP() #ifdef SHARED_HANDLERS // 用于为搜索处理程序设置搜索内容的 Helper 函数 void SetSearchContent(const CString& value); #endif // SHARED_HANDLERS };
[ "lixuat2014@gmail.com" ]
lixuat2014@gmail.com
ac9e120b0447b35edde36e2104edaca91764cf5b
c3c3420e2106dd676fa59deb8d33de8b8c701543
/spoj/ohaniser.cpp
667cc9b89521e565c1981e89e1fef7c61e8c6c10
[]
no_license
joydeepdas/Competitive-Codes
9031c35dd908e4139a6e0e90c4375b9149132baf
620734e7996a1ec969a9caa0385e3947fb052f3e
refs/heads/master
2022-02-16T12:01:06.877632
2019-08-18T14:11:19
2019-08-18T14:11:19
43,842,031
0
0
null
null
null
null
UTF-8
C++
false
false
396
cpp
#include<iostream> using namespace std; long long int pow1(long long int a,long long int b) { long long int c=1; for(int i=1;i<=b;i++){ c=(c*(a%1000000007))%1000000007; } return c; } int main(){ long long int n,t,ans; cin>>t; while(t--){ cin>>n; if(n==1){ cout<<1<<endl;continue; } else{ ans=(pow1(2,n-2)*((n+1)%1000000007))%1000000007; cout<<ans%1000000007<<endl; }}}
[ "joydeepdas994@gmail.com" ]
joydeepdas994@gmail.com
dea63e72d97f87d4b560925089d1b7be24470eee
4e239cdf86ab634d3d8aa21b593efc7f6218fa3f
/PE-lib/PE.h
92cda1f158b565b463e1ebcc4fd316d9c09edc9f
[ "MIT" ]
permissive
mgeeky/PE-library
f4690bddcbbf8090bc276a90d93e444fd75f5dfc
97e813cf73fa38ccc99fa3a2827512846940bf4b
refs/heads/master
2023-01-12T07:39:45.237605
2023-01-05T12:18:19
2023-01-05T12:18:19
53,013,509
76
21
MIT
2023-01-05T12:18:20
2016-03-03T02:24:23
C++
UTF-8
C++
false
false
22,949
h
#pragma once #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <iostream> #include <vector> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cctype> #include <string> #include <sstream> #include <winnt.h> #include <tlhelp32.h> #include <winternl.h> #include <psapi.h> #include <processthreadsapi.h> /////////////////////////////////// #define PE_MAX_SECTIONS_COUNT 96 // according to Microsoft "pecoff_v8.doc" // and "The Art of computer virus research // and defense" by Peter Szor #define PE_MAX_ELFANEW_VALUE 0x400 #define PE_MAX_SECTION_NAME_LEN 9 #define PE_MAX_RELOCS_LIMIT 0x3000 #define PE_MAX_BASE_RELOCATIONS 0x400 #define PE_MAX_IAT_SIZE 0x100000 #define PE_MAX_IAT_DESCRIPTORS 0x100 #define PE_MAX_IAT_THUNKS 0x2000 #define PE_MAX_EXPORTS_NUMBER 0x2000 // Errors #define ERROR_FILE_IS_COMPRESSED 0x80001 // File is probably compressed #define ERROR_IAT_UNACCESSIBLE 0x80002 // IAT is unaccessible #define ERROR_INVALID_MAGIC 0x80003 // DOS_HEADER.eMagic is not "MZ" #define ERROR_INVALID_PE ERROR_INVALID_MAGIC #define ERROR_INVALID_SIGNATURE 0x80004 // NT_HEADERS.Signature is not "PE" #define ERROR_HEAP_CORRUPTED 0x80005 // Error while allocating memory at the Heap #define ERROR_READ_LESS_THAN_SHOULD 0x80006 // Read less bytes than should read #define ERROR_WRITE_LESS_THAN_SHOULD 0x80007 // Write less bytes than should write #define ERROR_EAT_UNACCESSIBLE 0x80008 // EAT is unaccessible #define ERROR_IAT_CORRUPTED 0x80009 // IAT is corrupted #define ERROR_EAT_CORRUPTED 0x8000A // EAT is corrupted #define ERROR_OPENED_FOR_READ_ONLY 0x8000B // File was opened for read only access. #define ERROR_PE_HEADERS_CORRUPTED 0x8000C #define ERROR_NO_RELOCS 0x8000D #define ERROR_RELOCS_CORRUPTED 0x8000E #define ERROR_RESOURCES_CORRUPTED 0x8000F #define ERROR_NO_RESOURCES 0x80010 #define ERROR_IAT_TOO_BIG 0x80011 #define ERROR_TOO_MANY_EXPORTS 0x80012 #define ERROR_TOO_MANY_RELOCS 0x80013 typedef struct _LDR_MODULE { LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; void* BaseAddress; void* EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; HANDLE SectionHandle; ULONG CheckSum; ULONG TimeDateStamp; } LDR_MODULE, *PLDR_MODULE; struct IMPORTED_FUNCTION { IMPORTED_FUNCTION() { memset((void*)szFunction, 0, sizeof(szFunction)); } unsigned uImpDescriptorIndex; // Index of import descriptor (index in vector) unsigned uImportIndex; // Index of import inside import descriptor char szFunction[65]; ULONGLONG dwPtrValueVA; // Value of pointer to this thunk ULONGLONG dwPtrValueRVA; // Value of pointer to this thunk DWORD dwHint; // Hint WORD wOrdinal; DWORD dwThunkRVA; // RVA address of this Thunk in file (not of value) }; // Class describing each exported thunk struct EXPORTED_FUNCTION { EXPORTED_FUNCTION() { memset((void*)szFunction, 0, sizeof(szFunction)); } bool bIsOrdinal; // Specifies wheter function is exported by ordinal // instead of by name unsigned uExportIndex; // Export thunk index. union { char szFunction[65]; DWORD dwOrdinal; }; bool bIsForwarded; // Specifies wheter exported thunk is forwarded char szForwarder[256]; ULONGLONG dwPtrValue; // Value of pointer to this thunk DWORD dwPtrValueRVA; // Value of pointer to this thunk WORD wOrdinal; // Ordinal DWORD dwThunkRVA; // RVA address of this Thunk in file (not of value) }; // Class describing each import descriptor struct __IMAGE_IMPORT_DESCRIPTOR { IMAGE_IMPORT_DESCRIPTOR d; char szName[128]; std::vector< IMPORTED_FUNCTION> vImports; }; struct __IMAGE_EXPORT_DIRECTORY { IMAGE_EXPORT_DIRECTORY d; char szName[128]; }; struct __IMAGE_SECTION_HEADER { IMAGE_SECTION_HEADER s; char szSectionName[PE_MAX_SECTION_NAME_LEN]; }; struct __IMAGE_RELOC_ENTRY { WORD offset : 12; WORD type : 4; }; struct __IMAGE_RELOCATION { IMAGE_BASE_RELOCATION baseRelocation; std::vector<__IMAGE_RELOC_ENTRY> relocs; }; //////////////////////////////// class PE { class _MY_IMAGE_OPTIONAL_HEADER; public: struct HookTrampolineBuffers { // (Input) Buffer containing bytes that should be restored while unhooking. BYTE* originalBytes; DWORD originalBytesSize; // (Output) Buffer that will receive bytes present prior to trampoline installation/restoring. BYTE* previousBytes; DWORD previousBytesSize; }; enum class AccessMethod { Arbitrary = 0, File_Begin, File_Current, File_End }; enum class AnalysisType { None, File, MappedModule, Memory, Dump }; bool hasImports; bool hasExports; bool hasRelocs; bool bReadOnly; bool bIsValidPE; AnalysisType analysisType; std::string szFileName; BY_HANDLE_FILE_INFORMATION bhFileInformation; size_t sizeOfFile; // actual size of file // PE Headers IMAGE_DOS_HEADER imgDosHdr; IMAGE_NT_HEADERS32 imgNtHdrs32; IMAGE_NT_HEADERS64 imgNtHdrs64; __IMAGE_EXPORT_DIRECTORY imgExportDirectory; // If this module provides // EAT, then this structure // will be filled correspondly size_t numOfNewSections; // Number of added sections // (by CreateSection method) // DOS header & stub std::vector<uint8_t> lpDOSStub; // DOS STUB // Vectors std::vector<__IMAGE_SECTION_HEADER> vSections; std::vector< IMPORTED_FUNCTION> vImports; std::vector<__IMAGE_IMPORT_DESCRIPTOR> vImportDescriptors; std::vector< EXPORTED_FUNCTION> vExports; std::vector<__IMAGE_RELOCATION> vRelocations; // Address of mapped memory area LPBYTE lpMapOfFile; bool bUseRVAInsteadOfRAW; // Used for analysis of a previously mapped // dump file. HANDLE hFileHandle; // Process analysis specific variables bool bPreferBaseAddressThanImageBase; // If parsing PIC injected shellcode, its allocation // base address may be different than its expected ImageBase. // In such scenario, prefer allocation base over its ImageBase. bool bMemoryAnalysis; // PE interface is performing living // process/module analysis (memory). // This not flags actual memory // analysing, but in fact it's // switch used in recognizing // Process Memory operations. DWORD dwPID; // PID of the currently analysed process. ////////////////////////////// MEMBER METHODS //////////////////////////////////////////// ~PE(); // Implicit constructor. After you have to call PE::LoadFile member method to analyse an image PE() { _initVars(); } // Explicit constructor. After initialization instantly runs PE image analysis PE(const std::string& _szFileName, bool bRunAnalysis = false) : szFileName(_szFileName) { _initVars(); if (bRunAnalysis == true) { _bIsFileMapped = false; LoadFile(); } } void close(); //========= Address / offset conversions size_t RVA2RAW(size_t dwRVA, bool bForce = false) const; // Returns conversion from RVA to RAW. // If we set bForce to true, it will omit // usage of this->bUseRVAInsteadOfRAW variable DWORD RAW2RVA(size_t dwRAW) const; DWORD VA2RVA32(DWORD dwVA) const { return dwVA - GetIB32(); } DWORD RVA2VA32(DWORD dwRVA) const { return dwRVA + GetIB32(); } ULONGLONG VA2RVA64(ULONGLONG dwVA) const { return dwVA - GetIB64(); } ULONGLONG RVA2VA64(ULONGLONG dwRVA) const { return dwRVA + GetIB64(); } //========= Getting info DWORD GetEP() const { return bIs86 ? imgNtHdrs32.OptionalHeader.AddressOfEntryPoint : imgNtHdrs64.OptionalHeader.AddressOfEntryPoint; } ULONGLONG GetImageBase() const { return bIs86 ? GetIB32() : GetIB64(); } size_t GetSectionsCount() const { return vSections.size(); } __IMAGE_SECTION_HEADER& GetSection(size_t u) { return vSections[u]; } __IMAGE_SECTION_HEADER& GetLastSection() { return vSections.back(); } bool isArch86() const { return bIs86; } bool HasOverlay() const { return _bHasOverlay; } //========= Checking errors DWORD GetError() const { return _dwLastError; } DWORD GetErrorLine() const { return _dwErrorLine; } std::wstring GetErrorFunc() const { std::wstring func(_szErrorFunction.begin(), _szErrorFunction.end()); return func; } std::wstring GetErrorString() const; bool operator!() const { return (this->GetError() != 0); } void SetError(DWORD dwErrCode) { SetLastError(dwErrCode); _dwLastError = dwErrCode; } //=========== Analysis methods ============ // Simple file reading & writing (and of course parsing) bool AnalyseFile(const std::wstring& _szFileName, bool readOnly, bool _bIsValidPEImage = true) { std::string _name(_szFileName.begin(), _szFileName.end()); _filePath = _szFileName; return AnalyseFile(_name, readOnly, _bIsValidPEImage); } bool AnalyseFile(const std::string& _szFileName, bool readOnly, bool _bIsValidPEImage = true) { this->szFileName = _szFileName; this->_bIsFileMapped = false; this->bUseRVAInsteadOfRAW = false; this->bReadOnly = readOnly; this->bIsValidPE = _bIsValidPEImage; this->analysisType = AnalysisType::File; _filePath = std::wstring(_szFileName.begin(), _szFileName.end()); return PE::LoadFile(); } // Another type of analysis. This performs analysis from dump file which is aligned and // divided to sections. This means, that analysis must be RVA-based // and make file reading & writing on every I/O. // e.g. dump file may be a dumped process memory. // Simple file reading & writing (and of course parsing) bool AnalyseDump(const std::wstring& _szDump, bool readOnly) { std::string _name(_szDump.begin(), _szDump.end()); return AnalyseDump(_name, readOnly); } bool AnalyseDump(const std::string& _szDump, bool readOnly) { this->bUseRVAInsteadOfRAW = this->bIsValidPE = true; this->_bIsFileMapped = false; this->bReadOnly = readOnly; this->analysisType = AnalysisType::Dump; szFileName = _szDump; return PE::LoadFile(); } // Analyses current process memory treating input dwAddress as a base of // mapped image. This address should point to the mapped address of valid PE // file inside current process memory. // If analysed memory region is not a MEM_MAPPED or MEM_IMAGE, it may be PIC shellcode. // In such case, prefer dwAddress over expected ImageBase while calculating RVAs/VAs. // use isMapped=True if you plan to analyse memory mapped(or ordinarly loaded) PE module such as EXE/DLL, // or isMapped=False for PIC shellcode acting as a Reflective DLL injected one or PE-to-shellcode converted. // If adjustMemoryProtections is true, will iterate over memory pool and set R/RW pages wherever no Read/RW is applied. bool AnalyseMemory(DWORD dwPID, LPBYTE dwAddress, size_t dwSize, bool readOnly, bool isMapped, bool adjustMemoryProtections = false); // Below methods performs module analysis from specified process memory. // This works by reading process memory and parsing/analysing it. // If adjustMemoryProtections is true, will iterate over memory pool and set R/RW pages wherever no Read/RW is applied. bool AnalyseProcessModule(DWORD dwPID, HMODULE hModule, bool readOnly, bool adjustMemoryProtections = false); // This method performs process module analysis. Actually, it opens process, // enumerates process modules and compares it with the szModule name. Afterwards, // it sets module handle and launches analysis. By specifying szModule to nullptr user can // perform dwPID process analysis instead of one of it's modules. // If adjustMemoryProtections is true, will iterate over memory pool and set R/RW pages wherever no Read/RW is applied. bool AnalyseProcessModule(DWORD dwPID, const std::wstring& szModule, bool readOnly, bool adjustMemoryProtections = false) { std::string n(szModule.begin(), szModule.end()); return AnalyseProcessModule(dwPID, n, readOnly, adjustMemoryProtections); } bool AnalyseProcessModule(DWORD dwPID, const std::string& szModule, bool readOnly, bool adjustMemoryProtections = false); // Simple wrapper to _AnalyseProcessModule for quick process analysis bool AnalyseProcess(DWORD dwPID, bool readOnly) { return this->AnalyseProcessModule(dwPID, "", readOnly); } bool ApplyAllRelocs(ULONGLONG newImageBase = 0); bool ApplyRelocsInBuffer(ULONGLONG newBase, ULONGLONG bufferRVA, uint8_t *buffer, size_t sizeOfBuffer, ULONGLONG oldImageBase = 0); // This function actually opens the file, gathers headers from file, performs IAT parsing, and // if possible performs EAT parsing. Whole PE image analysis is beginning there. bool LoadFile(); bool getImport(const char* functionName, IMPORTED_FUNCTION* func); bool getExport(const char* exportFunction, EXPORTED_FUNCTION* func); // I/O - read/writes opened file/process (PE::_hFileHandle) and returns bool ReadBytes(LPVOID, size_t dwSize, size_t dwOffset = 0, enum class AccessMethod method = AccessMethod::File_Current, bool dontRestoreFilePointer = false); bool WriteBytes(LPVOID, size_t dwSize, size_t dwOffset = 0, enum class AccessMethod method = AccessMethod::File_Current, bool dontRestoreFilePointer = false); std::vector<uint8_t> ReadOverlay(); std::vector<uint8_t> ReadSection(const __IMAGE_SECTION_HEADER& section); // Writes PE headers back to the mapped file/memory. bool UpdateHeaders(); DWORD InsertShellcode(uint8_t *shellcode, size_t sizeOfShellcode, const std::string& szSectionName = ".extra", BYTE* whereToReturn = 0); std::vector<uint8_t> getJumpPayload(BYTE* whereToJump); // This method hooks IAT/EAT routine by swapping original IAT/EAT thunk address with input hook address // Returns: 0 if szImportThunk/szExportThunk has not been found, -1 if there has // occured an error during WriteBytes, or non-zero if function succeed, and this value will // be previous thunk EntryPoint address. ULONGLONG HookIAT(const std::string& szImportThunk, ULONGLONG hookedVA); DWORD HookEAT(const std::string& szExportThunk, DWORD hookedRVA); bool HookTrampoline(bool installHook, LPVOID address, LPVOID jumpAddress, HookTrampolineBuffers* buffers = NULL); // Creates image section and appends it to the PE::pSectionHdrs table __IMAGE_SECTION_HEADER CreateSection(DWORD dwSizeOfSection, DWORD dwDesiredAccess, const std::string& szNameOfSection); __IMAGE_SECTION_HEADER RemoveSection(size_t index); static int64_t LECharTo64bitNum(char a[]) { int64_t n = 0; n = (((int64_t)a[7] << 56) & 0xFF00000000000000U) | (((int64_t)a[6] << 48) & 0x00FF000000000000U) | (((int64_t)a[5] << 40) & 0x0000FF0000000000U) | (((int64_t)a[4] << 32) & 0x000000FF00000000U) | ((a[3] << 24) & 0x00000000FF000000U) | ((a[2] << 16) & 0x0000000000FF0000U) | ((a[1] << 8) & 0x000000000000FF00U) | (a[0] & 0x00000000000000FFU); return n; } static int32_t LECharTo32bitNum(char a[]) { int32_t n = 0; n = (((int32_t)a[3] << 24) & 0xFF000000) | (((int32_t)a[2] << 16) & 0x00FF0000) | (((int32_t)a[1] << 8) & 0x0000FF00) | (((int64_t)a[0] << 0) & 0x000000FF); return n; } static void convert64ToLECharArray(uint8_t *arr, uint64_t a) { size_t i = 0; for (i = 7; i > 0; i--) { arr[i] = (uint8_t)((((uint64_t)a) >> (56 - (8 * i))) & 0xFFu); } } static void convert32ToLECharArray(uint8_t *arr, uint32_t a) { size_t i = 0; for (i = 3; i > 0; i--) { arr[i] = (uint8_t)((((uint32_t)a) >> (24 - (8 * i))) & 0xFFu); } } private: // ========================================== void _initVars() { _bHasOverlay = _bIsFileMapped = _bIsIATFilled = bUseRVAInsteadOfRAW = bMemoryAnalysis = _selfProcessAnalysis = _bAutoMapOfFile = false; numOfNewSections = sizeOfFile = _dwCurrentOffset = _dwLastError = dwPID = 0; _hMapOfFile = hFileHandle = (HANDLE)INVALID_HANDLE_VALUE; lpMapOfFile = nullptr; analysisType = AnalysisType::None; if(!lpDOSStub.empty()) lpDOSStub.clear(); } // More detailed SetError version void _SetError(DWORD dwErrCode, int iLine, const char* szFunc) { if (this->_dwLastError != 0) return; this->SetError(dwErrCode); this->_dwErrorLine = (DWORD)iLine; this->_szErrorFunction = std::string(szFunc); } void adjustOptionalHeader(); std::string& trimQuote(std::string& szPath) const; // Trims from file path quote chars '"' bool ReadEntireModuleSafely(LPVOID lpBuffer, size_t dwSize, size_t dwOffset); void AddNewSection(size_t sizeOfSection, DWORD flags, const std::string& szSectionName); bool AppendShellcode(BYTE* whereToReturn, uint8_t *shellcode, size_t sizeOfShellcode, __IMAGE_SECTION_HEADER *imgNewSection); DWORD GetSafeSectionSize(const __IMAGE_SECTION_HEADER& sect) const; bool _OpenFile(); void SetFileMapped(LPBYTE _lpMapOfFile) { lpMapOfFile = _lpMapOfFile; _bIsFileMapped = true; _bAutoMapOfFile = false; } // Simple CreateFileMappingA and MapViewOfFile function LPBYTE MapFile(); // Function fills IAT in mapped memory (with GetProcAddr addresses // if dwAddresses hasn't been specified, or with addresses from dwAddresses table. bool FillIAT(DWORD *dwAddresses = nullptr, DWORD dwElements = 0); bool ParseIAT(DWORD dwAddressOfIAT = 0); // Function parses IAT (from input address, or if // not specified - from DataDirectory[1] ) bool ParseEAT(DWORD dwAddressOfEAT = 0); // Function parses EAT (from input address, or if // not specified - from DataDirectory[0] ) bool ParseRelocs(); bool ParseResources(); // Returns char intepretation of input, or '.' if it is not printable inline char _HexChar(int c); DWORD GetIB32() const; ULONGLONG GetIB64() const; bool changeProtection(LPVOID address, size_t size, DWORD newProtection, LPDWORD oldProtection); bool verifyAddressBounds(uintptr_t address, bool relative = true); bool verifyAddressBounds(uintptr_t address, size_t upperBoundary, bool relative = true); bool verifyAddressBounds(uintptr_t address, size_t lowerBoundary, size_t upperBoundary, bool relative = true); std::vector<MEMORY_BASIC_INFORMATION> collectProcessMemoryMap(); bool _LoadFile(); bool accomodateMemoryPagesForAccess( bool accomodateOrRestore, HMODULE hModule, std::vector<MEMORY_BASIC_INFORMATION>& origMemoryMap); /************************************/ std::wstring _filePath; bool bIs86; size_t ptrSize; DWORD _dwLastError; // PE interface last error // may be as well return of the // GetLastError() DWORD _dwErrorLine; // Line in code where error occured std::string _szErrorFunction; // Function name where error occured bool _bIsIATFilled; // Specifies wheter IAT has been // filled size_t _dwCurrentOffset; // During process analysis // we cannot use SetFilePointer // routine to seek inside process // memory, so that's how we obey it intptr_t _moduleStartPos; HANDLE _hMapOfFile; bool _bIsFileMapped; bool _bAutoMapOfFile; bool _selfProcessAnalysis; bool _bHasOverlay; bool adjustMemoryProtections; };
[ "mb@binary-offensive.com" ]
mb@binary-offensive.com
8fefd169a7b256edec5adebf239e8c4ba1d8b4e8
efd67fa3fdac58fd2bf6be94cd52d720f0cd2f25
/src/common/ast/nodes/class_definition/members/AttributeMemberNode.hpp
bfc929757136baf917ebb59a2973e1d899f6c68d
[]
no_license
pik694/TKOM-rasph
22cd129776e836c2217e9eb9f88ba95b8b51e619
a983cc2a77e8056bc20e4bb58d23cacc72295802
refs/heads/master
2020-03-09T03:00:56.247171
2018-06-05T21:51:47
2018-06-05T21:51:47
128,554,959
0
0
null
null
null
null
UTF-8
C++
false
false
661
hpp
// // Created by Piotr Żelazko on 07.05.2018. // #ifndef RASPH_ATTRIBUTEMEMBERNODE_HPP #define RASPH_ATTRIBUTEMEMBERNODE_HPP #include "ClassMemberNode.hpp" namespace rasph::common::ast::nodes { class AttributeMemberNode : public ClassMemberNode { public: explicit AttributeMemberNode(const std::string &name) : ClassMemberNode(name){}; void execute() override { //TODO throw std::runtime_error("Not implemented yet"); } void accept(interpreter::environment::ClassBuilder& builder) override { builder.addElement(*this); } }; } #endif //RASPH_ATTRIBUTEMEMBERNODE_HPP
[ "piotr.zelazko@icloud.com" ]
piotr.zelazko@icloud.com
24eae9933cadccdf3678c7313456de67dbd910f7
d8be4e5b942bb636617aae4dc7e660653c601494
/raytracing/lib/source/image.cpp
914471d3c95b49544e4aa21a1fe85a601e9e0e64
[]
no_license
alexgaiv/raytracing
d96aa1d52661922a741afb6ab0f4d3602fdc1d16
29eb7552ceaa3caf032134f92a5c57955be9b390
refs/heads/master
2021-01-01T03:43:18.110299
2016-05-19T10:10:45
2016-05-19T10:10:45
59,198,484
0
0
null
null
null
null
UTF-8
C++
false
false
2,612
cpp
#include "image.h" #pragma pack(push, 1) struct TGAHEADER { BYTE idLength; BYTE colorMapType; BYTE imageType; USHORT colorMapOffset; USHORT colorMapLength; BYTE colorMapEntrySize; USHORT xOrigin; USHORT yOrigin; USHORT width; USHORT height; BYTE depth; BYTE descriptor; }; #pragma pack(pop) Image Image::Clone() const { Image img; img.isGood = isGood; img.width = width; img.height = height; img.dataSize = dataSize; if (dataSize != 0) { img.ptr->data = new BYTE[dataSize]; memcpy(img.ptr->data, ptr->data, dataSize); } return img; } void Image::read(HANDLE hFile, LPVOID lpBuffer, DWORD nNumBytes) { DWORD bytesRead; BOOL success = ReadFile(hFile, lpBuffer, nNumBytes, &bytesRead, NULL); if (!success || bytesRead != nNumBytes) throw false; } bool Image::LoadTga(const char *filename) { ptr = my_shared_ptr<Shared>(new Shared); width = height = depth = 0; dataSize = 0; HANDLE file = CreateFileA(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0); if (file == INVALID_HANDLE_VALUE) return isGood = false; BYTE *data = 0; isGood = true; try { TGAHEADER tgaHeader = { }; read(file, &tgaHeader, sizeof(TGAHEADER)); if (tgaHeader.colorMapType != 0 || tgaHeader.imageType != 2 && tgaHeader.imageType != 3) { throw false; } if (tgaHeader.idLength != 0) { SetFilePointer(file, tgaHeader.idLength, NULL, FILE_CURRENT); } DWORD imageSize = tgaHeader.width * tgaHeader.height * tgaHeader.depth / 8; data = new(std::nothrow) BYTE[imageSize]; if (!data) throw false; read(file, data, imageSize); width = tgaHeader.width; height = tgaHeader.height; int rowSize = imageSize / height; if ((~tgaHeader.descriptor & 0x10)) { BYTE *tmp = new BYTE[rowSize]; for (int i = 0; i < height / 2; i++) { BYTE *r1 = &data[rowSize*i]; BYTE *r2 = &data[rowSize*(height - i - 1)]; memcpy(tmp, r1, rowSize); memcpy(r1, r2, rowSize); memcpy(r2, tmp, rowSize); } delete [] tmp; } if (tgaHeader.descriptor & 8) { int components = tgaHeader.depth / 8; BYTE *tmp = new BYTE[components]; for (int i = 0; i < height; i++) { for (int j = 0; j < width / 2; j++) { BYTE *c1 = &data[rowSize*i + j*components]; BYTE *c2 = &data[rowSize*i + (rowSize - (j+1)*components)]; memcpy(tmp, c1, components); memcpy(c1, c2, components); memcpy(c2, tmp, components); } } delete [] tmp; } ptr->data = data; dataSize = imageSize; depth = tgaHeader.depth; } catch(bool) { delete [] data; isGood = false; } CloseHandle(file); return isGood; }
[ "alexgaiv0748@gmail.com" ]
alexgaiv0748@gmail.com
9fcad3643fd8b36764160593b25bb56a438e5fca
e48a40b19ebe1ca64d877885f9f19e9a78b192c3
/Examples/Cxx/PolygonalObjectViewer/KWPolygonalObjectViewerExample.cxx
8e7605427bdf86f9ec8c890ed7f6495ca2955a55
[]
no_license
SIVICLab/KWWidgets
dbe2034caf065c30eafed92d73e9df9ff60a6565
f5a3e16063db773eaf79736ec31314d392fa934d
refs/heads/master
2021-01-18T20:08:02.372034
2017-04-01T20:57:19
2017-04-01T20:57:19
86,941,196
1
0
null
2017-04-01T20:34:24
2017-04-01T20:34:23
null
UTF-8
C++
false
false
5,166
cxx
#include "vtkActor.h" #include "vtkKWApplication.h" #include "vtkKWFrameWithLabel.h" #include "vtkKWRenderWidget.h" #include "vtkKWSurfaceMaterialPropertyWidget.h" #include "vtkKWWindow.h" #include "vtkPolyDataMapper.h" #include "vtkRenderWindow.h" #include "vtkXMLPolyDataReader.h" #include "vtkKWSimpleAnimationWidget.h" #include "vtkKWWidgetsPaths.h" #include <vtksys/SystemTools.hxx> #include <vtksys/CommandLineArguments.hxx> int my_main(int argc, char *argv[]) { // Initialize Tcl Tcl_Interp *interp = vtkKWApplication::InitializeTcl(argc, argv, &cerr); if (!interp) { cerr << "Error: InitializeTcl failed" << endl ; return 1; } // Process some command-line arguments // The --test option here is used to run this example as a non-interactive // test for software quality purposes. You can ignore it. int option_test = 0; vtksys::CommandLineArguments args; args.Initialize(argc, argv); args.AddArgument( "--test", vtksys::CommandLineArguments::NO_ARGUMENT, &option_test, ""); args.Parse(); // Create the application // If --test was provided, ignore all registry settings, and exit silently // Restore the settings that have been saved to the registry, like // the geometry of the user interface so far. vtkKWApplication *app = vtkKWApplication::New(); app->SetName("KWPolygonalObjectViewerExample"); if (option_test) { app->SetRegistryLevel(0); app->PromptBeforeExitOff(); } app->RestoreApplicationSettingsFromRegistry(); // Set a help link. Can be a remote link (URL), or a local file app->SetHelpDialogStartingPage("http://www.kwwidgets.org"); // Add a window // Set 'SupportHelp' to automatically add a menu entry for the help link vtkKWWindow *win = vtkKWWindow::New(); win->SupportHelpOn(); app->AddWindow(win); win->Create(); win->SecondaryPanelVisibilityOff(); // Add a render widget, attach it to the view frame, and pack vtkKWRenderWidget *rw = vtkKWRenderWidget::New(); rw->SetParent(win->GetViewFrame()); rw->Create(); app->Script("pack %s -expand y -fill both -anchor c -expand y", rw->GetWidgetName()); // Create a 3D object reader vtkXMLPolyDataReader *reader = vtkXMLPolyDataReader::New(); char data_path[2048]; sprintf(data_path, "%s/Data/teapot.vtp", KWWidgets_EXAMPLES_DIR); if (!vtksys::SystemTools::FileExists(data_path)) { sprintf(data_path, "%s/..%s/Examples/Data/teapot.vtp", app->GetInstallationDirectory(), KWWidgets_INSTALL_DATA_DIR); } reader->SetFileName(data_path); // Create the mapper and actor vtkPolyDataMapper *mapper = vtkPolyDataMapper::New(); mapper->SetInputConnection(reader->GetOutputPort()); vtkActor *actor = vtkActor::New(); actor->SetMapper(mapper); // Add the actor to the scene rw->AddViewProp(actor); rw->ResetCamera(); // Create a material property editor vtkKWSurfaceMaterialPropertyWidget *mat_prop_widget = vtkKWSurfaceMaterialPropertyWidget::New(); mat_prop_widget->SetParent(win->GetMainPanelFrame()); mat_prop_widget->Create(); mat_prop_widget->SetPropertyChangedCommand(rw, "Render"); mat_prop_widget->SetPropertyChangingCommand(rw, "Render"); mat_prop_widget->SetProperty(actor->GetProperty()); app->Script("pack %s -side top -anchor nw -expand n -fill x", mat_prop_widget->GetWidgetName()); // Create a simple animation widget vtkKWFrameWithLabel *animation_frame = vtkKWFrameWithLabel::New(); animation_frame->SetParent(win->GetMainPanelFrame()); animation_frame->Create(); animation_frame->SetLabelText("Movie Creator"); app->Script("pack %s -side top -anchor nw -expand n -fill x -pady 2", animation_frame->GetWidgetName()); vtkKWSimpleAnimationWidget *animation_widget = vtkKWSimpleAnimationWidget::New(); animation_widget->SetParent(animation_frame->GetFrame()); animation_widget->Create(); animation_widget->SetRenderWidget(rw); animation_widget->SetAnimationTypeToCamera(); app->Script("pack %s -side top -anchor nw -expand n -fill x", animation_widget->GetWidgetName()); // Start the application // If --test was provided, do not enter the event loop and run this example // as a non-interactive test for software quality purposes. int ret = 0; win->Display(); if (!option_test) { app->Start(argc, argv); ret = app->GetExitStatus(); } win->Close(); // Deallocate and exit mat_prop_widget->Delete(); animation_frame->Delete(); animation_widget->Delete(); reader->Delete(); actor->Delete(); mapper->Delete(); rw->Delete(); win->Delete(); app->Delete(); return ret; } #if defined(_WIN32) && !defined(__CYGWIN__) #include <windows.h> int __stdcall WinMain(HINSTANCE, HINSTANCE, LPSTR lpCmdLine, int) { int argc; char **argv; vtksys::SystemTools::ConvertWindowsCommandLineToUnixArguments( lpCmdLine, &argc, &argv); int ret = my_main(argc, argv); for (int i = 0; i < argc; i++) { delete [] argv[i]; } delete [] argv; return ret; } #else int main(int argc, char *argv[]) { return my_main(argc, argv); } #endif
[ "barre" ]
barre
a5fdf57a45defa678f2a9ebf4c561483135f6af7
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/ds/security/passport/atlmfc/atlutil.h
177379579924905d30d4c5e1d4a8ae3f7adb4278
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
90,186
h
// This is a part of the Active Template Library. // Copyright (C) 1996-2001 Microsoft Corporation // All rights reserved. // // This source code is only intended as a supplement to the // Active Template Library Reference and related // electronic documentation provided with the library. // See these sources for detailed information regarding the // Active Template Library product. #ifndef __ATLUTIL_H__ #define __ATLUTIL_H__ #pragma once #include <stdio.h> #include <string.h> #include <crtdbg.h> #include <stdlib.h> #include <mbstring.h> #include <atldef.h> #include <imagehlp.h> #include <atlbase.h> #include <atlstr.h> #include <atlcoll.h> #include <atlsiface.h> #include <atlenc.h> #include <atlcom.h> #ifndef _ATL_NO_DEFAULT_LIBS #pragma comment(lib, "imagehlp.lib") #endif // !_ATL_NO_DEFAULT_LIBS #pragma warning( push ) #pragma warning( disable: 4127 ) namespace ATL { inline BOOL IsFullPath(LPCTSTR szPath) { size_t nLen = _tcslen(szPath); if (nLen <= 1) return FALSE; if (*szPath == _T('"')) { szPath++; } if (szPath[1]==_T(':')) // drive: case return TRUE; if (nLen > 2 && szPath[0]==_T('\\') && szPath[1]==_T('\\')) // unc path name return TRUE; return FALSE; } inline BOOL IsFullPathA(LPCSTR szPath) { DWORD nLen = (DWORD) strlen(szPath); if (nLen <= 1) return FALSE; if (*szPath == '"') { szPath++; } if (szPath[1]==':') // drive: case return TRUE; if (nLen > 2 && szPath[0]=='\\' && szPath[1]=='\\') // unc path name return TRUE; return FALSE; } #if(_WIN32_WINNT >= 0x0400) // Helper class for reverting the thread impersonation token // and then restoring it back to what it was class CRevertThreadToken { public: HANDLE m_hThreadToken; CRevertThreadToken() { m_hThreadToken = INVALID_HANDLE_VALUE; } ~CRevertThreadToken() { Restore(); } // When called, this function // makes a copy of the thread's impersonation token // and then calls RevertToSelf() to revert the impersonation // level to the process // call Restore() to restore the impersonation // token // Restore is automatically called by the destructor BOOL Initialize() { if (OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE, FALSE, &m_hThreadToken)) { if (!RevertToSelf()) { CloseHandle(m_hThreadToken); m_hThreadToken = INVALID_HANDLE_VALUE; return FALSE; } return TRUE; } return FALSE; } void Restore() { if (m_hThreadToken != INVALID_HANDLE_VALUE) { SetThreadToken(NULL, m_hThreadToken); CloseHandle(m_hThreadToken); m_hThreadToken = INVALID_HANDLE_VALUE; } } }; #else // Dummy version for downlevel support class CRevertThreadToken { public: BOOL Initialize() { return FALSE; } void Restore() { } }; #endif // _WIN32_WINNT >= 0x0400) #ifndef ATL_ISAPI_BUFFER_SIZE #define ATL_ISAPI_BUFFER_SIZE 4096 #endif //typedefs and defines for CUrl (essentially the same as the ones from wininet, but with an ATL_ prepended) typedef WORD ATL_URL_PORT; typedef enum { ATL_URL_SCHEME_UNKNOWN = -1, ATL_URL_SCHEME_FTP = 0, ATL_URL_SCHEME_GOPHER = 1, ATL_URL_SCHEME_HTTP = 2, ATL_URL_SCHEME_HTTPS = 3, ATL_URL_SCHEME_FILE = 4, ATL_URL_SCHEME_NEWS = 5, ATL_URL_SCHEME_MAILTO = 6, ATL_URL_SCHEME_SOCKS = 7, } ATL_URL_SCHEME; #define ATL_URL_MAX_HOST_NAME_LENGTH 256 #define ATL_URL_MAX_USER_NAME_LENGTH 128 #define ATL_URL_MAX_PASSWORD_LENGTH 128 #define ATL_URL_MAX_PORT_NUMBER_LENGTH 5 // ATL_URL_PORT is unsigned short #define ATL_URL_MAX_PORT_NUMBER_VALUE 65535 // maximum unsigned short value #define ATL_URL_MAX_PATH_LENGTH 2048 #define ATL_URL_MAX_SCHEME_LENGTH 32 // longest protocol name length #define ATL_URL_MAX_URL_LENGTH (ATL_URL_MAX_SCHEME_LENGTH \ + sizeof("://") \ + ATL_URL_MAX_PATH_LENGTH) #define ATL_URL_INVALID_PORT_NUMBER 0 // use the protocol-specific default #define ATL_URL_DEFAULT_FTP_PORT 21 // default for FTP servers #define ATL_URL_DEFAULT_GOPHER_PORT 70 // " " gopher " #define ATL_URL_DEFAULT_HTTP_PORT 80 // " " HTTP " #define ATL_URL_DEFAULT_HTTPS_PORT 443 // " " HTTPS " #define ATL_URL_DEFAULT_SOCKS_PORT 1080 // default for SOCKS firewall servers. template <DWORD dwSizeT=ATL_ISAPI_BUFFER_SIZE> class CAtlIsapiBuffer { protected: char m_szBuffer[dwSizeT]; LPSTR m_pBuffer; DWORD m_dwLen; DWORD m_dwAlloc; HANDLE m_hProcHeap; public: CAtlIsapiBuffer() throw() { if (dwSizeT > 0) m_szBuffer[0] = 0; m_pBuffer = m_szBuffer; m_dwLen = 0; m_dwAlloc = dwSizeT; m_hProcHeap = GetProcessHeap(); } CAtlIsapiBuffer(LPCSTR sz) { m_pBuffer = m_szBuffer; m_dwLen = 0; m_dwAlloc = dwSizeT; m_hProcHeap = GetProcessHeap(); if (!Append(sz)) AtlThrow(E_OUTOFMEMORY); } ~CAtlIsapiBuffer() throw() { Free(); } BOOL Alloc(DWORD dwSize) throw() { if (m_dwAlloc >= dwSize) { return TRUE; } if (m_pBuffer != m_szBuffer) { HeapFree(m_hProcHeap, 0, m_pBuffer); m_dwLen = 0; m_dwAlloc = 0; } m_pBuffer = (LPSTR)HeapAlloc(m_hProcHeap, 0, dwSize); if (m_pBuffer) { m_dwAlloc = dwSize; return TRUE; } return FALSE; } BOOL ReAlloc(DWORD dwNewSize) throw() { if (dwNewSize <= m_dwAlloc) return TRUE; if (m_pBuffer == m_szBuffer) { BOOL bRet = Alloc(dwNewSize); if (bRet) memcpy(m_pBuffer, m_szBuffer, m_dwLen); return bRet; } LPSTR pvNew = (LPSTR )HeapReAlloc(m_hProcHeap, 0, m_pBuffer, dwNewSize); if (pvNew) { m_pBuffer = pvNew; m_dwAlloc = dwNewSize; return TRUE; } return FALSE; } void Free() throw() { if (m_pBuffer != m_szBuffer) { HeapFree(m_hProcHeap,0 , m_pBuffer); m_dwAlloc = dwSizeT; m_pBuffer = m_szBuffer; } Empty(); } void Empty() throw() { if (m_pBuffer) { m_pBuffer[0]=0; m_dwLen = 0; } } DWORD GetLength() throw() { return m_dwLen; } BOOL Append(LPCSTR sz, int nLen = -1) throw() { if (nLen == -1) nLen = (int) strlen(sz); if (m_dwLen + nLen + 1 > m_dwAlloc) { if (!ReAlloc(m_dwAlloc + (nLen+1 > ATL_ISAPI_BUFFER_SIZE ? nLen+1 : ATL_ISAPI_BUFFER_SIZE))) return FALSE; } memcpy(m_pBuffer + m_dwLen, sz, nLen); m_dwLen += nLen; m_pBuffer[m_dwLen]=0; return TRUE; } operator LPCSTR() throw() { return m_pBuffer; } CAtlIsapiBuffer& operator+=(LPCSTR sz) { if (!Append(sz)) AtlThrow(E_OUTOFMEMORY); return *this; } }; // class CAtlIsapiBuffer __interface IStackDumpHandler { public: void __stdcall OnBegin(); void __stdcall OnEntry(void *pvAddress, LPCSTR szModule, LPCSTR szSymbol); void __stdcall OnError(LPCSTR szError); void __stdcall OnEnd(); }; #define ATL_MODULE_NAME_LEN _MAX_PATH #define ATL_SYMBOL_NAME_LEN 1024 // Helper class for generating a stack dump // This is used internally by AtlDumpStack class CStackDumper { public: struct _ATL_SYMBOL_INFO { ULONG_PTR dwAddress; ULONG_PTR dwOffset; CHAR szModule[ATL_MODULE_NAME_LEN]; CHAR szSymbol[ATL_SYMBOL_NAME_LEN]; }; static LPVOID __stdcall FunctionTableAccess(HANDLE hProcess, ULONG_PTR dwPCAddress) { #ifdef _WIN64 return SymFunctionTableAccess(hProcess, dwPCAddress); #else return SymFunctionTableAccess(hProcess, (ULONG)dwPCAddress); #endif } static ULONG_PTR __stdcall GetModuleBase(HANDLE hProcess, ULONG_PTR dwReturnAddress) { IMAGEHLP_MODULE moduleInfo; #ifdef _WIN64 if (SymGetModuleInfo(hProcess, dwReturnAddress, &moduleInfo)) #else if (SymGetModuleInfo(hProcess, (ULONG)dwReturnAddress, &moduleInfo)) #endif return moduleInfo.BaseOfImage; else { MEMORY_BASIC_INFORMATION memoryBasicInfo; if (::VirtualQueryEx(hProcess, (LPVOID) dwReturnAddress, &memoryBasicInfo, sizeof(memoryBasicInfo))) { DWORD cch = 0; char szFile[MAX_PATH] = { 0 }; cch = GetModuleFileNameA((HINSTANCE)memoryBasicInfo.AllocationBase, szFile, MAX_PATH); // Ignore the return code since we can't do anything with it. SymLoadModule(hProcess, NULL, ((cch) ? szFile : NULL), #ifdef _WIN64 NULL, (DWORD_PTR) memoryBasicInfo.AllocationBase, 0); #else NULL, (DWORD)(DWORD_PTR)memoryBasicInfo.AllocationBase, 0); #endif return (DWORD_PTR) memoryBasicInfo.AllocationBase; } } return 0; } static BOOL ResolveSymbol(HANDLE hProcess, UINT_PTR dwAddress, _ATL_SYMBOL_INFO &siSymbol) { BOOL fRetval = TRUE; siSymbol.dwAddress = dwAddress; CHAR szUndec[ATL_SYMBOL_NAME_LEN]; CHAR szWithOffset[ATL_SYMBOL_NAME_LEN]; LPSTR pszSymbol = NULL; IMAGEHLP_MODULE mi; memset(&siSymbol, 0, sizeof(_ATL_SYMBOL_INFO)); mi.SizeOfStruct = sizeof(IMAGEHLP_MODULE); #ifdef _WIN64 if (!SymGetModuleInfo(hProcess, dwAddress, &mi)) #else if (!SymGetModuleInfo(hProcess, (UINT)dwAddress, &mi)) #endif lstrcpyA(siSymbol.szModule, "<no module>"); else { LPSTR pszModule = strchr(mi.ImageName, '\\'); if (pszModule == NULL) pszModule = mi.ImageName; else pszModule++; lstrcpynA(siSymbol.szModule, pszModule, sizeof(siSymbol.szModule)/sizeof(siSymbol.szModule[0])); } __try { union { CHAR rgchSymbol[sizeof(IMAGEHLP_SYMBOL) + ATL_SYMBOL_NAME_LEN]; IMAGEHLP_SYMBOL sym; } sym; memset(&sym.sym, 0x00, sizeof(sym.sym)); sym.sym.SizeOfStruct = sizeof(IMAGEHLP_SYMBOL); #ifdef _WIN64 sym.sym.Address = dwAddress; #else sym.sym.Address = (DWORD)dwAddress; #endif sym.sym.MaxNameLength = ATL_SYMBOL_NAME_LEN; #ifdef _WIN64 if (SymGetSymFromAddr(hProcess, dwAddress, &(siSymbol.dwOffset), &sym.sym)) #else if (SymGetSymFromAddr(hProcess, (DWORD)dwAddress, &(siSymbol.dwOffset), &sym.sym)) #endif { pszSymbol = sym.sym.Name; if (UnDecorateSymbolName(sym.sym.Name, szUndec, sizeof(szUndec)/sizeof(szUndec[0]), UNDNAME_NO_MS_KEYWORDS | UNDNAME_NO_ACCESS_SPECIFIERS)) { pszSymbol = szUndec; } else if (SymUnDName(&sym.sym, szUndec, sizeof(szUndec)/sizeof(szUndec[0]))) { pszSymbol = szUndec; } if (siSymbol.dwOffset != 0) { wsprintfA(szWithOffset, "%s + %d bytes", pszSymbol, siSymbol.dwOffset); pszSymbol = szWithOffset; } } else pszSymbol = "<no symbol>"; } __except (EXCEPTION_EXECUTE_HANDLER) { pszSymbol = "<EX: no symbol>"; siSymbol.dwOffset = dwAddress - mi.BaseOfImage; } lstrcpynA(siSymbol.szSymbol, pszSymbol, sizeof(siSymbol.szSymbol)/sizeof(siSymbol.szSymbol[0])); return fRetval; } }; // Helper function to produce a stack dump ATL_NOINLINE inline void AtlDumpStack(IStackDumpHandler *pHandler) { ATLASSERT(pHandler); pHandler->OnBegin(); CAtlArray<void *> adwAddress; HANDLE hProcess = ::GetCurrentProcess(); if (SymInitialize(hProcess, NULL, FALSE)) { // force undecorated names to get params DWORD dw = SymGetOptions(); dw &= ~SYMOPT_UNDNAME; SymSetOptions(dw); HANDLE hThread = ::GetCurrentThread(); CONTEXT threadContext; threadContext.ContextFlags = CONTEXT_FULL; if (::GetThreadContext(hThread, &threadContext)) { //DumpContext(&threadContext); STACKFRAME stackFrame; memset(&stackFrame, 0, sizeof(stackFrame)); stackFrame.AddrPC.Mode = AddrModeFlat; DWORD dwMachType; #if defined(_M_IX86) dwMachType = IMAGE_FILE_MACHINE_I386; // program counter, stack pointer, and frame pointer stackFrame.AddrPC.Offset = threadContext.Eip; stackFrame.AddrStack.Offset = threadContext.Esp; stackFrame.AddrStack.Mode = AddrModeFlat; stackFrame.AddrFrame.Offset = threadContext.Ebp; stackFrame.AddrFrame.Mode = AddrModeFlat; #elif defined(_M_AMD64) // only program counter dwMachType = IMAGE_FILE_MACHINE_AMD64; stackFrame.AddrPC.Offset = threadContext.Rip; #elif defined(_M_IA64) //IA64: What do we need to do here? dwMachType = IMAGE_FILE_MACHINE_IA64; #if 0 stackFrame.AddrPC.Offset = threadContext.StIIP; stackFrame.AddrPC.Mode = AddrModeFlat; stackFrame.AddrStack.Offset = threadContext.IntSp; stackFrame.AddrStack.Mode = AddrModeFlat; stackFrame.AddrFrame.Offset = threadContext.IntSp; stackFrame.AddrFrame.Mode = AddrModeFlat; stackFrame.AddrBStore.Offset = threadContext.RsBSP; stackFrame.AddrBStore.Mode = AddrModeFlat; stackFrame.AddrReturn.Offset = threadContext.BrRp; stackFrame.AddrReturn.Mode = AddrModeFlat; #endif #else #error("Unknown Target Machine"); #endif adwAddress.SetCount(0, 16); int nFrame; for (nFrame = 0; nFrame < 5; nFrame++) { if (!StackWalk(dwMachType, hProcess, hProcess, &stackFrame, &threadContext, NULL, CStackDumper::FunctionTableAccess, CStackDumper::GetModuleBase, NULL)) { break; } adwAddress.SetAtGrow(nFrame, (void*)(DWORD_PTR)stackFrame.AddrPC.Offset); } } } else { DWORD dw = GetLastError(); char sz[100]; wsprintfA(sz, "AtlDumpStack Error: IMAGEHLP.DLL wasn't found. " "GetLastError() returned 0x%8.8X\r\n", dw); pHandler->OnError(sz); } // dump it out now INT_PTR nAddress; INT_PTR cAddresses = adwAddress.GetCount(); for (nAddress = 0; nAddress < cAddresses; nAddress++) { CStackDumper::_ATL_SYMBOL_INFO info; UINT_PTR dwAddress = (UINT_PTR)adwAddress[nAddress]; LPCSTR szModule = NULL; LPCSTR szSymbol = NULL; if (CStackDumper::ResolveSymbol(hProcess, dwAddress, info)) { szModule = info.szModule; szSymbol = info.szSymbol; } pHandler->OnEntry((void *) dwAddress, szModule, szSymbol); } pHandler->OnEnd(); } #define STACK_TRACE_PART_DELIMITER ';' #define STACK_TRACE_LINE_DELIMITER '~' // CReportHookDumpHandler is a stack dump handler // that gathers the stack dump into the format // used by CDebugReportHook class CReportHookDumpHandler : public IStackDumpHandler { public: CReportHookDumpHandler() { m_pstr = NULL; } void GetStackDump(CStringA *pstr) { ATLASSERT(pstr); SetString(pstr); AtlDumpStack(this); SetString(NULL); } void SetString(CStringA *pstr) { m_pstr = pstr; } // implementation // IStackDumpHandler methods void __stdcall OnBegin() { } void __stdcall OnEntry(void *pvAddress, LPCSTR szModule, LPCSTR szSymbol) { // make sure SetString was called before // trying to get a stack dump ATLASSERT(m_pstr); if (!m_pstr) return; char szBuf[100]; sprintf(szBuf, "0x%p;", pvAddress); *m_pstr += szBuf; if (!szModule) szModule = "Unknown"; if (!szSymbol) szSymbol = "<No Info>"; *m_pstr += szModule; *m_pstr += STACK_TRACE_PART_DELIMITER; ATLASSERT(szSymbol); *m_pstr += szSymbol; *m_pstr += STACK_TRACE_PART_DELIMITER; *m_pstr += STACK_TRACE_LINE_DELIMITER; } void __stdcall OnError(LPCSTR /*szError*/) { } void __stdcall OnEnd() { } protected: CStringA *m_pstr; }; #define PIPE_INPUT_BUFFER_SIZE 4096 #define PIPE_OUTPUT_BUFFER_SIZE 2048 enum { DEBUG_SERVER_MESSAGE_TRACE, DEBUG_SERVER_MESSAGE_ASSERT, DEBUG_SERVER_MESSAGE_QUIT }; struct DEBUG_SERVER_MESSAGE { DWORD dwType; // one of DEBUG_SERVER_MESSAGE_* DWORD dwProcessId; // process id of client DWORD dwClientNameLen; // length of client name size_t dwTextLen; // length of text message including null terminator BOOL bIsDebuggerAttached; // TRUE if the debugger is already attached }; #ifdef _DEBUG extern "C" WINBASEAPI BOOL WINAPI IsDebuggerPresent( VOID ); class CDebugReportHook { protected: _CRT_REPORT_HOOK m_pfnOldHook; static char m_szPipeName[MAX_PATH+1]; static DWORD m_dwTimeout; static DWORD m_dwClientNameLen; static char m_szClientName[MAX_COMPUTERNAME_LENGTH+1]; public: CDebugReportHook(LPCSTR szMachineName = ".", LPCSTR szPipeName = "AtlsDbgPipe", DWORD dwTimeout = 20000) throw() { if (SetPipeName(szMachineName, szPipeName)) { SetTimeout(dwTimeout); SetHook(); } m_dwClientNameLen = sizeof(m_szClientName); GetComputerNameA(m_szClientName, &m_dwClientNameLen); } ~CDebugReportHook() throw() { RemoveHook(); } BOOL SetPipeName(LPCSTR szMachineName = ".", LPCSTR szPipeName = "AtlsDbgPipe") throw() { size_t nLen1 = strlen(szMachineName); size_t nLen2 = strlen(szPipeName); if (nLen1 + nLen2 + 8 <= MAX_PATH) { _snprintf(m_szPipeName, MAX_PATH, "\\\\%s\\pipe\\%s", szMachineName, szPipeName); return TRUE; } return FALSE; } void SetTimeout(DWORD dwTimeout) { m_dwTimeout = dwTimeout; } void SetHook() throw() { m_pfnOldHook = _CrtSetReportHook(CDebugReportHookProc); } void RemoveHook() throw() { _CrtSetReportHook(m_pfnOldHook); } static int __cdecl CDebugReportHookProc(int reportType, char *message, int *returnValue) throw() { DWORD dwWritten; *returnValue = 0; CRevertThreadToken revert; revert.Initialize(); CHandle hdlPipe; while (1) { HANDLE hPipe = CreateFileA(m_szPipeName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL); if (hPipe != INVALID_HANDLE_VALUE ) { hdlPipe.Attach(hPipe); break; } if (GetLastError() != ERROR_PIPE_BUSY) { if (reportType == _CRT_ASSERT) return TRUE; return FALSE; } //If the pipe is busy, we wait for up to m_dwTimeout if (!WaitNamedPipeA(m_szPipeName, m_dwTimeout)) { if (reportType == _CRT_ASSERT) return TRUE; return FALSE; } } DEBUG_SERVER_MESSAGE Message; Message.bIsDebuggerAttached = IsDebuggerPresent(); if (reportType == _CRT_ASSERT) { Message.dwType = DEBUG_SERVER_MESSAGE_ASSERT; } else { Message.dwType = DEBUG_SERVER_MESSAGE_TRACE; } Message.dwProcessId = GetCurrentProcessId(); Message.dwClientNameLen = m_dwClientNameLen+1; // add 1 for the null terminator Message.dwTextLen = strlen(message)+1; int nRet = 1; WriteFile(hdlPipe, &Message, sizeof(DEBUG_SERVER_MESSAGE), &dwWritten, NULL); WriteFile(hdlPipe, m_szClientName, Message.dwClientNameLen, &dwWritten, NULL); WriteFile(hdlPipe, message, (DWORD)Message.dwTextLen, &dwWritten, NULL); //Check to see whether or not to send stack trace BOOL bRet = ReadFile(hdlPipe, &nRet, sizeof(nRet), &dwWritten, NULL); //if nRet == 1, the user wants stack trace info if (bRet && nRet) { _ATLTRY { CStringA str; CReportHookDumpHandler stackDumper; stackDumper.GetStackDump(&str); if (!WriteFile(hdlPipe, (LPCSTR)str, str.GetLength(), &dwWritten, NULL)) return (reportType == _CRT_ASSERT ? TRUE : FALSE); } _ATLCATCHALL() { return (reportType == _CRT_ASSERT ? TRUE : FALSE); } } if (bRet) bRet = ReadFile(hdlPipe, &nRet, sizeof(nRet), &dwWritten, NULL); if (!bRet) nRet = 0; revert.Restore(); // possible return values // 0 -> Ignore or cancel // 1 -> Retry // 2 -> Abort if (nRet == 0) { return (reportType == _CRT_ASSERT ? TRUE : FALSE); } if (nRet == 1) { if (IsDebuggerPresent()) { DebugBreak(); } } if (nRet == 2) abort(); return (reportType == _CRT_ASSERT ? TRUE : FALSE); } }; // class CDebugReportHook __declspec(selectany) char CDebugReportHook::m_szPipeName[MAX_PATH+1]; __declspec(selectany) DWORD CDebugReportHook::m_dwTimeout; __declspec(selectany) DWORD CDebugReportHook::m_dwClientNameLen; __declspec(selectany) char CDebugReportHook::m_szClientName[MAX_COMPUTERNAME_LENGTH+1]; #endif #ifndef ATL_POOL_NUM_THREADS #define ATL_POOL_NUM_THREADS 0 #endif #ifndef ATL_POOL_STACK_SIZE #define ATL_POOL_STACK_SIZE 0 #endif #ifndef ATLS_DEFAULT_THREADSPERPROC #define ATLS_DEFAULT_THREADSPERPROC 2 #endif #ifndef ATLS_DEFAULT_THREADPOOLSHUTDOWNTIMEOUT #define ATLS_DEFAULT_THREADPOOLSHUTDOWNTIMEOUT 36000 #endif // // CThreadPool // This class is a simple IO completion port based thread pool // Worker: // is a class that is responsible for handling requests // queued on the thread pool. // It must have a typedef for RequestType, where request type // is the datatype to be queued on the pool // RequestType must be castable to (DWORD) // The value -1 is reserved for shutdown // of the pool // Worker must also have a void Execute(RequestType request, void *pvParam, OVERLAPPED *pOverlapped) function // ThreadTraits: // is a class that implements a static CreateThread function // This allows for overriding how the threads are created #define ATLS_POOL_SHUTDOWN ((OVERLAPPED*) ((__int64) -1)) template <class Worker, class ThreadTraits=DefaultThreadTraits> class CThreadPool : public IThreadPoolConfig { protected: CSimpleMap<DWORD, HANDLE> m_threadMap; DWORD m_dwThreadEventId; CComCriticalSection m_critSec; DWORD m_dwStackSize; DWORD m_dwMaxWait; void *m_pvWorkerParam; LONG m_bShutdown; HANDLE m_hThreadEvent; HANDLE m_hRequestQueue; public: CThreadPool() throw() : m_hRequestQueue(NULL), m_pvWorkerParam(NULL), m_dwMaxWait(ATLS_DEFAULT_THREADPOOLSHUTDOWNTIMEOUT), m_bShutdown(FALSE), m_dwThreadEventId(0), m_dwStackSize(0) { } ~CThreadPool() throw() { Shutdown(); } // Initialize the thread pool // if nNumThreads > 0, then it specifies the number of threads // if nNumThreads < 0, then it specifies the number of threads per proc (-) // if nNumThreads == 0, then it defaults to two threads per proc // hCompletion is a handle of a file to associate with the completion port // pvWorkerParam is a parameter that will be passed to Worker::Execute // dwStackSize: // The stack size to use when creating the threads HRESULT Initialize(void *pvWorkerParam=NULL, int nNumThreads=0, DWORD dwStackSize=0, HANDLE hCompletion=INVALID_HANDLE_VALUE) throw() { ATLASSERT( m_hRequestQueue == NULL ); if (m_hRequestQueue) // Already initialized return AtlHresultFromWin32(ERROR_ALREADY_INITIALIZED); if (S_OK != m_critSec.Init()) return E_FAIL; m_hThreadEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if (!m_hThreadEvent) { m_critSec.Term(); return AtlHresultFromLastError(); } // Create IO completion port to queue the requests m_hRequestQueue = CreateIoCompletionPort(hCompletion, NULL, 0, nNumThreads); if (m_hRequestQueue == NULL) { // failed creating the Io completion port m_critSec.Term(); CloseHandle(m_hThreadEvent); return AtlHresultFromLastError(); } m_pvWorkerParam = pvWorkerParam; m_dwStackSize = dwStackSize; HRESULT hr = SetSize(nNumThreads); if (hr != S_OK) { // Close the request queue handle CloseHandle(m_hRequestQueue); // Clear the queue handle m_hRequestQueue = NULL; // Uninitialize the critical sections m_critSec.Term(); CloseHandle(m_hThreadEvent); return hr; } return S_OK; } // Shutdown the thread pool // This function posts the shutdown request to all the threads in the pool // It will wait for the threads to shutdown a maximum of dwMaxWait MS. // If the timeout expires it just returns without terminating the threads. void Shutdown(DWORD dwMaxWait=0) throw() { if (!m_hRequestQueue) // Not initialized return; CComCritSecLock<CComCriticalSection> lock(m_critSec, false); if (FAILED(lock.Lock())) { // out of memory ATLASSERT( FALSE ); return; } if (dwMaxWait == 0) dwMaxWait = m_dwMaxWait; HRESULT hr = InternalResizePool(0, dwMaxWait); if (hr != S_OK) ATLTRACE(atlTraceUtil, 0, _T("Thread pool not shutting down cleanly : %08x"), hr); // If the threads have not returned, then something is wrong for (int i = m_threadMap.GetSize() - 1; i >= 0; i--) { HANDLE hThread = m_threadMap.GetValueAt(i); DWORD dwExitCode; GetExitCodeThread(hThread, &dwExitCode); if (dwExitCode == STILL_ACTIVE) { ATLTRACE(atlTraceUtil, 0, _T("Terminating thread")); TerminateThread(hThread, 0); } CloseHandle(hThread); } // Close the request queue handle CloseHandle(m_hRequestQueue); // Clear the queue handle m_hRequestQueue = NULL; ATLASSERT(m_threadMap.GetSize() == 0); // Uninitialize the critical sections lock.Unlock(); m_critSec.Term(); CloseHandle(m_hThreadEvent); } // IThreadPoolConfig methods HRESULT STDMETHODCALLTYPE SetSize(int nNumThreads) throw() { if (nNumThreads == 0) nNumThreads = -ATLS_DEFAULT_THREADSPERPROC; if (nNumThreads < 0) { SYSTEM_INFO si; GetSystemInfo(&si); nNumThreads = (int) (-nNumThreads) * si.dwNumberOfProcessors; } return InternalResizePool(nNumThreads, m_dwMaxWait); } HRESULT STDMETHODCALLTYPE GetSize(int *pnNumThreads) throw() { if (!pnNumThreads) return E_POINTER; *pnNumThreads = GetNumThreads(); return S_OK; } HRESULT STDMETHODCALLTYPE SetTimeout(DWORD dwMaxWait) throw() { m_dwMaxWait = dwMaxWait; return S_OK; } HRESULT STDMETHODCALLTYPE GetTimeout(DWORD *pdwMaxWait) throw() { if (!pdwMaxWait) return E_POINTER; *pdwMaxWait = m_dwMaxWait; return S_OK; } // IUnknown methods HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void **ppv) throw() { if (!ppv) return E_POINTER; *ppv = NULL; if (InlineIsEqualGUID(riid, __uuidof(IUnknown)) || InlineIsEqualGUID(riid, __uuidof(IThreadPoolConfig))) { *ppv = static_cast<IThreadPoolConfig*>(this); AddRef(); return S_OK; } return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE AddRef() throw() { return 1; } ULONG STDMETHODCALLTYPE Release() throw() { return 1; } HANDLE GetQueueHandle() throw() { return m_hRequestQueue; } int GetNumThreads() throw() { return m_threadMap.GetSize(); } // QueueRequest adds a request to the thread pool // it will be picked up by one of the threads and dispatched to the worker // in WorkerThreadProc BOOL QueueRequest(Worker::RequestType request) throw() { if (!PostQueuedCompletionStatus(m_hRequestQueue, 0, (ULONG_PTR) request, NULL)) return FALSE; return TRUE; } protected: DWORD ThreadProc() throw() { DWORD dwBytesTransfered; ULONG_PTR dwCompletionKey; OVERLAPPED* pOverlapped; // We instantiate an instance of the worker class on the stack // for the life time of the thread. Worker theWorker; if (theWorker.Initialize(m_pvWorkerParam) == FALSE) { return 1; } SetEvent(m_hThreadEvent); // Get the request from the IO completion port while (GetQueuedCompletionStatus(m_hRequestQueue, &dwBytesTransfered, &dwCompletionKey, &pOverlapped, INFINITE)) { if (pOverlapped == ATLS_POOL_SHUTDOWN) // Shut down { m_dwThreadEventId = GetCurrentThreadId(); LONG bResult = InterlockedExchange(&m_bShutdown, FALSE); if (bResult) // Shutdown has not been cancelled break; m_dwThreadEventId = 0; // else, shutdown has been cancelled -- continue as before } else // Do work { Worker::RequestType request = (Worker::RequestType) dwCompletionKey; // Process the request. Notice the following: // (1) It is the worker's responsibility to free any memory associated // with the request if the request is complete // (2) If the request still requires some more processing // the worker should queue the request again for dispatching theWorker.Execute(request, m_pvWorkerParam, pOverlapped); } } SetEvent(m_hThreadEvent); theWorker.Terminate(m_pvWorkerParam); return 0; } static DWORD WINAPI WorkerThreadProc(LPVOID pv) throw() { CThreadPool* pThis = reinterpret_cast< CThreadPool* >(pv); return pThis->ThreadProc(); } HRESULT InternalResizePool(int nNumThreads, int dwMaxWait) throw() { if (!m_hRequestQueue) // Not initialized return E_FAIL; CComCritSecLock<CComCriticalSection> lock(m_critSec, false); if (FAILED(lock.Lock())) { // out of memory ATLASSERT( FALSE ); return E_FAIL; } int nCurThreads = m_threadMap.GetSize(); if (nNumThreads == nCurThreads) { return S_OK; } else if (nNumThreads < nCurThreads) { int nNumShutdownThreads = nCurThreads - nNumThreads; for (int nThreadIndex = 0; nThreadIndex < nNumShutdownThreads; nThreadIndex++) { ResetEvent(m_hThreadEvent); m_bShutdown = TRUE; PostQueuedCompletionStatus(m_hRequestQueue, 0, 0, ATLS_POOL_SHUTDOWN); DWORD dwRet = WaitForSingleObject(m_hThreadEvent, dwMaxWait); if (dwRet == WAIT_TIMEOUT) { LONG bResult = InterlockedExchange(&m_bShutdown, FALSE); if (bResult) // Nobody picked up the shutdown message { // m_critSec.Unlock(); return HRESULT_FROM_WIN32(WAIT_TIMEOUT); } } else if (dwRet != WAIT_OBJECT_0) { // m_critSec.Unlock(); return AtlHresultFromLastError(); } int nIndex = m_threadMap.FindKey(m_dwThreadEventId); if (nIndex != -1) { HANDLE hThread = m_threadMap.GetValueAt(nIndex); CloseHandle(hThread); m_threadMap.RemoveAt(nIndex); } } } else { int nNumNewThreads = nNumThreads - nCurThreads; // Create and initialize worker threads for (int nThreadIndex = 0; nThreadIndex < nNumNewThreads; nThreadIndex++) { DWORD dwThreadID; ResetEvent(m_hThreadEvent); // HANDLE hThread = ThreadTraits::CreateThread(NULL, m_dwStackSize, WorkerThreadProc, (LPVOID)this, 0, &dwThreadID); CHandle hdlThread( ThreadTraits::CreateThread(NULL, m_dwStackSize, WorkerThreadProc, (LPVOID)this, 0, &dwThreadID) ); if (!hdlThread) { HRESULT hr = AtlHresultFromLastError(); ATLASSERT(hr != S_OK); // m_critSec.Unlock(); return hr; } DWORD dwRet = WaitForSingleObject(m_hThreadEvent, dwMaxWait); if (dwRet != WAIT_OBJECT_0) { if (dwRet == WAIT_TIMEOUT) { // m_critSec.Unlock(); return HRESULT_FROM_WIN32(WAIT_TIMEOUT); } else { // m_critSec.Unlock(); return AtlHresultFromLastError(); } } if (m_threadMap.Add(dwThreadID, hdlThread) != FALSE) { hdlThread.Detach(); } } } // m_critSec.Unlock(); return S_OK; } }; // class CThreadPool // // CNonStatelessWorker // This class is a simple wrapper for use with CThreadPool. // It instantiates one instance of Worker per request // this allows Worker to hold state for each request // and depend on the destructor being called // Worker: // is a class that is responsible for handling requests // queued on the thread pool (See CThreadPool) template <class Worker> class CNonStatelessWorker { public: typedef Worker::RequestType RequestType; BOOL Initialize(void * /*pvParam*/) throw() { return TRUE; } void Execute(Worker::RequestType request, void *pvWorkerParam, OVERLAPPED *pOverlapped) { Worker worker; worker.Execute(request, pvWorkerParam, pOverlapped); } void Terminate(void* /*pvParam*/) throw() { } }; // class CNonStatelessWorker //Flags #define ATL_URL_ESCAPE 1 // (un)escape URL characters #define ATL_URL_NO_ENCODE 2 // Don't convert unsafe characters to escape sequence #define ATL_URL_DECODE 4 // Convert %XX escape sequences to characters #define ATL_URL_NO_META 8 // Don't convert .. etc. meta path sequences #define ATL_URL_ENCODE_SPACES_ONLY 16 // Encode spaces only #define ATL_URL_BROWSER_MODE 32 // Special encode/decode rules for browser #define ATL_URL_ENCODE_PERCENT 64 // Encode percent (by default, not encoded) #define ATL_URL_CANONICALIZE 128 // Internal: used by Canonicalize for AtlEscapeUrl: Cannot be set via SetFlags #define ATL_URL_COMBINE 256 // Internal: Cannot be set via SetFlags //Get the decimal value of a hexadecimal character inline short AtlHexValue(char chIn) { unsigned char ch = (unsigned char)chIn; if (ch >= '0' && ch <= '9') return (short)(ch - '0'); if (ch >= 'A' && ch <= 'F') return (short)(ch - 'A' + 10); if (ch >= 'a' && ch <= 'f') return (short)(ch - 'a' + 10); return -1; } //Determine if the character is unsafe under the URI RFC document inline BOOL AtlIsUnsafeUrlChar(char chIn) throw() { unsigned char ch = (unsigned char)chIn; switch(ch) { case ';': case '\\': case '?': case '@': case '&': case '=': case '+': case '$': case ',': case ' ': case '<': case '>': case '#': case '%': case '\"': case '{': case '}': case '|': case '^': case '[': case ']': case '`': return TRUE; default: { if (ch < 32 || ch > 126) return TRUE; return FALSE; } } } //Get the default internet port for a particular scheme inline ATL_URL_PORT AtlGetDefaultUrlPort(ATL_URL_SCHEME m_nScheme) throw() { switch (m_nScheme) { case ATL_URL_SCHEME_FTP: return ATL_URL_DEFAULT_FTP_PORT; case ATL_URL_SCHEME_GOPHER: return ATL_URL_DEFAULT_GOPHER_PORT; case ATL_URL_SCHEME_HTTP: return ATL_URL_DEFAULT_HTTP_PORT; case ATL_URL_SCHEME_HTTPS: return ATL_URL_DEFAULT_HTTPS_PORT; case ATL_URL_SCHEME_SOCKS: return ATL_URL_DEFAULT_SOCKS_PORT; default: return ATL_URL_INVALID_PORT_NUMBER; } } //Escape a meta sequence with lpszOutUrl as the base url and lpszInUrl as the relative url //i.e. lpszInUrl = ./* or ../* ATL_NOINLINE inline BOOL AtlEscapeUrlMetaHelper( LPSTR* ppszOutUrl, DWORD dwOutLen, LPSTR* ppszInUrl, DWORD* pdwLen, DWORD dwFlags = 0, DWORD dwColonPos = ATL_URL_MAX_URL_LENGTH) throw() { ATLASSERT( ppszOutUrl != NULL ); ATLASSERT( ppszInUrl != NULL ); ATLASSERT( pdwLen != NULL); LPSTR szOut = *ppszOutUrl; LPSTR szIn = *ppszInUrl; DWORD dwUrlLen = dwOutLen; char chPrev = *(szOut-1); BOOL bRet = FALSE; //if the previous character is a directory delimiter if (chPrev == '/' || chPrev == '\\') { char chNext = *szIn; //if the next character is a directory delimiter if (chNext == '/' || chNext == '\\') { //the meta sequence is of the form /./* szIn++; bRet = TRUE; } else if (chNext == '.' && ((chNext = *(szIn+1)) == '/' || chNext == '\\' || chNext == '\0')) { //otherwise if the meta sequence is of the form "/../" //skip the preceding "/" szOut--; //skip the ".." of the meta sequence szIn+= 2; DWORD dwOutPos = dwUrlLen-1; LPSTR szTmp = szOut; //while we are not at the beginning of the base url while (dwOutPos) { szTmp--; dwOutPos--; //if it is a directory delimiter if (*szTmp == '/' || *szTmp == '\\') { //if we are canonicalizing the url and NOT combining it //and if we have encountered the ':' or we are at a position before the ':' if ((dwFlags & ATL_URL_CANONICALIZE) && ((dwFlags & ATL_URL_COMBINE) == 0) && (dwColonPos && (dwOutPos <= dwColonPos+1))) { //NOTE: this is to match the way that InternetCanonicalizeUrl and // InternetCombineUrl handle this case break; } //otherwise, set the current output string position to right after the '/' szOut = szTmp+1; //update the length to match dwUrlLen = dwOutPos+1; bRet = TRUE; break; } } //if we could not properly escape the meta sequence if (dwUrlLen != dwOutPos+1) { //restore everything to its original value szIn-= 2; szOut++; } else { bRet = TRUE; } } } //update the strings *ppszOutUrl = szOut; *ppszInUrl = szIn; *pdwLen = dwUrlLen; return bRet; } //Convert all unsafe characters in szStringIn to escape sequences //lpszStringIn and lpszStringOut should be different strings inline BOOL AtlEscapeUrlA( LPCSTR szStringIn, LPSTR szStringOut, DWORD* pdwStrLen, DWORD dwMaxLength, DWORD dwFlags = 0) throw() { ATLASSERT( szStringIn != NULL ); ATLASSERT( szStringOut != NULL ); ATLASSERT( szStringIn != szStringOut ); char ch; DWORD dwLen = 0; BOOL bRet = TRUE; BOOL bSchemeFile = FALSE; DWORD dwColonPos = 0; DWORD dwFlagsInternal = dwFlags; while((ch = *szStringIn++) != '\0') { //if we are at the maximum length, set bRet to FALSE //this ensures no more data is written to szStringOut, but //the length of the string is still updated, so the user //knows how much space to allocate if (dwLen == dwMaxLength) { bRet = FALSE; } //Keep track of the first ':' position to match the weird way //InternetCanonicalizeUrl handles it if (ch == ':' && (dwFlagsInternal & ATL_URL_CANONICALIZE) && !dwColonPos) { if (bRet) { *szStringOut = '\0'; _strlwr(szStringOut-dwLen); if (dwLen == 4 && !strncmp("file", (szStringOut-4), 4)) { bSchemeFile = TRUE; } } dwColonPos = dwLen+1; } else if (ch == '%' && (dwFlagsInternal & ATL_URL_DECODE)) { //decode the escaped sequence ch = (char)(16*AtlHexValue(*szStringIn++)); ch = (char)(ch+AtlHexValue(*szStringIn++)); } else if ((ch == '?' || ch == '#') && (dwFlagsInternal & ATL_URL_BROWSER_MODE)) { //ATL_URL_BROWSER mode does not encode after a '?' or a '#' dwFlagsInternal |= ATL_URL_NO_ENCODE; } if ((dwFlagsInternal & ATL_URL_CANONICALIZE) && (dwFlagsInternal & ATL_URL_NO_ENCODE)==0) { //canonicalize the '\' to '/' if (ch == '\\' && (dwColonPos || (dwFlagsInternal & ATL_URL_COMBINE)) && bRet) { //if the scheme is not file or it is file and the '\' is in "file:\\" //NOTE: This is to match the way InternetCanonicalizeUrl handles this case if (!bSchemeFile || (dwLen < 7)) { ch = '/'; } } else if (ch == '.' && dwLen > 0 && (dwFlagsInternal & ATL_URL_NO_META)==0) { //if we are escaping meta sequences, attempt to do so if (AtlEscapeUrlMetaHelper(&szStringOut, dwLen, (char**)(&szStringIn), &dwLen, dwFlagsInternal, dwColonPos)) continue; } } //if we are encoding and it is an unsafe character if (AtlIsUnsafeUrlChar(ch) && (dwFlagsInternal & ATL_URL_NO_ENCODE)==0) { //if we are only encoding spaces, and ch is not a space or //if we are not encoding meta sequences and it is a dot or //if we not encoding percents and it is a percent if (((dwFlagsInternal & ATL_URL_ENCODE_SPACES_ONLY) && ch != ' ') || ((dwFlagsInternal & ATL_URL_NO_META) && ch == '.') || (((dwFlagsInternal & ATL_URL_ENCODE_PERCENT) == 0) && ch == '%')) { //just output it without encoding if (bRet) *szStringOut++ = ch; } else { //if there is not enough space for the escape sequence if (dwLen >= (dwMaxLength-3)) { bRet = FALSE; } if (bRet) { //output the percent, followed by the hex value of the character *szStringOut++ = '%'; // sprintf(szStringOut, "%.2X", (unsigned char)(ch)); _itoa((int)ch, szStringOut, 16); szStringOut+= 2; } dwLen += 2; } } else //safe character { if (bRet) *szStringOut++ = ch; } dwLen++; } if ((dwFlags & ATL_URL_BROWSER_MODE)==0) { //trim trailing whitespace szStringOut--; while (1) { if (*szStringOut == ' ') { --szStringOut; continue; } if (!strncmp(szStringOut-2, "%20", 3)) { szStringOut -= 3; continue; } break; } szStringOut++; } if (bRet) *szStringOut = '\0'; if (pdwStrLen) *pdwStrLen = dwLen; return bRet; } inline BOOL AtlEscapeUrlW( LPCWSTR szStringIn, LPWSTR szStringOut, DWORD* pdwStrLen, DWORD dwMaxLength, DWORD dwFlags = 0) throw() { // convert to UTF8 BOOL bRet = FALSE; int nSrcLen = (int) wcslen(szStringIn); int nCnt = AtlUnicodeToUTF8(szStringIn, nSrcLen, NULL, 0); if (nCnt != 0) { nCnt++; CHeapPtr<char> szIn; char szInBuf[ATL_URL_MAX_URL_LENGTH]; char *pszIn = szInBuf; // try to avoid allocation if (nCnt > ATL_URL_MAX_URL_LENGTH) { if (!szIn.AllocateBytes(nCnt)) { // out of memory return FALSE; } pszIn = szIn; } nCnt = AtlUnicodeToUTF8(szStringIn, nSrcLen, pszIn, nCnt); ATLASSERT( nCnt != 0 ); pszIn[nCnt] = '\0'; char szOutBuf[ATL_URL_MAX_URL_LENGTH]; char *pszOut = szOutBuf; CHeapPtr<char> szTmp; // try to avoid allocation if (dwMaxLength > ATL_URL_MAX_URL_LENGTH) { if (!szTmp.AllocateBytes(dwMaxLength)) { // out of memory return FALSE; } pszOut = szTmp; } DWORD dwStrLen = 0; bRet = AtlEscapeUrlA(pszIn, pszOut, &dwStrLen, dwMaxLength, dwFlags); if (bRet != FALSE) { // it is now safe to convert using any codepage, since there // are no non-ASCII characters pszOut[dwStrLen] = '\0'; _ATLTRY { memcpy(szStringOut, CA2W( pszOut ), dwStrLen*sizeof(wchar_t)); szStringOut[dwStrLen] = '\0'; } _ATLCATCHALL() { bRet = FALSE; } } if (pdwStrLen) { *pdwStrLen = dwStrLen; } } return bRet; } //Convert all escaped characters in szString to their real values //lpszStringIn and lpszStringOut can be the same string inline BOOL AtlUnescapeUrlA( LPCSTR szStringIn, LPSTR szStringOut, LPDWORD pdwStrLen, DWORD dwMaxLength) throw() { ATLASSERT(szStringIn != NULL); ATLASSERT(szStringOut != NULL); int nValue = 0; char ch; DWORD dwLen = 0; BOOL bRet = TRUE; while ((ch = *szStringIn) != 0) { if (dwLen == dwMaxLength) bRet = FALSE; if (bRet) { if (ch == '%') { if ((*(szStringIn+1) == '\0') || (*(szStringIn+2) == '\0')) { bRet = FALSE; break; } ch = *(++szStringIn); //currently assuming 2 hex values after '%' //as per the RFC 2396 document nValue = 16*AtlHexValue(ch); nValue+= AtlHexValue(*(++szStringIn)); *szStringOut++ = (char) nValue; } else //non-escape character { if (bRet) *szStringOut++ = ch; } } dwLen++; szStringIn++; } if (bRet) *szStringOut = '\0'; if (pdwStrLen) *pdwStrLen = dwLen; return TRUE; } inline BOOL AtlUnescapeUrlW( LPCWSTR szStringIn, LPWSTR szStringOut, LPDWORD pdwStrLen, DWORD dwMaxLength) throw() { /// convert to UTF8 BOOL bRet = FALSE; int nSrcLen = (int) wcslen(szStringIn); int nCnt = AtlUnicodeToUTF8(szStringIn, nSrcLen, NULL, 0); if (nCnt != 0) { nCnt++; CHeapPtr<char> szIn; char szInBuf[ATL_URL_MAX_URL_LENGTH]; char *pszIn = szInBuf; // try to avoid allocation if (nCnt > ATL_URL_MAX_URL_LENGTH) { if (!szIn.AllocateBytes(nCnt)) { // out of memory return FALSE; } pszIn = szIn; } nCnt = AtlUnicodeToUTF8(szStringIn, nSrcLen, pszIn, nCnt); ATLASSERT( nCnt != 0 ); pszIn[nCnt] = '\0'; char szOutBuf[ATL_URL_MAX_URL_LENGTH]; char *pszOut = szOutBuf; CHeapPtr<char> szTmp; // try to avoid allocation if (dwMaxLength > ATL_URL_MAX_URL_LENGTH) { if (!szTmp.AllocateBytes(dwMaxLength)) { // out of memory return FALSE; } pszOut = szTmp; } DWORD dwStrLen = 0; bRet = AtlUnescapeUrlA(pszIn, pszOut, &dwStrLen, dwMaxLength); if (bRet != FALSE) { // it is now safe to convert using any codepage, since there // are no non-ASCII characters pszOut[dwStrLen] = '\0'; _ATLTRY { memcpy(szStringOut, CA2W( pszOut ), dwStrLen*sizeof(wchar_t)); szStringOut[dwStrLen] = '\0'; } _ATLCATCHALL() { bRet = FALSE; } } if (pdwStrLen) { *pdwStrLen = dwStrLen; } } return bRet; } #ifdef UNICODE #define AtlEscapeUrl AtlEscapeUrlW #define AtlUnescapeUrl AtlUnescapeUrlW #else #define AtlEscapeUrl AtlEscapeUrlA #define AtlUnescapeUrl AtlUnescapeUrlA #endif //Canonicalize a URL (same as InternetCanonicalizeUrl) inline BOOL AtlCanonicalizeUrl( LPCTSTR szUrl, LPTSTR szCanonicalized, DWORD* pdwMaxLength, DWORD dwFlags = 0) throw() { ATLASSERT( szUrl != NULL ); ATLASSERT( szCanonicalized != NULL ); ATLASSERT( pdwMaxLength != NULL); return AtlEscapeUrl(szUrl, szCanonicalized, pdwMaxLength, *pdwMaxLength, dwFlags | ATL_URL_CANONICALIZE); } //Combine a base and relative URL (same as InternetCombineUrl) inline BOOL AtlCombineUrl( LPCTSTR szBaseUrl, LPCTSTR szRelativeUrl, LPTSTR szBuffer, DWORD* pdwMaxLength, DWORD dwFlags = 0) throw() { ATLASSERT(szBaseUrl != NULL); ATLASSERT(szRelativeUrl != NULL); ATLASSERT(szBuffer != NULL); ATLASSERT(pdwMaxLength != NULL); size_t nLen1 = _tcslen(szBaseUrl); TCHAR szCombined[2*ATL_URL_MAX_URL_LENGTH]; if (nLen1 >= 2*ATL_URL_MAX_URL_LENGTH) { return FALSE; } _tcscpy(szCombined, szBaseUrl); // if last char of szBaseUrl is not a slash, add it. if (nLen1 > 0 && szCombined[nLen1-1] != _T('/')) { szCombined[nLen1] = _T('/'); nLen1++; szCombined[nLen1] = _T('\0'); } size_t nLen2 = _tcslen(szRelativeUrl); if (nLen2+nLen1+1 >= 2*ATL_URL_MAX_URL_LENGTH) { return FALSE; } _tcsncpy(szCombined+nLen1, szRelativeUrl, nLen2+1); DWORD dwLen = (DWORD) (nLen1+nLen2); if (dwLen >= *pdwMaxLength) { *pdwMaxLength = dwLen; return FALSE; } return AtlEscapeUrl(szCombined, szBuffer, pdwMaxLength, *pdwMaxLength, dwFlags | ATL_URL_COMBINE | ATL_URL_CANONICALIZE); } class CUrl { private: //scheme names cannot contain escape/unsafe characters TCHAR m_szScheme[ATL_URL_MAX_SCHEME_LENGTH+1]; //host names cannot contain escape/unsafe characters TCHAR m_szHostName[ATL_URL_MAX_HOST_NAME_LENGTH+1]; TCHAR m_szUserName[ATL_URL_MAX_USER_NAME_LENGTH+1]; TCHAR m_szPassword[ATL_URL_MAX_PASSWORD_LENGTH+1]; TCHAR m_szUrlPath[ATL_URL_MAX_PATH_LENGTH+1]; TCHAR m_szExtraInfo[ATL_URL_MAX_PATH_LENGTH+1]; ATL_URL_PORT m_nPortNumber; ATL_URL_SCHEME m_nScheme; DWORD m_dwSchemeNameLength; DWORD m_dwHostNameLength; DWORD m_dwUserNameLength; DWORD m_dwPasswordLength; DWORD m_dwUrlPathLength; DWORD m_dwExtraInfoLength; public: //Empty constructor CUrl() throw() { InitFields(); SetScheme(ATL_URL_SCHEME_HTTP); } //Copy constructor--maybe make private CUrl(const CUrl& urlThat) throw() { CopyFields(urlThat); } //Destructor (empty) ~CUrl() throw() { } CUrl& operator=(const CUrl& urlThat) throw() { CopyFields(urlThat); return (*this); } //Set the url BOOL CrackUrl(LPCTSTR lpszUrl, DWORD dwFlags = 0) throw() { ATLASSERT(lpszUrl != NULL); InitFields(); BOOL bRet = FALSE; if (dwFlags & ATL_URL_DECODE) { //decode the url before parsing it TCHAR szDecodedUrl[ATL_URL_MAX_URL_LENGTH]; DWORD dwLen; if (!AtlUnescapeUrl(lpszUrl, szDecodedUrl, &dwLen, ATL_URL_MAX_URL_LENGTH)) return FALSE; bRet = Parse(szDecodedUrl); } else { bRet = Parse(lpszUrl); } if (bRet && (dwFlags & ATL_URL_ESCAPE)) { bRet = AtlUnescapeUrl(m_szUserName, m_szUserName, &m_dwUserNameLength, ATL_URL_MAX_USER_NAME_LENGTH); if (bRet) { bRet = AtlUnescapeUrl(m_szPassword, m_szPassword, &m_dwPasswordLength, ATL_URL_MAX_PASSWORD_LENGTH); if (bRet) { bRet = AtlUnescapeUrl(m_szUrlPath, m_szUrlPath, &m_dwUrlPathLength, ATL_URL_MAX_PATH_LENGTH); if (bRet) { bRet = AtlUnescapeUrl(m_szExtraInfo, m_szExtraInfo, &m_dwExtraInfoLength, ATL_URL_MAX_PATH_LENGTH); } } } } return bRet; } inline BOOL CreateUrl(LPTSTR lpszUrl, DWORD* pdwMaxLength, DWORD dwFlags = 0) const throw() { ATLASSERT(lpszUrl != NULL); ATLASSERT(pdwMaxLength != NULL); //build URL: <scheme>://<user>:<pass>@<domain>:<port><path><extra> TCHAR szPortNumber[ATL_URL_MAX_PORT_NUMBER_LENGTH+2]; DWORD dwLength = *pdwMaxLength; *pdwMaxLength = GetUrlLength()+1; if (*pdwMaxLength > dwLength) return FALSE; _stprintf(szPortNumber, _T(":%d"), m_nPortNumber); LPTSTR lpszOutUrl = lpszUrl; *lpszUrl = '\0'; if (*m_szScheme) { _tcsncpy(lpszUrl, m_szScheme, m_dwSchemeNameLength); lpszUrl += m_dwSchemeNameLength; *lpszUrl++ = ':'; if (m_nScheme != ATL_URL_SCHEME_MAILTO) { *lpszUrl++ = '/'; *lpszUrl++ = '/'; } } if (*m_szUserName) { _tcsncpy(lpszUrl, m_szUserName, m_dwUserNameLength); lpszUrl += m_dwUserNameLength; if (*m_szPassword) { *lpszUrl++ = ':'; _tcsncpy(lpszUrl, m_szPassword, m_dwPasswordLength); lpszUrl += m_dwPasswordLength; } *lpszUrl++ = '@'; } if (*m_szHostName) { _tcsncpy(lpszUrl, m_szHostName, m_dwHostNameLength); lpszUrl += m_dwHostNameLength; if (m_nPortNumber != AtlGetDefaultUrlPort(m_nScheme)) { DWORD dwPortLen = (DWORD) _tcslen(szPortNumber); _tcsncpy(lpszUrl, szPortNumber, dwPortLen); lpszUrl += dwPortLen; } if (*m_szUrlPath && *m_szUrlPath != '/' && *m_szUrlPath != '\\') *lpszUrl++ = '/'; } if (*m_szUrlPath) { _tcsncpy(lpszUrl, m_szUrlPath, m_dwUrlPathLength); lpszUrl+= m_dwUrlPathLength; } if (*m_szExtraInfo) { _tcsncpy(lpszUrl, m_szExtraInfo, m_dwExtraInfoLength); lpszUrl += m_dwExtraInfoLength; } *lpszUrl = '\0'; (*pdwMaxLength)--; if (dwFlags & ATL_URL_ESCAPE) { TCHAR szUrl[ATL_URL_MAX_URL_LENGTH]; _tcsncpy(szUrl, lpszOutUrl, *pdwMaxLength+1); return AtlUnescapeUrl(szUrl, lpszOutUrl, pdwMaxLength, dwLength); } return TRUE; } inline void Clear() throw() { InitFields(); } inline DWORD GetUrlLength() const throw() { //The conditionals in this method are related to the conditionals in the CreateUrl method //scheme + ':' DWORD dwUrlLength = m_dwSchemeNameLength+1; //i.e. "//" if (m_nScheme != ATL_URL_SCHEME_MAILTO) dwUrlLength += 2; dwUrlLength += m_dwUserNameLength; //i.e. "username@" if (m_dwUserNameLength > 0) dwUrlLength += m_dwUserNameLength+1; //i.e. ":password" if (m_dwPasswordLength > 0) dwUrlLength += m_dwPasswordLength+1; dwUrlLength += m_dwHostNameLength; // will need to add an extra '/' in this case if (m_dwHostNameLength && m_dwUrlPathLength && *m_szUrlPath != '/' && *m_szUrlPath != '\\') dwUrlLength++; //i.e. ":xx" where "xx" is the port number if (m_nPortNumber != AtlGetDefaultUrlPort(m_nScheme)) { TCHAR szPortTmp[6]; dwUrlLength += _stprintf(szPortTmp, _T(":%d"), m_nPortNumber); } dwUrlLength += m_dwUrlPathLength + m_dwExtraInfoLength; return dwUrlLength; } //Get the Scheme Name (i.e. http, ftp, etc.) inline LPCTSTR GetSchemeName() const throw() { return m_szScheme; } //Get the Scheme Name length inline DWORD GetSchemeNameLength() const throw() { return m_dwSchemeNameLength; } //This method will incur the cost of //validating the scheme and updating the scheme name inline BOOL SetSchemeName(LPCTSTR lpszSchm) throw() { ATLASSERT(lpszSchm != NULL); const _schemeinfo *pSchemes = GetSchemes(); ATLASSERT( pSchemes != NULL ); int nScheme = -1; for (int i=0; i<s_nSchemes; i++) { if (_tcsicmp(lpszSchm, pSchemes[i].szSchemeName) == 0) { nScheme = i; break; } } if (nScheme != -1) { m_nScheme = (ATL_URL_SCHEME) nScheme; m_dwSchemeNameLength = pSchemes[nScheme].dwSchemeLength; m_nPortNumber = (ATL_URL_PORT) pSchemes[nScheme].nUrlPort; } else { // unknown scheme m_nScheme = ATL_URL_SCHEME_UNKNOWN; m_dwSchemeNameLength = (DWORD) _tcslen(lpszSchm); m_nPortNumber = ATL_URL_INVALID_PORT_NUMBER; } _tcsncpy(m_szScheme, lpszSchm, m_dwSchemeNameLength); m_szScheme[m_dwSchemeNameLength] = '\0'; return TRUE; } inline BOOL SetScheme(ATL_URL_SCHEME nScheme) throw() { if ((nScheme < 0) || (nScheme >= s_nSchemes)) { // invalid scheme return FALSE; } const _schemeinfo *pSchemes = GetSchemes(); ATLASSERT( pSchemes != NULL ); m_nScheme = (ATL_URL_SCHEME) nScheme; m_dwSchemeNameLength = pSchemes[nScheme].dwSchemeLength; m_nPortNumber = (ATL_URL_PORT) pSchemes[nScheme].nUrlPort; _tcsncpy(m_szScheme, pSchemes[nScheme].szSchemeName, m_dwSchemeNameLength); return TRUE; } inline ATL_URL_SCHEME GetScheme() const throw() { return m_nScheme; } //Get the host name inline LPCTSTR GetHostName() const throw() { return m_szHostName; } //Get the host name's length inline DWORD GetHostNameLength() const throw() { return m_dwHostNameLength; } //Set the Host name inline BOOL SetHostName(LPCTSTR lpszHost) throw() { ATLASSERT(lpszHost != NULL); DWORD dwLen = (DWORD) _tcslen(lpszHost); if (dwLen > ATL_URL_MAX_HOST_NAME_LENGTH) return FALSE; _tcsncpy(m_szHostName, lpszHost, dwLen+1); m_dwHostNameLength = dwLen; return TRUE; } //Get the port number in terms of ATL_URL_PORT inline ATL_URL_PORT GetPortNumber() const throw() { return m_nPortNumber; } //Set the port number in terms of ATL_URL_PORT inline BOOL SetPortNumber(ATL_URL_PORT nPrt) throw() { m_nPortNumber = nPrt; return TRUE; } //Get the user name inline LPCTSTR GetUserName() const throw() { return m_szUserName; } //Get the user name's length inline DWORD GetUserNameLength() const throw() { return m_dwUserNameLength; } //Set the user name inline BOOL SetUserName(LPCTSTR lpszUser) throw() { ATLASSERT(lpszUser != NULL); DWORD dwLen = (DWORD) _tcslen(lpszUser); if (dwLen > ATL_URL_MAX_USER_NAME_LENGTH) return FALSE; _tcsncpy(m_szUserName, lpszUser, dwLen+1); m_dwUserNameLength = dwLen; return TRUE; } //Get the password inline LPCTSTR GetPassword() const throw() { return m_szPassword; } //Get the password's length inline DWORD GetPasswordLength() const throw() { return m_dwPasswordLength; } //Set the password inline BOOL SetPassword(LPCTSTR lpszPass) throw() { ATLASSERT(lpszPass != NULL); if (*lpszPass && !*m_szUserName) return FALSE; DWORD dwLen = (DWORD) _tcslen(lpszPass); if (dwLen > ATL_URL_MAX_PASSWORD_LENGTH) return FALSE; _tcsncpy(m_szPassword, lpszPass, dwLen+1); m_dwPasswordLength = dwLen; return TRUE; } //Get the url path (everything after scheme and //before extra info) inline LPCTSTR GetUrlPath() const throw() { return m_szUrlPath; } //Get the url path's length inline DWORD GetUrlPathLength() const throw() { return m_dwUrlPathLength; } //Set the url path inline BOOL SetUrlPath(LPCTSTR lpszPath) throw() { ATLASSERT(lpszPath != NULL); DWORD dwLen = (DWORD) _tcslen(lpszPath); if (dwLen > ATL_URL_MAX_PATH_LENGTH) return FALSE; _tcsncpy(m_szUrlPath, lpszPath, dwLen+1); m_dwUrlPathLength = dwLen; return TRUE; } //Get extra info (i.e. ?something or #something) inline LPCTSTR GetExtraInfo() const throw() { return m_szExtraInfo; } //Get extra info's length inline DWORD GetExtraInfoLength() const throw() { return m_dwExtraInfoLength; } //Set extra info inline BOOL SetExtraInfo(LPCTSTR lpszInfo) throw() { ATLASSERT(lpszInfo != NULL); DWORD dwLen = (DWORD) _tcslen(lpszInfo); if (dwLen > ATL_URL_MAX_PATH_LENGTH) return FALSE; _tcsncpy(m_szExtraInfo, lpszInfo, dwLen+1); m_dwExtraInfoLength = dwLen; return TRUE; } //Insert Escape characters into URL inline BOOL Canonicalize(DWORD dwFlags = 0) throw() { _tcslwr(m_szScheme); TCHAR szTmp[ATL_URL_MAX_URL_LENGTH]; _tcscpy(szTmp, m_szUserName); BOOL bRet = AtlEscapeUrl(szTmp, m_szUserName, &m_dwUserNameLength, ATL_URL_MAX_USER_NAME_LENGTH, dwFlags); if (bRet) { _tcscpy(szTmp, m_szPassword); bRet = AtlEscapeUrl(szTmp, m_szPassword, &m_dwPasswordLength, ATL_URL_MAX_PASSWORD_LENGTH, dwFlags); } if (bRet) { _tcscpy(szTmp, m_szHostName); bRet = AtlEscapeUrl(szTmp, m_szHostName, &m_dwHostNameLength, ATL_URL_MAX_HOST_NAME_LENGTH, dwFlags); } if (bRet) { _tcscpy(szTmp, m_szUrlPath); bRet = AtlEscapeUrl(szTmp, m_szUrlPath, &m_dwUrlPathLength, ATL_URL_MAX_PATH_LENGTH, dwFlags); } //in ATL_URL_BROWSER mode, the portion of the URL following the '?' or '#' is not encoded if (bRet && (dwFlags & ATL_URL_BROWSER_MODE) == 0) { _tcscpy(szTmp, m_szExtraInfo); bRet = AtlEscapeUrl(szTmp+1, m_szExtraInfo+1, &m_dwExtraInfoLength, ATL_URL_MAX_PATH_LENGTH-1, dwFlags); if (bRet) m_dwExtraInfoLength++; } return bRet; } private: const static DWORD s_nSchemes = 8; struct _schemeinfo { LPCTSTR szSchemeName; DWORD dwSchemeLength; ATL_URL_PORT nUrlPort; }; const _schemeinfo * GetSchemes() throw() { const static _schemeinfo s_schemes[] = { { _T("ftp"), sizeof("ftp")-1, ATL_URL_DEFAULT_FTP_PORT }, { _T("gopher"), sizeof("gopher")-1, ATL_URL_DEFAULT_GOPHER_PORT }, { _T("http"), sizeof("http")-1, ATL_URL_DEFAULT_HTTP_PORT }, { _T("https"), sizeof("https")-1, ATL_URL_DEFAULT_HTTPS_PORT }, { _T("file"), sizeof("file")-1, ATL_URL_INVALID_PORT_NUMBER }, { _T("news"), sizeof("news")-1, ATL_URL_INVALID_PORT_NUMBER }, { _T("mailto"), sizeof("mailto")-1, ATL_URL_INVALID_PORT_NUMBER }, { _T("socks"), sizeof("socks")-1, ATL_URL_DEFAULT_SOCKS_PORT } }; return s_schemes; } inline BOOL Parse(LPCTSTR lpszUrl) throw() { ATLASSERT(lpszUrl != NULL); TCHAR ch; BOOL bGotScheme = FALSE; BOOL bGotUserName = FALSE; BOOL bGotHostName = FALSE; BOOL bGotPortNumber = FALSE; TCHAR szCurrentUrl[ATL_URL_MAX_URL_LENGTH+6]; TCHAR* pszCurrentUrl = szCurrentUrl; //parse lpszUrl using szCurrentUrl to store temporary data //this loop will get the following if it exists: //<protocol>://user:pass@server:port while ((ch = *lpszUrl) != '\0') { if (ch == ':') { //3 cases: //(1) Just encountered a scheme //(2) Port number follows //(3) Form of username:password@ // Check to see if we've just encountered a scheme *pszCurrentUrl = '\0'; if (!bGotScheme) { if (!SetSchemeName(szCurrentUrl)) goto error; //Set a flag to avoid checking for //schemes everytime we encounter a : bGotScheme = TRUE; if (*(lpszUrl+1) == '/') { if (*(lpszUrl+2) == '/') { //the mailto scheme cannot have a '/' following the "mailto:" portion if (bGotScheme && m_nScheme == ATL_URL_SCHEME_MAILTO) goto error; //Skip these characters and continue lpszUrl+= 2; } else { //it is an absolute path //no domain name, port, username, or password is allowed in this case //break to loop that gets path lpszUrl++; pszCurrentUrl = szCurrentUrl; break; } } //reset pszCurrentUrl pszCurrentUrl = szCurrentUrl; lpszUrl++; //if the scheme is file, skip to getting the path information if (m_nScheme == ATL_URL_SCHEME_FILE) break; continue; } else if (!bGotUserName || !bGotPortNumber) { //It must be a username:password or a port number *pszCurrentUrl = '\0'; pszCurrentUrl = szCurrentUrl; TCHAR tmpBuf[ATL_URL_MAX_PASSWORD_LENGTH]; TCHAR* pTmpBuf = tmpBuf; int nCnt = 0; //get the user or portnumber (break on either '/', '@', or '\0' while (((ch = *(++lpszUrl)) != '/') && (ch != '@') && (ch != '\0')) { if (nCnt >= ATL_URL_MAX_PASSWORD_LENGTH) goto error; *pTmpBuf++ = ch; nCnt++; } *pTmpBuf = '\0'; //if we broke on a '/' or a '\0', it must be a port number if (!bGotPortNumber && (ch == '/' || ch == '\0')) { //the host name must immediately preced the port number if (!SetHostName(szCurrentUrl)) goto error; //get the port number m_nPortNumber = (ATL_URL_PORT) _ttoi(tmpBuf); if (m_nPortNumber < 0) goto error; bGotPortNumber = bGotHostName = TRUE; } else if (!bGotUserName && ch=='@') { //otherwise it must be a username:password if (!SetUserName(szCurrentUrl) || !SetPassword(tmpBuf)) goto error; bGotUserName = TRUE; lpszUrl++; } else { goto error; } } } else if (ch == '@') { if (bGotUserName) goto error; //type is userinfo@ *pszCurrentUrl = '\0'; if (!SetUserName(szCurrentUrl)) goto error; bGotUserName = TRUE; lpszUrl++; pszCurrentUrl = szCurrentUrl; } else if (ch == '/' || ch == '?' || (!*(lpszUrl+1))) { //we're at the end of this loop //set the domain name and break if (!*(lpszUrl+1) && ch != '/' && ch != '?') { *pszCurrentUrl++ = ch; lpszUrl++; } *pszCurrentUrl = '\0'; if (!bGotHostName) { if (!SetHostName(szCurrentUrl)) goto error; } pszCurrentUrl = szCurrentUrl; break; } else { *pszCurrentUrl++ = ch; lpszUrl++; } } if (!bGotScheme) goto error; //Now build the path while ((ch = *lpszUrl) != '\0') { //break on a '#' or a '?', which delimit "extra information" if (m_nScheme != ATL_URL_SCHEME_FILE && (ch == '#' || ch == '?')) { break; } *pszCurrentUrl++ = ch; lpszUrl++; } *pszCurrentUrl = '\0'; if (*szCurrentUrl != '\0' && !SetUrlPath(szCurrentUrl)) goto error; pszCurrentUrl = szCurrentUrl; while ((ch = *lpszUrl++) != '\0') { *pszCurrentUrl++ = ch; } *pszCurrentUrl = '\0'; if (*szCurrentUrl != '\0' && !SetExtraInfo(szCurrentUrl)) goto error; switch(m_nScheme) { case ATL_URL_SCHEME_FILE: m_nPortNumber = ATL_URL_INVALID_PORT_NUMBER; break; case ATL_URL_SCHEME_NEWS: m_nPortNumber = ATL_URL_INVALID_PORT_NUMBER; break; case ATL_URL_SCHEME_MAILTO: m_nPortNumber = ATL_URL_INVALID_PORT_NUMBER; break; default: if (!bGotPortNumber) m_nPortNumber = (unsigned short)AtlGetDefaultUrlPort(m_nScheme); } return TRUE; error: InitFields(); return FALSE; } ATL_NOINLINE void InitFields() throw() { m_nPortNumber = ATL_URL_INVALID_PORT_NUMBER; m_nScheme = ATL_URL_SCHEME_UNKNOWN; m_dwSchemeNameLength = 0; m_dwHostNameLength = 0; m_dwUserNameLength = 0; m_dwUrlPathLength = 0; m_dwPasswordLength = 0; m_dwExtraInfoLength = 0; m_szScheme[0] = '\0'; m_szHostName[0] = '\0'; m_szUserName[0] = '\0'; m_szPassword[0] = '\0'; m_szUrlPath[0] = '\0'; m_szExtraInfo[0] = '\0'; } //copy all fields from urlThat inline void CopyFields(const CUrl& urlThat) throw() { _tcsncpy(m_szScheme, urlThat.m_szScheme, urlThat.m_dwSchemeNameLength+1); _tcsncpy(m_szHostName, urlThat.m_szHostName, urlThat.m_dwHostNameLength+1); _tcsncpy(m_szUserName, urlThat.m_szUserName, urlThat.m_dwUserNameLength+1); _tcsncpy(m_szPassword, urlThat.m_szPassword, urlThat.m_dwPasswordLength+1); _tcsncpy(m_szUrlPath, urlThat.m_szUrlPath, urlThat.m_dwUrlPathLength+1); _tcsncpy(m_szExtraInfo, urlThat.m_szExtraInfo, urlThat.m_dwExtraInfoLength+1); m_nPortNumber = urlThat.m_nPortNumber; m_nScheme = urlThat.m_nScheme; m_dwSchemeNameLength = urlThat.m_dwSchemeNameLength; m_dwHostNameLength = urlThat.m_dwHostNameLength; m_dwUserNameLength = urlThat.m_dwUserNameLength; m_dwPasswordLength = urlThat.m_dwPasswordLength; m_dwUrlPathLength = urlThat.m_dwUrlPathLength; m_dwExtraInfoLength = urlThat.m_dwExtraInfoLength; } }; // class CUrl typedef CUrl* LPURL; typedef const CUrl * LPCURL; #ifndef ATL_WORKER_THREAD_WAIT #define ATL_WORKER_THREAD_WAIT 10000 // time to wait when shutting down #endif // // CWorkerThread // This class creates a worker thread that waits on kernel // object handles and executes a specified client // function when the handle is signaled // To use it, construct an instance, call Initialize // then call add AddHandle with the handle of a kernel // object and pass a pointer to your implementation // of IWorkerThreadClient. Execute on your IWorkerThreadClient // implementation will be called when the handle is signaled // You can also use AddTimer() to add a waitable timer // to the worker thread. // If the thread is still active when your object is destroyed // you must call RemoveHandle() on each handle that your object // owns. // To terminate the thread, call Shutdown // template <class ThreadTraits=DefaultThreadTraits> class CWorkerThread { protected: HANDLE m_hThread; DWORD m_dwThreadId; CWorkerThread<ThreadTraits> *m_pThread; struct WorkerClientEntry { IWorkerThreadClient *pClient; DWORD_PTR dwParam; }; CSimpleArray<HANDLE> m_hWaitHandles; CSimpleArray<WorkerClientEntry, CSimpleArrayEqualHelperFalse<WorkerClientEntry> > m_ClientEntries; CComCriticalSection m_critSec; HANDLE m_hRefreshComplete; void Refresh() throw() { ATLASSERT(m_hRefreshComplete); BOOL bRet = SetEvent(m_hWaitHandles[1]); ATLASSERT(bRet); bRet; // unused WaitForSingleObject(m_hRefreshComplete, INFINITE); } public: CWorkerThread() throw() : m_hThread(NULL), m_dwThreadId(0), m_hRefreshComplete(NULL), m_pThread(NULL) { } ~CWorkerThread() throw() { Shutdown(); } DWORD GetThreadId() throw() { if (m_pThread) return m_pThread->GetThreadId(); return m_dwThreadId; } HANDLE GetThreadHandle() throw() { if (m_pThread) return m_pThread->GetThreadHandle(); return m_hThread; } HRESULT Initialize() throw() { if (m_pThread) return E_UNEXPECTED; // already initialized! // the object should be initialized first ATLASSERT(m_hWaitHandles.GetSize() == 0); m_critSec.Init(); // create the refresh complete event m_hRefreshComplete = CreateEvent(NULL, FALSE, FALSE, NULL); if (!m_hRefreshComplete) { m_critSec.Term(); return AtlHresultFromLastError(); } // add the shutdown event HRESULT hr; HANDLE hEventShutdown = CreateEvent(NULL, FALSE, FALSE, NULL); if (!hEventShutdown) { hr = AtlHresultFromLastError(); Shutdown(); return hr; } hr = AddHandle(hEventShutdown, NULL, 0); if (FAILED(hr)) { CloseHandle(hEventShutdown); Shutdown(); return hr; } // create the refresh event HANDLE hEventRefresh = CreateEvent(NULL, FALSE, FALSE, NULL); if (!hEventRefresh) { hr = AtlHresultFromLastError(); Shutdown(); return hr; } hr = AddHandle(hEventRefresh, NULL, 0); if (FAILED(hr)) { CloseHandle(hEventRefresh); Shutdown(); return hr; } m_hThread = ThreadTraits::CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) _WorkerThreadProc, this, 0, &m_dwThreadId); if (!m_hThread) { hr = AtlHresultFromLastError(); Shutdown(); return hr; } WaitForSingleObject(m_hRefreshComplete, INFINITE); return S_OK; } HRESULT Initialize(CWorkerThread<ThreadTraits> *pThread) { if (!pThread) return E_INVALIDARG; if (m_hThread) return E_UNEXPECTED; // already initialized if (!m_pThread) { m_pThread = pThread; } return S_OK; } HRESULT AddHandle(HANDLE hObject, IWorkerThreadClient *pClient, DWORD_PTR dwParam) throw() { if (m_pThread) return m_pThread->AddHandle(hObject, pClient, dwParam); // Make sure the object has been initialized ATLASSERT(m_hRefreshComplete != NULL); CComCritSecLock<CComCriticalSection> lock(m_critSec, false); HRESULT hr = lock.Lock(); if (FAILED(hr)) return hr; if (m_hWaitHandles.GetSize() == MAXIMUM_WAIT_OBJECTS) { return AtlHresultFromWin32(ERROR_INVALID_PARAMETER); } BOOL bRet = m_hWaitHandles.Add(hObject); if (!bRet) { return E_OUTOFMEMORY; } WorkerClientEntry entry; entry.pClient = pClient; entry.dwParam = dwParam; bRet = m_ClientEntries.Add(entry); if (!bRet) { m_hWaitHandles.RemoveAt(m_hWaitHandles.GetSize()-1); return E_OUTOFMEMORY; } if (m_hWaitHandles.GetSize() > 2) { // tell the worker thread to refresh Refresh(); } return S_OK; } #if (_WIN32_WINNT >= 0x0400) || (_WIN32_WINDOWS > 0x0400) HRESULT AddTimer(DWORD dwInterval, IWorkerThreadClient *pClient, DWORD_PTR dwParam, HANDLE *phTimer) throw() { if (m_pThread) return m_pThread->AddTimer(dwInterval, pClient, dwParam, phTimer); // Make sure the object has been initialized ATLASSERT(m_hRefreshComplete != NULL); ATLASSERT(phTimer); *phTimer = NULL; HANDLE hTimer = CreateWaitableTimer(NULL, FALSE, NULL); if (!hTimer) { return AtlHresultFromLastError(); } HRESULT hr; LARGE_INTEGER liDueTime; liDueTime.QuadPart = -10000 * (__int64) dwInterval; BOOL bRet = SetWaitableTimer(hTimer, &liDueTime, dwInterval, NULL, NULL, FALSE); if (!bRet) { hr = AtlHresultFromLastError(); CloseHandle(hTimer); return hr; } hr = AddHandle(hTimer, pClient, dwParam); if (FAILED(hr)) { CloseHandle(hTimer); return hr; } if (phTimer) *phTimer = hTimer; return S_OK; } #endif HRESULT RemoveHandle(HANDLE hObject) throw() { if (m_pThread) return m_pThread->RemoveHandle(hObject); // Make sure the object has been initialized ATLASSERT(m_hRefreshComplete != NULL); CComCritSecLock<CComCriticalSection> lock(m_critSec, false); HRESULT hr = lock.Lock(); if (FAILED(hr)) return hr; int nIndex = m_hWaitHandles.Find(hObject); if (nIndex >= 0) { ATLASSERT(nIndex < m_ClientEntries.GetSize()); IWorkerThreadClient *pClient = m_ClientEntries[nIndex].pClient; m_hWaitHandles.RemoveAt(nIndex); m_ClientEntries.RemoveAt(nIndex); Refresh(); // now it is safe to close the handle if (!pClient || FAILED(pClient->CloseHandle(hObject))) CloseHandle(hObject); } return S_OK; } HRESULT Shutdown(DWORD dwWait=ATL_WORKER_THREAD_WAIT) throw() { if (m_pThread) return S_OK; if (!m_hThread) { RemoveAllClients(); m_critSec.Term(); if (m_hRefreshComplete) { CloseHandle(m_hRefreshComplete); m_hRefreshComplete = NULL; } return S_OK; } ATLASSERT(m_hWaitHandles.GetSize() > 0); SetEvent(m_hWaitHandles[0]); DWORD dwRet = WaitForSingleObject(m_hThread, dwWait); RemoveAllClients(); CloseHandle(m_hThread); m_hThread = NULL; if (m_hRefreshComplete) { CloseHandle(m_hRefreshComplete); m_hRefreshComplete = NULL; } m_critSec.Term(); return (dwRet == WAIT_OBJECT_0) ? S_OK : AtlHresultFromWin32(dwRet); } protected: void RemoveAllClients() throw() { ATLASSERT(m_hWaitHandles.GetSize() == m_ClientEntries.GetSize()); int nLen = m_hWaitHandles.GetSize(); for (int i = 0; i < nLen; i++) { WorkerClientEntry& entry = m_ClientEntries[i]; if (!entry.pClient || FAILED(entry.pClient->CloseHandle(m_hWaitHandles[i]))) CloseHandle(m_hWaitHandles[i]); } m_hWaitHandles.RemoveAll(); m_ClientEntries.RemoveAll(); } DWORD WorkerThreadProc() throw() { // Make sure the object has been initialized ATLASSERT(m_hRefreshComplete != NULL); CSimpleArray<HANDLE> handles(m_hWaitHandles); CSimpleArray<WorkerClientEntry, CSimpleArrayEqualHelperFalse<WorkerClientEntry> > clientEntries(m_ClientEntries); // tell the main thread we're done copying SetEvent(m_hRefreshComplete); while (TRUE) { DWORD dwRet = WaitForMultipleObjects(handles.GetSize(), handles.GetData(), FALSE, INFINITE); // check for shutdown if (dwRet == WAIT_OBJECT_0) return 0; else if (dwRet == WAIT_OBJECT_0+1) // check for refresh { handles = m_hWaitHandles; clientEntries = m_ClientEntries; // tell the main thread we're done copying SetEvent(m_hRefreshComplete); continue; } else if (dwRet > WAIT_OBJECT_0 && dwRet < WAIT_OBJECT_0 + handles.GetSize()) { // execute the approriate client WorkerClientEntry& entry = clientEntries[dwRet - WAIT_OBJECT_0]; // We ignore the error code because nothing useful can be done with it in this // implementation entry.pClient->Execute(entry.dwParam, handles[dwRet - WAIT_OBJECT_0]); } else { // this probably means an invalid handle was added ATLASSERT(FALSE); return 1; } } return 0; } static DWORD WINAPI _WorkerThreadProc(CWorkerThread *pThis) throw() { return pThis->WorkerThreadProc(); } }; // class CWorkerThread // Use CNoWorkerThread as a template argument for classes // that need a worker thread type as a template argument but // don't require the services of a worker thread. An example // would be CDllCache (atlutil.h) when you want to create a // CDllCache with no sweeper thread. class CNoWorkerThread { public: DWORD GetThreadId() throw() { return 0; } HANDLE GetThreadHandle() throw() { return NULL; } HRESULT Initialize() throw() { return S_OK; } HRESULT AddHandle(HANDLE /*hObject*/, IWorkerThreadClient * /*pClient*/, DWORD_PTR /*dwParam*/) throw() { return S_OK; } HRESULT AddTimer(DWORD /*dwInterval*/, IWorkerThreadClient * /*pClient*/, DWORD_PTR /*dwParam*/, HANDLE * /*phTimer*/) throw() { return S_OK; } HRESULT RemoveHandle(HANDLE /*hObject*/) throw() { return S_OK; } HRESULT Shutdown(DWORD dwWait=ATL_WORKER_THREAD_WAIT) throw() { dwWait; return S_OK; } }; // CNoWorkerThread class CBrowserCaps : public IBrowserCaps, public CComObjectRootEx<CComSingleThreadModel> { public: BEGIN_COM_MAP(CBrowserCaps) COM_INTERFACE_ENTRY(IBrowserCaps) END_COM_MAP() CBrowserCaps() { } void FinalRelease() { if (m_pParent) m_pParent->Release(); } HRESULT Initialize(IXMLDOMNode * pNode, IBrowserCapsSvc * pSvc) { if (!pNode) return E_POINTER; HRESULT hr = pNode->QueryInterface(__uuidof(IXMLDOMElement), (void **)&m_spElement); if (FAILED(hr)) return hr; CComPtr<IXMLDOMNamedNodeMap> spList; hr = pNode->get_attributes(&spList); if (FAILED(hr)) return hr; CComPtr<IXMLDOMNode> spItem; hr = spList->getNamedItem((BSTR)L"parent", &spItem); if (FAILED(hr)) return hr; if (hr == S_FALSE) m_pParent = NULL; else { if (!spItem) return E_FAIL; CComVariant varVal; hr = spItem->get_nodeValue(&varVal); if (FAILED(hr)) return hr; varVal.ChangeType(VT_BSTR); hr = pSvc->GetCapsUserAgent(varVal.bstrVal, (IBrowserCaps **)&m_pParent); if (FAILED(hr)) return hr; } return S_OK; } HRESULT GetPropertyString(BSTR bstrProperty, BSTR * pbstrOut) { ATLASSERT(m_spElement); if (!m_spElement) return E_FAIL; if (!pbstrOut) return E_POINTER; *pbstrOut = NULL; CComPtr<IXMLDOMNodeList> spList; HRESULT hr = m_spElement->getElementsByTagName(bstrProperty, &spList); if (FAILED(hr)) return hr; long nLength; hr = spList->get_length(&nLength); if (FAILED(hr)) return hr; if (nLength == 0) { if (m_pParent) return m_pParent->GetPropertyString(bstrProperty, pbstrOut); else return E_FAIL; } // Assume the first one is the correct node CComPtr<IXMLDOMNode> spNode; hr = spList->get_item(0, &spNode); if (FAILED(hr)) return hr; CComBSTR bstrValue; hr = spNode->get_text(&bstrValue); if (FAILED(hr)) return hr; *pbstrOut = bstrValue.Detach(); return hr; } HRESULT GetBooleanPropertyValue(BSTR bstrProperty, BOOL* pbOut) { if (!pbOut) return E_POINTER; CComBSTR bstrOut; HRESULT hr = GetPropertyString(bstrProperty, &bstrOut); if (FAILED(hr)) return hr; if (bstrOut[0] == L'1' && bstrOut.Length() == 1) *pbOut = TRUE; else *pbOut = FALSE; return S_OK; } HRESULT GetBrowserName(BSTR * pbstrName) { return GetPropertyString(L"name", pbstrName); } HRESULT GetPlatform(BSTR * pbstrPlatform) { return GetPropertyString(L"platform", pbstrPlatform); } HRESULT GetVersion(BSTR * pbstrVersion) { return GetPropertyString(L"version", pbstrVersion); } HRESULT GetMajorVer(BSTR * pbstrMajorVer) { return GetPropertyString(L"majorver", pbstrMajorVer); } HRESULT GetMinorVer(BSTR * pbstrMinorVer) { return GetPropertyString(L"minorver", pbstrMinorVer); } HRESULT SupportsFrames(BOOL* pbFrames) { return GetBooleanPropertyValue(L"frames", pbFrames); } HRESULT SupportsTables(BOOL* pbTables) { return GetBooleanPropertyValue(L"tables", pbTables); } HRESULT SupportsCookies(BOOL* pbCookies) { return GetBooleanPropertyValue(L"cookies", pbCookies); } HRESULT SupportsBackgroundSounds(BOOL* pbBackgroundSounds) { return GetBooleanPropertyValue(L"backgroundsounds", pbBackgroundSounds); } HRESULT SupportsVBScript(BOOL* pbVBScript) { return GetBooleanPropertyValue(L"vbscript", pbVBScript); } HRESULT SupportsJavaScript(BOOL* pbJavaScript) { return GetBooleanPropertyValue(L"javascript", pbJavaScript); } HRESULT SupportsJavaApplets(BOOL* pbJavaApplets) { return GetBooleanPropertyValue(L"javaapplets", pbJavaApplets); } HRESULT SupportsActiveXControls(BOOL* pbActiveXControls) { return GetBooleanPropertyValue(L"ActiveXControls", pbActiveXControls); } HRESULT SupportsCDF(BOOL* pbCDF) { return GetBooleanPropertyValue(L"CDF", pbCDF); } HRESULT SupportsAuthenticodeUpdate(BOOL* pbAuthenticodeUpdate) { return GetBooleanPropertyValue(L"AuthenticodeUpdate", pbAuthenticodeUpdate); } HRESULT IsBeta(BOOL* pbIsBeta) { return GetBooleanPropertyValue(L"beta", pbIsBeta); } HRESULT IsCrawler(BOOL* pbIsCrawler) { return GetBooleanPropertyValue(L"Crawler", pbIsCrawler); } HRESULT IsAOL(BOOL* pbIsAOL) { return GetBooleanPropertyValue(L"AOL", pbIsAOL); } HRESULT IsWin16(BOOL* pbIsWin16) { return GetBooleanPropertyValue(L"Win16", pbIsWin16); } HRESULT IsAK(BOOL* pbIsAK) { return GetBooleanPropertyValue(L"AK", pbIsAK); } HRESULT IsSK(BOOL* pbIsSK) { return GetBooleanPropertyValue(L"SK", pbIsSK); } HRESULT IsUpdate(BOOL* pbIsUpdate) { return GetBooleanPropertyValue(L"Update", pbIsUpdate); } private: CComPtr<IXMLDOMElement> m_spElement; CComObjectNoLock<CBrowserCaps> * m_pParent; }; template <class TVal> class CWildCardEqualHelper { public: static bool IsEqualKey(LPCWSTR szPattern, LPCWSTR szInput) { while (*szPattern && *szInput && *szPattern == *szInput) { szPattern++; szInput++; } if (*szPattern == *szInput) return TRUE; if (*szPattern == '*') { szPattern++; if (!*szPattern) return true; while(*szInput) { if (IsEqualKey(szPattern, szInput)) return TRUE; szInput++; } } return FALSE; } static bool IsEqualValue(TVal& v1, const TVal& v2) { return (v1 == v2); } }; class CBrowserCapsSvc : public IBrowserCapsSvc, public CComObjectRootEx<CComSingleThreadModel> { public: BEGIN_COM_MAP(CBrowserCapsSvc) COM_INTERFACE_ENTRY(IBrowserCapsSvc) END_COM_MAP() HRESULT GetCaps(IHttpServerContext * pContext, IBrowserCaps ** ppOut) { if (!pContext) return E_POINTER; if (!ppOut) return E_POINTER; *ppOut = NULL; char szUserAgent[256]; DWORD dwSize = sizeof(szUserAgent); if (!pContext->GetServerVariable("HTTP_USER_AGENT", szUserAgent, &dwSize)) return E_FAIL; CComBSTR bstrAgent = szUserAgent; return GetCapsUserAgent(bstrAgent, ppOut); } HRESULT GetCapsUserAgent(BSTR bstrAgent, IBrowserCaps ** ppOut) { if (!bstrAgent) return E_POINTER; if (!ppOut) return E_POINTER; *ppOut = NULL; CComPtr<IXMLDOMNode> spNode; spNode = m_Map.Lookup((LPCWSTR)bstrAgent); if (spNode != NULL) { CComObjectNoLock<CBrowserCaps> *pRet = NULL; ATLTRY(pRet = new CComObjectNoLock<CBrowserCaps>); if (!pRet) return E_OUTOFMEMORY; HRESULT hr = pRet->Initialize(spNode, this); if (FAILED(hr)) { delete pRet; return hr; } pRet->AddRef(); *ppOut = pRet; return S_OK; } return E_FAIL; } HRESULT Initialize(HINSTANCE hInstance) { HRESULT hr = _Initialize(hInstance); if (FAILED(hr)) Clear(); return hr; } HRESULT Uninitialize() { Clear(); return S_OK; } private: HRESULT _Initialize(HINSTANCE hInstance) { if (m_spDoc) // Already initialized return S_OK; HRESULT hr; hr = m_spDoc.CoCreateInstance(__uuidof(DOMDocument), NULL, CLSCTX_INPROC); if (FAILED(hr)) return hr; if (!m_spDoc) return E_FAIL; hr = m_spDoc->put_async(VARIANT_FALSE); if (FAILED(hr)) return hr; char szPath[MAX_PATH]; int nRet = GetModuleFileNameA(hInstance, szPath, MAX_PATH); if (!nRet) return AtlHresultFromLastError(); LPSTR szMark = strrchr(szPath, '\\'); ATLASSERT(szMark); if (szMark) *szMark = '\0'; CComBSTR bstrFile; bstrFile += "file://"; bstrFile += szPath ; bstrFile += "\\browscap.xml"; CComVariant varFile(bstrFile); VARIANT_BOOL varBool; hr = m_spDoc->load(varFile, &varBool); if (FAILED(hr)) return hr; if (!varBool) return E_FAIL; hr = m_spDoc->get_documentElement(&m_spRoot); if (FAILED(hr)) return hr; if (!m_spRoot) return E_FAIL; CComPtr<IXMLDOMElement> spElement; hr = m_spRoot->QueryInterface(&spElement); if (FAILED(hr)) return hr; if (!spElement) return E_FAIL; CComPtr<IXMLDOMNodeList> spList; hr = spElement->getElementsByTagName(L"browser", &spList); if (FAILED(hr)) return hr; if (!spList) return E_FAIL; CComPtr<IXMLDOMNode> spCurrent; hr = spList->nextNode(&spCurrent); if (FAILED(hr)) return hr; while (spCurrent) { CComPtr<IXMLDOMNamedNodeMap> spAttrs; CComPtr<IXMLDOMNode> spItem; DOMNodeType nodeType; hr = spCurrent->get_nodeType(&nodeType); if (FAILED(hr)) return hr; if (nodeType == NODE_ELEMENT) { hr = spCurrent->get_attributes(&spAttrs); if (FAILED(hr)) return hr; hr = spAttrs->getNamedItem((BSTR)L"user-agent", &spItem); if (FAILED(hr)) return hr; CComVariant varVal; hr = spItem->get_nodeValue(&varVal); if (FAILED(hr)) return hr; hr = varVal.ChangeType(VT_BSTR); if (FAILED(hr)) return hr; CComBSTR bstrValue = varVal.bstrVal; m_Map.Add((LPCWSTR)bstrValue, spCurrent); bstrValue.Detach(); } CComPtr<IXMLDOMNode> spNext; spList->nextNode(&spNext); spCurrent = spNext; } return S_OK; } void Clear() { if (!m_spDoc) return; m_Map.RemoveAll(); m_spRoot.Release(); m_spDoc.Release(); } CSimpleMap<LPCWSTR, CComPtr<IXMLDOMNode>, CWildCardEqualHelper< CComPtr<IXMLDOMNode> > > m_Map; CComCriticalSection m_critSec; CComPtr<IXMLDOMDocument> m_spDoc; CComPtr<IXMLDOMElement> m_spRoot; }; // Copies a CString into a null-terminated string. // pdwDestLen on input is the size of the buffer in characters (including the null) // On success, pdwDestLen contains the length of the string in characters (not including the null) // On failure, pdwDestLen contains the length of the string including the null. template <class StringType> inline BOOL CopyCString(const StringType& str, StringType::PXSTR szDest, DWORD *pdwDestLen) throw() { if (!pdwDestLen) return FALSE; DWORD dwLen = str.GetLength(); if (!szDest || *pdwDestLen < (dwLen + 1)) { *pdwDestLen = dwLen + 1; return FALSE; } StringType::PCXSTR szBuffer = str; if (szBuffer) { memcpy(szDest, szBuffer, (dwLen+1) * sizeof(StringType::XCHAR)); *pdwDestLen = dwLen; return TRUE; } return FALSE; } // Call this function to convert from a SYSTEMTIME // structure to an Http-date as defined in rfc2616 inline void SystemTimeToHttpDate(const SYSTEMTIME& st, CStringA &strTime) { static LPCSTR szDays[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static LPCSTR szMonth[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; strTime.Format("%s, %02d %s %d %02d:%02d:%02d GMT", szDays[st.wDayOfWeek], st.wDay, szMonth[st.wMonth-1], st.wYear, st.wHour, st.wMinute, st.wSecond); } // RGBToHtml - Converts a COLORREF to a color that can be used in HTML. // Eg. RGB(11,22,33) would be converted to #112233 // color: The color to convert. // pbOut: The output buffer that will hold the the resulting color. // nBuffer: Specifies the number of bytes in pbOut. bool inline RGBToHtml(COLORREF color, LPTSTR pbOut, long nBuffer) { // make sure the buffer is big enough if (nBuffer < (7 * sizeof(TCHAR))) return false; wsprintf(pbOut, _T("#%0.2x%0.2x%0.2x"), GetRValue(color), GetGValue(color), GetBValue(color)); return true; } } // namespace ATL #pragma warning( pop ) #endif // __ATLUTIL_H__
[ "112426112@qq.com" ]
112426112@qq.com
ff23dcb37a1ddf240316ff8306c627362d55b471
73a420af13199645d793b81cd5166892ca005a00
/QtChatServer/chatserver.cpp
42f972aa7f54eb5bfdb9021999a663886a66ba06
[]
no_license
Roman-Markov/simple_chat
fd93b0cc83f7d48c75a9fd894c8d6fdb00f9a2a1
97136b79fa0298c8f8f43355da55304c4a2d2312
refs/heads/master
2021-01-10T15:28:58.780438
2016-04-08T04:40:47
2016-04-08T04:40:47
55,683,605
0
0
null
null
null
null
UTF-8
C++
false
false
5,349
cpp
#include <QtNetwork> #include <QtWidgets> #include "chatserver.h" #include "client.h" #include <QString> #include <iostream> #include <set> ChatServer::ChatServer(int numport, QWidget *pwgt): QWidget(pwgt), nBlockSize(0) { ptcpServer = new QTcpServer(this); if(!ptcpServer->listen(QHostAddress::Any, numport)) { QMessageBox::critical(0, "Server erro", "Unable to begin server work: " + ptcpServer->errorString()); ptcpServer->close(); return; } connect(ptcpServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection())); ptxt = new QTextEdit; ptxt->setReadOnly(true); QVBoxLayout* pvbxLayout = new QVBoxLayout; pvbxLayout->addWidget(new QLabel("<H1>Server<H1>")); pvbxLayout->addWidget(ptxt); setLayout(pvbxLayout); } /*virtual*/ void ChatServer::slotNewConnection(){ //Получение нового соединения и инициализация соответсвующего сокета QTcpSocket* pClientSocket = ptcpServer->nextPendingConnection(); connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater())); connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient())); newclients.insert(Client("whoiam" + QString::number(rand()%1000000000), pClientSocket)); qint32 n = newclients.size(); ptxt->append(QString::number(n) + " new connections"); sendToClient("Server response: Connected!"); } void ChatServer::slotReadClient(){ QTcpSocket* pClientSocket = (QTcpSocket*) sender(); for(std::set<Client>::iterator iter = clients.begin(); iter != clients.end(); iter++){ if(iter->socket()->socketDescriptor() == pClientSocket->socketDescriptor()){ readClient(pClientSocket); return; } } // не прошел проверку, т. е. новый, принимаем от него псевдоним QDataStream in(pClientSocket); in.setVersion(QDataStream::Qt_5_5); for(;;){ if(!nBlockSize){ if(pClientSocket->bytesAvailable() < (int) sizeof(quint16)) break; in >> nBlockSize; } if(pClientSocket->bytesAvailable() < nBlockSize) break; QString str; in >> str; int j = 0; // удаляем из новых, добавляем к активным std::set<Client>::iterator iter = newclients.begin(); while( j < newclients.size()){ if(iter->socket()->socketDescriptor() == pClientSocket->socketDescriptor()){ Client temp(str, pClientSocket); clients.insert(temp); connect(temp.socket(), SIGNAL(disconnected ()), this, SLOT(slotDisconnected())); newclients.erase(iter); qint32 n = newclients.size(); ptxt->append("Осталось в логине: " + QString::number(n)); QString strmsg = QTime::currentTime().toString() + " New user - " + str; ptxt->append(strmsg); nBlockSize = 0; sendToClient(str + " joined us"); break; } j++; iter++; } } } void ChatServer::sendToClient(const QString& str){ QByteArray ar; QDataStream out(&ar, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_5_5); out << quint16(0) << QTime::currentTime() << str; out.device()->seek(0); out << quint16(ar.size() - sizeof(quint16)); for(std::set<Client>::iterator iter = clients.begin(); iter != clients.end(); iter++){ iter->socket()->write(ar); } } // чтение сообщений активных сокетов void ChatServer::readClient(QTcpSocket* pClientSocket){ QDataStream in(pClientSocket); in.setVersion(QDataStream::Qt_5_5); for(;;){ if(!nBlockSize){ if(pClientSocket->bytesAvailable() < (int) sizeof(quint16)) break; in >> nBlockSize; } if(pClientSocket->bytesAvailable() < nBlockSize) break; QTime time; QString str; in >> time >> str; QString strmsg = time.toString() + " " + "Client has sent - " + str; ptxt->append(strmsg); nBlockSize = 0; QString strname; foreach(Client client, clients){ if(client.socket()->socketDescriptor() == pClientSocket->socketDescriptor()){ strname = client.name(); break; } } QString strhtml = "<H4><FONT COLOR=RED>" + strname + ":: </FONT><FONT COLOR=BLUE>" + str + "</FONT> <H4>"; sendToClient(strhtml); } } void ChatServer::slotDisconnected() { QTcpSocket* pClientSocket = (QTcpSocket*) sender(); // Удаление испорченных сокетов foreach(Client client, clients){ if(client.socket()->socketDescriptor() == pClientSocket->socketDescriptor()){ ptxt->append(client.name() + " go out"); clients.erase(client); break; } } qint32 n = clients.size(); ptxt->append("Осталось активных: " + QString::number(n)); }
[ "r_a_markov@mail.ru" ]
r_a_markov@mail.ru