blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4c8c28e0c991b557e45d93775a7369c4b8ceb8cf | 7bd101aa6d4eaf873fb9813b78d0c7956669c6f0 | /PPTShell/PPTShell/DUI/PencelView.h | 84afd185c7282c373d9e814f26ac3dea684a446c | [] | no_license | useafter/PPTShell-1 | 3cf2dad609ac0adcdba0921aec587e7168ee91a0 | 16d9592e8fa2d219a513e9f8cfbaf7f7f3d3c296 | refs/heads/master | 2021-06-24T13:33:54.039140 | 2017-09-10T06:31:11 | 2017-09-10T06:35:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | h | #pragma once
#include "InstrumentView.h"
class CPencelViewUI:
public CInstrumentView,
public INotifyUI
{
public:
CPencelViewUI(void);
virtual ~CPencelViewUI(void);
UIBEGIN_MSG_MAP
EVENT_ID_HANDLER(DUI_MSGTYPE_CLICK, _T("color_item"), OnColorItemClick);
UIEND_MSG_MAP
public:
virtual void Init();
protected:
void CreateColors();
void OnColorItemClick( TNotifyUI& msg );
int GetCurSel();
void SetCurSel(int nSel);
public:
virtual void OnSelected();
virtual void OnUnSelected();
virtual void OnPageChangeBefore();
virtual void OnPageScanneded();
private:
CListUI* m_pList;
CDialogBuilder m_ColorBuilder;
HWND m_hScreenWnd;
bool OnBlackboardColorRequest( void* pObj );
};
| [
"794549193@qq.com"
] | 794549193@qq.com |
e585e5d4e332f9c2b79ad5ffedbcc746d1c05eaa | ff1f8e352bcbf059e2c1c0aaafff120c56f3cf49 | /Zhengrui/Zhengrui2193.cpp | d1a1ecf8f411a537b1066b3726c0191324b41c04 | [] | no_license | keywet06/code | 040bc189fbabd06fc3026525ae3553cd4f395bf3 | fe0d570144e580f37281b13fd4106438d3169ab9 | refs/heads/master | 2022-12-19T12:12:16.635994 | 2022-11-27T11:39:29 | 2022-11-27T11:39:29 | 182,518,309 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,258 | cpp | #include <bits/stdc++.h>
#define Deb std::cerr
#define Delin Deb << "[Debug] at Line " << __LINE__
#define Debug Delin << " : "
#define Deline Delin << std::endl;
using int64 = long long;
template <typename Type>
class Fenwick {
protected:
std::vector<Type> a;
public:
Fenwick() {}
Fenwick(size_t n) : a(n + 1) {}
void Resize(size_t n) { a = std::vector<Type>(n + 1); }
void Add(size_t i, Type v) {
while (i < a.size()) a[i] += v, i += i & -i;
}
Type Sum(size_t i) {
Type Ret(0);
while (i) Ret += a[i], i &= i - 1;
return Ret;
}
};
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr), std::cout.tie(nullptr);
int n, L, R;
std::cin >> n >> L >> R;
std::vector<int> a(n), DD(n + 3);
DD[1] = n, DD[2] = -2 * n, DD[3] = n;
Fenwick<int> Fen(n);
for (int i = 0, x; i < n; ++i) {
std::cin >> x;
int c = i - Fen.Sum(x), d = n - x - c;
++DD[2], --DD[c + 2], ++DD[2], --DD[d + 2], Fen.Add(x, 1);
}
DD[3] -= n;
for (int i = 3; i <= n + 2; ++i) ++DD[i];
int64 D = 0, S = 0, Ans = 0;
for (int i = 1; i <= R; ++i) S += D += DD[i], Ans ^= i >= L ? S : 0;
std::cout << Ans << std::endl;
return 0;
} | [
"keywet06@tom.com"
] | keywet06@tom.com |
ee06cb2b9e5ac829d491eddfc159774c8b16866f | 5ebb2fea57c526137bd9b4ef2ac32d2853f3137f | /SwordToOffer/29_TwoSum/main.cpp | c12e24b2144bc18cdeaaa946bc57db308890cf4c | [] | no_license | zshellzhang1993-2025/algorithms | 918024b65c4de83bc100e4cfd45c7788ae2c8999 | c90142d33916840efa872c0390bb1d730b9a21cc | refs/heads/master | 2021-05-30T21:13:44.031788 | 2016-01-03T11:01:25 | 2016-01-03T11:01:25 | 28,854,364 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 926 | cpp | #include <iostream>
#include <vector>
using namespace std;
class Solution_29 {
public:
vector<int> FindNumbersWithSum ( vector<int> array, int sum ) {
vector<int> result;
if ( array.empty() )
return result;
int begin = 0;
int end = array.size() - 1;
while ( begin < end ) {
if ( array[begin] + array[end] == sum ) {
result.push_back ( array[begin] );
result.push_back ( array[end] );
return result;
} else if ( array[begin] + array[end] > sum )
end--;
else
begin++;
}
return result;
}
};
int main() {
int data[9] = {1, 2, 3, 5, 9, 12, 14, 20, 21};
vector<int> array ( data, data + 9 );
Solution_29 s;
vector<int> result = s.FindNumbersWithSum ( array, 4 );
cout << result[0] << " " << result[1];
return 0;
}
| [
"1557983850@qq.com"
] | 1557983850@qq.com |
8d650b4b31c3e6a0351a477d64a981f4cf099d54 | 780836c70e0a2649ba8b214f8c7f2e8ef034b9a0 | /File_Factory/File_Factory/CsvFile.h | dc49d638975d1739415399eef0dd1493a9354d79 | [
"Apache-2.0"
] | permissive | kboba/s3_File_Factory | cc3c06bf732599a477f2b43ae51b6060276c14e8 | 5640235c963beb96d9f5f9ca577106fa9bd05edc | refs/heads/master | 2022-10-22T20:17:27.695776 | 2020-06-16T22:23:55 | 2020-06-16T22:23:55 | 271,790,925 | 0 | 0 | Apache-2.0 | 2020-06-16T10:10:07 | 2020-06-12T12:17:49 | null | UTF-8 | C++ | false | false | 386 | h | #pragma once
#include "iFile.h"
class CsvFile : public iFile
{
void writeLine(const Point& p);
std::vector<std::string> split(std::string std, char delim);
public:
CsvFile(std::string path, std::string mode);
~CsvFile();
FileError write(const std::vector<Point>& points);
FileError read(std::vector<Point>& points);
FileError read(Point& p, int idx);
};
| [
"boba.krzysztof98@gmail.com"
] | boba.krzysztof98@gmail.com |
f68a755d42ebebdb7050fae12f734fc7da7b5a05 | ec4897cce9465140a04fb9947c844ed06178ea53 | /entrywriter.cpp | 57daaa5b258ef9a084f948655ba9cd8ad0e37d3a | [] | no_license | vlitomsk/evlog3 | 998c1c9bafaa1f92474b7bd11b3108f812c8a249 | 5c4d98c1ac8ea7b81cb2cc7a71fdab9a8da09f9c | refs/heads/master | 2020-06-30T23:44:57.350015 | 2016-12-14T02:51:51 | 2016-12-14T02:51:51 | 74,561,989 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 371 | cpp | #include "entrywriter.hpp"
EntryWriter::EntryWriter(std::ostream &os)
: os(os)
, first(true)
{}
EntryWriter::~EntryWriter() {
os << "\n]\n";
}
void EntryWriter::operator <<(const Entry &ent) {
if (first) {
os << "[\n";
first = false;
} else {
os << ",\n";
}
os << ent.getStr();
}
void EntryWriter::endOfSequence() {
}
| [
"kvas.omsk@gmail.com"
] | kvas.omsk@gmail.com |
a7db9b26ecd045926a29624c8c1852cb85bd3f23 | 950b506e3f8fd978f076a5b9a3a950f6f4d5607b | /cf/vkcup-2018/qual-1/C.cpp | d636a75893510e816f94adc054bdce9847c6961d | [] | no_license | Mityai/contests | 2e130ebb8d4280b82e7e017037fc983063228931 | 5b406b2a94cc487b0c71cb10386d1b89afd1e143 | refs/heads/master | 2021-01-09T06:09:17.441079 | 2019-01-19T12:47:20 | 2019-01-19T12:47:20 | 80,909,953 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,637 | cpp | #include <bits/stdc++.h>
#define proj asdajslkdjalskd
using namespace std;
using proj = pair<string, int>;
int main() {
#if __APPLE__
freopen("C.in", "r", stdin);
freopen("C.out", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
size_t n;
while (cin >> n) {
map<proj, vector<proj>> g;
proj polycarp;
for (size_t i = 0; i < n; ++i) {
proj current;
cin >> current.first >> current.second;
if (i == 0) polycarp = current;
size_t deps;
cin >> deps;
auto& cur_g = g[current];
cur_g.resize(deps);
for (size_t j = 0; j < deps; ++j) {
cin >> cur_g[j].first >> cur_g[j].second;
}
}
set<proj> alldeps;
set<string> used = {polycarp.first};
map<string, int> cur_lvl = {polycarp};
while (!cur_lvl.empty()) {
map<string, int> next_lvl;
for (const auto& cur_proj : cur_lvl) {
for (const auto& [name, version] : g[cur_proj]) {
if (used.find(name) == used.end()) {
next_lvl[name] = max(next_lvl[name], version);
}
}
}
alldeps.insert(next_lvl.begin(), next_lvl.end());
for (const auto& [name, version] : next_lvl) {
used.insert(name);
}
cur_lvl.swap(next_lvl);
}
cout << alldeps.size() << '\n';
for (const auto& [name, version] : alldeps) {
cout << name << ' ' << version << '\n';
}
}
}
| [
"dimaz1301@gmail.com"
] | dimaz1301@gmail.com |
9f57f926a6a6d6937fa899fe2b25a17460e68f17 | b3a042d294a90a1632d38a498a144129a22e7ade | /autograder/ioutils.cpp | d5f66bb8208cabaf57fce7ab72dcfbe22248f6e9 | [] | no_license | swordcyber/stanford-cpp-library | 4f0dd17397dc086add30b28e5a225d920a8f2e8d | cf5de556c65fff91a18aca4c8bb031dc280d4224 | refs/heads/master | 2020-03-30T02:57:14.809006 | 2018-09-26T01:28:40 | 2018-09-26T01:28:40 | 150,660,069 | 1 | 0 | null | 2018-09-27T23:42:13 | 2018-09-27T23:42:12 | null | UTF-8 | C++ | false | false | 3,811 | cpp | /*
* File: ioutils.cpp
* ---------------
* This file contains implementations of functions to help capture, redirect,
* and feed input to cin/cout/err.
* See ioutils.h for documentation of each function.
*
* @author Marty Stepp
* @version 2016/10/28
* - bug fix for output limit static var
* @version 2016/10/22
* - removed all static variables (replaced with STATIC_VARIABLE macros)
* @version 2014/10/14
* @since 2014/03/01
*/
#include "ioutils.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include "consoletext.h"
#include "error.h"
#include "private/echoinputstreambuf.h"
#include "private/limitoutputstreambuf.h"
#include "private/static.h"
namespace ioutils {
STATIC_VARIABLE_DECLARE_BLANK(std::stringstream, bufferOut)
STATIC_VARIABLE_DECLARE(std::streambuf*, oldOut, nullptr)
STATIC_VARIABLE_DECLARE_BLANK(std::stringstream, bufferErr)
STATIC_VARIABLE_DECLARE(std::streambuf*, oldErr, nullptr)
STATIC_VARIABLE_DECLARE_BLANK(std::stringstream, bufferIn)
STATIC_VARIABLE_DECLARE(std::streambuf*, oldIn, nullptr)
STATIC_VARIABLE_DECLARE(bool, consoleEchoUserInput, false)
STATIC_VARIABLE_DECLARE(int, consoleOutputLimit, 0)
void captureStderrBegin() {
STATIC_VARIABLE(bufferErr).str(std::string());
std::streambuf* newBuf;
int limit = getConsoleOutputLimit();
if (limit > 0) {
newBuf = new stanfordcpplib::LimitOutputStreambuf(STATIC_VARIABLE(bufferErr).rdbuf(), limit);
} else {
newBuf = STATIC_VARIABLE(bufferErr).rdbuf();
}
STATIC_VARIABLE(oldErr) = std::cerr.rdbuf(newBuf);
}
std::string captureStderrEnd() {
if (STATIC_VARIABLE(oldErr)) {
std::cerr.rdbuf(STATIC_VARIABLE(oldErr));
STATIC_VARIABLE(oldErr) = nullptr;
}
return STATIC_VARIABLE(bufferErr).str();
}
void captureStdoutBegin(bool alsoStderr) {
STATIC_VARIABLE(bufferOut).str(std::string());
std::streambuf* newBuf;
int limit = getConsoleOutputLimit();
if (limit > 0) {
newBuf = new stanfordcpplib::LimitOutputStreambuf(STATIC_VARIABLE(bufferOut).rdbuf(), limit);
} else {
newBuf = STATIC_VARIABLE(bufferOut).rdbuf();
}
STATIC_VARIABLE(oldOut) = std::cout.rdbuf(newBuf);
if (alsoStderr) {
STATIC_VARIABLE(bufferErr).str(std::string());
STATIC_VARIABLE(oldErr) = std::cerr.rdbuf(newBuf);
}
}
std::string captureStdoutEnd() {
if (STATIC_VARIABLE(oldOut)) {
std::cout.rdbuf(STATIC_VARIABLE(oldOut));
STATIC_VARIABLE(oldOut) = nullptr;
}
if (STATIC_VARIABLE(oldErr)) {
std::cerr.rdbuf(STATIC_VARIABLE(oldErr));
STATIC_VARIABLE(oldErr) = nullptr;
}
return STATIC_VARIABLE(bufferOut).str();
}
bool getConsoleEchoUserInput() {
return STATIC_VARIABLE(consoleEchoUserInput);
}
int getConsoleOutputLimit() {
return STATIC_VARIABLE(consoleOutputLimit);
}
void redirectStdinBegin(std::string userInput) {
STATIC_VARIABLE(bufferIn).str(std::string());
std::streambuf* newBuf;
if (getConsoleEchoUserInput()) {
newBuf = new stanfordcpplib::EchoInputStreambuf(STATIC_VARIABLE(bufferIn).rdbuf());
} else {
newBuf = STATIC_VARIABLE(bufferIn).rdbuf();
}
STATIC_VARIABLE(oldIn) = std::cin.rdbuf(newBuf);
redirectStdinFeedInput(userInput);
}
void redirectStdinFeedInput(std::string userInput) {
if (!userInput.empty()) {
STATIC_VARIABLE(bufferIn) << userInput << std::endl;
}
}
void redirectStdinEnd() {
if (STATIC_VARIABLE(oldIn)) {
std::cin.rdbuf(STATIC_VARIABLE(oldIn));
STATIC_VARIABLE(oldIn) = nullptr;
}
}
void setConsoleEchoUserInput(bool echo) {
STATIC_VARIABLE(consoleEchoUserInput) = echo;
}
void setConsoleOutputLimit(int limit) {
STATIC_VARIABLE(consoleOutputLimit) = limit;
}
} // namespace ioutils
| [
"stepp@cs.stanford.edu"
] | stepp@cs.stanford.edu |
82326aa9d3d6a6373bad30b6e67a64f9e45c1eec | 9c5ea7c1df4192291e3bec709d2526dfebdf59ae | /_Includes/precomp.h | 5a4474c712e16092e9c3e2a2d96a0348f29a1cfc | [] | no_license | Walter-Haynes/SMB_Unchained | c402741aa8ecde77d7afc7ec9b75626e0aaa7765 | 3e3f32420d4d7cb25d64d421a843b0d9226a15ba | refs/heads/develop | 2023-01-06T17:28:07.449521 | 2020-11-06T07:36:27 | 2020-11-06T07:36:27 | 308,101,067 | 0 | 0 | null | 2020-11-06T07:20:07 | 2020-10-28T18:04:53 | C | UTF-8 | C++ | false | false | 662 | h | // add your external includes to this file instead of to individual .cpp files
#include <GameSettings.h>
//#define SCRWIDTH Game::SCREEN_HEIGHT_PIXELS;
//#define SCRHEIGHT Game::SCREEN_WIDTH_PIXELS;
constexpr int SCRWIDTH = Game::SCREEN_WIDTH_PIXELS;
constexpr int SCRHEIGHT = Game::SCREEN_HEIGHT_PIXELS;
// #define FULLSCREEN
#define ADVANCEDGL // faster if your system supports it
#include <cinttypes>
#include <cmath>
#include <cstdlib>
#include <cassert>
#include <fstream>
#include <cstdio>
extern "C"
{
#include "glew.h"
}
#include "gl.h"
#include "wglext.h"
#include "SDL.h"
#include "FreeImage.h"
#include "template.h"
#include "surface.h" | [
"walter-haynes@outlook.com"
] | walter-haynes@outlook.com |
7a4dee754b5bb4610c04e0403511ef622681d754 | be07e3597fef471738fd5204b4690320acc07f74 | /src-generated/wxNode_wxPanel.h | 54964d96ecdb686fc661a7979598f2f34f67c247 | [] | no_license | happyhub/wxNode | 7a88e02187ddcbbe88abf111f638e49f87f7b49a | 4c4846656baaba0c9dea275a119d002e7e0f96de | refs/heads/master | 2020-04-09T00:30:08.392946 | 2012-02-09T05:25:31 | 2012-02-09T05:25:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,853 | h |
#ifndef _wxNode_wxPanel_h_
#define _wxNode_wxPanel_h_
#include "wxnode.h"
#include "wxNode_wxEvtHandler.h"
class wxNode_wxEvtHandler;
class wxNode_wxNavigationEnabled;
class wxNode_wxWindow;
class wxNode_wxPoint;
class wxNode_wxSize;
class wxNode_wxPanel : public wxPanel, public wxNodeObject, public NodeExEvtHandlerImpl {
public:
static void Init(v8::Handle<v8::Object> target);
static void AddMethods(v8::Handle<v8::FunctionTemplate> target);
virtual v8::Handle<v8::Object> self() { return m_self; }
static bool AssignableFrom(const v8::Handle<v8::String>& className);
static bool AssignableFrom(const char* className);
static v8::Handle<v8::Value> New(const wxPanel* obj);
static v8::Handle<v8::Value> New(const wxNode_wxPanel* obj);
static v8::Handle<v8::Value> NewCopy(const wxPanel& obj);
wxNode_wxPanel();
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos, wxSize& size, long int style, const wxString& name);
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos, wxSize& size, long int style);
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos, wxSize& size);
wxNode_wxPanel(wxWindow* parent, int winid, wxPoint& pos);
wxNode_wxPanel(wxWindow* parent, int winid);
wxNode_wxPanel(wxWindow* parent);
wxNode_wxPanel(wxWindow* parent, int x, int y, int width, int height, long int style, const wxString& name);
wxNode_wxPanel(wxWindow* parent, int x, int y, int width, int height, long int style);
wxNode_wxPanel(wxWindow* parent, int x, int y, int width, int height);
private:
static v8::Handle<v8::Value> _init(const v8::Arguments& args);
static v8::Handle<v8::Value> _Create(const v8::Arguments& args);
static v8::Handle<v8::Value> _InitDialog(const v8::Arguments& args);
static v8::Persistent<v8::FunctionTemplate> s_ct;
};
#endif
| [
"joe@fernsroth.com"
] | joe@fernsroth.com |
bb423b99f66827cd8017a6a5e2a262fbc160a83c | 03ffeb8290b24d81e8a0beba53a708fb604bc10d | /code/nepal/cc/src/struct.h | 59addc644227c4617defa804439d5b0ee2de6198 | [] | no_license | skn123/Nepal | ab027a1708884c557521ccd111a79c62a75b9ab6 | d1359862484fbd84625e56c7f9e9486e3499dad7 | refs/heads/master | 2021-09-06T11:33:42.966859 | 2018-02-06T03:56:14 | 2018-02-06T03:56:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 168 | h | #ifndef _STRUCT_H_
#define _STRUCT_H_
struct inputdata
{
std::string name;
std::string seq;
std::vector<std::vector<float>> pssm;
std::string alseq="";
};
#endif
| [
"yamada@sb.ecei.tohoku.ac.jp"
] | yamada@sb.ecei.tohoku.ac.jp |
1c922ddafad12901d428b5b4e98122f1033d1441 | bc7c30f48c5322cde4d810ff5fb0912ed49150df | /Assignments/PhysicsAssignment2/PhysicsAssignment2/Vec3.h | 900f950975c093b0d90458a571f7a8ffadcc5850 | [] | no_license | DustinBrown917/GamePhysics1 | ca7c1df9c10dda277266e8af22b2a67c7bab8a2f | 936106db5df38a636c9fa0688554943cbfc6ac45 | refs/heads/master | 2020-04-01T15:07:20.942644 | 2018-11-14T00:04:37 | 2018-11-14T00:04:37 | 153,322,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,748 | h |
#include <string> // Just for the ToString() method.
using namespace std;
//Guard statement - Prevents Vec3.h from being compiled more than once.
#ifndef VEC3_H
#define VEC3_H
//Vec3 Class Header
struct Vec3 {
//Member variables
float x, y, z;
//Constructors
//Create a Vec3 with all member properties initialized to 0.
Vec3();
//Create a Vec3 with all member properties initialized to val.
Vec3(float val);
//Create a Vec3 and initialize all member properties explicitly.
Vec3(float x, float y, float z);
//Destruct the Vec3
~Vec3();
//Operator overloads
// I inlined the operator overloads because they would generate more overhead if they were called as normal in the cpp.
// They are short and common enough that inlining the operators generates a justifiable improvement in efficiency.
//TS
//Assignment operator. Return a reference to value at this.
inline Vec3& operator = (const Vec3& vec) {
x = vec.x;
y = vec.y;
z = vec.z;
return *this;
}
//Add two different vectors.
inline const Vec3 operator + (const Vec3& vec) const {
return Vec3(x + vec.x, y + vec.y, z + vec.z);
}
//Subtract two different vectors.
inline const Vec3 operator - (const Vec3& vec) const {
return Vec3(x - vec.x, y - vec.y, z - vec.z);
}
//Multiply vector by scalar
inline const Vec3 operator * (const float f) const {
return Vec3(x * f, y * f, z * f);
}
//Divide vector by scalar
//Beware of dividing by extremely small numbers. Will update to handle such cases as the class develops.
inline const Vec3 operator /(const float f) const {
return Vec3(x / f, y / f, z / f);
}
//Add another vector to this and return a reference to itself.
inline Vec3& operator += (const Vec3& vec) {
x += vec.x;
y += vec.y;
z += vec.z;
return *this;
}
//Subtract another vector from this one and return a reference to itself.
inline Vec3& operator -= (const Vec3& vec) {
x -= vec.x;
y -= vec.y;
z -= vec.z;
return *this;
}
//Multiply this vector by float f and return a reference to itself.
inline Vec3& operator *= (float f) {
x *= f;
y *= f;
z *= f;
return *this;
}
//Divide this vector by float f and return a reference to itself.
inline Vec3& operator /= (float f) {
x /= f;
y /= f;
z /= f;
return *this;
}
//Member methods
//Get the magnitude of this Vec3.
float Mag() const;
//Scale the vector so its magnitude is 1.
void Normalize();
//Return the Dot product of this Vec3 given another.
float Dot(const Vec3& other) const;
//Scale a vector between itself and another Vec3 by factor t.
void Lerp(const Vec3& other, float t);
//Rotate a vector around its z axis.
void RotateZ(float angle);
//Get the Vec3 as a string.
string ToString();
};
#endif //!VEC3_H
| [
"43157195+DustinBrown917@users.noreply.github.com"
] | 43157195+DustinBrown917@users.noreply.github.com |
078899c9184b7b6016e2bdb8d7a8bc176df51be2 | f5f451c3e1c420789107addacb0da3107685bc4f | /TCMPhysicEngine/stdafx.cpp | ead1df20d5a5f9d319ed91cd4c255d21718e4c34 | [] | no_license | cl4nk/TayCaMead-Engine | 4db6089fd7d952f1aecee82378db0c3bad407c99 | 4e6a9281fbaf9b7708db95a95078e97b5aeb2772 | refs/heads/master | 2021-01-01T19:21:17.655499 | 2019-06-11T09:11:39 | 2019-06-11T09:11:39 | 98,566,424 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 294 | cpp | // stdafx.cpp : source file that includes just the standard includes
// TCMPhysicEngine.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"n.fontes@student.isartdigital.com"
] | n.fontes@student.isartdigital.com |
7b48930687cccc3afc730d43865eee5b4805aa6b | 7af9c24bb6cea6e77c74990fbdf061bd03c0e779 | /src/acpp/Stack_set.h | cb4f7f914d24c53bd09d498f77d2217fdddb32fa | [] | no_license | dtbinh/sedgewick_cpp | abfca17d774f03cfde912fe5404770fad68a8628 | b488e5df2ad9c855aaaed66397c457dba55a4463 | refs/heads/master | 2023-03-16T09:11:31.240153 | 2017-08-23T23:39:20 | 2017-08-23T23:39:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,005 | h | // Program 4.16 - Stack with index items and no duplicates
#ifndef STACK_SET_H
#define STACK_SET_H
#include <cstddef>
#include <vector>
#include <deque>
template<typename Item_t> // Item_t must be an integer type
class Stack_set {
public:
Stack_set(std::size_t size)
: _stack(size),
_size{0},
_on_stack(size, false) {}
inline bool empty() const noexcept { return _size == 0; }
void push(Item_t& item)
{
if (_on_stack[item]) { return; }
_stack[_size++] = item;
_on_stack[item] = true;
}
void push(Item_t&& item)
{
if (_on_stack[item]) { return; }
_stack[_size++] = item;
_on_stack[item] = true;
}
Item_t pop()
{
_on_stack[_stack[--_size]] = false;
return _stack[_size];
}
private:
std::vector<Item_t> _stack;
std::deque<bool> _on_stack; // used to test whether the item is already on the stack
std::size_t _size;
};
#endif // STACK_SET_H
| [
"timothyshull@gmail.com"
] | timothyshull@gmail.com |
19ba21ea42085a4c0cd5df1c04eef3928f90725f | de80b91a12b10bd962b59a89b2badbb83a0193da | /ClientProject/Mof/MofLibrary/Include/Graphics/PMD/ConvertPMD.h | 221e955307109d5791c1d5fc9cfca436fc5ca3b0 | [
"MIT"
] | permissive | OIC-Shinchaemin/RatchetNclank-PrivateCopy | 8845eea799b3346646c8c93435c0149e842dede8 | e2e646e89ef3c29d474a503f5ca80405c4c676c9 | refs/heads/main | 2023-08-15T06:36:05.244293 | 2021-10-08T00:34:48 | 2021-10-08T00:34:48 | 350,923,064 | 0 | 0 | MIT | 2021-10-06T11:05:03 | 2021-03-24T02:35:36 | C++ | SHIFT_JIS | C++ | false | false | 17,532 | h | /*****************************************************************************
[ファイル名] ConvertPMD.h
[処理概要] PMDメッシュ変換クラス
Author 濱田 享
Since 2009.04.01
*****************************************************************************/
//ONCE
#ifndef __CONVERTPMDMESH__H__
#define __CONVERTPMDMESH__H__
//INCLUDE
#include "ConvertVMD.h"
namespace Mof {
//TYPEDEF STRUCT
/*******************************//*!
@brief PMDファイルヘッダー構造体
PMDファイルヘッダー構造体。
@author CDW
*//********************************/
typedef struct tag_PMDHEADER {
char Magic[3]; //!<pmd
MofFloat Version; //!<バージョン
char Name[21]; //!<名前
char Comment[257]; //!<コメント
char EName[21]; //!<名前(英語)
char EComment[257]; //!<コメント(コメント)
MofU32 ExpressionCount; //!<表情数
MofU32 BoneFrameCount; //!<ボーン枠数
}PMDHEADER,*LPPMDHEADER;
/*******************************//*!
@brief PMDファイル頂点構造体
PMDファイル頂点構造体。
@author CDW
*//********************************/
typedef MOF_ALIGNED16_STRUCT tag_PMDVERTEX {
Vector3 Pos; //!<座標
Vector3 Normal; //!<法線
Vector2 UV; //!<UV
Vector4 Color[4]; //!<色
MofU8 BlendIndicesCount; //!<ブレンドボーン数
MofU8 BlendIndices[2]; //!<ブレンドインデックス
MofFloat BlendWait[2]; //!<ブレンドウェイト
MofU32 Index; //!<元番号
MOF_ALIGNED_NEW_OPERATOR(tag_PMDVERTEX);
}PMDVERTEX, *LPPMDVERTEX;
//リスト置き換え
typedef CDynamicArray< PMDVERTEX > PMDVERTEXLIST, *LPPMDVERTEXLIST;
/*******************************//*!
@brief PMDファイル頂点リスト構造体
PMDファイル頂点リスト構造体。
@author CDW
*//********************************/
typedef struct tag_PMDMESHVERTEX {
PMDVERTEXLIST VertexList; //!<頂点リスト
MofU32 Flag; //!<頂点フラグ
/*************************************************************************//*!
@brief コンストラクタ
@param None
@return None
*//**************************************************************************/
tag_PMDMESHVERTEX() :
VertexList(),
Flag(0) {
}
tag_PMDMESHVERTEX(const tag_PMDMESHVERTEX& Obj) :
VertexList(Obj.VertexList),
Flag(Obj.Flag) {
}
/*************************************************************************//*!
@brief デストラクタ
@param None
@return None
*//**************************************************************************/
virtual ~tag_PMDMESHVERTEX(){
VertexList.Release();
}
}PMDMESHVERTEX, *LPPMDMESHVERTEX;
/*******************************//*!
@brief Xファイルのマテリアルレンダリングオフセット情報構造体
Xファイルマテリアルレンダリングオフセット情報を読み込むための構造体。
@author CDW
*//********************************/
typedef struct tag_PMDMATERIALOFFSET {
char Name[256]; //!<名前
MofU32 Offset; //!<オフセット
MofU32 RenderFace; //!<描画フェイス
LPPMDVERTEX pRenderVertex; //!<描画頂点
MofU32 RenderVertexCount; //!<描画頂点数
LPMofU32 pRenderIndex; //!<描画インデックス
MofU32 RenderIndexCount; //!<描画インデックス数
/*************************************************************************//*!
@brief コンストラクタ
@param None
@return None
*//**************************************************************************/
tag_PMDMATERIALOFFSET() :
Offset(0) ,
RenderFace(0) ,
pRenderVertex(NULL) ,
RenderVertexCount(0) ,
pRenderIndex(NULL) ,
RenderIndexCount(0) {
memset(Name, 0, sizeof(Name));
}
/*************************************************************************//*!
@brief デストラクタ
@param None
@return None
*//**************************************************************************/
~tag_PMDMATERIALOFFSET(){
MOF_SAFE_FREE(pRenderVertex, "pRenderVertex");
MOF_SAFE_FREE(pRenderIndex, "pRenderIndex");
}
}PMDMATERIALOFFSET,*LPPMDMATERIALOFFSET;
typedef CDynamicArray< LPPMDMATERIALOFFSET > PMDMATERIALOFFSETLIST, *LPPMDMATERIALOFFSETLIST;
/*******************************//*!
@brief PMDファイルボーン構造体
PMDファイルボーン構造体。
@author CDW
*//********************************/
typedef struct tag_PMDBONE {
char Name[24];
Matrix44 GrobalTransform;
Matrix44 LocalTransform;
Matrix44 Offset;
MofS32 BNo;
MofS32 PNo;
MofU16 TNo;
MofU8 Type;
MofU16 IKNo;
}PMDBONE, *LPPMDBONE;
//リスト置き換え
typedef CDynamicArray< PMDBONE > PMDBONELIST, *LPPMDBONELIST;
/*******************************//*!
@brief PMDファイル剛体構造体
PMDファイル剛体構造体。
@author CDW
*//********************************/
typedef MOF_ALIGNED16_STRUCT tag_PMDRIGID {
char Name[24];
Vector3 Size;
Vector3 Pos;
Vector3 Angle;
MofU32 BNo;
MofU32 GNo;
MofU32 GTNo;
MofU32 Type;
MofU32 PType;
MofFloat Mass;
MofFloat LinearDamping;
MofFloat AngularDamping;
MofFloat Restitution;
MofFloat Friction;
MOF_ALIGNED_NEW_OPERATOR(tag_PMDRIGID);
}PMDRIGID, *LPPMDRIGID;
//リスト置き換え
typedef CDynamicArray< PMDRIGID > PMDRIGIDLIST, *LPPMDRIGIDLIST;
/*******************************//*!
@brief PMDファイルモーフィング構造体
PMDファイルモーフィング構造体。
@author CDW
*//********************************/
typedef struct tag_PMDMORPHING {
char Name[24];
MofU32 Count;
MofU32 Type;
CU32Array Index;
CDynamicArray< Vector3 > Vertex;
}PMDMORPHING, *LPPMDMORPHING;
//リスト置き換え
typedef CDynamicArray< LPPMDMORPHING > PMDMORPHINGLIST, *LPPMDMORPHINGLIST;
/*******************************//*!
@brief PMDファイル剛体形状
PMDファイル剛体形状。
@author CDW
*//********************************/
enum tag_PMDRIGIDBODYSHAPE {
PMDRIGIDBODYSHAPE_SPHERE, //!<球
PMDRIGIDBODYSHAPE_BOX, //!<箱
PMDRIGIDBODYSHAPE_CAPSULE, //!<カプセル
};
/*******************************//*!
@brief PMDファイル剛体形状
PMDファイル剛体形状。
@author CDW
*//********************************/
enum tag_PMDRIGIDBODYRELATION {
PMDRIGIDBODYRELATIONTYPE_RELATION, //!<参照優先
PMDRIGIDBODYRELATIONTYPE_RIGID, //!<物理演算
PMDRIGIDBODYRELATIONTYPE_RELATIONPOSITION, //!<参照優先(座標のみ)
};
//CLASS
/*******************************//*!
@brief PMDファイル変換
PMDファイル変換。
@author CDW
*//********************************/
class MOFLIBRARY_API CConvertPMD : public CWriteChunkFile {
private:
/*******************//*!
ファイルヘッダー
*//********************/
LPPMDHEADER m_pHeader;
/*******************//*!
読み込みファイル
*//********************/
LPReadBinaryFile m_pFile;
/*******************//*!
読み込みファイル
*//********************/
LPReadTextFile m_pMaterialFile;
/*******************//*!
モーフィング
*//********************/
PMDMORPHINGLIST m_Morphing;
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool Convert(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pVertex 頂点
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertVertex(LPPMDMESHVERTEX pVertex);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pIndex インデックス
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertFace(LPU32Array pIndex);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pVertex 頂点
@param[in] pIndex インデックス
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertMaterial(LPPMDMESHVERTEX pVertex, LPU32Array pIndex, LPPMDMATERIALOFFSETLIST pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pVertex 頂点
@param[in] Flag フラグ
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertGeometryVertex(LPPMDVERTEX pVertex, MofU32 Flag);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pMorphing モーフィング
@param[in] pVertex 頂点
@param[in] pIndex インデックス
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertMorphing(LPPMDMORPHING pMorphing, LPPMDMESHVERTEX pVertex, LPU32Array pIndex, LPPMDMATERIALOFFSET pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertBone(LPPMDBONELIST pBone, LPPMDMATERIALOFFSETLIST pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@param[in] pMO マテリアルオフセット
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertWeight(LPPMDBONE pBone, LPPMDMATERIALOFFSETLIST pMO);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertIK(LPPMDBONELIST pBone);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertExpression(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertExpressionViewList(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertBoneFrameList(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertBoneViewList(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertEnglishName(LPPMDBONELIST pBone);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param None
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertToonTexture(void);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pBone ボーン
@param[in] pRigid 剛体
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertRigidBody(LPPMDBONELIST pBone, LPPMDRIGIDLIST pRigid);
/*************************************************************************//*!
@brief メッシュファイルを変換する
@param[in] pRigid 剛体
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool ConvertJoint(LPPMDRIGIDLIST pRigid);
/*************************************************************************//*!
@brief ヘッダー読み込み
@param[in] pData 読み込みヘッダ−
@return TRUE 正常終了<br>
それ以外 解放エラー、エラーコードを返す。
*//**************************************************************************/
MofBool ReadHeader(LPPMDHEADER pData);
/*************************************************************************//*!
@brief モーフィング読み込み
@param None
@return TRUE 正常終了<br>
それ以外 解放エラー、エラーコードを返す。
*//**************************************************************************/
MofBool ReadMorphing(void);
public:
/*************************************************************************//*!
@brief コンストラクタ
@param None
@return None
*//**************************************************************************/
CConvertPMD();
/*************************************************************************//*!
@brief デストラクタ
@param None
@return None
*//**************************************************************************/
virtual ~CConvertPMD();
/*************************************************************************//*!
@brief ファイルを開いて解析を行い、独自形式で出力を行う
@param[in] pInName 入力ファイル名
@param[in] pOutName 出力ファイル名
@return TRUE 成功<br>
それ以外 失敗、エラーコードが戻り値となる
*//**************************************************************************/
MofBool Convert(LPCMofChar pInName,LPCMofChar pOutName);
/*************************************************************************//*!
@brief 解放
@param[in] pData 解放追加データ
@return TRUE 正常終了<br>
それ以外 解放エラー、エラーコードを返す。
*//**************************************************************************/
virtual MofBool Release(LPMofVoid pData = NULL);
//クラス基本定義
MOF_LIBRARYCLASS_NOTCOPY(CConvertPMD, MOF_CONVERTPMDCLASS_ID);
};
//INLINE INCLUDE
#include "ConvertPMD.inl"
}
#endif //__CONVERTPMDMESH__H__
//[EOF] | [
"shin@oic.jp"
] | shin@oic.jp |
41e7838aed24679ed4016b9f41791e515a2a5fc1 | f9c465192c40433fc67057471e9173dae3d4a8ca | /05_03/sortarray012.cpp | 5850094b6961106b48b5191e4f8373312121accb | [] | no_license | mlkorra/Prep | f77ebd4867008aaa457a7819e89ea1a2bfc95152 | fe2c4542c864bffae111923101048fb77b962bc9 | refs/heads/master | 2021-03-24T11:57:49.152570 | 2018-07-30T08:58:31 | 2018-07-30T08:58:31 | 107,019,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 413 | cpp | #include <bits/stdc++.h>
using namespace std;
void swap(int *a,int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int t;cin>>t;
while(t--){
int i,j,n;cin>>n;
int v[n];
for(i=0;i<n;i++){
cin>>v[i];
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(v[i]<=v[j]){
swap(&v[i],&v[j]);
}
}
}
for(i=0;i<n;i++){
printf("%d ",v[i]);
}
cout << "\n";
}
return 0;
} | [
"korrarahuldev@gmail.com"
] | korrarahuldev@gmail.com |
9e11e113d06c127b82bbc5ddb26af8f79212740c | 86a9081a05b837ad0f0feaf6e003a1cbb276993f | /cg_exercises-cg_exercise_03/cg_exercise_03/cglib/lib/glm/glm/gtx/matrix_interpolation.hpp | 7cf42e984d08e11b2fb8029a9d060cb608e0203a | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-happy-bunny",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | flex3r/cg_exercises | e2defd27427c251d5f0f567a8d192af8d87bca3c | 7c4b699a8211ba66710ac2137f0d460933069331 | refs/heads/master | 2020-12-11T14:06:15.052585 | 2018-02-11T13:58:23 | 2018-02-11T13:58:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,899 | hpp | /// @ref gtx_matrix_interpolation
/// @file glm/gtx/matrix_interpolation.hpp
/// @author Ghenadii Ursachi (the.asteroth@gmail.com)
///
/// @see core (dependence)
///
/// @defgroup gtx_matrix_interpolation GLM_GTX_matrix_interpolation
/// @ingroup gtx
///
/// @brief Allows to directly interpolate two exiciting matrices.
///
/// <glm/gtx/matrix_interpolation.hpp> need to be included to use these functionalities.
#pragma once
// Dependency:
#include "../glm.hpp"
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTX_matrix_interpolation extension included")
#endif
namespace glm
{
/// @addtogroup gtx_matrix_interpolation
/// @{
/// Get the axis and angle of the rotation from a matrix.
/// From GLM_GTX_matrix_interpolation extension.
template <typename T, precision P>
GLM_FUNC_DECL void axisAngle(
tmat4x4<T, P> const & mat,
tvec3<T, P> & axis,
T & angle);
/// Build a matrix from axis and angle.
/// From GLM_GTX_matrix_interpolation extension.
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> axisAngleMatrix(
tvec3<T, P> const & axis,
T const angle);
/// Extracts the rotation part of a matrix.
/// From GLM_GTX_matrix_interpolation extension.
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> extractMatrixRotation(
tmat4x4<T, P> const & mat);
/// Build a interpolation of 4 * 4 matrixes.
/// From GLM_GTX_matrix_interpolation extension.
/// Warning! works only with rotation and/or translation matrixes, scale will generate unexpected results.
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> interpolate(
tmat4x4<T, P> const & m1,
tmat4x4<T, P> const & m2,
T const delta);
/// @}
}//namespace glm
#include "matrix_interpolation.inl"
// CG_REVISION 5076130387d5a9915bfcd693bb4e6b142e11aa30
| [
"n1085633848@outlook.com"
] | n1085633848@outlook.com |
d1da66b2796bd59ad37d39324a7c68d2e9e82ab7 | ec4711e5444c280fc4fcd6505d5c0acca0627d55 | /hermit/scrollcom.h | 085aebe0a1a52ffb76185604950006e39f399533 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | ancientlore/hermit | 18f605d1cc8f145c6d936268c9139c92f6182590 | 0b6b5b3e364fe9a7080517a7f3ddb8cdb03f5b14 | refs/heads/master | 2020-05-16T21:02:57.517459 | 2012-01-26T00:17:12 | 2012-01-26T00:17:12 | 3,269,934 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,782 | h | // Scrollable COM Custom Viewer class
// Copyright (C) 1997 Michael D. Lore All Rights Reserved
#ifndef SCROLLCOM_H
#define SCROLLCOM_H
#include "console/scrollable.h"
#include "console/screen.h"
#include "hmtobjs.h"
class ScrollCOM : public Scrollable {
const CLSID& mClass;
IHermitScrollable *mpInterface;
const char *mpCompName;
public:
// All of these can throw exceptions from the component's failure.
// The COMScroller class catches these.
ScrollCOM (const CLSID& classid, const char *compName = "<unknown>");
virtual ~ScrollCOM ();
virtual int isAtHome () const; // returns whether cursor is at beginning
virtual int isAtEnd () const; // returns whether cursor is at end
virtual int moveCursor (int count); // returns amount it actually moved; negative to go up
virtual int home (); // returns how much the cursor moved to get there
virtual int end (); // returns how much the cursor moved to get there
// The convention with these is to return "empty" values when the position is bogus
// The lines do NOT need to be padded on the right, but the attributes must fill the whole thing
virtual int getText (int pos, char *line, int width) const; // pos relative to cursor
virtual void getAttributes (int pos, WORD *attrs, int width) const; // pos relative to cursor
// Extra methods specific to ScrollCOM
void showFile (const char *filename); // should be called after construction
int processEvent (int key, DWORD data, int& redraw); // returns 1 if the key was handled
int getStatusText (char *line, int width) const; // returns 1 if status to be drawn
void positionCursor (int absolutePos); // should redraw
};
#endif
| [
"michael.lore@gmail.com"
] | michael.lore@gmail.com |
79dff7c56116a5ac19f9dbb908a1bbccd5b5cd10 | 3cf2add5c4358157fb31390e3c2fc6ebd8ebb9c8 | /Samples_Cplusplus/sample_traverse_directory.cpp | 45e65c0b7be52ef75b308d13393bb541f4fdc556 | [] | no_license | fengbingchun/Linux_Code_Test | 4b4f4eef5805f47f757a2bfae2d598c4ba9788c4 | 87c1a30e2d9d6a8183c44611663593ef1189eded | refs/heads/master | 2023-08-03T12:41:50.793738 | 2023-07-23T05:20:18 | 2023-07-23T05:20:18 | 55,020,430 | 71 | 52 | null | null | null | null | UTF-8 | C++ | false | false | 3,864 | cpp | #include <dirent.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <string>
namespace {
void Usage(const char* exe)
{
fprintf(stderr, "input params error, run this exe as following command line:\n");
fprintf(stderr, "\t%s arg1 arg2 arg3\n", exe);
fprintf(stderr, "\targ1: specify the directory to traverse\n");
fprintf(stderr, "\targ2: type:\n"
"\t\t0: tarverse all files and all directories in directory;\n"
"\t\t1: only tarverse all files, don't include directories in directory;\n"
"\t\t2: only tarverse all directories, don't include files in directory.\n");
fprintf(stderr, "\targ3: optional, filter, default is *, which is don't filter. \n");
fprintf(stderr, "for example(support relative path), only traverse jpg image:\n");
fprintf(stderr, "\t%s ./images 0 .jpg\n", exe);
fprintf(stderr, "##### test fail #####\n");
}
// 遍历指定文件夹下的所有文件,不包括指定文件夹内的文件夹
std::vector<std::string> GetListFiles(const std::string& path, const std::string& exten = "*")
{
std::vector<std::string> list;
list.clear();
DIR* dp = nullptr;
struct dirent* dirp = nullptr;
if ((dp = opendir(path.c_str())) == nullptr) {
return list;
}
while ((dirp = readdir(dp)) != nullptr) {
if (dirp->d_type == DT_REG) {
if (exten.compare("*") == 0)
list.emplace_back(static_cast<std::string>(dirp->d_name));
else
if (std::string(dirp->d_name).find(exten) != std::string::npos)
list.emplace_back(static_cast<std::string>(dirp->d_name));
}
}
closedir(dp);
return list;
}
// 遍历指定文件夹下的所有文件夹,不包括指定文件夹下的文件
std::vector<std::string> GetListFolders(const std::string& path, const std::string& exten = "*")
{
std::vector<std::string> list;
list.clear();
DIR* dp = nullptr;
struct dirent* dirp = nullptr;
if ((dp = opendir(path.c_str())) == nullptr) {
return list;
}
while ((dirp = readdir(dp)) != nullptr) {
if (dirp->d_type == DT_DIR && strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0) {
if (exten.compare("*") == 0)
list.emplace_back(static_cast<std::string>(dirp->d_name));
else
if (std::string(dirp->d_name).find(exten) != std::string::npos)
list.emplace_back(static_cast<std::string>(dirp->d_name));
}
}
closedir(dp);
return list;
}
// 遍历指定文件夹下的所有文件,包括指定文件夹内的文件夹
std::vector<std::string> GetListFilesR(const std::string& path, const std::string& exten = "*")
{
std::vector<std::string> list = GetListFiles(path, exten);
std::vector<std::string> dirs = GetListFolders(path, exten);
for (auto it = dirs.cbegin(); it != dirs.cend(); ++it) {
std::vector<std::string> cl = GetListFiles(*it, exten);
for (auto file : cl) {
list.emplace_back(*it + "/" + file);
}
}
return list;
}
} // namespace
int main(int argc, char* argv[])
{
if (argc < 3 || argc > 4) {
Usage(argv[0]);
return -1;
}
int type = atoi(argv[2]);
std::string exten = "*";
if (argc == 4) exten = std::string(argv[3]);
std::vector<std::string> vec;
if (type == 0) vec = GetListFilesR(std::string(argv[1]), exten);
else if (type == 1) vec = GetListFiles(std::string(argv[1]), exten);
else if (type == 2) vec = GetListFolders(std::string(argv[1]), exten);
else { Usage(argv[0]); return -1;}
fprintf(stdout, "traverse result: files count: %d\n", vec.size());
for (auto& file : vec) {
fprintf(stderr, "\t%s\n", file.c_str());
}
fprintf(stdout, "===== test success =====\n");
} | [
"fengbingchun@163.com"
] | fengbingchun@163.com |
4f1613f0ccddd76fd46d2393322883c77637be6f | 18da60961156696d4dfa7368cab91a6ed20cc223 | /Source/RRM/LinkAdaptation/LinkAdaptation.h | d0b88addc9af0e97f2c44894df785729b372dc33 | [] | no_license | Snorlaxgithub/4g-lte | d377dfb59657152f595a36589bea1c5490950ed2 | 55d15c04bccb847622da5c25e65669f1ee7f00d9 | refs/heads/master | 2020-03-27T10:02:09.798542 | 2013-11-20T19:11:55 | 2013-11-20T19:11:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,350 | h | /**
* @file LinkAdaptation.h
* Name: 3G LTE System Simulator
* @author Guilherme Silveira Rabelo
* Date: 03/12/2008
*
* This file is part of the undergraduate final project, under the supervision
* of Robson Domingos and Paulo Portela.
*
* @author_2 Luiz Gustavo da Silva Carvalho
* @author_3 Marcos Samuel Santos Ouriques
* Date: 09/01/2012 (Month/Day/Year)
*
* This file is also a part of the undergraduate final project, under the supervision
* of Andre Noll Barreto.
*/
#ifndef _LinkAdaptation_h_
#define _LinkAdaptation_h_
#include <itpp/itbase.h>
#include "User.h"
#include "PhysicalResourceBlock.h"
using namespace itpp;
using namespace std;
/**
* LinkAdaptation Namespace.
* Detailed Description.
*/
namespace LinkAdaptation
{
enum MCS_e
{
MCS1,
MCS2,
MCS3,
MCS4,
MCS5,
MCS6,
MCS7,
MCS8,
MCS9
};
/**
* LinkAdaptation Class.
* Detailed Description.
*/
class LinkAdaptation
{
public:
/**
* Destructor.
* Left empty.
*/
~LinkAdaptation();
/**
* Interface.
* Sinlgetown instance of the class.
*/
static LinkAdaptation* getInstance();
/**
* Interface.
* Initializes numberMCSs_, BERt_, codingRate_, betas_ and MCSThresholds_.
*/
void setParameters();
/**
* Interface.
* Left empty.
*/
void initialize();
/**
* Interface.
* Detailed description.
*/
void clear();
/**
* Interface.
* Detailed description.
*/
double mapSINRs( const vec& sinrs,
const int MCS );
/**
* Interface.
* Detailed description.
*/
void chooseMCS( vec sinrs,
double& sinr,
int& MCS,
int& rawBits,
double& effectiveBits );
/**
* Interface.
* Detailed description.
*/
double getBER( const double sinr,
const int MCS );
/**
* Interface.
* Detailed description.
*/
bool isBERvalid( const double BER );
/**
* Interface.
* Where effectively happens the transmission, according to MCS.
*/
void setBits( const int MCS,
int& rawBits,
double& effectiveBits );
/**
* Interface.
* Detailed description.
*/
bool checkMCS( vec sinrs,
int MCS );
private:
/**
* Constructor.
* Left empty.
*/
LinkAdaptation();
/**
* Member.
* Left empty.
*/
static LinkAdaptation* instance_;
/**
* Member.
* Left empty.
*/
vec betas_;
/**
* Member.
* Left empty.
*/
vec MCSThresholds_;
/**
* Member.
* Equals to 3.
*/
int numberMCSs_;
/**
* Member.
* Equals to 1e-6.
*/
double BERt_;
/**
* Member.
* Left empty.
*/
double codingRate_;
};
};
#endif
| [
"marcos.samuel@gmail.com"
] | marcos.samuel@gmail.com |
4564d52d10c333a63137b207b1109fc6efe2f17e | e92afca02bd03aa5d8d92147fa854c51d0bd4705 | /src/node_main.cc | 5091594db413034b177c0b657731d921b2690c98 | [
"ICU",
"LicenseRef-scancode-unicode",
"NAIST-2003",
"MIT",
"ISC",
"LicenseRef-scancode-public-domain",
"NTP",
"Artistic-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"Zlib",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-openssl"
] | permissive | ajamshed/node.js | 18725a630c82b5188ec43929be6330c17ef8e496 | 9faeacbd97a09024ee984a0140f7dac2af74bc20 | refs/heads/master | 2021-08-28T17:18:28.712229 | 2017-12-12T22:31:47 | 2017-12-12T22:31:47 | 113,892,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cc | #include "node.h"
#ifdef _WIN32
#include <VersionHelpers.h>
#include <WinError.h>
int wmain(int argc, wchar_t *wargv[]) {
if (!IsWindows7OrGreater()) {
fprintf(stderr, "This application is only supported on Windows 7, "
"Windows Server 2008 R2, or higher.");
exit(ERROR_EXE_MACHINE_TYPE_MISMATCH);
}
// Convert argv to to UTF8
char** argv = new char*[argc + 1];
for (int i = 0; i < argc; i++) {
// Compute the size of the required buffer
DWORD size = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
nullptr,
0,
nullptr,
nullptr);
if (size == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
// Do the actual conversion
argv[i] = new char[size];
DWORD result = WideCharToMultiByte(CP_UTF8,
0,
wargv[i],
-1,
argv[i],
size,
nullptr,
nullptr);
if (result == 0) {
// This should never happen.
fprintf(stderr, "Could not convert arguments to utf8.");
exit(1);
}
}
argv[argc] = nullptr;
// Now that conversion is done, we can finally start.
return node::Start(argc, argv);
}
#else
// UNIX
extern "C" {
int node_mtcp_init_wrapper();
}
int main(int argc, char *argv[]) {
// Disable stdio buffering, it interacts poorly with printf()
// calls elsewhere in the program (e.g., any logging from V8.)
setvbuf(stdout, nullptr, _IONBF, 0);
setvbuf(stderr, nullptr, _IONBF, 0);
if (node_mtcp_init_wrapper() < 0) {
printf("Failed to initialized mtcp_wrapper\n");
exit(1);
}
return node::Start(argc, argv);
}
#endif
| [
"ajamshed@ndsl.kaist.edu"
] | ajamshed@ndsl.kaist.edu |
5c78d634cb27994fcb03a2dbb68c17d4e52dee90 | d85fa954775b1bf2ecca0d3291cbe3df408ed1ce | /homework_lection_6/alloc.cpp | f83f3f762c4679c7930c875198a401b4a5f06601 | [] | no_license | cojuer/advanced_cpp_2018 | 546a73f6e18aa57bb997543cd9448a1425ccfcca | 4655b5ad39506af2d3e34b4c063cd3347c8e967c | refs/heads/master | 2020-03-29T07:31:37.994210 | 2018-12-24T08:20:02 | 2018-12-24T08:20:02 | 149,668,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,253 | cpp | #include <iostream>
#include <vector>
#define STACK_SIZE 40
template <class T>
struct TestAllocator {
public:
using value_type = T;
T* allocate (size_t n)
{
if (n == 0) return nullptr;
if (!m_is_buf_used && n * sizeof(T) < STACK_SIZE) {
std::cout << "alloc " << n * sizeof(T) << " static memory at " << (void*)m_buf << std::endl;
m_is_buf_used = true;
return (T*)(m_buf);
}
void* mem = operator new(n * sizeof(T));
std::cout << "alloc " << n * sizeof(T) << " dynamic memory at " << mem << std::endl;
return (T*)mem;
}
void deallocate (void* p, size_t)
{
if (p == m_buf) {
std::cout << "dealloc static memory at " << p << std::endl;
m_is_buf_used = false;
}
else if (p) {
operator delete(p);
std::cout << "dealloc dynamic memory at " << p << std::endl;
}
}
private:
char m_buf[STACK_SIZE];
bool m_is_buf_used = false;
};
int main(void)
{
std::vector<int, TestAllocator<int>> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(4);
return 0;
}
| [
"akovalev@arccn.ru"
] | akovalev@arccn.ru |
50e0aa78e26f3a06a405b50af70609a15ba9635d | 51f2e9c389af4fe6070a822ca39755ffd20bcd05 | /src/appinfo.cpp | 61a9f0d53829ba519220c8a2c1f7dced37081603 | [
"BSD-3-Clause"
] | permissive | tapir-dream/berserkjs-2.0 | 0927b59e4ac9d2bfaa26aa6297938c8a29427ba2 | b4daf997f4d35e8f2d45807e50df1ff72a31345b | refs/heads/master | 2021-01-22T11:37:01.494648 | 2020-03-26T11:03:02 | 2020-03-26T11:03:02 | 34,240,472 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,255 | cpp | #include "appinfo.h"
#if defined(Q_OS_WIN32)
#include <w32api.h>
#include <windows.h>
#include <psapi.h>
CRITICAL_SECTION cs; // 供多线程同步的临界区变量
HANDLE hd; // 当前进程的句柄
DWORD t1; // 时间戳
double percent; // 最近一次计算的CPU占用率
__int64 oldp;
// 时间格式转换
__int64 fileTimeToInt64(const FILETIME& time)
{
ULARGE_INTEGER tt;
tt.LowPart = time.dwLowDateTime;
tt.HighPart = time.dwHighDateTime;
return(tt.QuadPart);
}
// 得到进程占用的CPU时间
int getTime(__int64& proc)
{
FILETIME create;
FILETIME exit;
FILETIME ker; // 内核占用时间
FILETIME user; // 用户占用时间
if(!GetProcessTimes(hd, &create, &exit, &ker, &user)){
return -1;
}
proc = (fileTimeToInt64(ker) + fileTimeToInt64(user)) / 10000;
return 0;
}
// 获取内核总数
int getCPUCoresCount()
{
SYSTEM_INFO siSysInfo;
// Copy the hardware information to the SYSTEM_INFO structure.
GetSystemInfo(&siSysInfo);
return siSysInfo.dwNumberOfProcessors;
/*
// Display the contents of the SYSTEM_INFO structure.
printf("Hardware information: \n");
printf(" OEM ID: %u\n", siSysInfo.dwOemId);
printf(" Number of processors: %u\n",
siSysInfo.dwNumberOfProcessors);
printf(" Page size: %u\n", siSysInfo.dwPageSize);
printf(" Processor type: %u\n", siSysInfo.dwProcessorType);
printf(" Minimum application address: %lx\n",
siSysInfo.lpMinimumApplicationAddress);
printf(" Maximum application address: %lx\n",
siSysInfo.lpMaximumApplicationAddress);
printf(" Active processor mask: %u\n",
siSysInfo.dwActiveProcessorMask);s
*/
}
void init()
{
// 初始化线程临界区变量
InitializeCriticalSection(&cs);
// 初始的占用率
percent = 0;
// 得到当前进程id
DWORD pid = GetCurrentProcessId();
// 通过id得到进程的句柄
hd = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if(hd == NULL){
return;
}
// 得到初始时刻的值
getTime(oldp);
t1 = GetTickCount();
}
void destroy()
{
if(hd != NULL){
CloseHandle(hd);
}
DeleteCriticalSection(&cs);
}
// 进行换算
double cpu()
{
uint time = 15; // 毫秒数。用一个比较少的时间片作为计算单位,这个值可修改
if(hd == NULL) {
return 0;
}
EnterCriticalSection(&cs);
DWORD t2 = GetTickCount();
DWORD dt = t2 - t1;
if(dt > time) {
__int64 proc;
getTime(proc);
percent = ((proc - oldp) * 100)/dt;
t1 = t2;
oldp = proc;
}
LeaveCriticalSection(&cs);
return int(percent/getCPUCoresCount()*10)/10.0;
}
double memory()
{
/*
而内存信息结构的定义如下:
typedef struct _PROCESS_MEMORY_COUNTERS {
DWORD cb;
DWORD PageFaultCount; // 分页错误数目
SIZE_T PeakWorkingSetSize; // 工作集列 ( 物理内存 ) 的最大值
SIZE_T WorkingSetSize; // 工作集列 ( 物理内存 ) 的大小
SIZE_T QuotaPeakPagedPoolUsage; // 分页池的峰值的最大值
SIZE_T QuotaPagedPoolUsage; // 分页池的峰值大小
SIZE_T QuotaPeakNonPagedPoolUsage; // 非分页池的峰值的最大值
SIZE_T QuotaNonPagedPoolUsage; // 非分页池的峰值大小
SIZE_T PagefileUsage; // 页文件页的大小(虚拟内存)
SIZE_T PeakPagefileUsage; // 页文件页的最大值
}
*/
if(hd == NULL) {
return 0;
}
PROCESS_MEMORY_COUNTERS pmc;
pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
GetProcessMemoryInfo(hd, &pmc, sizeof(pmc));
// WorkingSetSize 值通常会比在任务管理器中看到的值要大
// 因为它是表示程序使用内存的工作总集
// 而任务管理器中仅仅显示专用内存集
// 其区别在于后者不包括可共享的内存(如加载的DLL)
return (pmc.WorkingSetSize/1024);
}
#endif
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
#include <unistd.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <stdlib.h>
#include <QString>
void exec(const char *cmd, char *result)
{
FILE* stream;
char buf[128] = {0};
stream = popen(cmd, "r" );
//将FILE* stream的数据流读取到buf中
fread(buf, sizeof(char), sizeof(buf), stream);
// buf 复制
strcpy(result, buf);
pclose(stream);
}
double cpu()
{
int pid = int(getpid());
char result[128];
std::stringstream newstr;
newstr<<pid;
std::string cmd = "ps aux|grep " + newstr.str() + "|awk '{print $3}'|awk 'NR==1'";
exec(cmd.c_str(), result);
return QString(result).toDouble();
}
double memory()
{
int pid = int(getpid());
char result[128];
std::stringstream newstr;
newstr<<pid;
std::string cmd = "ps aux|grep " + newstr.str() + "|awk '{print $6}'|awk 'NR==1'";
exec(cmd.c_str(), result);
return QString(result).toDouble();
}
#endif
AppInfo::AppInfo()
{
#ifdef Q_OS_WIN32
init();
#endif
}
AppInfo::~AppInfo()
{
#ifdef Q_OS_WIN32
destroy();
#endif
}
double AppInfo::getCPU()
{
return cpu();
}
double AppInfo::getMemory()
{
return memory();
}
| [
"tapir.dream@gmail.com"
] | tapir.dream@gmail.com |
7e007c9098cb1459535979fd19534ec51af5fe84 | 80a4bea7acdfb6ce22f2d1b0b0603c418dd85fc9 | /OpenGL/src/GLObject/VertexBufferLayout/VertexBufferLayout.cpp | 99b73f477f33814e19ff3bd9a00d568b56225b4d | [
"MIT"
] | permissive | dusko2/OpenGL | 859dd5a191cc5230a85c2f66407f89afc0919c68 | 3610f83698a0ddc54760afef1e90822adf8d16db | refs/heads/master | 2023-03-19T22:16:17.536614 | 2021-02-26T19:01:17 | 2021-02-26T19:01:17 | 340,934,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 919 | cpp | #include <glad/glad.h>
#include "VertexBufferLayout.h"
VertexBufferLayout::VertexBufferLayout() : stride(0) {}
template<>
void VertexBufferLayout::Add<float>(uint32 count, bool normalized) {
elements.push_back({ GL_FLOAT, count, normalized });
stride += count * sizeof(float);
}
template<>
void VertexBufferLayout::Add<uint32>(uint32 count, bool normalized) {
elements.push_back({ GL_UNSIGNED_INT, count, normalized });
stride += count * sizeof(uint32);
}
template <>
void VertexBufferLayout::Add<uint8>(uint32 count, bool normalized) {
elements.push_back({ GL_UNSIGNED_BYTE, count, normalized });
stride += count * sizeof(uint8);
}
template void VertexBufferLayout::Add<float>(uint32 count, bool normalized = false);
template void VertexBufferLayout::Add<uint32>(uint32 count, bool normalized = false);
template void VertexBufferLayout::Add<uint8>(uint32 count, bool normalized = false);
| [
"mirkovic.dusko.16@sinergija.com"
] | mirkovic.dusko.16@sinergija.com |
33497a22342d4eca468edccab99877102a1f334f | 408c27cbe3407cc770ab4149e52498ae7da4ed0b | /hangman.h | 1ad49be41b25d9dccdbad4a89bd4d42ef9b046d7 | [] | no_license | JulianFortik/POP2-HANGMAN | d03ac42362e416f62b4744ae5a286dda4ddf2294 | 47819cc41daaf2932300592505cb41bead08d31d | refs/heads/main | 2023-04-03T15:42:38.335990 | 2021-04-09T15:36:33 | 2021-04-09T15:36:33 | 356,315,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,841 | h | /*************************************************************
* Instructor's Name: Mrs. Vernelle Sylvester *
* Group Members: Lianni Mathews, Jason Fortik *
* Project: Hangman *
* Description: Hangman utilizes object oriented programming *
* to create an object that stores the statistics that are being *
* generated and also uses classes to separate the functions and *
* their declarations as libraries outside the main file *
* Due Date: March 25,2021 *
*************************************************************/
#ifndef HANGMAN_H
#define HANGMAN_H
#include <string>
#include <vector>
#include "player.h"
using std::vector;
using std::string;
class Hangman
{
public:
const static int ALPHABET_SIZE = 26; //const set rows for Alphabet
const static int ASCII_ROWS = 7;
const static int ASCII_COLS = 8;
Hangman(string filename, string username);
int selectGameLevel();
int generateRandomNumber();
string selectRandomWord(int random_number);
void loadWordList(std::string filename);
void startGame();
void printMessage(string message, bool printTop = true, bool printBottom = true);
void drawHangman(int guessCount = 0);
void resetAvailableLetters();
void printAsciiMessage(string message);
void printAvailableLetters(string taken);
bool checkWin(string wordToGuess, string guessesSoFar);
bool processResults(string wordToGuess, int guessAttempts, bool hasWon);
void setDifficultyLevel(unsigned diffLevel);
unsigned getDifficultyLevel();
void setMaxAllowedAttempts(unsigned allowedAttempts);
unsigned getMaxAllowedAttempts();
unsigned attemptsMadeSoFar(std::string wordToGuess, std::string guessesSoFar);
private:
Player player;
vector<string> wordVector;
unsigned difficultyLevel;
unsigned maxAllowedAttempts;
char alphabetArray[ALPHABET_SIZE + 1];
constexpr static char G[ASCII_ROWS][ASCII_COLS]={
" #### ", //Row=0
" # ", //Row=1
" # ", //Row=2
" # ### ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" ### " //Row=6
};
constexpr static char A[ASCII_ROWS][ASCII_COLS] = {
" ### ", //Row=0
" # # ", //Row=1
" # # ", //Row=2
" ##### ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" # # " //Row=6
};
constexpr static char M[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row=0
" ## ## ",//Row=1
" # # # ",//Row=2
" # # # ",//Row=3
" # # ",//Row=4
" # # ",//Row=5
" # # " //Row=6
};
constexpr static char E[ASCII_ROWS][ASCII_COLS] = {
" ##### ", //Row=0
" # ", //Row=1
" # ", //Row=2
" ##### ", //Row=3
" # ", //Row=4
" # ", //Row=5
" ##### " //Row=6
};
constexpr static char O[ASCII_ROWS][ASCII_COLS] = {
" ### ", //Row=0
" # # ", //Row=1
" # # ", //Row=2
" # # ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" ### " //Row=6
};
constexpr static char V[ASCII_ROWS][ASCII_COLS]={ " # # ", //Row=0
" # # ", //Row=1
" # # ", //Row=2
" # # ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" # "}; //Row=6
constexpr static char R[ASCII_ROWS][ASCII_COLS] = {
" ### ", //Row 0
" # # ", //Row=1
" # # ", //Row=2
" #### ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" # # " //Row=6
};
constexpr static char Y[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row = 0
" # # ", //Row=1
" # # ", //Row=2
" ### ", //Row=3
" # ", //Row=4
" # ", //Row=5
" # " //Row=6
};
constexpr static char U[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row = 0
" # # ",//Row=1
" # # ",//Row=2
" # # ",//Row=3
" # # ",//Row=4
" # # ",//Row=5
" ### " //Row=6
};
constexpr static char W[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row =0
" # # ", //Row=1
" # # ", //Row=2
" # # # ", //Row=3
" # # # ", //Row=4
" ## ## ", //Row=5
" # # " //Row=6
};
constexpr static char N[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row=0
" ## # ", //Row=1
" # # # ", //Row=2
" # # # ", //Row=3
" # ## ", //Row=4
" # ## ", //Row=5
" # # " //Row=6
};
constexpr static char exclamation[ASCII_ROWS][ASCII_COLS] = {
" ## ", //Row=0
" ## ", //Row=1
" ## ", //Row=2
" ## ", //Row=3
" ## ", //Row=4
" ", //Row=5
" ## " //Row=6
};
constexpr static char space[ASCII_ROWS][ASCII_COLS] = {
" ", //Row=0
" ", //Row=1
" ", //Row=2
" ", //Row=3
" ", //Row=4
" ", //Row=5
" " //Row=6
};
};
#endif // HANGMAN_H
| [
"fortikdev@gmail.com"
] | fortikdev@gmail.com |
594fe263bec14a62807954ceed574c68b196184f | 6e6d008c24d8540e28a3dd6b51a7387d7c700921 | /Vision week 3&4/Vision_timer/BinaryYellow.cpp | 4b7a36b1bd517cc9cef247404d613cd74e723890 | [] | no_license | bryanbaan/Themaopdracht-07---Lokalisatie-2 | a8a9c4779e4f3054ce98b6c5835c7ada64a4b711 | e3490029d6b67f97ba96b0c5bcb2226bd44b0e2c | refs/heads/master | 2021-01-22T17:58:45.149697 | 2014-04-14T12:31:49 | 2014-04-14T12:31:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,099 | cpp | #include "BinaryYellow.h"
//AUTHOR Lars Veenendaal
BinaryYellow::BinaryYellow() {
bt = new BaseTimer();
}
BinaryYellow::~BinaryYellow() {
delete bt;
}
void BinaryYellow::CreateBinaryImage(Image &sourceImage, Image &destinationImage) {
bt->reset();
bt->start();
if (sourceImage.GetWidth() != destinationImage.GetWidth() && sourceImage.GetHeight() != destinationImage.GetHeight()) {
std::cout << "Error images are not the same size" << std::endl;
return;
}
for (int y = sourceImage.GetHeight() - 1; y >= 0; y--) {
for (int x = sourceImage.GetWidth() - 1; x >= 0; x--) {
// red = 130 -255
// Green = 80 -255
// Blue = 0 -85
if (((int)sourceImage.GetPixelRed(x, y) >= 130) && ((int)sourceImage.GetPixelGreen(x, y) >= 80) && ((int)sourceImage.GetPixelBlue(x, y) <= 85)){
destinationImage.SetPixel(x, y, 0xFFFFFFFF);
}
else{
destinationImage.SetPixel(x, y, 0x000000FF);
}
}
}
bt->stop();
std::cout << "Time for the binary yellow function: " << bt->elapsedMicroSeconds() << " Microseconds (" << bt->elapsedMilliSeconds() << "ms)" << std::endl;
}
| [
"chanan_van_ooijen13_7@hotmail.com"
] | chanan_van_ooijen13_7@hotmail.com |
06cbfcb7ca794e640e5896f098522bb8bdba81e7 | 436d5cde84d3ec4bd16c0b663c7fdc68db02a723 | /ch01/e1.16.cpp | b71d72661721ae3692f6a4ef8252ad8a2311029a | [] | no_license | focus000/cppprimer | 31f0cadd1ee69f20a6a2a20fc62ddfa0c5341b83 | c901b55da35922a96857a108d25213fa37121b33 | refs/heads/master | 2020-09-13T04:56:55.130773 | 2020-05-09T09:23:00 | 2020-05-09T09:23:00 | 222,660,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | cpp | //
// Created by 李蕴方 on 2019-02-19.
//
#include <iostream>
int main() {
int sum = 0, i = 0;
std::cout << "input: " << std::endl;
while (std::cin >> i) {
sum += i;
}
std::cout << "the sum is: " << sum <<std::endl;
return 0;
} | [
"hanszimmerme@gmail.com"
] | hanszimmerme@gmail.com |
aa5d2677f30a0759a5839a283a7b403b2f8eed40 | a92b18defb50c5d1118a11bc364f17b148312028 | /src/prod/src/Hosting2/NonActivatedApplicationHost.h | b9345e32c4cb4358dd68cc3e6a89a7c675619eb5 | [
"MIT"
] | permissive | KDSBest/service-fabric | 34694e150fde662286e25f048fb763c97606382e | fe61c45b15a30fb089ad891c68c893b3a976e404 | refs/heads/master | 2023-01-28T23:19:25.040275 | 2020-11-30T11:11:58 | 2020-11-30T11:11:58 | 301,365,601 | 1 | 0 | MIT | 2020-11-30T11:11:59 | 2020-10-05T10:05:53 | null | UTF-8 | C++ | false | false | 1,719 | h | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Hosting2
{
class NonActivatedApplicationHost :
public ApplicationHost
{
public:
NonActivatedApplicationHost(
std::wstring const & hostId,
KtlSystem *,
std::wstring const & runtimeServiceAddress);
virtual ~NonActivatedApplicationHost();
static Common::ErrorCode NonActivatedApplicationHost::Create(
KtlSystem *,
std::wstring const & runtimeServiceAddress,
__out ApplicationHostSPtr & applicationHost);
static Common::ErrorCode NonActivatedApplicationHost::Create2(
KtlSystem *,
std::wstring const & runtimeServiceAddress,
std::wstring const & hostId,
__out ApplicationHostSPtr & applicationHost);
protected:
virtual Common::ErrorCode OnCreateAndAddFabricRuntime(
FabricRuntimeContextUPtr const & fabricRuntimeContextUPtr,
Common::ComPointer<IFabricProcessExitHandler> const & fabricExitHandler,
__out FabricRuntimeImplSPtr & fabricRuntime);
virtual Common::ErrorCode OnGetCodePackageActivationContext(
CodePackageContext const & codeContext,
__out CodePackageActivationContextSPtr & codePackageActivationContext);
virtual Common::ErrorCode OnUpdateCodePackageContext(
CodePackageContext const & codeContext);
};
}
| [
"noreply-sfteam@microsoft.com"
] | noreply-sfteam@microsoft.com |
0aa65fb44a251568f07449ce6d78dfd0f1548de5 | 36d16576057cafec3dd4a35fd5a6fc05e4baa08e | /qglv_gallery/src/background_image.cpp | 249650cdbdb51df68d1c2841400b5c7d832a55ae | [] | no_license | yichoe/qglv_toolkit | 44774941ba51510632ed487510e7a95b752bfdc8 | 1f12b2866a3c6cd0b7864ed7591a09e709011e53 | refs/heads/devel | 2020-06-19T08:26:34.839694 | 2017-06-13T07:33:36 | 2017-06-13T07:33:36 | 94,182,308 | 0 | 0 | null | 2017-06-13T07:16:18 | 2017-06-13T07:16:18 | null | UTF-8 | C++ | false | false | 5,397 | cpp | /**
* @file /dslam_viewer/src/qgl_gallery/background_image.cpp
*
* @brief Short description of this file.
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <qapplication.h>
#include <QGLViewer/qglviewer.h>
#include <qimage.h>
#include <qfiledialog.h>
#include <QKeyEvent>
/*****************************************************************************
** Namespaces
*****************************************************************************/
using namespace qglviewer;
using namespace std;
/*****************************************************************************
** Interface
*****************************************************************************/
class Viewer : public QGLViewer
{
protected :
virtual void init();
virtual void draw();
virtual void drawBackground();
virtual void keyPressEvent(QKeyEvent *e);
virtual QString helpString() const;
void loadImage();
private :
float ratio, u_max, v_max;
bool background_;
};
/*****************************************************************************
** Implementation
*****************************************************************************/
void Viewer::init()
{
restoreStateFromFile();
// Enable GL textures
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
// Nice texture coordinate interpolation
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
u_max = 1.0;
v_max = 1.0;
ratio = 1.0;
background_ = true;
setKeyDescription(Qt::Key_L, "Loads a new background image");
setKeyDescription(Qt::Key_B, "Toggles background display");
loadImage();
help();
qWarning("fin init");
}
void Viewer::draw()
{
drawBackground();
const float nbSteps = 200.0;
glBegin(GL_QUAD_STRIP);
for (float i=0; i<nbSteps; ++i)
{
float ratio = i/nbSteps;
float angle = 21.0*ratio;
float c = cos(angle);
float s = sin(angle);
float r1 = 1.0 - 0.8*ratio;
float r2 = 0.8 - 0.8*ratio;
float alt = ratio - 0.5;
const float nor = .5;
const float up = sqrt(1.0-nor*nor);
glColor3f(1.0-ratio, 0.2f , ratio);
glNormal3f(nor*c, up, nor*s);
glVertex3f(r1*c, alt, r1*s);
glVertex3f(r2*c, alt+0.05, r2*s);
}
glEnd();
}
void Viewer::drawBackground()
{
if (!background_)
return;
glDisable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glColor3f(1,1,1);
startScreenCoordinatesSystem(true);
// Draws the background quad
glNormal3f(0.0, 0.0, 1.0);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0-v_max); glVertex2i(0,0);
glTexCoord2f(0.0, 1.0); glVertex2i(0,height());
glTexCoord2f(u_max, 1.0); glVertex2i(width(),height());
glTexCoord2f(u_max, 1.0-v_max); glVertex2i(width(),0);
glEnd();
stopScreenCoordinatesSystem();
// Depth clear is not absolutely needed. An other option would have been to draw the
// QUAD with a 0.999 z value (z ranges in [0, 1[ with startScreenCoordinatesSystem()).
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
}
void Viewer::loadImage()
{
QString name = QFileDialog::getOpenFileName(this, "Select an image", ".", "Images (*.png *.xpm *.jpg)");
// In case of Cancel
if (name.isEmpty())
return;
QImage img(name);
if (img.isNull())
{
qWarning("Unable to load file, unsupported file format");
return;
}
qWarning("Loading %s, %dx%d pixels", name.toLatin1().constData(), img.width(), img.height());
// 1E-3 needed. Just try with width=128 and see !
int newWidth = 1<<(int)(1+log(img.width() -1+1E-3) / log(2.0));
int newHeight = 1<<(int)(1+log(img.height()-1+1E-3) / log(2.0));
u_max = img.width() / (float)newWidth;
v_max = img.height() / (float)newHeight;
if ((img.width()!=newWidth) || (img.height()!=newHeight))
{
qWarning("Image size set to %dx%d pixels", newWidth, newHeight);
img = img.copy(0, 0, newWidth, newHeight);
}
ratio = newWidth / float(newHeight);
QImage glImg = QGLWidget::convertToGLFormat(img); // flipped 32bit RGBA
// Bind the img texture...
glTexImage2D(GL_TEXTURE_2D, 0, 4, glImg.width(), glImg.height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, glImg.bits());
}
void Viewer::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
case Qt::Key_L :
loadImage();
break;
case Qt::Key_B :
background_ = !background_;
updateGL();
break;
default: QGLViewer::keyPressEvent(e);
}
}
QString Viewer::helpString() const
{
QString text("<h2>B a c k g r o u n d I m a g e</h2>");
text += "This example is derivated from textureViewer.<br><br>";
text += "It displays a background image in the viewer using a texture.<br><br>";
text += "Press <b>L</b> to load a new image, and <b>B</b> to toggle the background display.";
return text;
}
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char** argv)
{
QApplication application(argc,argv);
Viewer viewer;
viewer.setWindowTitle("backgroundImage");
viewer.show();
return application.exec();
}
| [
"d.stonier@gmail.com"
] | d.stonier@gmail.com |
1fbc595629bc7a242e2a482d35309306f100b542 | 8cb2d3088cee07199c9778adf8d4856a3301a555 | /Game.h | ff2e3569b0465317e38dbb5ccd3375a865dbcf1b | [] | no_license | cj-dimaggio/OldRogueLike | 7b72dff89afb7d1afb5242c68cd1b6d9cb119b66 | 251b994c077ee272d50fea728fca20bbe6bc65b6 | refs/heads/master | 2021-05-28T00:49:48.495217 | 2014-10-26T14:47:49 | 2014-10-26T14:47:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | h | #ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#include "precompiledheaders.h"
#include "GameObject.h"
#include "Tile.h"
#include "Message.h"
class Game
{
public:
Game();
static void Start();
static void GameLoop();
static void HandleKeys();
static void RenderAll();
static void HandleAI();
static void CreateDungeon();
static void DrawDungeon();
static void DrawBars();
static void DrawMessages();
static void RenderInventoryScreen();
static const int SCREEN_WIDTH = 100;
static const int SCREEN_HEIGHT = 75;
static const int MAP_WIDTH = 100;
static const int MAP_HEIGHT = 60;
static const int PANEL_HEIGHT = 15;
static const int BAR_WIDTH = 20;
static TCODConsole* gameConsole;
static TCODConsole* panel;
static TCODConsole* inventoryScreen;
enum States {PlayersTurn, EnemysTurn, UpdateScreen, InventoryScreen};
static States gameState;
private:
static bool _exit;
};
#endif // GAME_H_INCLUDED
| [
"ssawaa@yahoo.com"
] | ssawaa@yahoo.com |
e64ceabac9c703dd2b111bf4945500619ee6a24b | 5413baae6a6d9ec1c64d6ba45de4defbad796a45 | /NES Emulator/Source/Audio/DMC.hpp | 6b3322f27cdc05e57815666cbb0e92ac0da18770 | [] | no_license | Sjhunt93/Nes-Emulator | e17f93a98d71472e7b196270a406b0cc0682dd83 | 385e4f595c6a482c77a3afef5a555b15ea76ee5d | refs/heads/master | 2020-04-21T14:10:40.298245 | 2019-03-12T16:28:10 | 2019-03-12T16:28:10 | 169,625,647 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,811 | hpp | //
// DMC.hpp
// NES Emulator - App
//
// Created by Samuel Hunt on 21/02/2019.
//
#ifndef DMC_hpp
#define DMC_hpp
#include "Audio.h"
class CPU;
class DMC {
public:
CPU * cpu;
bool enabled;
Byte value;
UInt16 sampleAddress;
UInt16 sampleLength;
UInt16 currentAddress;
UInt16 currentLength;
Byte shiftRegister;
Byte bitCount;
Byte tickPeriod;
Byte tickValue;
bool loop;
bool irq;
void writeControl(Byte _value) {
irq = (_value&0x80) == 0x80;
loop = (_value&0x40) == 0x40;
tickPeriod = dmcTable[_value&0x0F];
}
void writeValue(Byte _value) {
value = _value & 0x7F;
}
void writeAddress(Byte _value) {
// Sample address = %11AAAAAA.AA000000
sampleAddress = 0xC000 | (UInt16(_value) << 6);
}
void writeLength(Byte value ) {
// Sample length = %0000LLLL.LLLL0001
sampleLength = (UInt16(value) << 4) | 1;
}
void restart() {
currentAddress = sampleAddress;
currentLength = sampleLength;
}
void stepTimer() {
if (!enabled) {
return;
}
stepReader();
if (tickValue == 0) {
tickValue = tickPeriod;
stepShifter();
} else {
tickValue--;
}
}
void stepReader();
void stepShifter() {
if (bitCount == 0) {
return;
}
if ((shiftRegister&1) == 1) {
if (value <= 125) {
value += 2;
}
}
else {
if (value >= 2) {
value -= 2;
}
}
shiftRegister >>= 1;
bitCount--;
}
Byte output() {
return value;
}
};
#endif /* DMC_hpp */
| [
"samuel.hunt@uwe.ac.uk"
] | samuel.hunt@uwe.ac.uk |
d8e274d32e4ef0708993c3fe2f26c12c90818d3c | 62a7d30053e7640ef770e041f65b249d101c9757 | /Discover Vladivostok 2019. Division A Day 4/F.cpp | 2a857af646340fe5de4618db6f31b002ed2e2cb1 | [] | no_license | wcysai/Calabash | 66e0137fd59d5f909e4a0cab940e3e464e0641d0 | 9527fa7ffa7e30e245c2d224bb2fb77a03600ac2 | refs/heads/master | 2022-05-15T13:11:31.904976 | 2022-04-11T01:22:50 | 2022-04-11T01:22:50 | 148,618,062 | 76 | 16 | null | 2019-11-07T05:27:40 | 2018-09-13T09:53:04 | C++ | UTF-8 | C++ | false | false | 1,546 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < int(n); i++)
#define Rep(i, n) for (int i = 1; i <=int(n); i++)
#define range(x) begin(x), end(x)
#ifdef __LOCAL_DEBUG__
#define _debug(fmt, ...) fprintf(stderr, "[%s] " fmt "\n", __func__, ##__VA_ARGS__)
#else
#define _debug(...) ((void) 0)
#endif
typedef long long LL;
typedef unsigned long long ULL;
int p[] = {3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71};
int n;
const LL mod = 1'000'000'009;
LL powmod(LL b, LL e) {
LL r = 1;
while (e) {
if (e & 1) r = r * b % mod;
b = b * b % mod;
e >>= 1;
}
return r;
}
vector<int> ps;
map<double, LL> ans;
vector<int> cur;
void compute() {
auto s = cur;
sort(range(s), greater<>());
LL ans = 1;
double apans = 0.0;
for (int i = 0; i < s.size(); i++) {
ans = ans * powmod(p[i], s[i] - 1) % mod;
apans += log(p[i]) * (s[i] - 1);
}
::ans[apans] = ans;
}
void dfs(int ptr, int s) {
if (ptr == ps.size()) {
compute();
return;
}
if (ptr and ps[ptr] != ps[ptr - 1]) s = 0;
for (; s < cur.size(); s++) {
cur[s] *= ps[ptr];
dfs(ptr + 1, s);
cur[s] /= ps[ptr];
}
cur.push_back(ps[ptr]);
dfs(ptr + 1, s);
cur.pop_back();
}
int main() {
int n; cin >> n;
for (int f = 2; n > 1; f++) {
while (n % f == 0) {
n /= f;
ps.push_back(f);
}
}
dfs(0, 0);
cout << ans.begin()->second << endl;
return 0;
}
| [
"wcysai@foxmail.com"
] | wcysai@foxmail.com |
b15688c875a4660140c9e800aa40da02977c6729 | 10c0a8cb0899692014417ef60093ace05e5e1763 | /include/RMsg_Ping.i | 8b329294c78ba907e31b08b3c847d7014d85819e | [
"BSD-3-Clause"
] | permissive | openunderlight/ULServer | 56cb96360c57598be6f72f2a20c41f69b41b56bd | 42e12e245506e6a76c3905d64378eff79c908fc5 | refs/heads/dev | 2023-03-10T22:50:51.591229 | 2023-01-31T20:27:44 | 2023-01-31T20:27:44 | 145,008,033 | 7 | 5 | NOASSERTION | 2019-12-24T19:08:59 | 2018-08-16T15:40:15 | TSQL | UTF-8 | C++ | false | false | 427 | i | // RMsg_Ping.i -*- C++ -*-
// $Id: RMsg_Ping.i,v 1.3 1997-07-18 17:26:00-07 jason Exp $
// Copyright 1996-1997 Lyra LLC, All rights reserved.
//
// conditionally inline methods/functions
#ifndef USE_DEBUG
INLINE void RMsg_Ping::Dump(FILE*, int) const
{
// empty
}
#endif /* !USE_DEBUG */
INLINE int RMsg_Ping::Nonce() const
{
return data_.nonce;
}
INLINE void RMsg_Ping::SetNonce(int nonce)
{
data_.nonce = nonce;
}
| [
"root@underlightlyra.(none)"
] | root@underlightlyra.(none) |
0936992199c97ed6d8ab51f8b53caacb340cc923 | ac719e4e5d8bf134a6ad3ce1175e68a10ad52da2 | /Classes/Native/System_Core_System_Func_2_gen2397331331.h | 69f22e2785a0a41db810d7f06ba7df25466b3d30 | [
"MIT"
] | permissive | JasonMcCoy/BOOM-Bound | b5fa6305ec23fd6742d804da0e206a923ff22118 | 574223c5643f8d89fdad3b8fc3c5d49a6a669e6e | refs/heads/master | 2021-01-11T06:23:28.917883 | 2020-05-20T17:28:58 | 2020-05-20T17:28:58 | 72,157,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// UnityEngine.Purchasing.ProductDefinition
struct ProductDefinition_t2168837728;
// System.IAsyncResult
struct IAsyncResult_t2754620036;
// System.AsyncCallback
struct AsyncCallback_t1369114871;
// System.Object
struct Il2CppObject;
#include "mscorlib_System_MulticastDelegate3389745971.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Func`2<UnityEngine.Purchasing.ProductDefinition,System.Boolean>
struct Func_2_t2397331331 : public MulticastDelegate_t3389745971
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"jasonmccoy@Jasons-MacBook-Pro.local"
] | jasonmccoy@Jasons-MacBook-Pro.local |
a9c05e1433f2e6aec0fdef34856b7d50cd32292d | cc1701cadaa3b0e138e30740f98d48264e2010bd | /chrome/browser/policy/messaging_layer/encryption/test_encryption_module.cc | f35841d79c82e645230169cf7e0c60289ef7c333 | [
"BSD-3-Clause"
] | permissive | dbuskariol-org/chromium | 35d3d7a441009c6f8961227f1f7f7d4823a4207e | e91a999f13a0bda0aff594961762668196c4d22a | refs/heads/master | 2023-05-03T10:50:11.717004 | 2020-06-26T03:33:12 | 2020-06-26T03:33:12 | 275,070,037 | 1 | 3 | BSD-3-Clause | 2020-06-26T04:04:30 | 2020-06-26T04:04:29 | null | UTF-8 | C++ | false | false | 715 | cc | // Copyright 2020 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 <string>
#include "chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h"
#include "chrome/browser/policy/messaging_layer/util/statusor.h"
namespace reporting {
namespace test {
StatusOr<std::string> TestEncryptionModule::EncryptRecord(
base::StringPiece record) const {
return std::string(record);
}
StatusOr<std::string> AlwaysFailsEncryptionModule::EncryptRecord(
base::StringPiece record) const {
return Status(error::UNKNOWN, "Failing for tests");
}
} // namespace test
} // namespace reporting
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c305ad949e2f362d6d5db7aaab186b20967ce5d8 | bd60b432bd871101c1e2c1dc28fcf695c4940e50 | /Source/BattleTanks/Public/TankTurret.h | 13698e27bfdd0c87cb49d072aaa978593cac61f1 | [] | no_license | setg2002/04_BattleTanks | 1b2e7da456671eecc2c7771e229a34a38f0fda5a | cd880a871b0219b4a6fc577d747784bad909328d | refs/heads/master | 2021-07-14T06:55:03.630232 | 2019-03-05T20:57:06 | 2019-03-05T20:57:06 | 149,185,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/StaticMeshComponent.h"
#include "TankTurret.generated.h"
/**
*
*/
UCLASS( meta = (BlueprintSpawnableComponent) )
class BATTLETANKS_API UTankTurret : public UStaticMeshComponent
{
GENERATED_BODY()
public:
// -1 is max downward speed, and +1 is max up movement
void Rotate(float RelativeSpeed);
private:
UPROPERTY(EditDefaultsOnly, Category = "Setup")
float MaxDegreesPerSecond = 20; // Default
};
| [
"soren.gilbertson13@gmail.com"
] | soren.gilbertson13@gmail.com |
8e477f86d56901db2564fdd0237b8ff96fba6f61 | 48c116c9b62998dbd6d4823cff15e1480783703b | /Class/22.08.20/22.08.20/Source.cpp | 004302903aab59f18750a188d3196e459568f3bc | [] | no_license | Orest3321/C---Base | f28bbc4c4e5dcd213fb134244e30d6b17a68c142 | 9e0e9740abbfd644ecef87824c8d08c880f6d56b | refs/heads/master | 2022-12-03T13:51:03.724087 | 2020-08-22T14:25:35 | 2020-08-22T14:25:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99 | cpp | #include<iostream>
using namespace std;
int main()
{
system("pause");
return 0;
} | [
"mka@rivne.itstep.org"
] | mka@rivne.itstep.org |
adceae0e77b4cc5271094d3eb40aa47f8663c227 | 6197740e6297da2f3d0c8ffd2a1d7ef5d8b3d2cb | /cmake-2.8.12.2/Source/cmGetTargetPropertyCommand.cxx | bacd051a9750ff98f7e0f2d08e681dd8888c91e2 | [
"BSD-3-Clause"
] | permissive | ssh352/cppcode | 1159d4137b68ada253678718b3d416639d3849ba | 5b7c28963286295dfc9af087bed51ac35cd79ce6 | refs/heads/master | 2020-11-24T18:07:17.587795 | 2016-07-15T13:13:05 | 2016-07-15T13:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | cxx | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmGetTargetPropertyCommand.h"
// cmSetTargetPropertyCommand
bool cmGetTargetPropertyCommand
::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
{
if(args.size() != 3 )
{
this->SetError("called with incorrect number of arguments");
return false;
}
std::string var = args[0].c_str();
const char* targetName = args[1].c_str();
const char *prop = 0;
if(args[2] == "ALIASED_TARGET")
{
if(this->Makefile->IsAlias(targetName))
{
if(cmTarget* target =
this->Makefile->FindTargetToUse(targetName))
{
prop = target->GetName();
}
}
}
else if(cmTarget* tgt = this->Makefile->FindTargetToUse(targetName))
{
cmTarget& target = *tgt;
prop = target.GetProperty(args[2].c_str());
}
if (prop)
{
this->Makefile->AddDefinition(var.c_str(), prop);
return true;
}
this->Makefile->AddDefinition(var.c_str(), (var+"-NOTFOUND").c_str());
return true;
}
| [
"qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f"
] | qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f |
2cf5572094068417d5d7eb55cb9b6fc2b25d6242 | 2723bc08dfb2499343e7ba5e3e0edd2ddfb65291 | /lldb/source/Plugins/Process/Windows/DebuggerThread.h | 586a1a76856e4326fa1d5d76d544c6e0827468d4 | [
"NCSA"
] | permissive | Rombur/llvm-project | ff5f223655f8af875eb39651b84b3144d9ca57bc | 2d153d08a9514ca4e602b96f56d94ac38f439a0a | refs/heads/master | 2020-05-29T11:35:25.185427 | 2014-12-09T18:45:30 | 2014-12-09T18:45:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,125 | h | //===-- DebuggerThread.h ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_Plugins_Process_Windows_DebuggerThread_H_
#define liblldb_Plugins_Process_Windows_DebuggerThread_H_
#include "ForwardDecl.h"
#include "lldb/Host/HostProcess.h"
#include "lldb/Host/HostThread.h"
#include "lldb/Host/Predicate.h"
#include "lldb/Host/windows/windows.h"
#include <memory>
namespace lldb_private
{
//----------------------------------------------------------------------
// DebuggerThread
//
// Debugs a single process, notifying listeners as appropriate when interesting
// things occur.
//----------------------------------------------------------------------
class DebuggerThread : public std::enable_shared_from_this<DebuggerThread>
{
public:
DebuggerThread(DebugDelegateSP debug_delegate);
virtual ~DebuggerThread();
Error DebugLaunch(const ProcessLaunchInfo &launch_info);
HostProcess
GetProcess() const
{
return m_process;
}
HostThread
GetMainThread() const
{
return m_main_thread;
}
ExceptionRecord *
GetActiveException()
{
return m_active_exception.get();
}
Error StopDebugging(bool terminate);
void ContinueAsyncException(ExceptionResult result);
private:
void FreeProcessHandles();
void DebugLoop();
ExceptionResult HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info, DWORD thread_id);
DWORD HandleRipEvent(const RIP_INFO &info, DWORD thread_id);
DebugDelegateSP m_debug_delegate;
HostProcess m_process; // The process being debugged.
HostThread m_main_thread; // The main thread of the inferior.
HANDLE m_image_file; // The image file of the process being debugged.
ExceptionRecordUP m_active_exception; // The current exception waiting to be handled
Predicate<ExceptionResult> m_exception_pred; // A predicate which gets signalled when an exception
// is finished processing and the debug loop can be
// continued.
static lldb::thread_result_t DebuggerThreadRoutine(void *data);
lldb::thread_result_t DebuggerThreadRoutine(const ProcessLaunchInfo &launch_info);
};
}
#endif
| [
"zturner@google.com"
] | zturner@google.com |
e9afa857d14c2f627df07c3567b1764e1680850f | c3a2034eaa707b98462b788c2882e105e78a239f | /src/txdb-leveldb.cpp | d88d3b197113cd8db9a296eff36194624bbdd05e | [
"MIT"
] | permissive | nixoncoindev/nixon | da11def9cc6b7fbc02573c2c0f5ccd2781d1ed31 | 992f49841463198559e9f0e5f6a13c22f9f6163e | refs/heads/master | 2021-01-09T20:11:16.738774 | 2017-02-07T19:11:35 | 2017-02-07T19:11:35 | 81,244,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,146 | 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 license.txt or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <boost/version.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <leveldb/env.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
#include <memenv/memenv.h>
#include "kernel.h"
#include "checkpoints.h"
#include "txdb.h"
#include "util.h"
#include "main.h"
using namespace std;
using namespace boost;
leveldb::DB *txdb; // global pointer for LevelDB object instance
static leveldb::Options GetOptions() {
leveldb::Options options;
int nCacheSizeMB = GetArgInt("-dbcache", 25);
options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576);
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
return options;
}
void init_blockindex(leveldb::Options& options, bool fRemoveOld = false) {
// First time init.
filesystem::path directory = GetDataDir() / "txleveldb";
if (fRemoveOld) {
filesystem::remove_all(directory); // remove directory
unsigned int nFile = 1;
while (true)
{
filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
// Break if no such file
if( !filesystem::exists( strBlockFile ) )
break;
filesystem::remove(strBlockFile);
nFile++;
}
}
filesystem::create_directory(directory);
printf("Opening LevelDB in %s\n", directory.string().c_str());
leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
if (!status.ok()) {
throw runtime_error(strprintf("init_blockindex(): error opening database environment %s", status.ToString().c_str()));
}
}
// CDB subclasses are created and destroyed VERY OFTEN. That's why
// we shouldn't treat this as a free operations.
CTxDB::CTxDB(const char* pszMode)
{
assert(pszMode);
activeBatch = NULL;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (txdb) {
pdb = txdb;
return;
}
bool fCreate = strchr(pszMode, 'c');
options = GetOptions();
options.create_if_missing = fCreate;
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
init_blockindex(options); // Init directory
pdb = txdb;
if (Exists(string("version")))
{
ReadVersion(nVersion);
printf("Transaction index version is %d\n", nVersion);
if (nVersion < DATABASE_VERSION)
{
printf("Required index version is %d, removing old database\n", DATABASE_VERSION);
// Leveldb instance destruction
delete txdb;
txdb = pdb = NULL;
delete activeBatch;
activeBatch = NULL;
init_blockindex(options, true); // Remove directory and create new database
pdb = txdb;
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(DATABASE_VERSION); // Save transaction index version
fReadOnly = fTmp;
}
}
else if (fCreate)
{
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(DATABASE_VERSION);
fReadOnly = fTmp;
}
printf("Opened LevelDB successfully\n");
}
void CTxDB::Close()
{
delete txdb;
txdb = pdb = NULL;
delete options.filter_policy;
options.filter_policy = NULL;
delete options.block_cache;
options.block_cache = NULL;
delete activeBatch;
activeBatch = NULL;
}
bool CTxDB::TxnBegin()
{
assert(!activeBatch);
activeBatch = new leveldb::WriteBatch();
return true;
}
bool CTxDB::TxnCommit()
{
assert(activeBatch);
leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
delete activeBatch;
activeBatch = NULL;
if (!status.ok()) {
printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
return false;
}
return true;
}
class CBatchScanner : public leveldb::WriteBatch::Handler {
public:
std::string needle;
bool *deleted;
std::string *foundValue;
bool foundEntry;
CBatchScanner() : foundEntry(false) {}
virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
if (key.ToString() == needle) {
foundEntry = true;
*deleted = false;
*foundValue = value.ToString();
}
}
virtual void Delete(const leveldb::Slice& key) {
if (key.ToString() == needle) {
foundEntry = true;
*deleted = true;
}
}
};
// When performing a read, if we have an active batch we need to check it first
// before reading from the database, as the rest of the code assumes that once
// a database transaction begins reads are consistent with it. It would be good
// to change that assumption in future and avoid the performance hit, though in
// practice it does not appear to be large.
bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
assert(activeBatch);
*deleted = false;
CBatchScanner scanner;
scanner.needle = key.str();
scanner.deleted = deleted;
scanner.foundValue = value;
leveldb::Status status = activeBatch->Iterate(&scanner);
if (!status.ok()) {
throw runtime_error(status.ToString());
}
return scanner.foundEntry;
}
bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
{
assert(!fClient);
txindex.SetNull();
return Read(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
{
assert(!fClient);
return Write(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
{
assert(!fClient);
// Add to tx index
uint256 hash = tx.GetHash();
CTxIndex txindex(pos, tx.vout.size());
return Write(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::EraseTxIndex(const CTransaction& tx)
{
assert(!fClient);
uint256 hash = tx.GetHash();
return Erase(make_pair(string("tx"), hash));
}
bool CTxDB::ContainsTx(uint256 hash)
{
assert(!fClient);
return Exists(make_pair(string("tx"), hash));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
{
assert(!fClient);
tx.SetNull();
if (!ReadTxIndex(hash, txindex))
return false;
return (tx.ReadFromDisk(txindex.pos));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
{
CTxIndex txindex;
return ReadDiskTx(hash, tx, txindex);
}
bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
{
return ReadDiskTx(outpoint.hash, tx, txindex);
}
bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
{
CTxIndex txindex;
return ReadDiskTx(outpoint.hash, tx, txindex);
}
bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
}
bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
{
return Read(string("hashBestChain"), hashBestChain);
}
bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
{
return Write(string("hashBestChain"), hashBestChain);
}
bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
{
return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
{
return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
{
return Read(string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
{
return Write(string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
{
return Read(string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
{
return Write(string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
{
return Read(string("nUpgradeTime"), nUpgradeTime);
}
bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
{
return Write(string("nUpgradeTime"), nUpgradeTime);
}
static CBlockIndex *InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool CTxDB::LoadBlockIndex()
{
if (mapBlockIndex.size() > 0) {
// Already loaded once in this session. It can happen during migration
// from BDB.
return true;
}
// The block index is an in-memory structure that maps hashes to on-disk
// locations where the contents of the block can be found. Here, we scan it
// out of the DB and into mapBlockIndex.
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
ssStartKey << make_pair(string("blockindex"), uint256(0));
iterator->Seek(ssStartKey.str());
// Now read each entry.
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
string strType;
ssKey >> strType;
// Did we reach the end of the data to read?
if (fRequestShutdown || strType != "blockindex")
break;
CDiskBlockIndex diskindex;
ssValue >> diskindex;
uint256 blockHash = diskindex.GetBlockHash();
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
pindexNew->nFile = diskindex.nFile;
pindexNew->nBlockPos = diskindex.nBlockPos;
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nMint = diskindex.nMint;
pindexNew->nMoneySupply = diskindex.nMoneySupply;
pindexNew->nFlags = diskindex.nFlags;
pindexNew->nStakeModifier = diskindex.nStakeModifier;
pindexNew->prevoutStake = diskindex.prevoutStake;
pindexNew->nStakeTime = diskindex.nStakeTime;
pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
// Watch for genesis block
if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
pindexGenesisBlock = pindexNew;
if (!pindexNew->CheckIndex()) {
delete iterator;
return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
}
// NixonCoin: build setStakeSeen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
iterator->Next();
}
delete iterator;
if (fRequestShutdown)
return true;
// Calculate nChainTrust
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
// NixonCoin: calculate stake modifier checksum
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindex->nHeight, pindex->nStakeModifier);
}
// Load hashBestChain pointer to end of best chain
if (!ReadHashBestChain(hashBestChain))
{
if (pindexGenesisBlock == NULL)
return true;
return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
}
if (!mapBlockIndex.count(hashBestChain))
return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
pindexBest = mapBlockIndex[hashBestChain];
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexBest->nChainTrust;
printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// NixonCoin: load hashSyncCheckpoint
if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
// Load bnBestInvalidTrust, OK if it doesn't exist
CBigNum bnBestInvalidTrust;
ReadBestInvalidTrust(bnBestInvalidTrust);
nBestInvalidTrust = bnBestInvalidTrust.getuint256();
// Verify blocks in the best chain
int nCheckLevel = GetArgInt("-checklevel", 1);
int nCheckDepth = GetArgInt( "-checkblocks", 2500);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
// check level 1: verify block validity
// check level 7: verify block signature too
if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
uint256 hashTx = tx.GetHash();
CTxIndex txindex;
if (ReadTxIndex(hashTx, txindex))
{
// check level 3: checker transaction hashes
if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
{
// either an error or a duplicate transaction
CTransaction txFound;
if (!txFound.ReadFromDisk(txindex.pos))
{
printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
else
if (txFound.GetHash() != hashTx) // not a duplicate tx
{
printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
}
// check level 4: check whether spent txouts were spent within the main chain
unsigned int nOutput = 0;
if (nCheckLevel>3)
{
BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
{
if (!txpos.IsNull())
{
pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
if (!mapBlockPos.count(posFind))
{
printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 6: check whether spent txouts were spent by a valid transaction that consume them
if (nCheckLevel>5)
{
CTransaction txSpend;
if (!txSpend.ReadFromDisk(txpos))
{
printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
else if (!txSpend.CheckTransaction())
{
printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
else
{
bool fFound = false;
BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
fFound = true;
if (!fFound)
{
printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
}
}
}
nOutput++;
}
}
}
// check level 5: check whether all prevouts are marked spent
if (nCheckLevel>4)
{
BOOST_FOREACH(const CTxIn &txin, tx.vin)
{
CTxIndex txindex;
if (ReadTxIndex(txin.prevout.hash, txindex))
if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
{
printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
}
}
}
}
}
if (pindexFork && !fRequestShutdown)
{
// Reorg back to the fork
printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
CBlock block;
if (!block.ReadFromDisk(pindexFork))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
CTxDB txdb;
block.SetBestChain(txdb, pindexFork);
}
return true;
}
| [
"nixoncoin@protonmail"
] | nixoncoin@protonmail |
b22839aff57a4bbe0c23e5047dde5b28d0f46894 | db557a30a28f77774cf4662c119a9197fb3ae0a0 | /HelperFunctions/getVkGeometryAABBNV.cpp | 86a5bd76ede73ddf573e5275e8e3f8f18ff09bc5 | [
"Apache-2.0"
] | permissive | dkaip/jvulkan-natives-Linux-x86_64 | b076587525a5ee297849e08368f32d72098ae87e | ea7932f74e828953c712feea11e0b01751f9dc9b | refs/heads/master | 2021-07-14T16:57:14.386271 | 2020-09-13T23:04:39 | 2020-09-13T23:04:39 | 183,515,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,021 | cpp | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.
*/
/*
* getVkGeometryAABBNV.cpp
*
* Created on: Apr 1, 2019
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkGeometryAABBNV(
JNIEnv *env,
const jobject jVkGeometryAABBNVObject,
VkGeometryAABBNV *vkGeometryAABBNV,
std::vector<void *> *memoryToFree)
{
jclass vkGeometryAABBNVClass = env->GetObjectClass(jVkGeometryAABBNVObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
VkStructureType sTypeValue = getSType(env, jVkGeometryAABBNVObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
jobject pNextObject = getpNextObject(env, jVkGeometryAABBNVObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNext failed.");
return;
}
if (pNextObject != nullptr)
{
LOGERROR(env, "%s", "pNext must be null.");
return;
}
void *pNext = nullptr;
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(vkGeometryAABBNVClass, "getAabbData", "()Lcom/CIMthetics/jvulkan/VulkanCore/Handles/VkBuffer;");
if (env->ExceptionOccurred())
{
return;
}
jobject jVkBufferHandleObject = env->CallObjectMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
VkBuffer_T *aabbDataHandle = (VkBuffer_T *)jvulkan::getHandleValue(env, jVkBufferHandleObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkGeometryAABBNVClass, "getNumAABBs", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint numAABBs = env->CallIntMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkGeometryAABBNVClass, "getStride", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint stride = env->CallIntMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkGeometryAABBNVClass, "getOffset", "()J");
if (env->ExceptionOccurred())
{
return;
}
jlong offset = env->CallLongMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
vkGeometryAABBNV->sType = sTypeValue;
vkGeometryAABBNV->pNext = (void *)pNext;
vkGeometryAABBNV->aabbData = aabbDataHandle;
vkGeometryAABBNV->numAABBs = numAABBs;
vkGeometryAABBNV->stride = stride;
vkGeometryAABBNV->offset = offset;
}
}
| [
"dkaip@earthlink.net"
] | dkaip@earthlink.net |
0bb0dc322175d3a9d95dc71b591b535cbfc28f91 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE590_Free_Memory_Not_on_Heap/s01/CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16.cpp | 8efca7a69ba827068e64262e73e3281d5f8a28d3 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,824 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-16.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: static Data buffer is declared static on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 16 Control flow: while(1)
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16
{
#ifndef OMITBAD
void bad()
{
char * data;
data = NULL; /* Initialize data */
while(1)
{
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
static char dataBuffer[100];
memset(dataBuffer, 'A', 100-1); /* fill with 'A's */
dataBuffer[100-1] = '\0'; /* null terminate */
data = dataBuffer;
}
break;
}
printLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */
static void goodG2B()
{
char * data;
data = NULL; /* Initialize data */
while(1)
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
char * dataBuffer = new char[100];
memset(dataBuffer, 'A', 100-1); /* fill with 'A's */
dataBuffer[100-1] = '\0'; /* null terminate */
data = dataBuffer;
}
break;
}
printLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
8c22d629f321ccdddff30c45e76141a155398334 | 6012374a36d037c2b609d99fdefdee087c6e2bfa | /World.h | adb6d904f8a1b8c000ce28edc4b30d054d6f6d24 | [] | no_license | super-nova/Allegro5Framework | c61cefb6e29fb7d9e91493257c5f6036ab3e4927 | 9054c58d88777d8ec861d4429d4fd5b437d4b22c | refs/heads/master | 2020-06-05T18:07:43.732412 | 2012-09-07T18:18:04 | 2012-09-07T18:18:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | h | #pragma once
class Entity;
class BaseComponent;
#include "Entity.h"
#include "BaseComponent.h"
#include <vector>
#include <boost/multi_array.hpp>
using std::vector;
typedef unsigned __int16 uint_16;
typedef uint_16 entityId;
typedef uint_16 componentId;
class World
{
entityId lastid;
componentId lastCompTypeId;
vector<Entity*> ents;
boost::multi_array<BaseComponent*,2> *map;
public:
World(void);
~World(void);
BaseComponent* GetComponent( Entity *ent , componentId id);
void AddComponent( Entity* ent, BaseComponent* comp );
entityId createEntity()
{
return ++lastid;
}
static World& GetInstance()
{
static World w;
return w;
}
};
| [
"super_nova26@hotmail.com"
] | super_nova26@hotmail.com |
e1179e891c8c1cfe2fbc8e13c76543be840f863d | c6563a1fd7008f1bd6b63e71d9a4b1c50ea4a206 | /JewelThief2/Game/MapLoader.cpp | 868c4c207460df27799eaabf9157005a363620f0 | [
"MIT"
] | permissive | Munky665/AIForGames | 7a1a421f88e60384565d45eb646e362f18ab6e65 | 5b77c257c5453df867537b37a5ebf960f90bcc82 | refs/heads/master | 2020-09-22T14:09:58.362779 | 2020-03-03T04:07:13 | 2020-03-03T04:07:13 | 225,225,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,109 | cpp | #include "MapLoader.h"
#include "Room.h"
#include "Player.h"
#include "Collider.cpp"
#include "Tile.h"
#include "Node.h"
MapLoader::MapLoader()
{
//push rooms to list based on number of rooms
for (int i = 0; i < m_numberOfRooms; ++i)
{
m_rooms.push_back(new Room(i));
}
}
MapLoader::~MapLoader()
{
}
//load new room if player collides with doorway
void MapLoader::LoadNextRoom(Player * p)
{
for (Tile* t : m_rooms[m_currentRoom]->GetMap())
{
if (t->GetId() == 4 || t->GetId() == 5)
{
if (CheckCollision(t->GetCollider(), p->GetCollider(), glm::vec2(0, 0)))
{
switch (m_currentRoom)
{
case 0://room 1
//top door to room 2
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 1; //connects line 40
break;
case 1:// room2
//bottom door to room one
if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 0; //connects line 33
}
//right door to room 3
else if (p->GetPosition().x >= m_roomRightPos)
{
p->SetPosition(glm::vec2(m_roomLeftPos, t->GetPosition().y));
m_currentRoom = 2; //connects line 60
}
//top door to room 4
else if (p->GetPosition().y >= m_roomTopPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 3; //connects line 74
}
break;
case 2://room3
//left door to room 2
if (p->GetPosition().x < m_roomLeftPos)
{
p->SetPosition(glm::vec2(m_roomRightPos, t->GetPosition().y));
m_currentRoom = 1; //connects line 46
}
//top door to room 5
else if (p->GetPosition().y >= m_roomTopPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 4; //connects line 88
}
break;
case 3://room4
//bottom door to room 2
if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 1; //connects line 52
}
//right door to room 5
else if (p->GetPosition().x >= m_roomRightPos)
{
p->SetPosition(glm::vec2(m_roomLeftPos, t->GetPosition().y));
m_currentRoom = 4; //connects line 94
}
break;
case 4: //room5
//bottom door to room 3
if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 2; //connects line 66
}
//left door to room
else if (p->GetPosition().x < m_roomLeftPos)
{
p->SetPosition(glm::vec2(m_roomRightPos, t->GetPosition().y));
m_currentRoom = 3;//connects line 80
}
//right door
else if (p->GetPosition().x >= m_roomRightPos)
{
p->SetPosition(glm::vec2(m_roomLeftPos, t->GetPosition().y));
m_currentRoom = 5; //connects line 108
}
break;
case 5: //room6
//left door
if (p->GetPosition().x < m_roomLeftPos)
{
p->SetPosition(glm::vec2(m_roomRightPos, t->GetPosition().y));
m_currentRoom = 4; //connects line 100
}
//bottom door
else if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 6; //connects line 122
}
break;
case 6: //room7
//top door
if (p->GetPosition().y >= m_roomTopPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 5; //connects line 114
}
break;
}
}
}
}
}
//returns current room
Room* MapLoader::GetCurrentRoom()
{
return m_rooms[m_currentRoom];
}
//return room by index
Room* MapLoader::GetRoom(int n)
{
return m_rooms[n];
}
//change current room
void MapLoader::ChangeRoom(int roomNumber)
{
m_currentRoom = roomNumber;
}
//reset the node maps g scores to stop aStar from failing
void MapLoader::ResetGraph()
{
for (int i = 0; i < GetCurrentRoom()->GetMap().size(); ++i)
{
GetCurrentRoom()->GetNodeMap()[i]->gScore = std::numeric_limits<float>::max();
}
} | [
"adam.b.whitty@gmail.com"
] | adam.b.whitty@gmail.com |
54f460049e86385f65f41cffef4f27fb82461349 | d6a66abbeda631e1534141eab6061001c57eb583 | /Prepost_CCP/constant/triSurface/nozzle_down.eMesh | c59e18c378852f2bb74157ea81172bcd65910c0c | [] | no_license | MelodyLiu666/Mold_straightNozzle | 243c265e3e361175d207de185372de2ad9d036e1 | 81c942e6ebdfb949a71bf377385e9294ae4df799 | refs/heads/master | 2021-02-04T11:31:16.108979 | 2020-03-03T12:54:00 | 2020-03-03T12:54:00 | 243,661,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,063 | emesh | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class featureEdgeMesh;
location "constant/triSurface";
object nozzle_down.eMesh;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// points:
128
(
(0.00634 -0.031876 0.5)
(0.012437 -0.030026 0.5)
(0.012437 -0.030026 0.45)
(0.00634 -0.031876 0.45)
(0.012437 0.030026 0.5)
(0.00634 0.031876 0.5)
(0.00634 0.031876 0.45)
(0.012437 0.030026 0.45)
(-0.018056 0.027023 0.5)
(-0.022981 0.022981 0.5)
(-0.022981 0.022981 0.45)
(-0.018056 0.027023 0.45)
(0 -0.0325 0.5)
(-0 -0.0325 0.45)
(0.018056 0.027023 0.5)
(0.018056 0.027023 0.45)
(-0.012437 0.030026 0.5)
(-0.012437 0.030026 0.45)
(-0.00634 -0.031876 0.5)
(-0.00634 -0.031876 0.45)
(0.022981 0.022981 0.5)
(0.022981 0.022981 0.45)
(-0.00634 0.031876 0.5)
(-0.00634 0.031876 0.45)
(-0.012437 -0.030026 0.5)
(-0.012437 -0.030026 0.45)
(0.027023 0.018056 0.5)
(0.027023 0.018056 0.45)
(0 0.0325 0.5)
(-0 0.0325 0.45)
(-0.018056 -0.027023 0.5)
(-0.018056 -0.027023 0.45)
(0.030026 0.012437 0.5)
(0.030026 0.012437 0.45)
(-0.022981 -0.022981 0.5)
(-0.022981 -0.022981 0.45)
(0.031875 0.00634 0.5)
(0.031875 0.00634 0.45)
(-0.027023 -0.018056 0.5)
(-0.027023 -0.018056 0.45)
(0.0325 0 0.5)
(0.0325 -0 0.45)
(-0.030026 -0.012437 0.5)
(-0.030026 -0.012437 0.45)
(0.031875 -0.00634 0.5)
(0.031875 -0.00634 0.45)
(-0.031875 -0.00634 0.5)
(-0.031875 -0.00634 0.45)
(0.030026 -0.012437 0.5)
(0.030026 -0.012437 0.45)
(-0.0325 0 0.5)
(-0.0325 -0 0.45)
(0.027023 -0.018056 0.5)
(0.027023 -0.018056 0.45)
(-0.031875 0.00634 0.5)
(-0.031875 0.00634 0.45)
(0.022981 -0.022981 0.5)
(0.022981 -0.022981 0.45)
(-0.030026 0.012437 0.5)
(-0.030026 0.012437 0.45)
(0.018056 -0.027023 0.5)
(0.018056 -0.027023 0.45)
(-0.027023 0.018056 0.5)
(-0.027023 0.018056 0.45)
(-0.017164 0.003414 0.45)
(-0.0175 0 0.45)
(-0.0175 0 0.5)
(-0.017164 0.003414 0.5)
(0.012374 -0.012374 0.45)
(0.014551 -0.009722 0.45)
(0.014551 -0.009722 0.5)
(0.012374 -0.012374 0.5)
(-0.016168 0.006697 0.45)
(-0.016168 0.006697 0.5)
(0.009722 -0.014551 0.45)
(0.009722 -0.014551 0.5)
(-0.014551 0.009722 0.45)
(-0.014551 0.009722 0.5)
(0.006697 -0.016168 0.45)
(0.006697 -0.016168 0.5)
(0.003414 0.017164 0.45)
(0 0.0175 0.45)
(0 0.0175 0.5)
(0.003414 0.017164 0.5)
(-0.012374 0.012374 0.45)
(-0.012374 0.012374 0.5)
(0.003414 -0.017164 0.45)
(0.003414 -0.017164 0.5)
(0.006697 0.016168 0.45)
(0.006697 0.016168 0.5)
(-0.009722 0.014551 0.45)
(-0.009722 0.014551 0.5)
(-0 -0.0175 0.45)
(-0 -0.0175 0.5)
(0.009722 0.014551 0.45)
(0.009722 0.014551 0.5)
(-0.006697 0.016168 0.45)
(-0.006697 0.016168 0.5)
(-0.003414 -0.017164 0.45)
(-0.003414 -0.017164 0.5)
(0.012374 0.012374 0.45)
(0.012374 0.012374 0.5)
(-0.003414 0.017164 0.45)
(-0.003414 0.017164 0.5)
(-0.006697 -0.016168 0.45)
(-0.006697 -0.016168 0.5)
(0.014551 0.009722 0.45)
(0.014551 0.009722 0.5)
(-0.009722 -0.014551 0.45)
(-0.009722 -0.014551 0.5)
(0.016168 0.006697 0.45)
(0.016168 0.006697 0.5)
(-0.012374 -0.012374 0.45)
(-0.012374 -0.012374 0.5)
(0.017164 0.003414 0.45)
(0.017164 0.003414 0.5)
(-0.014551 -0.009722 0.45)
(-0.014551 -0.009722 0.5)
(0.0175 0 0.45)
(0.0175 0 0.5)
(-0.016168 -0.006697 0.45)
(-0.016168 -0.006697 0.5)
(0.017164 -0.003414 0.45)
(0.017164 -0.003414 0.5)
(-0.017164 -0.003414 0.45)
(-0.017164 -0.003414 0.5)
(0.016168 -0.006697 0.45)
(0.016168 -0.006697 0.5)
)
// edges:
256
(
(65 66)
(67 64)
(69 70)
(71 68)
(73 72)
(75 74)
(77 76)
(79 78)
(81 82)
(83 80)
(85 84)
(87 86)
(89 88)
(91 90)
(93 92)
(95 94)
(97 96)
(99 98)
(101 100)
(103 102)
(105 104)
(107 106)
(109 108)
(111 110)
(113 112)
(115 114)
(117 116)
(119 118)
(121 120)
(123 122)
(125 124)
(127 126)
(1 2)
(3 0)
(5 6)
(7 4)
(9 10)
(11 8)
(13 12)
(15 14)
(17 16)
(19 18)
(21 20)
(23 22)
(25 24)
(27 26)
(29 28)
(31 30)
(33 32)
(35 34)
(37 36)
(39 38)
(41 40)
(43 42)
(45 44)
(47 46)
(49 48)
(51 50)
(53 52)
(55 54)
(57 56)
(59 58)
(61 60)
(63 62)
(6 4)
(10 8)
(3 12)
(7 14)
(19 24)
(21 26)
(23 28)
(25 30)
(35 38)
(37 40)
(45 48)
(47 50)
(49 52)
(55 58)
(57 60)
(59 62)
(71 74)
(73 76)
(85 90)
(87 92)
(89 94)
(101 106)
(103 81)
(105 108)
(113 116)
(115 118)
(125 65)
(127 69)
(2 0)
(11 16)
(13 18)
(15 20)
(17 22)
(27 32)
(31 34)
(33 36)
(39 42)
(41 44)
(43 46)
(51 54)
(53 56)
(61 1)
(29 5)
(63 9)
(66 64)
(70 68)
(67 72)
(75 78)
(82 80)
(77 84)
(79 86)
(83 88)
(91 96)
(93 98)
(95 100)
(97 102)
(99 104)
(107 110)
(109 112)
(111 114)
(117 120)
(119 122)
(121 124)
(123 126)
(0 1)
(2 3)
(4 5)
(6 7)
(8 9)
(10 11)
(12 0)
(3 13)
(14 4)
(7 15)
(16 8)
(11 17)
(18 12)
(13 19)
(20 14)
(15 21)
(22 16)
(17 23)
(24 18)
(19 25)
(26 20)
(21 27)
(28 22)
(23 29)
(30 24)
(25 31)
(32 26)
(27 33)
(34 30)
(31 35)
(36 32)
(33 37)
(38 34)
(35 39)
(40 36)
(37 41)
(42 38)
(39 43)
(44 40)
(41 45)
(46 42)
(43 47)
(48 44)
(45 49)
(50 46)
(47 51)
(52 48)
(49 53)
(54 50)
(51 55)
(56 52)
(53 57)
(58 54)
(55 59)
(60 56)
(57 61)
(62 58)
(59 63)
(1 60)
(61 2)
(5 28)
(29 6)
(9 62)
(63 10)
(64 65)
(66 67)
(68 69)
(70 71)
(72 64)
(67 73)
(74 68)
(71 75)
(76 72)
(73 77)
(78 74)
(75 79)
(80 81)
(82 83)
(84 76)
(77 85)
(86 78)
(79 87)
(88 80)
(83 89)
(90 84)
(85 91)
(92 86)
(87 93)
(94 88)
(89 95)
(96 90)
(91 97)
(98 92)
(93 99)
(100 94)
(95 101)
(102 96)
(97 103)
(104 98)
(99 105)
(106 100)
(101 107)
(81 102)
(103 82)
(108 104)
(105 109)
(110 106)
(107 111)
(112 108)
(109 113)
(114 110)
(111 115)
(116 112)
(113 117)
(118 114)
(115 119)
(120 116)
(117 121)
(122 118)
(119 123)
(124 120)
(121 125)
(126 122)
(123 127)
(65 124)
(125 66)
(69 126)
(127 70)
)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ************************************************************************* //
| [
"xiaoyuliu_neu@163.com"
] | xiaoyuliu_neu@163.com |
8f8eb32af4b815bcddcafcd6756e929e416b64f6 | 298bf79bae0ca3d499b066259f148dbd0e28fce9 | /src/main/cpp/pistis/concurrent/EpollEventType.cpp | 317926f67c703b91b147c58edafb45b8536c9eaf | [
"Apache-2.0"
] | permissive | tomault/pistis-concurrent | 12b54fb4132a05d015db052addc8d1f2a152de83 | ce3206feb3ca42468e35f6d276cd1871c0f9133f | refs/heads/master | 2020-04-11T10:19:29.794117 | 2019-08-25T19:33:51 | 2019-08-25T19:33:51 | 161,710,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include "EpollEventType.hpp"
#include <tuple>
#include <vector>
using namespace pistis::concurrent;
namespace {
static const std::vector< std::tuple<EpollEventType, std::string> >&
eventToNameMap() {
static const std::vector< std::tuple<EpollEventType, std::string> >
EVENT_TO_NAME_MAP{
std::tuple<EpollEventType, std::string>(EpollEventType::READ, "READ"),
std::tuple<EpollEventType, std::string>(EpollEventType::WRITE, "WRITE"),
std::tuple<EpollEventType, std::string>(EpollEventType::READ_HANGUP,
"READ_HANGUP"),
std::tuple<EpollEventType, std::string>(EpollEventType::HANGUP,
"HANGUP"),
std::tuple<EpollEventType, std::string>(EpollEventType::PRIORITY,
"PRIORITY"),
std::tuple<EpollEventType, std::string>(EpollEventType::ERROR, "ERROR")
};
return EVENT_TO_NAME_MAP;
}
}
namespace pistis {
namespace concurrent {
std::ostream& operator<<(std::ostream& out, EpollEventType events) {
if (events == EpollEventType::NONE) {
return out << "NONE";
} else {
int cnt = 0;
for (const auto& event : eventToNameMap()) {
if ((events & std::get<0>(event)) != EpollEventType::NONE) {
if (cnt) {
out << "|";
}
out << std::get<1>(event);
++cnt;
}
}
return out;
}
}
}
}
| [
"ault.tom@gmail.com"
] | ault.tom@gmail.com |
ae73cc115e7d7eef9d0324fdfa347b87c0c77f81 | 85b6258fce5bf77b996800563374e4455b3dd421 | /c++/first.cpp | 131e0cc0179d6f5730197de3ef9c26dd92ceecef | [] | no_license | YaoChungLiang/NTUclass | 09786048d88b37e0d66a87f53397055d3961e2ed | 9e2a597fd9766e27b6695e98238963c7560ae30c | refs/heads/master | 2022-10-25T10:55:20.904284 | 2020-06-19T11:07:53 | 2020-06-19T11:07:53 | 262,518,405 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | cpp |
class Position{
private :
int x;
int y;
public:
Position(int x, int y):x(x),y(y) {} // damn c++ 17, when do we need
void Print() {
// ....
}
void SetX(int x){ // this encapsulate the idea of interface
this->x = x; // x(x) == this-.x = x
}
};
int main(){
Position p(3,5); // Position p = {3,5} if x y are public
p.Print();
// if we want to be p.x = 10, means it to be public
}
| [
"yliang2@uw.edu"
] | yliang2@uw.edu |
a539632454770dbe999b0555f46a77173fee6006 | 1990964ad16e40e560e5796e52725cb395e1e926 | /src/datasets/DataSetClassifier.cpp | 7b3f6f98443cd1c93450e9132568ccebfd9c305a | [] | no_license | tnas/neural-networks | 4775e6337143e0c1e437e6f8142619b94cc6514d | 9ed6d27e9a18c918d715595669ede8756523725f | refs/heads/master | 2020-07-29T03:13:35.919578 | 2019-10-24T18:58:35 | 2019-10-24T18:58:35 | 209,646,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,315 | cpp | #include "../../include/datasets/DataSetClassifier.h"
void DataSetClassifier::buildDataMatrix()
{
this->dataMatrix[0][0] = 0;
this->dataMatrix[0][1] = 1;
this->dataMatrix[1][0] = 0;
this->dataMatrix[1][1] = 2;
this->dataMatrix[2][0] = 1;
this->dataMatrix[2][1] = 1;
this->dataMatrix[3][0] = 1;
this->dataMatrix[3][1] = 2;
this->dataMatrix[4][0] = 1;
this->dataMatrix[4][1] = 3;
this->dataMatrix[5][0] = 2;
this->dataMatrix[5][1] = 2;
this->dataMatrix[6][0] = 2;
this->dataMatrix[6][1] = 3;
this->dataMatrix[7][0] = 3;
this->dataMatrix[7][1] = 2;
this->dataMatrix[8][0] = 4;
this->dataMatrix[8][1] = 1;
this->dataMatrix[9][0] = 4;
this->dataMatrix[9][1] = 3;
this->dataMatrix[10][0] = 0;
this->dataMatrix[10][1] = 3;
this->dataMatrix[11][0] = 2;
this->dataMatrix[11][1] = 0;
this->dataMatrix[12][0] = 2;
this->dataMatrix[12][1] = 1;
this->dataMatrix[13][0] = 3;
this->dataMatrix[13][1] = 0;
this->dataMatrix[14][0] = 3;
this->dataMatrix[14][1] = 1;
this->dataMatrix[15][0] = 3;
this->dataMatrix[15][1] = 3;
this->dataMatrix[16][0] = 4;
this->dataMatrix[16][1] = 0;
this->dataMatrix[17][0] = 4;
this->dataMatrix[17][1] = 2;
this->dataMatrix[18][0] = 5;
this->dataMatrix[18][1] = 0;
this->dataMatrix[19][0] = 5;
this->dataMatrix[19][1] = 1;
this->dataMatrix[20][0] = 5;
this->dataMatrix[20][1] = 2;
this->dataMatrix[21][0] = 5;
this->dataMatrix[21][1] = 3;
}
void DataSetClassifier::defineDesiredOutput()
{
this->desiredOutput[0] = 1;
this->desiredOutput[1] = 1;
this->desiredOutput[2] = 1;
this->desiredOutput[3] = 1;
this->desiredOutput[4] = 1;
this->desiredOutput[5] = 1;
this->desiredOutput[6] = 1;
this->desiredOutput[7] = 1;
this->desiredOutput[8] = 1;
this->desiredOutput[9] = 1;
this->desiredOutput[10] = 1;
this->desiredOutput[11] = -1;
this->desiredOutput[12] = -1;
this->desiredOutput[13] = -1;
this->desiredOutput[14] = -1;
this->desiredOutput[15] = -1;
this->desiredOutput[16] = -1;
this->desiredOutput[17] = -1;
this->desiredOutput[18] = -1;
this->desiredOutput[19] = -1;
this->desiredOutput[20] = -1;
this->desiredOutput[21] = -1;
}
| [
"nascimenthiago@gmail.com"
] | nascimenthiago@gmail.com |
07634842868bb695c4a643d5886a0b4c1d15d82d | e1d6417b995823e507a1e53ff81504e4bc795c8f | /gbk/Common/GameStruct.h | 6cfe483de49b1d4bd0e30d4c3a10f7ce422ecd09 | [] | no_license | cjmxp/pap_full | f05d9e3f9390c2820a1e51d9ad4b38fe044e05a6 | 1963a8a7bda5156a772ccb3c3e35219a644a1566 | refs/heads/master | 2020-12-02T22:50:41.786682 | 2013-11-15T08:02:30 | 2013-11-15T08:02:30 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 36,993 | h |
#ifndef __GAMESTRUCT_H__
#define __GAMESTRUCT_H__
#include "Type.h"
#include "GameDefine.h"
#pragma pack(push, 1)
//用来定义在世界的浮点位置
struct WORLD_POS
{
FLOAT m_fX ;
FLOAT m_fZ ;
WORLD_POS(VOID) : m_fX(0.0f), m_fZ(0.0f) {}
WORLD_POS(FLOAT fX, FLOAT fZ) : m_fX(fX) , m_fZ(fZ) {}
VOID CleanUp( ){
m_fX = 0.0f ;
m_fZ = 0.0f ;
};
WORLD_POS& operator=(WORLD_POS const& rhs)
{
m_fX = rhs.m_fX;
m_fZ = rhs.m_fZ;
return *this;
}
BOOL operator==(WORLD_POS& Ref)
{
return (fabs(m_fX-Ref.m_fX)+fabs(m_fZ-Ref.m_fZ))<0.0001f;
}
BOOL operator==(const WORLD_POS& Ref)
{
return (fabs(m_fX-Ref.m_fX)+fabs(m_fZ-Ref.m_fZ))<0.0001f;
}
};
//用来定义在世界的网格位置
struct MAP_POS
{
Coord_t m_nX ;
Coord_t m_nZ ;
MAP_POS(VOID) : m_nX(0) , m_nZ(0) {}
MAP_POS(Coord_t nX, Coord_t nZ) : m_nX(nX) , m_nZ(nZ) {}
VOID CleanUp( ){
m_nX = 0 ;
m_nX = 0 ;
};
};
//效果状态
struct _EFFECT
{
BOOL m_bActive ;
INT m_Value ; //效果值
INT m_Time ; //效果时间
_EFFECT( )
{
CleanUp( ) ;
}
VOID CleanUp( ){
m_bActive = FALSE ;
m_Value = 0 ;
m_Time = 0 ;
};
BOOL IsActive( ){ return m_bActive ; } ;
VOID SetActive( BOOL bActive ){ m_bActive = bActive ; } ;
};
//怪物生成器初始化数据
struct _MONSTERCREATER_INIT
{
CHAR m_FileName[_MAX_PATH] ;
WORLD_POS m_Position ;
};
#define DEFAULT_ITEMBOX_RECYCLE_TIME 300000 //300秒,5分钟
//装备定义
struct EQUIP_LIST
{
GUID_t m_GUID; //装备类型ID
UINT m_uParam1; //装备属性1
UINT m_uParam2; //装备属性2
};
#define EQUIP_PLAYER_FIXNUM (8) //玩家身上最多可佩戴的装备数
//饰品定义
struct EMBELLISH_LIST
{
GUID_t m_GUID; //饰品类型ID
UINT m_uParam1; //饰品属性1
UINT m_uParam2; //饰品属性2
};
#define EMBELLISH_PLAYER_FIXNUM (6) //玩家身上最多可佩戴的饰品数
//玩家基本序列化信息
struct PLAYER_OWN
{
GUID_t m_nGUID; //玩家完全唯一ID
CHAR m_szName[MAX_CHARACTER_NAME]; //玩家姓名
Coord_t m_nX; //玩家位置X
Coord_t m_nZ; //玩家位置Z
FLOAT m_fDir; //玩家面朝的方向(范围:0~1.0)
//
// 0.25
// \ | /
// 0.5 \ | /
// ---- ---- 0.0 (1.0f)
// / | \
// / | \
// 0.75
PLAYER_OWN( )
{
m_nGUID = INVALID_ID ;
memset( m_szName, 0, MAX_CHARACTER_NAME ) ;
m_nX = 0 ;
m_nZ = 0 ;
m_fDir = 0.0 ;
};
};
struct PLAYER_S
{
GUID_t m_nGUID; //玩家完全唯一ID
CHAR m_szName[MAX_CHARACTER_NAME]; //玩家姓名
Coord_t m_nX; //玩家位置X
Coord_t m_nZ; //玩家位置Z
FLOAT m_fDir; //玩家面朝的方向(范围:0~1.0)
//
// 0.25
// \ | /
// 0.5 \ | /
// ---- ---- 0.0 (1.0f)
// / | \
// / | \
// 0.75
PLAYER_S( )
{
m_nGUID = INVALID_ID ;
memset( m_szName, 0, MAX_CHARACTER_NAME ) ;
m_nX = 0 ;
m_nZ = 0 ;
m_fDir = 0.0 ;
};
};
struct VRECT
{
INT nStartx ;
INT nStartz ;
INT nEndx ;
INT nEndz ;
VRECT( )
{
nStartx = 0 ;
nStartz = 0 ;
nEndx = 0 ;
nEndz = 0 ;
};
BOOL IsContinue( INT x, INT z )const
{
if ( x < nStartx || x > nEndx || z < nStartz || z > nEndz )
return FALSE;
else
return TRUE;
}
};
//一级战斗属性结构
struct _ATTR_LEVEL1
{
INT m_pAttr[CATTR_LEVEL1_NUMBER] ;
_ATTR_LEVEL1( )
{
CleanUp( ) ;
};
INT Get( INT iAttr )const{
Assert( iAttr>=0 && iAttr<CATTR_LEVEL1_NUMBER ) ;
return m_pAttr[iAttr] ;
};
VOID Set( INT iAttr, INT iValue ){
Assert( iAttr>=0 && iAttr<CATTR_LEVEL1_NUMBER ) ;
m_pAttr[iAttr] = iValue ;
} ;
VOID CleanUp()
{
memset( m_pAttr, 0, sizeof(INT)*CATTR_LEVEL1_NUMBER ) ;
} ;
};
//二级战斗属性结构
struct _ATTR_LEVEL2
{
INT m_pAttr[CATTR_LEVEL2_NUMBER] ;
_ATTR_LEVEL2( )
{
memset( m_pAttr, 0, sizeof(INT)*CATTR_LEVEL2_NUMBER ) ;
}
INT Get( INT iAttr ){
Assert( iAttr>=0 && iAttr<CATTR_LEVEL2_NUMBER ) ;
return m_pAttr[iAttr] ;
};
VOID Set( INT iAttr, INT iValue ){
Assert( iAttr>=0 && iAttr<CATTR_LEVEL2_NUMBER ) ;
m_pAttr[iAttr] = iValue ;
} ;
};
//角色所拥有的称号
//#开头的字符串代表是一个字符串资源ID,必须通过表格索引,服务器不用保留这个表格
#define IDTOSTRING(str, strid, strsize) char str[strsize];\
memset(str, 0, strsize);\
sprintf(str, "#%d", strid);\
#define STRINGTOID(str, strid) INT strid = atoi((CHAR*)(str+1));\
struct _TITLE
{
enum
{
NO_TITLE = -1,
GUOJIA_TITLE = 1, //国家称号
BANGPAI_TITLE, //帮派称号
WANFA_TITLE, //玩法称号
MOOD_TITLE, //玩家心情
MAX_NUM_TITLE,
};
struct TITLE_INFO
{
INT m_iTitleID;
INT m_iSuitID; //组合称号ID 单一称号填-1
INT m_iTitleType; //称号类型 国家,帮会,玩法称号
INT m_iBuffID; //称号的BUFFid
UINT m_uTime; //时限title到期时间,无限期的用0
//CHAR m_szFemaleName[32];
//CHAR m_szMaleName[32];
TITLE_INFO()
{
m_iTitleID = INVALID_ID;
m_iSuitID = INVALID_ID;
m_iTitleType= INVALID_ID;
m_iBuffID = INVALID_ID;
m_uTime = 0;
//memset(m_szFemaleName, 0, sizeof(m_szFemaleName));
//memset(m_szMaleName, 0, sizeof(m_szMaleName));
}
};
struct TITLE_COMBINATION //组成称号信息
{
INT m_iGroupID;
INT m_comTitleID;
INT m_arPart[MAX_TITLE_COMBINATION]; //组合成员上限10个
TITLE_COMBINATION ()
{
m_comTitleID = INVALID_ID;
memset(m_arPart, 0, sizeof(INT)*MAX_TITLE_COMBINATION);
}
};
public:
INT m_CurCountryTitle; //当前国家称号ID 无效均为-1
INT m_CurGuildTitle; //当前帮派称号ID 无效均为-1
INT m_CurNormalTitle; //当前普通称号ID 无效均为-1
TITLE_INFO m_TitleArray[MAX_TITLE_SIZE];
CHAR m_szCurCountryTitle[MAX_CHARACTER_TITLE]; //当前国家称号
CHAR m_szCurGuildTitle[MAX_CHARACTER_TITLE]; //当前帮会称号
CHAR m_szCurNormalTitle[MAX_CHARACTER_TITLE]; //当前玩法称号
CHAR m_szOfficialTitleName[MAX_CHARACTER_TITLE]; //自定义官职称号
VOID CleanUp()
{
m_CurCountryTitle = -1;
m_CurGuildTitle = -1;
m_CurNormalTitle = -1;
memset((void*)m_TitleArray, -1, sizeof(TITLE_INFO)*MAX_TITLE_SIZE);
memset((void*)m_szOfficialTitleName, 0, MAX_CHARACTER_TITLE);
memset((void*)m_szCurCountryTitle, 0, MAX_CHARACTER_TITLE);
memset((void*)m_szCurGuildTitle, 0, MAX_CHARACTER_TITLE);
memset((void*)m_szCurNormalTitle, 0, MAX_CHARACTER_TITLE);
}
};
struct ITEM_PICK_CTL
{
ObjID_t OwnerID; //最终的拾取者ID
uint uBetTime; //系统赌博时间
UCHAR uMaxBetPoint; //最大Bet点数
PICK_RULER ePickRuler; //系统控制符号
ITEM_PICK_CTL()
{
CleanUp();
}
VOID CleanUp()
{
OwnerID = INVALID_ID; //无所有者
ePickRuler = IPR_FREE_PICK; //自由拾取
uBetTime = 0; //可以拾取
uMaxBetPoint = 0;
}
};
typedef ITEM_PICK_CTL IPC;
#define MAX_PICKER_COUNT 6
//队伍能参与拾取的人员列表
struct TEAM_PICKER
{
UINT m_uCount;
ObjID_t m_PickerID[MAX_PICKER_COUNT];
TEAM_PICKER()
{
memset(this,0,sizeof(TEAM_PICKER));
}
VOID AddPicker(ObjID_t id)
{
for(UINT nIndex=0;nIndex<m_uCount;nIndex++)
{
if(m_PickerID[nIndex]==id)
return;
}
m_PickerID[m_uCount] = id;
m_uCount++;
}
};
//最大伤害纪录
#define MAX_DAMAGE_REC_COUNT 10
//伤害纪录
struct DAMAGE_RECORD
{
GUID_t m_Killer;
ObjID_t m_KillerObjID;
TeamID_t m_TeamID;
UINT m_uDamage;
DAMAGE_RECORD()
{
CleanUp();
}
void CleanUp()
{
m_Killer = INVALID_ID;
m_KillerObjID = INVALID_ID;
m_TeamID = INVALID_ID;
m_uDamage = 0;
}
};
//伤害队列
struct DAMAGE_MEM_LIST
{
UINT m_uCount;
DAMAGE_RECORD m_DamageRec[MAX_DAMAGE_REC_COUNT];
DAMAGE_MEM_LIST()
{
CleanUp();
}
void CleanUp()
{
m_uCount = 0;
for(int i = 0;i<MAX_DAMAGE_REC_COUNT;i++)
m_DamageRec[i].CleanUp();
}
void AddMember(GUID_t KillerID, ObjID_t KillerObjID, TeamID_t KillerTeam, UINT Damage)
{
if(KillerTeam!=INVALID_ID)
{
m_DamageRec[m_uCount].m_Killer = KillerID;
m_DamageRec[m_uCount].m_KillerObjID = KillerObjID;
m_DamageRec[m_uCount].m_TeamID = KillerTeam;
m_DamageRec[m_uCount].m_uDamage = Damage;
}
else
{
m_DamageRec[m_uCount].m_Killer = KillerID;
m_DamageRec[m_uCount].m_KillerObjID = KillerObjID;
m_DamageRec[m_uCount].m_TeamID = INVALID_ID;
m_DamageRec[m_uCount].m_uDamage = Damage;
}
m_uCount++;
}
void AddMember(DAMAGE_RECORD& dRec)
{
if(dRec.m_TeamID!=INVALID_ID)
{
m_DamageRec[m_uCount].m_Killer = dRec.m_Killer;
m_DamageRec[m_uCount].m_TeamID = dRec.m_TeamID;
m_DamageRec[m_uCount].m_uDamage = dRec.m_uDamage;
}
else
{
m_DamageRec[m_uCount].m_Killer = dRec.m_Killer;
m_DamageRec[m_uCount].m_TeamID = INVALID_ID;
m_DamageRec[m_uCount].m_uDamage = dRec.m_uDamage;
}
m_uCount++;
}
DAMAGE_RECORD* FindMember(GUID_t KillerID)
{
for(UINT i =0;i<m_uCount;i++)
{
if(m_DamageRec[i].m_Killer == KillerID && KillerID!=INVALID_ID)
{
return &m_DamageRec[i];
}
}
return NULL;
}
};
struct _OWN_ABILITY
{
// AbilityID_t m_Ability_ID; 不需要 ID,索引就是 ID
WORD m_Level; // 技能等级
WORD m_Exp; // 技能熟练度
};
#define MAX_MONSTER_DROP_TASK_ITEM 5
#define MAX_MONSTER_KILLER_NUM 18
struct CHAR_OWNER_DROP_LIST
{
ObjID_t HumanID;
UINT DropItemIndex[MAX_MONSTER_DROP_TASK_ITEM];
UINT DropCount;
CHAR_OWNER_DROP_LIST()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
VOID AddItem(UINT ItemIndex)
{
Assert(DropCount<MAX_MONSTER_DROP_TASK_ITEM);
DropItemIndex[DropCount] = ItemIndex;
DropCount++;
}
};
struct OWNERCHARACTER
{
GUID_t m_Guid;
ObjID_t m_ObjID;
};
struct MONSTER_OWNER_LIST
{
OWNERCHARACTER OwnerDropList[MAX_TEAM_MEMBER];
UINT OwnerCount;
MONSTER_OWNER_LIST()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
VOID AddOwner(GUID_t HumanID, ObjID_t HumanObjID)
{
if(OwnerCount == MAX_TEAM_MEMBER)
return;
BOOL bAlive = FALSE;
for(UINT i=0; i<OwnerCount; ++i)
{
if(OwnerDropList[i].m_Guid == HumanID)
{
bAlive = TRUE;
}
}
if(!bAlive)
{
OwnerDropList[OwnerCount].m_Guid = HumanID;
OwnerDropList[OwnerCount].m_ObjID = HumanObjID;
OwnerCount++;
}
}
};
struct RELATION_MEMBER
{
GUID_t m_MemberGUID ;
CHAR m_szMemberName[MAX_CHARACTER_NAME] ;
INT m_nLevel; //角色等级
INT m_nMenPai; //门派 MENPAI_ATTRIBUTE
INT m_nPortrait; // 头像
GuildID_t m_GuildID; //帮会ID
struct ReMember_ExtData
{
INT m_nLevel; //角色等级
INT m_nMenPai; //门派 MENPAI_ATTRIBUTE
INT m_nPortrait; //头像
GuildID_t m_GuildID; //帮会ID
};
RELATION_MEMBER( )
{
CleanUp( );
};
VOID CleanUp( )
{
m_MemberGUID = INVALID_ID;
memset( m_szMemberName, 0, sizeof(m_szMemberName) );
m_nLevel = 0;
m_nMenPai = INVALID_JOB;
m_nPortrait = -1;
m_GuildID = INVALID_ID;
};
ReMember_ExtData GetExtData()
{
ReMember_ExtData ExtData;
ExtData.m_nLevel = m_nLevel;
ExtData.m_nMenPai = m_nMenPai;
ExtData.m_nPortrait = m_nPortrait;
ExtData.m_GuildID = m_GuildID;
return ExtData;
}
VOID SetExtData(ReMember_ExtData& ExtData)
{
m_nLevel = ExtData.m_nLevel;
m_nMenPai = ExtData.m_nMenPai;
m_nPortrait = ExtData.m_nPortrait;
m_GuildID = ExtData.m_GuildID;
}
};
struct MarriageInfo
{
GUID_t m_SpouseGUID; // 配偶的 GUID
// UINT m_uWeddingTime; // 婚礼时间
MarriageInfo()
{
CleanUp();
}
VOID CleanUp()
{
m_SpouseGUID = INVALID_ID;
}
};
struct PrenticeInfo
{
// UINT m_uRecruitingTime; // 收徒时间
time_t m_BetrayingTime; // 最后一次叛师时间
UINT m_uMoralPoint; // 师德点
UCHAR m_uPrenticeCount; // 徒弟数量
GUID_t m_PrenticeGUID[MAX_PRENTICE_COUNT]; // 徒弟的 GUID
PrenticeInfo()
{
CleanUp();
}
VOID CleanUp()
{
m_BetrayingTime = 0;
m_uMoralPoint = 0;
m_uPrenticeCount = 0;
for( INT i=0; i<MAX_PRENTICE_COUNT; ++i )
{
m_PrenticeGUID[i] = INVALID_ID;
}
}
};
struct MasterInfo
{
GUID_t m_MasterGUID; // 师傅的 GUID
// UINT m_uApprenticingTime; // 拜师时间
// UINT m_uBetrayingTime; // 上次叛师时间
// UINT m_uBetrayTimes; // 叛师次数
MasterInfo()
{
CleanUp();
}
VOID CleanUp()
{
m_MasterGUID = INVALID_ID;
}
};
class SocketOutputStream ;
class SocketInputStream ;
//邮件
struct MAIL
{
struct MailInfo
{
GUID_t m_GUID; // 发信人 GUID
BYTE m_SourSize ;
INT m_nPortrait; // 发信人头像
BYTE m_DestSize ;
WORD m_ContexSize ;
UINT m_uFlag ; //邮件标志 enum MAIL_TYPE
time_t m_uCreateTime ; //邮件创建时间
//执行邮件应用参数
UINT m_uParam0 ;
UINT m_uParam1 ;
UINT m_uParam2 ;
UINT m_uParam3 ;
};
VOID GetMailInfo(MailInfo& mInfo)
{
mInfo.m_GUID = m_GUID;
mInfo.m_SourSize = m_SourSize;
mInfo.m_nPortrait = m_nPortrait;
mInfo.m_DestSize = m_DestSize;
mInfo.m_ContexSize = m_ContexSize;
mInfo.m_uFlag = m_uFlag;
mInfo.m_uCreateTime = m_uCreateTime;
mInfo.m_uParam0 = m_uParam0;
mInfo.m_uParam1 = m_uParam1;
mInfo.m_uParam2 = m_uParam2;
mInfo.m_uParam3 = m_uParam3;
}
VOID SetMailInfo(MailInfo& mInfo)
{
m_GUID = mInfo.m_GUID;
m_SourSize = mInfo.m_SourSize;
m_nPortrait = mInfo.m_nPortrait;
m_DestSize = mInfo.m_DestSize;
m_ContexSize = mInfo.m_ContexSize;
m_uFlag = mInfo.m_uFlag;
m_uCreateTime = mInfo.m_uCreateTime;
m_uParam0 = mInfo.m_uParam0;
m_uParam1 = mInfo.m_uParam1;
m_uParam2 = mInfo.m_uParam2;
m_uParam3 = mInfo.m_uParam3;
}
GUID_t m_GUID; // 发信人 GUID
BYTE m_SourSize ;
CHAR m_szSourName[MAX_CHARACTER_NAME] ; //发信人
INT m_nPortrait; // 发信人头像
BYTE m_DestSize ;
CHAR m_szDestName[MAX_CHARACTER_NAME] ; //收信人
WORD m_ContexSize ;
CHAR m_szContex[MAX_MAIL_CONTEX] ; //内容
UINT m_uFlag ; //邮件标志 enum MAIL_TYPE
time_t m_uCreateTime ; //邮件创建时间
//执行邮件应用参数
UINT m_uParam0 ;
UINT m_uParam1 ;
UINT m_uParam2 ;
UINT m_uParam3 ;
MAIL( )
{
CleanUp( ) ;
};
VOID CleanUp( )
{
m_GUID = INVALID_INDEX;
m_SourSize = 0 ;
memset( m_szSourName, 0, sizeof(CHAR)*MAX_CHARACTER_NAME ) ;
m_nPortrait = -1;
m_DestSize = 0 ;
memset( m_szDestName, 0, sizeof(CHAR)*MAX_CHARACTER_NAME ) ;
m_ContexSize = 0 ;
memset( m_szContex, 0, sizeof(CHAR)*MAX_MAIL_CONTEX ) ;
m_uFlag = MAIL_TYPE_NORMAL ;
m_uCreateTime = 0 ;
m_uParam0 = 0 ;
m_uParam1 = 0 ;
m_uParam2 = 0 ;
m_uParam3 = 0 ;
};
VOID Read( SocketInputStream& iStream ) ;
VOID Write( SocketOutputStream& oStream ) const ;
};
#define MAX_MAIL_SIZE 20
struct MAIL_LIST
{
MAIL m_aMail[MAX_MAIL_SIZE] ;
BYTE m_Count ;//邮件数量
BYTE m_TotalLeft ;//用户帐号里的邮件剩余数量
MAIL_LIST( )
{
CleanUp( ) ;
};
VOID CleanUp( )
{
m_Count = 0 ;
m_TotalLeft = 0 ;
for( INT i=0;i<MAX_MAIL_SIZE; i++ )
{
m_aMail[i].CleanUp() ;
}
};
VOID Read( SocketInputStream& iStream ) ;
VOID Write( SocketOutputStream& oStream ) const ;
};
// 批量邮件,指发送给不同人的同内容邮件
#define MAX_RECEIVER 100
struct BATCH_MAIL
{
GUID_t m_GUID; // GUID
BYTE m_SourSize;
CHAR m_szSourName[MAX_CHARACTER_NAME]; //发信人
BYTE m_ReceiverCount; //收信人数量
struct
{
BYTE m_DestSize;
CHAR m_szDestName[MAX_CHARACTER_NAME]; //收信人
}m_Receivers[MAX_RECEIVER];
WORD m_ContentSize;
CHAR m_szContent[MAX_MAIL_CONTEX]; //内容
UCHAR m_uFlag; //邮件标志 enum MAIL_TYPE
time_t m_uCreateTime; //邮件创建时间
BATCH_MAIL() { CleanUp(); }
GUID_t GetGUID( )
{
return m_GUID;
}
VOID SetGUID( GUID_t guid )
{
m_GUID = guid;
}
const CHAR* GetSourName()
{
return m_szSourName;
}
VOID SetSourName( const CHAR* szName )
{
strncpy(m_szSourName, szName, MAX_CHARACTER_NAME - 1);
m_SourSize = (UCHAR)strlen(m_szSourName);
}
BYTE GetReceiverCount()
{
return m_ReceiverCount;
}
const CHAR* GetDestName(BYTE idx)
{
if( idx >= m_ReceiverCount )
{
Assert( idx );
return NULL;
}
return m_Receivers[idx].m_szDestName;
}
VOID AddDestName( const CHAR* szName )
{
strncpy(m_Receivers[m_ReceiverCount].m_szDestName, szName, MAX_CHARACTER_NAME - 1);
m_Receivers[m_ReceiverCount].m_DestSize = (UCHAR)strlen(m_Receivers[m_ReceiverCount].m_szDestName);
++m_ReceiverCount;
}
const CHAR* GetMailContent()
{
return m_szContent;
}
VOID SetMailContent( const CHAR* szContent )
{
strncpy(m_szContent, szContent, MAX_MAIL_CONTEX - 1);
m_ContentSize = (UCHAR)strlen(m_szContent);
}
UCHAR GetMailFlag()
{
return m_uFlag;
}
VOID SetMailFlag(UCHAR uFlag)
{
m_uFlag = uFlag;
}
time_t GetCreateTime()
{
return m_uCreateTime;
}
VOID SetCreateTime(time_t uCreateTime)
{
m_uCreateTime = uCreateTime;
}
VOID CleanUp();
UINT GetSize() const;
VOID Read( SocketInputStream& iStream );
VOID Write( SocketOutputStream& oStream ) const;
};
struct USER_SIMPLE_DATA
{
CHAR m_Name[MAX_CHARACTER_NAME]; // 此用户的角色名字
CHAR m_Account[MAX_ACCOUNT_LENGTH]; // 此角色所在账号
GUID_t m_GUID; // 此用户的唯一号
INT m_nCountry; // 国家
UINT m_uMenPai; // 门派
INT m_nPortrait; // 头像
UCHAR m_uFaceMeshID; // 脸部模型
UCHAR m_uHairMeshID; // 头发模型
UINT m_uHairColor; // 发色
INT m_nLevel; // 级别
USHORT m_uSex; // 性别
CHAR m_szTitle[MAX_CHARACTER_TITLE]; // 称号
GuildID_t m_GuildID; // 帮会 ID
CHAR m_szGuildName[MAX_GUILD_NAME_SIZE]; // 帮会名字
CHAR m_szFamilyName[MAX_GUILD_FAMILY_NAME_SIZE]; // 家族名字
INT m_iPostCode; // 邮编号
UINT m_uMoney; //角色身上货币
UINT m_uBankMoney; //角色银行货币
USER_SIMPLE_DATA( )
{
CleanUp( ) ;
}
VOID CleanUp( )
{
memset( m_Name, 0, sizeof(m_Name) );
memset( m_Account, 0, sizeof(m_Account) );
m_GUID = INVALID_ID;
m_nCountry = INVALID_COUNTRY;
m_uMenPai = INVALID_JOB;
m_nPortrait = -1;
m_nLevel = 0;
m_uSex = 0;
memset( m_szTitle, 0, sizeof(m_szTitle) );
memset( m_szGuildName, 0, sizeof(m_szGuildName));
memset( m_szFamilyName, 0, sizeof(m_szFamilyName));
m_GuildID = INVALID_ID;
m_iPostCode = 0;
m_uMoney = 0;
m_uBankMoney = 0;
}
};
#define MAX_SQL_LENGTH 4096
#define MAX_LONG_SQL_LENGTH 204800
struct DB_QUERY
{
UCHAR m_SqlStr[MAX_SQL_LENGTH]; //执行的Sql语句
VOID Clear()
{
memset(m_SqlStr,0,MAX_SQL_LENGTH);
}
VOID Parse(const CHAR* pTemplate,...);
};
struct LONG_DB_QUERY
{
UCHAR m_SqlStr[MAX_LONG_SQL_LENGTH]; //执行的Sql语句
VOID Clear()
{
memset(m_SqlStr,0,MAX_LONG_SQL_LENGTH);
}
VOID Parse(const CHAR* pTemplate,...);
};
struct DB_CHAR_EQUIP_LIST
{
DB_CHAR_EQUIP_LIST()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
UINT m_Equip[HEQUIP_NUMBER]; //装备
};
struct DB_CHAR_BASE_INFO
{
DB_CHAR_BASE_INFO()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
m_Menpai = INVALID_JOB; //角色门派
m_Country = INVALID_COUNTRY; //国家
m_Sex = INVALID_SEX;
}
GUID_t m_GUID; //角色全局编号
BYTE m_Sex; //性别
CHAR m_Name[MAX_CHARACTER_NAME]; //角色名字
INT m_Level; //角色等级
UINT m_HairColor; //头发颜色
BYTE m_FaceColor; //脸形颜色
BYTE m_HairModel; //头发模型
BYTE m_FaceModel; //脸形模型
SceneID_t m_StartScene; //角色所在场景
INT m_Menpai; //角色门派
INT m_HeadID; //头部编号
DB_CHAR_EQUIP_LIST m_EquipList; //装备列表
INT m_Country; //国家
};
// 队员列表中的队员信息项
struct TEAM_LIST_ENTRY
{
GUID_t m_GUID; // GUID
SceneID_t m_SceneID; // 场景ID
ID_t m_SceneResID; // 场景资源 ID
UINT m_ExtraID; // 队员的 PlayerID(WG) 或 ObjID(GC)
UCHAR m_NameSize; // 姓名长度
CHAR m_Name[MAX_CHARACTER_NAME]; // 队员的名字
INT m_nPortrait; // 头像
USHORT m_uDataID; // 队员的性别
UINT m_uFamily; // 2.门派
TEAM_LIST_ENTRY( )
{
CleanUp( );
};
VOID CleanUp( )
{
m_GUID = INVALID_ID;
m_SceneID = INVALID_ID;
m_SceneResID = INVALID_ID;
m_ExtraID = INVALID_ID;
m_NameSize = 0;
memset (m_Name, 0, sizeof(m_Name));
m_nPortrait = -1;
m_uDataID = 0;
m_uFamily = 0;
};
TEAM_LIST_ENTRY& operator= ( const TEAM_LIST_ENTRY& entry )
{
m_GUID = entry.m_GUID;
m_SceneID = entry.m_SceneID;
m_SceneResID = entry.m_SceneResID;
m_ExtraID = entry.m_ExtraID;
m_NameSize = entry.m_NameSize;
strncpy ( m_Name, entry.m_Name, sizeof(m_Name) - 1 );
m_nPortrait = entry.m_nPortrait;
m_uDataID = entry.m_uDataID;
m_uFamily = entry.m_uFamily;
return *this;
}
VOID SetGUID( GUID_t guid ) { m_GUID = guid; }
GUID_t GetGUID( ) const { return m_GUID; }
VOID SetSceneID( SceneID_t SceneID ) { m_SceneID = SceneID; }
SceneID_t GetSceneID( ) const { return m_SceneID; }
VOID SetSceneResID( ID_t SceneID ) { m_SceneResID = SceneID; }
ID_t GetSceneResID( ) const { return m_SceneResID; }
VOID SetExtraID( UINT id ) { m_ExtraID = id; }
UINT GetExtraID( ) const { return m_ExtraID; }
VOID SetName( const CHAR* pName )
{
strncpy ( m_Name, pName, MAX_CHARACTER_NAME-1 );
m_NameSize = (UCHAR)strlen(m_Name);
}
const CHAR* GetName( ) const { return m_Name; }
VOID SetIcon( INT icon ) { m_nPortrait = icon; }
INT GetIcon( ) const { return m_nPortrait; }
VOID SetDataID(USHORT dataid) { m_uDataID = dataid; }
USHORT GetDataID() const { return m_uDataID; }
VOID SetFamily(UINT uFamily) { m_uFamily = uFamily; }
UINT GetFamily() const { return m_uFamily; }
UINT GetSize() const;
VOID Read( SocketInputStream& iStream );
VOID Write( SocketOutputStream& oStream ) const;
};
//ID List
typedef struct _ObjID_List
{
enum
{
MAX_LIST_SIZE = 512,
};
_ObjID_List()
{
CleanUp();
}
VOID CleanUp(VOID)
{
m_nCount=0;
memset((VOID*)m_aIDs, INVALID_ID, sizeof(m_aIDs));
}
INT m_nCount;
ObjID_t m_aIDs[MAX_LIST_SIZE];
} ObjID_List;
//玩家商店的唯一ID
struct _PLAYERSHOP_GUID
{
ID_t m_World ; //世界号:
ID_t m_Server ; //服务端程序号:
ID_t m_Scene ; //场景号
INT m_PoolPos ; //数据池位置
_PLAYERSHOP_GUID()
{
Reset();
}
_PLAYERSHOP_GUID& operator=(_PLAYERSHOP_GUID const& rhs)
{
m_PoolPos = rhs.m_PoolPos;
m_Server = rhs.m_Server;
m_World = rhs.m_World;
m_Scene = rhs.m_Scene;
return *this;
}
BOOL operator ==(_PLAYERSHOP_GUID& Ref) const
{
return (Ref.m_Scene==m_Scene)&&(Ref.m_PoolPos==m_PoolPos)&&(Ref.m_Server==m_Server)&&(Ref.m_World==m_World);
}
BOOL isNull() const
{
return (m_Scene ==INVALID_ID)&&(m_World ==INVALID_ID)&&(m_PoolPos==-1)&&(m_Server == INVALID_ID);
}
VOID Reset()
{
m_PoolPos = -1;
m_Server = INVALID_ID;
m_World = INVALID_ID;
m_Scene = INVALID_ID;
}
};
enum SM_COMMANDS
{
CMD_UNKNOW,
CMD_SAVE_ALL,
CMD_CLEAR_ALL,
};
struct SM_COMMANDS_STATE
{
SM_COMMANDS cmdType;
union
{
INT iParam[6];
FLOAT fParam[6];
CHAR cParam[24];
};
};
struct GLOBAL_CONFIG
{
GLOBAL_CONFIG()
{
Commands.cmdType = CMD_UNKNOW;
}
SM_COMMANDS_STATE Commands;
};
//密保相关
#define MIBAOUNIT_NAME_LENGTH 2 //每个键值的长度
#define MIBAOUNIT_VALUE_LENGTH 2 //每个数值的长度
#define MIBAOUNIT_NUMBER 3 //密保卡一组有效数据的密保单元个数
//7×7
#define MIBAO_TABLE_ROW_MAX 7 //密保使用的表的最大行数
#define MIBAO_TABLE_COLUMN_MAX 7 //密保使用的表的最大列数
//密保单元
struct MiBaoUint
{
BYTE row;
BYTE column;
CHAR key[MIBAOUNIT_NAME_LENGTH+1];
CHAR value[MIBAOUNIT_VALUE_LENGTH+1];
MiBaoUint()
{
CleanUp();
}
VOID CleanUp()
{
row = column = BYTE_MAX;
memset(key,0,MIBAOUNIT_NAME_LENGTH+1);
memset(value,0,MIBAOUNIT_VALUE_LENGTH+1);
}
BOOL IsSame(const MiBaoUint& mu) const
{
if(row >= MIBAO_TABLE_ROW_MAX || column >= MIBAO_TABLE_COLUMN_MAX) return FALSE;
return (row == mu.row && column == mu.column)?TRUE:FALSE;
}
};
//创建人物验证码
struct CreateCode
{
USHORT code[ANASWER_LENGTH_1];
CreateCode()
{
CleanUp();
}
VOID CleanUp()
{
memset(code,0,sizeof(USHORT)*ANASWER_LENGTH_1);
}
BOOL IsSame(CreateCode* pcd)
{
//CreateCode tmp;
//if(memcmp(code,tmp.code,sizeof(USHORT)*ANASWER_LENGTH_1) == 0)
// return FALSE;
if(!pcd) return FALSE;
return (memcmp(code,pcd->code,sizeof(USHORT)*ANASWER_LENGTH_1) == 0);
}
};
//一组密保数据
struct MiBaoGroup
{
MiBaoUint unit[MIBAOUNIT_NUMBER];
MiBaoGroup()
{
CleanUp();
}
VOID CleanUp()
{
for(INT i = 0; i < MIBAOUNIT_NUMBER; ++i) unit[i].CleanUp();
}
BOOL IsAlreadyHaveUnit(BYTE row,BYTE column)
{
if(/*row < 0 || */row >= MIBAO_TABLE_ROW_MAX || /*column < 0 || */column >= MIBAO_TABLE_COLUMN_MAX) return TRUE;
MiBaoUint tu;
tu.row = row;
tu.column = column;
for(INT i = 0; i < MIBAOUNIT_NUMBER; ++i)
{
if(TRUE == unit[i].IsSame(tu)) return TRUE;
}
return FALSE;
}
const CHAR* GetMiBaoKey(INT idx) const
{
if(idx < 0 || idx >= MIBAOUNIT_NUMBER) return NULL;
return unit[idx].key;
}
};
//////////////////////////////////////////////////////
// 抽奖相关操作数据
//////////////////////////////////////////////////////
#define MAX_PRIZE_STRING 20 //参见《天龙八部推广员帐号领奖通信协议》中的奖品代码长度定义
#define MAX_PRIZE_NUMBER 30 //一次最多领30个不同种类的奖品
#define MAX_NEWUSER_CARD_SIZE 20 //新手卡长度
enum PRIZE_TYPE_ENUM
{
PRIZE_TYPE_INVALID = 0,
PRIZE_TYPE_CDKEY = 1, //推广员
PRIZE_TYPE_YUANBAO = 2, //元宝
PRIZE_TYPE_NEWUSER = 3, //新手卡(财富卡)
PRIZE_TYPE_ZENGDIAN = 4, //赠点
PRIZE_TYPE_ITEM = 5, //物品
PRIZE_TYPE_SPORTS = 6, //体育竞猜卡
PRIZE_TYPE_JU = 7, //网聚活动卡
};
//Billing返回的奖品结构
struct _PRIZE_DATA
{
CHAR m_PrizeString[MAX_PRIZE_STRING]; //奖品代码
BYTE m_PrizeNum; //奖品数量
_PRIZE_DATA()
{
memset(m_PrizeString,0,MAX_PRIZE_STRING);
m_PrizeNum = 0;
}
static UINT getSize()
{
return sizeof(CHAR)*MAX_PRIZE_STRING+sizeof(BYTE);
}
};
//Billing返回的购买结构
struct _RETBUY_DATA
{
UINT m_BuyInt; //商品代码(元宝)
USHORT m_BuyNumber; //商品数量
_RETBUY_DATA()
{
m_BuyInt = 0;
m_BuyNumber = 0;
}
static UINT getSize()
{
return sizeof(UINT)+sizeof(USHORT);
}
};
//商品结构
struct _BUY_DATA
{
CHAR m_BuyString[MAX_PRIZE_STRING]; //商品代码(CD-KEY)
UINT m_BuyPoint; //商品消耗点数
UINT m_BuyInt; //商品代码(元宝)
UINT m_BuyNumber; //商品数量
_BUY_DATA()
{
memset(m_BuyString,0,MAX_PRIZE_STRING);
m_BuyPoint = 0;
m_BuyInt = 0;
m_BuyNumber = 0;
}
BYTE GetPrizeType(); //奖品类型
UINT GetPrizeSerial(); //奖品序列号
BYTE GetPrizeNum(); //奖品数量
UINT GetCostPoint(); //消耗点数
VOID GetSubString(INT nIdx,CHAR* pBuf,INT nBufLength); //拆分奖品字串
BYTE GetGoodsType(); //商品类型
USHORT GetGoodsNum(); //商品数量
};
#define MAX_CHOOSE_SCENE_NUMBER 10
struct DB_CHOOSE_SCENE
{
DB_CHOOSE_SCENE()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
CHAR mSceneCount;
SceneID_t mSceneID[MAX_CHOOSE_SCENE_NUMBER];
};
struct CFG_CHOOSE_SCENE
{
CFG_CHOOSE_SCENE()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
CHAR mSceneCount;
SceneID_t mSceneID[MAX_CHOOSE_SCENE_NUMBER];
WORLD_POS mPos[MAX_CHOOSE_SCENE_NUMBER];
};
//帐号安全相关
enum _ACCOUNT_SAFE_FLAG
{
ASF_BIND_NONE = 0,
ASF_BIND_IP =2, //IP绑定
ASF_BIND_MIBAOKA = 4, //密保卡绑定
ASF_BIND_MOBILE_PHONE = 8, //手机绑定
ASF_BIND_MAC = 16, //MAC绑定
ASF_BIND_REALNAME = 32, //实名验证过(公安局数据库验证过)
ASF_BIND_INPUTNAME = 64, //填写过实名(玩家在WEB上填写过实名的信息,但尚未通过公安局数据库验证)
};
typedef struct tag_AccountSafeSign
{
INT m_Sign;
tag_AccountSafeSign()
{
CleanUp();
}
VOID CleanUp()
{
m_Sign = ASF_BIND_NONE;
}
BOOL IsBindSafeSign(INT nSign)
{
switch(nSign)
{
case ASF_BIND_IP:
case ASF_BIND_MIBAOKA:
case ASF_BIND_MOBILE_PHONE:
case ASF_BIND_MAC:
case ASF_BIND_REALNAME:
case ASF_BIND_INPUTNAME:
return (m_Sign & nSign)?TRUE:FALSE;
case ASF_BIND_NONE:
default:
return FALSE;
}
return FALSE;
}
VOID SetBindSafeSign(INT nSign,BOOL bSet = TRUE)
{
switch(nSign)
{
case ASF_BIND_IP:
case ASF_BIND_MIBAOKA:
case ASF_BIND_MOBILE_PHONE:
case ASF_BIND_MAC:
case ASF_BIND_REALNAME:
case ASF_BIND_INPUTNAME:
(bSet)?(m_Sign |= nSign):(m_Sign &= ~nSign);
break;
case ASF_BIND_NONE:
default:
break;
}
}
}AccountSafeSign;
//消费记录结构
struct _COST_LOG
{
CHAR m_SerialKey[MAX_PRIZE_SERIAL_LENGTH+1]; //消费序列号
INT m_WorldId; //World号
INT m_ServerId; //Server号
INT m_SceneId; //Scene号
GUID_t m_UserGUID; //用户GUID
INT m_UserLevel; //用户等级
LONG m_CostTime; //消费时间(自1970-01-01 的秒数)
INT m_YuanBao; //消耗的元宝数
CHAR m_AccName[MAX_ACCOUNT+1]; //帐号
CHAR m_CharName[MAX_CHARACTER_NAME+1]; //角色
CHAR m_Host[IP_SIZE+1]; //IP
CHAR m_OtherInfo[MAX_COST_OTHER_SIZE+1]; //Log的备注信息
_COST_LOG()
{
CleanUp();
}
VOID CleanUp()
{
memset( this, 0, sizeof(*this) ) ;
m_UserGUID = INVALID_GUID;
}
BOOL IsSame(const CHAR* pSerial)
{
return (0 == strcmp(pSerial,m_SerialKey))?TRUE:FALSE;
}
};
// add by gh for souxia 2010/05/10
//1 将 SOUXIA_DATA 中固定属性,退化为通过查表获取
struct SouXia_Skill
{
SkillID_t StudySkillId[MAX_SKILL_COUNT]; // 学习过的Skill 索引
BYTE StudyCount;
//加个赋值重载,用来做交换用
SouXia_Skill& operator =(const SouXia_Skill& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudySkillId[i] = other.StudySkillId[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
struct SouXia_Product
{
SkillID_t StudyProductId[MAX_PRODUCT_COUNT]; // 学习过的神器配方 索引
BYTE StudyCount;
//加个赋值重载,用来做交换用
SouXia_Product& operator =(const SouXia_Product& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudyProductId[i] = other.StudyProductId[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
struct ZhaoHuan
{
SkillID_t StudyZhaoHuan; // 学习过的神兽召唤技能索引
SHORT LeftUseTime; // 还可以使用的次数
//加个赋值重载,用来做交换用
ZhaoHuan& operator =(const ZhaoHuan& other )
{
if(this == &other)
{
return *this;
}
StudyZhaoHuan = other.StudyZhaoHuan;
LeftUseTime = other.LeftUseTime;
return *this;
}
};
struct SouXia_PetZhaoHuan
{
ZhaoHuan StudyPet[MAX_PET_ZHAOHUAN_COUNT]; // 学习过的神兽召唤技能索引
BYTE StudyCount; // 当前学习的数量
//加个赋值重载,用来做交换用
SouXia_PetZhaoHuan& operator =(const SouXia_PetZhaoHuan& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudyPet[i] = other.StudyPet[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
struct SouXia_ZuojiZhaoHuan
{
ZhaoHuan StudyZuoji[MAX_ZUOJI_ZHAOHUAN_COUNT]; // 学习过的坐骑召唤技能索引
BYTE StudyCount; // 当前学习的数量
//加个赋值重载,用来做交换用
SouXia_ZuojiZhaoHuan& operator = (const SouXia_ZuojiZhaoHuan& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudyZuoji[i] = other.StudyZuoji[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
/*
注意:现在拷贝构造和赋值构造由系统默认提供位拷贝,已经实现了部分用到的暂时用不到的先没写
*/
enum
{
SKILL_PER_PAGE = 3,
PRODUCT_PER_PAGE = 1,
PET_ZHAOHUAN_PER_PAGE = 8,
ZUOJI_ZHAOHUAN_PER_PAGE = PET_ZHAOHUAN_PER_PAGE,
};
struct SOUXIA_DATA
{
SHORT m_CurPos;
UINT m_SouXiaID; // 捜侠录索引
SouXia_Skill m_Skill; // 包含的搜侠技能
SouXia_Product m_Product; // ... 神器配方
SouXia_PetZhaoHuan m_Pet; // ... 神兽召唤
SouXia_ZuojiZhaoHuan m_ZuoJi; // ... 坐骑召唤
SOUXIA_DATA()
{
CleanUp();
};
void CleanUp()
{
memset(this, 0, sizeof(SOUXIA_DATA));
m_CurPos = -1;
}
SOUXIA_DATA& operator = (const SOUXIA_DATA& other)
{
if(this == &other)
{
return *this;
}
m_CurPos = other.m_CurPos;
m_SouXiaID = other.m_SouXiaID;
m_Skill = other.m_Skill;
m_Product = other.m_Product;
m_Pet = other.m_Pet;
m_ZuoJi = other.m_ZuoJi;
return *this;
};
SHORT GetCurPos() { return m_CurPos; }
VOID SetCurPos(BYTE pos) { m_CurPos = pos; }
BYTE GetCurTypeCount() { return GetCurSkillCount()>0 ? 1:0 +
GetCurProductCount() >0?1:0 +
GetCurPetCount()>0?1:0 +
GetCurZuoJiCount()>0?1:0 ; }
BOOL SkillIsFull()
{
if(MAX_SKILL_COUNT/SKILL_PER_PAGE == GetCurSkillPage())
{
return TRUE;
}
return FALSE;
}
BOOL ProductIsFull()
{
if(MAX_PRODUCT_COUNT/PRODUCT_PER_PAGE == GetCurProductPage())
{
return TRUE;
}
return FALSE;
}
BOOL PetIsFull()
{
if(MAX_PET_ZHAOHUAN_COUNT/ZUOJI_ZHAOHUAN_PER_PAGE == GetCurPetZhaoHuanPage())
{
return TRUE;
}
return FALSE;
}
BOOL ZuoJiIsFull()
{
if(MAX_ZUOJI_ZHAOHUAN_COUNT/PET_ZHAOHUAN_PER_PAGE == GetCurZuoJiZhaoHuanPage() )
{
return TRUE;
}
return FALSE;
}
BYTE GetCurSkillCount() {return m_Skill.StudyCount;}
BYTE GetCurProductCount(){return m_Product.StudyCount;}
BYTE GetCurPetCount() {return m_Pet.StudyCount;}
BYTE GetCurZuoJiCount() {return m_ZuoJi.StudyCount;}
VOID IncCurSkillCount() { m_Skill.StudyCount++; }
VOID IncCurProductCount(){ m_Product.StudyCount++; }
VOID IncCurPetCount() { m_Pet.StudyCount++; }
VOID IncCurZuoJiCount() { m_ZuoJi.StudyCount++; }
//VOID DecCurSkillCount() { m_Skill.StudyCount--; }
//VOID DecCurProductCount(){ m_Product.StudyCount--; }
VOID DecCurPetCount() { Assert(m_Pet.StudyCount>0); m_Pet.StudyCount--; }
VOID DecCurZuoJiCount() { Assert(m_ZuoJi.StudyCount>0); m_ZuoJi.StudyCount--; }
// 取得当前各项总的页数
BYTE GetCurSkillPage() { return (BYTE)(((GetCurSkillCount()+SKILL_PER_PAGE)-1)/SKILL_PER_PAGE); }
BYTE GetCurProductPage() { return GetCurProductCount(); }
BYTE GetCurPetZhaoHuanPage() { return (BYTE)(((GetCurPetCount()+PET_ZHAOHUAN_PER_PAGE)-1)/PET_ZHAOHUAN_PER_PAGE); }
BYTE GetCurZuoJiZhaoHuanPage() { return (BYTE)(((GetCurZuoJiCount()+ZUOJI_ZHAOHUAN_PER_PAGE)-1)/ZUOJI_ZHAOHUAN_PER_PAGE); }
VOID ReadSouXiaVarAttr(SocketInputStream& iStream);
VOID WriteSouXiaVarAttr(SocketOutputStream& oStream) const;
};
#pragma pack(pop)
//后面的文件会用到前面的定义
#include "GameStruct_Item.h"
#include "GameStruct_Skill.h"
#include "GameStruct_Scene.h"
#include "GameStruct_Relation.h"
#include "GameStruct_Guild.h"
#include "GameStruct_City.h"
#include "GameStruct_Script.h"
#include "GameStruct_MinorPasswd.h"
#include "GameStruct_Finger.h"
#include "GameStruct_Country.h"
#endif
| [
"viticm@126.com"
] | viticm@126.com |
24f7345de7a7cdd9f8dc25f659afad3a4c41e153 | c6eeb0463648da5b8d8c6ba44cb2d058adfcdbb0 | /ProceduralTexture.cpp | a5e4a9e593c7ee9e3a157071a2612fd80870b214 | [] | no_license | fbgtoke/TerrainGenerator | 1091e7a8e4e54728ee6a5559ad987caccf2ff9d1 | 6c96cf7613ca1c7c133ec8d572d8e74f1c9d4a2b | refs/heads/master | 2021-01-18T16:12:09.426363 | 2018-06-18T08:22:29 | 2018-06-18T08:22:29 | 86,726,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,003 | cpp | #include "ProceduralTexture.h"
ProceduralTexture::ProceduralTexture() {}
ProceduralTexture::~ProceduralTexture() {
if (mTextureId != GL_INVALID_VALUE)
glDeleteTextures(1, &mTextureId);
if (mPixels != nullptr) free(mPixels);
}
void ProceduralTexture::generate(unsigned int width, unsigned int height, uint64_t seed) {
mWidth = width;
mHeight = height;
mPixels = (unsigned char*) malloc(mWidth * mHeight * 3 * sizeof(unsigned char));
Simplex2d simplex(seed, 1.f/8.f, 16.f, 255.f);
unsigned int i, j;
for (i = 0; i < mHeight; ++i) {
for (j = 0; j < mWidth; ++j) {
mPixels[i*mWidth*3 + j*3 + 0] = (unsigned int)simplex.getValue(j, i)*0.25f;
mPixels[i*mWidth*3 + j*3 + 1] = (unsigned int)simplex.getValue(j, i);
mPixels[i*mWidth*3 + j*3 + 2] = (unsigned int)simplex.getValue(j, i)*0.25f;
}
}
glGenTextures(1, &mTextureId);
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB8, mWidth, mHeight);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mWidth, mHeight, GL_RGB, GL_UNSIGNED_BYTE, mPixels);
}
void ProceduralTexture::setWrapS(GLint value) { wrapS = value; }
void ProceduralTexture::setWrapT(GLint value) { wrapT = value; }
void ProceduralTexture::setMinFilter(GLint value) { minFilter = value; }
void ProceduralTexture::setMagFilter(GLint value) { magFilter = value; }
void ProceduralTexture::use() const {
glActiveTexture(mTextureUnit);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
}
unsigned int ProceduralTexture::getWidth() const { return mWidth; }
unsigned int ProceduralTexture::getHeight() const { return mHeight; }
GLuint ProceduralTexture::getTexId() const { return mTextureId; }
void ProceduralTexture::setTexUnit(GLenum unit) { mTextureUnit = unit; } | [
"fabio.banchelli@bsc.es"
] | fabio.banchelli@bsc.es |
7b20efd5814f9e912ba6de14b3644813f20dc095 | 080d2db2d45683f760bfa0f7f64755e8b8e6e466 | /src/checkpoints.cpp | 4926d37644c66cb96bf1c9fac1a68251bfbcd7ab | [
"MIT"
] | permissive | latinumcoin/latinumcoin | 5ae2109388f89fca66833201af704aafdb5e4860 | 441e4ac7fcfe25041e0f71e193b552fd3d5638e2 | refs/heads/master | 2021-03-12T23:05:44.467689 | 2014-07-08T19:28:34 | 2014-07-08T19:28:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,641 | cpp | // Copyright (c) 2009-2014 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 "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(11111, uint256("0x000000000020b76e429fbd1fab0ab72788f9147457650d171f4ca257eb079527"))
(22222, uint256("0x0000000000008d98496877ef7a043ba49fbd6b29ff37d60861d3cac54c9e4023"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1404710134, // * UNIX timestamp of last checkpoint block
24470, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
50000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1338180505,
16341,
300
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET)
return dataTestnet;
else if (Params().NetworkID() == CChainParams::MAIN)
return data;
else
return dataRegtest;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex==NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
| [
"einewton@gmail.com"
] | einewton@gmail.com |
86d2bebb57176fbc11821a5392d56b4ea5a5e9c4 | 14104bd60d0ba1316e71d9557440b4aaf61e8dc2 | /98/include/Date.h | 1a74c37f31d234430b0cea9e63eb6da6ab17a75b | [] | no_license | xiaoyujia66/xiao_yujia | b935d49f8d79c05a91794dbc7ec0651dcf411c22 | 1eafd7bfd483479556debdfd4e827568d225c212 | refs/heads/master | 2020-04-27T23:48:51.897277 | 2019-06-02T11:24:39 | 2019-06-02T11:24:39 | 174,791,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #ifndef DATE_H
#define DATE_H
class Date
{
public:
Date( int, int, int );
void print();
void setDate( int, int, int );
void setMonth( int );
void setDay( int );
void setYear( int );
int getMonth();
int getDay();
int getYear();
void nextDay();
private:
int month;
int day;
int year;
bool leapYear();
int monthDays();
};
#endif // DATE_H
| [
"435713285@qq.com"
] | 435713285@qq.com |
d4b0f0bf1f9e43f4f5d73c00616c906302087b5b | 19c74c41c2cee8c0b8b56f76d2156950e0ba8391 | /debug_log.h | 212bc58401a85873d6f3d7ce2a6b178c28085a5b | [] | no_license | tyzjames/midi-editor | cd32296d849a36feef60058bc491e432c8587828 | 64fdfb30c0bc0321fabe1ebba46da5249618ba36 | refs/heads/master | 2021-01-25T07:19:51.683076 | 2016-01-12T16:14:29 | 2016-01-12T16:14:29 | 42,509,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | h | #ifndef DEBUG_LOG
#define DEBUG_LOG
#include <QTextStream>
#include <QFile>
#include <QCoreApplication>
class debug_log {
public:
debug_log(bool newFile);
void writeLog(QString text);
private:
QString filename;
};
#endif // DEBUG_LOG
| [
"tyzjames@hotmail.com"
] | tyzjames@hotmail.com |
d3a6aec92141a50773a0612b26a2bc19c0203621 | aaa60b19f500fc49dbaac1ec87e9c535a66b4ff5 | /array-easy/605.种花问题.cpp | 52ad3db8bcf8aed7dd5b8dde825fdff4012b1c35 | [] | no_license | younger-1/leetcode-younger | c24e4a2a77c2f226c064c4eaf61e7f47d7e98d74 | a6dc92bbb90c5a095ac405476aeae6690e204b6b | refs/heads/master | 2023-07-25T02:31:42.430740 | 2021-09-09T08:06:05 | 2021-09-09T08:06:05 | 334,441,040 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | cpp | /*
* @lc app=leetcode.cn id=605 lang=cpp
*
* [605] 种花问题
*/
#include <iostream>
#include <vector>
using namespace std;
// @lc code=start
// 124/124 cases passed (24 ms)
// Your runtime beats 80.42 % of cpp submissions
// Your memory usage beats 5 % of cpp submissions (20.7 MB)
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int m = flowerbed.size();
vector<int> bed(m + 2, 0);
for (int i = 0; i < m; i++) {
bed[i + 1] = flowerbed[i];
}
int i = 0;
while (i < m) {
i += 1;
if (bed[i - 1] || bed[i] || bed[i + 1]) {
continue;
}
bed[i] = 1;
n -= 1;
}
return n > 0 ? false : true;
}
};
// @lc code=end
int main() {
vector<int> v{1, 0, 0, 0, 1};
Solution s = Solution();
cout << boolalpha << s.canPlaceFlowers(v, 3);
} | [
"45989017+younger-1@users.noreply.github.com"
] | 45989017+younger-1@users.noreply.github.com |
bc253f95d204a419e9e65a867abab6c08aac4a1d | 2b7ca25e4fba0ce04104987328f28dd6c2b4195e | /2018-2019/sem06/05_class_templ.cpp | 9bff485e3d29441a9d42befe145ee15022ca3018 | [] | no_license | blackav/cmc-cpp-seminars | 7da500782901115cfc4f808b8ad367d126ea3879 | 48c94bb340e98c3856a4f0ea8267fafd73ae318d | refs/heads/master | 2023-04-30T05:16:17.788261 | 2023-04-15T03:37:48 | 2023-04-15T03:37:48 | 53,767,957 | 18 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | template<typename T>
struct is_int
{
static constexpr auto value = false;
};
template<>
struct is_int<int>
{
static constexpr auto value = true;
};
#include <iostream>
using namespace std;
int main()
{
cout << is_int<double>::value << endl;
cout << is_int<int>::value << endl;
int x = 10;
static_assert(is_int<decltype(x)>::value);
if constexpr(is_int<decltype(x)>::value) {
cout << x << endl;
}
}
| [
"blackav@gmail.com"
] | blackav@gmail.com |
e6f481e76204dc3913615119602e8689fa5e61c6 | 0f527eb8d84d99f9dba8ee9e7d34d9062434d03b | /Convert/Convert/Src/BSPHandler.h | 63a9f290832224c2dcd37255399a3a3db576c393 | [] | no_license | weichx/pof_to_dae | 50212d519a3b70252b8bae21155c96f10f5c6339 | 38b3f81b4e892e4cd2fe65f66de38fc979c3c6ef | refs/heads/master | 2016-09-06T09:26:55.390228 | 2015-06-29T04:03:07 | 2015-06-29T04:03:07 | 38,220,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | h | #include "BSPDataStructs.h"
#include <ios>
#if !defined(_BSP_HANDLER_H_)
#define _BSP_HANDLER_H_
class BSP
{
public:
std::vector<BSP_BoundBox> bounders;
std::vector<BSP_DefPoints> points;
std::vector<BSP_FlatPoly> fpolys;
std::vector<BSP_SortNorm> snorms;
std::vector<BSP_TmapPoly> tpolys;
int numbounders, numpoints, numfpolys, numsnorms, numtpolys;
void Clear()
{
bounders.clear();
points.clear();
fpolys.clear();
snorms.clear();
tpolys.clear();
}
BSP()
{
Clear();
}
BSP(char *buffer, int size)
{
Clear();
DataIn(buffer, size);
}
//~BSP();
//--------------------------------
std::string DataIn(char *buffer, int size);
std::ostream& BSPDump(std::ostream &os); // dumps human readable BSP information into ostream;
int Count_Bounding()
{
return bounders.size();
}
int Count_Points()
{
return points.size();
}
int Count_FlatPolys()
{
return fpolys.size();
}
int Count_SortNorms()
{
return snorms.size();
}
int Count_TmapPolys()
{
return tpolys.size();
}
//--------------------------------
void Add_BoundBox(BSP_BoundBox bound);
bool Del_BoundBox(int index);
void Add_DefPoints(BSP_DefPoints pnts);
bool Del_DefPoints(int index);
void Add_FlatPoly(BSP_FlatPoly fpol);
bool Del_FlatPoly(int index);
void Add_SortNorm(BSP_SortNorm sn);
bool Del_SortNorm(int index);
void Add_TmapPoly(BSP_TmapPoly tpol);
bool Del_TmapPoly(int index);
};
std::ostream& operator<<(std::ostream &os, BSP_TmapPoly tpoly);
std::ostream& operator<<(std::ostream &os, BSP_FlatPoly fpoly);
bool operator==(BSP_TmapPoly &a, BSP_TmapPoly &b);
bool operator==(BSP_FlatPoly &a, BSP_FlatPoly &b);
#endif //_BSP_HANDLER_H_
| [
"matthew.weichselbaum@gmail.com"
] | matthew.weichselbaum@gmail.com |
fabd888fca8f42911693a7d0e6a018660eca6c08 | 33683be0126967b13c5af32e979d8242fb85acaa | /MyClient_System_Editing/tabs/group.h | 39286a9de929be99f4f85bf2db582396a4d57413 | [
"MIT"
] | permissive | ASIKOO/metin2-myclient-system-editing | 5b5a8bb9e1b42d077640cee2398daa2621d7bf8e | 067e0b5cd0b0b4341321be810b0e2dd6ec424df7 | refs/heads/master | 2021-06-07T06:18:50.744992 | 2016-10-14T09:48:08 | 2016-10-14T09:48:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #ifndef MANAGER_H
#define MANAGER_H
#include "global.h"
struct GroupStruct
{
QString Name;
uint32_t Vnum;
QString Leader;
uint32_t LeaderVnum;
QStringList SubMob;
QList<uint32_t> SubMobVnum;
};
class GroupInfo
{
public:
GroupInfo();
static QList<GroupStruct> *Groups;
bool CheckType(QStringList tabs);
void OpenGroup(char *groupPath);
private:
bool isOpen;
GroupStruct *tempGr;
};
#endif // MANAGER_H
| [
"christian.roggia@gmail.com"
] | christian.roggia@gmail.com |
b13047b14d7705f1be3079b301e7b3c85dc22373 | 6ce014545af76c9f52c3a80ef3a93fc249437a0b | /include/query_structs.h | 1e5cde84395e8415904d64c9d863290790466c9a | [] | no_license | David-Durst/nba_queries | fd9340b9c140531068fa195e2249c800cbc80d47 | 0a7a2a9925d8d008b22b389fe05afd7a6c88284a | refs/heads/master | 2023-03-06T15:17:26.390528 | 2021-02-16T05:10:26 | 2021-02-16T05:10:26 | 311,221,043 | 1 | 0 | null | 2021-02-15T04:53:42 | 2020-11-09T04:13:33 | C++ | UTF-8 | C++ | false | false | 8,652 | h | #ifndef QUERY_STRUCTS_H
#define QUERY_STRUCTS_H
#include <string>
#include <vector>
#include <cmath>
#include <functional>
using std::string;
using std::vector;
struct moment {
long int team_id;
int player_id;
double x_loc;
double y_loc;
double radius;
double game_clock;
double shot_clock;
short int quarter;
long int game_id;
long int event_id;
int moment_in_event;
int64_t internal_id;
} ;
bool operator==(moment const & lhs, moment const & rhs);
std::ostream& operator<<(std::ostream& os, moment const& value);
void print_moment_csv(std::ostream& os, const moment& value);
struct player_data {
long int team_id;
int player_id;
double x_loc;
double y_loc;
double radius;
};
bool operator==(player_data const & lhs, player_data const & rhs);
std::ostream& operator<<(std::ostream& os, player_data const& value);
void print_player_data_csv(std::ostream& os, const player_data& value);
struct event_moment_data {
long int event_id;
int moment_in_event;
};
bool operator==(event_moment_data const & lhs, event_moment_data const & rhs);
std::ostream& operator<<(std::ostream& os, event_moment_data const& value);
void print_event_moment_data_csv(std::ostream& os, const event_moment_data& value);
struct extra_game_data {
long int game_id;
int game_num;
int num_ot_periods;
};
bool operator==(extra_game_data const & lhs, extra_game_data const & rhs);
std::ostream& operator<<(std::ostream& os, extra_game_data const& value);
void print_extra_game_data_csv(std::ostream& os, const extra_game_data& value);
class clock_fixed_point {
public:
long int seconds;
int twenty_fifths_of_second;
clock_fixed_point () { }
clock_fixed_point (double f) {
seconds = std::floor(f);
twenty_fifths_of_second = std::round((f - seconds) * 25);
if (twenty_fifths_of_second == 25) {
seconds++;
twenty_fifths_of_second = 0;
}
}
inline double to_double() const {
return seconds + (twenty_fifths_of_second / 25.0);
}
clock_fixed_point abs_diff(const clock_fixed_point& other) const {
return clock_fixed_point(std::abs(this->to_double() - other.to_double()));
}
bool gt(double f) const {
return this->to_double() > f;
}
inline bool gt(clock_fixed_point c) const {
return this->seconds > c.seconds || (this->seconds == c.seconds && this->twenty_fifths_of_second > c.twenty_fifths_of_second);
}
inline int64_t time_to_index(vector<extra_game_data>& extra_data, int game_num, int quarter) {
int ot_quarters = 0;
for (int i = 0; i < game_num; i++) {
ot_quarters += extra_data.at(i).num_ot_periods;
}
int non_ot_quarters_finished_this_game = std::min(4, quarter - 1);
int ot_quarters_finished_this_game = std::max(0, quarter - 5);
int seconds_elapsed_this_quarter = quarter >= 5 ? 300 - seconds : 720 - seconds;
// 720 seconds in a quarter
return
// time for multiple games
25 * 720 * 4 * game_num +
// time for Ot
25 * 300 * ot_quarters +
// time in game
(25 * (720 * non_ot_quarters_finished_this_game + 300 * ot_quarters_finished_this_game + seconds_elapsed_this_quarter) - twenty_fifths_of_second);
}
};
bool operator==(clock_fixed_point const & lhs, clock_fixed_point const & rhs);
bool operator!=(clock_fixed_point const& lhs, clock_fixed_point const& rhs);
struct cleaned_moment {
player_data ball;
player_data players[10];
clock_fixed_point game_clock;
double shot_clock;
short int quarter;
long int game_id; // game_id assigned by nba
int game_num; // game num stores game's number in vector of cleaned_moments
vector<event_moment_data> events;
} ;
bool operator==(cleaned_moment const & lhs, cleaned_moment const & rhs);
std::ostream& operator<<(std::ostream& os, cleaned_moment const& value);
void print_cleaned_moment_csv(std::ostream& os, const cleaned_moment& value);
void print_cleaned_moment_csv_header(std::ostream& os);
void get_all_player_data(vector<std::reference_wrapper<player_data>>& data, cleaned_moment& c);
struct event {
long int game_id;
long int event_num;
int event_msg_type;
int event_msg_action_type;
short int period;
string wc_timestring;
string pc_timestring;
string home_description;
string neutral_description;
string visitor_description;
string score;
string score_margin;
int person1_type;
int player1_id;
string player1_name;
float player1_team_id;
string player1_team_city;
string player1_team_nickname;
string player1_team_abbreviation;
int person2_type;
int player2_id;
string player2_name;
float player2_team_id;
string player2_team_city;
string player2_team_nickname;
string player2_team_abbreviation;
int person3_type;
int player3_id;
string player3_name;
float player3_team_id;
string player3_team_city;
string player3_team_nickname;
string player3_team_abbreviation;
} ;
struct shot {
string action_type;
int event_time;
string event_type;
string game_date;
long int game_event_id;
long int game_id;
string grid_type;
string htm;
float loc_x;
float loc_y;
int minutes_remaining;
int period;
int player_id;
string player_name;
float quarter;
int seconds_remaining;
bool shot_attempted_flag;
int shot_distance;
bool shot_made_flag;
clock_fixed_point shot_time;
string shot_type;
string shot_zone_area;
string shot_zone_basic;
string shot_zone_range;
long int team_id;
string team_name;
string team_vtm;
} ;
bool operator==(shot const & lhs, shot const & rhs);
std::ostream& operator<<(std::ostream& os, shot const& value);
void print_shot_csv(std::ostream& os, const shot& value);
bool shot_before_moment(const shot & s, const moment & m);
bool moment_before_shot(const moment & m, const shot & s);
struct cleaned_shot {
string action_type;
int event_time;
string event_type;
string game_date;
long int game_event_id;
long int game_id;
int game_num;
string grid_type;
string htm;
float loc_x;
float loc_y;
int minutes_remaining;
int period;
int player_id;
string player_name;
int quarter;
int seconds_remaining;
bool shot_attempted_flag;
int shot_distance;
bool shot_made_flag;
clock_fixed_point shot_time;
string shot_type;
string shot_zone_area;
string shot_zone_basic;
string shot_zone_range;
long int team_id;
string team_name;
string team_vtm;
} ;
bool operator==(cleaned_shot const & lhs, shot const & rhs);
std::ostream& operator<<(std::ostream& os, cleaned_shot const& value);
void print_cleaned_shot_csv(std::ostream& os, const cleaned_shot& value);
template <typename T>
struct list_node {
T data;
list_node<T>* next;
};
template <typename T>
class list {
list_node<T> *head, *tail;
size_t size;
public:
list() : head(NULL), tail(NULL), size(0) { }
~list() { clear(); }
void append_node(T elem);
T * get(size_t i);
size_t get_size();
void clear();
void to_vector(vector<T> & vec);
};
template <typename T>
inline void list<T>::append_node(T elem) {
if (head == NULL) {
head = new list_node<T>();
tail = head;
head->data = elem;
}
else {
list_node<T> * next_tail = new list_node<T>();
next_tail->data = elem;
tail->next = next_tail;
tail = tail->next;
}
size++;
}
template <typename T>
T * list<T>::get(size_t i) {
if (i >= size) {
throw std::invalid_argument("size " + std::to_string(i) + "greater than list size " + std::to_string(size));
}
list_node<T> * result_node = head;
for (int j = 0; j < i; j++) {
result_node = result_node->next;
}
return result_node->data;
}
template <typename T>
size_t list<T>::get_size() {
return size;
}
template <typename T>
void list<T>::clear() {
list_node<T> * cur_node = head;
tail = NULL;
for (int i = 0; i < size; i++) {
list_node<T> * prior_node = cur_node;
cur_node = cur_node->next;
free(prior_node);
}
head = NULL;
size = 0;
}
template <typename T>
void list<T>::to_vector(vector<T> &vec) {
vec.clear();
list_node<T> * cur_node = head;
for (int i = 0; i < size; i++) {
vec.push_back(cur_node->data);
cur_node = cur_node->next;
}
}
#endif
| [
"davidbdurst@gmail.com"
] | davidbdurst@gmail.com |
9b89b3931cca6621aa0e2901cc2d08e403988de1 | ad07a5478488e166dfd057db46ef22fb652e6bb1 | /src/BookKeeping.h | bbc009bbf4ce4edff4f4b9ae0d55a7bcd927ea75 | [
"Zlib"
] | permissive | shaobohou/pearley | d51714722c0055a3131f6b04d78ebeb5eb11e4fe | d451c03e9d8465135fb0c4a4cf54408db60b1e3f | refs/heads/master | 2021-01-01T05:51:10.638506 | 2012-05-21T13:21:13 | 2012-05-21T13:21:13 | 3,509,166 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,812 | h | #ifndef BOOKKEEPING
#define BOOKKEEPING
class ParseEntry
{
public:
ParseEntry()
: the_col(static_cast<unsigned int>(-1)), the_row(static_cast<unsigned int>(-1))
{}
ParseEntry(unsigned int col, unsigned int row)
: the_col(col), the_row(row)
{}
unsigned int& row()
{
return the_row;
}
const unsigned int& col() const
{
return the_col;
}
const unsigned int& row() const
{
return the_row;
}
private:
unsigned int the_col, the_row;
};
class Progenitor
{
public:
Progenitor(const ParseEntry &incompleted_index, double weight)
: the_incompleted_index(incompleted_index), the_weight(weight)
{}
Progenitor(const ParseEntry &incompleted_index, const ParseEntry &complete_index)
: the_incompleted_index(incompleted_index), the_complete_index(complete_index), the_weight(0.0)
{}
Progenitor(const ParseEntry &incompleted_index, const ParseEntry &complete_index, double weight)
: the_incompleted_index(incompleted_index), the_complete_index(complete_index), the_weight(weight)
{}
ParseEntry& complete_index()
{
return the_complete_index;
}
const ParseEntry& incompleted_index() const
{
return the_incompleted_index;
}
const ParseEntry& complete_index() const
{
return the_complete_index;
}
const double& weight() const
{
return the_weight;
}
private:
ParseEntry the_incompleted_index, the_complete_index;
double the_weight;
};
typedef std::vector<std::vector<Progenitor> > ProgenitorsLists;
#endif
| [
"shaobohou@c06704c2-2886-2df8-2b27-5efbbc2a7cc3"
] | shaobohou@c06704c2-2886-2df8-2b27-5efbbc2a7cc3 |
37dd0de3ead170c8a563d05c7e26cdfef21f9d22 | 083100943aa21e05d2eb0ad745349331dd35239a | /aws-cpp-sdk-iam/include/aws/iam/model/GetPolicyVersionResult.h | 3618f23ea1b4485bee601b346f0cbeae79cc4afc | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bmildner/aws-sdk-cpp | d853faf39ab001b2878de57aa7ba132579d1dcd2 | 983be395fdff4ec944b3bcfcd6ead6b4510b2991 | refs/heads/master | 2021-01-15T16:52:31.496867 | 2015-09-10T06:57:18 | 2015-09-10T06:57:18 | 41,954,994 | 1 | 0 | null | 2015-09-05T08:57:22 | 2015-09-05T08:57:22 | null | UTF-8 | C++ | false | false | 3,946 | h | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/iam/IAM_EXPORTS.h>
#include <aws/iam/model/PolicyVersion.h>
#include <aws/iam/model/ResponseMetadata.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace IAM
{
namespace Model
{
/*
<p>Contains the response to a successful <a>GetPolicyVersion</a> request. </p>
*/
class AWS_IAM_API GetPolicyVersionResult
{
public:
GetPolicyVersionResult();
GetPolicyVersionResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
GetPolicyVersionResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline const PolicyVersion& GetPolicyVersion() const{ return m_policyVersion; }
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline void SetPolicyVersion(const PolicyVersion& value) { m_policyVersion = value; }
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline void SetPolicyVersion(PolicyVersion&& value) { m_policyVersion = value; }
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline GetPolicyVersionResult& WithPolicyVersion(const PolicyVersion& value) { SetPolicyVersion(value); return *this;}
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline GetPolicyVersionResult& WithPolicyVersion(PolicyVersion&& value) { SetPolicyVersion(value); return *this;}
inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }
inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }
inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = value; }
inline GetPolicyVersionResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}
inline GetPolicyVersionResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(value); return *this;}
private:
PolicyVersion m_policyVersion;
ResponseMetadata m_responseMetadata;
};
} // namespace Model
} // namespace IAM
} // namespace Aws | [
"henso@amazon.com"
] | henso@amazon.com |
feaf53f3f38334a2fa6380792c126afbc5009595 | f4e5d2bde7171e0e9ccc4592cf66147de9a06f67 | /OGFLoader.h | b51c672168c77c7bf316cfc12fbc78f2af42ea72 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | mortany/OGFViewer | 585b48883e8036bffb35d7cbd670cb77a2af5592 | 35d380eaafd9bd1481f2da68349eca80cc00ed25 | refs/heads/master | 2021-10-19T14:32:47.360825 | 2019-02-21T19:49:57 | 2019-02-21T19:56:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | h | #pragma once
#include "OGFModel.h"
struct Chunk2564
{
int header[3]; //1 44 2564
float info[10]; //data chunk
};
struct Chunk1284
{
int header[3]; //1 44 284
char data[40];
};
struct OGFHeader
{
int count;
int size;
char modelname[1024];
int hz1; //9
int pos1;
int hz2; //1638
int pos2;
int hz3; //0
int pos3;
int hz4; //1630
int pos4;
};
struct Bone
{
int id;
char bone[8192];
};
struct structF
{
int f[2];
};
struct TextData
{
int type;
int size;
char data[1024];
};
struct Indices
{
int count;
unsigned short *idx;
};
struct OGFVertex
{
float x,y,z;
float t1,t2;
float aa;
char flag;
float t[2];
float b[2];
float s[2];
float d[2];
};
OGFModel *Load(char *fileName,const std::string &pathToTextures); | [
"dmitrysafronov1996@gmail.com"
] | dmitrysafronov1996@gmail.com |
cd52a0f7c0eaca90bc84c9cd5cf20a9753ed8601 | 892a394660d04682b486792f6850146113b34db6 | /uncharted-client/UnchartedClient/Input.cpp | 50663f353cda8dae755e7a82e98df7ce498acc47 | [] | no_license | inhibitor1217/Direct3D-tutorial | d2ef49d7f0270185bf3d31d90821f3a7f7589e28 | 37668a7c61960b95d14c7920b088d43d988e7a13 | refs/heads/master | 2020-04-11T13:35:33.982227 | 2019-01-18T04:14:28 | 2019-01-18T04:14:28 | 161,822,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | cpp | #include "Input.h"
Input::Input()
{
}
Input::Input(const Input &other)
{
}
Input::~Input()
{
}
bool Input::Init(HINSTANCE hInstance, HWND hwnd, int screenWidth, int screenHeight)
{
for (int i = 0; i < 256; i++) {
m_keyboardState[i] = false;
}
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
if (FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void **>(&m_pDirectInput), NULL)))
return false;
if(FAILED(m_pDirectInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, NULL)))
return false;
if (FAILED(m_pKeyboard->SetDataFormat(&c_dfDIKeyboard)))
return false;
if (FAILED(m_pKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE)))
return false;
if (FAILED(m_pKeyboard->Acquire()))
return false;
if (FAILED(m_pDirectInput->CreateDevice(GUID_SysMouse, &m_pMouse, NULL)))
return false;
if (FAILED(m_pMouse->SetDataFormat(&c_dfDIMouse)))
return false;
if (FAILED(m_pMouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
return false;
if (FAILED(m_pMouse->Acquire()))
return false;
return true;
}
void Input::Shutdown()
{
if (m_pMouse) {
m_pMouse->Unacquire();
Memory::SafeRelease(m_pMouse);
}
if (m_pKeyboard) {
m_pKeyboard->Unacquire();
Memory::SafeRelease(m_pKeyboard);
}
Memory::SafeRelease(m_pDirectInput);
}
bool Input::Frame()
{
if (!ReadKeyboard())
return false;
if (!ReadMouse())
return false;
ProcessInput();
return true;
}
void Input::GetMouse(int &x, int &y)
{
x = m_mouseX;
y = m_mouseY;
}
bool Input::IsKeyDown(UINT key)
{
return m_keyboardState[key];
}
bool Input::ReadKeyboard()
{
HRESULT result;
if (FAILED(result = m_pKeyboard->GetDeviceState(sizeof(m_keyboardState), reinterpret_cast<void *>(&m_keyboardState)))) {
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED)
m_pKeyboard->Acquire();
else
return false;
}
return true;
}
bool Input::ReadMouse()
{
HRESULT result;
if (FAILED(result = m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE), reinterpret_cast<void *>(&m_mouseState)))) {
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED)
m_pMouse->Acquire();
else
return false;
}
return true;
}
void Input::ProcessInput()
{
m_mouseX += m_mouseState.lX;
m_mouseY += m_mouseState.lY;
if (m_mouseX < 0)
m_mouseX = 0;
if (m_mouseX > m_screenWidth)
m_mouseX = m_screenWidth;
if (m_mouseY < 0)
m_mouseY = 0;
if (m_mouseY > m_screenHeight)
m_mouseY = m_screenHeight;
} | [
"cytops1217@gmail.com"
] | cytops1217@gmail.com |
f389226213bd0f506ac04b3c4a3c733d888eb7ac | 349fe789ab1e4e46aae6812cf60ada9423c0b632 | /FIB_DataModule/GurRoznDoc/UDMGurRoznDoc.h | 125cafca16aa6508422e462650d89684e4b66fea | [] | no_license | presscad/ERP | a6acdaeb97b3a53f776677c3a585ca860d4de980 | 18ecc6c8664ed7fc3f01397d587cce91fc3ac78b | refs/heads/master | 2020-08-22T05:24:15.449666 | 2019-07-12T12:59:13 | 2019-07-12T12:59:13 | 216,326,440 | 1 | 0 | null | 2019-10-20T07:52:26 | 2019-10-20T07:52:26 | null | WINDOWS-1251 | C++ | false | false | 3,043 | h | //---------------------------------------------------------------------------
#ifndef UDMGurRoznDocH
#define UDMGurRoznDocH
//---------------------------------------------------------------------------
#include "IDMFibConnection.h"
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <DB.hpp>
#include <IBCustomDataSet.hpp>
#include <IBDatabase.hpp>
#include <IBQuery.hpp>
#include "FIBDatabase.hpp"
#include "FIBDataSet.hpp"
#include "pFIBDatabase.hpp"
#include "pFIBDataSet.hpp"
#include "FIBQuery.hpp"
#include "pFIBQuery.hpp"
//---------------------------------------------------------------------------
class TDMGurRoznDoc : public TDataModule
{
__published: // IDE-managed Components
TDataSource *DataSourceTable;
TpFIBDataSet *IBQ;
TpFIBDataSet *Table;
TpFIBTransaction *IBTr;
TFIBDateTimeField *TablePOSDOC;
TFIBSmallIntField *TablePRDOC;
TFIBIntegerField *TableNUMDOC;
TFIBBCDField *TableSUMDOC;
TFIBBCDField *TableIDDOC;
TFIBBCDField *TableIDFIRMDOC;
TFIBBCDField *TableIDSKLDOC;
TFIBBCDField *TableIDKLDOC;
TFIBBCDField *TableIDDOGDOC;
TFIBBCDField *TableIDUSERDOC;
TFIBBCDField *TableIDDOCOSNDOC;
TFIBBCDField *TableIDEXTDOC;
TFIBIntegerField *TableTYPEEXTDOC;
TpFIBQuery *Query;
TFIBBCDField *TableIDBASE_GALLDOC;
TFIBWideStringField *TableTDOC;
TFIBWideStringField *TableGID_DOC;
TFIBWideStringField *TablePREFIKSDOC;
TFIBBCDField *TableIDPROJECT_GALLDOC;
TFIBWideStringField *TableNAMEFIRM;
TFIBWideStringField *TableNAMESKLAD;
TFIBWideStringField *TableNAMEKLIENT;
TFIBWideStringField *TableNAME_USER;
void __fastcall DataModuleDestroy(TObject *Sender);
void __fastcall DataModuleCreate(TObject *Sender);
private: // User declarations
bool ExecPriv, InsertPriv, EditPriv, DeletePriv;
public: // User declarations
__fastcall TDMGurRoznDoc(TComponent* Owner);
IkanUnknown * InterfaceMainObject;
IkanUnknown * InterfaceOwnerObject;
IkanUnknown * InterfaceImpl; //интерфейс класса реализации
GUID ClsIdImpl; //GUID класса реализации
IDMFibConnection * DM_Connection;
IkanCom *InterfaceGlobalCom;
typedef void (__closure * TFunctionDeleteImplType)(void);
TFunctionDeleteImplType FunctionDeleteImpl;
bool flDeleteImpl;
int CodeError;
UnicodeString TextError;
bool Init(void);
int Done(void);
void OpenTable();
void UpdateTable(void);
__int64 IdDoc;
__int64 IdKlient;
__int64 IdSklad;
__int64 IdFirm;
UnicodeString StringTypeDoc;
UnicodeString StringFullTypeDoc;
bool OtborVkl;
bool OtborPoKlient ;
bool OtborPoFirm;
bool OtborPoSklad;
bool OtborPoTypeDoc;
TDateTime PosNach;
TDateTime PosCon;
int FindDocPoIdDog(__int64 iddogovor);
__int64 IdBase;
};
//---------------------------------------------------------------------------
extern PACKAGE TDMGurRoznDoc *DMGurRoznDoc;
//---------------------------------------------------------------------------
#endif
| [
"sasha@kaserv.ru"
] | sasha@kaserv.ru |
f760d13b3d558f6a17afa89a04a4f466d8a711a4 | 136ee4eec7e1591af2ba60ba6ae342d05b187cee | /traversingBinaryTree.cpp | c88ac4ae4710a0fb54b941b8f09974b20332fff0 | [] | no_license | hujunyu1222/leetcode | 7cd79c6d5287a6cf1db8ce0e7abb225bd53e525b | b20d4a607bdcbc1fc92670b11142433214d7e32b | refs/heads/master | 2021-01-11T06:06:55.377430 | 2017-04-11T02:54:30 | 2017-04-11T02:54:30 | 71,687,068 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,285 | cpp | #include <iostream>
#include <stack>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x), left(NULL), right(NULL){}
};
//后续遍历用于标记节点
enum Tags {Left,Right};
struct element{
TreeNode *pointer;
Tags tag;
};
//前序遍历 非递归
void PreOrder(TreeNode *root){
stack<TreeNode*> aStack;
TreeNode *p = root;
aStack.push(NULL);
while(p != NULL){
//先访问根
cout << p->val;
//右子数入栈
if (p->right != NULL){
aStack.push(p->right);
}
//左子树下降
if (p->left != NULL){
p = p->left;
}
else{
p = aStack.top();
aStack.pop();
}
}
}
//中序遍历 非递归
void InOrder(TreeNode *root){
stack<TreeNode *> aStack;
TreeNode *p = root;
while (!aStack.empty() || p != NULL){
if(p != NULL){
aStack.push(p);
p = p->left;
}
else{
p = aStack.top();
aStack.pop();
cout << p->val;
p = p->right;
}
}
}
//后续遍历 非递归
void PostOrder(TreeNode *root){
stack<element> aStack;
element node;
TreeNode *p = root;
while (!aStack.empty() || p != NULL){
while(p != NULL){
node.pointer = p;
//左路下降,tag至左
node.tag = Left;
aStack.push(node);
p = p->left;
}
node = aStack.top();
aStack.pop();
p = node.pointer;
if (node.tag == Left){
node.tag = Right;
//回到栈中
aStack.push(node);
p = p->right;
}
else{
cout << p->val;
//置p为NULL,使其继续弹栈
p = NULL;
}
}
}
int main()
{
TreeNode A(1), B(2), C(3), D(4), E(5), F(6), G(7), H(8), I(9);
A.left = &B;
A.right = &C;
B.left = &D;
B.right = &E;
E.left = &G;
C.right = &F;
F.left = &H;
F.right = &I;
cout <<"前序遍历:\n";
PreOrder(&A);
cout <<"\n中序遍历:\n";
InOrder(&A);
cout <<"\n后序遍历:\n";
PostOrder(&A);
return 0;
}
| [
"hujunyu1222@gmail.com"
] | hujunyu1222@gmail.com |
d9b62a95dead57b38aac2cb4ef7da6bc5903750e | 59c94d223c8e1eb1720d608b9fc040af22f09e3a | /garnet/bin/run_test_component/run_test_component.cc | 4cf09e53e5cdee8d008d01abadd7fa6b154fdc39 | [
"BSD-3-Clause"
] | permissive | bootingman/fuchsia2 | 67f527712e505c4dca000a9d54d3be1a4def3afa | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | refs/heads/master | 2022-12-25T20:28:37.134803 | 2019-05-14T08:26:08 | 2019-05-14T08:26:08 | 186,606,695 | 1 | 1 | BSD-3-Clause | 2022-12-16T21:17:16 | 2019-05-14T11:17:16 | C++ | UTF-8 | C++ | false | false | 3,219 | cc | // Copyright 2018 The Fuchsia 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 "garnet/bin/run_test_component/run_test_component.h"
#include <fuchsia/sys/index/cpp/fidl.h>
#include <glob.h>
#include <lib/fit/defer.h>
#include <lib/sys/cpp/service_directory.h>
#include <regex>
#include <string>
#include "src/lib/fxl/strings/string_printf.h"
#include "src/lib/pkg_url/fuchsia_pkg_url.h"
namespace run {
using fuchsia::sys::index::ComponentIndex_FuzzySearch_Result;
using fuchsia::sys::index::ComponentIndexSyncPtr;
static constexpr char kComponentIndexerUrl[] =
"fuchsia-pkg://fuchsia.com/component_index#meta/component_index.cmx";
ParseArgsResult ParseArgs(
const std::shared_ptr<sys::ServiceDirectory>& services, int argc,
const char** argv) {
ParseArgsResult result;
result.error = false;
if (argc < 2) {
result.error = true;
result.error_msg = "Pass atleast one argument";
return result;
}
std::string url = argv[1];
if (!component::FuchsiaPkgUrl::IsFuchsiaPkgScheme(url)) {
fuchsia::sys::LaunchInfo index_launch_info;
index_launch_info.url = kComponentIndexerUrl;
auto index_provider = sys::ServiceDirectory::CreateWithRequest(
&index_launch_info.directory_request);
// Connect to the Launcher service through our static environment.
fuchsia::sys::LauncherSyncPtr launcher;
services->Connect(launcher.NewRequest());
fuchsia::sys::ComponentControllerPtr component_index_controller;
launcher->CreateComponent(std::move(index_launch_info),
component_index_controller.NewRequest());
ComponentIndexSyncPtr index;
index_provider->Connect(index.NewRequest());
std::string test_name = argv[1];
ComponentIndex_FuzzySearch_Result fuzzy_search_result;
zx_status_t status = index->FuzzySearch(test_name, &fuzzy_search_result);
if (status != ZX_OK) {
result.error = true;
result.error_msg = fxl::StringPrintf(
"\"%s\" is not a valid URL. Attempted to match to a URL with "
"fuchsia.sys.index.FuzzySearch, but the service is not available.",
test_name.c_str());
return result;
}
if (fuzzy_search_result.is_err()) {
result.error = true;
result.error_msg = fxl::StringPrintf(
"\"%s\" contains unsupported characters for fuzzy "
"matching. Valid characters are [A-Z a-z 0-9 / _ - .].\n",
test_name.c_str());
return result;
} else {
std::vector<std::string> uris = fuzzy_search_result.response().uris;
if (uris.size() == 0) {
result.error = true;
result.error_msg = fxl::StringPrintf(
"\"%s\" did not match any components.\n", test_name.c_str());
return result;
} else {
for (auto& uri : uris) {
result.matching_urls.push_back(uri);
}
if (uris.size() > 1) {
return result;
}
url = uris[0];
}
}
}
result.launch_info.url = url;
for (int i = 2; i < argc; i++) {
result.launch_info.arguments.push_back(argv[i]);
}
return result;
}
} // namespace run
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
cb82e1c523f9630a1e956e2563e02bb529a80012 | 01193a36c2c26af2856333e7ee4d535716b0bb32 | /Source/UePortal/Portal/Throughable.h | c5d76f79ba2ff1c60a42a4e4c38fb284669837b2 | [] | no_license | WeaponSoon/UePortal | 50310ac14e17c8786a32b0eb8d336a0a4f9d2c3f | b139cb8042273a652b30d000f0611a7b04ccb413 | refs/heads/master | 2020-04-11T19:20:52.562799 | 2019-01-07T08:19:35 | 2019-01-07T08:19:35 | 162,031,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,593 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "PortalDoorComponent.h"
#include "Throughable.generated.h"
class UThroughableComponent;
USTRUCT()
struct FThroughablePrePhysicsTickFunction : public FTickFunction
{
GENERATED_USTRUCT_BODY()
/** CharacterMovementComponent that is the target of this tick **/
class UThroughableComponent* Target;
/**
* Abstract function actually execute the tick.
* @param DeltaTime - frame time to advance, in seconds
* @param TickType - kind of tick for this frame
* @param CurrentThread - thread we are executing on, useful to pass along as new tasks are created
* @param MyCompletionGraphEvent - completion event for this task. Useful for holding the completion of this task until certain child tasks are complete.
**/
virtual void ExecuteTick(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) override;
/** Abstract function to describe this tick. Used to print messages about illegal cycles in the dependency graph **/
virtual FString DiagnosticMessage() override;
};
template<>
struct TStructOpsTypeTraits<FThroughablePrePhysicsTickFunction> : public TStructOpsTypeTraitsBase2<FThroughablePrePhysicsTickFunction>
{
enum
{
WithCopy = false
};
};
USTRUCT()
struct FThroughablePostPhysicsTickFunction : public FTickFunction
{
GENERATED_USTRUCT_BODY()
/** CharacterMovementComponent that is the target of this tick **/
class UThroughableComponent* Target;
/**
* Abstract function actually execute the tick.
* @param DeltaTime - frame time to advance, in seconds
* @param TickType - kind of tick for this frame
* @param CurrentThread - thread we are executing on, useful to pass along as new tasks are created
* @param MyCompletionGraphEvent - completion event for this task. Useful for holding the completion of this task until certain child tasks are complete.
**/
virtual void ExecuteTick(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) override;
/** Abstract function to describe this tick. Used to print messages about illegal cycles in the dependency graph **/
virtual FString DiagnosticMessage() override;
};
template<>
struct TStructOpsTypeTraits<FThroughablePostPhysicsTickFunction> : public TStructOpsTypeTraitsBase2<FThroughablePostPhysicsTickFunction>
{
enum
{
WithCopy = false
};
};
// This class does not need to be modified.
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class UEPORTAL_API UThroughableComponent : public UActorComponent
{
GENERATED_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
UThroughableComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
UPROPERTY()
struct FThroughablePostPhysicsTickFunction PostPhysicsTickFunction;
UPROPERTY()
struct FThroughablePrePhysicsTickFunction PrePhysicsTickFunction;
TSet<TWeakObjectPtr<UPortalDoorComponent>> nearPortals;
TWeakObjectPtr<UPortalDoorComponent> passingPortal;
TWeakObjectPtr<USceneComponent> throughableComponent;
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
UFUNCTION()
void AddNearPortalDoor(UPortalDoorComponent* nearPortal);
UFUNCTION()
void RemoveNearPortalDoor(UPortalDoorComponent* nearPortal);
UFUNCTION()
void UpdatePassingPortal();
UFUNCTION(BlueprintCallable, Category="Portal Component")
void SetThroughableComponent(class USceneComponent* throughable);
static const TMap<TWeakObjectPtr<USceneComponent>, TWeakObjectPtr<UThroughableComponent>>& GetThroughableMap();
virtual void PrePhysics(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent);
virtual void PostPhysics(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent);
virtual void RegisterComponentTickFunctions(bool bRegister) override;
protected:
UFUNCTION()
virtual void OnSetThroughableComponent(class USceneComponent* oldOne, class USceneComponent* newOne);
protected:
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void BeginPlay() override;
private:
static TMap<TWeakObjectPtr<USceneComponent>, TWeakObjectPtr<UThroughableComponent>> throughableMap;
};
| [
"sdswp@126.com"
] | sdswp@126.com |
64ceb2929e3822d9dae61e0431532518b9941a61 | 8cf32b4cbca07bd39341e1d0a29428e420b492a6 | /programs/nodeseat/main.cpp | 6a4709d381d452bbd27c04f11c5a349aa837cb0d | [
"MIT"
] | permissive | cubetrain/CubeTrain | e1cd516d5dbca77082258948d3c7fc70ebd50fdc | b930a3e88e941225c2c54219267f743c790e388f | refs/heads/master | 2020-04-11T23:00:50.245442 | 2018-12-17T16:07:16 | 2018-12-17T16:07:16 | 156,970,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,229 | cpp | /**
* @file
* @copyright defined in cubetrain/LICENSE.txt
*/
#include <appbase/application.hpp>
#include <cubetrain/chain_plugin/chain_plugin.hpp>
#include <cubetrain/http_plugin/http_plugin.hpp>
#include <cubetrain/history_plugin/history_plugin.hpp>
#include <cubetrain/net_plugin/net_plugin.hpp>
#include <cubetrain/producer_plugin/producer_plugin.hpp>
#include <cubetrain/utilities/common.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/log/appender.hpp>
#include <fc/exception/exception.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "config.hpp"
using namespace appbase;
using namespace cubetrain;
namespace fc {
std::unordered_map<std::string,appender::ptr>& get_appender_map();
}
namespace detail {
void configure_logging(const bfs::path& config_path)
{
try {
try {
fc::configure_logging(config_path);
} catch (...) {
elog("Error reloading logging.json");
throw;
}
} catch (const fc::exception& e) {
elog("${e}", ("e",e.to_detail_string()));
} catch (const boost::exception& e) {
elog("${e}", ("e",boost::diagnostic_information(e)));
} catch (const std::exception& e) {
elog("${e}", ("e",e.what()));
} catch (...) {
// empty
}
}
} // namespace detail
void logging_conf_loop()
{
std::shared_ptr<boost::asio::signal_set> sighup_set(new boost::asio::signal_set(app().get_io_service(), SIGHUP));
sighup_set->async_wait([sighup_set](const boost::system::error_code& err, int /*num*/) {
if(!err)
{
ilog("Received HUP. Reloading logging configuration.");
auto config_path = app().get_logging_conf();
if(fc::exists(config_path))
::detail::configure_logging(config_path);
for(auto iter : fc::get_appender_map())
iter.second->initialize(app().get_io_service());
logging_conf_loop();
}
});
}
void initialize_logging()
{
auto config_path = app().get_logging_conf();
if(fc::exists(config_path))
fc::configure_logging(config_path); // intentionally allowing exceptions to escape
for(auto iter : fc::get_appender_map())
iter.second->initialize(app().get_io_service());
logging_conf_loop();
}
enum return_codes {
OTHER_FAIL = -2,
INITIALIZE_FAIL = -1,
SUCCESS = 0,
BAD_ALLOC = 1,
DATABASE_DIRTY = 2,
FIXED_REVERSIBLE = 3,
EXTRACTED_GENESIS = 4,
NODE_MANAGEMENT_SUCCESS = 5
};
int main(int argc, char** argv)
{
try {
app().set_version(cubetrain::nodeseat::config::version);
app().register_plugin<history_plugin>();
auto root = fc::app_path();
app().set_default_data_dir(root / "cubetrain/nodeseat/data" );
app().set_default_config_dir(root / "cubetrain/nodeseat/config" );
if(!app().initialize<chain_plugin, http_plugin, net_plugin, producer_plugin>(argc, argv))
return INITIALIZE_FAIL;
initialize_logging();
ilog("nodeseat version ${ver}", ("ver", app().version_string()));
ilog("cubetrain root is ${root}", ("root", root.string()));
app().startup();
app().exec();
} catch( const extract_genesis_state_exception& e ) {
return EXTRACTED_GENESIS;
} catch( const fixed_reversible_db_exception& e ) {
return FIXED_REVERSIBLE;
} catch( const node_management_success& e ) {
return NODE_MANAGEMENT_SUCCESS;
} catch( const fc::exception& e ) {
if( e.code() == fc::std_exception_code ) {
if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else if( e.top_message().find( "database metadata dirty flag set" ) != std::string::npos ) {
elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
}
}
elog( "${e}", ("e", e.to_detail_string()));
return OTHER_FAIL;
} catch( const boost::interprocess::bad_alloc& e ) {
elog("bad alloc");
return BAD_ALLOC;
} catch( const boost::exception& e ) {
elog("${e}", ("e",boost::diagnostic_information(e)));
return OTHER_FAIL;
} catch( const std::runtime_error& e ) {
if( std::string(e.what()) == "database dirty flag set" ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else if( std::string(e.what()) == "database metadata dirty flag set" ) {
elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else {
elog( "${e}", ("e",e.what()));
}
return OTHER_FAIL;
} catch( const std::exception& e ) {
elog("${e}", ("e",e.what()));
return OTHER_FAIL;
} catch( ... ) {
elog("unknown exception");
return OTHER_FAIL;
}
return SUCCESS;
}
| [
"1848@shanchain.com"
] | 1848@shanchain.com |
938b9a5384ad75f399c62be573d118e86ee5d15b | c971f2bb3a0a547daedfdc637c9be4a6ed63be29 | /environmental/main.cpp | 85768f670a84d0d1d06d511b7925e7914509fbfe | [
"BSD-3-Clause"
] | permissive | eric33440/project_connect | fc6ab5ee97844d1879289c638713887318553db1 | 531dd94d22b8af83d0837f1c73c492ea0ac341dd | refs/heads/master | 2020-12-20T04:53:41.446443 | 2019-12-14T09:00:15 | 2019-12-14T09:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | cpp | /**
* @file main.cpp
* @author Eric Rebillon (eric.rebillon@ynov.com)
* @brief
* @version 0.1
* @date 2019-11-29
*
* @copyright Copyright (c) 2019
*
*/
#include <QCoreApplication>
#include <QObject>
#include "Sensor.h"
/**
* @brief main
* @param argc
* @param argv
* @return
* call the class contains the both class
*/
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Sensor *sensor = new Sensor();
Q_UNUSED(sensor)
a.exec();
}
| [
"offougajoris@gmail.com"
] | offougajoris@gmail.com |
4242e38f548e2919099daa905b9db61b73e7f2fe | 63d2a6e4de06261adb6eedf312171be3f8c45f46 | /Lab5/Hash_Table/login.cpp | a32776cd4ca6a44b09c77ef7f9615c9ebbc91dd0 | [
"MIT"
] | permissive | HanlinHu/CS210_LAB_code | 17963ae5e801d81407fd1affd91fda10d6bd6c3c | c0f2d89cb6b1d2047bd6fea7e2a041660245dc32 | refs/heads/master | 2020-05-29T21:25:45.776141 | 2015-08-21T22:46:48 | 2015-08-21T22:46:48 | 39,524,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,205 | cpp | //--------------------------------------------------------------------
//
// Hash Table Application: STL unordered_map
// Based on Laboratory 12 from
// A Laboratory Course in C++ Data Structures, Second Edition
//
// Modified by Alex Clarke on Nov. 8, 2014
//
// Complete this program so that it:
// 1) Inserts Passwords structures into the passwords unordered_map
// using username as the hashkey.
// Print the full contents of the hashtable to confirm that it worked.
//
// 2) "Authenticates" user login attempts using the the hashtable
//
// 3) Uses a custom hash function specified in the lab notes.
//
//--------------------------------------------------------------------
#include <string>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <iomanip>
using namespace std;
//This will be the data stored in the HashTbl (class DT)
struct UserInfo
{
string firstname,
lastname,
password;
};
//*****************************************************************
// Step 3a: Add your own string hashing class
//*****************************************************************
// Our special string hashing class
class stringHash{
public:
size_t operator()(const string& Hashit) const
{
size_t val = 0;
for (size_t i = 0; i < Hashit.length(); i++)
{
val += Hashit[i];
}
return val;
}
};
int main()
{
//*************************************************************
// Step 3b: Use your own hash function
//*************************************************************
//** Rewrite this line so it uses one of your string hashing
//** objects instead of the STL string hasher.
//** You must complete Step 3a for it to work.
unordered_map<string, UserInfo> passwords;
unordered_map<string, UserInfo>::iterator i;
UserInfo tempInfo;
string username, // user-supplied name
password; // user-supplied password
//*************************************************************
// Step 1a: Read in the password file
//*************************************************************
ifstream passFile( "password.dat" );
if ( !passFile )
{
cout << "Unable to open 'password.dat'!" << endl;
return 1;
}
while (passFile >> username >> tempInfo.password
>> tempInfo.firstname >> tempInfo.lastname)
{
//**add code here to insert user info into the unordered_map
//Note: passwords is the name of the unordered map
// username is the key
// tempInfo is the mapped value
passwords[username] = tempInfo;
}
//*************************************************************
// Step 1b: Show that the data is in the hash table
//*************************************************************
//** add code here to traverse and print the unordered_map
cout << "Number of entries in table: " << passwords.size() << endl;
cout << "Number of buckets: " << passwords.bucket_count() << endl;
for (i = passwords.begin(); i != passwords.end(); i++)
{
cout << setw(10) << left << i->first << setw(4) << passwords.bucket(i->first);
cout << setw(15) << i->second.password;
cout << setw(10) << i->second.firstname;
cout << setw(10) << i->second.lastname << endl;
}
cout << endl;
//*********************************************************
// Step 2: Prompt for a Login and Password and check if valid
//*********************************************************
cout << "Login: ";
while ( cin >> username ) // to quit, type CTRL Z in Visual C++
{
cout << "Password: ";
cin >> password;
//** Retrieve element based on key.
i = passwords.find(username);
//** if user existed in table and
//** if the retrieved user password matches the
//** input password print "Authentication succeeded."
//** followed by the user's information
if (i != passwords.end() && password == i->second.password)
{
cout <<"Authentication succeeded"<< endl;
cout << i->second.firstname << " " << i->second.lastname << endl;
}
//** in all other cases print "Authentication failed."
else
{
cout << "Authentication failed" << endl;
}
cout << "Login: ";
}
cout << endl;
return 0;
}
| [
"HanlinHu@users.noreply.github.com"
] | HanlinHu@users.noreply.github.com |
8e27382a945eefbdcc9852a9a0b672a732f72453 | 7046a5f8618ec6b3b015d03e68e2f4b7b7090288 | /3DAugmentation/Ferns/RealFerns/affine_image_generator06.cc | 2ede4e8528d777491a79e12fbcf9562af5af8836 | [] | no_license | dmaulikr/3DAugmentation | ca48bbb2dddcdd5fe1766c357595cbeba76b8292 | fc41bd799e81c387720f5870d1b1418691050b9a | refs/heads/master | 2021-01-01T19:36:15.639180 | 2013-06-19T10:09:35 | 2013-06-19T10:09:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,583 | cc | /*
Copyright 2007 Computer Vision Lab,
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland.
All rights reserved.
Author: Vincent Lepetit (http://cvlab.epfl.ch/~lepetit)
This file is part of the ferns_demo software.
ferns_demo 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.
ferns_demo 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
ferns_demo; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
#include "general.h"
#include "mcv.h"
#include "affine_image_generator06.h"
static const int prime = 307189;
affine_image_generator06::affine_image_generator06(void)
{
original_image = 0;
generated_image = 0;
original_image_with_128_as_background = 0;
white_noise = new char[prime];
limited_white_noise = new int[prime];
set_default_values();
save_images = false;
}
affine_image_generator06::~affine_image_generator06(void)
{
if (original_image != 0) cvReleaseImage(&original_image);
if (generated_image != 0) cvReleaseImage(&generated_image);
if (original_image_with_128_as_background) cvReleaseImage(&original_image_with_128_as_background);
delete [] white_noise;
delete [] limited_white_noise;
}
void affine_image_generator06::load_transformation_range(ifstream & f)
{
transformation_range.load(f);
}
void affine_image_generator06::save_transformation_range(ofstream & f)
{
transformation_range.save(f);
}
void affine_image_generator06::set_transformation_range(affine_transformation_range * range)
{
transformation_range = *range;
}
void affine_image_generator06::generate_Id_image(void)
{
generate_Id_affine_transformation();
generate_affine_image();
}
void affine_image_generator06::generate_random_affine_image(void)
{
generate_random_affine_transformation();
generate_affine_image();
}
void affine_image_generator06::save_generated_images(char * generic_name)
{
save_images = true;
strcpy(generic_name_of_saved_images, generic_name);
}
void affine_image_generator06::set_default_values(void)
{
set_noise_level(20);
set_use_random_background(true);
set_add_gaussian_smoothing(true);
set_change_intensities(true);
add_noise = true;
}
void affine_image_generator06::set_noise_level(int noise_level)
{
this->noise_level = noise_level;
index_white_noise = 0;
for(int i = 0; i < prime; i++) {
limited_white_noise[i] = rand() % (2 * noise_level) - noise_level;
white_noise[i] = char(rand() % 256);
}
}
void affine_image_generator06::set_original_image(IplImage * p_original_image,
int generated_image_width,
int generated_image_height)
{
if (original_image != 0) cvReleaseImage(&original_image);
original_image = cvCloneImage(p_original_image);
if (generated_image != 0) cvReleaseImage(&generated_image);
if (generated_image_width < 0)
generated_image = cvCloneImage(p_original_image);
else
generated_image = cvCreateImage(cvSize(generated_image_width, generated_image_height), IPL_DEPTH_8U, 1);
if (original_image_with_128_as_background != 0) cvReleaseImage(&original_image_with_128_as_background);
original_image_with_128_as_background = cvCloneImage(p_original_image);
mcvReplace(original_image_with_128_as_background, 128, int(127));
}
void affine_image_generator06::set_mask(int x_min, int y_min, int x_max, int y_max)
{
for(int v = 0; v < original_image_with_128_as_background->height; v++) {
unsigned char * row = mcvRow(original_image_with_128_as_background, v, unsigned char);
for(int u = 0; u < original_image_with_128_as_background->width; u++)
if (u < x_min || u > x_max || v < y_min || v > y_max)
row[u] = 128;
}
}
void affine_image_generator06::generate_affine_transformation(float a[6],
float initialTx, float initialTy,
float theta, float phi,
float lambda1, float lambda2,
float finalTx, float finalTy)
{
float t1 = cos(theta);
float t2 = cos(phi);
float t4 = sin(theta);
float t5 = sin(phi);
float t7 = t1 * t2 + t4 * t5;
float t8 = t7 * lambda1;
float t12 = t1 * t5 - t4 * t2;
float t13 = t12 * lambda2;
float t15 = t8 * t2 + t13 * t5;
float t18 = -t8 * t5 + t13 * t2;
float t22 = -t12 * lambda1;
float t24 = t7 * lambda2;
float t26 = t22 * t2 + t24 * t5;
float t29 = -t22 * t5 + t24 * t2;
a[0] = t15;
a[1] = t18;
a[2] = t15 * initialTx + t18 * initialTy + finalTx;
a[3] = t26;
a[4] = t29;
a[5] = t26 * initialTx + t29 * initialTy + finalTy;
}
void affine_image_generator06::generate_random_affine_transformation(void)
{
float theta, phi, lambda1, lambda2;
transformation_range.generate_random_parameters(theta, phi, lambda1, lambda2);
generate_affine_transformation(a, 0, 0, theta, phi, lambda1, lambda2, 0, 0);
int Tx, Ty;
float nu0, nv0, nu1, nv1, nu2, nv2, nu3, nv3;
affine_transformation(0., 0., nu0, nv0);
affine_transformation(float(original_image->width), 0., nu1, nv1);
affine_transformation(float(original_image->width), float(original_image->height), nu2, nv2);
affine_transformation(0., float(original_image->height), nu3, nv3);
if (rand() % 2 == 0) Tx = -(int)min(min(nu0, nu1), min(nu2, nu3));
else Tx = generated_image->width - (int)max(max(nu0, nu1), max(nu2, nu3));
if (rand() % 2 == 0) Ty = -(int)min(min(nv0, nv1), min(nv2, nv3));
else Ty = generated_image->height - (int)max(max(nv0, nv1), max(nv2, nv3));
generate_affine_transformation(a, 0., 0., theta, phi, lambda1, lambda2, float(Tx), float(Ty));
}
void affine_image_generator06::generate_Id_affine_transformation(void)
{
generate_affine_transformation(a, 0, 0 , 0, 0, 1, 1, 0, 0);
}
void affine_image_generator06::affine_transformation(float p_a[6],
float u, float v,
float & nu, float & nv)
{
nu = u * p_a[0] + v * p_a[1] + p_a[2];
nv = u * p_a[3] + v * p_a[4] + p_a[5];
}
void affine_image_generator06::inverse_affine_transformation(float p_a[6],
float u, float v,
float & nu, float & nv)
{
float det = p_a[0] * p_a[4] - p_a[3] * p_a[1];
nu = 1.f / det * ( p_a[4] * (u - p_a[2]) - p_a[1] * (v - p_a[5]));
nv = 1.f / det * (-p_a[3] * (u - p_a[2]) + p_a[0] * (v - p_a[5]));
}
void affine_image_generator06::affine_transformation(float u, float v, float & nu, float & nv)
{
affine_transformation(a, u, v, nu, nv);
}
void affine_image_generator06::inverse_affine_transformation(float u, float v, float & nu, float & nv)
{
inverse_affine_transformation(a, u, v, nu, nv);
}
void affine_image_generator06::add_white_noise(IplImage * image, int gray_level_to_avoid)
{
for(int y = 0; y < image->height; y++) {
unsigned char * line = (unsigned char *)(image->imageData + y * image->widthStep);
int * noise = limited_white_noise + rand() % (prime - image->width);
for(int x = 0; x < image->width; x++) {
int p = int(*line);
if (p != gray_level_to_avoid) {
p += *noise;
*line = (p > 255) ? 255 : (p < 0) ? 0 : (unsigned char)p;
}
line++;
noise++;
}
}
}
void affine_image_generator06::replace_by_noise(IplImage * image, int value)
{
for(int y = 0; y < image->height; y++) {
unsigned char * row = mcvRow(image, y, unsigned char);
for(int x = 0; x < image->width; x++)
if (int(row[x]) == value) {
row[x] = white_noise[index_white_noise];
index_white_noise++;
if (index_white_noise >= prime) index_white_noise = 1 + rand() % 6;
}
}
}
void affine_image_generator06::generate_affine_image(void)
{
CvMat A = cvMat(2, 3, CV_32F, a);
if (use_random_background)
cvSet(generated_image, cvScalar(128));
else
cvSet(generated_image, cvScalar(rand() % 256));
cvWarpAffine(original_image_with_128_as_background, generated_image, &A,
CV_INTER_NN + CV_WARP_FILL_OUTLIERS /* + CV_WARP_INVERSE_MAP*/, cvScalarAll(128));
if (use_random_background)
replace_by_noise(generated_image, 128);
if (add_gaussian_smoothing && rand() % 3 == 0) {
int aperture = 3 + 2 * (rand() % 3);
cvSmooth(generated_image, generated_image, CV_GAUSSIAN, aperture, aperture);
}
if (change_intensities) cvCvtScale(generated_image, generated_image, rand(0.8f, 1.2f), rand(-10, 10));
// mcvSaveImage("g.bmp", generated_image);
// exit(0);
if (noise_level > 0 && add_noise) {
if (use_random_background)
add_white_noise(generated_image);
else
add_white_noise(generated_image, 128);
}
if (save_images) {
static int n = 0;
mcvSaveImage(generic_name_of_saved_images, n, generated_image);
n++;
}
}
| [
"yltastep@gmail.com"
] | yltastep@gmail.com |
4be381803c1e27e1848e59c4b612f93092e82185 | be4737ec5e569506a3beea5cdfedafdd778e32e1 | /secondmaximum.cpp | abe1f70de3483272e273778742a40ba78411cbaf | [] | no_license | Samykakkar/DSA-practice | 8fd49c690f9c6af56437cb09475e7796538df77b | d10938f34e9467688f178b6570ccc740d3cc4dff | refs/heads/master | 2023-07-24T22:10:26.953125 | 2021-09-06T09:26:00 | 2021-09-06T09:26:00 | 392,998,137 | 0 | 1 | null | 2021-08-13T10:46:25 | 2021-08-05T10:21:28 | C++ | UTF-8 | C++ | false | false | 727 | cpp | #include <iostream>
#include<vector>
using namespace std;
vector<int> largestandsecondlargest(int sizeofarray, int arr[])
{
int max= INT_MIN , max2=INT_MIN;
for(int i=0;i<sizeofarray;i++)
{
if(arr[i]>max)
{
max2=max;
max=arr[i];
}
else if(arr[i]>max2 && arr[i]!=max)
{
max2=arr[i];
}
}
if(max2==INT_MIN)
{
max2=-1;
}
vector<int> temp(2);
temp[0]=max;
temp[1]=max2;
return temp;
}
int main()
{
std::vector<int> arr[]={2,3,5,3,5};
int n= sizeof(arr)/sizeof(arr[0]);
cout<<"Largest and second largest are"<<" "<<largestandsecondlargest(n, arr)<<endl;
return 0;
} | [
"sam8377984375@gmail.com"
] | sam8377984375@gmail.com |
bd175753adeec83d03cdd8ce7e1be7dfdd41e764 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s01/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42.cpp | e8aa2f4df60dace10399f6fffeb07b6f1899cf38 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,830 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml
Template File: sources-sink-42.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sink: cpy
* BadSink : Copy string to data using strcpy()
* Flow Variant: 42 Data flow: data returned from one function to another in the same source file
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42
{
#ifndef OMITBAD
static char * badSource(char * data)
{
/* FLAW: Did not leave space for a null terminator */
data = new char[10];
return data;
}
void bad()
{
char * data;
data = NULL;
data = badSource(data);
{
char source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
strcpy(data, source);
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
static char * goodG2BSource(char * data)
{
/* FIX: Allocate space for a null terminator */
data = new char[10+1];
return data;
}
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
data = NULL;
data = goodG2BSource(data);
{
char source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
strcpy(data, source);
printLine(data);
delete [] data;
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
f09dbbfe499a36150b1b63d5b52c635b4d547c1e | 05f6bc4445a4e7d4dcf2d899520abd5ff5913599 | /trunk/VoiceEngine/audio_engine/modules/utility/source/audio_frame_operations.cc | ecda730daf905d175c0b64185712f7b23cedef3a | [] | no_license | XudongPan/audio-engine | c76deee93c751c5da2425b9ef56cf92337f191e6 | eea8b1f3943fb88088a90eab01d3572e49078eba | refs/heads/master | 2022-03-26T01:10:47.430520 | 2020-01-06T20:09:11 | 2020-01-06T20:09:11 | 32,212,042 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,977 | cc | #include "audio_engine/modules/interface/module_common_types.h"
#include "audio_engine/modules/utility/interface/audio_frame_operations.h"
namespace VoIP {
void AudioFrameOperations::MonoToStereo(const int16_t* src_audio,
int samples_per_channel,
int16_t* dst_audio) {
for (int i = 0; i < samples_per_channel; i++) {
dst_audio[2 * i] = src_audio[i];
dst_audio[2 * i + 1] = src_audio[i];
}
}
int AudioFrameOperations::MonoToStereo(AudioFrame* frame) {
if (frame->num_channels_ != 1) {
return -1;
}
if ((frame->samples_per_channel_ * 2) >= AudioFrame::kMaxDataSizeSamples) {
// Not enough memory to expand from mono to stereo.
return -1;
}
int16_t data_copy[AudioFrame::kMaxDataSizeSamples];
memcpy(data_copy, frame->data_,
sizeof(int16_t) * frame->samples_per_channel_);
MonoToStereo(data_copy, frame->samples_per_channel_, frame->data_);
frame->num_channels_ = 2;
return 0;
}
void AudioFrameOperations::StereoToMono(const int16_t* src_audio,
int samples_per_channel,
int16_t* dst_audio) {
for (int i = 0; i < samples_per_channel; i++) {
dst_audio[i] = (src_audio[2 * i] + src_audio[2 * i + 1]) >> 1;
}
}
int AudioFrameOperations::StereoToMono(AudioFrame* frame) {
if (frame->num_channels_ != 2) {
return -1;
}
StereoToMono(frame->data_, frame->samples_per_channel_, frame->data_);
frame->num_channels_ = 1;
return 0;
}
void AudioFrameOperations::SwapStereoChannels(AudioFrame* frame) {
if (frame->num_channels_ != 2) return;
for (int i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
int16_t temp_data = frame->data_[i];
frame->data_[i] = frame->data_[i + 1];
frame->data_[i + 1] = temp_data;
}
}
void AudioFrameOperations::Mute(AudioFrame& frame) {
memset(frame.data_, 0, sizeof(int16_t) *
frame.samples_per_channel_ * frame.num_channels_);
frame.energy_ = 0;
}
int AudioFrameOperations::Scale(float left, float right, AudioFrame& frame) {
if (frame.num_channels_ != 2) {
return -1;
}
for (int i = 0; i < frame.samples_per_channel_; i++) {
frame.data_[2 * i] =
static_cast<int16_t>(left * frame.data_[2 * i]);
frame.data_[2 * i + 1] =
static_cast<int16_t>(right * frame.data_[2 * i + 1]);
}
return 0;
}
int AudioFrameOperations::ScaleWithSat(float scale, AudioFrame& frame) {
int32_t temp_data = 0;
// Ensure that the output result is saturated [-32768, +32767].
for (int i = 0; i < frame.samples_per_channel_ * frame.num_channels_;
i++) {
temp_data = static_cast<int32_t>(scale * frame.data_[i]);
if (temp_data < -32768) {
frame.data_[i] = -32768;
} else if (temp_data > 32767) {
frame.data_[i] = 32767;
} else {
frame.data_[i] = static_cast<int16_t>(temp_data);
}
}
return 0;
}
} // namespace VoIP
| [
"hawking81@gmail.com"
] | hawking81@gmail.com |
3c8f8470d2bf3b4c4d7d339c0b3c89d421010eca | 0914ef830712bcddd43732f4f6d4c83d42f62430 | /SupportedTitles.cpp | 480cea409d8050d7ba44a1b994d246e45d9a6f2c | [] | no_license | interdpth/RD1Engine | e6f6cf8191429bb33d6e2e60434ed1b87ceccbdf | fb9ba7d7357fed4bfc490c5a97b9bd6163640932 | refs/heads/master | 2023-03-28T18:00:30.651415 | 2021-03-29T03:07:44 | 2021-03-29T03:07:44 | 150,758,140 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 113 | cpp | #include "SupportedTitles.h"
SupportedTitles::SupportedTitles()
{
}
SupportedTitles::~SupportedTitles()
{
}
| [
"interdpth@gmail.com"
] | interdpth@gmail.com |
3061e44c92b3fa6cbd719990c6229d6e879b68d3 | 286d04e93943ab67f18e9cad96211c050e4f9aee | /Arduino/msp430f2013_SD16_I2C/msp430f2013_SD16_I2C.ino | af3514e39aba4f16210bb81c74439d6795a4116f | [
"MIT"
] | permissive | agaelema/msp430f20x3_as_i2c_16bit_adc | 3b66a38be10e7bf505201b2adf3587338377a775 | 5c788fb15cdd05bb998a9a159e4da4baf5c56305 | refs/heads/master | 2020-05-16T01:28:43.140584 | 2019-04-22T04:45:32 | 2019-04-22T04:45:32 | 182,603,578 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,170 | ino | /******************************************************************************
* control SD16_A of MSP430F2013 as a I2C ADC
* - MSP430 address: 0X0B
******************************************************************************
*
* Arduino Uno/Nano
* -----------------
* | |
* I2C SDA -|A4 |
* I2C SCL -|A5 |
* | |
* | |
*
* check voltage levels between master and slave (iso converter if needed)
*
* Haroldo Amaral - 2019
* https://github.com/agaelema/msp430f20x3_as_i2c_16bit_adc
******************************************************************************/
#include "Arduino.h"
#include <Wire.h>
/******************************************************************************
* SD16 definitions and header
******************************************************************************/
#include "sd16_header.h"
#define SLV_Addr 0x0B // Address is 0x0B<<1 for R/W
/* Select operation mode - uncomment desired mode - comment all others */
//#define I2C_ADC_START_CONVERSION // start with current configuration
//#define I2C_ADC_STOP_CONVERSION
#define I2C_ADC_START_SING_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S
//#define I2C_ADC_START_CONT_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S
/******************************************************************************
* ADS1115 configuration
******************************************************************************/
#define ENABLE_ADS1115 // enable/disable ADS1115
#if defined ( ENABLE_ADS1115 )
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads(0x48);
#endif
/******************************************************************************
* setup
******************************************************************************/
void setup()
{
Serial.begin (9600);
while (!Serial);
#if defined (ENABLE_ADS1115)
ads.setGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.03125mV
ads.begin();
#endif
}
/******************************************************************************
* main program
******************************************************************************/
void loop()
{
int var = 0;
uint8_t counter = 0;
Wire.begin();
while(1)
{
#if defined (I2C_ADC_START_CONVERSION)
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_START_CONVERSION);
var = Wire.endTransmission();
#endif
#if defined (I2C_ADC_STOP_CONVERSION)
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_STOP_CONVERSION);
var = Wire.endTransmission();
#endif
#if defined (I2C_ADC_START_SING_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S)
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_LOW);
var = Wire.write(SD16_DF_2S_COMP);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_HIGH);
var = Wire.write(SD16_OSR_1024x|SD16_SNG_CONV|SD16_BIPOLAR);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_IN_CTRL);
var = Wire.write(SD16_CH1|SD16_GAIN1x);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_START_CONVERSION);
var = Wire.endTransmission();
#endif
#if defined (I2C_ADC_START_CONT_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S)
if ( counter == 0 )
{
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_LOW);
var = Wire.write(SD16_DF_2S_COMP);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_HIGH);
var = Wire.write(SD16_OSR_1024x|SD16_CONT_CONV|SD16_BIPOLAR);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_IN_CTRL);
var = Wire.write(SD16_CH1|SD16_GAIN1x);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_START_CONVERSION);
var = Wire.endTransmission();
}
counter++;
#endif
volatile int c = 0;
int counter = 0;
int16_t bufferReceived[2] = {0};
Wire.requestFrom(SLV_Addr, 2); // read 2 bytes from i2c
while (Wire.available())
{
c = Wire.read();
bufferReceived[counter] = (int16_t)c; // save on buffer
counter++;
}
/*
* convert 2 bytes in 1 16-bit integer variable
*/
int16_t received = 0;
received |= bufferReceived[0] & 0xFF;
received |= (bufferReceived[1] & 0xFF) << 8;
#if defined (ENABLE_ADS1115)
int16_t adc0 = 0;
adc0 = ads.readADC_Differential_0_1();
Serial.print((int16_t)(adc0 & 0xFFFF)); Serial.print(' ');
#endif
Serial.println((int16_t)(received & 0xFFFF));
}
}
| [
"agaelema@gmail.com"
] | agaelema@gmail.com |
4ff9a7669503e0562497176e8e0cba38d8c47038 | 1ef4c6274b3cfb29789c1f7f2fb513d489b7e6d7 | /stack/stack.cpp | 7dec1acecbf76d9238969662113cd606c861bc92 | [
"MIT"
] | permissive | theMorning/katas | 0b0bb797dabb8b72b54d32473c095680604c46a1 | b88bab906b3891eac9c375c865cd91ab8dcef6b8 | refs/heads/master | 2020-12-19T12:06:45.660274 | 2020-01-31T05:06:13 | 2020-01-31T05:06:13 | 235,729,036 | 0 | 0 | null | 2020-01-23T05:26:30 | 2020-01-23T05:26:29 | null | UTF-8 | C++ | false | false | 452 | cpp | #include "stack.hpp"
template <typename T> Stack<T>::Stack(int lim) {
size = 0;
position = 0;
limit = lim;
items = new T[lim];
}
template <typename T> Stack<T>::~Stack() { delete[] items; }
template <typename T> void Stack<T>::push(T item) {
items[position] = item;
size++;
position++;
}
template <typename T> T Stack<T>::pop() {
size--;
return items[--position];
}
template <typename T> int Stack<T>::getSize() { return size; }
| [
"ryantmcdermott@gmail.com"
] | ryantmcdermott@gmail.com |
4f8f3bae2902a4cf0c04e2e9fec2a6f27fcb5ed8 | 7f62f204ffde7fed9c1cb69e2bd44de9203f14c8 | /DboServer/Server/GameServer/BotAiAction_Escort.cpp | 240f0e6c9f8de42de0d4f8fe64f14f8fdea81fce | [] | no_license | 4l3dx/DBOGLOBAL | 9853c49f19882d3de10b5ca849ba53b44ab81a0c | c5828b24e99c649ae6a2953471ae57a653395ca2 | refs/heads/master | 2022-05-28T08:57:10.293378 | 2020-05-01T00:41:08 | 2020-05-01T00:41:08 | 259,094,679 | 3 | 3 | null | 2020-04-29T17:06:22 | 2020-04-26T17:43:08 | null | UTF-8 | C++ | false | false | 2,076 | cpp | #include "stdafx.h"
#include "BotAiAction_Escort.h"
#include "SPSNodeAction_Escort.h"
#include "BotAiAction_EscortFollow.h"
#include "BotAiState.h"
CBotAiAction_Escort::CBotAiAction_Escort(CNpc* pBot)
: CBotAiAction(pBot, BOTCONTROL_ACTION_DIRECT_PLAY, "BOTCONTROL_ACTION_DIRECT_PLAY")
{
m_eEscortType = INVALID_ESCORT_TYPE;
m_fRadius = 5.0f;
m_bRunMode = false;
m_eventID = INVALID_DWORD;
}
CBotAiAction_Escort::~CBotAiAction_Escort()
{
}
bool CBotAiAction_Escort::AttachControlScriptNode(CControlScriptNode* pControlScriptNode)
{
CSPSNodeAction_Escort* pAction = dynamic_cast<CSPSNodeAction_Escort*>(pControlScriptNode);
if (pAction)
{
m_eEscortType = pAction->m_eEscortType;
m_vDestLoc = pAction->m_vDestLoc;
m_fRadius = pAction->m_fRadius;
m_bRunMode = pAction->m_bRunMode;
m_eventID = pAction->m_eventID;
return true;
}
ERR_LOG(LOG_BOTAI, "fail : Can't dynamic_cast from CControlScriptNode[%X] to CSPSNodeAction_Escort", pControlScriptNode);
return false;
}
void CBotAiAction_Escort::OnEnter()
{
GetBot()->GetEscortManager()->Clear();
}
void CBotAiAction_Escort::OnExit()
{
}
int CBotAiAction_Escort::OnUpdate(DWORD dwTickDiff, float fMultiple)
{
return m_status;
}
int CBotAiAction_Escort::OnObjectMsg(CObjectMsg* pObjMsg) //on retail npc-server its OnEvent but we use objectmsg same as event because makes no sense to create event
{
if (pObjMsg->GetID() != OBJMSG_START_ESCORT)
return m_status;
CObjMsg_StartEscort* pMsg = check_cast<CObjMsg_StartEscort *>(pObjMsg);
if (!pMsg)
return m_status;
if (pMsg->m_byEscortType != m_eEscortType)
return m_status;
if (m_eEscortType == ESCORT_TYPE_TARGET_FOLLOW)
{
CBotAiState* pCurState = GetBot()->GetBotController()->GetCurrentState();
if (pCurState == NULL)
return m_status;
CBotAiAction_EscortFollow* pEscortFollow = new CBotAiAction_EscortFollow(GetBot(), m_vDestLoc, m_fRadius, m_bRunMode, m_eventID);
if (pCurState->AddSubControlQueue(pEscortFollow, true))
{
m_status = FAILED;
return m_status;
}
}
m_status = COMPLETED;
return m_status;
} | [
"64261665+dboguser@users.noreply.github.com"
] | 64261665+dboguser@users.noreply.github.com |
3161e4e9ca836dea1657c32bbab01941ec4cb567 | 2a8364c331fd6d052bf6001aa21ff8131830af0a | /boost/optional/stdafx.cpp | 2b1e85f26c8d3dcaf62fe4218b6c76deaf6f72ae | [] | no_license | sld666666/cpp_small_code | 5ceb3555be035079a9eb697707ebfc74c1ec3151 | aca310c403b2fd44da3d5a7924bc86c5944f8cc2 | refs/heads/master | 2021-01-10T22:03:12.161120 | 2014-08-25T15:27:48 | 2014-08-25T15:27:48 | 5,014,970 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 260 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// optional.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"sld666666@gmail.com"
] | sld666666@gmail.com |
79fca7ded61a43d50d58b437f972fbac21d2c716 | 5ec61911b971de3deb2e98b3fe92df1bba63db77 | /prj_4/obj_dir/Vmem__Syms.h | 243b42c70bd995cc4875679e876a88b992f08c7d | [] | no_license | nchronas/verilator_examples | 574ff2a9505ff47e33ae2861d61236ceb98678eb | 3fab42395a02f762ccfff7b71ad2f6bc4801e28d | refs/heads/master | 2021-01-23T16:53:00.316724 | 2017-06-09T10:53:38 | 2017-06-09T10:53:38 | 93,307,996 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | h | // Verilated -*- C++ -*-
// DESCRIPTION: Verilator output: Symbol table internal header
//
// Internal details; most calling programs do not need this header
#ifndef _Vmem__Syms_H_
#define _Vmem__Syms_H_
#include "verilated_heavy.h"
// INCLUDE MODULE CLASSES
#include "Vmem.h"
// SYMS CLASS
class Vmem__Syms : public VerilatedSyms {
public:
// LOCAL STATE
const char* __Vm_namep;
bool __Vm_activity; ///< Used by trace routines to determine change occurred
bool __Vm_didInit;
//char __VpadToAlign10[6];
// SUBCELL STATE
Vmem* TOPp;
// COVERAGE
// SCOPE NAMES
// CREATORS
Vmem__Syms(Vmem* topp, const char* namep);
~Vmem__Syms() {};
// METHODS
inline const char* name() { return __Vm_namep; }
inline bool getClearActivity() { bool r=__Vm_activity; __Vm_activity=false; return r;}
} VL_ATTR_ALIGNED(64);
#endif /*guard*/
| [
"nchronas@gmail.com"
] | nchronas@gmail.com |
bdcfa4aa5b724b6ba93dedb1075261714d934925 | d0a6fc4f9a4a2d96451faa34cf99df92039ba9b3 | /ReactCommon/turbomodule/core/TurboModuleBinding.cpp | 5b370eede9ae6d59ee1db793982d65b0629779d5 | [
"CC-BY-4.0",
"CC-BY-NC-SA-4.0",
"CC-BY-SA-4.0",
"MIT"
] | permissive | kylieclin/local_pick2 | 2e8bc0ca0995e38dacf8cb3bfd0f9ef722bb82ce | d696fcee4615ad4cb70545dfdf1f074c452fa175 | refs/heads/master | 2023-01-08T19:10:45.790326 | 2019-12-13T01:22:23 | 2019-12-13T01:22:23 | 192,242,298 | 0 | 0 | MIT | 2023-01-04T00:42:59 | 2019-06-16T22:24:26 | JavaScript | UTF-8 | C++ | false | false | 2,343 | cpp | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "TurboModuleBinding.h"
#include <string>
#include <cxxreact/SystraceSection.h>
#include <jsireact/LongLivedObject.h>
using namespace facebook;
namespace facebook {
namespace react {
/**
* Public API to install the TurboModule system.
*/
TurboModuleBinding::TurboModuleBinding(const TurboModuleProviderFunctionType &moduleProvider)
: moduleProvider_(moduleProvider) {}
void TurboModuleBinding::install(
jsi::Runtime &runtime,
std::shared_ptr<TurboModuleBinding> binding) {
runtime.global().setProperty(
runtime,
"__turboModuleProxy",
jsi::Function::createFromHostFunction(
runtime,
jsi::PropNameID::forAscii(runtime, "__turboModuleProxy"),
1,
[binding](jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) {
return binding->jsProxy(rt, thisVal, args, count);
}));
}
void TurboModuleBinding::invalidate() const {
// TODO (T45804587): Revisit this invalidation logic.
// The issue was that Promise resolve/reject functions that are invoked in
// some distance future might end up accessing PromiseWrapper that was already
// destroyed, if the binding invalidation removed it from the
// LongLivedObjectCollection.
// LongLivedObjectCollection::get().clear();
}
std::shared_ptr<TurboModule> TurboModuleBinding::getModule(const std::string &name) {
std::shared_ptr<TurboModule> module = nullptr;
{
SystraceSection s("TurboModuleBinding::getModule", "module", name);
module = moduleProvider_(name);
}
return module;
}
jsi::Value TurboModuleBinding::jsProxy(
jsi::Runtime& runtime,
const jsi::Value& thisVal,
const jsi::Value* args,
size_t count) {
if (count != 1) {
throw std::invalid_argument("TurboModuleBinding::jsProxy arg count must be 1");
}
std::string moduleName = args[0].getString(runtime).utf8(runtime);
std::shared_ptr<TurboModule> module = getModule(moduleName);
if (module == nullptr) {
return jsi::Value::null();
}
return jsi::Object::createFromHostObject(runtime, std::move(module));
}
} // namespace react
} // namespace facebook
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
d09caa8585ae593996bf75ed91e8d4477624461d | 9d1f6a1a84410652961fbff5aff437d7dc658eca | /Training001/Training001/stdafx.cpp | dc158effba270a4aec56478713ec5c540548c28e | [] | no_license | matei-re/holiday2018 | d46b87e1075a7a387a342b41fa09aca348bf775b | d22de5b887d979c4418ae2b5efa888a67f99e6e2 | refs/heads/master | 2020-03-21T09:26:01.955254 | 2018-08-01T16:02:57 | 2018-08-01T16:02:57 | 138,399,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Training001.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"re.matei@gmail.com"
] | re.matei@gmail.com |
8608aa9b6c947fe1ae5e9c64a8a6e94d66b6141a | f38fed03bd6efedc0c28cae62a60994a4f5a621c | /src/main.cpp | b66a7b1de82132836c5928cfb4eb98a6d666860a | [
"MIT"
] | permissive | fubendong2/kaiyuancoind | 8419effa746a783e63993966dcb212a7632c91c9 | 712b69af211c9dbdc6e1bb2a2db7164082db8dee | refs/heads/master | 2021-01-10T18:59:14.004257 | 2014-03-15T16:47:36 | 2014-03-15T16:47:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111,003 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Kaiyuancoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.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;
uint256 hashGenesisBlock("0xa2135e5d3b49440f7b71b51b4919787e78f1748f85b6892ee453d49166a399e5");
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Kaiyuancoin: starting difficulty is 1 / 2^12
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainWork = 0;
CBigNum bnBestInvalidWork = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "Kaiyuancoin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = 0;
int64 nMinimumInputValue = CENT / 1000;
//////////////////////////////////////////////////////////////////////////////
//
// 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)
{
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 static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// 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:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
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, CDataStream*>::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 CTransaction::IsStandard() const
{
if (nVersion > CTransaction::CURRENT_VERSION)
return false;
BOOST_FOREACH(const CTxIn& txin, 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;
}
BOOST_FOREACH(const CTxOut& txout, vout)
if (!::IsStandard(txout.scriptPubKey))
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)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
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 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
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"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (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 = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
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 (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : 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("CTxMemPool::accept() : 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 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
if (nFees < tx.GetMinFee(1000, true, GMF_RELAY))
return error("CTxMemPool::accept() : not enough fees");
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make other's transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(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("CTxMemPool::accept() : 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(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
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("CTxMemPool::accept() : accepted %s (poolsz %u)\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept 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(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
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::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// 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::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
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);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
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
//
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();
}
static const int64 nDiffChangeTarget = 600000;
int64 static GetBlockValue(int nHeight, int64 nFees)
{
int64 nSubsidy = 40 * COIN;
if (nHeight < 90)
{
nSubsidy = 8888888 * COIN;
}else if (nHeight < 990)
{
nSubsidy = 5 * COIN;
}else if (nHeight < 11790)
{
nSubsidy = 100 * COIN;
}else if (nHeight < 76590)
{
nSubsidy = 200 * COIN;
}else if (nHeight < 141390)
{
nSubsidy = 300 * COIN;
}else if (nHeight < 206190)
{
nSubsidy = 400 * COIN;
}else if (nHeight < 270990)
{
nSubsidy = 500 * COIN;
}else if (nHeight < 335790)
{
nSubsidy = 400 * COIN;
}else if (nHeight < 400590)
{
nSubsidy = 300 * COIN;
}else if (nHeight < 465390)
{
nSubsidy = 200 * COIN;
}else if (nHeight < 530190)
{
nSubsidy = 160 * COIN;
}else if (nHeight < 594990)
{
nSubsidy = 120 * COIN;
}else if (nHeight < 659790)
{
nSubsidy = 90 * COIN;
}else if (nHeight < 724590)
{
nSubsidy = 60 * COIN;
}
return nSubsidy + nFees;
}
static const int64 nTargetTimespan = 60 * 60; // Kaiyuancoin: 1 hour
static const int64 nTargetSpacing = 40; // Kaiyuancoin: 40 sec
static const int64 nInterval = nTargetTimespan / nTargetSpacing;
static const int64 nTargetTimespanRe = 60 * 60; // 60 Minutes
static const int64 nTargetSpacingRe = 30; // Kaiyuancoin: 30 seconds
static const int64 nIntervalRe = nTargetTimespanRe / nTargetSpacingRe;
//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
// Testnet has min-difficulty blocks
// after nTargetSpacing*2 time between blocks:
if (fTestNet && nTime > nTargetSpacing*2)
return bnProofOfWorkLimit.GetCompact();
CBigNum bnResult;
bnResult.SetCompact(nBase);
while (nTime > 0 && bnResult < bnProofOfWorkLimit)
{
if(nBestHeight+1<nDiffChangeTarget){
// Maximum 400% adjustment...
bnResult *= 6;
// ... in best-case exactly 4-times-normal target time
nTime -= nTargetTimespan*4;
} else {
// Maximum 10% adjustment...
bnResult = (bnResult * 110) / 100;
// ... in best-case exactly 4-times-normal target time
nTime -= nTargetTimespanRe*4;
}
}
if (bnResult > bnProofOfWorkLimit)
bnResult = bnProofOfWorkLimit;
return bnResult.GetCompact();
}
unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
{
unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
int nHeight = pindexLast->nHeight + 1;
bool fNewDifficultyProtocol = (nHeight >= nDiffChangeTarget || fTestNet);
int blockstogoback = 0;
//set default to pre-v6.4.3 patch values
int64 retargetTimespan = nTargetTimespan;
int64 retargetSpacing = nTargetSpacing;
int64 retargetInterval = nInterval;
// Genesis block
if (pindexLast == NULL) return nProofOfWorkLimit;
//if patch v6.4.3 changes are in effect for block num, alter retarget values
if(fNewDifficultyProtocol) {
retargetTimespan = nTargetTimespanRe;
retargetSpacing = nTargetSpacingRe;
retargetInterval = nIntervalRe;
}
// Only change once per interval
if ((pindexLast->nHeight+1) % retargetInterval != 0){
// Special difficulty rule for testnet:
if (fTestNet){
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->nTime > pindexLast->nTime + retargetSpacing*2)
return nProofOfWorkLimit;
else {
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % retargetInterval != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Kaiyuancoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
blockstogoback = retargetInterval-1;
if ((pindexLast->nHeight+1) != retargetInterval) blockstogoback = retargetInterval;
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
CBigNum bnNew;
bnNew.SetCompact(pindexLast->nBits);
// thanks to RealSolid for this code
if(fNewDifficultyProtocol) {
if (nActualTimespan < (retargetTimespan - (retargetTimespan/10)) ) nActualTimespan = (retargetTimespan - (retargetTimespan/10));
if (nActualTimespan > (retargetTimespan + (retargetTimespan/10)) ) nActualTimespan = (retargetTimespan + (retargetTimespan/10));
}
else {
if (nActualTimespan < retargetTimespan/4) nActualTimespan = retargetTimespan/4;
if (nActualTimespan > retargetTimespan*4) nActualTimespan = retargetTimespan*4;
}
// Retarget
bnNew *= nActualTimespan;
bnNew /= retargetTimespan;
/// debug print
printf("GetNextWorkRequired RETARGET \n");
printf("retargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", retargetTimespan, nActualTimespan);
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
if (bnNew > bnProofOfWorkLimit)
bnNew = bnProofOfWorkLimit;
return bnNew.GetCompact();
}
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()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainWork > bnBestInvalidWork)
{
bnBestInvalidWork = pindexNew->bnChainWork;
CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
uiInterface.NotifyBlocksChanged();
}
printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
// Updating time can change work required on testnet:
if (fTestNet)
nBits = GetNextWorkRequired(pindexPrev, this);
}
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 anway.
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
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
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());
txPrev = mempool.lookup(prevout.hash);
}
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's 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 %d %d 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 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 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(MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// 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 kaiyuancoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 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 %d %d 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, check that it's matured
if (txPrev.IsCoinBase())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
// 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, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
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 (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
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");
}
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock())
return false;
// 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 id's entirely.
// This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC.
int64 nBIP30SwitchTime = 1349049600;
bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime);
// BIP16 didn't become active until October 1 2012
int64 nBIP16SwitchTime = 1349049600;
bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
//// issue here: it doesn't know the version
unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
if (fEnforceBIP30) {
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);
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (!tx.IsCoinBase())
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
if (fStrictPayToScriptHash)
{
// 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"));
}
nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
// 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");
}
if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
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 = 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 %i 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 %i 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
vector<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
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!tx.IsCoinBase())
vResurrect.push_back(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)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(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 == hashGenesisBlock)
{
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->bnChainWork > pindexBest->bnChainWork)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %i reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect futher 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;
nBestHeight = pindexBest->nHeight;
bnBestChainWork = pindexNew->bnChainWork;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d work=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
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;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// 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");
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainWork > bnBestChainWork)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
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() 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 (!CheckProofOfWork(GetPoWHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
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 transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// 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 merkleroot
if (hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
// 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;
// Check proof of work
if (nBits != GetNextWorkRequired(pindexPrev, this))
return DoS(100, error("AcceptBlock() : incorrect proof of work"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(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::CheckBlock(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
// 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))
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));
}
return true;
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// 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());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
if (deltaTime < 0)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with timestamp before last checkpoint");
}
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little proof-of-work");
}
}
// 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());
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));
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());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
return true;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 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, "Kaiyuancoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", 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;
loop
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < 0x7F000000 - MAX_SIZE)
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
pchMessageStart[0] = 0xfc;
pchMessageStart[1] = 0xc1;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xdc;
hashGenesisBlock = uint256("0xa2135e5d3b49440f7b71b51b4919787e78f1748f85b6892ee453d49166a399e5");
}
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis Block:
// block.GetHash() = 7231b064d3e620c55960abce2963ea19e1c3ffb6f5ff70e975114835a7024107
// hashGenesisBlock = 7231b064d3e620c55960abce2963ea19e1c3ffb6f5ff70e975114835a7024107
// block.hashMerkleRoot = 4fe8c1ba0a102fea0643287bb22ce7469ecb9b690362013f269a423fefa77b6e
// CBlock(hash=7231b064d3e620c55960, PoW=ecab9c4d0cff0d84a093, ver=1, hashPrevBlock=00000000000000000000,
// hashMerkleRoot=4fe8c1ba0a, nTime=1368503907, nBits=1e0ffff0, nNonce=102158625, vtx=1)
// CTransaction(hash=4fe8c1ba0a, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d01044c534d61792031332c20323031332031313a3334706d204544543a20552e532e2063727564652066757475726573207765726520757020302e332070657263656e74206174202439352e343120612062617272656c)
// CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4)
// vMerkleTree: 4fe8c1ba0a
// Genesis block
const char* pszTimestamp = "kaiyuancoin kaiyuancoin";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 50 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1394784846;
block.nBits = 0x1e0ffff0;
block.nNonce = 331270;
if (fTestNet)
{
block.nTime = 1394784846;
block.nNonce = 1292958;
}
//// debug print
printf("block.GetHash() = %s\n", block.GetHash().ToString().c_str());
printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str());
printf("block.hashMerkleRoot = %s\n", block.hashMerkleRoot.ToString().c_str());
assert(block.hashMerkleRoot == uint256("0xe12ffcd9ad2477ee5072f5a4be98a5d1e32d5b5b306df5d7bf2c6d90ef0302de"));
// If genesis block hash does not match, then generate new genesis hash.
if (false && block.GetHash() != hashGenesisBlock)
//if (true)
{
printf("Searching for genesis block...\n");
// This will figure out a valid hash and Nonce if you're
// creating a different genesis block:
uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
uint256 thash;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
loop
{
scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
if (thash <= hashTarget)
break;
if ((block.nNonce & 0xFFF) == 0)
{
printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
}
++block.nNonce;
if (block.nNonce == 0)
{
printf("NONCE WRAPPED, incrementing time\n");
++block.nTime;
}
}
printf("block.nTime = %u \n", block.nTime);
printf("block.nNonce = %u \n", block.nNonce);
printf("block.GetHash = %s\n", block.GetHash().ToString().c_str());
}
block.print();
printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str());
printf("block.GetHash() = %s\n", block.GetHash().ToString().c_str());
assert(block.GetHash() == hashGenesisBlock);
// 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))
return error("LoadBlockIndex() : genesis block not accepted");
}
return true;
}
void PrintBlockTree()
{
// precompute 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 %s tx %d",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().substr(0,20).c_str(),
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main timechain 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)
{
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\n", nLoaded);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
map<uint256, CAlert> mapAlerts;
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;
}
// Longer invalid proof-of-work chain
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
{
nPriority = 2000;
strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
}
// 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 (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
CAlert CAlert::getAlertByHash(const uint256 &hash)
{
CAlert retval;
{
LOCK(cs_mapAlerts);
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
if(mi != mapAlerts.end())
retval = mi->second;
}
return retval;
}
bool CAlert::ProcessAlert()
{
return false;
//commenting out this code until we properly implement KYB alerts.
/*
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
{
printf("cancelling alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else if (!alert.IsInEffect())
{
printf("expiring alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.Cancels(*this))
{
printf("alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
// Notify UI if it applies to me
if(AppliesToMe())
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
}
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
return true;
*/
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
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] = { 0xfb, 0xc0, 0xb6, 0xdb }; // Kaiyuancoin: increase each by adding 2 to bitcoin's value.
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%d 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 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
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;
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.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->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);
}
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);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(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() = %d", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 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 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() > 50000)
{
pfrom->Misbehaving(20);
return error("message inv size() = %d", 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.
std::vector<CInv> vGetData(1,inv);
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() > 50000)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %d", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%d 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)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end())
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
}
}
// 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());
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 == "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;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
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 (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// 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;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
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 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 == "alnalert")
{
CAlert alert;
vRecv >> alert;
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alert.GetHash());
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
}
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;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
loop
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> 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;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
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;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from underlength 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 overlong 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);
}
vRecv.Compact();
return true;
}
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->vSend.empty()) {
uint64 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 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 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;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// It operates on big endian data. Caller does the byte reversing.
// All input buffers are 16-byte aligned. nNonce is usually preserved
// between calls, but periodically or if nNonce is 0xffff0000 or above,
// the block is rebuilt and nNonce starts over at zero.
//
unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
{
unsigned int& nNonce = *(unsigned int*)(pdata + 12);
for (;;)
{
// Crypto++ SHA-256
// Hash pdata using pmidstate as the starting state into
// preformatted buffer phash1, then hash phash1 into phash
nNonce++;
SHA256Transform(phash1, pdata, pmidstate);
SHA256Transform(phash, phash1, pSHA256InitState);
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
if (((unsigned short*)phash)[14] == 0)
return nNonce;
// If nothing found after trying for a while, return -1
if ((nNonce & 0xffff) == 0)
{
nHashesDone = 0xffff+1;
return (unsigned int) -1;
}
}
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
CBlock* CreateNewBlock(CReserveKey& reservekey)
{
CBlockIndex* pindexPrev = pindexBest;
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
multimap<double, CTransaction*> mapPriority;
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
// Read block header
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
if (fDebug && GetBoolArg("-printpriority"))
printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
}
// Priority is sum(valuein * age) / txsize
dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (porphan)
porphan->dPriority = dPriority;
else
mapPriority.insert(make_pair(-dPriority, &(*mi).second));
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
if (porphan)
porphan->print();
printf("\n");
}
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
while (!mapPriority.empty())
{
// Take highest priority transaction off priority queue
double dPriority = -(*mapPriority.begin()).first;
CTransaction& tx = *(*mapPriority.begin()).second;
mapPriority.erase(mapPriority.begin());
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Transaction fee required depends on block size
// Kaiyuancoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes)
bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority));
int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
printf("CreateNewBlock(): total size %lu\n", nBlockSize);
}
pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
pblock->UpdateTime(pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
pblock->nNonce = 0;
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Prebuild hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetPoWHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget)
return false;
//// debug print
printf("BitcoinMiner:\n");
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("BitcoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
void static BitcoinMiner(CWallet *pwallet)
{
printf("BitcoinMiner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("bitcoin-miner");
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (fGenerateBitcoins)
{
if (fShutdown)
return;
while (vNodes.empty() || IsInitialBlockDownload())
{
Sleep(1000);
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
}
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
//
// Prebuild hash buffers
//
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
//unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
loop
{
unsigned int nHashesDone = 0;
//unsigned int nNonceFound;
uint256 thash;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
loop
{
scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad);
if (thash <= hashTarget)
{
// Found a solution
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
pblock->nNonce += 1;
nHashesDone += 1;
if ((pblock->nNonce & 0xFF) == 0)
break;
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return;
if (vNodes.empty())
break;
if (pblock->nNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);
if (fTestNet)
{
// Changing pblock->nTime can change work required on testnet:
nBlockBits = ByteReverse(pblock->nBits);
hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
}
}
}
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!CreateThread(ThreadBitcoinMiner, pwallet))
printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
| [
"fubendong100@163.com"
] | fubendong100@163.com |
a3e67b3f3d07fd3af99f1114b1d92233993c49f9 | b233702c5bb01514838ad6d3213f785f54f83ecb | /extra/chromium/files/patch-extensions_browser_api_serial_serial__api.cc | 8d02a3abb95dbdf00d447ddb5a30077385a24516 | [] | no_license | markzz/abs | f44d8d3c03653c7fec96f0702dd16c93790ea23e | f142c918c3d679b807f4548bcb926976364d0a8b | refs/heads/master | 2021-01-21T15:37:29.684333 | 2017-05-19T23:21:51 | 2017-05-19T23:21:51 | 91,852,456 | 0 | 0 | null | 2017-05-19T23:26:25 | 2017-05-19T23:26:25 | null | UTF-8 | C++ | false | false | 662 | cc | --- extensions/browser/api/serial/serial_api.cc.orig 2016-05-25 15:01:02.000000000 -0400
+++ extensions/browser/api/serial/serial_api.cc 2016-05-27 11:12:01.060235000 -0400
@@ -86,11 +86,13 @@
void SerialGetDevicesFunction::Work() {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+#if !defined(OS_BSD)
scoped_ptr<device::SerialDeviceEnumerator> enumerator =
device::SerialDeviceEnumerator::Create();
mojo::Array<device::serial::DeviceInfoPtr> devices = enumerator->GetDevices();
results_ = serial::GetDevices::Results::Create(
devices.To<std::vector<serial::DeviceInfo>>());
+#endif
}
SerialConnectFunction::SerialConnectFunction() {
| [
"amzo@archbsd.com"
] | amzo@archbsd.com |
d141ab65cb1f6eb22265e5a12aaf937ca18c202d | f1bd4d38d8a279163f472784c1ead12920b70be2 | /xrFS/xr_ini.h | 31a13155f53ec242a0c87497706c1c3519d18552 | [] | no_license | YURSHAT/stk_2005 | 49613f4e4a9488ae5e3fd99d2b60fd9c6aca2c83 | b68bbf136688d57740fd9779423459ef5cbfbdbb | refs/heads/master | 2023-04-05T16:08:44.658227 | 2021-04-18T09:08:18 | 2021-04-18T18:35:59 | 361,129,668 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,152 | h | #ifndef xr_iniH
#define xr_iniH
// refs
class CInifile;
struct xr_token;
//-----------------------------------------------------------------------------------------------------------
//Описание Inifile
//-----------------------------------------------------------------------------------------------------------
class XRCORE_API CInifile
{
public:
struct XRCORE_API Item
{
shared_str first;
shared_str second;
shared_str comment;
Item() : first(0), second(0), comment(0) {};
};
typedef xr_vector<Item> Items;
typedef Items::iterator SectIt;
struct XRCORE_API Sect {
shared_str Name;
Items Data;
IC SectIt begin() { return Data.begin(); }
IC SectIt end() { return Data.end(); }
IC size_t size() { return Data.size(); }
IC void clear() { Data.clear(); }
BOOL line_exist (LPCSTR L, LPCSTR* val=0);
};
typedef xr_vector<Sect> Root;
typedef Root::iterator RootIt;
// factorisation
static CInifile* Create ( LPCSTR szFileName, BOOL ReadOnly=TRUE);
static void Destroy ( CInifile*);
static IC BOOL IsBOOL ( LPCSTR B) { return (xr_strcmp(B,"on")==0 || xr_strcmp(B,"yes")==0 || xr_strcmp(B,"true")==0 || xr_strcmp(B,"1")==0);}
private:
LPSTR fName;
Root DATA;
BOOL bReadOnly;
void Load (IReader* F, LPCSTR path);
public:
BOOL bSaveAtEnd;
public:
CInifile ( IReader* F, LPCSTR path=0 );
CInifile ( LPCSTR szFileName, BOOL ReadOnly=TRUE, BOOL bLoadAtStart=TRUE, BOOL SaveAtEnd=TRUE);
virtual ~CInifile ( );
bool save_as ( LPCSTR new_fname=0 );
LPCSTR fname ( ) { return fName; };
Sect& r_section ( LPCSTR S );
Sect& r_section ( const shared_str& S );
BOOL line_exist ( LPCSTR S, LPCSTR L );
BOOL line_exist ( const shared_str& S, const shared_str& L );
u32 line_count ( LPCSTR S );
u32 line_count ( const shared_str& S );
BOOL section_exist ( LPCSTR S );
BOOL section_exist ( const shared_str& S );
Root& sections ( ){return DATA;}
CLASS_ID r_clsid ( LPCSTR S, LPCSTR L );
CLASS_ID r_clsid ( const shared_str& S, LPCSTR L ) { return r_clsid(*S,L); }
LPCSTR r_string ( LPCSTR S, LPCSTR L); // оставляет кавычки
LPCSTR r_string ( const shared_str& S, LPCSTR L) { return r_string(*S,L); } // оставляет кавычки
shared_str r_string_wb ( LPCSTR S, LPCSTR L); // убирает кавычки
shared_str r_string_wb ( const shared_str& S, LPCSTR L) { return r_string_wb(*S,L); } // убирает кавычки
u8 r_u8 ( LPCSTR S, LPCSTR L );
u8 r_u8 ( const shared_str& S, LPCSTR L ) { return r_u8(*S,L); }
u16 r_u16 ( LPCSTR S, LPCSTR L );
u16 r_u16 ( const shared_str& S, LPCSTR L ) { return r_u16(*S,L); }
u32 r_u32 ( LPCSTR S, LPCSTR L );
u32 r_u32 ( const shared_str& S, LPCSTR L ) { return r_u32(*S,L); }
s8 r_s8 ( LPCSTR S, LPCSTR L );
s8 r_s8 ( const shared_str& S, LPCSTR L ) { return r_s8(*S,L); }
s16 r_s16 ( LPCSTR S, LPCSTR L );
s16 r_s16 ( const shared_str& S, LPCSTR L ) { return r_s16(*S,L); }
s32 r_s32 ( LPCSTR S, LPCSTR L );
s32 r_s32 ( const shared_str& S, LPCSTR L ) { return r_s32(*S,L); }
float r_float ( LPCSTR S, LPCSTR L );
float r_float ( const shared_str& S, LPCSTR L ) { return r_float(*S,L); }
Fcolor r_fcolor ( LPCSTR S, LPCSTR L );
Fcolor r_fcolor ( const shared_str& S, LPCSTR L ) { return r_fcolor(*S,L); }
u32 r_color ( LPCSTR S, LPCSTR L );
u32 r_color ( const shared_str& S, LPCSTR L ) { return r_color(*S,L); }
Ivector2 r_ivector2 ( LPCSTR S, LPCSTR L );
Ivector2 r_ivector2 ( const shared_str& S, LPCSTR L ) { return r_ivector2(*S,L); }
Ivector3 r_ivector3 ( LPCSTR S, LPCSTR L );
Ivector3 r_ivector3 ( const shared_str& S, LPCSTR L ) { return r_ivector3(*S,L); }
Ivector4 r_ivector4 ( LPCSTR S, LPCSTR L );
Ivector4 r_ivector4 ( const shared_str& S, LPCSTR L ) { return r_ivector4(*S,L); }
Fvector2 r_fvector2 ( LPCSTR S, LPCSTR L );
Fvector2 r_fvector2 ( const shared_str& S, LPCSTR L ) { return r_fvector2(*S,L); }
Fvector3 r_fvector3 ( LPCSTR S, LPCSTR L );
Fvector3 r_fvector3 ( const shared_str& S, LPCSTR L ) { return r_fvector3(*S,L); }
Fvector4 r_fvector4 ( LPCSTR S, LPCSTR L );
Fvector4 r_fvector4 ( const shared_str& S, LPCSTR L ) { return r_fvector4(*S,L); }
BOOL r_bool ( LPCSTR S, LPCSTR L );
BOOL r_bool ( const shared_str& S, LPCSTR L ) { return r_bool(*S,L); }
int r_token ( LPCSTR S, LPCSTR L, const xr_token *token_list);
BOOL r_line ( LPCSTR S, int L, LPCSTR* N, LPCSTR* V );
BOOL r_line ( const shared_str& S, int L, LPCSTR* N, LPCSTR* V );
void w_string ( LPCSTR S, LPCSTR L, LPCSTR V, LPCSTR comment=0 );
void w_u8 ( LPCSTR S, LPCSTR L, u8 V, LPCSTR comment=0 );
void w_u16 ( LPCSTR S, LPCSTR L, u16 V, LPCSTR comment=0 );
void w_u32 ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment=0 );
void w_s8 ( LPCSTR S, LPCSTR L, s8 V, LPCSTR comment=0 );
void w_s16 ( LPCSTR S, LPCSTR L, s16 V, LPCSTR comment=0 );
void w_s32 ( LPCSTR S, LPCSTR L, s32 V, LPCSTR comment=0 );
void w_float ( LPCSTR S, LPCSTR L, float V, LPCSTR comment=0 );
void w_fcolor ( LPCSTR S, LPCSTR L, const Fcolor& V, LPCSTR comment=0 );
void w_color ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment=0 );
void w_ivector2 ( LPCSTR S, LPCSTR L, const Ivector2& V, LPCSTR comment=0 );
void w_ivector3 ( LPCSTR S, LPCSTR L, const Ivector3& V, LPCSTR comment=0 );
void w_ivector4 ( LPCSTR S, LPCSTR L, const Ivector4& V, LPCSTR comment=0 );
void w_fvector2 ( LPCSTR S, LPCSTR L, const Fvector2& V, LPCSTR comment=0 );
void w_fvector3 ( LPCSTR S, LPCSTR L, const Fvector3& V, LPCSTR comment=0 );
void w_fvector4 ( LPCSTR S, LPCSTR L, const Fvector4& V, LPCSTR comment=0 );
void w_bool ( LPCSTR S, LPCSTR L, BOOL V, LPCSTR comment=0 );
void remove_line ( LPCSTR S, LPCSTR L );
};
// Main configuration file
extern XRCORE_API CInifile *pSettings;
#endif //__XR_INI_H__
| [
"loxotron@bk.ru"
] | loxotron@bk.ru |
4d46cb688a4ffb8aabeb3de832dd1624269181df | 9cea22db134f1fcec4ac14dfc8cf8f4fc123a14f | /test/test_json.cc | 14cd55410016c3a8f54f9bc1e921407bdb366020 | [] | no_license | plasorak/ptmp | d17e48c6c053378384e62da40afead94df3b5860 | 2718cd63cff564521d02ed8a5a3116f162d3f000 | refs/heads/master | 2020-04-25T05:23:33.034321 | 2019-06-25T23:40:22 | 2019-06-25T23:40:22 | 172,541,335 | 0 | 0 | null | 2019-02-25T16:23:14 | 2019-02-25T16:23:13 | null | UTF-8 | C++ | false | false | 626 | cc | #include "json.hpp"
#include <iostream>
using json = nlohmann::json;
int main()
{
// note, this isn't real JSON schema for anything in PTMP
auto jcfg = R"(
{
"name": "testcontrol",
"ports": [ ],
"type": "control",
"bind": "tcp://127.0.0.1:12345"
}
)"_json;
std::cout << jcfg.dump() << std::endl;
std::string type = jcfg["type"];
std::cout << "type: " << type << std::endl;
json cfg = { { "socket",
{
{ "type", jcfg["type"] },
{ "bind", jcfg["bind"] } }}};
std::cout << "cfg: " << cfg << std::endl;
return 0;
}
| [
"brett.viren@gmail.com"
] | brett.viren@gmail.com |
b48dddf61a18abe1dc81e415a2ad0435fd464144 | 84257c31661e43bc54de8ea33128cd4967ecf08f | /ppc_85xx/usr/include/c++/4.2.2/gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.h | 6f87aec7cbae33e15784f69604abdd71769e3e06 | [] | no_license | nateurope/eldk | 9c334a64d1231364980cbd7bd021d269d7058240 | 8895f914d192b83ab204ca9e62b61c3ce30bb212 | refs/heads/master | 2022-11-15T01:29:01.991476 | 2020-07-10T14:31:34 | 2020-07-10T14:31:34 | 278,655,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | h | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_javax_crypto_jce_key_SquareSecretKeyFactoryImpl__
#define __gnu_javax_crypto_jce_key_SquareSecretKeyFactoryImpl__
#pragma interface
#include <gnu/javax/crypto/jce/key/SecretKeyFactoryImpl.h>
extern "Java"
{
namespace gnu
{
namespace javax
{
namespace crypto
{
namespace jce
{
namespace key
{
class SquareSecretKeyFactoryImpl;
}
}
}
}
}
}
class gnu::javax::crypto::jce::key::SquareSecretKeyFactoryImpl : public ::gnu::javax::crypto::jce::key::SecretKeyFactoryImpl
{
public:
SquareSecretKeyFactoryImpl ();
static ::java::lang::Class class$;
};
#endif /* __gnu_javax_crypto_jce_key_SquareSecretKeyFactoryImpl__ */
| [
"Andre.Mueller@nateurope.com"
] | Andre.Mueller@nateurope.com |
af365a047d27ce34fba65ea7c227c84c97527b7d | 4999e175dff66ebed9bfcd7a6090eaea5dc4ee49 | /Chapter3/Chapter3_test.cc | b0c62b7509936e1f8974574640eb526641df08ba | [] | no_license | zhiminJimmyXiang/CrackingTheCodingInterview | fea16250c77d5aca75b98c7e52da846f83504d7a | 00041b7397dcc368ab29a11bf06f62d0272ce38b | refs/heads/master | 2021-01-25T08:48:49.439884 | 2014-06-27T06:01:17 | 2014-06-27T06:01:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,289 | cc | #include "Chapter3.h"
bool Chapter3_test::Problem_2_test(){
Chapter3 chapter3;
int a[]={2,3,9,0,8,-1,3,3,-2,-3};
int minVal[]={2,2,2,0,0,-1,-1,-1,-2,-3};
for(int i=0; i<10; ++i){
chapter3.problem_2.push(a[i]);
if(chapter3.problem_2.top()!=a[i])
return false;
if(chapter3.problem_2.getMin()!=minVal[i])
return false;
}
for(int i=9; i>=0; --i){
if(chapter3.problem_2.top()!=a[i])
return false;
if(chapter3.problem_2.getMin()!=minVal[i])
return false;
chapter3.problem_2.pop();
}
return true;
}
bool Chapter3_test::Problem_3_test(){
Chapter3 chapter3;
//case 1
int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
for(unsigned i=0; i<16; ++i){
chapter3.problem_3.push(a[i]);
}
for(int i=15; i>=0; --i){
if(chapter3.problem_3.back()!=a[i])
return false;
chapter3.problem_3.pop();
}
//case 2
for(unsigned i=0; i<16; ++i)
chapter3.problem_3.push(a[i]);
int correctResult[]={5,6,7,8,9,10,11,12,13,14,15,16};
for(unsigned i=0; i<12; ++i){
if(chapter3.problem_3.getElement(0,4)!=correctResult[i])
return false;
chapter3.problem_3.popAt(0);
}
return true;
}
// Hanoi tower, have to test manually
bool Chapter3_test::Problem_4_test(){
Chapter3 chapter3;
//case 1
chapter3.Problem_4(3,1,3,2);
cout<<endl;
//case 2
chapter3.Problem_4(5,1,3,2);
cout<<endl;
return true;
}
bool Chapter3_test::Problem_5_test(){
Chapter3 chapter3;
int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13};
for(unsigned i=0; i<13; ++i)
chapter3.problem_5.push_back(a[i]);
for(unsigned i=0; i<13; ++i){
if(chapter3.problem_5.front()!=a[i])
return false;
chapter3.problem_5.pop_front();
}
return true;
}
bool Chapter3_test::Problem_6_test(){
Chapter3 chapter3;
//case 1
vector<int> input;
chapter3.Problem_6(input);
if(!input.empty())
return false;
//case 2
int a[]={5,92,18,-1,9,2,4,0,8,4,0,2,0};
int correctAnswer[]={-1,0,0,0,2,2,4,4,5,8,9,18,92};
input.assign(a, a+13);
chapter3.Problem_6(input);
if(input.size()!=13)
return false;
for(unsigned i=0; i<13; ++i){
if(input[i]!=correctAnswer[i])
return false;
}
return true;
}
bool Chapter3_test::Problem_7_test(){
Chapter3 chapter3;
vector<Animal> animalVec;
//case 1
Animal a1 = chapter3.problem_7.dequeueAny();
Animal a2 = chapter3.problem_7.dequeueDog();
Animal a3 = chapter3.problem_7.dequeueCat();
if(a1.type!=0 || a2.type!=0 || a3.type!=0)
return false;
//case 2
for(int i=0; i<16; ++i){
Animal animal;
animal.type=(i%2==0?1:2);
animal.id = i;
chapter3.problem_7.enqueue(animal);
}
for(int i=0; i<16; ++i){
Animal animal = chapter3.problem_7.dequeueAny();
if(animal.type!=(i%2==0?1:2) || animal.time!=i || animal.id!=i)
return false;
}
//case 3
for(int i=0; i<16; ++i){
Animal animal;
animal.type=(i%2==0?1:2);
animal.id = i;
chapter3.problem_7.enqueue(animal);
}
for(int i=0; i<16; i+=2){
Animal animal = chapter3.problem_7.dequeueDog();
if(animal.type!=1 || animal.id!=i)
return false;
}
//case 4
for(int i=0; i<16; ++i){
Animal animal;
animal.type=(i%2==0?1:2);
animal.id = i;
chapter3.problem_7.enqueue(animal);
}
for(int i=1; i<16; i+=2){
Animal animal = chapter3.problem_7.dequeueCat();
if(animal.type!=2 || animal.id!=i)
return false;
}
return true;
}
int main(){
Chapter3_test testor;
//--- Problem 2 test ---
if(!testor.Problem_2_test())
cout<<"Test 2 Failed!!!!!"<<endl;
else
cout<<"Test 2 Passed!"<<endl;
//--- Problem 3 test ---
if(!testor.Problem_3_test())
cout<<"Test 3 Failed!!!!!"<<endl;
else
cout<<"Test 3 Passed!"<<endl;
//--- Problem 4 test ---
//testor.Problem_4_test();
//correct
//--- Problem 5 test ---
if(!testor.Problem_5_test())
cout<<"Test 5 Failed!!!!!"<<endl;
else
cout<<"Test 5 Passed!"<<endl;
//--- Problem 6 test ---
if(!testor.Problem_6_test())
cout<<"Test 6 Failed!!!!!"<<endl;
else
cout<<"Test 6 Passed!"<<endl;
//--- Problem 7 test ---
if(!testor.Problem_7_test())
cout<<"Test 7 Failed!!!!!"<<endl;
else
cout<<"Test 7 Passed!"<<endl;
return 0;
}
| [
"zhiminx1@uci.edu"
] | zhiminx1@uci.edu |
607063e44f2926877646a7d444e5f74534461c8b | 64b5c5e0e86733601c268c173c6c89a8dbe9b093 | /AnimalBobble/cpp&h/tlybg.h | 3b364a7b8decb3c68d7dfb63a279d13a0ce210af | [] | no_license | Nishin3614/KOKI_NISHIYAMA | ab2ef12de5072b73fe49318a4742fedc5fc23f14 | 64bc2144f3c7655ab501606fe41bba68ea46f2e0 | refs/heads/master | 2020-09-30T13:45:25.199250 | 2020-01-31T07:26:06 | 2020-01-31T07:26:06 | 227,298,698 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,358 | h | // ----------------------------------------
//
// 試し背景処理の説明[tlybg.h]
// Author : Koki Nishiyama
//
// ----------------------------------------
#ifndef _TLYBG_H_
#define _TLYBG_H_ // ファイル名を基準を決める
// ----------------------------------------
//
// インクルードファイル
//
// ----------------------------------------
#include "main.h"
#include "scene_two.h"
// ----------------------------------------
//
// マクロ定義
//
// ----------------------------------------
#define MAX_TLYBG (1)
// ------------------------------------------------------------------------------------------
//
// クラス
//
// ------------------------------------------------------------------------------------------
class CTlyBg : public CScene
{
public:
/* 関数 */
CTlyBg();
~CTlyBg();
void Init(void);
void Uninit(void);
void Update(void);
void Draw(void);
static HRESULT Load(void);
static void UnLoad(void);
static CTlyBg * Create(CManager::MODE mode); // 作成
protected:
private:
static LPDIRECT3DTEXTURE9 m_pTex[CManager::MODE_MAX][MAX_TLYBG];
static CManager::MODE m_mode; // モード
static D3DXVECTOR3 m_pos[CManager::MODE_MAX][MAX_TLYBG]; // 位置情報
static D3DXVECTOR2 m_size[CManager::MODE_MAX][MAX_TLYBG]; // サイズ情報
CScene_TWO *m_aScene_Two[MAX_TLYBG];
};
#endif | [
"work.nishio240@gmail.com"
] | work.nishio240@gmail.com |
3544c4d3b05b6fd3ec6b3fbdf372e8fa7c897086 | 0a09ae843324049a02df2430a42443518887779c | /client/src/inventoryboard.cpp | eda7ce07f888aea549b7f864b7f8d02f3a78c048 | [] | no_license | FlingPenguin/mir2x | 7653b3e6179042bac94069127e4cb3276428314b | 35e9deeee4b304198fd087f4ca368d32373d8d23 | refs/heads/master | 2023-06-02T04:30:15.810406 | 2021-06-10T17:56:43 | 2021-06-10T17:56:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,131 | cpp | /*
* =====================================================================================
*
* Filename: inventoryboard.cpp
* Created: 10/08/2017 19:22:30
* Description:
*
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: ANHONG
* Email: anhonghe@gmail.com
* Organization: USTC
*
* =====================================================================================
*/
#include "pngtexdb.hpp"
#include "sdldevice.hpp"
#include "processrun.hpp"
#include "inventoryboard.hpp"
extern PNGTexDB *g_progUseDB;
extern PNGTexDB *g_itemDB;
extern SDLDevice *g_sdlDevice;
InventoryBoard::InventoryBoard(int nX, int nY, ProcessRun *pRun, Widget *pwidget, bool autoDelete)
: Widget(DIR_UPLEFT, nX, nY, 0, 0, pwidget, autoDelete)
, m_opNameBoard
{
DIR_UPLEFT,
132,
16,
u8"【背包】",
1,
12,
0,
colorf::WHITE + 255,
this,
}
, m_wmdAniBoard
{
DIR_UPLEFT,
23,
14,
this,
}
, m_slider
{
DIR_UPLEFT,
258,
64,
291,
2,
nullptr,
this,
}
, m_closeButton
{
DIR_UPLEFT,
242,
422,
{SYS_TEXNIL, 0X0000001C, 0X0000001D},
nullptr,
nullptr,
[this]()
{
show(false);
},
0,
0,
0,
0,
true,
true,
this,
}
, m_processRun(pRun)
{
show(false);
auto texPtr = g_progUseDB->Retrieve(0X0000001B);
if(!texPtr){
throw fflerror("no valid inventory frame texture");
}
std::tie(m_w, m_h) = SDLDeviceHelper::getTextureSize(texPtr);
}
void InventoryBoard::drawItem(int dstX, int dstY, size_t startRow, bool cursorOn, const PackBin &bin) const
{
if(true
&& bin
&& bin.x >= 0
&& bin.y >= 0
&& bin.w > 0
&& bin.h > 0){
if(auto texPtr = g_itemDB->Retrieve(DBCOM_ITEMRECORD(bin.item.itemID).pkgGfxID | 0X01000000)){
const int startX = dstX + m_invGridX0;
const int startY = dstY + m_invGridY0 - startRow * SYS_INVGRIDPH;
const int viewX = dstX + m_invGridX0;
const int viewY = dstY + m_invGridY0;
const auto [itemPW, itemPH] = SDLDeviceHelper::getTextureSize(texPtr);
int drawDstX = startX + bin.x * SYS_INVGRIDPW + (bin.w * SYS_INVGRIDPW - itemPW) / 2;
int drawDstY = startY + bin.y * SYS_INVGRIDPH + (bin.h * SYS_INVGRIDPH - itemPH) / 2;
int drawSrcX = 0;
int drawSrcY = 0;
int drawSrcW = itemPW;
int drawSrcH = itemPH;
if(mathf::ROICrop(
&drawSrcX, &drawSrcY,
&drawSrcW, &drawSrcH,
&drawDstX, &drawDstY,
drawSrcW,
drawSrcH,
0, 0, -1, -1,
viewX, viewY, SYS_INVGRIDPW * 6, SYS_INVGRIDPH * 8)){
g_sdlDevice->drawTexture(texPtr, drawDstX, drawDstY, drawSrcX, drawSrcY, drawSrcW, drawSrcH);
}
int binGridX = bin.x;
int binGridY = bin.y;
int binGridW = bin.w;
int binGridH = bin.h;
if(mathf::rectangleOverlapRegion<int>(0, startRow, 6, 8, &binGridX, &binGridY, &binGridW, &binGridH)){
if(cursorOn){
g_sdlDevice->fillRectangle(colorf::WHITE + 64,
startX + binGridX * SYS_INVGRIDPW,
startY + binGridY * SYS_INVGRIDPH, // startY is for (0, 0), not for (0, startRow)
binGridW * SYS_INVGRIDPW,
binGridH * SYS_INVGRIDPH);
}
if(bin.item.count > 1){
const LabelBoard itemCount
{
DIR_UPLEFT,
0, // reset by new width
0,
to_u8cstr(std::to_string(bin.item.count)),
1,
10,
0,
colorf::RGBA(0XFF, 0XFF, 0X00, 0XFF),
};
itemCount.drawAt(DIR_UPRIGHT, startX + (binGridX + binGridW) * SYS_INVGRIDPW, startY + binGridY * SYS_INVGRIDPH - 2 /* pixel adjust */);
}
}
}
}
}
void InventoryBoard::update(double fUpdateTime)
{
m_wmdAniBoard.update(fUpdateTime);
}
void InventoryBoard::drawEx(int dstX, int dstY, int, int, int, int) const
{
if(auto pTexture = g_progUseDB->Retrieve(0X0000001B)){
g_sdlDevice->drawTexture(pTexture, dstX, dstY);
}
const auto myHeroPtr = m_processRun->getMyHero();
if(!myHeroPtr){
return;
}
const auto startRow = getStartRow();
const auto [mousePX, mousePY] = SDLDeviceHelper::getMousePLoc();
const auto &packBinListCRef = myHeroPtr->getInvPack().getPackBinList();
const auto cursorOnIndex = getPackBinIndex(mousePX, mousePY);
for(int i = 0; i < to_d(packBinListCRef.size()); ++i){
drawItem(dstX, dstY, startRow, (i == cursorOnIndex), packBinListCRef.at(i));
}
drawGold();
m_opNameBoard.draw();
m_wmdAniBoard.draw();
m_slider .draw();
m_closeButton.draw();
if(cursorOnIndex >= 0){
drawItemHoverText(packBinListCRef.at(cursorOnIndex));
}
}
bool InventoryBoard::processEvent(const SDL_Event &event, bool valid)
{
if(!valid){
focus(false);
return false;
}
if(!show()){
return false;
}
if(m_closeButton.processEvent(event, valid)){
return true;
}
if(m_slider.processEvent(event, valid)){
return true;
}
switch(event.type){
case SDL_MOUSEMOTION:
{
if((event.motion.state & SDL_BUTTON_LMASK) && (in(event.motion.x, event.motion.y) || focus())){
const auto [rendererW, rendererH] = g_sdlDevice->getRendererSize();
const int maxX = rendererW - w();
const int maxY = rendererH - h();
const int newX = std::max<int>(0, std::min<int>(maxX, x() + event.motion.xrel));
const int newY = std::max<int>(0, std::min<int>(maxY, y() + event.motion.yrel));
moveBy(newX - x(), newY - y());
return focusConsume(this, true);
}
return focusConsume(this, false);
}
case SDL_MOUSEBUTTONDOWN:
{
auto myHeroPtr = m_processRun->getMyHero();
auto &invPackRef = myHeroPtr->getInvPack();
auto lastGrabbedItem = invPackRef.getGrabbedItem();
switch(event.button.button){
case SDL_BUTTON_LEFT:
{
if(in(event.button.x, event.button.y)){
if(const int selectedPackIndex = getPackBinIndex(event.button.x, event.button.y); selectedPackIndex >= 0){
auto selectedPackBin = invPackRef.getPackBinList().at(selectedPackIndex);
invPackRef.setGrabbedItem(selectedPackBin.item);
invPackRef.remove(selectedPackBin.item);
if(lastGrabbedItem){
// when swapping
// prefer to use current location to store
invPackRef.add(lastGrabbedItem, selectedPackBin.x, selectedPackBin.y);
}
}
else if(lastGrabbedItem){
const auto [gridX, gridY] = getInvGrid(event.button.x, event.button.y);
const auto [gridW, gridH] = InvPack::getPackBinSize(lastGrabbedItem.itemID);
const auto startGridX = gridX - gridW / 2; // can give an invalid (x, y)
const auto startGridY = gridY - gridH / 2;
invPackRef.add(lastGrabbedItem, startGridX, startGridY);
invPackRef.setGrabbedItem({});
}
return focusConsume(this, true);
}
return focusConsume(this, false);
}
case SDL_BUTTON_RIGHT:
{
if(in(event.button.x, event.button.y)){
if(const int selectedPackIndex = getPackBinIndex(event.button.x, event.button.y); selectedPackIndex >= 0){
packBinConsume(invPackRef.getPackBinList().at(selectedPackIndex));
}
return focusConsume(this, true);
}
return focusConsume(this, false);
}
default:
{
return focusConsume(this, false);
}
}
}
case SDL_MOUSEWHEEL:
{
const auto [mousePX, mousePY] = SDLDeviceHelper::getMousePLoc();
if(mathf::pointInRectangle<int>(mousePX, mousePY, x() + m_invGridX0, y() + m_invGridY0, 6 * SYS_INVGRIDPW, 8 * SYS_INVGRIDPH)){
const auto rowCount = getRowCount();
if(rowCount > 8){
m_slider.addValue((event.wheel.y > 0 ? -1.0 : 1.0) / (rowCount - 8));
}
return focusConsume(this, true);
}
return false;
}
default:
{
return focusConsume(this, false);
}
}
}
std::string InventoryBoard::getGoldStr() const
{
return str_ksep([this]() -> int
{
if(auto p = m_processRun->getMyHero()){
return p->getGold();
}
return 0;
}(), ',');
}
size_t InventoryBoard::getRowCount() const
{
const auto &packBinList = m_processRun->getMyHero()->getInvPack().getPackBinList();
if(packBinList.empty()){
return 0;
}
size_t rowCount = 0;
for(const auto &bin: packBinList){
rowCount = std::max<size_t>(rowCount, bin.y + bin.h);
}
return rowCount;
}
size_t InventoryBoard::getStartRow() const
{
const size_t rowGfxCount = 8;
const size_t rowCount = getRowCount();
if(rowCount <= rowGfxCount){
return 0;
}
return std::lround((rowCount - rowGfxCount) * m_slider.getValue());
}
void InventoryBoard::drawGold() const
{
const LabelBoard goldBoard
{
DIR_UPLEFT,
0, // reset by new width
0,
to_u8cstr(getGoldStr()),
1,
12,
0,
colorf::RGBA(0XFF, 0XFF, 0X00, 0XFF),
};
goldBoard.drawAt(DIR_NONE, x() + 106, y() + 409);
}
int InventoryBoard::getPackBinIndex(int locPX, int locPY) const
{
const auto [gridX, gridY] = getInvGrid(locPX, locPY);
if(gridX < 0 || gridY < 0){
return -1;
}
const auto startRow = getStartRow();
const auto myHeroPtr = m_processRun->getMyHero();
const auto &packBinListCRef = myHeroPtr->getInvPack().getPackBinList();
for(int i = 0; i < to_d(packBinListCRef.size()); ++i){
const auto &binCRef = packBinListCRef.at(i);
if(mathf::pointInRectangle<int>(gridX, gridY, binCRef.x, binCRef.y - startRow, binCRef.w, binCRef.h)){
return i;
}
}
return -1;
}
std::tuple<int, int> InventoryBoard::getInvGrid(int locPX, int locPY) const
{
const int gridPX0 = m_invGridX0 + x();
const int gridPY0 = m_invGridY0 + y();
if(!mathf::pointInRectangle<int>(locPX, locPY, gridPX0, gridPY0, 6 * SYS_INVGRIDPW, 8 * SYS_INVGRIDPH)){
return {-1, -1};
}
return
{
(locPX - gridPX0) / SYS_INVGRIDPW,
(locPY - gridPY0) / SYS_INVGRIDPH,
};
}
void InventoryBoard::drawItemHoverText(const PackBin &bin) const
{
const auto &ir = DBCOM_ITEMRECORD(bin.item.itemID);
const auto hoverText = str_printf
(
u8R"###( <layout> )###""\n"
u8R"###( <par>【名称】%s</par> )###""\n"
u8R"###( <par>【描述】%s</par> )###""\n"
u8R"###( </layout> )###""\n",
ir.name,
str_haschar(ir.description) ? ir.description : u8"游戏处于开发阶段,此物品暂无描述。"
);
LayoutBoard hoverTextBoard
{
DIR_UPLEFT,
0,
0,
200,
false,
{0, 0, 0, 0},
false,
1,
12,
0,
colorf::WHITE + 255,
0,
LALIGN_JUSTIFY,
};
hoverTextBoard.loadXML(to_cstr(hoverText));
const auto [mousePX, mousePY] = SDLDeviceHelper::getMousePLoc();
const auto textBoxW = std::max<int>(hoverTextBoard.w(), 200) + 20;
const auto textBoxH = hoverTextBoard.h() + 20;
g_sdlDevice->fillRectangle(colorf::RGBA(0, 0, 0, 200), mousePX, mousePY, textBoxW, textBoxH, 5);
g_sdlDevice->drawRectangle(colorf::RGBA(0, 0, 255, 255), mousePX, mousePY, textBoxW, textBoxH, 5);
hoverTextBoard.drawAt(DIR_UPLEFT, mousePX + 10, mousePY + 10);
}
void InventoryBoard::packBinConsume(const PackBin &bin)
{
const auto &ir = DBCOM_ITEMRECORD(bin.item.itemID);
if(false
|| to_u8sv(ir.type) == u8"恢复药水"
|| to_u8sv(ir.type) == u8"强化药水"
|| to_u8sv(ir.type) == u8"技能书"){
m_processRun->requestConsumeItem(bin.item.itemID, bin.item.seqID, 1);
}
}
| [
"anhonghe@gmail.com"
] | anhonghe@gmail.com |
52a364b2ac5fdc6bcf4d4c9ddbed3c7b1432ac5d | 88ff7bd277882913983145850d0d14457241b525 | /src/SingleLayerOptics/tst/units/RectangularPerforatedScatteringShade1.unit.cpp | 2012c82bb0aa6009d2eff3ecd3989ff99bd6b88b | [
"BSD-3-Clause-LBNL"
] | permissive | LBNL-ETA/Windows-CalcEngine | 4a3f7eeff094a277d0cce304c9339c8c8c238f19 | 610cc20b4beddfe379c566aa1adcffc71d2dd75e | refs/heads/main | 2023-08-10T17:02:43.415941 | 2023-08-03T15:32:16 | 2023-08-03T15:32:16 | 54,597,431 | 17 | 13 | NOASSERTION | 2023-08-24T16:59:01 | 2016-03-23T22:31:42 | C++ | UTF-8 | C++ | false | false | 2,779 | cpp | #include <memory>
#include <gtest/gtest.h>
#include "WCESingleLayerOptics.hpp"
#include "WCECommon.hpp"
using namespace SingleLayerOptics;
using namespace FenestrationCommon;
class TestRectangularPerforatedScatteringShade1 : public testing::Test
{
protected:
virtual void SetUp()
{}
};
TEST_F(TestRectangularPerforatedScatteringShade1, TestProperties)
{
SCOPED_TRACE("Begin Test: Rectangular perforated cell - properties.");
// make material
const auto Tmat = 0.1;
const auto Rfmat = 0.4;
const auto Rbmat = 0.4;
const auto minLambda = 0.3;
const auto maxLambda = 2.5;
const auto aMaterial = Material::singleBandMaterial(Tmat, Tmat, Rfmat, Rbmat);
// make cell geometry
const auto x = 20.0; // mm
const auto y = 25.0; // mm
const auto thickness = 7.0; // mm
const auto xHole = 5.0; // mm
const auto yHole = 8.0; // mm
auto shade =
CScatteringLayer::createPerforatedRectangularLayer(aMaterial, x, y, thickness, xHole, yHole);
const double tir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::T, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(tir, 0.112482, 1e-6);
const double rir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::R, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(rir, 0.394452, 1e-6);
auto irLayer = CScatteringLayerIR(shade);
const double emiss = irLayer.emissivity(Side::Front);
EXPECT_NEAR(emiss, 0.493065, 1e-6);
}
TEST_F(TestRectangularPerforatedScatteringShade1, TestHighEmissivity)
{
SCOPED_TRACE("Begin Test: Rectangular perforated cell - properties.");
// make material
const auto Tmat = 0.1;
const auto Rfmat = 0.01;
const auto Rbmat = 0.01;
const auto minLambda = 0.3;
const auto maxLambda = 2.5;
const auto aMaterial = Material::singleBandMaterial(Tmat, Tmat, Rfmat, Rbmat);
// make cell geometry
const auto x = 20.0; // mm
const auto y = 25.0; // mm
const auto thickness = 7.0; // mm
const auto xHole = 0.001; // mm
const auto yHole = 0.001; // mm
auto shade =
CScatteringLayer::createPerforatedRectangularLayer(aMaterial, x, y, thickness, xHole, yHole);
const double tir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::T, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(tir, 0.1, 1e-6);
const double rir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::R, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(rir, 0.01, 1e-6);
auto irLayer = CScatteringLayerIR(shade);
const double emiss = irLayer.emissivity(Side::Front);
EXPECT_NEAR(emiss, 0.89, 1e-6);
}
| [
"dvvidanovic@lbl.gov"
] | dvvidanovic@lbl.gov |
57925ea0e476b821a17b75d7e104b0d4f1007135 | 4d3b52892720a540e35809c8c3a6925f1b887857 | /src/symboltable.cpp | 2d7652baf3a50c0be8871b9cf866b20ab4426c09 | [
"MIT"
] | permissive | AshOlogn/ash-language-interpreter | f2376785a1bdd09bea982902691c79601e8019ff | add9f2cc76edd3a91e38446fb4c11a1ce1348af0 | refs/heads/master | 2020-03-18T18:22:42.991069 | 2018-08-28T10:32:37 | 2018-08-28T10:32:37 | 135,088,789 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,313 | cpp | #include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include "parsetoken.h"
#include "symboltable.h"
using namespace std;
SymbolTable::SymbolTable() {
table = new vector<unordered_map<string, ParseData>*>();
table->push_back(new unordered_map<string, ParseData>());
depth = 0;
}
void SymbolTable::enterNewScope() {
//the next time something is added, a new symbol table is created
table->push_back(new unordered_map<string, ParseData>());
depth++;
}
void SymbolTable::leaveScope() {
//leave a scope, so discard "innermost" symbol table
table->pop_back();
depth--;
}
//create new key in innermost scope
void SymbolTable::declare(string var, ParseData value) {
//get symbol table at innermost scope
unordered_map<string, ParseData>* map = table->back();
//add element to the map
(*map)[var] = value;
}
//update value in innermost scope in which it is found
void SymbolTable::update(string var, ParseData value) {
//start at innermost scope and work your way up
vector<unordered_map<string, ParseData>*>::reverse_iterator rit;
for(rit = table->rbegin(); rit != table->rend(); rit++) {
//map at this particular scope
unordered_map<string, ParseData>* map = (*rit);
//if this map contains it, update its value
if(map->find(var) != map->end()) {
(*map)[var] = value;
return;
}
}
}
//returns if variable is already declared in current innermost scope
bool SymbolTable::isDeclaredInScope(string var) {
unordered_map<string, ParseData>* map = *(table->rbegin());
return map->find(var) != map->end();
}
//returns if variable is declared anywhere at all
bool SymbolTable::isDeclared(string var) {
//start at innermost scope and work your way up
vector<unordered_map<string, ParseData>*>::reverse_iterator rit;
for(rit = table->rbegin(); rit != table->rend(); rit++) {
//map at this particular scope
unordered_map<string, ParseData>* map = (*rit);
//if this map contains it, return true
if(map->find(var) != map->end())
return true;
}
return false;
}
ParseData SymbolTable::get(string var) {
//start at innermost scope and work your way up
vector<unordered_map<string, ParseData>*>::reverse_iterator rit;
for(rit = table->rbegin(); rit != table->rend(); rit++) {
//map at this particular scope
unordered_map<string, ParseData>* map = (*rit);
//see if this map contains the variable
unordered_map<string, ParseData>::const_iterator value = map->find(var);
if(value != map->end())
return value->second;
}
//not found, return "invalid" data
ParseData d;
d.type = INVALID_T;
return d;
}
std::string SymbolTable::toString() {
std::string str = "";
//loop through all the hash maps
std::vector<std::unordered_map<string, ParseData>*>::iterator it;
for(it = table->begin(); it != table->end(); it++) {
//loop through the keys in the hash map and print those
std::unordered_map<string, ParseData>::iterator it2;
for(it2 = (*it)->begin(); it2 != (*it)->end(); it2++) {
str.append(it2->first);
str.append(", ");
str.append(toStringParseDataType(it2->second.type));
str.append("\n");
}
str.append("----------------------------\n");
}
str.append("end of table");
return str;
}
| [
"ashwin.dev.pro@gmail.com"
] | ashwin.dev.pro@gmail.com |
5824ef7db52242bad8e07095fdd4ceb727cc48e1 | 2134298eaeedc3d0efe98939676b41b17a8db7c8 | /RoutTableAdder.h | b96c87f43530e76eb0fca7664f2d6f2eadf6643b | [] | no_license | CSEKimDoYeon/DC-RouterTestApp | dfd26454f8c55a42d3a97d81dc0c3cb63d86f620 | ab16209eb5078d7d1f23781ef008185809213806 | refs/heads/master | 2020-04-07T16:11:43.652915 | 2018-11-21T08:57:59 | 2018-11-21T08:57:59 | 158,519,255 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,212 | h | #pragma once
#include "afxcmn.h"
#include "afxwin.h"
// CRoutTableAdder 대화 상자입니다.
class CRoutTableAdder : public CDialog
{
DECLARE_DYNAMIC(CRoutTableAdder)
public:
CRoutTableAdder(); // 표준 생성자입니다.
virtual ~CRoutTableAdder();
// 대화 상자 데이터입니다.
enum { IDD = IDD_ROUTE_ADD_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
CString d1,d2;
void setDeviceList(CString dev1,CString dev2);
unsigned char dest_ip[4];
unsigned char net_ip[4];
unsigned char gate_ip[4];
unsigned char flag;
int router_interface;
// routetableDestination
CIPAddressCtrl m_add_dest;
CIPAddressCtrl m_add_netmask;
CIPAddressCtrl m_gateway;
CComboBox m_add_interface;
CButton m_flag_u;
CButton m_flag_g;
CButton m_flag_h;
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedCancel();
// get destination
unsigned char * GetDestIp(void);
// get netmask
unsigned char * GetNetmask(void);
// get Gateway
unsigned char * GetGateway(void);
// get inter face
int GetInterface(void);
// get metric
int GetMetric(void);
// get flag
unsigned char GetFlag(void);
int m_metric;
};
| [
"ehdus0008@naver.com"
] | ehdus0008@naver.com |
f94f59e3ac65a3a0451c0ac3c0142e540c8e7cfd | 3d424a8d682d4e056668b5903206ccc603f6e997 | /NeoGUI/GUI/DetailsView.h | 363cb75cdd2748cb83d190ba1fd81898ee189d1a | [] | no_license | markus851/NeoLoader | 515e238b385354b83bbc4f7399a85524d5b03d12 | 67c9b642054ead500832406a9c301a7b4cbfffd3 | refs/heads/master | 2022-04-22T07:51:15.418184 | 2015-05-08T11:37:53 | 2015-05-08T11:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,333 | h | #pragma once
class CCoverView;
#include "ProgressBar.h"
class CDetailsView: public QWidget
{
Q_OBJECT
public:
CDetailsView(UINT Mode, QWidget *parent = 0);
~CDetailsView();
void ShowDetails(uint64 ID);
void ChangeMode(UINT Mode) {m_Mode = Mode;}
public slots:
void UpdateDetails();
void OnMenuRequested(const QPoint &point);
void OnSetFileName();
void OnSetRating();
void OnEnableSubmit();
void OnCopyHash();
void OnSetMaster();
void OnAddHash();
void OnRemoveHash();
void OnSelectHash();
void OnBanHash();
protected:
virtual void timerEvent(QTimerEvent *e);
int m_TimerId;
uint64 m_ID;
UINT m_Mode;
friend class CDetailsUpdateJob;
friend class CDetailsApplyJob;
QVBoxLayout* m_pMainLayout;
CProgressBar* m_pProgress;
QWidget* m_pWidget;
QHBoxLayout* m_pLayout;
QWidget* m_pDetailWidget;
QFormLayout* m_pDetailLayout;
QLineEdit* m_pFileName;
QTextEdit* m_pDescription;
QComboBox* m_pRating;
QLabel* m_pInfo;
QPushButton* m_pSubmit;
QTableWidget* m_pHashes;
QMenu* m_pMenu;
QAction* m_pCopyHash;
QAction* m_pSetMaster;
QAction* m_pAddHash;
QAction* m_pRemoveHash;
QAction* m_pSelectHash;
QAction* m_pBanHash;
CCoverView* m_pCoverView;
bool m_IsComplete;
bool m_bLockDown;
}; | [
"David@X.com"
] | David@X.com |
041be98441ab83c76d9f870115002ccd8052b464 | 27c917a12edbfd2dba4f6ce3b09aa2e3664d3bb1 | /Tree/array_to_BST.cpp | 2e2345db1c9314994badcf7c23c5079e95d822a0 | [] | no_license | Spetsnaz-Dev/CPP | 681ba9be0968400e00b5b2cb9b52713f947c66f8 | 88991e3b7164dd943c4c92784d6d98a3c9689653 | refs/heads/master | 2023-06-24T05:32:30.087866 | 2021-07-15T19:33:02 | 2021-07-15T19:33:02 | 193,662,717 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include<iostream>
using namespace std;
struct Node{
int data;
Node* right;
Node* left;
};
Node* newNode(int x)
{
Node* ptr = (Node*)malloc(sizeof(Node*));
ptr->data =x;
ptr->left = NULL;
ptr->right = NULL;
return ptr;
}
Node *buildBST(int arr[], int low, int high)
{
int mid = (low+high)/2;
Node *root = newNode(arr[mid]);
buildBST(arr, low, mid-1);
buildBST(arr, mid+1, high);
return root;
}
void preorder(Node *root){
if(!root)
return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
int main()
{
int t;
cin>>t;
while(t--) {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
Node *root = buildBST(arr, 0, n-1);
preorder(root);
cout<<"\n";
}
return 0;
}
//Method 2
TreeNode *buildBST(TreeNode* &root, int ele) {
if(!root)
return root = new TreeNode(ele);
if(root->val > ele)
root->left = buildBST(root->left, ele);
else
root->right = buildBST(root->right, ele);
return root;
}
TreeNode* bstFromPreorder(vector<int>& pre) {
TreeNode *root = NULL;
for(auto x : pre)
buildBST(root, x);
return root;
} | [
"ravindrafk@gmail.com"
] | ravindrafk@gmail.com |
3c4237f37b509e8bde03ecc435459419c7b57fb0 | 006ac2f948ad3cf5e7ca646daa1a2130d23c42dd | /c++/《OpenCV图像处理编程实例-源码-20160801/chapter2/2-11.cpp | 0889a54f248573248dc443072ff28c512e7f8e0d | [] | no_license | gitgaoqian/OpenCv | 610463e2bc8bfdb648cf4378ebe6f6891803c3c3 | 2f86037969f002bb7787364deabcb4ea7e753830 | refs/heads/master | 2020-04-10T22:05:44.031755 | 2018-12-11T10:15:52 | 2018-12-11T10:15:52 | 161,315,015 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,573 | cpp | // 功能:代码 2-11 旋转变换
// 作者:朱伟 zhu1988wei@163.com
// 来源:《OpenCV图像处理编程实例》
// 博客:http://blog.csdn.net/zhuwei1988
// 更新:2016-8-1
// 说明:版权所有,引用或摘录请联系作者,并按照上面格式注明出处,谢谢。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <cmath>
using namespace cv;
using namespace std;
cv::Mat angelRotate(cv::Mat& src, int angle)
{
// 角度转换
float alpha = angle * CV_PI / 180;
// 构造旋转矩阵
float rotateMat[3][3] = {
{cos(alpha), -sin(alpha), 0},
{sin(alpha), cos(alpha), 0},
{0, 0, 1} };
int nSrcRows = src.rows;
int nSrcCols = src.cols;
// 计算旋转后图像矩阵各个顶点位置
float a1 = nSrcCols * rotateMat[0][0] ;
float b1 = nSrcCols * rotateMat[1][0] ;
float a2 = nSrcCols * rotateMat[0][0] +
nSrcRows * rotateMat[0][1];
float b2 = nSrcCols * rotateMat[1][0] +
nSrcRows * rotateMat[1][1];
float a3 = nSrcRows * rotateMat[0][1];
float b3 = nSrcRows * rotateMat[1][1];
// 计算出极值点
float kxMin = min( min( min(0.0f,a1), a2 ), a3);
float kxMax = max( max( max(0.0f,a1), a2 ), a3);
float kyMin = min( min( min(0.0f,b1), b2 ), b3);
float kyMax = max( max( max(0.0f,b1), b2 ), b3);
// 计算输出矩阵的尺寸
int nRows = abs(kxMax - kxMin);
int nCols = abs(kyMax - kyMin);
cv::Mat dst(nRows, nCols, src.type(),cv::Scalar::all(0));
for( int i = 0; i < nRows; ++i)
{
for (int j = 0; j < nCols; ++j)
{
// 旋转坐标转换
int x = (j + kxMin) * rotateMat[0][0] -
(i + kyMin) * rotateMat[0][1] ;
int y = -(j + kxMin) * rotateMat[1][0] +
(i + kyMin) * rotateMat[1][1] ;
if( (x >= 0) && (x < nSrcCols) &&
(y >= 0) && (y < nSrcRows) )
{
dst.at<cv::Vec3b>(i,j) =
src.at<cv::Vec3b>(y,x);
}
}
}
return dst;
}
int main()
{
cv::Mat srcImage = cv::imread("..\\images\\pool.jpg");
if(!srcImage.data)
return -1;
cv::imshow("srcImage", srcImage);
int angle = 30;
cv::Mat resultImage = angelRotate(srcImage, angle);
imshow("resultImage", resultImage);
cv::waitKey(0);
return 0;
}
| [
"734756851@qq.com"
] | 734756851@qq.com |
3211bc94d9280920198f3c8840d58597b848c6b2 | bf023953b735f3c877e5af047526688e88e17bb3 | /demos/simple-udp/playground/net_stream.h | e90b7a1358298eeff1ce9c6516034215bb59ea52 | [] | no_license | puma10100505/documents | f38d37496602009deb1910d55a91bbaee27e82dd | c1b8b69d1109403de4215852e6768370a5bd214b | refs/heads/master | 2020-11-26T05:39:59.094822 | 2020-09-04T12:13:32 | 2020-09-04T12:13:32 | 228,979,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,298 | h | /*
Simple Network Library from "Networking for Game Programmers"
http://www.gaffer.org/networking-for-game-programmers
Author: Glenn Fiedler <gaffer@gaffer.org>
*/
#ifndef NET_STREAM_H
#define NET_STREAM_H
#include <assert.h>
#include <string.h>
#include <algorithm>
namespace net
{
// bitpacker class
// + read and write non-8 multiples of bits efficiently
class BitPacker
{
public:
enum Mode
{
Read,
Write
};
BitPacker( Mode mode, void * buffer, int bytes )
{
assert( bytes >= 0 );
this->mode = mode;
this->buffer = (unsigned char*) buffer;
this->ptr = (unsigned char*) buffer;
this->bytes = bytes;
bit_index = 0;
if ( mode == Write )
memset( buffer, 0, bytes );
}
void WriteBits( unsigned int value, int bits = 32 )
{
assert( ptr );
assert( buffer );
assert( bits > 0 );
assert( bits <= 32 );
assert( mode == Write );
if ( bits < 32 )
{
const unsigned int mask = ( 1 << bits ) - 1;
value &= mask;
}
do
{
assert( ptr - buffer < bytes );
*ptr |= (unsigned char) ( value << bit_index );
assert( bit_index < 8 );
const int bits_written = std::min( bits, 8 - bit_index );
assert( bits_written > 0 );
assert( bits_written <= 8 );
bit_index += bits_written;
if ( bit_index >= 8 )
{
ptr++;
bit_index = 0;
value >>= bits_written;
}
bits -= bits_written;
assert( bits >= 0 );
assert( bits <= 32 );
}
while ( bits > 0 );
}
void ReadBits( unsigned int & value, int bits = 32 )
{
assert( ptr );
assert( buffer );
assert( bits > 0 );
assert( bits <= 32 );
assert( mode == Read );
int original_bits = bits;
int value_index = 0;
value = 0;
do
{
assert( ptr - buffer < bytes );
assert( bits >= 0 );
assert( bits <= 32 );
int bits_to_read = std::min( 8 - bit_index, bits );
assert( bits_to_read > 0 );
assert( bits_to_read <= 8 );
value |= ( *ptr >> bit_index ) << value_index;
bits -= bits_to_read;
bit_index += bits_to_read;
value_index += bits_to_read;
assert( value_index >= 0 );
assert( value_index <= 32 );
if ( bit_index >= 8 )
{
ptr++;
bit_index = 0;
}
}
while ( bits > 0 );
if ( original_bits < 32 )
{
const unsigned int mask = ( 1 << original_bits ) - 1;
value &= mask;
}
}
void * GetData()
{
return buffer;
}
int GetBits() const
{
return ( ptr - buffer ) * 8 + bit_index;
}
int GetBytes() const
{
return (int) ( ptr - buffer ) + ( bit_index > 0 ? 1 : 0 );
}
int BitsRemaining() const
{
return bytes * 8 - ( ( ptr - buffer ) * 8 + bit_index );
}
Mode GetMode() const
{
return mode;
}
bool IsValid() const
{
return buffer != NULL;
}
private:
int bit_index;
unsigned char * ptr;
unsigned char * buffer;
int bytes;
Mode mode;
};
// arithmetic coder
// + todo: implement arithmetic coder based on jon blow's game developer article
class ArithmeticCoder
{
public:
enum Mode
{
Read,
Write
};
ArithmeticCoder( Mode mode, void * buffer, unsigned int size )
{
assert( buffer );
assert( size >= 0 );
this->mode = mode;
this->buffer = (unsigned char*) buffer;
this->size = size;
}
bool WriteInteger( unsigned int value, unsigned int minimum = 0, unsigned int maximum = 0xFFFFFFFF )
{
// ...
return false;
}
bool ReadInteger( unsigned int value, unsigned int minimum = 0, unsigned int maximum = 0xFFFFFFFF )
{
// ...
return false;
}
private:
unsigned char * buffer;
int size;
Mode mode;
};
// stream class
// + unifies read and write into a serialize operation
// + provides attribution of stream for debugging purposes
class Stream
{
public:
enum Mode
{
Read,
Write
};
Stream( Mode mode, void * buffer, int bytes, void * journal_buffer = NULL, int journal_bytes = 0 )
: bitpacker( mode == Write ? BitPacker::Write : BitPacker::Read, buffer, bytes ),
journal( mode == Write ? BitPacker::Write : BitPacker::Read, journal_buffer, journal_bytes )
{
}
bool SerializeBoolean( bool & value )
{
unsigned int tmp = (unsigned int) value;
bool result = SerializeBits( tmp, 1 );
value = (bool) tmp;
return result;
}
bool SerializeByte( char & value, char min = -127, char max = +128 )
{
// wtf: why do I have to do this!?
unsigned int tmp = (unsigned int) ( value + 127 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 127 ), ( max + 127 ) );
value = ( (char) tmp ) - 127;
return result;
}
bool SerializeByte( signed char & value, signed char min = -127, signed char max = +128 )
{
unsigned int tmp = (unsigned int) ( value + 127 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 127 ), ( max + 127 ) );
value = ( (signed char) tmp ) - 127;
return result;
}
bool SerializeByte( unsigned char & value, unsigned char min = 0, unsigned char max = 0xFF )
{
unsigned int tmp = (unsigned int) value;
bool result = SerializeInteger( tmp, min, max );
value = (unsigned char) tmp;
return result;
}
bool SerializeShort( signed short & value, signed short min = -32767, signed short max = +32768 )
{
unsigned int tmp = (unsigned int) ( value + 32767 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 32767 ), ( max + 32767 ) );
value = ( (signed short) tmp ) - 32767;
return result;
}
bool SerializeShort( unsigned short & value, unsigned short min = 0, unsigned short max = 0xFFFF )
{
unsigned int tmp = (unsigned int) value;
bool result = SerializeInteger( tmp, min, max );
value = (unsigned short) tmp;
return result;
}
bool SerializeInteger( signed int & value, signed int min = -2147483646, signed int max = +2147483647 )
{
unsigned int tmp = (unsigned int) ( value + 2147483646 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 2147483646 ), ( max + 2147483646 ) );
value = ( (signed int) tmp ) - 2147483646;
return result;
}
bool SerializeInteger( unsigned int & value, unsigned int min = 0, unsigned int max = 0xFFFFFFFF )
{
assert( min < max );
if ( IsWriting() )
{
assert( value >= min );
assert( value <= max );
}
const int bits_required = BitsRequired( min, max );
unsigned int bits = value - min;
bool result = SerializeBits( bits, bits_required );
if ( IsReading() )
{
value = bits + min;
assert( value >= min );
assert( value <= max );
}
return result;
}
bool SerializeFloat( float & value )
{
union FloatInt
{
unsigned int i;
float f;
};
if ( IsReading() )
{
FloatInt floatInt;
if ( !SerializeBits( floatInt.i, 32 ) )
return false;
value = floatInt.f;
return true;
}
else
{
FloatInt floatInt;
floatInt.f = value;
return SerializeBits( floatInt.i, 32 );
}
}
bool SerializeBits( unsigned int & value, int bits )
{
assert( bits >= 1 );
assert( bits <= 32 );
if ( bitpacker.BitsRemaining() < bits )
return false;
if ( journal.IsValid() )
{
unsigned int token = 2 + bits; // note: 0 = end, 1 = checkpoint, [2,34] = n - 2 bits written
if ( IsWriting() )
{
journal.WriteBits( token, 6 );
}
else
{
journal.ReadBits( token, 6 );
int bits_written = token - 2;
if ( bits != bits_written )
{
printf( "desync read/write: attempting to read %d bits when %d bits were written\n", bits, bits_written );
return false;
}
}
}
if ( IsReading() )
bitpacker.ReadBits( value, bits );
else
bitpacker.WriteBits( value, bits );
return true;
}
bool Checkpoint()
{
if ( journal.IsValid() )
{
unsigned int token = 1; // note: 0 = end, 1 = checkpoint, [2,34] = n - 2 bits written
if ( IsWriting() )
{
journal.WriteBits( token, 6 );
}
else
{
journal.ReadBits( token, 6 );
if ( token != 1 )
{
printf( "desync read/write: checkpoint not present in journal\n" );
return false;
}
}
}
unsigned int magic = 0x12345678;
unsigned int value = magic;
if ( bitpacker.BitsRemaining() < 32 )
{
printf( "not enough bits remaining for checkpoint\n" );
return false;
}
if ( IsWriting() )
bitpacker.WriteBits( value, 32 );
else
bitpacker.ReadBits( value, 32 );
if ( value != magic )
{
printf( "checkpoint failed!\n" );
return false;
}
return true;
}
bool IsReading() const
{
return bitpacker.GetMode() == BitPacker::Read;
}
bool IsWriting() const
{
return bitpacker.GetMode() == BitPacker::Write;
}
int GetBitsProcessed() const
{
return bitpacker.GetBits();
}
int GetBitsRemaining() const
{
return bitpacker.BitsRemaining();
}
static int BitsRequired( unsigned int minimum, unsigned int maximum )
{
assert( maximum > minimum );
assert( maximum >= 1 );
if ( maximum - minimum >= 0x7FFFFFF )
return 32;
return BitsRequired( maximum - minimum + 1 );
}
static int BitsRequired( unsigned int distinctValues )
{
assert( distinctValues > 1 );
unsigned int maximumValue = distinctValues - 1;
for ( int index = 0; index < 32; ++index )
{
if ( ( maximumValue & ~1 ) == 0 )
return index + 1;
maximumValue >>= 1;
}
return 32;
}
int GetDataBytes() const
{
return bitpacker.GetBytes();
}
int GetJournalBytes() const
{
return journal.GetBytes();
}
void DumpJournal()
{
if ( journal.IsValid() )
{
printf( "-----------------------------\n" );
printf( "dump journal:\n" );
BitPacker reader( BitPacker::Read, journal.GetData(), journal.GetBytes() );
while ( reader.BitsRemaining() > 6 )
{
unsigned int token = 0;
reader.ReadBits( token, 6 );
if ( token == 0 )
break;
if ( token == 1 )
printf( " (checkpoint)\n" );
else
printf( " + %d bits\n", token - 2 );
}
printf( "-----------------------------\n" );
}
else
printf( "no journal exists!\n" );
}
private:
BitPacker bitpacker;
BitPacker journal;
};
}
#endif | [
"yinpsoft@vip.qq.com"
] | yinpsoft@vip.qq.com |
cdf81bf63d2da602e6de8925a3439d07eb248eb9 | 93294d148df93b4378f59ac815476919273d425f | /src/Lib/steam/isteamugc.h | 4a7d2964b66dd427ab4869f7ed9678240a8f854f | [
"MIT"
] | permissive | FreeAllegiance/Allegiance | f1addb3b26efb6b8518705a0b0300974820333c3 | 3856ebcd8c35a6d63dbf398a4bc7f0264d6c823c | refs/heads/master | 2023-07-06T17:53:24.363387 | 2023-06-29T00:24:26 | 2023-06-29T00:24:26 | 98,829,929 | 86 | 34 | MIT | 2023-06-28T03:57:34 | 2017-07-30T23:09:14 | C++ | UTF-8 | C++ | false | false | 28,116 | h | //====== Copyright 1996-2013, Valve Corporation, All rights reserved. =======
//
// Purpose: interface to steam ugc
//
//=============================================================================
#ifndef ISTEAMUGC_H
#define ISTEAMUGC_H
#ifdef _WIN32
#pragma once
#endif
#include "isteamclient.h"
// callbacks
#if defined( VALVE_CALLBACK_PACK_SMALL )
#pragma pack( push, 4 )
#elif defined( VALVE_CALLBACK_PACK_LARGE )
#pragma pack( push, 8 )
#else
#error isteamclient.h must be included
#endif
typedef uint64 UGCQueryHandle_t;
typedef uint64 UGCUpdateHandle_t;
const UGCQueryHandle_t k_UGCQueryHandleInvalid = 0xffffffffffffffffull;
const UGCUpdateHandle_t k_UGCUpdateHandleInvalid = 0xffffffffffffffffull;
// Matching UGC types for queries
enum EUGCMatchingUGCType
{
k_EUGCMatchingUGCType_Items = 0, // both mtx items and ready-to-use items
k_EUGCMatchingUGCType_Items_Mtx = 1,
k_EUGCMatchingUGCType_Items_ReadyToUse = 2,
k_EUGCMatchingUGCType_Collections = 3,
k_EUGCMatchingUGCType_Artwork = 4,
k_EUGCMatchingUGCType_Videos = 5,
k_EUGCMatchingUGCType_Screenshots = 6,
k_EUGCMatchingUGCType_AllGuides = 7, // both web guides and integrated guides
k_EUGCMatchingUGCType_WebGuides = 8,
k_EUGCMatchingUGCType_IntegratedGuides = 9,
k_EUGCMatchingUGCType_UsableInGame = 10, // ready-to-use items and integrated guides
k_EUGCMatchingUGCType_ControllerBindings = 11,
k_EUGCMatchingUGCType_GameManagedItems = 12, // game managed items (not managed by users)
k_EUGCMatchingUGCType_All = ~0, // return everything
};
// Different lists of published UGC for a user.
// If the current logged in user is different than the specified user, then some options may not be allowed.
enum EUserUGCList
{
k_EUserUGCList_Published,
k_EUserUGCList_VotedOn,
k_EUserUGCList_VotedUp,
k_EUserUGCList_VotedDown,
k_EUserUGCList_WillVoteLater,
k_EUserUGCList_Favorited,
k_EUserUGCList_Subscribed,
k_EUserUGCList_UsedOrPlayed,
k_EUserUGCList_Followed,
};
// Sort order for user published UGC lists (defaults to creation order descending)
enum EUserUGCListSortOrder
{
k_EUserUGCListSortOrder_CreationOrderDesc,
k_EUserUGCListSortOrder_CreationOrderAsc,
k_EUserUGCListSortOrder_TitleAsc,
k_EUserUGCListSortOrder_LastUpdatedDesc,
k_EUserUGCListSortOrder_SubscriptionDateDesc,
k_EUserUGCListSortOrder_VoteScoreDesc,
k_EUserUGCListSortOrder_ForModeration,
};
// Combination of sorting and filtering for queries across all UGC
enum EUGCQuery
{
k_EUGCQuery_RankedByVote = 0,
k_EUGCQuery_RankedByPublicationDate = 1,
k_EUGCQuery_AcceptedForGameRankedByAcceptanceDate = 2,
k_EUGCQuery_RankedByTrend = 3,
k_EUGCQuery_FavoritedByFriendsRankedByPublicationDate = 4,
k_EUGCQuery_CreatedByFriendsRankedByPublicationDate = 5,
k_EUGCQuery_RankedByNumTimesReported = 6,
k_EUGCQuery_CreatedByFollowedUsersRankedByPublicationDate = 7,
k_EUGCQuery_NotYetRated = 8,
k_EUGCQuery_RankedByTotalVotesAsc = 9,
k_EUGCQuery_RankedByVotesUp = 10,
k_EUGCQuery_RankedByTextSearch = 11,
k_EUGCQuery_RankedByTotalUniqueSubscriptions = 12,
k_EUGCQuery_RankedByPlaytimeTrend = 13,
k_EUGCQuery_RankedByTotalPlaytime = 14,
k_EUGCQuery_RankedByAveragePlaytimeTrend = 15,
k_EUGCQuery_RankedByLifetimeAveragePlaytime = 16,
k_EUGCQuery_RankedByPlaytimeSessionsTrend = 17,
k_EUGCQuery_RankedByLifetimePlaytimeSessions = 18,
};
enum EItemUpdateStatus
{
k_EItemUpdateStatusInvalid = 0, // The item update handle was invalid, job might be finished, listen too SubmitItemUpdateResult_t
k_EItemUpdateStatusPreparingConfig = 1, // The item update is processing configuration data
k_EItemUpdateStatusPreparingContent = 2, // The item update is reading and processing content files
k_EItemUpdateStatusUploadingContent = 3, // The item update is uploading content changes to Steam
k_EItemUpdateStatusUploadingPreviewFile = 4, // The item update is uploading new preview file image
k_EItemUpdateStatusCommittingChanges = 5 // The item update is committing all changes
};
enum EItemState
{
k_EItemStateNone = 0, // item not tracked on client
k_EItemStateSubscribed = 1, // current user is subscribed to this item. Not just cached.
k_EItemStateLegacyItem = 2, // item was created with ISteamRemoteStorage
k_EItemStateInstalled = 4, // item is installed and usable (but maybe out of date)
k_EItemStateNeedsUpdate = 8, // items needs an update. Either because it's not installed yet or creator updated content
k_EItemStateDownloading = 16, // item update is currently downloading
k_EItemStateDownloadPending = 32, // DownloadItem() was called for this item, content isn't available until DownloadItemResult_t is fired
};
enum EItemStatistic
{
k_EItemStatistic_NumSubscriptions = 0,
k_EItemStatistic_NumFavorites = 1,
k_EItemStatistic_NumFollowers = 2,
k_EItemStatistic_NumUniqueSubscriptions = 3,
k_EItemStatistic_NumUniqueFavorites = 4,
k_EItemStatistic_NumUniqueFollowers = 5,
k_EItemStatistic_NumUniqueWebsiteViews = 6,
k_EItemStatistic_ReportScore = 7,
k_EItemStatistic_NumSecondsPlayed = 8,
k_EItemStatistic_NumPlaytimeSessions = 9,
k_EItemStatistic_NumComments = 10,
k_EItemStatistic_NumSecondsPlayedDuringTimePeriod = 11,
k_EItemStatistic_NumPlaytimeSessionsDuringTimePeriod = 12,
};
enum EItemPreviewType
{
k_EItemPreviewType_Image = 0, // standard image file expected (e.g. jpg, png, gif, etc.)
k_EItemPreviewType_YouTubeVideo = 1, // video id is stored
k_EItemPreviewType_Sketchfab = 2, // model id is stored
k_EItemPreviewType_EnvironmentMap_HorizontalCross = 3, // standard image file expected - cube map in the layout
// +---+---+-------+
// | |Up | |
// +---+---+---+---+
// | L | F | R | B |
// +---+---+---+---+
// | |Dn | |
// +---+---+---+---+
k_EItemPreviewType_EnvironmentMap_LatLong = 4, // standard image file expected
k_EItemPreviewType_ReservedMax = 255, // you can specify your own types above this value
};
const uint32 kNumUGCResultsPerPage = 50;
const uint32 k_cchDeveloperMetadataMax = 5000;
// Details for a single published file/UGC
struct SteamUGCDetails_t
{
PublishedFileId_t m_nPublishedFileId;
EResult m_eResult; // The result of the operation.
EWorkshopFileType m_eFileType; // Type of the file
AppId_t m_nCreatorAppID; // ID of the app that created this file.
AppId_t m_nConsumerAppID; // ID of the app that will consume this file.
char m_rgchTitle[k_cchPublishedDocumentTitleMax]; // title of document
char m_rgchDescription[k_cchPublishedDocumentDescriptionMax]; // description of document
uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content.
uint32 m_rtimeCreated; // time when the published file was created
uint32 m_rtimeUpdated; // time when the published file was last updated
uint32 m_rtimeAddedToUserList; // time when the user added the published file to their list (not always applicable)
ERemoteStoragePublishedFileVisibility m_eVisibility; // visibility
bool m_bBanned; // whether the file was banned
bool m_bAcceptedForUse; // developer has specifically flagged this item as accepted in the Workshop
bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer
char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file
// file/url information
UGCHandle_t m_hFile; // The handle of the primary file
UGCHandle_t m_hPreviewFile; // The handle of the preview file
char m_pchFileName[k_cchFilenameMax]; // The cloud filename of the primary file
int32 m_nFileSize; // Size of the primary file
int32 m_nPreviewFileSize; // Size of the preview file
char m_rgchURL[k_cchPublishedFileURLMax]; // URL (for a video or a website)
// voting information
uint32 m_unVotesUp; // number of votes up
uint32 m_unVotesDown; // number of votes down
float m_flScore; // calculated score
// collection details
uint32 m_unNumChildren;
};
//-----------------------------------------------------------------------------
// Purpose: Steam UGC support API
//-----------------------------------------------------------------------------
class ISteamUGC
{
public:
// Query UGC associated with a user. Creator app id or consumer app id must be valid and be set to the current running app. unPage should start at 1.
virtual UGCQueryHandle_t CreateQueryUserUGCRequest( AccountID_t unAccountID, EUserUGCList eListType, EUGCMatchingUGCType eMatchingUGCType, EUserUGCListSortOrder eSortOrder, AppId_t nCreatorAppID, AppId_t nConsumerAppID, uint32 unPage ) = 0;
// Query for all matching UGC. Creator app id or consumer app id must be valid and be set to the current running app. unPage should start at 1.
virtual UGCQueryHandle_t CreateQueryAllUGCRequest( EUGCQuery eQueryType, EUGCMatchingUGCType eMatchingeMatchingUGCTypeFileType, AppId_t nCreatorAppID, AppId_t nConsumerAppID, uint32 unPage ) = 0;
// Query for the details of the given published file ids (the RequestUGCDetails call is deprecated and replaced with this)
virtual UGCQueryHandle_t CreateQueryUGCDetailsRequest( PublishedFileId_t *pvecPublishedFileID, uint32 unNumPublishedFileIDs ) = 0;
// Send the query to Steam
CALL_RESULT( SteamUGCQueryCompleted_t )
virtual SteamAPICall_t SendQueryUGCRequest( UGCQueryHandle_t handle ) = 0;
// Retrieve an individual result after receiving the callback for querying UGC
virtual bool GetQueryUGCResult( UGCQueryHandle_t handle, uint32 index, SteamUGCDetails_t *pDetails ) = 0;
virtual bool GetQueryUGCPreviewURL( UGCQueryHandle_t handle, uint32 index, OUT_STRING_COUNT(cchURLSize) char *pchURL, uint32 cchURLSize ) = 0;
virtual bool GetQueryUGCMetadata( UGCQueryHandle_t handle, uint32 index, OUT_STRING_COUNT(cchMetadatasize) char *pchMetadata, uint32 cchMetadatasize ) = 0;
virtual bool GetQueryUGCChildren( UGCQueryHandle_t handle, uint32 index, PublishedFileId_t* pvecPublishedFileID, uint32 cMaxEntries ) = 0;
virtual bool GetQueryUGCStatistic( UGCQueryHandle_t handle, uint32 index, EItemStatistic eStatType, uint64 *pStatValue ) = 0;
virtual uint32 GetQueryUGCNumAdditionalPreviews( UGCQueryHandle_t handle, uint32 index ) = 0;
virtual bool GetQueryUGCAdditionalPreview( UGCQueryHandle_t handle, uint32 index, uint32 previewIndex, OUT_STRING_COUNT(cchURLSize) char *pchURLOrVideoID, uint32 cchURLSize, OUT_STRING_COUNT(cchURLSize) char *pchOriginalFileName, uint32 cchOriginalFileNameSize, EItemPreviewType *pPreviewType ) = 0;
virtual uint32 GetQueryUGCNumKeyValueTags( UGCQueryHandle_t handle, uint32 index ) = 0;
virtual bool GetQueryUGCKeyValueTag( UGCQueryHandle_t handle, uint32 index, uint32 keyValueTagIndex, OUT_STRING_COUNT(cchKeySize) char *pchKey, uint32 cchKeySize, OUT_STRING_COUNT(cchValueSize) char *pchValue, uint32 cchValueSize ) = 0;
// Release the request to free up memory, after retrieving results
virtual bool ReleaseQueryUGCRequest( UGCQueryHandle_t handle ) = 0;
// Options to set for querying UGC
virtual bool AddRequiredTag( UGCQueryHandle_t handle, const char *pTagName ) = 0;
virtual bool AddExcludedTag( UGCQueryHandle_t handle, const char *pTagName ) = 0;
virtual bool SetReturnOnlyIDs( UGCQueryHandle_t handle, bool bReturnOnlyIDs ) = 0;
virtual bool SetReturnKeyValueTags( UGCQueryHandle_t handle, bool bReturnKeyValueTags ) = 0;
virtual bool SetReturnLongDescription( UGCQueryHandle_t handle, bool bReturnLongDescription ) = 0;
virtual bool SetReturnMetadata( UGCQueryHandle_t handle, bool bReturnMetadata ) = 0;
virtual bool SetReturnChildren( UGCQueryHandle_t handle, bool bReturnChildren ) = 0;
virtual bool SetReturnAdditionalPreviews( UGCQueryHandle_t handle, bool bReturnAdditionalPreviews ) = 0;
virtual bool SetReturnTotalOnly( UGCQueryHandle_t handle, bool bReturnTotalOnly ) = 0;
virtual bool SetReturnPlaytimeStats( UGCQueryHandle_t handle, uint32 unDays ) = 0;
virtual bool SetLanguage( UGCQueryHandle_t handle, const char *pchLanguage ) = 0;
virtual bool SetAllowCachedResponse( UGCQueryHandle_t handle, uint32 unMaxAgeSeconds ) = 0;
// Options only for querying user UGC
virtual bool SetCloudFileNameFilter( UGCQueryHandle_t handle, const char *pMatchCloudFileName ) = 0;
// Options only for querying all UGC
virtual bool SetMatchAnyTag( UGCQueryHandle_t handle, bool bMatchAnyTag ) = 0;
virtual bool SetSearchText( UGCQueryHandle_t handle, const char *pSearchText ) = 0;
virtual bool SetRankedByTrendDays( UGCQueryHandle_t handle, uint32 unDays ) = 0;
virtual bool AddRequiredKeyValueTag( UGCQueryHandle_t handle, const char *pKey, const char *pValue ) = 0;
// DEPRECATED - Use CreateQueryUGCDetailsRequest call above instead!
virtual SteamAPICall_t RequestUGCDetails( PublishedFileId_t nPublishedFileID, uint32 unMaxAgeSeconds ) = 0;
// Steam Workshop Creator API
CALL_RESULT( CreateItemResult_t )
virtual SteamAPICall_t CreateItem( AppId_t nConsumerAppId, EWorkshopFileType eFileType ) = 0; // create new item for this app with no content attached yet
virtual UGCUpdateHandle_t StartItemUpdate( AppId_t nConsumerAppId, PublishedFileId_t nPublishedFileID ) = 0; // start an UGC item update. Set changed properties before commiting update with CommitItemUpdate()
virtual bool SetItemTitle( UGCUpdateHandle_t handle, const char *pchTitle ) = 0; // change the title of an UGC item
virtual bool SetItemDescription( UGCUpdateHandle_t handle, const char *pchDescription ) = 0; // change the description of an UGC item
virtual bool SetItemUpdateLanguage( UGCUpdateHandle_t handle, const char *pchLanguage ) = 0; // specify the language of the title or description that will be set
virtual bool SetItemMetadata( UGCUpdateHandle_t handle, const char *pchMetaData ) = 0; // change the metadata of an UGC item (max = k_cchDeveloperMetadataMax)
virtual bool SetItemVisibility( UGCUpdateHandle_t handle, ERemoteStoragePublishedFileVisibility eVisibility ) = 0; // change the visibility of an UGC item
virtual bool SetItemTags( UGCUpdateHandle_t updateHandle, const SteamParamStringArray_t *pTags ) = 0; // change the tags of an UGC item
virtual bool SetItemContent( UGCUpdateHandle_t handle, const char *pszContentFolder ) = 0; // update item content from this local folder
virtual bool SetItemPreview( UGCUpdateHandle_t handle, const char *pszPreviewFile ) = 0; // change preview image file for this item. pszPreviewFile points to local image file, which must be under 1MB in size
virtual bool RemoveItemKeyValueTags( UGCUpdateHandle_t handle, const char *pchKey ) = 0; // remove any existing key-value tags with the specified key
virtual bool AddItemKeyValueTag( UGCUpdateHandle_t handle, const char *pchKey, const char *pchValue ) = 0; // add new key-value tags for the item. Note that there can be multiple values for a tag.
virtual bool AddItemPreviewFile( UGCUpdateHandle_t handle, const char *pszPreviewFile, EItemPreviewType type ) = 0; // add preview file for this item. pszPreviewFile points to local file, which must be under 1MB in size
virtual bool AddItemPreviewVideo( UGCUpdateHandle_t handle, const char *pszVideoID ) = 0; // add preview video for this item
virtual bool UpdateItemPreviewFile( UGCUpdateHandle_t handle, uint32 index, const char *pszPreviewFile ) = 0; // updates an existing preview file for this item. pszPreviewFile points to local file, which must be under 1MB in size
virtual bool UpdateItemPreviewVideo( UGCUpdateHandle_t handle, uint32 index, const char *pszVideoID ) = 0; // updates an existing preview video for this item
virtual bool RemoveItemPreview( UGCUpdateHandle_t handle, uint32 index ) = 0; // remove a preview by index starting at 0 (previews are sorted)
CALL_RESULT( SubmitItemUpdateResult_t )
virtual SteamAPICall_t SubmitItemUpdate( UGCUpdateHandle_t handle, const char *pchChangeNote ) = 0; // commit update process started with StartItemUpdate()
virtual EItemUpdateStatus GetItemUpdateProgress( UGCUpdateHandle_t handle, uint64 *punBytesProcessed, uint64* punBytesTotal ) = 0;
// Steam Workshop Consumer API
CALL_RESULT( SetUserItemVoteResult_t )
virtual SteamAPICall_t SetUserItemVote( PublishedFileId_t nPublishedFileID, bool bVoteUp ) = 0;
CALL_RESULT( GetUserItemVoteResult_t )
virtual SteamAPICall_t GetUserItemVote( PublishedFileId_t nPublishedFileID ) = 0;
CALL_RESULT( UserFavoriteItemsListChanged_t )
virtual SteamAPICall_t AddItemToFavorites( AppId_t nAppId, PublishedFileId_t nPublishedFileID ) = 0;
CALL_RESULT( UserFavoriteItemsListChanged_t )
virtual SteamAPICall_t RemoveItemFromFavorites( AppId_t nAppId, PublishedFileId_t nPublishedFileID ) = 0;
CALL_RESULT( RemoteStorageSubscribePublishedFileResult_t )
virtual SteamAPICall_t SubscribeItem( PublishedFileId_t nPublishedFileID ) = 0; // subscribe to this item, will be installed ASAP
CALL_RESULT( RemoteStorageUnsubscribePublishedFileResult_t )
virtual SteamAPICall_t UnsubscribeItem( PublishedFileId_t nPublishedFileID ) = 0; // unsubscribe from this item, will be uninstalled after game quits
virtual uint32 GetNumSubscribedItems() = 0; // number of subscribed items
virtual uint32 GetSubscribedItems( PublishedFileId_t* pvecPublishedFileID, uint32 cMaxEntries ) = 0; // all subscribed item PublishFileIDs
// get EItemState flags about item on this client
virtual uint32 GetItemState( PublishedFileId_t nPublishedFileID ) = 0;
// get info about currently installed content on disc for items that have k_EItemStateInstalled set
// if k_EItemStateLegacyItem is set, pchFolder contains the path to the legacy file itself (not a folder)
virtual bool GetItemInstallInfo( PublishedFileId_t nPublishedFileID, uint64 *punSizeOnDisk, OUT_STRING_COUNT( cchFolderSize ) char *pchFolder, uint32 cchFolderSize, uint32 *punTimeStamp ) = 0;
// get info about pending update for items that have k_EItemStateNeedsUpdate set. punBytesTotal will be valid after download started once
virtual bool GetItemDownloadInfo( PublishedFileId_t nPublishedFileID, uint64 *punBytesDownloaded, uint64 *punBytesTotal ) = 0;
// download new or update already installed item. If function returns true, wait for DownloadItemResult_t. If the item is already installed,
// then files on disk should not be used until callback received. If item is not subscribed to, it will be cached for some time.
// If bHighPriority is set, any other item download will be suspended and this item downloaded ASAP.
virtual bool DownloadItem( PublishedFileId_t nPublishedFileID, bool bHighPriority ) = 0;
// game servers can set a specific workshop folder before issuing any UGC commands.
// This is helpful if you want to support multiple game servers running out of the same install folder
virtual bool BInitWorkshopForGameServer( DepotId_t unWorkshopDepotID, const char *pszFolder ) = 0;
// SuspendDownloads( true ) will suspend all workshop downloads until SuspendDownloads( false ) is called or the game ends
virtual void SuspendDownloads( bool bSuspend ) = 0;
// usage tracking
CALL_RESULT( StartPlaytimeTrackingResult_t )
virtual SteamAPICall_t StartPlaytimeTracking( PublishedFileId_t *pvecPublishedFileID, uint32 unNumPublishedFileIDs ) = 0;
CALL_RESULT( StopPlaytimeTrackingResult_t )
virtual SteamAPICall_t StopPlaytimeTracking( PublishedFileId_t *pvecPublishedFileID, uint32 unNumPublishedFileIDs ) = 0;
CALL_RESULT( StopPlaytimeTrackingResult_t )
virtual SteamAPICall_t StopPlaytimeTrackingForAllItems() = 0;
// parent-child relationship or dependency management
CALL_RESULT( AddUGCDependencyResult_t )
virtual SteamAPICall_t AddDependency( PublishedFileId_t nParentPublishedFileID, PublishedFileId_t nChildPublishedFileID ) = 0;
CALL_RESULT( RemoveUGCDependencyResult_t )
virtual SteamAPICall_t RemoveDependency( PublishedFileId_t nParentPublishedFileID, PublishedFileId_t nChildPublishedFileID ) = 0;
// add/remove app dependence/requirements (usually DLC)
CALL_RESULT( AddAppDependencyResult_t )
virtual SteamAPICall_t AddAppDependency( PublishedFileId_t nPublishedFileID, AppId_t nAppID ) = 0;
CALL_RESULT( RemoveAppDependencyResult_t )
virtual SteamAPICall_t RemoveAppDependency( PublishedFileId_t nPublishedFileID, AppId_t nAppID ) = 0;
// request app dependencies. note that whatever callback you register for GetAppDependenciesResult_t may be called multiple times
// until all app dependencies have been returned
CALL_RESULT( GetAppDependenciesResult_t )
virtual SteamAPICall_t GetAppDependencies( PublishedFileId_t nPublishedFileID ) = 0;
// delete the item without prompting the user
CALL_RESULT( DeleteItemResult_t )
virtual SteamAPICall_t DeleteItem( PublishedFileId_t nPublishedFileID ) = 0;
};
#define STEAMUGC_INTERFACE_VERSION "STEAMUGC_INTERFACE_VERSION010"
//-----------------------------------------------------------------------------
// Purpose: Callback for querying UGC
//-----------------------------------------------------------------------------
struct SteamUGCQueryCompleted_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 1 };
UGCQueryHandle_t m_handle;
EResult m_eResult;
uint32 m_unNumResultsReturned;
uint32 m_unTotalMatchingResults;
bool m_bCachedData; // indicates whether this data was retrieved from the local on-disk cache
};
//-----------------------------------------------------------------------------
// Purpose: Callback for requesting details on one piece of UGC
//-----------------------------------------------------------------------------
struct SteamUGCRequestUGCDetailsResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 2 };
SteamUGCDetails_t m_details;
bool m_bCachedData; // indicates whether this data was retrieved from the local on-disk cache
};
//-----------------------------------------------------------------------------
// Purpose: result for ISteamUGC::CreateItem()
//-----------------------------------------------------------------------------
struct CreateItemResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 3 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId; // new item got this UGC PublishFileID
bool m_bUserNeedsToAcceptWorkshopLegalAgreement;
};
//-----------------------------------------------------------------------------
// Purpose: result for ISteamUGC::SubmitItemUpdate()
//-----------------------------------------------------------------------------
struct SubmitItemUpdateResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 4 };
EResult m_eResult;
bool m_bUserNeedsToAcceptWorkshopLegalAgreement;
PublishedFileId_t m_nPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: a Workshop item has been installed or updated
//-----------------------------------------------------------------------------
struct ItemInstalled_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 5 };
AppId_t m_unAppID;
PublishedFileId_t m_nPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: result of DownloadItem(), existing item files can be accessed again
//-----------------------------------------------------------------------------
struct DownloadItemResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 6 };
AppId_t m_unAppID;
PublishedFileId_t m_nPublishedFileId;
EResult m_eResult;
};
//-----------------------------------------------------------------------------
// Purpose: result of AddItemToFavorites() or RemoveItemFromFavorites()
//-----------------------------------------------------------------------------
struct UserFavoriteItemsListChanged_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 7 };
PublishedFileId_t m_nPublishedFileId;
EResult m_eResult;
bool m_bWasAddRequest;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to SetUserItemVote()
//-----------------------------------------------------------------------------
struct SetUserItemVoteResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 8 };
PublishedFileId_t m_nPublishedFileId;
EResult m_eResult;
bool m_bVoteUp;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to GetUserItemVote()
//-----------------------------------------------------------------------------
struct GetUserItemVoteResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 9 };
PublishedFileId_t m_nPublishedFileId;
EResult m_eResult;
bool m_bVotedUp;
bool m_bVotedDown;
bool m_bVoteSkipped;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to StartPlaytimeTracking()
//-----------------------------------------------------------------------------
struct StartPlaytimeTrackingResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 10 };
EResult m_eResult;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to StopPlaytimeTracking()
//-----------------------------------------------------------------------------
struct StopPlaytimeTrackingResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 11 };
EResult m_eResult;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to AddDependency
//-----------------------------------------------------------------------------
struct AddUGCDependencyResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 12 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId;
PublishedFileId_t m_nChildPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to RemoveDependency
//-----------------------------------------------------------------------------
struct RemoveUGCDependencyResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 13 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId;
PublishedFileId_t m_nChildPublishedFileId;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to AddAppDependency
//-----------------------------------------------------------------------------
struct AddAppDependencyResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 14 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId;
AppId_t m_nAppID;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to RemoveAppDependency
//-----------------------------------------------------------------------------
struct RemoveAppDependencyResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 15 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId;
AppId_t m_nAppID;
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to GetAppDependencies. Callback may be called
// multiple times until all app dependencies have been returned.
//-----------------------------------------------------------------------------
struct GetAppDependenciesResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 16 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId;
AppId_t m_rgAppIDs[32];
uint32 m_nNumAppDependencies; // number returned in this struct
uint32 m_nTotalNumAppDependencies; // total found
};
//-----------------------------------------------------------------------------
// Purpose: The result of a call to DeleteItem
//-----------------------------------------------------------------------------
struct DeleteItemResult_t
{
enum { k_iCallback = k_iClientUGCCallbacks + 17 };
EResult m_eResult;
PublishedFileId_t m_nPublishedFileId;
};
#pragma pack( pop )
#endif // ISTEAMUGC_H
| [
"nick@zaphop.com"
] | nick@zaphop.com |
d62f08a68dae57354f14046bfc572f2d1682234d | cb3fff5404fc151e064a586895245e796f025425 | /assignment2/salestax.cpp | ce718424a877990f7328d39206b1f57dd91b0bd0 | [] | no_license | hkumar01/interterm2021-c- | 5dd5b70bb30d633e6ed29f570387a25439d1d411 | a63b53d98b5aff2bbe85d3ae00b6a51b003efb17 | refs/heads/main | 2023-02-25T14:07:23.616171 | 2021-01-29T12:28:22 | 2021-01-29T12:28:22 | 333,880,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | #include <iostream>
using namespace std;
float addTax(float cost, float taxRate)
{
cost = cost + (cost * taxRate);
return cost;
}
int main(int argc, char**argv)
{
float totalCost;
float salesTax;
cout << "Enter total cost: " << endl;
cin >> totalCost;
cout << "Enter sales tax rate as decimal value: " << endl;
cin >> salesTax;
totalCost = addTax(totalCost, salesTax);
cout << "Total cost with tax is: " << totalCost << endl;
}
| [
"hkumar@chapman.edu"
] | hkumar@chapman.edu |
4e60a470cb6bc71862a230112518cabc30f44ba0 | 6499b38172ef0f86be100d024d7ed4e74f6aa2bc | /Engine/Sprite.h | e8887e3bde985bc3d171dc27c7c370be83addd79 | [] | no_license | ralphsmith80/Game_Engine | a76ab08b0a3834571658915f7c52c71fbce3a01a | 6ad9544638c247de0ead285a5e36b244949cf036 | refs/heads/master | 2020-05-20T09:27:08.919374 | 2012-11-03T20:13:06 | 2012-11-03T20:13:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,215 | h | /*
* Sprite.h
* Advanced2D
*
* Created by Ralph Smith on 8/3/10.
* Copyright 2010 Ralph Smith. All rights reserved.
*
*/
#include "Advanced2D.h"
#ifndef __SPRITE_H__
#define __SPRITE_H__
namespace Advanced2D {
enum CollisionType {
COLLISION_NONE = 0,
COLLISION_RECT = 1,
COLLISION_DIST = 2
};
class Sprite : public Entity {
private:
Vector3 position;
Vector3 velocity;
bool imageLoaded;
int state;
int direction;
bool initialized;
float texWidthRatio;
float texHeightRatio;
Quad2f *vertices;
Quad2f *textureCoordinates;
Quad2f *transformedVerts;
GLushort *indices;
GPoint lastTextureOffset, textureOffset;
void calculateVerticesAtPoint (GPoint aPoint, GLuint aSubImageWidth, GLuint aSubImageHeight, bool aCenter);
void calculateTexCoordsAtOffset (GPoint aOffsetPoint, int aSubImageWidth, int aSubImageHeight);
protected:
Texture *image;
int width,height;
int animcolumns;
double framestart,frametimer;
double movestart, movetimer;
bool collidable;
enum CollisionType collisionMethod;
int curframe,totalframes,animdir;
double faceAngle, moveAngle;
int animstartx, animstarty;
double rotation, scaling;
GLfloat colorfilter[4][4];
Color4f color;
public:
Sprite();
virtual ~Sprite();
void init();
bool loadImage(std::string filename, TextureType type=TGA, GLenum filter=GL_LINEAR);
void setImage(Texture *);
void move();
void animate();
void draw(bool aCenter=true);
Texture* getImage() {return image;}
Sprite* getSubSprite(GPoint aPoint, int subWidth, int subHeight);
//screen position
Vector3 getPosition() { return position; }
void setPosition(Vector3 position) { this->position = position; }
void setPosition(double x, double y) { position.Set(x,y,0); }
double getX() { return position.getX(); }
double getY() { return position.getY(); }
void setX(double x) { position.setX(x); }
void setY(double y) { position.setY(y); }
//movement velocity
Vector3 getVelocity() { return velocity; }
void setVelocity(Vector3 v) { this->velocity = v; }
void setVelocity(double x, double y) { velocity.setX(x); velocity.setY(y); }
//image size
void setSize(int width, int height) { this->width = width; this->height = height; }
int getWidth() { return this->width; }
void setWidth(int value) { this->width = value; }
int getHeight() { return this->height; }
void setHeight(int value) { this->height = value; }
void setTextureOffset(float x, float y) {textureOffset.x = x; textureOffset.y = y;}
int getState() { return state; }
void setState(int value) { state = value; }
int getDirection() { return direction; }
void setDirection(int value) { direction = value; }
int getColumns() { return animcolumns; }
void setColumns(int value) { animcolumns = value; }
int getFrameTimer() { return frametimer; }
void setFrameTimer(int value) { frametimer = value; }
int getCurrentFrame() { return curframe; }
void setCurrentFrame(int value) { curframe = value; }
int getTotalFrames() { return totalframes; }
void setTotalFrames(int value) { totalframes = value; }
int getAnimationDirection() { return animdir; }
void setAnimationDirection(int value) { animdir = value; }
double getRotation() { return rotation; }
void setRotation(double value) { rotation = value; }
double getScale() { return scaling; }
void setScale(double value) { scaling = value; }
//modified from original -- new accessor
Color4f getColor() { return color; }
void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a=1.0) { color.red = r; color.green = g; color.blue = b; color.alpha = a;}
void setAlpha(GLfloat a) { color.alpha = a;}
int getMoveTimer() { return movetimer; }
void setMoveTimer(int value) { movetimer = value; }
bool isCollidable() { return collidable; }
void setCollidable(bool value) { collidable = value; }
CollisionType getCollisionMethod() { return collisionMethod; }
void setCollisionMethod(CollisionType type) { collisionMethod = type; }
Rect getBounds();
}; //class
};
#endif | [
"ralphsmith80@gmail.com"
] | ralphsmith80@gmail.com |
7c63e0ef398760ee517e826e76540ca70537ea12 | 6180c9e8278145285dbc2bf880a32cb20ca5a5a0 | /scenargie_simulator/2.2/source/simulator/routing/nuOLSRv2/olsrv2/ibase_n.h | 5ef90cf542b6d302470ff5522801afeba1a4c080 | [] | no_license | superzaxi/DCC | 0c529002e9f84a598247203a015f0f4ee0d61c22 | cd3e5755410a1266d705d74c0b037cc1609000cf | refs/heads/main | 2023-07-15T05:15:31.466339 | 2021-08-10T11:23:42 | 2021-08-10T11:23:42 | 384,296,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,170 | h | //
// (N) Neighbor Set
//
#ifndef OLSRV2_IBASE_N_H_
#define OLSRV2_IBASE_N_H_
#include "core/pvector.h"
namespace NuOLSRv2Port { //ScenSim-Port://
/************************************************************//**
* @defgroup ibase_n OLSRv2 :: (N) Neighbor Tuple
* @{
*/
/**
* (N) Neighbor Tuple
*/
typedef struct tuple_n {
struct tuple_n* next; ///< next tuple
struct tuple_n* prev; ///< prev tuple
nu_ip_set_t neighbor_ip_list; ///< N_neighbor_ifaddr_list
nu_bool_t symmetric; ///< N_symmetric
nu_ip_t orig_addr; ///< N_orig_addr
uint8_t willingness; ///< N_willingness
nu_bool_t routing_mpr; ///< N_routing_mpr
nu_bool_t flooding_mpr; ///< N_flooding_mpr
nu_bool_t mpr_selector; ///< N_mpr_selector
nu_bool_t advertised; ///< N_advertised
nu_link_metric_t _in_metric; ///< N_in_metric
nu_link_metric_t _out_metric; ///< N_out_metric
nu_bool_t flooding_mprs; ///< ...
nu_bool_t advertised_save; ///< previous advertised status
nu_bool_t routing_mpr_save; ///< previous mpr status
nu_bool_t flooding_mpr_save; ///< previous mpr status
nu_link_metric_t in_metric_save; ///< previous N_in_metric
nu_link_metric_t out_metric_save; ///< previous N_out_metric
size_t tuple_l_count; ///< # of tuple_l
} tuple_n_t;
/**
* (N) Neighbor Set
*/
typedef struct ibase_n {
tuple_n_t* next; ///< first tuple
tuple_n_t* prev; ///< last tuple
size_t n; ///< size
uint16_t ansn; ///< ANSN
nu_bool_t change; ///< change flag for links
nu_bool_t sym_change; ///< change flag for symmetric links
} ibase_n_t;
////////////////////////////////////////////////////////////////
//
// tuple_n_t
//
PUBLIC nu_bool_t tuple_n_has_symlink(const tuple_n_t*);
PUBLIC nu_bool_t tuple_n_has_link(const tuple_n_t*);
PUBLIC void tuple_n_add_neighbor_ip_list(tuple_n_t*, nu_ip_t);
PUBLIC void tuple_n_set_orig_addr(tuple_n_t*, nu_ip_t);
PUBLIC void tuple_n_set_symmetric(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_willingness(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_flooding_mpr(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_routing_mpr(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_mpr_selector(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_advertised(tuple_n_t*, nu_bool_t);
////////////////////////////////////////////////////////////////
//
// ibase_n_t
//
}//namespace// //ScenSim-Port://
#include "olsrv2/ibase_n_.h"
namespace NuOLSRv2Port { //ScenSim-Port://
#undef ibase_n_clear_change_flag
/** Clears the change flag.
*/
#define ibase_n_clear_change_flag() \
do { \
IBASE_N->change = false; \
IBASE_N->sym_change = false; \
} \
while (0)
#undef ibase_n_is_changed
/** Checks whether ibase_n is changed or not.
*/
#define ibase_n_is_changed() (IBASE_N->sym_change || IBASE_N->change)
PUBLIC void ibase_n_init(void);
PUBLIC void ibase_n_destroy(void);
PUBLIC tuple_n_t* ibase_n_add(const nu_ip_set_t*, const nu_ip_t);
PUBLIC tuple_n_t* ibase_n_search_tuple_l(tuple_l_t*);
PUBLIC nu_bool_t ibase_n_contain_symmetric(const nu_ip_t);
PUBLIC nu_bool_t ibase_n_contain_symmetric_without_prefix(const nu_ip_t);
PUBLIC tuple_n_t* ibase_n_iter_remove(tuple_n_t*);
PUBLIC void ibase_n_save_advertised(void);
PUBLIC nu_bool_t ibase_n_commit_advertised(void);
PUBLIC void ibase_n_save_flooding_mpr(void);
PUBLIC void ibase_n_commit_flooding_mpr(void);
PUBLIC void ibase_n_save_routing_mpr(void);
PUBLIC void ibase_n_commit_routing_mpr(void);
PUBLIC void ibase_n_save_advertised(void);
PUBLIC nu_bool_t ibase_n_commit_advertised(void);
PUBLIC void tuple_n_put_log(tuple_n_t*, nu_logger_t*);
PUBLIC void ibase_n_put_log(nu_logger_t*);
/** @} */
}//namespace// //ScenSim-Port://
#endif
| [
"zaki@keio.jp"
] | zaki@keio.jp |
175be1719b2a04ab851a40fb2dc411f85b87f774 | a5ea23ee7cd18bde94b8ae26bdf3224f64ebc70f | /C++/Day-1/Day-1-B.cpp | a9a73fab5772d861a7c982ab85325bc7128f9a19 | [] | no_license | Back-Log/AITH-CP-Club | f8c9f59c85bf6bc9d4a05ad0525b908a4dacdc35 | 164b4bca8a427c9608a891d3d684f49424f1b0ea | refs/heads/main | 2023-02-18T15:25:59.513175 | 2021-01-23T17:00:27 | 2021-01-23T17:00:27 | 332,251,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 143 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
cout<<(((n%2==0) and (n!=2))?"YES":"NO");
return 0;
}
| [
"64234448+Back-Log-Pratyush@users.noreply.github.com"
] | 64234448+Back-Log-Pratyush@users.noreply.github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.