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
14a85419e2473f2ea38bc6223477cc2570726f8a
0b4dbb9ae315adfa91b047fbc616884276d1a97d
/build-supervisor-Desktop_Qt_6_1_2_MinGW_64_bit-Debug/debug/moc_mainwindow.cpp
920c2d4d4b79e5ff81e7e8e87c25316e5b32424e
[]
no_license
JoaoPauloPrata/supervisor
fcb28aed0ab6d5ae7527f5ed80b2f8242fb26601
618e9ccaa3b6ce8da252d950c06658717e0ef9eb
refs/heads/master
2023-07-18T13:08:50.655007
2021-08-26T15:08:10
2021-08-26T15:08:10
392,493,109
0
1
null
2021-08-19T02:22:14
2021-08-04T00:14:52
C++
UTF-8
C++
false
false
3,634
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'mainwindow.h' ** ** Created by: The Qt Meta Object Compiler version 68 (Qt 6.1.2) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../../supervisor/mainwindow.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'mainwindow.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 68 #error "This file was generated using the moc from 6.1.2. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_MainWindow_t { const uint offsetsAndSize[6]; char stringdata0[36]; }; #define QT_MOC_LITERAL(ofs, len) \ uint(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs), len static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = { { QT_MOC_LITERAL(0, 10), // "MainWindow" QT_MOC_LITERAL(11, 23), // "on_button_login_clicked" QT_MOC_LITERAL(35, 0) // "" }, "MainWindow\0on_button_login_clicked\0" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_MainWindow[] = { // content: 9, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags, initial metatype offsets 1, 0, 20, 2, 0x08, 0 /* Private */, // slots: parameters QMetaType::Void, 0 // eod }; void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<MainWindow *>(_o); (void)_t; switch (_id) { case 0: _t->on_button_login_clicked(); break; default: ; } } (void)_a; } const QMetaObject MainWindow::staticMetaObject = { { QMetaObject::SuperData::link<QMainWindow::staticMetaObject>(), qt_meta_stringdata_MainWindow.offsetsAndSize, qt_meta_data_MainWindow, qt_static_metacall, nullptr, qt_incomplete_metaTypeArray<qt_meta_stringdata_MainWindow_t , QtPrivate::TypeAndForceComplete<void, std::false_type> >, nullptr } }; const QMetaObject *MainWindow::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *MainWindow::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0)) return static_cast<void*>(this); return QMainWindow::qt_metacast(_clname); } int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QMainWindow::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 1) *reinterpret_cast<QMetaType *>(_a[0]) = QMetaType(); _id -= 1; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
[ "joaoppcosta@hotmail.com.br" ]
joaoppcosta@hotmail.com.br
b431cb6f46bc3cc2df0aa3a461f5505695056892
4f27d12349224583c24f8941d2561684ee4f48de
/Source/Lastim/Public/Pickups/DroppedPickup.h
b774e87fedad28dae017245653ce3d9c4caf39c9
[]
no_license
nik3122/SolUnderSiege
5002af1e182ebb9a8e1616458a8b84e926c5b71b
167ce5cbafc29ef6ee33f160179eb6ca2b8f39f6
refs/heads/master
2023-08-26T03:46:40.485253
2021-10-20T06:49:37
2021-10-20T06:49:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
708
h
// Copyright Kyle Taylor Lange #pragma once #include "SpecificPickup.h" #include "DroppedPickup.generated.h" /** * CAN PROBABLY DELETE THIS CLASS LATER (parent class has lifespan functionality), BUT LET'S KEEP IT FOR NOW. */ UCLASS() class LASTIM_API ADroppedPickup : public ASpecificPickup { GENERATED_BODY() public: ADroppedPickup(const FObjectInitializer& ObjectInitializer); // Currently overridden to set a 60 second lifetime. //Todo?: maybe only set a life span if there are too many pickups in the level? //Also todo: check the game mode for a proper life span; we probably don't want to delete pickups on singleplayer/cooperative/etc gametypes. virtual void BeginPlay() override; };
[ "dakatsu@gmail.com" ]
dakatsu@gmail.com
3e867f84cf3f9caac1bfea889ddacee91860d7f5
7c3793fc4a1896efbcce2d9d871dccebf7150e6c
/cpp/1d_to_2d.cpp
25fcd447576fdd86749d1b6e3eb92afc1e4da846
[]
no_license
LePtC/Backup
b4d4d95d237936debbce2e139486d083a4fe6e8b
92272ef0ffc885c1799a1db53c5eb6168ea1eac3
refs/heads/master
2023-02-23T10:52:28.175549
2023-02-08T14:28:29
2023-02-08T14:28:29
17,785,927
0
0
null
null
null
null
UTF-8
C++
false
false
910
cpp
#include <vector> #include <algorithm> using namespace std; vector<vector<int>> fill_square(vector<vector<int>>& arr) { int rows = arr.size(); int cols = arr[0].size(); int size = max(rows, cols); vector<vector<int>> result(size, vector<int>(size, 0)); if (rows < size) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < size; ++j) { result[j][i] = arr[i][0]; } } } else { for (int i = 0; i < size; ++i) { for (int j = 0; j < cols; ++j) { result[i][j] = arr[0][j]; } } } return result; } int main() { vector<vector<int>> arr = {{1, 2, 3}, {4, 5, 6}}; auto result = fill_square(arr); for (const auto& row : result) { for (const auto& col : row) { cout << col << " "; } cout << endl; } return 0; }
[ "alileptc@gmail.com" ]
alileptc@gmail.com
4bcc12311816942f3f3339421aa79ed7d2bf8315
cb0963eeedf5d15a5364891e2690eda75dcdba8b
/Source/DigitViewer2/DigitReaders/BasicTextReader.h
25c35e7b89345fd65dddcd8399370d1a45511ad5
[ "BSD-3-Clause" ]
permissive
Mysticial/DigitViewer
ed17e786f6850555a4cd384a153c192e021d82b1
369d4bd94729712fb770100a9bec904071fd9bf9
refs/heads/master
2021-05-02T08:35:14.078443
2021-03-25T05:10:27
2021-03-25T05:10:27
13,462,178
45
13
BSD-3-Clause
2023-09-05T05:19:08
2013-10-10T04:42:48
C++
UTF-8
C++
false
false
3,754
h
/* BasicTextReader.h * * Author : Alexander J. Yee * Date Created : 01/14/2018 * Last Modified : 03/20/2018 * * This reader uses raw (unbuffered) I/O. * * The advantages of raw disk I/O are: * - Faster for bulk transfers because it eliminates the OS memcpy(). * - Saves memory since the OS doesn't need to allocate a buffer. * - Prevents the OS from doing any stupid caching that may lead to * the pagefile Thrash of Death. * * The disadvantage is that the buffer needs to be larger and must satisfy * stricter alignment requirements. It is also more difficult to implement. * */ #pragma once #ifndef ydv_DigitViewer_BasicTextReader_H #define ydv_DigitViewer_BasicTextReader_H //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // Dependencies #include <mutex> #include "PublicLibs/SystemLibs/FileIO/RawFile/RawFile.h" #include "BasicDigitReader.h" namespace DigitViewer2{ using namespace ymp; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// class BasicTextReader : public BasicDigitReader{ public: static const upL_t FILE_ALIGNMENT = FileIO::DEFAULT_FILE_ALIGNMENT; BasicTextReader(const std::string& path, char radix = 0); virtual std::string first_digits () override; virtual uiL_t stream_end () const override{ return m_total_digits; } virtual bool range_is_available (uiL_t offset, uiL_t digits) override; virtual upL_t recommend_buffer_size (uiL_t digits, upL_t limit) const override; virtual void load_stats( DigitStats& stats, uiL_t offset, uiL_t digits, const AlignedBufferC<BUFFER_ALIGNMENT>& buffer, BasicParallelizer& parallelizer, upL_t tds ) override; virtual void load_digits( char* output, DigitStats* stats, uiL_t offset, upL_t digits, const AlignedBufferC<BUFFER_ALIGNMENT>& buffer, BasicParallelizer& parallelizer, upL_t tds ) override; private: static const upL_t CACHE_BLOCK = 8192; void process( DigitStats* stats, char* output, const char* txt_digits, upL_t digits ) const; void process( DigitStats* stats, char* output, const char* txt_digits, upL_t digits, BasicParallelizer& parallelizer, upL_t tds ) const; class Action_process; private: using ConvertFunction = bool (*)(char* raw_digits, const char* buffer, upL_t digits); std::mutex m_lock; FileIO::RawFile m_file; // File handle ConvertFunction m_fp_convert; ufL_t m_data_offset; // Offset in the file of the first digit after the decimal place. ufL_t m_total_digits; // Digits after the decimal place. std::string m_first_digits; }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// } #endif
[ "a-yee@u.northwestern.edu" ]
a-yee@u.northwestern.edu
180b2b2824a445efc72de2663bcdcada8142b615
d3723ce7b88292110120460e538692995c50b426
/4-( Object Oriented Design and Programming)/2-PointRectangle(public).cpp
d163c03f71df290422e62792bd730dae9ed40873
[]
no_license
BackTo2012/CPP-OOP
abf68a7ae72a99b13c59fc3dcdfc98686eabeb3e
59569687a4fa7fd085ed4fac6303d84845c0470e
refs/heads/main
2023-06-16T19:03:51.500525
2021-07-04T07:35:58
2021-07-04T07:35:58
382,268,587
0
0
null
null
null
null
UTF-8
C++
false
false
871
cpp
#include <iostream> using namespace std; class Point { double x, y; public: void SetPoint(double x = 0, double y = 0) { this->x = x, this->y = y; } double GetX() const {return x;} double GetY() const {return y;} void Move(double xOff, double yOff) { x += xOff, y += yOff; } }; class Rectangle: public Point { private: double w, h; public: void SetRect(double x, double y, double w, double h) { SetPoint(x, y); this->w = w; this->h = h; } double GetW() const { return w; } double GetH() const { return h; } }; //StudybarCommentBegin int main() { Rectangle rect; rect.SetRect(0, 0, 1, 1); rect.Move(3, 2); cout << "sizeof(Point):" << sizeof(Point) << " and sizeof(rect):" << sizeof(rect) << ", (x,y,w,h) is (" << rect.GetX() << "," << rect.GetY() << "," << rect.GetW() << "," << rect.GetH() << ")"; return 0; } //StudybarCommentEnd
[ "1742331636@qq.com" ]
1742331636@qq.com
31faf293cc4c27fef775c3a92141c43e30b2a0c7
ed2be5ce5b5a66f32f36a0b5d2f6b38644efa90a
/test/TestThreadData.cpp
239411899742aeb07bdb8e85b207d61c48681dbd
[]
no_license
skyformat99/ccinfra
0784cf7cf1091e40799fc3d3e4916944fc68520a
07071aa91eb00f5ee2526e6e9c5e989621e01f0f
refs/heads/master
2021-01-21T00:05:18.692068
2016-06-11T04:18:16
2016-06-11T04:18:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
894
cpp
#include "gtest/gtest.h" #include <ccinfra/sched/ThreadData.h> namespace { struct ThreadInfo { static unsigned int getCurrentId() { return index; } static void setCurrentId(unsigned int id) { index = id; } const static unsigned int MAX_THREAD_NUM = 2; private: static unsigned int index; }; unsigned int ThreadInfo::index = 0; } struct ThreadDataTest : testing::Test { protected: ThreadData<int, ThreadInfo> data; }; TEST_F(ThreadDataTest, should_write_the_correct_thread_data_when_default_thread_id) { *data = 2; ASSERT_EQ(2, *data); ASSERT_EQ(2, data[0]); } TEST_F(ThreadDataTest, should_write_the_correct_thread_data_when_change_the_current_thread_id) { ThreadInfo::setCurrentId(1); *data = 5; ASSERT_EQ(5, *data); ASSERT_EQ(5, data[1]); }
[ "wang.bo123@zte.com.cn" ]
wang.bo123@zte.com.cn
0f6ded5402d78168e28705bc636185c9e402f7d1
9eb9796d34f587b02672d98a9e9dbda1cd7af3e6
/CS/1/C++PrimerPlus/unit4/programList/7strtype1.cpp
fa4aec632f253577808f7a31fdd3f761149ed761
[]
no_license
eternity6666/university
ef0b902158917d7c70287eaa1207ee28d9d98c20
953188832fd174270c43c584fc8c4beda297d95d
refs/heads/master
2021-07-15T04:16:50.128943
2020-05-15T02:34:17
2020-05-15T02:34:17
141,017,995
1
2
null
null
null
null
UTF-8
C++
false
false
673
cpp
// strtype1.cpp -- using the C++ string class #include <iostream> #include <string> #include <cstring> int main() { using namespace std; char charr1[20]; char charr2[20] = "jaguar"; string str1; string str2 = "panther"; cout << "Enter a kind of feline: "; cin >> charr1; cout << "Enter another kind of feline: "; cin >> str1; cout << "Here some felines: \n"; cout << charr1 << " " << charr2 << " " << str1 << " " << str2 << " " << endl; cout << "The third letter in " << charr2 << " is " << charr2[2] << endl; cout << "The third letter in " << str2 << " is " << str2[2] << endl; return 0; }
[ "eternity6666@qq.com" ]
eternity6666@qq.com
a4b8aa2b754d907b2fff02dfbcf60412ceed77eb
3279a02a10e0ddda4029d0db9c538dfb0014aa31
/Towers/Towers/towers.cpp
8c27958b16e636916de3d09634152ca2556f505d
[]
no_license
chengjieyun59/UCLA_CS32_projects
02089f968205b2ae544118cd29393456efabc98b
6320db86896538d09e1098f52f9201ac56803d40
refs/heads/master
2021-05-05T15:25:13.871335
2020-05-02T06:20:30
2020-05-02T06:20:30
117,296,171
0
0
null
null
null
null
UTF-8
C++
false
false
6,476
cpp
#include <stack> #include <iostream> using namespace std; #include "towers.h" TowersOfHanoi::TowersOfHanoi() { num_disks = 3; for (int i = num_disks - 1; i >= 0; --i) { m_towers[0].push(i); } printGameState(); } TowersOfHanoi::TowersOfHanoi(int n) { this->num_disks = n; for (int i = n - 1; i >= 0; --i) { m_towers[0].push(i); } printGameState(); } // function that doesn't return, but prints some result // you can move a disk from one tower to any other tower // as long as you obey the rule that a larger disk (larger // int) can never be place on top of a smaller disk void TowersOfHanoi::moveDisk(int fromTower, int toTower) { cout << "\n\n\n"; if (fromTower == toTower) { cout << "No point in moving a disk to the same tower!\n"; } else if (m_towers[fromTower].empty()) { cout << "Nothing on that tower to move!\n"; } else if (m_towers[toTower].empty()) { int fromDisk = m_towers[fromTower].top(); cout << "Moved " << fromDisk << " from tower " << fromTower << " to tower " << toTower << " which was empty\n"; m_towers[fromTower].pop(); m_towers[toTower].push(fromDisk); } else { int fromDisk = m_towers[fromTower].top(); int toDisk = m_towers[toTower].top(); if (toDisk < fromDisk) { cout << "Can't place a larger disk on a smaller disk!\n"; return; } else { cout << "Moved disk sized " << fromDisk << " from tower " << fromTower << " to tower " << toTower << " which had " << toDisk << " at the top." << endl; m_towers[fromTower].pop(); m_towers[toTower].push(fromDisk); } } printGameState(); } void TowersOfHanoi::printGameState() { // print out each of the towers for (int i = 0; i < 3; ++i) { cout << i << endl; stack<int> temp = m_towers[i]; while (!temp.empty()) { int disk_size = temp.top() + 1; temp.pop(); // print disk_size X's for (int j = 0; j < disk_size; ++j) { cout << 'X'; } cout << endl; } cout << endl; } checkWonState(); } void TowersOfHanoi::checkWonState() { // won state if (m_towers[0].empty() && m_towers[2].empty()) { stack<int> temp = m_towers[1]; bool won = true; while (temp.size() > 1) { int top = temp.top(); temp.pop(); int next = temp.top(); if (top > next) { won = false; } } if (won) { cout << "CONGRATULATIONS YOU WON!!!\n"; } } } int main() { TowersOfHanoi toh; toh.moveDisk(0, 1); toh.moveDisk(0, 2); toh.moveDisk(1, 2); toh.moveDisk(0, 1); toh.moveDisk(0, 2); toh.moveDisk(2, 0); toh.moveDisk(2, 1); toh.moveDisk(0, 1); return 0; } #include <stack> #include <queue> #include <string> #include <iostream> using namespace std; // // // STACK STUFF // // // correctParens - takes in a stack of chars that (from the bottom up) // is a string of parens, valid or not // this function should return true if it's a valid parenthesis string // and false if not bool correctParens(stack<char>& s) { stack<char> temp; while (!s.empty()) { if (s.top() == ')') { // put all preceding closed parens in stack while (s.top() == ')' && !s.empty()) { temp.push(s.top()); s.pop(); } // pop one off of temp for each subsequent open you get while (!s.empty() && s.top() == '(') { temp.pop(); s.pop(); } } // if you're ever looking at an open paren // without having seen an closed one, it's no good else { return false; } } return temp.empty(); } // binarytoDecimal // if you wanna read binary right to left, // push everything into a stack (right goes in last) and // pop out one at a time, adding in accordingly // BUT if you wanna read left to right ... you can use a // queue and read the front then pop // little endian: least significant value is stored first // so you read it left to right -- QUEUE // big endian: most significant value is stored first // so you read it right to left -- STACK int binaryToDecimal(string s) { // need to convert string to stack of 1's and 0's // push all of the bits into a stack so that you // can easily read them backwards and add in 2^pos // or not stack<int> binary; // change to queue if little endian for (int i = 0; i < s.size(); ++i) { binary.push(int(s[i]) - 48); } int pos = 0; int ret = 0; // run through the stack, adding in 2^pos if 1 or not while (!binary.empty()) { if (binary.top() == 1) { // change to front if little endian ret += pow(2, pos); } binary.pop(); ++pos; } return ret; } // // // QUEUE STUFF // // // this function takes in n, a number of people // and m, meaning each mth person will be killed // until there is just one person left void dontGetKilled(int m, int n) { queue<int> s; // push all of the people into a queue for (int i = 0; i < n; ++i) { s.push(i); } // you know all of the positions that are going to be killed // by printing and popping every m people until the queue is empty // the last person's position to be printed is not going to die while (!s.empty()) { // to avoid modulus, we can keep a countdown of people // to not kill and once that's 0, kill that person int betweeners = m - 1; while (betweeners != 0) { // every s.push(s.front()); s.pop(); --betweeners; } // kill the mth person - print them out and // take them out of the queue cout << s.front() << " " ; s.pop(); } cout << endl; }
[ "chengjieyun59@gmail.com" ]
chengjieyun59@gmail.com
b59006eb8c9e5ea3553ee4b89e25a133595d5f9e
6466da0d6adc644d11c39046583ef3ae0a8bffd1
/insert_element_inarry.cpp
436e3af38eb633102237a3788a66522e37bc5765
[]
no_license
Solayman-Emon/Hackerrank_Practise
319cdec530d5925741ff778b178ab2557fb13006
c25c412a749250f27f2366e96f3bd415b2ad1ae6
refs/heads/master
2020-05-17T00:58:57.584639
2019-04-25T10:37:58
2019-04-25T10:37:58
183,413,200
1
0
null
null
null
null
UTF-8
C++
false
false
562
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n,arr[100]; cout<<"How many number do you want to enter : "<<endl; cin>>n; for(int i=0; i<n; i++) { cin>>arr[i]; } int location,num; cout<<"In what location you want to entered the element : "<<endl; cin>>location; cout<<"Enter your number : "<<endl; cin>>num; for(int i=n-1; i>=location-1; i--) { arr[i+1]=arr[i]; } arr[location-1]=num; for(int i=0; i<=n; i++) { cout<<arr[i]<<"\t"; } return 0; }
[ "emonqt19@gmail.com" ]
emonqt19@gmail.com
158bd88e06fd85fe2d19f1e100a1c1311c73e663
46811b2012137ff6daaf22385d78c4aa0f6a5880
/SourceCode/ModelClass.h
bb95a0cf09fdd23f3d15cf01eae1a713e52250b7
[]
no_license
maggyo07/SelfMadeLibrary
e8ae444abcfa63dd80c7ab033ab359d8ac2b4cd0
d5ebe4b2bd48751f5a7782f3368b89194a4392dc
refs/heads/master
2020-06-09T12:01:15.025097
2019-06-24T05:31:36
2019-06-24T05:31:36
193,434,327
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,380
h
#pragma once //システム系のヘッダーインクルード #include <d3d11.h> #include <D3DX10math.h> #include <fstream> //Gameシステム用ヘッダー(自作)インクルード #include "TextureArrayClass.h" using namespace std; //3Dモデルのジオメトリをカプセル化 class ModelClass { private: //頂点情報(シェーダーのものと同じになければならない) struct VertexType { D3DXVECTOR3 position; D3DXVECTOR2 texture; D3DXVECTOR3 normal; D3DXVECTOR3 tangent; D3DXVECTOR3 binormal; }; struct ModelType { float x, y, z; //位置 float tu, tv; //テクスチャ座標 float nx, ny, nz; //法線 float tx, ty, tz; // float bx, by, bz; // }; //タンジェントとバイノーマルの計算に使う struct TempVertexType { float x, y, z; float tu, tv; float nx, ny, nz; }; public: ModelClass(); ModelClass(const ModelClass&); ~ModelClass(); //初期化関数 bool Initialize(WCHAR* modelFilename); //シャットダウン関数 void Shutdown(); //ファイル名からテクスチャを読み込む bool LoadTexture(WCHAR*); //描画関数 void Render(ID3D11DeviceContext*); //モデルの接線ベクトルと二値ベクトルを計算用 void CalculateModelVectors(); void CalculateTangentBinormal(TempVertexType, TempVertexType, TempVertexType,D3DXVECTOR3&,D3DXVECTOR3&); void CalculateNormal(D3DXVECTOR3, D3DXVECTOR3, D3DXVECTOR3&); int GetIndexCount(); ID3D11ShaderResourceView** GetTextureArray(); private: //初期化関数(モデルの読み込み、バッファを作成) bool InitalizeBuffers(const WCHAR* modelFilename); //シャットダウン関数(バッファ専用) void ShutdownBuffers(); //描画関数(GPUの入力アセンブラで頂点、インデックスバッファをアクティブに設定する) void RenderBuffers(ID3D11DeviceContext*); void ReleaseTexture(); //ファイルからモデル情報を読み込む bool LoadModel(const WCHAR* filename, VertexType*& vertexs, unsigned long*& indices); void ReleaseModel(); private: ID3D11Buffer* m_vertex_buffer; //頂点バッファ ID3D11Buffer* m_index_buffer; //インデックスバッファ int m_vertex_count; //頂点の数 int m_index_count; //インデックスの数 TextureArrayClass* m_texture_array; //テクスチャデータ ModelType* m_model; //モデル情報 };
[ "h1201619006@hiratagakuen.onmicrosoft.com" ]
h1201619006@hiratagakuen.onmicrosoft.com
8b8cd9d2dda01ce529cee7a048abccc877844530
3fc7cfc6a2e2cddcd685620b9ad5b6e8745b9a04
/include/libtorrent/aux_/torrent_list.hpp
dd003fd268f85f28191cf5827579fa03f4b766cb
[ "BSD-3-Clause", "BSL-1.0", "Zlib" ]
permissive
jriker1/libtorrent
e8663a19a0dd58fe50ee9651f272fb7f84b33c5a
a53e19d16b49d0d725f184dd8c332263feb9ea52
refs/heads/master
2020-07-02T14:18:58.912154
2019-08-06T23:19:52
2019-08-07T04:19:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,854
hpp
/* Copyright (c) 2019, Arvid Norberg All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef TORRENT_TORRENT_LIST_HPP_INCLUDED #define TORRENT_TORRENT_LIST_HPP_INCLUDED #include "libtorrent/config.hpp" #include "libtorrent/sha1_hash.hpp" #if !defined TORRENT_DISABLE_ENCRYPTION #include "libtorrent/hasher.hpp" #endif #include <memory> // for shared_ptr #include <vector> #include <unordered_map> namespace libtorrent { namespace aux { template <typename T> struct torrent_list { // These are non-owning pointers. Lifetime is managed by the `torrent_array` using torrent_map = std::unordered_map<sha1_hash, T*>; using torrent_array = std::vector<std::shared_ptr<T>>; using iterator = typename torrent_array::iterator; using const_iterator = typename torrent_array::const_iterator; using value_type = typename torrent_array::value_type; bool empty() const { return m_array.empty(); } iterator begin() { return m_array.begin(); } iterator end() { return m_array.end(); } const_iterator begin() const { return m_array.begin(); } const_iterator end() const { return m_array.end(); } std::size_t size() const { return m_array.size(); } T* operator[](std::size_t const idx) { TORRENT_ASSERT(idx < m_array.size()); return m_array[idx].get(); } T const* operator[](std::size_t const idx) const { TORRENT_ASSERT(idx < m_array.size()); return m_array[idx].get(); } bool insert(sha1_hash const& ih, std::shared_ptr<T> t) { TORRENT_ASSERT(t); bool const added = m_index.insert({ih, t.get()}).second; // if we already have a torrent with this hash, don't do anything if (!added) return false; #if !defined TORRENT_DISABLE_ENCRYPTION static char const req2[4] = {'r', 'e', 'q', '2'}; hasher h(req2); h.update(ih); // this is SHA1("req2" + info-hash), used for // encrypted hand shakes m_obfuscated_index.emplace(h.final(), t.get()); #endif m_array.emplace_back(std::move(t)); return true; } #if !defined TORRENT_DISABLE_ENCRYPTION T* find_obfuscated(sha1_hash const& ih) { auto const i = m_obfuscated_index.find(ih); if (i == m_obfuscated_index.end()) return nullptr; return i->second; } #endif T* find(sha1_hash const& ih) const { auto const i = m_index.find(ih); if (i == m_index.end()) return nullptr; return i->second; } bool erase(sha1_hash const& ih) { auto const i = m_index.find(ih); if (i == m_index.end()) return false; auto const array_iter = std::find_if(m_array.begin(), m_array.end() , [&](std::shared_ptr<T> const& p) { return p.get() == i->second; }); TORRENT_ASSERT(array_iter != m_array.end()); m_index.erase(i); #if !defined TORRENT_DISABLE_ENCRYPTION static char const req2[4] = {'r', 'e', 'q', '2'}; hasher h(req2); h.update(ih); m_obfuscated_index.erase(h.final()); #endif TORRENT_ASSERT(m_index.find(ih) == m_index.end()); if (array_iter != m_array.end() - 1) std::swap(*array_iter, m_array.back()); // This is where we, potentially, remove the last reference m_array.pop_back(); return true; } void clear() { m_array.clear(); m_index.clear(); #if !defined TORRENT_DISABLE_ENCRYPTION m_obfuscated_index.clear(); #endif } private: torrent_array m_array; torrent_map m_index; #if !defined TORRENT_DISABLE_ENCRYPTION // this maps obfuscated hashes to torrents. It's only // used when encryption is enabled torrent_map m_obfuscated_index; #endif }; } } #endif
[ "arvid.norberg@gmail.com" ]
arvid.norberg@gmail.com
2d960eacc4404f926f7bb7c4cd7bcd4354c9ec6f
b97faacb3d682883ef5b35c2a872a204e9604129
/serverGUI/ClientManager/sotadb.cpp
4a87fef9db44011f2e47b0a1fc61d324b41817d4
[]
no_license
garrettharvey/sota-server
7a0f1f5ee824bd3ab602064143dfa3025b954bdb
500452ec1ec49e3df4bfa7b62deeec4dd33350e8
refs/heads/master
2022-07-01T17:18:15.609883
2020-05-05T07:10:27
2020-05-05T07:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,386
cpp
#include <QString> #include <string> #include <stdlib.h> #include <time.h> #include <QQuickView> #include <QQmlContext> #include "sotadb.h" QSqlDatabase db; const QString DRIVER("QSQLITE"); const QString dbName("/home/" + qgetenv("USER") + "/sota-server/db/sotaserver.db"); QVariantList clientList; int numclients = 0; SOTAdb::SOTAdb(QObject *parent) : QObject(parent) { numclients = 0; qDebug() << "creating db object"; if(QSqlDatabase::isDriverAvailable(DRIVER)){ //check for database driver db = QSqlDatabase::addDatabase(DRIVER); db.setDatabaseName(dbName); if(!db.open()){ //db didn't open qWarning() << "ERROR: " << db.lastError(); //emit openFailed(); }else{//opened db open = true; qDebug() << "opened/created database"; //need set initialized after checking if tabels exist if(!initialized){ //db tables haven't been created initDB(); //will either create tables, or they already exist //successfully created tables initialized = true; queryAllClients(); }else{ //db tables exist queryAllClients(); }//end check initialized }//end try open }else{ //driver not available qWarning() << "QSQLITE database driver unavailable"; }//end check driver } int SOTAdb::initDB() { if(!open || initialized){//db didn't open on object creation OR tables already created qWarning() << "ERROR: " << db.lastError(); return 0; } QSqlQuery sqlClientsTable("CREATE TABLE CLIENTS (" \ "unique_id CHAR(16) NOT NULL PRIMARY KEY," \ "init_id CHAR(22)," \ "software_id CHAR(16)," \ "last_seen INTEGER," \ "last_ip TEXT," \ "status TEXT," \ "group_id CHAR(16)," \ "last_sw_id CHAR(16)," \ "active TEXT," \ "FOREIGN KEY(software_id) REFERENCES SOFTWARE(id)" \ ");"); QSqlQuery sqlSoftwareTable("CREATE TABLE SOFTWARE (" \ "id CHAR(16) NOT NULL PRIMARY KEY," \ "name TEXT," \ "version TEXT," \ "num_users INTEGER," \ "size INTEGER," \ "location TEXT" \ ");"); if(!sqlClientsTable.isActive()){ //something went wrong creating Clients table qWarning() << "ERROR: " << sqlClientsTable.lastError().text(); return 0; } if(!sqlSoftwareTable.isActive()){ //something went wrong creating Software table qWarning() << "ERROR: " << sqlSoftwareTable.lastError().text(); return 0; } return 1; //success }// end initDB void SOTAdb::createClient(QString rand) { // init-12345-abcde-123ab QString initID(rand.left(15)); initID.prepend("init-"); initID.insert(16, "-"); initID.insert(10, "-"); QString uniqueID(rand.right(16)); if(!db.open()){ // can't open db qWarning() << "ERROR: " << db.lastError(); return; } QSqlQuery query; query.prepare("INSERT INTO CLIENTS (unique_id, init_id) " "VALUES (:unique_id, :init_id)"); query.bindValue(":unique_id", uniqueID); query.bindValue(":init_id", initID); query.exec(); if(!query.isActive()){ qWarning() << "ERROR: " << query.lastError().text(); return; }else{ //insert successful // emit newdata(); ClientModel tempclient; tempclient.setUnique_id(uniqueID); tempclient.setInit_id(initID); tempclient.setSoftware_id(""); tempclient.setLast_seen(""); tempclient.setLast_ip(""); tempclient.setStatus(""); tempclient.setGroup_id(""); tempclient.setLast_sw_id(""); tempclient.setActive(""); cList.append(tempclient); } } int SOTAdb::queryAllClients() // get all info for many clients { qDebug() << "starting loadAllClients()"; if (!open){ //db isn't open, try to open if(!db.open()){ // can't open db qWarning() << "ERROR opening db in SOTAdb::loadAllClients: " << db.lastError(); return 0; } } QSqlQuery query; query.prepare("SELECT * FROM CLIENTS"); if(!query.exec()){ //error executing query qWarning() << "ERROR executing query in SOTAdb::loadAllClients: " << query.lastError().text(); return 0; } qDebug() << "successfully ran select * from clients"; while (query.next()){ //create new ClientEntity type and set values // ClientEntity dbclient = // { // query.value(0).toString(), // query.value(1).toString(), // query.value(2).toString(), // query.value(3).toString(), // query.value(4).toString(), // query.value(5).toString(), // query.value(6).toString(), // query.value(7).toString(), // query.value(8).toString() // }; QString uniqueid = query.value(0).toString(); QString initid = query.value(1).toString(); QString softwareid = query.value(2).toString(); QString lastseen = query.value(3).toString(); QString lastip = query.value(4).toString(); QString status = query.value(5).toString(); QString groupid = query.value(6).toString(); QString lastswid = query.value(7).toString(); QString active = query.value(8).toString(); ClientModel tempclient; tempclient.setUnique_id(uniqueid); tempclient.setInit_id(initid); tempclient.setSoftware_id(softwareid); tempclient.setLast_seen(lastseen); tempclient.setLast_ip(lastip); tempclient.setStatus(status); tempclient.setGroup_id(groupid); tempclient.setLast_sw_id(lastswid); tempclient.setActive(active); cList.append(tempclient); // dbclient << query.value(0).toString(); // dbclient << query.value(1).toString(); // dbclient << query.value(2).toString(); // dbclient << query.value(3).toString(); // dbclient << query.value(4).toString(); // dbclient << query.value(5).toString(); // dbclient << query.value(6).toString(); // dbclient << query.value(7).toString(); // dbclient << query.value(8).toString(); //conver client to QVariant //QVariant qclient; //qclient.setValue(dbclient); //qclient.setValue(tempclient); //clientList.append(qclient); qDebug() << "loaded client uniqueid: " + query.value(0).toString(); } numclients = cList.size(); qDebug() << "loaded All clients"; qDebug() << "Num clients: " << numclients; return 1; }//end constructor /* int SOTAdb::getnumclients() //might only return number of columns - fix { if(!db.open()){ // can't open db qWarning() << "ERROR: " << db.lastError(); } QSqlQuery query; query.prepare("SELECT * FROM CLIENTS"); if(!query.exec()){ qWarning() << "ERROR: " << query.lastError().text(); return 0; } int numclients = query.size(); return numclients; } */ //QString SOTAdb::updateClient() //{ // return QString("not done"); //} //QString SOTAdb::deleteClient() //{ // return QString("not done"); //} //QString SOTAdb::numActive() //{ //} //QString SOTAdb::numInactive() //{ //}
[ "glharvey@go.olemiss.edu" ]
glharvey@go.olemiss.edu
558ebc504ddf4a8251f30ef9d8a1ef4c08727c92
237313342e4ab6d924855072dbe506ecdac0ef37
/Cipher.cpp
d8960050a876c6f007b3df2dc64ff8592f0e955a
[ "OpenSSL", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "BSD-3-Clause" ]
permissive
tresorit/ZeroKit-Client-Native-Crypto
b1473383340ff10164289e77d128190e8058aaf3
02af3e54dcd557dc8f93913cd2137382992e7db2
refs/heads/master
2021-01-20T14:39:29.123247
2018-06-19T07:34:03
2018-06-19T07:34:03
90,640,581
2
1
null
null
null
null
UTF-8
C++
false
false
5,629
cpp
/** * Copyright (c) 2017, Tresorit Kft. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Cipher.hpp" #include <limits> #include <openssl/evp.h> #include "OpenSSLException.hpp" const EVP_CIPHER* getCipher(CipherType cipherType) { switch (cipherType) { case CipherType::AES128GCM: return EVP_aes_128_gcm(); case CipherType::AES256GCM: return EVP_aes_256_gcm(); default: throw OpenSSLException(); } } CipherCtx::CipherCtx() : ctx(nullptr) { OPENSSL_THROW_IF_NULL(this->ctx = EVP_CIPHER_CTX_new()); } CipherCtx::CipherCtx(CipherCtx&& other) : ctx(other.ctx) { other.ctx = nullptr; } CipherCtx& CipherCtx::operator=(CipherCtx&& other) { if (this != &other) { if (this->ctx != nullptr) { EVP_CIPHER_CTX_free(this->ctx); } this->ctx = other.ctx; other.ctx = nullptr; } return *this; } CipherCtx::~CipherCtx() { if (this->ctx != nullptr) { EVP_CIPHER_CTX_free(this->ctx); } } EVP_CIPHER_CTX* CipherCtx::get() { return this->ctx; } void CipherCtx::setType(const EVP_CIPHER* cipher, CipherOperation operation) { OPENSSL_THROW_IF_ERROR(EVP_CipherInit_ex( this->get(), cipher, nullptr, nullptr, nullptr, static_cast<int>(operation))); } void CipherCtx::setPadding(bool enable) { OPENSSL_THROW_IF_ERROR(EVP_CIPHER_CTX_set_padding(this->get(), enable)); } void CipherCtx::setKey(const uint8_t* key, size_t len) { OPENSSL_THROW_IF(len > std::numeric_limits<int>::max()) int keyLen = EVP_CIPHER_CTX_key_length(this->get()); OPENSSL_THROW_IF(keyLen < 0); OPENSSL_THROW_IF(len != static_cast<size_t>(keyLen)); OPENSSL_THROW_IF_ERROR(EVP_CipherInit_ex(this->get(), nullptr, nullptr, key, nullptr, -1)); } void CipherCtx::setIV(const uint8_t* iv, size_t len) { if (EVP_CIPHER_CTX_cipher(this->get()) == getCipher(CipherType::AES128GCM) || EVP_CIPHER_CTX_cipher(this->get()) == getCipher(CipherType::AES256GCM)) { OPENSSL_THROW_IF(len > std::numeric_limits<int>::max()) OPENSSL_THROW_IF_ERROR(EVP_CIPHER_CTX_ctrl( this->get(), EVP_CTRL_AEAD_SET_IVLEN, static_cast<int>(len), nullptr)); } OPENSSL_THROW_IF_ERROR(EVP_CipherInit_ex(this->get(), nullptr, nullptr, nullptr, iv, -1)); } void CipherCtx::updateAAD(const uint8_t* aad, size_t len) { OPENSSL_THROW_IF(len > std::numeric_limits<int>::max()) if (aad == nullptr || len == 0) { return; } int outl = 0; OPENSSL_THROW_IF_ERROR( EVP_CipherUpdate(this->get(), nullptr, &outl, aad, static_cast<int>(len))); } SecureVector CipherCtx::update(const uint8_t* data, size_t len) { OPENSSL_THROW_IF(len > std::numeric_limits<int>::max()) if (data == nullptr || len == 0) { return SecureVector(); } int blockSize = EVP_CIPHER_CTX_block_size(this->get()); OPENSSL_THROW_IF(blockSize < 1); SecureVector res(len + static_cast<size_t>(blockSize) - 1); int outl = 0; OPENSSL_THROW_IF_ERROR( EVP_CipherUpdate(this->get(), res.data(), &outl, data, static_cast<int>(len))); OPENSSL_THROW_IF(outl < 0); res.resize(static_cast<size_t>(outl)); return res; } SecureVector CipherCtx::finalize() { int blockSize = EVP_CIPHER_CTX_block_size(this->get()); OPENSSL_THROW_IF(blockSize < 1); SecureVector res(static_cast<size_t>(blockSize)); int outl = 0; OPENSSL_THROW_IF_ERROR(EVP_CipherFinal_ex(this->get(), res.data(), &outl)); OPENSSL_THROW_IF(outl < 0); res.resize(static_cast<size_t>(outl)); return res; } SecureVector CipherCtx::getTag(size_t len) { OPENSSL_THROW_IF(len > std::numeric_limits<int>::max()) SecureVector tag(len); OPENSSL_THROW_IF_ERROR( EVP_CIPHER_CTX_ctrl(this->get(), EVP_CTRL_AEAD_GET_TAG, static_cast<int>(len), tag.data())); return tag; } void CipherCtx::setTag(const uint8_t* tag, size_t len) { OPENSSL_THROW_IF(len > std::numeric_limits<int>::max()) OPENSSL_THROW_IF_ERROR(EVP_CIPHER_CTX_ctrl(this->get(), EVP_CTRL_AEAD_SET_TAG, static_cast<int>(len), static_cast<void*>(const_cast<uint8_t*>(tag)))); }
[ "daniel.bakai@tresorit.com" ]
daniel.bakai@tresorit.com
243937977692893fc4f713d14d750fca71e41bce
9d94929753208f65f3789b9ae454a225c344d9c0
/SuperTagEditor/SuperTagEditorDoc.cpp
211ae120762cdf9ff228b21d446cd389fbd27ebc
[]
no_license
de-ataka/mm_STEP_M
7c68cc4033428a67b19e8308cd01b4bfe285bdae
d85179c370dc56aa709cc3494a8e89e8e7b44f5d
refs/heads/master
2021-09-14T09:41:55.798522
2011-07-19T13:29:56
2011-07-19T13:29:56
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
30,013
cpp
// SuperTagEditorDoc.cpp : CSuperTagEditorDoc クラスの動作の定義を行います。 // #include "stdafx.h" #include "Shlwapi.h" #include "FileMP3.h" #include "SuperTagEditor.h" #include "DlgCommonProg.h" #include "DlgEnvSheet.h" #include "SHBrowseForFolder.h" #include "SuperTagEditorView.h" #include "SuperTagEditorDoc.h" #include "DlgPluginSetup.h" #include "INI/Profile.h" //#include "NewAPIs.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////////////// //GetLongPathName //短いファイル名を長いファイル名に変換 ////////////////////////////////////////////////////////////////////////////// /* 引数: LPSTR lpszLongFileName 長いファイル名を受け取るバッファへのポインタ LPSTR lpszShortPathName 短いファイル名を含むパス名へのポインタ DWORD dwSize バッファサイズ 戻り値: DWORD バッファにコピーした文字列の長さ 0のとき異常終了 */ DWORD GetLongPathName(LPSTR lpszLongFileName, LPSTR lpszShortPathName, DWORD dwSize) { WIN32_FIND_DATA fd; HANDLE hFind; //短いファイル名でファイルを検索 if((hFind = FindFirstFile(lpszShortPathName,&fd)) != INVALID_HANDLE_VALUE) { FindClose(hFind); if((DWORD)lstrlen(fd.cFileName) <= dwSize) { //長いファイル名をバッファにコピー lstrcpy(lpszLongFileName,fd.cFileName); //バッファにコピーした文字列を返す return lstrlen(lpszLongFileName); } } lstrcpy(lpszLongFileName, ""); //バッファのサイズを超えたかファイルが見つからなかったときは異常終了 return 0; } ///////////////////////////////////////////////////////////////////////////// // CSuperTagEditorDoc IMPLEMENT_DYNCREATE(CSuperTagEditorDoc, CDocument) BEGIN_MESSAGE_MAP(CSuperTagEditorDoc, CDocument) //{{AFX_MSG_MAP(CSuperTagEditorDoc) ON_UPDATE_COMMAND_UI(ID_OPEN_FOLDER, OnUpdateOpenFolder) ON_COMMAND(ID_OPEN_FOLDER, OnOpenFolder) ON_UPDATE_COMMAND_UI(ID_SAVE_ALL_TAG, OnUpdateSaveAllTag) ON_COMMAND(ID_SAVE_ALL_TAG, OnSaveAllTag) ON_UPDATE_COMMAND_UI(ID_FILE_OPEN, OnUpdateFileOpen) ON_UPDATE_COMMAND_UI(ID_EDIT_FIELD_SI, OnUpdateEditFieldSi) ON_COMMAND(ID_EDIT_FIELD_SI, OnEditFieldSi) ON_UPDATE_COMMAND_UI(ID_EDIT_TD3_TAG, OnUpdateEditTd3Tag) ON_COMMAND(ID_EDIT_TD3_TAG, OnEditTd3Tag) ON_UPDATE_COMMAND_UI(ID_EDIT_CHANGE_FIELD, OnUpdateEditChangeField) ON_COMMAND(ID_EDIT_CHANGE_FIELD, OnEditChangeField) ON_UPDATE_COMMAND_UI(ID_EXEC_CLASSIFICATION, OnUpdateExecClassification) ON_COMMAND(ID_EXEC_CLASSIFICATION, OnExecClassification) ON_COMMAND(ID_DLG_SETUP_PLUGIN, OnDlgSetupPlugin) ON_UPDATE_COMMAND_UI(ID_DLG_SETUP_PLUGIN, OnUpdateDlgSetupPlugin) ON_COMMAND(ID_DLG_ENVIRONMENT, OnDlgEnvironment) ON_UPDATE_COMMAND_UI(ID_DLG_ENVIRONMENT, OnUpdateDlgEnvironment) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CSuperTagEditorDoc クラスの構築/消滅 CSuperTagEditorDoc::CSuperTagEditorDoc() { // TODO: この位置に1度だけ呼ばれる構築用のコードを追加してください。 m_dlgLoadProgress = new CDlgCommonProgress; m_nArrayFileCount = 0; m_nArrayRequestFileCount = 0; m_StartLoadFileCount = 0;//追加 by Kobarin m_TagUpdatingCount = 0;//追加 by Kobarin m_bInitialized = false; /* StartInaction2 055 */ } CSuperTagEditorDoc::~CSuperTagEditorDoc() { delete m_dlgLoadProgress; m_dlgLoadProgress = NULL; } BOOL CSuperTagEditorDoc::OnNewDocument() { // 保存確認 if (m_nArrayFileCount && CanCloseFrame((CFrameWnd *)AfxGetMainWnd()) == FALSE) { return FALSE; } if (!CDocument::OnNewDocument()) return FALSE; // TODO: この位置に再初期化処理を追加してください。 // (SDI ドキュメントはこのドキュメントを再利用します。) InitFileList(); // ファイルリストの初期化 ClearRequestFiles(); // 追加リクエストファイルリストの初期化 if (!m_bInitialized) { InitPlugin(); // プラグインのロード // 初期化処理 GetView()->m_List.InitializeGrid(); // フォントの設定 GetView()->UpdateFontListView(); } InitGridList(); // グリッドを初期化 m_bInitialized = true; return TRUE; } ///////////////////////////////////////////////////////////////////////////// // CSuperTagEditorDoc シリアライゼーション void CSuperTagEditorDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { } else { } } ///////////////////////////////////////////////////////////////////////////// // CSuperTagEditorDoc クラスの診断 #ifdef _DEBUG void CSuperTagEditorDoc::AssertValid() const { CDocument::AssertValid(); } void CSuperTagEditorDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CSuperTagEditorDoc コマンド //**************************************************************************** // ファイル検索処理関連 //**************************************************************************** // ============================================= // CSuperTagEditorDoc::GetFileTime // 概要 : ファイルのタイムスタンプを取得 // 引数 : sFileName = ファイル名 // 戻り値: CTime = タイムスタンプ(CTime(0):エラー) // ============================================= CTime CSuperTagEditorDoc::GetFileTime(const char *sFileName) { CFileStatus status; if (sFileName == NULL || CFile::GetStatus(sFileName, status) == FALSE) { return(CTime(0)); } if (status.m_mtime == -1) return(CTime(0)); if (status.m_mtime.GetTime() == -1) return(CTime(0)); return(status.m_mtime); } // ============================================= // CSuperTagEditorDoc::AddRequestFile // 概要 : ファイル追加リクエストリストにファイルを追加する // 引数 : sFillPath = フルパス名 // : pParent = 親アイテム(NULLも可) // 戻り値: int = インデックス(追加しなかった場合は-1を返す) // ============================================= int CSuperTagEditorDoc::AddRequestFile(const char *sFillPath, CSuperGridCtrl::CTreeItem *pParent) { //追加 by Kobarin if(IsTagUpdating())//タグを更新中は追加しない return -1; if(m_dlgLoadProgress->IsCanceled()){ //キャンセルボタンが押されている return -1; } FILE_STATE stat; stat.strFullPathName = sFillPath; stat.pParent = pParent; // 配列に追加 if (m_nArrayRequestFileCount > m_arrayRequestFiles.GetUpperBound()) { // 配列が足りない場合は、確保サイズを増加させる m_arrayRequestFiles.SetSize(m_arrayRequestFiles.GetUpperBound() + ADD_ARRAY_SIZE); } m_arrayRequestFiles[m_nArrayRequestFileCount] = stat; m_nArrayRequestFileCount++; return(m_nArrayRequestFileCount); } void CSuperTagEditorDoc::StartLoadFile(const char *sTitle) { if (m_dlgLoadProgress->GetSafeHwnd() == NULL) { // プログレスバーを生成 // m_dlgLoadProgress = new CDlgCommonProgress; m_dlgLoadProgress->Create(AfxGetMainWnd()); m_dlgLoadProgress->SetWindowText(sTitle); UpdateAllViews(NULL); } m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "ファイル検索中..."); m_StartLoadFileCount++;//追加 by Kobarin } void CSuperTagEditorDoc::EndLoadFile(void) { if(--m_StartLoadFileCount != 0)return;//追加 by Kobarin if (m_dlgLoadProgress->GetSafeHwnd() != NULL) { m_dlgLoadProgress->DestroyWindow(); m_dlgLoadProgress->SetCanceled(FALSE);//追加 by Kobarin // delete m_dlgLoadProgress; // m_dlgLoadProgress = NULL; } } // ============================================= // CSuperTagEditorDoc::ExecRequestFiles // 概要 : 追加リクエストリストのファイルを処理する // 引数 : bListClear = 追加処理終了後に追加リクエストのリストをクリアするか? // : bCheck = チェックマークを付けるかどうか // 戻り値: none // ============================================= void CSuperTagEditorDoc::ExecRequestFiles(bool bListClear, bool bCheck) { m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "タグ情報の読み込み中..."); // CMySuperGrid &listCtrl = GetListCtrl(); // listCtrl.SetRedraw(FALSE); //int nFileCount = m_nArrayFileCount; /* STEP 015 */ for (int no = 0; no < m_nArrayRequestFileCount; no++) { int nFileCount = m_nArrayFileCount; /* STEP 015 */ // プログレスバー更新 if (m_nArrayRequestFileCount > 1) { m_dlgLoadProgress->SetPos(no * 100 / (m_nArrayRequestFileCount-1)); } // 追加 by Kobarin if(m_dlgLoadProgress->IsCanceled()){ //キャンセルボタンが押されていた break; } // 多重登録チェック if (nFileCount > 0) { bool bFound = false; CString *strFileName = &m_arrayRequestFiles[no].strFullPathName; int i; for (i = 0; i < nFileCount; i++) { if (GetListMP3(i)->strFullPathName == *strFileName) { bFound = true; break; } } if (bFound == false) { // MP3ファイル情報の取得 FoundFile(*strFileName, m_arrayRequestFiles[no].pParent, bCheck); } } else { // MP3ファイル情報の取得 FoundFile(m_arrayRequestFiles[no].strFullPathName, m_arrayRequestFiles[no].pParent, bCheck); } } // listCtrl.SetRedraw(TRUE); if (bListClear) { ClearRequestFiles(); } if (g_bOptShowTotalParent) { CMySuperGrid &listCtrl = GetListCtrl(); listCtrl.CalcSum(0); } // カラム幅の自動調整 if (g_bOptLoadFileAdjustColumn) { CMySuperGrid &listCtrl = GetListCtrl(); listCtrl.AutoSizeColumns(-1); } } // ============================================= // CSuperTagEditorDoc::ClearRequestFiles // 概要 : 追加リクエストファイルリストの初期化 // 引数 : none // 戻り値: none // ============================================= void CSuperTagEditorDoc::ClearRequestFiles(void) { m_arrayRequestFiles.RemoveAll(); m_arrayRequestFiles.SetSize(INIT_ARRAY_SIZE); m_nArrayRequestFileCount = 0; } // ============================================= // CSuperTagEditorDoc::LoadPlayList // 概要 : プレイリストを読みこみます // 引数 : sPlayList = プレイリストファイル名(絶対パスで指定) // 戻り値: bool = true:正常終了 / false:エラー // ============================================= bool CSuperTagEditorDoc::LoadPlayList(const char *sPlayList) { TRY { CFile file; // プレイリストファイルのカレントディレクトリを取得 TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR]; _tsplitpath(sPlayList, drive, dir, NULL, NULL); if (file.Open(sPlayList, CFile::modeRead)) { CString strLine; CArchive ar(&file, CArchive::load); while(ar.ReadString(strLine)) { if (strLine.GetLength() >= 3) { if (strLine[0] != '#') { // リストに追加 if ((strLine[0] == '\\' && strLine[1] == '\\') || strLine[1] == ':') { // 絶対パス AddRequestFile(strLine, NULL); } else { // 相対パス CString strName; if (strLine[0] == '\\') { // ドライブ名無しのルート指定 strName.Format("%s%s", drive, strLine); } else { // ルート以外 strName.Format("%s%s%s", drive, dir, strLine); } AddRequestFile(strName, NULL); } } } } } } CATCH( CFileException, e) { CString str; str.Format("%s の読み込みに失敗しました", sPlayList); MessageBox(NULL, str, "ファイルエラー", MB_ICONSTOP|MB_OK|MB_TOPMOST); } END_CATCH return(true); } // ============================================= // CSuperTagEditorDoc::FoundFile // 概要 : ファイル検索:ファイルを発見 // 引数 : sFileName = ファイル名 // : pItemParent = 親アイテム(NULL=ルート) // : bCheck = チェックマークを付けるかどうか // 戻り値: bool = true:正常終了 / false:異常終了 // ============================================= bool CSuperTagEditorDoc::FoundFile(const char *sFileName, CSuperGridCtrl::CTreeItem *pItemParent, bool bCheck) { // MP3ファイル情報の取得 CFileMP3 fileMP3; if (fileMP3.Attach(sFileName)) { int nIndex = m_nArrayFileCount; // 配列に追加 if (m_nArrayFileCount > m_arrayFiles.GetUpperBound()) { // 配列が足りない場合は、確保サイズを増加させる m_arrayFiles.SetSize(m_arrayFiles.GetUpperBound() + ADD_ARRAY_SIZE); } m_arrayFiles[m_nArrayFileCount] = fileMP3.m_fileMP3; m_nArrayFileCount++; // リストコントロールを取得 CMySuperGrid &listCtrl = GetListCtrl(); if (g_classInfo.nType == 0) { // フォルダで分類 listCtrl.AddFile(GetListMP3(nIndex), pItemParent, (LPARAM)nIndex, bCheck); } else { // タグ情報で分類 listCtrl.AddFile2(GetListMP3(nIndex), pItemParent, (LPARAM)nIndex, bCheck); } return(true); } else { CString strMessage; strMessage.Format("%s の読み込みに失敗しました", sFileName); //MessageBox(NULL, strMessage, "ファイル読み込みエラー", MB_ICONSTOP|MB_OK|MB_TOPMOST); ((CMainFrame *)AfxGetMainWnd())->SetStatusBarText(strMessage); // ステータスバーにエラーを表示 } return(false); } // ============================================= // CSuperTagEditorDoc::SearchFileReent // 概要 : ファイル検索:検索処理 // 引数 : sDir = 検索するディレクトリ // : pItemDir = ディレクトリアイテム(NULL=ルート) // 戻り値: bool = true:正常終了 / false:異常終了 // ============================================= bool CSuperTagEditorDoc::SearchFileReent(const char *sDir, CSuperGridCtrl::CTreeItem *pItemDir) { //追加 by Kobarin if(m_dlgLoadProgress->IsCanceled()){ return true; } HANDLE hFindFile; WIN32_FIND_DATA data; char *sCurFile = new char [MAX_PATH + 1]; if (sCurFile == NULL) return(false); // 割り当て失敗 // 検索開始ディレクトリの場合の処理 if (pItemDir == NULL) { // ルートにディレクトリアイテム追加 if (g_classInfo.nType == 0) { // フォルダで分類 CMySuperGrid &listCtrl = GetListCtrl(); // pItemDir = listCtrl.AddDirectory(sDir, listCtrl.m_itemClassOK, 0); pItemDir = listCtrl.m_pItemRoot; } } // 同一ディレクトリの全てのファイルを検索 // サブディレクトリの検索は行わない //static char *sFindPattern[] = { // "*.rmp", "*.mp3", "*.ape", "*.wma", "*.wmv", "*.asf", "*.ogg"/* Conspiracy 196 */, "*.wav"/* Conspiracy 197 */, "*.avi"/* Conspiracy 197 */, NULL, //}; extern void GetFileExtList(CStringArray& arExt); CStringArray arExt; GetFileExtList(arExt); for (int nType = 0; nType < arExt.GetSize() ; nType++) { // 検索ファイルのパターンを設定 sprintf(sCurFile, "%s%s", sDir, "*." + arExt[nType]); // ファイル検索 if ((hFindFile = FindFirstFile(sCurFile, &data)) != INVALID_HANDLE_VALUE) { do { m_dlgLoadProgress->SetPos(0);//追加 by Kobarin if(m_dlgLoadProgress->IsCanceled()){ break; } if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { // ディレクトリ付きファイル名作成 strcpy(sCurFile, sDir); strcat(sCurFile, data.cFileName); m_sTargetFile = sCurFile; // ファイル発見処理 AddRequestFile(m_sTargetFile, pItemDir); } } while(FindNextFile(hFindFile, &data) == TRUE); } if (hFindFile != INVALID_HANDLE_VALUE) FindClose(hFindFile); } if (g_bEnableSearchSubDir) { // サブディレクトリの検索 sprintf(sCurFile, "%s*.*", sDir); if ((hFindFile = FindFirstFile(sCurFile, &data)) != INVALID_HANDLE_VALUE) { do { m_dlgLoadProgress->SetPos(0);//追加 by Kobarin if(m_dlgLoadProgress->IsCanceled()){ break; } if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { if (strcmp(data.cFileName, "." ) != 0 // カレントディレクトリ以外 && strcmp(data.cFileName, "..") != 0 // 親ディレクトリ以外 && (data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) == 0/* STEP 032 */) { // 隠しフォルダ以外 // ディレクトリ付きファイル名作成 strcpy(sCurFile, sDir); strcat(sCurFile, data.cFileName); m_sTargetFile = sCurFile; // ツリーにディレクトリアイテム追加 CSuperGridCtrl::CTreeItem *pItemSubDir = NULL; if (g_classInfo.nType == 0) { // フォルダで分類 CMySuperGrid &listCtrl = GetListCtrl(); pItemSubDir = listCtrl.AddDirectory(data.cFileName, pItemDir); } // サブディレクトリ突入処理 strcat(sCurFile, "\\"); if (!SearchFileReent(sCurFile, pItemSubDir)) { break; // サブディレクトリ検索エラー } sCurFile[strlen(sCurFile)-1] = NULL; m_sTargetFile = sCurFile; // サブディレクトリの処理が入るので再設定 } } } while(FindNextFile(hFindFile, &data) == TRUE); } if (hFindFile != INVALID_HANDLE_VALUE) FindClose(hFindFile); /* 2004.02.18 こっちに移動 */ } delete[] sCurFile; return(true); } // ============================================= // CSenkyokuMeijinDoc::SelectDirectory // 概要 : フォルダ参照ダイアログ処理 // 引数 : sLocal = パス(入出力) // 戻り値: bool // ============================================= BOOL CSuperTagEditorDoc::SelectDirectory(char *sLocal) { bool bResult; CSHBrowseForFolder browse(true, g_bEnableSearchSubDir); bResult = browse.Exec(sLocal); g_bEnableSearchSubDir = browse.GetSearchSubDirState(); return(bResult); } void CSuperTagEditorDoc::OpenFolder(const char *sOpenDir) { //追加 by Kobarin if(IsTagUpdating())//タグを更新中は追加しない return; if(m_dlgLoadProgress->IsCanceled()){ //キャンセルボタンが押されている return ; } ((CSuperTagEditorApp *)AfxGetApp())->AddToRecentFileList (sOpenDir); /* StartInaction 053 */ // ディレクトリのファイルを読み込む char sFolderName[_MAX_PATH] = {'\0'}; strcpy(sFolderName, sOpenDir); int nLen; nLen = strlen(sFolderName); if (nLen > 0) { if (IsFolderName(sFolderName) == false) { // 最後は '\\' である事 strcat(sFolderName, "\\"); } // プログレスバー初期化 BOOL bIsOpen = (m_dlgLoadProgress->GetSafeHwnd() == NULL) ? TRUE : FALSE; if (bIsOpen) StartLoadFile("MP3ファイル読み込み中..."); // フォルダ読み込み if (g_classInfo.nType == 0) { // フォルダで分類 CMySuperGrid &listCtrl = GetListCtrl(); TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR]; _tsplitpath(sFolderName, drive, dir, NULL, NULL); CString str; str.Format("%s%s", drive, dir); SearchFileReent(sFolderName, listCtrl.AddDirectory(str, listCtrl.m_pItemRoot, 2)); } else { // タグ情報で分類 SearchFileReent(sFolderName); } // 追加リクエストのあったファイルのタグ情報を読み込む #ifdef FLICKERFREE //CMySuperGrid &listCtrl = GetListCtrl(); //listCtrl.SetRedraw(FALSE); //GetView()->SetRedraw(FALSE); #endif ExecRequestFiles(true, g_bOptLoadFileChecked); #ifdef FLICKERFREE //listCtrl.SetRedraw(TRUE); //GetView()->SetRedraw(TRUE); #endif // プログレスバー終了 if (bIsOpen) EndLoadFile(); UpdateAllViews(NULL); } } void CSuperTagEditorDoc::OnUpdateOpenFolder(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } void CSuperTagEditorDoc::OnOpenFolder() { char sFolderName[_MAX_PATH] = {'\0'}; // フォルダ選択ダイアログを開く strcpy(sFolderName, g_strCurrentDirectory); if (SelectDirectory(sFolderName) == TRUE) { g_strCurrentDirectory = sFolderName; OpenFolder(g_strCurrentDirectory); } } BOOL CSuperTagEditorDoc::CanCloseFrame(CFrameWnd* pFrame) { if (CheckFileModified()) { int nResult; nResult = MessageBox(AfxGetMainWnd()->GetSafeHwnd(), "タグ情報が変更されています。\n" "変更されているファイルを更新してもよろしいですか?", "保存確認", MB_YESNOCANCEL); switch(nResult) { case IDYES: //OnSaveAllTag(); SaveAllTag(TRUE); if (m_bSaveAllTagResult == false) { return(FALSE); } break; case IDNO: break; case IDCANCEL: return(FALSE); } } InitFileList(); /* Conspiracy 196 */ return CDocument::CanCloseFrame(pFrame); } void CSuperTagEditorDoc::OnUpdateSaveAllTag(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } void CSuperTagEditorDoc::OnSaveAllTag() { SaveAllTag(FALSE); } void CSuperTagEditorDoc::OnUpdateFileOpen(CCmdUI* pCmdUI) { pCmdUI->Enable(FALSE); } // [オプション設定]-[全部] void CSuperTagEditorDoc::OnUpdateDlgEnvironment(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } void CSuperTagEditorDoc::OnDlgEnvironment() { CDlgEnvSheet dialog("オプション設定"); bool bKeepTimeStamp = g_bOptKeepTimeStamp; bool bHideMP3ListFile = g_bOptHideMP3ListFile; bool bFileNameMaxCellColor = g_bFileNameMaxCellColor; /* SeaKnows 036 */ dialog.m_pDoc = this; dialog.DoModal(CDlgEnvSheet::ENV_ALL); CMySuperGrid &listCtrl = GetListCtrl(); // タイムスタンプ保持の設定項目が変更された // MP3 List のファイル名表示の有無が変更された if (bKeepTimeStamp != g_bOptKeepTimeStamp || bHideMP3ListFile != g_bOptHideMP3ListFile) { // 表示を更新させる listCtrl.UpdateAllFiles(); // カラム幅の自動調整 if (g_bOptLoadFileAdjustColumn) listCtrl.AutoSizeColumns(-1); } if (bFileNameMaxCellColor != g_bFileNameMaxCellColor) { /* SeaKnows 036 */ // 表示を更新させる listCtrl.UpdateAllFiles(); } // 分類済みフォルダの名称を更新する listCtrl.UpdateSyncFolderItemName(); // ジャンルリストを更新させる listCtrl.MakeStrListGenre(); } BOOL CSuperTagEditorDoc::OnOpenDocument(LPCTSTR lpszPathName) { // if (!CDocument::OnOpenDocument(lpszPathName)) // return FALSE; char sFileName[FILENAME_MAX]; strcpy(sFileName, lpszPathName); // 初期化処理 if (m_bInitialized == false) { /* StartInaction2 055 */ InitFileList(); // ファイルリストの初期化 ClearRequestFiles(); // 追加リクエストファイルリストの初期化 m_bInitialized = true; InitPlugin(); // プラグインのロード // 初期化処理 GetView()->m_List.InitializeGrid(); // フォントの設定 GetView()->UpdateFontListView(); InitGridList(); // グリッドを初期化 } // プレイリストか? CString strFileName = sFileName; strFileName.MakeLower(); if (strFileName.Find(".m3u") != -1) { // プレイリスト追加 GetView()->LoadPlayList(sFileName); return(TRUE); } // プログレスバー初期化 StartLoadFile("MP3ファイル読み込み中..."); CFileStatus status; if (CFile::GetStatus(sFileName, status) == TRUE && status.m_mtime != -1) { if (status.m_attribute & CFile::directory) { // ディレクトリの場合 // 最後の '\\' は必要 if (IsFolderName(sFileName) == false) { strcat(sFileName, "\\"); } bool bEnableSearchSubDir = g_bEnableSearchSubDir; /* TyphoonSwell 026 */ if (g_bOptDropSearchSubFolder) { g_bEnableSearchSubDir = true; } /* WildCherry2 078 */ //SearchFileReent(sFileName); OpenFolder(sFileName); g_bEnableSearchSubDir = bEnableSearchSubDir; } else { // ファイルの場合(ロングファイル名に変換してから処理する) if (GetLongPathName(sFileName, status.m_szFullName, FILENAME_MAX) != 0) { CString strLongFileName; TCHAR drive[_MAX_DRIVE], dir[_MAX_DIR]; _tsplitpath(status.m_szFullName, drive, dir, NULL, NULL); strLongFileName.Format("%s%s%s", drive, dir, sFileName); AddRequestFile(strLongFileName, NULL); } } } else if (strlen(sFileName) == 3 && sFileName[1] == ':' && sFileName[2] == '\\') { /* STEP 027 */ // ドライブの場合 // 下位階層を検索 bool bEnableSearchSubDir = g_bEnableSearchSubDir; if (g_bOptDropSearchSubFolder) { g_bEnableSearchSubDir = true; } OpenFolder(sFileName); g_bEnableSearchSubDir = bEnableSearchSubDir; } // 追加リクエストのあったファイルのタグ情報を読み込む #ifdef FLICKERFREE //GetView()->SetRedraw(FALSE); #endif ExecRequestFiles(true, g_bOptLoadFileChecked); #ifdef FLICKERFREE //GetView()->SetRedraw(TRUE); #endif // プログレスバー終了 EndLoadFile(); UpdateAllViews(NULL); return(TRUE); } // SI フィールドを表示/編集 void CSuperTagEditorDoc::OnUpdateEditFieldSi(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); pCmdUI->SetCheck(g_bOptEditFieldSIF ? TRUE : FALSE); } void CSuperTagEditorDoc::OnEditFieldSi() { if (g_bOptEditFieldSIF != true) { g_bOptEditFieldSIF = true; // 情報を更新 UpdateAllFiles(true); } } // ID3 tag 情報を表示/編集 void CSuperTagEditorDoc::OnUpdateEditTd3Tag(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); pCmdUI->SetCheck(g_bOptEditFieldSIF ? FALSE : TRUE); } void CSuperTagEditorDoc::OnEditTd3Tag() { if (g_bOptEditFieldSIF != false) { g_bOptEditFieldSIF = false; // 情報を更新 UpdateAllFiles(true); } } // [ID3 tag] <=> [SIフィールド]を切替 void CSuperTagEditorDoc::OnUpdateEditChangeField(CCmdUI* pCmdUI) { pCmdUI->Enable(TRUE); } void CSuperTagEditorDoc::OnEditChangeField() { g_bOptEditFieldSIF = g_bOptEditFieldSIF ? false : true; // 情報を更新 UpdateAllFiles(true); } // 分類表示の更新 void CSuperTagEditorDoc::OnUpdateExecClassification(CCmdUI* pCmdUI) { pCmdUI->Enable((m_nArrayFileCount > 0 && g_classInfo.nType) ? TRUE : FALSE); } void CSuperTagEditorDoc::OnExecClassification() { // プレイリスト読みこみ StartLoadFile("分類表示を更新中..."); m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "処理中..."); m_dlgLoadProgress->EnableCancelButton(FALSE); // グリッドに再登録 CMySuperGrid &listCtrl = GetListCtrl(); listCtrl.DeleteAllEx(); // グリッドを初期化 for (int no = 0; no < m_nArrayFileCount; no++) { // プログレスバー更新 if (m_nArrayFileCount > 1) { m_dlgLoadProgress->SetPos(no * 100 / (m_nArrayFileCount-1)); } // フォルダで分類 if (GetListMP3(no)->nFormat != FILE_FORMAT_UNKNOWN) { listCtrl.AddFile2(GetListMP3(no), NULL, (LPARAM)no, g_bOptLoadFileChecked); } } // ファイルのタグ情報を読み込む EndLoadFile(); UpdateAllViews(NULL); } #include "DlgFileOverWrite.h" bool CSuperTagEditorDoc::CheckFileAttribute(FILE_MP3 *fileMP3) { extern int g_nWriteTagProcFlag; if (g_nWriteTagProcFlag == 3) { return(false); // 以降中止 } // ファイル情報を取得 CFileStatus fileStatus; if (CFile::GetStatus(fileMP3->strFullPathName, fileStatus) == FALSE) { return(false); } // 読み出し専用ファイルは、上書き確認を行う if (fileStatus.m_attribute & CFile::readOnly) { if (g_nWriteTagProcFlag != 1) { // 上書き確認ダイアログを開く CDlgFileOverWrite dialog; dialog.m_strFileName = fileMP3->strFullPathName; dialog.m_strSize.Format("%ld byte", fileStatus.m_size); if (fileStatus.m_mtime.GetTime() < 0) { dialog.m_strTimeStamp.Format("----/--/-- --:--:--"); } else { dialog.m_strTimeStamp.Format("%04d/%02d/%02d %02d:%02d:%02d", fileStatus.m_mtime.GetYear(), fileStatus.m_mtime.GetMonth(), fileStatus.m_mtime.GetDay(), fileStatus.m_mtime.GetHour(), fileStatus.m_mtime.GetMinute(), fileStatus.m_mtime.GetSecond()); } dialog.DoModal(); g_nWriteTagProcFlag = dialog.m_nResult; switch(dialog.m_nResult) { case 0: // このファイルを上書き case 1: // 以降全て上書き break; case 2: // スキップ case 3: // 中止 default: return(false); } } // 読み込み専用属性を解除 SetFileAttributes(fileMP3->strFullPathName, CFile::normal); } return(true); } void CSuperTagEditorDoc::OnDlgSetupPlugin() { // TODO: この位置にコマンド ハンドラ用のコードを追加してください CDlgPluginSetup dialog; if (dialog.DoModal() == IDOK) { ((CSuperTagEditorApp *)AfxGetApp())->UpdateAccelerator(); /* STEP 030 */ } } void CSuperTagEditorDoc::OnUpdateDlgSetupPlugin(CCmdUI* pCmdUI) { // TODO: この位置に command update UI ハンドラ用のコードを追加してください pCmdUI->Enable(TRUE); } void CSuperTagEditorDoc::SaveAllTag(BOOL bSaveOnly) { m_bSaveAllTagResult = true; extern int g_nWriteTagProcFlag; // プログレスバー表示 StartLoadFile("タグ情報を更新中..."); m_dlgLoadProgress->SetDlgItemText(IDC_ST_MESSAGE, "処理中..."); // 更新ファイルのタグ情報更新 g_nWriteTagProcFlag = 0; for (int no = 0; no < m_nArrayFileCount; no++) { FILE_MP3 *fileMP3 = GetListMP3(no); if (m_nArrayFileCount != 1) { // プログレスバー更新 m_dlgLoadProgress->SetPos(no * 100 / (m_nArrayFileCount-1)); // 追加 by Kobarin if(m_dlgLoadProgress->IsCanceled()){ m_bSaveAllTagResult = false; break; } } if (fileMP3->nFormat != FILE_FORMAT_UNKNOWN && fileMP3->bModifyFlag) { if (CFileMP3::WriteTag(fileMP3, g_bOptKeepTimeStamp)) { fileMP3->bModifyFlag = FALSE; } else { MessageBox(NULL, "タグ情報をファイルを更新できませんでした", fileMP3->strFullPathName, MB_ICONSTOP|MB_OK|MB_TOPMOST); m_bSaveAllTagResult = false; } } } // プログレスバー終了 EndLoadFile(); if (bSaveOnly) return; // 情報を更新 CMySuperGrid &listCtrl = GetListCtrl(); #ifdef FLICKERFREE //listCtrl.SetRedraw(FALSE); #endif listCtrl.UpdateAllFiles(); UpdateAllFiles(true); if (g_bOptLoadFileAdjustColumn) listCtrl.AutoSizeColumns(-1); /* 2003.06.26 */ #ifdef FLICKERFREE //listCtrl.SetRedraw(TRUE); #endif }
[ "mimura1133@yahoo.co.jp" ]
mimura1133@yahoo.co.jp
df91068c0db0e72bbb753d7831a339d881ea0c22
cc57145c6aaed587aae05fe5f7e586f1032409ba
/gui/output/Outputs.h
c2d0a98d60fcef9486ff1db43093ab2c7f1e25d6
[]
no_license
andygarcia/denmod
f12fb8e0a2691228ce99f0c93c2f3cd318deac86
01f85e803ff8f90f121f1070f194d3f297d93842
refs/heads/master
2020-04-15T14:39:46.321111
2015-06-05T20:29:42
2015-06-05T20:29:42
9,421,998
3
1
null
null
null
null
UTF-8
C++
false
false
3,780
h
#pragma once #include "Enums.h" using namespace System; using namespace System::Collections::Generic; namespace gui { namespace output { public interface class IOutput { public: property String ^ Name; property Collections::IList ^ Data; }; generic<class T> public ref class Output : public IOutput { public: Output( String ^ name, array<T> ^ data ) : _name(name), _data(gcnew List<T>()) { for each( T t in data ) { _data->Add( t ); } } public: property String ^ Name { virtual String ^ get(void) { return _name; } virtual void set(String ^ s) { _name = s; } } property Collections::IList ^ Data { virtual Collections::IList ^ get(void) { return _data; } virtual void set(Collections::IList ^ il) { throw gcnew InvalidOperationException( "not implemented" ); } } protected: String ^ _name; List<T> ^ _data; }; typedef Collections::Generic::List<IOutput^> OutputCollection; public ref class DatedOutput : public Output<double> { public: DatedOutput( String ^ name, DateTime startDate, DateTime stopDate, array<double> ^ data ) : Output(name,data), _startDate(startDate), _stopDate(stopDate) {} public: List<DateTime> ^ GetDates(void); List<DateTime> ^ GetWeeks(void); List<DateTime> ^ GetMonths(void); List<double> ^ GetWeeklyData( TimePeriodFunction function ); List<double> ^ GetMonthlyData( TimePeriodFunction function ); private: DateTime _startDate; DateTime _stopDate; }; public ref class ClassOutput : public Output<double> { public: ClassOutput( String ^ name, array<double> ^ data ) : Output( name, data ) {} virtual ~ClassOutput(void) {} }; ref class CimsimOutput; ref class DensimOutput; public ref class SimOutput abstract { public: SimOutput( String ^ name, DateTime startDate, DateTime stopDate ); virtual ~SimOutput(void); public: virtual void SaveToDisk( IO::DirectoryInfo ^ di ) abstract; void WriteDailyWorksheet( IO::StreamWriter ^ sw, String ^ worksheetName, List<String^> ^ headers, List<DateTime> ^ dates, List<array<double>^> ^ columns ); void WriteClassWorksheet( IO::StreamWriter ^ sw, String ^ worksheetName, List<String^> ^ headers, List<String^> ^ indices, List<array<double>^> ^ columns ); protected: void GenerateWeeks(void); void GenerateMonths(void); void WriteWorkbookOpen( IO::StreamWriter ^ sw ); void WriteWorkbookStyles( IO::StreamWriter ^ sw ); void WriteWorkbookClose( IO::StreamWriter ^ sw ); public: property String ^ Name { String ^ get(void) { return _name; } } property DateTime StartDate { DateTime get(void) { return _startDate; } } property DateTime StopDate { DateTime get(void) { return _stopDate; } } property int NumberOfDays { int get(void) { return _numberOfDays; } } property List<DateTime> ^ Dates { List<DateTime> ^ get(void) { return _dates; } } property List<DateTime> ^ Weeks { List<DateTime> ^ get(void) { if( _weeks == nullptr ) { GenerateWeeks(); } return _weeks; } } property List<DateTime> ^ Months { List<DateTime> ^ get(void) { if( _months == nullptr ) { GenerateMonths(); } return _months; } } protected: String ^ _name; DateTime _startDate; DateTime _stopDate; int _numberOfDays; List<DateTime> ^ _dates; List<DateTime> ^ _weeks; List<DateTime> ^ _months; Dictionary<Type^,String^> ^ _typeToStyle; Dictionary<Type^,String^> ^ _typeToCellType; }; }; };
[ "andygarcia@gmail.com" ]
andygarcia@gmail.com
5820f160b3afabc47c2fa60ee76523fee14bacc2
17f5ceec908be809e16e201856140ce9c11cd37a
/ABGameMode.h
2fb2b383972ff114f3ef7866376e923f74b0ea67
[]
no_license
kojea0919/UE4_BookCode
cd27ceedb14af51641de955a7bde6f54f1981b2d
3ce9b42b1773e24f5c94d57eb55fe2e8f3e78439
refs/heads/master
2020-07-07T11:14:49.929238
2019-08-20T08:29:30
2019-08-20T08:29:30
203,333,284
0
0
null
null
null
null
UTF-8
C++
false
false
391
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "ArenaBattle.h" #include "GameFramework/GameModeBase.h" #include "ABGameMode.generated.h" /** * */ UCLASS() class ARENABATTLE_API AABGameMode : public AGameModeBase { GENERATED_BODY() AABGameMode(); public: virtual void PostLogin(APlayerController * NewPlayer) override; };
[ "gottkf0919@naver.com" ]
gottkf0919@naver.com
be4bfdaf30f91d99fb8c8651fe083e0e03136ee0
2f6b17aa5911b83e27f365a28ad09ee74e0d63f9
/source/organizer/organizercore.cpp
19c55e8df71df6ad654236383e71d747820af82b
[]
no_license
GrantSP/OriginalMO
afcc7b9bc8225db36216fe963c162696193e4b74
7935114fa2bbc6e38ad7a7b485754d20ee9bec23
refs/heads/master
2021-09-02T06:20:13.207699
2017-12-31T00:44:07
2017-12-31T00:44:07
115,833,608
0
1
null
null
null
null
UTF-8
C++
false
false
54,237
cpp
#include "organizercore.h" #include "mainwindow.h" #include "gameinfoimpl.h" #include "messagedialog.h" #include "logbuffer.h" #include "credentialsdialog.h" #include "filedialogmemory.h" #include "lockeddialog.h" #include "modinfodialog.h" #include "spawn.h" #include "safewritefile.h" #include "syncoverwritedialog.h" #include "nxmaccessmanager.h" #include <ipluginmodpage.h> #include <dataarchives.h> #include <directoryentry.h> #include <scopeguard.h> #include <utility.h> #include <appconfig.h> #include <report.h> #include <questionboxmemory.h> #include <QNetworkInterface> #include <QMessageBox> #include <QDialogButtonBox> #include <QApplication> #include <Psapi.h> #include <functional> using namespace MOShared; using namespace MOBase; static bool isOnline() { QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces(); bool connected = false; for (auto iter = interfaces.begin(); iter != interfaces.end() && !connected; ++iter) { if ( (iter->flags() & QNetworkInterface::IsUp) && (iter->flags() & QNetworkInterface::IsRunning) && !(iter->flags() & QNetworkInterface::IsLoopBack)) { auto addresses = iter->addressEntries(); if (addresses.count() == 0) { continue; } qDebug("interface %s seems to be up (address: %s)", qPrintable(iter->humanReadableName()), qPrintable(addresses[0].ip().toString())); connected = true; } } return connected; } static bool renameFile(const QString &oldName, const QString &newName, bool overwrite = true) { if (overwrite && QFile::exists(newName)) { QFile::remove(newName); } return QFile::rename(oldName, newName); } static std::wstring getProcessName(DWORD processId) { HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION, false, processId); wchar_t buffer[MAX_PATH]; if (::GetProcessImageFileNameW(process, buffer, MAX_PATH) != 0) { wchar_t *fileName = wcsrchr(buffer, L'\\'); if (fileName == nullptr) { fileName = buffer; } else { fileName += 1; } return fileName; } else { return std::wstring(L"unknown"); } } static void startSteam(QWidget *widget) { QSettings steamSettings("HKEY_CURRENT_USER\\Software\\Valve\\Steam", QSettings::NativeFormat); QString exe = steamSettings.value("SteamExe", "").toString(); if (!exe.isEmpty()) { exe = QString("\"%1\"").arg(exe); //See if username and password supplied. If so, pass them into steam. QStringList args; QString username; QString password; if (Settings::instance().getSteamLogin(username, password)) { args << "-login"; args << username; if (password != "") { args << password; } } if (!QProcess::startDetached(exe, args)) { reportError(QObject::tr("Failed to start \"%1\"").arg(exe)); } else { QMessageBox::information(widget, QObject::tr("Waiting"), QObject::tr("Please press OK once you're logged into steam.")); } } } template <typename InputIterator> QStringList toStringList(InputIterator current, InputIterator end) { QStringList result; for (; current != end; ++current) { result.append(*current); } return result; } OrganizerCore::OrganizerCore(const QSettings &initSettings) : m_GameInfo(new GameInfoImpl()) , m_UserInterface(nullptr) , m_PluginContainer(nullptr) , m_GameName() , m_CurrentProfile(nullptr) , m_Settings(initSettings) , m_Updater(NexusInterface::instance()) , m_AboutToRun() , m_FinishedRun() , m_ModInstalled() , m_ModList(this) , m_PluginList(this) , m_DirectoryRefresher() , m_DirectoryStructure(new DirectoryEntry(L"data", nullptr, 0)) , m_DownloadManager(NexusInterface::instance(), this) , m_InstallationManager() , m_RefresherThread() , m_AskForNexusPW(false) , m_DirectoryUpdate(false) , m_ArchivesInit(false) , m_PluginListsWriter(std::bind(&OrganizerCore::savePluginList, this)) { m_DownloadManager.setOutputDirectory(m_Settings.getDownloadDirectory()); m_DownloadManager.setPreferredServers(m_Settings.getPreferredServers()); NexusInterface::instance()->setCacheDirectory(m_Settings.getCacheDirectory()); NexusInterface::instance()->setNMMVersion(m_Settings.getNMMVersion()); MOBase::QuestionBoxMemory::init(initSettings.fileName()); m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); m_InstallationManager.setDownloadDirectory(m_Settings.getDownloadDirectory()); connect(&m_DownloadManager, SIGNAL(downloadSpeed(QString,int)), this, SLOT(downloadSpeed(QString,int))); connect(&m_DirectoryRefresher, SIGNAL(refreshed()), this, SLOT(directory_refreshed())); connect(&m_ModList, SIGNAL(removeOrigin(QString)), this, SLOT(removeOrigin(QString))); connect(NexusInterface::instance()->getAccessManager(), SIGNAL(loginSuccessful(bool)), this, SLOT(loginSuccessful(bool))); connect(NexusInterface::instance()->getAccessManager(), SIGNAL(loginFailed(QString)), this, SLOT(loginFailed(QString))); connect(this, SIGNAL(managedGameChanged(MOBase::IPluginGame*)), &m_Settings, SLOT(managedGameChanged(MOBase::IPluginGame*))); connect(&m_PluginList, &PluginList::writePluginsList, &m_PluginListsWriter, &DelayedFileWriterBase::write); // make directory refresher run in a separate thread m_RefresherThread.start(); m_DirectoryRefresher.moveToThread(&m_RefresherThread); m_AskForNexusPW = initSettings.value("ask_for_nexuspw", true).toBool(); } OrganizerCore::~OrganizerCore() { m_RefresherThread.exit(); m_RefresherThread.wait(); prepareStart(); // profile has to be cleaned up before the modinfo-buffer is cleared delete m_CurrentProfile; m_CurrentProfile = nullptr; ModInfo::clear(); LogBuffer::cleanQuit(); m_ModList.setProfile(nullptr); NexusInterface::instance()->cleanup(); delete m_GameInfo; delete m_DirectoryStructure; } QString OrganizerCore::commitSettings(const QString &iniFile) { if (!shellRename(iniFile + ".new", iniFile, true, qApp->activeWindow())) { DWORD err = ::GetLastError(); // make a second attempt using qt functions but if that fails print the error from the first attempt if (!renameFile(iniFile + ".new", iniFile)) { return windowsErrorString(err); } } return QString(); } QSettings::Status OrganizerCore::storeSettings(const QString &fileName) { QSettings settings(fileName, QSettings::IniFormat); if (m_UserInterface != nullptr) { m_UserInterface->storeSettings(settings); } if (m_CurrentProfile != nullptr) { settings.setValue("selected_profile", m_CurrentProfile->name().toUtf8().constData()); } settings.setValue("ask_for_nexuspw", m_AskForNexusPW); settings.remove("customExecutables"); settings.beginWriteArray("customExecutables"); std::vector<Executable>::const_iterator current, end; m_ExecutablesList.getExecutables(current, end); int count = 0; for (; current != end; ++current) { const Executable &item = *current; settings.setArrayIndex(count++); settings.setValue("title", item.m_Title); settings.setValue("custom", item.isCustom()); settings.setValue("toolbar", item.isShownOnToolbar()); settings.setValue("ownicon", item.usesOwnIcon()); if (item.isCustom()) { settings.setValue("binary", item.m_BinaryInfo.absoluteFilePath()); settings.setValue("arguments", item.m_Arguments); settings.setValue("workingDirectory", item.m_WorkingDirectory); settings.setValue("closeOnStart", item.m_CloseMO == ExecutableInfo::CloseMOStyle::DEFAULT_CLOSE); settings.setValue("steamAppID", item.m_SteamAppID); } } settings.endArray(); FileDialogMemory::save(settings); settings.sync(); return settings.status(); } void OrganizerCore::storeSettings() { QString iniFile = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::iniFileName()); if (QFileInfo(iniFile).exists()) { if (!shellCopy(iniFile, iniFile + ".new", true, qApp->activeWindow())) { QMessageBox::critical(qApp->activeWindow(), tr("Failed to write settings"), tr("An error occured trying to update MO settings to %1: %2").arg( iniFile, windowsErrorString(::GetLastError()))); return; } } QSettings::Status result = storeSettings(iniFile + ".new"); if (result == QSettings::NoError) { QString errMsg = commitSettings(iniFile); if (!errMsg.isEmpty()) { qWarning("settings file not writable, may be locked by another application, trying direct write"); result = storeSettings(iniFile); } } if (result != QSettings::NoError) { QString reason = result == QSettings::AccessError ? tr("File is write protected") : result == QSettings::FormatError ? tr("Invalid file format (probably a bug)") : tr("Unknown error %1").arg(result); QMessageBox::critical(qApp->activeWindow(), tr("Failed to write settings"), tr("An error occured trying to write back MO settings to %1: %2").arg(iniFile + ".new", reason)); } } bool OrganizerCore::testForSteam() { size_t currentSize = 1024; std::unique_ptr<DWORD[]> processIDs; DWORD bytesReturned; bool success = false; while (!success) { processIDs.reset(new DWORD[currentSize]); if (!::EnumProcesses(processIDs.get(), currentSize * sizeof(DWORD), &bytesReturned)) { qWarning("failed to determine if steam is running"); return true; } if (bytesReturned == (currentSize * sizeof(DWORD))) { // maximum size used, list probably truncated currentSize *= 2; } else { success = true; } } TCHAR processName[MAX_PATH]; for (unsigned int i = 0; i < bytesReturned / sizeof(DWORD); ++i) { memset(processName, '\0', sizeof(TCHAR) * MAX_PATH); if (processIDs[i] != 0) { HANDLE process = ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processIDs[i]); if (process != nullptr) { HMODULE module; DWORD ignore; // first module in a process is always the binary if (EnumProcessModules(process, &module, sizeof(HMODULE) * 1, &ignore)) { ::GetModuleBaseName(process, module, processName, MAX_PATH); if ((_tcsicmp(processName, TEXT("steam.exe")) == 0) || (_tcsicmp(processName, TEXT("steamservice.exe")) == 0)) { return true; } } } } } return false; } void OrganizerCore::updateExecutablesList(QSettings &settings) { if (m_PluginContainer == nullptr) { qCritical("can't update executables list now"); return; } m_ExecutablesList.init(m_PluginContainer->managedGame(ToQString(GameInfo::instance().getGameName()))); qDebug("setting up configured executables"); int numCustomExecutables = settings.beginReadArray("customExecutables"); for (int i = 0; i < numCustomExecutables; ++i) { settings.setArrayIndex(i); ExecutableInfo::CloseMOStyle closeMO = settings.value("closeOnStart").toBool() ? ExecutableInfo::CloseMOStyle::DEFAULT_CLOSE : ExecutableInfo::CloseMOStyle::DEFAULT_STAY; Executable::Flags flags; if (settings.value("custom", true).toBool()) flags |= Executable::CustomExecutable; if (settings.value("toolbar", false).toBool()) flags |= Executable::ShowInToolbar; if (settings.value("ownicon", false).toBool()) flags |= Executable::UseApplicationIcon; m_ExecutablesList.addExecutable(settings.value("title").toString(), settings.value("binary").toString(), settings.value("arguments").toString(), settings.value("workingDirectory", "").toString(), closeMO, settings.value("steamAppID", "").toString(), flags); } settings.endArray(); // TODO this has nothing to do with executables list move to an appropriate function! ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, m_Settings.displayForeign()); } void OrganizerCore::setUserInterface(IUserInterface *userInterface, QWidget *widget) { storeSettings(); m_UserInterface = userInterface; if (widget != nullptr) { connect(&m_ModList, SIGNAL(modlist_changed(QModelIndex, int)), widget, SLOT(modlistChanged(QModelIndex, int))); connect(&m_ModList, SIGNAL(showMessage(QString)), widget, SLOT(showMessage(QString))); connect(&m_ModList, SIGNAL(modRenamed(QString,QString)), widget, SLOT(modRenamed(QString,QString))); connect(&m_ModList, SIGNAL(modUninstalled(QString)), widget, SLOT(modRemoved(QString))); connect(&m_ModList, SIGNAL(removeSelectedMods()), widget, SLOT(removeMod_clicked())); connect(&m_ModList, SIGNAL(requestColumnSelect(QPoint)), widget, SLOT(displayColumnSelection(QPoint))); connect(&m_ModList, SIGNAL(fileMoved(QString, QString, QString)), widget, SLOT(fileMoved(QString, QString, QString))); connect(&m_ModList, SIGNAL(modorder_changed()), widget, SLOT(modorder_changed())); connect(&m_DownloadManager, SIGNAL(showMessage(QString)), widget, SLOT(showMessage(QString))); } m_InstallationManager.setParentWidget(widget); m_Updater.setUserInterface(widget); if (userInterface != nullptr) { // this currently wouldn't work reliably if the ui isn't initialized yet to display the result if (isOnline() && !m_Settings.offlineMode()) { m_Updater.testForUpdate(); } else { qDebug("user doesn't seem to be connected to the internet"); } } } void OrganizerCore::connectPlugins(PluginContainer *container) { m_DownloadManager.setSupportedExtensions(m_InstallationManager.getSupportedExtensions()); m_PluginContainer = container; if (!m_GameName.isEmpty()) { m_GamePlugin = m_PluginContainer->managedGame(m_GameName); emit managedGameChanged(m_GamePlugin); } } void OrganizerCore::disconnectPlugins() { m_AboutToRun.disconnect_all_slots(); m_FinishedRun.disconnect_all_slots(); m_ModInstalled.disconnect_all_slots(); m_ModList.disconnectSlots(); m_PluginList.disconnectSlots(); m_Settings.clearPlugins(); m_GamePlugin = nullptr; m_PluginContainer = nullptr; } void OrganizerCore::setManagedGame(const QString &gameName, const QString &gamePath) { m_GameName = gameName; if (m_PluginContainer != nullptr) { m_GamePlugin = m_PluginContainer->managedGame(m_GameName); m_GamePlugin->setGamePath(gamePath); qApp->setProperty("managed_game", QVariant::fromValue(m_GamePlugin)); emit managedGameChanged(m_GamePlugin); } } Settings &OrganizerCore::settings() { return m_Settings; } bool OrganizerCore::nexusLogin(bool retry) { NXMAccessManager *accessManager = NexusInterface::instance()->getAccessManager(); if ((accessManager->loginAttempted() || accessManager->loggedIn()) && !retry) { // previous attempt, maybe even successful return false; } else { QString username, password; if ((!retry && m_Settings.getNexusLogin(username, password)) || (m_AskForNexusPW && queryLogin(username, password))) { // credentials stored or user entered them manually qDebug("attempt login with username %s", qPrintable(username)); accessManager->login(username, password); return true; } else { // no credentials stored and user didn't enter them accessManager->refuseLogin(); return false; } } } bool OrganizerCore::queryLogin(QString &username, QString &password) { CredentialsDialog dialog(qApp->activeWindow()); int res = dialog.exec(); if (dialog.neverAsk()) { m_AskForNexusPW = false; } if (res == QDialog::Accepted) { username = dialog.username(); password = dialog.password(); if (dialog.store()) { m_Settings.setNexusLogin(username, password); } return true; } else { return false; } } void OrganizerCore::startMOUpdate() { if (nexusLogin()) { m_PostLoginTasks.append([&]() { m_Updater.startUpdate(); }); } else { m_Updater.startUpdate(); } } void OrganizerCore::downloadRequestedNXM(const QString &url) { qDebug("download requested: %s", qPrintable(url)); if (nexusLogin()) { m_PendingDownloads.append(url); } else { m_DownloadManager.addNXMDownload(url); } } void OrganizerCore::externalMessage(const QString &message) { if (message.left(6).toLower() == "nxm://") { MessageDialog::showMessage(tr("Download started"), qApp->activeWindow()); downloadRequestedNXM(message); } } void OrganizerCore::downloadRequested(QNetworkReply *reply, int modID, const QString &fileName) { try { if (m_DownloadManager.addDownload(reply, QStringList(), fileName, modID, 0, new ModRepositoryFileInfo(modID))) { MessageDialog::showMessage(tr("Download started"), qApp->activeWindow()); } } catch (const std::exception &e) { MessageDialog::showMessage(tr("Download failed"), qApp->activeWindow()); qCritical("exception starting download: %s", e.what()); } } void OrganizerCore::removeOrigin(const QString &name) { FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(name)); origin.enable(false); refreshLists(); } void OrganizerCore::downloadSpeed(const QString &serverName, int bytesPerSecond) { m_Settings.setDownloadSpeed(serverName, bytesPerSecond); } InstallationManager *OrganizerCore::installationManager() { return &m_InstallationManager; } void OrganizerCore::createDefaultProfile() { QString profilesPath = qApp->property("dataPath").toString() + "/" + QString::fromStdWString(AppConfig::profilesPath()); if (QDir(profilesPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot).size() == 0) { Profile newProf("Default", managedGame(), false); } } void OrganizerCore::setCurrentProfile(const QString &profileName) { if ((m_CurrentProfile != nullptr) && (profileName == m_CurrentProfile->name())) { return; } QString profileDir = qApp->property("dataPath").toString() + "/" + ToQString(AppConfig::profilesPath()) + "/" + profileName; Profile *newProfile = new Profile(QDir(profileDir), managedGame()); delete m_CurrentProfile; m_CurrentProfile = newProfile; m_ModList.setProfile(newProfile); if (m_CurrentProfile->invalidationActive(nullptr)) { m_CurrentProfile->activateInvalidation(); } else { m_CurrentProfile->deactivateInvalidation(); } connect(m_CurrentProfile, SIGNAL(modStatusChanged(uint)), this, SLOT(modStatusChanged(uint))); refreshDirectoryStructure(); } MOBase::IGameInfo &OrganizerCore::gameInfo() const { return *m_GameInfo; } MOBase::IModRepositoryBridge *OrganizerCore::createNexusBridge() const { return new NexusBridge(); } QString OrganizerCore::profileName() const { if (m_CurrentProfile != nullptr) { return m_CurrentProfile->name(); } else { return ""; } } QString OrganizerCore::profilePath() const { if (m_CurrentProfile != nullptr) { return m_CurrentProfile->absolutePath(); } else { return ""; } } QString OrganizerCore::downloadsPath() const { return QDir::fromNativeSeparators(m_Settings.getDownloadDirectory()); } MOBase::VersionInfo OrganizerCore::appVersion() const { return m_Updater.getVersion(); } MOBase::IModInterface *OrganizerCore::getMod(const QString &name) { unsigned int index = ModInfo::getIndex(name); if (index == UINT_MAX) { return nullptr; } else { return ModInfo::getByIndex(index).data(); } } MOBase::IModInterface *OrganizerCore::createMod(GuessedValue<QString> &name) { bool merge = false; if (!m_InstallationManager.testOverwrite(name, &merge)) { return nullptr; } m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); QString targetDirectory = QDir::fromNativeSeparators(m_Settings.getModDirectory()).append("/").append(name); QSettings settingsFile(targetDirectory + "/meta.ini", QSettings::IniFormat); if (!merge) { settingsFile.setValue("modid", 0); settingsFile.setValue("version", ""); settingsFile.setValue("newestVersion", ""); settingsFile.setValue("category", 0); settingsFile.setValue("installationFile", ""); settingsFile.beginWriteArray("installedFiles", 0); settingsFile.endArray(); } return ModInfo::createFrom(QDir(targetDirectory), &m_DirectoryStructure).data(); } bool OrganizerCore::removeMod(MOBase::IModInterface *mod) { unsigned int index = ModInfo::getIndex(mod->name()); if (index == UINT_MAX) { return mod->remove(); } else { return ModInfo::removeMod(index); } } void OrganizerCore::modDataChanged(MOBase::IModInterface*) { refreshModList(false); } QVariant OrganizerCore::pluginSetting(const QString &pluginName, const QString &key) const { return m_Settings.pluginSetting(pluginName, key); } void OrganizerCore::setPluginSetting(const QString &pluginName, const QString &key, const QVariant &value) { m_Settings.setPluginSetting(pluginName, key, value); } QVariant OrganizerCore::persistent(const QString &pluginName, const QString &key, const QVariant &def) const { return m_Settings.pluginPersistent(pluginName, key, def); } void OrganizerCore::setPersistent(const QString &pluginName, const QString &key, const QVariant &value, bool sync) { m_Settings.setPluginPersistent(pluginName, key, value, sync); } QString OrganizerCore::pluginDataPath() const { return qApp->applicationDirPath() + "/" + ToQString(AppConfig::pluginPath()) + "/data"; } MOBase::IModInterface *OrganizerCore::installMod(const QString &fileName, const QString &initModName) { if (m_CurrentProfile == nullptr) { return nullptr; } bool hasIniTweaks = false; GuessedValue<QString> modName; if (!initModName.isEmpty()) { modName.update(initModName, GUESS_USER); } m_CurrentProfile->writeModlistNow(); m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { MessageDialog::showMessage(tr("Installation successful"), qApp->activeWindow()); refreshModList(); int modIndex = ModInfo::getIndex(modName); if (modIndex != UINT_MAX) { ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); if (hasIniTweaks && (m_UserInterface != nullptr) && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), tr("This mod contains ini tweaks. Do you want to configure them now?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) { m_UserInterface->displayModInformation(modInfo, modIndex, ModInfoDialog::TAB_INIFILES); } m_ModInstalled(modName); return modInfo.data(); } else { reportError(tr("mod \"%1\" not found").arg(modName)); } } else if (m_InstallationManager.wasCancelled()) { QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"), tr("The mod was not installed completely."), QMessageBox::Ok); } return nullptr; } void OrganizerCore::installDownload(int index) { try { QString fileName = m_DownloadManager.getFilePath(index); int modID = m_DownloadManager.getModID(index); int fileID = m_DownloadManager.getFileInfo(index)->fileID; GuessedValue<QString> modName; // see if there already are mods with the specified mod id if (modID != 0) { std::vector<ModInfo::Ptr> modInfo = ModInfo::getByModID(modID); for (auto iter = modInfo.begin(); iter != modInfo.end(); ++iter) { std::vector<ModInfo::EFlag> flags = (*iter)->getFlags(); if (std::find(flags.begin(), flags.end(), ModInfo::FLAG_BACKUP) == flags.end()) { modName.update((*iter)->name(), GUESS_PRESET); (*iter)->saveMeta(); } } } m_CurrentProfile->writeModlistNow(); bool hasIniTweaks = false; m_InstallationManager.setModsDirectory(m_Settings.getModDirectory()); if (m_InstallationManager.install(fileName, modName, hasIniTweaks)) { MessageDialog::showMessage(tr("Installation successful"), qApp->activeWindow()); refreshModList(); int modIndex = ModInfo::getIndex(modName); if (modIndex != UINT_MAX) { ModInfo::Ptr modInfo = ModInfo::getByIndex(modIndex); modInfo->addInstalledFile(modID, fileID); if (hasIniTweaks && m_UserInterface != nullptr && (QMessageBox::question(qApp->activeWindow(), tr("Configure Mod"), tr("This mod contains ini tweaks. Do you want to configure them now?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)) { m_UserInterface->displayModInformation(modInfo, modIndex, ModInfoDialog::TAB_INIFILES); } m_ModInstalled(modName); } else { reportError(tr("mod \"%1\" not found").arg(modName)); } m_DownloadManager.markInstalled(index); emit modInstalled(modName); } else if (m_InstallationManager.wasCancelled()) { QMessageBox::information(qApp->activeWindow(), tr("Installation cancelled"), tr("The mod was not installed completely."), QMessageBox::Ok); } } catch (const std::exception &e) { reportError(e.what()); } } QString OrganizerCore::resolvePath(const QString &fileName) const { if (m_DirectoryStructure == nullptr) { return QString(); } const FileEntry::Ptr file = m_DirectoryStructure->searchFile(ToWString(fileName), nullptr); if (file.get() != nullptr) { return ToQString(file->getFullPath()); } else { return QString(); } } QStringList OrganizerCore::listDirectories(const QString &directoryName) const { QStringList result; DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(ToWString(directoryName)); if (dir != nullptr) { std::vector<DirectoryEntry*>::iterator current, end; dir->getSubDirectories(current, end); for (; current != end; ++current) { result.append(ToQString((*current)->getName())); } } return result; } QStringList OrganizerCore::findFiles(const QString &path, const std::function<bool (const QString &)> &filter) const { QStringList result; DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(ToWString(path)); if (dir != nullptr) { std::vector<FileEntry::Ptr> files = dir->getFiles(); foreach (FileEntry::Ptr file, files) { if (filter(ToQString(file->getFullPath()))) { result.append(ToQString(file->getFullPath())); } } } else { qWarning("directory %s not found", qPrintable(path)); } return result; } QStringList OrganizerCore::getFileOrigins(const QString &fileName) const { QStringList result; const FileEntry::Ptr file = m_DirectoryStructure->searchFile(ToWString(QFileInfo(fileName).fileName()), nullptr); if (file.get() != nullptr) { result.append(ToQString(m_DirectoryStructure->getOriginByID(file->getOrigin()).getName())); foreach (int i, file->getAlternatives()) { result.append(ToQString(m_DirectoryStructure->getOriginByID(i).getName())); } } else { qDebug("%s not found", qPrintable(fileName)); } return result; } QList<MOBase::IOrganizer::FileInfo> OrganizerCore::findFileInfos(const QString &path, const std::function<bool (const MOBase::IOrganizer::FileInfo &)> &filter) const { QList<IOrganizer::FileInfo> result; DirectoryEntry *dir = m_DirectoryStructure->findSubDirectoryRecursive(ToWString(path)); if (dir != nullptr) { std::vector<FileEntry::Ptr> files = dir->getFiles(); foreach (FileEntry::Ptr file, files) { IOrganizer::FileInfo info; info.filePath = ToQString(file->getFullPath()); bool fromArchive = false; info.origins.append(ToQString(m_DirectoryStructure->getOriginByID(file->getOrigin(fromArchive)).getName())); info.archive = fromArchive ? ToQString(file->getArchive()) : ""; foreach (int idx, file->getAlternatives()) { info.origins.append(ToQString(m_DirectoryStructure->getOriginByID(idx).getName())); } if (filter(info)) { result.append(info); } } } return result; } DownloadManager *OrganizerCore::downloadManager() { return &m_DownloadManager; } PluginList *OrganizerCore::pluginList() { return &m_PluginList; } ModList *OrganizerCore::modList() { return &m_ModList; } void OrganizerCore::spawnBinary(const QFileInfo &binary, const QString &arguments, const QDir &currentDirectory, bool closeAfterStart, const QString &steamAppID) { LockedDialog *dialog = new LockedDialog(qApp->activeWindow()); dialog->show(); ON_BLOCK_EXIT([&] () { dialog->hide(); dialog->deleteLater(); }); HANDLE processHandle = spawnBinaryDirect(binary, arguments, m_CurrentProfile->name(), currentDirectory, steamAppID); if (processHandle != INVALID_HANDLE_VALUE) { if (closeAfterStart && (m_UserInterface != nullptr)) { m_UserInterface->closeWindow(); } else { if (m_UserInterface != nullptr) { m_UserInterface->setWindowEnabled(false); } // re-enable the locked dialog because what'd be the point otherwise? dialog->setEnabled(true); QCoreApplication::processEvents(); DWORD processExitCode; DWORD retLen; JOBOBJECT_BASIC_PROCESS_ID_LIST info; { DWORD currentProcess = 0UL; bool isJobHandle = true; DWORD res = ::MsgWaitForMultipleObjects(1, &processHandle, false, 1000, QS_KEY | QS_MOUSE); while ((res != WAIT_FAILED) && (res != WAIT_OBJECT_0) && !dialog->unlockClicked()) { if (isJobHandle) { if (::QueryInformationJobObject(processHandle, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) { if (info.NumberOfProcessIdsInList == 0) { break; } else { if (info.ProcessIdList[0] != currentProcess) { currentProcess = info.ProcessIdList[0]; dialog->setProcessName(ToQString(getProcessName(currentProcess))); } } } else { // the info-object I passed only provides space for 1 process id. but since this code only cares about whether there // is more than one that's good enough. ERROR_MORE_DATA simply signals there are at least two processes running. // any other error probably means the handle is a regular process handle, probably caused by running MO in a job without // the right to break out. if (::GetLastError() != ERROR_MORE_DATA) { isJobHandle = false; } } } // keep processing events so the app doesn't appear dead QCoreApplication::processEvents(); res = ::MsgWaitForMultipleObjects(1, &processHandle, false, 1000, QS_KEY | QS_MOUSE); } ::GetExitCodeProcess(processHandle, &processExitCode); } ::CloseHandle(processHandle); if (m_UserInterface != nullptr) { m_UserInterface->setWindowEnabled(true); } refreshDirectoryStructure(); // need to remove our stored load order because it may be outdated if a foreign tool changed the // file time. After removing that file, refreshESPList will use the file time as the order if (GameInfo::instance().getLoadOrderMechanism() == GameInfo::TYPE_FILETIME) { qDebug("removing loadorder.txt"); QFile::remove(m_CurrentProfile->getLoadOrderFileName()); } refreshESPList(); if (GameInfo::instance().getLoadOrderMechanism() == GameInfo::TYPE_FILETIME) { // the load order should have been retrieved from file time, now save it to our own format savePluginList(); } m_FinishedRun(binary.absoluteFilePath(), processExitCode); } } } HANDLE OrganizerCore::spawnBinaryDirect(const QFileInfo &binary, const QString &arguments, const QString &profileName, const QDir &currentDirectory, const QString &steamAppID) { prepareStart(); if (!binary.exists()) { reportError(tr("Executable \"%1\" not found").arg(binary.absoluteFilePath())); return INVALID_HANDLE_VALUE; } if (!steamAppID.isEmpty()) { ::SetEnvironmentVariableW(L"SteamAPPId", ToWString(steamAppID).c_str()); } else { ::SetEnvironmentVariableW(L"SteamAPPId", ToWString(m_Settings.getSteamAppID()).c_str()); } if ((GameInfo::instance().requiresSteam()) && (m_Settings.getLoadMechanism() == LoadMechanism::LOAD_MODORGANIZER)) { if (!testForSteam()) { QWidget *window = qApp->activeWindow(); if ((window != nullptr) && (!window->isVisible())) { window = nullptr; } if (QuestionBoxMemory::query(window, "steamQuery", tr("Start Steam?"), tr("Steam is required to be running already to correctly start the game. " "Should MO try to start steam now?"), QDialogButtonBox::Yes | QDialogButtonBox::No) == QDialogButtonBox::Yes) { startSteam(qApp->activeWindow()); } } } while (m_DirectoryUpdate) { ::Sleep(100); QCoreApplication::processEvents(); } // need to make sure all data is saved before we start the application if (m_CurrentProfile != nullptr) { m_CurrentProfile->modlistWriter().writeImmediately(true); } // TODO: should also pass arguments if (m_AboutToRun(binary.absoluteFilePath())) { return startBinary(binary, arguments, profileName, m_Settings.logLevel(), currentDirectory, true); } else { qDebug("start of \"%s\" canceled by plugin", qPrintable(binary.absoluteFilePath())); return INVALID_HANDLE_VALUE; } } HANDLE OrganizerCore::startApplication(const QString &executable, const QStringList &args, const QString &cwd, const QString &profile) { QFileInfo binary; QString arguments = args.join(" "); QString currentDirectory = cwd; QString profileName = profile; if (profile.length() == 0) { if (m_CurrentProfile != nullptr) { profileName = m_CurrentProfile->name(); } else { throw MyException(tr("No profile set")); } } QString steamAppID; if (executable.contains('\\') || executable.contains('/')) { // file path binary = QFileInfo(executable); if (binary.isRelative()) { // relative path, should be relative to game directory binary = QFileInfo(QDir::fromNativeSeparators(ToQString(GameInfo::instance().getGameDirectory())) + "/" + executable); } if (cwd.length() == 0) { currentDirectory = binary.absolutePath(); } try { const Executable &exe = m_ExecutablesList.findByBinary(binary); steamAppID = exe.m_SteamAppID; } catch (const std::runtime_error&) { // nop } } else { // only a file name, search executables list try { const Executable &exe = m_ExecutablesList.find(executable); steamAppID = exe.m_SteamAppID; if (arguments == "") { arguments = exe.m_Arguments; } binary = exe.m_BinaryInfo; if (cwd.length() == 0) { currentDirectory = exe.m_WorkingDirectory; } } catch (const std::runtime_error&) { qWarning("\"%s\" not set up as executable", executable.toUtf8().constData()); binary = QFileInfo(executable); } } return spawnBinaryDirect(binary, arguments, profileName, currentDirectory, steamAppID); } bool OrganizerCore::waitForApplication(HANDLE handle, LPDWORD exitCode) { if (m_UserInterface != nullptr) { m_UserInterface->lock(); ON_BLOCK_EXIT([&] () { m_UserInterface->unlock(); }); } DWORD retLen; JOBOBJECT_BASIC_PROCESS_ID_LIST info; bool isJobHandle = true; ULONG lastProcessID = ULONG_MAX; HANDLE processHandle = handle; DWORD res = ::MsgWaitForMultipleObjects(1, &handle, false, 500, QS_KEY | QS_MOUSE); while ((res != WAIT_FAILED) && (res != WAIT_OBJECT_0) && ((m_UserInterface == nullptr) || !m_UserInterface->unlockClicked())) { if (isJobHandle) { if (::QueryInformationJobObject(handle, JobObjectBasicProcessIdList, &info, sizeof(info), &retLen) > 0) { if (info.NumberOfProcessIdsInList == 0) { // fake signaled state res = WAIT_OBJECT_0; break; } else { // this is indeed a job handle. Figure out one of the process handles as well. if (lastProcessID != info.ProcessIdList[0]) { lastProcessID = info.ProcessIdList[0]; if (processHandle != handle) { ::CloseHandle(processHandle); } processHandle = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, lastProcessID); } } } else { // the info-object I passed only provides space for 1 process id. but since this code only cares about whether there // is more than one that's good enough. ERROR_MORE_DATA simply signals there are at least two processes running. // any other error probably means the handle is a regular process handle, probably caused by running MO in a job without // the right to break out. if (::GetLastError() != ERROR_MORE_DATA) { isJobHandle = false; } } } // keep processing events so the app doesn't appear dead QCoreApplication::processEvents(); res = ::MsgWaitForMultipleObjects(1, &handle, false, 500, QS_KEY | QS_MOUSE); } if (exitCode != nullptr) { ::GetExitCodeProcess(processHandle, exitCode); } ::CloseHandle(processHandle); return res == WAIT_OBJECT_0; } bool OrganizerCore::onAboutToRun(const std::function<bool (const QString &)> &func) { auto conn = m_AboutToRun.connect(func); return conn.connected(); } bool OrganizerCore::onFinishedRun(const std::function<void (const QString &, unsigned int)> &func) { auto conn = m_FinishedRun.connect(func); return conn.connected(); } bool OrganizerCore::onModInstalled(const std::function<void (const QString &)> &func) { auto conn = m_ModInstalled.connect(func); return conn.connected(); } void OrganizerCore::refreshModList(bool saveChanges) { // don't lose changes! if (saveChanges) { m_CurrentProfile->modlistWriter().writeImmediately(true); } ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, m_Settings.displayForeign()); m_CurrentProfile->refreshModStatus(); m_ModList.notifyChange(-1); refreshDirectoryStructure(); } void OrganizerCore::refreshESPList() { if (m_DirectoryUpdate) { // don't mess up the esp list if we're currently updating the directory structure m_PostRefreshTasks.append([this] () { this->refreshESPList(); }); return; } m_CurrentProfile->modlistWriter().write(); // clear list try { m_PluginList.refresh(m_CurrentProfile->name(), *m_DirectoryStructure, m_CurrentProfile->getPluginsFileName(), m_CurrentProfile->getLoadOrderFileName(), m_CurrentProfile->getLockedOrderFileName()); } catch (const std::exception &e) { reportError(tr("Failed to refresh list of esps: %1").arg(e.what())); } } void OrganizerCore::refreshBSAList() { DataArchives *archives = m_GamePlugin->feature<DataArchives>(); if (archives != nullptr) { m_ArchivesInit = false; // default archives are the ones enabled outside MO. if the list can't be found (which might // happen if ini files are missing) use hard-coded defaults (preferrably the same the game would use) m_DefaultArchives = archives->archives(m_CurrentProfile); if (m_DefaultArchives.length() == 0) { m_DefaultArchives = archives->vanillaArchives(); } m_ActiveArchives.clear(); auto iter = enabledArchives(); m_ActiveArchives = toStringList(iter.begin(), iter.end()); if (m_ActiveArchives.isEmpty()) { m_ActiveArchives = m_DefaultArchives; } if (m_UserInterface != nullptr) { m_UserInterface->updateBSAList(m_DefaultArchives, m_ActiveArchives); } m_ArchivesInit = true; } } void OrganizerCore::refreshLists() { if ((m_CurrentProfile != nullptr) && m_DirectoryStructure->isPopulated()) { refreshESPList(); refreshBSAList(); } // no point in refreshing lists if no files have been added to the directory tree } void OrganizerCore::updateModActiveState(int index, bool active) { ModInfo::Ptr modInfo = ModInfo::getByIndex(index); QDir dir(modInfo->absolutePath()); for (const QString &esm : dir.entryList(QStringList() << "*.esm", QDir::Files)) { m_PluginList.enableESP(esm, active); } int enabled = 0; QStringList esps = dir.entryList(QStringList() << "*.esp", QDir::Files); for (const QString &esp : esps) { const FileEntry::Ptr file = m_DirectoryStructure->findFile(ToWString(esp)); if (file.get() == nullptr) { qWarning("failed to activate %s", qPrintable(esp)); continue; } if (active != m_PluginList.isEnabled(esp) && file->getAlternatives().empty()) { m_PluginList.enableESP(esp, active); ++enabled; } } if (active && (enabled > 1)) { MessageDialog::showMessage(tr("Multiple esps activated, please check that they don't conflict."), qApp->activeWindow()); } m_PluginList.refreshLoadOrder(); // immediately save affected lists m_PluginListsWriter.writeImmediately(false); } void OrganizerCore::updateModInDirectoryStructure(unsigned int index, ModInfo::Ptr modInfo) { // add files of the bsa to the directory structure m_DirectoryRefresher.addModFilesToStructure(m_DirectoryStructure , modInfo->name() , m_CurrentProfile->getModPriority(index) , modInfo->absolutePath() , modInfo->stealFiles() ); DirectoryRefresher::cleanStructure(m_DirectoryStructure); // need to refresh plugin list now so we can activate esps refreshESPList(); // activate all esps of the specified mod so the bsas get activated along with it updateModActiveState(index, true); // now we need to refresh the bsa list and save it so there is no confusion about what archives are avaiable and active refreshBSAList(); if (m_UserInterface != nullptr) { m_UserInterface->archivesWriter().write(); } std::vector<QString> archives = enabledArchives(); m_DirectoryRefresher.setMods(m_CurrentProfile->getActiveMods(), std::set<QString>(archives.begin(), archives.end())); // finally also add files from bsas to the directory structure m_DirectoryRefresher.addModBSAToStructure(m_DirectoryStructure , modInfo->name() , m_CurrentProfile->getModPriority(index) , modInfo->absolutePath() , modInfo->archives() ); } void OrganizerCore::requestDownload(const QUrl &url, QNetworkReply *reply) { if (m_PluginContainer != nullptr) { for (IPluginModPage *modPage : m_PluginContainer->plugins<MOBase::IPluginModPage>()) { ModRepositoryFileInfo *fileInfo = new ModRepositoryFileInfo(); if (modPage->handlesDownload(url, reply->url(), *fileInfo)) { fileInfo->repository = modPage->name(); m_DownloadManager.addDownload(reply, fileInfo); return; } } } // no mod found that could handle the download. Is it a nexus mod? if (url.host() == "www.nexusmods.com") { int modID = 0; int fileID = 0; QRegExp modExp("mods/(\\d+)"); if (modExp.indexIn(url.toString()) != -1) { modID = modExp.cap(1).toInt(); } QRegExp fileExp("fid=(\\d+)"); if (fileExp.indexIn(reply->url().toString()) != -1) { fileID = fileExp.cap(1).toInt(); } m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo(modID, fileID)); } else { if (QMessageBox::question(qApp->activeWindow(), tr("Download?"), tr("A download has been started but no installed page plugin recognizes it.\n" "If you download anyway no information (i.e. version) will be associated with the download.\n" "Continue?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) { m_DownloadManager.addDownload(reply, new ModRepositoryFileInfo()); } } } ModListSortProxy *OrganizerCore::createModListProxyModel() { ModListSortProxy *result = new ModListSortProxy(m_CurrentProfile, this); result->setSourceModel(&m_ModList); return result; } PluginListSortProxy *OrganizerCore::createPluginListProxyModel() { PluginListSortProxy *result = new PluginListSortProxy(this); result->setSourceModel(&m_PluginList); return result; } IPluginGame *OrganizerCore::managedGame() const { return m_GamePlugin; } std::vector<QString> OrganizerCore::enabledArchives() { std::vector<QString> result; QFile archiveFile(m_CurrentProfile->getArchivesFileName()); if (archiveFile.open(QIODevice::ReadOnly)) { while (!archiveFile.atEnd()) { result.push_back(QString::fromUtf8(archiveFile.readLine()).trimmed()); } archiveFile.close(); } return result; } void OrganizerCore::refreshDirectoryStructure() { if (!m_DirectoryUpdate) { m_CurrentProfile->modlistWriter().writeImmediately(true); m_DirectoryUpdate = true; std::vector<std::tuple<QString, QString, int> > activeModList = m_CurrentProfile->getActiveMods(); auto archives = enabledArchives(); m_DirectoryRefresher.setMods(activeModList, std::set<QString>(archives.begin(), archives.end())); QTimer::singleShot(0, &m_DirectoryRefresher, SLOT(refresh())); } } void OrganizerCore::directory_refreshed() { DirectoryEntry *newStructure = m_DirectoryRefresher.getDirectoryStructure(); Q_ASSERT(newStructure != m_DirectoryStructure); if (newStructure != nullptr) { std::swap(m_DirectoryStructure, newStructure); delete newStructure; } else { // TODO: don't know why this happens, this slot seems to get called twice with only one emit return; } m_DirectoryUpdate = false; if (m_CurrentProfile != nullptr) { refreshLists(); } for (int i = 0; i < m_ModList.rowCount(); ++i) { ModInfo::Ptr modInfo = ModInfo::getByIndex(i); modInfo->clearCaches(); } for (auto task : m_PostRefreshTasks) { task(); } } void OrganizerCore::profileRefresh() { // have to refresh mods twice (again in refreshModList), otherwise the refresh isn't complete. Not sure why ModInfo::updateFromDisc(m_Settings.getModDirectory(), &m_DirectoryStructure, m_Settings.displayForeign()); m_CurrentProfile->refreshModStatus(); refreshModList(); } void OrganizerCore::modStatusChanged(unsigned int index) { try { ModInfo::Ptr modInfo = ModInfo::getByIndex(index); if (m_CurrentProfile->modEnabled(index)) { updateModInDirectoryStructure(index, modInfo); } else { updateModActiveState(index, false); refreshESPList(); if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { FilesOrigin &origin = m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())); origin.enable(false); } if (m_UserInterface != nullptr) { m_UserInterface->archivesWriter().write(); } } modInfo->clearCaches(); for (unsigned int i = 0; i < m_CurrentProfile->numMods(); ++i) { ModInfo::Ptr modInfo = ModInfo::getByIndex(i); int priority = m_CurrentProfile->getModPriority(i); if (m_DirectoryStructure->originExists(ToWString(modInfo->name()))) { // priorities in the directory structure are one higher because data is 0 m_DirectoryStructure->getOriginByName(ToWString(modInfo->name())).setPriority(priority + 1); } } m_DirectoryStructure->getFileRegister()->sortOrigins(); refreshLists(); } catch (const std::exception& e) { reportError(tr("failed to update mod list: %1").arg(e.what())); } } void OrganizerCore::loginSuccessful(bool necessary) { if (necessary) { MessageDialog::showMessage(tr("login successful"), qApp->activeWindow()); } foreach (QString url, m_PendingDownloads) { downloadRequestedNXM(url); } m_PendingDownloads.clear(); for (auto task : m_PostLoginTasks) { task(); } m_PostLoginTasks.clear(); NexusInterface::instance()->loginCompleted(); } void OrganizerCore::loginSuccessfulUpdate(bool necessary) { if (necessary) { MessageDialog::showMessage(tr("login successful"), qApp->activeWindow()); } m_Updater.startUpdate(); } void OrganizerCore::loginFailed(const QString &message) { if (QMessageBox::question(qApp->activeWindow(), tr("Login failed"), tr("Login failed, try again?")) == QMessageBox::Yes) { if (nexusLogin(true)) { return; } } if (!m_PendingDownloads.isEmpty()) { MessageDialog::showMessage(tr("login failed: %1. Download will not be associated with an account").arg(message), qApp->activeWindow()); for (QString url : m_PendingDownloads) { downloadRequestedNXM(url); } m_PendingDownloads.clear(); } else { MessageDialog::showMessage(tr("login failed: %1").arg(message), qApp->activeWindow()); m_PostLoginTasks.clear(); } NexusInterface::instance()->loginCompleted(); } void OrganizerCore::loginFailedUpdate(const QString &message) { MessageDialog::showMessage(tr("login failed: %1. You need to log-in with Nexus to update MO.").arg(message), qApp->activeWindow()); } void OrganizerCore::syncOverwrite() { unsigned int overwriteIndex = ModInfo::findMod([](ModInfo::Ptr mod) -> bool { std::vector<ModInfo::EFlag> flags = mod->getFlags(); return std::find(flags.begin(), flags.end(), ModInfo::FLAG_OVERWRITE) != flags.end(); }); ModInfo::Ptr modInfo = ModInfo::getByIndex(overwriteIndex); SyncOverwriteDialog syncDialog(modInfo->absolutePath(), m_DirectoryStructure, qApp->activeWindow()); if (syncDialog.exec() == QDialog::Accepted) { syncDialog.apply(QDir::fromNativeSeparators(m_Settings.getModDirectory())); modInfo->testValid(); refreshDirectoryStructure(); } } std::vector<unsigned int> OrganizerCore::activeProblems() const { std::vector<unsigned int> problems; if (m_PluginList.enabledCount() > 255) { problems.push_back(PROBLEM_TOOMANYPLUGINS); } return problems; } QString OrganizerCore::shortDescription(unsigned int key) const { switch (key) { case PROBLEM_TOOMANYPLUGINS: { return tr("Too many esps and esms enabled"); } break; default: { return tr("Description missing"); } break; } } QString OrganizerCore::fullDescription(unsigned int key) const { switch (key) { case PROBLEM_TOOMANYPLUGINS: { return tr("The game doesn't allow more than 255 active plugins (including the official ones) to be loaded. You have to disable some unused plugins or " "merge some plugins into one. You can find a guide here: <a href=\"http://wiki.step-project.com/Guide:Merging_Plugins\">http://wiki.step-project.com/Guide:Merging_Plugins</a>"); } break; default: { return tr("Description missing"); } break; } } bool OrganizerCore::hasGuidedFix(unsigned int) const { return false; } void OrganizerCore::startGuidedFix(unsigned int) const { } bool OrganizerCore::saveCurrentLists() { if (m_DirectoryUpdate) { qWarning("not saving lists during directory update"); return false; } try { savePluginList(); if (m_UserInterface != nullptr) { m_UserInterface->archivesWriter().write(); } } catch (const std::exception &e) { reportError(tr("failed to save load order: %1").arg(e.what())); } return true; } void OrganizerCore::savePluginList() { if (m_DirectoryUpdate) { // delay save till after directory update m_PostRefreshTasks.append([&] () { this->savePluginList(); }); return; } m_PluginList.saveTo(m_CurrentProfile->getPluginsFileName(), m_CurrentProfile->getLoadOrderFileName(), m_CurrentProfile->getLockedOrderFileName(), m_CurrentProfile->getDeleterFileName(), m_Settings.hideUncheckedPlugins()); m_PluginList.saveLoadOrder(*m_DirectoryStructure); } void OrganizerCore::prepareStart() { if (m_CurrentProfile == nullptr) { return; } m_CurrentProfile->modlistWriter().write(); m_CurrentProfile->createTweakedIniFile(); saveCurrentLists(); m_Settings.setupLoadMechanism(); storeSettings(); } std::vector<std::pair<QString, QString>> OrganizerCore::fileMapping() { IPluginGame *game = qApp->property("managed_game").value<IPluginGame*>(); return fileMapping(game->dataDirectory().absolutePath(), directoryStructure(), directoryStructure()); } std::vector<std::pair<QString, QString>> OrganizerCore::fileMapping( const QString &dataPath, const DirectoryEntry *base, const DirectoryEntry *directoryEntry) { std::vector<std::pair<QString, QString>> result; for (FileEntry::Ptr current : directoryEntry->getFiles()) { bool isArchive = false; int origin = current->getOrigin(isArchive); if (isArchive || (origin == 0)) { continue; } QString fileName = ToQString(current->getRelativePath()); QString source = ToQString(base->getOriginByID(origin).getPath()) + fileName; QString target = QDir::toNativeSeparators(dataPath) + fileName; result.push_back(std::make_pair(source, target)); } // recurse into subdirectories std::vector<DirectoryEntry*>::const_iterator current, end; directoryEntry->getSubDirectories(current, end); for (; current != end; ++current) { std::vector<std::pair<QString, QString>> subRes = fileMapping(dataPath, base, *current); result.insert(result.end(), subRes.begin(), subRes.end()); } return result; }
[ "fr00gyl@gmail.com" ]
fr00gyl@gmail.com
57c4a1b988cbf9d3f59bc38076d83bba8b55f2f4
4bd36dae2e4e69e9d04438b9197ae23bbab255e1
/Status/GeneratedFiles/ui_s_functionButtonWidget.h
e24a5f17dca915fb3cbf3c78b0053079d7c2f5bb
[]
no_license
StatusOnIineEducationDev/status-desktop
6b40704a25b8082a22bb16ea923dacd2f20e6938
f8632fa835306a8ec34d5324cd1f44406b1dcdb5
refs/heads/master
2020-07-30T19:29:04.119987
2019-12-30T11:22:54
2019-12-30T11:22:54
210,332,367
0
0
null
null
null
null
UTF-8
C++
false
false
9,571
h
/******************************************************************************** ** Form generated from reading UI file 's_functionButtonWidget.ui' ** ** Created by: Qt User Interface Compiler version 5.13.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_S_FUNCTIONBUTTONWIDGET_H #define UI_S_FUNCTIONBUTTONWIDGET_H #include <QtCore/QVariant> #include <QtGui/QIcon> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QFrame> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_StudentFunctionButtonWidget { public: QVBoxLayout *verticalLayout; QLabel *function_navigation_text; QPushButton *course_management_btn; QPushButton *online_classroom_btn; QPushButton *history_btn; QFrame *line_2; QLabel *other_navigation_text; QPushButton *setting_btn; QPushButton *document_btn; QButtonGroup *buttonGroup; void setupUi(QWidget *StudentFunctionButtonWidget) { if (StudentFunctionButtonWidget->objectName().isEmpty()) StudentFunctionButtonWidget->setObjectName(QString::fromUtf8("StudentFunctionButtonWidget")); StudentFunctionButtonWidget->resize(155, 248); StudentFunctionButtonWidget->setStyleSheet(QString::fromUtf8("QPushButton { \n" " text-align: left;\n" " padding-left: 15px;\n" " border: none;\n" " color: #79A0BA;;\n" " background-color: none;\n" "}\n" "\n" "QPushButton:hover {\n" " background-color: #385368;\n" "}\n" "\n" "QPushButton:checked {\n" " background-color: #537b9b;\n" " border-left: 5px solid #699BC3;\n" "}")); verticalLayout = new QVBoxLayout(StudentFunctionButtonWidget); verticalLayout->setSpacing(5); verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); function_navigation_text = new QLabel(StudentFunctionButtonWidget); function_navigation_text->setObjectName(QString::fromUtf8("function_navigation_text")); function_navigation_text->setMinimumSize(QSize(155, 30)); function_navigation_text->setMaximumSize(QSize(155, 30)); QFont font; font.setFamily(QString::fromUtf8("\345\276\256\350\275\257\351\233\205\351\273\221")); font.setPointSize(10); function_navigation_text->setFont(font); function_navigation_text->setStyleSheet(QString::fromUtf8("QLabel {\n" " color: #5b788c;\n" "}")); function_navigation_text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); verticalLayout->addWidget(function_navigation_text); course_management_btn = new QPushButton(StudentFunctionButtonWidget); buttonGroup = new QButtonGroup(StudentFunctionButtonWidget); buttonGroup->setObjectName(QString::fromUtf8("buttonGroup")); buttonGroup->addButton(course_management_btn); course_management_btn->setObjectName(QString::fromUtf8("course_management_btn")); course_management_btn->setMinimumSize(QSize(155, 30)); course_management_btn->setMaximumSize(QSize(155, 30)); course_management_btn->setFont(font); course_management_btn->setCursor(QCursor(Qt::PointingHandCursor)); course_management_btn->setStyleSheet(QString::fromUtf8("")); QIcon icon; icon.addFile(QString::fromUtf8(":/button/Resources/material/button/course.png"), QSize(), QIcon::Normal, QIcon::Off); course_management_btn->setIcon(icon); course_management_btn->setIconSize(QSize(18, 18)); course_management_btn->setCheckable(true); course_management_btn->setChecked(true); verticalLayout->addWidget(course_management_btn); online_classroom_btn = new QPushButton(StudentFunctionButtonWidget); buttonGroup->addButton(online_classroom_btn); online_classroom_btn->setObjectName(QString::fromUtf8("online_classroom_btn")); online_classroom_btn->setMinimumSize(QSize(155, 30)); online_classroom_btn->setMaximumSize(QSize(155, 30)); online_classroom_btn->setFont(font); online_classroom_btn->setCursor(QCursor(Qt::PointingHandCursor)); online_classroom_btn->setStyleSheet(QString::fromUtf8("")); QIcon icon1; icon1.addFile(QString::fromUtf8(":/button/Resources/material/button/interaction.png"), QSize(), QIcon::Normal, QIcon::Off); online_classroom_btn->setIcon(icon1); online_classroom_btn->setIconSize(QSize(18, 18)); online_classroom_btn->setCheckable(true); verticalLayout->addWidget(online_classroom_btn); history_btn = new QPushButton(StudentFunctionButtonWidget); buttonGroup->addButton(history_btn); history_btn->setObjectName(QString::fromUtf8("history_btn")); history_btn->setMinimumSize(QSize(155, 30)); history_btn->setMaximumSize(QSize(155, 30)); history_btn->setFont(font); history_btn->setCursor(QCursor(Qt::PointingHandCursor)); history_btn->setStyleSheet(QString::fromUtf8("")); QIcon icon2; icon2.addFile(QString::fromUtf8(":/button/Resources/material/button/history.png"), QSize(), QIcon::Normal, QIcon::Off); history_btn->setIcon(icon2); history_btn->setIconSize(QSize(18, 18)); history_btn->setCheckable(true); verticalLayout->addWidget(history_btn); line_2 = new QFrame(StudentFunctionButtonWidget); line_2->setObjectName(QString::fromUtf8("line_2")); line_2->setFrameShape(QFrame::HLine); line_2->setFrameShadow(QFrame::Sunken); verticalLayout->addWidget(line_2); other_navigation_text = new QLabel(StudentFunctionButtonWidget); other_navigation_text->setObjectName(QString::fromUtf8("other_navigation_text")); other_navigation_text->setMinimumSize(QSize(155, 30)); other_navigation_text->setMaximumSize(QSize(155, 30)); other_navigation_text->setFont(font); other_navigation_text->setStyleSheet(QString::fromUtf8("QLabel {\n" " color: #5b788c;\n" "}")); other_navigation_text->setAlignment(Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter); verticalLayout->addWidget(other_navigation_text); setting_btn = new QPushButton(StudentFunctionButtonWidget); buttonGroup->addButton(setting_btn); setting_btn->setObjectName(QString::fromUtf8("setting_btn")); setting_btn->setMinimumSize(QSize(155, 30)); setting_btn->setMaximumSize(QSize(155, 30)); setting_btn->setFont(font); setting_btn->setCursor(QCursor(Qt::PointingHandCursor)); setting_btn->setStyleSheet(QString::fromUtf8("")); QIcon icon3; icon3.addFile(QString::fromUtf8(":/button/Resources/material/button/setting.png"), QSize(), QIcon::Normal, QIcon::Off); setting_btn->setIcon(icon3); setting_btn->setIconSize(QSize(18, 18)); setting_btn->setCheckable(true); verticalLayout->addWidget(setting_btn); document_btn = new QPushButton(StudentFunctionButtonWidget); buttonGroup->addButton(document_btn); document_btn->setObjectName(QString::fromUtf8("document_btn")); document_btn->setMinimumSize(QSize(155, 30)); document_btn->setMaximumSize(QSize(155, 30)); document_btn->setFont(font); document_btn->setCursor(QCursor(Qt::PointingHandCursor)); document_btn->setStyleSheet(QString::fromUtf8("")); QIcon icon4; icon4.addFile(QString::fromUtf8(":/button/Resources/material/button/document.png"), QSize(), QIcon::Normal, QIcon::Off); document_btn->setIcon(icon4); document_btn->setIconSize(QSize(18, 18)); document_btn->setCheckable(true); verticalLayout->addWidget(document_btn); retranslateUi(StudentFunctionButtonWidget); QMetaObject::connectSlotsByName(StudentFunctionButtonWidget); } // setupUi void retranslateUi(QWidget *StudentFunctionButtonWidget) { StudentFunctionButtonWidget->setWindowTitle(QCoreApplication::translate("StudentFunctionButtonWidget", "Form", nullptr)); function_navigation_text->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\212\237\350\203\275\350\217\234\345\215\225", nullptr)); course_management_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \350\257\276\347\250\213\347\256\241\347\220\206", nullptr)); online_classroom_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\234\250\347\272\277\346\225\231\345\256\244", nullptr)); history_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\216\206\345\217\262\350\256\260\345\275\225", nullptr)); other_navigation_text->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \345\205\266\344\273\226", nullptr)); setting_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \350\256\276\347\275\256", nullptr)); document_btn->setText(QCoreApplication::translate("StudentFunctionButtonWidget", " \344\275\277\347\224\250\345\270\256\345\212\251", nullptr)); } // retranslateUi }; namespace Ui { class StudentFunctionButtonWidget: public Ui_StudentFunctionButtonWidget {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_S_FUNCTIONBUTTONWIDGET_H
[ "lanyangbo@foxmail.com" ]
lanyangbo@foxmail.com
0e320c93d7ea521caaed1c45a597ebfe89104f47
8d01f870a612201c61bfa42068e2d40b7ae58675
/src/momentum.cpp
e158ac56d7df05fac563cbccf39379cf73052045
[]
no_license
hsitaram/nadi
0808779ce585b5f07325bc6bee2eb25746e32aa9
a02cb06900eb5be789cf724249f3dbec40f50bde
refs/heads/main
2023-03-16T12:35:05.280608
2021-03-05T21:04:58
2021-03-05T21:04:58
326,523,744
0
0
null
null
null
null
UTF-8
C++
false
false
7,222
cpp
#include<solve_manager.H> #include<global_defines.H> //======================================================================= void solveManager::vel_solve(Real time,Real dt) { const auto dx = m_geom.CellSizeArray(); Real visc=m_visc; Real delt=dt; for(MFIter mfi(*m_cc_flow_vars); mfi.isValid(); ++mfi) { const Box& bx = mfi.validbox(); auto vx=(*m_vx)[mfi].array(); auto vy=(*m_vy)[mfi].array(); auto vz=(*m_vz)[mfi].array(); Box x_bx=convert(bx, {1,0,0}); Box y_bx=convert(bx, {0,1,0}); Box z_bx=convert(bx, {0,0,1}); FArrayBox vx_src(x_bx, 1); Elixir vx_src_eli = vx_src.elixir(); Array4<Real> const& vx_src_arr = vx_src.array(); FArrayBox vy_src(y_bx, 1); Elixir vy_src_eli = vy_src.elixir(); Array4<Real> const& vy_src_arr = vy_src.array(); FArrayBox vz_src(z_bx, 1); Elixir vz_src_eli = vz_src.elixir(); Array4<Real> const& vz_src_arr = vz_src.array(); amrex::ParallelFor(x_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k) { Real vmid; vx_src_arr(i,j,k)=0.0; //left face vmid=0.5*(vx(i,j,k)+vx(i-1,j,k)); if(vmid > 0) vx_src_arr(i,j,k) -= vmid*vx(i-1,j,k)/dx[0]; else vx_src_arr(i,j,k) -= vmid*vx(i,j,k)/dx[0]; //right face vmid=0.5*(vx(i,j,k)+vx(i+1,j,k)); if(vmid > 0) vx_src_arr(i,j,k) += vmid*vx(i,j,k)/dx[0]; else vx_src_arr(i,j,k) += vmid*vx(i+1,j,k)/dx[0]; //bottom face vmid=0.5*(vy(i-1,j,k)+vy(i,j,k)); if(vmid > 0) vx_src_arr(i,j,k) -= vmid*vx(i,j-1,k)/dx[1]; else vx_src_arr(i,j,k) -= vmid*vx(i,j,k)/dx[1]; //top face vmid=0.5*(vy(i-1,j+1,k)+vy(i,j+1,k)); if(vmid > 0) vx_src_arr(i,j,k) += vmid*vx(i,j,k)/dx[1]; else vx_src_arr(i,j,k) += vmid*vx(i,j+1,k)/dx[1]; //back face vmid=0.5*(vz(i-1,j,k)+vz(i,j,k)); if(vmid > 0) vx_src_arr(i,j,k) -= vmid*vx(i,j,k-1)/dx[2]; else vx_src_arr(i,j,k) -= vmid*vx(i,j,k)/dx[2]; //front face vmid=0.5*(vz(i-1,j,k+1)+vz(i,j,k+1)); if(vmid > 0) vx_src_arr(i,j,k) += vmid*vx(i,j,k)/dx[2]; else vx_src_arr(i,j,k) += vmid*vx(i,j,k+1)/dx[2]; //diffusion vx_src_arr(i,j,k) -= visc*(vx(i+1,j,k)+vx(i-1,j,k)-2.0*vx(i,j,k))/(dx[0]*dx[0]); vx_src_arr(i,j,k) -= visc*(vx(i,j+1,k)+vx(i,j-1,k)-2.0*vx(i,j,k))/(dx[1]*dx[1]); vx_src_arr(i,j,k) -= visc*(vx(i,j,k+1)+vx(i,j,k-1)-2.0*vx(i,j,k))/(dx[2]*dx[2]); }); amrex::ParallelFor(y_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k) { Real vmid; vy_src_arr(i,j,k)=0.0; //left face vmid=0.5*(vx(i,j,k)+vx(i,j-1,k)); if(vmid > 0) vy_src_arr(i,j,k) -= vmid*vy(i-1,j,k)/dx[0]; else vy_src_arr(i,j,k) -= vmid*vy(i,j,k)/dx[0]; //right face vmid=0.5*(vx(i+1,j-1,k)+vx(i+1,j,k)); if(vmid > 0) vy_src_arr(i,j,k) += vmid*vy(i,j,k)/dx[0]; else vy_src_arr(i,j,k) += vmid*vy(i+1,j,k)/dx[0]; //bottom face vmid=0.5*(vy(i,j,k)+vy(i,j-1,k)); if(vmid > 0) vy_src_arr(i,j,k) -= vmid*vy(i,j-1,k)/dx[1]; else vy_src_arr(i,j,k) -= vmid*vy(i,j,k)/dx[1]; //top face vmid=0.5*(vy(i,j+1,k)+vy(i,j,k)); if(vmid > 0) vy_src_arr(i,j,k) += vmid*vy(i,j,k)/dx[1]; else vy_src_arr(i,j,k) += vmid*vy(i,j+1,k)/dx[1]; //back face vmid=0.5*(vz(i,j,k)+vz(i,j-1,k)); if(vmid > 0) vy_src_arr(i,j,k) -= vmid*vy(i,j,k-1)/dx[2]; else vy_src_arr(i,j,k) -= vmid*vy(i,j,k)/dx[2]; //front face vmid=0.5*(vz(i,j-1,k+1)+vz(i,j,k+1)); if(vmid > 0) vy_src_arr(i,j,k) += vmid*vy(i,j,k)/dx[2]; else vy_src_arr(i,j,k) += vmid*vy(i,j,k+1)/dx[2]; //diffusion vy_src_arr(i,j,k) -= visc*(vy(i+1,j,k)+vy(i-1,j,k)-2.0*vy(i,j,k))/(dx[0]*dx[0]); vy_src_arr(i,j,k) -= visc*(vy(i,j+1,k)+vy(i,j-1,k)-2.0*vy(i,j,k))/(dx[1]*dx[1]); vy_src_arr(i,j,k) -= visc*(vy(i,j,k+1)+vy(i,j,k-1)-2.0*vy(i,j,k))/(dx[2]*dx[2]); }); amrex::ParallelFor(z_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k) { Real vmid; vz_src_arr(i,j,k)=0.0; //left face vmid=0.5*(vx(i,j,k)+vx(i,j,k-1)); if(vmid > 0) vz_src_arr(i,j,k) -= vmid*vz(i-1,j,k)/dx[0]; else vz_src_arr(i,j,k) -= vmid*vz(i,j,k)/dx[0]; //right face vmid=0.5*(vx(i+1,j,k-1)+vx(i+1,j,k)); if(vmid > 0) vz_src_arr(i,j,k) += vmid*vz(i,j,k)/dx[0]; else vz_src_arr(i,j,k) += vmid*vz(i+1,j,k)/dx[0]; //bottom face vmid=0.5*(vy(i,j,k)+vy(i,j,k-1)); if(vmid > 0) vz_src_arr(i,j,k) -= vmid*vz(i,j-1,k)/dx[1]; else vz_src_arr(i,j,k) -= vmid*vz(i,j,k)/dx[1]; //top face vmid=0.5*(vy(i,j+1,k-1)+vy(i,j,k)); if(vmid > 0) vz_src_arr(i,j,k) += vmid*vz(i,j,k)/dx[1]; else vz_src_arr(i,j,k) += vmid*vz(i,j+1,k)/dx[1]; //back face vmid=0.5*(vz(i,j,k)+vz(i,j,k-1)); if(vmid > 0) vz_src_arr(i,j,k) -= vmid*vz(i,j,k-1)/dx[2]; else vz_src_arr(i,j,k) -= vmid*vz(i,j,k)/dx[2]; //front face vmid=0.5*(vz(i,j,k)+vz(i,j,k+1)); if(vmid > 0) vz_src_arr(i,j,k) += vmid*vz(i,j,k)/dx[2]; else vz_src_arr(i,j,k) += vmid*vz(i,j,k+1)/dx[2]; //diffusion vz_src_arr(i,j,k) -= visc*(vz(i+1,j,k)+vz(i-1,j,k)-2.0*vz(i,j,k))/(dx[0]*dx[0]); vz_src_arr(i,j,k) -= visc*(vz(i,j+1,k)+vz(i,j-1,k)-2.0*vz(i,j,k))/(dx[1]*dx[1]); vz_src_arr(i,j,k) -= visc*(vz(i,j,k+1)+vz(i,j,k-1)-2.0*vz(i,j,k))/(dx[2]*dx[2]); }); amrex::ParallelFor(x_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k) { vx(i,j,k) += -vx_src_arr(i,j,k)*delt; }); amrex::ParallelFor(y_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k) { vy(i,j,k) += -vy_src_arr(i,j,k)*delt; }); amrex::ParallelFor(z_bx, [=] AMREX_GPU_DEVICE(int i,int j,int k) { vz(i,j,k) += -vz_src_arr(i,j,k)*delt; }); } }
[ "hariswaran.sitaraman@nrel.gov" ]
hariswaran.sitaraman@nrel.gov
43b54cd30f3e64cb3d2864118d1f417be6c3ffdb
1d5dfe11d0bf4cb628cafafbc5c3660fee065397
/9.cpp
309f2910ee534d987e0ea2e64844d52778778a5f
[]
no_license
Eberty/ProgrammingSkillsAndSQL
955d42ed164ccf24b2aba6e9313d11093c60a006
311fde2a36892dd4d03533868be45d0de2de2ec5
refs/heads/main
2023-07-15T01:05:21.275945
2021-08-19T03:31:28
2021-08-19T03:31:28
397,298,301
0
0
null
null
null
null
UTF-8
C++
false
false
551
cpp
/* * Copyright 2021 Eberty Alves * * 9. Make a program in C/C++ or Java language that calculates the length of a string informed by the user (do not use * any pre-existing function or method for this, such as len(), count(), strlen() or length()); * * How to compile and run: * g++ 9.cpp -o StringLength * ./StringLength */ #include <bits/stdc++.h> int main(int argc, char** argv) { std::string str; std::getline(std::cin, str); size_t i = 0; while (str[i] != '\0') { i++; } std::cout << i << std::endl; return 0; }
[ "eberty.silva@hotmail.com" ]
eberty.silva@hotmail.com
8910e016c4afcdb35801a692b82f42443a3c5d59
438e67f05d962053e400d6417249c116d2a6954b
/StringToInteger.cpp
301477c39afd40e30fba29626a937dc5e75e4374
[]
no_license
alexandersdickinson/LeetCode
c09e8f0e70fe714b4d285812692e74ad4f3d75c6
d381b1e603beeb31aa9ac38085e887874852152c
refs/heads/master
2020-12-02T21:04:18.426840
2017-09-13T21:09:04
2017-09-13T21:09:04
96,253,888
0
0
null
null
null
null
UTF-8
C++
false
false
1,334
cpp
class Solution { public: int myAtoi(string str) { int signs = int(); long converted = 0; bool negative = false; if(str.find_first_of("1234567890") == string::npos || str.length() == 0){ return 0; } str = str.substr(str.find_first_not_of(" \t"), str.length()); str = str.substr(0, str.find_first_not_of("+-1234567890")); for(int i = str.length() - 1, j = 0; i >= 0; --i, ++j){ if(str.at(i) == '+' || str.at(i) == '-'){ break; } else{ converted += ((long)str.at(i) - 48) * (long)pow(10, j); if(j >= 9 && converted > INT_MAX){ if(str.find_first_of("1234567890") > 1){ return 0; } else if(str.at(0) == '-'){ return INT_MIN; } else{ return INT_MAX; } } } } if(str.find_first_of("1234567890") > 1){ return 0; } else if(str.at(0) == '-'){ negative = true; } if(negative){ return (int)converted * -1; } else{ return converted; } } };
[ "alexandersdickinson@gmail.com" ]
alexandersdickinson@gmail.com
b092a6266a302c5d495ecca8003b6680604f04f3
438f884b4b69a8ec50edac904cee9ab4f274d9ca
/GradTeme/GameThings/Door.h
d4e5f19a2c8cb1b32f5eb1ccf26e11d0cffe8e70
[]
no_license
Zeepooh1/RG_Seminar
66e1a5171cbfda95763e735ee12f834e65d50066
24d09522ed4ea882ad28fbd4e91681ad38f20c9a
refs/heads/master
2020-04-11T09:36:41.080332
2019-03-10T20:18:32
2019-03-10T20:18:32
161,684,510
1
0
null
null
null
null
UTF-8
C++
false
false
432
h
#pragma once #include <GL\glew.h> #include <glm\glm.hpp> #include <PlayingGround\SpriteBatch.h> class Door { public: Door(); ~Door(); void init(GLint pID); void update(); void draw(PlayingGround::SpriteBatch&); private: glm::mat4 m_projection; glm::mat4 m_model; glm::mat4 m_view; float m_speed = 0.1f; bool m_isOpen = false; GLfloat m_viewLoc; GLfloat m_modelLoc; GLfloat m_projectionLoc; glm::vec3 m_position; };
[ "zb0382@student.uni-lj.si" ]
zb0382@student.uni-lj.si
7a6f1a058397aeb54e45554597fe217d6eebb4a6
7481cd579dbd72999141a2533cfab5414a9af059
/src/training/agents/nn_agent.h
e371df73619be7afec648665cc76b9cfedb972e6
[]
no_license
Omegastick/bots
36d9c99ede06aed54fc66b6a8bc0b493924e3c34
25342bbeec18c228bd1ec5350573a1e4bee11337
refs/heads/master
2022-04-13T20:36:46.847747
2020-04-14T12:09:07
2020-04-14T12:09:07
150,558,810
1
1
null
null
null
null
UTF-8
C++
false
false
710
h
#pragma once #include <cpprl/model/policy.h> #include <nlohmann/json_fwd.hpp> #include "iagent.h" namespace ai { class NNAgent : public IAgent { private: mutable cpprl::Policy policy; public: NNAgent(cpprl::Policy policy, const nlohmann::json &body_spec, const std::string &name); ActResult act(torch::Tensor observations, torch::Tensor hidden_states, torch::Tensor masks) const; virtual std::unique_ptr<IAgent> clone() const; inline int get_hidden_state_size() const { return policy->get_hidden_size(); } inline cpprl::Policy &get_policy() { return policy; } inline void set_policy(cpprl::Policy policy) { this->policy = policy; } }; }
[ "omegastick@hotmail.co.uk" ]
omegastick@hotmail.co.uk
36eeca246bd05d2293ddce2748bffa0798be8126
c76adc973e5251452e1beb3de7776d0a2b709fce
/submissions/c3.s822.ncu100502028.Group1B.cpp.0.100502028.cpp
fee75edb4ea92af8ff6234fdb113e49cc0b34adf
[]
no_license
ncuoolab/domjudge
779a167f695f45a6a33437996ec5ad0f9d01c563
bda18c69d418c829ff653f9183b3244520139f8a
refs/heads/master
2020-05-19T08:10:39.974107
2015-03-10T19:35:03
2015-03-10T19:43:26
31,972,137
0
0
null
null
null
null
UTF-8
C++
false
false
2,120
cpp
#include <iostream> #include <cstdlib> #include <string> #include <sstream> using namespace std; int main () { string line = ""; int outCount = 0; bool flag[2] = {true, true}; string temp[2] = {}; while (true) { getline(cin, line); istringstream in(line); string input[3]; int count = 0; while(in >> input[count]) count++; if (count == 3) { if (input[0][0] == 'l' || input[0][0] == 'b') { int sizeOfFirstName = input[1].length(); for (int i = 1; i < sizeOfFirstName - 1; i++){ if ((input[1][i] >= 'a' && input[1][i] <= 'z') && (input[1][0] >= 'A' && input[1][0] <= 'Z')) { flag[outCount] = true; int sizeOfLastName = input[2].length(); for (int i = 0; i < sizeOfLastName - 1; i++){ if ((input[2][i] == 'a'|| (input[2][i] >= 'c' && input[2][i] <= 'z'))) { flag[outCount] = true; } else { flag[outCount] = false; } } } else { flag[outCount] = false; } } if (flag[outCount] == true) { if (input[0][0] == 'l') temp[outCount] += "level " + input[0] + "\n"; else temp[outCount] += "battle " + input[0] + "\n"; temp[outCount] += "FirstName " + input[1] + "\n"; temp[outCount] += "LastName " + input[2] + "\n"; } } else { flag[outCount] = false; } } else if (count == 2) { if (input[0][0] == 'b') { int sizeOfID = input[1].length(); for (int i = 0; i < sizeOfID - 1; i++){ if ((input[1][i] >= '0' && input[1][i] <= '9')) { flag[outCount] = true; } else { flag[outCount] = false; } } if (flag[outCount] == true) { temp[outCount] += "battle " + input[0] + "\n"; temp[outCount] += "cid " + input[1] + "\n"; } } else { flag[outCount] = false; } } else { flag[outCount] = false; } outCount++; } if(flag[0] == true && flag[1] == true) { cout << temp[0]; cout << temp[1]; } else cout << "invalid input" << endl; system("pause"); return 0; }
[ "fntsrlike@gmail.com" ]
fntsrlike@gmail.com
beeca12c7a0b550ce926b3ba13310e516f6a34bd
058641627a8f32e691be01ae01560e05badf5db9
/symbian/kernel/src/SimRequest.cpp
5941663f3b32e0291be0d6ceca1f16d2422d39f6
[]
no_license
migrsoft/nbk
7ae29bd44ec6d92ee0065953885056cef04a27b1
30eedbbddddd605a70ca1210b8467820bbbd6efd
refs/heads/master
2023-03-21T14:23:05.626831
2021-03-10T07:29:32
2021-03-10T07:29:32
346,268,899
0
0
null
null
null
null
UTF-8
C++
false
false
8,756
cpp
/* ============================================================================ Name : SimRequest.cpp Author : Yulun Wu Version : 1.0 Copyright : Baidu MIC Description : CSimRequest implementation ============================================================================ */ #include "SimRequest.h" #include "ResourceManager.h" #include <coemain.h> #include <bautils.h> #include "../../../stdc/tools/str.h" #define BUFFER_SIZE 32768 CSimRequest::CSimRequest(TInt aType) : CActive(EPriorityStandard) { iType = aType; iCompressed = EFalse; iFileOpen = EFalse; iMime = NEMIME_UNKNOWN; iBuf = NULL; } CSimRequest* CSimRequest::NewLC(TInt aType) { CSimRequest* self = new (ELeave) CSimRequest(aType); CleanupStack::PushL(self); self->ConstructL(); return self; } CSimRequest* CSimRequest::NewL(TInt aType) { CSimRequest* self = CSimRequest::NewLC(aType); CleanupStack::Pop(); // self; return self; } void CSimRequest::ConstructL() { User::LeaveIfError(iTimer.CreateLocal()); CActiveScheduler::Add(this); } CSimRequest::~CSimRequest() { Cancel(); iTimer.Close(); if (iFileOpen) { iFile.Close(); } if (iBuffer) { delete iBuffer; iBuffer = NULL; } if (iUrl) { delete iUrl; iUrl = NULL; } if (iBuf) NBK_free(iBuf); } void CSimRequest::DoCancel() { iTimer.Cancel(); } void CSimRequest::StartL() { Cancel(); iStage = EUninitialized; iTimer.After(iStatus, 5); SetActive(); } void CSimRequest::RC_Cancel() { DoCancel(); } void CSimRequest::RunL() { TBool stop = EFalse; if (iStage == EUninitialized) { iStage = EInitialized; if (iType == EHistoryCache) { stop = CheckFile(); } else if (iType == EFileCache) { iObserver->OnSimRequestData(MSimRequestObserver::ESimReqHeader); } else if (iType == ESimNoCacheError) { iObserver->OnSimRequestData(MSimRequestObserver::ESimReqNoCache); stop = ETrue; } else if (iType == ESimApError) { iObserver->OnSimRequestData(MSimRequestObserver::ESimReqError); stop = ETrue; } else stop = ETrue; } else if (iStage != EError) { if (iType == EHistoryCache) stop = ReadData(); else if (iType == EFileCache) stop = ReadCacheData(); else stop = ETrue; } if (stop) { iStage = EError; } else { iTimer.After(iStatus, 5); SetActive(); } } TInt CSimRequest::RunError(TInt aError) { return aError; } // 检测临时缓存目录中是否存在请求的资源 TBool CSimRequest::CheckFile() { CResourceManager* manager = CResourceManager::GetPtr(); RFs& rfs = CCoeEnv::Static()->FsSession(); iByteRead = 0; if (iFileOpen) { iFile.Close(); iFileOpen = EFalse; } int len = manager->GetCachePath().Length(); HBufC* name = HBufC::New(len + 64); name->Des().Zero(); switch (iRequest->type) { // 主文档请求,包含主页面或云浏览页面数据包 case NEREQT_MAINDOC: { TPtr p = name->Des(); TPtr path = manager->GetCachePath(); // 主文档URI数据文件 p.Format(KCacheUriFormat, &path, iRequest->pageId); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { int size; iFile.Size(size); if (iUrl) delete iUrl; iUrl = HBufC8::New(size); TPtr8 p = iUrl->Des(); iFile.Read(p, size); iFile.Close(); } } // gzip压缩的主文档 p.Format(KCacheDocFormat, &path, iRequest->pageId); p.Append(KGzipSuffix); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { iFileOpen = ETrue; iCompressed = ETrue; } break; } // 未压缩的主文档 p.Format(KCacheDocFormat, &path, iRequest->pageId); p.Append(KHtmlSuffix); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { iFileOpen = ETrue; } break; } // wap.wmlc p.Format(KCacheDocFormat, &path, iRequest->pageId); p.Append(KWbxmlSuffix); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { iFileOpen = ETrue; iMime = NEMIME_DOC_WMLC; } break; } break; } // 单张图片请求 case NEREQT_IMAGE: { TPtrC8 url; TBuf8<32> md5str; TBuf<32> md5strU; url.Set((TUint8*)iRequest->url, nbk_strlen(iRequest->url)); CResourceManager::GetMsgDigestByMd5L(md5str, url); md5strU.Copy(md5str); // 图片以URI的MD5值命名的文件存储路径 TPtr p = name->Des(); TPtr path = manager->GetCachePath(); p.Format(KCachePathFormat, &path, iRequest->pageId); p.Append(md5strU); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { iFileOpen = ETrue; } } break; } // CSS case NEREQT_CSS: { TPtrC8 url; TBuf8<32> md5str; TBuf<32> md5strU; url.Set((TUint8*)iRequest->url, nbk_strlen(iRequest->url)); CResourceManager::GetMsgDigestByMd5L(md5str, url); md5strU.Copy(md5str); TPtr p = name->Des(); TPtr path = manager->GetCachePath(); // 压缩 p.Format(KCachePathFormat, &path, iRequest->pageId); p.Append(md5strU); p.Append(KCszSuffix); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { iFileOpen = ETrue; iMime = NEMIME_DOC_CSS; iCompressed = ETrue; } } // 非压缩 p.Format(KCachePathFormat, &path, iRequest->pageId); p.Append(md5strU); p.Append(KCssSuffix); if (BaflUtils::FileExists(rfs, p)) { if (iFile.Open(rfs, p, EFileRead) == KErrNone) { iFileOpen = ETrue; iMime = NEMIME_DOC_CSS; } } break; } } // switch delete name; if (iFileOpen) { iFile.Size(iSize); if (iBuffer == NULL) iBuffer = HBufC8::New(BUFFER_SIZE); iObserver->OnSimRequestData(MSimRequestObserver::ESimReqHeader); return EFalse; } else { iObserver->OnSimRequestData(MSimRequestObserver::ESimReqError); return ETrue; } } TBool CSimRequest::ReadData() { if (iFileOpen) { TPtr8 p = iBuffer->Des(); if (iFile.Read(p, BUFFER_SIZE) == KErrNone) { iObserver->OnSimRequestData(MSimRequestObserver::ESimReqData); iByteRead += p.Length(); if (iByteRead >= iSize) { iFile.Close(); iFileOpen = EFalse; iObserver->OnSimRequestData(MSimRequestObserver::ESimReqComplete); } else return EFalse; } } return ETrue; } TBool CSimRequest::ReadCacheData() { if (iBuf == NULL) { iBuf = (char*)NBK_malloc(BUFFER_SIZE); iByteRead = 0; } iRead = cacheMgr_getData(iCacheMgr, iCacheId, iBuf, BUFFER_SIZE, iByteRead); iByteRead += iRead; iObserver->OnSimRequestData(MSimRequestObserver::ESimReqData); if (iByteRead >= iSize) { iObserver->OnSimRequestData(MSimRequestObserver::ESimReqComplete); return ETrue; } return EFalse; } TBool CSimRequest::GetNextDataPart(TPtrC8& aDataPart) { if (iBuf) aDataPart.Set((TUint8*)iBuf, iRead); else aDataPart.Set(iBuffer->Des()); return (iByteRead >= iSize) ? EFalse : ETrue; } void CSimRequest::ReleaseData() { if (iBuffer) iBuffer->Des().Zero(); }
[ "yulun2013@outlook.com" ]
yulun2013@outlook.com
1be87b75c9cbf4a266a03b0f66087b7c618af7cd
b7f1758aa724c14248e3dd426417c7b861c03df0
/libraries/microLED/examples/other_func/other_func.ino
644b01a107413105c9062734d7581206b5d365e2
[ "MIT" ]
permissive
AlexGyver/GyverDrink
9ce774b99d12d7543f3242e9b3d06be4417bc4ad
78e83d8fb7ab93b2ba84f5721c5fd36c8b0a47a6
refs/heads/master
2022-03-08T10:48:35.548930
2021-09-09T16:11:03
2021-09-09T16:11:03
217,405,392
32
23
MIT
2022-02-25T21:42:05
2019-10-24T22:21:42
C++
UTF-8
C++
false
false
1,706
ino
// пример работы с лентой #define LED_PIN 6 // пин ленты #define NUMLEDS 64 // кол-во светодиодов #define ORDER_GRB // порядок цветов ORDER_GRB / ORDER_RGB / ORDER_BRG #define MAX_DATA_SPEED // разогнанный протокол связи (на 40% быстрее). Работает на ws2812/13. На 2811 не работает #define COLOR_DEBTH 2 // цветовая глубина: 1, 2, 3 (в байтах) // на меньшем цветовом разрешении скетч будет занимать в разы меньше места, // но уменьшится и количество оттенков и уровней яркости! // ВНИМАНИЕ! define настройки (ORDER_GRB и COLOR_DEBTH) делаются до подключения библиотеки! #include <microLED.h> LEDdata leds[NUMLEDS]; // буфер ленты типа LEDdata (размер зависит от COLOR_DEBTH) microLED strip(leds, NUMLEDS, LED_PIN); // объект лента void setup() { strip.setBrightness(30); // яркость (0-255) // яркость применяется при выводе .show() ! strip.setVoltage(4500); // установить напряжение питания в мв, по умолч. 5000 (для расчёта тока) strip.setMaxCurrent(700); // установить максимальный ток (автокоррекция яркости). 0 - выключено // при .show() яркость будет скорректирована, чтобы ток не превышал установленный } void loop() { }
[ "victor.glekler@gmail.com" ]
victor.glekler@gmail.com
01fd5618f36525edee24474e7ce0c5b91bf29e7e
23513134b9a28be57b9bb325a4873174df3008d8
/src/system/modules/ext2/Ext2Node.h
aefce54ca5348c0b047551e0b7c7c75dc28b806c
[]
no_license
berkus/pedigree
1012c29e78acb17c3696dcb2061a07f0515c88b7
9e2af017526a91566cc9560f9bb31b1cac784a3f
refs/heads/master
2023-09-01T21:28:46.221619
2009-04-13T16:40:11
2009-04-13T16:40:11
32,474,092
0
0
null
null
null
null
UTF-8
C++
false
false
2,364
h
/* * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef EXT2_NODE_H #define EXT2_NODE_H #include "ext2.h" #include <utilities/Vector.h> #include "Ext2Filesystem.h" /** A node in an ext2 filesystem. */ class Ext2Node { private: /** Copy constructors are hidden - unused! */ Ext2Node(const Ext2Node &file); Ext2Node& operator =(const Ext2Node&); public: /** Constructor, should be called only by a Filesystem. */ Ext2Node(uintptr_t inode_num, Inode inode, class Ext2Filesystem *pFs); /** Destructor */ virtual ~Ext2Node(); Inode *getInode() {return &m_Inode;} uint32_t getInodeNumber() {return m_InodeNumber;} /** Updates inode attributes. */ void fileAttributeChanged(size_t size, size_t atime, size_t mtime, size_t ctime); uint64_t read(uint64_t location, uint64_t size, uintptr_t buffer); uint64_t write(uint64_t location, uint64_t size, uintptr_t buffer); void truncate(); protected: /** Ensures the inode is at least 'size' big. */ bool ensureLargeEnough(size_t size); bool addBlock(uint32_t blockValue); bool ensureBlockLoaded(size_t nBlock); bool getBlockNumber(size_t nBlock); bool getBlockNumberIndirect(uint32_t inode_block, size_t nBlocks, size_t nBlock); bool getBlockNumberBiindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock); bool getBlockNumberTriindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock); bool setBlockNumber(size_t blockNum, uint32_t blockValue); Inode m_Inode; uint32_t m_InodeNumber; class Ext2Filesystem *m_pExt2Fs; uint32_t *m_pBlocks; uint32_t m_nBlocks; size_t m_nSize; }; #endif
[ "mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d" ]
mankeyrabbit@8f46629d-ec43-0410-9b68-4d101553c41d
f9a2df98d620732395bf150a1d2fa2a6da8aaafc
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/browser/safe_browsing/cloud_content_scanning/file_source_request_unittest.cc
5e2ff081c325c28f713e8d476c594e647e764b16
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
16,509
cc
// Copyright (c) 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 "chrome/browser/safe_browsing/cloud_content_scanning/file_source_request.h" #include "base/bind_helpers.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/test/bind_test_util.h" #include "base/test/task_environment.h" #include "chrome/browser/enterprise/connectors/common.h" #include "chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.h" #include "chrome/browser/safe_browsing/cloud_content_scanning/deep_scanning_dialog_delegate.h" #include "chrome/common/chrome_paths.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace safe_browsing { namespace { enterprise_connectors::AnalysisSettings settings(bool block_unsupported_types) { enterprise_connectors::AnalysisSettings settings; settings.block_unsupported_file_types = block_unsupported_types; return settings; } // Helpers to cast base::DoNothing, otherwise FileSourceRequest's ctor calls // would be ambiguous. This hack should be removed once only // ContentAnalysisResponse is supported. BinaryUploadService::ContentAnalysisCallback DoNothingConnector() { return base::DoNothing(); } BinaryUploadService::Callback DoNothingLegacy() { return base::DoNothing(); } } // namespace class FileSourceRequestTest : public testing::TestWithParam<bool> { public: FileSourceRequestTest() = default; bool use_legacy_proto() const { return GetParam(); } std::unique_ptr<FileSourceRequest> MakeRequest(bool block_unsupported_types, base::FilePath path, base::FilePath file_name) { if (use_legacy_proto()) { return std::make_unique<FileSourceRequest>( settings(block_unsupported_types), path, file_name, DoNothingLegacy()); } else { return std::make_unique<FileSourceRequest>( settings(block_unsupported_types), path, file_name, DoNothingConnector()); } } void GetResultsForFileContents(const std::string& file_contents, BinaryUploadService::Result* out_result, BinaryUploadService::Request::Data* out_data) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.doc"); base::WriteFile(file_path, file_contents.data(), file_contents.size()); auto request = MakeRequest(/*block_unsupported_types=*/false, file_path, file_path.BaseName()); bool called = false; base::RunLoop run_loop; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called, &out_result, &out_data]( BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { called = true; run_loop.Quit(); *out_result = result; *out_data = data; })); run_loop.Run(); EXPECT_TRUE(called); } private: }; INSTANTIATE_TEST_SUITE_P(, FileSourceRequestTest, testing::Bool()); TEST_P(FileSourceRequestTest, InvalidFiles) { base::test::TaskEnvironment task_environment; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); { // Non-existent files should return UNKNOWN and have no information set. base::FilePath path = temp_dir.GetPath().AppendASCII("not_a_real.doc"); auto request = MakeRequest(/*block_unsupported_types=*/false, path, path.BaseName()); bool called = false; base::RunLoop run_loop; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called](BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { called = true; run_loop.Quit(); EXPECT_EQ(result, BinaryUploadService::Result::UNKNOWN); EXPECT_EQ(data.size, 0u); EXPECT_TRUE(data.contents.empty()); EXPECT_TRUE(data.hash.empty()); })); run_loop.Run(); EXPECT_TRUE(called); } { // Directories should not be used as paths passed to GetFileSHA256Blocking, // so they should return UNKNOWN and have no information set. base::FilePath path = temp_dir.GetPath(); auto request = MakeRequest(/*block_unsupported_types=*/false, path, path.BaseName()); bool called = false; base::RunLoop run_loop; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called](BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { called = true; run_loop.Quit(); EXPECT_EQ(result, BinaryUploadService::Result::UNKNOWN); EXPECT_EQ(data.size, 0u); EXPECT_TRUE(data.contents.empty()); EXPECT_TRUE(data.hash.empty()); })); run_loop.Run(); EXPECT_TRUE(called); } } TEST_P(FileSourceRequestTest, NormalFiles) { base::test::TaskEnvironment task_environment; BinaryUploadService::Result result; BinaryUploadService::Request::Data data; std::string normal_contents = "Normal file contents"; GetResultsForFileContents(normal_contents, &result, &data); EXPECT_EQ(result, BinaryUploadService::Result::SUCCESS); EXPECT_EQ(data.size, normal_contents.size()); EXPECT_EQ(data.contents, normal_contents); // printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B"); std::string long_contents = std::string(BinaryUploadService::kMaxUploadSizeBytes, 'a'); GetResultsForFileContents(long_contents, &result, &data); EXPECT_EQ(result, BinaryUploadService::Result::SUCCESS); EXPECT_EQ(data.size, long_contents.size()); EXPECT_EQ(data.contents, long_contents); // printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "4F0E9C6A1A9A90F35B884D0F0E7343459C21060EEFEC6C0F2FA9DC1118DBE5BE"); } TEST_P(FileSourceRequestTest, LargeFiles) { base::test::TaskEnvironment task_environment; BinaryUploadService::Result result; BinaryUploadService::Request::Data data; std::string large_file_contents(BinaryUploadService::kMaxUploadSizeBytes + 1, 'a'); GetResultsForFileContents(large_file_contents, &result, &data); EXPECT_EQ(result, BinaryUploadService::Result::FILE_TOO_LARGE); EXPECT_EQ(data.size, large_file_contents.size()); EXPECT_TRUE(data.contents.empty()); // python3 -c "print('a' * (50 * 1024 * 1024 + 1), end='')" | sha256sum | tr // '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "9EB56DB30C49E131459FE735BA6B9D38327376224EC8D5A1233F43A5B4A25942"); std::string very_large_file_contents( 2 * BinaryUploadService::kMaxUploadSizeBytes, 'a'); GetResultsForFileContents(very_large_file_contents, &result, &data); EXPECT_EQ(result, BinaryUploadService::Result::FILE_TOO_LARGE); EXPECT_EQ(data.size, very_large_file_contents.size()); EXPECT_TRUE(data.contents.empty()); // python3 -c "print('a' * (100 * 1024 * 1024), end='')" | sha256sum | tr // '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "CEE41E98D0A6AD65CC0EC77A2BA50BF26D64DC9007F7F1C7D7DF68B8B71291A6"); } TEST_P(FileSourceRequestTest, PopulatesDigest) { base::test::TaskEnvironment task_environment; std::string file_contents = "Normal file contents"; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath file_path = temp_dir.GetPath().AppendASCII("foo.doc"); // Create the file. base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE); file.WriteAtCurrentPos(file_contents.data(), file_contents.size()); auto request = MakeRequest(/*block_unsupported_types=*/false, file_path, file_path.BaseName()); base::RunLoop run_loop; request->GetRequestData(base::BindLambdaForTesting( [&run_loop](BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { run_loop.Quit(); })); run_loop.Run(); // printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]' EXPECT_EQ(request->digest(), "29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B"); } TEST_P(FileSourceRequestTest, PopulatesFilename) { base::test::TaskEnvironment task_environment; std::string file_contents = "contents"; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath file_path = temp_dir.GetPath().AppendASCII("foo.doc"); // Create the file. base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE); file.WriteAtCurrentPos(file_contents.data(), file_contents.size()); auto request = MakeRequest(/*block_unsupported_types=*/false, file_path, file_path.BaseName()); base::RunLoop run_loop; request->GetRequestData(base::BindLambdaForTesting( [&run_loop](BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { run_loop.Quit(); })); run_loop.Run(); EXPECT_EQ(request->filename(), "foo.doc"); } TEST_P(FileSourceRequestTest, CachesResults) { base::test::TaskEnvironment task_environment; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); std::string normal_contents = "Normal file contents"; base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.doc"); base::WriteFile(file_path, normal_contents.data(), normal_contents.size()); BinaryUploadService::Result async_result; BinaryUploadService::Request::Data async_data; auto request = MakeRequest(/*block_unsupported_types=*/false, file_path, file_path.BaseName()); bool called = false; base::RunLoop run_loop; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called, &async_result, &async_data]( BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { called = true; run_loop.Quit(); async_result = result; async_data = data; })); run_loop.Run(); ASSERT_TRUE(called); BinaryUploadService::Result sync_result; BinaryUploadService::Request::Data sync_data; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called, &sync_result, &sync_data]( BinaryUploadService::Result result, const BinaryUploadService::Request::Data& data) { called = true; run_loop.Quit(); sync_result = result; sync_data = data; })); EXPECT_EQ(sync_result, async_result); EXPECT_EQ(sync_data.contents, async_data.contents); EXPECT_EQ(sync_data.size, async_data.size); EXPECT_EQ(sync_data.hash, async_data.hash); } TEST_P(FileSourceRequestTest, Encrypted) { content::BrowserTaskEnvironment browser_task_environment; content::InProcessUtilityThreadHelper in_process_utility_thread_helper; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); base::FilePath test_zip; EXPECT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_zip)); test_zip = test_zip.AppendASCII("safe_browsing") .AppendASCII("download_protection") .AppendASCII("encrypted.zip"); auto request = MakeRequest(/*block_unsupported_types=*/false, test_zip, test_zip.BaseName()); bool called = false; base::RunLoop run_loop; BinaryUploadService::Result result; BinaryUploadService::Request::Data data; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called, &result, &data]( BinaryUploadService::Result tmp_result, const BinaryUploadService::Request::Data& tmp_data) { called = true; run_loop.Quit(); result = tmp_result; data = tmp_data; })); run_loop.Run(); ASSERT_TRUE(called); EXPECT_EQ(result, BinaryUploadService::Result::FILE_ENCRYPTED); // du chrome/test/data/safe_browsing/download_protection -b EXPECT_EQ(data.size, 20015u); // sha256sum < chrome/test/data/safe_browsing/download_protection/\ // encrypted.zip | tr '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "701FCEA8B2112FFAB257A8A8DFD3382ABCF047689AB028D42903E3B3AA488D9A"); EXPECT_EQ(request->digest(), data.hash); } TEST_P(FileSourceRequestTest, UnsupportedFileTypeBlock) { base::test::TaskEnvironment task_environment; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); std::string normal_contents = "Normal file contents"; base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.xyz"); base::WriteFile(file_path, normal_contents.data(), normal_contents.size()); auto request = MakeRequest(/*block_unsupported_types=*/true, file_path, file_path.BaseName()); if (request->use_legacy_proto()) { request->set_request_dlp_scan(DlpDeepScanningClientRequest()); request->set_request_malware_scan(MalwareDeepScanningClientRequest()); } else { request->add_tag("dlp"); request->add_tag("malware"); } bool called = false; base::RunLoop run_loop; BinaryUploadService::Result result; BinaryUploadService::Request::Data data; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called, &result, &data]( BinaryUploadService::Result tmp_result, const BinaryUploadService::Request::Data& tmp_data) { called = true; run_loop.Quit(); result = tmp_result; data = tmp_data; })); run_loop.Run(); ASSERT_TRUE(called); EXPECT_EQ(result, BinaryUploadService::Result::DLP_SCAN_UNSUPPORTED_FILE_TYPE); EXPECT_EQ(data.contents, normal_contents); EXPECT_EQ(data.size, normal_contents.size()); // printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B"); EXPECT_EQ(request->digest(), data.hash); } TEST_P(FileSourceRequestTest, UnsupportedFileTypeNoBlock) { base::test::TaskEnvironment task_environment; base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); std::string normal_contents = "Normal file contents"; base::FilePath file_path = temp_dir.GetPath().AppendASCII("normal.xyz"); base::WriteFile(file_path, normal_contents.data(), normal_contents.size()); auto request = MakeRequest(/*block_unsupported_types=*/false, file_path, file_path.BaseName()); if (request->use_legacy_proto()) { request->set_request_dlp_scan(DlpDeepScanningClientRequest()); request->set_request_malware_scan(MalwareDeepScanningClientRequest()); } else { request->add_tag("dlp"); request->add_tag("malware"); } bool called = false; base::RunLoop run_loop; BinaryUploadService::Result result; BinaryUploadService::Request::Data data; request->GetRequestData(base::BindLambdaForTesting( [&run_loop, &called, &result, &data]( BinaryUploadService::Result tmp_result, const BinaryUploadService::Request::Data& tmp_data) { called = true; run_loop.Quit(); result = tmp_result; data = tmp_data; })); run_loop.Run(); ASSERT_TRUE(called); // The dlp request should have been removed since the type is unsupported. if (request->use_legacy_proto()) { EXPECT_FALSE(request->deep_scanning_request().has_dlp_scan_request()); } else { for (const std::string& tag : request->content_analysis_request().tags()) EXPECT_NE("dlp", tag); } EXPECT_EQ(result, BinaryUploadService::Result::SUCCESS); EXPECT_EQ(data.contents, normal_contents); EXPECT_EQ(data.size, normal_contents.size()); // printf "Normal file contents" | sha256sum | tr '[:lower:]' '[:upper:]' EXPECT_EQ(data.hash, "29644C10BD036866FCFD2BDACFF340DB5DE47A90002D6AB0C42DE6A22C26158B"); EXPECT_EQ(request->digest(), data.hash); } } // namespace safe_browsing
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
b23bd17bb8e3874f911452cc2afe746baff0419e
30ec2372ac36d40f4557c5f39cb606452e6e6bf5
/StarVMC/geant3/geant321/mmass.inc
3ad06c9ed8e8c56e6091d6e7380c635f392e9a99
[]
no_license
yfisyak/star-sw
fe77d1f6f246bfa200a0781a0335ede7e3f0ce77
449bba9cba3305baacbd7f18f7b3a51c61b81e61
refs/heads/main
2023-07-12T01:15:45.728968
2021-08-04T22:59:16
2021-08-04T22:59:16
382,115,093
2
0
null
2021-07-01T17:54:02
2021-07-01T17:54:01
null
UTF-8
C++
false
false
531
inc
* * $Id: mmass.inc,v 1.1.1.3 2009/02/18 20:33:07 fisyak Exp $ * * $Log: mmass.inc,v $ * Revision 1.1.1.3 2009/02/18 20:33:07 fisyak * *** empty log message *** * * Revision 1.1.1.1 2002/06/16 15:18:38 hristov * Separate distribution of Geant3 * * Revision 1.1.1.1 1999/05/18 15:55:16 fca * AliRoot sources * * Revision 1.1.1.1 1995/10/24 10:20:45 cernlib * Geant * * #ifndef CERNLIB_GEANT321_MMASS_INC #define CERNLIB_GEANT321_MMASS_INC * * * mmass.inc * COMMON/MMASS/ZN,ZP,ZD,ZT,ZHE3,ZA,AN,AP,AD,AT,AHE3,AA #endif
[ "fisyak@rcas6005.rcf.bnl.gov" ]
fisyak@rcas6005.rcf.bnl.gov
87d1637e4a0df057a6e8f5950f07b11f9830d693
65e3391b6afbef10ec9429ca4b43a26b5cf480af
/PHOS/macros/Trigger/raw/AliTRUPedestalAnalysis.h
45236bd1bb6e26669e1cc3babb4b4eafa60b0df9
[]
permissive
alisw/AliRoot
c0976f7105ae1e3d107dfe93578f819473b2b83f
d3f86386afbaac9f8b8658da6710eed2bdee977f
refs/heads/master
2023-08-03T11:15:54.211198
2023-07-28T12:39:57
2023-07-28T12:39:57
53,312,169
61
299
BSD-3-Clause
2023-07-28T13:19:50
2016-03-07T09:20:12
C++
UTF-8
C++
false
false
1,436
h
/* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ // Author: Henrik Qvigstad <henrik.qvigstad@cern.ch> /* $Id$ */ #ifndef ALITRUPEDESTALANALYSIS_H #define ALITRUPEDESTALANALYSIS_H #include <Rtypes.h> class AliCaloRawStreamV3; class AliTRUPedestalOutput; class AliPHOSTriggerRawReader; class AliTRUPedestalAnalysis { public: AliTRUPedestalAnalysis(); virtual ~AliTRUPedestalAnalysis(); void ProcessEvent(AliCaloRawStreamV3* ); AliTRUPedestalOutput* GetOutput() { return fOutput; } static UInt_t Get2x2Max(AliPHOSTriggerRawReader* reader, int mod, int row, int branch, int x, int z); // Constants const static UInt_t kNMods = 5; const static UInt_t kNTRURows = 4; const static UInt_t kNBranches = 2; const static UInt_t kN2x2X = 64/2; const static UInt_t kN2x2Z = 56/2; const static UInt_t kN2x2XPrTRURow = kN2x2X / kNTRURows; const static UInt_t kN2x2ZPrBranch = kN2x2Z / kNBranches; const static UInt_t kNTRUTimeBins = 128; const static UInt_t kNEMCTimeBins = 62; private: AliTRUPedestalAnalysis ( const AliTRUPedestalAnalysis& other ); // not impl. AliTRUPedestalAnalysis& operator= ( const AliTRUPedestalAnalysis& other ); // not impl. AliTRUPedestalOutput* fOutput; AliPHOSTriggerRawReader* fTriggerReader; }; #endif // ALITRUPEDESTALANALYSIS_H
[ "hqvigsta@f7af4fe6-9843-0410-8265-dc069ae4e863" ]
hqvigsta@f7af4fe6-9843-0410-8265-dc069ae4e863
78e7d13d8763b94ce9fcc7bb85f987c4c94c0225
732cfb5872b378252168e34601faf5d0f4d23b12
/Source/Gdk/Graphics/Shader/ShaderManager.cpp
01b81e44847d9762d75b5d425ac7930f2e51bdfe
[]
no_license
jnonline/gdk
d6d069541d3381817c58cb47511be92f403c954d
8f02e10465fd2cba0af9e19f431322333d55c301
refs/heads/master
2016-09-06T01:02:53.443856
2012-02-20T06:14:03
2012-02-20T06:14:03
35,491,285
0
0
null
null
null
null
UTF-8
C++
false
false
2,034
cpp
/* * Copyright (c) 2011, Raincity Games LLC * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php */ #include "BasePCH.h" #include "ShaderManager.h" using namespace Gdk; // Static Instantiations ShaderManager* ShaderManager::singleton = NULL; // ***************************************************************** /// @brief /// Constructor // ***************************************************************** ShaderManager::ShaderManager() { } // ***************************************************************** /// @brief /// Destructor // ***************************************************************** ShaderManager::~ShaderManager() { } // ***************************************************************** /// @brief /// Creates an Shader resource from the given Gdk Shader asset /// @param name /// Name of the Gdk Shader asset. This will also be the resource name. /// @param async /// If true, the asset will be loaded by a background thread. (Default = false) /// @param height /// The priority for an asyncronous load. Higher priority items are processed first. // ***************************************************************** Shader* ShaderManager::FromAsset(const char *name, bool async, int asyncPriority) { return (Shader*) singleton->LoadUtility(name, async, asyncPriority, &ShaderManager::PerformLoadFromAsset); } // ***************************************************************** /// @brief /// Gets a new Shader instance for the base ResourceManager. /// @remarks /// GDK Internal use only // ***************************************************************** Resource* ShaderManager::OnCreateNewResourceInstance() { return new Shader(); } // ***************************************************************** void ShaderManager::PerformLoadFromAsset(Resource* resource) { // Get the Shader* Shader* shader = (Shader*)resource; // Load the Shader from it's corresponding asset shader->LoadFromAsset(); }
[ "justin@raincitygames.com@84234807-5fa8-7533-bdbf-dec7f933a0b8" ]
justin@raincitygames.com@84234807-5fa8-7533-bdbf-dec7f933a0b8
ca03f5c263c449a259def270f1e820f29e150b49
f6f1053bc63911d671c5699dbf304e245ae646e4
/control_system/control_system/tests/SIL_sysMSD.cpp
b9dfdba1347e07e0857f803e39e48a998d6616c8
[]
no_license
gordon1258/control_system
635bb76486d322609cc2a97ac326534e7849029a
04c435fa3f90163994d5e8395f241020084890f3
refs/heads/master
2020-11-25T05:14:42.896164
2020-02-02T01:11:27
2020-02-02T01:11:27
228,512,930
1
0
null
null
null
null
UTF-8
C++
false
false
4,092
cpp
// // SIL_sysMSD.cpp // control_systemUT // // Created by Li-Cheng Hsu on 1/31/20. // Copyright © 2020 Li-Cheng Hsu. All rights reserved. // #include <stdio.h> #include "gtest/gtest.h" // GNUplot headers #include "gnuplot-iostream.h" #include <map> #include <vector> #include <boost/tuple/tuple.hpp> #include "mass_spring_damper.hpp" #include "pid.hpp" TEST(SIL_sysMSD_pid, SIL_test_sysMSD_pid) { // Mass-spring-damper system with PID controller sysMSD* sys; pid* pidCtrl; sys = new sysMSD; pidCtrl = new pid; // Parameters double t0 = 0; double dt_plant = 0.1; // sec double tFinal = 10; // sec double x_init = 0; // m double v_init = 0; // m/s double m = 1; // kg double b = 10; // N s/m double k = 20; // N/m double kp = 3; double ki = 0.01; double kd = 0; double dt_C = 0.01; std::vector<std::pair<double,double>> x_t; std::vector<std::pair<double,double>> v_t; std::vector<std::pair<double,double>> y_t; std::vector<std::pair<double,double>> err_t; std::vector<std::pair<double,double>> F_t; std::vector<std::pair<double,double>> xDes_t; // Init sys->setInitTime(t0); sys->setSampleTime(dt_plant); sys->setInitState(x_init, v_init); sys->setMass(m); sys->setDamper(b); sys->setSpring(k); std::cout << "t = " << sys->getCurTime() << std::endl; std::cout << "x = " << sys->getState().x1 << std::endl; x_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x1)); v_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x2)); y_t.push_back(std::make_pair(sys->getCurTime(), sys->getY())); // PID control double x_des = 1; xDes_t.push_back(std::make_pair(sys->getCurTime(), x_des)); err_t.push_back(std::make_pair(sys->getCurTime(), x_des - sys->getState().x1)); pidCtrl->setDt(dt_C); pidCtrl->setGains(kp, ki, kd); double F = pidCtrl->getCmdCtrl().cmdCtrl; F_t.push_back(std::make_pair(sys->getCurTime(), F)); // Simulation starts while(sys->getCurTime() < tFinal) { sys->dynSys(F); // Update F with PID controller double err = x_des - sys->getState().x1; pidCtrl->pidCalculate(err); if(pidCtrl->getCmdCtrl().isValid) F = pidCtrl->getCmdCtrl().cmdCtrl; // Push the states, outputs, and errors for plotting std::cout << "t = " << sys->getCurTime() << ", "; std::cout << "x = " << sys->getState().x1 << std::endl; x_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x1)); v_t.push_back(std::make_pair(sys->getCurTime(), sys->getState().x2)); y_t.push_back(std::make_pair(sys->getCurTime(), sys->getY())); F_t.push_back(std::make_pair(sys->getCurTime(), F)); xDes_t.push_back(std::make_pair(sys->getCurTime(), x_des)); err_t.push_back(std::make_pair(sys->getCurTime(), err)); } // Plot : gnuplot Gnuplot gp; //gp << "set xrange [0:3]\n"; gp << "set multiplot layout 3, 1 title 'Mass-Spring-Damper with PID controller'" << "font ',15'" << std::endl; // plot 1: Pos gp << "set title 'Position'" << "font ',11'" << std::endl; gp << "set xlabel 'time [sec]'" << std::endl; gp << "set ylabel 'position [m]'" << std::endl; gp << "plot '-' with lines title 'position', '-' with lines title 'pos_{des}'"<<std::endl; gp.send1d(x_t); gp.send1d(xDes_t); // plot 2: Err gp << "set title 'Error'" << "font ',11'" << std::endl; gp << "set xlabel 'time [sec]'" << std::endl; gp << "set ylabel 'err [m]'" << std::endl; gp << "plot '-' with lines title 'err'"<<std::endl; gp.send1d(err_t); // plot 3: Force gp << "set title 'Force'" << "font ',11'" << std::endl; gp << "set xlabel 'time [sec]'" << std::endl; gp << "set ylabel 'force [N]'" << std::endl; gp << "plot '-' with lines title 'force'"<<std::endl; gp.send1d(F_t); }
[ "gordon1258@gmail.com" ]
gordon1258@gmail.com
06dae261ded5f872dcdc5f5959a3db6e2439607b
6fcfe3a7263f365dddc5c4653f3a50e02adfd1ec
/1. C vs C++/function_call_puzzle_in_c++.cpp
bcaf3a6841c2d458219d3efb1d495c0d186cda69
[]
no_license
Gurkamal2323/Data-Structures-and-Algorithms
dcfe84003458d16c358bb5b7d28d7d7b90391754
2aa353d19989108a66f10ae991b51db5f1e651a2
refs/heads/master
2021-01-10T23:54:51.221471
2016-11-19T14:23:44
2016-11-19T14:23:44
70,786,998
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
#include<iostream> using namespace std; void func() { /*definition*/ } int main() { func(); func(2); return 0; }
[ "gurkamal2323@gmail.com" ]
gurkamal2323@gmail.com
0af3244911f3596061df2f84decb9cbd8709c4ea
db628fea8fef4587a806c38e1f4cb0b45616005e
/Source/Spriter/Public/SpriterImportData.h
62a8d420fe05f78fc47811d0a4dd99f7dc12f5d6
[]
no_license
FashGek/Spriter-1
a1dd0a9546aa41c6311e96acca1b1c8cf78c8eef
5a625a65e366f2d27de6936fec1eb18eb928d090
refs/heads/master
2021-06-01T05:07:40.233449
2016-05-29T10:43:59
2016-05-29T10:43:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
871
h
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #pragma once #include "SpriterDataModel.h" //@TODO: For debug only #include "SpriterImportData.generated.h" // This is the 'hub' asset that tracks other imported assets for a rigged sprite character exported from Spriter UCLASS(BlueprintType) class SPRITER_API USpriterImportData : public UObject { GENERATED_UCLASS_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spriter") FSpriterSCON ImportedData; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Spriter") float PixelsPerUnrealUnit; // Import data for this UPROPERTY(EditAnywhere, Instanced, Category=ImportSettings) class UAssetImportData* AssetImportData; /** Override to ensure we write out the asset import data */ virtual void GetAssetRegistryTags(TArray<FAssetRegistryTag>& OutTags) const override; };
[ "jacobmaley@yahoo.com" ]
jacobmaley@yahoo.com
6fa32a1000fbffccded27efe35f782658020387b
c1eacf630af8b23852845f27d6509b4b0d5eea1b
/DataStruct/AAAAA19_0522KMP.cpp
b26a21768bed32c827009ddbb1b8eed07da72d3b
[]
no_license
GISjingjie/DataStruct
59f2408a44cdcde9b6307847267be9b7d07388f7
9bed92b9a19b09dd51479f73460b31a6b8dee464
refs/heads/master
2021-07-12T16:23:31.641629
2020-06-15T08:59:43
2020-06-15T08:59:43
146,618,934
0
0
null
null
null
null
UTF-8
C++
false
false
1,244
cpp
#include <stdio.h> #include <Stdlib.h> void PreFix(char pattern[],int prefix[],int lenP) { prefix[0]=0; int len=0; int i=1; while(i<=lenP) { if(pattern[i]==pattern[len]) { len++; prefix[i]=len; i++; }else { if(len>0) { len=prefix[len-1]; }else { prefix[i]=len; i++; } } } } void SortPreFix(int prefix[],int len) { for(int i=len;i>0;i--) { prefix[i]=prefix[i-1]; } prefix[0]=0; } int KMP(char string[],char pattern[],int prefix[],int strlen,int lenP) { int j=0; int ret=-1; for(int i=0;i<strlen&&pattern[j]!='\0';) { if(string[i]==pattern[j]) { i++; j++; ret=i; if(j==lenP) { ret-=lenP; return ret; } }else if(string[i]!=pattern[j]&&j==0) { j=prefix[j]; i++; }else { j=prefix[j]; } } return -1; } int main() { char Pattern[]="BCABCA"; int lenP=sizeof(Pattern)/sizeof(Pattern[0])-1; printf("LEP:%d\n",lenP); int prefix[lenP]; PreFix(Pattern,prefix,lenP); SortPreFix(prefix,lenP); for(int i=0;i<lenP;i++) { printf("%d\n",prefix[i]); } char String[]="ABCBCABACBCABCAAB"; int StrLen=sizeof(String)/sizeof(String[0])-1; int position=KMP(String,Pattern,prefix,StrLen,lenP); printf("Position:%d\n",position); }
[ "479309982@qq.com" ]
479309982@qq.com
37456a66ddca6d5b53a1009c6c1c424911679795
f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d
/SDK/PVR_DatasmithContent_classes.hpp
c097e0a94725264ac3f6e98b5d2f2bb523fb6be9
[]
no_license
hinnie123/PavlovVRSDK
9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b
503f8d9a6770046cc23f935f2df1f1dede4022a8
refs/heads/master
2020-03-31T05:30:40.125042
2020-01-28T20:16:11
2020-01-28T20:16:11
151,949,019
5
2
null
null
null
null
UTF-8
C++
false
false
22,670
hpp
#pragma once // PavlovVR (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class DatasmithContent.DatasmithObjectTemplate // 0x0000 (0x0028 - 0x0028) class UDatasmithObjectTemplate : public UObject { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithObjectTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithActorTemplate // 0x00A0 (0x00C8 - 0x0028) class UDatasmithActorTemplate : public UDatasmithObjectTemplate { public: unsigned char UnknownData00[0x50]; // 0x0028(0x0050) UNKNOWN PROPERTY: SetProperty DatasmithContent.DatasmithActorTemplate.Layers unsigned char UnknownData01[0x50]; // 0x0078(0x0050) UNKNOWN PROPERTY: SetProperty DatasmithContent.DatasmithActorTemplate.Tags static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithActorTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithAreaLightActor // 0x0020 (0x0348 - 0x0328) class ADatasmithAreaLightActor : public AActor { public: EDatasmithAreaLightActorShape LightShape; // 0x0328(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0329(0x0003) MISSED OFFSET struct FVector2D Dimensions; // 0x032C(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) struct FLinearColor Color; // 0x0334(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float Intensity; // 0x0344(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAreaLightActor"); return ptr; } }; // Class DatasmithContent.DatasmithAreaLightActorTemplate // 0x0028 (0x0050 - 0x0028) class UDatasmithAreaLightActorTemplate : public UDatasmithObjectTemplate { public: EDatasmithAreaLightActorShape LightShape; // 0x0028(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET struct FVector2D Dimensions; // 0x002C(0x0008) (ZeroConstructor, IsPlainOldData) struct FLinearColor Color; // 0x0034(0x0010) (ZeroConstructor, IsPlainOldData) float Intensity; // 0x0044(0x0004) (ZeroConstructor, IsPlainOldData) unsigned char bHidden : 1; // 0x0048(0x0001) unsigned char UnknownData01[0x7]; // 0x0049(0x0007) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAreaLightActorTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithAssetImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithAssetImportData : public UAssetImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAssetImportData"); return ptr; } }; // Class DatasmithContent.DatasmithStaticMeshImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithStaticMeshImportData : public UDatasmithAssetImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshImportData"); return ptr; } }; // Class DatasmithContent.DatasmithStaticMeshCADImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithStaticMeshCADImportData : public UDatasmithStaticMeshImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshCADImportData"); return ptr; } }; // Class DatasmithContent.DatasmithSceneImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithSceneImportData : public UAssetImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSceneImportData"); return ptr; } }; // Class DatasmithContent.DatasmithCADImportSceneData // 0x0000 (0x0028 - 0x0028) class UDatasmithCADImportSceneData : public UDatasmithSceneImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithCADImportSceneData"); return ptr; } }; // Class DatasmithContent.DatasmithMDLSceneImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithMDLSceneImportData : public UDatasmithSceneImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithMDLSceneImportData"); return ptr; } }; // Class DatasmithContent.DatasmithDeltaGenAssetImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithDeltaGenAssetImportData : public UDatasmithAssetImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithDeltaGenAssetImportData"); return ptr; } }; // Class DatasmithContent.DatasmithDeltaGenSceneImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithDeltaGenSceneImportData : public UDatasmithSceneImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithDeltaGenSceneImportData"); return ptr; } }; // Class DatasmithContent.DatasmithVREDAssetImportData // 0x0008 (0x0030 - 0x0028) class UDatasmithVREDAssetImportData : public UDatasmithAssetImportData { public: unsigned char UnknownData00[0x8]; // 0x0028(0x0008) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithVREDAssetImportData"); return ptr; } }; // Class DatasmithContent.DatasmithVREDSceneImportData // 0x0000 (0x0028 - 0x0028) class UDatasmithVREDSceneImportData : public UDatasmithSceneImportData { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithVREDSceneImportData"); return ptr; } }; // Class DatasmithContent.DatasmithAssetUserData // 0x0050 (0x0078 - 0x0028) class UDatasmithAssetUserData : public UAssetUserData { public: TMap<struct FName, struct FString> MetaData; // 0x0028(0x0050) (Edit, BlueprintVisible, ZeroConstructor, EditConst) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithAssetUserData"); return ptr; } }; // Class DatasmithContent.DatasmithCineCameraComponentTemplate // 0x0068 (0x0090 - 0x0028) class UDatasmithCineCameraComponentTemplate : public UDatasmithObjectTemplate { public: struct FDatasmithCameraFilmbackSettingsTemplate FilmbackSettings; // 0x0028(0x0008) (ZeroConstructor, IsPlainOldData) struct FDatasmithCameraLensSettingsTemplate LensSettings; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData) struct FDatasmithCameraFocusSettingsTemplate FocusSettings; // 0x0034(0x0008) (ZeroConstructor, IsPlainOldData) float CurrentFocalLength; // 0x003C(0x0004) (ZeroConstructor, IsPlainOldData) float CurrentAperture; // 0x0040(0x0004) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0xC]; // 0x0044(0x000C) MISSED OFFSET struct FDatasmithPostProcessSettingsTemplate PostProcessSettings; // 0x0050(0x0040) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithCineCameraComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithContentBlueprintLibrary // 0x0000 (0x0028 - 0x0028) class UDatasmithContentBlueprintLibrary : public UBlueprintFunctionLibrary { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithContentBlueprintLibrary"); return ptr; } struct FString STATIC_GetDatasmithUserDataValueForKey(class UObject* Object, const struct FName& Key); void STATIC_GetDatasmithUserDataKeysAndValuesForValue(class UObject* Object, const struct FString& StringToMatch, TArray<struct FName>* OutKeys, TArray<struct FString>* OutValues); class UDatasmithAssetUserData* STATIC_GetDatasmithUserData(class UObject* Object); }; // Class DatasmithContent.DatasmithImportOptions // 0x0060 (0x0088 - 0x0028) class UDatasmithImportOptions : public UObject { public: EDatasmithImportSearchPackagePolicy SearchPackagePolicy; // 0x0028(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportAssetConflictPolicy MaterialConflictPolicy; // 0x0029(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportAssetConflictPolicy TextureConflictPolicy; // 0x002A(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportActorPolicy StaticMeshActorImportPolicy; // 0x002B(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportActorPolicy LightImportPolicy; // 0x002C(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportActorPolicy CameraImportPolicy; // 0x002D(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportActorPolicy OtherActorImportPolicy; // 0x002E(0x0001) (ZeroConstructor, Transient, IsPlainOldData) EDatasmithImportMaterialQuality MaterialQuality; // 0x002F(0x0001) (ZeroConstructor, Transient, IsPlainOldData) unsigned char UnknownData00[0x8]; // 0x0030(0x0008) MISSED OFFSET struct FDatasmithImportBaseOptions BaseOptions; // 0x0038(0x0018) (Edit, BlueprintVisible, Config) struct FDatasmithTessellationOptions TessellationOptions; // 0x0050(0x000C) (Edit, BlueprintVisible, Config) struct FDatasmithReimportOptions ReimportOptions; // 0x005C(0x0002) (Edit, BlueprintVisible, Config) unsigned char UnknownData01[0x2A]; // 0x005E(0x002A) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithImportOptions"); return ptr; } }; // Class DatasmithContent.DatasmithLandscapeTemplate // 0x0010 (0x0038 - 0x0028) class UDatasmithLandscapeTemplate : public UDatasmithObjectTemplate { public: class UMaterialInterface* LandscapeMaterial; // 0x0028(0x0008) (ZeroConstructor, IsPlainOldData) int StaticLightingLOD; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x0034(0x0004) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithLandscapeTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithLightComponentTemplate // 0x0038 (0x0060 - 0x0028) class UDatasmithLightComponentTemplate : public UDatasmithObjectTemplate { public: unsigned char bVisible : 1; // 0x0028(0x0001) unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET unsigned char CastShadows : 1; // 0x002C(0x0001) unsigned char bUseTemperature : 1; // 0x002C(0x0001) unsigned char bUseIESBrightness : 1; // 0x002C(0x0001) unsigned char UnknownData01[0x3]; // 0x002D(0x0003) MISSED OFFSET float Intensity; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData) float Temperature; // 0x0034(0x0004) (ZeroConstructor, IsPlainOldData) float IESBrightnessScale; // 0x0038(0x0004) (ZeroConstructor, IsPlainOldData) struct FLinearColor LightColor; // 0x003C(0x0010) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData02[0x4]; // 0x004C(0x0004) MISSED OFFSET class UMaterialInterface* LightFunctionMaterial; // 0x0050(0x0008) (ZeroConstructor, IsPlainOldData) class UTextureLightProfile* IESTexture; // 0x0058(0x0008) (ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithLightComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithPointLightComponentTemplate // 0x0010 (0x0038 - 0x0028) class UDatasmithPointLightComponentTemplate : public UDatasmithObjectTemplate { public: ELightUnits IntensityUnits; // 0x0028(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET float SourceRadius; // 0x002C(0x0004) (ZeroConstructor, IsPlainOldData) float SourceLength; // 0x0030(0x0004) (ZeroConstructor, IsPlainOldData) float AttenuationRadius; // 0x0034(0x0004) (ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithPointLightComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithScene // 0x0000 (0x0028 - 0x0028) class UDatasmithScene : public UObject { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithScene"); return ptr; } }; // Class DatasmithContent.DatasmithSceneActor // 0x0058 (0x0380 - 0x0328) class ADatasmithSceneActor : public AActor { public: class UDatasmithScene* Scene; // 0x0328(0x0008) (Edit, ZeroConstructor, EditConst, IsPlainOldData) unsigned char UnknownData00[0x50]; // 0x0330(0x0050) UNKNOWN PROPERTY: MapProperty DatasmithContent.DatasmithSceneActor.RelatedActors static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSceneActor"); return ptr; } }; // Class DatasmithContent.DatasmithSceneComponentTemplate // 0x00B8 (0x00E0 - 0x0028) class UDatasmithSceneComponentTemplate : public UDatasmithObjectTemplate { public: unsigned char UnknownData00[0x8]; // 0x0028(0x0008) MISSED OFFSET struct FTransform RelativeTransform; // 0x0030(0x0030) (IsPlainOldData) TEnumAsByte<EComponentMobility> Mobility; // 0x0060(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData01[0x7]; // 0x0061(0x0007) MISSED OFFSET unsigned char UnknownData02[0x28]; // 0x0061(0x0028) UNKNOWN PROPERTY: SoftObjectProperty DatasmithContent.DatasmithSceneComponentTemplate.AttachParent unsigned char UnknownData03[0x50]; // 0x0090(0x0050) UNKNOWN PROPERTY: SetProperty DatasmithContent.DatasmithSceneComponentTemplate.Tags static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSceneComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithSkyLightComponentTemplate // 0x0010 (0x0038 - 0x0028) class UDatasmithSkyLightComponentTemplate : public UDatasmithObjectTemplate { public: TEnumAsByte<ESkyLightSourceType> SourceType; // 0x0028(0x0001) (ZeroConstructor, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0029(0x0003) MISSED OFFSET int CubemapResolution; // 0x002C(0x0004) (ZeroConstructor, IsPlainOldData) class UTextureCube* Cubemap; // 0x0030(0x0008) (ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSkyLightComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithSpotLightComponentTemplate // 0x0008 (0x0030 - 0x0028) class UDatasmithSpotLightComponentTemplate : public UDatasmithObjectTemplate { public: float InnerConeAngle; // 0x0028(0x0004) (ZeroConstructor, IsPlainOldData) float OuterConeAngle; // 0x002C(0x0004) (ZeroConstructor, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithSpotLightComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithStaticMeshComponentTemplate // 0x0020 (0x0100 - 0x00E0) class UDatasmithStaticMeshComponentTemplate : public UDatasmithSceneComponentTemplate { public: class UStaticMesh* StaticMesh; // 0x00E0(0x0008) (ZeroConstructor, IsPlainOldData) TArray<class UMaterialInterface*> OverrideMaterials; // 0x00E8(0x0010) (ZeroConstructor) unsigned char UnknownData00[0x8]; // 0x00F8(0x0008) MISSED OFFSET static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshComponentTemplate"); return ptr; } }; // Class DatasmithContent.DatasmithStaticMeshTemplate // 0x0078 (0x00A0 - 0x0028) class UDatasmithStaticMeshTemplate : public UDatasmithObjectTemplate { public: struct FDatasmithMeshSectionInfoMapTemplate SectionInfoMap; // 0x0028(0x0050) (Edit, EditConst) int LightMapCoordinateIndex; // 0x0078(0x0004) (Edit, ZeroConstructor, EditConst, IsPlainOldData) int LightMapResolution; // 0x007C(0x0004) (Edit, ZeroConstructor, EditConst, IsPlainOldData) TArray<struct FDatasmithMeshBuildSettingsTemplate> BuildSettings; // 0x0080(0x0010) (Edit, ZeroConstructor, EditConst) TArray<struct FDatasmithStaticMaterialTemplate> StaticMaterials; // 0x0090(0x0010) (Edit, ZeroConstructor, EditConst) static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class DatasmithContent.DatasmithStaticMeshTemplate"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "hsibma02@gmail.com" ]
hsibma02@gmail.com
7c853f110c1b4af4b04129942b69339d89dbae5c
44ea78720cf1fbbbb57a204d462f08ef8ccb7c42
/Others/diverta-2019/B/main.cpp
a36e8a2b0bbc116bae96a67b40e40d46caf1c333
[]
no_license
kironbot/AtCoder
854a85d55e2d3c0c8ef76589ad905af20d9c567d
4c05bf806413f5c601baa7432b9d85b102ba34b7
refs/heads/master
2021-06-29T16:14:47.667960
2020-09-27T06:17:02
2020-09-27T06:17:02
138,470,049
0
0
null
null
null
null
UTF-8
C++
false
false
642
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; const ll MOD = 1e9 + 7; const ll INF = 1LL << 60; #define rep(i, a, n) for (ll i = (a); i < (n); i++) #define debug(x) cerr << #x << ": " << x << endl; template<typename T1,typename T2> inline void chmin(T1 &a,T2 b){if(a>b) a=b;} template<typename T1,typename T2> inline void chmax(T1 &a,T2 b){if(a<b) a=b;} int main() { ll r, g, b, n; cin >> r >> g >> b >> n; ll ans = 0; rep(i, 0, n+1) { rep(j, 0, n+1) { if ((n - i*r - j*g) % b == 0 && n - i*r - j*g >= 0) ans++; else continue; } } cout << ans << endl; }
[ "sgr.araki@gmail.com" ]
sgr.araki@gmail.com
2ee0f7f4ad35a3f3a107ca8dc4096efce85bc1a4
ec2d8729d794cd682d17b5b6cf6d74c729ca2ca1
/server/PlayerInfo.h
10231437c7cb44739db064f539c77bb37f8b9576
[ "MIT" ]
permissive
Jekmant/sampvoice
640bea3aa94adf545e0027b5a49d0a02109109a4
13cab77a740d456e3ca6109c24563344312271fd
refs/heads/master
2022-11-28T15:00:12.033481
2020-08-11T18:25:34
2020-08-11T18:25:34
286,818,282
2
0
null
2020-08-11T18:23:31
2020-08-11T18:23:30
null
UTF-8
C++
false
false
707
h
/* This is a SampVoice project file Developer: CyberMor <cyber.mor.2020@gmail.ru> See more here https://github.com/CyberMor/sampvoice Copyright (c) Daniel (CyberMor) 2020 All rights reserved */ #pragma once #include <set> #include <atomic> #include <cstdint> #include "Stream.h" struct PlayerInfo { const uint8_t pluginVersion = NULL; const bool microStatus = false; std::atomic_bool muteStatus = { false }; std::atomic_bool recordStatus = { false }; std::set<Stream*> listenerStreams; std::set<Stream*> speakerStreams; std::set<uint8_t> keys; PlayerInfo( const uint8_t pluginVersion, const bool microStatus ) : pluginVersion(pluginVersion), microStatus(microStatus) {} };
[ "cyber.mor.2020@gmail.com" ]
cyber.mor.2020@gmail.com
c98d2f22f4434cebc8d40beaa9f07e6407474dba
48c78b8111787c175a1a0481d211ddac38385ae9
/src/core/FBPComponent.h
f001a2f74c6a9fbba5febbcacafad9a203017665
[]
no_license
Qt-Widgets/qcircuit
9b37feeee8f2daf61e432a2bbe251bba54fc0b9e
7bfceafbba7872890e0310e41300c70c801384ec
refs/heads/master
2021-05-27T14:11:42.766528
2014-08-29T10:26:26
2014-08-29T10:26:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,515
h
/* * File: FBPComponent.h * Author: acailly * * Created on 13 février 2014, 18:17 */ #ifndef FBPCOMPONENT_H #define FBPCOMPONENT_H #include <QtCore/QFuture> #include <QtCore/QQueue> #include <QtCore/QVariant> class FBPInputPort; class FBPOutputPort; class FBPComponentListener; class FBPComponent : public QObject { Q_OBJECT public: enum State { NOT_STARTED, ACTIVATED, FINISHED }; public: FBPComponent(QObject* parent = NULL); virtual ~FBPComponent(); FBPInputPort* addInputPort(QString name); FBPOutputPort* addOutputPort(QString name); FBPInputPort* getInputPort(QString name); FBPOutputPort* getOutputPort(QString name); bool isSelfStarting(); void setSelfStarting(bool value); bool isActive(); bool isFinished(); void wait(); void activate(); void addListener(FBPComponentListener* listener); void removeListener(FBPComponentListener* listener); protected: virtual void execute()=0; bool receive(QString name, QVariant& outData); int received(QString name); void send(QString name, QVariant value); void close(QString name); private: void execute0(); QMap<QString, FBPInputPort*> inputPorts; QMap<QString, FBPOutputPort*> outputPorts; bool selfStarting; QFuture<void> future; State state; QSet<FBPComponentListener*> listeners; }; #endif /* FBPCOMPONENT_H */
[ "acailly@itlink.fr" ]
acailly@itlink.fr
d3bc9b612d441642fa63c7850da9b818b8d6bda7
b11b140ef2fbb3e3e2d0eb53fdbe4c8943ad5ebb
/NorthMultiUnivTrain/week2_codeheaven/G/g.cpp
40d422a15c3ca0b062eb85af1f00e78c75a6dd51
[]
no_license
jer22/OI
ea953208ab43542c51eada3c62ef529a6c14588e
545c2424f277a6626b0f22fb666edd8c37e7328b
refs/heads/master
2021-04-18T22:57:05.678732
2017-11-02T15:40:34
2017-11-02T15:40:34
27,431,322
1
0
null
null
null
null
UTF-8
C++
false
false
1,465
cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 100005; bool pri[1000005]; int p[1000005], num = 0, tot = 0; int fa[MAXN], pos[1000005]; int minfac[1000005]; int fin(int p) { if (p == fa[p]) return p; return fa[p] = fin(fa[p]); } void un(int a, int b) { fa[fin(a)] = fin(b); } void init() { for (int i = 2; i <= 1000000; i++) { if (!pri[i]) { minfac[i] = i; p[++num] = i; pos[i] = num; } for (int j = 1; j <= num; j++) { if(i * p[j] > 1000000) break; pri[i * p[j]] = 1; minfac[p[j] * i] = p[j]; } } // for (int i = 2; i <= 1000000; i++) { // int x = i; // while (x > 1) { // int t = minfac[x]; // fac[i].push_back(t); // while (!(x % t)) x /= t; // } // } } bool vis[MAXN], vv[MAXN]; int main() { freopen("g.in", "r", stdin); // freopen("out", "w", stdout); init(); int T, n; scanf("%d", &T); for (int cas = 1; cas <= T; cas++) { scanf("%d", &n); for (int i = 1; i <= num; i++) { vis[i] = vv[i] = 0; fa[i] = i; } int ans = 0; int x; for (int i = 1; i <= n; i++) { scanf("%d", &x); if (x == 1) ans++; int pre = 0; while (x > 1) { int t = minfac[x]; vis[pos[t]] = 1; if (pre) { un(pre, pos[t]); } pre = pos[t]; while (!(x % t)) x /= t; } } for (int i = 1; i <= num; i++) { if (!vis[i]) continue; int p = fin(i); if (!vv[p]) { ans++; vv[p] = 1; } } printf("Case %d: %d\n", cas, ans); } return 0; }
[ "shijieyywd@gmail.com" ]
shijieyywd@gmail.com
a729705b8f52d4018319078d29777673ee5f801f
ca780c75c1e7339ee2cc8802b18c48cf70f10172
/re2c/src/dfa/cfg/freeze.cc
926089d306f59173f533e85e3997add86ae5ae2c
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
gkantsidis/re2c
b8f793c727dc4cb96ef12d862e687afdeb9fc3b3
8a82ee027744a3a21ae45c70ace0d5076cf591a8
refs/heads/master
2021-05-04T13:25:42.903156
2018-02-06T14:34:06
2018-02-06T14:34:06
120,313,604
1
0
null
2018-02-05T14:12:48
2018-02-05T14:12:48
null
UTF-8
C++
false
false
1,297
cc
#include <stddef.h> #include <vector> #include "src/dfa/dfa.h" #include "src/dfa/tcmd.h" namespace re2c { /* note [tag freezing] * * Comparison of tag commands should be very fast (constant time): * many optimizations rely on this (like tunnelling, hoisting and * especially Moore's minimization, which compares whole classes * of tagged transition at once). So we bring each command to some * 'normal form' and insert it into common index. * * After that commands can be addressed and compared by index. * They also become immutable, because different commands may * share representation in memory. */ void freeze_tags(dfa_t &dfa) { tcpool_t &pool = dfa.tcpool; const size_t nstate = dfa.states.size(), nsym = dfa.nchars; dfa.tcid0 = pool.insert(dfa.tcmd0); dfa.tcmd0 = NULL; for (size_t i = 0; i < nstate; ++i) { dfa_state_t *s = dfa.states[i]; tcmd_t **cmd = s->tcmd, **const fin = cmd + nsym, **const fall = fin + 1; tcid_t *id = s->tcid = new tcid_t[nsym + 2]; // transition commands for(; cmd < fin; ++cmd) { *id++ = pool.insert(*cmd); } // final epsilon-transition command *id++ = pool.insert(*fin); // fallback epsilon-transition command *id++ = pool.insert(*fall); delete[] s->tcmd; s->tcmd = NULL; } } } // namespace re2c
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
045bba8865b28a03fc13eec6073dcd016095db9f
3cd4cc83515c335728b7c16e7610f25dd8e087fe
/examples/Examples/Chap05/5.3_ImageResliceExample2.cpp
bbb429a1daa733dfd34c92b01c4c6f23f397fc06
[]
no_license
liuyaoxinneo/VTK
a223cf1f05639299ce6afae23c19d2989d55578b
90dc403896aef1ba828e413950e4ffe3ab041eb6
refs/heads/master
2021-05-08T08:02:22.252992
2017-10-15T13:55:37
2017-10-15T13:55:37
106,976,917
1
1
null
null
null
null
GB18030
C++
false
false
5,889
cpp
/********************************************************************** 文件名: 5.3_ImageResliceExample2.cpp Copyright (c) 张晓东, 罗火灵. All rights reserved. 更多信息请访问: http://www.vtkchina.org (VTK中国) http://blog.csdn.net/www_doling_net (东灵工作室) **********************************************************************/ #include <vtkSmartPointer.h> #include <vtkImageReader2.h> #include <vtkMatrix4x4.h> #include <vtkImageReslice.h> #include <vtkLookupTable.h> #include <vtkImageMapToColors.h> #include <vtkImageActor.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkInteractorStyleImage.h> #include <vtkCommand.h> #include <vtkImageData.h> #include <vtkMetaImageReader.h> #include <vtkImageCast.h> class vtkImageInteractionCallback : public vtkCommand { public: static vtkImageInteractionCallback *New() { return new vtkImageInteractionCallback; } vtkImageInteractionCallback() { this->Slicing = 0; this->ImageReslice = 0; this->Interactor = 0; } void SetImageReslice(vtkImageReslice *reslice) { this->ImageReslice = reslice; } vtkImageReslice *GetImageReslice() { return this->ImageReslice; } void SetInteractor(vtkRenderWindowInteractor *interactor) { this->Interactor = interactor; } vtkRenderWindowInteractor *GetInteractor() { return this->Interactor; } virtual void Execute(vtkObject *, unsigned long event, void *) { vtkRenderWindowInteractor *interactor = this->GetInteractor(); int lastPos[2]; interactor->GetLastEventPosition(lastPos); int currPos[2]; interactor->GetEventPosition(currPos); if (event == vtkCommand::LeftButtonPressEvent) { this->Slicing = 1; } else if (event == vtkCommand::LeftButtonReleaseEvent) { this->Slicing = 0; } else if (event == vtkCommand::MouseMoveEvent) { if (this->Slicing) { vtkImageReslice *reslice = this->ImageReslice; // Increment slice position by deltaY of mouse int deltaY = lastPos[1] - currPos[1]; reslice->Update(); double sliceSpacing = reslice->GetOutput()->GetSpacing()[2]; vtkMatrix4x4 *matrix = reslice->GetResliceAxes(); // move the center point that we are slicing through double point[4]; double center[4]; point[0] = 0.0; point[1] = 0.0; point[2] = sliceSpacing * deltaY; point[3] = 1.0; matrix->MultiplyPoint(point, center); matrix->SetElement(0, 3, center[0]); matrix->SetElement(1, 3, center[1]); matrix->SetElement(2, 3, center[2]); //printf("%f %f %f\n", center[0], center[1], center[2]); interactor->Render(); } else { vtkInteractorStyle *style = vtkInteractorStyle::SafeDownCast( interactor->GetInteractorStyle()); if (style) { style->OnMouseMove(); } } } } private: int Slicing; vtkImageReslice *ImageReslice; vtkRenderWindowInteractor *Interactor; }; int main() { vtkSmartPointer<vtkMetaImageReader> reader = vtkSmartPointer<vtkMetaImageReader>::New(); reader->SetFileName ( "..\\data\\brain.mhd" ); reader->Update(); int extent[6]; double spacing[3]; double origin[3]; reader->GetOutput()->GetExtent(extent); reader->GetOutput()->GetSpacing(spacing); reader->GetOutput()->GetOrigin(origin); double center[3]; center[0] = origin[0] + spacing[0] * 0.5 * (extent[0] + extent[1]); center[1] = origin[1] + spacing[1] * 0.5 * (extent[2] + extent[3]); center[2] = origin[2] + spacing[2] * 0.5 * (extent[4] + extent[5]); static double axialElements[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; vtkSmartPointer<vtkMatrix4x4> resliceAxes = vtkSmartPointer<vtkMatrix4x4>::New(); resliceAxes->DeepCopy(axialElements); resliceAxes->SetElement(0, 3, center[0]); resliceAxes->SetElement(1, 3, center[1]); resliceAxes->SetElement(2, 3, center[2]); vtkSmartPointer<vtkImageReslice> reslice = vtkSmartPointer<vtkImageReslice>::New(); reslice->SetInputConnection(reader->GetOutputPort()); reslice->SetOutputDimensionality(2); reslice->SetResliceAxes(resliceAxes); reslice->SetInterpolationModeToLinear(); vtkSmartPointer<vtkLookupTable> colorTable = vtkSmartPointer<vtkLookupTable>::New(); colorTable->SetRange(0, 1000); colorTable->SetValueRange(0.0, 1.0); colorTable->SetSaturationRange(0.0, 0.0); colorTable->SetRampToLinear(); colorTable->Build(); vtkSmartPointer<vtkImageMapToColors> colorMap = vtkSmartPointer<vtkImageMapToColors>::New(); colorMap->SetLookupTable(colorTable); colorMap->SetInputConnection(reslice->GetOutputPort()); vtkSmartPointer<vtkImageActor> imgActor = vtkSmartPointer<vtkImageActor>::New(); imgActor->SetInput(colorMap->GetOutput()); vtkSmartPointer<vtkRenderer> renderer = vtkSmartPointer<vtkRenderer>::New(); renderer->AddActor(imgActor); renderer->SetBackground(.4, .5, .6); vtkSmartPointer<vtkRenderWindow> renderWindow = vtkSmartPointer<vtkRenderWindow>::New(); renderWindow->SetSize(500, 500); renderWindow->AddRenderer(renderer); vtkSmartPointer<vtkRenderWindowInteractor> renderWindowInteractor = vtkSmartPointer<vtkRenderWindowInteractor>::New(); vtkSmartPointer<vtkInteractorStyleImage> imagestyle = vtkSmartPointer<vtkInteractorStyleImage>::New(); renderWindowInteractor->SetInteractorStyle(imagestyle); renderWindowInteractor->SetRenderWindow(renderWindow); renderWindowInteractor->Initialize(); vtkSmartPointer<vtkImageInteractionCallback> callback = vtkSmartPointer<vtkImageInteractionCallback>::New(); callback->SetImageReslice(reslice); callback->SetInteractor(renderWindowInteractor); imagestyle->AddObserver(vtkCommand::MouseMoveEvent, callback); imagestyle->AddObserver(vtkCommand::LeftButtonPressEvent, callback); imagestyle->AddObserver(vtkCommand::LeftButtonReleaseEvent, callback); renderWindowInteractor->Start(); return EXIT_SUCCESS; }
[ "neo19941120@hotmail.com" ]
neo19941120@hotmail.com
295cdc5f8e03f5692c59cc131f64cb2a95697a8b
d0eb64e4aabebdc2fac7a3284e363bf82639e18e
/sketches/vlqp/enemies.cpp
659e7826ff3bc2ad621b9f5769cdf69eea7fa888
[]
no_license
dspig/arduboy-for-pc
a07ebe6814b19780cc94ea419bf0a99fdc1a2d15
a4ac47bb22da367e373232589f0c516f1300d3ba
refs/heads/master
2021-06-15T22:03:36.157382
2016-04-12T18:57:25
2016-04-12T18:57:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,982
cpp
#include "enemies.h" #include "player.h" #include "pickup.h" // globals /////////////////////////////////////////////////////////////////// Enemy zombies[ZOMBIE_MAX]; // method implementations //////////////////////////////////////////////////// // setZombie // sets the position of a zombie, and enables that instance void setZombie(Enemy& obj, int x, int y) { obj.frame = 0; obj.active = true; obj.direction = ENEMY_FACING_WEST; obj.x = x; obj.y = y; obj.health = 2; obj.flashTime = 0; } // spawnZombie // adds a zombie in a random place in the map // returns true if success, false if failure bool spawnZombie() { int x = random(16, LEVEL_WIDTH-ZOMBIE_WIDTH-16); int y = random(16, LEVEL_HEIGHT-ZOMBIE_HEIGHT-16); if((x < coolGirl.x - WIDTH) || (x > coolGirl.x + WIDTH) || (y < coolGirl.y - HEIGHT) || (y > coolGirl.y + HEIGHT)) { return addZombie(x, y); } return false; } // addZombie // searches the zombies list for an empty slot, adds one if available // returns true if successful, false otherwise bool addZombie(int x, int y) { byte id; for(id=0; id<ZOMBIE_MAX; id++) { if(!zombies[id].active) { setZombie(zombies[id], x, y); return true; break; } } return false; } // updateZombie // updates the zombie according to game rules // zombies are "removed" (set inactive) when health reaches zero void updateZombie(Enemy& obj) { char vx = 0; char vy = 0; if (arduboy.everyXFrames(ZOMBIE_STEP_DELAY)) { /////////// // input // /////////// // chase player if(obj.x < coolGirl.x) vx = ZOMBIE_SPEED; if(obj.x > coolGirl.x) vx = -ZOMBIE_SPEED; if(obj.y < coolGirl.y) vy = ZOMBIE_SPEED; if(obj.y > coolGirl.y) vy = -ZOMBIE_SPEED; // if out of bounds, delete this if((obj.x < 0) || (obj.y < 0) || (obj.x >= LEVEL_WIDTH) || (obj.y >= LEVEL_HEIGHT)) { obj.active = false; return; } // update orientation if(vx < 0) obj.direction = ENEMY_FACING_WEST; else if(vx > 0) obj.direction = ENEMY_FACING_EAST; //////////////////////// // horizontal physics // //////////////////////// // update position obj.x += vx; // collide with other zombies zombieCollide(obj.x, obj.y, true, vx, ZOMBIE_WIDTH, ZOMBIE_HEIGHT); // collide with player if(zombieCollision(obj, coolGirl.x, coolGirl.y, PLAYER_WIDTH, PLAYER_HEIGHT)) { if(vx > 0) obj.x = coolGirl.x - ZOMBIE_WIDTH; else if(vx < 0) obj.x = coolGirl.x + PLAYER_WIDTH; playerHealthOffset(coolGirl, -1); vx = 0; } // collide with walls mapCollide(obj.x, obj.y, true, vx, ZOMBIE_WIDTH, ZOMBIE_HEIGHT); ////////////////////// // vertical physics // ////////////////////// // update position obj.y += vy; // collide with other zombies zombieCollide(obj.x, obj.y, false, vy, ZOMBIE_WIDTH, ZOMBIE_HEIGHT); // collide with player if(zombieCollision(obj, coolGirl.x, coolGirl.y, PLAYER_WIDTH, PLAYER_HEIGHT)) { if(vy > 0) obj.y = coolGirl.y - ZOMBIE_HEIGHT; else if(vy < 0) obj.y = coolGirl.y + PLAYER_HEIGHT; playerHealthOffset(coolGirl, -1); vy = 0; } // collide with walls mapCollide(obj.x, obj.y, false, vy, ZOMBIE_WIDTH, ZOMBIE_HEIGHT); /////////////// // animation // /////////////// if(vx || vy) { // Advance animation frame if (arduboy.everyXFrames(ZOMBIE_FRAME_SKIP)) obj.frame++; // Just 4 frames if (obj.frame >= ZOMBIE_FRAME_COUNT ) obj.frame = 0; } else { obj.frame = 0; } } if(obj.health == 0) { obj.active = false; } } // updateZombies // updates every active zombie in the list void updateZombies() { byte i; for(i=0; i<ZOMBIE_MAX; i++) { if(!zombies[i].active) continue; updateZombie(zombies[i]); } } /* void drawZombieBlips() { short drawX, drawY; byte id; for(id=0; id<ZOMBIE_MAX; id++) { if(!zombies[id].active) continue; drawX = zombies[id].x - mapPositionX; drawY = zombies[id].y - mapPositionY; byte drawColor = (arduboy.frameCount % 16) < 8; if(drawX < 0 && drawX > -WIDTH/2) { arduboy.drawPixel(1, drawY + ZOMBIE_HEIGHT/2, drawColor); arduboy.drawPixel(1, drawY + ZOMBIE_HEIGHT/2+1, drawColor); arduboy.drawPixel(2, drawY + ZOMBIE_HEIGHT/2, drawColor); arduboy.drawPixel(2, drawY + ZOMBIE_HEIGHT/2+1, drawColor); } else if(drawX > WIDTH && drawX < WIDTH/2+WIDTH) { arduboy.drawPixel(WIDTH-1, drawY + ZOMBIE_HEIGHT/2, drawColor); arduboy.drawPixel(WIDTH-1, drawY + ZOMBIE_HEIGHT/2+1, drawColor); arduboy.drawPixel(WIDTH-2, drawY + ZOMBIE_HEIGHT/2, drawColor); arduboy.drawPixel(WIDTH-2, drawY + ZOMBIE_HEIGHT/2+1, drawColor); } else if(drawY < 0 && drawY > -HEIGHT/2) { arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2, 1, drawColor); arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2+1, 1, drawColor); arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2, 2, drawColor); arduboy.drawPixel(drawX + ZOMBIE_WIDTH/2+1, 2, drawColor); } else if(drawY > HEIGHT && drawY < HEIGHT/2+HEIGHT) { arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2, HEIGHT-1, drawColor); arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2+1, HEIGHT-1, drawColor); arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2, HEIGHT-2, drawColor); arduboy.drawPixel(drawX + ZOMBIE_HEIGHT/2+1, HEIGHT-2, drawColor); } } } */ // drawZombie // draws a single zombie void drawZombie(Enemy& obj) { short drawX, drawY; if(obj.active) { if(obj.flashTime > 0) { obj.flashTime--; } if((obj.flashTime % 4) < 2) { drawX = obj.x - mapPositionX; drawY = obj.y - mapPositionY; sprites.drawPlusMask(drawX, drawY, zombie_plus_mask, obj.frame + 8*obj.direction); } } else if(obj.flashTime > 0) { obj.flashTime--; arduboy.drawCircle(obj.x - mapPositionX + ZOMBIE_WIDTH/2, obj.y - mapPositionY + ZOMBIE_HEIGHT/2, 12 - obj.flashTime*2, 1); } } // drawZombies // draws every active zombie in the zombie list void drawZombies() { byte id; // Draw all the zombies! for (id=0; id<ZOMBIE_MAX; id++) { drawZombie(zombies[id]); } } // zombieHealthOffset // takes a value to be added to zombie health // kills the zombie if health goes below zero bool zombieHealthOffset(Enemy& obj, char amount) { obj.health += amount; // killed if(obj.health <= 0) { arduboy.tunes.tone(220, 20); obj.flashTime = ZOMBIE_FLASH_TIME; obj.active = false; rollingScore += 100; addPickup(obj.x + 4, obj.y + 4); } else if(amount < 0) { obj.flashTime = ZOMBIE_FLASH_TIME; arduboy.tunes.tone(640, 20); } } // zombieCollision // takes zombie id, collision box to test against // returns true if collision boxes intersect bool zombieCollision(Enemy& obj, int x, int y, char w, char h) { return ( obj.active ) && ( obj.x < x+w ) && ( obj.x + ZOMBIE_WIDTH > x ) && ( obj.y < y+h ) && ( obj.y + ZOMBIE_HEIGHT > y ); } // clearZombies // clears the entire list of zombies void clearZombies() { byte id; for(id=0; id<ZOMBIE_MAX; id++) { zombies[id].active = false; } } void zombieCollide(int &x, int &y, bool horizontal, char &vel, char w, char h) { byte id; for(id=0; id<ZOMBIE_MAX; id++) { if(zombieCollision(zombies[id], x, y, w, h)) { if(x == zombies[id].x && y == zombies[id].y) continue; if(horizontal) { if(vel > 0) x = zombies[id].x - w; else if(vel < 0) x = zombies[id].x + ZOMBIE_WIDTH; } else { if(vel > 0) y = zombies[id].y - h; else if(vel < 0) y = zombies[id].y + ZOMBIE_HEIGHT; } vel = 0; } } }
[ "info@JO3RI.be" ]
info@JO3RI.be
2941abc0c960bb70b6bf1533aaa04676862b6e26
eafc52e8480fbc2021e2480235b14843b6682b10
/src/main.cpp
9bdd64dbbeffd03559a03c88e168844ef9a5dcda
[ "MIT" ]
permissive
grand151/esp32-laser-show
22e0a19354ccc6423b129c1910c9ffe2731b73d4
0aa26b065101aa4ef93a5ba2202d0c6c1671cb44
refs/heads/main
2023-06-26T09:21:55.779652
2021-07-26T12:16:31
2021-07-26T12:16:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,532
cpp
#include <stdio.h> #include <string.h> #include "esp_err.h" #include "esp_log.h" #include "esp_spiffs.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include <arpa/inet.h> #include <vector> #include "ILDAFile.h" #include "SPIRenderer.h" static const char *TAG = "main"; extern "C" { void app_main(void); } static const char *files[] = { "/spiffs/Xwing.ild.gz", "/spiffs/LemmTumble.ild.gz", "/spiffs/Vader.ild.gz", "/spiffs/Enterprise2.ild.gz"}; static const int num_files = 4; void app_main() { vTaskDelay(2000 / portTICK_PERIOD_MS); esp_vfs_spiffs_conf_t conf = { .base_path = "/spiffs", .partition_label = NULL, .max_files = 5, .format_if_mount_failed = false}; esp_err_t ret = esp_vfs_spiffs_register(&conf); if (ret != ESP_OK) { if (ret == ESP_FAIL) { ESP_LOGE(TAG, "Failed to mount or format filesystem"); } else if (ret == ESP_ERR_NOT_FOUND) { ESP_LOGE(TAG, "Failed to find SPIFFS partition"); } else { ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret)); } return; } // read all the files in std::vector<ILDAFile *> ilda_files; for (int i = 0; i < num_files; i++) { ILDAFile *ilda = new ILDAFile(); ilda->read(files[i]); ilda_files.push_back(ilda); } esp_vfs_spiffs_unregister(NULL); SPIRenderer *renderer = new SPIRenderer(ilda_files); renderer->start(); // run forever while (true) { vTaskDelay(600000 / portTICK_PERIOD_MS); } }
[ "chris@cmgresearch.com" ]
chris@cmgresearch.com
31f9d57023e4d1b176c49ed6335064aabfb3470d
0b3aad9b8519368712217328f5909d1f944f466b
/Map.h
01c5660c631092a5dab8d4be82043d5d998d064e
[]
no_license
CCA-Programs/RPG.txt
729e4aa938ba6e969348bfb340bcd3181fc37df1
5a0d0c0d94182944c085833d15770cc4c97b37bc
refs/heads/master
2020-12-24T10:54:55.878903
2016-11-11T19:12:31
2016-11-11T19:12:31
73,122,562
1
2
null
null
null
null
UTF-8
C++
false
false
1,034
h
#ifndef MAP_H #define MAP_H #include<vector> using namespace std; //Last modified by Todd Selwitz //This header file defines the map that the character traverses. //The vector holds the positions, and the enumerator determines what is on that square. //EMPTY means that that square is not walkable, has no traps. //OK means that the square is walkable and has no traps //WALL implies the square is not walkable (different from EMPTY?) //DOOR represents a link to another level or another part of the same level //WATER could be used for fishing, healing, etc. (undetermined for now) //LAVA steadily causes damage over time. //TRAP has a one-time hazard (could be level dependent) //ENEMY starts an "enemy" event enum FLOOR_STATE {EMPTY, OK, WALL, DOOR, WATER, LAVA, TRAP, ENEMY} //Types of floor tiles ("OK" means //the tile is walkable and has no traps class Map{ private: vector <vector<int> > map; //holds all positions on the map. int character_pos; //holds the character location }; #endif
[ "selwitz.todd@gmail.com" ]
selwitz.todd@gmail.com
2ce777b89e1823ff0e88ebc2f7df46328471a6ff
4bebe4f1116f59c3ad8075580ab03a4e2c1a561e
/code_caffe-rc3_fvmtl_ccelc/include/caffe/layers/sigmoid_cross_entropyNeg_loss_layer.hpp
f53b8b23df54d10c95fe63961dff7b000ceff2c9
[ "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "BSD-3-Clause" ]
permissive
markatopoulou/fvmtl-ccelc
2f74d68e3fee9bd516fce24604da5044acebde6c
4c6e0ac2e4c0cc6181f0836151a871bbff257ddb
refs/heads/master
2020-03-20T05:25:08.515265
2018-06-13T13:17:44
2018-06-13T13:17:44
137,213,724
3
0
null
null
null
null
UTF-8
C++
false
false
4,670
hpp
#ifndef CAFFE_SIGMOID_CROSS_ENTROPYNEG_LOSS_LAYER_HPP_ #define CAFFE_SIGMOID_CROSS_ENTROPYNEG_LOSS_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/layers/loss_layer.hpp" #include "caffe/layers/sigmoidNeg_layer.hpp" namespace caffe { /** * @brief Computes the cross-entropy (logistic) loss @f$ * E = \frac{-1}{n} \sum\limits_{n=1}^N \left[ * p_n \log \hat{p}_n + * (1 - p_n) \log(1 - \hat{p}_n) * \right] * @f$, often used for predicting targets interpreted as probabilities. * * This layer is implemented rather than separate * SigmoidLayer + CrossEntropyLayer * as its gradient computation is more numerically stable. * At test time, this layer can be replaced simply by a SigmoidLayer. * * @param bottom input Blob vector (length 2) * -# @f$ (N \times C \times H \times W) @f$ * the scores @f$ x \in [-\infty, +\infty]@f$, * which this layer maps to probability predictions * @f$ \hat{p}_n = \sigma(x_n) \in [0, 1] @f$ * using the sigmoid function @f$ \sigma(.) @f$ (see SigmoidLayer). * -# @f$ (N \times C \times H \times W) @f$ * the targets @f$ y \in [0, 1] @f$ * @param top output Blob vector (length 1) * -# @f$ (1 \times 1 \times 1 \times 1) @f$ * the computed cross-entropy loss: @f$ * E = \frac{-1}{n} \sum\limits_{n=1}^N \left[ * p_n \log \hat{p}_n + (1 - p_n) \log(1 - \hat{p}_n) * \right] * @f$ */ template <typename Dtype> class SigmoidCrossEntropyNegLossLayer : public LossLayer<Dtype> { public: explicit SigmoidCrossEntropyNegLossLayer(const LayerParameter& param) : LossLayer<Dtype>(param), sigmoid_layer_(new SigmoidNegLayer<Dtype>(param)), sigmoid_output_(new Blob<Dtype>()) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "SigmoidCrossEntropyNegLoss"; } protected: /// @copydoc SigmoidCrossEntropyNegLossLayer virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); /** * @brief Computes the sigmoid cross-entropy loss error gradient w.r.t. the * predictions. * * Gradients cannot be computed with respect to the target inputs (bottom[1]), * so this method ignores bottom[1] and requires !propagate_down[1], crashing * if propagate_down[1] is set. * * @param top output Blob vector (length 1), providing the error gradient with * respect to the outputs * -# @f$ (1 \times 1 \times 1 \times 1) @f$ * This Blob's diff will simply contain the loss_weight* @f$ \lambda @f$, * as @f$ \lambda @f$ is the coefficient of this layer's output * @f$\ell_i@f$ in the overall Net loss * @f$ E = \lambda_i \ell_i + \mbox{other loss terms}@f$; hence * @f$ \frac{\partial E}{\partial \ell_i} = \lambda_i @f$. * (*Assuming that this top Blob is not used as a bottom (input) by any * other layer of the Net.) * @param propagate_down see Layer::Backward. * propagate_down[1] must be false as gradient computation with respect * to the targets is not implemented. * @param bottom input Blob vector (length 2) * -# @f$ (N \times C \times H \times W) @f$ * the predictions @f$x@f$; Backward computes diff * @f$ \frac{\partial E}{\partial x} = * \frac{1}{n} \sum\limits_{n=1}^N (\hat{p}_n - p_n) * @f$ * -# @f$ (N \times 1 \times 1 \times 1) @f$ * the labels -- ignored as we can't compute their error gradients */ virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); //virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, // const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); /// The internal SigmoidLayer used to map predictions to probabilities. shared_ptr<SigmoidNegLayer<Dtype> > sigmoid_layer_; /// sigmoid_output stores the output of the SigmoidLayer. shared_ptr<Blob<Dtype> > sigmoid_output_; /// bottom vector holder to call the underlying SigmoidLayer::Forward vector<Blob<Dtype>*> sigmoid_bottom_vec_; /// top vector holder to call the underlying SigmoidLayer::Forward vector<Blob<Dtype>*> sigmoid_top_vec_; }; } // namespace caffe #endif // CAFFE_SIGMOID_CROSS_ENTROPYNEG_LOSS_LAYER_HPP_
[ "markatopoulou@iti.gr" ]
markatopoulou@iti.gr
c27f59de03510ad17d140860da30230b8b27b6eb
1495647af9e5941772ab7d383b4cf78cdb0fb77f
/Graph/Home/adjacency_matrix.cpp
0b9ea70df2b8595ecb16f8d89543555a07c2ece1
[]
no_license
Imran4424/Data-Structure
aa7e33b567406dd9bf25be7cc35d72f0cee761a9
9b6b8e5367849e133aa437040946794db63399b1
refs/heads/master
2022-04-07T12:47:23.894934
2022-02-10T16:13:12
2022-02-10T16:13:12
124,618,740
4
2
null
null
null
null
UTF-8
C++
false
false
1,988
cpp
#include <iostream> #include <iomanip> using namespace std; /// adjacency matrix of fig 8.3 of example 8.3 int main() { int n,i,j,sum,k; cout<<"Number of nodes"<<endl; cin>>n; int mat[n][n],mat2[n][n],mat3[n][n],mat4[n][n],B[n][n]; cout<<"Input your adjacency matrix"<<endl; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cin>>mat[i][j]; } } cout<<endl<<"mat:"<<endl<<endl; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<setw(2)<<mat[i][j]<<" "; } cout<<endl; } for(i=0;i<n;i++){ for(j=0;j<n;j++){ sum = 0; for(k=0;k<n;k++){ sum += mat[i][k]*mat[k][j]; } mat2[i][j] = sum; } } cout<<endl<<"mat2:"<<endl<<endl; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<setw(2)<<mat2[i][j]<<" "; } cout<<endl; } for(i=0;i<n;i++){ for(j=0;j<n;j++){ sum = 0; for(k=0;k<n;k++){ sum += mat2[i][k]*mat[k][j]; } mat3[i][j] = sum; } } cout<<endl<<"mat3:"<<endl<<endl; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<setw(2)<<mat3[i][j]<<" "; } cout<<endl; } for(i=0;i<n;i++){ for(j=0;j<n;j++){ sum = 0; for(k=0;k<n;k++){ sum += mat3[i][k]*mat[k][j]; } mat4[i][j] = sum; } } cout<<endl<<"mat4:"<<endl<<endl; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<setw(2)<<mat4[i][j]<<" "; } cout<<endl; } for(i=0;i<n;i++){ for(j=0;j<n;j++){ B[i][j] = (mat[i][j]+ mat2[i][j]+ mat3[i][j]+ mat4[i][j]); } } cout<<endl<<"B:"<<endl<<endl; for(i=0;i<n;i++){ for(j=0;j<n;j++){ cout<<setw(2)<<B[i][j]<<" "; } cout<<endl; } return 0; }
[ "akashganga.programming.534363@gmail.com" ]
akashganga.programming.534363@gmail.com
b223ffeb28765d7c2cc2a3b372731d8abbfacfdb
03151cea816f33416b5cbb6356d875bf9ccf732a
/oled.cpp
d20faccfa3d7829c3918936704c9fec49a9064a4
[]
no_license
HybridAir/pndt_v1
f59e720d76d92625bdecfc0d640c05e57a06d22e
371e976acfa1b1267b7de502f85859be3c4be572
refs/heads/master
2021-03-12T22:46:34.769004
2014-12-13T14:46:03
2014-12-13T14:46:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,261
cpp
//handles the main hardware display related operations #include "oled.h" extern settings set; extern menus menu; extern io inout; //extern rtcTime time; extern Adafruit_SSD1306 display; extern pages page; extern pageBatt batt; //function that is called all the time in main to update the display //"page" functionality //page/mode selection menu //scrolling text announcement page, home screen clock data thing, battery/charge, settings, games, power warnings //Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS); oled::oled() { display.setTextSize(4); display.setTextColor(WHITE); display.setTextWrap(false); } void oled::begin() { display.begin(SSD1306_SWITCHCAPVCC); //turn the display on display.display(); //show the splash screen //prepare the startup timer unsigned long previousMillis = millis(); unsigned long currentMillis = 0; while(currentMillis < previousMillis + 2000) { //while we're waiting for 1 second to elapse currentMillis = millis(); //keep checking the time //stabilize the temperature and battery levels so they're correct inout.processTmp(true); inout.processBatt(true); //also give the user some time to view the splash screen } display.clearDisplay(); batt.powerCheck(); //need to check the battery and display any priority warnings } void oled::dispMon() { //there's going to be stuff in here okay //first line is always going to clear the display //next lines are going to go through each page to see what needs displaying //each page will add it's stuff if necessary //after that there will be some other "functions" that might need displaying //includes the button bar and probably battery warnings //last line is a display.display display.clearDisplay(); batt.powerCheck(); if(set.getMenu()) { //check if the menu needs to be displayed menu.doMain(); //do the main menu page } else { page.doPage(); //the menu isn't open, resume normal operation } display.display(); } void oled::drawBtnBar(char left, String center, char right) { display.drawFastHLine(0, 55, SSD1306_LCDWIDTH, WHITE); //draw the separator line display.setTextSize(1); //left display.fillTriangle(8, 56, 16, 56, 8, 64, WHITE); //left side designy stuff display.fillRect(0, 56, 8, 8, WHITE); display.setTextColor(BLACK); //print out the left indicator character, and "bold" it display.setCursor(2, 56); display.print(left); display.setCursor(3, 56); display.print(left); //center display.setTextColor(WHITE); centerText(57, 1, center); //right display.fillTriangle(112, 56, 120, 56, 120, 64, WHITE); //right side designy stuff display.fillRect(120, 56, 8, 8, WHITE); display.setTextColor(BLACK); //print out the right indicator character, and "bold" it display.setCursor(121, 56); display.print(right); display.setCursor(120, 56); display.print(right); } void oled::centerText(byte y, byte size, String in) { byte textSize = (in.length() * 6) * size; //24px 4 chars //byte out = (SSD1306_LCDWIDTH - textSize)/2; display.setTextSize(size); display.setCursor((SSD1306_LCDWIDTH - textSize)/2, y); display.print(in); } void oled::showTitle(String in) { display.setTextColor(WHITE); centerText(0, 1, in); display.drawFastHLine(0, 8, SSD1306_LCDWIDTH, WHITE); } byte oled::extractD0(byte input) { //extracts the digit in the tens place return input / 10; } byte oled::extractD1(byte input) { //extracts the digit in the ones place return input - (extractD0(input) * 10); }
[ "s.tratton.blake@gmail.com" ]
s.tratton.blake@gmail.com
67192cb9533fab6d2210b70d28c843fcf0bd2ae0
2df690d1f8a617e016f00911fe9aa8d4e83949a3
/dsp/rrc_compute.cpp
e840c75077ae1ad6cf00a24191599945d477532a
[ "MIT" ]
permissive
kb3gtn/kb3gtn_sdr
60aeb83696261c857ebe05b7c590f4e5b1053f1f
384c2ea7c778cd0ddbf355a705a19cbf08725d4e
refs/heads/master
2020-04-09T16:42:54.435094
2018-12-17T00:43:13
2018-12-17T00:43:13
160,460,690
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
cpp
#include <cmath> #include <iostream> #include <vector> #include <algorithm> using namespace std; std::vector<double> computeRRC(double sps, double a, double d); int main() { cout << "computing RRC response for:\n"; double sps = 4; cout << " samples/symbol => " << sps << "\n"; double a = 0.35; cout << " rolloff (a) => " << a << "\n"; double d = 4; cout << " duration (d) => " << -1.0*d << "-> +" << d << "\n"; std::vector<double> coeff = computeRRC( sps, a, d ); std::cout << "Number of Taps computed: " << coeff.size() << "\n"; std::cout << "Coefficents calculated:\n"; for (auto &c: coeff) std::cout << c << ", "; std::cout << "\n"; return 0; } std::vector<double> computeRRC(double sps, double a, double d) { double tap_count = ( sps*2.0*d )+1.0; std::vector<double> p(tap_count); std::fill(p.begin(), p.end(), 0.0); std::vector<double>::iterator cp = p.begin(); // current tap iterator. for ( double t=-1*d; t <= d+(1.0/sps); t=t+(1.0/sps) ) { if ( t == 0 ) { std::cout << "(debug) t=0 case hit..\n"; *cp = (1-a)+4.0*a/M_PI; // OK } else { if ( ( t == 1.0/(4.0*a)) || (t == -1.0/(4.0*a)) ) { std::cout << "(debug) t=1/(4*a) case hit..\n"; *cp = a/std::sqrt(2)*((1.0+2.0/M_PI)*std::sin(M_PI/(4.0*a))+(1.0-2.0/M_PI)*std::cos(M_PI/(4.0*a))); } else { // matlab: (sin(pi*-4*(1-a))+4*a*-4*cos(pi*-4*(1+a)))/(pi*-4*(1-(4*a*-4)^2)) *cp =(sin(M_PI*t*(1-a))+4*a*t*cos(M_PI*t*(1+a)))/(M_PI*t*(1-pow(4*a*t,2))); } } cp++; // next tap. } // Normalize unit energy // get squared sum double ss=0; for ( auto &t: p) ss = ss + (t*t); // compute the normalization value (nv) double nv = std::sqrt(ss); // apply normalization value to all taps for ( auto &t: p ) t = t / nv; // return taps computed return p; }
[ "kb3gtn@gmail.com" ]
kb3gtn@gmail.com
d8a61c2f740b53e2f194d9823b866319d330ca43
fd472b2dcd3b28477f61574c6d41dabf1993d6df
/src/gc/main_debug3.cc
990cc94643354565649427221c64c5e84c60d1c8
[]
no_license
SimonHPedersen/gbvm
566db9b53e7a2c3c50e5d050351729302438b6b7
2d5041b9373b41724110afb89f0be5d1b6c19f48
refs/heads/master
2016-09-06T02:33:26.023454
2014-02-26T18:19:07
2014-02-26T18:19:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,778
cc
//$Id: main_debug3.cc,v 1.3 2000/12/06 14:50:13 ilsoe Exp $ #include <stdlib.h> #include <stdio.h> #include <iostream.h> #include "garbage_collector.hpp" class Test_t { public: void *operator new(size_t size, void *freePointer) { return freePointer; } Test_t() { } void *a; void *b; void *c; void *d; void *e; void *f; void *g; }; int main(int argc, char** argv) { DB_ENABLE(gc_gc); DB_ENABLE(gc_mg); DB_ENABLE(gc_mg_heapdump); DB_ENABLE(gc_remset_dump); DB_ENABLE(gc_car); DB_ENABLE(gc_car_delete); DB_ENABLE(gc_vmo); DB_ENABLE(gc_vmo_dump_refs); //DB_ENABLE(gc_vmo_mro_verb); DB_ENABLE(gc_trn); DB_ENABLE(gc_objd); DB_ENABLE(gc_glob_setvmr); ObjectDescriptor_t *objDes = new ObjectDescriptor_t(300,0); //objDes->print(); objDes->setReferenceAt(0); objDes->setReferenceAt(1); objDes->setReferenceAt(2); objDes->setReferenceAt(3); objDes->setReferenceAt(4); objDes->setReferenceAt(5); objDes->setReferenceAt(6); //objDes->print(); // test 1 BYTES_IN_CAR should be 1024, 2 cars in train VMObject_t *o0 = garbageCollector->addRootObject(objDes); Test_t *t0 = new (o0->getDataPtr())Test_t(); VMObject_t *o1 = garbageCollector->addNewObject(objDes); Test_t *t1 = new (o1->getDataPtr())Test_t(); VMObject_t *o2 = garbageCollector->addNewObject(objDes); Test_t *t2 = new (o2->getDataPtr())Test_t(); VMObject_t *o3 = garbageCollector->addNewObject(objDes); Test_t *t3 = new (o3->getDataPtr())Test_t(); VMObject_t *o4 = garbageCollector->addNewObject(objDes); Test_t *t4 = new (o4->getDataPtr())Test_t(); VMObject_t *o5 = garbageCollector->addNewObject(objDes); Test_t *t5 = new (o5->getDataPtr())Test_t(); VMObject_t *o6 = garbageCollector->addNewObject(objDes); Test_t *t6 = new (o6->getDataPtr())Test_t(); VMObject_t *o7 = garbageCollector->addNewObject(objDes); Test_t *t7 = new (o7->getDataPtr())Test_t(); VMObject_t *o8 = garbageCollector->addNewObject(objDes); Test_t *t8 = new (o8->getDataPtr())Test_t(); /* creating popular object */ VMObject_t *o_n; Test_t *t_n; for(int i = 0; i < 100; i++) { o_n = garbageCollector->addNewObject(objDes); t_n = new (o_n->getDataPtr()) Test_t(); setVMReference(t_n, &(t_n->a), t1); } setVMReference(t0, &(t0->a), t5); setVMReference(t1, &(t1->a), t2); setVMReference(t2, &(t2->a), t3); setVMReference(t3, &(t3->a), t4); setVMReference(t4, &(t4->a), t3); setVMReference(t5, &(t5->a), t1); setVMReference(t5, &(t5->b), t6); setVMReference(t7, &(t7->a), t8); setVMReference(t8, &(t8->a), t7); /* setVMReference(t0, &(t0->b), t1); setVMReference(t0, &(t0->c), t1); setVMReference(t0, &(t0->d), t1); setVMReference(t0, &(t0->e), t1); setVMReference(t0, &(t0->f), t1); setVMReference(t0, &(t0->g), t1); setVMReference(t2, &(t2->b), t1); setVMReference(t2, &(t2->c), t1); setVMReference(t2, &(t2->d), t1); setVMReference(t2, &(t2->e), t1); setVMReference(t2, &(t2->f), t1); setVMReference(t2, &(t2->g), t1); setVMReference(t3, &(t3->b), t1); setVMReference(t3, &(t3->c), t1); setVMReference(t3, &(t3->d), t1); setVMReference(t3, &(t3->e), t1); setVMReference(t3, &(t3->f), t1); setVMReference(t3, &(t3->g), t1); setVMReference(t4, &(t4->b), t1); setVMReference(t4, &(t4->c), t1); setVMReference(t4, &(t4->d), t1); setVMReference(t4, &(t4->e), t1); setVMReference(t4, &(t4->f), t1); setVMReference(t4, &(t4->g), t1); setVMReference(t5, &(t5->c), t1); setVMReference(t5, &(t5->d), t1); setVMReference(t5, &(t5->e), t1); setVMReference(t5, &(t5->f), t1); setVMReference(t5, &(t5->g), t1); */ while(1) { garbageCollector->garbageCollect(); } }
[ "shp@trifork.com" ]
shp@trifork.com
75f1512e11e75cceabcce7800a11c78f727297b6
f4e17640afef6d1b4d4a85f583a90e37f705dbd5
/B2G/gecko/content/xslt/src/xpath/nsXPathNamespace.h
ef27f3924096f71a7b8d6703eba9bfb7eeb14262
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
wilebeast/FireFox-OS
d370362916f0c5a5408fa08285dbf4779f8b5eb3
43067f28711d78c429a1d6d58c77130f6899135f
refs/heads/master
2016-09-05T22:06:54.838558
2013-09-03T13:49:21
2013-09-03T13:49:21
12,572,236
4
3
null
null
null
null
UTF-8
C++
false
false
968
h
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef nsXPathNamespace_h__ #define nsXPathNamespace_h__ #include "nsIDOMXPathNamespace.h" /* d0a75e07-b5e7-11d5-a7f2-df109fb8a1fc */ #define TRANSFORMIIX_XPATH_NAMESPACE_CID \ { 0xd0a75e07, 0xb5e7, 0x11d5, { 0xa7, 0xf2, 0xdf, 0x10, 0x9f, 0xb8, 0xa1, 0xfc } } #define TRANSFORMIIX_XPATH_NAMESPACE_CONTRACTID \ "@mozilla.org/transformiix/xpath-namespace;1" /** * A class for representing XPath namespace nodes in the DOM. */ class nsXPathNamespace : public nsIDOMXPathNamespace { public: // nsISupports interface NS_DECL_ISUPPORTS // nsIDOMNode interface NS_DECL_NSIDOMNODE // nsIDOMXPathNamespace interface NS_DECL_NSIDOMXPATHNAMESPACE }; #endif
[ "info@hadrons.me" ]
info@hadrons.me
9414deb06b716abe05fdfc392db6585d8d4895c4
5c5ba0cbdc972b56a3ac7664f68a74fe382c645a
/uri/8 - Computer Geometry/1991/Main.cpp
1ec2e7228f457d353a29d3518af879ff10d881d0
[]
no_license
humbertodias/challenges
91e090b70ed65269ff94f0b8d4096526d3545ba3
b832d55491b4d5c840b0bb25b931aef8f04f5784
refs/heads/master
2020-04-05T14:03:38.384606
2019-01-29T12:28:13
2019-01-29T12:28:13
94,749,550
0
0
null
null
null
null
UTF-8
C++
false
false
3,433
cpp
#include <cstdio> #include <cstring> #include <string> #include <cmath> #include <cstdlib> #include <iostream> #include <algorithm> #include <vector> #include <vector> #include <queue> #include <list> #include <stack> #include <map> #include <sstream> #include <climits> #include <set> // #include <unordered_map> #define ll long long #define ull unsigned long long #define PII pair<int,int> #define PDD pair<double,double> #define FT first #define SD second #define REP(i,j,k) for(int (i)=(j);(i)<(k);++(i)) #define PB push_back #define PI acos(-1) #define DB(x) cerr << #x << " = " << x << endl; #define _ << ", " << #define MP make_pair #define EPS 1e-9 #define INF 0x3f3f3f3f #define IOFAST() ios_base::sync_with_stdio(0);cin.tie(0) #define FILL(x,v) memset(x,v,sizeof(x)) // #define umap unordered_map using namespace std; template <class _T> inline string tostr(const _T& a){ ostringstream os(""); os<<a;return os.str(); } const int MAXN = 2000; double cen[2][MAXN]; double rad[2][MAXN]; bool nor[2][MAXN]; int sz[2]; char str[10]; int main(){ double A; while( cin >> A ){ if( A < 0) break; REP(i,0,2){ scanf("%d%s", &sz[i], str); int rdsum = 0; bool north = (str[0] == 'N'); REP(j,0,sz[i]){ int a; scanf("%d", &a); rdsum += a; cen[i][j] = rdsum; rad[i][j] = a; nor[i][j] = north; north = !north; rdsum += a; } } double mid, lo = 0, hi = A; while( fabs( hi - lo ) > EPS){ mid = (lo+hi)/2; //DB( mid ); bool touch = false; int i = 0, j = 0; while( i < sz[0] || j < sz[1]){ double distrad = sqrt( pow( cen[0][i] - cen[1][j], 2) + pow(mid,2)); if( !nor[0][i] && nor[1][j] ){ if( distrad < rad[0][i] + rad[1][j] ){ //TODO EPS touch = true; goto leave; } } else if( nor[0][i] && !nor[1][j] ){ if( mid < EPS ){ touch = true; goto leave; } } else { double c1 , c2 , r1, r2; if( nor[0][i] && nor[1][j]){ c1 = cen[0][i]; c2 = cen[1][j]; r1 = rad[0][i]; r2 = rad[1][j]; } else { c1 = cen[1][j]; c2 = cen[0][i]; r1 = rad[1][j]; r2 = rad[0][i]; } double distleft = sqrt(pow( (c1+r1) - c2, 2) + pow(mid,2)); double distright = sqrt(pow( (c1-r1) - c2, 2) + pow(mid,2)); if( distleft < r2 || distright < r2 ){ touch = true; goto leave; } } if( i < sz[0] && j < sz[1] && fabs( (cen[0][i] + rad[0][i]) - (cen[1][j] + rad[1][j]) ) < 1e-5){ i++, j++; } else if( cen[0][i] + rad[0][i] > cen[1][j] + rad[1][j] && j + 1 < sz[1]) { j++; } else { i++; } } leave : if( touch ) lo = mid; else hi = mid; } printf("%.2lf\n", (A - mid)); } return 0; }
[ "humberto.dias@techne.com.br" ]
humberto.dias@techne.com.br
9b5443d214f9a24ea42537f461c19f84a2ad54d6
b8be56136362dc4cf3c51136285f38815ff6ab4b
/sketch_oct15b/sketch_oct15b.ino
afc6d60e0f3f1fb50597520d203e83f64021a425
[]
no_license
ivanferrier/ECE-196
3910fb0c313a0374fe4bd60e4f37f46ceea6cb97
f9c30bf20ebe6025b3efa09d5d341ad5a2324ec9
refs/heads/master
2020-04-11T05:26:22.896109
2018-12-12T21:49:07
2018-12-12T21:49:07
161,549,574
0
0
null
null
null
null
UTF-8
C++
false
false
100
ino
#include <Blnk.h> Blnk blnk(13); void setup() { } void loop() { blnk.start(); delay(3000); }
[ "i_ferrier@aol.com" ]
i_ferrier@aol.com
42faa582bcb17db69b2c7560bac4f01060f9b042
b2dedee28c3aa96fac1d9f31bf55c724ffde442d
/Sparky_core/src/utils/ImageLoad.h
ad6344e32d7e52a676b216258a4c66a10feed0c4
[]
no_license
Arrekusu/Sparky
fd7834e73fe566316a580d1f3444df47439af63d
dcaf589415da8d44664710ab4322b721bdf9fd00
refs/heads/master
2021-07-08T01:56:42.358799
2017-10-05T06:36:43
2017-10-05T06:36:43
104,973,582
0
0
null
null
null
null
UTF-8
C++
false
false
836
h
#pragma once #include <FreeImage.h> #include <string> namespace sparky { namespace graphics{ static BYTE* load_image(const char* filename, GLsizei* width, GLsizei* height) { FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; FIBITMAP *dib = nullptr; BYTE* bits = nullptr; fif = FreeImage_GetFileType(filename, 0); if (fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename); if (fif == FIF_UNKNOWN) return nullptr; if (FreeImage_FIFSupportsReading(fif)) dib = FreeImage_Load(fif, filename); if (!dib) return nullptr; BYTE* pixels = FreeImage_GetBits(dib); *width = FreeImage_GetWidth(dib); *height = FreeImage_GetHeight(dib); int bpp = FreeImage_GetBPP(dib); int size = *width * *height * (bpp / 8); BYTE* result = new BYTE[size]; memcpy(result, pixels, size); return result; } } }
[ "arrekusu.a@gmail.com" ]
arrekusu.a@gmail.com
fb0f072c07e65e0d314c26a12ec33f2762a1da6e
f2cba86a7fad90570e2020bb12a7f51729aa6afa
/include/ITransaction.h
58ffa159ca016c2249adcb678fcdc167285f6edd
[]
no_license
emergebtc/TavosBTC
7ddcc01c2c5b1811785120d0e4c9d31b7b813e04
f1bf530b9be008452ff7259fbbb3dbff8ba1da18
refs/heads/master
2016-09-15T21:13:02.156429
2015-08-01T08:21:06
2015-08-01T08:21:06
39,250,551
2
3
null
null
null
null
UTF-8
C++
false
false
4,791
h
// Copyright (c) 2011-2015 The Cryptonote developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #pragma once #include <array> #include <cstdint> #include <vector> namespace CryptoNote { typedef std::array<uint8_t, 32> PublicKey; typedef std::array<uint8_t, 32> SecretKey; typedef std::array<uint8_t, 32> KeyImage; typedef std::array<uint8_t, 32> Hash; typedef std::vector<uint8_t> Blob; struct AccountAddress { PublicKey spendPublicKey; PublicKey viewPublicKey; }; struct AccountKeys { AccountAddress address; SecretKey spendSecretKey; SecretKey viewSecretKey; }; struct KeyPair { PublicKey publicKey; SecretKey secretKey; }; namespace TransactionTypes { enum class InputType : uint8_t { Invalid, Key, Multisignature, Generating }; enum class OutputType : uint8_t { Invalid, Key, Multisignature }; struct InputKey { uint64_t amount; std::vector<uint64_t> keyOffsets; KeyImage keyImage; // double spending protection }; struct InputMultisignature { uint64_t amount; uint32_t signatures; uint64_t outputIndex; }; struct OutputKey { uint64_t amount; PublicKey key; }; struct OutputMultisignature { uint64_t amount; std::vector<PublicKey> keys; uint32_t requiredSignatures; }; struct GlobalOutput { PublicKey targetKey; uint64_t outputIndex; }; typedef std::vector<GlobalOutput> GlobalOutputsContainer; struct OutputKeyInfo { PublicKey transactionPublicKey; size_t transactionIndex; size_t outputInTransaction; }; struct InputKeyInfo { uint64_t amount; GlobalOutputsContainer outputs; OutputKeyInfo realOutput; }; } // // ITransactionReader // class ITransactionReader { public: virtual ~ITransactionReader() { } virtual Hash getTransactionHash() const = 0; virtual Hash getTransactionPrefixHash() const = 0; virtual PublicKey getTransactionPublicKey() const = 0; virtual uint64_t getUnlockTime() const = 0; // extra virtual bool getPaymentId(Hash& paymentId) const = 0; virtual bool getExtraNonce(std::string& nonce) const = 0; // inputs virtual size_t getInputCount() const = 0; virtual uint64_t getInputTotalAmount() const = 0; virtual TransactionTypes::InputType getInputType(size_t index) const = 0; virtual void getInput(size_t index, TransactionTypes::InputKey& input) const = 0; virtual void getInput(size_t index, TransactionTypes::InputMultisignature& input) const = 0; // outputs virtual size_t getOutputCount() const = 0; virtual uint64_t getOutputTotalAmount() const = 0; virtual TransactionTypes::OutputType getOutputType(size_t index) const = 0; virtual void getOutput(size_t index, TransactionTypes::OutputKey& output) const = 0; virtual void getOutput(size_t index, TransactionTypes::OutputMultisignature& output) const = 0; // signatures virtual size_t getRequiredSignaturesCount(size_t inputIndex) const = 0; virtual bool findOutputsToAccount(const AccountAddress& addr, const SecretKey& viewSecretKey, std::vector<uint32_t>& outs, uint64_t& outputAmount) const = 0; // various checks virtual bool validateInputs() const = 0; virtual bool validateOutputs() const = 0; virtual bool validateSignatures() const = 0; // serialized transaction virtual Blob getTransactionData() const = 0; }; // // ITransactionWriter // class ITransactionWriter { public: virtual ~ITransactionWriter() { } // transaction parameters virtual void setUnlockTime(uint64_t unlockTime) = 0; // extra virtual void setPaymentId(const Hash& paymentId) = 0; virtual void setExtraNonce(const std::string& nonce) = 0; // Inputs/Outputs virtual size_t addInput(const TransactionTypes::InputKey& input) = 0; virtual size_t addInput(const AccountKeys& senderKeys, const TransactionTypes::InputKeyInfo& info, KeyPair& ephKeys) = 0; virtual size_t addInput(const TransactionTypes::InputMultisignature& input) = 0; virtual size_t addOutput(uint64_t amount, const AccountAddress& to) = 0; virtual size_t addOutput(uint64_t amount, const std::vector<AccountAddress>& to, uint32_t requiredSignatures) = 0; // transaction info virtual bool getTransactionSecretKey(SecretKey& key) const = 0; virtual void setTransactionSecretKey(const SecretKey& key) = 0; // signing virtual void signInputKey(size_t input, const TransactionTypes::InputKeyInfo& info, const KeyPair& ephKeys) = 0; virtual void signInputMultisignature(size_t input, const PublicKey& sourceTransactionKey, size_t outputIndex, const AccountKeys& accountKeys) = 0; }; class ITransaction : public ITransactionReader, public ITransactionWriter { public: virtual ~ITransaction() { } }; }
[ "smallstratos@hotmail.com" ]
smallstratos@hotmail.com
464c0b3d0ffc084dd5eb20711edb392538de7339
fd8fdf41880f3f67f8e6413c297b5144097b50ad
/trunk/src/cgi/notice_cgi/cgi_notice_notify_get.cpp
343d873e7828f3ad88b611d60883500a33d7468d
[]
no_license
liuxuanhai/CGI_Web
c67d4db6a3a4de3714babbd31f095d2285545aac
273343bb06a170ac3086d633435e7bcaaa81e8c5
refs/heads/master
2020-03-18T12:27:40.035442
2016-09-28T11:18:26
2016-09-28T11:18:26
134,727,689
1
1
null
null
null
null
UTF-8
C++
false
false
2,356
cpp
#include "notice_server_cgi.h" #include "proto_io_tcp_client.h" class CgiNoticeNotifyGet: public NoticeServerCgi { public: CgiNoticeNotifyGet() : NoticeServerCgi(0, "config.ini", "logger.properties") { } bool InnerProcess() { uint64_t iPaAppidMd5 = strtoul(((string)GetInput().GetValue("pa_appid_md5")).c_str(),NULL,10); uint64_t iOpenidMd5 = strtoul(((string)GetInput().GetValue("openid_md5")).c_str(),NULL,10); ZERO_INT_RETURN(iPaAppidMd5); ZERO_INT_RETURN(iOpenidMd5); ::common::protoio::ProtoIOTcpClient client(m_notice_server_ip, m_notice_server_port); std::string strErrMsg = ""; ::hoosho::msg::Msg stRequest; ::hoosho::msg::Msg stResponse; ::hoosho::msg::MsgHead* header = stRequest.mutable_head(); uint32_t iSeq = 1; header->set_seq(iSeq); header->set_cmd(hoosho::msg::QUERY_NOTICE_NOTIFY_REQ); ::hoosho::noticenotify::QueryNoticeNotifyReq* req = stRequest.mutable_notice_notify_query_req(); req->set_pa_appid_md5(iPaAppidMd5); req->set_openid_md5(iOpenidMd5); if (client.io(stRequest, stResponse, strErrMsg) < 0) { LOG4CPLUS_DEBUG(logger, "failed, strErrMsg=" << strErrMsg << std::endl;); return -1; } std::ostringstream oss; if (stResponse.head().cmd() == hoosho::msg::QUERY_NOTICE_NOTIFY_RES && stResponse.head().seq() == iSeq) { if (stResponse.head().result() == hoosho::msg::E_OK) { LOG4CPLUS_DEBUG(logger, "succe!!\n"<<stResponse.Utf8DebugString() << std::endl); uint32_t stauts =stResponse.notice_notify_query_res().status(); GetAnyValue()["status"]=stauts; DoReply(CGI_RET_CODE_OK); } else if (stResponse.head().result() == hoosho::msg::E_SERVER_INNER_ERROR) { LOG4CPLUS_DEBUG(logger, "error!! result= 1" << std::endl); LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl); DoReply(CGI_RET_CODE_SERVER_BUSY); } else { LOG4CPLUS_DEBUG(logger, "error!! result no 1 or 0" << std::endl); LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl); DoReply(CGI_RET_CODE_SERVER_BUSY); } } else { LOG4CPLUS_DEBUG(logger, "error!! what 7 package?" << std::endl); LOG4CPLUS_DEBUG(logger, stResponse.Utf8DebugString() << std::endl); DoReply(CGI_RET_CODE_SERVER_BUSY); } return true; } }; int main() { CgiNoticeNotifyGet cgi; if (!cgi.Run()) { return -1; } return 0; }
[ "penghuijun6738@163.com" ]
penghuijun6738@163.com
197b2cbc0737392f5f59ad0f359d26278aa81bc4
7e68c3e0e86d1a1327026d189a613297b769c411
/Lib/Include/CompactKeyType.h
91cd060dd9b7d9869bb64201c2751f0a08374246
[]
no_license
staticlibs/Big-Numbers
bc08092e36c7c640dcf43d863448cd066abaebed
adbfa38cc2e3b8ef706a3ac8bbd3e398f741baf3
refs/heads/master
2023-03-16T20:25:08.699789
2020-12-20T20:50:25
2020-12-20T20:50:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,347
h
#pragma once template <typename T> class CompactKeyType { private: T m_value; public: CompactKeyType() { } inline CompactKeyType(T value) : m_value(value) { } #pragma warning( push ) #pragma warning(disable:4311 4302) inline ULONG hashCode() const { if(sizeof(m_value) > sizeof(ULONG)) { ULONG result = 0; const ULONG *start = (ULONG*)&m_value; const ULONG *end = start + sizeof(m_value) / sizeof(ULONG); for(const ULONG *p = start; p < end;) { result ^= *(p++); } return result; } else { return (ULONG)m_value; } } #pragma warning( pop ) inline bool operator==(const CompactKeyType &k) const { return m_value == k.m_value; } operator T() const { return m_value; } }; class Packer; template<typename T> Packer &operator<<(Packer &p, const CompactKeyType<T> &v) { p << (T)v; return p; } template<typename T> Packer &operator>>(Packer &p, CompactKeyType<T> &v) { T tmp; p >> tmp; v = tmp; return p; } class CompactStrKeyType { private: const TCHAR *m_value; public: CompactStrKeyType() : m_value(EMPTYSTRING) { } inline CompactStrKeyType(const TCHAR *value) : m_value(value) { } #pragma warning( push ) #pragma warning(disable:4311 4302) inline ULONG hashCode() const { return strHash(m_value); } #pragma warning( pop ) inline bool operator==(const CompactStrKeyType &k) const { return _tcscmp(m_value,k.m_value) == 0; } operator const TCHAR*() const { return m_value; } }; class CompactStrIKeyType { private: const TCHAR *m_value; public: CompactStrIKeyType() : m_value(EMPTYSTRING) { } inline CompactStrIKeyType(const TCHAR *value) : m_value(value) { } #pragma warning( push ) #pragma warning(disable:4311 4302) inline ULONG hashCode() const { return striHash(m_value); } #pragma warning( pop ) inline bool operator==(const CompactStrIKeyType &k) const { return _tcsicmp(m_value,k.m_value) == 0; } operator const TCHAR*() const { return m_value; } }; typedef CompactKeyType<short > CompactShortKeyType; typedef CompactKeyType<USHORT> CompactUShortKeyType; typedef CompactKeyType<int > CompactIntKeyType; typedef CompactKeyType<UINT > CompactUIntKeyType; typedef CompactKeyType<float > CompactFloatKeyType; typedef CompactKeyType<double> CompactDoubleKeyType;
[ "jesper.gr.mikkelsen@gmail.com" ]
jesper.gr.mikkelsen@gmail.com
cfd5a4f665f3f306c3ee608e9d5188c271012ddc
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Source/Editor/GraphEditor/Public/SNameComboBox.h
5af17b83389331c84c88779ead4971042f15b6f0
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
2,959
h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Styling/SlateColor.h" #include "Layout/Margin.h" #include "Widgets/SWidget.h" #include "Widgets/SCompoundWidget.h" #include "Framework/SlateDelegates.h" #include "Widgets/Input/SComboBox.h" //#include "UnrealString.h" /** * A combo box that shows FName content. */ class SNameComboBox : public SCompoundWidget { public: DECLARE_DELEGATE_RetVal_OneParam(FString, FGetNameComboLabel, TSharedPtr<FName>); typedef TSlateDelegates< TSharedPtr<FName> >::FOnSelectionChanged FOnNameSelectionChanged; SLATE_BEGIN_ARGS( SNameComboBox ) : _ColorAndOpacity( FSlateColor::UseForeground() ) , _ContentPadding(FMargin(4.0, 2.0)) , _OnGetNameLabelForItem() {} /** Selection of FNames to pick from */ SLATE_ARGUMENT( TArray< TSharedPtr<FName> >*, OptionsSource ) /** Text color and opacity */ SLATE_ATTRIBUTE( FSlateColor, ColorAndOpacity ) /** Visual padding of the button content for the combobox */ SLATE_ATTRIBUTE( FMargin, ContentPadding ) /** Called when the FName is chosen. */ SLATE_EVENT( FOnNameSelectionChanged, OnSelectionChanged) /** Called when the combo box is opened */ SLATE_EVENT( FOnComboBoxOpening, OnComboBoxOpening ) /** Called when combo box needs to establish selected item */ SLATE_ARGUMENT( TSharedPtr<FName>, InitiallySelectedItem ) /** [Optional] Called to get the label for the currently selected item */ SLATE_EVENT( FGetNameComboLabel, OnGetNameLabelForItem ) SLATE_END_ARGS() void Construct( const FArguments& InArgs ); /** Called to create a widget for each FName */ TSharedRef<SWidget> MakeItemWidget( TSharedPtr<FName> StringItem ); void SetSelectedItem (TSharedPtr<FName> NewSelection); /** Returns the currently selected FName */ TSharedPtr<FName> GetSelectedItem() { return SelectedItem; } /** Request to reload the name options in the combobox from the OptionsSource attribute */ void RefreshOptions(); /** Clears the selected item in the name combo */ void ClearSelection(); private: TSharedPtr<FName> OnGetSelection() const {return SelectedItem;} /** Called when selection changes in the combo pop-up */ void OnSelectionChanged(TSharedPtr<FName> Selection, ESelectInfo::Type SelectInfo); /** Helper method to get the text for a given item in the combo box */ FText GetSelectedNameLabel() const; FText GetItemNameLabel(TSharedPtr<FName> StringItem) const; private: /** Called to get the text label for an item */ FGetNameComboLabel GetTextLabelForItem; /** The FName item selected */ TSharedPtr<FName> SelectedItem; /** Array of shared pointers to FNames so combo widget can work on them */ TArray< TSharedPtr<FName> > Names; /** The combo box */ TSharedPtr< SComboBox< TSharedPtr<FName> > > NameCombo; /** Forwarding Delegate */ FOnNameSelectionChanged SelectionChanged; };
[ "tungnt.rec@gmail.com" ]
tungnt.rec@gmail.com
abcdb79140e4edbf8ee5f593c0687f9a3fd18362
87464fd51294f061472244148aebce14e454f2a6
/DataStructures/Graph/Graph_AdjList.cpp
bdbaabe339429e31702b3a801382605407916a33
[]
no_license
msk4862/DS-Algo
6fb348e4ae0f685f58b89f619ce4edc6690c3817
10e41a8ce1879fceee6f064c81192aa3e981d8d4
refs/heads/master
2021-08-02T23:31:44.813569
2021-07-24T11:18:51
2021-07-24T11:18:51
199,693,163
4
3
null
2020-10-07T19:28:55
2019-07-30T16:56:48
C++
UTF-8
C++
false
false
886
cpp
#include<bits/stdc++.h> using namespace std; /* Graph data structure using Adjacency list */ class Graph { public: int V; unordered_map<int, list<int>> l; /* If vecrtices are numeric values from 1 to N we can use simply use array of list i.e. list<int> *l; */ Graph(int V) { this->V = V; // l = new list<int>[V]; } // assuming biderectional edges void addEdge(int v1, int v2) { l[v1].push_back(v2); l[v2].push_back(v1); } void printAdjacencyList() { for (auto e: l) { cout<<"Vertex "<<e.first<<"-> "; for(auto nbr : e.second) cout<<nbr<<" "; cout<<"\n"; } } }; int main() { Graph g(4); g.addEdge(1, 2); g.addEdge(2, 3); g.addEdge(3, 4); g.addEdge(4, 1); g.printAdjacencyList(); }
[ "shoaib.mca19.du@gmail.com" ]
shoaib.mca19.du@gmail.com
179ad58d76af742208e0b39680351d420eb97fab
67e0f28469124358d518dacff4cef3dd1956450e
/OneWaySurvivor/SourceFolder/Source/Sound/Base/Sound_Base_3D.cpp
431a8cef7bf369d24c1989bbd64cde532d70eb94
[]
no_license
FUKUDA87/OneWaySurvivor
4593e669c032a357f248380c2b355eb794173f22
056f9dd621bc00d75fd95178c0b4b63db1ddf74c
refs/heads/master
2020-11-27T17:43:11.055535
2020-07-20T09:55:18
2020-07-20T09:55:18
229,548,351
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,240
cpp
#include "Sound_Base_3D.h" extern LPDIRECTSOUND3DLISTENER8 lpSListener; C_Sound_Base_3D::C_Sound_Base_3D(const S_SOUND_DATA * Data, std::string FileName) { M_Sound_Data = *Data; Init_Sound(&M_Sound_Data.Sound_CategoryNo, &M_Sound_Data.Sound_No, FileName); } bool C_Sound_Base_3D::Update(const S_CAMERA_POS * CamPos, const bool * Flg,const int *Volume) { if (DeleteFlg > 1)return false; DWORD SFlg; soundCol.Sound3D->SetPosition(M_Sound_Data.Pos.x, M_Sound_Data.Pos.y, M_Sound_Data.Pos.z, DS3D_IMMEDIATE);//音源の位置 lpSListener->SetPosition(CamPos->Pos.x, CamPos->Pos.y, CamPos->Pos.z, DS3D_IMMEDIATE);//リスナーの位置 //リスナーが見ている方向計算 D3DXVECTOR3 Vec; Vec = CamPos->Look - CamPos->Pos; D3DXVec3Normalize(&Vec, &Vec); lpSListener->SetOrientation(Vec.x, Vec.y, Vec.z, CamPos->Head.x, CamPos->Head.y, CamPos->Head.z, DS3D_IMMEDIATE);//リスナーが見ている方向とリスナーの頭の方向 soundCol.Sound->GetStatus(&SFlg); if (M_MoveFlg != 2) { if ((SFlg&DSBSTATUS_PLAYING) == 0) { Loop_Mode(); if ((*Flg == true) || (Loop_Mode_Flg == true)) { soundCol.Sound->Play(0, 0, 0); M_MoveFlg = 1; } } } soundCol.Sound->SetVolume(*Volume); return true; }
[ "kd1290926@st.kobedenshi.ac.jp" ]
kd1290926@st.kobedenshi.ac.jp
fd89085ed0100d3ce5b4f11df84112502ef7e7d5
b21bcc5c2203ce4a7d5ceb9bcf0d72cf79db6abc
/leetcode/hard/candy/src/main.cpp
e06c928b0bbb02733832fd5b3635e491c19d6e98
[]
no_license
zhaoyunfuture/study
81ad69a4abfedb3d14efa1080a2bcf091ab2e1a8
ebed9809c84c31ff67b988b3bb3c3289b2b818d7
refs/heads/master
2022-01-18T21:33:06.613463
2022-01-09T13:19:58
2022-01-09T13:19:58
47,873,321
0
0
null
null
null
null
UTF-8
C++
false
false
1,401
cpp
#include <string.h> #include <string> #include <iostream> using namespace std; class Solution { public: struct myclass { bool operator() (int i,int j) { return (i<j);} } myobject; int candy(vector<int>& ratings) { int size = ratings.size(); if(size==1) return size; vector<int> c; bool onlyfall = true; for(int i=0;i<size-1;i++){ c.push_back(1); if(ratings.at(i)<ratings.at(i+1)) onlyfall = false; } c.push_back(1); if(onlyfall){ sort (ratings.begin(), ratings.end(), myobject); } bool flag = false; do{ flag = false; for(int i=0;i<size-1;i++){ if(ratings.at(i)>ratings.at(i+1)){ if(c.at(i)<=c.at(i+1)){ c.at(i) += c.at(i+1) -c.at(i) + 1; flag = true; } }else if(ratings.at(i)<ratings.at(i+1)){ if(c.at(i)>=c.at(i+1)){ c.at(i+1) += c.at(i) -c.at(i+1) + 1; flag = true; } } } }while(flag); int out=0; for(int i=0;i<size;i++){ out +=c.at(i); } return out; } }; int main(int argc, char* argv[]) { return 0; }
[ "zyfuture@qq.com" ]
zyfuture@qq.com
d73a3b6ac91e621194fbd262454983e9ae8ae0ee
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/86/daea033a9686a0/main.cpp
96bf8525753723004de8122fe71ff6795cf44c1d
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,775
cpp
#include <map> #include <iostream> #include <string> #include <boost/foreach.hpp> #include <sstream> #include <cstdarg> enum JType { JInt = 0, JVoid = 1, JString = 2, JBool = 3 }; std::string JTypeToString(JType type) { switch (type) { case(JInt): return "I"; case(JVoid): return "V"; case(JString): return "Ljava/lang/String;"; case(JBool): return "Z"; default: return ""; } return ""; } template<int N> struct JTypeList; template<> struct JTypeList<0> { void insert(std::stringstream& ss) const {} }; template<> struct JTypeList<1> : JTypeList<0> { JTypeList(JType v) : value(v) {}; JTypeList(JTypeList<0> const&, JType v) : value(v) {} void insert(std::stringstream& ss) const { ss << JTypeToString(value); } JType value; }; template<int N> struct JTypeList : JTypeList<N-1> { JTypeList(JTypeList<N-1> const& init, JType last) : JTypeList<N-1>(init, init.value), value(last) {} void insert(std::stringstream& ss) const { JTypeList<N-1>::insert(ss); ss << JTypeToString(value); } JType value; }; JTypeList<2> operator,(JType lhs, JType rhs) { return JTypeList<2>(JTypeList<1>(lhs), rhs); } template<int N> JTypeList<N+1> operator,(JTypeList<N> const& l, JType next) { return JTypeList<N+1>(l, next); } static JTypeList<0> const NoArgs = {}; template<int N> std::string MakeSig(JType returnType, JTypeList<N> const& args) { std::stringstream ss; ss << "("; args.insert(ss); ss << ")" << JTypeToString(returnType); return ss.str(); } int main() { std::cout << MakeSig(JInt, (JString, JBool)) << std::endl; std::cout << MakeSig(JInt, NoArgs); }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
5e453ab330b1464279b795a125decc5e1238cd1b
ecf5f95dd74fd008f9c8d6d4d89393362a821d9c
/manos_cartesian_velocity_control/include/manos_cartesian_velocity_control/cartesian_state_controller.h
cd0826addf520e3a9f79a9a2bf4a07208017f1cb
[]
no_license
ThanasisTs/manos
29ae0778b76e2fb4ba827dfd2f02e33b968ef3de
f8b897150a9de59ee1c4c58a347abea39b7e59b6
refs/heads/master
2021-09-10T03:20:23.679620
2020-03-12T10:55:40
2020-03-12T10:55:40
207,255,111
0
1
null
2019-09-09T07:55:11
2019-09-09T07:55:11
null
UTF-8
C++
false
false
2,172
h
#ifndef CARTESIAN_STATE_CONTROLLER_H #define CARTESIAN_STATE_CONTROLLER_H #include <ros/node_handle.h> #include <cartesian_state_msgs/PoseTwist.h> #include <hardware_interface/joint_state_interface.h> #include <controller_interface/controller.h> #include <kdl/chainfksolvervel_recursive.hpp> #include <kdl/chainfksolverpos_recursive.hpp> #include "manos_cartesian_velocity_control/kinematic_chain_controller_base.h" #include <realtime_tools/realtime_publisher.h> namespace controller_interface { /** \brief This class implements a cartesian state publisher * for ROS control. */ class CartesianStateController: public KinematicChainControllerBase< hardware_interface::JointStateInterface> { public: CartesianStateController() {} ~CartesianStateController() {} /** \brief The init function is called to initialize the controller from a * non-realtime thread with a pointer to the hardware interface, itself, * instead of a pointer to a RobotHW. *s * \param robot The specific hardware interface used by this controller. * * \param n A NodeHandle in the namespace from which the controller * should read its configuration, and where it should set up its ROS * interface. * * \returns True if initialization was successful and the controller * is ready to be started. */ bool init(hardware_interface::JointStateInterface *robot, ros::NodeHandle &n); /** \brief This is called from within the realtime thread just before the * first call to \ref update * * \param time The current time */ void starting(const ros::Time& time); /*! * \brief Issues commands to the joint. Called at regular intervals */ void update(const ros::Time& time, const ros::Duration& period); protected: ros::Publisher pub_state_; KDL::FrameVel x_dot_; KDL::Frame x_; boost::shared_ptr<KDL::ChainFkSolverVel> fk_vel_solver_; boost::shared_ptr<KDL::ChainFkSolverPos> fk_pos_solver_; boost::shared_ptr<realtime_tools::RealtimePublisher< cartesian_state_msgs::PoseTwist> > realtime_pub_; ros::Time last_publish_time_; double publish_rate_; }; } // namespace controller_interface #endif
[ "ThanasisTs@github.com" ]
ThanasisTs@github.com
d63d86fa8a3104e787d0e4da83aaa9d517ad1c62
7d4977f51c74af9548fa607b518c7b5dafeba576
/Programmers/src/49191/solution.cpp
44447bdcd4b319e1cf5b0f8dcfa9cd8d6abf25b7
[ "MIT" ]
permissive
lstar2397/algorithms
7b200c7ee929ba21e0eb6432677bf234d6c8b239
686ea882079e26111f86b5bd5a7ab1b14ccf0fa2
refs/heads/master
2020-04-15T21:38:15.618585
2019-02-01T14:50:37
2019-02-01T14:50:37
165,040,577
0
0
null
null
null
null
UTF-8
C++
false
false
981
cpp
#include <vector> #include <algorithm> using namespace std; void dfs(vector<int> graph[], int v, int e, bool visited[], int arr[][101]) { visited[e] = true; if (v != e) { arr[v][e] = 1; arr[e][v] = 0; } for (size_t i = 0; i < graph[e].size(); i++) { int next = graph[e][i]; if (!visited[next]) dfs(graph, v, next, visited, arr); } } int solution(int n, vector<vector<int>> results) { int arr[101][101]; vector<int> graph[101]; fill(&arr[0][0], &arr[0][0] + (sizeof(arr) / sizeof(int)), -1); for (int i = 1; i <= n; i++) arr[i][i] = 0; for (size_t i = 0; i < results.size(); i++) graph[results[i][0]].push_back(results[i][1]); for (int i = 1; i <= n; i++) { bool visited[101] = { false, }; dfs(graph, i, i, visited, arr); } int answer = n; for (int i = 1; i <= n; i++) { bool flag = false; for (int j = 1; j <= n; j++) { if (arr[i][j] == -1) { flag = true; break; } } if (flag) answer--; } return answer; }
[ "lstar2397@naver.com" ]
lstar2397@naver.com
623b32470be70f217e861752e32cbe6c6c7350f4
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/components/metrics/structured/reporting/structured_metrics_reporting_service.cc
ebd0adcdec1d0ac37adb1c58e2672c09b67c1700
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
3,693
cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/metrics/structured/reporting/structured_metrics_reporting_service.h" #include "base/metrics/histogram_functions.h" #include "components/metrics/metrics_service_client.h" #include "components/metrics/structured/reporting/structured_metrics_log_metrics.h" #include "components/metrics/structured/structured_metrics_prefs.h" #include "components/metrics/url_constants.h" #include "components/prefs/pref_registry_simple.h" namespace metrics::structured::reporting { StructuredMetricsReportingService::StructuredMetricsReportingService( MetricsServiceClient* client, PrefService* local_state, const UnsentLogStore::UnsentLogStoreLimits& storage_limits) : ReportingService(client, local_state, storage_limits.max_log_size_bytes, /*logs_event_manager=*/nullptr), log_store_(std::make_unique<StructuredMetricsLogMetrics>(), local_state, prefs::kLogStoreName, /* metadata_pref_name=*/nullptr, storage_limits, client->GetUploadSigningKey(), /* logs_event_manager=*/nullptr) {} void StructuredMetricsReportingService::StoreLog( const std::string& serialized_log, metrics::MetricsLogsEventManager::CreateReason reason) { LogMetadata metadata; log_store_.StoreLog(serialized_log, metadata, reason); } metrics::LogStore* StructuredMetricsReportingService::log_store() { return &log_store_; } void StructuredMetricsReportingService::Purge() { log_store_.Purge(); } // Getters for MetricsLogUploader parameters. GURL StructuredMetricsReportingService::GetUploadUrl() const { return client()->GetMetricsServerUrl(); } GURL StructuredMetricsReportingService::GetInsecureUploadUrl() const { return client()->GetInsecureMetricsServerUrl(); } base::StringPiece StructuredMetricsReportingService::upload_mime_type() const { return kDefaultMetricsMimeType; } MetricsLogUploader::MetricServiceType StructuredMetricsReportingService::service_type() const { return MetricsLogUploader::STRUCTURED_METRICS; } // Methods for recording data to histograms. void StructuredMetricsReportingService::LogActualUploadInterval( base::TimeDelta interval) { base::UmaHistogramCustomCounts( "StructuredMetrics.Reporting.ActualUploadInterval", interval.InMinutes(), 1, base::Hours(12).InMinutes(), 50); } void StructuredMetricsReportingService::LogResponseOrErrorCode( int response_code, int error_code, bool /*was_http*/) { // TODO(crbug.com/1445155) Do we assume |was_https| is always true? UMA // doesn't but UKM does. if (response_code >= 0) { base::UmaHistogramSparse("StructuredMetrics.Reporting.HTTPResponseCode", response_code); } else { base::UmaHistogramSparse("StructuredMetrics.Reporting.HTTPErrorCode", error_code); } } void StructuredMetricsReportingService::LogSuccessLogSize(size_t log_size) { base::UmaHistogramMemoryKB("StructuredMetrics.Reporting.LogSize.OnSuccess", log_size); } void StructuredMetricsReportingService::LogLargeRejection(size_t log_size) { base::UmaHistogramMemoryKB("StructuredMetrics.Reporting.LogSize.RejectedSize", log_size); } // static: void StructuredMetricsReportingService::RegisterPrefs( PrefRegistrySimple* registry) { registry->RegisterListPref(prefs::kLogStoreName); } } // namespace metrics::structured::reporting
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
55c7193bbf4fa47c60e7d50eabb9e565ecf8fbca
6f11c693f13a5c9dfb0c453fab13611344e238fb
/vtorcs-RL-color/src/tools/accc/mainaccc.cpp
6cb170b85c2116dbe7cbcacdde7ae681b8a2e9c2
[ "MIT", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
tushartk/gym_torcs
ebc0eb867a1e37d7efdceb99ba4fb582d36425ff
32d694f209dd94924bb9454733aeb6cc5ffeca11
refs/heads/master
2022-04-14T01:54:43.320746
2020-04-14T01:15:00
2020-04-14T01:15:00
255,478,013
0
0
MIT
2020-04-14T01:11:31
2020-04-14T01:11:30
null
UTF-8
C++
false
false
9,419
cpp
/*************************************************************************** file : accc.cpp created : Fri Apr 18 23:10:53 CEST 2003 copyright : (C) 2003 by Christophe Guionneau version : $Id: mainaccc.cpp,v 1.4.2.1 2008/11/09 17:50:23 berniw Exp $ ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ /** @file @author Christophe Guionneau @version $Id: mainaccc.cpp,v 1.4.2.1 2008/11/09 17:50:23 berniw Exp $ */ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <cstring> #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <math.h> #include "accc.h" /* -g g-track-2.ac -l0 g2.ac -d3 200900 -d2 200 -d1 100 -S 200 >t */ /* +es 80 p-gt1.ac porsche-gt1.ac>t */ int distSplit=0; char *InputFileName = NULL; char *OutputFileName = NULL; char * fileL0=NULL; char * fileL1=NULL; char * fileL2=NULL; char * fileL3=NULL; char * OrderString=NULL; int d1=0; int d2=0; int d3=0; int useStrip=0; int extendedStrips=0; int extendedEnvCoord=0; int isobjectacar=0; int extendedTriangles=0; int notexturesplit=0; int collapseObject=0; int typeConvertion =0; int far_dist=10000; int normalMapping=0; extern double smooth_angle; void usage(void) { fprintf(stderr, "Ac3d Compiler $Revision: 1.4.2.1 $ \n"); fprintf(stderr, "Usage: accc [option] <inputfile> <outputfile> [dist][-order \"orderstring\"]<\n"); /*fprintf(stderr, "-strip : stripify any ac3d output models\n");*/ fprintf(stderr, "+o: ac3d to ac3d : the result file is optimized\n"); fprintf(stderr, " in using groups by zone of track\n"); fprintf(stderr, " track must be named TKMNxxx\n"); fprintf(stderr, " dist is used to determine the distance of the objects\n"); /* fprintf(stderr, "+om: ac3d to ac3d : the result is a vertex merged unique obj\n" ); fprintf(stderr, " for smooth car only\n");*/ fprintf(stderr, "-o: ac3d to obj \n"); fprintf(stderr, "+s: ac3d to ac3d with strips (used for cars) \n"); fprintf(stderr, "+es <angle_of_smooth>: ac3d to ac3d with strips (used for cars) and extended ac3d file output \n"); fprintf(stderr, " (computed normals) angle is in degrees : example : +es 80.0 clkdtm_o.ac clkdtm.ac \n"); fprintf(stderr, " the output file will also contains the secondary textcoord for the env sliding \n"); fprintf(stderr, "+et: ac3d to ac3d with triangles (used for cars) and extended ac3d file output (normals normals) \n"); fprintf(stderr, "+etn: ac3d to ac3d with triangles no split and extended ac3d file output (normals normals) \n"); fprintf(stderr, "+shad: ac3d to ac3d with triangles, create a new ac3d file used for track shading\n vertical mapping of a single texture \n"); fprintf(stderr, "<inputfile>: \n"); fprintf(stderr, "<oututfile>: \n"); fprintf(stderr, "-order \"orderstring\": only used with +es , +s and +et \n"); fprintf(stderr, " \"orderstring\" is the order of the objects during the save\n"); fprintf(stderr, " for example : \"HB;OB;OBM\" is the names of the objet separate\n"); fprintf(stderr, " by a semicolon\n"); fprintf(stderr, " for imported NFS cars the object name \"HB\" must be used instead\n"); fprintf(stderr, " of \":HB\"\n"); fprintf(stderr, "-g <outputfile>: for grouping multilayer ac3d track \n"); fprintf(stderr, " -l0 <input filename> : the base geometry\n"); fprintf(stderr, " -l1 <input filename> : the base geometry map-tiled \n"); fprintf(stderr, " -l2 <input filename> : the base geometry skids/and grass details \n"); fprintf(stderr, " -l3 <input filename> : the base geometry shadows \n"); fprintf(stderr, " -d3 <val> : the max distance of groups in tkmn\n"); fprintf(stderr, " -d2 <val> : the distance of group 2 in tkmn\n"); fprintf(stderr, " -d1 <val> : the distance of group 1 in tkmn\n"); fprintf(stderr, " -S <val> : the distance of splitting for TERRAIN* objects\n"); fprintf(stderr, " -es : for extended ac3d file format for strips\n"); fprintf(stderr, " -nts : no texture split (for debug)\n"); } void init_args(int argc, char **argv) { if (argc<4) {usage();exit(1);} if (!strcmp(argv[1],"-o")) { typeConvertion=_AC3DTOOBJ; } else if (!strcmp(argv[1],"+o")) { typeConvertion=_AC3DTOAC3D; } else if (!strcmp(argv[1],"+om")) { typeConvertion=_AC3DTOAC3DM; } else if (!strcmp(argv[1],"+s")) { typeConvertion=_AC3DTOAC3DS; } else if (!strcmp(argv[1],"+es")) { typeConvertion=_AC3DTOAC3DS; isobjectacar=1; extendedStrips=1; extendedEnvCoord=1; collapseObject=1; sscanf(argv[2],"%lf",&smooth_angle); InputFileName = strdup(argv[3]); OutputFileName = strdup(argv[4]); } else if (!strcmp(argv[1],"+et")) { typeConvertion=_AC3DTOAC3D; extendedStrips=0; isobjectacar=1; extendedEnvCoord=1; extendedTriangles=1; collapseObject=1; } else if (!strcmp(argv[1],"+etn")) { typeConvertion=_AC3DTOAC3D; extendedStrips=0; isobjectacar=1; extendedEnvCoord=1; notexturesplit=0; collapseObject=1; extendedTriangles=1; } else if (!strcmp(argv[1],"+shad")) { typeConvertion=_AC3DTOAC3D; extendedStrips=0; isobjectacar=0; notexturesplit=1; extendedTriangles=0; normalMapping=1; collapseObject=1; } else if (!strcmp(argv[1],"-g")) { typeConvertion=_AC3DTOAC3DGROUP; } else { usage(); exit(1); } if (typeConvertion==_AC3DTOAC3DGROUP) { int i=3; /* read other arguments */ OutputFileName = strdup(argv[2]); for (i=3; i<argc; i++) { if (!strcmp(argv[i],"-es")) { extendedStrips=1; continue; } if (!strcmp(argv[i],"-nts")) { notexturesplit=1; continue; } if (!strcmp(argv[i],"-S")) { if (argc<=i+1){usage();exit(-1);} i++; distSplit=atoi(argv[i]); continue; } if (!strcmp(argv[i],"-l0")) { if (argc<=i+1){usage();exit(-1);} i++; fileL0=argv[i]; continue; } if (!strcmp(argv[i],"-l1")) { if (argc<=i+1){usage();exit(-1);} i++; fileL1=argv[i]; continue; } if (!strcmp(argv[i],"-l2")) { if (argc<=i+1){usage();exit(-1);} i++; fileL2=argv[i]; continue; } if (!strcmp(argv[i],"-l3")) { if (argc<=i+1){usage();exit(-1);} i++; fileL3=argv[i]; continue; } if (!strcmp(argv[i],"-d3")) { if (argc<=i+1){usage();exit(-1);} i++; d3=atoi(argv[i]); continue; } if (!strcmp(argv[i],"-d2")) { if (argc<=i+1){usage();exit(-1);} i++; d2=atoi(argv[i]); continue; } if (!strcmp(argv[i],"-d1")) { if (argc<=i+1){usage();exit(-1);} i++; d1=atoi(argv[i]); continue; } } } else { if (InputFileName==NULL) InputFileName = strdup(argv[2]); if (OutputFileName==NULL) OutputFileName = strdup(argv[3]); if (argc==7) {if (!strcmp(argv[5],"-order")) OrderString=argv[6]; } else if (typeConvertion==_AC3DTOAC3D) if (argc>=5) if (!strcmp(argv[4],"-order")) OrderString=argv[5]; else far_dist=atoi(argv[4]); } } /*extern void WindowsSpecInit(void);*/ void redraw () {} void reshape ( int w, int h ) {} void keyboard ( unsigned char, int, int ) { exit ( 0 ) ;} int main(int argc, char **argv) { char *fake_argv[3] ; fake_argv[0] = "ac3dto3ds" ; fake_argv[1] = "converter" ; fake_argv[2] = NULL ; init_args(argc, argv); extern int loadACo( char * inputFilename, char * outputFilename, int saveIn); extern int loadAC( char * inputFilename, char * outputFilename, int saveIn); #ifdef _3DS extern int load3ds( char * inputFilename, char * outputFilename); #endif if (typeConvertion==_AC3DTO3DS) { loadAC( InputFileName, OutputFileName,0); } else if (typeConvertion==_3DSTOAC3D) { #ifdef _3DS load3ds( InputFileName, OutputFileName); #endif } else if (typeConvertion==_AC3DTOAC3D) { loadACo( InputFileName, OutputFileName,0); } else if (typeConvertion==_AC3DTOOBJ) { loadAC( InputFileName, OutputFileName,1); } else if (typeConvertion==_AC3DTOAC3DM) { loadAC( InputFileName, OutputFileName,2); } else if (typeConvertion==_AC3DTOAC3DS) { loadAC( InputFileName, OutputFileName,3); } else if (typeConvertion==_AC3DTOAC3DGROUP) { loadAndGroup( OutputFileName); } return 0; }
[ "yossy0157@gmail.com" ]
yossy0157@gmail.com
a18a355bf6ab005814beee72a71a3767e7e015a7
b800fcf6bc5b78a5f84c9da4c3bab74cb8693a3d
/pgm7/Grain.hpp
45d3f92e5e23fb8d4b73e951263e25c118fc64aa
[]
no_license
billymeli/CS311
15f3f42259cd5df0c2cf6cd1521c21456225569f
47f4d26963a85f42b31b45bac71bf56837ec5227
refs/heads/master
2021-05-09T16:11:37.693620
2018-05-02T01:17:39
2018-05-02T01:17:39
119,101,152
0
0
null
null
null
null
UTF-8
C++
false
false
1,073
hpp
/* * Grain.h * * Created on: Feb 9, 2018 * Author: Joe */ #include <string> #ifndef GRAIN_H_ #define GRAIN_H_ /** * The Grain class identifies properties of a sample of grain */ class Grain { public: // Constructor default Grain(); // Constructor allowing caller to specify sample's moisture level (%) and foreign material (%) Grain(double moistureLevel, double foreignMaterial); // Destructor virtual ~Grain(); // pure virtual functions virtual Grain* clone() const = 0; virtual std::string getType() const = 0; virtual int getTypeVal() const = 0; virtual const double getAverageTestWeight() const = 0; virtual const double getIdealMoistureLevel() const = 0; // returns a string that represents the grain type std::string toString() const; // Accessor to return sample's moisture level (percent) double getMoistureLevel() const; // Accessor to return sample's foreign material (percent) double getForeignMaterial() const; protected: // Member variables double moistureLevel; double foreignMaterial; }; #endif /* GRAIN_H_ */
[ "mstevebilly@yahoo.com" ]
mstevebilly@yahoo.com
9f3791b3e90ab8967b39f68f32f31c934319c9c7
7161fa984e5312f6861f1a2f99ccde463b5302d7
/Source/UnrealFastNoisePlugin/Private/UFNConstantModule.cpp
14b84459d2d5ce2824da45322b6701f25a6babb1
[ "MIT" ]
permissive
Kolky/UnrealFastNoise
067d7d15d6b315bd4184d617f1b07e805a1a538c
a769ab7f0fd8fb0fb8b7efab4a6a10d4ff8550f7
refs/heads/master
2020-09-07T04:45:40.313390
2019-11-09T15:14:37
2019-11-09T15:14:37
220,659,504
0
0
MIT
2019-11-09T15:08:54
2019-11-09T15:08:53
null
UTF-8
C++
false
false
361
cpp
#include "UFNConstantModule.h" #include "UFNNoiseGenerator.h" UUFNConstantModule::UUFNConstantModule(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } float UUFNConstantModule::GetNoise3D(float aX, float aY, float aZ) { return constantValue; } float UUFNConstantModule::GetNoise2D(float aX, float aY) { return constantValue; }
[ "chrisashworth@appzeit.com" ]
chrisashworth@appzeit.com
0ef4a57115b45355e2f8c7096f9a67f78f5e4d03
daa634c9c80abedf2f3fcd94c1af81c1fccf5255
/吉田学園情報ビジネス専門学校 尾崎大輔/ゲーム作品/01_個人作品/02_1年 2Dアクションゲーム(著作権アクション)/ソースプロジェクト/Gameover.cpp
803e49532b71e65c455234f36673a6a4090e01fc
[]
no_license
ozakidaisukea/GamePerformance
49de174c52942d1ecfae011136031208254e1c7a
31eea2507bcc8f0f5543425c82adf2f4d869a210
refs/heads/master
2022-01-06T17:31:21.956265
2019-05-15T09:14:30
2019-05-15T09:14:30
185,955,578
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,399
cpp
//============================================================================= // // 背景の処理 [Gameover.cpp] // Author : Ozaki // //============================================================================= #include "main.h" #include "BG.h" #include "Gameover.h" #include "fade.h" #include "input.h" #include "sound.h" //***************************************************************************** // マクロ定義 //***************************************************************************** #define GAMEOVER_WIDTH (SCREEN_WIDTH) #define GAMEOVER_HEIGHT (SCREEN_HEIGHT) //***************************************************************************** // グローバル変数 //***************************************************************************** //VERTEX_2D g_aVertex[4]; //頂点情報を格納する LPDIRECT3DTEXTURE9 g_pTextureGAMEOVER = NULL; //テクスチャへのポインタ LPDIRECT3DVERTEXBUFFER9 g_pVtxBuffGAMEOVER = NULL; //テクスチャのポインタ int Gameovertimer; //============================================================================= // 初期化処理(ポリゴン) //============================================================================= void InitGameover(void) { LPDIRECT3DDEVICE9 pDevise; //デバイスのポインタ //デバイスの取得 pDevise = GetDevice(); Gameovertimer = 0; //テクスチャの読み込み D3DXCreateTextureFromFile(pDevise, "data\\TEXTURE\\gameover.jpg", &g_pTextureGAMEOVER); //頂点バッファの生成 pDevise->CreateVertexBuffer(sizeof(VERTEX_2D) * 4, D3DUSAGE_WRITEONLY, FVF_VRETEX_2D, D3DPOOL_MANAGED, &g_pVtxBuffGAMEOVER, NULL); //ローカル変数 VERTEX_2D*pVtx; //頂点情報へのポインタ //頂点バッファをロックし、頂点データのポインタの取得 g_pVtxBuffGAMEOVER->Lock(0, 0, (void**)&pVtx, 0); //頂点座標の設定 pVtx[0].pos = D3DXVECTOR3(0, 0, 0.0f); pVtx[1].pos = D3DXVECTOR3(SCREEN_WIDTH, 0, 0.0f); pVtx[2].pos = D3DXVECTOR3(0, SCREEN_HEIGHT, 0.0f); pVtx[3].pos = D3DXVECTOR3(SCREEN_WIDTH, SCREEN_HEIGHT, 0.0f); //テクスチャの設定 pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f); pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f); pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f); pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f); //rhwの設定 pVtx[0].rhw = 1.0f; pVtx[1].rhw = 1.0f; pVtx[2].rhw = 1.0f; pVtx[3].rhw = 1.0f; //頂点カラーの設定 pVtx[0].col = D3DCOLOR_RGBA(255, 255, 255, 255); pVtx[1].col = D3DCOLOR_RGBA(255, 255, 255, 255); pVtx[2].col = D3DCOLOR_RGBA(255, 255, 255, 255); pVtx[3].col = D3DCOLOR_RGBA(255, 255, 255, 255); //頂点バッファをアンロック g_pVtxBuffGAMEOVER->Unlock(); } //============================================================================= // 終了処理(ポリゴン) //============================================================================= void UninitGameover(void) { //テクスチャの破棄 if (g_pTextureGAMEOVER != NULL) { g_pTextureGAMEOVER->Release(); g_pTextureGAMEOVER = NULL; } //頂点バッファの破棄 if (g_pVtxBuffGAMEOVER != NULL) { g_pVtxBuffGAMEOVER->Release(); g_pVtxBuffGAMEOVER = NULL; } } //============================================================================= // 更新処理(ポリゴン) //============================================================================= void UpdateGameover(void) { FADE Fade; Fade = GetFade(); Gameovertimer++; if (Fade == FADE_NONE) { if (GetKeyboardTrigger(DIK_RETURN) == true && Fade == FADE_NONE) { SetFade(MODE_RANKING); PlaySound(SOUND_LABEL_SE_DECIDE); } if (Gameovertimer == 700) { SetFade(MODE_TITLE); Gameovertimer = 0; } } } //============================================================================= // 描画処理(ポリゴン) //============================================================================= void DrawGameover(void) { LPDIRECT3DDEVICE9 pDevice; //デヴァイスを取得 pDevice = GetDevice(); //頂点バッファをデータストリームに設定 pDevice->SetStreamSource(0, g_pVtxBuffGAMEOVER, 0, sizeof(VERTEX_2D)); //頂点フォーマットの設定 pDevice->SetFVF(FVF_VRETEX_2D); //テクスチャの設定 pDevice->SetTexture(0, g_pTextureGAMEOVER); //ポリゴンの描画 pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); }
[ "daisuke,vip17@gmail.com" ]
daisuke,vip17@gmail.com
b03e01a371cfd5daceae1a8ab785721bdb4c2f1e
553eacf6292ab90a4d1a264cac5bc4118928fb8a
/asteria/test/stack_overflow.cpp
c125b20475c6c735827acc84bd4d7af517284e2b
[ "BSD-3-Clause" ]
permissive
JamesChenGithub/asteria
71fc8e34cc19a7f0c0271774d2b4a04a89c77904
ef954d87f90235f900ba6ec21ae4d4d5471ad2c5
refs/heads/master
2022-12-30T21:39:10.377391
2020-10-21T09:55:43
2020-10-21T09:55:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
743
cpp
// This file is part of Asteria. // Copyleft 2018 - 2020, LH_Mouse. All wrongs reserved. #include "util.hpp" #include "../src/simple_script.hpp" #include "../src/runtime/global_context.hpp" using namespace asteria; int main() { Simple_Script code; code.reload_string( /////////////////////////////////////////////////////////////////////////////// ::rocket::sref(__FILE__), __LINE__, ::rocket::sref(R"__( func recur(n) { std.debug.logf("recur($1)", n + 1); return recur(n + 1) + 1; } return recur(0); /////////////////////////////////////////////////////////////////////////////// )__")); Global_Context global; ASTERIA_TEST_CHECK_CATCH(code.execute(global)); }
[ "lh_mouse@126.com" ]
lh_mouse@126.com
b42a363fd99bebee954c959e0e361d74c7e7994d
a8f3402afea0c2766bfa0c51c7234fcef1c113ef
/SBSystemBackup/global.cpp
62cb86dd7584ef397d017a0ccd325b7697b02852
[]
no_license
iceboundx/SBSystem
2c432af5b73acc0b63aebb244ddd9c710ce798e9
e305dd6bf761b085c29de7d0e13f99090a12cde7
refs/heads/master
2020-03-28T17:37:59.351135
2018-09-20T18:54:53
2018-09-20T18:54:53
148,809,159
2
1
null
null
null
null
UTF-8
C++
false
false
113
cpp
#include "global.h" SBSmanager *man; site empty_site; order empty_order; site init_site; QDateTime lst_vis_time;
[ "icebound1999@hotmail.com" ]
icebound1999@hotmail.com
1e03d65262eecb200ef5398b5f48027d7cf5c459
c9bdc65d2bbe24b75ae9f83461936605a266786b
/project1/tree_species.cpp
2e6e618dd3f58f320b4dc6dce12c38e833ffec74
[]
no_license
thomas-westfall/csci335
3c3ce25e3f3b787d2d09f02b5a44edd1c0ebff5e
93154a3a50e0c11431d18f3d34d6394c02ee0932
refs/heads/master
2020-04-26T11:28:06.026785
2019-05-13T02:28:02
2019-05-13T02:28:02
173,517,427
0
0
null
null
null
null
UTF-8
C++
false
false
5,024
cpp
#include <algorithm> #include "tree_species.h" TreeSpecies::TreeSpecies(){ sizev = 0; } TreeSpecies::~TreeSpecies(){ } void TreeSpecies::print_all_species(ostream & out) const{ //copy the vector to a temp vector, sort the temp, then print in order. vector<string> speciestemp; for(int i = 0; i < speciesv.size(); i++){ speciestemp.push_back(speciesv[i]); } sort(speciestemp.begin(),speciestemp.end()); for(int i = 0; i < speciestemp.size(); i++){ out<<speciestemp[i]<<endl; } } int TreeSpecies::number_of_species() const{ return sizev; } int TreeSpecies::add_species( const string & species){ //check if the species is already in treespecies. if not, add it int notfound = find(speciesv.begin(), speciesv.end(), species) == speciesv.end(); if(notfound){ speciesv.push_back(species); sizev++; } return notfound; } list<string> TreeSpecies::get_matching_species(const string & partial_name) const{ list<string> ans; //where the matching species names are stored string tree_type; //current species name string tree_to_find = ""; //= partial_name; //remove the leading space tacked on to partial_name from the command line if(partial_name.at(0) == ' '){ for(int k = 1; k < partial_name.length(); k++) tree_to_find = tree_to_find + partial_name.at(k); } string temp = "";//where each space/dash-seperated value is stored // bool ispecial = false; //does the current species have spaces/hyphens bool ispecialp = false; //does partial name have spaces/hyphens //for possibility 3 (both partialname and speciesname have special chars) int stillmatching = 0; //check if partialname still matches speciesname vector<string> v1; //each element is a vector<string> v2; //get a lowercase version of partial_name and tree_to_find transform(tree_to_find.begin(), tree_to_find.end(), tree_to_find.begin(), ::tolower); //check if partial name has spaces or dashes size_t found = tree_to_find.find(" "); size_t foundh = tree_to_find.find("-"); if(found != string::npos or foundh != string::npos) ispecialp = true; for(int i = 0; i < speciesv.size(); i++){ //make current species lowercase tree_type = speciesv[i]; transform(tree_type.begin(), tree_type.end(), tree_type.begin(), ::tolower); if(tree_type.compare(tree_to_find) == 0){ ans.push_back(speciesv[i]); continue; //avoid pushing the same species again } //check if current species has ' ' or '-' found = tree_type.find(" "); foundh = tree_type.find("-"); if(found != string::npos or foundh != string::npos) ispecial = true; //case 2: tree_to_find has no special chars but tree_species does if((!ispecialp) and (ispecial)){ temp = ""; //construct temp (current string separated by ' ' or '-' for(int k = 0; k < tree_type.length(); k++){ //temp is complete (reached a specialchar or end of string) if((tree_type.at(k) == ' ' or tree_type.at(k) == '-') or k == tree_type.length()-1){ if(k == tree_type.length() - 1){ temp = temp + tree_type.at(k); } //check if the current separated value is equal to partialname if(temp.compare(tree_to_find) == 0){ ans.push_back(speciesv[i]); break; } temp = ""; } //temp is incomplete, add current char to temp if(tree_type.at(k) != ' ' and tree_type.at(k) != '-') temp = temp + tree_type.at(k); } } //case 3: tree_to_find and tree_species both have special chars if((ispecialp) and (ispecial)){ v1.clear(); v2.clear(); temp = ""; //construct v1 (holds words of partial name seperated by ' ' or '-') for(int f = 0; f < tree_to_find.length();f++){ if((tree_to_find.at(f) == ' ' or tree_to_find.at(f) == '-') or f == tree_to_find.length() - 1){ if(f == tree_to_find.length() - 1) temp = temp + tree_to_find.at(f); v1.push_back(temp); temp = ""; continue; } if(tree_to_find.at(f) != ' ' and tree_to_find.at(f) != '-') temp = temp + tree_to_find.at(f); } temp = ""; //construct v2 (holds words of current species name) //seperated by ' ' or '-' for(int g = 0; g < tree_type.length(); g++){ if((tree_type.at(g) == ' ' or tree_type.at(g) == '-') or g == tree_type.length() - 1){ if(g == tree_type.length() - 1) temp = temp + tree_type.at(g); v2.push_back(temp); temp = ""; continue; } if(tree_type.at(g) != ' ' and tree_type.at(g) != '-') temp = temp + tree_type.at(g); } //iterate through v2 (currentspecies vector) //v2 is always at least one larger than v1 (since v1 is a partial name) //check if all of v1 (partial name) is in v2 (in order) stillmatching = 0; for(int d = 0; d < v2.size(); d++){ if(v2[d] == v1[stillmatching]) stillmatching++; else stillmatching = 0; if(v1[v1.size()-1] == v2[d] and stillmatching == v1.size()){ ans.push_back(speciesv[i]); break; } } } } return ans; }
[ "thomas.westfall64@myhunter.cuny.edu" ]
thomas.westfall64@myhunter.cuny.edu
95a08b8e2989d1f7e1ccb3bcf4ed9e2f56f845eb
1f9be2d5e42817e39ae2b9ef7ead5883b179b6bd
/GameApp/GoButton.cpp
6d56d02ed8c35e31e2f1c9c3b1d2deb15f23f37c
[]
no_license
shreyjindal81/CSE335-Project1
827a960cd93e2d2d3cc17478bfd22daf1dd46c1b
04c3bfb80419b79dadcea5e250ef5b5000edcb9f
refs/heads/master
2023-04-03T14:48:58.296090
2021-04-14T10:21:26
2021-04-14T10:21:26
357,852,477
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
#include "pch.h" #include "GoButton.h" #include "Game.h" #include "Tile.h" using namespace std; using namespace Gdiplus; /** Constructor * \param game The game this is a member of */ CGoButton::CGoButton(CGame* game) : CItem(game) { } /** * Destructor */ CGoButton::~CGoButton() { }
[ "shreyjindal81@gmail.com" ]
shreyjindal81@gmail.com
f488fec4f5dec308957c7cfd1e1fd553bef972d6
a8c2ab2fdcac66596773d737db5bc9fb84f27653
/src/clientversion.cpp
c990b70edfac2245f2f4d61cc056c279e5bb3ae8
[ "MIT" ]
permissive
blocksninja/das-coin
6d3ee0fd1d52292705cf241589ac172a9b69a8b5
c91484c5ec2f1c3001429104d28d45177a7c257b
refs/heads/master
2021-04-09T10:14:49.048660
2018-03-16T09:26:42
2018-03-16T09:26:42
115,623,990
0
0
null
null
null
null
UTF-8
C++
false
false
3,971
cpp
// Copyright (c) 2012-2014 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "clientversion.h" #include "tinyformat.h" #include <string> /** * Name of client reported in the 'version' message. Report the same name * for both dasd and das-qt, to make it harder for attackers to * target servers or GUI users specifically. */ const std::string CLIENT_NAME("Das Core"); /** * Client version number */ #define CLIENT_VERSION_SUFFIX "" /** * The following part of the code determines the CLIENT_BUILD variable. * Several mechanisms are used for this: * * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is * generated by the build environment, possibly containing the output * of git-describe in a macro called BUILD_DESC * * secondly, if this is an exported version of the code, GIT_ARCHIVE will * be defined (automatically using the export-subst git attribute), and * GIT_COMMIT will contain the commit id. * * then, three options exist for determining CLIENT_BUILD: * * if BUILD_DESC is defined, use that literally (output of git-describe) * * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit] * * otherwise, use v[maj].[min].[rev].[build]-unk * finally CLIENT_VERSION_SUFFIX is added */ //! First, include build.h if requested #ifdef HAVE_BUILD_INFO #include "build.h" #endif //! git will put "#define GIT_ARCHIVE 1" on the next line inside archives. //#define GIT_ARCHIVE 1 #ifdef GIT_ARCHIVE #define GIT_COMMIT_ID " 92d7461" #define GIT_COMMIT_DATE "Jul 23, 2017" #endif #define BUILD_DESC_WITH_SUFFIX(maj, min, rev, build, suffix) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-" DO_STRINGIZE(suffix) #define BUILD_DESC_FROM_COMMIT(maj, min, rev, build, commit) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit #define BUILD_DESC_FROM_UNKNOWN(maj, min, rev, build) \ "v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk" #ifndef BUILD_DESC #ifdef BUILD_SUFFIX #define BUILD_DESC BUILD_DESC_WITH_SUFFIX(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, BUILD_SUFFIX) #elif defined(GIT_COMMIT_ID) #define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID) #else #define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) #endif #endif #ifndef BUILD_DATE #ifdef GIT_COMMIT_DATE #define BUILD_DATE GIT_COMMIT_DATE #else #define BUILD_DATE __DATE__ ", " __TIME__ #endif #endif const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX); const std::string CLIENT_DATE(BUILD_DATE); static std::string FormatVersion(int nVersion) { if (nVersion % 100 == 0) return strprintf("%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100); else return strprintf("%d.%d.%d.%d", nVersion / 1000000, (nVersion / 10000) % 100, (nVersion / 100) % 100, nVersion % 100); } std::string FormatFullVersion() { return CLIENT_BUILD; } /** * Format the subversion field according to BIP 14 spec (https://github.com/bitcoin/bips/blob/master/bip-0014.mediawiki) */ std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) { std::vector<std::string>::const_iterator it(comments.begin()); ss << "(" << *it; for(++it; it != comments.end(); ++it) ss << "; " << *it; ss << ")"; } ss << "/"; return ss.str(); }
[ "183516+blocksninja@users.noreply.github.com" ]
183516+blocksninja@users.noreply.github.com
b109033c85ebd03a55c0432f54b76e6f14f1f659
3aa06b06c2c7007f1e3dee1f71c913ce43605e6a
/Windows API/002-InitializeDirectX/Sample/DirectXEnvironment.cpp
3a51b405dee18c1ff0bb693e0cf6a69ee0eebc1c
[ "MIT" ]
permissive
lightyen/DirectX-Sample
819d389b10ccc8660dc4a19acb55ec6c3fbdaa95
71fda4cf23a49bbe618fbb306c9a33ffcc4ce311
refs/heads/master
2020-03-10T11:21:37.904215
2018-05-28T09:31:14
2018-05-28T09:31:14
129,354,873
0
0
null
null
null
null
BIG5
C++
false
false
4,232
cpp
#include "stdafx.h" #include "DirectXEnvironment.h" #define CHECKRETURN(a,b) if (CheckFailed(a,b)) { \ return; \ } namespace DirectX { BOOL DirectXIsReady; D3D_FEATURE_LEVEL FeatureLevel; ComPtr<IDXGIFactory2> DXGIFactory; ComPtr<IDXGIAdapter2> DXGIAdapter; ComPtr<ID3D11Device> D3D11Device; ComPtr<IDXGISwapChain1> SwapChain; ComPtr<ID3D11DeviceContext> Context; ComPtr<ID3D11Texture2D> BackBuffer; ComPtr<ID3D11RenderTargetView> RenderTargetView; void InitializeDirectX(HWND hWnd, D3D11_CREATE_DEVICE_FLAG flags) { HRESULT result = E_FAIL; if (DirectXIsReady) return; // 獲得DXGI介面 ComPtr<IDXGIFactory> _dxgiFactory; result = CreateDXGIFactory(IID_PPV_ARGS(&_dxgiFactory)); CHECKRETURN(result, TEXT("CreateDXGIFactory")); result = _dxgiFactory.As(&DXGIFactory); CHECKRETURN(result,TEXT("Get DXGIFactory2")); // 列舉所有繪圖介面卡 vector<ComPtr<IDXGIAdapter1>> adapters = EnumerateAdapters(DXGIFactory); // 選擇一個高效能介面卡 ComPtr<IDXGIAdapter1> adpater = FindHardwareAdapter(adapters); result = adpater.As(&DXGIAdapter); CHECKRETURN(result, TEXT("Get DXGIAdapter1")); ComPtr<IDXGIAdapter> adapter0; result = DXGIAdapter.As(&adapter0); CHECKRETURN(result, TEXT("Get DXGIAdapter")); // 建立Direct3D 11 Device D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, }; result = D3D11CreateDevice(adapter0.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, flags, featureLevels, ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, &D3D11Device, &FeatureLevel, &Context); CHECKRETURN(result, TEXT("Create D3D11 Device")); DXGI_SWAP_CHAIN_DESC1 desc; ZeroMemory(&desc, sizeof(DXGI_SWAP_CHAIN_DESC1)); desc.BufferCount = 2; desc.Width = 0; //auto sizing desc.Height = 0; //auto sizing desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL; desc.BufferUsage = DXGI_USAGE_BACK_BUFFER | DXGI_USAGE_RENDER_TARGET_OUTPUT; result = DXGIFactory->CreateSwapChainForHwnd(D3D11Device.Get(), hWnd, &desc, nullptr, nullptr, &SwapChain); CHECKRETURN(result, TEXT("Create SwapChain")); DirectXIsReady = TRUE; } void CreateRenderTargetView() { HRESULT hr; if (!DirectXIsReady) return; hr = SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&BackBuffer); CHECKRETURN(hr, TEXT("Get BackBuffer")); hr = D3D11Device->CreateRenderTargetView(BackBuffer.Get(), nullptr, &RenderTargetView); CHECKRETURN(hr, TEXT("CreateRenderTargetView")); } vector<ComPtr<IDXGIAdapter1>> EnumerateAdapters(const ComPtr<IDXGIFactory2>& DXGIFactory) { vector<ComPtr<IDXGIAdapter1>> adapters; ComPtr<IDXGIAdapter1> pAdapter; for (UINT i = 0; DXGIFactory->EnumAdapters1(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++i) { adapters.push_back(pAdapter); } return adapters; } ComPtr<IDXGIAdapter1> FindHardwareAdapter(const vector<ComPtr<IDXGIAdapter1>>& vAdapters) { DXGI_ADAPTER_DESC1 desc; for (const auto& p : vAdapters) { p->GetDesc1(&desc); // NVIDIA if (desc.VendorId == 0x10DE) { return p; } } for (const auto& p : vAdapters) { p->GetDesc1(&desc); // AMD if (desc.VendorId == 0x1022) { return p; } } for (const auto& p : vAdapters) { p->GetDesc1(&desc); // AMD if (desc.VendorId == 0x8086) { return p; } } if (vAdapters.size()) return *vAdapters.begin(); return ComPtr<IDXGIAdapter1>(); } String GetFeatureLevelString() { switch (FeatureLevel) { case D3D_FEATURE_LEVEL_12_1: return TEXT("Direct3D 12.1"); case D3D_FEATURE_LEVEL_12_0: return TEXT("Direct3D 12.0"); case D3D_FEATURE_LEVEL_11_1: return TEXT("Direct3D 11.1"); case D3D_FEATURE_LEVEL_11_0: return TEXT("Direct3D 11.0"); case D3D_FEATURE_LEVEL_10_1: return TEXT("Direct3D 10.1"); case D3D_FEATURE_LEVEL_10_0: return TEXT("Direct3D 10.0"); case D3D_FEATURE_LEVEL_9_3: return TEXT("Direct3D 9.3"); case D3D_FEATURE_LEVEL_9_2: return TEXT("Direct3D 9.2"); case D3D_FEATURE_LEVEL_9_1: return TEXT("Direct3D 9.1"); default: return TEXT("Direct3D Unknown"); } } }
[ "lightyen0123@gmail.com" ]
lightyen0123@gmail.com
d35160a3fdacc6488563f18a6525fbde718f27b9
2b00823785bb182898609d5565d39cba92036840
/src/vgui2/vgui_controls/BuildGroup.cpp
ec7dba221b1e90921e004c004a9ecee129f1c23f
[]
no_license
rlabrecque/Source2007SDKTemplate
4d401595c0381b6fb46cef5bbfc2bcd31fe2a12d
2e3c7e4847342f575d145452c6246b296e6eee67
refs/heads/master
2021-01-10T20:44:46.700845
2012-10-18T23:47:21
2012-10-18T23:47:21
5,194,511
3
1
null
null
null
null
WINDOWS-1252
C++
false
false
38,932
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// //========= Copyright © 1996-2003, Valve LLC, All rights reserved. ============ // // The copyright to the contents herein is the property of Valve, L.L.C. // The contents may be used and/or copied only with the written permission of // Valve, L.L.C., or in accordance with the terms and conditions stipulated in // the agreement/contract under which the contents have been supplied. // // Purpose: // // $NoKeywords: $ //============================================================================= #include <stdio.h> #define PROTECTED_THINGS_DISABLE #include "utldict.h" #include <vgui/KeyCode.h> #include <vgui/Cursor.h> #include <vgui/MouseCode.h> #include <KeyValues.h> #include <vgui/IInput.h> #include <vgui/ISystem.h> #include <vgui/IVGui.h> #include <vgui/ISurface.h> #include <vgui_controls/BuildGroup.h> #include <vgui_controls/Panel.h> #include <vgui_controls/PHandle.h> #include <vgui_controls/Label.h> #include <vgui_controls/EditablePanel.h> #include <vgui_controls/MessageBox.h> #include "filesystem.h" #if defined( _X360 ) #include "xbox/xbox_win32stubs.h" #endif // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> using namespace vgui; //----------------------------------------------------------------------------- // Handle table //----------------------------------------------------------------------------- IMPLEMENT_HANDLES( BuildGroup, 20 ) //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- BuildGroup::BuildGroup(Panel *parentPanel, Panel *contextPanel) { CONSTRUCT_HANDLE( ); _enabled=false; _snapX=1; _snapY=1; _cursor_sizenwse = dc_sizenwse; _cursor_sizenesw = dc_sizenesw; _cursor_sizewe = dc_sizewe; _cursor_sizens = dc_sizens; _cursor_sizeall = dc_sizeall; _currentPanel=null; _dragging=false; m_pResourceName=NULL; m_pResourcePathID = NULL; m_hBuildDialog=NULL; m_pParentPanel=parentPanel; for (int i=0; i<4; ++i) _rulerNumber[i] = NULL; SetContextPanel(contextPanel); _controlGroup = NULL; _groupDeltaX = 0; _groupDeltaX = 0; _showRulers = false; } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- BuildGroup::~BuildGroup() { if (m_hBuildDialog) delete m_hBuildDialog.Get(); m_hBuildDialog = NULL; delete [] m_pResourceName; delete [] m_pResourcePathID; for (int i=0; i <4; ++i) { if (_rulerNumber[i]) { delete _rulerNumber[i]; _rulerNumber[i]= NULL; } } DESTRUCT_HANDLE(); } //----------------------------------------------------------------------------- // Purpose: Toggles build mode on/off // Input : state - new state //----------------------------------------------------------------------------- void BuildGroup::SetEnabled(bool state) { if(_enabled != state) { _enabled = state; _currentPanel = NULL; if ( state ) { ActivateBuildDialog(); } else { // hide the build dialog if ( m_hBuildDialog ) { m_hBuildDialog->OnCommand("Close"); } // request focus for our main panel m_pParentPanel->RequestFocus(); } } } //----------------------------------------------------------------------------- // Purpose: Check if buildgroup is enabled //----------------------------------------------------------------------------- bool BuildGroup::IsEnabled() { return _enabled; } //----------------------------------------------------------------------------- // Purpose: Get the list of panels that are currently selected //----------------------------------------------------------------------------- CUtlVector<PHandle> *BuildGroup::GetControlGroup() { return &_controlGroup; } //----------------------------------------------------------------------------- // Purpose: Check if ruler display is activated //----------------------------------------------------------------------------- bool BuildGroup::HasRulersOn() { return _showRulers; } //----------------------------------------------------------------------------- // Purpose: Toggle ruler display //----------------------------------------------------------------------------- void BuildGroup::ToggleRulerDisplay() { _showRulers = !_showRulers; if (_rulerNumber[0] == NULL) // rulers haven't been initialized { _rulerNumber[0] = new Label(m_pBuildContext, NULL, ""); _rulerNumber[1] = new Label(m_pBuildContext, NULL, ""); _rulerNumber[2] = new Label(m_pBuildContext, NULL, ""); _rulerNumber[3] = new Label(m_pBuildContext, NULL, ""); } SetRulerLabelsVisible(_showRulers); m_pBuildContext->Repaint(); } //----------------------------------------------------------------------------- // Purpose: Tobble visibility of ruler number labels //----------------------------------------------------------------------------- void BuildGroup::SetRulerLabelsVisible(bool state) { _rulerNumber[0]->SetVisible(state); _rulerNumber[1]->SetVisible(state); _rulerNumber[2]->SetVisible(state); _rulerNumber[3]->SetVisible(state); } void BuildGroup::ApplySchemeSettings( IScheme *pScheme ) { DrawRulers(); } //----------------------------------------------------------------------------- // Purpose: Draw Rulers on screen if conditions are right //----------------------------------------------------------------------------- void BuildGroup::DrawRulers() { // don't draw if visibility is off if (!_showRulers) { return; } // no drawing if we selected the context panel if (m_pBuildContext == _currentPanel) { SetRulerLabelsVisible(false); return; } else SetRulerLabelsVisible(true); int x, y, wide, tall; // get base panel's postition m_pBuildContext->GetBounds(x, y, wide, tall); m_pBuildContext->ScreenToLocal(x,y); int cx, cy, cwide, ctall; _currentPanel->GetBounds (cx, cy, cwide, ctall); surface()->PushMakeCurrent(m_pBuildContext->GetVPanel(), false); // draw rulers surface()->DrawSetColor(255, 255, 255, 255); // white color surface()->DrawFilledRect(0, cy, cx, cy+1); //top horiz left surface()->DrawFilledRect(cx+cwide, cy, wide, cy+1); //top horiz right surface()->DrawFilledRect(0, cy+ctall-1, cx, cy+ctall); //bottom horiz left surface()->DrawFilledRect(cx+cwide, cy+ctall-1, wide, cy+ctall); //bottom horiz right surface()->DrawFilledRect(cx,0,cx+1,cy); //top vert left surface()->DrawFilledRect(cx+cwide-1,0, cx+cwide, cy); //top vert right surface()->DrawFilledRect(cx,cy+ctall, cx+1, tall); //bottom vert left surface()->DrawFilledRect(cx+cwide-1, cy+ctall, cx+cwide, tall); //bottom vert right surface()->PopMakeCurrent(m_pBuildContext->GetVPanel()); // now let's put numbers with the rulers char textstring[20]; Q_snprintf (textstring, sizeof( textstring ), "%d", cx); _rulerNumber[0]->SetText(textstring); int twide, ttall; _rulerNumber[0]->GetContentSize(twide,ttall); _rulerNumber[0]->SetSize(twide,ttall); _rulerNumber[0]->SetPos(cx/2-twide/2, cy-ttall+3); Q_snprintf (textstring, sizeof( textstring ), "%d", cy); _rulerNumber[1]->SetText(textstring); _rulerNumber[1]->GetContentSize(twide,ttall); _rulerNumber[1]->SetSize(twide,ttall); _rulerNumber[1]->GetSize(twide,ttall); _rulerNumber[1]->SetPos(cx-twide + 3, cy/2-ttall/2); Q_snprintf (textstring, sizeof( textstring ), "%d", cy); _rulerNumber[2]->SetText(textstring); _rulerNumber[2]->GetContentSize(twide,ttall); _rulerNumber[2]->SetSize(twide,ttall); _rulerNumber[2]->SetPos(cx+cwide+(wide-cx-cwide)/2 - twide/2, cy+ctall-3); Q_snprintf (textstring, sizeof( textstring ), "%d", cy); _rulerNumber[3]->SetText(textstring); _rulerNumber[3]->GetContentSize(twide,ttall); _rulerNumber[3]->SetSize(twide,ttall); _rulerNumber[3]->SetPos(cx+cwide, cy+ctall+(tall-cy-ctall)/2 - ttall/2); } //----------------------------------------------------------------------------- // Purpose: respond to cursor movments //----------------------------------------------------------------------------- bool BuildGroup::CursorMoved(int x, int y, Panel *panel) { Assert(panel); if ( !m_hBuildDialog.Get() ) { if ( panel->GetParent() ) { EditablePanel *ep = dynamic_cast< EditablePanel * >( panel->GetParent() ); if ( ep ) { BuildGroup *bg = ep->GetBuildGroup(); if ( bg && bg != this ) { bg->CursorMoved( x, y, panel ); } } } return false; } // no moving uneditable panels // commented out because this has issues with panels moving // to front and obscuring other panels //if (!panel->IsBuildModeEditable()) // return; if (_dragging) { input()->GetCursorPos(x, y); if (_dragMouseCode == MOUSE_RIGHT) { int newW = max( 1, _dragStartPanelSize[ 0 ] + x - _dragStartCursorPos[0] ); int newH = max( 1, _dragStartPanelSize[ 1 ] + y - _dragStartCursorPos[1] ); bool shift = ( input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT) ); bool ctrl = ( input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL) ); if ( shift ) { newW = _dragStartPanelSize[ 0 ]; } if ( ctrl ) { newH = _dragStartPanelSize[ 1 ]; } panel->SetSize( newW, newH ); ApplySnap(panel); } else { for (int i=0; i < _controlGroup.Count(); ++i) { // now fix offset of member panels with respect to the one we are dragging Panel *groupMember = _controlGroup[i].Get(); groupMember->SetPos(_dragStartPanelPos[0] + _groupDeltaX[i] +(x-_dragStartCursorPos[0]), _dragStartPanelPos[1] + _groupDeltaY[i] +(y-_dragStartCursorPos[1])); ApplySnap(groupMember); } } // update the build dialog if (m_hBuildDialog) { KeyValues *keyval = new KeyValues("UpdateControlData"); keyval->SetPtr("panel", GetCurrentPanel()); ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), keyval, NULL); keyval = new KeyValues("EnableSaveButton"); ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), keyval, NULL); } panel->Repaint(); panel->CallParentFunction(new KeyValues("Repaint")); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool BuildGroup::MousePressed(MouseCode code, Panel *panel) { Assert(panel); if ( !m_hBuildDialog.Get() ) { if ( panel->GetParent() ) { EditablePanel *ep = dynamic_cast< EditablePanel * >( panel->GetParent() ); if ( ep ) { BuildGroup *bg = ep->GetBuildGroup(); if ( bg && bg != this ) { bg->MousePressed( code, panel ); } } } return false; } // if people click on the base build dialog panel. if (panel == m_hBuildDialog) { // hide the click menu if its up ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("HideNewControlMenu"), NULL); return true; } // don't select unnamed items if (strlen(panel->GetName()) < 1) return true; bool shift = ( input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT) ); if (!shift) { _controlGroup.RemoveAll(); } // Show new ctrl menu if they click on the bg (not on a subcontrol) if ( code == MOUSE_RIGHT && panel == GetContextPanel()) { // trigger a drop down menu to create new controls ivgui()->PostMessage (m_hBuildDialog->GetVPanel(), new KeyValues("ShowNewControlMenu"), NULL); } else { // don't respond if we click on ruler numbers if (_showRulers) // rulers are visible { for ( int i=0; i < 4; i++) { if ( panel == _rulerNumber[i]) return true; } } _dragging = true; _dragMouseCode = code; ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("HideNewControlMenu"), NULL); int x, y; input()->GetCursorPos(x, y); _dragStartCursorPos[0] = x; _dragStartCursorPos[1] = y; input()->SetMouseCapture(panel->GetVPanel()); _groupDeltaX.RemoveAll(); _groupDeltaY.RemoveAll(); // basepanel is the panel that all the deltas will be calculated from. // it is the last panel we clicked in because if we move the panels as a group // it would be from that one Panel *basePanel = NULL; // find the panel we clicked in, that is the base panel // it might already be in the group for (int i=0; i< _controlGroup.Count(); ++i) { if (panel == _controlGroup[i].Get()) { basePanel = panel; break; } } // if its not in the group we just added this panel. get it in the group if (basePanel == NULL) { PHandle temp; temp = panel; _controlGroup.AddToTail(temp); basePanel = panel; } basePanel->GetPos(x,y); _dragStartPanelPos[0]=x; _dragStartPanelPos[1]=y; basePanel->GetSize( _dragStartPanelSize[ 0 ], _dragStartPanelSize[ 1 ] ); // figure out the deltas of the other panels from the base panel for (int i=0; i<_controlGroup.Count(); ++i) { int cx, cy; _controlGroup[i].Get()->GetPos(cx, cy); _groupDeltaX.AddToTail(cx - x); _groupDeltaY.AddToTail(cy - y); } // if this panel wasn't already selected update the buildmode dialog controls to show its info if(_currentPanel != panel) { _currentPanel = panel; if ( m_hBuildDialog ) { // think this is taken care of by SetActiveControl. //ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("ApplyDataToControls"), NULL); KeyValues *keyval = new KeyValues("SetActiveControl"); keyval->SetPtr("PanelPtr", GetCurrentPanel()); ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), keyval, NULL); } } // store undo information upon panel selection. ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("StoreUndo"), NULL); panel->RequestFocus(); } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool BuildGroup::MouseReleased(MouseCode code, Panel *panel) { if ( !m_hBuildDialog.Get() ) { if ( panel->GetParent() ) { EditablePanel *ep = dynamic_cast< EditablePanel * >( panel->GetParent() ); if ( ep ) { BuildGroup *bg = ep->GetBuildGroup(); if ( bg && bg != this ) { bg->MouseReleased( code, panel ); } } } return false; } Assert(panel); _dragging=false; input()->SetMouseCapture(null); return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool BuildGroup::MouseDoublePressed(MouseCode code, Panel *panel) { Assert(panel); return MousePressed( code, panel ); } bool BuildGroup::KeyTyped( wchar_t unichar, Panel *panel ) { if ( !m_hBuildDialog.Get() ) { if ( panel->GetParent() ) { EditablePanel *ep = dynamic_cast< EditablePanel * >( panel->GetParent() ); if ( ep ) { BuildGroup *bg = ep->GetBuildGroup(); if ( bg && bg != this ) { bg->KeyTyped( unichar, panel ); } } } return false; } return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool BuildGroup::KeyCodeTyped(KeyCode code, Panel *panel) { if ( !m_hBuildDialog.Get() ) { if ( panel->GetParent() ) { EditablePanel *ep = dynamic_cast< EditablePanel * >( panel->GetParent() ); if ( ep ) { BuildGroup *bg = ep->GetBuildGroup(); if ( bg && bg != this ) { bg->KeyCodeTyped( code, panel ); } } } return false; } Assert(panel); int dx=0; int dy=0; bool shift = ( input()->IsKeyDown(KEY_LSHIFT) || input()->IsKeyDown(KEY_RSHIFT) ); bool ctrl = ( input()->IsKeyDown(KEY_LCONTROL) || input()->IsKeyDown(KEY_RCONTROL) ); bool alt = (input()->IsKeyDown(KEY_LALT) || input()->IsKeyDown(KEY_RALT)); if ( ctrl && shift && alt && code == KEY_B) { // enable build mode EditablePanel *ep = dynamic_cast< EditablePanel * >( panel ); if ( ep ) { ep->ActivateBuildMode(); } return true; } switch (code) { case KEY_LEFT: { dx-=_snapX; break; } case KEY_RIGHT: { dx+=_snapX; break; } case KEY_UP: { dy-=_snapY; break; } case KEY_DOWN: { dy+=_snapY; break; } case KEY_DELETE: { // delete the panel we have selected ivgui()->PostMessage (m_hBuildDialog->GetVPanel(), new KeyValues ("DeletePanel"), NULL); break; } } if (ctrl) { switch (code) { case KEY_Z: { ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("Undo"), NULL); break; } case KEY_C: { ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("Copy"), NULL); break; } case KEY_V: { ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("Paste"), NULL); break; } } } if(dx||dy) { //TODO: make this stuff actually snap int x,y,wide,tall; panel->GetBounds(x,y,wide,tall); if(shift) { panel->SetSize(wide+dx,tall+dy); } else { panel->SetPos(x+dx,y+dy); } ApplySnap(panel); panel->Repaint(); if (panel->GetVParent() != NULL) { panel->PostMessage(panel->GetVParent(), new KeyValues("Repaint")); } // update the build dialog if (m_hBuildDialog) { // post that it's active KeyValues *keyval = new KeyValues("SetActiveControl"); keyval->SetPtr("PanelPtr", GetCurrentPanel()); ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), keyval, NULL); // post that it's been changed ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), new KeyValues("PanelMoved"), NULL); } } // If holding key while dragging, simulate moving cursor so shift/ctrl key changes take effect if ( _dragging && panel != GetContextPanel() ) { int x, y; input()->GetCursorPos( x, y ); CursorMoved( x, y, panel ); } return true; } bool BuildGroup::KeyCodeReleased(KeyCode code, Panel *panel ) { if ( !m_hBuildDialog.Get() ) { if ( panel->GetParent() ) { EditablePanel *ep = dynamic_cast< EditablePanel * >( panel->GetParent() ); if ( ep ) { BuildGroup *bg = ep->GetBuildGroup(); if ( bg && bg != this ) { bg->KeyCodeTyped( code, panel ); } } } return false; } // If holding key while dragging, simulate moving cursor so shift/ctrl key changes take effect if ( _dragging && panel != GetContextPanel() ) { int x, y; input()->GetCursorPos( x, y ); CursorMoved( x, y, panel ); } return true; } //----------------------------------------------------------------------------- // Purpose: Searches for a BuildModeDialog in the hierarchy //----------------------------------------------------------------------------- Panel *BuildGroup::CreateBuildDialog( void ) { // request the panel Panel *buildDialog = NULL; KeyValues *data = new KeyValues("BuildDialog"); data->SetPtr("BuildGroupPtr", this); if (m_pBuildContext->RequestInfo(data)) { buildDialog = (Panel *)data->GetPtr("PanelPtr"); } // initialize the build dialog if found if ( buildDialog ) { input()->ReleaseAppModalSurface(); } return buildDialog; } //----------------------------------------------------------------------------- // Purpose: Activates the build mode settings dialog //----------------------------------------------------------------------------- void BuildGroup::ActivateBuildDialog( void ) { // create the build mode dialog first time through if (!m_hBuildDialog.Get()) { m_hBuildDialog = CreateBuildDialog(); if (!m_hBuildDialog.Get()) return; } m_hBuildDialog->SetVisible( true ); // send a message to set the initial dialog controls info _currentPanel = m_pParentPanel; KeyValues *keyval = new KeyValues("SetActiveControl"); keyval->SetPtr("PanelPtr", GetCurrentPanel()); ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), keyval, NULL); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- HCursor BuildGroup::GetCursor(Panel *panel) { Assert(panel); int x,y,wide,tall; input()->GetCursorPos(x,y); panel->ScreenToLocal(x,y); panel->GetSize(wide,tall); if(x < 2) { if(y < 4) { return _cursor_sizenwse; } else if(y<(tall-4)) { return _cursor_sizewe; } else { return _cursor_sizenesw; } } return _cursor_sizeall; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void BuildGroup::ApplySnap(Panel *panel) { Assert(panel); int x,y,wide,tall; panel->GetBounds(x,y,wide,tall); x=(x/_snapX)*_snapX; y=(y/_snapY)*_snapY; panel->SetPos(x,y); int xx,yy; xx=x+wide; yy=y+tall; xx=(xx/_snapX)*_snapX; yy=(yy/_snapY)*_snapY; panel->SetSize(xx-x,yy-y); } //----------------------------------------------------------------------------- // Purpose: Return the currently selected panel //----------------------------------------------------------------------------- Panel *BuildGroup::GetCurrentPanel() { return _currentPanel; } //----------------------------------------------------------------------------- // Purpose: Add panel the list of panels that are in the build group //----------------------------------------------------------------------------- void BuildGroup::PanelAdded(Panel *panel) { Assert(panel); PHandle temp; temp = panel; int c = _panelDar.Count(); for ( int i = 0; i < c; ++i ) { if ( _panelDar[ i ] == temp ) { return; } } _panelDar.AddToTail(temp); } //----------------------------------------------------------------------------- // Purpose: loads the control settings from file //----------------------------------------------------------------------------- void BuildGroup::LoadControlSettings(const char *controlResourceName, const char *pathID, KeyValues *pPreloadedKeyValues) { // make sure the file is registered RegisterControlSettingsFile(controlResourceName, pathID); // Use the keyvalues they passed in or load them. KeyValues *rDat = pPreloadedKeyValues; if ( !rDat ) { // load the resource data from the file rDat = new KeyValues(controlResourceName); // check the skins directory first, if an explicit pathID hasn't been set bool bSuccess = false; if (!pathID) { bSuccess = rDat->LoadFromFile(g_pFullFileSystem, controlResourceName, "SKIN"); } if (!bSuccess) { bSuccess = rDat->LoadFromFile(g_pFullFileSystem, controlResourceName, pathID); } if ( bSuccess ) { if ( IsX360() ) { rDat->ProcessResolutionKeys( surface()->GetResolutionKey() ); } if ( IsPC() ) { ConVarRef cl_hud_minmode( "cl_hud_minmode", true ); if ( cl_hud_minmode.IsValid() && cl_hud_minmode.GetBool() ) { rDat->ProcessResolutionKeys( "_minmode" ); } } } } // save off the resource name delete [] m_pResourceName; m_pResourceName = new char[strlen(controlResourceName) + 1]; strcpy(m_pResourceName, controlResourceName); if (pathID) { delete [] m_pResourcePathID; m_pResourcePathID = new char[strlen(pathID) + 1]; strcpy(m_pResourcePathID, pathID); } // delete any controls not in both files DeleteAllControlsCreatedByControlSettingsFile(); // loop through the resource data sticking info into controls ApplySettings(rDat); if (m_pParentPanel) { m_pParentPanel->InvalidateLayout(); m_pParentPanel->Repaint(); } if ( rDat != pPreloadedKeyValues ) { rDat->deleteThis(); } } //----------------------------------------------------------------------------- // Purpose: registers that a control settings file may be loaded // use when the dialog may have multiple states and the editor will need to be able to switch between them //----------------------------------------------------------------------------- void BuildGroup::RegisterControlSettingsFile(const char *controlResourceName, const char *pathID) { // add the file into a list for build mode CUtlSymbol sym(controlResourceName); if (!m_RegisteredControlSettingsFiles.IsValidIndex(m_RegisteredControlSettingsFiles.Find(sym))) { m_RegisteredControlSettingsFiles.AddToTail(sym); } } //----------------------------------------------------------------------------- // Purpose: data accessor / iterator //----------------------------------------------------------------------------- int BuildGroup::GetRegisteredControlSettingsFileCount() { return m_RegisteredControlSettingsFiles.Count(); } //----------------------------------------------------------------------------- // Purpose: data accessor //----------------------------------------------------------------------------- const char *BuildGroup::GetRegisteredControlSettingsFileByIndex(int index) { return m_RegisteredControlSettingsFiles[index].String(); } //----------------------------------------------------------------------------- // Purpose: reloads the control settings from file //----------------------------------------------------------------------------- void BuildGroup::ReloadControlSettings() { delete m_hBuildDialog.Get(); m_hBuildDialog = NULL; // loop though objects in the current control group and remove them all // the 0th panel is always the contextPanel which is not deletable for( int i = 1; i < _panelDar.Count(); i++ ) { if (!_panelDar[i].Get()) // this can happen if we had two of the same handle in the list { _panelDar.Remove(i); --i; continue; } // only delete deletable panels, as the only deletable panels // are the ones created using the resource file if ( _panelDar[i].Get()->IsBuildModeDeletable()) { delete _panelDar[i].Get(); _panelDar.Remove(i); --i; } } if (m_pResourceName) { EditablePanel *edit = dynamic_cast<EditablePanel *>(m_pParentPanel); if (edit) { edit->LoadControlSettings(m_pResourceName, m_pResourcePathID); } else { LoadControlSettings(m_pResourceName, m_pResourcePathID); } } _controlGroup.RemoveAll(); ActivateBuildDialog(); } //----------------------------------------------------------------------------- // Purpose: changes which control settings are currently loaded //----------------------------------------------------------------------------- void BuildGroup::ChangeControlSettingsFile(const char *controlResourceName) { // clear any current state _controlGroup.RemoveAll(); _currentPanel = m_pParentPanel; // load the new state, via the dialog if possible EditablePanel *edit = dynamic_cast<EditablePanel *>(m_pParentPanel); if (edit) { edit->LoadControlSettings(controlResourceName, m_pResourcePathID); } else { LoadControlSettings(controlResourceName, m_pResourcePathID); } // force it to update KeyValues *keyval = new KeyValues("SetActiveControl"); keyval->SetPtr("PanelPtr", GetCurrentPanel()); ivgui()->PostMessage(m_hBuildDialog->GetVPanel(), keyval, NULL); } //----------------------------------------------------------------------------- // Purpose: saves control settings to file //----------------------------------------------------------------------------- bool BuildGroup::SaveControlSettings( void ) { bool bSuccess = false; if ( m_pResourceName ) { KeyValues *rDat = new KeyValues( m_pResourceName ); // get the data from our controls GetSettings( rDat ); char fullpath[ 512 ]; g_pFullFileSystem->RelativePathToFullPath( m_pResourceName, m_pResourcePathID, fullpath, sizeof( fullpath ) ); // save the data out to a file bSuccess = rDat->SaveToFile( g_pFullFileSystem, fullpath, NULL ); if (!bSuccess) { MessageBox *dlg = new MessageBox("BuildMode - Error saving file", "Error: Could not save changes. File is most likely read only."); dlg->DoModal(); } rDat->deleteThis(); } return bSuccess; } //----------------------------------------------------------------------------- // Purpose: Deletes all the controls not created by the code //----------------------------------------------------------------------------- void BuildGroup::DeleteAllControlsCreatedByControlSettingsFile() { // loop though objects in the current control group and remove them all // the 0th panel is always the contextPanel which is not deletable for ( int i = 1; i < _panelDar.Count(); i++ ) { if (!_panelDar[i].Get()) // this can happen if we had two of the same handle in the list { _panelDar.Remove(i); --i; continue; } // only delete deletable panels, as the only deletable panels // are the ones created using the resource file if ( _panelDar[i].Get()->IsBuildModeDeletable()) { delete _panelDar[i].Get(); _panelDar.Remove(i); --i; } } _currentPanel = m_pBuildContext; _currentPanel->InvalidateLayout(); m_pBuildContext->Repaint(); } //----------------------------------------------------------------------------- // Purpose: serializes settings from a resource data container //----------------------------------------------------------------------------- void BuildGroup::ApplySettings( KeyValues *resourceData ) { // loop through all the keys, applying them wherever for (KeyValues *controlKeys = resourceData->GetFirstSubKey(); controlKeys != NULL; controlKeys = controlKeys->GetNextKey()) { bool bFound = false; // Skip keys that are atomic.. if (controlKeys->GetDataType() != KeyValues::TYPE_NONE) continue; char const *keyName = controlKeys->GetName(); // check to see if any buildgroup panels have this name for ( int i = 0; i < _panelDar.Count(); i++ ) { Panel *panel = _panelDar[i].Get(); if (!panel) // this can happen if we had two of the same handle in the list { _panelDar.Remove(i); --i; continue; } Assert (panel); // make the control name match CASE INSENSITIVE! char const *panelName = panel->GetName(); if (!Q_stricmp(panelName, keyName)) { // apply the settings panel->ApplySettings(controlKeys); bFound = true; break; } } if ( !bFound ) { // the key was not found in the registered list, check to see if we should create it if ( keyName /*controlKeys->GetInt("AlwaysCreate", false)*/ ) { // create the control even though it wasn't registered NewControl( controlKeys ); } } } } //----------------------------------------------------------------------------- // Purpose: Create a new control in the context panel // Input: name: class name of control to create // controlKeys: keyvalues of settings for the panel. // name OR controlKeys should be set, not both. // x,y position relative to base panel // Output: Panel *newPanel, NULL if failed to create new control. //----------------------------------------------------------------------------- Panel *BuildGroup::NewControl( const char *name, int x, int y) { Assert (name); Panel *newPanel = NULL; // returns NULL on failure newPanel = static_cast<EditablePanel *>(m_pParentPanel)->CreateControlByName(name); if (newPanel) { // panel successfully created newPanel->SetParent(m_pParentPanel); newPanel->SetBuildGroup(this); newPanel->SetPos(x, y); char newFieldName[255]; GetNewFieldName(newFieldName, sizeof(newFieldName), newPanel); newPanel->SetName(newFieldName); newPanel->AddActionSignalTarget(m_pParentPanel); newPanel->SetBuildModeEditable(true); newPanel->SetBuildModeDeletable(true); // make sure it gets freed newPanel->SetAutoDelete(true); } return newPanel; } //----------------------------------------------------------------------------- // Purpose: Create a new control in the context panel // Input: controlKeys: keyvalues of settings for the panel only works when applying initial settings. // Output: Panel *newPanel, NULL if failed to create new control. //----------------------------------------------------------------------------- Panel *BuildGroup::NewControl( KeyValues *controlKeys, int x, int y) { Assert (controlKeys); Panel *newPanel = NULL; if (controlKeys) { KeyValues *keyVal = new KeyValues("ControlFactory", "ControlName", controlKeys->GetString("ControlName")); m_pBuildContext->RequestInfo(keyVal); // returns NULL on failure newPanel = (Panel *)keyVal->GetPtr("PanelPtr"); keyVal->deleteThis(); } else { return NULL; } if (newPanel) { // panel successfully created newPanel->SetParent(m_pParentPanel); newPanel->SetBuildGroup(this); newPanel->SetPos(x, y); newPanel->SetName(controlKeys->GetName()); // name before applysettings :) newPanel->ApplySettings(controlKeys); newPanel->AddActionSignalTarget(m_pParentPanel); newPanel->SetBuildModeEditable(true); newPanel->SetBuildModeDeletable(true); // make sure it gets freed newPanel->SetAutoDelete(true); } return newPanel; } //----------------------------------------------------------------------------- // Purpose: Get a new unique fieldname for a new control //----------------------------------------------------------------------------- void BuildGroup::GetNewFieldName(char *newFieldName, int newFieldNameSize, Panel *newPanel) { int fieldNameNumber=1; char defaultName[25]; Q_strncpy( defaultName, newPanel->GetClassName(), sizeof( defaultName ) ); while (1) { Q_snprintf (newFieldName, newFieldNameSize, "%s%d", defaultName, fieldNameNumber); if ( FieldNameTaken(newFieldName) == NULL) break; ++fieldNameNumber; } } //----------------------------------------------------------------------------- // Purpose: check to see if any buildgroup panels have this fieldname // Input : fieldName, name to check // Output : ptr to a panel that has the name if it is taken //----------------------------------------------------------------------------- Panel *BuildGroup::FieldNameTaken(const char *fieldName) { for ( int i = 0; i < _panelDar.Count(); i++ ) { Panel *panel = _panelDar[i].Get(); if ( !panel ) continue; if (!stricmp(panel->GetName(), fieldName) ) { return panel; } } return NULL; } //----------------------------------------------------------------------------- // Purpose: serializes settings to a resource data container //----------------------------------------------------------------------------- void BuildGroup::GetSettings( KeyValues *resourceData ) { // loop through all the objects getting their settings for( int i = 0; i < _panelDar.Count(); i++ ) { Panel *panel = _panelDar[i].Get(); if (!panel) continue; bool isRuler = false; // do not get setting for ruler labels. if (_showRulers) // rulers are visible { for (int i = 0; i < 4; i++) { if (panel == _rulerNumber[i]) { isRuler = true; break; } } if (isRuler) { isRuler = false; continue; } } // Don't save the setting of the buildmodedialog if (!stricmp(panel->GetName(), "BuildDialog")) continue; // get the keys section from the data file if (panel->GetName() && *panel->GetName()) { KeyValues *datKey = resourceData->FindKey(panel->GetName(), true); // get the settings panel->GetSettings(datKey); } } } //----------------------------------------------------------------------------- // Purpose: loop though objects in the current control group and remove them all //----------------------------------------------------------------------------- void BuildGroup::RemoveSettings() { // loop though objects in the current control group and remove them all int i; for( i = 0; i < _controlGroup.Count(); i++ ) { // only delete delatable panels if ( _controlGroup[i].Get()->IsBuildModeDeletable()) { delete _controlGroup[i].Get(); _controlGroup.Remove(i); --i; } } // remove deleted panels from the handle list for( i = 0; i < _panelDar.Count(); i++ ) { if ( !_panelDar[i].Get() ) { _panelDar.Remove(i); --i; } } _currentPanel = m_pBuildContext; _currentPanel->InvalidateLayout(); m_pBuildContext->Repaint(); } //----------------------------------------------------------------------------- // Purpose: sets the panel from which the build group gets all it's object creation info //----------------------------------------------------------------------------- void BuildGroup::SetContextPanel(Panel *contextPanel) { m_pBuildContext = contextPanel; } //----------------------------------------------------------------------------- // Purpose: gets the panel from which the build group gets all it's object creation info //----------------------------------------------------------------------------- Panel *BuildGroup::GetContextPanel() { return m_pBuildContext; } //----------------------------------------------------------------------------- // Purpose: get the list of panels in the buildgroup //----------------------------------------------------------------------------- CUtlVector<PHandle> *BuildGroup::GetPanelList() { return &_panelDar; } //----------------------------------------------------------------------------- // Purpose: dialog variables //----------------------------------------------------------------------------- KeyValues *BuildGroup::GetDialogVariables() { EditablePanel *edit = dynamic_cast<EditablePanel *>(m_pParentPanel); if (edit) { return edit->GetDialogVariables(); } return NULL; }
[ "rileylabrecque@gmail.com" ]
rileylabrecque@gmail.com
30317711832e9acfd7aec3403267e183cd1c8c9a
93cec5d03afc857474a4a1e5b1be18b98bbd1876
/src/ruukku/config/packing.hpp
ed67fa1031653d69643a0a25c3820c0d3029b6bb
[]
no_license
wuffehauhau/runrun
e4b41c2b85c2c743ee6ec6274002006564fe9ab8
2433b9feab1d05ea2e22c30ddb86aeb4011565de
refs/heads/master
2020-06-06T23:09:51.521599
2014-08-13T12:46:40
2014-08-13T12:51:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
485
hpp
/* * Copyright (C) Jani Salo 2013 - * All rights reserved unless otherwise stated. * * Kukkaruukku framework. * * File: packing.hpp * Created: 2013-01-22 * Authors: Jani Salo */ /* * Definition of packing values for ensuring tight packing of several classes. * The source for this file has static assertions to check these values. */ #ifndef RUUKKU_PACKING_HPP #define RUUKKU_PACKING_HPP #define RUUKKU_FLOATING_POINT_TYPE_PACKING 4 #endif /* RUUKKU_PACKING_HPP */
[ "jani.salo.cpp@gmail.com" ]
jani.salo.cpp@gmail.com
62d7560271c574a2e9f7d7b7519939f9e34328ff
251e135267b5af08e934c0e2f0b32d7fb557d7af
/test/thread/test_thread.cpp
e32104a30c8fef0f86e4cea68527d7e82eb3a706
[]
no_license
androids7/fancystar
221eafae3a8cef4bd6256a56eb3a74f843169b5a
6807008f639c15cff57192adb25e36404bffe85a
refs/heads/master
2021-05-27T08:31:01.065707
2014-12-19T14:18:44
2014-12-19T14:18:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,861
cpp
#include "winpch.h" #include "wyc/util/util.h" #include "wyc/util/time.h" #ifdef _DEBUG #pragma comment(lib, "fslog_d.lib") #pragma comment(lib, "fsutil_d.lib") #pragma comment(lib, "fsthread_d.lib") #else #pragma comment(lib, "fslog.lib") #pragma comment(lib, "fsutil.lib") #pragma comment(lib, "fsthread.lib") #endif extern void test_read_write_fence(void); extern void test_reference_counter(void); extern void test_critical_section(void); extern void test_peterson_lock(void); extern void test_asyncque(void); extern void test_mpmc_queue(void); extern void test_async_cache(void); extern void test_ring_queue(void); #include <atomic> void std_atomic_lock_free_check() { std::atomic_bool bval; std::atomic_char cval; std::atomic_int ival; std::atomic_long lval; std::atomic_int32_t i32val; std::atomic_int64_t i64val; std::atomic<float> fval; std::atomic<double> dval; const char *t = "true"; const char *f = "false"; printf("std::atomic_bool is lock-free: %s\n",bval.is_lock_free()?t:f); printf("std::atomic_char is lock-free: %s\n",cval.is_lock_free()?t:f); printf("std::atomic_int is lock-free: %s\n",ival.is_lock_free()?t:f); printf("std::atomic_long is lock-free: %s\n",lval.is_lock_free()?t:f); printf("std::atomic_int32_t is lock-free: %s\n",i32val.is_lock_free()?t:f); printf("std::atomic_int64_t is lock-free: %s\n",i64val.is_lock_free()?t:f); printf("std::atomic<float> is lock-free: %s\n",fval.is_lock_free()?t:f); printf("std::atomic<double> is lock-free: %s\n",dval.is_lock_free()?t:f); } int main(int, char **) { // std_atomic_lock_free_check(); // test_read_write_fence(); // test_reference_counter(); // test_critical_section(); // test_peterson_lock(); // test_asyncque(); test_mpmc_queue(); // test_async_cache(); // test_ring_queue(); wyc_print("Press [Enter] to continue"); getchar(); return 0; }
[ "wangyongcong@gmail.com" ]
wangyongcong@gmail.com
179661a94dc8de6a2242ca532421355f58975e5e
1963de9ddf820f1ca8e8cdc4519f5032e76b5043
/crm4.cpp
4bd2741b046560ce780c331ac53de403a8159f60
[]
no_license
phildeb/qtzenit2
59e9371f64abd9c59992b8c4ad4ce10afc22eba1
9379f803d27468fab17d2acb6139f0a1e4b4e1c3
refs/heads/master
2020-08-04T13:12:49.226199
2019-10-01T16:45:56
2019-10-01T16:45:56
212,148,003
0
0
null
null
null
null
UTF-8
C++
false
false
38,772
cpp
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <time.h> #include <fcntl.h> #include <pthread.h> #include <errno.h> #include "debug.h" #include "misc.h" #include "conf.h" #include "rude/config.h" #define CRM4_KEYS_SECTION_NAME "keys" QMap<int,int> CRM4::m_common_touche_select_device; QMap<int,int> CRM4::m_common_touche_select_conf; QMap<int,int> CRM4::m_common_keymap_number; QMap<int,QString> CRM4::m_common_keymap_action; QMap<QString,int> CRM4::m_common_key_number_by_action; void CRM4::init_thread_led() // static function { pthread_t thread_id; int ret = pthread_create(&(thread_id), NULL, CRM4::led_thread, NULL); if (ret < 0) { vega_log(INFO,"error pthread_create CRM4_led_thread - cause: %s", strerror(errno)); } } void* CRM4::led_thread(void *) { sleep(2); while (1){ foreach(CRM4* d1, qlist_crm4){ if (d1) d1->update_all_leds(); // pdl: parcours le tableau des etats des leds voir si qq chose a change a cause de l evenement !!! } sleep(2); } } void CRM4::update_all_leds() // si un element du tableau a change depuis la derniere fois ! { //vega_log(INFO,"D%d:update %d leds",number,CRM4_MAX_KEYS); for (int i=0;i<CRM4_MAX_KEYS;i++) { if ( tab_green_led[i] != old_tab_green_led[i] )//|| INDEFINI==tab_green_led[i]) { //vega_log(INFO,"tab_green_led[%d]:%d <= old_tab_green_led[%d]:%d", i, tab_green_led[i] , i, old_tab_green_led[i] ); // on commence par l'eteindre !!! /*device_set_led(i,LED_COLOR_GREEN, LED_MODE_FIX, 0); device_set_led(i, LED_COLOR_GREEN, LED_MODE_SLOW_BLINK, 0) ; device_set_led(i, LED_COLOR_GREEN, LED_MODE_FAST_BLINK, 0) ;*/ if ( old_tab_green_led[i]==FIXE ) device_set_led(i,LED_COLOR_GREEN, LED_MODE_FIX, 0); if ( old_tab_green_led[i]==CLIGNOTEMENT_RAPIDE ) device_set_led(i,LED_COLOR_GREEN, LED_MODE_FAST_BLINK, 0); if ( old_tab_green_led[i]==CLIGNOTEMENT_LENT ) device_set_led(i,LED_COLOR_GREEN, LED_MODE_SLOW_BLINK, 0); if ( tab_green_led[i]==FIXE ) device_set_led(i,LED_COLOR_GREEN, LED_MODE_FIX, 1); if ( tab_green_led[i]==CLIGNOTEMENT_RAPIDE ) device_set_led(i,LED_COLOR_GREEN, LED_MODE_FAST_BLINK, 1); if ( tab_green_led[i]==CLIGNOTEMENT_LENT ) device_set_led(i,LED_COLOR_GREEN, LED_MODE_SLOW_BLINK, 1); old_tab_green_led[i] = tab_green_led[i] ; // economise une remise a jour si la led ne change pas entre 2 update !!! } if ( tab_red_led[i] != old_tab_red_led[i] )//|| INDEFINI==tab_red_led[i]) { //vega_log(INFO,"tab_red_led[%d]:%d <= old_tab_red_led[%d]:%d", i, tab_red_led[i] , i, old_tab_red_led[i] ); /*device_set_led(i,LED_COLOR_RED, LED_MODE_FIX, 0); device_set_led(i, LED_COLOR_RED, LED_MODE_SLOW_BLINK, 0) ; device_set_led( i, LED_COLOR_RED, LED_MODE_FAST_BLINK, 0) ;*/ if ( old_tab_red_led[i]==FIXE ) device_set_led(i,LED_COLOR_RED, LED_MODE_FIX, 0); if ( old_tab_red_led[i]==CLIGNOTEMENT_RAPIDE ) device_set_led(i,LED_COLOR_RED, LED_MODE_FAST_BLINK, 0); if ( old_tab_red_led[i]==CLIGNOTEMENT_LENT ) device_set_led(i,LED_COLOR_RED, LED_MODE_SLOW_BLINK, 0); if ( tab_red_led[i]==FIXE ) device_set_led(i,LED_COLOR_RED, LED_MODE_FIX, 1); if ( tab_red_led[i]==CLIGNOTEMENT_RAPIDE ) device_set_led(i,LED_COLOR_RED, LED_MODE_FAST_BLINK, 1); if ( tab_red_led[i]==CLIGNOTEMENT_LENT ) device_set_led(i,LED_COLOR_RED, LED_MODE_SLOW_BLINK, 1); old_tab_red_led[i] = tab_red_led[i];// economise une remise a jour si la led ne change pas entre 2 update !!! } } } // RED // pdl: maintenant ,on met juste le nouvel etat de la led dans un tableau int CRM4::device_set_blink_fast_red_color(int button) { //device_set_led(button, LED_COLOR_RED, LED_MODE_FAST_BLINK, 1); //vega_log(INFO, "device_set_blink_fast_red_color=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_red_led[button] = CLIGNOTEMENT_RAPIDE; return 0; } int CRM4::device_set_blink_slow_red_color(int button) { //device_set_led(button, LED_COLOR_RED, LED_MODE_SLOW_BLINK, 1); //vega_log(INFO, "device_set_blink_slow_red_color=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_red_led[button] = CLIGNOTEMENT_LENT; return 0; } int CRM4::device_set_color_red(int button) { //device_set_led(button, LED_COLOR_RED, LED_MODE_FIX, 1); //vega_log(INFO, "device_set_color_red=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_red_led[button] = FIXE; return 0; } int CRM4::device_set_no_red_color(int button) { //vega_log(INFO, "device_set_no_red_color=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_red_led[button] = ETEINTE; // todo : memoriser le dernier mode afin de n'envoyer qu'une seule commande !!! //device_set_led(button, LED_COLOR_RED, LED_MODE_SLOW_BLINK, 0) ; //device_set_led( button, LED_COLOR_RED, LED_MODE_FAST_BLINK, 0) ; //device_set_led(button, LED_COLOR_RED, LED_MODE_FIX, 0); return 0; } // GREEN int CRM4::device_set_blink_fast_green_color(int button) { //device_set_led(button, LED_COLOR_GREEN, LED_MODE_FAST_BLINK, 1); //vega_log(INFO, "device_set_blink_fast_green_color=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_green_led[button] = CLIGNOTEMENT_RAPIDE; return 0; } int CRM4::device_set_blink_slow_green_color(int button) { //device_set_led(button, LED_COLOR_GREEN, LED_MODE_SLOW_BLINK, 1); //vega_log(INFO, "device_set_blink_slow_green_color=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_green_led[button] = CLIGNOTEMENT_LENT; return 0; } int CRM4::device_set_color_green(int button) { //device_set_led( button, LED_COLOR_GREEN, LED_MODE_FIX, 1); //vega_log(INFO, "device_set_color_green=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_green_led[button] = FIXE; return 0; } int CRM4::device_set_no_green_color(int button) { //vega_log(INFO, "device_set_no_green_color=%d\n",button); if ( button< CRM4_MAX_KEYS ) tab_green_led[button] = ETEINTE; //device_set_led(button, LED_COLOR_GREEN, LED_MODE_SLOW_BLINK, 0); //device_set_led( button, LED_COLOR_GREEN, LED_MODE_FAST_BLINK, 0); //device_set_led(button, LED_COLOR_GREEN, LED_MODE_FIX, 0); return 0; } /*[D11] number = 11 type = crm4 gain = 0 name = D11 [D25] number = 25 type = radio full_duplex = 0 contact_sec = 0 name = D25*/ void CRM4::load_crm4_device_section(const char* fname) { rude::Config config; if (config.load(fname) == false) { printf("rude cannot load %s file", fname); return ; } int dnumber=0; for ( dnumber=1;dnumber<=46;dnumber++) { QString strdevsection = QString("D%1").arg(dnumber); if ( true == config.setSection(qPrintable(strdevsection),false) ) { //int key_number = i;char *elt2 = strdup(config.getStringValue("gain")); // ce qu'il y a apres le "=" int gain = atoi(config.getStringValue("gain")); int full_duplex = atoi(config.getStringValue("full_duplex")); int audio_detection = atoi(config.getStringValue("contact_sec")); if ( strlen( config.getStringValue("name") ) > 0 ) { strdevsection = config.getStringValue("name") ; } CRM4 *d = NULL;//(CRM4*)device_t::by_number(dnumber); Radio *r = NULL; if ( dnumber >=1 && dnumber <= 24 ) { d = CRM4::create(dnumber,qPrintable(strdevsection),gain); }else{ r = Radio::create(dnumber,qPrintable(strdevsection),gain); } printf("D%d: config.getStringValue(keys)=%s\n",dnumber, config.getStringValue("keys")); if ( d ) { if ( strlen( config.getStringValue("keys") ) > 0 ) { char temp[1024]; strncpy(temp,config.getStringValue("keys"),sizeof(temp)); d->init_groups_keys( temp ); // GESTION DES touches de GROUPES propre a chaque CRM4 } } switch(dnumber) { // CRM4 stations case 1: if (d) d->init( 1, 0, 0, 20, 0, 0); break; case 2: if (d) d->init( 1, 0, 1, 20, 0, 1); break; case 3: if (d) d->init( 1, 0, 2, 20, 0, 2); break; case 4: if (d) d->init( 1, 0, 3, 20, 0, 3); break; case 5: if (d) d->init( 1, 0, 4, 20, 0, 4); break; case 6: if (d) d->init( 1, 0, 5, 20, 0, 5); break; case 7: if (d) d->init( 2, 0, 0, 20, 0, 6); break; case 8: if (d) d->init( 2, 0, 1, 20, 0, 7); break; case 9: if (d) d->init( 2, 0, 2, 20, 1, 0); break; case 10: if (d) d->init( 2, 0, 3, 20, 1, 1); break; case 11: if (d) d->init( 2, 0, 4, 20, 1, 2); break; // RADIOS case 25: if (r) r->init_radio( full_duplex, 22, 0, 0, audio_detection); break; case 26: if (r) r->init_radio( full_duplex, 22, 0, 2,audio_detection); break; case 27: if (r) r->init_radio( full_duplex, 22, 0, 4,audio_detection); break; case 28: if (r) r->init_radio( full_duplex, 22, 0, 6,audio_detection); break; case 29: if (r) r->init_radio( full_duplex, 22, 1, 0,audio_detection); break; case 30: if (r) r->init_radio( full_duplex, 22, 1, 2,audio_detection); break; case 31: if (r) r->init_radio( full_duplex, 22, 1, 4,audio_detection); break; case 32: if (r) r->init_radio( full_duplex, 22, 1, 6,audio_detection); break; case 33: if (r) r->init_radio( full_duplex, 23, 0, 0,audio_detection); break; case 34: if (r) r->init_radio( full_duplex, 23, 0, 2,audio_detection); break; case 35: if (r) r->init_radio( full_duplex, 23, 0, 4,audio_detection); break; // JUPITERS case 36: if (r) r->init_jupiter( 23, 0, 6, audio_detection); break; case 41: if (r) r->init_jupiter( 23, 1, 0, audio_detection); break; case 42: if (r) r->init_jupiter( 23, 1, 2, audio_detection); break; case 43: if (r) r->init_jupiter( 23, 1, 4, audio_detection); break; case 44: if (r) r->init_jupiter( 23, 1, 6, audio_detection); break; case 45: if (r) r->init_jupiter( 24, 0, 0, audio_detection); break; case 46: if (r) r->init_jupiter( 24, 0, 2, audio_detection); break; } } } } void CRM4::check_modif_crm4_device_section(const char* fname) { printf("check_modif_crm4_device_section %s \n",fname); rude::Config config; if (config.load(fname) == false) { printf("rude cannot load %s file", fname); return ; } int dnumber=0; for ( dnumber=1;dnumber<=46;dnumber++) { CRM4 *d = dynamic_cast<CRM4*>(device_t::by_number(dnumber)); QString strdevsection = QString("D%1").arg(dnumber); if ( true == config.setSection(qPrintable(strdevsection),false) ) { //int key_number = i;char *elt2 = strdup(config.getStringValue("gain")); // ce qu'il y a apres le "=" int gain = atoi(config.getStringValue("gain")); int full_duplex = atoi(config.getStringValue("full_duplex")); int audio_detection = atoi(config.getStringValue("contact_sec")); if ( strlen( config.getStringValue("name") ) > 0 ) { printf("device changed name to %s\n",config.getStringValue("name")); //vega_log(INFO, "device changed name %s -> %s\n",d->name, config.getStringValue("name")); if ( dnumber >=1 && dnumber <= 24 ) { if ( d ) { strncpy(d->name, config.getStringValue("name"),sizeof(d->name) ); //d->device_line_printf(1,"D%d:%s********",d->number,d->name); EVENT evt; evt.device_number = d->number; evt.code = EVT_DEVICE_UPDATE_DISPLAY; BroadcastEvent(&evt); } } } if ( dnumber >=1 && dnumber <= 24 && gain >=-12 && gain <=14) { if ( d ) { printf("device changed gain %d -> %d\n",d->gain, gain); vega_log(INFO, "D%d changed gain %d -> %d\n",dnumber, d->gain, gain); d->gain = gain; // todo : check gain entre -12 et 14 d->device_change_gain(d->gain); printf("D%d: config.getStringValue(gain)=%s\n",dnumber, config.getStringValue("gain")); } } } } } /*[keys] 1=action_activate_conf 2=action_on_off_conf 4=action_exclude_include_conf 5=action_select_conf,1 6=action_select_conf,2 7=action_select_conf,3 8=action_select_conf,4 9=action_select_conf,5 10=action_select_conf,6 11=action_select_conf,7 12=action_select_conf,8 13=action_select_conf,9 14=action_select_conf,10 15=action_select_device,25 16=action_select_device,26 17=action_select_device,27 18=action_select_device,28 19=action_select_device,29 20=action_select_device,1 21=action_select_device,2 22=action_select_device,3 23=action_select_device,4 24=action_select_device,5 25=action_select_device,6 26=action_select_device,7 27=action_select_device,8 28=action_select_device,9 29=action_select_device,10 30=action_select_device,11 32=action_select_device,41 33=action_select_device,42 34=action_select_device,43 35=action_select_device,44 36=action_select_device,45 38=action_general_call */ void CRM4::load_crm4_keys_section(const char* fname) { rude::Config config; if (config.load(fname) == false) { printf("rude cannot load %s file", fname); return ; } int nb_keys=0; for (int i = 1; i <= 38; i++) { //config.setSection(qPrintable(config.getSectionNameAt(i)); if ( true == config.setSection(CRM4_KEYS_SECTION_NAME,false) ) { QString str = QString("%1").arg(i); int key_number = i; char *elt2 = strdup(config.getStringValue(qPrintable(str))); // ce qu'il y a apres le "=" nb_keys++; vega_log(INFO, "nb_keys:%d key_number=%d elt2=%s\n",nb_keys, key_number, elt2); printf("nb_keys:%d key_number=%d elt2=%s\n",nb_keys, key_number, elt2); m_common_key_number_by_action[elt2] = key_number; // m_common_key_number_by_action["action_activate_conf"]=1 if (strstr(elt2, "action_activate_conf")) { m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_ACTIVATE_CONFERENCE ; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; nb_keys ++; } else if (strstr(elt2, "action_on_off_conf")) { m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_ON_OFF_CONF; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; nb_keys ++; } else if (strstr(elt2, "action_exclude_include_conf")) { m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_INCLUDE_EXCLUDE; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; nb_keys ++; } else if (strstr(elt2, "action_select_conf")) {/* 5=action_select_conf,1 6=action_select_conf,2 7=action_select_conf,3 8=action_select_conf,4 9=action_select_conf,5 10=action_select_conf,6 11=action_select_conf,7 12=action_select_conf,8 13=action_select_conf,9 14=action_select_conf,10*/ vega_log(INFO, "action_select_conf %d %d", nb_keys, key_number ); //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_SELECT_CONF; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; char *e1; char *e2; e1 = strtok(elt2, ","); e2 = strtok(NULL, ","); //device_keys_configuration->device_key_configuration[nb_keys].action.select_conf.conference_number = atoi(e2); m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=atoi(e2);; m_common_touche_select_conf[atoi(e2)] = key_number; nb_keys ++; } else if(strstr(elt2, "action_select_device")) { /*15=action_select_device,25 16=action_select_device,26 17=action_select_device,27 18=action_select_device,28 19=action_select_device,29 20=action_select_device,1 21=action_select_device,2 22=action_select_device,3 23=action_select_device,4 24=action_select_device,5 25=action_select_device,6 26=action_select_device,7 27=action_select_device,8 28=action_select_device,9 29=action_select_device,10 30=action_select_device,11 32=action_select_device,41 33=action_select_device,42 34=action_select_device,43 35=action_select_device,44 36=action_select_device,45 */ //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_SELECT_DEVICE; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; char *e1; char *e2; e1 = strtok(elt2, ","); e2 = strtok(NULL, ","); //device_keys_configuration->device_key_configuration[nb_keys].action.select_device.device_number = atoi(e2); m_common_keymap_action[key_number]=elt2; // m_common_keymap_action[20]="action_select_device" m_common_keymap_number[key_number]=atoi(e2); // m_common_keymap_number[20]=1 m_common_touche_select_device[atoi(e2)] = key_number; nb_keys ++; } // pdl 20090927 les appels de groupe sont dynamiques et charges depuis le fichier devices.conf /*else if(strstr(elt2, "action_group_call")) { device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_GROUP_CALL; device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; char *e1; char *e2; e1 = strtok(elt2, ","); e2 = strtok(NULL, ","); device_keys_configuration->device_key_configuration[nb_keys].action.group_call.group_number = atoi(e2); nb_keys ++; }*/ else if(strstr(elt2, "action_general_call")) { //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_GENERAL_CALL; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; nb_keys ++; } } } //exit(-1); } void CRM4::load_crm4_keys_configuration(const char* fname) { //device_keys_configuration_t* device_keys_configuration = &the_unic_static_device_keys_configuration; char line[128]={0}; int i; int nb_keys = 0; FILE *fp = fopen(fname, "r"); if (fp == NULL) { vega_log(ERROR, "cannot open file %s - cause : %s", fname, strerror(errno)); return; } /* read a line */ int f = 0; while (1) { bzero(line, sizeof(line)); for (i = 0; ; i++) { if (fread(line + i, 1, 1, fp) != 1) { f = 1; break; } if (line[i] == '\n') break; } if (line[i] == '\n') line[i] = '\0'; if (!strcmp(line, "")) break; if (line[0] == ';') continue; char *elt1; char *elt2; if ((elt1 = strtok(line, "=")) == NULL) { vega_log(ERROR, "cannot process line %s", line); } //vega_log(ERROR, "processing line %s", line); int key_number = atoi(elt1); if ((elt2 = strtok(NULL, "=")) == NULL) { vega_log(ERROR, "cannont process line %s", line); continue; } vega_log(INFO, "nb_keys:%d key_number=%d elt2=%s\n",nb_keys, key_number, elt2); m_common_key_number_by_action[elt2] = key_number; // m_common_key_number_by_action["action_activate_conf"]=1 //38=action_general_call m_common_key_number_by_action["action_general_call"]=38 if (strstr(elt2, "action_activate_conf")) { m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_ACTIVATE_CONFERENCE ; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; nb_keys ++; } else if (strstr(elt2, "action_on_off_conf")) { m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_ON_OFF_CONF; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; nb_keys ++; } else if (strstr(elt2, "action_exclude_include_conf")) { m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_INCLUDE_EXCLUDE; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; nb_keys ++; } else if (strstr(elt2, "action_select_conf")) {/* 5=action_select_conf,1 6=action_select_conf,2 7=action_select_conf,3 8=action_select_conf,4 9=action_select_conf,5 10=action_select_conf,6 11=action_select_conf,7 12=action_select_conf,8 13=action_select_conf,9 14=action_select_conf,10*/ vega_log(INFO, "action_select_conf %d %d", nb_keys, key_number ); //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_SELECT_CONF; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; char *e1; char *e2; e1 = strtok(elt2, ","); e2 = strtok(NULL, ","); //device_keys_configuration->device_key_configuration[nb_keys].action.select_conf.conference_number = atoi(e2); m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=atoi(e2);; m_common_touche_select_conf[atoi(e2)] = key_number; nb_keys ++; } else if(strstr(elt2, "action_select_device")) { /*15=action_select_device,25 16=action_select_device,26 17=action_select_device,27 18=action_select_device,28 19=action_select_device,29 20=action_select_device,1 21=action_select_device,2 22=action_select_device,3 23=action_select_device,4 24=action_select_device,5 25=action_select_device,6 26=action_select_device,7 27=action_select_device,8 28=action_select_device,9 29=action_select_device,10 30=action_select_device,11 32=action_select_device,41 33=action_select_device,42 34=action_select_device,43 35=action_select_device,44 36=action_select_device,45 */ //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_SELECT_DEVICE; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; char *e1; char *e2; e1 = strtok(elt2, ","); e2 = strtok(NULL, ","); //device_keys_configuration->device_key_configuration[nb_keys].action.select_device.device_number = atoi(e2); m_common_keymap_action[key_number]=elt2; // m_common_keymap_action[20]="action_select_device" m_common_keymap_number[key_number]=atoi(e2); // m_common_keymap_number[20]=1 m_common_touche_select_device[atoi(e2)] = key_number; nb_keys ++; } // pdl 20090927 les appels de groupe sont dynamiques et charges depuis le fichier devices.conf /*else if(strstr(elt2, "action_group_call")) { device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_GROUP_CALL; device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; char *e1; char *e2; e1 = strtok(elt2, ","); e2 = strtok(NULL, ","); device_keys_configuration->device_key_configuration[nb_keys].action.group_call.group_number = atoi(e2); nb_keys ++; }*/ else if(strstr(elt2, "action_general_call")) { //device_keys_configuration->device_key_configuration[nb_keys].type = ACTION_GENERAL_CALL; //device_keys_configuration->device_key_configuration[nb_keys].key_number = key_number; m_common_keymap_action[key_number]=elt2; m_common_keymap_number[key_number]=key_number; nb_keys ++; } if (f) break; }/*while*/ vega_log(INFO,"load_crm4_keys_configuration: nb_keys=%d\n",nb_keys); } int CRM4::all_devices_display_general_call_led(int busy /* if a director is doing a general call*/) { foreach(CRM4* d,qlist_crm4) { if ( d) d->display_general_call_led(busy); } return 0; } int CRM4::display_general_call_led(int busy /* if a director is doing a general call*/) { //int key = 0;//get_key_number_by_action_type(device.crm4.keys_configuration, ACTION_GENERAL_CALL, 0 ); if ( m_common_key_number_by_action.contains( "action_general_call" ) ) { int key=m_common_key_number_by_action["action_general_call"]; device_set_color_green( key); if ( busy ) device_set_color_red( key); else device_set_no_red_color( key); } /* QMap<int,QString>::const_iterator i = CRM4::m_common_keymap_action.constBegin(); while ( i != CRM4::m_common_keymap_action.constEnd() ) { if ( i.value() == "action_general_call" ) { int no_touche = i.key(); device_set_color_green( key); if ( busy ) device_set_color_red( key); else device_set_no_red_color( key); } i++; }*/ //vega_log(INFO,"set led ACTION_GENERAL_CALL key %d on D%d...\n", key , d->number); return 0; } int CRM4::all_devices_display_group_key(int allume) // static { // STATIC vega_log(INFO,"all_devices_display_group_key G%d <= %d..\n", doing_group_call); //unsigned int i=0;for (i = 0; i < g_list_length(devices) ; i++) foreach(CRM4* d,qlist_crm4) { QMap<int, int>::const_iterator i = d->keymap_groups.constBegin(); while (i != d->keymap_groups.constEnd()) { //printf("D%d has_group_key G%d in KEY %d ( doing_group_call=G%d )\n", d->number, i.value() , i.key(),doing_group_call); d->device_set_color_green( i.key()); if ( doing_group_call == i.value() ) { if (allume) d->device_set_blink_fast_red_color(i.key()); else d->device_set_no_red_color( i.key()); } ++i; } } return 0; } int CRM4::device_MAJ_groups_led(int doing_group_cal) { CRM4* d = this; vega_log(INFO, "----------------------------------->DISPLAY G%d LED on D%d",doing_group_cal, number); QMap<int, int>::const_iterator i = keymap_groups.constBegin(); while (i != keymap_groups.constEnd()) { //cout << i.key() << ": " << i.value() << endl; { printf("D%d has_group_key G%d in KEY %d\n", d->number, i.value() , i.key()); d->device_set_color_green( i.key()); if ( i.value() == doing_group_cal ) //if ( working ) //d->device_set_color_red( key); d->device_set_blink_fast_red_color(i.key()); else d->device_set_no_red_color( i.key()); } ++i; } //QMap<int /*crm4key*/,int /*numero_group*/> keymap_groups; // dynamic keys different for each CRM4 /*foreach( int key, this->keymap_groups ) { //int key = get_key_number_by_action_type(d->device.crm4.keys_configuration, ACTION_GROUP_CALL, NG ); //vega_log(INFO,"set led ACTION_GROUP_CALL keys_group[%d]=%d on D%d...\n", NG, key , number); if ( key > 0 ) { device_set_color_green( key); if ( grpnum == grpnum ) device_set_color_red( key); else device_set_no_red_color( key); } }*/ /* unsigned int NG; for ( NG=0; NG< MAX_GROUPS; NG++) { //int key = device.crm4.keys_group[NG]; if ( keymap_groups.contains(NG) ) { // Returns true if the map contains an item with key key; otherwise returns false. int key = keymap_groups[NG] ;//= num_touche; //int key = get_key_number_by_action_type(d->device.crm4.keys_configuration, ACTION_GROUP_CALL, NG ); //vega_log(INFO,"set led ACTION_GROUP_CALL keys_group[%d]=%d on D%d...\n", NG, key , number); if ( key > 0 ) { device_set_color_green( key); if ( grpnum == NG ) device_set_color_red( key); else device_set_no_red_color( key); } } }*/ return 0; } void CRM4::all_devices_set_green_led_possible_conferences() { foreach(CRM4* d,qlist_crm4) { if ( d ) d->set_green_led_possible_conferences(); } } void CRM4::set_green_led_possible_conferences() { //vega_log(INFO, "UPDATE CONFERENCE LEDS in D%d (active in %d conferences)", number, nb_active_conf_where_device_is_active() ); //printf("UPDATE CONFERENCE LEDS in D%d (active in %d conferences)", number, nb_active_conf_where_device_is_active() ); unsigned int k; foreach(vega_conference_t *C,vega_conference_t::qlist){ if ( C ) set_led_conference(C); // pdl 20090911 } } int CRM4::device_MAJ_particpant_key(device_t* d1, int hide_participant, participant_st etat) { if ( d1 ){ int keyD = 0;//get_key_number_by_action_type(device.crm4.keys_configuration, ACTION_SELECT_DEVICE, d1->number); /*QMap<int,QString>::const_iterator i = CRM4::m_common_keymap_action.constBegin(); while ( i != CRM4::m_common_keymap_action.constEnd() ) { if ( i.value() == "action_select_device" ) { keyD = i.key(); } i++; }*/ //m_common_touche_select_conf[NoDevice] = touche if ( m_common_touche_select_device.contains(d1->number ) ) { keyD = m_common_touche_select_device[d1->number] ; //vega_log(INFO, "D%d: particpant_key of D%d (key %d)", number, d1->number, keyD); }else{ //vega_log(INFO, "D%d: NO particpant_key for D%d (key %d)", number, d1->number, keyD); } if (keyD > 0) { // STOP blinking red led even if not speaking in conf //device_set_no_red_color(keyD); if ( m_is_plugged ) { if ( hide_participant ){ // hide particpants of this conference ( used when swicthing from on conf to another ) vega_log(INFO, "HIDE participants D%d in D%d",d1->number, number ); device_set_no_red_color( keyD); device_set_no_green_color( keyD); } else { if ( NOT_PARTICIPANT==etat)//C->get_state_in_conference(d1) ) { device_set_no_green_color( keyD); device_set_no_red_color( keyD); } else if ( PARTICIPANT_ACTIVE==etat)//C->get_state_in_conference(d1) ) { if ( d1->b_speaking ) { device_set_color_green( keyD); //device_set_( keyD); device_set_blink_fast_red_color(keyD); }else{ device_set_color_green( keyD); device_set_no_red_color( keyD); } }else{ // EXCLUDED participant device_set_no_green_color( keyD); device_set_color_red(keyD); } } }else{ device_set_no_red_color(keyD); device_set_no_green_color(keyD); } } } } /* update conferences led ( and show/hide participants led ) on mydevice CRM4 */ int CRM4::device_MAJ(vega_conference_t *C, int update_conferences_led,int update_participants_led, int hide_participants) { if ( update_participants_led && C ){ device_MAJ_participants_led(C,hide_participants); } if ( update_conferences_led ) { set_green_led_possible_conferences(); } } int CRM4::device_MAJ_participants_led( vega_conference_t *C, int hide_participant) { unsigned int j=0; if (!C) return -1; /*unsigned int devnum =0; for ( devnum=15; devnum<=37; devnum++) { int keyD = get_key_number_by_action_type(device.crm4.keys_configuration, ACTION_SELECT_DEVICE, devnum); //vega_log(INFO, "participants[%d] is device %d (key %d)", j, d1->number, keyD); if (keyD > 0){ { // hide particpants of this conference ( used when swicthing from on conf to another ) device_set_no_red_color( keyD); device_set_no_green_color( keyD); } } }*/ if ( C->active || hide_participant) { // mise a jour des participants : soit conference active, soit effacement complet ! if ( C->participant_director.device ) device_MAJ_particpant_key(C->participant_director.device,hide_participant,C->get_state_in_conference(C->participant_director.device)); if ( C->participant_radio1.device ) device_MAJ_particpant_key(C->participant_radio1.device,hide_participant,C->get_state_in_conference(C->participant_radio1.device)); if ( C->participant_radio2.device ) device_MAJ_particpant_key(C->participant_radio2.device,hide_participant,C->get_state_in_conference(C->participant_radio2.device)); if ( C->participant_jupiter.device ) device_MAJ_particpant_key(C->participant_jupiter.device,hide_participant,C->get_state_in_conference(C->participant_jupiter.device)); for (j = 0; j < C->nb_particpants; j++) { if ( C->participants[j].device ) this->device_MAJ_particpant_key(C->participants[j].device,hide_participant,C->get_state_in_conference( C->participants[j].device )); } }else{ vega_log(INFO, "D%d: no need to device_MAJ_participants_led when C%d not active!!!",number,C->number); } return 0; } #define MAX_LEN_CRM4_LINE 18 int CRM4::device_line_printf(int line, const char* fmt, ...) { //if ( line == 1 ) return 0; //if ( line == 4 ) return 0; if ( line >= 5 ) return 0; if ( line <= 0 ) return 0; if ( fmt==NULL || line <= 0 || line > 4 ) return -1; char temp[1024]={0}; //char str[128]={0}; va_list args; va_start(args, fmt); int nb = vsnprintf(temp, sizeof(temp) , fmt, args); //int nb = vsprintf(temp, fmt, args); va_end (args); temp[MAX_LEN_CRM4_LINE]=0; // force end of line device_display_msg( line, temp); return 0; } int CRM4::device_line_print_time_now(int line) { struct timeval tv; struct tm* ptm; char str[32]; gettimeofday (&tv, NULL); ptm = localtime (&tv.tv_sec); strftime (str, sizeof(str)-1, "%d/%m %H:%M:%S ......", ptm); device_line_printf(line,str); } int CRM4::device_display_conferences_state() { CRM4* d = this; d->device_MAJ(NULL,1,0,0); return 0; } int CRM4::set_green_led_of_conf(vega_conference_t *conf,int on) { //if ( conf->is_in(this) ) if ( m_common_touche_select_conf.contains( conf->number ) ) { vega_log(INFO, "set in D%d the GREEN led of C%d: %d", number, conf->number,on); int keyC = m_common_touche_select_conf[conf->number];//get_key_number_by_action_type(this->device.crm4.keys_configuration, ACTION_SELECT_CONF, conf->number); if ( on ) this->device_set_color_green(keyC); else device_set_no_green_color(keyC); /*QMap<int,QString>::const_iterator i = CRM4::m_common_keymap_action.constBegin(); while ( i != CRM4::m_common_keymap_action.constEnd() ) { if ( i.value() == "action_select_conf" ) { int no_touche = i.key(); if ( m_common_keymap_number[no_touche] == conf->number ) { if ( on ) this->device_set_color_green(keyC); else device_set_no_green_color(keyC); } } i++; }*/ } return 0; } int CRM4::set_red_led_of_conf(vega_conference_t *conf,int on) { if ( m_common_touche_select_conf.contains( conf->number ) ) { vega_log(INFO, "set in D%d the RED led of C%d: %d", number, conf->number,on); int keyC = m_common_touche_select_conf[conf->number];//get_key_number_by_action_type(this->device.crm4.keys_configuration, ACTION_SELECT_CONF, conf->number); if ( on ) this->device_set_color_red(keyC); else device_set_no_red_color(keyC); /*QMap<int,QString>::const_iterator i = CRM4::m_common_keymap_action.constBegin(); while ( i != CRM4::m_common_keymap_action.constEnd() ) { if ( i.value() == "action_select_conf" ) { int no_touche = i.key(); if ( m_common_keymap_number[no_touche] == conf->number ) { if ( on ) this->device_set_color_red(keyC); else device_set_no_red_color(keyC); } } i++; }*/ } return 0; } int CRM4::all_devices_display_led_of_device_speaking_in_conf(vega_conference_t *conf, device_t * d) // STATIC { if ( NULL==d || NULL==conf) return -1; vega_log(INFO, "display EVERYWHERE D%d speaking in C%d(current==%d)", d->number, conf->number, d->current_conference); /* diffuse ,pour chaque device dans la conference qui est en train de parler, l'etat de tous les postes crm4 de la conference qui sont dedans */ foreach(CRM4* d1,qlist_crm4) { d1->set_led_conference(conf); if ( d1 && d1->current_conference==conf->number ) {//d1->set_led_conference(conf); // pdl20090624 d1->device_MAJ_particpant_key(d,0,conf->get_state_in_conference(d)); // probleme when MICRO released just before being excluded by director! } } return 0; } int CRM4::all_devices_display_led_of_device_NOT_speaking_in_conf(vega_conference_t *conf, device_t * d) { if ( NULL==d || NULL==conf) return -1; vega_log(INFO, "display EVERYWHERE D%d NOT speaking in C%d", d->number, conf->number); foreach(CRM4* d1,qlist_crm4) { d1->set_led_conference(conf); if (d1->current_conference==conf->number ) { vega_log(INFO, "display on D%d led of D%d NOT speaking in C%d", d1->number, d->number, conf->number); d1->device_MAJ_particpant_key(d,0,conf->get_state_in_conference(d)); // probleme when MICRO released just before being excluded by director! } } return 0; } void CRM4::set_led_conference(vega_conference_t* C) { unsigned int k; if(C) { if ( m_common_touche_select_conf.contains(C->number) ) { int key = m_common_touche_select_conf[C->number];//0;//get_key_number_by_action_type( device.crm4.keys_configuration, ACTION_SELECT_CONF, C->number); vega_log(INFO, "OK:UPDATE key%d C%d LED in D%d (%d speaking)", key, C->number, number, C->nb_people_speaking() ); // RAZ in case of slow blink for director reinclusion ! //device_set_no_green_color( key); //device_set_no_red_color( key); switch ( C->get_state_in_conference(this) ) { case NOT_PARTICIPANT: //vega_log(INFO, "UPDATE CONFERENCE LEDS D%d NOT_PARTICIPANT in C%d",number,C->number); //device_set_no_green_color( key); //device_set_no_red_color( key); device_set_no_green_color( key); device_set_no_red_color( key); break; case PARTICIPANT_ACTIVE: vega_log(INFO, "UPDATE CONFERENCE LEDS D%d PARTICIPANT_ACTIVE in C%d",number,C->number); if ( C->active ) { if ( C->nb_people_speaking() > 0 ) { //device_set_no_red_color(key); device_set_blink_fast_red_color( key); }else { //device_set_no_red_color(key); // trick to stop the blink!!! device_set_color_red( key); } }else{ device_set_no_red_color( key); } //device_set_no_green_color( key); device_set_color_green( key); break; case PARTICIPANT_SELF_EXCLUDED: vega_log(INFO, "UPDATE CONFERENCE LEDS D%d PARTICIPANT_SELF_EXCLUDED in C%d",number,C->number); if ( C->active ) { if ( C->nb_people_speaking() > 0 ){ //device_set_no_red_color(key); device_set_blink_fast_red_color( key); }else { //device_set_no_red_color(key);// trick to stop the blink!!! device_set_color_red( key); } device_set_color_green( key); }else { device_set_no_red_color( key); } device_set_no_green_color( key); break; case PARTICIPANT_DTOR_EXCLUDED: vega_log(INFO, "UPDATE CONFERENCE LEDS D%d PARTICIPANT_DTOR_EXCLUDED in C%d",number,C->number); if ( C->active ) { if ( C->nb_people_speaking() > 0 ){ //device_set_no_red_color(key); device_set_blink_fast_red_color( key); }else { //device_set_no_red_color(key);// trick to stop the blink!!! device_set_color_red( key); } device_set_color_green( key); }else { device_set_no_red_color( key); } device_set_no_green_color( key); break; } }else{ vega_log(INFO, "NOK:UPDATE C%d LED in D%d (%d speaking)", C->number, number, C->nb_people_speaking() ); } } }
[ "phd@debreuil.fr" ]
phd@debreuil.fr
1834fa3c43ac6d660ba393bcd391f3efcd062e7f
dccf5f6339baba548a83a7d390b63e285c9f0581
/chrome/browser/resource_coordinator/tab_manager_stats_collector.cc
b086923148926e355b335b91d440573e35c072dd
[ "BSD-3-Clause" ]
permissive
Trailblazer01010111/chromium
83843c9e45abb74a1a23df7302c1b274e460aee2
3fd9a73f1e93ce041a4580c20e30903ab090e95c
refs/heads/master
2022-12-06T22:58:46.158304
2018-05-12T09:55:21
2018-05-12T09:55:21
133,138,333
1
0
null
2018-05-12T11:07:57
2018-05-12T11:07:56
null
UTF-8
C++
false
false
18,673
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/resource_coordinator/tab_manager_stats_collector.h" #include <cstdint> #include <memory> #include <unordered_set> #include <utility> #include "base/atomic_sequence_num.h" #include "base/memory/ptr_util.h" #include "base/metrics/histogram.h" #include "base/metrics/histogram_macros.h" #include "base/rand_util.h" #include "base/stl_util.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/resource_coordinator/resource_coordinator_web_contents_observer.h" #include "chrome/browser/resource_coordinator/tab_manager_web_contents_data.h" #include "chrome/browser/resource_coordinator/time.h" #include "chrome/browser/sessions/session_restore.h" #include "components/metrics/system_memory_stats_recorder.h" #include "content/public/browser/swap_metrics_driver.h" #include "services/metrics/public/cpp/ukm_builders.h" #include "services/metrics/public/cpp/ukm_recorder.h" namespace resource_coordinator { namespace { const char* kSessionTypeName[] = {"SessionRestore", "BackgroundTabOpening"}; constexpr int kSamplingOdds = 10; // Only report a subset of this metric as the volume is too high. bool ShouldReportExpectedTaskQueueingDurationToUKM( size_t background_tab_loading_count, size_t background_tab_pending_count) { size_t tab_count = background_tab_loading_count + background_tab_pending_count; DCHECK_GE(tab_count, 1u); // We always collect this metric when we have 2 or more backgrounded loading // or pending tabs (|tab_count|). And we sample the rest, i.e. when there is // one tab loading in the background and no tabs pending, which is the less // interesting majority. In this way, we cap the volume while keeping all // interesting data. if (tab_count > 1) return true; if (base::RandUint64() % kSamplingOdds == 0) return true; return false; } ukm::SourceId GetUkmSourceId(content::WebContents* contents) { ResourceCoordinatorWebContentsObserver* observer = ResourceCoordinatorWebContentsObserver::FromWebContents(contents); if (!observer) return ukm::kInvalidSourceId; return observer->ukm_source_id(); } } // namespace void TabManagerStatsCollector::BackgroundTabCountStats::Reset() { tab_count = 0u; tab_paused_count = 0u; tab_load_auto_started_count = 0u; tab_load_user_initiated_count = 0u; } class TabManagerStatsCollector::SwapMetricsDelegate : public content::SwapMetricsDriver::Delegate { public: explicit SwapMetricsDelegate( TabManagerStatsCollector* tab_manager_stats_collector, SessionType type) : tab_manager_stats_collector_(tab_manager_stats_collector), session_type_(type) {} ~SwapMetricsDelegate() override = default; void OnSwapInCount(uint64_t count, base::TimeDelta interval) override { tab_manager_stats_collector_->RecordSwapMetrics( session_type_, "SwapInPerSecond", count, interval); } void OnSwapOutCount(uint64_t count, base::TimeDelta interval) override { tab_manager_stats_collector_->RecordSwapMetrics( session_type_, "SwapOutPerSecond", count, interval); } void OnDecompressedPageCount(uint64_t count, base::TimeDelta interval) override { tab_manager_stats_collector_->RecordSwapMetrics( session_type_, "DecompressedPagesPerSecond", count, interval); } void OnCompressedPageCount(uint64_t count, base::TimeDelta interval) override { tab_manager_stats_collector_->RecordSwapMetrics( session_type_, "CompressedPagesPerSecond", count, interval); } void OnUpdateMetricsFailed() override { tab_manager_stats_collector_->OnUpdateSwapMetricsFailed(); } private: TabManagerStatsCollector* tab_manager_stats_collector_; const SessionType session_type_; }; TabManagerStatsCollector::TabManagerStatsCollector() { SessionRestore::AddObserver(this); } TabManagerStatsCollector::~TabManagerStatsCollector() { SessionRestore::RemoveObserver(this); } void TabManagerStatsCollector::RecordWillDiscardUrgently(int num_alive_tabs) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); base::TimeTicks discard_time = NowTicks(); UMA_HISTOGRAM_COUNTS_100("Discarding.Urgent.NumAliveTabs", num_alive_tabs); if (last_urgent_discard_time_.is_null()) { UMA_HISTOGRAM_CUSTOM_TIMES( "Discarding.Urgent.TimeSinceStartup", discard_time - start_time_, base::TimeDelta::FromSeconds(1), base::TimeDelta::FromDays(1), 50); } else { UMA_HISTOGRAM_CUSTOM_TIMES("Discarding.Urgent.TimeSinceLastUrgent", discard_time - last_urgent_discard_time_, base::TimeDelta::FromMilliseconds(100), base::TimeDelta::FromDays(1), 50); } // TODO(fdoray): Remove this #if when RecordMemoryStats is implemented for all // platforms. #if defined(OS_WIN) || defined(OS_CHROMEOS) // Record system memory usage at the time of the discard. metrics::RecordMemoryStats(metrics::RECORD_MEMORY_STATS_TAB_DISCARDED); #endif last_urgent_discard_time_ = discard_time; } void TabManagerStatsCollector::RecordSwitchToTab( content::WebContents* old_contents, content::WebContents* new_contents) { if (!is_session_restore_loading_tabs_ && !is_in_background_tab_opening_session_) { return; } if (IsInOverlappedSession()) return; auto* new_data = TabManager::WebContentsData::FromWebContents(new_contents); DCHECK(new_data); if (is_session_restore_loading_tabs_) { UMA_HISTOGRAM_ENUMERATION(kHistogramSessionRestoreSwitchToTab, new_data->tab_loading_state(), TAB_LOADING_STATE_MAX); } if (is_in_background_tab_opening_session_) { UMA_HISTOGRAM_ENUMERATION(kHistogramBackgroundTabOpeningSwitchToTab, new_data->tab_loading_state(), TAB_LOADING_STATE_MAX); } if (old_contents) foreground_contents_switched_to_times_.erase(old_contents); DCHECK( !base::ContainsKey(foreground_contents_switched_to_times_, new_contents)); if (new_data->tab_loading_state() != TAB_IS_LOADED) { foreground_contents_switched_to_times_.insert( std::make_pair(new_contents, NowTicks())); } } void TabManagerStatsCollector::RecordExpectedTaskQueueingDuration( content::WebContents* contents, base::TimeDelta queueing_time) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // TODO(fdoray): Consider not recording this for occluded tabs. if (contents->GetVisibility() == content::Visibility::HIDDEN) return; if (IsInOverlappedSession()) return; ukm::SourceId ukm_source_id = GetUkmSourceId(contents); if (is_session_restore_loading_tabs_) { UMA_HISTOGRAM_TIMES( kHistogramSessionRestoreForegroundTabExpectedTaskQueueingDuration, queueing_time); size_t restored_tab_count = g_browser_process->GetTabManager()->restored_tab_count(); if (ukm_source_id != ukm::kInvalidSourceId && restored_tab_count > 1) { ukm::builders:: TabManager_SessionRestore_ForegroundTab_ExpectedTaskQueueingDurationInfo( ukm_source_id) .SetExpectedTaskQueueingDuration(queueing_time.InMilliseconds()) .SetSequenceId(sequence_++) .SetSessionRestoreSessionId(session_id_) .SetSessionRestoreTabCount(restored_tab_count) .SetSystemTabCount( g_browser_process->GetTabManager()->GetTabCount()) .Record(ukm::UkmRecorder::Get()); } } if (is_in_background_tab_opening_session_) { UMA_HISTOGRAM_TIMES( kHistogramBackgroundTabOpeningForegroundTabExpectedTaskQueueingDuration, queueing_time); size_t background_tab_loading_count = g_browser_process->GetTabManager()->GetBackgroundTabLoadingCount(); size_t background_tab_pending_count = g_browser_process->GetTabManager()->GetBackgroundTabPendingCount(); if (ukm_source_id != ukm::kInvalidSourceId && ShouldReportExpectedTaskQueueingDurationToUKM( background_tab_loading_count, background_tab_pending_count)) { ukm::builders:: TabManager_BackgroundTabOpening_ForegroundTab_ExpectedTaskQueueingDurationInfo( ukm_source_id) .SetBackgroundTabLoadingCount(background_tab_loading_count) .SetBackgroundTabOpeningSessionId(session_id_) .SetBackgroundTabPendingCount(background_tab_pending_count) .SetExpectedTaskQueueingDuration(queueing_time.InMilliseconds()) .SetSequenceId(sequence_++) .SetSystemTabCount( g_browser_process->GetTabManager()->GetTabCount()) .Record(ukm::UkmRecorder::Get()); } } } void TabManagerStatsCollector::RecordBackgroundTabCount() { DCHECK(is_in_background_tab_opening_session_); if (!is_overlapping_background_tab_opening_) { UMA_HISTOGRAM_COUNTS_100(kHistogramBackgroundTabOpeningTabCount, background_tab_count_stats_.tab_count); UMA_HISTOGRAM_COUNTS_100(kHistogramBackgroundTabOpeningTabPausedCount, background_tab_count_stats_.tab_paused_count); UMA_HISTOGRAM_COUNTS_100( kHistogramBackgroundTabOpeningTabLoadAutoStartedCount, background_tab_count_stats_.tab_load_auto_started_count); UMA_HISTOGRAM_COUNTS_100( kHistogramBackgroundTabOpeningTabLoadUserInitiatedCount, background_tab_count_stats_.tab_load_user_initiated_count); } } void TabManagerStatsCollector::OnSessionRestoreStartedLoadingTabs() { DCHECK(!is_session_restore_loading_tabs_); UpdateSessionAndSequence(); CreateAndInitSwapMetricsDriverIfNeeded(SessionType::kSessionRestore); is_session_restore_loading_tabs_ = true; ClearStatsWhenInOverlappedSession(); } void TabManagerStatsCollector::OnSessionRestoreFinishedLoadingTabs() { DCHECK(is_session_restore_loading_tabs_); UMA_HISTOGRAM_BOOLEAN(kHistogramSessionOverlapSessionRestore, is_overlapping_session_restore_ ? true : false); if (swap_metrics_driver_) swap_metrics_driver_->UpdateMetrics(); is_session_restore_loading_tabs_ = false; is_overlapping_session_restore_ = false; } void TabManagerStatsCollector::OnBackgroundTabOpeningSessionStarted() { DCHECK(!is_in_background_tab_opening_session_); UpdateSessionAndSequence(); background_tab_count_stats_.Reset(); CreateAndInitSwapMetricsDriverIfNeeded(SessionType::kBackgroundTabOpening); is_in_background_tab_opening_session_ = true; ClearStatsWhenInOverlappedSession(); } void TabManagerStatsCollector::OnBackgroundTabOpeningSessionEnded() { DCHECK(is_in_background_tab_opening_session_); UMA_HISTOGRAM_BOOLEAN(kHistogramSessionOverlapBackgroundTabOpening, is_overlapping_background_tab_opening_ ? true : false); if (swap_metrics_driver_) swap_metrics_driver_->UpdateMetrics(); RecordBackgroundTabCount(); is_in_background_tab_opening_session_ = false; is_overlapping_background_tab_opening_ = false; } void TabManagerStatsCollector::CreateAndInitSwapMetricsDriverIfNeeded( SessionType type) { if (IsInOverlappedSession()) { swap_metrics_driver_ = nullptr; return; } // Always create a new instance in case there is a SessionType change because // this is shared between SessionRestore and BackgroundTabOpening. swap_metrics_driver_ = content::SwapMetricsDriver::Create( base::WrapUnique<content::SwapMetricsDriver::Delegate>( new SwapMetricsDelegate(this, type)), base::TimeDelta::FromSeconds(0)); // The driver could still be null on a platform with no swap driver support. if (swap_metrics_driver_) swap_metrics_driver_->InitializeMetrics(); } void TabManagerStatsCollector::RecordSwapMetrics(SessionType type, const std::string& metric_name, uint64_t count, base::TimeDelta interval) { base::HistogramBase* histogram = base::Histogram::FactoryGet( "TabManager.Experimental." + std::string(kSessionTypeName[type]) + "." + metric_name, 1, // minimum 10000, // maximum 50, // bucket_count base::HistogramBase::kUmaTargetedHistogramFlag); histogram->Add(static_cast<double>(count) / interval.InSecondsF()); } void TabManagerStatsCollector::OnUpdateSwapMetricsFailed() { swap_metrics_driver_ = nullptr; } void TabManagerStatsCollector::OnDidStartMainFrameNavigation( content::WebContents* contents) { foreground_contents_switched_to_times_.erase(contents); } void TabManagerStatsCollector::OnWillLoadNextBackgroundTab(bool timeout) { UMA_HISTOGRAM_BOOLEAN(kHistogramBackgroundTabOpeningTabLoadTimeout, timeout); } void TabManagerStatsCollector::OnTabIsLoaded(content::WebContents* contents) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); if (!base::ContainsKey(foreground_contents_switched_to_times_, contents)) return; base::TimeDelta switch_load_time = NowTicks() - foreground_contents_switched_to_times_[contents]; ukm::SourceId ukm_source_id = GetUkmSourceId(contents); if (is_session_restore_loading_tabs_ && !IsInOverlappedSession()) { UMA_HISTOGRAM_MEDIUM_TIMES(kHistogramSessionRestoreTabSwitchLoadTime, switch_load_time); if (ukm_source_id != ukm::kInvalidSourceId) { ukm::builders:: TabManager_Experimental_SessionRestore_TabSwitchLoadStopped( ukm_source_id) .SetSequenceId(sequence_++) .SetSessionRestoreSessionId(session_id_) .SetSessionRestoreTabCount( g_browser_process->GetTabManager()->restored_tab_count()) .SetSystemTabCount( g_browser_process->GetTabManager()->GetTabCount()) .SetTabSwitchLoadTime(switch_load_time.InMilliseconds()) .Record(ukm::UkmRecorder::Get()); } } if (is_in_background_tab_opening_session_ && !IsInOverlappedSession()) { UMA_HISTOGRAM_MEDIUM_TIMES(kHistogramBackgroundTabOpeningTabSwitchLoadTime, switch_load_time); if (ukm_source_id != ukm::kInvalidSourceId) { ukm::builders:: TabManager_Experimental_BackgroundTabOpening_TabSwitchLoadStopped( ukm_source_id) .SetBackgroundTabLoadingCount( g_browser_process->GetTabManager() ->GetBackgroundTabLoadingCount()) .SetBackgroundTabOpeningSessionId(session_id_) .SetBackgroundTabPendingCount( g_browser_process->GetTabManager() ->GetBackgroundTabPendingCount()) .SetSequenceId(sequence_++) .SetSystemTabCount( g_browser_process->GetTabManager()->GetTabCount()) .SetTabSwitchLoadTime(switch_load_time.InMilliseconds()) .Record(ukm::UkmRecorder::Get()); } } foreground_contents_switched_to_times_.erase(contents); } void TabManagerStatsCollector::OnWebContentsDestroyed( content::WebContents* contents) { foreground_contents_switched_to_times_.erase(contents); } bool TabManagerStatsCollector::IsInOverlappedSession() { return is_session_restore_loading_tabs_ && is_in_background_tab_opening_session_; } void TabManagerStatsCollector::ClearStatsWhenInOverlappedSession() { if (!IsInOverlappedSession()) return; swap_metrics_driver_ = nullptr; foreground_contents_switched_to_times_.clear(); background_tab_count_stats_.Reset(); is_overlapping_session_restore_ = true; is_overlapping_background_tab_opening_ = true; } void TabManagerStatsCollector::UpdateSessionAndSequence() { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); // This function is used by both SessionRestore and BackgroundTabOpening. This // is fine because we do not report any metric when those two overlap. ++session_id_; sequence_ = 0; } // static const char TabManagerStatsCollector:: kHistogramSessionRestoreForegroundTabExpectedTaskQueueingDuration[] = "TabManager.SessionRestore.ForegroundTab.ExpectedTaskQueueingDuration"; // static const char TabManagerStatsCollector:: kHistogramBackgroundTabOpeningForegroundTabExpectedTaskQueueingDuration[] = "TabManager.BackgroundTabOpening.ForegroundTab." "ExpectedTaskQueueingDuration"; // static const char TabManagerStatsCollector::kHistogramSessionRestoreSwitchToTab[] = "TabManager.SessionRestore.SwitchToTab"; // static const char TabManagerStatsCollector::kHistogramBackgroundTabOpeningSwitchToTab[] = "TabManager.BackgroundTabOpening.SwitchToTab"; // static const char TabManagerStatsCollector::kHistogramSessionRestoreTabSwitchLoadTime[] = "TabManager.Experimental.SessionRestore.TabSwitchLoadTime." "UntilTabIsLoaded"; // static const char TabManagerStatsCollector:: kHistogramBackgroundTabOpeningTabSwitchLoadTime[] = "TabManager.Experimental.BackgroundTabOpening.TabSwitchLoadTime." "UntilTabIsLoaded"; // static const char TabManagerStatsCollector::kHistogramBackgroundTabOpeningTabCount[] = "TabManager.BackgroundTabOpening.TabCount"; // static const char TabManagerStatsCollector::kHistogramBackgroundTabOpeningTabPausedCount[] = "TabManager.BackgroundTabOpening.TabPausedCount"; // static const char TabManagerStatsCollector:: kHistogramBackgroundTabOpeningTabLoadAutoStartedCount[] = "TabManager.BackgroundTabOpening.TabLoadAutoStartedCount"; // static const char TabManagerStatsCollector:: kHistogramBackgroundTabOpeningTabLoadUserInitiatedCount[] = "TabManager.BackgroundTabOpening.TabLoadUserInitiatedCount"; // static const char TabManagerStatsCollector::kHistogramBackgroundTabOpeningTabLoadTimeout[] = "TabManager.BackgroundTabOpening.TabLoadTimeout"; // static const char TabManagerStatsCollector::kHistogramSessionOverlapSessionRestore[] = "TabManager.SessionOverlap.SessionRestore"; // static const char TabManagerStatsCollector::kHistogramSessionOverlapBackgroundTabOpening[] = "TabManager.SessionOverlap.BackgroundTabOpening"; } // namespace resource_coordinator
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0529f73efe3e278582cda29c969523799aa84893
cfad0bf70426c15566d317f26a7423242325bba4
/libco/co_hook_sys_call.cpp
dd2399e447b4bcdec176cf8c8060ce6272dbb645
[]
no_license
bjut-hz/code-notes
25bc6f8fe0a65f77a85f5c6c5f24399fcdafb46c
50a8b4f58136f0771a5210ca1b7a6dff33f2f54e
refs/heads/master
2020-05-05T13:08:40.413979
2019-12-24T08:49:00
2019-12-24T08:49:00
158,189,650
0
0
null
null
null
null
UTF-8
C++
false
false
24,754
cpp
/* * Tencent is pleased to support the open source community by making Libco available. * Copyright (C) 2014 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <sys/socket.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/un.h> #include <dlfcn.h> #include <fcntl.h> #include <poll.h> #include <unistd.h> #include <errno.h> #include <netinet/in.h> #include <time.h> #include <pthread.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <resolv.h> #include <time.h> #include <map> #include "co_routine.h" #include "co_routine_inner.h" #include "co_routine_specific.h" typedef long long ll64_t; struct rpchook_t { int user_flag; struct sockaddr_in dest; // maybe sockaddr_un; int domain; // AF_LOCAL , AF_INET struct timeval read_timeout; struct timeval write_timeout; }; static inline pid_t GetPid() { char **p = (char **)pthread_self(); return p ? *(pid_t *)(p + 18) : getpid(); } static rpchook_t *g_rpchook_socket_fd[102400] = {0}; typedef int (*socket_pfn_t)(int domain, int type, int protocol); typedef int (*connect_pfn_t)(int socket, const struct sockaddr *address, socklen_t address_len); typedef int (*close_pfn_t)(int fd); typedef ssize_t (*read_pfn_t)(int fildes, void *buf, size_t nbyte); typedef ssize_t (*write_pfn_t)(int fildes, const void *buf, size_t nbyte); typedef ssize_t (*sendto_pfn_t)(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len); typedef ssize_t (*recvfrom_pfn_t)(int socket, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len); typedef size_t (*send_pfn_t)(int socket, const void *buffer, size_t length, int flags); typedef ssize_t (*recv_pfn_t)(int socket, void *buffer, size_t length, int flags); typedef int (*poll_pfn_t)(struct pollfd fds[], nfds_t nfds, int timeout); typedef int (*setsockopt_pfn_t)(int socket, int level, int option_name, const void *option_value, socklen_t option_len); typedef int (*fcntl_pfn_t)(int fildes, int cmd, ...); typedef struct tm *(*localtime_r_pfn_t)(const time_t *timep, struct tm *result); typedef void *(*pthread_getspecific_pfn_t)(pthread_key_t key); typedef int (*pthread_setspecific_pfn_t)(pthread_key_t key, const void *value); typedef int (*setenv_pfn_t)(const char *name, const char *value, int overwrite); typedef int (*unsetenv_pfn_t)(const char *name); typedef char *(*getenv_pfn_t)(const char *name); typedef hostent *(*gethostbyname_pfn_t)(const char *name); typedef res_state (*__res_state_pfn_t)(); typedef int (*__poll_pfn_t)(struct pollfd fds[], nfds_t nfds, int timeout); static socket_pfn_t g_sys_socket_func = (socket_pfn_t)dlsym(RTLD_NEXT, "socket"); static connect_pfn_t g_sys_connect_func = (connect_pfn_t)dlsym(RTLD_NEXT, "connect"); static close_pfn_t g_sys_close_func = (close_pfn_t)dlsym(RTLD_NEXT, "close"); static read_pfn_t g_sys_read_func = (read_pfn_t)dlsym(RTLD_NEXT, "read"); static write_pfn_t g_sys_write_func = (write_pfn_t)dlsym(RTLD_NEXT, "write"); static sendto_pfn_t g_sys_sendto_func = (sendto_pfn_t)dlsym(RTLD_NEXT, "sendto"); static recvfrom_pfn_t g_sys_recvfrom_func = (recvfrom_pfn_t)dlsym(RTLD_NEXT, "recvfrom"); static send_pfn_t g_sys_send_func = (send_pfn_t)dlsym(RTLD_NEXT, "send"); static recv_pfn_t g_sys_recv_func = (recv_pfn_t)dlsym(RTLD_NEXT, "recv"); static poll_pfn_t g_sys_poll_func = (poll_pfn_t)dlsym(RTLD_NEXT, "poll"); static setsockopt_pfn_t g_sys_setsockopt_func = (setsockopt_pfn_t)dlsym(RTLD_NEXT, "setsockopt"); static fcntl_pfn_t g_sys_fcntl_func = (fcntl_pfn_t)dlsym(RTLD_NEXT, "fcntl"); static setenv_pfn_t g_sys_setenv_func = (setenv_pfn_t)dlsym(RTLD_NEXT, "setenv"); static unsetenv_pfn_t g_sys_unsetenv_func = (unsetenv_pfn_t)dlsym(RTLD_NEXT, "unsetenv"); static getenv_pfn_t g_sys_getenv_func = (getenv_pfn_t)dlsym(RTLD_NEXT, "getenv"); static __res_state_pfn_t g_sys___res_state_func = (__res_state_pfn_t)dlsym(RTLD_NEXT, "__res_state"); static gethostbyname_pfn_t g_sys_gethostbyname_func = (gethostbyname_pfn_t)dlsym(RTLD_NEXT, "gethostbyname"); static __poll_pfn_t g_sys___poll_func = (__poll_pfn_t)dlsym(RTLD_NEXT, "__poll"); /* static pthread_getspecific_pfn_t g_sys_pthread_getspecific_func = (pthread_getspecific_pfn_t)dlsym(RTLD_NEXT,"pthread_getspecific"); static pthread_setspecific_pfn_t g_sys_pthread_setspecific_func = (pthread_setspecific_pfn_t)dlsym(RTLD_NEXT,"pthread_setspecific"); static pthread_rwlock_rdlock_pfn_t g_sys_pthread_rwlock_rdlock_func = (pthread_rwlock_rdlock_pfn_t)dlsym(RTLD_NEXT,"pthread_rwlock_rdlock"); static pthread_rwlock_wrlock_pfn_t g_sys_pthread_rwlock_wrlock_func = (pthread_rwlock_wrlock_pfn_t)dlsym(RTLD_NEXT,"pthread_rwlock_wrlock"); static pthread_rwlock_unlock_pfn_t g_sys_pthread_rwlock_unlock_func = (pthread_rwlock_unlock_pfn_t)dlsym(RTLD_NEXT,"pthread_rwlock_unlock"); */ static inline unsigned long long get_tick_count() { uint32_t lo, hi; __asm__ __volatile__("rdtscp" : "=a"(lo), "=d"(hi)); return ((unsigned long long)lo) | (((unsigned long long)hi) << 32); } struct rpchook_connagent_head_t { unsigned char bVersion; struct in_addr iIP; unsigned short hPort; unsigned int iBodyLen; unsigned int iOssAttrID; unsigned char bIsRespNotExist; unsigned char sReserved[6]; } __attribute__((packed)); #define HOOK_SYS_FUNC(name) \ if (!g_sys_##name##_func) { \ g_sys_##name##_func = (name##_pfn_t)dlsym(RTLD_NEXT, #name); \ } static inline ll64_t diff_ms(struct timeval &begin, struct timeval &end) { ll64_t u = (end.tv_sec - begin.tv_sec); u *= 1000 * 10; u += (end.tv_usec - begin.tv_usec) / (100); return u; } static inline rpchook_t *get_by_fd(int fd) { if (fd > -1 && fd < (int)sizeof(g_rpchook_socket_fd) / (int)sizeof(g_rpchook_socket_fd[0])) { return g_rpchook_socket_fd[fd]; } return NULL; } static inline rpchook_t *alloc_by_fd(int fd) { if (fd > -1 && fd < (int)sizeof(g_rpchook_socket_fd) / (int)sizeof(g_rpchook_socket_fd[0])) { rpchook_t *lp = (rpchook_t *)calloc(1, sizeof(rpchook_t)); lp->read_timeout.tv_sec = 1; lp->write_timeout.tv_sec = 1; g_rpchook_socket_fd[fd] = lp; return lp; } return NULL; } static inline void free_by_fd(int fd) { if (fd > -1 && fd < (int)sizeof(g_rpchook_socket_fd) / (int)sizeof(g_rpchook_socket_fd[0])) { rpchook_t *lp = g_rpchook_socket_fd[fd]; if (lp) { g_rpchook_socket_fd[fd] = NULL; free(lp); } } return; } int socket(int domain, int type, int protocol) { HOOK_SYS_FUNC(socket); if (!co_is_enable_sys_hook()) { return g_sys_socket_func(domain, type, protocol); } int fd = g_sys_socket_func(domain, type, protocol); if (fd < 0) { return fd; } rpchook_t *lp = alloc_by_fd(fd); lp->domain = domain; fcntl(fd, F_SETFL, g_sys_fcntl_func(fd, F_GETFL, 0)); return fd; } int co_accept(int fd, struct sockaddr *addr, socklen_t *len) { int cli = accept(fd, addr, len); if (cli < 0) { return cli; } alloc_by_fd(cli); return cli; } int connect(int fd, const struct sockaddr *address, socklen_t address_len) { HOOK_SYS_FUNC(connect); if (!co_is_enable_sys_hook()) { return g_sys_connect_func(fd, address, address_len); } // 1.sys call int ret = g_sys_connect_func(fd, address, address_len); rpchook_t *lp = get_by_fd(fd); if (!lp) return ret; if (sizeof(lp->dest) >= address_len) { memcpy(&(lp->dest), address, (int)address_len); } if (O_NONBLOCK & lp->user_flag) { return ret; } if (!(ret < 0 && errno == EINPROGRESS)) { return ret; } // 2.wait int pollret = 0; struct pollfd pf = {0}; for (int i = 0; i < 3; i++) // 25s * 3 = 75s { memset(&pf, 0, sizeof(pf)); pf.fd = fd; pf.events = (POLLOUT | POLLERR | POLLHUP); pollret = poll(&pf, 1, 25000); if (1 == pollret) { break; } } if (pf.revents & POLLOUT) // connect succ { // 3.check getsockopt ret int err = 0; socklen_t errlen = sizeof(err); ret = getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &errlen); if (ret < 0) { return ret; } else if (err != 0) { errno = err; return -1; } errno = 0; return 0; } errno = ETIMEDOUT; return ret; } int close(int fd) { HOOK_SYS_FUNC(close); if (!co_is_enable_sys_hook()) { return g_sys_close_func(fd); } free_by_fd(fd); int ret = g_sys_close_func(fd); return ret; } ssize_t read(int fd, void *buf, size_t nbyte) { HOOK_SYS_FUNC(read); if (!co_is_enable_sys_hook()) { return g_sys_read_func(fd, buf, nbyte); } rpchook_t *lp = get_by_fd(fd); if (!lp || (O_NONBLOCK & lp->user_flag)) { ssize_t ret = g_sys_read_func(fd, buf, nbyte); return ret; } int timeout = (lp->read_timeout.tv_sec * 1000) + (lp->read_timeout.tv_usec / 1000); struct pollfd pf = {0}; pf.fd = fd; pf.events = (POLLIN | POLLERR | POLLHUP); int pollret = poll(&pf, 1, timeout); ssize_t readret = g_sys_read_func(fd, (char *)buf, nbyte); if (readret < 0) { co_log_err("CO_ERR: read fd %d ret %ld errno %d poll ret %d timeout %d", fd, readret, errno, pollret, timeout); } return readret; } ssize_t write(int fd, const void *buf, size_t nbyte) { HOOK_SYS_FUNC(write); if (!co_is_enable_sys_hook()) { return g_sys_write_func(fd, buf, nbyte); } rpchook_t *lp = get_by_fd(fd); if (!lp || (O_NONBLOCK & lp->user_flag)) { ssize_t ret = g_sys_write_func(fd, buf, nbyte); return ret; } size_t wrotelen = 0; int timeout = (lp->write_timeout.tv_sec * 1000) + (lp->write_timeout.tv_usec / 1000); ssize_t writeret = g_sys_write_func(fd, (const char *)buf + wrotelen, nbyte - wrotelen); if (writeret == 0) { return writeret; } if (writeret > 0) { wrotelen += writeret; } while (wrotelen < nbyte) { struct pollfd pf = {0}; pf.fd = fd; pf.events = (POLLOUT | POLLERR | POLLHUP); poll(&pf, 1, timeout); writeret = g_sys_write_func(fd, (const char *)buf + wrotelen, nbyte - wrotelen); if (writeret <= 0) { break; } wrotelen += writeret; } if (writeret <= 0 && wrotelen == 0) { return writeret; } return wrotelen; } ssize_t sendto(int socket, const void *message, size_t length, int flags, const struct sockaddr *dest_addr, socklen_t dest_len) { /* 1.no enable sys call ? sys 2.( !lp || lp is non block ) ? sys 3.try 4.wait 5.try */ HOOK_SYS_FUNC(sendto); if (!co_is_enable_sys_hook()) { return g_sys_sendto_func(socket, message, length, flags, dest_addr, dest_len); } rpchook_t *lp = get_by_fd(socket); if (!lp || (O_NONBLOCK & lp->user_flag)) { return g_sys_sendto_func(socket, message, length, flags, dest_addr, dest_len); } ssize_t ret = g_sys_sendto_func(socket, message, length, flags, dest_addr, dest_len); if (ret < 0 && EAGAIN == errno) { int timeout = (lp->write_timeout.tv_sec * 1000) + (lp->write_timeout.tv_usec / 1000); struct pollfd pf = {0}; pf.fd = socket; pf.events = (POLLOUT | POLLERR | POLLHUP); poll(&pf, 1, timeout); ret = g_sys_sendto_func(socket, message, length, flags, dest_addr, dest_len); } return ret; } ssize_t recvfrom(int socket, void *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len) { HOOK_SYS_FUNC(recvfrom); if (!co_is_enable_sys_hook()) { return g_sys_recvfrom_func(socket, buffer, length, flags, address, address_len); } rpchook_t *lp = get_by_fd(socket); if (!lp || (O_NONBLOCK & lp->user_flag)) { return g_sys_recvfrom_func(socket, buffer, length, flags, address, address_len); } int timeout = (lp->read_timeout.tv_sec * 1000) + (lp->read_timeout.tv_usec / 1000); struct pollfd pf = {0}; pf.fd = socket; pf.events = (POLLIN | POLLERR | POLLHUP); poll(&pf, 1, timeout); ssize_t ret = g_sys_recvfrom_func(socket, buffer, length, flags, address, address_len); return ret; } ssize_t send(int socket, const void *buffer, size_t length, int flags) { HOOK_SYS_FUNC(send); if (!co_is_enable_sys_hook()) { return g_sys_send_func(socket, buffer, length, flags); } rpchook_t *lp = get_by_fd(socket); if (!lp || (O_NONBLOCK & lp->user_flag)) { return g_sys_send_func(socket, buffer, length, flags); } size_t wrotelen = 0; int timeout = (lp->write_timeout.tv_sec * 1000) + (lp->write_timeout.tv_usec / 1000); ssize_t writeret = g_sys_send_func(socket, buffer, length, flags); if (writeret == 0) { return writeret; } if (writeret > 0) { wrotelen += writeret; } while (wrotelen < length) { struct pollfd pf = {0}; pf.fd = socket; pf.events = (POLLOUT | POLLERR | POLLHUP); poll(&pf, 1, timeout); writeret = g_sys_send_func(socket, (const char *)buffer + wrotelen, length - wrotelen, flags); if (writeret <= 0) { break; } wrotelen += writeret; } if (writeret <= 0 && wrotelen == 0) { return writeret; } return wrotelen; } ssize_t recv(int socket, void *buffer, size_t length, int flags) { HOOK_SYS_FUNC(recv); if (!co_is_enable_sys_hook()) { return g_sys_recv_func(socket, buffer, length, flags); } rpchook_t *lp = get_by_fd(socket); if (!lp || (O_NONBLOCK & lp->user_flag)) { return g_sys_recv_func(socket, buffer, length, flags); } int timeout = (lp->read_timeout.tv_sec * 1000) + (lp->read_timeout.tv_usec / 1000); struct pollfd pf = {0}; pf.fd = socket; pf.events = (POLLIN | POLLERR | POLLHUP); int pollret = poll(&pf, 1, timeout); ssize_t readret = g_sys_recv_func(socket, buffer, length, flags); if (readret < 0) { co_log_err("CO_ERR: read fd %d ret %ld errno %d poll ret %d timeout %d", socket, readret, errno, pollret, timeout); } return readret; } extern int co_poll_inner(stCoEpoll_t *ctx, struct pollfd fds[], nfds_t nfds, int timeout, poll_pfn_t pollfunc); int poll(struct pollfd fds[], nfds_t nfds, int timeout) { HOOK_SYS_FUNC(poll); if (!co_is_enable_sys_hook() || timeout == 0) { return g_sys_poll_func(fds, nfds, timeout); } pollfd *fds_merge = NULL; nfds_t nfds_merge = 0; std::map<int, int> m; // fd --> idx std::map<int, int>::iterator it; if (nfds > 1) { fds_merge = (pollfd *)malloc(sizeof(pollfd) * nfds); for (size_t i = 0; i < nfds; i++) { if ((it = m.find(fds[i].fd)) == m.end()) { fds_merge[nfds_merge] = fds[i]; m[fds[i].fd] = nfds_merge; nfds_merge++; } else { int j = it->second; fds_merge[j].events |= fds[i].events; // merge in j slot } } } int ret = 0; if (nfds_merge == nfds || nfds == 1) { ret = co_poll_inner(co_get_epoll_ct(), fds, nfds, timeout, g_sys_poll_func); } else { ret = co_poll_inner(co_get_epoll_ct(), fds_merge, nfds_merge, timeout, g_sys_poll_func); if (ret > 0) { for (size_t i = 0; i < nfds; i++) { it = m.find(fds[i].fd); if (it != m.end()) { int j = it->second; fds[i].revents = fds_merge[j].revents & fds[i].events; } } } } free(fds_merge); return ret; } int setsockopt(int fd, int level, int option_name, const void *option_value, socklen_t option_len) { HOOK_SYS_FUNC(setsockopt); if (!co_is_enable_sys_hook()) { return g_sys_setsockopt_func(fd, level, option_name, option_value, option_len); } rpchook_t *lp = get_by_fd(fd); if (lp && SOL_SOCKET == level) { struct timeval *val = (struct timeval *)option_value; if (SO_RCVTIMEO == option_name) { memcpy(&lp->read_timeout, val, sizeof(*val)); } else if (SO_SNDTIMEO == option_name) { memcpy(&lp->write_timeout, val, sizeof(*val)); } } return g_sys_setsockopt_func(fd, level, option_name, option_value, option_len); } int fcntl(int fildes, int cmd, ...) { HOOK_SYS_FUNC(fcntl); if (fildes < 0) { return __LINE__; } va_list arg_list; va_start(arg_list, cmd); int ret = -1; rpchook_t *lp = get_by_fd(fildes); switch (cmd) { case F_DUPFD: { int param = va_arg(arg_list, int); ret = g_sys_fcntl_func(fildes, cmd, param); break; } case F_GETFD: { ret = g_sys_fcntl_func(fildes, cmd); if (lp && !(lp->user_flag & O_NONBLOCK)) { ret = ret & (~O_NONBLOCK); } break; } case F_SETFD: { int param = va_arg(arg_list, int); ret = g_sys_fcntl_func(fildes, cmd, param); break; } case F_GETFL: { ret = g_sys_fcntl_func(fildes, cmd); break; } case F_SETFL: { int param = va_arg(arg_list, int); int flag = param; if (co_is_enable_sys_hook() && lp) { flag |= O_NONBLOCK; } ret = g_sys_fcntl_func(fildes, cmd, flag); if (0 == ret && lp) { lp->user_flag = param; } break; } case F_GETOWN: { ret = g_sys_fcntl_func(fildes, cmd); break; } case F_SETOWN: { int param = va_arg(arg_list, int); ret = g_sys_fcntl_func(fildes, cmd, param); break; } case F_GETLK: { struct flock *param = va_arg(arg_list, struct flock *); ret = g_sys_fcntl_func(fildes, cmd, param); break; } case F_SETLK: { struct flock *param = va_arg(arg_list, struct flock *); ret = g_sys_fcntl_func(fildes, cmd, param); break; } case F_SETLKW: { struct flock *param = va_arg(arg_list, struct flock *); ret = g_sys_fcntl_func(fildes, cmd, param); break; } } va_end(arg_list); return ret; } struct stCoSysEnv_t { char *name; char *value; }; struct stCoSysEnvArr_t { stCoSysEnv_t *data; size_t cnt; }; static stCoSysEnvArr_t *dup_co_sysenv_arr(stCoSysEnvArr_t *arr) { stCoSysEnvArr_t *lp = (stCoSysEnvArr_t *)calloc(sizeof(stCoSysEnvArr_t), 1); if (arr->cnt) { lp->data = (stCoSysEnv_t *)calloc(sizeof(stCoSysEnv_t) * arr->cnt, 1); lp->cnt = arr->cnt; memcpy(lp->data, arr->data, sizeof(stCoSysEnv_t) * arr->cnt); } return lp; } static int co_sysenv_comp(const void *a, const void *b) { return strcmp(((stCoSysEnv_t *)a)->name, ((stCoSysEnv_t *)b)->name); } static stCoSysEnvArr_t g_co_sysenv = {0}; void co_set_env_list(const char *name[], size_t cnt) { if (g_co_sysenv.data) { return; } g_co_sysenv.data = (stCoSysEnv_t *)calloc(1, sizeof(stCoSysEnv_t) * cnt); for (size_t i = 0; i < cnt; i++) { if (name[i] && name[i][0]) { g_co_sysenv.data[g_co_sysenv.cnt++].name = strdup(name[i]); } } if (g_co_sysenv.cnt > 1) { qsort(g_co_sysenv.data, g_co_sysenv.cnt, sizeof(stCoSysEnv_t), co_sysenv_comp); stCoSysEnv_t *lp = g_co_sysenv.data; stCoSysEnv_t *lq = g_co_sysenv.data + 1; for (size_t i = 1; i < g_co_sysenv.cnt; i++) { if (strcmp(lp->name, lq->name)) { ++lp; if (lq != lp) { *lp = *lq; } } ++lq; } g_co_sysenv.cnt = lp - g_co_sysenv.data + 1; } } int setenv(const char *n, const char *value, int overwrite) { HOOK_SYS_FUNC(setenv) if (co_is_enable_sys_hook() && g_co_sysenv.data) { stCoRoutine_t *self = co_self(); if (self) { if (!self->pvEnv) { self->pvEnv = dup_co_sysenv_arr(&g_co_sysenv); } stCoSysEnvArr_t *arr = (stCoSysEnvArr_t *)(self->pvEnv); stCoSysEnv_t name = {(char *)n, 0}; stCoSysEnv_t *e = (stCoSysEnv_t *)bsearch(&name, arr->data, arr->cnt, sizeof(name), co_sysenv_comp); if (e) { if (overwrite || !e->value) { if (e->value) free(e->value); e->value = (value ? strdup(value) : 0); } return 0; } } } return g_sys_setenv_func(n, value, overwrite); } int unsetenv(const char *n) { HOOK_SYS_FUNC(unsetenv) if (co_is_enable_sys_hook() && g_co_sysenv.data) { stCoRoutine_t *self = co_self(); if (self) { if (!self->pvEnv) { self->pvEnv = dup_co_sysenv_arr(&g_co_sysenv); } stCoSysEnvArr_t *arr = (stCoSysEnvArr_t *)(self->pvEnv); stCoSysEnv_t name = {(char *)n, 0}; stCoSysEnv_t *e = (stCoSysEnv_t *)bsearch(&name, arr->data, arr->cnt, sizeof(name), co_sysenv_comp); if (e) { if (e->value) { free(e->value); e->value = 0; } return 0; } } } return g_sys_unsetenv_func(n); } char *getenv(const char *n) { HOOK_SYS_FUNC(getenv) if (co_is_enable_sys_hook() && g_co_sysenv.data) { stCoRoutine_t *self = co_self(); stCoSysEnv_t name = {(char *)n, 0}; if (!self->pvEnv) { self->pvEnv = dup_co_sysenv_arr(&g_co_sysenv); } stCoSysEnvArr_t *arr = (stCoSysEnvArr_t *)(self->pvEnv); stCoSysEnv_t *e = (stCoSysEnv_t *)bsearch(&name, arr->data, arr->cnt, sizeof(name), co_sysenv_comp); if (e) { return e->value; } } return g_sys_getenv_func(n); } struct hostent *co_gethostbyname(const char *name); struct hostent *gethostbyname(const char *name) { HOOK_SYS_FUNC(gethostbyname); #if defined(__APPLE__) || defined(__FreeBSD__) return g_sys_gethostbyname_func(name); #else if (!co_is_enable_sys_hook()) { return g_sys_gethostbyname_func(name); } return co_gethostbyname(name); #endif } struct res_state_wrap { struct __res_state state; }; CO_ROUTINE_SPECIFIC(res_state_wrap, __co_state_wrap); extern "C" { res_state __res_state() { HOOK_SYS_FUNC(__res_state); if (!co_is_enable_sys_hook()) { return g_sys___res_state_func(); } return &(__co_state_wrap->state); } int __poll(struct pollfd fds[], nfds_t nfds, int timeout) { return poll(fds, nfds, timeout); } } struct hostbuf_wrap { struct hostent host; char *buffer; size_t iBufferSize; int host_errno; }; CO_ROUTINE_SPECIFIC(hostbuf_wrap, __co_hostbuf_wrap); #if !defined(__APPLE__) && !defined(__FreeBSD__) struct hostent *co_gethostbyname(const char *name) { if (!name) { return NULL; } if (__co_hostbuf_wrap->buffer && __co_hostbuf_wrap->iBufferSize > 1024) { free(__co_hostbuf_wrap->buffer); __co_hostbuf_wrap->buffer = NULL; } if (!__co_hostbuf_wrap->buffer) { __co_hostbuf_wrap->buffer = (char *)malloc(1024); __co_hostbuf_wrap->iBufferSize = 1024; } struct hostent *host = &__co_hostbuf_wrap->host; struct hostent *result = NULL; int *h_errnop = &(__co_hostbuf_wrap->host_errno); int ret = -1; while (ret = gethostbyname_r(name, host, __co_hostbuf_wrap->buffer, __co_hostbuf_wrap->iBufferSize, &result, h_errnop) == ERANGE && *h_errnop == NETDB_INTERNAL) { free(__co_hostbuf_wrap->buffer); __co_hostbuf_wrap->iBufferSize = __co_hostbuf_wrap->iBufferSize * 2; __co_hostbuf_wrap->buffer = (char *)malloc(__co_hostbuf_wrap->iBufferSize); } if (ret == 0 && (host == result)) { return host; } return NULL; } #endif void co_enable_hook_sys() //这函数必须在这里,否则本文件会被忽略!!! { stCoRoutine_t *co = GetCurrThreadCo(); if (co) { co->cEnableSysHook = 1; } }
[ "936432896@qq.com" ]
936432896@qq.com
38eb9ba6a722efcc5db2cb43215b5fe8f50c4073
8117703ce58eddc2eef1a8d85b81a4632f9d30b9
/src/managers/ImageManager.cpp
0342496968e519ea74cd94b6d9aa1377eff200ff
[]
no_license
JesseTG/RAY
f7434b2b96a5c933df941020ce7b512ef1595e7b
1cb9487852eb07fc0f702da595d77d346e4d8e8d
refs/heads/master
2020-05-18T19:43:42.832051
2014-05-17T03:03:16
2014-05-17T03:03:16
16,424,298
1
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#include "ImageManager.hpp" #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> namespace ray { ImageManager::ImageManager() { //ctor } ImageManager::~ImageManager() { //dtor } bool ImageManager::loadConfigFile(const string& path) { boost::property_tree::ptree config; boost::property_tree::read_json(path, config); // TODO: Handle exception for (const auto& i : config.get_child("files")) { // i.first is the key, i.second is the path this->acquire(thor::Resources::fromFile<Image>(i.second.data())); } return true; } }
[ "jessetalavera@aol.com" ]
jessetalavera@aol.com
a0ad6b776e06f15c931ae4126a83dd124072f229
69b71cc6f8a4fd470c344ecdaff4e69dc648efe2
/examples/deleter0.cpp
b657d7fd9f0cd16b1bca0b20940ae477b447080f
[]
no_license
chardan/Provo_2016
a7497e06c8de4f1ec42fdaf327d113a11425991b
80d5fea8efee1edcc782545a72357cd4ac71d3ce
refs/heads/master
2020-07-03T11:51:39.164179
2016-11-18T23:53:11
2016-11-18T23:53:11
74,175,582
0
0
null
null
null
null
UTF-8
C++
false
false
479
cpp
/* Example showing a deleter being used to help interface with C: */ #include <cstdio> #include <vector> #include <memory> using namespace std; using file_ptr = unique_ptr<FILE, decltype(&fclose)>; auto write_things(const vector<char>& things) { // Real-world programs should check for errors: auto fp = file_ptr(fopen("data.dat", "w"), &fclose); return fwrite(things.data(), things.size(), 1, fp.get()); } int main() { write_things({ 'a', 'b', 'c', 'd', 'e' }); }
[ "jwilliamson@suse.de" ]
jwilliamson@suse.de
763efff91438b91e98a939b6359b5200b604d4e7
6fbf7d4855a0639eb57d37eb4a02758fc137e77e
/ModuleAlgorithm/include/implement/composer/GateCoordinateConverterImpl.h
0ee2ed9ac11c0f83cfb583ec36252c82d07bea26
[]
no_license
wws2003/Research
f9abb8ea7acd98ed829f23a39cb05a80d738bb6d
3c839b7b35ddfcc5373f96808c3dc7125200da94
refs/heads/master
2020-04-06T07:04:28.103498
2016-08-10T06:18:04
2016-08-10T06:18:04
33,717,928
0
0
null
null
null
null
UTF-8
C++
false
false
1,385
h
/* * GateCoordinateConverterImpl.h * * Created on: Dec 8, 2015 * Author: pham */ #ifndef GATECOORDINATECONVERTERIMPL_H_ #define GATECOORDINATECONVERTERIMPL_H_ #include "Gate.h" #include "Coordinate.hpp" #include "IConverter.h" #include "ICoordinateCalculator.h" #include "IMatrixOperator.h" class GateCoordinateConverterImpl: public IConverter<GatePtr, RealCoordinate<GatePtr> >{ public: GateCoordinateConverterImpl(GateRealCoordinateCalculatorPtr pGateCoordinateCalculator, MatrixOperatorPtr pMatrixOperator, bool phaseIgnored = false); //Override void convert12(const GatePtr& t1, RealCoordinate<GatePtr>& t2); //Override void convert21(const RealCoordinate<GatePtr>& t2, GatePtr& t1); private: void getEquivalentCoordinates(const GatePtr& pGate, std::vector<RealCoordinatePtr<GatePtr> >& equivalentCoordinates); void getEquivalentGates(const RealCoordinatePtr<GatePtr> pGateCoord, std::vector<GatePtr> & equivalentGates); void getEquivalentPhaseFactors(std::vector<ComplexVal>& phaseFactors, int matrixSize); void releaseEquivalentGates(std::vector<GatePtr> & equivalentGates); void releaseEquivalentCoordinates(std::vector<RealCoordinatePtr<GatePtr> >& equivalentCoordinates); GateRealCoordinateCalculatorPtr m_pGateCoordinateCalculator; MatrixOperatorPtr m_pMatrixOperator; bool m_phaseIgnored; }; #endif /* GATECOORDINATECONVERTERIMPL_H_ */
[ "pham@apecsa-indonesia.com" ]
pham@apecsa-indonesia.com
4849c7cf3ed8efd276805164475680ea27469edd
585a2ab4efc6783d97a9eb0b04bcceb8379cec30
/csp-integral-test/tests/capi-2/encrypt-message.h
93b497cce0d17597c96fe5f05b05f64c37f82b9f
[]
no_license
kirillsms/XmlSignWebService
8fbf3f7ab3aa29d28de3321e8ae8c88b6cd10a14
cd778449fd1cecf00f662dc5bf0ee939c14204b8
refs/heads/master
2021-05-27T14:04:17.833715
2013-07-03T11:38:58
2013-07-03T11:38:58
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,147
h
/// @file /// @brief Файл содержит определение класса, тестирующего шифрование форматированного сообщения. /// /// Copyright (c) InfoTeCS. All Rights Reserved. #ifndef encrypt_message_h__ #define encrypt_message_h__ #include "../test-base.h" #if defined(_WIN32) #include "../../tools/certificate-search.h" #endif /// @brief Тестирует формирование и шифрование форматированного сообщения class EncryptMessage: public TestBase { public: EncryptMessage(); ~EncryptMessage(); /// @brief Запуск теста. virtual void Run(); private: // void PrepareProviderContext(); /// @brief Шифрование сообщения. void Encrypt(); /// @brief Расшифрование сообщения. void Decrypt() const; private: // HCRYPTPROV prov_; std::vector<BYTE> message_; std::vector<BYTE> encryptedBlob_; #if defined(_WIN32) CertificateGuiSearch certificateSearch_; #endif }; #endif // encrypt_message_h__
[ "yurabuy@yandex.ru" ]
yurabuy@yandex.ru
4c39052ee365dd1938796d55e5f4e5e0f1a11ed2
d0fb46aecc3b69983e7f6244331a81dff42d9595
/companyreg/src/model/CreateBusinessOpportunityRequest.cc
5c5d953b2a9d718a483bd23a2c59de373da662c1
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-cpp-sdk
3d8d051d44ad00753a429817dd03957614c0c66a
e862bd03c844bcb7ccaa90571bceaa2802c7f135
refs/heads/master
2023-08-29T11:54:00.525102
2023-08-29T03:32:48
2023-08-29T03:32:48
115,379,460
104
82
NOASSERTION
2023-09-14T06:13:33
2017-12-26T02:53:27
C++
UTF-8
C++
false
false
2,224
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/companyreg/model/CreateBusinessOpportunityRequest.h> using AlibabaCloud::Companyreg::Model::CreateBusinessOpportunityRequest; CreateBusinessOpportunityRequest::CreateBusinessOpportunityRequest() : RpcServiceRequest("companyreg", "2020-03-06", "CreateBusinessOpportunity") { setMethod(HttpRequest::Method::Post); } CreateBusinessOpportunityRequest::~CreateBusinessOpportunityRequest() {} std::string CreateBusinessOpportunityRequest::getMobile()const { return mobile_; } void CreateBusinessOpportunityRequest::setMobile(const std::string& mobile) { mobile_ = mobile; setParameter("Mobile", mobile); } int CreateBusinessOpportunityRequest::getSource()const { return source_; } void CreateBusinessOpportunityRequest::setSource(int source) { source_ = source; setParameter("Source", std::to_string(source)); } std::string CreateBusinessOpportunityRequest::getVCode()const { return vCode_; } void CreateBusinessOpportunityRequest::setVCode(const std::string& vCode) { vCode_ = vCode; setParameter("VCode", vCode); } std::string CreateBusinessOpportunityRequest::getContactName()const { return contactName_; } void CreateBusinessOpportunityRequest::setContactName(const std::string& contactName) { contactName_ = contactName; setParameter("ContactName", contactName); } std::string CreateBusinessOpportunityRequest::getBizType()const { return bizType_; } void CreateBusinessOpportunityRequest::setBizType(const std::string& bizType) { bizType_ = bizType; setParameter("BizType", bizType); }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
6b44b684572df7fdb377cdb4c5b6a3dc77ceb982
96206b0c1a2e831f52f3154a4e3a8874c9a0d7e8
/src/kits/random_input.cpp
efd28afdeae3bce0c5c9989c72228afadce20859
[]
no_license
shemmer/zapps
6b9d3fb7457c0e0acb3415aebbe1e3b364dde38d
ec7d1b06dc4da724c46003f79fbd84b752c872ea
refs/heads/master
2021-01-19T06:02:56.997905
2015-07-28T08:04:30
2015-07-28T08:04:30
40,187,071
1
0
null
2015-08-04T13:41:48
2015-08-04T13:41:48
null
UTF-8
C++
false
false
1,798
cpp
#include "util/random_input.h" const char CAPS_CHAR_ARRAY[] = { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" }; const char NUMBERS_CHAR_ARRAY[] = { "012345789" }; int URand(const int low, const int high) { thread_t* self = thread_get_self(); assert (self); randgen_t* randgenp = self->randgen(); assert (randgenp); int d = high - low + 1; return (low + randgenp->rand(d)); } bool URandBool() { return (URand(0,1) ? true : false); } short URandShort(const short low, const short high) { thread_t* self = thread_get_self(); assert (self); randgen_t* randgenp = self->randgen(); assert (randgenp); short d = high - low + 1; return (low + (short)randgenp->rand(d)); } void URandFillStrCaps(char* dest, const int sz) { assert (dest); for (int i=0; i<sz; i++) { dest[i] = CAPS_CHAR_ARRAY[URand(0,sizeof(CAPS_CHAR_ARRAY)-1)]; } } void URandFillStrNumbx(char* dest, const int sz) { assert (dest); for (int i=0; i<sz; i++) { dest[i] = NUMBERS_CHAR_ARRAY[URand(0,sizeof(NUMBERS_CHAR_ARRAY)-1)]; } } #define USE_ZIPF 1 bool _g_enableZipf = false; double _g_ZipfS = 0.0; //Zipfian between low and high int ZRand(const int low, const int high) { zipfian myZipf(high-low+2,_g_ZipfS); thread_t* self = thread_get_self(); assert (self); randgen_t* randgenp = self->randgen(); assert (randgenp); double u = (double)randgenp->rand(10000)/double(10000); return (myZipf.next(u)+low-1); } void setZipf(const bool isEnabled, const double s) { _g_enableZipf = isEnabled; _g_ZipfS = s; } //If enableZip is set to 1 then return zipfian else returns uniform int UZRand(const int low, const int high) { #ifdef USE_ZIPF return ( _g_enableZipf? ( ZRand(low,high) ):( URand(low,high) )); #else return URand(low,high); #endif }
[ "csauer@cs.uni-kl.de" ]
csauer@cs.uni-kl.de
7716f40249792531adcacbc3094e7ddb55058e7f
846f4dc2f720f88080df1e1082e0c854f188450b
/main.cpp
326d5134554f58903385877a94a54f97829d9081
[]
no_license
Ali-1999/link-list-in-c-
bebd94ebb595932b1bb047eb8cc77a726c0ad983
736f08051bea130205abb9411f58c8b03d60a445
refs/heads/master
2022-04-17T12:10:27.726526
2020-04-19T19:16:48
2020-04-19T19:16:48
257,081,527
0
0
null
null
null
null
UTF-8
C++
false
false
1,603
cpp
#include"student.h" #include<conio.h> #include"course.h" #include<iostream> #include<string> using namespace std; void main() { string cour, stud; int c, csd, cms,tr; cout << "\nenter course name : "; getline(cin, cour); cout << "\ncourse id : "; cin >> csd; course cr(csd,cour); do { cout << "\n|1|\t<---------------ADD at top------> "; cout << "\n|2|\t<---------------ADD at last----->"; cout << "\n|3|\t<---------------ADD at anywhere->"; cout << "\n|4|\t<---------------Delete student--->"; cout << "\n|5|\t<---------------Print the list----> "; cin >> c; switch (c) { case 1: cin.ignore(); cout << "\n Student name : "; getline(cin, stud); cout << "\nenter cms : "; cin >> cms; cr.add_head(cms, stud); cout << "\n<-----------added successfullu---------->\n"; break; case 2: cin.ignore(); cout << "\n Student name : "; getline(cin, stud); cout << "\nenter cms : "; cin >> cms; cr.add_tail(cms, stud); cout << "\n<-----------added successfullu---------->\n"; break; case 3: cout << "\n enter previous cms : "; cin >> tr; cin.ignore(); cout << "\n Student name : "; getline(cin, stud); cout << "\nenter cms : "; cin >> cms; cr.add_target(tr,cms, stud); cout << "\n<-----------added successfullu---------->\n"; break; case 4: cout << "\n enter student cms : "; cin >> tr; cr.delete_node(tr); cout << "\n<-----------deleted successfullu---------->\n"; break; case 5: cr.print(); break; } } while (c < 6); }
[ "63450457+Ali-1999@users.noreply.github.com" ]
63450457+Ali-1999@users.noreply.github.com
843f87d78196725d6dd3de96a522bc5821117317
134261434927aecde7f78035afd1e2cfd27e4772
/Board.cpp
d38bff3d7a98401ab99f38ff54139deef074e834
[]
no_license
GalTurgeman/CPPEx6_Board
905d9d1dcb47e2aeb67a246b091629441e396911
3a2b4f112c819fc878a146e7728a5ae0b4aa6e59
refs/heads/master
2020-03-16T03:12:26.273790
2018-05-09T17:59:19
2018-05-09T17:59:19
132,482,576
0
0
null
null
null
null
UTF-8
C++
false
false
3,216
cpp
// // Created by Gal on 07/05/2018. // #include "Board.h" #include "MyException.h" /** * Default Constructor init all board to '.' */ Board::Board() { for (int i = 0; i <this->size ; i++) { board[i] = new MyChar[size]; } } /** * Constructor init by int; * @param s */ Board::Board(int s) { this->size = s; this->board = new MyChar *[size]; for (int i = 0; i < this->size; i++) { this->board[i] = new MyChar[size]; } for (int i = 0; i < this->size; i++) { for (int j = 0; j < this->size; j++) { this->board[i][j].setChar('.'); } } } /** * Copy Constructor perform deep copy. * @param Board */ Board::Board(const Board& b) { this->size = b.size; board = new MyChar*[size]; for (int i = 0; i <this->size ; i++) { board[i] = new MyChar[size]; } for (int i = 0; i <this->size ; i++) { for (int j = 0; j <this->size ; j++) { board[i][j] = b.board[i][j]; } } } /** * All board will fill with c. * @param char c * @return &Board */ Board &Board::operator=(char c) { if( c != 'X' && c != 'O' && c!= '.') { IllegalCharException ex(c); throw ex; } else{ for (int i = 0; i <this->size ; i++) { for (int j = 0; j <this->size ; j++) { this->board[i][j]=c; } } return *this; } } /** * All board will fill with other.c . * check if is the same board * check if need to create new board , than delete old one. * @param Board b * @return &Board */ Board &Board::operator=(const Board& other) { if(this == &other) return *this;//Same Board! if(size != other.size) { clean(*this); size = other.size; board = new MyChar*[size]; for (int i = 0; i <size ; i++) { board[i] = new MyChar[size]; } for (int i = 0; i < this->size; i++) { for (int j = 0; j < this->size; j++) { this->board[i][j] = MyChar{other.board[i][j].getChar()}; } } } return *this; } /** * Delete Board. * @param Board b */ void Board::clean(const Board& b){ for (int i = 0; i <b.size ; i++) { delete[] b.board[i]; } delete[]b.board; } /** * override '[]' * @param list l * @return &MyChar */ MyChar& Board::operator[](list<int> l) { if(l.front() >= this->size || l.back() >= this->size || l.back() < 0 || l.front() < 0){ IllegalCoordinateException ex(l.front(),l.back()); throw ex; } return board[l.front()][l.back()]; } /** * Check if all board equal to other board. * @param Board * @return boolean */ bool Board::operator==(const Board &l) const{ if(size != l.size) return false; else{ for (int i = 0; i <size; i++) { for (int j = 0; j <size ; j++) { if(board[i][j] != l.board[i][j]) return false; } } } return true; } /** * destructor * @param * */ Board::~Board() { // cout<<"destructor"<<endl; for (int i = 0; i < size; i++) { delete[] board[i]; } delete[](board); }
[ "user154@gmail.com" ]
user154@gmail.com
cf40a0ea43dff0aa457e64aecf2309df31bb25a6
7c4cf781d58dbbba073cf94e7b057dcd1dc294fb
/codes/c/visual_c_plus/MFC/FlowSwitch/FlowSwitch/FlowSwitch.cpp
cb30be0c8ecb9bd7c68892a7069116925dd7f290
[]
no_license
DoveMX/james_works
8d17986878d0e9d796d660bcca57188efbd1f0da
9635f0b23b02e93c42ab603aca0f9f1280f179bb
refs/heads/master
2020-04-05T10:55:42.447587
2019-03-21T23:13:20
2019-03-21T23:13:20
156,816,208
0
1
null
null
null
null
UTF-8
C++
false
false
5,099
cpp
// FlowSwitch.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include "FlowSwitch.h" // 引用工程文件 #include "CConfig.h" #define MAX_LOADSTRING 100 // 全局变量: HINSTANCE hInst; // 当前实例 WCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 WCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 // 此代码模块中包含的函数的前向声明: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: 在此处放置代码。 // 读取CConfig CConfig *cfg = new CConfig(); // TODO: 在此处放置代码 // 初始化全局字符串 LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_FLOWSWITCH, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化: if (!InitInstance (hInstance, nCmdShow)) { delete cfg; return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_FLOWSWITCH)); MSG msg; // 主消息循环: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } delete cfg; return (int) msg.wParam; } // // 函数: MyRegisterClass() // // 目标: 注册窗口类。 // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_FLOWSWITCH)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_FLOWSWITCH); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // 函数: InitInstance(HINSTANCE, int) // // 目标: 保存实例句柄并创建主窗口 // // 注释: // // 在此函数中,我们在全局变量中保存实例句柄并 // 创建和显示主程序窗口。 // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // 将实例句柄存储在全局变量中 HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // 函数: WndProc(HWND, UINT, WPARAM, LPARAM) // // 目标: 处理主窗口的消息。 // // WM_COMMAND - 处理应用程序菜单 // WM_PAINT - 绘制主窗口 // WM_DESTROY - 发送退出消息并返回 // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_COMMAND: { int wmId = LOWORD(wParam); // 分析菜单选择: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: 在此处添加使用 hdc 的任何绘图代码... HBRUSH hbrush = ::CreateSolidBrush(RGB(0, 0, 255)); ::SelectObject(hdc, hbrush); ::Ellipse(hdc, ps.rcPaint.left, ps.rcPaint.top, ps.rcPaint.right, ps.rcPaint.bottom); ::DeleteObject(hbrush); EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // “关于”框的消息处理程序。 INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "Jane@gmagon.com" ]
Jane@gmagon.com
f54977d2433c871d456e73a7c5d6743175d2f44f
6b40e9cba1dd06cd31a289adff90e9ea622387ac
/Develop/Server/GameServer/unittest/MockDBTask.h
7f3d90cf77eb09d54bb028d3cc2682c0b17246c0
[]
no_license
AmesianX/SHZPublicDev
c70a84f9170438256bc9b2a4d397d22c9c0e1fb9
0f53e3b94a34cef1bc32a06c80730b0d8afaef7d
refs/heads/master
2022-02-09T07:34:44.339038
2014-06-09T09:20:04
2014-06-09T09:20:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
405
h
#pragma once #include "GDBAsyncTask.h" class MockDBTask : public GDBAsyncTask { public : MockDBTask(const MUID& uidReqPlayer) : GDBAsyncTask(uidReqPlayer, SDBT_DBTYPE_NONE, SDBTID_NONE) {} void OnExecute(mdb::MDatabase& rfDB) {} mdb::MDB_THRTASK_RESULT _OnCompleted() { return mdb::MDBTR_SUCESS; } using GDBAsyncTask::IncreaseRefCount; using GDBAsyncTask::DecreaseRefCount; };
[ "shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4" ]
shzdev@8fd9ef21-cdc5-48af-8625-ea2f38c673c4
f8dc5469dfbbddf5e627d033ce075eb2af8e3aac
ed470637412a01b6d29f44dbf7461c2698d19e0c
/many_bone_ik/src/math/qcp.h
881bb5a4d1fd616097db90115874fb9577ac3a25
[ "MIT" ]
permissive
V-Sekai/godot-modules-groups
51df9b5feb2320856cb88ddee5bb18152b6e5aca
7c0096edf39eb71f86ec8ddaa30e22591c515f8d
refs/heads/main
2023-04-22T17:50:43.323793
2023-04-22T17:49:28
2023-04-22T17:49:28
302,478,554
4
0
null
null
null
null
UTF-8
C++
false
false
8,193
h
/**************************************************************************/ /* qcp.h */ /**************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /**************************************************************************/ /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /**************************************************************************/ #ifndef QCP_H #define QCP_H #include "core/math/basis.h" #include "core/math/vector3.h" #include "core/variant/variant.h" /** * Implementation of the Quaternionf-Based Characteristic Polynomial algorithm * for RMSD and Superposition calculations. * <p> * Usage: * <p> * The input consists of 2 Vector3 arrays of equal length. The input * coordinates are not changed. * * <pre> * Vector3[] x = ... * Vector3[] y = ... * SuperPositionQCP qcp = new SuperPositionQCP(); * qcp.set(x, y); * </pre> * <p> * or with weighting factors [0 - 1]] * * <pre> * double[] weights = ... * qcp.set(x, y, weights); * </pre> * <p> * For maximum efficiency, create a SuperPositionQCP object once and reuse it. * <p> * A. Calculate rmsd only * * <pre> * double rmsd = qcp.getRmsd(); * </pre> * <p> * B. Calculate a 4x4 transformation (Quaternionation and translation) matrix * * <pre> * Matrix4f Quaterniontrans = qcp.getTransformationMatrix(); * </pre> * <p> * C. Get transformated points (y superposed onto the reference x) * * <pre> * Vector3[] ySuperposed = qcp.getTransformedCoordinates(); * </pre> * <p> * Citations: * <p> * Liu P, Agrafiotis DK, & Theobald DL (2011) Reply to comment on: "Fast * determination of the optimal Quaternionation matrix for macromolecular * superpositions." Journal of Computational Chemistry 32(1):185-186. * [http://dx.doi.org/10.1002/jcc.21606] * <p> * Liu P, Agrafiotis DK, & Theobald DL (2010) "Fast determination of the optimal * Quaternionation matrix for macromolecular superpositions." Journal of Computational * Chemistry 31(7):1561-1563. [http://dx.doi.org/10.1002/jcc.21439] * <p> * Douglas L Theobald (2005) "Rapid calculation of RMSDs using a * quaternion-based characteristic polynomial." Acta Crystallogr A * 61(4):478-480. [http://dx.doi.org/10.1107/S0108767305015266 ] * <p> * This is an adoption of the original C code QCPQuaternion 1.4 (2012, October 10) to * Java. The original C source code is available from * http://theobald.brandeis.edu/qcp/ and was developed by * <p> * Douglas L. Theobald Department of Biochemistry MS 009 Brandeis University 415 * South St Waltham, MA 02453 USA * <p> * dtheobald@brandeis.edu * <p> * Pu Liu Johnson & Johnson Pharmaceutical Research and Development, L.L.C. 665 * Stockton Drive Exton, PA 19341 USA * <p> * pliu24@its.jnj.com * <p> * * @author Douglas L. Theobald (original C code) * @author Pu Liu (original C code) * @author Peter Rose (adopted to Java) * @author Aleix Lafita (adopted to Java) * @author Eron Gjoni (adopted to EWB IK) */ class QCP { double evec_prec = static_cast<double>(1E-6); double eval_prec = static_cast<double>(1E-11); PackedVector3Array target; PackedVector3Array moved; Vector<real_t> weight; double w_sum = 0; Vector3 target_center; Vector3 moved_center; double e0 = 0; double rmsd = 0; double Sxy = 0, Sxz = 0, Syx = 0, Syz = 0, Szx = 0, Szy = 0; double SxxpSyy = 0, Szz = 0, mxEigenV = 0, SyzmSzy = 0, SxzmSzx = 0, SxymSyx = 0; double SxxmSyy = 0, SxypSyx = 0, SxzpSzx = 0; double Syy = 0, Sxx = 0, SyzpSzy = 0; bool rmsd_calculated = false; bool transformation_calculated = false; bool inner_product_calculated = false; /** * Calculates the RMSD value for superposition of y onto x. This requires the * coordinates to be precentered. * * @param x * 3f points of reference coordinate set * @param y * 3f points of coordinate set for superposition */ void calculate_rmsd(PackedVector3Array &x, PackedVector3Array &y); /** * Calculates the inner product between two coordinate sets x and y (optionally * weighted, if weights set through * {@link #set(Vector3[], Vector3[], double[])}). It also calculates an upper * bound of the most positive root of the key matrix. * http://theobald.brandeis.edu/qcp/qcpQuaternion.c * * @param coords1 * @param coords2 * @return */ void inner_product(PackedVector3Array &coords1, PackedVector3Array &coords2); void calculate_rmsd(double r_length); void set(PackedVector3Array &r_target, PackedVector3Array &r_moved); Quaternion calculate_rotation(); /** * Sets the two input coordinate arrays and weight array. All input arrays must * be of equal length. Input coordinates are not modified. * * @param fixed * 3f points of reference coordinate set * @param moved * 3f points of coordinate set for superposition * @param weight * a weight in the inclusive range [0,1] for each point */ void set(PackedVector3Array &p_moved, PackedVector3Array &p_target, Vector<real_t> &p_weight, bool p_translate); static void translate(Vector3 r_translate, PackedVector3Array &r_x); double get_rmsd(PackedVector3Array &r_fixed, PackedVector3Array &r_moved); Vector3 move_to_weighted_center(PackedVector3Array &r_to_center, Vector<real_t> &r_weight); public: /** * Constructor with option to set the precision values. * * @param evec_prec * required eigenvector precision * @param eval_prec * required eigenvalue precision */ QCP(double p_evec_prec, double p_eval_prec); /** * Return the RMSD of the superposition of input coordinate set y onto x. Note, * this is the faster way to calculate an RMSD without actually superposing the * two sets. The calculation is performed "lazy", meaning calculations are only * performed if necessary. * * @return root mean square deviation for superposition of y onto x */ double get_rmsd(); /** * Weighted superposition. * * @param moved * @param target * @param weight array of weights for each equivalent point position * @param translate translate * @return */ Quaternion weighted_superpose(PackedVector3Array &p_moved, PackedVector3Array &p_target, Vector<real_t> &p_weight, bool translate); Quaternion get_rotation(); Vector3 get_translation(); }; #endif // QCP_H
[ "ernest.lee@chibifire.com" ]
ernest.lee@chibifire.com
df814e7c3c166bc153cc93d47560240d0040bcde
e5c0b38c9cc0c0e6155c9d626e299c7b03affd1e
/trunk/Code/Engine/GUI/GUIManager.cpp
d14872c8bd87206a2d626289c5c4bb6470061f9d
[]
no_license
BGCX261/zombigame-svn-to-git
4e5ec3ade52da3937e2b7d395424c40939657743
aa9fb16789f1721557085deae123771f5aefc4dd
refs/heads/master
2020-05-26T21:56:40.088036
2015-08-25T15:33:27
2015-08-25T15:33:27
41,597,035
0
0
null
null
null
null
ISO-8859-1
C++
false
false
31,672
cpp
#include "GUIManager.h" #include "Core.h" #include "Base.h" #include "InputManager.h" #include "RenderManager.h" #include "Logger/Logger.h" #include "GUIWindow.h" #include "xml/XMLTreeNode.h" #include "Texture/TextureManager.h" #include "ScriptManager.h" //--Includes GuiElements--- #include "Exceptions/Exception.h" #include "TextBox.h" #include "PointerMouse.h" #include "Button.h" #include "CheckButton.h" #include "DialogBox.h" #include "EditableTextBox.h" #include "Image.h" #include "TextBox.h" #include "ProgressBar.h" #include "RadioBox.h" #include "Slider.h" #include "Statictext.h" //------------------------- //---------------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------------- CGUIManager::CGUIManager(const Vect2i& resolution) : m_sCurrentWindows("Main.xml") , m_TextBox(NULL) , m_PointerMouse(NULL) , m_bRenderError(false) , m_bUpdateError(false) , m_ScreenResolution(resolution) , m_bIsOk(false) , m_bLoadedGuiFiles(false) , m_sLastLoadpathGUI_XML("") , m_bFirstUpdate(true) , m_bVisiblePointerMouse(true) { int jorls = 0; } //---------------------------------------------------------------------------- // Finalize data //---------------------------------------------------------------------------- void CGUIManager::Done () { if (IsOk()) { Release(); m_bIsOk = false; } } //---------------------------------------------------------------------------- // Free memory //---------------------------------------------------------------------------- void CGUIManager::Release () { LOGGER->AddNewLog(ELL_INFORMATION, "GUIManager:: shutting down GUI"); std::map<std::string, CGUIWindow*>::iterator it; std::map<std::string, CGUIWindow*>::iterator itEnd(m_WindowsMap.end()); for( it = m_WindowsMap.begin(); it != itEnd; ++it) { CGUIWindow* windows = it->second; CHECKED_DELETE(windows); } m_WindowsMap.clear(); CHECKED_DELETE(m_TextBox); CHECKED_DELETE(m_PointerMouse); LOGGER->AddNewLog(ELL_INFORMATION, "GUIManager:: offline (ok)"); } //---------------------------------------------------------------------------- // Init //---------------------------------------------------------------------------- bool CGUIManager::Init (const std::string& initGuiXML) { m_bIsOk = false; LOGGER->AddNewLog(ELL_INFORMATION, "CGUIManager:: calling initialization"); CXMLTreeNode parser; if (!parser.LoadFile(initGuiXML.c_str())) { std::string msg_error = "CGUIManager::Init-> Error al leer el archivo de configuracion GUI: " + initGuiXML; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); throw CException(__FILE__, __LINE__, msg_error); } else { CTextureManager* textureM = CORE->GetTextureManager(); CXMLTreeNode m = parser["GuiFiles"]; if (m.Exists()) { std::string path = m.GetPszProperty("path",""); if (path.compare("") != 0) m_bIsOk = LoadGuiFiles(path); else { m_bIsOk = true; } } else { std::string msg_error = "CGUIManager::Init-> Error al intentar leer el tag <GuiFiles> del archivo de configuracion GUI: " + initGuiXML; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); throw CException(__FILE__, __LINE__, msg_error); } if (m_bIsOk) { m = parser["TextBox"]; if (m.Exists()) { float posx = m.GetFloatProperty("posx", 30.f); float posy = m.GetFloatProperty("posy", 30.f); float w = m.GetFloatProperty("width", 35.f); float h = m.GetFloatProperty("height", 35.f); float button_w = m.GetFloatProperty("button_width", 5.f); float button_h = m.GetFloatProperty("button_height", 5.f); std::string buttonClose_normal = m.GetPszProperty("buttonClose_normal", "./Data/GUI/Textures_Test/CloseDialegBox.jpg"); std::string buttonClose_over = m.GetPszProperty("buttonClose_over", "./Data/GUI/Textures_Test/CloseDialegBoxO.jpg"); std::string buttonClose_clicked = m.GetPszProperty("buttonClose_clicked", "./Data/GUI/Textures_Test/CloseDialegBoxC.jpg"); std::string buttonClose_deactivated = m.GetPszProperty("buttonClose_deactivated", "./Data/GUI/Textures_Test/CloseDialegBoxC.jpg" ); std::string buttonMove_normal = m.GetPszProperty("buttonMove_normal", "./Data/GUI/Textures_Test/ButtonDialegBoxN.jpg"); std::string buttonMove_over = m.GetPszProperty("buttonMove_over", "./Data/GUI/Textures_Test/ButtonDialegBoxO.jpg"); std::string buttonMove_clicked = m.GetPszProperty("buttonMove_clicked", "./Data/GUI/Textures_Test/ButtonDialegBoxC.jpg"); std::string buttonMove_deactivated = m.GetPszProperty("buttonMove_deactivated", "./Data/GUI/Textures_Test/ButtonDialegBoxC.jpg"); std::string quad = m.GetPszProperty("quad", "./Data/GUI/Textures_Test/BaseDialegBox.jpg"); CTexture* Close_normal = textureM->GetTexture(buttonClose_normal); CTexture* Close_over = textureM->GetTexture(buttonClose_over); CTexture* Close_clicked = textureM->GetTexture(buttonClose_clicked); CTexture* Close_deactivated = textureM->GetTexture(buttonClose_deactivated); CTexture* Move_normal = textureM->GetTexture(buttonMove_normal); CTexture* Move_over = textureM->GetTexture(buttonMove_over); CTexture* Move_clicked = textureM->GetTexture(buttonMove_clicked); CTexture* Move_deactivated = textureM->GetTexture(buttonMove_deactivated); CTexture* back = textureM->GetTexture(quad); m_TextBox = new CTextBox( m_ScreenResolution.x, m_ScreenResolution.y, h, w, Vect2f(posx,posy), button_w, button_h); assert(m_TextBox); m_TextBox->SetName("TextBox"); m_TextBox->SetCloseButtonTextures(Close_normal, Close_over, Close_clicked, Close_deactivated); m_TextBox->SetMoveButtonTextures(Move_normal, Move_over, Move_clicked, Move_deactivated); m_TextBox->SetDialogTexture(back); m_TextBox->SetVisible(false); } else { std::string msg_error = "CGUIManager::Init-> Error al intentar leer el tag <TextBox> del archivo de configuracion GUI: " + initGuiXML; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); throw CException(__FILE__, __LINE__, msg_error); } m = parser["PointerMouse"]; if (m.Exists()) { float posx = m.GetFloatProperty("posx", 5.f); float posy = m.GetFloatProperty("posy", 5.f); float w = m.GetFloatProperty("width", 5.f); float h = m.GetFloatProperty("height", 5.f); std::string texture = m.GetPszProperty("texture", "./Data/GUI/Textures_Test/gui_pointer_mouse.tga"); bool isQuadrant = m.GetBoolProperty("isQuadrant", true); CTexture* texture_pointer = textureM->GetTexture(texture); m_PointerMouse = new CPointerMouse(m_ScreenResolution.y,m_ScreenResolution.x, h,w,Vect2f(posx,posy)); assert(m_PointerMouse); m_PointerMouse->SetTexture(texture_pointer,"default"); m_PointerMouse->SetActiveTexture("default"); m_PointerMouse->SetQuadrant(isQuadrant); } else { std::string msg_error = "CGUIManager::Init-> Error al intentar leer el tag <PointerMouse> del archivo de configuracion GUI: " + initGuiXML; LOGGER->AddNewLog(ELL_ERROR, msg_error.c_str()); throw CException(__FILE__, __LINE__, msg_error); } m_bIsOk = m_TextBox && m_PointerMouse; }//END if (m_bIsOk) } //END if (!parser.LoadFile(initGuiXML.c_str())) if (!m_bIsOk) { Release(); } else { LOGGER->AddNewLog(ELL_INFORMATION, "CSoundManager:: online (ok)"); } return m_bIsOk; } //---------------------------------------------------------------------------- // Render //---------------------------------------------------------------------------- void CGUIManager::Render (CRenderManager *renderManager, CFontManager* fm) { if (m_bIsOk) { CORE->GetRenderManager()->EnableAlphaBlend(); if (m_bLoadedGuiFiles) { std::map<std::string, CGUIWindow*>::iterator it; it = m_WindowsMap.find( m_sCurrentWindows ); if( it != m_WindowsMap.end() ) { CGUIWindow * currentWindows = it->second; currentWindows->Render(renderManager, fm); RenderTransitionEffect(renderManager); m_bRenderError = false; } else { if (!m_bRenderError) { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: Se ha intentado pintar la windows %s no registrada ", m_sCurrentWindows.c_str()); m_bRenderError = true; } } }//END if (m_bLoadedGuiFiles) //Siempre los últimos en pintarse assert(m_TextBox); m_TextBox->Render(renderManager, fm); RenderPointerMouse(renderManager, fm); CORE->GetRenderManager()->DisableAlphaBlend(); }//END if (m_bIsOk) } void CGUIManager::RenderPointerMouse (CRenderManager *renderManager, CFontManager* fontManager) { if(m_bVisiblePointerMouse) m_PointerMouse->Render(renderManager, fontManager); } //---------------------------------------------------------------------------- // Update //---------------------------------------------------------------------------- void CGUIManager::Update (float elapsedTime) { if (m_bIsOk) { assert(m_TextBox); assert(m_PointerMouse); //Si es la primera vez que actualizamos la GUI debemos hacer un load de la main.xml: if (m_bFirstUpdate) { std::map<std::string, CGUIWindow*>::iterator itCurrentWindows; itCurrentWindows = m_WindowsMap.find( m_sCurrentWindows ); if( itCurrentWindows != m_WindowsMap.end() ) { CGUIWindow * currentWindow = itCurrentWindows->second; currentWindow->LoadWindows(); } m_bFirstUpdate = false; } CInputManager* intputManager = CORE->GetInputManager(); m_PointerMouse->Update(intputManager, elapsedTime); m_TextBox->Update(intputManager, elapsedTime); if( !m_TextBox->IsVisible() && m_bLoadedGuiFiles) { std::map<std::string, CGUIWindow*>::iterator it; it = m_WindowsMap.find( m_sCurrentWindows ); if( it != m_WindowsMap.end() ) { CGUIWindow * currentWindow = it->second; if (!UpdateTransitionEffect(elapsedTime)) { currentWindow->Update(intputManager, elapsedTime); } m_bUpdateError = false; } else { if (!m_bUpdateError) { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: Se ha intentado updatear la windows %s no registrada ", m_sCurrentWindows.c_str()); m_bUpdateError = true; } } }//END if( !m_TextBox.IsVisible() ) } } void CGUIManager::RenderTransitionEffect(CRenderManager *renderManager) { if (m_sTransitionEffect.m_bDoEffect) { switch (m_sTransitionEffect.m_eType) { case TE_SHADOW: { //Dibujamos un quad2d en toda la pantalla: // - Durante la primera mitad de tiempo irá de totalmente transparente a totalmente opaco negro // - Durante la segunda mitad de tiempo irá de totalmente opaco negro a totalmente transparente CColor color = colBLACK; float alpha; if (m_sTransitionEffect.m_fTimeCounter < m_sTransitionEffect.m_fTransitionTime*0.5f) { //Durante la primera mitad del tiempo: alpha de 0.f -> 1.f alpha = m_sTransitionEffect.m_fTimeCounter / (m_sTransitionEffect.m_fTransitionTime*0.5f); color.SetAlpha(alpha); } else { //Durante la segunda mitad del tiempo: alpha de 1.f -> 0.f alpha = m_sTransitionEffect.m_fTimeCounter / (m_sTransitionEffect.m_fTransitionTime*0.5f); //esto va de 1->2 color.SetAlpha(abs(alpha-2)); } renderManager->DrawQuad2D(Vect2i(0,0),m_ScreenResolution.x,m_ScreenResolution.y,CRenderManager::UPPER_LEFT,color); } break; case TE_FADE_TO_BLACK: { //Dibujamos un quad2d en toda la pantalla: // - Irá de totalmente transparente a totalmente opaco negro CColor color = colBLACK; if (m_sTransitionEffect.m_fTimeCounter < m_sTransitionEffect.m_fTransitionTime) { // alpha de 0.f -> 1.f float alpha = m_sTransitionEffect.m_fTimeCounter / m_sTransitionEffect.m_fTransitionTime; color.SetAlpha(alpha); } else { color.SetAlpha(0.f); } renderManager->DrawQuad2D(Vect2i(0,0),m_ScreenResolution.x,m_ScreenResolution.y,CRenderManager::UPPER_LEFT,color); } break; case TE_SHADOW_OFF: { //Dibujamos un quad2d en toda la pantalla: // - Irá de totalmente opaco negro a totalmente transparente CColor color = colBLACK; if (m_sTransitionEffect.m_fTimeCounter < m_sTransitionEffect.m_fTransitionTime) { // alpha de 1.f -> 0.f float alpha = m_sTransitionEffect.m_fTimeCounter / m_sTransitionEffect.m_fTransitionTime; color.SetAlpha(abs(alpha - 1)); } renderManager->DrawQuad2D(Vect2i(0,0),m_ScreenResolution.x,m_ScreenResolution.y,CRenderManager::UPPER_LEFT,color); } break; default: { LOGGER->AddNewLog(ELL_ERROR,"CGUIManager::RenderTransitionEffect-> No se reconoce el efecto a realizar!"); } } } } bool CGUIManager::UpdateTransitionEffect (float elapsedTime) { if (m_sTransitionEffect.m_bDoEffect) { m_sTransitionEffect.m_fTimeCounter += elapsedTime; switch (m_sTransitionEffect.m_eType) { case TE_SHADOW: { if (!m_sTransitionEffect.m_bActiveWindows && m_sTransitionEffect.m_fTimeCounter > m_sTransitionEffect.m_fTransitionTime*0.5f) { ActiveWindows(m_sTransitionEffect.m_sWindowsName); m_sTransitionEffect.m_bActiveWindows = true; } if (m_sTransitionEffect.m_fTimeCounter > m_sTransitionEffect.m_fTransitionTime) { m_sTransitionEffect.m_bDoEffect = false; m_sTransitionEffect.m_fTimeCounter = 0.f; m_sTransitionEffect.m_bActiveWindows = false; } } break; case TE_FADE_TO_BLACK: { if (m_sTransitionEffect.m_fTimeCounter >= m_sTransitionEffect.m_fTransitionTime) { ActiveWindows(m_sTransitionEffect.m_sWindowsName); m_sTransitionEffect.m_bDoEffect = false; m_sTransitionEffect.m_fTimeCounter = 0.f; m_sTransitionEffect.m_bActiveWindows = true; } } break; case TE_SHADOW_OFF: { if (!m_sTransitionEffect.m_bActiveWindows) { ActiveWindows(m_sTransitionEffect.m_sWindowsName); m_sTransitionEffect.m_bActiveWindows = true; } if (m_sTransitionEffect.m_fTimeCounter >= m_sTransitionEffect.m_fTransitionTime) { //ActiveWindows(m_sTransitionEffect.m_sWindowsName); m_sTransitionEffect.m_bDoEffect = false; m_sTransitionEffect.m_fTimeCounter = 0.f; //m_sTransitionEffect.m_bActiveWindows = true; } } break; } return true; } return false; } void CGUIManager::ActiveWindowsWithEffect (const std::string& inNameWindow, EtypeTransitionEffect type, float transitionTime ) { m_sTransitionEffect.m_bActiveWindows = false; m_sTransitionEffect.m_bDoEffect = true; m_sTransitionEffect.m_eType = type; m_sTransitionEffect.m_fTransitionTime = transitionTime; m_sTransitionEffect.m_fTimeCounter = 0.f; m_sTransitionEffect.m_sWindowsName = inNameWindow; } void CGUIManager::ActiveWindows( const std::string& inNameWindow ) { std::map<std::string, CGUIWindow*>::iterator it; it = m_WindowsMap.find( inNameWindow ); if( it != m_WindowsMap.end() ) { //Primero finalizamos la ventana actual std::map<std::string, CGUIWindow*>::iterator itCurrentWindows; itCurrentWindows = m_WindowsMap.find( m_sCurrentWindows ); if( itCurrentWindows != m_WindowsMap.end() ) { CGUIWindow * currentWindow = itCurrentWindows->second; currentWindow->SaveWindows(); //A continuación leemos los valores de la nueva ventana CGUIWindow* windows = it->second; windows->LoadWindows(); m_sCurrentWindows = inNameWindow; } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: Al intentar cambiar de windows, la actual-->%s no se ha encontrado registrada", m_sCurrentWindows.c_str()); } } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: Al intentar cambiar a la windows-->%s esta no se ha encontrado registrada", inNameWindow.c_str()); } } void CGUIManager::PushWindows (const std::string& inNameWindow ) { std::map<std::string, CGUIWindow*>::iterator it; it = m_WindowsMap.find( inNameWindow ); if( it != m_WindowsMap.end() ) { m_PrevWindows.push_back(m_sCurrentWindows); ActiveWindows(inNameWindow); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager::PushWindows Al intentar cambiar a la windows-->%s etsa no se ha encontrado registrada", inNameWindow.c_str()); } } void CGUIManager::PopWindows () { if (m_PrevWindows.size() == 0) { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager::PopWindows -> El vector de PrevWindows esta vacío!"); } else { std::string popWindows = m_PrevWindows[m_PrevWindows.size()-1]; m_PrevWindows.pop_back(); ActiveWindows(popWindows); } } void CGUIManager::SetScreenResolution(const Vect2i& resolution) { std::map<std::string, CGuiElement*>::iterator it(m_ElementsMap.begin()); std::map<std::string, CGuiElement*>::iterator itEnd(m_ElementsMap.end()); while (it != itEnd) { CGuiElement* guiElement = it->second; guiElement->SetWindowsWidth(resolution.x); guiElement->SetWindowsHeight(resolution.y); it++; } } bool CGUIManager::LoadGuiFiles (const std::string& pathGUI_XML) { m_bLoadedGuiFiles = false; LOGGER->AddNewLog(ELL_INFORMATION, "GUIManager:: Empezando a leer los .xml del directorio->%s",pathGUI_XML.c_str()); //Read xml files: std::map<std::string, CGUIWindow*>::iterator it(m_WindowsMap.begin()); std::map<std::string, CGUIWindow*>::iterator itEnd(m_WindowsMap.end()); while (it != itEnd) { CGUIWindow* windows = it->second; CHECKED_DELETE(windows); ++it; } m_WindowsMap.clear(); m_ElementsMap.clear(); m_sCurrentWindows = "Main.xml"; WIN32_FIND_DATA FindFileData; HANDLE hFind; // We read the XmlGui files m_sLastLoadpathGUI_XML = pathGUI_XML; std::string path_xmls = pathGUI_XML+"/*.xml"; hFind = FindFirstFile(path_xmls.c_str(), &FindFileData); // we check the existence of the XmlGui directory if ( hFind == INVALID_HANDLE_VALUE ) { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: Error al intentar leer los .xml del directorio %s", pathGUI_XML.c_str()); return false; } else { std::string FileName = FindFileData.cFileName; CGUIWindow* windows = new CGUIWindow(); std::string pathFile = pathGUI_XML+"/"; pathFile += FileName; bool isOk = false; isOk = windows->LoadXML(pathFile,m_ScreenResolution); if (!isOk) { return false; } windows->RegisterElements(m_ElementsMap); windows->SetName(FileName); m_WindowsMap.insert( std::pair<std::string,CGUIWindow*>(FileName,windows) ); while( FindNextFile(hFind, &FindFileData) != 0 ) { std::string FileName = FindFileData.cFileName; CGUIWindow* windows = new CGUIWindow(); std::string pathFile = pathGUI_XML+"/"; pathFile += FileName; isOk = windows->LoadXML(pathFile,m_ScreenResolution); if (!isOk) { return false; } windows->RegisterElements(m_ElementsMap); windows->SetName(FileName); m_WindowsMap.insert( std::pair<std::string,CGUIWindow*>(FileName,windows) ); } FindClose(hFind); } m_bLoadedGuiFiles = true; return true; } bool CGUIManager::ReloadGuiFiles () { bool isOk = false; std::string windows = m_sCurrentWindows; isOk = LoadGuiFiles(m_sLastLoadpathGUI_XML); std::map<std::string, CGUIWindow*>::iterator it; it = m_WindowsMap.find( windows ); if (it != m_WindowsMap.end()) { m_sCurrentWindows = windows; } return isOk; } void CGUIManager::SetMessageBox( const std::string& text ) { if (m_bIsOk) { assert(m_TextBox); if( !m_TextBox->IsVisible() ) { m_TextBox->SetMessage( text ); m_TextBox->SetVisible( true ); m_TextBox->SetActive( true ); m_TextBox->SetPosition(Vect2i(30,30)); } } } //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Funciones para modificar los GuiElements //------------------------------------------------------------------------- //------------------------------------------------------------------------- void CGUIManager::SetActiveGuiElement (const std::string& inNameGuiElement, bool flag) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameGuiElement); if( it!= m_ElementsMap.end() ) { it->second->SetActive(flag); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetActiveGuiElement", inNameGuiElement.c_str()); } } bool CGUIManager::GetVisibleGuiElement (const std::string& inNameGuiElement) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameGuiElement); if( it!= m_ElementsMap.end() ) { return it->second->IsVisible(); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetVisibleGuiElement", inNameGuiElement.c_str()); } return false; } void CGUIManager::SetVisibleGuiElement (const std::string& inNameGuiElement, bool flag) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameGuiElement); if( it!= m_ElementsMap.end() ) { it->second->SetVisible(flag); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetVisibleGuiElement", inNameGuiElement.c_str()); } } bool CGUIManager::GetProgressBarValue (const std::string& inNameGuiElement, float& outValue) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameGuiElement); if( it!= m_ElementsMap.end() ) { CProgressBar * progress = (CProgressBar*) (it->second); outValue = progress->GetProgress(); return true; } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetProgressBarValue", inNameGuiElement.c_str()); } return false; } bool CGUIManager::SetProgressBarValue (const std::string& inNameGuiElement, float inValue) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameGuiElement); if( it!= m_ElementsMap.end() ) { CProgressBar * progress = (CProgressBar*) (it->second); progress->SetProgress(inValue); return true; } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetProgressBarValue", inNameGuiElement.c_str()); } return false; } std::string CGUIManager::GetButtonCheckInRadioBox (const std::string& inNameRadioBox) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameRadioBox); if( it!= m_ElementsMap.end() ) { CRadioBox * rb = (CRadioBox*) (it->second); return rb->GetDefaultCheckButton(); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetButtonCheckInRadioBox", inNameRadioBox.c_str()); } return ""; } void CGUIManager::SetButtonCheckInRadioBox( const std::string& inNameRadioBox, const std::string& button ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameRadioBox); if( it!= m_ElementsMap.end() ) { CRadioBox * rb = (CRadioBox*) (it->second); rb->SetDefaultCheckButton(button); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetButtonCheckInRadioBox", inNameRadioBox.c_str()); } } void CGUIManager::SetStateCheckButton ( const std::string& inCheckButtonName, bool state ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inCheckButtonName); if( it!= m_ElementsMap.end() ) { CCheckButton * checkButton = (CCheckButton*) (it->second); checkButton->SetOn(state); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetStateCheckButton", inCheckButtonName.c_str()); } } bool CGUIManager::GetStateCheckButton( const std::string& inCheckButtonName ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inCheckButtonName); if( it!= m_ElementsMap.end() ) { CCheckButton * checkButton = (CCheckButton*) (it->second); return checkButton->GetState(); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetStateCheckButton", inCheckButtonName.c_str()); } return false; } void CGUIManager::SetEditableTextBox( const std::string& inEditableText, const std::string& text ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inEditableText); if( it!= m_ElementsMap.end() ) { CEditableTextBox * editableTextBox = (CEditableTextBox*) (it->second); editableTextBox->SetBuffer(text); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetEditableTextBox", inEditableText.c_str()); } } std::string CGUIManager::GetEditableTextBox( const std::string& inEditableText ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inEditableText); if( it!= m_ElementsMap.end() ) { CEditableTextBox * editableTextBox = (CEditableTextBox*) (it->second); return editableTextBox->GetBuffer(); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetEditableTextBox", inEditableText.c_str()); } return ""; } void CGUIManager::SetImage( const std::string& inImageName, const std::string& activeImage ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inImageName); if( it!= m_ElementsMap.end() ) { CImage * image = (CImage*) (it->second); image->SetActiveTexture(activeImage); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetImage", inImageName.c_str()); } } std::string CGUIManager::GetImage( const std::string& inImageName ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inImageName); if( it!= m_ElementsMap.end() ) { CImage * image = (CImage*) (it->second); return image->GetActiveTexture(); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetImage", inImageName.c_str()); } return ""; } void CGUIManager::PlayImage (const std::string& inImageName, float timePerImage, bool loop) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inImageName); if( it!= m_ElementsMap.end() ) { CImage * image = (CImage*) (it->second); image->PlayAnimation(timePerImage, loop); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetImage", inImageName.c_str()); } } void CGUIManager::SetAlphaImage(const std::string& inImageName, float _Alpha) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inImageName); if( it!= m_ElementsMap.end() ) { CImage * image = (CImage*) (it->second); image->SetAlpha(_Alpha); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager::GetGUIElement: No se ha encontrado el guiElement %s", inImageName.c_str()); } } void CGUIManager::FadeOutImage(const std::string& inImageName, float startTime, float fadePerSecond) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inImageName); if( it!= m_ElementsMap.end() ) { CImage * image = (CImage*) (it->second); image->FadeOut(startTime, fadePerSecond); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager::GetGUIElement: No se ha encontrado el guiElement %s", inImageName.c_str()); } } void CGUIManager::SetStateSlider( const std::string& inSliderName, float amount ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inSliderName); if( it!= m_ElementsMap.end() ) { CSlider * slider= (CSlider*) (it->second); slider->SetValue(amount); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetStateSlider", inSliderName.c_str()); } } float CGUIManager::GetStateSlider( const std::string& inSliderName ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inSliderName); if( it!= m_ElementsMap.end() ) { CSlider * slider= (CSlider*) (it->second); float kk=slider->GetValue(); return slider->GetValue(); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion GetStateSlider", inSliderName.c_str()); } return 0.f; } void CGUIManager::SetLiteralInStaticText( const std::string& inStaticText, const std::string& lit ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inStaticText); if( it!= m_ElementsMap.end() ) { CStaticText * st = (CStaticText*) (it->second); st->SetLiteral(lit); } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion SetVariableText", inStaticText.c_str()); } } bool CGUIManager::NextBlockInRadioBox( const std::string& inNameRadioBox ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameRadioBox); if( it!= m_ElementsMap.end() ) { CRadioBox * rb = (CRadioBox*) (it->second); rb->NextBlock(); return true; } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion NextBlockInRadioBox", inNameRadioBox.c_str()); } return false; } bool CGUIManager::PrevBlockInRadioBox( const std::string& inNameRadioBox ) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameRadioBox); if( it!= m_ElementsMap.end() ) { CRadioBox * rb = (CRadioBox*) (it->second); rb->PrevBlock(); return true; } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager:: No se ha encontrado el guiElement %s al ejecutar la funcion PrevBlockInRadioBox", inNameRadioBox.c_str()); } return false; } //------------------------------------------------------------------------- //------------------------------------------------------------------------- CGuiElement* CGUIManager::GetGUIElement(const std::string& inNameGuiElement) { std::map<std::string, CGuiElement*>::iterator it; it = m_ElementsMap.find(inNameGuiElement); if( it!= m_ElementsMap.end() ) { return it->second; } else { LOGGER->AddNewLog(ELL_ERROR, "CGUIManager::GetGUIElement: No se ha encontrado el guiElement %s", inNameGuiElement.c_str()); } return NULL; }
[ "you@example.com" ]
you@example.com
55f935dca4033b8f155eae016a9080ef43ae7c47
a1b4702c9b2a48300b8b4c5f44b3e77467471c0f
/jni/tcp_transmittion/ISocketListener.h
4fb18b03b65079d31d0ada808a169d200fec3c52
[]
no_license
studyNowHa/ball
38a12395b8c324390974e1bcc8db2edbd71fd600
14f2f9a5cb44d8c592d2062a6bda2f57c213d87c
refs/heads/master
2020-03-26T12:59:55.473703
2018-08-16T00:52:47
2018-08-16T00:54:00
144,917,942
0
0
null
null
null
null
UTF-8
C++
false
false
267
h
#ifndef ISCK_LISTENER #define ISCK_LISTENER class ISocketListener { public: virtual ~ISocketListener() { }; virtual void notify(std::string msg) = 0; }; class iiSocketListener : public ISocketListener { public: virtual void notify(std::string msg); }; #endif
[ "903058621@qq.com" ]
903058621@qq.com
36f7e40401dc69ab12ed7d54512e5c084f5aba27
df7183168307670df562970687ec0f98d3424862
/Graphs/BFS.cpp
a8a4b7cd4818128083cce18904cd5ca80100a35e
[]
no_license
iSumitYadav/DS-Algo
cf816669c1468c1b6bc1e37f36114b944c6e71c2
453b5723269690b0e765ae510e392d667df45e3f
refs/heads/master
2021-09-03T17:36:22.384809
2018-01-10T18:55:02
2018-01-10T18:55:02
113,206,635
1
0
null
null
null
null
UTF-8
C++
false
false
1,184
cpp
#include<bits/stdc++.h> using namespace std; class Graph{ int nodes; list<int> *adj_list; public: Graph(int nodes){ this->nodes = nodes; adj_list = new list<int>[nodes]; } void addEdge(int a, int b){ adj_list[a].push_back(b); } void breadthFirstSearch(int src); }; void Graph::breadthFirstSearch(int src){ bool *visited = new bool[nodes]; memset(visited, false, sizeof(visited)); list<int> q; list<int>::iterator it; q.push_back(src); visited[src] = true; while(!q.empty()){ src = q.front(); printf("%d ", src); q.pop_front(); for(it=adj_list[src].begin(); it!=adj_list[src].end(); it++){ if(!visited[*it]){ q.push_back(*it); visited[*it] = true; } } } } int main(){ /* GRAPH 0---------1 || / || / || / __ || / | | 2---------3 \ / \ / \ / \ / 4 |_| */ Graph g(5); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 4); g.addEdge(2, 3); g.addEdge(3, 3); g.addEdge(3, 4); g.addEdge(4, 4); printf("Breadth First Traversal: \n"); g.breadthFirstSearch(2); return 0; }
[ "sumityadavcools@gmail.com" ]
sumityadavcools@gmail.com
ac25538e9ca2e4e0874a9193e2a8b1ff4b43ed90
381d605da20ca3342687e26c5bd00936fe7a46e7
/Codechef/REARRAN-Rearrangement.cpp
5edea6316110e94b8f99cb998d81f7933f7999d5
[]
no_license
z0CoolCS/CompetitiveProgramming
4a4c278533001a0a4e8440ecfba9c7a4bb8132db
0894645c918f316c2ce6ddc5fd5fb20af6c8b071
refs/heads/master
2023-04-28T08:15:29.245592
2021-04-20T01:02:28
2021-04-20T01:02:28
228,505,384
0
0
null
null
null
null
UTF-8
C++
false
false
152
cpp
#include<bits/stdc++.h> using namespace std; #define REP(i,a,b) for(int i=a;i<b;i++) int main(){ int t; cin>>t; while(t--){ } return 0; }
[ "giordano.alvitez@utec.edu.pe" ]
giordano.alvitez@utec.edu.pe
23eb12c268f65b72118eeab0b03ff6e621b94c71
31865a003fa6401beec870ba7a5abb8adf3f83ff
/Libs/SurgeryNavigation/stkIGTLToMRMLPosition.cpp
0ad0b522a49f8bd2c0e8b9909058bcbba2153f2a
[ "BSD-3-Clause" ]
permissive
zpphigh/STK
fafe7060c0f046ccd0a1ff4fd45112fa69fde03d
97b94fbd761f82a68a5b709f0fdfb01f56f7b479
refs/heads/master
2021-01-18T16:17:21.008691
2013-11-05T17:37:41
2013-11-05T17:37:41
null
0
0
null
null
null
null
GB18030
C++
false
false
10,191
cpp
// OpenIGTLinkIF MRML includes #include "stkIGTLToMRMLPosition.h" // OpenIGTLink includes #include <igtlPositionMessage.h> #include <igtlWin32Header.h> #include <igtlMath.h> // MRML includes #include <vtkMRMLLinearTransformNode.h> #include <vtkMRMLModelNode.h> #include <vtkMRMLDisplayNode.h> #include <vtkMRMLModelDisplayNode.h> //#include "vtkMRMLProbeNode.h" // VTK includes #include <vtkIntArray.h> #include <vtkMatrix4x4.h> #include <vtkObjectFactory.h> #include <vtkAppendPolyData.h> #include <vtkCylinderSource.h> #include <vtkSphereSource.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> #include <vtkSTLReader.h> // VTKSYS includes #include <vtksys/SystemTools.hxx> //--------------------------------------------------------------------------- vtkStandardNewMacro(stkIGTLToMRMLPosition); vtkCxxRevisionMacro(stkIGTLToMRMLPosition, "$Revision: 15552 $"); //--------------------------------------------------------------------------- stkIGTLToMRMLPosition::stkIGTLToMRMLPosition() { } //--------------------------------------------------------------------------- stkIGTLToMRMLPosition::~stkIGTLToMRMLPosition() { } //--------------------------------------------------------------------------- void stkIGTLToMRMLPosition::PrintSelf(ostream& os, vtkIndent indent) { this->vtkObject::PrintSelf(os, indent); } //--------------------------------------------------------------------------- vtkMRMLNode* stkIGTLToMRMLPosition::CreateNewNode(vtkMRMLScene* scene, const char* name) { vtkMRMLLinearTransformNode* transformNode; transformNode = vtkMRMLLinearTransformNode::New(); transformNode->SetName(name); transformNode->SetDescription("Received by OpenIGTLink"); vtkMatrix4x4* transform = vtkMatrix4x4::New(); transform->Identity(); //transformNode->SetAndObserveImageData(transform); transformNode->ApplyTransformMatrix(transform); transform->Delete(); vtkMRMLNode* n = scene->AddNode(transformNode); this->SetVisibility(1,scene,transformNode); transformNode->Delete(); return n; } //--------------------------------------------------------------------------- vtkIntArray* stkIGTLToMRMLPosition::GetNodeEvents() { vtkIntArray* events; events = vtkIntArray::New(); events->InsertNextValue(vtkMRMLTransformableNode::TransformModifiedEvent); return events; } //--------------------------------------------------------------------------- int stkIGTLToMRMLPosition::IGTLToMRML(igtl::MessageBase::Pointer buffer, vtkMRMLNode* node) { stkIGTLToMRMLBase::IGTLToMRML(buffer, node); // Create a message buffer to receive transform data igtl::PositionMessage::Pointer positionMsg; positionMsg = igtl::PositionMessage::New(); positionMsg->Copy(buffer); // !! TODO: copy makes performance issue. // Deserialize the transform data // If CheckCRC==0, CRC check is skipped. int c = positionMsg->Unpack(this->CheckCRC); if (!(c & igtl::MessageHeader::UNPACK_BODY)) // if CRC check fails { // TODO: error handling return 0; } if (node == NULL) { return 0; } vtkMRMLLinearTransformNode* transformNode = vtkMRMLLinearTransformNode::SafeDownCast(node); float position[3]; float quaternion[4]; igtl::Matrix4x4 matrix; positionMsg->GetPosition(position); positionMsg->GetQuaternion(quaternion); igtl::QuaternionToMatrix(quaternion, matrix); vtkMatrix4x4* transformToParent = transformNode->GetMatrixTransformToParent(); int row, column; for (row = 0; row < 3; row++) { for (column = 0; column < 3; column++) { transformToParent->Element[row][column] = matrix[row][column]; } transformToParent->Element[row][3] = position[row]; } transformToParent->Element[3][0] = 0.0; transformToParent->Element[3][1] = 0.0; transformToParent->Element[3][2] = 0.0; transformToParent->Element[3][3] = 1.0; transformToParent->Modified(); return 1; } //--------------------------------------------------------------------------- int stkIGTLToMRMLPosition::MRMLToIGTL(unsigned long event, vtkMRMLNode* mrmlNode, int* size, void** igtlMsg) { if (mrmlNode && event == vtkMRMLTransformableNode::TransformModifiedEvent) { vtkMRMLLinearTransformNode* transformNode = vtkMRMLLinearTransformNode::SafeDownCast(mrmlNode); vtkMatrix4x4* matrix = transformNode->GetMatrixTransformToParent(); //igtl::PositionMessage::Pointer OutPositionMsg; if (this->OutPositionMsg.IsNull()) { this->OutPositionMsg = igtl::PositionMessage::New(); } this->OutPositionMsg->SetDeviceName(mrmlNode->GetName()); igtl::Matrix4x4 igtlmatrix; igtlmatrix[0][0] = matrix->Element[0][0]; igtlmatrix[1][0] = matrix->Element[1][0]; igtlmatrix[2][0] = matrix->Element[2][0]; igtlmatrix[3][0] = matrix->Element[3][0]; igtlmatrix[0][1] = matrix->Element[0][1]; igtlmatrix[1][1] = matrix->Element[1][1]; igtlmatrix[2][1] = matrix->Element[2][1]; igtlmatrix[3][1] = matrix->Element[3][1]; igtlmatrix[0][2] = matrix->Element[0][2]; igtlmatrix[1][2] = matrix->Element[1][2]; igtlmatrix[2][2] = matrix->Element[2][2]; igtlmatrix[3][2] = matrix->Element[3][2]; igtlmatrix[0][3] = matrix->Element[0][3]; igtlmatrix[1][3] = matrix->Element[1][3]; igtlmatrix[2][3] = matrix->Element[2][3]; igtlmatrix[3][3] = matrix->Element[3][3]; float position[3]; float quaternion[4]; position[0] = igtlmatrix[0][3]; position[1] = igtlmatrix[1][3]; position[2] = igtlmatrix[2][3]; igtl::MatrixToQuaternion(igtlmatrix, quaternion); //this->OutPositionMsg->SetMatrix(igtlmatrix); this->OutPositionMsg->SetPosition(position); this->OutPositionMsg->SetQuaternion(quaternion); this->OutPositionMsg->Pack(); *size = this->OutPositionMsg->GetPackSize(); *igtlMsg = (void*)this->OutPositionMsg->GetPackPointer(); return 1; } return 0; } //--------------------------------------------------------------------------- void stkIGTLToMRMLPosition::SetVisibility(int sw, vtkMRMLScene * scene, vtkMRMLNode * node) { vtkMRMLLinearTransformNode * tnode = vtkMRMLLinearTransformNode::SafeDownCast(node); if (!tnode || !scene) { // If the node is not a linear transform node, do nothing. return; } vtkMRMLModelNode* locatorModel = NULL; vtkMRMLDisplayNode* locatorDisp = NULL; const char * attr = tnode->GetAttribute("IGTLModelID"); if (!attr || !scene->GetNodeByID(attr)) // no locator has been created { if (sw) { std::stringstream ss; ss << "Locator_" << tnode->GetName(); locatorModel = AddLocatorModel(scene, ss.str().c_str(), 0.0, 1.0, 1.0); if (locatorModel) { tnode->SetAttribute("IGTLModelID", locatorModel->GetID()); scene->Modified(); locatorModel->SetAndObserveTransformNodeID(tnode->GetID()); locatorModel->InvokeEvent(vtkMRMLTransformableNode::TransformModifiedEvent); } } else { locatorModel = NULL; } } else { locatorModel = vtkMRMLModelNode::SafeDownCast(scene->GetNodeByID(attr)); } if (locatorModel) { locatorDisp = locatorModel->GetDisplayNode(); locatorDisp->SetVisibility(sw); locatorModel->Modified(); } } vtkMRMLModelNode* stkIGTLToMRMLPosition::AddLocatorModel(vtkMRMLScene * scene, const char* nodeName, double r, double g, double b) { vtkMRMLModelNode *locatorModel; vtkMRMLModelDisplayNode *locatorDisp; locatorModel = vtkMRMLModelNode::New(); locatorDisp = vtkMRMLModelDisplayNode::New(); // Cylinder represents the locator stick vtkCylinderSource *cylinder = vtkCylinderSource::New(); cylinder->SetRadius(1.5); cylinder->SetHeight(100); cylinder->SetCenter(0, 0, 0); cylinder->Update(); // Rotate cylinder char* str1 = "CalibrationTool"; char* str2 = "UltrasoundTool"; char* str3 = "SurgeryTool"; vtkTransformPolyDataFilter *tfilter = vtkTransformPolyDataFilter::New(); vtkTransform* trans = vtkTransform::New(); if(strstr(nodeName,str1) != NULL) //CalibrationTool { //trans->RotateZ(-90.0); //polaris,acession的坐标系 trans->RotateX(90.0); //aurora的坐标系 }else if(strstr(nodeName,str2) != NULL) //UltrasoundTool { trans->RotateZ(90.0); //aurora的坐标系 }else if(strstr(nodeName,str3) != NULL) //SurgeryTool { trans->RotateX(90.0); //aurora的坐标系 } trans->Translate(0.0, -50.0, 0.0); trans->Update(); tfilter->SetInput(cylinder->GetOutput()); tfilter->SetTransform(trans); tfilter->Update(); // Sphere represents the locator tip vtkSphereSource *sphere = vtkSphereSource::New(); sphere->SetRadius(3.0); sphere->SetCenter(0, 0, 0); sphere->Update(); vtkAppendPolyData *apd = vtkAppendPolyData::New(); apd->AddInput(sphere->GetOutput()); //apd->AddInput(cylinder->GetOutput()); apd->AddInput(tfilter->GetOutput()); //if( std::string(nodeName) == "Locator_CalibrationTool") //{ // vtkSTLReader* reader = vtkSTLReader::New(); // reader->SetFileName("C:/config/MicrowaveTool.stl"); // reader->Update(); // apd->AddInput(reader->GetOutput()); // reader->Delete(); //} //else if ( std::string(nodeName) == "Locator_MicrowaveTool") //{ // vtkSTLReader* reader = vtkSTLReader::New(); // reader->SetFileName("C:/config/MicrowaveTool.stl"); // reader->Update(); // apd->AddInput(reader->GetOutput()); // reader->Delete(); //} apd->Update(); locatorModel->SetAndObservePolyData(apd->GetOutput()); double color[3]; color[0] = r; color[1] = g; color[2] = b; // locatorDisp->SetPolyData(locatorModel->GetPolyData()); locatorDisp->SetColor(color); trans->Delete(); tfilter->Delete(); cylinder->Delete(); sphere->Delete(); apd->Delete(); scene->SaveStateForUndo(); scene->AddNode(locatorDisp); vtkMRMLNode* lm = scene->AddNode(locatorModel); locatorDisp->SetScene(scene); locatorModel->SetName(nodeName); locatorModel->SetScene(scene); locatorModel->SetAndObserveDisplayNodeID(locatorDisp->GetID()); locatorModel->SetHideFromEditors(0); locatorModel->Delete(); locatorDisp->Delete(); return vtkMRMLModelNode::SafeDownCast(lm); }
[ "wmzhai@gmail.com" ]
wmzhai@gmail.com
66a3f5cfbdfb6b168eee4be4dfdca8d4c2aacda0
9b104545333c86ff6bde962a6f47d691dcdd38ca
/LiczbyPierwsze.cpp
48057275e2b3f3c5398e655bdb452b0a13736fbb
[]
no_license
KrzysztofTab/Cpp
5413c832a0d2db96ba9275e31f4a2af132609381
52636c1071ff164ea164cf9d8a72f073a41e9476
refs/heads/master
2023-01-01T13:36:08.553538
2020-10-10T16:58:23
2020-10-10T16:58:23
297,703,765
0
0
null
null
null
null
UTF-8
C++
false
false
580
cpp
#include <iostream> using namespace std; int a,x=0; float m[10000]; int main() { cin>>a; for (int i=2; i<a; i++) { m[i-2]=a%i; //pakuje do szufladek reszty z dzielenia } for (int i=0; i<a-2;i++) { if (m[i]==0) //sprawdzam czy ktores dzielenie odbylo sie bez reszty x=x+1; //jesli tak to zwiekszam "x" o 1 } if (x>0) //jesli x>0 to znaczy ze dla liczby "a" istnial jakis dzielnik rozny od niej samej cout<<"NIE"; else cout<<"TAK"; return 0; }
[ "61905322+KrzysztofTab@users.noreply.github.com" ]
61905322+KrzysztofTab@users.noreply.github.com
cd7baaa1836267a823a55eea33578ae5a992c1f7
b1e6d8c20facf0c265febf93cfc405b7a157dc0d
/cSceneManager.h
912d35e6bea5f26e32746b2d157e816f1dc92a06
[]
no_license
donghoyu/Ready
f30251da3c6b068cb0e18c2a367d1f30269df52f
1b07c3a5766a25a39a1cf04ef73b8c2f6cc3088b
refs/heads/master
2021-01-25T14:03:24.635629
2018-03-29T14:30:09
2018-03-29T14:30:09
123,641,123
0
0
null
null
null
null
UHC
C++
false
false
1,188
h
#pragma once #define SCENEMANAGER cSceneManager::GetInstance() #include <map> #include <string> class SceneList; class cSceneManager { private: SINGLETONE(cSceneManager); typedef map<string, SceneList*> mapSceneList; typedef map<string, SceneList*>::iterator mapSceneIter; public: static SceneList* _currentScene; //현재 씬 static SceneList* _loadingScene; //로딩 씬(안쓰일듯) static SceneList* _readyScene; //대기 씬 mapSceneList _mSceneList; mapSceneList _mLoadingSceneList; DWORD _loadingThreadID; //혹시 몰라 넣어놓는 쓰레드용 ID public: HRESULT init(void); void release(void); void update(void); void render(void); //씬 추가 함수 SceneList* addScene(string sceneName, SceneList* scene); SceneList* addLoadingScene(string loadingSceneName, SceneList* scene); //씬 변경 HRESULT changeScene(string sceneName); HRESULT changeScene(string sceneName, string loadingSceneName); //friend란 선언하면 클래스의 private까지 그냥 접근 가능케 한다 //남발하면 안되는데, 구조상 왠지 1~2개정도는 해두면 좋을 것 같으면 해도됨 friend DWORD CALLBACK loadingThread(LPVOID prc); };
[ "dbehdgh_@naver.com" ]
dbehdgh_@naver.com
9d4f1212f909a1a3a86a774eab481839fe43d249
f4f4130c502c937061b8a72aeb27f8d892638277
/UUA/Player.h
e79d7493ae915b54a8b8553796d98ef99df496c9
[]
no_license
Kundan0/UUA
9ed7f8bdcd2c7d47765a60396339a33c8356db5f
23cd9627890332cb70bb0a00c2b54508affbe256
refs/heads/master
2021-10-21T02:51:37.423877
2019-03-02T14:30:12
2019-03-02T14:30:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
487
h
#pragma once #include"pch.h" #include "Game.h" class Player : public GameObject { float x, y, z; int jump; int yLevel; Point p; sf::Clock clock; float width, height; sf::Texture texture[4]; sf::Sprite sprite[4]; public: static int playerNo; Player(); Player(float Width, float Height); bool isPlayer() { return true; } void Update(float dt); void Reset(); void Reset(int); void Draw(sf::RenderWindow&); sf::Vector3f position3d(); sf::Vector3f size(); ~Player(); };
[ "074bct517.kundan@pcampus.edu.np" ]
074bct517.kundan@pcampus.edu.np