blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
d02baa54e37c41299f3f9061d51f56457684c5bb
af4d5f1ec7ab228b9cfe32c887ed91d263531a36
/src/test/netbase_tests.cpp
d5e2535cfaf9a302480578eaafa8c5b3a26f4ae5
[ "MIT" ]
permissive
qyno/qynocoin
c800bcaa888b69efd9b83f7a5241a862a3c29213
d7f9bf8933eb37d02e7b73ebbd20f395acbdaf40
refs/heads/master
2020-03-22T21:47:49.732425
2018-12-07T10:20:02
2018-12-07T10:20:02
140,714,015
8
11
null
null
null
null
UTF-8
C++
false
false
11,636
cpp
// Copyright (c) 2012-2014 The Bitcoin Core developers // Copyright (c) 2014-2015 The Dash Core developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The Qyno Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "netbase.h" #include <string> #include <boost/test/unit_test.hpp> using namespace std; BOOST_AUTO_TEST_SUITE(netbase_tests) BOOST_AUTO_TEST_CASE(netbase_networks) { BOOST_CHECK(CNetAddr("127.0.0.1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(CNetAddr("::1").GetNetwork() == NET_UNROUTABLE); BOOST_CHECK(CNetAddr("8.8.8.8").GetNetwork() == NET_IPV4); BOOST_CHECK(CNetAddr("2001::8888").GetNetwork() == NET_IPV6); BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").GetNetwork() == NET_TOR); } BOOST_AUTO_TEST_CASE(netbase_properties) { BOOST_CHECK(CNetAddr("127.0.0.1").IsIPv4()); BOOST_CHECK(CNetAddr("::FFFF:192.168.1.1").IsIPv4()); BOOST_CHECK(CNetAddr("::1").IsIPv6()); BOOST_CHECK(CNetAddr("10.0.0.1").IsRFC1918()); BOOST_CHECK(CNetAddr("192.168.1.1").IsRFC1918()); BOOST_CHECK(CNetAddr("172.31.255.255").IsRFC1918()); BOOST_CHECK(CNetAddr("2001:0DB8::").IsRFC3849()); BOOST_CHECK(CNetAddr("169.254.1.1").IsRFC3927()); BOOST_CHECK(CNetAddr("2002::1").IsRFC3964()); BOOST_CHECK(CNetAddr("FC00::").IsRFC4193()); BOOST_CHECK(CNetAddr("2001::2").IsRFC4380()); BOOST_CHECK(CNetAddr("2001:10::").IsRFC4843()); BOOST_CHECK(CNetAddr("FE80::").IsRFC4862()); BOOST_CHECK(CNetAddr("64:FF9B::").IsRFC6052()); BOOST_CHECK(CNetAddr("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").IsTor()); BOOST_CHECK(CNetAddr("127.0.0.1").IsLocal()); BOOST_CHECK(CNetAddr("::1").IsLocal()); BOOST_CHECK(CNetAddr("8.8.8.8").IsRoutable()); BOOST_CHECK(CNetAddr("2001::1").IsRoutable()); BOOST_CHECK(CNetAddr("127.0.0.1").IsValid()); } bool static TestSplitHost(string test, string host, int port) { string hostOut; int portOut = -1; SplitHostPort(test, portOut, hostOut); return hostOut == host && port == portOut; } BOOST_AUTO_TEST_CASE(netbase_splithost) { BOOST_CHECK(TestSplitHost("www.bitcoin.org", "www.bitcoin.org", -1)); BOOST_CHECK(TestSplitHost("[www.bitcoin.org]", "www.bitcoin.org", -1)); BOOST_CHECK(TestSplitHost("www.bitcoin.org:80", "www.bitcoin.org", 80)); BOOST_CHECK(TestSplitHost("[www.bitcoin.org]:80", "www.bitcoin.org", 80)); BOOST_CHECK(TestSplitHost("127.0.0.1", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("127.0.0.1:39741", "127.0.0.1", 39741)); BOOST_CHECK(TestSplitHost("[127.0.0.1]", "127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("[127.0.0.1]:39741", "127.0.0.1", 39741)); BOOST_CHECK(TestSplitHost("::ffff:127.0.0.1", "::ffff:127.0.0.1", -1)); BOOST_CHECK(TestSplitHost("[::ffff:127.0.0.1]:39741", "::ffff:127.0.0.1", 39741)); BOOST_CHECK(TestSplitHost("[::]:39741", "::", 39741)); BOOST_CHECK(TestSplitHost("::39741", "::39741", -1)); BOOST_CHECK(TestSplitHost(":39741", "", 39741)); BOOST_CHECK(TestSplitHost("[]:39741", "", 39741)); BOOST_CHECK(TestSplitHost("", "", -1)); } bool static TestParse(string src, string canon) { CService addr; if (!LookupNumeric(src.c_str(), addr, 65535)) return canon == ""; return canon == addr.ToString(); } BOOST_AUTO_TEST_CASE(netbase_lookupnumeric) { BOOST_CHECK(TestParse("127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("127.0.0.1:39741", "127.0.0.1:39741")); BOOST_CHECK(TestParse("::ffff:127.0.0.1", "127.0.0.1:65535")); BOOST_CHECK(TestParse("::", "[::]:65535")); BOOST_CHECK(TestParse("[::]:39741", "[::]:39741")); BOOST_CHECK(TestParse("[127.0.0.1]", "127.0.0.1:65535")); BOOST_CHECK(TestParse(":::", "")); } BOOST_AUTO_TEST_CASE(onioncat_test) { // values from https://web.archive.org/web/20121122003543/http://www.cypherpunk.at/onioncat/wiki/OnionCat CNetAddr addr1("5wyqrzbvrdsumnok.onion"); CNetAddr addr2("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca"); BOOST_CHECK(addr1 == addr2); BOOST_CHECK(addr1.IsTor()); BOOST_CHECK(addr1.ToStringIP() == "5wyqrzbvrdsumnok.onion"); BOOST_CHECK(addr1.IsRoutable()); } BOOST_AUTO_TEST_CASE(subnet_test) { BOOST_CHECK(CSubNet("1.2.3.0/24") == CSubNet("1.2.3.0/255.255.255.0")); BOOST_CHECK(CSubNet("1.2.3.0/24") != CSubNet("1.2.4.0/255.255.255.0")); BOOST_CHECK(CSubNet("1.2.3.0/24").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("1.2.2.0/24").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(CSubNet("1.2.3.4").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(CSubNet("1.2.3.4/32").Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("1.2.3.4").Match(CNetAddr("5.6.7.8"))); BOOST_CHECK(!CSubNet("1.2.3.4/32").Match(CNetAddr("5.6.7.8"))); BOOST_CHECK(CSubNet("::ffff:127.0.0.1").Match(CNetAddr("127.0.0.1"))); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:8"))); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8").Match(CNetAddr("1:2:3:4:5:6:7:9"))); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:0/112").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(CSubNet("192.168.0.1/24").Match(CNetAddr("192.168.0.2"))); BOOST_CHECK(CSubNet("192.168.0.20/29").Match(CNetAddr("192.168.0.18"))); BOOST_CHECK(CSubNet("1.2.2.1/24").Match(CNetAddr("1.2.2.4"))); BOOST_CHECK(CSubNet("1.2.2.110/31").Match(CNetAddr("1.2.2.111"))); BOOST_CHECK(CSubNet("1.2.2.20/26").Match(CNetAddr("1.2.2.63"))); // All-Matching IPv6 Matches arbitrary IPv4 and IPv6 BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); BOOST_CHECK(CSubNet("::/0").Match(CNetAddr("1.2.3.4"))); // All-Matching IPv4 does not Match IPv6 BOOST_CHECK(!CSubNet("0.0.0.0/0").Match(CNetAddr("1:2:3:4:5:6:7:1234"))); // Invalid subnets Match nothing (not even invalid addresses) BOOST_CHECK(!CSubNet().Match(CNetAddr("1.2.3.4"))); BOOST_CHECK(!CSubNet("").Match(CNetAddr("4.5.6.7"))); BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("0.0.0.0"))); BOOST_CHECK(!CSubNet("bloop").Match(CNetAddr("hab"))); // Check valid/invalid BOOST_CHECK(CSubNet("1.2.3.0/0").IsValid()); BOOST_CHECK(!CSubNet("1.2.3.0/-1").IsValid()); BOOST_CHECK(CSubNet("1.2.3.0/32").IsValid()); BOOST_CHECK(!CSubNet("1.2.3.0/33").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/0").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/33").IsValid()); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/-1").IsValid()); BOOST_CHECK(CSubNet("1:2:3:4:5:6:7:8/128").IsValid()); BOOST_CHECK(!CSubNet("1:2:3:4:5:6:7:8/129").IsValid()); BOOST_CHECK(!CSubNet("fuzzy").IsValid()); //CNetAddr constructor test BOOST_CHECK(CSubNet(CNetAddr("127.0.0.1")).IsValid()); BOOST_CHECK(CSubNet(CNetAddr("127.0.0.1")).Match(CNetAddr("127.0.0.1"))); BOOST_CHECK(!CSubNet(CNetAddr("127.0.0.1")).Match(CNetAddr("127.0.0.2"))); BOOST_CHECK(CSubNet(CNetAddr("127.0.0.1")).ToString() == "127.0.0.1/32"); BOOST_CHECK(CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).IsValid()); BOOST_CHECK(CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).Match(CNetAddr("1:2:3:4:5:6:7:8"))); BOOST_CHECK(!CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).Match(CNetAddr("1:2:3:4:5:6:7:9"))); BOOST_CHECK(CSubNet(CNetAddr("1:2:3:4:5:6:7:8")).ToString() == "1:2:3:4:5:6:7:8/128"); CSubNet subnet = CSubNet("1.2.3.4/255.255.255.255"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/32"); subnet = CSubNet("1.2.3.4/255.255.255.254"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/31"); subnet = CSubNet("1.2.3.4/255.255.255.252"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.4/30"); subnet = CSubNet("1.2.3.4/255.255.255.248"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/29"); subnet = CSubNet("1.2.3.4/255.255.255.240"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/28"); subnet = CSubNet("1.2.3.4/255.255.255.224"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/27"); subnet = CSubNet("1.2.3.4/255.255.255.192"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/26"); subnet = CSubNet("1.2.3.4/255.255.255.128"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/25"); subnet = CSubNet("1.2.3.4/255.255.255.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.3.0/24"); subnet = CSubNet("1.2.3.4/255.255.254.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.2.0/23"); subnet = CSubNet("1.2.3.4/255.255.252.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/22"); subnet = CSubNet("1.2.3.4/255.255.248.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/21"); subnet = CSubNet("1.2.3.4/255.255.240.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/20"); subnet = CSubNet("1.2.3.4/255.255.224.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/19"); subnet = CSubNet("1.2.3.4/255.255.192.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/18"); subnet = CSubNet("1.2.3.4/255.255.128.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/17"); subnet = CSubNet("1.2.3.4/255.255.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/16"); subnet = CSubNet("1.2.3.4/255.254.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/15"); subnet = CSubNet("1.2.3.4/255.252.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/14"); subnet = CSubNet("1.2.3.4/255.248.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/13"); subnet = CSubNet("1.2.3.4/255.240.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/12"); subnet = CSubNet("1.2.3.4/255.224.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/11"); subnet = CSubNet("1.2.3.4/255.192.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/10"); subnet = CSubNet("1.2.3.4/255.128.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/9"); subnet = CSubNet("1.2.3.4/255.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.0.0.0/8"); subnet = CSubNet("1.2.3.4/254.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/7"); subnet = CSubNet("1.2.3.4/252.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/6"); subnet = CSubNet("1.2.3.4/248.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/5"); subnet = CSubNet("1.2.3.4/240.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/4"); subnet = CSubNet("1.2.3.4/224.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/3"); subnet = CSubNet("1.2.3.4/192.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/2"); subnet = CSubNet("1.2.3.4/128.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/1"); subnet = CSubNet("1.2.3.4/0.0.0.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "0.0.0.0/0"); subnet = CSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"); BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/128"); subnet = CSubNet("1:2:3:4:5:6:7:8/ffff:0000:0000:0000:0000:0000:0000:0000"); BOOST_CHECK_EQUAL(subnet.ToString(), "1::/16"); subnet = CSubNet("1:2:3:4:5:6:7:8/0000:0000:0000:0000:0000:0000:0000:0000"); BOOST_CHECK_EQUAL(subnet.ToString(), "::/0"); subnet = CSubNet("1.2.3.4/255.255.232.0"); BOOST_CHECK_EQUAL(subnet.ToString(), "1.2.0.0/255.255.232.0"); subnet = CSubNet("1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f"); BOOST_CHECK_EQUAL(subnet.ToString(), "1:2:3:4:5:6:7:8/ffff:ffff:ffff:fffe:ffff:ffff:ffff:ff0f"); } BOOST_AUTO_TEST_SUITE_END()
[ "contact@qyno.org" ]
contact@qyno.org
49b4392301bb0b0ef778f2e16e0a3feae0a3ef3b
4f4ddc396fa1dfc874780895ca9b8ee4f7714222
/src/xtp/Samples/CommandBars/TearOffPopups/TearOffPopups.cpp
6530c08ae693f030ab2b7879e8096b67c4703d72
[]
no_license
UtsavChokshiCNU/GenSym-Test2
3214145186d032a6b5a7486003cef40787786ba0
a48c806df56297019cfcb22862dd64609fdd8711
refs/heads/master
2021-01-23T23:14:03.559378
2017-09-09T14:20:09
2017-09-09T14:20:09
102,960,203
3
5
null
null
null
null
UTF-8
C++
false
false
4,605
cpp
// TearOffPopups.cpp : Defines the class behaviors for the application. // // This file is a part of the XTREME TOOLKIT PRO MFC class library. // (c)1998-2011 Codejock Software, All Rights Reserved. // // THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE // RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN // CONSENT OF CODEJOCK SOFTWARE. // // THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED // IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO // YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A // SINGLE COMPUTER. // // CONTACT INFORMATION: // support@codejock.com // http://www.codejock.com // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "TearOffPopups.h" #include "MainFrm.h" #include "ChildFrm.h" #include "TearOffPopupsDoc.h" #include "TearOffPopupsView.h" #include "AboutDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTearOffPopupsApp BEGIN_MESSAGE_MAP(CTearOffPopupsApp, CWinApp) //{{AFX_MSG_MAP(CTearOffPopupsApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) // Standard print setup command ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTearOffPopupsApp construction CTearOffPopupsApp::CTearOffPopupsApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CTearOffPopupsApp object CTearOffPopupsApp theApp; ///////////////////////////////////////////////////////////////////////////// // CTearOffPopupsApp initialization BOOL CTearOffPopupsApp::InitInstance() { // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); CXTPWinDwmWrapper().SetProcessDPIAware(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #if _MSC_VER <= 1200 // MFC 6.0 or earlier #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else Enable3dControlsStatic(); // Call this when linking to MFC statically #endif #endif // MFC 6.0 or earlier // Change the registry key under which our settings are stored. // TODO: You should modify this string to be something appropriate // such as the name of your company or organization. SetRegistryKey(_T("Codejock Software Sample Applications")); LoadStdProfileSettings(); // Load standard INI file options (including MRU) // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CMultiDocTemplate* pDocTemplate; pDocTemplate = new CMultiDocTemplate( IDR_TEAROFTYPE, RUNTIME_CLASS(CTearOffPopupsDoc), RUNTIME_CLASS(CChildFrame), // custom MDI child frame RUNTIME_CLASS(CTearOffPopupsView)); //pDocTemplate->SetContainerInfo(IDR_TEAROFTYPE_CNTR_IP); AddDocTemplate(pDocTemplate); // create main MDI Frame window CMainFrame* pMainFrame = new CMainFrame; if (!pMainFrame->LoadFrame(IDR_MAINFRAME)) return FALSE; m_pMainWnd = pMainFrame; // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) return FALSE; // The main window has been initialized, so show and update it. pMainFrame->ShowWindow(m_nCmdShow); pMainFrame->UpdateWindow(); return TRUE; } // App command to run the dialog void CTearOffPopupsApp::OnAppAbout() { CAboutDlg dlgAbout; dlgAbout.DoModal(); } ///////////////////////////////////////////////////////////////////////////// // CTearOffPopupsApp message handlers
[ "utsavchokshi@Utsavs-MacBook-Pro.local" ]
utsavchokshi@Utsavs-MacBook-Pro.local
2ec45f340dd54c489df9c78a890f9edbb06a9b39
f2ce8e1f84bb26707b507d7d7866fa017e393380
/main.cpp
afb21e06bf8ea0f6fb82d2691e7b89d6dff3b906
[]
no_license
TylerHinojosa/CIS2013_Week10_Lab
62b9d9f3ffc320ab268a6874d907434c27a2f0b3
ddca1babaa73e065c3d23856a3b820ac0ef85e69
refs/heads/master
2020-05-02T17:27:28.822411
2019-03-28T01:27:02
2019-03-28T01:27:02
178,099,089
0
0
null
null
null
null
UTF-8
C++
false
false
638
cpp
#include <iostream> #include <string> #include "person.cpp" using namespace std; int main(){ Person bob; Person tom("Tom", "M", "stupid"); Person p3("Susan", "F", "pretty"); person mypeople[10]; cout << bob.getStats() << endl; cout << " Age: " << bob.getAge() << endl; cout << tom.getStats() << endl; cout << " Age: " << tom.getAge() << endl; cout << p3.getStats() << endl; cout << " Age: " << p3.getAge() << endl; bob.setName("Bob"); bob.setAge(1000); cout << " Age: " << bob.getAge() << endl; bob.setRace("Obnoxious"); bob.setAlive(true); bob.setGender("Male"); cout << bob.getStats() << endl; return 0; };
[ "46981261+TylerHinojosa@users.noreply.github.com" ]
46981261+TylerHinojosa@users.noreply.github.com
100123a047dd1fb8ea82e7fa565c8159e6e9d59d
4390196b0e570027406aab894c805657628cc5f5
/Array/1.6.cpp
bdb960ecc64b2b3e927e6ccd674eedb50326241f
[]
no_license
zyandeep/Data-Structure-in-C-
0e7c32beabfc19c0426d6ddb4533ef25b640aa11
e2fb7b1edc49e92a9716c203fe3d0b5ee74853fe
refs/heads/master
2020-03-21T11:19:24.958128
2018-06-24T17:06:03
2018-06-24T17:06:03
138,500,521
0
0
null
null
null
null
UTF-8
C++
false
false
3,131
cpp
#include <iostream> using namespace std; #define SIZE 10 class Menu { int a[SIZE], count; int array1[SIZE],array2[SIZE],array3[SIZE * 2]; public: void bubble_sort(int[], int); void insert(); void del(); void traversal(); void merged(); Menu() { count=0; for (int i = 0; i < SIZE; i++) // array is empty a[i]=0; } }; int main() { int n; Menu mn; for(;;) { cout<<endl<<"*** YOUR CHOICES ARE ***"<<endl; cout<<"1. Insert\n"; cout<<"2. Delete\n"; cout<<"3. Traverse\n"; cout<<"4. Merged\n"; cout<<"5. Exit\n"; cout<<"NOW ENTER YOUR CHOICE :"<<endl; cin>>n; switch(n) { case 1: mn.insert(); break; case 2: mn.del(); break; case 3: mn.traversal(); break; case 4: mn.merged(); break; case 5: return 0; default: cout<<"SORRY!YOUR CHOICE IS INVALID!!"<<endl; } } } void Menu::insert() { int num, pos, i, temp; if(count < 10) { cout<<"Enter the number and its positon: "; cin>>num>>pos; pos--; if(a[pos] == 0) a[pos]=num; else { for (i = pos; i < SIZE; i++) { temp=a[i]; a[i]=num; num=temp; } } count++; } else { cout<<"The Array is Full"; } } void Menu::traversal() { int i; for(i=0; i<SIZE; i++) { cout<<endl<<a[i]; } } void Menu::del() //Body of del function { int item, i, flag=0, pos; cout<<"Enter the number to delete : "<<endl; cin>>item; // locate the element in the array for (i=0; i < SIZE; i++) { if(a[i]==item) { flag=1; pos=i; break; } } if(flag) { for(i=pos; i<SIZE-1; i++) { a[i]=a[i+1]; } a[i] = 0; count--; } else { cout<<"The numner is not in list"<<endl; } } void Menu::merged() { int i, j, k; cout<<"Enter the 1st array: "<<endl; for (i = 0; i < SIZE; i++) cin>>array1[i]; cout<<"Enter the 2nd array: "<<endl; for (i = 0; i < SIZE; i++) cin>>array2[i]; // sort the arrays in ascending order bubble_sort(array1, SIZE); bubble_sort(array2, SIZE); // Sorting while merging for (i=0, j=0, k=0; i < SIZE && j < SIZE; ) { if( array1[i] < array2[j] ) { array3[k] = array1[i]; i++; } else if ( array2[j] < array1[i] ) { array3[k] = array2[j]; j++; } else { array3[k] = array1[i]; i++; j++; } k++; } if(i == SIZE) // 1st array has been fully copied { while(j < SIZE) { array3[k++] = array2[j++]; } } else if (j == SIZE) // 2nd array has been fully copied { while(i < SIZE) { array3[k++] = array2[i++]; } } // Display the sorted merged array cout<<"The sorted merged array--->" <<endl; for (i = 0; i < k; i++) { cout<<array3[i]<<" "; } cout<<"\n"; } void Menu :: bubble_sort(int arr[], int n) { int i, pass, temp; for (pass = n-1; pass >= 1; pass--) { for (i = 0; i < pass; i++) { if (arr[i] > arr[i+1]) { temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; } } } }
[ "zyandeep000@gmail.com" ]
zyandeep000@gmail.com
c10ea672d23d2938a8d0920872df00cb0fda9d06
a82f21ddb1a9fcff19629597a9d754ae9356f4c9
/src/test/crypto_tests.cpp
f65057922b60a1891926a7c46380f0ab143fcad1
[ "MIT" ]
permissive
Tanzanite-Team/Tanzanite
ca9f6bdd4baa7813623640d6d0d510a5fcbdb517
630c3e5aabc823a60026357063401a4f09633d77
refs/heads/main
2023-03-11T06:58:03.981527
2021-02-26T14:07:58
2021-02-26T14:07:58
279,105,162
0
0
null
null
null
null
UTF-8
C++
false
false
19,953
cpp
// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2019 The Tanzanite developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "crypto/rfc6979_hmac_sha256.h" #include "crypto/chacha20.h" #include "crypto/ripemd160.h" #include "crypto/sha1.h" #include "crypto/sha256.h" #include "crypto/sha512.h" #include "crypto/hmac_sha256.h" #include "crypto/hmac_sha512.h" #include "random.h" #include "utilstrencodings.h" #include "test/test_tanzanite.h" #include <vector> #include <boost/assign/list_of.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(crypto_tests, BasicTestingSetup) template<typename Hasher, typename In, typename Out> void TestVector(const Hasher &h, const In &in, const Out &out) { Out hash; BOOST_CHECK(out.size() == h.OUTPUT_SIZE); hash.resize(out.size()); { // Test that writing the whole input string at once works. Hasher(h).Write((unsigned char*)&in[0], in.size()).Finalize(&hash[0]); BOOST_CHECK(hash == out); } for (int i=0; i<32; i++) { // Test that writing the string broken up in random pieces works. Hasher hasher(h); size_t pos = 0; while (pos < in.size()) { size_t len = InsecureRandRange((in.size() - pos + 1) / 2 + 1); hasher.Write((unsigned char*)&in[pos], len); pos += len; if (pos > 0 && pos + 2 * out.size() > in.size() && pos < in.size()) { // Test that writing the rest at once to a copy of a hasher works. Hasher(hasher).Write((unsigned char*)&in[pos], in.size() - pos).Finalize(&hash[0]); BOOST_CHECK(hash == out); } } hasher.Finalize(&hash[0]); BOOST_CHECK(hash == out); } } void TestSHA1(const std::string &in, const std::string &hexout) { TestVector(CSHA1(), in, ParseHex(hexout));} void TestSHA256(const std::string &in, const std::string &hexout) { TestVector(CSHA256(), in, ParseHex(hexout));} void TestSHA512(const std::string &in, const std::string &hexout) { TestVector(CSHA512(), in, ParseHex(hexout));} void TestRIPEMD160(const std::string &in, const std::string &hexout) { TestVector(CRIPEMD160(), in, ParseHex(hexout));} void TestHMACSHA256(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); TestVector(CHMAC_SHA256(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestHMACSHA512(const std::string &hexkey, const std::string &hexin, const std::string &hexout) { std::vector<unsigned char> key = ParseHex(hexkey); TestVector(CHMAC_SHA512(&key[0], key.size()), ParseHex(hexin), ParseHex(hexout)); } void TestChaCha20(const std::string &hexkey, uint64_t nonce, uint64_t seek, const std::string& hexout) { std::vector<unsigned char> key = ParseHex(hexkey); ChaCha20 rng(key.data(), key.size()); rng.SetIV(nonce); rng.Seek(seek); std::vector<unsigned char> out = ParseHex(hexout); std::vector<unsigned char> outres; outres.resize(out.size()); rng.Output(outres.data(), outres.size()); BOOST_CHECK(out == outres); } std::string LongTestString(void) { std::string ret; for (int i=0; i<200000; i++) { ret += (unsigned char)(i); ret += (unsigned char)(i >> 4); ret += (unsigned char)(i >> 8); ret += (unsigned char)(i >> 12); ret += (unsigned char)(i >> 16); } return ret; } const std::string test1 = LongTestString(); BOOST_AUTO_TEST_CASE(ripemd160_testvectors) { TestRIPEMD160("", "9c1185a5c5e9fc54612808977ee8f548b2258d31"); TestRIPEMD160("abc", "8eb208f7e05d987a9b044a8e98c6b087f15a0bfc"); TestRIPEMD160("message digest", "5d0689ef49d2fae572b881b123a85ffa21595f36"); TestRIPEMD160("secure hash algorithm", "20397528223b6a5f4cbc2808aba0464e645544f9"); TestRIPEMD160("RIPEMD160 is considered to be safe", "a7d78608c7af8a8e728778e81576870734122b66"); TestRIPEMD160("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "12a053384a9c0c88e405a06c27dcf49ada62eb2b"); TestRIPEMD160("For this sample, this 63-byte string will be used as input data", "de90dbfee14b63fb5abf27c2ad4a82aaa5f27a11"); TestRIPEMD160("This is exactly 64 bytes long, not counting the terminating byte", "eda31d51d3a623b81e19eb02e24ff65d27d67b37"); TestRIPEMD160(std::string(1000000, 'a'), "52783243c1697bdbe16d37f97f68f08325dc1528"); TestRIPEMD160(test1, "464243587bd146ea835cdf57bdae582f25ec45f1"); } BOOST_AUTO_TEST_CASE(sha1_testvectors) { TestSHA1("", "da39a3ee5e6b4b0d3255bfef95601890afd80709"); TestSHA1("abc", "a9993e364706816aba3e25717850c26c9cd0d89d"); TestSHA1("message digest", "c12252ceda8be8994d5fa0290a47231c1d16aae3"); TestSHA1("secure hash algorithm", "d4d6d2f0ebe317513bbd8d967d89bac5819c2f60"); TestSHA1("SHA1 is considered to be safe", "f2b6650569ad3a8720348dd6ea6c497dee3a842a"); TestSHA1("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "84983e441c3bd26ebaae4aa1f95129e5e54670f1"); TestSHA1("For this sample, this 63-byte string will be used as input data", "4f0ea5cd0585a23d028abdc1a6684e5a8094dc49"); TestSHA1("This is exactly 64 bytes long, not counting the terminating byte", "fb679f23e7d1ce053313e66e127ab1b444397057"); TestSHA1(std::string(1000000, 'a'), "34aa973cd4c4daa4f61eeb2bdbad27316534016f"); TestSHA1(test1, "b7755760681cbfd971451668f32af5774f4656b5"); } BOOST_AUTO_TEST_CASE(sha256_testvectors) { TestSHA256("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); TestSHA256("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); TestSHA256("message digest", "f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650"); TestSHA256("secure hash algorithm", "f30ceb2bb2829e79e4ca9753d35a8ecc00262d164cc077080295381cbd643f0d"); TestSHA256("SHA256 is considered to be safe", "6819d915c73f4d1e77e4e1b52d1fa0f9cf9beaead3939f15874bd988e2a23630"); TestSHA256("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1"); TestSHA256("For this sample, this 63-byte string will be used as input data", "f08a78cbbaee082b052ae0708f32fa1e50c5c421aa772ba5dbb406a2ea6be342"); TestSHA256("This is exactly 64 bytes long, not counting the terminating byte", "ab64eff7e88e2e46165e29f2bce41826bd4c7b3552f6b382a9e7d3af47c245f8"); TestSHA256("As Bitcoin relies on 80 byte header hashes, we want to have an example for that.", "7406e8de7d6e4fffc573daef05aefb8806e7790f55eab5576f31349743cca743"); TestSHA256(std::string(1000000, 'a'), "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); TestSHA256(test1, "a316d55510b49662420f49d145d42fb83f31ef8dc016aa4e32df049991a91e26"); } BOOST_AUTO_TEST_CASE(sha512_testvectors) { TestSHA512("", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); TestSHA512("abc", "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a" "2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"); TestSHA512("message digest", "107dbf389d9e9f71a3a95f6c055b9251bc5268c2be16d6c13492ea45b0199f33" "09e16455ab1e96118e8a905d5597b72038ddb372a89826046de66687bb420e7c"); TestSHA512("secure hash algorithm", "7746d91f3de30c68cec0dd693120a7e8b04d8073cb699bdce1a3f64127bca7a3" "d5db502e814bb63c063a7a5043b2df87c61133395f4ad1edca7fcf4b30c3236e"); TestSHA512("SHA512 is considered to be safe", "099e6468d889e1c79092a89ae925a9499b5408e01b66cb5b0a3bd0dfa51a9964" "6b4a3901caab1318189f74cd8cf2e941829012f2449df52067d3dd5b978456c2"); TestSHA512("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c335" "96fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445"); TestSHA512("For this sample, this 63-byte string will be used as input data", "b3de4afbc516d2478fe9b518d063bda6c8dd65fc38402dd81d1eb7364e72fb6e" "6663cf6d2771c8f5a6da09601712fb3d2a36c6ffea3e28b0818b05b0a8660766"); TestSHA512("This is exactly 64 bytes long, not counting the terminating byte", "70aefeaa0e7ac4f8fe17532d7185a289bee3b428d950c14fa8b713ca09814a38" "7d245870e007a80ad97c369d193e41701aa07f3221d15f0e65a1ff970cedf030"); TestSHA512("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmno" "ijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018" "501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"); TestSHA512(std::string(1000000, 'a'), "e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb" "de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"); TestSHA512(test1, "40cac46c147e6131c5193dd5f34e9d8bb4951395f27b08c558c65ff4ba2de594" "37de8c3ef5459d76a52cedc02dc499a3c9ed9dedbfb3281afd9653b8a112fafc"); } BOOST_AUTO_TEST_CASE(hmac_sha256_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA256("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265", "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"); TestHMACSHA256("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f", "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddd", "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"); TestHMACSHA256("0102030405060708090a0b0c0d0e0f10111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a" "65204b6579202d2048617368204b6579204669727374", "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"); TestHMACSHA256("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "5468697320697320612074657374207573696e672061206c6172676572207468" "616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074" "68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565" "647320746f20626520686173686564206265666f7265206265696e6720757365" "642062792074686520484d414320616c676f726974686d2e", "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"); } BOOST_AUTO_TEST_CASE(hmac_sha512_testvectors) { // test cases 1, 2, 3, 4, 6 and 7 of RFC 4231 TestHMACSHA512("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", "4869205468657265", "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cde" "daa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"); TestHMACSHA512("4a656665", "7768617420646f2079612077616e7420666f72206e6f7468696e673f", "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea250554" "9758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" "dddddddddddddddddddddddddddddddddddd", "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39" "bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb"); TestHMACSHA512("0102030405060708090a0b0c0d0e0f10111213141516171819", "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd" "cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd", "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3db" "a91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "54657374205573696e67204c6172676572205468616e20426c6f636b2d53697a" "65204b6579202d2048617368204b6579204669727374", "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f352" "6b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"); TestHMACSHA512("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" "aaaaaa", "5468697320697320612074657374207573696e672061206c6172676572207468" "616e20626c6f636b2d73697a65206b657920616e642061206c61726765722074" "68616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565" "647320746f20626520686173686564206265666f7265206265696e6720757365" "642062792074686520484d414320616c676f726974686d2e", "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944" "b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"); } void TestRFC6979(const std::string& hexkey, const std::string& hexmsg, const std::vector<std::string>& hexout) { std::vector<unsigned char> key = ParseHex(hexkey); std::vector<unsigned char> msg = ParseHex(hexmsg); RFC6979_HMAC_SHA256 rng(&key[0], key.size(), &msg[0], msg.size()); for (unsigned int i = 0; i < hexout.size(); i++) { std::vector<unsigned char> out = ParseHex(hexout[i]); std::vector<unsigned char> gen; gen.resize(out.size()); rng.Generate(&gen[0], gen.size()); BOOST_CHECK(out == gen); } } BOOST_AUTO_TEST_CASE(rfc6979_hmac_sha256) { TestRFC6979( "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f00", "4bf5122f344554c53bde2ebb8cd2b7e3d1600ad631c385a5d7cce23c7785459a", boost::assign::list_of ("4fe29525b2086809159acdf0506efb86b0ec932c7ba44256ab321e421e67e9fb") ("2bf0fff1d3c378a22dc5de1d856522325c65b504491a0cbd01cb8f3aa67ffd4a") ("f528b410cb541f77000d7afb6c5b53c5c471eab43e466d9ac5190c39c82fd82e")); TestRFC6979( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", boost::assign::list_of ("9c236c165b82ae0cd590659e100b6bab3036e7ba8b06749baf6981e16f1a2b95") ("df471061625bc0ea14b682feee2c9c02f235da04204c1d62a1536c6e17aed7a9") ("7597887cbd76321f32e30440679a22cf7f8d9d2eac390e581fea091ce202ba94")); } BOOST_AUTO_TEST_CASE(chacha20_testvector) { // Test vector from RFC 7539 TestChaCha20("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 0x4a000000UL, 1, "224f51f3401bd9e12fde276fb8631ded8c131f823d2c06e27e4fcaec9ef3cf788a3b0aa372600a92b57974cded2b9334794cb" "a40c63e34cdea212c4cf07d41b769a6749f3f630f4122cafe28ec4dc47e26d4346d70b98c73f3e9c53ac40c5945398b6eda1a" "832c89c167eacd901d7e2bf363"); // Test vectors from https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7 TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000", 0, 0, "76b8e0ada0f13d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d7724e03fb8d84a376a43b" "8f41518a11cc387b669b2ee6586"); TestChaCha20("0000000000000000000000000000000000000000000000000000000000000001", 0, 0, "4540f05a9f1fb296d7736e7b208e3c96eb4fe1834688d2604f450952ed432d41bbe2a0b6ea7566d2a5d1e7e20d42af2c53d79" "2b1c43fea817e9ad275ae546963"); TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000", 0x0100000000000000ULL, 0, "de9cba7bf3d69ef5e786dc63973f653a0b49e015adbff7134fcb7df137821031e85a050278a7084527214f73efc7fa5b52770" "62eb7a0433e445f41e3"); TestChaCha20("0000000000000000000000000000000000000000000000000000000000000000", 1, 0, "ef3fdfd6c61578fbf5cf35bd3dd33b8009631634d21e42ac33960bd138e50d32111e4caf237ee53ca8ad6426194a88545ddc4" "97a0b466e7d6bbdb0041b2f586b"); TestChaCha20("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f", 0x0706050403020100ULL, 0, "f798a189f195e66982105ffb640bb7757f579da31602fc93ec01ac56f85ac3c134a4547b733b46413042c9440049176905d3b" "e59ea1c53f15916155c2be8241a38008b9a26bc35941e2444177c8ade6689de95264986d95889fb60e84629c9bd9a5acb1cc1" "18be563eb9b3a4a472f82e09a7e778492b562ef7130e88dfe031c79db9d4f7c7a899151b9a475032b63fc385245fe054e3dd5" "a97a5f576fe064025d3ce042c566ab2c507b138db853e3d6959660996546cc9c4a6eafdc777c040d70eaf46f76dad3979e5c5" "360c3317166a1c894c94a371876a94df7628fe4eaaf2ccb27d5aaae0ad7ad0f9d4b6ad3b54098746d4524d38407a6deb3ab78" "fab78c9"); } BOOST_AUTO_TEST_CASE(countbits_tests) { FastRandomContext ctx; for (int i = 0; i <= 64; ++i) { if (i == 0) { // Check handling of zero. BOOST_CHECK_EQUAL(CountBits(0), 0); } else if (i < 10) { for (uint64_t j = 1 << (i - 1); (j >> i) == 0; ++j) { // Exhaustively test up to 10 bits BOOST_CHECK_EQUAL(CountBits(j), i); } } else { for (int k = 0; k < 1000; k++) { // Randomly test 1000 samples of each length above 10 bits. uint64_t j = ((uint64_t)1) << (i - 1) | ctx.randbits(i - 1); BOOST_CHECK_EQUAL(CountBits(j), i); } } } } BOOST_AUTO_TEST_SUITE_END()
[ "info.tanzanite.coin@gmail.com" ]
info.tanzanite.coin@gmail.com
a6a369719b38a4b4228b6a2a7c32dd5475a87708
bffd8e212f6c336784d8efbcf657f1538f985e25
/nullptr/valve_sdk/interfaces/i_game_event_manager.h
876ff5b3cbd7229f570af278a985a355cdec962b
[]
no_license
Galenika/nullptr
7f97a0d9fc2dadec3f243f70ec53860c327f16c0
0c2009e42a7a64b58ea4094097f79be40bd11b71
refs/heads/master
2022-06-08T21:28:03.067574
2020-05-10T13:20:28
2020-05-10T13:20:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,880
h
#pragma once #include <cstdint> #define EVENT_DEBUG_ID_INIT 42 #define EVENT_DEBUG_ID_SHUTDOWN 13 class bf_write; class bf_read; class i_game_event { public: virtual ~i_game_event() {}; virtual const char* get_name() const = 0; virtual bool is_reliable() const = 0; virtual bool is_local() const = 0; virtual bool is_empty(const char* keyname = nullptr) = 0; virtual bool get_bool(const char* keyname = nullptr, bool default_value = false) = 0; virtual int get_int(const char* keyname = nullptr, int default_value = 0) = 0; virtual uint64_t get_uint64(const char* keyname = nullptr, uint64_t default_value = 0) = 0; virtual float get_float(const char* keyname = nullptr, float default_value = 0.0f) = 0; virtual const char* get_string(const char* keyname = nullptr, const char* default_value = "") = 0; virtual const wchar_t* get_wstring(const char* keyname = nullptr, const wchar_t* default_value = L"") = 0; virtual const void* get_ptr(const char* keyname = nullptr, const void* default_values = nullptr) = 0; virtual void set_bool(const char* keyname, bool value) = 0; virtual void set_int(const char* keyname, int value) = 0; virtual void set_uint64(const char* keyname, uint64_t value) = 0; virtual void set_float(const char* keyname, float value) = 0; virtual void set_string(const char* keyname, const char* value) = 0; virtual void set_wstring(const char* keyname, const wchar_t* value) = 0; virtual void set_ptr(const char* keyname, const void* value) = 0; }; class i_game_event_listener2 { public: virtual ~i_game_event_listener2(void) {} virtual void fire_game_event(i_game_event*event) = 0; virtual int get_event_debug_id(void) = 0; public: int m_iDebugId; }; class i_game_event_manager2 { public: virtual ~i_game_event_manager2() = 0; virtual int load_events_from_file(const char *filename) = 0; virtual void reset() = 0; virtual bool add_listener(i_game_event_listener2*listener, const char *name, bool bServerSide) = 0; virtual bool find_listener(i_game_event_listener2*listener, const char *name) = 0; virtual int remove_listener(i_game_event_listener2*listener) = 0; virtual i_game_event* create_event(const char *name, bool bForce, unsigned int dwUnknown) = 0; virtual bool fire_event(i_game_event*event, bool bDontBroadcast = false) = 0; virtual bool fire_event_client_side(i_game_event*event) = 0; virtual i_game_event* duplicate_event(i_game_event*event) = 0; virtual void free_event(i_game_event*event) = 0; virtual bool serialize_event(i_game_event*event, bf_write *buf) = 0; virtual i_game_event* unserialize_event(bf_read *buf) = 0; };
[ "azaza.mail.ru63@gmail.com" ]
azaza.mail.ru63@gmail.com
2154a059b9994d4c9605031d1114d1e9c5a8c27d
df2ef1f29dfa66a221bf829c6037fcbfdb7d6193
/src/qt/rpcconsole.cpp
a95529eb9e416a52bd062099b09e121e31433607
[ "MIT" ]
permissive
gmccoin2018/gmccoin
1c72e005e9407e6c167c66d7b4c9a2f77f50a303
a508207358f0d0a1d61cc314d59c9d94f95b5c32
refs/heads/master
2021-08-29T15:47:04.092651
2017-12-14T06:37:43
2017-12-14T06:37:43
112,313,788
11
3
null
null
null
null
UTF-8
C++
false
false
14,506
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the gmccoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
[ "quyenduy@icsc.vn" ]
quyenduy@icsc.vn
0ef246242c452d20a4f7be4f5581822be493074b
8dc84558f0058d90dfc4955e905dab1b22d12c08
/chrome/browser/extensions/api/image_writer_private/test_utils.h
1031b57f7fa41b2b7c5a19cf80b6e6bc9d77720d
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
meniossin/src
42a95cc6c4a9c71d43d62bc4311224ca1fd61e03
44f73f7e76119e5ab415d4593ac66485e65d700a
refs/heads/master
2022-12-16T20:17:03.747113
2020-09-03T10:43:12
2020-09-03T10:43:12
263,710,168
1
0
BSD-3-Clause
2020-05-13T18:20:09
2020-05-13T18:20:08
null
UTF-8
C++
false
false
7,353
h
// Copyright 2013 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. #ifndef CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_TEST_UTILS_H_ #define CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_TEST_UTILS_H_ #include <stdint.h> #include <memory> #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/test/scoped_task_environment.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/image_writer_private/image_writer_utility_client.h" #include "chrome/browser/extensions/api/image_writer_private/operation_manager.h" #include "content/public/test/test_browser_thread_bundle.h" #include "content/public/test/test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_CHROMEOS) #include "chromeos/disks/disk_mount_manager.h" #include "chromeos/disks/mock_disk_mount_manager.h" #endif namespace extensions { namespace image_writer { const char kDummyExtensionId[] = "DummyExtension"; // Default file size to use in tests. Currently 32kB. const int kTestFileSize = 32 * 1024; // Pattern to use in the image file. const int kImagePattern = 0x55555555; // 01010101 // Pattern to use in the device file. const int kDevicePattern = 0xAAAAAAAA; // 10101010 // Disk file system type const char kTestFileSystemType[] = "vfat"; // A mock around the operation manager for tracking callbacks. Note that there // are non-virtual methods on this class that should not be called in tests. class MockOperationManager : public OperationManager { public: explicit MockOperationManager(content::BrowserContext* context); ~MockOperationManager() override; MOCK_METHOD3(OnProgress, void(const ExtensionId& extension_id, image_writer_api::Stage stage, int progress)); // Callback for completion events. MOCK_METHOD1(OnComplete, void(const std::string& extension_id)); // Callback for error events. MOCK_METHOD4(OnError, void(const ExtensionId& extension_id, image_writer_api::Stage stage, int progress, const std::string& error_message)); }; #if defined(OS_CHROMEOS) // A fake for the DiskMountManager that will successfully call the unmount // callback. class FakeDiskMountManager : public chromeos::disks::MockDiskMountManager { public: FakeDiskMountManager(); ~FakeDiskMountManager() override; void UnmountDeviceRecursively( const std::string& device_path, const UnmountDeviceRecursivelyCallbackType& callback) override; private: DiskMap disks_; }; #endif struct SimulateProgressInfo { SimulateProgressInfo(const std::vector<int>& progress_list, bool will_succeed); ~SimulateProgressInfo(); SimulateProgressInfo(const SimulateProgressInfo&); std::vector<int> progress_list; bool will_succeed; }; class FakeImageWriterClient : public ImageWriterUtilityClient { public: FakeImageWriterClient(); void Write(const ProgressCallback& progress_callback, const SuccessCallback& success_callback, const ErrorCallback& error_callback, const base::FilePath& source, const base::FilePath& target) override; void Verify(const ProgressCallback& progress_callback, const SuccessCallback& success_callback, const ErrorCallback& error_callback, const base::FilePath& source, const base::FilePath& target) override; void Cancel(const CancelCallback& cancel_callback) override; void Shutdown() override; // Issues Operation::Progress() calls with items in |progress_list| on // Operation Write(). Sends Operation::Success() iff |will_succeed| is true, // otherwise issues an error. void SimulateProgressOnWrite(const std::vector<int>& progress_list, bool will_succeed); // Same as SimulateProgressOnWrite, but applies to Operation::VerifyWrite(). void SimulateProgressOnVerifyWrite(const std::vector<int>& progress_list, bool will_succeed); // Triggers the progress callback. void Progress(int64_t progress); // Triggers the success callback. void Success(); // Triggers the error callback. void Error(const std::string& message); // Triggers the cancel callback. void Cancel(); protected: ~FakeImageWriterClient() override; private: void SimulateProgressAndCompletion(const SimulateProgressInfo& info); ProgressCallback progress_callback_; SuccessCallback success_callback_; ErrorCallback error_callback_; CancelCallback cancel_callback_; base::Optional<SimulateProgressInfo> simulate_on_write_; base::Optional<SimulateProgressInfo> simulate_on_verify_; }; class ImageWriterTestUtils { public: ImageWriterTestUtils(); virtual ~ImageWriterTestUtils(); #if !defined(OS_CHROMEOS) using UtilityClientCreationCallback = base::OnceCallback<void(FakeImageWriterClient*)>; void RunOnUtilityClientCreation(UtilityClientCreationCallback callback); // Called when an instance of utility client is created. void OnUtilityClientCreated(FakeImageWriterClient* client); #endif // Verifies that the data in image_path was written to the file at // device_path. This is different from base::ContentsEqual because the device // may be larger than the image. bool ImageWrittenToDevice(); // Fills |file| with |length| bytes of |pattern|, overwriting any existing // data. bool FillFile(const base::FilePath& file, const int pattern, const int length); // Set up the test utils, creating temporary folders and such. // Note that browser tests should use the alternate form and pass "true" as an // argument. virtual void SetUp(); // Set up the test utils, creating temporary folders and such. If // |is_browser_test| is true then it will use alternate initialization // appropriate for a browser test. This should be run in // |SetUpInProcessBrowserTestFixture|. virtual void SetUp(bool is_browser_test); virtual void TearDown(); const base::FilePath& GetTempDir(); const base::FilePath& GetImagePath(); const base::FilePath& GetDevicePath(); protected: base::ScopedTempDir temp_dir_; base::FilePath test_image_path_; base::FilePath test_device_path_; #if !defined(OS_CHROMEOS) scoped_refptr<FakeImageWriterClient> client_; ImageWriterUtilityClient::ImageWriterUtilityClientFactory utility_client_factory_; base::OnceCallback<void(FakeImageWriterClient*)> client_creation_callback_; #endif }; // Base class for unit tests that manages creating image and device files. class ImageWriterUnitTestBase : public testing::Test { protected: ImageWriterUnitTestBase(); ~ImageWriterUnitTestBase() override; void SetUp() override; void TearDown() override; ImageWriterTestUtils test_utils_; base::test::ScopedTaskEnvironment scoped_task_environment_; private: content::TestBrowserThreadBundle thread_bundle_; }; } // namespace image_writer } // namespace extensions #endif // CHROME_BROWSER_EXTENSIONS_API_IMAGE_WRITER_PRIVATE_TEST_UTILS_H_
[ "arnaud@geometry.ee" ]
arnaud@geometry.ee
aeb68034827f28e816fc50ab5d78b96d030945fa
9a1b1aed12d3cfd9d52f21bf1a77f26cf99cc01b
/RayTracers/scene.cpp
32eabd73d11fb57d9ea259872cbe5e4431b6de46
[]
no_license
bhbosman/raytracer
41d4767318f3a6e625206131e2b11fc7f663987b
3882c4619e76e2f61dfdf2c745d9522edea02d37
refs/heads/master
2021-01-03T12:52:10.023435
2020-07-06T09:17:31
2020-07-06T09:17:31
39,560,985
0
0
null
null
null
null
UTF-8
C++
false
false
3,127
cpp
#include "scene.h" #include "plane.h" #include "rotation.h" #include "normalscene.h" Scene::Scene() { } Scene::~Scene() { } void Scene::ClearAll() { ClearPointLights(); ClearScene(); } void Scene::ClearPointLights() { m_PointLights.clear(); } void Scene::ClearScene() { m_PointLights.clear(); } void Scene::AddSceneObject(SceneObject *object) { SceneObject::ptr x(object); AddSceneObject(x); } void NormalScene::AddSceneObject(const SceneObject::ptr& object) { m_VisualObjects.push_back(object); } void Scene::AddPointLight(PointLight *object) { AddPointLight(PointLight::ptr(object)); } void Scene::AddPointLight(const PointLight::ptr &object) { m_PointLights.push_back(object); } void Scene::Rotate(const Vector &axis, const double degrees, const Vector& origin) const { Matrix M = Rotation::RotationAroundAxisAtOrigin(axis, degrees, origin); this->Rotate(M); } void Scene::scale(const double scale) const { Matrix M = MatrixHelper::Scale(scale); this->Rotate(M); } void NormalScene::Rotate(const Matrix &rotationMatrix) const { for( SceneObject::ptr_vec::const_iterator it = m_VisualObjects.begin(); it != m_VisualObjects.end(); ++it) { const SceneObject::ptr& entry = (*it); entry->Rotate(rotationMatrix); } } const SceneObject::ptr_vec &NormalScene::VisualObjects() const { return m_VisualObjects; } const PointLight::ptr_vec &Scene::PointLights() const { return m_PointLights; } InterSectionType Scene::SendRayToScene(const Ray &ray) const { IntersectionCtx ctx(ray.direction(), ray.origin()); return SendRayToScene(ctx, ray); } InterSectionType Scene::SendRayToScene(IntersectionCtx& ctx, const Ray &ray) const { InterSectionType smallest = InterSectionType_No; for( SceneObject::ptr_vec::const_iterator it = VisualObjects().begin(); it != VisualObjects().end(); ++it) { const SceneObject& entry = *(*it); IntersectionCtx ctx_local(ray.direction(), ray.origin()); InterSectionType interSection = entry.intersect(ctx_local, ray); if (interSection != InterSectionType_No) { if (ctx_local.time() > 1e-7) { switch (interSection) { case InterSectionType_Outside: if(ctx_local.time() < ctx.time()) { ctx.Assign( ctx_local.time(), ctx_local.sceneObject(), ctx_local.normal(), ctx_local.interSectionType(), ctx_local.surfaceD(), ctx_local.colorCalculation()); smallest = interSection; } break; case InterSectionType_Inside: break; default: break; } } } } return smallest; }
[ "bhbosman@gmail.com" ]
bhbosman@gmail.com
1f0217dd661a460c11e156a8801b3e3b97e1d500
9fad4848e43f4487730185e4f50e05a044f865ab
/src/ui/base/ime/ime_input_context_handler_interface.h
b8fbb2b358be9366e128c47a0e0293e387adef0a
[ "BSD-3-Clause" ]
permissive
dummas2008/chromium
d1b30da64f0630823cb97f58ec82825998dbb93e
82d2e84ce3ed8a00dc26c948219192c3229dfdaa
refs/heads/master
2020-12-31T07:18:45.026190
2016-04-14T03:17:45
2016-04-14T03:17:45
56,194,439
4
0
null
null
null
null
UTF-8
C++
false
false
1,183
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_BASE_IME_IME_INPUT_CONTEXT_HANDLER_INTERFACE_H_ #define UI_BASE_IME_IME_INPUT_CONTEXT_HANDLER_INTERFACE_H_ #include <stdint.h> #include <string> #include "ui/base/ime/composition_text.h" #include "ui/base/ime/ui_base_ime_export.h" #include "ui/events/event.h" namespace ui { class UI_BASE_IME_EXPORT IMEInputContextHandlerInterface { public: // Called when the engine commit a text. virtual void CommitText(const std::string& text) = 0; // Called when the engine updates composition text. virtual void UpdateCompositionText(const CompositionText& text, uint32_t cursor_pos, bool visible) = 0; // Called when the engine request deleting surrounding string. virtual void DeleteSurroundingText(int32_t offset, uint32_t length) = 0; // Called when the engine sends a key event. virtual void SendKeyEvent(KeyEvent* event) = 0; }; } // namespace ui #endif // UI_BASE_IME_IME_INPUT_CONTEXT_HANDLER_INTERFACE_H_
[ "dummas@163.com" ]
dummas@163.com
7144e6c0de233a05cc1473b222cbb6d747e80003
de21acd764c4f053bb884b4b696c06a0133e439f
/Engine/Game.cpp
58196444779117c89c5d8e625a20b249047dc216
[]
no_license
DEM0N194/Pong
69f079ecb7327baf0c36979ebc98f32853821300
471d414bfa664a49fc019df55c6618039fb638dc
refs/heads/master
2021-01-19T16:58:18.671831
2017-05-01T01:50:11
2017-05-01T01:50:11
88,294,059
0
0
null
null
null
null
UTF-8
C++
false
false
3,936
cpp
#include "MainWindow.h" #include "Game.h" //!? If you think paging some data from disk into RAM is slow, //!? try paging it into a simian cerebrum over a pair of optical nerves. //!? - gameprogrammingpatterns.com Game::Game( MainWindow& wnd ) :wnd( wnd ) ,gfx( wnd ) ,player1(10) ,player2(gfx.ScreenWidth - Paddle::width - 10) ,bullet1(10) ,bullet2(gfx.ScreenWidth - Paddle::width - 10) { p1score.SetPostion(gfx.ScreenWidth/2 - 50, 10); p1score.AlignMiddle(); p1score.SetNumOf0(1); p2score.SetPostion(gfx.ScreenWidth/2 + 50, 10); p2score.AlignMiddle(); p2score.SetNumOf0(1); } void Game::Go() { gfx.BeginFrame(); UpdateModel(); ComposeFrame(); gfx.EndFrame(); } void Game::UpdateModel() { float dt = ft.Mark(); if (isPlaying) { //! ----------player1 update model---------- if (wnd.kbd.KeyIsPressed(0x57)) { player1.MoveUp(dt); } if (wnd.kbd.KeyIsPressed(0x53)) { player1.MoveDown(dt); } player1.Update(); //! ----------player2 update model---------- if (wnd.kbd.KeyIsPressed(VK_UP)) { player2.MoveUp(dt); } if (wnd.kbd.KeyIsPressed(VK_DOWN)) { player2.MoveDown(dt); } player2.Update(); //! ----------bullet1 update model---------- if (wnd.kbd.KeyIsPressed(0x44)) { if (!bullet1.IsActive()) { bullet1.Shoot(10 * 60, player1.GetY()); } } if (bullet1.IsActive()) { bullet1.Update(dt); bullet1.Collision(&player2); bullet1.Collision(&ball); } //! ----------bullet2 update model---------- if (wnd.kbd.KeyIsPressed(VK_LEFT)) { if (!bullet2.IsActive()) { bullet2.Shoot(-10 * 60, player2.GetY()); } } if (bullet2.IsActive()) { bullet2.Update(dt); bullet2.Collision(&player1); bullet2.Collision(&ball); } if (bullet1.IsActive() && bullet2.IsActive()) { if (bullet1.GetX() - Projectile::width / 2 <= bullet2.GetX() + Projectile::width / 2 && bullet1.GetX() + Projectile::width / 2 >= bullet2.GetX() - Projectile::width / 2 && bullet1.GetY() - Projectile::height / 2 <= bullet2.GetY() + Projectile::height / 2 && bullet1.GetY() + Projectile::height / 2 >= bullet2.GetY() - Projectile::height / 2) { bullet1.StopBullet(); bullet2.StopBullet(); } } //! ----------ball update model---------- ball.Collision(&player1); ball.Collision(&player2); switch (ball.Update(dt)) { case 1: p1score++; isPlaying = false; player1.Reset(); player2.Reset(); bullet1.StopBullet(); bullet2.StopBullet(); break; case 2: p2score++; isPlaying = false; player1.Reset(); player2.Reset(); bullet1.StopBullet(); bullet2.StopBullet(); break; } } else { if (wnd.kbd.KeyIsPressed(VK_SPACE)) { isPlaying = true; ball.RandDirection(); } } } void Game::ComposeFrame() { DrawPaddle(&player1); DrawPaddle(&player2); DrawBall(&ball); if (bullet1.IsActive()) DrawBullet(&bullet1); if (bullet2.IsActive()) DrawBullet(&bullet2); p1score.Draw(gfx); p2score.Draw(gfx); gfx.chDash(gfx.ScreenWidth/2-10, 15, Colors::White); } void Game::DrawPaddle(Paddle *paddle) { for (int i = paddle->GetY() - paddle->GetHeight()/2; i <= paddle->GetY() + paddle->GetHeight()/2; i++) { for (int j = paddle->GetX(); j < paddle->GetX() + Paddle::width; j++) { gfx.PutPixel(j, i, 255, 255, 255); } } } void Game::DrawBall(Ball *ball) { for (int i = ball->GetY() - Ball::height/2; i < ball->GetY() + Ball::height/2; i++) { for (int j = ball->GetX() - Ball::width/2; j < ball->GetX() + Ball::width/2; j++) { gfx.PutPixel(j, i, 255, 255, 255); } } } void Game::DrawBullet(Projectile *bullet) { for (int i = bullet->GetY() - Projectile::height/2; i < bullet->GetY() + Projectile::height/2; i++) { for (int j = bullet->GetX() - Projectile::width/2; j < bullet->GetX() + Projectile::width/2; j++) { gfx.PutPixel(j, i, 100, 100, 100); } } }
[ "kevinlacko.kl@gmail.com" ]
kevinlacko.kl@gmail.com
6f05efda44448dcd00c992ef246e62e3a960125b
c83475fec6e55b9d23588482438536fa47d5a384
/GameEngine/tower.hh
737705e260f689218a869e56bf802c08a8be78ee
[]
no_license
Belphemur/Organ-Defence
8a4da36663111f61b4dbc4f84f83901bcf647518
f51b4dc131323d3e0101f1ee8397c27a06341527
refs/heads/master
2016-09-10T10:00:48.830968
2014-07-27T13:51:56
2014-07-27T13:51:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
856
hh
#ifndef _TOWER_H_ #define _TOWER_H_ #include "aiActor.hh" #include <map> using std::map; class Tower : public AiActor{ unsigned timeout; public: Tower(Drawable_Type img, double x, double y, unsigned r, short health, Weapon* w, int timeout) : AiActor(img, x, y, r, PLAYER_TEAM, health, w, 0), timeout(timeout) {} virtual ~Tower() {} bool tick(); }; class TowerFactory : public ActorFactory{ static map<string, TowerFactory*> towerFactories; unsigned timeout; void make(double x, double y); static TowerFactory* load(string name); public: TowerFactory(unsigned r, Drawable_Type img, string weaponName, short health, string brainName, int timeout) : ActorFactory(r, img, PLAYER_TEAM, weaponName, health, 0, brainName), timeout(timeout) {} static void create(string name, double x, double y); }; #endif /* _TOWER_H_ */
[ "antoineaf@admincmd.com" ]
antoineaf@admincmd.com
258955471de3542101821016298380c37e2ba6fe
138c9720daee27fa8e88be3f33159171833ac4a4
/src/flop.cpp
97b7e38dd3fc31e51d2b429008a24868a1de765a
[ "CC0-1.0" ]
permissive
spectromas/RackPlugins
a911c35a1169a7961d51cc65e03366409d4f848f
6c42eb5676b17acc201e625341655a37d413a8fe
refs/heads/uno
2020-07-08T09:07:14.976765
2019-08-21T17:00:33
2019-08-21T17:00:33
203,627,740
1
1
NOASSERTION
2019-08-21T17:00:34
2019-08-21T16:55:39
C++
WINDOWS-1250
C++
false
false
5,008
cpp
#include "../include/common.hpp" #include "../include/flop.hpp" void flop::process(const ProcessArgs &args) { bool hiz = params[HIZ].value > 0.1; bool compare = params[COMPAREMODE].value > 0.1; for(int k = 0; k < NUM_FLOPS; k++) { if(outputs[OUT_1 + k].isConnected() || outputs[OUTNEG_1+k].isConnected()) process(k, hiz, compare); else lights[LED_A + k].value = lights[LED_B + k].value = lights[LED_OUTNEG + k].value = lights[LED_OUT + k].value = LED_OFF; } } void flop::setOutput(int index, bool on) { lights[LED_OUT + index].value = on ? LED_ON : LED_OFF; outputs[OUT_1 + index].value = on ? LVL_ON : LVL_OFF; lights[LED_OUTNEG + index].value = on ? LED_OFF : LED_ON; outputs[OUTNEG_1 + index].value = on ? LVL_OFF : LVL_ON; } float flop::getVoltage(int index, bool hiz) { if (hiz && !inputs[index].isConnected()) { if(random::uniform() > 0.6) { float n = random::normal(); if (n > 2.1) return random::uniform() * 9.2; else if (n > 2.0) return random::uniform() * 7.0; else if (n > 1.0) return random::uniform() * 5.0; else if (n > 0.5) return random::uniform() * 2.5; else if (n < -1.0) return random::uniform() * 1.0; } return 0; } return inputs[index].getNormalVoltage(0.0); } bool flop::logicLevel(float v1, float v2, bool compare) { return compare ? fabs(v1 - v2) < std::numeric_limits<float>::epsilon() : v1 > v2; } void flop::process(int num_op, bool hiz, bool compare) { bool a_in = logicLevel(getVoltage(IN_A + num_op, hiz), params[THRESH_A + num_op].value, compare); lights[LED_A + num_op].value = a_in ? LED_ON : LED_OFF; bool b_in = logicLevel(getVoltage(IN_B + num_op, hiz), params[THRESH_B + num_op].value, compare); lights[LED_B + num_op].value = b_in ? LED_ON : LED_OFF; int trig_b = b_Trig[num_op].process(b_in); if(a_Trig[num_op].process(a_in) != 0 || trig_b != 0) { bool stat = false; switch(num_op) { case 0: stat = flipflip_SR(a_in, b_in); break; case 1: stat = flipflip_JK(a_in, b_in); break; case 2: stat = flipflip_T(a_in, b_in, trig_b); break; case 3: stat = flipflip_D(a_in, b_in, trig_b); break; } setOutput(num_op, stat); } } bool flop::flipflip_SR(bool s, bool r) { /* s=0 e r=1 il flip-flop si resetta, cioč porta a 0 il valore della variabile d'uscita q s=1 e r=0 il flip-flop si setta cioč porta a 1 il valore della variabile d'uscita q s=0 e r=0 il flip-flop conserva, cioč mantiene inalterato s=1 e r=1 non viene utilizzata in quanto instabile */ if(s) return r ? (random::uniform() > 0.5) /* s=1 e r=1: instabile! */ : (sr_state = true) /* s=1 e r=0: set*/; else return r ? (sr_state = false) /* s=0 e r=1: reset! */ : sr_state /* s=0 e r=0: latch*/; } bool flop::flipflip_JK(bool j, bool k) { /* j=0 e k=0 : latch j=0 e k=1 : reset j=1 e k=0 : set j=1 e k=1 : toggle */ if(j) return jk_state = (k ? !jk_state : true); else return k ? (jk_state = false) : jk_state; } bool flop::flipflip_T(bool t, bool clk_in, int trig_b) { /* t = 0 : latch t = 1 : i negato (fronte di salita) */ if(t) { if(trig_b == 1) // 1=rise, -1=fall t_state = !t_state; } return t_state; } bool flop::flipflip_D(bool d, bool clk_in, int trig_b) { if(trig_b == 1) // 1=rise, -1=fall d_state = d; return d_state; } flopWidget::flopWidget(flop *module) : ModuleWidget() { CREATE_PANEL(module, this, 14, "res/modules/flop.svg"); for(int k = 0; k < NUM_FLOPS; k++) { // A + Q addInput(createInput<PJ301GRPort>(Vec(mm2px(7.536f), yncscape(106.746-k*27.103f, 8.255)), module, flop::IN_A + k)); addParam(createParam<Davies1900hFixWhiteKnobSmall>(Vec(mm2px(22.927f), yncscape(106.874f - k * 27.103f, 8.0)), module, flop::THRESH_A + k)); addChild(createLight<SmallLight<WhiteLight>>(Vec(mm2px(18.144f), yncscape(109.786f - k * 27.103f, 2.176)), module, flop::LED_A +k)); addOutput(createOutput<PJ301WPort>(Vec(mm2px(56.753f), yncscape(106.746 - k * 27.103f, 8.255)), module, flop::OUT_1 + k)); addChild(createLight<SmallLight<RedLight>>(Vec(mm2px(53.069f), yncscape(109.786f - k * 27.103f, 2.176)), module, flop::LED_OUT + k)); // B + Qneg addInput(createInput<PJ301GRPort>(Vec(mm2px(7.536f), yncscape(94.826 - k * 27.103f, 8.255)), module, flop::IN_B + k)); addParam(createParam<Davies1900hFixWhiteKnobSmall>(Vec(mm2px(22.927f), yncscape(94.954f - k * 27.103f, 8.0)), module, flop::THRESH_B + k)); addChild(createLight<SmallLight<WhiteLight>>(Vec(mm2px(18.144f), yncscape(97.866f - k * 27.103f, 2.176)), module, flop::LED_B + k)); addOutput(createOutput<PJ301WPort>(Vec(mm2px(56.753f), yncscape(94.826 - k * 27.103f, 8.255)), module, flop::OUTNEG_1 + k)); addChild(createLight<SmallLight<RedLight>>(Vec(mm2px(53.069f), yncscape(97.866f - k * 27.103f, 2.176)), module, flop::LED_OUTNEG + k)); } addParam(createParam<TL1105HSw>(Vec(mm2px(10.228), yncscape(120.086, 4.477)), module, flop::COMPAREMODE)); addParam(createParam<TL1105HSw>(Vec(mm2px(21.197), yncscape(2.319, 4.477)), module, flop::HIZ)); }
[ "1h3x0r@gmail.com" ]
1h3x0r@gmail.com
667be202e205d62a0a45c558a7f459e7a937e818
98cca7e7dec4eaf106037f30da3ee52d761059f7
/Composite/Project.h
eaabc1549fe73e636668e687a40898236ef3f242
[]
no_license
IronTony-Stark/Design-Patterns
fb3cc70b46c3447e7bcf00e35df3e46c57ddbefe
7967799e5526347c31c1bedde77a4daece8728a1
refs/heads/master
2023-03-02T15:03:52.330846
2021-02-02T14:57:24
2021-02-02T14:57:24
261,569,351
0
1
null
2021-02-02T14:57:25
2020-05-05T19:52:54
C++
UTF-8
C++
false
false
1,275
h
// // Created by Iron Tony on 11/05/2020. // #ifndef COMPOSITE_PROJECT_H #define COMPOSITE_PROJECT_H #include <list> #include "ATodo.h" class Project : public ATodo { public: explicit Project(const std::string& todo) : ATodo(todo) {} void markAsDone() override { ATodo::markAsDone(); auto iterator = mTodos.begin(); while (iterator != mTodos.end()) (*iterator++)->markAsDone(); } std::string getTodo() override { std::string res = "\n" + ATodo::getTodo() + "\n "; auto iterator = mTodos.begin(); while (iterator != mTodos.end()) res += (*iterator++)->getTodo() + "\n "; return res; } void addTodo(ATodo* todo) { mTodos.push_back(todo); } void removeTodo(ATodo* todo) { mTodos.remove(todo); } bool checkIfDone() { auto iterator = mTodos.begin(); while (iterator != mTodos.end()) if (!(*iterator)->isDone()) return false; return true; } ~Project() override { auto iterator = mTodos.begin(); while (iterator != mTodos.end()) delete *iterator++; } private: std::list<ATodo*> mTodos; }; #endif //COMPOSITE_PROJECT_H
[ "lifegamecom1@gmail.com" ]
lifegamecom1@gmail.com
c5477cfdded5b0e0bdc06539933a3f329907ea20
7a6105f869babcd056723fe785475814852b1bc6
/Client/View/Common/Image.cpp
e7e049640eea03682befe5f213c33eb18861a874
[]
no_license
uvbs/TowerDefense
79b4eedfe331981a4f1db55de17304a6f8189377
c6c0801c31b9896b37fba301f4fcbb541c456a38
refs/heads/master
2020-03-21T10:26:38.971016
2018-03-11T22:57:17
2018-03-11T22:57:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
524
cpp
#include "Image.h" Image::Image(int posX, int posY, int width, int height, SDL_Texture *texture, Renderer &renderer) : renderer(renderer), texture(texture), button(SDL_Rect{posX, posY, width, height}) {} void Image::draw(int number, int padding) { renderer.copyEuclidean(texture, &button); } bool Image::isClicked() { return false; } bool Image::belongsToHorda(int horda) { return false; } Image::~Image() {}
[ "damiancassinotti.33@gmail.com" ]
damiancassinotti.33@gmail.com
2003408c07ce034a714e40020424475f74d97ea2
c910b384330f2724cd2364de06bd0b4ce58099f7
/blimp/engine/ui/blimp_screen.h
99858b8a949a2995f10f9c623dd1a591d3b0236c
[ "BSD-3-Clause" ]
permissive
techtonik/chromium
3d4d5cf30a1a61f2d5559ac58638ce38cf2ab5cd
319329de7edb672d11217094c5f9b77bc7af1f26
refs/heads/master
2021-10-02T05:10:56.666038
2015-10-13T20:09:21
2015-10-13T20:10:56
44,329,819
0
1
null
2015-10-15T16:14:05
2015-10-15T16:14:04
null
UTF-8
C++
false
false
1,492
h
// Copyright 2015 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. #ifndef BLIMP_ENGINE_UI_BLIMP_SCREEN_H_ #define BLIMP_ENGINE_UI_BLIMP_SCREEN_H_ #include <vector> #include "ui/gfx/display.h" #include "ui/gfx/screen.h" namespace blimp { namespace engine { // Presents the client's single screen. class BlimpScreen : public gfx::Screen { public: BlimpScreen(); ~BlimpScreen() override; // Updates the size reported by the primary display. void UpdateDisplaySize(const gfx::Size& size); // gfx::Screen implementation. gfx::Point GetCursorScreenPoint() override; gfx::NativeWindow GetWindowUnderCursor() override; gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point) override; int GetNumDisplays() const override; std::vector<gfx::Display> GetAllDisplays() const override; gfx::Display GetDisplayNearestWindow(gfx::NativeView view) const override; gfx::Display GetDisplayNearestPoint(const gfx::Point& point) const override; gfx::Display GetDisplayMatching(const gfx::Rect& match_rect) const override; gfx::Display GetPrimaryDisplay() const override; void AddObserver(gfx::DisplayObserver* observer) override; void RemoveObserver(gfx::DisplayObserver* observer) override; private: gfx::Display display_; DISALLOW_COPY_AND_ASSIGN(BlimpScreen); }; } // namespace engine } // namespace blimp #endif // BLIMP_ENGINE_UI_BLIMP_SCREEN_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
5404fb28cd334f9d795fd8ab5c36707ad07aa9d2
6c8d985d858cd14174e7d8b0ef186445be5ddbd3
/Paint Fence.cpp
c18b78ed4f8977f43ec7e8918221316b456d3787
[]
no_license
Nov11/lintcode
a18e97f8101da1eeb29634491c1b8cfb9ff3e63f
19014228ac334987444450b83dff91a24fee503f
refs/heads/master
2021-01-16T18:55:45.003549
2018-02-08T06:04:11
2018-02-08T06:04:11
100,129,682
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
class Solution { int h(int height, int k){ if(height == 1){return k - 1;} return pow(k - 1, height - 1) * k; } public: /* * @param n: non-negative integer, n posts * @param k: non-negative integer, k colors * @return: an integer, the total number of ways */ int numWays(int n, int k) { // write your code here if(n == 1){return k;} if(n == 2){return k * k;} int p3 = k; int p2 = k * k; for(int i = 3; i <= n; i++){ int p1 = p2 * (k - 1) + p3 * (k - 1); p3 = p2; p2 = p1; } return p2; } };
[ "529079634@qq.com" ]
529079634@qq.com
1833db5a72e88661f4e1206e9d057dea15c32ce9
0436bf0c8276500a3ff59093bc6d3561268134c6
/apps/rtigo3/inc/Texture.h
e97640fff865b17d1c3359b856641bafa1d5abfc
[]
no_license
NVIDIA/OptiX_Apps
7e21234c3e3c0e5237d011fc567da7f3f90e2c51
2ff552ce4b2cf0e998531899bb8b39d27e064d06
refs/heads/master
2023-08-20T02:47:58.294963
2023-08-08T10:29:36
2023-08-08T10:29:36
239,562,369
223
42
null
2023-09-04T09:31:07
2020-02-10T16:47:28
C++
UTF-8
C++
false
false
7,053
h
/* * Copyright (c) 2013-2020, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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. */ #pragma once #ifndef TEXTURE_H #define TEXTURE_H // Always include this before any OptiX headers. #include <cuda.h> #include <cuda_runtime.h> #include "inc/Picture.h" #include <string> #include <vector> // Bitfield encoding of the texture channels. // These are used to remap user format and user data to the internal format. // Each four bits hold the channel index of red, green, blue, alpha, and luminance. // (encoding >> ENC_*_SHIFT) & ENC_MASK gives the channel index if the result is less than 4. // That encoding allows to automatically swap red and blue, map luminance to RGB (not the other way round though!), // fill in alpha with input data or force it to one if required. // 49 remapper functions take care to convert the data types including fixed-point adjustments. #define ENC_MASK 0xF #define ENC_RED_SHIFT 0 #define ENC_RED_0 ( 0u << ENC_RED_SHIFT) #define ENC_RED_1 ( 1u << ENC_RED_SHIFT) #define ENC_RED_2 ( 2u << ENC_RED_SHIFT) #define ENC_RED_3 ( 3u << ENC_RED_SHIFT) #define ENC_RED_NONE (15u << ENC_RED_SHIFT) #define ENC_GREEN_SHIFT 4 #define ENC_GREEN_0 ( 0u << ENC_GREEN_SHIFT) #define ENC_GREEN_1 ( 1u << ENC_GREEN_SHIFT) #define ENC_GREEN_2 ( 2u << ENC_GREEN_SHIFT) #define ENC_GREEN_3 ( 3u << ENC_GREEN_SHIFT) #define ENC_GREEN_NONE (15u << ENC_GREEN_SHIFT) #define ENC_BLUE_SHIFT 8 #define ENC_BLUE_0 ( 0u << ENC_BLUE_SHIFT) #define ENC_BLUE_1 ( 1u << ENC_BLUE_SHIFT) #define ENC_BLUE_2 ( 2u << ENC_BLUE_SHIFT) #define ENC_BLUE_3 ( 3u << ENC_BLUE_SHIFT) #define ENC_BLUE_NONE (15u << ENC_BLUE_SHIFT) #define ENC_ALPHA_SHIFT 12 #define ENC_ALPHA_0 ( 0u << ENC_ALPHA_SHIFT) #define ENC_ALPHA_1 ( 1u << ENC_ALPHA_SHIFT) #define ENC_ALPHA_2 ( 2u << ENC_ALPHA_SHIFT) #define ENC_ALPHA_3 ( 3u << ENC_ALPHA_SHIFT) #define ENC_ALPHA_NONE (15u << ENC_ALPHA_SHIFT) #define ENC_LUM_SHIFT 16 #define ENC_LUM_0 ( 0u << ENC_LUM_SHIFT) #define ENC_LUM_1 ( 1u << ENC_LUM_SHIFT) #define ENC_LUM_2 ( 2u << ENC_LUM_SHIFT) #define ENC_LUM_3 ( 3u << ENC_LUM_SHIFT) #define ENC_LUM_NONE (15u << ENC_LUM_SHIFT) #define ENC_CHANNELS_SHIFT 20 #define ENC_CHANNELS_1 (1u << ENC_CHANNELS_SHIFT) #define ENC_CHANNELS_2 (2u << ENC_CHANNELS_SHIFT) #define ENC_CHANNELS_3 (3u << ENC_CHANNELS_SHIFT) #define ENC_CHANNELS_4 (4u << ENC_CHANNELS_SHIFT) #define ENC_TYPE_SHIFT 24 // These are indices into the remapper table. #define ENC_TYPE_CHAR ( 0u << ENC_TYPE_SHIFT) #define ENC_TYPE_UNSIGNED_CHAR ( 1u << ENC_TYPE_SHIFT) #define ENC_TYPE_SHORT ( 2u << ENC_TYPE_SHIFT) #define ENC_TYPE_UNSIGNED_SHORT ( 3u << ENC_TYPE_SHIFT) #define ENC_TYPE_INT ( 4u << ENC_TYPE_SHIFT) #define ENC_TYPE_UNSIGNED_INT ( 5u << ENC_TYPE_SHIFT) #define ENC_TYPE_FLOAT ( 6u << ENC_TYPE_SHIFT) #define ENC_TYPE_UNDEFINED (15u << ENC_TYPE_SHIFT) // Flags to indicate that special handling is required. #define ENC_MISC_SHIFT 28 #define ENC_FIXED_POINT (1u << ENC_MISC_SHIFT) #define ENC_ALPHA_ONE (2u << ENC_MISC_SHIFT) // Highest bit set means invalid encoding. #define ENC_INVALID (8u << ENC_MISC_SHIFT) class Texture { public: Texture(); ~Texture(); void setTextureDescription(CUDA_TEXTURE_DESC const& descr); void setAddressMode(CUaddress_mode s, CUaddress_mode t, CUaddress_mode r); void setFilterMode(CUfilter_mode filter, CUfilter_mode filterMipmap); void setReadMode(bool asInteger); void setSRGB(bool srgb); void setBorderColor(float r, float g, float b, float a); void setNormalizedCoords(bool normalized); void setMaxAnisotropy(unsigned int aniso); void setMipmapLevelBiasMinMax(float bias, float minimum, float maximum); bool create(const Picture* picture, const unsigned int flags); bool update(const Picture* picture); unsigned int getWidth() const; unsigned int getHeight() const; unsigned int getDepth() const; cudaTextureObject_t getTextureObject() const; // Specific to spherical environment map. // Create cumulative distribution function for importance sampling of spherical environment lights. Call last. void calculateSphericalCDF(const float* rgba); CUdeviceptr getCDF_U() const; CUdeviceptr getCDF_V() const; float getIntegral() const; private: bool create1D(const Picture* picture); bool create2D(const Picture* picture); bool create3D(const Picture* picture); bool createCube(const Picture* picture); bool createEnv(const Picture* picture); bool update1D(const Picture* picture); bool update2D(const Picture* picture); bool update3D(const Picture* picture); bool updateCube(const Picture* picture); bool updateEnv(const Picture* picture); private: unsigned int m_width; unsigned int m_height; unsigned int m_depth; unsigned int m_flags; unsigned int m_hostEncoding; unsigned int m_deviceEncoding; CUDA_ARRAY3D_DESCRIPTOR m_descArray3D; size_t m_sizeBytesPerElement; CUDA_RESOURCE_DESC m_resourceDescription; // For the final texture object creation. CUDA_TEXTURE_DESC m_textureDescription; // This contains all texture parameters which can be set individually or as a whole. CUtexObject m_textureObject; CUarray m_d_array; CUmipmappedArray m_d_mipmappedArray; // Specific to spherical environment map. CUdeviceptr m_d_envCDF_U; CUdeviceptr m_d_envCDF_V; float m_integral; }; #endif // TEXTURE_H
[ "droettger@nvidia.com" ]
droettger@nvidia.com
ac17f1b526907ba2994e015142a683e96991b9e2
8a0004cd8e31cbfa07476b659951e4b9ddd8eb6e
/pattern1.cpp
e5e727cf950cfa31bb86c2e95eb7734ae1523ea2
[ "Apache-2.0" ]
permissive
jsjose/katas-Cpp
77d5fd2d4df87d3b91056f351e3e5de42658c38b
799c3ab1ef91969c2cc5aa83f93b372fe2177dd8
refs/heads/master
2021-01-20T06:27:50.071596
2017-07-15T18:27:13
2017-07-15T18:27:13
89,881,428
1
0
null
null
null
null
UTF-8
C++
false
false
347
cpp
#include <sstream> #include <string> #include <iostream> using namespace std; //string header file and namespace are already included for you string pattern(int n){ ostringstream solPattern; int i, j; for (i = 1; i <= n; i++) { for (j = 1; j<= i; j++) solPattern << i; solPattern << endl; } return solPattern.str(); }
[ "noreply@github.com" ]
noreply@github.com
bed3a137bf30e908548321fbe2d83fe1bf172250
71192028e259a0d0aed75ede0e3f95e57be0d844
/World.h
b220fd65f272d0065aed2364f0b353d3e95362ba
[]
no_license
vHanda/Survival
9deb67b2beb02d05e8e7b005fa56347bc109b246
72fa72e633d56b160ddcbb07895fc89852886bb7
refs/heads/master
2021-01-20T04:49:58.111226
2012-02-09T14:05:38
2012-02-09T14:05:38
3,057,142
0
0
null
null
null
null
UTF-8
C++
false
false
1,632
h
/* * Survival * * Copyright (C) 2009-2011 Vishesh Handa <me@vhanda.in> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WORLD_H #define WORLD_H #include "Box2D/Box2D.h" class World { private : World(); ~World(); public : /*static b2World * getInstance() { b2AABB worldAABB; worldAABB.lowerBound.Set(-200.0f, -200.0f); worldAABB.upperBound.Set(200.0f, 200.0f); b2Vec2 gravity(0.0f, 0.0f); bool doSleep = true; static b2World world(worldAABB, gravity, doSleep); return &world; }*/ static const float ratio = 25; /* static void reset() { b2World * pWorld = World::getInstance(); b2Body* b = pWorld->GetBodyList(); while( b != NULL ) { b2Body * p = b; b = b->GetNext(); pWorld->DestroyBody( p ); } }*/ }; //#define gWorld World::getInstance() #endif
[ "handa.vish@gmail.com" ]
handa.vish@gmail.com
b77aa6404ce811c58b5dd949ef438e15142f0c60
e113e1fbe9ac49baf5431a5543e43cb5ac3aa56e
/src/entity/Bullet.cpp
aea459ecf6918cc6051f25f91d3cb54eabf9b04c
[]
no_license
ArnoTroch/SpaceInvaders
36eebce998697bf60bb6a535d54d22ba84e2f1f2
1e62402c1af4b9348e64b6a5d7566d540c4e9aef
refs/heads/master
2022-03-29T01:45:14.376066
2020-01-18T19:03:18
2020-01-18T19:03:18
222,168,661
0
0
null
null
null
null
UTF-8
C++
false
false
444
cpp
// // Created by Arno Troch on 20/12/2019. // #include "Bullet.h" entity::Bullet::Bullet(const entity::Position &position, MovingDirection direction) : Creature(position, {0.05, 0.1}, 1, 3) { if (direction == MovingDirection::UP || direction == MovingDirection::DOWN) { setMovingDirection(direction); } } std::string entity::Bullet::getResourcePath() { return entity::getResourcesDir() + "entities/bullet.png"; }
[ "arno.troch@student.uantwerpen.be" ]
arno.troch@student.uantwerpen.be
1282840f4237da94f11dd3c4a021a1607dbefa1a
dca653bb975528bd1b8ab2547f6ef4f48e15b7b7
/tags/wxPy-2.8.11.0/samples/scroll/scroll.cpp
098c34f1ea907ba10d69a19d7aa79c89549c5000
[]
no_license
czxxjtu/wxPython-1
51ca2f62ff6c01722e50742d1813f4be378c0517
6a7473c258ea4105f44e31d140ea5c0ae6bc46d8
refs/heads/master
2021-01-15T12:09:59.328778
2015-01-05T20:55:10
2015-01-05T20:55:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,939
cpp
///////////////////////////////////////////////////////////////////////////// // Name: scroll.cpp // Purpose: wxScrolledWindow sample // Author: Robert Roebling // Modified by: // Created: // RCS-ID: $Id$ // Copyright: (C) 1998 Robert Roebling, 2002 Ron Lee, 2003 Matt Gregory // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "wx/image.h" #include "wx/listctrl.h" #include "wx/sizer.h" #include "wx/log.h" const long ID_QUIT = wxID_EXIT; const long ID_ABOUT = wxID_ABOUT; const long ID_DELETE_ALL = 100; const long ID_INSERT_NEW = 101; // ---------------------------------------------------------------------- // a trivial example // ---------------------------------------------------------------------- class MySimpleFrame; class MySimpleCanvas; // MySimpleCanvas class MySimpleCanvas: public wxScrolledWindow { public: MySimpleCanvas() { } MySimpleCanvas( wxWindow *parent, wxWindowID, const wxPoint &pos, const wxSize &size ); void OnPaint( wxPaintEvent &event ); private: DECLARE_DYNAMIC_CLASS(MyCanvas) DECLARE_EVENT_TABLE() }; IMPLEMENT_DYNAMIC_CLASS(MySimpleCanvas, wxScrolledWindow) BEGIN_EVENT_TABLE(MySimpleCanvas, wxScrolledWindow) EVT_PAINT( MySimpleCanvas::OnPaint) END_EVENT_TABLE() MySimpleCanvas::MySimpleCanvas( wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size ) : wxScrolledWindow( parent, id, pos, size, wxSUNKEN_BORDER, _T("test canvas") ) { SetScrollRate( 10, 10 ); SetVirtualSize( 92, 97 ); SetBackgroundColour( *wxWHITE ); } void MySimpleCanvas::OnPaint( wxPaintEvent &WXUNUSED(event) ) { wxPaintDC dc(this); PrepareDC( dc ); dc.SetPen( *wxRED_PEN ); dc.SetBrush( *wxTRANSPARENT_BRUSH ); dc.DrawRectangle( 0,0,92,97 ); } // MySimpleFrame class MySimpleFrame: public wxFrame { public: MySimpleFrame(); void OnQuit( wxCommandEvent &event ); MySimpleCanvas *m_canvas; private: DECLARE_DYNAMIC_CLASS(MySimpleFrame) DECLARE_EVENT_TABLE() }; IMPLEMENT_DYNAMIC_CLASS( MySimpleFrame, wxFrame ) BEGIN_EVENT_TABLE(MySimpleFrame,wxFrame) EVT_MENU (ID_QUIT, MySimpleFrame::OnQuit) END_EVENT_TABLE() MySimpleFrame::MySimpleFrame() : wxFrame( (wxFrame *)NULL, wxID_ANY, _T("wxScrolledWindow sample"), wxPoint(120,120), wxSize(150,150) ) { wxMenu *file_menu = new wxMenu(); file_menu->Append( ID_QUIT, _T("E&xit\tAlt-X")); wxMenuBar *menu_bar = new wxMenuBar(); menu_bar->Append(file_menu, _T("&File")); SetMenuBar( menu_bar ); m_canvas = new MySimpleCanvas( this, wxID_ANY, wxPoint(0,0), wxSize(100,100) ); } void MySimpleFrame::OnQuit( wxCommandEvent &WXUNUSED(event) ) { Close( true ); } // ---------------------------------------------------------------------- // a complex example // ---------------------------------------------------------------------- // derived classes class MyFrame; class MyApp; // MyCanvas class MyCanvas: public wxScrolledWindow { public: MyCanvas() {} MyCanvas( wxWindow *parent, wxWindowID, const wxPoint &pos, const wxSize &size ); ~MyCanvas(){}; void OnPaint( wxPaintEvent &event ); void OnQueryPosition( wxCommandEvent &event ); void OnAddButton( wxCommandEvent &event ); void OnDeleteButton( wxCommandEvent &event ); void OnMoveButton( wxCommandEvent &event ); void OnScrollWin( wxCommandEvent &event ); void OnMouseRightDown( wxMouseEvent &event ); void OnMouseWheel( wxMouseEvent &event ); wxButton *m_button; DECLARE_DYNAMIC_CLASS(MyCanvas) DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // Autoscrolling example. // ---------------------------------------------------------------------------- // this class uses the 'virtual' size attribute along with an internal // sizer to automatically set up scrollbars as needed class MyAutoScrollWindow : public wxScrolledWindow { private: wxButton *m_button; public: MyAutoScrollWindow( wxWindow *parent ); void OnResizeClick( wxCommandEvent &WXUNUSED( event ) ); DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // MyScrolledWindow classes: examples of wxScrolledWindow usage // ---------------------------------------------------------------------------- // base class for both of them class MyScrolledWindowBase : public wxScrolledWindow { public: MyScrolledWindowBase(wxWindow *parent) : wxScrolledWindow(parent) , m_nLines( 100 ) { wxClientDC dc(this); dc.GetTextExtent(_T("Line 17"), NULL, &m_hLine); } protected: // the height of one line on screen wxCoord m_hLine; // the number of lines we draw size_t m_nLines; }; // this class does "stupid" redrawing - it redraws everything each time // and sets the scrollbar extent directly. class MyScrolledWindowDumb : public MyScrolledWindowBase { public: MyScrolledWindowDumb(wxWindow *parent) : MyScrolledWindowBase(parent) { // no horz scrolling SetScrollbars(0, m_hLine, 0, m_nLines + 1, 0, 0, true /* no refresh */); } virtual void OnDraw(wxDC& dc); }; // this class does "smart" redrawing - only redraws the lines which must be // redrawn and sets the scroll rate and virtual size to affect the // scrollbars. // // Note that this class should produce identical results to the one above. class MyScrolledWindowSmart : public MyScrolledWindowBase { public: MyScrolledWindowSmart(wxWindow *parent) : MyScrolledWindowBase(parent) { // no horz scrolling SetScrollRate( 0, m_hLine ); SetVirtualSize( wxDefaultCoord, ( m_nLines + 1 ) * m_hLine ); } virtual void OnDraw(wxDC& dc); }; // ---------------------------------------------------------------------------- // MyAutoTimedScrollingWindow: implements a text viewer with simple blocksize // selection to test auto-scrolling functionality // ---------------------------------------------------------------------------- class MyAutoTimedScrollingWindow : public wxScrolledWindow { protected: // member data // test data variables static const wxChar* sm_testData; static const int sm_lineCnt; // line count static const int sm_lineLen; // line length in characters // sizes for graphical data wxCoord m_fontH, m_fontW; // selection tracking wxPoint m_selStart; // beginning of blockwise selection wxPoint m_cursor; // end of blockwise selection (mouse position) protected: // gui stuff wxFont m_font; public: // interface MyAutoTimedScrollingWindow( wxWindow* parent ); wxRect DeviceCoordsToGraphicalChars(wxRect updRect) const; wxPoint DeviceCoordsToGraphicalChars(wxPoint pos) const; wxPoint GraphicalCharToDeviceCoords(wxPoint pos) const; wxRect LogicalCoordsToGraphicalChars(wxRect updRect) const; wxPoint LogicalCoordsToGraphicalChars(wxPoint pos) const; wxPoint GraphicalCharToLogicalCoords(wxPoint pos) const; void MyRefresh(); bool IsSelected(int chX, int chY) const; static bool IsInside(int k, int bound1, int bound2); static wxRect DCNormalize(wxCoord x, wxCoord y, wxCoord w, wxCoord h); protected: // event stuff void OnDraw(wxDC& dc); void OnMouseLeftDown(wxMouseEvent& event); void OnMouseLeftUp(wxMouseEvent& event); void OnMouseMove(wxMouseEvent& event); void OnScroll(wxScrollWinEvent& event); DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // MyFrame // ---------------------------------------------------------------------------- class MyFrame: public wxFrame { public: MyFrame(); void OnAbout( wxCommandEvent &event ); void OnQuit( wxCommandEvent &event ); void OnDeleteAll( wxCommandEvent &event ); void OnInsertNew( wxCommandEvent &event ); MyCanvas *m_canvas; wxTextCtrl *m_log; DECLARE_DYNAMIC_CLASS(MyFrame) DECLARE_EVENT_TABLE() }; // ---------------------------------------------------------------------------- // MyApp // ---------------------------------------------------------------------------- class MyApp: public wxApp { public: virtual bool OnInit(); }; // ---------------------------------------------------------------------------- // main program // ---------------------------------------------------------------------------- IMPLEMENT_APP(MyApp) // ids const long ID_ADDBUTTON = wxNewId(); const long ID_DELBUTTON = wxNewId(); const long ID_MOVEBUTTON = wxNewId(); const long ID_SCROLLWIN = wxNewId(); const long ID_QUERYPOS = wxNewId(); const long ID_NEWBUTTON = wxNewId(); // ---------------------------------------------------------------------------- // MyCanvas // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS(MyCanvas, wxScrolledWindow) BEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow) EVT_PAINT( MyCanvas::OnPaint) EVT_RIGHT_DOWN( MyCanvas::OnMouseRightDown) EVT_MOUSEWHEEL( MyCanvas::OnMouseWheel) EVT_BUTTON( ID_QUERYPOS, MyCanvas::OnQueryPosition) EVT_BUTTON( ID_ADDBUTTON, MyCanvas::OnAddButton) EVT_BUTTON( ID_DELBUTTON, MyCanvas::OnDeleteButton) EVT_BUTTON( ID_MOVEBUTTON, MyCanvas::OnMoveButton) EVT_BUTTON( ID_SCROLLWIN, MyCanvas::OnScrollWin) END_EVENT_TABLE() MyCanvas::MyCanvas( wxWindow *parent, wxWindowID id, const wxPoint &pos, const wxSize &size ) : wxScrolledWindow( parent, id, pos, size, wxSUNKEN_BORDER | wxTAB_TRAVERSAL, _T("test canvas") ) { SetScrollRate( 10, 10 ); SetVirtualSize( 500, 1000 ); (void) new wxButton( this, ID_ADDBUTTON, _T("add button"), wxPoint(10,10) ); (void) new wxButton( this, ID_DELBUTTON, _T("del button"), wxPoint(10,40) ); (void) new wxButton( this, ID_MOVEBUTTON, _T("move button"), wxPoint(150,10) ); (void) new wxButton( this, ID_SCROLLWIN, _T("scroll win"), wxPoint(250,10) ); #if 0 wxString choices[] = { "This", "is one of my", "really", "wonderful", "examples." }; m_button = new wxButton( this, ID_QUERYPOS, "Query position", wxPoint(10,110) ); (void) new wxTextCtrl( this, wxID_ANY, "wxTextCtrl", wxPoint(10,150), wxSize(80,wxDefaultCoord) ); (void) new wxRadioButton( this, wxID_ANY, "Disable", wxPoint(10,190) ); (void) new wxComboBox( this, wxID_ANY, "This", wxPoint(10,230), wxDefaultSize, 5, choices ); (void) new wxRadioBox( this, wxID_ANY, "This", wxPoint(10,310), wxDefaultSize, 5, choices, 2, wxRA_SPECIFY_COLS ); (void) new wxRadioBox( this, wxID_ANY, "This", wxPoint(10,440), wxDefaultSize, 5, choices, 2, wxRA_SPECIFY_ROWS ); wxListCtrl *m_listCtrl = new wxListCtrl( this, wxID_ANY, wxPoint(200, 110), wxSize(180, 120), wxLC_REPORT | wxSIMPLE_BORDER | wxLC_SINGLE_SEL ); m_listCtrl->InsertColumn(0, "First", wxLIST_FORMAT_LEFT, 90); m_listCtrl->InsertColumn(1, "Last", wxLIST_FORMAT_LEFT, 90); for ( int i=0; i < 30; i++) { char buf[20]; sprintf(buf, "Item %d", i); m_listCtrl->InsertItem(i, buf); } m_listCtrl->SetItemState( 3, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED ); (void) new wxListBox( this, wxID_ANY, wxPoint(260,280), wxSize(120,120), 5, choices, wxLB_ALWAYS_SB ); #endif wxPanel *test = new wxPanel( this, wxID_ANY, wxPoint(10, 110), wxSize(130,50), wxSIMPLE_BORDER | wxTAB_TRAVERSAL ); test->SetBackgroundColour( wxT("WHEAT") ); #if 0 wxButton *test2 = new wxButton( test, wxID_ANY, "Hallo", wxPoint(10,10) ); test = new wxPanel( this, wxID_ANY, wxPoint(160, 530), wxSize(130,120), wxSUNKEN_BORDER | wxTAB_TRAVERSAL ); test->SetBackgroundColour( wxT("WHEAT") ); test->SetCursor( wxCursor( wxCURSOR_NO_ENTRY ) ); test2 = new wxButton( test, wxID_ANY, "Hallo", wxPoint(10,10) ); test2->SetCursor( wxCursor( wxCURSOR_PENCIL ) ); test = new wxPanel( this, wxID_ANY, wxPoint(310, 530), wxSize(130,120), wxRAISED_BORDER | wxTAB_TRAVERSAL ); test->SetBackgroundColour( wxT("WHEAT") ); test->SetCursor( wxCursor( wxCURSOR_PENCIL ) ); test2 = new wxButton( test, wxID_ANY, "Hallo", wxPoint(10,10) ); test2->SetCursor( wxCursor( wxCURSOR_NO_ENTRY ) ); #endif SetBackgroundColour( wxT("BLUE") ); SetCursor( wxCursor( wxCURSOR_IBEAM ) ); } void MyCanvas::OnMouseRightDown( wxMouseEvent &event ) { wxPoint pt( event.GetPosition() ); int x,y; CalcUnscrolledPosition( pt.x, pt.y, &x, &y ); wxLogMessage( wxT("Mouse down event at: %d %d, scrolled: %d %d"), pt.x, pt.y, x, y ); } void MyCanvas::OnMouseWheel( wxMouseEvent &event ) { wxPoint pt( event.GetPosition() ); int x,y; CalcUnscrolledPosition( pt.x, pt.y, &x, &y ); wxLogMessage( wxT("Mouse wheel event at: %d %d, scrolled: %d %d\n") wxT("Rotation: %d, delta = %d"), pt.x, pt.y, x, y, event.GetWheelRotation(), event.GetWheelDelta() ); event.Skip(); } void MyCanvas::OnPaint( wxPaintEvent &WXUNUSED(event) ) { wxPaintDC dc( this ); PrepareDC( dc ); dc.DrawText( _T("Press mouse button to test calculations!"), 160, 50 ); dc.DrawText( _T("Some text"), 140, 140 ); dc.DrawRectangle( 100, 160, 200, 200 ); } void MyCanvas::OnQueryPosition( wxCommandEvent &WXUNUSED(event) ) { wxPoint pt( m_button->GetPosition() ); wxLogMessage( wxT("Position of \"Query position\" is %d %d"), pt.x, pt.y ); pt = ClientToScreen( pt ); wxLogMessage( wxT("Position of \"Query position\" on screen is %d %d"), pt.x, pt.y ); } void MyCanvas::OnAddButton( wxCommandEvent &WXUNUSED(event) ) { wxLogMessage( wxT("Inserting button at position 10,70...") ); wxButton *button = new wxButton( this, ID_NEWBUTTON, wxT("new button"), wxPoint(10,70), wxSize(80,25) ); wxPoint pt( button->GetPosition() ); wxLogMessage( wxT("-> Position after inserting %d %d"), pt.x, pt.y ); } void MyCanvas::OnDeleteButton( wxCommandEvent &WXUNUSED(event) ) { wxLogMessage( wxT("Deleting button inserted with \"Add button\"...") ); wxWindow *win = FindWindow( ID_NEWBUTTON ); if (win) win->Destroy(); else wxLogMessage( wxT("-> No window with id = ID_NEWBUTTON found.") ); } void MyCanvas::OnMoveButton( wxCommandEvent &event ) { wxLogMessage( wxT("Moving button 10 pixels downward..") ); wxWindow *win = FindWindow( event.GetId() ); wxPoint pt( win->GetPosition() ); wxLogMessage( wxT("-> Position before move is %d %d"), pt.x, pt.y ); win->Move( wxDefaultCoord, pt.y + 10 ); pt = win->GetPosition(); wxLogMessage( wxT("-> Position after move is %d %d"), pt.x, pt.y ); } void MyCanvas::OnScrollWin( wxCommandEvent &WXUNUSED(event) ) { wxLogMessage( wxT("Scrolling 2 units up.\nThe white square and the controls should move equally!") ); int x,y; GetViewStart( &x, &y ); Scroll( wxDefaultCoord, y+2 ); } // ---------------------------------------------------------------------------- // MyAutoScrollWindow // ---------------------------------------------------------------------------- const long ID_RESIZEBUTTON = wxNewId(); const wxSize SMALL_BUTTON( 100, 50 ); const wxSize LARGE_BUTTON( 300, 100 ); BEGIN_EVENT_TABLE( MyAutoScrollWindow, wxScrolledWindow) EVT_BUTTON( ID_RESIZEBUTTON, MyAutoScrollWindow::OnResizeClick) END_EVENT_TABLE() MyAutoScrollWindow::MyAutoScrollWindow( wxWindow *parent ) : wxScrolledWindow( parent, -1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER|wxScrolledWindowStyle ) { SetBackgroundColour( wxT("GREEN") ); // Set the rate we'd like for scrolling. SetScrollRate( 5, 5 ); // Populate a sizer with a 'resizing' button and some // other static decoration wxFlexGridSizer *innersizer = new wxFlexGridSizer( 2, 2 ); m_button = new wxButton( this, ID_RESIZEBUTTON, _T("Press me"), wxDefaultPosition, SMALL_BUTTON ); // We need to do this here, because wxADJUST_MINSIZE below // will cause the initial size to be ignored for Best/Min size. // It would be nice to fix the sizers to handle this a little // more cleanly. m_button->SetSizeHints( SMALL_BUTTON.GetWidth(), SMALL_BUTTON.GetHeight() ); innersizer->Add( m_button, 0, wxALIGN_CENTER | wxALL | wxADJUST_MINSIZE, 20 ); innersizer->Add( new wxStaticText( this, wxID_ANY, _T("This is just") ), 0, wxALIGN_CENTER ); innersizer->Add( new wxStaticText( this, wxID_ANY, _T("some decoration") ), 0, wxALIGN_CENTER ); innersizer->Add( new wxStaticText( this, wxID_ANY, _T("for you to scroll...") ), 0, wxALIGN_CENTER ); // Then use the sizer to set the scrolled region size. SetSizer( innersizer ); } void MyAutoScrollWindow::OnResizeClick( wxCommandEvent &WXUNUSED( event ) ) { // Arbitrarily resize the button to change the minimum size of // the (scrolled) sizer. if( m_button->GetSize() == SMALL_BUTTON ) m_button->SetSizeHints( LARGE_BUTTON.GetWidth(), LARGE_BUTTON.GetHeight() ); else m_button->SetSizeHints( SMALL_BUTTON.GetWidth(), SMALL_BUTTON.GetHeight() ); // Force update layout and scrollbars, since nothing we do here // necessarily generates a size event which would do it for us. FitInside(); } // ---------------------------------------------------------------------------- // MyFrame // ---------------------------------------------------------------------------- IMPLEMENT_DYNAMIC_CLASS( MyFrame, wxFrame ) BEGIN_EVENT_TABLE(MyFrame,wxFrame) EVT_MENU (ID_DELETE_ALL, MyFrame::OnDeleteAll) EVT_MENU (ID_INSERT_NEW, MyFrame::OnInsertNew) EVT_MENU (ID_ABOUT, MyFrame::OnAbout) EVT_MENU (ID_QUIT, MyFrame::OnQuit) END_EVENT_TABLE() MyFrame::MyFrame() : wxFrame( (wxFrame *)NULL, wxID_ANY, _T("wxScrolledWindow sample"), wxPoint(20,20), wxSize(800,500) ) { wxMenu *file_menu = new wxMenu(); file_menu->Append( ID_DELETE_ALL, _T("Delete all")); file_menu->Append( ID_INSERT_NEW, _T("Insert new")); file_menu->Append( ID_ABOUT, _T("&About..")); file_menu->Append( ID_QUIT, _T("E&xit\tAlt-X")); wxMenuBar *menu_bar = new wxMenuBar(); menu_bar->Append(file_menu, _T("&File")); SetMenuBar( menu_bar ); #if wxUSE_STATUSBAR CreateStatusBar(2); int widths[] = { -1, 100 }; SetStatusWidths( 2, widths ); #endif // wxUSE_STATUSBAR wxBoxSizer *topsizer = new wxBoxSizer( wxHORIZONTAL ); // subsizer splits topsizer down the middle wxBoxSizer *subsizer = new wxBoxSizer( wxVERTICAL ); // Setting an explicit size here is superfluous, it will be overridden // by the sizer in any case. m_canvas = new MyCanvas( this, wxID_ANY, wxPoint(0,0), wxSize(100,100) ); // This is done with ScrollRate/VirtualSize in MyCanvas ctor now, // both should produce identical results. //m_canvas->SetScrollbars( 10, 10, 50, 100 ); subsizer->Add( m_canvas, 1, wxEXPAND ); subsizer->Add( new MyAutoScrollWindow( this ), 1, wxEXPAND ); wxSizer *sizerBtm = new wxBoxSizer(wxHORIZONTAL); sizerBtm->Add( new MyScrolledWindowDumb(this), 1, wxEXPAND ); sizerBtm->Add( new MyScrolledWindowSmart(this), 1, wxEXPAND ); subsizer->Add( sizerBtm, 1, wxEXPAND ); topsizer->Add( subsizer, 1, wxEXPAND ); topsizer->Add( new MyAutoTimedScrollingWindow( this ), 1, wxEXPAND ); SetSizer( topsizer ); } void MyFrame::OnDeleteAll( wxCommandEvent &WXUNUSED(event) ) { m_canvas->DestroyChildren(); } void MyFrame::OnInsertNew( wxCommandEvent &WXUNUSED(event) ) { (void)new wxButton( m_canvas, wxID_ANY, _T("Hello"), wxPoint(100,100) ); } void MyFrame::OnQuit( wxCommandEvent &WXUNUSED(event) ) { Close( true ); } void MyFrame::OnAbout( wxCommandEvent &WXUNUSED(event) ) { (void)wxMessageBox( _T("wxScroll demo\n") _T("Robert Roebling (c) 1998\n") _T("Autoscrolling examples\n") _T("Ron Lee (c) 2002\n") _T("Auto-timed-scrolling example\n") _T("Matt Gregory (c) 2003\n"), _T("About wxScroll Demo"), wxICON_INFORMATION | wxOK ); } //----------------------------------------------------------------------------- // MyApp //----------------------------------------------------------------------------- bool MyApp::OnInit() { wxFrame *frame = new MyFrame(); frame->Show( true ); frame = new MySimpleFrame(); frame->Show(); return true; } // ---------------------------------------------------------------------------- // MyScrolledWindowXXX // ---------------------------------------------------------------------------- void MyScrolledWindowDumb::OnDraw(wxDC& dc) { // this is useful to see which lines are redrawn static size_t s_redrawCount = 0; dc.SetTextForeground(s_redrawCount++ % 2 ? *wxRED : *wxBLUE); wxCoord y = 0; for ( size_t line = 0; line < m_nLines; line++ ) { wxCoord yPhys; CalcScrolledPosition(0, y, NULL, &yPhys); dc.DrawText(wxString::Format(_T("Line %u (logical %d, physical %d)"), unsigned(line), y, yPhys), 0, y); y += m_hLine; } } void MyScrolledWindowSmart::OnDraw(wxDC& dc) { // this is useful to see which lines are redrawn static size_t s_redrawCount = 0; dc.SetTextForeground(s_redrawCount++ % 2 ? *wxRED : *wxBLUE); // update region is always in device coords, translate to logical ones wxRect rectUpdate = GetUpdateRegion().GetBox(); CalcUnscrolledPosition(rectUpdate.x, rectUpdate.y, &rectUpdate.x, &rectUpdate.y); size_t lineFrom = rectUpdate.y / m_hLine, lineTo = rectUpdate.GetBottom() / m_hLine; if ( lineTo > m_nLines - 1) lineTo = m_nLines - 1; wxCoord y = lineFrom*m_hLine; for ( size_t line = lineFrom; line <= lineTo; line++ ) { wxCoord yPhys; CalcScrolledPosition(0, y, NULL, &yPhys); dc.DrawText(wxString::Format(_T("Line %u (logical %d, physical %d)"), unsigned(line), y, yPhys), 0, y); y += m_hLine; } } // ---------------------------------------------------------------------------- // MyAutoTimedScrollingWindow // ---------------------------------------------------------------------------- BEGIN_EVENT_TABLE(MyAutoTimedScrollingWindow, wxScrolledWindow) EVT_LEFT_DOWN(MyAutoTimedScrollingWindow::OnMouseLeftDown) EVT_LEFT_UP(MyAutoTimedScrollingWindow::OnMouseLeftUp) EVT_MOTION(MyAutoTimedScrollingWindow::OnMouseMove) EVT_SCROLLWIN(MyAutoTimedScrollingWindow::OnScroll) END_EVENT_TABLE() MyAutoTimedScrollingWindow::MyAutoTimedScrollingWindow(wxWindow* parent) : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize //, wxSUNKEN_BORDER) // can't seem to do it this way , wxVSCROLL | wxHSCROLL | wxSUNKEN_BORDER) , m_selStart(-1, -1), m_cursor(-1, -1) , m_font(9, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL , wxFONTWEIGHT_NORMAL) { wxClientDC dc(this); // query dc for text size dc.SetFont(m_font); dc.GetTextExtent(wxString(_T("A")), &m_fontW, &m_fontH); // set up the virtual window SetScrollbars(m_fontW, m_fontH, sm_lineLen, sm_lineCnt); } wxRect MyAutoTimedScrollingWindow::DeviceCoordsToGraphicalChars (wxRect updRect) const { wxPoint pos(updRect.GetPosition()); pos = DeviceCoordsToGraphicalChars(pos); updRect.x = pos.x; updRect.y = pos.y; updRect.width /= m_fontW; updRect.height /= m_fontH; // the *CoordsToGraphicalChars() funcs round down to upper-left corner, // so an off-by-one correction is needed ++updRect.width; // kludge ++updRect.height; // kludge return updRect; } wxPoint MyAutoTimedScrollingWindow::DeviceCoordsToGraphicalChars (wxPoint pos) const { pos.x /= m_fontW; pos.y /= m_fontH; int vX, vY; GetViewStart(&vX, &vY); pos.x += vX; pos.y += vY; return pos; } wxPoint MyAutoTimedScrollingWindow::GraphicalCharToDeviceCoords (wxPoint pos) const { int vX, vY; GetViewStart(&vX, &vY); pos.x -= vX; pos.y -= vY; pos.x *= m_fontW; pos.y *= m_fontH; return pos; } wxRect MyAutoTimedScrollingWindow::LogicalCoordsToGraphicalChars (wxRect updRect) const { wxPoint pos(updRect.GetPosition()); pos = LogicalCoordsToGraphicalChars(pos); updRect.x = pos.x; updRect.y = pos.y; updRect.width /= m_fontW; updRect.height /= m_fontH; // the *CoordsToGraphicalChars() funcs round down to upper-left corner, // so an off-by-one correction is needed ++updRect.width; // kludge ++updRect.height; // kludge return updRect; } wxPoint MyAutoTimedScrollingWindow::LogicalCoordsToGraphicalChars (wxPoint pos) const { pos.x /= m_fontW; pos.y /= m_fontH; return pos; } wxPoint MyAutoTimedScrollingWindow::GraphicalCharToLogicalCoords (wxPoint pos) const { pos.x *= m_fontW; pos.y *= m_fontH; return pos; } void MyAutoTimedScrollingWindow::MyRefresh() { static wxPoint lastSelStart(-1, -1), lastCursor(-1, -1); // refresh last selected area (to deselect previously selected text) wxRect lastUpdRect( GraphicalCharToDeviceCoords(lastSelStart), GraphicalCharToDeviceCoords(lastCursor) ); // off-by-one corrections, necessary because it's not possible to know // when to round up until rect is normalized by lastUpdRect constructor lastUpdRect.width += m_fontW; // kludge lastUpdRect.height += m_fontH; // kludge // refresh currently selected (to select previously unselected text) wxRect updRect( GraphicalCharToDeviceCoords(m_selStart), GraphicalCharToDeviceCoords(m_cursor) ); // off-by-one corrections updRect.width += m_fontW; // kludge updRect.height += m_fontH; // kludge // find necessary refresh areas wxCoord rx = lastUpdRect.x; wxCoord ry = lastUpdRect.y; wxCoord rw = updRect.x - lastUpdRect.x; wxCoord rh = lastUpdRect.height; if (rw && rh) { RefreshRect(DCNormalize(rx, ry, rw, rh)); } rx = updRect.x; ry = updRect.y + updRect.height; rw= updRect.width; rh = (lastUpdRect.y + lastUpdRect.height) - (updRect.y + updRect.height); if (rw && rh) { RefreshRect(DCNormalize(rx, ry, rw, rh)); } rx = updRect.x + updRect.width; ry = lastUpdRect.y; rw = (lastUpdRect.x + lastUpdRect.width) - (updRect.x + updRect.width); rh = lastUpdRect.height; if (rw && rh) { RefreshRect(DCNormalize(rx, ry, rw, rh)); } rx = updRect.x; ry = lastUpdRect.y; rw = updRect.width; rh = updRect.y - lastUpdRect.y; if (rw && rh) { RefreshRect(DCNormalize(rx, ry, rw, rh)); } // update last lastSelStart = m_selStart; lastCursor = m_cursor; } bool MyAutoTimedScrollingWindow::IsSelected(int chX, int chY) const { if (IsInside(chX, m_selStart.x, m_cursor.x) && IsInside(chY, m_selStart.y, m_cursor.y)) { return true; } return false; } bool MyAutoTimedScrollingWindow::IsInside(int k, int bound1, int bound2) { if ((k >= bound1 && k <= bound2) || (k >= bound2 && k <= bound1)) { return true; } return false; } wxRect MyAutoTimedScrollingWindow::DCNormalize(wxCoord x, wxCoord y , wxCoord w, wxCoord h) { // this is needed to get rid of the graphical remnants from the selection // I think it's because DrawRectangle() excludes a pixel in either direction const int kludge = 1; // make (x, y) the top-left corner if (w < 0) { w = -w + kludge; x -= w; } else { x -= kludge; w += kludge; } if (h < 0) { h = -h + kludge; y -= h; } else { y -= kludge; h += kludge; } return wxRect(x, y, w, h); } void MyAutoTimedScrollingWindow::OnDraw(wxDC& dc) { dc.SetFont(m_font); wxBrush normBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW) , wxSOLID); wxBrush selBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT) , wxSOLID); dc.SetPen(*wxTRANSPARENT_PEN); wxString str = sm_testData; // draw the characters // 1. for each update region for (wxRegionIterator upd(GetUpdateRegion()); upd; ++upd) { wxRect updRect = upd.GetRect(); wxRect updRectInGChars(DeviceCoordsToGraphicalChars(updRect)); // 2. for each row of chars in the update region for (int chY = updRectInGChars.y ; chY <= updRectInGChars.y + updRectInGChars.height; ++chY) { // 3. for each character in the row for (int chX = updRectInGChars.x ; chX <= updRectInGChars.x + updRectInGChars.width ; ++chX) { // 4. set up dc if (IsSelected(chX, chY)) { dc.SetBrush(selBrush); dc.SetTextForeground( wxSystemSettings::GetColour (wxSYS_COLOUR_HIGHLIGHTTEXT)); } else { dc.SetBrush(normBrush); dc.SetTextForeground( wxSystemSettings::GetColour (wxSYS_COLOUR_WINDOWTEXT)); } // 5. find position info wxPoint charPos = GraphicalCharToLogicalCoords(wxPoint (chX, chY)); // 6. draw! dc.DrawRectangle(charPos.x, charPos.y, m_fontW, m_fontH); size_t charIndex = chY * sm_lineLen + chX; if (chY < sm_lineCnt && chX < sm_lineLen && charIndex < str.Length()) { dc.DrawText(str.Mid(charIndex,1), charPos.x, charPos.y); } } } } } void MyAutoTimedScrollingWindow::OnMouseLeftDown(wxMouseEvent& event) { // initial press of mouse button sets the beginning of the selection m_selStart = DeviceCoordsToGraphicalChars(event.GetPosition()); // set the cursor to the same position m_cursor = m_selStart; // draw/erase selection MyRefresh(); } void MyAutoTimedScrollingWindow::OnMouseLeftUp(wxMouseEvent& WXUNUSED(event)) { // this test is necessary if (HasCapture()) { // uncapture mouse ReleaseMouse(); } } void MyAutoTimedScrollingWindow::OnMouseMove(wxMouseEvent& event) { // if user is dragging if (event.Dragging() && event.LeftIsDown()) { // set the new cursor position m_cursor = DeviceCoordsToGraphicalChars(event.GetPosition()); // draw/erase selection MyRefresh(); // capture mouse to activate auto-scrolling if (!HasCapture()) { CaptureMouse(); } } } void MyAutoTimedScrollingWindow::OnScroll(wxScrollWinEvent& event) { // need to move the cursor when autoscrolling // FIXME: the cursor also moves when the scrollbar arrows are clicked if (HasCapture()) { if (event.GetOrientation() == wxHORIZONTAL) { if (event.GetEventType() == wxEVT_SCROLLWIN_LINEUP) { --m_cursor.x; } else if (event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN) { ++m_cursor.x; } } else if (event.GetOrientation() == wxVERTICAL) { if (event.GetEventType() == wxEVT_SCROLLWIN_LINEUP) { --m_cursor.y; } else if (event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN) { ++m_cursor.y; } } } MyRefresh(); event.Skip(); } const int MyAutoTimedScrollingWindow::sm_lineCnt = 125; const int MyAutoTimedScrollingWindow::sm_lineLen = 79; const wxChar* MyAutoTimedScrollingWindow::sm_testData = _T("162 Cult of the genius out of vanity. Because we think well of ourselves, but ") _T("nonetheless never suppose ourselves capable of producing a painting like one of ") _T("Raphael's or a dramatic scene like one of Shakespeare's, we convince ourselves ") _T("that the capacity to do so is quite extraordinarily marvelous, a wholly ") _T("uncommon accident, or, if we are still religiously inclined, a mercy from on ") _T("high. Thus our vanity, our self-love, promotes the cult of the genius: for only ") _T("if we think of him as being very remote from us, as a miraculum, does he not ") _T("aggrieve us (even Goethe, who was without envy, called Shakespeare his star of ") _T("the most distant heights [\"William! Stern der schonsten Ferne\": from Goethe's, ") _T("\"Between Two Worlds\"]; in regard to which one might recall the lines: \"the ") _T("stars, these we do not desire\" [from Goethe's, \"Comfort in Tears\"]). But, aside ") _T("from these suggestions of our vanity, the activity of the genius seems in no ") _T("way fundamentally different from the activity of the inventor of machines, the ") _T("scholar of astronomy or history, the master of tactics. All these activities ") _T("are explicable if one pictures to oneself people whose thinking is active in ") _T("one direction, who employ everything as material, who always zealously observe ") _T("their own inner life and that of others, who perceive everywhere models and ") _T("incentives, who never tire of combining together the means available to them. ") _T("Genius too does nothing except learn first how to lay bricks then how to build, ") _T("except continually seek for material and continually form itself around it. ") _T("Every activity of man is amazingly complicated, not only that of the genius: ") _T("but none is a \"miracle.\" Whence, then, the belief that genius exists only in ") _T("the artist, orator and philosopher? that only they have \"intuition\"? (Whereby ") _T("they are supposed to possess a kind of miraculous eyeglass with which they can ") _T("see directly into \"the essence of the thing\"!) It is clear that people speak of ") _T("genius only where the effects of the great intellect are most pleasant to them ") _T("and where they have no desire to feel envious. To call someone \"divine\" means: ") _T("\"here there is no need for us to compete.\" Then, everything finished and ") _T("complete is regarded with admiration, everything still becoming is undervalued. ") _T("But no one can see in the work of the artist how it has become; that is its ") _T("advantage, for wherever one can see the act of becoming one grows somewhat ") _T("cool. The finished and perfect art of representation repulses all thinking as ") _T("to how it has become; it tyrannizes as present completeness and perfection. ") _T("That is why the masters of the art of representation count above all as gifted ") _T("with genius and why men of science do not. In reality, this evaluation of the ") _T("former and undervaluation of the latter is only a piece of childishness in the ") _T("realm of reason. ") _T("\n\n") _T("163 The serious workman. Do not talk about giftedness, inborn talents! One can ") _T("name great men of all kinds who were very little gifted. The acquired ") _T("greatness, became \"geniuses\" (as we put it), through qualities the lack of ") _T("which no one who knew what they were would boast of: they all possessed that ") _T("seriousness of the efficient workman which first learns to construct the parts ") _T("properly before it ventures to fashion a great whole; they allowed themselves ") _T("time for it, because they took more pleasure in making the little, secondary ") _T("things well than in the effect of a dazzling whole. the recipe for becoming a ") _T("good novelist, for example, is easy to give, but to carry it out presupposes ") _T("qualities one is accustomed to overlook when one says \"I do not have enough ") _T("talent.\" One has only to make a hundred or so sketches for novels, none longer ") _T("than two pages but of such distinctness that every word in them is necessary; ") _T("one should write down anecdotes each day until one has learned how to give them ") _T("the most pregnant and effective form; one should be tireless in collecting and ") _T("describing human types and characters; one should above all relate things to ") _T("others and listen to others relate, keeping one's eyes and ears open for the ") _T("effect produced on those present, one should travel like a landscape painter or ") _T("costume designer; one should excerpt for oneself out of the individual sciences ") _T("everything that will produce an artistic effect when it is well described, one ") _T("should, finally, reflect on the motives of human actions, disdain no signpost ") _T("to instruction about them and be a collector of these things by day and night. ") _T("One should continue in this many-sided exercise some ten years: what is then ") _T("created in the workshop, however, will be fit to go out into the world. What, ") _T("however, do most people do? They begin, not with the parts, but with the whole. ") _T("Perhaps they chance to strike a right note, excite attention and from then on ") _T("strike worse and worse notes, for good, natural reasons. Sometimes, when the ") _T("character and intellect needed to formulate such a life-plan are lacking, fate ") _T("and need take their place and lead the future master step by step through all ") _T("the stipulations of his trade. ") _T("\n\n") _T("164 Peril and profit in the cult of the genius. The belief in great, superior, ") _T("fruitful spirits is not necessarily, yet nonetheless is very frequently ") _T("associated with that religious or semi-religious superstition that these ") _T("spirits are of supra-human origin and possess certain miraculous abilities by ") _T("virtue of which they acquire their knowledge by quite other means than the rest ") _T("of mankind. One ascribes to them, it seems, a direct view of the nature of the ") _T("world, as it were a hole in the cloak of appearance, and believes that, by ") _T("virtue of this miraculous seer's vision, they are able to communicate something ") _T("conclusive and decisive about man and the world without the toil and ") _T("rigorousness required by science. As long as there continue to be those who ") _T("believe in the miraculous in the domain of knowledge one can perhaps concede ") _T("that these people themselves derive some benefit from their belief, inasmuch as ") _T("through their unconditional subjection to the great spirits they create for ") _T("their own spirit during its time of development the finest form of discipline ") _T("and schooling. On the other hand, it is at least questionable whether the ") _T("superstitious belief in genius, in its privileges and special abilities, is of ") _T("benefit to the genius himself if it takes root in him. It is in any event a ") _T("dangerous sign when a man is assailed by awe of himself, whether it be the ") _T("celebrated Caesar's awe of Caesar or the awe of one's own genius now under ") _T("consideration; when the sacrificial incense which is properly rendered only to ") _T("a god penetrates the brain of the genius, so that his head begins to swim and ") _T("he comes to regard himself as something supra-human. The consequences that ") _T("slowly result are: the feeling of irresponsibility, of exceptional rights, the ") _T("belief that he confers a favor by his mere presence, insane rage when anyone ") _T("attempts even to compare him with others, let alone to rate him beneath them, ") _T("or to draw attention to lapses in his work. Because he ceases to practice ") _T("criticism of himself, at last one pinion after the other falls out of his ") _T("plumage: that superstitious eats at the roots of his powers and perhaps even ") _T("turns him into a hypocrite after his powers have fled from him. For the great ") _T("spirits themselves it is therefore probably more beneficial if they acquire an ") _T("insight into the nature and origin of their powers, if they grasp, that is to ") _T("say, what purely human qualities have come together in them and what fortunate ") _T("circumstances attended them: in the first place undiminished energy, resolute ") _T("application to individual goals, great personal courage, then the good fortune ") _T("to receive an upbringing which offered in the early years the finest teachers, ") _T("models and methods. To be sure, when their goal is the production of the ") _T("greatest possible effect, unclarity with regard to oneself and that ") _T("semi-insanity superadded to it has always achieved much; for what has been ") _T("admired and envied at all times has been that power in them by virtue of which ") _T("they render men will-less and sweep them away into the delusion that the ") _T("leaders they are following are supra-natural. Indeed, it elevates and inspires ") _T("men to believe that someone is in possession of supra-natural powers: to this ") _T("extent Plato was right to say [Plato: Phaedrus, 244a] that madness has brought ") _T("the greatest of blessings upon mankind. In rare individual cases this portion ") _T("of madness may, indeed, actually have been the means by which such a nature, ") _T("excessive in all directions, was held firmly together: in the life of ") _T("individuals, too, illusions that are in themselves poisons often play the role ") _T("of healers; yet, in the end, in the case of every \"genius\" who believes in his ") _T("own divinity the poison shows itself to the same degree as his \"genius\" grows ") _T("old: one may recall, for example, the case of Napoleon, whose nature certainly ") _T("grew into the mighty unity that sets him apart from all men of modern times ") _T("precisely through his belief in himself and his star and through the contempt ") _T("for men that flowed from it; until in the end, however, this same belief went ") _T("over into an almost insane fatalism, robbed him of his acuteness and swiftness ") _T("of perception, and became the cause of his destruction.");
[ "RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775" ]
RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775
a4ee0066ae292b6e9aefe1fda77d6829f416bf7e
2ed41ec8cf3f270bbbe0bd646873b34e6c4fe9a6
/laomashitu/chapter01functionParamAndRet/chapter01functionParamAndRet/chapter01functionParamAndRet.cpp
16ec42f1c15a79e221498d1ff3980647bcc3eff0
[]
no_license
LiWeilian/MachineCode
d8a924dc8cbc8e9900f3508499d4a0b6fa530843
169af9386f8000243063cf7447ac1525fc43e8b0
refs/heads/master
2020-04-18T02:24:52.315992
2013-10-22T12:32:25
2013-10-22T12:32:25
13,772,554
1
0
null
null
null
null
GB18030
C++
false
false
234
cpp
// chapter01functionParamAndRet.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" int Add(int x, int y) { int sum; sum = x + y; return sum; } void main() { int z; z = Add(1, 2); printf("z=%d\n", z); }
[ "liweilian0822@163.com" ]
liweilian0822@163.com
518c61c9d91ff5844a2e5adad01b1e76f1607073
b04bcbee8d6a6fe8b519d148e15e8e88868fdf1c
/bnc_source/BNC/src/rinex/rnxnavfile.cpp
3b0b78838fc1526e6f371cd63ffc17b9ff3248bc
[]
no_license
kad-huisml/grs-bnc-docker
a37b18b389337d7cc46d3ca5257fce324a7d5cd2
3e747d9b27aa2b9f34c0ca460a66af5d9e5aa769
refs/heads/master
2023-09-02T11:24:55.513964
2021-11-22T16:21:37
2021-11-22T16:21:37
430,779,470
0
2
null
null
null
null
UTF-8
C++
false
false
9,981
cpp
// Part of BNC, a utility for retrieving decoding and // converting GNSS data streams from NTRIP broadcasters. // // Copyright (C) 2007 // German Federal Agency for Cartography and Geodesy (BKG) // http://www.bkg.bund.de // Czech Technical University Prague, Department of Geodesy // http://www.fsv.cvut.cz // // Email: euref-ip@bkg.bund.de // // 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, version 2. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /* ------------------------------------------------------------------------- * BKG NTRIP Client * ------------------------------------------------------------------------- * * Class: t_rnxNavFile * * Purpose: Reads RINEX Navigation File * * Author: L. Mervart * * Created: 24-Jan-2012 * * Changes: * * -----------------------------------------------------------------------*/ #include <iostream> #include <newmatio.h> #include "rnxnavfile.h" #include "bnccore.h" #include "bncutils.h" #include "ephemeris.h" using namespace std; // Constructor //////////////////////////////////////////////////////////////////////////// t_rnxNavFile::t_rnxNavHeader::t_rnxNavHeader() { _version = 0.0; _glonass = false; } // Destructor //////////////////////////////////////////////////////////////////////////// t_rnxNavFile::t_rnxNavHeader::~t_rnxNavHeader() { } // Read Header //////////////////////////////////////////////////////////////////////////// t_irc t_rnxNavFile::t_rnxNavHeader::read(QTextStream* stream) { while (stream->status() == QTextStream::Ok && !stream->atEnd()) { QString line = stream->readLine(); if (line.isEmpty()) { continue; } QString value = line.left(60).trimmed(); QString key = line.mid(60).trimmed(); if (key == "END OF HEADER") { break; } else if (key == "RINEX VERSION / TYPE") { QTextStream in(value.toAscii(), QIODevice::ReadOnly); in >> _version; if (value.indexOf("GLONASS") != -1) { _glonass = true; } } else if (key == "COMMENT") { _comments.append(value.trimmed()); } } return success; } // Constructor //////////////////////////////////////////////////////////////////////////// t_rnxNavFile::t_rnxNavFile(const QString& fileName, e_inpOut inpOut) { _inpOut = inpOut; _stream = 0; _file = 0; if (_inpOut == input) { openRead(fileName); } else { openWrite(fileName); } } // Open for input //////////////////////////////////////////////////////////////////////////// void t_rnxNavFile::openRead(const QString& fileName) { _fileName = fileName; expandEnvVar(_fileName); _file = new QFile(_fileName); _file->open(QIODevice::ReadOnly | QIODevice::Text); _stream = new QTextStream(); _stream->setDevice(_file); _header.read(_stream); this->read(_stream); } // Open for output //////////////////////////////////////////////////////////////////////////// void t_rnxNavFile::openWrite(const QString& fileName) { _fileName = fileName; expandEnvVar(_fileName); _file = new QFile(_fileName); _file->open(QIODevice::WriteOnly | QIODevice::Text); _stream = new QTextStream(); _stream->setDevice(_file); } // Destructor //////////////////////////////////////////////////////////////////////////// t_rnxNavFile::~t_rnxNavFile() { close(); for (unsigned ii = 0; ii < _ephs.size(); ii++) { delete _ephs[ii]; } } // Close //////////////////////////////////////////////////////////////////////////// void t_rnxNavFile::close() { delete _stream; _stream = 0; delete _file; _file = 0; } // Read File Content //////////////////////////////////////////////////////////////////////////// void t_rnxNavFile::read(QTextStream* stream) { while (stream->status() == QTextStream::Ok && !stream->atEnd()) { QString line = stream->readLine(); if (line.isEmpty()) { continue; } QStringList hlp = line.split(QRegExp("\\s+"), QString::SkipEmptyParts); QString prn; if (version() >= 3.0) { prn = hlp.at(0); } else { if (glonass()) { prn = QString("R%1_0").arg(hlp.at(0).toInt(), 2, 10, QChar('0')); } else { prn = QString("G%1_0").arg(hlp.at(0).toInt(), 2, 10, QChar('0')); } } t_eph* eph = 0; QStringList lines; lines << line; if (prn[0] == 'G') { for (int ii = 1; ii < 8; ii++) { lines << stream->readLine(); } eph = new t_ephGPS(version(), lines); } else if (prn[0] == 'R') { int num = 4; if (version() >= 3.05) { num += 1; } for (int ii = 1; ii < num; ii++) { lines << stream->readLine(); } eph = new t_ephGlo(version(), lines); } else if (prn[0] == 'E') { for (int ii = 1; ii < 8; ii++) { lines << stream->readLine(); } eph = new t_ephGal(version(), lines); } else if (prn[0] == 'J') { for (int ii = 1; ii < 8; ii++) { lines << stream->readLine(); } eph = new t_ephGPS(version(), lines); } else if (prn[0] == 'S') { for (int ii = 1; ii < 4; ii++) { lines << stream->readLine(); } eph = new t_ephSBAS(version(), lines); } else if (prn[0] == 'C') { for (int ii = 1; ii < 8; ii++) { lines << stream->readLine(); } eph = new t_ephBDS(version(), lines); } else if (prn[0] == 'I') { for (int ii = 1; ii < 8; ii++) { lines << stream->readLine(); } eph = new t_ephGPS(version(), lines); } _ephs.push_back(eph); } } // Read Next Ephemeris //////////////////////////////////////////////////////////////////////////// t_eph* t_rnxNavFile::getNextEph(const bncTime& tt, const QMap<QString, unsigned int>* corrIODs) { // Get Ephemeris according to IOD // ------------------------------ if (corrIODs) { QMapIterator<QString, unsigned int> itIOD(*corrIODs); while (itIOD.hasNext()) { itIOD.next(); QString prn = itIOD.key(); unsigned int iod = itIOD.value(); vector<t_eph*>::iterator it = _ephs.begin(); while (it != _ephs.end()) { t_eph* eph = *it; double dt = eph->TOC() - tt; if (dt < 8*3600.0 && QString(eph->prn().toInternalString().c_str()) == prn && eph->IOD() == iod) { it = _ephs.erase(it); return eph; } ++it; } } } // Get Ephemeris according to time // ------------------------------- else { vector<t_eph*>::iterator it = _ephs.begin(); while (it != _ephs.end()) { t_eph* eph = *it; double dt = eph->TOC() - tt; if (dt < 2*3600.0) { it = _ephs.erase(it); return eph; } ++it; } } return 0; } // //////////////////////////////////////////////////////////////////////////// void t_rnxNavFile::writeHeader(const QMap<QString, QString>* txtMap) { QString runBy = BNC_CORE->userName(); QStringList comments; if (txtMap) { QMapIterator<QString, QString> it(*txtMap); while (it.hasNext()) { it.next(); if (it.key() == "RUN BY") { runBy = it.value(); } else if (it.key() == "COMMENT") { comments = it.value().split("\\n", QString::SkipEmptyParts); } } } if (version() < 3.0) { const QString fmt = glonass() ? "%1 GLONASS navigation data" : "%1 Navigation data"; *_stream << QString(fmt) .arg(_header._version, 9, 'f', 2) .leftJustified(60) << "RINEX VERSION / TYPE\n"; } else { QString fmt; t_eph::e_type sys = satSystem(); switch(sys) { case t_eph::GPS: fmt.append("%1 N: GNSS NAV DATA G: GPS"); break; case t_eph::GLONASS: fmt.append("%1 N: GNSS NAV DATA R: GLONASS"); break; case t_eph::Galileo: fmt.append("%1 N: GNSS NAV DATA E: Galileo"); break; case t_eph::QZSS: fmt.append("%1 N: GNSS NAV DATA J: QZSS"); break; case t_eph::BDS: fmt.append("%1 N: GNSS NAV DATA C: BDS"); break; case t_eph::IRNSS: fmt.append("%1 N: GNSS NAV DATA I: IRNSS"); break; case t_eph::SBAS: fmt.append("%1 N: GNSS NAV DATA S: SBAS"); break; case t_eph::unknown: fmt.append("%1 N: GNSS NAV DATA M: MIXED"); break; } *_stream << fmt .arg(_header._version, 9, 'f', 2) .leftJustified(60) << "RINEX VERSION / TYPE\n"; } const QString fmtDate = (version() < 3.0) ? "dd-MMM-yy hh:mm" : "yyyyMMdd hhmmss UTC"; *_stream << QString("%1%2%3") .arg(BNC_CORE->pgmName(), -20) .arg(runBy.trimmed().left(20), -20) .arg(QDateTime::currentDateTime().toUTC().toString(fmtDate), -20) .leftJustified(60) << "PGM / RUN BY / DATE\n"; QStringListIterator itCmnt(comments); while (itCmnt.hasNext()) { *_stream << itCmnt.next().trimmed().left(60).leftJustified(60) << "COMMENT\n"; } *_stream << QString() .leftJustified(60) << "END OF HEADER\n"; } // //////////////////////////////////////////////////////////////////////////// void t_rnxNavFile::writeEph(const t_eph* eph) { *_stream << eph->toString(version()); }
[ "lennard.huisman@kadaster.nl" ]
lennard.huisman@kadaster.nl
4e07d85b2234ac53a45e0fb9faf3b3fcbcfe324f
a7e8534ace26b82f7d6addef6867eee75cc51af5
/Utilities/MicronTracker/src/FL/Fl_Input_Choice.H
4bfd981caa2ddb4915eaa8edf6631a5f6bec0a28
[ "LicenseRef-scancode-other-permissive", "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
JQiu/IGSTK-4.4
c8885d2868e5c3181343c5b8b1932faf3bec5e9e
d883f529eaa410b24f3467be3d3432fc99509aef
refs/heads/master
2016-08-12T20:46:03.893378
2016-03-09T22:49:12
2016-03-09T22:49:12
53,537,422
1
1
null
null
null
null
UTF-8
C++
false
false
5,845
h
// // "$Id: Fl_Input_Choice.H,v 1.1 2010-11-14 05:00:08 patrick Exp $" // // An input/chooser widget. // ______________ ____ // | || __ | // | input area || \/ | // |______________||____| // // Copyright 1998-2005 by Bill Spitzak and others. // Copyright 2004 by Greg Ercolano. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems on the following page: // // http://www.fltk.org/str.php // #ifndef Fl_Input_Choice_H #define Fl_Input_Choice_H #include <FL/Fl.H> #include <FL/Fl_Group.H> #include <FL/Fl_Input.H> #include <FL/Fl_Menu_Button.H> #include <FL/fl_draw.H> #include <string.h> class Fl_Input_Choice : public Fl_Group { // Private class to handle slightly 'special' behavior of menu button class InputMenuButton : public Fl_Menu_Button { void draw() { draw_box(FL_UP_BOX, color()); fl_color(active_r() ? labelcolor() : fl_inactive(labelcolor())); int xc = x()+w()/2, yc=y()+h()/2; fl_polygon(xc-5,yc-3,xc+5,yc-3,xc,yc+3); if (Fl::focus() == this) draw_focus(); } public: InputMenuButton(int x,int y,int w,int h,const char*l=0) : Fl_Menu_Button(x,y,w,h,l) { box(FL_UP_BOX); } }; Fl_Input *inp_; InputMenuButton *menu_; static void menu_cb(Fl_Widget*, void *data) { Fl_Input_Choice *o=(Fl_Input_Choice *)data; const Fl_Menu_Item *item = o->menubutton()->mvalue(); if (item && item->flags & (FL_SUBMENU|FL_SUBMENU_POINTER)) return; // ignore submenus if (!strcmp(o->inp_->value(), o->menu_->text())) { o->Fl_Widget::clear_changed(); if (o->when() & FL_WHEN_NOT_CHANGED) o->do_callback(); } else { o->inp_->value(o->menu_->text()); o->inp_->set_changed(); o->Fl_Widget::set_changed(); if (o->when() & (FL_WHEN_CHANGED|FL_WHEN_RELEASE)) o->do_callback(); } if (o->callback() != default_callback) { o->Fl_Widget::clear_changed(); o->inp_->clear_changed(); } } static void inp_cb(Fl_Widget*, void *data) { Fl_Input_Choice *o=(Fl_Input_Choice *)data; if (o->inp_->changed()) { o->Fl_Widget::set_changed(); if (o->when() & (FL_WHEN_CHANGED|FL_WHEN_RELEASE)) o->do_callback(); } else { o->Fl_Widget::clear_changed(); if (o->when() & FL_WHEN_NOT_CHANGED) o->do_callback(); } if (o->callback() != default_callback) o->Fl_Widget::clear_changed(); } // Custom resize behavior -- input stretches, menu button doesn't inline int inp_x() { return(x() + Fl::box_dx(box())); } inline int inp_y() { return(y() + Fl::box_dy(box())); } inline int inp_w() { return(w() - Fl::box_dw(box()) - 20); } inline int inp_h() { return(h() - Fl::box_dh(box())); } inline int menu_x() { return(x() + w() - 20 - Fl::box_dx(box())); } inline int menu_y() { return(y() + Fl::box_dy(box())); } inline int menu_w() { return(20); } inline int menu_h() { return(h() - Fl::box_dh(box())); } public: Fl_Input_Choice (int x,int y,int w,int h,const char*l=0) : Fl_Group(x,y,w,h,l) { Fl_Group::box(FL_DOWN_BOX); align(FL_ALIGN_LEFT); // default like Fl_Input inp_ = new Fl_Input(inp_x(), inp_y(), inp_w(), inp_h()); inp_->callback(inp_cb, (void*)this); inp_->box(FL_FLAT_BOX); // cosmetic inp_->when(FL_WHEN_CHANGED|FL_WHEN_NOT_CHANGED); menu_ = new InputMenuButton(menu_x(), menu_y(), menu_w(), menu_h()); menu_->callback(menu_cb, (void*)this); menu_->box(FL_FLAT_BOX); // cosmetic end(); } void add(const char *s) { menu_->add(s); } int changed() const { return inp_->changed() | Fl_Widget::changed(); } void clear_changed() { inp_->clear_changed(); Fl_Widget::clear_changed(); } void set_changed() { inp_->set_changed(); // no need to call Fl_Widget::set_changed() } void clear() { menu_->clear(); } Fl_Boxtype down_box() const { return (menu_->down_box()); } void down_box(Fl_Boxtype b) { menu_->down_box(b); } const Fl_Menu_Item *menu() { return (menu_->menu()); } void menu(const Fl_Menu_Item *m) { menu_->menu(m); } void resize(int X, int Y, int W, int H) { Fl_Group::resize(X,Y,W,H); inp_->resize(inp_x(), inp_y(), inp_w(), inp_h()); menu_->resize(menu_x(), menu_y(), menu_w(), menu_h()); } Fl_Color textcolor() const { return (inp_->textcolor()); } void textcolor(Fl_Color c) { inp_->textcolor(c); } uchar textfont() const { return (inp_->textfont()); } void textfont(uchar f) { inp_->textfont(f); } uchar textsize() const { return (inp_->textsize()); } void textsize(uchar s) { inp_->textsize(s); } const char* value() const { return (inp_->value()); } void value(const char *val) { inp_->value(val); } void value(int val) { menu_->value(val); inp_->value(menu_->text(val)); } Fl_Menu_Button *menubutton() { return menu_; } Fl_Input *input() { return inp_; } }; #endif // !Fl_Input_Choice_H // // End of "$Id: Fl_Input_Choice.H,v 1.1 2010-11-14 05:00:08 patrick Exp $". //
[ "jqvroom@gmail.com" ]
jqvroom@gmail.com
25f76fcfb0297379ee57e9d81c29f840edad5a2d
829b0a557d3cc43a108f9b76d748e923fba8d928
/llvm/projects/tapi/include/tapi/Core/TapiError.h
9a6d1caa8f2799a040f91baf56f3bfaa119e5e5e
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
ljh740/llvm-project
31766f1f687939a679531d372d56755dbb5c415b
89295aa3f2aebcd930e5ee7272ca47349bb7767d
refs/heads/sbingner/master
2023-04-06T14:15:22.003403
2020-01-07T08:36:49
2020-01-07T08:36:49
255,562,403
0
0
Apache-2.0
2021-04-15T14:56:23
2020-04-14T09:12:17
null
UTF-8
C++
false
false
1,026
h
//===- tapi/Core/TapiError.h - TAPI Error -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Define TAPI specific error codes. /// //===----------------------------------------------------------------------===// #ifndef TAPI_CORE_TAPIERROR_H #define TAPI_CORE_TAPIERROR_H #include "tapi/Core/LLVM.h" #include "tapi/Defines.h" #include "llvm/Support/Error.h" TAPI_NAMESPACE_INTERNAL_BEGIN enum class TapiErrorCode { NoSuchArchitecture, }; class TapiError : public llvm::ErrorInfo<TapiError> { public: static char ID; TapiErrorCode ec; TapiError(TapiErrorCode ec) : ec(ec) {} void log(raw_ostream &os) const override; std::error_code convertToErrorCode() const override; }; TAPI_NAMESPACE_INTERNAL_END #endif // TAPI_CORE_TAPIERROR_H
[ "sam@bingner.com" ]
sam@bingner.com
de261c02cc9921df6bf9c49c4cca65d02910e0fa
15f0eac88515292bf6e686abc399ec95966b6c80
/AtCoder/ABC/ABC051-100/ABC085/D.cpp
e22f3966c580ba04c4650c62371f19a5563b518c
[]
no_license
punipuni21/competitive-programming
e08bbdcdd6a83571f2dd6272ab638d6ce3471c75
ed498c950bebf716572f33b4e63756cf269320f4
refs/heads/master
2022-09-05T08:27:54.198244
2020-05-30T07:28:36
2020-05-30T07:28:36
178,848,951
2
0
null
null
null
null
UTF-8
C++
false
false
2,161
cpp
#include<iostream> #include<vector> #include<algorithm> #include<cctype> #include<utility> #include<string> #include<cmath> #define REP(i, n) for(int i = 0;i < n;i++) #define REPR(i, n) for(int i = n;i >= 0;i--) #define FOR(i, m, n) for(int i = m;i < n;i++) #define FORR(i, m, n) for(int i = m;i >= n;i--) #define SORT(v, n) sort(v, v+n); #define VSORT(v) sort(v.begin(), v.end()); #define llong long long #define pb(a) push_back(a) #define INF 999999999 using namespace std; typedef pair<int, int> P; typedef pair<llong, llong> LP; typedef pair<int, P> PP; typedef pair<llong, LP> LPP; typedef long long int ll; int main(){ ll n,h; cin >> n >> h; vector<ll> a(n),b(n); REP(i,n){ cin >> a[i] >> b[i]; } sort(a.begin(),a.end(),greater<ll>()); sort(b.begin(),b.end(),greater<ll>()); ll cut_damage = a[0]; ll count = 0; bool flag = true;/*操作の継続条件*/ while(flag){ for(int i = 0;i < n;i++){ /*切るダメージが投げるダメージを超えるまではひたすら投げる*/ if(h <= 0){ flag = false; break; } if(b[i] <= cut_damage){ /*切るダメージのほうが大きくなるので投げるのを終了*/ break; }else{ /*投げるダメージのほうが大きい*/ if(b[i] >= h){ /*この投げる操作でダメージが0になるのでカウントして操作を終了する*/ count++; flag = false; h -= b[i]; }else{ /*投げてダメージを減らす*/ h -= b[i]; count++; } } } if(h <= 0){ break; } /*この時点で残りは切るのみ*/ if(h % cut_damage == 0){ count += h/cut_damage; flag = false; }else{ count += h/cut_damage + 1; flag = false; } } cout << count << endl; return 0; }
[ "watanabe-ryotaro-yp@ynu.jp" ]
watanabe-ryotaro-yp@ynu.jp
c10b02e5793e977bc7293abef3c6d4c94ae688d5
5ec94f304ccb26c4095e51d0310b9dc17189c5c6
/graphicEditor/graphicEditor/GraphicEditor.hpp
448bc245c5b538748fd103ac2614479224ab108f
[]
no_license
fuss123/cPlusPlusProgrammingPractice
92d1408a0f0b3d469bc38753cf4c15bb8e54b2a0
541ec2128a6ee4751ba8d0606a213f258a14453a
refs/heads/master
2021-05-16T14:05:20.445141
2018-01-18T11:07:06
2018-01-18T11:07:06
116,914,508
0
0
null
null
null
null
UTF-8
C++
false
false
1,650
hpp
// // GraphicEditor.hpp // graphicEditor // // Created by GODJin on 2018. 1. 17.. // Copyright © 2018년 GODJin. All rights reserved. // #ifndef GraphicEditor_hpp #define GraphicEditor_hpp #include "Shape.hpp" #include "Console.hpp" class GraphicEditor { public: // 생성자, 소멸자 GraphicEditor(); ~GraphicEditor(); // 메세지 출력 메서드 const int selectMenu() const; const int selectShape() const; void integerError() const; void scopeError(const int& index) const; // getter, setter const int& getSize() const; inline void incrSize(); inline void decrSize(); Shape* getStartPtr(); void setStartPtr(Shape* inPtr); Shape* getEndPtr(); void setEndPtr(Shape* inPtr); template<typename T> void insertFactory(T* inNewItem); // 힙에 객체를 생성하여 큐에 삽입 void run(); void insertGraphic(); // 큐에 데이터를 삽입하는 메서드 void deleteGraphic(); // 입력받은 인덱스 데이터 값을 큐에서 삭제하는 메서드 void viewAll() const; // 큐에 담겨있는 데이터 전체를 출력하는 메서드 private: int mSize; Shape* mStartPtr; Shape* mEndPtr; enum class Menu { Insert = 1, Delete, ViewAll, Quit }; enum class Type { Circle = 1, Rectangle, Line }; }; template<typename T> void GraphicEditor::insertFactory(T* inNewItem) { Shape* newItem = inNewItem; newItem->setNext(nullptr); if(getStartPtr() == nullptr) setStartPtr(inNewItem); else getEndPtr()->setNext(inNewItem); setEndPtr(inNewItem); } #endif /* GraphicEditor_hpp */
[ "wonyoori8541@gmail.com" ]
wonyoori8541@gmail.com
136969da80b5f612ea86a1f4ced11d7e920b0546
5e1f5f2090013041b13d1e280f747aa9f914caa4
/src/devices/misc/drivers/compat/loader.h
876476fb75a4641712952a0fe14ed63998316c97
[ "BSD-2-Clause" ]
permissive
mvanotti/fuchsia-mirror
477b7d51ae6818e456d5803eea68df35d0d0af88
7fb60ae374573299dcb1cc73f950b4f5f981f95c
refs/heads/main
2022-11-29T08:52:01.817638
2021-10-06T05:37:42
2021-10-06T05:37:42
224,297,435
0
1
BSD-2-Clause
2022-11-21T01:19:37
2019-11-26T22:28:11
C++
UTF-8
C++
false
false
1,591
h
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SRC_DEVICES_MISC_DRIVERS_COMPAT_LOADER_H_ #define SRC_DEVICES_MISC_DRIVERS_COMPAT_LOADER_H_ #include <fidl/fuchsia.ldsvc/cpp/wire.h> namespace compat { constexpr char kLibDriverName[] = "libdriver.so"; // Loader is a loader service that is used to override the DFv1 driver library // with an alternative implementation. // // For most requests, it passes them along to a backing loader service, however // if the DFv1 driver library is requested, it will return the compatibility // driver's VMO. class Loader : public fidl::WireServer<fuchsia_ldsvc::Loader> { public: explicit Loader(async_dispatcher_t* dispatcher); // Binds a backing loader, `client_end`, and the VMO for the compatibility // driver, `driver_vmo`. zx::status<> Bind(fidl::ClientEnd<fuchsia_ldsvc::Loader> client_end, zx::vmo driver_vmo); private: // fidl::WireServer<fuchsia_ldsvc::Loader> void Done(DoneRequestView request, DoneCompleter::Sync& completer) override; void LoadObject(LoadObjectRequestView request, LoadObjectCompleter::Sync& completer) override; void Config(ConfigRequestView request, ConfigCompleter::Sync& completer) override; void Clone(CloneRequestView request, CloneCompleter::Sync& completer) override; async_dispatcher_t* dispatcher_; fidl::WireSharedClient<fuchsia_ldsvc::Loader> client_; zx::vmo driver_vmo_; }; } // namespace compat #endif // SRC_DEVICES_MISC_DRIVERS_COMPAT_LOADER_H_
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
e6c000c70697b615c1777fac37daf84d3e5885c1
e542522d4bcddbe88a66879a7183a73c1bbdbb17
/Codechef/Cookoff/2021/March/CONDEL/solve.cpp
79aa37cc0580e639f657ad9a7d842b141dcde98d
[]
no_license
ishank-katiyar/Competitive-programming
1103792f0196284cf24ef3f24bd243d18536f2f6
5240227828d5e94e2587d5d2fd69fa242d9d44ef
refs/heads/master
2023-06-21T17:30:48.855410
2021-08-13T14:51:53
2021-08-13T14:51:53
367,391,580
0
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; int K; cin >> K; vector<int> a (n); for (int i = 0; i < n; i++) { cin >> a[i]; } vector<int> dp (n); dp[0] = a[0]; for (int i = 1; i < n; i++) { dp[i] += dp[i - 1] + a[i]; } auto f = [&] (int L, int R) -> int { if (L == 0) { return dp[R]; } return dp[R] - dp[L - 1]; }; int64_t ans = LLONG_MAX; for (int i = K - 1; i < n; i++) { int64_t x = f (i - K + 1, i); int64_t cur_ans = (x * (x + 1)) / 2; cur_ans += dp.back() - x; ans = min (ans, cur_ans); } cout << ans << '\n'; } return 0; }
[ "ishankkatiyar162@gmail.com" ]
ishankkatiyar162@gmail.com
a464d8f308fa5ae9c7581132db421d52afd0a451
79813a2689ae22b0315323f398337017639662bb
/src/pcl/ColorSpace.cpp
70f0fc49b5d51dae4ca1cd28f106cfe64f467e7f
[ "LicenseRef-scancode-other-permissive" ]
permissive
jackros1022/PCL-1
4b51b494c69e4d97182387aa84ead1a964798264
059423bc8a3d7946a628fe1913b805bc3633aea5
refs/heads/master
2021-01-23T05:09:19.844862
2017-02-08T11:53:24
2017-02-08T11:53:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,106
cpp
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 02.01.01.0784 // ---------------------------------------------------------------------------- // pcl/ColorSpace.cpp - Released 2016/02/21 20:22:19 UTC // ---------------------------------------------------------------------------- // This file is part of the PixInsight Class Library (PCL). // PCL is a multiplatform C++ framework for development of PixInsight modules. // // Copyright (c) 2003-2016 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (http://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) 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 <pcl/ImageColor.h> namespace pcl { namespace ColorSpace { String Name( int s ) { static const char* name[] = { "Grayscale", "RGB", "CIE XYZ", "CIE L*a*b*", "CIE L*c*h*", "HSV", "HSI" }; PCL_PRECONDITION( s >= 0 && s < NumberOfColorSpaces ) if ( s >= 0 && s < NumberOfColorSpaces ) return String( name[s] ); return String(); } String ChannelId( int s, int c ) { static const char* id[3][7] = { { "K", "R", "X", "L*", "L*", "H", "H" }, { "", "G", "Y", "a*", "c*", "S", "S" }, { "", "B", "Z", "b*", "h*", "V", "I" } }; PCL_PRECONDITION( s >= 0 && s < NumberOfColorSpaces ) PCL_PRECONDITION( c >= 0 ) if ( s >= 0 && s < NumberOfColorSpaces && c >= 0 ) { if ( s == Gray && c > 0 ) c += 2; if ( c < 3 ) return String( id[c][s] ); return String().Format( "alpha%02d", c-2 ); } return String(); } } // ColorSpace } // pcl // ---------------------------------------------------------------------------- // EOF pcl/ColorSpace.cpp - Released 2016/02/21 20:22:19 UTC
[ "juan.conejero@pixinsight.com" ]
juan.conejero@pixinsight.com
9fd445c6c505be51595893c27bfd17e1901df794
f4724666236cde60b99815c5fa2d98eca33f62ad
/src/mips/regexp-macro-assembler-mips.cc
e1a27295e8f7df9e40c34dcd2c59399c17bbec20
[ "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
lihuibng/v8
520657515b3b73d1dad5f2524b7b1fcc335e3256
c455e582b0a5061db950f0010a58b73476cd83ed
refs/heads/master
2023-01-02T14:38:10.446081
2014-11-30T14:37:54
2014-11-30T14:37:54
27,338,675
1
1
NOASSERTION
2022-12-18T08:19:35
2014-11-30T14:36:18
C++
UTF-8
C++
false
false
47,434
cc
// Copyright 2012 the V8 project 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 "src/v8.h" #if V8_TARGET_ARCH_MIPS #include "src/code-stubs.h" #include "src/log.h" #include "src/macro-assembler.h" #include "src/regexp-macro-assembler.h" #include "src/regexp-stack.h" #include "src/unicode.h" #include "src/mips/regexp-macro-assembler-mips.h" namespace v8 { namespace internal { #ifndef V8_INTERPRETED_REGEXP /* * This assembler uses the following register assignment convention * - t7 : Temporarily stores the index of capture start after a matching pass * for a global regexp. * - t1 : Pointer to current code object (Code*) including heap object tag. * - t2 : Current position in input, as negative offset from end of string. * Please notice that this is the byte offset, not the character offset! * - t3 : Currently loaded character. Must be loaded using * LoadCurrentCharacter before using any of the dispatch methods. * - t4 : Points to tip of backtrack stack * - t5 : Unused. * - t6 : End of input (points to byte after last character in input). * - fp : Frame pointer. Used to access arguments, local variables and * RegExp registers. * - sp : Points to tip of C stack. * * The remaining registers are free for computations. * Each call to a public method should retain this convention. * * The stack will have the following structure: * * - fp[64] Isolate* isolate (address of the current isolate) * - fp[60] direct_call (if 1, direct call from JavaScript code, * if 0, call through the runtime system). * - fp[56] stack_area_base (High end of the memory area to use as * backtracking stack). * - fp[52] capture array size (may fit multiple sets of matches) * - fp[48] int* capture_array (int[num_saved_registers_], for output). * - fp[44] secondary link/return address used by native call. * --- sp when called --- * - fp[40] return address (lr). * - fp[36] old frame pointer (r11). * - fp[0..32] backup of registers s0..s7. * --- frame pointer ---- * - fp[-4] end of input (address of end of string). * - fp[-8] start of input (address of first character in string). * - fp[-12] start index (character index of start). * - fp[-16] void* input_string (location of a handle containing the string). * - fp[-20] success counter (only for global regexps to count matches). * - fp[-24] Offset of location before start of input (effectively character * position -1). Used to initialize capture registers to a * non-position. * - fp[-28] At start (if 1, we are starting at the start of the * string, otherwise 0) * - fp[-32] register 0 (Only positions must be stored in the first * - register 1 num_saved_registers_ registers) * - ... * - register num_registers-1 * --- sp --- * * The first num_saved_registers_ registers are initialized to point to * "character -1" in the string (i.e., char_size() bytes before the first * character of the string). The remaining registers start out as garbage. * * The data up to the return address must be placed there by the calling * code and the remaining arguments are passed in registers, e.g. by calling the * code entry as cast to a function with the signature: * int (*match)(String* input_string, * int start_index, * Address start, * Address end, * Address secondary_return_address, // Only used by native call. * int* capture_output_array, * byte* stack_area_base, * bool direct_call = false) * The call is performed by NativeRegExpMacroAssembler::Execute() * (in regexp-macro-assembler.cc) via the CALL_GENERATED_REGEXP_CODE macro * in mips/simulator-mips.h. * When calling as a non-direct call (i.e., from C++ code), the return address * area is overwritten with the ra register by the RegExp code. When doing a * direct call from generated code, the return address is placed there by * the calling code, as in a normal exit frame. */ #define __ ACCESS_MASM(masm_) RegExpMacroAssemblerMIPS::RegExpMacroAssemblerMIPS( Mode mode, int registers_to_save, Zone* zone) : NativeRegExpMacroAssembler(zone), masm_(new MacroAssembler(zone->isolate(), NULL, kRegExpCodeSize)), mode_(mode), num_registers_(registers_to_save), num_saved_registers_(registers_to_save), entry_label_(), start_label_(), success_label_(), backtrack_label_(), exit_label_(), internal_failure_label_() { ASSERT_EQ(0, registers_to_save % 2); __ jmp(&entry_label_); // We'll write the entry code later. // If the code gets too big or corrupted, an internal exception will be // raised, and we will exit right away. __ bind(&internal_failure_label_); __ li(v0, Operand(FAILURE)); __ Ret(); __ bind(&start_label_); // And then continue from here. } RegExpMacroAssemblerMIPS::~RegExpMacroAssemblerMIPS() { delete masm_; // Unuse labels in case we throw away the assembler without calling GetCode. entry_label_.Unuse(); start_label_.Unuse(); success_label_.Unuse(); backtrack_label_.Unuse(); exit_label_.Unuse(); check_preempt_label_.Unuse(); stack_overflow_label_.Unuse(); internal_failure_label_.Unuse(); } int RegExpMacroAssemblerMIPS::stack_limit_slack() { return RegExpStack::kStackLimitSlack; } void RegExpMacroAssemblerMIPS::AdvanceCurrentPosition(int by) { if (by != 0) { __ Addu(current_input_offset(), current_input_offset(), Operand(by * char_size())); } } void RegExpMacroAssemblerMIPS::AdvanceRegister(int reg, int by) { ASSERT(reg >= 0); ASSERT(reg < num_registers_); if (by != 0) { __ lw(a0, register_location(reg)); __ Addu(a0, a0, Operand(by)); __ sw(a0, register_location(reg)); } } void RegExpMacroAssemblerMIPS::Backtrack() { CheckPreemption(); // Pop Code* offset from backtrack stack, add Code* and jump to location. Pop(a0); __ Addu(a0, a0, code_pointer()); __ Jump(a0); } void RegExpMacroAssemblerMIPS::Bind(Label* label) { __ bind(label); } void RegExpMacroAssemblerMIPS::CheckCharacter(uint32_t c, Label* on_equal) { BranchOrBacktrack(on_equal, eq, current_character(), Operand(c)); } void RegExpMacroAssemblerMIPS::CheckCharacterGT(uc16 limit, Label* on_greater) { BranchOrBacktrack(on_greater, gt, current_character(), Operand(limit)); } void RegExpMacroAssemblerMIPS::CheckAtStart(Label* on_at_start) { Label not_at_start; // Did we start the match at the start of the string at all? __ lw(a0, MemOperand(frame_pointer(), kStartIndex)); BranchOrBacktrack(&not_at_start, ne, a0, Operand(zero_reg)); // If we did, are we still at the start of the input? __ lw(a1, MemOperand(frame_pointer(), kInputStart)); __ Addu(a0, end_of_input_address(), Operand(current_input_offset())); BranchOrBacktrack(on_at_start, eq, a0, Operand(a1)); __ bind(&not_at_start); } void RegExpMacroAssemblerMIPS::CheckNotAtStart(Label* on_not_at_start) { // Did we start the match at the start of the string at all? __ lw(a0, MemOperand(frame_pointer(), kStartIndex)); BranchOrBacktrack(on_not_at_start, ne, a0, Operand(zero_reg)); // If we did, are we still at the start of the input? __ lw(a1, MemOperand(frame_pointer(), kInputStart)); __ Addu(a0, end_of_input_address(), Operand(current_input_offset())); BranchOrBacktrack(on_not_at_start, ne, a0, Operand(a1)); } void RegExpMacroAssemblerMIPS::CheckCharacterLT(uc16 limit, Label* on_less) { BranchOrBacktrack(on_less, lt, current_character(), Operand(limit)); } void RegExpMacroAssemblerMIPS::CheckGreedyLoop(Label* on_equal) { Label backtrack_non_equal; __ lw(a0, MemOperand(backtrack_stackpointer(), 0)); __ Branch(&backtrack_non_equal, ne, current_input_offset(), Operand(a0)); __ Addu(backtrack_stackpointer(), backtrack_stackpointer(), Operand(kPointerSize)); __ bind(&backtrack_non_equal); BranchOrBacktrack(on_equal, eq, current_input_offset(), Operand(a0)); } void RegExpMacroAssemblerMIPS::CheckNotBackReferenceIgnoreCase( int start_reg, Label* on_no_match) { Label fallthrough; __ lw(a0, register_location(start_reg)); // Index of start of capture. __ lw(a1, register_location(start_reg + 1)); // Index of end of capture. __ Subu(a1, a1, a0); // Length of capture. // If length is zero, either the capture is empty or it is not participating. // In either case succeed immediately. __ Branch(&fallthrough, eq, a1, Operand(zero_reg)); __ Addu(t5, a1, current_input_offset()); // Check that there are enough characters left in the input. BranchOrBacktrack(on_no_match, gt, t5, Operand(zero_reg)); if (mode_ == ASCII) { Label success; Label fail; Label loop_check; // a0 - offset of start of capture. // a1 - length of capture. __ Addu(a0, a0, Operand(end_of_input_address())); __ Addu(a2, end_of_input_address(), Operand(current_input_offset())); __ Addu(a1, a0, Operand(a1)); // a0 - Address of start of capture. // a1 - Address of end of capture. // a2 - Address of current input position. Label loop; __ bind(&loop); __ lbu(a3, MemOperand(a0, 0)); __ addiu(a0, a0, char_size()); __ lbu(t0, MemOperand(a2, 0)); __ addiu(a2, a2, char_size()); __ Branch(&loop_check, eq, t0, Operand(a3)); // Mismatch, try case-insensitive match (converting letters to lower-case). __ Or(a3, a3, Operand(0x20)); // Convert capture character to lower-case. __ Or(t0, t0, Operand(0x20)); // Also convert input character. __ Branch(&fail, ne, t0, Operand(a3)); __ Subu(a3, a3, Operand('a')); __ Branch(&loop_check, ls, a3, Operand('z' - 'a')); // Latin-1: Check for values in range [224,254] but not 247. __ Subu(a3, a3, Operand(224 - 'a')); // Weren't Latin-1 letters. __ Branch(&fail, hi, a3, Operand(254 - 224)); // Check for 247. __ Branch(&fail, eq, a3, Operand(247 - 224)); __ bind(&loop_check); __ Branch(&loop, lt, a0, Operand(a1)); __ jmp(&success); __ bind(&fail); GoTo(on_no_match); __ bind(&success); // Compute new value of character position after the matched part. __ Subu(current_input_offset(), a2, end_of_input_address()); } else { ASSERT(mode_ == UC16); // Put regexp engine registers on stack. RegList regexp_registers_to_retain = current_input_offset().bit() | current_character().bit() | backtrack_stackpointer().bit(); __ MultiPush(regexp_registers_to_retain); int argument_count = 4; __ PrepareCallCFunction(argument_count, a2); // a0 - offset of start of capture. // a1 - length of capture. // Put arguments into arguments registers. // Parameters are // a0: Address byte_offset1 - Address captured substring's start. // a1: Address byte_offset2 - Address of current character position. // a2: size_t byte_length - length of capture in bytes(!). // a3: Isolate* isolate. // Address of start of capture. __ Addu(a0, a0, Operand(end_of_input_address())); // Length of capture. __ mov(a2, a1); // Save length in callee-save register for use on return. __ mov(s3, a1); // Address of current input position. __ Addu(a1, current_input_offset(), Operand(end_of_input_address())); // Isolate. __ li(a3, Operand(ExternalReference::isolate_address(masm_->isolate()))); { AllowExternalCallThatCantCauseGC scope(masm_); ExternalReference function = ExternalReference::re_case_insensitive_compare_uc16(masm_->isolate()); __ CallCFunction(function, argument_count); } // Restore regexp engine registers. __ MultiPop(regexp_registers_to_retain); __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE); __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd)); // Check if function returned non-zero for success or zero for failure. BranchOrBacktrack(on_no_match, eq, v0, Operand(zero_reg)); // On success, increment position by length of capture. __ Addu(current_input_offset(), current_input_offset(), Operand(s3)); } __ bind(&fallthrough); } void RegExpMacroAssemblerMIPS::CheckNotBackReference( int start_reg, Label* on_no_match) { Label fallthrough; Label success; // Find length of back-referenced capture. __ lw(a0, register_location(start_reg)); __ lw(a1, register_location(start_reg + 1)); __ Subu(a1, a1, a0); // Length to check. // Succeed on empty capture (including no capture). __ Branch(&fallthrough, eq, a1, Operand(zero_reg)); __ Addu(t5, a1, current_input_offset()); // Check that there are enough characters left in the input. BranchOrBacktrack(on_no_match, gt, t5, Operand(zero_reg)); // Compute pointers to match string and capture string. __ Addu(a0, a0, Operand(end_of_input_address())); __ Addu(a2, end_of_input_address(), Operand(current_input_offset())); __ Addu(a1, a1, Operand(a0)); Label loop; __ bind(&loop); if (mode_ == ASCII) { __ lbu(a3, MemOperand(a0, 0)); __ addiu(a0, a0, char_size()); __ lbu(t0, MemOperand(a2, 0)); __ addiu(a2, a2, char_size()); } else { ASSERT(mode_ == UC16); __ lhu(a3, MemOperand(a0, 0)); __ addiu(a0, a0, char_size()); __ lhu(t0, MemOperand(a2, 0)); __ addiu(a2, a2, char_size()); } BranchOrBacktrack(on_no_match, ne, a3, Operand(t0)); __ Branch(&loop, lt, a0, Operand(a1)); // Move current character position to position after match. __ Subu(current_input_offset(), a2, end_of_input_address()); __ bind(&fallthrough); } void RegExpMacroAssemblerMIPS::CheckNotCharacter(uint32_t c, Label* on_not_equal) { BranchOrBacktrack(on_not_equal, ne, current_character(), Operand(c)); } void RegExpMacroAssemblerMIPS::CheckCharacterAfterAnd(uint32_t c, uint32_t mask, Label* on_equal) { __ And(a0, current_character(), Operand(mask)); Operand rhs = (c == 0) ? Operand(zero_reg) : Operand(c); BranchOrBacktrack(on_equal, eq, a0, rhs); } void RegExpMacroAssemblerMIPS::CheckNotCharacterAfterAnd(uint32_t c, uint32_t mask, Label* on_not_equal) { __ And(a0, current_character(), Operand(mask)); Operand rhs = (c == 0) ? Operand(zero_reg) : Operand(c); BranchOrBacktrack(on_not_equal, ne, a0, rhs); } void RegExpMacroAssemblerMIPS::CheckNotCharacterAfterMinusAnd( uc16 c, uc16 minus, uc16 mask, Label* on_not_equal) { ASSERT(minus < String::kMaxUtf16CodeUnit); __ Subu(a0, current_character(), Operand(minus)); __ And(a0, a0, Operand(mask)); BranchOrBacktrack(on_not_equal, ne, a0, Operand(c)); } void RegExpMacroAssemblerMIPS::CheckCharacterInRange( uc16 from, uc16 to, Label* on_in_range) { __ Subu(a0, current_character(), Operand(from)); // Unsigned lower-or-same condition. BranchOrBacktrack(on_in_range, ls, a0, Operand(to - from)); } void RegExpMacroAssemblerMIPS::CheckCharacterNotInRange( uc16 from, uc16 to, Label* on_not_in_range) { __ Subu(a0, current_character(), Operand(from)); // Unsigned higher condition. BranchOrBacktrack(on_not_in_range, hi, a0, Operand(to - from)); } void RegExpMacroAssemblerMIPS::CheckBitInTable( Handle<ByteArray> table, Label* on_bit_set) { __ li(a0, Operand(table)); if (mode_ != ASCII || kTableMask != String::kMaxOneByteCharCode) { __ And(a1, current_character(), Operand(kTableSize - 1)); __ Addu(a0, a0, a1); } else { __ Addu(a0, a0, current_character()); } __ lbu(a0, FieldMemOperand(a0, ByteArray::kHeaderSize)); BranchOrBacktrack(on_bit_set, ne, a0, Operand(zero_reg)); } bool RegExpMacroAssemblerMIPS::CheckSpecialCharacterClass(uc16 type, Label* on_no_match) { // Range checks (c in min..max) are generally implemented by an unsigned // (c - min) <= (max - min) check. switch (type) { case 's': // Match space-characters. if (mode_ == ASCII) { // One byte space characters are '\t'..'\r', ' ' and \u00a0. Label success; __ Branch(&success, eq, current_character(), Operand(' ')); // Check range 0x09..0x0d. __ Subu(a0, current_character(), Operand('\t')); __ Branch(&success, ls, a0, Operand('\r' - '\t')); // \u00a0 (NBSP). BranchOrBacktrack(on_no_match, ne, a0, Operand(0x00a0 - '\t')); __ bind(&success); return true; } return false; case 'S': // The emitted code for generic character classes is good enough. return false; case 'd': // Match ASCII digits ('0'..'9'). __ Subu(a0, current_character(), Operand('0')); BranchOrBacktrack(on_no_match, hi, a0, Operand('9' - '0')); return true; case 'D': // Match non ASCII-digits. __ Subu(a0, current_character(), Operand('0')); BranchOrBacktrack(on_no_match, ls, a0, Operand('9' - '0')); return true; case '.': { // Match non-newlines (not 0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029). __ Xor(a0, current_character(), Operand(0x01)); // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c. __ Subu(a0, a0, Operand(0x0b)); BranchOrBacktrack(on_no_match, ls, a0, Operand(0x0c - 0x0b)); if (mode_ == UC16) { // Compare original value to 0x2028 and 0x2029, using the already // computed (current_char ^ 0x01 - 0x0b). I.e., check for // 0x201d (0x2028 - 0x0b) or 0x201e. __ Subu(a0, a0, Operand(0x2028 - 0x0b)); BranchOrBacktrack(on_no_match, ls, a0, Operand(1)); } return true; } case 'n': { // Match newlines (0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029). __ Xor(a0, current_character(), Operand(0x01)); // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c. __ Subu(a0, a0, Operand(0x0b)); if (mode_ == ASCII) { BranchOrBacktrack(on_no_match, hi, a0, Operand(0x0c - 0x0b)); } else { Label done; BranchOrBacktrack(&done, ls, a0, Operand(0x0c - 0x0b)); // Compare original value to 0x2028 and 0x2029, using the already // computed (current_char ^ 0x01 - 0x0b). I.e., check for // 0x201d (0x2028 - 0x0b) or 0x201e. __ Subu(a0, a0, Operand(0x2028 - 0x0b)); BranchOrBacktrack(on_no_match, hi, a0, Operand(1)); __ bind(&done); } return true; } case 'w': { if (mode_ != ASCII) { // Table is 128 entries, so all ASCII characters can be tested. BranchOrBacktrack(on_no_match, hi, current_character(), Operand('z')); } ExternalReference map = ExternalReference::re_word_character_map(); __ li(a0, Operand(map)); __ Addu(a0, a0, current_character()); __ lbu(a0, MemOperand(a0, 0)); BranchOrBacktrack(on_no_match, eq, a0, Operand(zero_reg)); return true; } case 'W': { Label done; if (mode_ != ASCII) { // Table is 128 entries, so all ASCII characters can be tested. __ Branch(&done, hi, current_character(), Operand('z')); } ExternalReference map = ExternalReference::re_word_character_map(); __ li(a0, Operand(map)); __ Addu(a0, a0, current_character()); __ lbu(a0, MemOperand(a0, 0)); BranchOrBacktrack(on_no_match, ne, a0, Operand(zero_reg)); if (mode_ != ASCII) { __ bind(&done); } return true; } case '*': // Match any character. return true; // No custom implementation (yet): s(UC16), S(UC16). default: return false; } } void RegExpMacroAssemblerMIPS::Fail() { __ li(v0, Operand(FAILURE)); __ jmp(&exit_label_); } Handle<HeapObject> RegExpMacroAssemblerMIPS::GetCode(Handle<String> source) { Label return_v0; if (masm_->has_exception()) { // If the code gets corrupted due to long regular expressions and lack of // space on trampolines, an internal exception flag is set. If this case // is detected, we will jump into exit sequence right away. __ bind_to(&entry_label_, internal_failure_label_.pos()); } else { // Finalize code - write the entry point code now we know how many // registers we need. // Entry code: __ bind(&entry_label_); // Tell the system that we have a stack frame. Because the type is MANUAL, // no is generated. FrameScope scope(masm_, StackFrame::MANUAL); // Actually emit code to start a new stack frame. // Push arguments // Save callee-save registers. // Start new stack frame. // Store link register in existing stack-cell. // Order here should correspond to order of offset constants in header file. RegList registers_to_retain = s0.bit() | s1.bit() | s2.bit() | s3.bit() | s4.bit() | s5.bit() | s6.bit() | s7.bit() | fp.bit(); RegList argument_registers = a0.bit() | a1.bit() | a2.bit() | a3.bit(); __ MultiPush(argument_registers | registers_to_retain | ra.bit()); // Set frame pointer in space for it if this is not a direct call // from generated code. __ Addu(frame_pointer(), sp, Operand(4 * kPointerSize)); __ mov(a0, zero_reg); __ push(a0); // Make room for success counter and initialize it to 0. __ push(a0); // Make room for "position - 1" constant (value irrelevant). // Check if we have space on the stack for registers. Label stack_limit_hit; Label stack_ok; ExternalReference stack_limit = ExternalReference::address_of_stack_limit(masm_->isolate()); __ li(a0, Operand(stack_limit)); __ lw(a0, MemOperand(a0)); __ Subu(a0, sp, a0); // Handle it if the stack pointer is already below the stack limit. __ Branch(&stack_limit_hit, le, a0, Operand(zero_reg)); // Check if there is room for the variable number of registers above // the stack limit. __ Branch(&stack_ok, hs, a0, Operand(num_registers_ * kPointerSize)); // Exit with OutOfMemory exception. There is not enough space on the stack // for our working registers. __ li(v0, Operand(EXCEPTION)); __ jmp(&return_v0); __ bind(&stack_limit_hit); CallCheckStackGuardState(a0); // If returned value is non-zero, we exit with the returned value as result. __ Branch(&return_v0, ne, v0, Operand(zero_reg)); __ bind(&stack_ok); // Allocate space on stack for registers. __ Subu(sp, sp, Operand(num_registers_ * kPointerSize)); // Load string end. __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd)); // Load input start. __ lw(a0, MemOperand(frame_pointer(), kInputStart)); // Find negative length (offset of start relative to end). __ Subu(current_input_offset(), a0, end_of_input_address()); // Set a0 to address of char before start of the input string // (effectively string position -1). __ lw(a1, MemOperand(frame_pointer(), kStartIndex)); __ Subu(a0, current_input_offset(), Operand(char_size())); __ sll(t5, a1, (mode_ == UC16) ? 1 : 0); __ Subu(a0, a0, t5); // Store this value in a local variable, for use when clearing // position registers. __ sw(a0, MemOperand(frame_pointer(), kInputStartMinusOne)); // Initialize code pointer register __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE); Label load_char_start_regexp, start_regexp; // Load newline if index is at start, previous character otherwise. __ Branch(&load_char_start_regexp, ne, a1, Operand(zero_reg)); __ li(current_character(), Operand('\n')); __ jmp(&start_regexp); // Global regexp restarts matching here. __ bind(&load_char_start_regexp); // Load previous char as initial value of current character register. LoadCurrentCharacterUnchecked(-1, 1); __ bind(&start_regexp); // Initialize on-stack registers. if (num_saved_registers_ > 0) { // Always is, if generated from a regexp. // Fill saved registers with initial value = start offset - 1. if (num_saved_registers_ > 8) { // Address of register 0. __ Addu(a1, frame_pointer(), Operand(kRegisterZero)); __ li(a2, Operand(num_saved_registers_)); Label init_loop; __ bind(&init_loop); __ sw(a0, MemOperand(a1)); __ Addu(a1, a1, Operand(-kPointerSize)); __ Subu(a2, a2, Operand(1)); __ Branch(&init_loop, ne, a2, Operand(zero_reg)); } else { for (int i = 0; i < num_saved_registers_; i++) { __ sw(a0, register_location(i)); } } } // Initialize backtrack stack pointer. __ lw(backtrack_stackpointer(), MemOperand(frame_pointer(), kStackHighEnd)); __ jmp(&start_label_); // Exit code: if (success_label_.is_linked()) { // Save captures when successful. __ bind(&success_label_); if (num_saved_registers_ > 0) { // Copy captures to output. __ lw(a1, MemOperand(frame_pointer(), kInputStart)); __ lw(a0, MemOperand(frame_pointer(), kRegisterOutput)); __ lw(a2, MemOperand(frame_pointer(), kStartIndex)); __ Subu(a1, end_of_input_address(), a1); // a1 is length of input in bytes. if (mode_ == UC16) { __ srl(a1, a1, 1); } // a1 is length of input in characters. __ Addu(a1, a1, Operand(a2)); // a1 is length of string in characters. ASSERT_EQ(0, num_saved_registers_ % 2); // Always an even number of capture registers. This allows us to // unroll the loop once to add an operation between a load of a register // and the following use of that register. for (int i = 0; i < num_saved_registers_; i += 2) { __ lw(a2, register_location(i)); __ lw(a3, register_location(i + 1)); if (i == 0 && global_with_zero_length_check()) { // Keep capture start in a4 for the zero-length check later. __ mov(t7, a2); } if (mode_ == UC16) { __ sra(a2, a2, 1); __ Addu(a2, a2, a1); __ sra(a3, a3, 1); __ Addu(a3, a3, a1); } else { __ Addu(a2, a1, Operand(a2)); __ Addu(a3, a1, Operand(a3)); } __ sw(a2, MemOperand(a0)); __ Addu(a0, a0, kPointerSize); __ sw(a3, MemOperand(a0)); __ Addu(a0, a0, kPointerSize); } } if (global()) { // Restart matching if the regular expression is flagged as global. __ lw(a0, MemOperand(frame_pointer(), kSuccessfulCaptures)); __ lw(a1, MemOperand(frame_pointer(), kNumOutputRegisters)); __ lw(a2, MemOperand(frame_pointer(), kRegisterOutput)); // Increment success counter. __ Addu(a0, a0, 1); __ sw(a0, MemOperand(frame_pointer(), kSuccessfulCaptures)); // Capture results have been stored, so the number of remaining global // output registers is reduced by the number of stored captures. __ Subu(a1, a1, num_saved_registers_); // Check whether we have enough room for another set of capture results. __ mov(v0, a0); __ Branch(&return_v0, lt, a1, Operand(num_saved_registers_)); __ sw(a1, MemOperand(frame_pointer(), kNumOutputRegisters)); // Advance the location for output. __ Addu(a2, a2, num_saved_registers_ * kPointerSize); __ sw(a2, MemOperand(frame_pointer(), kRegisterOutput)); // Prepare a0 to initialize registers with its value in the next run. __ lw(a0, MemOperand(frame_pointer(), kInputStartMinusOne)); if (global_with_zero_length_check()) { // Special case for zero-length matches. // t7: capture start index // Not a zero-length match, restart. __ Branch( &load_char_start_regexp, ne, current_input_offset(), Operand(t7)); // Offset from the end is zero if we already reached the end. __ Branch(&exit_label_, eq, current_input_offset(), Operand(zero_reg)); // Advance current position after a zero-length match. __ Addu(current_input_offset(), current_input_offset(), Operand((mode_ == UC16) ? 2 : 1)); } __ Branch(&load_char_start_regexp); } else { __ li(v0, Operand(SUCCESS)); } } // Exit and return v0. __ bind(&exit_label_); if (global()) { __ lw(v0, MemOperand(frame_pointer(), kSuccessfulCaptures)); } __ bind(&return_v0); // Skip sp past regexp registers and local variables.. __ mov(sp, frame_pointer()); // Restore registers s0..s7 and return (restoring ra to pc). __ MultiPop(registers_to_retain | ra.bit()); __ Ret(); // Backtrack code (branch target for conditional backtracks). if (backtrack_label_.is_linked()) { __ bind(&backtrack_label_); Backtrack(); } Label exit_with_exception; // Preempt-code. if (check_preempt_label_.is_linked()) { SafeCallTarget(&check_preempt_label_); // Put regexp engine registers on stack. RegList regexp_registers_to_retain = current_input_offset().bit() | current_character().bit() | backtrack_stackpointer().bit(); __ MultiPush(regexp_registers_to_retain); CallCheckStackGuardState(a0); __ MultiPop(regexp_registers_to_retain); // If returning non-zero, we should end execution with the given // result as return value. __ Branch(&return_v0, ne, v0, Operand(zero_reg)); // String might have moved: Reload end of string from frame. __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd)); __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE); SafeReturn(); } // Backtrack stack overflow code. if (stack_overflow_label_.is_linked()) { SafeCallTarget(&stack_overflow_label_); // Reached if the backtrack-stack limit has been hit. // Put regexp engine registers on stack first. RegList regexp_registers = current_input_offset().bit() | current_character().bit(); __ MultiPush(regexp_registers); Label grow_failed; // Call GrowStack(backtrack_stackpointer(), &stack_base) static const int num_arguments = 3; __ PrepareCallCFunction(num_arguments, a0); __ mov(a0, backtrack_stackpointer()); __ Addu(a1, frame_pointer(), Operand(kStackHighEnd)); __ li(a2, Operand(ExternalReference::isolate_address(masm_->isolate()))); ExternalReference grow_stack = ExternalReference::re_grow_stack(masm_->isolate()); __ CallCFunction(grow_stack, num_arguments); // Restore regexp registers. __ MultiPop(regexp_registers); // If return NULL, we have failed to grow the stack, and // must exit with a stack-overflow exception. __ Branch(&exit_with_exception, eq, v0, Operand(zero_reg)); // Otherwise use return value as new stack pointer. __ mov(backtrack_stackpointer(), v0); // Restore saved registers and continue. __ li(code_pointer(), Operand(masm_->CodeObject()), CONSTANT_SIZE); __ lw(end_of_input_address(), MemOperand(frame_pointer(), kInputEnd)); SafeReturn(); } if (exit_with_exception.is_linked()) { // If any of the code above needed to exit with an exception. __ bind(&exit_with_exception); // Exit with Result EXCEPTION(-1) to signal thrown exception. __ li(v0, Operand(EXCEPTION)); __ jmp(&return_v0); } } CodeDesc code_desc; masm_->GetCode(&code_desc); Handle<Code> code = isolate()->factory()->NewCode( code_desc, Code::ComputeFlags(Code::REGEXP), masm_->CodeObject()); LOG(masm_->isolate(), RegExpCodeCreateEvent(*code, *source)); return Handle<HeapObject>::cast(code); } void RegExpMacroAssemblerMIPS::GoTo(Label* to) { if (to == NULL) { Backtrack(); return; } __ jmp(to); return; } void RegExpMacroAssemblerMIPS::IfRegisterGE(int reg, int comparand, Label* if_ge) { __ lw(a0, register_location(reg)); BranchOrBacktrack(if_ge, ge, a0, Operand(comparand)); } void RegExpMacroAssemblerMIPS::IfRegisterLT(int reg, int comparand, Label* if_lt) { __ lw(a0, register_location(reg)); BranchOrBacktrack(if_lt, lt, a0, Operand(comparand)); } void RegExpMacroAssemblerMIPS::IfRegisterEqPos(int reg, Label* if_eq) { __ lw(a0, register_location(reg)); BranchOrBacktrack(if_eq, eq, a0, Operand(current_input_offset())); } RegExpMacroAssembler::IrregexpImplementation RegExpMacroAssemblerMIPS::Implementation() { return kMIPSImplementation; } void RegExpMacroAssemblerMIPS::LoadCurrentCharacter(int cp_offset, Label* on_end_of_input, bool check_bounds, int characters) { ASSERT(cp_offset >= -1); // ^ and \b can look behind one character. ASSERT(cp_offset < (1<<30)); // Be sane! (And ensure negation works). if (check_bounds) { CheckPosition(cp_offset + characters - 1, on_end_of_input); } LoadCurrentCharacterUnchecked(cp_offset, characters); } void RegExpMacroAssemblerMIPS::PopCurrentPosition() { Pop(current_input_offset()); } void RegExpMacroAssemblerMIPS::PopRegister(int register_index) { Pop(a0); __ sw(a0, register_location(register_index)); } void RegExpMacroAssemblerMIPS::PushBacktrack(Label* label) { if (label->is_bound()) { int target = label->pos(); __ li(a0, Operand(target + Code::kHeaderSize - kHeapObjectTag)); } else { Assembler::BlockTrampolinePoolScope block_trampoline_pool(masm_); Label after_constant; __ Branch(&after_constant); int offset = masm_->pc_offset(); int cp_offset = offset + Code::kHeaderSize - kHeapObjectTag; __ emit(0); masm_->label_at_put(label, offset); __ bind(&after_constant); if (is_int16(cp_offset)) { __ lw(a0, MemOperand(code_pointer(), cp_offset)); } else { __ Addu(a0, code_pointer(), cp_offset); __ lw(a0, MemOperand(a0, 0)); } } Push(a0); CheckStackLimit(); } void RegExpMacroAssemblerMIPS::PushCurrentPosition() { Push(current_input_offset()); } void RegExpMacroAssemblerMIPS::PushRegister(int register_index, StackCheckFlag check_stack_limit) { __ lw(a0, register_location(register_index)); Push(a0); if (check_stack_limit) CheckStackLimit(); } void RegExpMacroAssemblerMIPS::ReadCurrentPositionFromRegister(int reg) { __ lw(current_input_offset(), register_location(reg)); } void RegExpMacroAssemblerMIPS::ReadStackPointerFromRegister(int reg) { __ lw(backtrack_stackpointer(), register_location(reg)); __ lw(a0, MemOperand(frame_pointer(), kStackHighEnd)); __ Addu(backtrack_stackpointer(), backtrack_stackpointer(), Operand(a0)); } void RegExpMacroAssemblerMIPS::SetCurrentPositionFromEnd(int by) { Label after_position; __ Branch(&after_position, ge, current_input_offset(), Operand(-by * char_size())); __ li(current_input_offset(), -by * char_size()); // On RegExp code entry (where this operation is used), the character before // the current position is expected to be already loaded. // We have advanced the position, so it's safe to read backwards. LoadCurrentCharacterUnchecked(-1, 1); __ bind(&after_position); } void RegExpMacroAssemblerMIPS::SetRegister(int register_index, int to) { ASSERT(register_index >= num_saved_registers_); // Reserved for positions! __ li(a0, Operand(to)); __ sw(a0, register_location(register_index)); } bool RegExpMacroAssemblerMIPS::Succeed() { __ jmp(&success_label_); return global(); } void RegExpMacroAssemblerMIPS::WriteCurrentPositionToRegister(int reg, int cp_offset) { if (cp_offset == 0) { __ sw(current_input_offset(), register_location(reg)); } else { __ Addu(a0, current_input_offset(), Operand(cp_offset * char_size())); __ sw(a0, register_location(reg)); } } void RegExpMacroAssemblerMIPS::ClearRegisters(int reg_from, int reg_to) { ASSERT(reg_from <= reg_to); __ lw(a0, MemOperand(frame_pointer(), kInputStartMinusOne)); for (int reg = reg_from; reg <= reg_to; reg++) { __ sw(a0, register_location(reg)); } } void RegExpMacroAssemblerMIPS::WriteStackPointerToRegister(int reg) { __ lw(a1, MemOperand(frame_pointer(), kStackHighEnd)); __ Subu(a0, backtrack_stackpointer(), a1); __ sw(a0, register_location(reg)); } bool RegExpMacroAssemblerMIPS::CanReadUnaligned() { return false; } // Private methods: void RegExpMacroAssemblerMIPS::CallCheckStackGuardState(Register scratch) { int stack_alignment = base::OS::ActivationFrameAlignment(); // Align the stack pointer and save the original sp value on the stack. __ mov(scratch, sp); __ Subu(sp, sp, Operand(kPointerSize)); ASSERT(IsPowerOf2(stack_alignment)); __ And(sp, sp, Operand(-stack_alignment)); __ sw(scratch, MemOperand(sp)); __ mov(a2, frame_pointer()); // Code* of self. __ li(a1, Operand(masm_->CodeObject()), CONSTANT_SIZE); // We need to make room for the return address on the stack. ASSERT(IsAligned(stack_alignment, kPointerSize)); __ Subu(sp, sp, Operand(stack_alignment)); // Stack pointer now points to cell where return address is to be written. // Arguments are in registers, meaning we teat the return address as // argument 5. Since DirectCEntryStub will handleallocating space for the C // argument slots, we don't need to care about that here. This is how the // stack will look (sp meaning the value of sp at this moment): // [sp + 3] - empty slot if needed for alignment. // [sp + 2] - saved sp. // [sp + 1] - second word reserved for return value. // [sp + 0] - first word reserved for return value. // a0 will point to the return address, placed by DirectCEntry. __ mov(a0, sp); ExternalReference stack_guard_check = ExternalReference::re_check_stack_guard_state(masm_->isolate()); __ li(t9, Operand(stack_guard_check)); DirectCEntryStub stub(isolate()); stub.GenerateCall(masm_, t9); // DirectCEntryStub allocated space for the C argument slots so we have to // drop them with the return address from the stack with loading saved sp. // At this point stack must look: // [sp + 7] - empty slot if needed for alignment. // [sp + 6] - saved sp. // [sp + 5] - second word reserved for return value. // [sp + 4] - first word reserved for return value. // [sp + 3] - C argument slot. // [sp + 2] - C argument slot. // [sp + 1] - C argument slot. // [sp + 0] - C argument slot. __ lw(sp, MemOperand(sp, stack_alignment + kCArgsSlotsSize)); __ li(code_pointer(), Operand(masm_->CodeObject())); } // Helper function for reading a value out of a stack frame. template <typename T> static T& frame_entry(Address re_frame, int frame_offset) { return reinterpret_cast<T&>(Memory::int32_at(re_frame + frame_offset)); } int RegExpMacroAssemblerMIPS::CheckStackGuardState(Address* return_address, Code* re_code, Address re_frame) { Isolate* isolate = frame_entry<Isolate*>(re_frame, kIsolate); StackLimitCheck check(isolate); if (check.JsHasOverflowed()) { isolate->StackOverflow(); return EXCEPTION; } // If not real stack overflow the stack guard was used to interrupt // execution for another purpose. // If this is a direct call from JavaScript retry the RegExp forcing the call // through the runtime system. Currently the direct call cannot handle a GC. if (frame_entry<int>(re_frame, kDirectCall) == 1) { return RETRY; } // Prepare for possible GC. HandleScope handles(isolate); Handle<Code> code_handle(re_code); Handle<String> subject(frame_entry<String*>(re_frame, kInputString)); // Current string. bool is_ascii = subject->IsOneByteRepresentationUnderneath(); ASSERT(re_code->instruction_start() <= *return_address); ASSERT(*return_address <= re_code->instruction_start() + re_code->instruction_size()); Object* result = isolate->stack_guard()->HandleInterrupts(); if (*code_handle != re_code) { // Return address no longer valid. int delta = code_handle->address() - re_code->address(); // Overwrite the return address on the stack. *return_address += delta; } if (result->IsException()) { return EXCEPTION; } Handle<String> subject_tmp = subject; int slice_offset = 0; // Extract the underlying string and the slice offset. if (StringShape(*subject_tmp).IsCons()) { subject_tmp = Handle<String>(ConsString::cast(*subject_tmp)->first()); } else if (StringShape(*subject_tmp).IsSliced()) { SlicedString* slice = SlicedString::cast(*subject_tmp); subject_tmp = Handle<String>(slice->parent()); slice_offset = slice->offset(); } // String might have changed. if (subject_tmp->IsOneByteRepresentation() != is_ascii) { // If we changed between an ASCII and an UC16 string, the specialized // code cannot be used, and we need to restart regexp matching from // scratch (including, potentially, compiling a new version of the code). return RETRY; } // Otherwise, the content of the string might have moved. It must still // be a sequential or external string with the same content. // Update the start and end pointers in the stack frame to the current // location (whether it has actually moved or not). ASSERT(StringShape(*subject_tmp).IsSequential() || StringShape(*subject_tmp).IsExternal()); // The original start address of the characters to match. const byte* start_address = frame_entry<const byte*>(re_frame, kInputStart); // Find the current start address of the same character at the current string // position. int start_index = frame_entry<int>(re_frame, kStartIndex); const byte* new_address = StringCharacterPosition(*subject_tmp, start_index + slice_offset); if (start_address != new_address) { // If there is a difference, update the object pointer and start and end // addresses in the RegExp stack frame to match the new value. const byte* end_address = frame_entry<const byte* >(re_frame, kInputEnd); int byte_length = static_cast<int>(end_address - start_address); frame_entry<const String*>(re_frame, kInputString) = *subject; frame_entry<const byte*>(re_frame, kInputStart) = new_address; frame_entry<const byte*>(re_frame, kInputEnd) = new_address + byte_length; } else if (frame_entry<const String*>(re_frame, kInputString) != *subject) { // Subject string might have been a ConsString that underwent // short-circuiting during GC. That will not change start_address but // will change pointer inside the subject handle. frame_entry<const String*>(re_frame, kInputString) = *subject; } return 0; } MemOperand RegExpMacroAssemblerMIPS::register_location(int register_index) { ASSERT(register_index < (1<<30)); if (num_registers_ <= register_index) { num_registers_ = register_index + 1; } return MemOperand(frame_pointer(), kRegisterZero - register_index * kPointerSize); } void RegExpMacroAssemblerMIPS::CheckPosition(int cp_offset, Label* on_outside_input) { BranchOrBacktrack(on_outside_input, ge, current_input_offset(), Operand(-cp_offset * char_size())); } void RegExpMacroAssemblerMIPS::BranchOrBacktrack(Label* to, Condition condition, Register rs, const Operand& rt) { if (condition == al) { // Unconditional. if (to == NULL) { Backtrack(); return; } __ jmp(to); return; } if (to == NULL) { __ Branch(&backtrack_label_, condition, rs, rt); return; } __ Branch(to, condition, rs, rt); } void RegExpMacroAssemblerMIPS::SafeCall(Label* to, Condition cond, Register rs, const Operand& rt) { __ BranchAndLink(to, cond, rs, rt); } void RegExpMacroAssemblerMIPS::SafeReturn() { __ pop(ra); __ Addu(t5, ra, Operand(masm_->CodeObject())); __ Jump(t5); } void RegExpMacroAssemblerMIPS::SafeCallTarget(Label* name) { __ bind(name); __ Subu(ra, ra, Operand(masm_->CodeObject())); __ push(ra); } void RegExpMacroAssemblerMIPS::Push(Register source) { ASSERT(!source.is(backtrack_stackpointer())); __ Addu(backtrack_stackpointer(), backtrack_stackpointer(), Operand(-kPointerSize)); __ sw(source, MemOperand(backtrack_stackpointer())); } void RegExpMacroAssemblerMIPS::Pop(Register target) { ASSERT(!target.is(backtrack_stackpointer())); __ lw(target, MemOperand(backtrack_stackpointer())); __ Addu(backtrack_stackpointer(), backtrack_stackpointer(), kPointerSize); } void RegExpMacroAssemblerMIPS::CheckPreemption() { // Check for preemption. ExternalReference stack_limit = ExternalReference::address_of_stack_limit(masm_->isolate()); __ li(a0, Operand(stack_limit)); __ lw(a0, MemOperand(a0)); SafeCall(&check_preempt_label_, ls, sp, Operand(a0)); } void RegExpMacroAssemblerMIPS::CheckStackLimit() { ExternalReference stack_limit = ExternalReference::address_of_regexp_stack_limit(masm_->isolate()); __ li(a0, Operand(stack_limit)); __ lw(a0, MemOperand(a0)); SafeCall(&stack_overflow_label_, ls, backtrack_stackpointer(), Operand(a0)); } void RegExpMacroAssemblerMIPS::LoadCurrentCharacterUnchecked(int cp_offset, int characters) { Register offset = current_input_offset(); if (cp_offset != 0) { // t7 is not being used to store the capture start index at this point. __ Addu(t7, current_input_offset(), Operand(cp_offset * char_size())); offset = t7; } // We assume that we cannot do unaligned loads on MIPS, so this function // must only be used to load a single character at a time. ASSERT(characters == 1); __ Addu(t5, end_of_input_address(), Operand(offset)); if (mode_ == ASCII) { __ lbu(current_character(), MemOperand(t5, 0)); } else { ASSERT(mode_ == UC16); __ lhu(current_character(), MemOperand(t5, 0)); } } #undef __ #endif // V8_INTERPRETED_REGEXP }} // namespace v8::internal #endif // V8_TARGET_ARCH_MIPS
[ "notmycupoftea@163.com" ]
notmycupoftea@163.com
d0d487bd9bd02467d59f9e90e7292ec5ba049e48
7e167301a49a7b7ac6ff8b23dc696b10ec06bd4b
/prev_work/opensource/fMRI/FSL/fsl/extras/include/boost/boost/mpl/set/aux_/erase_impl.hpp
78d44257327a4d079b46ba169e54d89a6516063f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Sejik/SignalAnalysis
6c6245880b0017e9f73b5a343641065eb49e5989
c04118369dbba807d99738accb8021d77ff77cb6
refs/heads/master
2020-06-09T12:47:30.314791
2019-09-06T01:31:16
2019-09-06T01:31:16
193,439,385
5
4
null
null
null
null
UTF-8
C++
false
false
1,016
hpp
#ifndef BOOST_MPL_SET_AUX_ERASE_IMPL_HPP_INCLUDED #define BOOST_MPL_SET_AUX_ERASE_IMPL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /usr/local/share/sources/boost/boost/mpl/set/aux_/erase_impl.hpp,v $ // $Date: 2007/06/12 15:03:24 $ // $Revision: 1.1.1.1 $ #include <boost/mpl/erase_fwd.hpp> #include <boost/mpl/set/aux_/erase_key_impl.hpp> #include <boost/mpl/set/aux_/tag.hpp> namespace boost { namespace mpl { template<> struct erase_impl< aux::set_tag > { template< typename Set , typename Pos , typename unused_ > struct apply : erase_key_impl<aux::set_tag> ::apply<Set,typename Pos::type> { }; }; }} #endif // BOOST_MPL_SET_AUX_ERASE_IMPL_HPP_INCLUDED
[ "sejik6307@gmail.com" ]
sejik6307@gmail.com
b5ab67db1e34f5bb7d89e19dcf39137450915398
e393fad837587692fa7dba237856120afbfbe7e8
/contest/atcoder/abc/abc112/d.cpp
c1fed1f94e9e05ee389dbf6c18b5dc77f72519b0
[]
no_license
XapiMa/procon
83e36c93dc55f4270673ac459f8c59bacb8c6924
e679cd5d3c325496490681c9126b8b6b546e0f27
refs/heads/master
2020-05-03T20:18:47.783312
2019-05-31T12:33:33
2019-05-31T12:33:33
178,800,254
0
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include <bits/stdc++.h> using namespace std; #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define REP(i, k, n) for(int i = k; i < (int)(n); i++) const int maxN = int(1e5 + 10); int e[maxN] = {}, o[maxN] = {}; int num[maxN] = {}; using ll = long long; int main() { ll n, m; ll ans = 0; cin >> n >> m; for(ll i = 1; i * i <= m; i++) { if(m % i == 0) { ll i1 = i, i2 = m / i; if(n * i1 <= m && ans < i1) { ans = i1; } if(n * i2 <= m && ans < i2) { ans = i2; } } } cout << ans << endl; return 0; }
[ "hurry4170@gmail.com" ]
hurry4170@gmail.com
511a3a4ea9b46876efa162b35e09a5464c00922f
7f7e5a5f70dc3f1d0bdcd3c526d21b27508979a2
/Asteroids_A_La_Mode/Intermediate/Plugins/NativizedAssets/Windows/Game/Intermediate/Build/Win64/UE4/Inc/NativizedAssets/Coop__pf1232574660.generated.h
d96aba27c1ffcf03eea4dc1d544d4ad6fdfe24c7
[]
no_license
Haczar/Asteroids_a_la_Mode
b363c327580681c2399fa3f28e0f0f54e1f06288
03dfe2ff7bacd57ec8691d6f0ae8ac8be1ae7c23
refs/heads/master
2021-09-11T16:58:35.026311
2018-04-10T03:17:41
2018-04-10T03:17:41
124,698,574
2
1
null
null
null
null
UTF-8
C++
false
false
9,644
h
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "ObjectMacros.h" #include "ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS enum class E__ECoOpSel__pf : uint8; class UTextBlock; struct FSlateColor; #ifdef NATIVIZEDASSETS_Coop__pf1232574660_generated_h #error "Coop__pf1232574660.generated.h already included, missing '#pragma once' in Coop__pf1232574660.h" #endif #define NATIVIZEDASSETS_Coop__pf1232574660_generated_h #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execbpf__SetxAlphaxxMenuxItemx__pfTTLTK) \ { \ P_GET_ENUM(E__ECoOpSel__pf,Z_Param_bpp__Selection__pf); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__SetxAlphaxxMenuxItemx__pfTTLTK(E__ECoOpSel__pf(Z_Param_bpp__Selection__pf)); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__RevertxAlphaxxMenuxItemx__pfTTLTK) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__RevertxAlphaxxMenuxItemx__pfTTLTK(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__SetxObjxxColorxandxOpacity__pfT3TTT) \ { \ P_GET_OBJECT(UTextBlock,Z_Param_bpp__TextxObj__pfT); \ P_GET_STRUCT(FSlateColor,Z_Param_bpp__ColorxandxAlpha__pfTT); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__SetxObjxxColorxandxOpacity__pfT3TTT(Z_Param_bpp__TextxObj__pfT,Z_Param_bpp__ColorxandxAlpha__pfTT); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MovexUp__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MovexUp__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MovexDown__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MovexDown__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MenuxSelect__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MenuxSelect__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MenuxBack__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MenuxBack__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__Construct__pf) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__Construct__pf(); \ P_NATIVE_END; \ } #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execbpf__SetxAlphaxxMenuxItemx__pfTTLTK) \ { \ P_GET_ENUM(E__ECoOpSel__pf,Z_Param_bpp__Selection__pf); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__SetxAlphaxxMenuxItemx__pfTTLTK(E__ECoOpSel__pf(Z_Param_bpp__Selection__pf)); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__RevertxAlphaxxMenuxItemx__pfTTLTK) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__RevertxAlphaxxMenuxItemx__pfTTLTK(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__SetxObjxxColorxandxOpacity__pfT3TTT) \ { \ P_GET_OBJECT(UTextBlock,Z_Param_bpp__TextxObj__pfT); \ P_GET_STRUCT(FSlateColor,Z_Param_bpp__ColorxandxAlpha__pfTT); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__SetxObjxxColorxandxOpacity__pfT3TTT(Z_Param_bpp__TextxObj__pfT,Z_Param_bpp__ColorxandxAlpha__pfTT); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MovexUp__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MovexUp__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MovexDown__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MovexDown__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MenuxSelect__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MenuxSelect__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__MenuxBack__pfT) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__MenuxBack__pfT(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execbpf__Construct__pf) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->bpf__Construct__pf(); \ P_NATIVE_END; \ } #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_EVENT_PARMS #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_CALLBACK_WRAPPERS \ void eventbpf__Construct__pf(); \ #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUCoop_C__pf1232574660(); \ friend NATIVIZEDASSETS_API class UClass* Z_Construct_UClass_UCoop_C__pf1232574660(); \ public: \ DECLARE_CLASS(UCoop_C__pf1232574660, UUserWidget, COMPILED_IN_FLAGS(0), 0, TEXT("/Game/UserInterface/MainScreen/Coop"), NO_API) \ DECLARE_SERIALIZER(UCoop_C__pf1232574660) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; \ static const TCHAR* StaticConfigName() {return TEXT("Engine");} \ #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_INCLASS \ private: \ static void StaticRegisterNativesUCoop_C__pf1232574660(); \ friend NATIVIZEDASSETS_API class UClass* Z_Construct_UClass_UCoop_C__pf1232574660(); \ public: \ DECLARE_CLASS(UCoop_C__pf1232574660, UUserWidget, COMPILED_IN_FLAGS(0), 0, TEXT("/Game/UserInterface/MainScreen/Coop"), NO_API) \ DECLARE_SERIALIZER(UCoop_C__pf1232574660) \ enum {IsIntrinsic=COMPILED_IN_INTRINSIC}; \ static const TCHAR* StaticConfigName() {return TEXT("Engine");} \ #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API UCoop_C__pf1232574660(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UCoop_C__pf1232574660) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UCoop_C__pf1232574660); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UCoop_C__pf1232574660); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UCoop_C__pf1232574660(UCoop_C__pf1232574660&&); \ NO_API UCoop_C__pf1232574660(const UCoop_C__pf1232574660&); \ public: #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API UCoop_C__pf1232574660(UCoop_C__pf1232574660&&); \ NO_API UCoop_C__pf1232574660(const UCoop_C__pf1232574660&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UCoop_C__pf1232574660); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UCoop_C__pf1232574660); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UCoop_C__pf1232574660) #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_PRIVATE_PROPERTY_OFFSET #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_12_PROLOG \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_EVENT_PARMS #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_PRIVATE_PROPERTY_OFFSET \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_RPC_WRAPPERS \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_CALLBACK_WRAPPERS \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_INCLASS \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_PRIVATE_PROPERTY_OFFSET \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_RPC_WRAPPERS_NO_PURE_DECLS \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_CALLBACK_WRAPPERS \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_INCLASS_NO_PURE_DECLS \ Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h_16_ENHANCED_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID Asteroids_A_La_Mode_Intermediate_Plugins_NativizedAssets_Windows_Game_Source_NativizedAssets_Public_Coop__pf1232574660_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "edwardgz@gmail.com" ]
edwardgz@gmail.com
1fa1b60da344cfb9fb2685cfff94698df2816106
c1f9d441613a2cce25eaf3e1d0c4e99067c066d8
/Shirodora/Classes/Factory/King/CreateFactory/KingCreateFactory.hpp
5c80eeee43a70410fe4a35197dc85b7bcb28a1e1
[ "MIT" ]
permissive
shirodora2/Shirodora2
d8fb0add67f3bcfb58b949555164491e31b97bca
f11ec413e13182367cf56ac20e5e0fc4a7bb517d
refs/heads/master
2020-12-29T00:55:06.206040
2016-09-10T03:07:52
2016-09-10T03:07:52
62,932,205
0
1
null
null
null
null
UTF-8
C++
false
false
2,619
hpp
// // CreateFactory.hpp // Shirodora // // Created by 服部優宇一 on 2016/08/20. // // #ifndef KingCreateFactory_hpp #define KingCreateFactory_hpp #include <stdio.h> //========================================================================= // 前方宣言 //========================================================================= class CKing ; //========================================================================= // // SummonCreateFactory // //========================================================================= class CKingCreateFactory { public : //========================================================================= // コンストラクタ/デストラクタ //========================================================================= /** * @desc destructor */ virtual ~CKingCreateFactory() ; //========================================================================= // メンバ関数 //========================================================================= /** * @desc キング生成 * @param タグ * @param 生成位置 */ CKing *create(int tag, const cocos2d::Vec2 &position) ; private : //========================================================================= // メンバ関数 //========================================================================= /** * @desc キング生成とメンバ変数取り付け */ CKing *create() ; /** * @desc 位置データ設定 * @param CKing* */ virtual void setMove(CKing* , const cocos2d::Vec2 &position) = 0 ; /** * @desc 画像データ設定 * @param CKing* */ virtual void setSprite(CKing*) = 0 ; /** * @desc ステータス設定 * @param CKing* */ virtual void setStatus(CKing*) = 0 ; /** * @desc 実体データ設定 * @param CKing* */ virtual void setCollisionBody(CKing*) = 0 ; /** * @desc 攻撃範囲データ設定 * @param CKing* */ virtual void setAttackBody(CKing*) = 0 ; /** * @desc アニメーションデータ設定 * @param CKing* */ virtual void setAnimation(CKing*) = 0 ; /** * @desc アクションデータ設定 * @param CKing* */ virtual void setAction(CKing*) = 0 ; /** * @desc タグ設定 * @param タグNo */ virtual void setTag(CKing*, int tag) = 0 ; }; #endif /* KingCreateFactory_hpp */
[ "hatoppoppo1208@gmail.com" ]
hatoppoppo1208@gmail.com
6f0df77a88a6f8910615bb767b529a4d69d2fbc8
37cfcdfa3b8f1499f5899d2dfa2a48504a690abd
/src/qt/test/addressbooktests.cpp
c33f94e62ca7349c45de84385c81e10d1ceae5e0
[ "MIT" ]
permissive
CJwon-98/Pyeongtaekcoin
28acc53280be34b69c986198021724181eeb7d4d
45a81933a98a7487f11e57e6e9315efe740a297e
refs/heads/master
2023-08-17T11:18:24.401724
2021-10-14T04:32:55
2021-10-14T04:32:55
411,525,736
0
0
null
null
null
null
UTF-8
C++
false
false
5,359
cpp
#include <qt/test/addressbooktests.h> #include <qt/test/util.h> #include <test/test_pyeongtaekcoin.h> #include <interfaces/chain.h> #include <interfaces/node.h> #include <qt/addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/editaddressdialog.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/qvalidatedlineedit.h> #include <qt/walletmodel.h> #include <key.h> #include <key_io.h> #include <pubkey.h> #include <wallet/wallet.h> #include <QApplication> #include <QTimer> #include <QMessageBox> namespace { /** * Fill the edit address dialog box with data, submit it, and ensure that * the resulting message meets expectations. */ void EditAddressAndSubmit( EditAddressDialog* dialog, const QString& label, const QString& address, QString expected_msg) { QString warning_text; dialog->findChild<QLineEdit*>("labelEdit")->setText(label); dialog->findChild<QValidatedLineEdit*>("addressEdit")->setText(address); ConfirmMessage(&warning_text, 5); dialog->accept(); QCOMPARE(warning_text, expected_msg); } /** * Test adding various send addresses to the address book. * * There are three cases tested: * * - new_address: a new address which should add as a send address successfully. * - existing_s_address: an existing sending address which won't add successfully. * - existing_r_address: an existing receiving address which won't add successfully. * * In each case, verify the resulting state of the address book and optionally * the warning message presented to the user. */ void TestAddAddressesToSendBook() { TestChain100Setup test; auto chain = interfaces::MakeChain(); std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(*chain, WalletLocation(), WalletDatabase::CreateMock()); bool firstRun; wallet->LoadWallet(firstRun); auto build_address = [&wallet]() { CKey key; key.MakeNewKey(true); CTxDestination dest(GetDestinationForKey( key.GetPubKey(), wallet->m_default_address_type)); return std::make_pair(dest, QString::fromStdString(EncodeDestination(dest))); }; CTxDestination r_key_dest, s_key_dest; // Add a preexisting "receive" entry in the address book. QString preexisting_r_address; QString r_label("already here (r)"); // Add a preexisting "send" entry in the address book. QString preexisting_s_address; QString s_label("already here (s)"); // Define a new address (which should add to the address book successfully). QString new_address; std::tie(r_key_dest, preexisting_r_address) = build_address(); std::tie(s_key_dest, preexisting_s_address) = build_address(); std::tie(std::ignore, new_address) = build_address(); { LOCK(wallet->cs_wallet); wallet->SetAddressBook(r_key_dest, r_label.toStdString(), "receive"); wallet->SetAddressBook(s_key_dest, s_label.toStdString(), "send"); } auto check_addbook_size = [&wallet](int expected_size) { LOCK(wallet->cs_wallet); QCOMPARE(static_cast<int>(wallet->mapAddressBook.size()), expected_size); }; // We should start with the two addresses we added earlier and nothing else. check_addbook_size(2); // Initialize relevant QT models. std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); auto node = interfaces::MakeNode(); OptionsModel optionsModel(*node); AddWallet(wallet); WalletModel walletModel(std::move(node->getWallets()[0]), *node, platformStyle.get(), &optionsModel); RemoveWallet(wallet); EditAddressDialog editAddressDialog(EditAddressDialog::NewSendingAddress); editAddressDialog.setModel(walletModel.getAddressTableModel()); EditAddressAndSubmit( &editAddressDialog, QString("uhoh"), preexisting_r_address, QString( "Address \"%1\" already exists as a receiving address with label " "\"%2\" and so cannot be added as a sending address." ).arg(preexisting_r_address).arg(r_label)); check_addbook_size(2); EditAddressAndSubmit( &editAddressDialog, QString("uhoh, different"), preexisting_s_address, QString( "The entered address \"%1\" is already in the address book with " "label \"%2\"." ).arg(preexisting_s_address).arg(s_label)); check_addbook_size(2); // Submit a new address which should add successfully - we expect the // warning message to be blank. EditAddressAndSubmit( &editAddressDialog, QString("new"), new_address, QString("")); check_addbook_size(3); } } // namespace void AddressBookTests::addressBookTests() { #ifdef Q_OS_MAC if (QApplication::platformName() == "minimal") { // Disable for mac on "minimal" platform to avoid crashes inside the Qt // framework when it tries to look up unimplemented cocoa functions, // and fails to handle returned nulls // (https://bugreports.qt.io/browse/QTBUG-49686). QWARN("Skipping AddressBookTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke " "with 'test_pyeongtaekcoin-qt -platform cocoa' on mac, or else use a linux or windows build."); return; } #endif TestAddAddressesToSendBook(); }
[ "cjone98692996@gmail.com" ]
cjone98692996@gmail.com
c5a8c84ec42bd89394523544e92c8fbcf9e08ad3
7ad7838a349e229ae8aec980e5d43a68cd7362cd
/ghost/TerrainParser.cpp
c795e72f3ab151d1e101c4326a8170666665f41b
[]
no_license
smworks/smengine
612c33c859c5ae03d7d10223051c9c5120e2d452
4221e58e193470e8c55a267cbfe5a3f9d75080f7
refs/heads/master
2021-01-13T15:46:53.359185
2020-01-27T09:28:36
2020-01-27T09:28:36
79,839,253
0
0
null
null
null
null
UTF-8
C++
false
false
7,300
cpp
/* * TerrainParser.cpp * * Created on: 2012.12.24 * Author: MS */ #include "TerrainParser.h" #include "BoundingSphere.h" #include "Shapes.h" #include "Multiplatform/ServiceLocator.h" #include "Resources/Texture.h" TerrainGeometry::~TerrainGeometry() { for (SIZE i = 0; i < indices_->size(); i++) { delete (*indices_)[i]; } for (SIZE i = 0; i < bounds_->size(); i++) { delete (*bounds_)[i]; } indices_->clear(); delete indices_; bounds_->clear(); delete bounds_; delete vertices_; delete normals_; delete uv_; } TerrainParser::TerrainParser( ServiceLocator* services, Texture* heightMap, float heightRatio, float heightOffset) { services_ = services; heightMap_ = heightMap; heightRatio_ = heightRatio; heightOffset_ = heightOffset; segmentSize_ = 128; dx_ = 0.5f; dz_ = 0.5f; } TerrainParser::~TerrainParser() { // TODO Auto-generated destructor stub } bool TerrainParser::load(TerrainGeometry& geometry, BoundingVolume *& bv) { PROFILE("Started generating terrain."); UINT32 width = heightMap_->getWidth(); UINT32 height = heightMap_->getHeight(); if (width % 2 != 0) { LOGE("Terrain width must be power of 2."); return false; } vector<float>* vertices = NEW vector<float>(); vertices->reserve(width * 3 * height);\ vector<UINT16>* fullIndices = 0; //new vector<UINT16>(); vector<float>* uv = NEW vector<float>; uv->reserve(height * width * 2); UINT8 color[] = {0, 0, 0, 255}; int blue = 0; Shapes::grid(height - 1, width - 1, dx_, dz_, vertices, fullIndices); for (int j = height - 1; j >= 0; j--) { for (unsigned int i = 0; i < width; i++) { UINT8* pixel = heightMap_->getPixel(j, i); float heightVal = heightOffset_ + heightRatio_ * pixel[0]; (*vertices)[(height - j - 1) * width * 3 + i * 3 + 1] = heightVal; blue = pixel[2]; if (blue > 0) { int b = 255 - blue; if (b < 70) { b += 70; } color[0] = color[1] = color[2] = b; } else { color[0] = color[2] = 0; color[1] = heightMap_->getPixel(j, i)[0]; color[1] = 255; color[0] = color[2] = 0; } uv->push_back((float) i / width); uv->push_back((float) j / height); } } filterHeights(vertices, width, height); vector<float>* normals = NEW vector<float>(); normals->resize(vertices->size(), 0.0f); for (UINT32 i = 0; i < height - 1; i++) { for (UINT32 j = 0; j < width * 3 - 3; j += 3) { int offset = i * width * 3 + j; Vec3 a( vertices->at(offset + 0), vertices->at(offset + 1), vertices->at(offset + 2)); offset = i * width * 3 + j + 3; Vec3 b( vertices->at(offset + 0), vertices->at(offset + 1), vertices->at(offset + 2)); offset = (i + 1) * width * 3 + j; Vec3 c( vertices->at(offset + 0), vertices->at(offset + 1), vertices->at(offset + 2)); offset = (i + 1) * width * 3 + j + 3; Vec3 d( vertices->at(offset + 0), vertices->at(offset + 1), vertices->at(offset + 2)); Vec3 u(b); u -= a; Vec3 v(c); v -= a; Vec3 res(v); res.crossProduct(u); res.normalize(); offset = i * width * 3 + j; (*normals)[offset + 0] = res.getX(); (*normals)[offset + 1] = res.getY(); (*normals)[offset + 2] = res.getZ(); offset = i * width * 3 + j + 3; (*normals)[offset + 0] = res.getX(); (*normals)[offset + 1] = res.getY(); (*normals)[offset + 2] = res.getZ(); offset = (i + 1) * width * 3 + j; (*normals)[offset + 0] = res.getX(); (*normals)[offset + 1] = res.getY(); (*normals)[offset + 2] = res.getZ(); offset = (i + 1) * width * 3 + j + 3; (*normals)[offset + 0] = res.getX(); (*normals)[offset + 1] = res.getY(); (*normals)[offset + 2] = res.getZ(); } } vector<float> heights; float minHeight = FLT_MAX, maxHeight = -FLT_MAX; SIZE size = vertices->size(); for (SIZE i = 0; i < size; i += 3) { float hVal = vertices->at(i + 1); if (minHeight > hVal) { minHeight = hVal; } if (maxHeight < hVal) { maxHeight = hVal; } } float offset = (maxHeight - minHeight) * 0.5f + minHeight; for (UINT32 i = 0; i < size; i += 3) { float hVal = vertices->at(i + 1) - offset; vertices->at(i + 1) = hVal; heights.push_back(hVal); } geometry.normals_ = normals; geometry.uv_ = uv; int segmentRows = height / segmentSize_ + (height % segmentSize_ == 0 ? 0 : 1); int segmentCols = width / segmentSize_ + (width % segmentSize_ == 0 ? 0 : 1); int segmentCount = segmentRows * segmentCols; vector<vector<unsigned short>*>* indices = NEW vector<vector<unsigned short>*>(); vector<BoundingVolume*>* bounds = NEW vector<BoundingVolume*>(); indices->reserve(segmentCount); bounds->reserve(segmentCount); for (unsigned int i = 0; i < height; i += segmentSize_) { for (unsigned int j = 0; j < width; j += segmentSize_) { bounds->push_back(generateBoundingVolume( i, j, segmentSize_, segmentSize_, height, width, dx_, dz_)); indices->push_back(generateSubTerrainIndices( i, j, segmentSize_, segmentSize_, width, height)); } } geometry.bounds_ = bounds; geometry.vertices_ = vertices; geometry.indices_ = indices; LOGD("Terrain vertex count: %u", (UINT32) vertices->size() / 3); LOGD("Terrain index array count: %u", (UINT32) indices->size()); PROFILE("Terrain generated."); return true; } BoundingVolume* TerrainParser::generateBoundingVolume( int rowOffset, int colOffset, int rows, int cols, int height, int width, float dx, float dz) { //float centerX = -(width * dx / 2.0f) + colOffset * dx + (cols * dx / 2.0f); //float centerZ = -(height * dz / 2.0f) + rowOffset * dz + (rows * dz / 2.0f); ////float radius = (float) Math.sqrt(cols * dx * cols * dx + rows * dz * rows * dz); float radius = 70.0f; BoundingSphere* bs = NEW BoundingSphere(radius); //Vec3 pos(centerX, 0.0, centerZ); //bs->setPos(pos); return bs; } vector<unsigned short>* TerrainParser::generateSubTerrainIndices(int rowOffset, int colOffset, int rows, int cols, int width, int height) { int h = rowOffset + rows < height ? rows : height - rowOffset - 1; int w = colOffset + cols < width ? cols : width - colOffset - 1; vector<unsigned short>* indices = NEW vector<unsigned short>(); indices->reserve(h * w * 6); for (int i = rowOffset; i < h + rowOffset; i++) { for (int j = colOffset; j < w + colOffset; j++) { indices->push_back((i + 1) * width + j); indices->push_back(i * width + j + 1); indices->push_back(i * width + j); indices->push_back((i + 1) * width + j + 1); indices->push_back(i * width + j + 1); indices->push_back((i + 1) * width + j); } } return indices; } void TerrainParser::filterHeights( vector<float>* vertices, int width, int height) { float sum, heights; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { sum = 0.0f; heights = 0.0f; for (int i = row - 1; i < row + 1; i++) { for (int j = col - 1; j < col + 1; j++) { if (i > 0 && i < height && j > 0 && j < width) { sum += (*vertices)[i * width * 3 + j * 3 + 1]; heights += 1.0f; } } } (*vertices)[row * width * 3 + col * 3 + 1] = sum / heights; } } }
[ "martynas.su@gmail.com" ]
martynas.su@gmail.com
18cf69619233d06ea7b9d70cc312dfe12044026d
84257c31661e43bc54de8ea33128cd4967ecf08f
/ppc_85xx/usr/include/c++/4.2.2/gnu/javax/print/ipp/attribute/defaults/DocumentFormatDefault.h
b401a145e1fadca5175d211f04e3645cb3dfee6d
[]
no_license
nateurope/eldk
9c334a64d1231364980cbd7bd021d269d7058240
8895f914d192b83ab204ca9e62b61c3ce30bb212
refs/heads/master
2022-11-15T01:29:01.991476
2020-07-10T14:31:34
2020-07-10T14:31:34
278,655,691
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __gnu_javax_print_ipp_attribute_defaults_DocumentFormatDefault__ #define __gnu_javax_print_ipp_attribute_defaults_DocumentFormatDefault__ #pragma interface #include <javax/print/attribute/TextSyntax.h> extern "Java" { namespace gnu { namespace javax { namespace print { namespace ipp { namespace attribute { namespace defaults { class DocumentFormatDefault; } } } } } } namespace javax { namespace print { namespace attribute { class Attribute; } } } } class gnu::javax::print::ipp::attribute::defaults::DocumentFormatDefault : public ::javax::print::attribute::TextSyntax { public: DocumentFormatDefault (::java::lang::String *, ::java::util::Locale *); virtual ::java::lang::Class *getCategory (); virtual ::java::lang::String *getName (); virtual ::javax::print::attribute::Attribute *getAssociatedAttribute (); static ::java::lang::Class class$; }; #endif /* __gnu_javax_print_ipp_attribute_defaults_DocumentFormatDefault__ */
[ "Andre.Mueller@nateurope.com" ]
Andre.Mueller@nateurope.com
41727c35f0ab0cb1c23ded98b7f29738a3c014c7
33a8ed6ea048d51c647f1e8f50df9dad0a351c61
/Kvadratn^uravnenie/kv.cpp
29e4b0a08c8b34d20ee617520cd98b7c8f78e9e8
[]
no_license
AnastasiVokhmyanina28/kvadratik
3b460abc2cdeb3505022466bc5acca95ce435df3
58a64b4c03dfce8bef4f2bc54e54dae356a0fdd8
refs/heads/master
2020-11-29T12:28:25.390951
2019-12-25T14:33:12
2019-12-25T14:33:12
230,114,030
0
0
null
null
null
null
UTF-8
C++
false
false
1,553
cpp
#include "kv.h" #include <math.h> kv::kv() { } QString kv::set(QString text_a,QString text_b,QString text_c){ double a,b,c; bool ok_a,ok_b,ok_c; a=text_a.toInt(&ok_a,10); b=text_b.toInt(&ok_b,10); c=text_c.toInt(&ok_c,10); if (ok_a==false||ok_b==false||ok_c==false){ return "Incorrect input"; } else{ double d=(b*b)-(4*a*c); QString vivod1,vivod2; double x1,x2; if (a==0.00000000&&b==0.00000000&&c==0.00000000){ return "Any number"; } else if (b==0.00000000&&c==0.00000000&&a!=0.00000000){ return "0"; } else if (b==0.00000000&&a!=0.00000000&&c!=0.00000000){ if ((-1*(c/a))<=0){return "No roots";} else { x1=sqrt(-(c/a)); x2=-1*sqrt(-(c/a)); vivod2.setNum(x2,'g',6); vivod1.setNum(x1,'g',6); return vivod1+ " "+vivod2; } } else if (c==0.00000000&&b!=0.00000000&&a!=0.00000000) { vivod1="0"; x2=-(b/a); vivod2.setNum(x2,'g',6); return vivod1+ " "+vivod2; } else if (d<0) { return "No roots"; } else if (d==0.00000000) { x1=(-1*b)/(2*a); vivod1.setNum(x1,'g',6); return vivod1; } else if (d>0) { x1=((-1*b)+sqrt(d))/(2*a); x2=((-1*b)-sqrt(d))/(2*a); vivod1.setNum(x1,'g',6); vivod2.setNum(x2,'g',6); return vivod1+ " "+vivod2; } } }
[ "noreply@github.com" ]
noreply@github.com
70938d379c6ccb735a56e9b258ac14d024084ea6
e41ef85aebcf2bffdab9fdb24c9bdf92b4782c40
/Learning/Classes.cpp
280e97b645be7f7600cb17427b0320366f2a52a1
[]
no_license
rubengura/LearningCpp
03137a2ba1f2048567dc9aa1b175dc58484a1d53
f29757ae02e78c81519f12cd7b7dc1fd7e0545a3
refs/heads/master
2021-04-11T06:30:36.581456
2020-05-30T11:53:15
2020-05-30T11:53:15
248,999,970
0
0
null
null
null
null
UTF-8
C++
false
false
231
cpp
class Player { public: int x, y; int speed; void Move(int xa, int ya) { x += xa * speed; y += ya * speed; } }; int run() { Player player; player.x = 0; player.y = 0; player.speed = 1; player.Move(1, 1); return 0; }
[ "ruben.guerrero.ramirez@gmail.com" ]
ruben.guerrero.ramirez@gmail.com
42a02197d2c5dbd6266caebd891d049b4c01463e
56cb0d5fe1c7428dac7a2851432854c2f39995e7
/src/client/motion_detection_application/application.h
6dc24608f757d519142cf6d3d8bfa987998c67f3
[ "MIT" ]
permissive
EdgeLab-FHDO/ResourceAllocationE2EL
b52f222c0fb80d23a60b56bc4175692dc0fc3dbd
426d0104ab3439c1b107262aeade340999a8bafb
refs/heads/master
2021-01-05T07:11:29.236322
2020-04-14T17:52:12
2020-04-14T17:52:12
240,926,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
h
#ifndef APPLICATION_H #define APPLICATION_H #include <mutex> #include <unistd.h> #include <thread> #include <chrono> #include <fstream> #include <vector> #include <string> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/videoio.hpp> #include <opencv2/highgui.hpp> #include <opencv2/video.hpp> #include "clientTCP.h" using namespace cv; using namespace std; using namespace std::chrono; class Application { private: bool should_start; mutex should_start_mutex; bool finished; mutex finished_mutex; vector<int> min_threshold_list; vector<int> max_threshold_list; vector<long> threshold_end_time_list; int threshold_current_index; time_point<system_clock, milliseconds> start_time; double fps; long number_of_frames; VideoCapture capture; bool initialized; char* data; int data_size; Mat frame; Mat frame_resized; Mat frame_gray; Mat first_frame; Mat * frames; Size frame_size; ClientTCP * connection_TCP; bool terminating; thread cycles; void run_one_cycle(); void cycles_thread(); void correct_threshold_index(); public: Application(); ~Application(); void start(); void initialize(ClientTCP * connection_TCP, int dummy_data_size); bool is_finished(); int get_min_threshold(); int get_max_threshold(); }; #endif //APPLICATION_H
[ "noreply@github.com" ]
noreply@github.com
4b6ce7454fdd1c0dfa9583d31ea7bc3c3253ef04
9aee810d0d9d72d3dca7920447872216a3af49fe
/AtCoder/ABC/000-099/ABC096/abc096_d.cpp
288712e8cb44c44c65fbc528a0cc7217e700a460
[]
no_license
pulcherriman/Programming_Contest
37d014a414d473607a11c2edcb25764040edd686
715308628fc19843b8231526ad95dbe0064597a8
refs/heads/master
2023-08-04T00:36:36.540090
2023-07-30T18:31:32
2023-07-30T18:31:32
163,375,122
3
0
null
2023-01-24T11:02:11
2018-12-28T06:33:16
C++
UTF-8
C++
false
false
1,209
cpp
#include <bits/stdc++.h> using namespace std; using ll=long long; using vi=vector<int>; using vvi=vector<vi>; using pii=pair<int,int>; #define rep(i,n) for(int i=0;i<n;i++) #define range(i,a,n) for(int i=a;i<n;i++) #define all(a) a.begin(),a.end() #define rall(a) a.rbegin(),a.rend() #define INF 1e9 #define EPS 1e-9 #define MOD (1e9+7) void put(string d){}template<class H,class...T>void put(string d,H&h,T&...t){cout<<h;if(sizeof...(t))cout<<d;put(d,t...);} template<class T>void puti(T&a,string d=" "){bool f=1;for(auto&_:a)cout<<(exchange(f,0)?"":d)<<_;cout<<endl;} template<class T>void putii(T&a,string d=" "){for(auto&_:a)puti(_,d);} class Eratosthenes{ public: int n, sqlim; vector<bool> prime; Eratosthenes(int N):n(N+1){ sqlim=(int)ceil(sqrt(n)); prime=vector<bool>(n,1); prime[0]=prime[1]=0; for(int i=2;i<=sqlim;i++) if(prime[i]) for(int j=i*i;j<=n;j+=i) prime[j]=0;} vector<int> primeArray(){vi ret; for(int i=2;i<=55555;i++) if(prime[i]) ret.push_back(i); return ret;} }; int main(){ int n;cin>>n; Eratosthenes e(55555); vi v=e.primeArray(),ans; for(auto i:v){ if(i%5==1)ans.push_back(i); if(ans.size()==n)break; } puti(ans); return 0; }
[ "tsukasawa_agu@yahoo.co.jp" ]
tsukasawa_agu@yahoo.co.jp
bd590411c42eba11f9266d730ab73a651ccefc43
e57c2bea71b20c6fbcf145e67240eac419e78513
/PROJECT/game/src/ai/enemy_manager.h
15eea6e4940cbc1cda3cbec62f8cec488553e315
[ "MIT" ]
permissive
Blastinghavoc/Masters-AGT
5acb14698f32b542c3c201af936b4684f1c301de
fe3e2210d3e218ab82498a57a76c102078c99121
refs/heads/master
2023-01-14T03:43:04.809332
2020-11-13T10:45:36
2020-11-13T10:45:36
211,108,622
0
0
null
null
null
null
UTF-8
C++
false
false
2,580
h
#pragma once #include "../entities/abstract_enemy.h" #include "../grid/grid.h" #include <deque> #include "../ai/pathfinder.h" #include "../lighting/light_manager.h" #include "../gameplay/wave_definition.h" /*Static class to manage the movement of enemies in the level Spawns enemies according to a wave_definition, and detects when enemies die or reach the exit. */ class enemy_manager { public: static void init(engine::ref<grid> level_grid); static void on_update(const engine::timestep& time_step); static void begin_wave(wave_definition wave_def); /* Two different rendering methods, because animated enemies need a different shader than static enemies. */ static void render_animated(const engine::ref<engine::shader>& shader); static void render_static(const engine::ref<engine::shader>& shader); //For debug purposes only static void render_trigger_boxes(const engine::ref<engine::shader>& shader); //Number of enemies currently alive, and remaining this wave. static int current_active() { return (int)s_current_active_minions.size(); }; static int remaining() { return s_current_wave_remaining; }; //Obtain a vector of the currently active enemies, sorted by distance to the exit static const std::vector<engine::ref<abstract_enemy>>& get_active_enemies() { return s_current_active_minions; }; private: //Map of enemy IDs to enemies. This is the definitve store of enemies. static std::map<int, engine::ref<abstract_enemy>> s_minions; //id to be assigned to next spawned minion. static int s_next_id; //Reference to the level grid, for pathfinding. static engine::ref<grid> s_level_grid; //Current path obtained from pathfinder static std::deque<glm::vec3> s_current_path; //Enemies remaining to spawn for the current wave static int s_current_wave_remaining; //Timer between spawning enemies static float s_interval_accumulator; static float s_current_wave_interval; //Holds pointers to the created but inactive minions of various types. static std::multimap<enemy_type,engine::ref<abstract_enemy>> s_minion_buffer; //Holds pointers to the minions currently alive static std::vector<engine::ref<abstract_enemy>> s_current_active_minions; //Holds the amount and type of enemies to spawn for a given wave. static std::deque<std::pair<int, enemy_type>> s_spawn_sequence; //Highlights the furthest forward enemy static engine::ref<engine::SpotLight> m_spot_light; //---private methods //Spawn a new minion of the desired type. static engine::ref<abstract_enemy> spawn_minion(enemy_type type,glm::vec3 position); };
[ "taylj024@gmail.com" ]
taylj024@gmail.com
c1722aac6994f1e23cf10f52387b72618ec2f29d
4503b4ec29e9a30d26c433bac376f2bddaefd9e5
/PCL 1.7.2_vs2013/x64/3rdParty/VTK-6.1.0/include/vtk-6.1/vtkExtentTranslator.h
b6d4d0163af40d146c067c00329c7235e485e7f8
[]
no_license
SwunZH/ecocommlibs
0a872e0bbecbb843a0584fb787cf0c5e8a2a270b
4cff09ff1e479f5f519f207262a61ee85f543b3a
refs/heads/master
2021-01-25T12:02:39.067444
2018-02-23T07:04:43
2018-02-23T07:04:43
123,447,012
1
0
null
2018-03-01T14:37:53
2018-03-01T14:37:53
null
UTF-8
C++
false
false
4,617
h
/*========================================================================= Program: Visualization Toolkit Module: vtkExtentTranslator.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkExtentTranslator - Generates a structured extent from unstructured. // .SECTION Description // vtkExtentTranslator generates a structured extent from an unstructured // extent. It uses a recursive scheme that splits the largest axis. A hard // coded extent can be used for a starting point. // .SECTION Caveats // This object is still under development. #ifndef __vtkExtentTranslator_h #define __vtkExtentTranslator_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkObject.h" class VTKCOMMONDATAMODEL_EXPORT vtkExtentTranslator : public vtkObject { public: static vtkExtentTranslator *New(); vtkTypeMacro(vtkExtentTranslator,vtkObject); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Set the Piece/NumPieces. Set the WholeExtent and then call PieceToExtent. // The result can be obtained from the Extent ivar. vtkSetVector6Macro(WholeExtent, int); vtkGetVector6Macro(WholeExtent, int); vtkSetVector6Macro(Extent, int); vtkGetVector6Macro(Extent, int); vtkSetMacro(Piece,int); vtkGetMacro(Piece,int); vtkSetMacro(NumberOfPieces,int); vtkGetMacro(NumberOfPieces,int); vtkSetMacro(GhostLevel, int); vtkGetMacro(GhostLevel, int); // Description: // These are the main methods that should be called. These methods // are responsible for converting a piece to an extent. The signatures // without arguments are only thread safe when each thread accesses a // different instance. The signatures with arguments are fully thread // safe. virtual int PieceToExtent(); virtual int PieceToExtentByPoints(); virtual int PieceToExtentThreadSafe(int piece, int numPieces, int ghostLevel, int *wholeExtent, int *resultExtent, int splitMode, int byPoints); // Description: // How should the streamer break up extents. Block mode // tries to break an extent up into cube blocks. It always chooses // the largest axis to split. // Slab mode first breaks up the Z axis. If it gets to one slice, // then it starts breaking up other axes. void SetSplitModeToBlock() {this->SplitMode = vtkExtentTranslator::BLOCK_MODE;} void SetSplitModeToXSlab() {this->SplitMode = vtkExtentTranslator::X_SLAB_MODE;} void SetSplitModeToYSlab() {this->SplitMode = vtkExtentTranslator::Y_SLAB_MODE;} void SetSplitModeToZSlab() {this->SplitMode = vtkExtentTranslator::Z_SLAB_MODE;} vtkGetMacro(SplitMode,int); //Description: // By default the translator creates N structured subextents by repeatedly // splitting the largest current dimension until there are N pieces. // If you do not want it always split the largest dimension, for instance when the // shortest dimension is the slowest changing and thus least coherent in memory, // use this to tell the translator which dimensions to split. void SetSplitPath(int len, int *splitpath); //BTX // Don't change the numbers here - they are used in the code // to indicate array indices. enum Modes { X_SLAB_MODE=0, Y_SLAB_MODE=1, Z_SLAB_MODE=2, BLOCK_MODE= 3 }; //ETX protected: vtkExtentTranslator(); ~vtkExtentTranslator(); // Description: // Returns 0 if no data exist for a piece. // The whole extent Should be passed in as the extent. // It is modified to return the result. int SplitExtent(int piece, int numPieces, int *extent, int splitMode); int SplitExtentByPoints(int piece, int numPieces, int *extent, int splitMode); int Piece; int NumberOfPieces; int GhostLevel; int Extent[6]; int WholeExtent[6]; int SplitMode; int* SplitPath; int SplitLen; private: vtkExtentTranslator(const vtkExtentTranslator&); // Not implemented. void operator=(const vtkExtentTranslator&); // Not implemented. }; #endif
[ "hnk0313@3e9e098e-e079-49b3-9d2b-ee27db7392fb" ]
hnk0313@3e9e098e-e079-49b3-9d2b-ee27db7392fb
fa8664bce588ced63d4ef822160cf924dd50a92e
3e57be15cc00a3a8d24bfe8396a3283a8d74166e
/Lib/SharedNodesLib/NodeWordArray.h
6e4be7f09f549224e5c8c94873c3dfba57df6064
[]
no_license
CodElecCz/TracerUIv1
f6b0e6c1c172953fff20a53e9f08bdeff8b3647f
11a5a70838dff671f3838a50a907e7e197911db6
refs/heads/master
2023-03-01T12:10:24.467636
2021-02-12T14:53:11
2021-02-12T14:53:11
327,567,164
0
0
null
null
null
null
UTF-8
C++
false
false
3,141
h
#pragma once #include "stdafx.h" #include "Def.h" using namespace std; using namespace Utilities; namespace Utilities { namespace Node { class LIB_API NodeWordArray : public INode { public: NodeWordArray(string Id, NodeType Type, NodeAccess Access, UINT16 StartingAddress, UINT16 RequestedCount, UINT16 CustomType = 0, UINT32 LoopTimeMS = 0); ~NodeWordArray(void); public: //area void SetReadArea(UINT16 ReadData[], UINT32 ReadDataSize); void SetWriteArea(UINT16 WriteData[], UINT32 WriteDataSize); void GetWriteArea(UINT16 WriteData[], UINT16 WriteFlag[], PUINT32 WriteDataSize); void SetWriteAreaAcknoledge(UINT16 Offset, UINT32 WriteDataSize); void Read(UINT16 ReadData[], PUINT32 ReadDataSize); //nodes INode* CreateNode(const char* Id, NodeType Type, UINT16 Offset); INode* CreateNode(const char* Id, NodeType Type, UINT16 Offset, NodeAccess Access); void Refresh(void); //timestamp SYSTEMTIME ReadTimeStamp() { CAutoLock al(m_ReadLock); return m_ReadTimeGlobal; } SYSTEMTIME WriteTimeStamp() { CAutoLock al(m_WriteLock); return m_WriteTimeGlobal; } //counter UINT64 ReadCounter() { CAutoLock al(m_ReadLock); return m_ReadCounterGlobal; } UINT64 WriteCounter() { CAutoLock al(m_WriteLock); return m_WriteCounterGlobal; } //properties UINT16 Address() const { return m_Address; } UINT16 Count() const { return m_Count; } UINT16 CustomType() const { return m_CustomType; } UINT32 LoopTimeMS() const { return m_LoopTimeMS; } void SetSerialDevId(UINT8 DevId) { m_SerialDevId = DevId; } UINT8 GetSerialDevId() { return m_SerialDevId; } void SetVarStr(string Variable) { m_VarStr = Variable; } string GetVarStr() { return m_VarStr; } private: //timestamp void SetReadTimeStamp() { GetSystemTime(&m_ReadTimeGlobal); } void SetWriteTimeStamp() { GetSystemTime(&m_WriteTimeGlobal); } void SetReadTimeStamp(UINT16 Offset) { GetSystemTime(&m_ReadTimeGlobal); m_ReadTime[Offset] = m_ReadTimeGlobal; } void SetWriteTimeStamp(UINT16 Offset) { GetSystemTime(&m_WriteTimeGlobal); m_WriteTime[Offset] = m_WriteTimeGlobal; } void SetReadCounter(UINT16 Offset) { m_ReadCounterGlobal++; m_ReadCounter[Offset]++; } void SetWriteCounter(UINT16 Offset) { m_WriteCounterGlobal++; m_WriteCounter[Offset]++; } public: typedef shared_ptr<NodeWordArray> NodeWordArrayPtr; private: #pragma warning(push) #pragma warning(disable:4251) //register vector<UINT16> m_ReadData; vector<UINT16> m_WriteData; //flag vector<UINT16> m_ReadFlag; vector<UINT16> m_WriteFlag; //counter UINT64 m_ReadCounterGlobal; UINT64 m_WriteCounterGlobal; vector<UINT64> m_ReadCounter; vector<UINT64> m_WriteCounter; //lock CLock m_ReadLock; CLock m_WriteLock; UINT8 m_SerialDevId; string m_VarStr; //timestamp SYSTEMTIME m_ReadTimeGlobal; SYSTEMTIME m_WriteTimeGlobal; vector<SYSTEMTIME> m_ReadTime; vector<SYSTEMTIME> m_WriteTime; #pragma warning(pop) bool m_rValueInit; //area UINT16 m_Address; UINT16 m_Count; UINT16 m_CustomType; UINT32 m_LoopTimeMS; }; } }
[ "radomir.turca@codelec.cz" ]
radomir.turca@codelec.cz
00ba8be32f6c222ea7346473c72dc209278079cd
4b60d1c1d0cb3706fab40e4f4b34b63f750f5c50
/include/Math.h
cd947ce21bed01aad9004f8d50a718c2785348b2
[]
no_license
alexm622/Alexs-salt-tool-cpp
c1e9ed8be6654b0596a03195ea12acd80ebe8db2
a5eb59df310a38678a2592249df02808968d7088
refs/heads/master
2023-06-20T02:29:49.424480
2021-07-22T17:33:53
2021-07-22T17:33:53
379,016,058
0
0
null
null
null
null
UTF-8
C++
false
false
309
h
#ifndef MATH_H #define MATH_H #include "string" class Math { public: Math(); virtual ~Math(); static int binaryToDecimal(int n); static int binaryToDecimal(std::string n); static std::string decToBinary(int n); protected: private: }; #endif // MATH_H
[ "alex@remi-it.com" ]
alex@remi-it.com
bdc7a23c859f0a8e0be8f5a255e073e889b3b297
9447120f61cfcb42a2dfdec36a34d2c29a8a038a
/.history/outbreak_seq_20200422083505.cpp
793721965860be87c0aad23b710ea49f12d2a262
[]
no_license
rahuljroy/Outbreak-contact_tracing
98de7c0011a0a5e1bf5b008333c077ba315b267d
020fa70d5f18b929a88d4f1cbc377565eb970054
refs/heads/master
2022-05-26T22:33:39.474732
2020-04-30T06:32:41
2020-04-30T06:32:41
256,914,532
1
0
null
null
null
null
UTF-8
C++
false
false
3,723
cpp
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include <string> #include <map> #include <bits/stdc++.h> using namespace std; struct graph{ int Day; vector< vector<long int> > graph_for_the_day; }; long int get_no_lines(char* filename){ long int no_vertices = 0; string data; ifstream myfile; myfile.open(filename); if(myfile){ cout<<"File Opened"<<endl; } else{ cout<<"File not opened"<<endl; } while(getline(myfile, data)){ no_vertices++; } myfile.close(); return no_vertices; } void get_infected(char* filename, long int no_infected, vector<long int>& infected){ long int u; // vector<vector<long int>> graph; string data; // graph.resize(no_vertices); ifstream myfile; myfile.open(filename); if(myfile){ cout<<"File Opened"<<endl; } else{ cout<<"File not opened"<<endl; } while(myfile>>u){ graph[u].push_back(node_weight); } myfile.close(); // cout<<"Graph created"<<endl; } void build_graph(char* filename, long int no_vertices, vector< vector<long int> >& graph){ long int u, node_weight; // vector<vector<long int>> graph; string data; // graph.resize(no_vertices); ifstream myfile; myfile.open(filename); if(myfile){ cout<<"File Opened"<<endl; } else{ cout<<"File not opened"<<endl; } while(myfile>>u>>node_weight){ graph[u].push_back(node_weight); } myfile.close(); // cout<<"Graph created"<<endl; } vector<long int> get_neighbours(vector< vector<long int> >& graph, int u){ return graph[u]; } int main(int argc, char** argv){ int i, j, k, count=0; long int u, v, graph_number; struct graph day_graphs[10]; vector< vector<long int> > weight, node_weights, no_of_neighbours; long int no_vertices = 0, no_infected = 0; string data, file_number, txt, filename, filename1; char* file; ifstream myfile; file = "../../../../scratch/graph-inputs_PP/node_weights.txt"; no_vertices = get_no_lines(file); cout<<"The number of vertices are : "<<no_vertices<<endl; no_of_neighbours.resize(no_vertices); weight.resize(no_vertices); node_weights.resize(no_vertices); file = "../../../../scratch/graph-inputs_PP/node_weights.txt"; build_graph(file, no_vertices, node_weights); filename = "../../../../scratch/graph-inputs_PP/wiki-"; txt = ".txt"; for (i=1; i<=10; i++){ day_graphs[i-1].Day = i; day_graphs[i-1].graph_for_the_day.resize(no_vertices); graph_number = i; file_number = to_string(graph_number); // filename.append(file_number); // filename.append(txt); filename1 = filename+file_number+txt; file = &filename1[0]; cout<<file<<endl; build_graph(file, no_vertices, day_graphs[i-1].graph_for_the_day); cout<<"Graph "<<i<<" built"<<endl; } // filename = "../../../../scratch/graph-inputs_PP/wiki-6.txt"; for (k=0; k<10; k++){ count = 0; for (i=0; i<no_vertices; i++){ no_of_neighbours[i].push_back(day_graphs[k].graph_for_the_day[i].size()); } } // cout<<"The final non zero count is "<<count<<" for graph "<<k<<endl; for (i=0; i<no_vertices; i++){ for (j=0; j<no_of_neighbours[i].size(); j++){ cout<<no_of_neighbours[i][j]<<" "; } cout<<endl; } vector<long int> infected; filename = "infected.txt"; file = &filename[0]; no_infected = get_no_lines(file); myfile.open(file); while() }
[ "rjroy196@gmail.com" ]
rjroy196@gmail.com
b96ef11df5d5730ae120f2eacc5be36eebb66c86
01ed149e0d30128a9a95d8af3f81e92be1637ec8
/srook/config/arch/Convex/core.hpp
f1c21d9bbf659bbfdb54e37c3e4d9f2dda8308f3
[ "MIT" ]
permissive
falgon/SrookCppLibraries
59e1fca9fb8ed26aba0e3bf5677a52bbd4605669
ebcfacafa56026f6558bcd1c584ec774cc751e57
refs/heads/master
2020-12-25T14:40:34.979476
2020-09-25T11:46:45
2020-09-25T11:46:45
66,266,655
1
1
MIT
2018-12-31T15:04:38
2016-08-22T11:23:24
C++
UTF-8
C++
false
false
985
hpp
// Copyright (C) 2011-2020 Roki. Distributed under the MIT License #ifndef INCLUDED_SROOK_CONFIG_ARCH_CONVEX_CORE_HPP #define INCLUDED_SROOK_CONFIG_ARCH_CONVEX_CORE_HPP #if defined(__convex__) # define SROOK_ARCH_IS_CONVEX 1 # if defined(__convex_c1__) # define SROOK_CONVEX_C1 __convex_c1__ # else # define SROOK_CONVEX_C1 0 # endif # if defined(__convex_c2__) # define SROOK_CONVEX_C2 __convex_c2__ # else # define SROOK_CONVEX_C2 0 # endif # if defined(__convex_c32__) # define SROOK_CONVEX_C32 __convex_c32__ # else # define SROOK_CONVEX_C32 0 # endif # if defiend(__convex_c34__) # define SROOK_CONVEX_C34 __convex_c34__ # else # define SROOK_CONVEX_C34 0 # endif # if defined(__convex_c38__) # define SROOK_CONVEX_C38 __convex_c38__ # else # define SROOK_CONVEX_C38 0 # endif #else # define SROOK_ARCH_IS_CONVEX 0 # define SROOK_CONVEX_C1 0 # define SROOK_CONVEX_C2 0 # define SROOK_CONVEX_C32 0 # define SROOK_CONVEX_C34 0 # define SROOK_CONVEX_C38 0 #endif #endif
[ "falgon53@yahoo.co.jp" ]
falgon53@yahoo.co.jp
e2aa632847309da1799ae51cc12ce4fdf8d9c26b
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-organizations/source/model/CancelHandshakeResult.cpp
f189eebd2ca823ae32ec5f138996343a86dc7798
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
1,373
cpp
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/organizations/model/CancelHandshakeResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Organizations::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; CancelHandshakeResult::CancelHandshakeResult() { } CancelHandshakeResult::CancelHandshakeResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } CancelHandshakeResult& CancelHandshakeResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("Handshake")) { m_handshake = jsonValue.GetObject("Handshake"); } return *this; }
[ "henso@amazon.com" ]
henso@amazon.com
dc1a6e690ba2144ac917523c32c6f4ba06fa07d7
5d3961e453a30b99945d1ee7ab502e8705973ef9
/media/mojo/services/gpu_mojo_media_client.cc
053ea8a509c484fdedfd63c70c5f9bdbc5e088e9
[ "BSD-3-Clause" ]
permissive
mayitbeegh/chromium
cf0c4663a4da9e102024f2a5052f5a14856ab8bd
de6c3d36fbafd1f2da6fb4e8bb71023e0b170626
refs/heads/master
2023-03-10T03:41:25.329289
2019-06-06T17:25:25
2019-06-06T17:25:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,911
cc
// Copyright 2016 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 "media/mojo/services/gpu_mojo_media_client.h" #include <utility> #include "base/bind.h" #include "base/feature_list.h" #include "base/memory/ptr_util.h" #include "gpu/ipc/service/gpu_channel.h" #include "media/base/audio_decoder.h" #include "media/base/cdm_factory.h" #include "media/base/fallback_video_decoder.h" #include "media/base/media_switches.h" #include "media/base/video_decoder.h" #include "media/gpu/buildflags.h" #include "media/gpu/gpu_video_accelerator_util.h" #include "media/gpu/gpu_video_decode_accelerator_factory.h" #include "media/gpu/ipc/service/media_gpu_channel_manager.h" #include "media/gpu/ipc/service/vda_video_decoder.h" #include "media/mojo/interfaces/video_decoder.mojom.h" #include "media/video/supported_video_decoder_config.h" #include "media/video/video_decode_accelerator.h" #if defined(OS_ANDROID) #include "base/memory/ptr_util.h" #include "media/base/android/android_cdm_factory.h" #include "media/filters/android/media_codec_audio_decoder.h" #include "media/gpu/android/android_video_surface_chooser_impl.h" #include "media/gpu/android/codec_allocator.h" #include "media/gpu/android/maybe_render_early_manager.h" #include "media/gpu/android/media_codec_video_decoder.h" #include "media/gpu/android/video_frame_factory_impl.h" #include "media/mojo/interfaces/media_drm_storage.mojom.h" #include "media/mojo/interfaces/provision_fetcher.mojom.h" #include "media/mojo/services/mojo_media_drm_storage.h" #include "media/mojo/services/mojo_provision_fetcher.h" #include "services/service_manager/public/cpp/connect.h" #endif // defined(OS_ANDROID) #if defined(OS_WIN) #include "media/gpu/windows/d3d11_video_decoder.h" #include "ui/gl/gl_angle_util_win.h" #endif // defined(OS_WIN) #if defined(OS_ANDROID) #include "media/mojo/services/android_mojo_util.h" using media::android_mojo_util::CreateProvisionFetcher; using media::android_mojo_util::CreateMediaDrmStorage; #endif // defined(OS_ANDROID) namespace media { namespace { #if defined(OS_ANDROID) || defined(OS_CHROMEOS) || defined(OS_MACOSX) || \ defined(OS_WIN) || defined(OS_LINUX) gpu::CommandBufferStub* GetCommandBufferStub( base::WeakPtr<MediaGpuChannelManager> media_gpu_channel_manager, base::UnguessableToken channel_token, int32_t route_id) { if (!media_gpu_channel_manager) return nullptr; gpu::GpuChannel* channel = media_gpu_channel_manager->LookupChannel(channel_token); if (!channel) return nullptr; gpu::CommandBufferStub* stub = channel->LookupCommandBuffer(route_id); if (!stub) return nullptr; // Only allow stubs that have a ContextGroup, that is, the GLES2 ones. Later // code assumes the ContextGroup is valid. if (!stub->decoder_context()->GetContextGroup()) return nullptr; return stub; } #endif #if defined(OS_WIN) // Return a callback to get the D3D11 device for D3D11VideoDecoder. Since it // only supports the ANGLE device right now, that's what we return. D3D11VideoDecoder::GetD3D11DeviceCB GetD3D11DeviceCallback() { return base::BindRepeating( []() { return gl::QueryD3D11DeviceObjectFromANGLE(); }); } #endif } // namespace GpuMojoMediaClient::GpuMojoMediaClient( const gpu::GpuPreferences& gpu_preferences, const gpu::GpuDriverBugWorkarounds& gpu_workarounds, const gpu::GpuFeatureInfo& gpu_feature_info, scoped_refptr<base::SingleThreadTaskRunner> gpu_task_runner, base::WeakPtr<MediaGpuChannelManager> media_gpu_channel_manager, AndroidOverlayMojoFactoryCB android_overlay_factory_cb, CdmProxyFactoryCB cdm_proxy_factory_cb) : gpu_preferences_(gpu_preferences), gpu_workarounds_(gpu_workarounds), gpu_feature_info_(gpu_feature_info), gpu_task_runner_(std::move(gpu_task_runner)), media_gpu_channel_manager_(std::move(media_gpu_channel_manager)), android_overlay_factory_cb_(std::move(android_overlay_factory_cb)), cdm_proxy_factory_cb_(std::move(cdm_proxy_factory_cb)) {} GpuMojoMediaClient::~GpuMojoMediaClient() = default; void GpuMojoMediaClient::Initialize(service_manager::Connector* connector) {} std::unique_ptr<AudioDecoder> GpuMojoMediaClient::CreateAudioDecoder( scoped_refptr<base::SingleThreadTaskRunner> task_runner) { #if defined(OS_ANDROID) return std::make_unique<MediaCodecAudioDecoder>(task_runner); #else return nullptr; #endif // defined(OS_ANDROID) } SupportedVideoDecoderConfigMap GpuMojoMediaClient::GetSupportedVideoDecoderConfigs() { #if defined(OS_ANDROID) static SupportedVideoDecoderConfigMap supported_configs{ {VideoDecoderImplementation::kDefault, MediaCodecVideoDecoder::GetSupportedConfigs()}, }; return supported_configs; #else SupportedVideoDecoderConfigMap supported_config_map; #if defined(OS_WIN) // Start with the configurations supported by D3D11VideoDecoder. // VdaVideoDecoder is still used as a fallback. if (!d3d11_supported_configs_) { d3d11_supported_configs_ = D3D11VideoDecoder::GetSupportedVideoDecoderConfigs( gpu_preferences_, gpu_workarounds_, GetD3D11DeviceCallback()); } supported_config_map[VideoDecoderImplementation::kAlternate] = *d3d11_supported_configs_; #endif auto& default_configs = supported_config_map[VideoDecoderImplementation::kDefault]; // VdaVideoDecoder will be used to wrap a VDA. Add the configs supported // by the VDA implementation. // TODO(sandersd): Move conversion code into VdaVideoDecoder. VideoDecodeAccelerator::Capabilities capabilities = GpuVideoAcceleratorUtil::ConvertGpuToMediaDecodeCapabilities( GpuVideoDecodeAcceleratorFactory::GetDecoderCapabilities( gpu_preferences_, gpu_workarounds_)); bool allow_encrypted = capabilities.flags & VideoDecodeAccelerator::Capabilities::SUPPORTS_ENCRYPTED_STREAMS; for (const auto& supported_profile : capabilities.supported_profiles) { default_configs.push_back(SupportedVideoDecoderConfig( supported_profile.profile, // profile_min supported_profile.profile, // profile_max supported_profile.min_resolution, // coded_size_min supported_profile.max_resolution, // coded_size_max allow_encrypted, // allow_encrypted supported_profile.encrypted_only)); // require_encrypted } return supported_config_map; #endif // defined(OS_ANDROID) } std::unique_ptr<VideoDecoder> GpuMojoMediaClient::CreateVideoDecoder( scoped_refptr<base::SingleThreadTaskRunner> task_runner, MediaLog* media_log, mojom::CommandBufferIdPtr command_buffer_id, VideoDecoderImplementation implementation, RequestOverlayInfoCB request_overlay_info_cb, const gfx::ColorSpace& target_color_space) { // All implementations require a command buffer. if (!command_buffer_id) return nullptr; std::unique_ptr<VideoDecoder> video_decoder; switch (implementation) { case VideoDecoderImplementation::kDefault: { #if defined(OS_ANDROID) auto get_stub_cb = base::Bind(&GetCommandBufferStub, media_gpu_channel_manager_, command_buffer_id->channel_token, command_buffer_id->route_id); video_decoder = std::make_unique<MediaCodecVideoDecoder>( gpu_preferences_, gpu_feature_info_, DeviceInfo::GetInstance(), CodecAllocator::GetInstance(gpu_task_runner_), std::make_unique<AndroidVideoSurfaceChooserImpl>( DeviceInfo::GetInstance()->IsSetOutputSurfaceSupported()), android_overlay_factory_cb_, std::move(request_overlay_info_cb), std::make_unique<VideoFrameFactoryImpl>( gpu_task_runner_, std::move(get_stub_cb), gpu_preferences_, MaybeRenderEarlyManager::Create(gpu_task_runner_))); #elif defined(OS_CHROMEOS) || defined(OS_MACOSX) || defined(OS_WIN) || \ defined(OS_LINUX) video_decoder = VdaVideoDecoder::Create( task_runner, gpu_task_runner_, media_log->Clone(), target_color_space, gpu_preferences_, gpu_workarounds_, base::BindRepeating(&GetCommandBufferStub, media_gpu_channel_manager_, command_buffer_id->channel_token, command_buffer_id->route_id)); #endif // defined(OS_ANDROID) } break; case VideoDecoderImplementation::kAlternate: #if defined(OS_WIN) if (base::FeatureList::IsEnabled(kD3D11VideoDecoder)) { // If nothing has cached the configs yet, then do so now. if (!d3d11_supported_configs_) GetSupportedVideoDecoderConfigs(); video_decoder = D3D11VideoDecoder::Create( gpu_task_runner_, media_log->Clone(), gpu_preferences_, gpu_workarounds_, base::BindRepeating(&GetCommandBufferStub, media_gpu_channel_manager_, command_buffer_id->channel_token, command_buffer_id->route_id), GetD3D11DeviceCallback(), *d3d11_supported_configs_); } #endif // defined(OS_WIN) break; }; // switch // |video_decoder| may be null if we don't support |implementation|. return video_decoder; } std::unique_ptr<CdmFactory> GpuMojoMediaClient::CreateCdmFactory( service_manager::mojom::InterfaceProvider* interface_provider) { #if defined(OS_ANDROID) return std::make_unique<AndroidCdmFactory>( base::Bind(&CreateProvisionFetcher, interface_provider), base::Bind(&CreateMediaDrmStorage, interface_provider)); #else return nullptr; #endif // defined(OS_ANDROID) } #if BUILDFLAG(ENABLE_LIBRARY_CDMS) std::unique_ptr<CdmProxy> GpuMojoMediaClient::CreateCdmProxy( const base::Token& cdm_guid) { if (cdm_proxy_factory_cb_) return cdm_proxy_factory_cb_.Run(cdm_guid); return nullptr; } #endif // BUILDFLAG(ENABLE_LIBRARY_CDMS) } // namespace media
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
a4818d9cbd310a1a5f83dbfafedb4edee5e51fd7
a33aac97878b2cb15677be26e308cbc46e2862d2
/program_data/PKU_raw/94/463.c
250a024346579eb6a0f9328c0419aad1d17e17e0
[]
no_license
GabeOchieng/ggnn.tensorflow
f5d7d0bca52258336fc12c9de6ae38223f28f786
7c62c0e8427bea6c8bec2cebf157b6f1ea70a213
refs/heads/master
2022-05-30T11:17:42.278048
2020-05-02T11:33:31
2020-05-02T11:33:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
475
c
int main(){ int N; int e,i; int m=0; scanf("%d",&N); int sz[1000]; for(i=0;i<N;i++){ scanf("%d",&sz[i]); } for(int k=N-1;k>0;k--){ for(i=0;i<k;i++){ if(sz[i]>sz[i+1]){ e=sz[i]; sz[i]=sz[i+1]; sz[i+1]=e; } } } for(i=0;i<N;i++){ if(sz[i]%2!=0){ m=i; } } for(i=0;i<=m;i++){ if(sz[i]%2!=0&&i<m){ printf("%d,",sz[i]); } if(i==m){ printf("%d",sz[m]); } } return 0; }
[ "bdqnghi@gmail.com" ]
bdqnghi@gmail.com
099730485766e2fbac14fab366fda4ae94315336
ec829f4844a11bb379b1c3b8c4876735abe83573
/src/qt/intro.cpp
77869e67e8a2b4cb47e84e6834f7dff0b01d30cd
[ "MIT" ]
permissive
retzger/CBN
f1d4d448ed9c87659c5a35965f6d4e4532a90d5f
dea43b9bd3c75cc1f34c2d30ed85e14432978bbd
refs/heads/master
2020-11-25T20:14:47.555336
2019-09-01T10:10:55
2019-09-01T10:10:55
228,827,109
1
0
MIT
2019-12-18T11:36:33
2019-12-18T11:36:32
null
UTF-8
C++
false
false
8,925
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "intro.h" #include "ui_intro.h" #include "guiutil.h" #include "util.h" #include <boost/filesystem.hpp> #include <QFileDialog> #include <QMessageBox> #include <QSettings> /* Minimum free space (in bytes) needed for data directory */ static const uint64_t GB_BYTES = 1000000000LL; static const uint64_t BLOCK_CHAIN_SIZE = 1LL * GB_BYTES; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: FreespaceChecker(Intro* intro); enum Status { ST_OK, ST_ERROR }; public slots: void check(); signals: void reply(int status, const QString& message, quint64 available); private: Intro* intro; }; #include "intro.moc" FreespaceChecker::FreespaceChecker(Intro* intro) { this->intro = intro; } void FreespaceChecker::check() { namespace fs = boost::filesystem; QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while (parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if (fs::exists(dataDir)) { if (fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (fs::filesystem_error& e) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } emit reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget* parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE / GB_BYTES)); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ emit stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString& dataDir) { ui->dataDirectory->setText(dataDir); if (dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { namespace fs = boost::filesystem; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if (!GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if (!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while (true) { if (!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); break; } catch (fs::filesystem_error& e) { QMessageBox::critical(0, tr("CBN Core"), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the cbn.conf file in the default data directory * (to be consistent with cbnd behavior) */ if (dataDir != getDefaultDataDirectory()) SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString& message, quint64 bytesAvailable) { switch (status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if (status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%1 GB of free space available").arg(bytesAvailable / GB_BYTES); if (bytesAvailable < BLOCK_CHAIN_SIZE) { freeString += " " + tr("(of %1 GB needed)").arg(BLOCK_CHAIN_SIZE / GB_BYTES); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString& dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if (!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker* executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int, QString, quint64)), this, SLOT(setStatus(int, QString, quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString& dataDir) { mutex.lock(); pathToCheck = dataDir; if (!signalled) { signalled = true; emit requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; }
[ "ziofabry@hotmail.com" ]
ziofabry@hotmail.com
675d3904adc37b2d1cd482b9dae25b67f8d57385
5a0b853d1d80d426d4edb3572b7f2c38c70ce377
/src/pugixml/pugixml/tests/test_memory.cpp
3cb975e9f7e561bf8b8d846043a95285e23e3a99
[ "MIT" ]
permissive
lvous/hadesmem
1537af2779f8f12e7367dab159548572af78ef83
3aa789a42799dfae03e2be0c86f1fbc0f5b82ddd
refs/heads/master
2020-05-17T07:56:17.251294
2015-01-07T15:48:36
2015-01-07T15:48:36
40,565,165
4
1
null
null
null
null
UTF-8
C++
false
false
5,284
cpp
#include "common.hpp" #include "writer_string.hpp" #include <string> namespace { int allocate_count = 0; int deallocate_count = 0; void* allocate(size_t size) { ++allocate_count; return new char[size]; } void deallocate(void* ptr) { ++deallocate_count; delete[] reinterpret_cast<char*>(ptr); } } TEST(memory_custom_memory_management) { allocate_count = deallocate_count = 0; // remember old functions allocation_function old_allocate = get_memory_allocation_function(); deallocation_function old_deallocate = get_memory_deallocation_function(); // replace functions set_memory_management_functions(allocate, deallocate); { // parse document xml_document doc; CHECK(allocate_count == 0 && deallocate_count == 0); CHECK(doc.load(STR("<node />"))); CHECK(allocate_count == 2 && deallocate_count == 0); // modify document (no new page) CHECK(doc.first_child().set_name(STR("foobars"))); CHECK(allocate_count == 2 && deallocate_count == 0); // modify document (new page) std::basic_string<pugi::char_t> s(65536, 'x'); CHECK(doc.first_child().set_name(s.c_str())); CHECK(allocate_count == 3 && deallocate_count == 0); // modify document (new page, old one should die) s += s; CHECK(doc.first_child().set_name(s.c_str())); CHECK(allocate_count == 4 && deallocate_count == 1); } CHECK(allocate_count == 4 && deallocate_count == 4); // restore old functions set_memory_management_functions(old_allocate, old_deallocate); } TEST(memory_large_allocations) { allocate_count = deallocate_count = 0; // remember old functions allocation_function old_allocate = get_memory_allocation_function(); deallocation_function old_deallocate = get_memory_deallocation_function(); // replace functions set_memory_management_functions(allocate, deallocate); { xml_document doc; CHECK(allocate_count == 0 && deallocate_count == 0); // initial fill for (size_t i = 0; i < 128; ++i) { std::basic_string<pugi::char_t> s(i * 128, 'x'); CHECK(doc.append_child(node_pcdata).set_value(s.c_str())); } CHECK(allocate_count > 0 && deallocate_count == 0); // grow-prune loop while (doc.first_child()) { pugi::xml_node node; // grow for (node = doc.first_child(); node; node = node.next_sibling()) { std::basic_string<pugi::char_t> s = node.value(); CHECK(node.set_value((s + s).c_str())); } // prune for (node = doc.first_child(); node; ) { pugi::xml_node next = node.next_sibling().next_sibling(); node.parent().remove_child(node); node = next; } } CHECK(allocate_count == deallocate_count + 1); // only one live page left (it waits for new allocations) char buffer; CHECK(doc.load_buffer_inplace(&buffer, 0, parse_fragment, get_native_encoding())); CHECK(allocate_count == deallocate_count); // no live pages left } CHECK(allocate_count == deallocate_count); // everything is freed // restore old functions set_memory_management_functions(old_allocate, old_deallocate); } TEST(memory_string_allocate_increasing) { xml_document doc; doc.append_child(node_pcdata).set_value(STR("x")); std::basic_string<char_t> s = STR("ab"); for (int i = 0; i < 17; ++i) { doc.append_child(node_pcdata).set_value(s.c_str()); s += s; } std::string result = save_narrow(doc, format_no_declaration | format_raw, encoding_utf8); CHECK(result.size() == 262143); CHECK(result[0] == 'x'); for (size_t j = 1; j < result.size(); ++j) { CHECK(result[j] == (j % 2 ? 'a' : 'b')); } } TEST(memory_string_allocate_decreasing) { xml_document doc; std::basic_string<char_t> s = STR("ab"); for (int i = 0; i < 17; ++i) s += s; for (int j = 0; j < 17; ++j) { s.resize(s.size() / 2); doc.append_child(node_pcdata).set_value(s.c_str()); } doc.append_child(node_pcdata).set_value(STR("x")); std::string result = save_narrow(doc, format_no_declaration | format_raw, encoding_utf8); CHECK(result.size() == 262143); CHECK(result[result.size() - 1] == 'x'); for (size_t k = 0; k + 1 < result.size(); ++k) { CHECK(result[k] == (k % 2 ? 'b' : 'a')); } } TEST(memory_string_allocate_increasing_inplace) { xml_document doc; xml_node node = doc.append_child(node_pcdata); node.set_value(STR("x")); std::basic_string<char_t> s = STR("ab"); for (int i = 0; i < 17; ++i) { node.set_value(s.c_str()); s += s; } std::string result = save_narrow(doc, format_no_declaration | format_raw, encoding_utf8); CHECK(result.size() == 131072); for (size_t j = 0; j < result.size(); ++j) { CHECK(result[j] == (j % 2 ? 'b' : 'a')); } } TEST(memory_string_allocate_decreasing_inplace) { xml_document doc; xml_node node = doc.append_child(node_pcdata); std::basic_string<char_t> s = STR("ab"); for (int i = 0; i < 17; ++i) s += s; for (int j = 0; j < 17; ++j) { s.resize(s.size() / 2); node.set_value(s.c_str()); } node.set_value(STR("x")); std::string result = save_narrow(doc, format_no_declaration | format_raw, encoding_utf8); CHECK(result == "x"); }
[ "raptorfactor@raptorfactor.com" ]
raptorfactor@raptorfactor.com
645b4d227a608a8c6d68f7fbd8f88635886dc8c2
1bfb510ae1d67391a7993015aeda56a52b019564
/2Dgame_MetalSlugAttack/2Dgame_MetalSlugAttack/Image.h
5daba12f14ca88f3cf25418abda0c1e15dddfaff
[]
no_license
kslee9512/2D_MetalSlugAttack
d147b3387e142434ef3ca28a44e1cca03963752b
a0dd322231aa66c8d3fa7ea23c5207344fb7c9f1
refs/heads/main
2023-05-13T15:26:27.758788
2021-06-02T08:24:35
2021-06-02T08:24:35
365,885,358
0
0
null
null
null
null
UHC
C++
false
false
3,079
h
#pragma once #include "config.h" class Image { public: enum IMAGE_LOAD_KIND { RESOURCE, // 프로젝트 자체에 포함 시킬 이미지 FILE, // 외부에서 로드할 이미지 EMPTY, // 자체 생산 이미지 END }; typedef struct tagImageInfo { DWORD resID; // 리소스의 고유한 ID HDC hMemDC; // 그리기를 주관하는 핸들 HBITMAP hBitmap; // 이미지 정보 HBITMAP hOldBit; // 기존 이미지 정보 int width; // 이미지 가로 크기 int height; // 이미지 세로 크기 BYTE loadType; // 로드 타입 // 알파블랜드 HDC hBlendDC; HBITMAP hBlendBit; HBITMAP hOldBlendBit; // 애니메이션 관련 (프레임데이터) int maxFrameX; int maxFrameY; int frameWidth; int frameHeight; int currFrameX; int currFrameY; tagImageInfo() { resID = 0; hMemDC = NULL; hBitmap = NULL; hOldBit = NULL; width = 0; height = 0; loadType = IMAGE_LOAD_KIND::EMPTY; hBlendDC = NULL; hBlendBit = NULL; hOldBlendBit = NULL; maxFrameX = 0; maxFrameY = 0; frameWidth = 0; frameHeight = 0; currFrameX = 0; currFrameY = 0; }; } IMAGE_INFO, * LPIMAGE_INFO; private: IMAGE_INFO* imageInfo; // 이미지 정보 구조체 포인터 //LPIMAGE_INFO imageInfo; bool isTransparent; COLORREF transColor; BLENDFUNCTION blendFunc; public: // 빈 비트맵 이미지를 만드는 함수 HRESULT Init(int width, int height); // 파일로부터 이미지를 로드하는 함수 HRESULT Init(const char* fileName, int width, int height, bool isTransparent = FALSE, COLORREF transColor = FALSE); // 파일로부터 이미지를 로드하는 함수 HRESULT Init(const char* fileName, int width, int height, int maxFrameX, int maxFrameY, bool isTransparent = FALSE, COLORREF transColor = FALSE); // 화면에 출력 void Render(HDC hdc, int destX = 0, int destY = 0, bool isCenterRenderring = false); void CoolTimeRender(HDC hdc, int destX = 0, int destY = 0, bool isCenterRenderring = false, float maxCoolTime = 1.0f, float currTime = 1.0f); void FrameRender(HDC hdc, int destX, int destY, int currFrameX, int currFrameY, bool isCenterRenderring = false, int size = 1); void AlphaRender(HDC hdc, int destX, int destY, bool isCenterRenderring = false); void PlayerBaseHpRender(HDC hdc, int destX = 0, int destY = 0, bool isCenterRenderring = false, float currBaseHp = 1.0f, float maxBaseHp = 1.0f); void EnemyBaseHpRender(HDC hdc, int destX = 0, int destY = 0, bool isCenterRendering = false, float currBaseHp = 1.0f, float maxBaseHp = 1.0f); void Release(); // get, set HDC GetMemDC() { if (this->imageInfo) return this->imageInfo->hMemDC; return NULL; } BLENDFUNCTION* GetBlendFunc() { return &(this->blendFunc); } int GetWidth() { return this->imageInfo->width; } int GetHeight() { return this->imageInfo->height; } int GetFrameWidth() { return this->imageInfo->frameWidth; } int GetFrameHeight() { return this->imageInfo->frameHeight; } IMAGE_INFO* const GetImageInfo() { return this->imageInfo; } };
[ "kslee9512@gmail.com" ]
kslee9512@gmail.com
2934203c7c2ebd97cb4e9503e9204886be4d1399
e398a585764f16511a70d0ef33a3b61da0733b69
/7600.16385.1/src/print/XPSDrvSmpl/src/filters/color/scaniter.cpp
4b7bed1ebab7dc8663faa18d6553ada586275dd8
[ "MIT" ]
permissive
MichaelDavidGK/WinDDK
f9e4fc6872741ee742f8eace04b2b3a30b049495
eea187e357d61569e67292ff705550887c4df908
refs/heads/master
2020-05-30T12:26:40.125588
2019-06-01T13:28:10
2019-06-01T13:28:10
189,732,991
0
0
null
2019-06-01T12:58:11
2019-06-01T12:58:11
null
UTF-8
C++
false
false
14,704
cpp
/*++ Copyright (c) 2005 Microsoft Corporation All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. File Name: scaniter.cpp Abstract: CScanIterator class implementation. The scan iterator class provides a convenient interface for iterating over WIC data and retrieving scanline data approriate for consumption in WCS/ICM. For example, the WIC pixel formats do not have alpha channel positions that correspond with the WCS/ICM BMFORMAT types so this class is responsible for presenting bitmap data without the alpha channel and for copying alpha data from source to destination when scnaline changes are commited to the underlying WIC bitmap. --*/ #include "precomp.h" #include "debug.h" #include "xdexcept.h" #include "globals.h" #include "scaniter.h" /*++ Routine Name: CScanIterator::CScanIterator Routine Description: CScanIterator constructor Arguments: bmpConv - Bitmap converter class encapsulating the underlying WIC bitmap pRect - The rectangular area of the bitmap over which we want to iterate scanlines Return Value: None Throws an exception on error. --*/ CScanIterator::CScanIterator( __in CONST CBmpConverter& bmpConv, __in_opt WICRect* pRect ) : CBmpConverter(bmpConv), m_bSrcLine(TRUE), m_cbWICStride(0), m_cWICWidth(0), m_cWICHeight(0), m_cbWICData(0), m_pbWICData(NULL) { HRESULT hr = S_OK; UINT cWidth = 0; UINT cHeight = 0; if (SUCCEEDED(hr = CHECK_POINTER(m_pBitmap, E_POINTER)) && SUCCEEDED(hr = m_pBitmap->GetSize(&cWidth, &cHeight))) { if (pRect == NULL) { // // We want to iterate over the entire surface // m_rectTotal.X = 0; m_rectTotal.Y = 0; m_rectTotal.Width = static_cast<INT>(cWidth); m_rectTotal.Height = static_cast<INT>(cHeight); } else { if (pRect->X >= 0 && pRect->Y >= 0 && pRect->Width <= static_cast<INT>(cWidth) && pRect->Height <= static_cast<INT>(cHeight)) { m_rectTotal = *pRect; } else { hr = E_INVALIDARG; } } } if (FAILED(hr)) { throw CXDException(hr); } } /*++ Routine Name: CScanIterator::~CScanIterator Routine Description: CScanIterator destructor Arguments: None Return Value: None --*/ CScanIterator::~CScanIterator() { UnlockSurface(); } /*++ Routine Name: CScanIterator::Initialize Routine Description: Initialize the iterator. Here we are going to: 1. Convert to a suitable WIC format for processing 2. Allocate an intermediate color buffer (if required) for processing 3. Allocate an intermediate alpha buffer (if required) for processing 4. Reset and lock the iterator rect ready for processing Arguments: bSrcLine - true if this is a source scanline (i.e. read only) Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CScanIterator::Initialize( __in CONST BOOL& bSrcLine ) { HRESULT hr = S_OK; m_bSrcLine = bSrcLine; // // Look up the pixel format to convert to so that the bitmap is appropriate // for consumption by WCS/ICM. // // Note: we are not dealing with the limitations of ICM downlevel. Downlevel // we need to convert floating and fixed point values to values appropriate // to ICM then back again before writing out so the underlying bitmap type is // unmodified. // EWICPixelFormat eConversionFormat = kWICPixelFormatDontCare; if (m_ePixelFormat > 0 && m_ePixelFormat < kWICPixelFormatMax) { eConversionFormat = g_lutWICToBMFormat[m_ePixelFormat].m_pixFormTarget; } else { RIP("Unrecognised pixel format.\n"); hr = E_FAIL; } // // Apply the conversion if required // BOOL bCanConvert = FALSE; if (eConversionFormat != m_ePixelFormat && SUCCEEDED(hr) && SUCCEEDED(hr = Convert(eConversionFormat, &bCanConvert))) { if (!bCanConvert) { RIP("Cannot convert to target type.\n"); hr = E_FAIL; } } // // Set the current iteration data ready for processing // if (SUCCEEDED(hr)) { // // Ensure the iterator is reset to the start of the area to be processed. This // ensures that the current rect lock is valid so that we can initialise the // first scanline to process // Reset(); // // Initialise the WIC <-> BM scan line converter // if (SUCCEEDED(hr = m_currScan.Initialize(g_lutWICToBMFormat[m_ePixelFormat]))) { hr = SetCurrentIterationData(); } } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CScanIterator::Reset Routine Description: Resets the current rect to the first scanline in the buffer. Arguments: None Return Value: None --*/ VOID CScanIterator::Reset( VOID ) { m_rectCurrLock.X = m_rectTotal.X; m_rectCurrLock.Y = m_rectTotal.Y; m_rectCurrLock.Width = m_rectTotal.Width; m_rectCurrLock.Height = 1; } /*++ Routine Name: CScanIterator::operator++ Routine Description: Iterate to the next scan line. Arguments: None Return Value: Reference to this iterator --*/ CScanIterator& CScanIterator::operator++(INT) { HRESULT hr = S_OK; m_rectCurrLock.Y++; if (!Finished()) { if (FAILED(hr = SetCurrentIterationData())) { throw CXDException(hr); } } return *this; } /*++ Routine Name: CScanIterator::GetScanBuffer Routine Description: Retrieves the scanline buffer appropriate for WCS/ICM consumption Arguments: ppData - Pointer to pointer that recieves the address of the data buffer Note: the buffer is only valid for the lifetime of the CScanIterator object. pBmFormat - Pointer to a BMFORMAT enumeration that recieves the format pcWidth - Pointer to storage that recieves the pixel width pcHeight - Pointer to storage that recieves the pixel height pcbStride - Pointer to storage that recieves the stride Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CScanIterator::GetScanBuffer( __deref_bcount(*pcbStride) PBYTE* ppData, __out BMFORMAT* pBmFormat, __out UINT* pcWidth, __out UINT* pcHeight, __out UINT* pcbStride ) { HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(ppData, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(pBmFormat, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(pcWidth, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(pcHeight, E_POINTER)) && SUCCEEDED(hr = CHECK_POINTER(pcbStride, E_POINTER))) { *ppData = NULL; *pcWidth = 0; *pcHeight = 1; *pcbStride = 0; *pBmFormat = BM_RGBTRIPLETS; // // Get the data from the WIC <-> BMFORMAT scanline converter // hr = m_currScan.GetData(ppData, pBmFormat, pcWidth, pcbStride); } ERR_ON_HR(hr); return hr; } /*++ Routine Name: CScanIterator::Commit Routine Description: Commits the current color buffer to the surface if required and applies an optional alpha channel passed in from a source iterator Arguments: alphaSource - Scan iterator instance with any potential alpha data to copy Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CScanIterator::Commit( __in CONST CScanIterator& alphaSource ) { HRESULT hr = S_OK; COLORDATATYPE srcDataType = COLOR_BYTE; COLORDATATYPE dstDataType = COLOR_BYTE; if (m_bSrcLine) { RIP("Cannot commit to readonly surface.\n"); hr = E_FAIL; } else if (alphaSource.m_ePixelFormat >= kWICPixelFormatMax || alphaSource.m_ePixelFormat < kWICPixelFormatMin || m_ePixelFormat >= kWICPixelFormatMax || m_ePixelFormat < kWICPixelFormatMin) { RIP("Invalid pixel format.\n"); hr = E_FAIL; } else { srcDataType = g_lutWICToBMFormat[alphaSource.m_ePixelFormat].m_colDataType; dstDataType = g_lutWICToBMFormat[m_ePixelFormat].m_colDataType; if (srcDataType > COLOR_S2DOT13FIXED || srcDataType < COLOR_BYTE || dstDataType > COLOR_S2DOT13FIXED || dstDataType < COLOR_BYTE) { RIP("Invalid data type.\n"); hr = E_FAIL; } } if (SUCCEEDED(hr) && alphaSource.HasAlphaChannel() && HasAlphaChannel()) { // // Convert and copy alpha data into destination // PBYTE pDst = m_pbWICData; size_t cbDstChannel = g_lutColorDataSize[dstDataType]; size_t cbDstAlphaOffset = g_lutWICToBMFormat[m_ePixelFormat].m_cAlphaOffset * cbDstChannel; UINT cDstChannels = g_lutWICToBMFormat[m_ePixelFormat].m_cChannels; PBYTE pSrc = alphaSource.m_pbWICData; size_t cbSrcChannel = g_lutColorDataSize[srcDataType]; size_t cbSrcAlphaOffset = g_lutWICToBMFormat[alphaSource.m_ePixelFormat].m_cAlphaOffset * cbSrcChannel; UINT cSrcChannels = g_lutWICToBMFormat[alphaSource.m_ePixelFormat].m_cChannels; if (m_cWICWidth * cDstChannels * cbDstChannel <= m_cbWICStride && alphaSource.m_cWICWidth * cSrcChannels * cbSrcChannel <= alphaSource.m_cbWICStride) { // // Move the source and destination to the first alpha channel // pDst += cbDstAlphaOffset; pSrc += cbSrcAlphaOffset; // // Call the appropriate convert copy function by casting the src pointer // to the underlying data type // switch (srcDataType) { case COLOR_BYTE: hr = ConvertCopyAlphaChannels(reinterpret_cast<PBYTE>(pSrc), m_cWICWidth, cSrcChannels, dstDataType, pDst, m_cWICWidth, cDstChannels); break; case COLOR_WORD: hr = ConvertCopyAlphaChannels(reinterpret_cast<PWORD>(pSrc), m_cWICWidth, cSrcChannels, dstDataType, pDst, m_cWICWidth, cDstChannels); break; case COLOR_FLOAT: hr = ConvertCopyAlphaChannels(reinterpret_cast<PFLOAT>(pSrc), m_cWICWidth, cSrcChannels, dstDataType, pDst, m_cWICWidth, cDstChannels); break; case COLOR_S2DOT13FIXED: hr = ConvertCopyAlphaChannels(reinterpret_cast<PS2DOT13FIXED>(pSrc), m_cWICWidth, cSrcChannels, dstDataType, pDst, m_cWICWidth, cDstChannels); break; default: { RIP("Unrecognized source format.\n"); hr = E_FAIL; } break; } } else { RIP("Insufficient buffer sizes.\n"); hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); } } // // Commit the scanline // if (SUCCEEDED(hr)) { hr = m_currScan.Commit(m_pbWICData, m_cbWICStride); } // // Release the lock // UnlockSurface(); m_cbWICStride = 0; m_cWICWidth = 0; m_cWICHeight = 0; m_cbWICData = 0; m_pbWICData = NULL; ERR_ON_HR(hr); return hr; } /*++ Routine Name: CScanIterator::Finished Routine Description: We are done once all scanlines have been processed. Arguments: None Return Value: TRUE - We have iterated over all requested scanlines FALSE - There are scanlines remaining --*/ BOOL CScanIterator::Finished( VOID ) { return m_rectCurrLock.Y >= (m_rectTotal.Y + m_rectTotal.Height); } /*++ Routine Name: CScanIterator::SetCurrentIterationData Routine Description: Sets up the current iteration data by locking the relevant area of the WIC bitmap source and getting the WIC to BMFORMAT converter class to apply any conversion required Arguments: None Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CScanIterator::SetCurrentIterationData( VOID ) { HRESULT hr = S_OK; m_cbWICStride = 0; m_cWICWidth = 0; m_cWICHeight = 0; m_cbWICData = 0; m_pbWICData = NULL; if (SUCCEEDED(hr = LockSurface(&m_rectCurrLock, m_bSrcLine, &m_cbWICStride, &m_cWICWidth, &m_cWICHeight, &m_cbWICData, &m_pbWICData)) && SUCCEEDED(hr = CHECK_POINTER(m_pbWICData, E_FAIL))) { hr = m_currScan.SetData(m_bSrcLine, m_pbWICData, m_cbWICStride, m_cWICWidth); } ERR_ON_HR(hr); return hr; }
[ "blindtiger@foxmail.com" ]
blindtiger@foxmail.com
95e1e61905a04a3a870c6d62283f81f494f88d94
f8df0470893e10f25f4362b84feecb9011293f43
/build/iOS/Preview/include/Fuse.Gestures.LongPressedHandler.h
3e96328298b9d4ef9542247273ab22c5ff37752c
[]
no_license
cekrem/PlateNumber
0593a84a5ff56ebd9663382905dc39ae4e939b08
3a4e40f710bb0db109a36d65000dca50e79a22eb
refs/heads/master
2021-08-23T02:06:58.388256
2017-12-02T11:01:03
2017-12-02T11:01:03
112,779,024
0
0
null
null
null
null
UTF-8
C++
false
false
428
h
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Gestures/1.4.0/LongPress.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Delegate.h> namespace g{ namespace Fuse{ namespace Gestures{ // public delegate void LongPressedHandler(object sender, Fuse.Gestures.LongPressedArgs args) :15 uDelegateType* LongPressedHandler_typeof(); }}} // ::g::Fuse::Gestures
[ "cekrem@Christians-MacBook-Pro.local" ]
cekrem@Christians-MacBook-Pro.local
de9d7c85b350d3b4ea87c00186ec6cb9e859d851
9c0b20b9c9670b2e918194e2e492d25768a1029d
/LongestCommonSubsequence.cpp
34cefe6abb567959dc7a23fab73c3c4ec1c01c8c
[]
no_license
emuemuJP/AOJ
3162571915d95a0d1baee198fa11f7b11ae1b32c
e02b229afe47adef7c398961f49c3f22bf1d1731
refs/heads/master
2023-05-03T04:25:40.951980
2021-05-22T11:13:49
2021-05-22T11:13:49
328,708,599
0
0
null
null
null
null
UTF-8
C++
false
false
1,336
cpp
#include <iostream> #include <vector> #include <queue> #include <algorithm> #include <cmath> #include <bitset> #include <iomanip> #include <stack> #include <list> #include <map> #include <unordered_map> #include <chrono> #include <numeric> using namespace std; using ll = long long; const ll INF = (ll)1e18+1; const ll DIV = 1000000007; //#define TEST int main() { cin.tie(0); ios::sync_with_stdio(false); #ifdef TEST chrono::system_clock::time_point start, end; start = chrono::system_clock::now(); #endif int q; cin >> q; for(size_t i=0;i<q; i++) { string X, Y; cin >> X; cin >> Y; std::vector<std::vector<int>> mat(X.length()+1, vector<int>(Y.length()+1, 0)); for(size_t ii=1;ii<X.length()+1; ii++) { for(size_t jj=1;jj<Y.length()+1; jj++) { if(X[ii-1]==Y[jj-1]) mat[ii][jj] = mat[ii-1][jj-1]+1; else if(mat[ii][jj-1] >= mat[ii-1][jj]) mat[ii][jj] = mat[ii][jj-1]; else mat[ii][jj] = mat[ii-1][jj]; } } cout << mat[X.length()][Y.length()] << endl; } #ifdef TEST end = chrono::system_clock::now(); cerr << static_cast<double>(chrono::duration_cast<chrono::microseconds>(end - start).count() / 1000.0) << "[ms]" << endl; #endif return 0; }
[ "k.matsumoto.0807@gmail.com" ]
k.matsumoto.0807@gmail.com
4a9b1ab8bae7fb29e122a3b6caa1823da6a31e41
9a412c6a2584bf64215948a6fa975f205eab61d3
/src/qt/miningpage.cpp
e1ece78e262853769b0886e7cb1d2fe89ca1d7a2
[ "MIT" ]
permissive
tm0r20w/meowcoin
39f0cf4d74f60a56f2a0e7f430698f76f3c8dc65
cf85f83099701b2d03312756461958426a44c183
refs/heads/main
2023-05-09T12:28:25.575791
2021-06-01T08:35:07
2021-06-01T08:35:07
372,749,555
0
0
null
null
null
null
UTF-8
C++
false
false
11,678
cpp
#include "miningpage.h" #include "ui_miningpage.h" MiningPage::MiningPage(QWidget *parent) : QWidget(parent), ui(new Ui::MiningPage) { ui->setupUi(this); setFixedSize(400, 420); minerActive = false; minerProcess = new QProcess(this); minerProcess->setProcessChannelMode(QProcess::MergedChannels); readTimer = new QTimer(this); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; initThreads = 0; connect(readTimer, SIGNAL(timeout()), this, SLOT(readProcessOutput())); connect(ui->startButton, SIGNAL(pressed()), this, SLOT(startPressed())); connect(ui->typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int))); connect(ui->debugCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugToggled(bool))); connect(minerProcess, SIGNAL(started()), this, SLOT(minerStarted())); connect(minerProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(minerError(QProcess::ProcessError))); connect(minerProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(minerFinished())); connect(minerProcess, SIGNAL(readyRead()), this, SLOT(readProcessOutput())); } MiningPage::~MiningPage() { minerProcess->kill(); delete ui; } void MiningPage::setModel(ClientModel *model) { this->model = model; loadSettings(); bool pool = model->getMiningType() == ClientModel::PoolMining; ui->threadsBox->setValue(model->getMiningThreads()); ui->typeBox->setCurrentIndex(pool ? 1 : 0); // if (model->getMiningStarted()) // startPressed(); } void MiningPage::startPressed() { initThreads = ui->threadsBox->value(); if (minerActive == false) { saveSettings(); if (getMiningType() == ClientModel::SoloMining) minerStarted(); else startPoolMining(); } else { if (getMiningType() == ClientModel::SoloMining) minerFinished(); else stopPoolMining(); } } void MiningPage::startPoolMining() { QStringList args; QString url = ui->serverLine->text(); if (!url.contains("http://")) url.prepend("http://"); QString urlLine = QString("%1:%2").arg(url, ui->portLine->text()); QString userpassLine = QString("%1:%2").arg(ui->usernameLine->text(), ui->passwordLine->text()); args << "--algo" << "scrypt"; args << "--scantime" << ui->scantimeBox->text().toAscii(); args << "--url" << urlLine.toAscii(); args << "--userpass" << userpassLine.toAscii(); args << "--threads" << ui->threadsBox->text().toAscii(); args << "--retries" << "-1"; // Retry forever. args << "-P"; // This is needed for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker. threadSpeed.clear(); acceptedShares = 0; rejectedShares = 0; roundAcceptedShares = 0; roundRejectedShares = 0; // If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere. QString program = QDir::current().filePath("minerd"); if (!QFile::exists(program)) program = "minerd"; if (ui->debugCheckBox->isChecked()) ui->list->addItem(args.join(" ").prepend(" ").prepend(program)); ui->mineSpeedLabel->setText("Speed: N/A"); ui->shareCount->setText("Accepted: 0 - Rejected: 0"); minerProcess->start(program,args); minerProcess->waitForStarted(-1); readTimer->start(500); } void MiningPage::stopPoolMining() { ui->mineSpeedLabel->setText(""); minerProcess->kill(); readTimer->stop(); } void MiningPage::saveSettings() { model->setMiningDebug(ui->debugCheckBox->isChecked()); model->setMiningScanTime(ui->scantimeBox->value()); model->setMiningServer(ui->serverLine->text()); model->setMiningPort(ui->portLine->text()); model->setMiningUsername(ui->usernameLine->text()); model->setMiningPassword(ui->passwordLine->text()); } void MiningPage::loadSettings() { ui->debugCheckBox->setChecked(model->getMiningDebug()); ui->scantimeBox->setValue(model->getMiningScanTime()); ui->serverLine->setText(model->getMiningServer()); ui->portLine->setText(model->getMiningPort()); ui->usernameLine->setText(model->getMiningUsername()); ui->passwordLine->setText(model->getMiningPassword()); } void MiningPage::readProcessOutput() { QByteArray output; minerProcess->reset(); output = minerProcess->readAll(); QString outputString(output); if (!outputString.isEmpty()) { QStringList list = outputString.split("\n", QString::SkipEmptyParts); int i; for (i=0; i<list.size(); i++) { QString line = list.at(i); // Ignore protocol dump if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr")) continue; if (ui->debugCheckBox->isChecked()) { ui->list->addItem(line.trimmed()); ui->list->scrollToBottom(); } if (line.contains("(yay!!!)")) reportToList("Share accepted", SHARE_SUCCESS, getTime(line)); else if (line.contains("(booooo)")) reportToList("Share rejected", SHARE_FAIL, getTime(line)); else if (line.contains("LONGPOLL detected new block")) reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line)); else if (line.contains("Supported options:")) reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL); else if (line.contains("The requested URL returned error: 403")) reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL); else if (line.contains("HTTP request failed")) reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL); else if (line.contains("JSON-RPC call failed")) reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL); else if (line.contains("thread ") && line.contains("khash/s")) { QString threadIDstr = line.at(line.indexOf("thread ")+7); int threadID = threadIDstr.toInt(); int threadSpeedindx = line.indexOf(","); QString threadSpeedstr = line.mid(threadSpeedindx); threadSpeedstr.chop(8); threadSpeedstr.remove(", "); threadSpeedstr.remove(" "); threadSpeedstr.remove('\n'); double speed=0; speed = threadSpeedstr.toDouble(); threadSpeed[threadID] = speed; updateSpeed(); } } } } void MiningPage::minerError(QProcess::ProcessError error) { if (error == QProcess::FailedToStart) { reportToList("Miner failed to start. Make sure you have the minerd executable and libraries in the same directory as meowcoin-qt.", ERROR, NULL); } } void MiningPage::minerFinished() { if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining stopped.", ERROR, NULL); else reportToList("Miner exited.", ERROR, NULL); ui->list->addItem(""); minerActive = false; resetMiningButton(); model->setMining(getMiningType(), false, initThreads, 0); } void MiningPage::minerStarted() { if (!minerActive) if (getMiningType() == ClientModel::SoloMining) reportToList("Solo mining started.", ERROR, NULL); else reportToList("Miner started. You might not see any output for a few minutes.", STARTED, NULL); minerActive = true; resetMiningButton(); model->setMining(getMiningType(), true, initThreads, 0); } void MiningPage::updateSpeed() { double totalSpeed=0; int totalThreads=0; QMapIterator<int, double> iter(threadSpeed); while(iter.hasNext()) { iter.next(); totalSpeed += iter.value(); totalThreads++; } // If all threads haven't reported the hash speed yet, make an assumption if (totalThreads != initThreads) { totalSpeed = (totalSpeed/totalThreads)*initThreads; } QString speedString = QString("%1").arg(totalSpeed); QString threadsString = QString("%1").arg(initThreads); QString acceptedString = QString("%1").arg(acceptedShares); QString rejectedString = QString("%1").arg(rejectedShares); QString roundAcceptedString = QString("%1").arg(roundAcceptedShares); QString roundRejectedString = QString("%1").arg(roundRejectedShares); if (totalThreads == initThreads) ui->mineSpeedLabel->setText(QString("Speed: %1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); else ui->mineSpeedLabel->setText(QString("Speed: ~%1 khash/sec - %2 thread(s)").arg(speedString, threadsString)); ui->shareCount->setText(QString("Accepted: %1 (%3) - Rejected: %2 (%4)").arg(acceptedString, rejectedString, roundAcceptedString, roundRejectedString)); model->setMining(getMiningType(), true, initThreads, totalSpeed*1000); } void MiningPage::reportToList(QString msg, int type, QString time) { QString message; if (time == NULL) message = QString("[%1] - %2").arg(QTime::currentTime().toString(), msg); else message = QString("[%1] - %2").arg(time, msg); switch(type) { case SHARE_SUCCESS: acceptedShares++; roundAcceptedShares++; updateSpeed(); break; case SHARE_FAIL: rejectedShares++; roundRejectedShares++; updateSpeed(); break; case LONGPOLL: roundAcceptedShares = 0; roundRejectedShares = 0; break; default: break; } ui->list->addItem(message); ui->list->scrollToBottom(); } // Function for fetching the time QString MiningPage::getTime(QString time) { if (time.contains("[")) { time.resize(21); time.remove("["); time.remove("]"); time.remove(0,11); return time; } else return NULL; } void MiningPage::enableMiningControls(bool enable) { ui->typeBox->setEnabled(enable); ui->threadsBox->setEnabled(enable); ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } void MiningPage::enablePoolMiningControls(bool enable) { ui->scantimeBox->setEnabled(enable); ui->serverLine->setEnabled(enable); ui->portLine->setEnabled(enable); ui->usernameLine->setEnabled(enable); ui->passwordLine->setEnabled(enable); } ClientModel::MiningType MiningPage::getMiningType() { if (ui->typeBox->currentIndex() == 0) // Solo Mining { return ClientModel::SoloMining; } else if (ui->typeBox->currentIndex() == 1) // Pool Mining { return ClientModel::PoolMining; } return ClientModel::SoloMining; } void MiningPage::typeChanged(int index) { if (index == 0) // Solo Mining { enablePoolMiningControls(false); } else if (index == 1) // Pool Mining { enablePoolMiningControls(true); } } void MiningPage::debugToggled(bool checked) { model->setMiningDebug(checked); } void MiningPage::resetMiningButton() { ui->startButton->setText(minerActive ? "Stop Mining" : "Start Mining"); enableMiningControls(!minerActive); }
[ "noreply@github.com" ]
noreply@github.com
ca96abf5bd9f593d4e0681c3afc4346ceb4ade57
0f3122ce2aa1a5c4c5e0d38c3d8c590ce485ca03
/security/adrms/acquireclientlicensor/AcquireClientLicensor.cpp
c4da967426d1d94a1917f828751d8d0ee866c7d2
[]
no_license
WindowsKernel/sdk71examples
15cfee86bcb6621d13b91ca59bba425391b1b7a8
677997402e3bd3e51558464e50e4c33ebe1dd491
refs/heads/master
2022-04-27T21:10:51.846940
2015-01-19T18:35:09
2015-01-19T18:35:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,412
cpp
/*===================================================================== File: acquireclientlicensor.cpp THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. Copyright (C) Microsoft Corporation. All rights reserved. =====================================================================*/ // // This sample shows how to acquire a client licensor certificate. It // takes an optional activation and certification server URL as input. // It will use Service Discovery to find the server URLs if the URLs are // not provided. The sample requires that a UserID be provided as input. // See the comments at the beginning of wmain() for a more detailed // description. // #include <stdio.h> #include <Wtypes.h> #include <strsafe.h> #include "msdrm.h" #include "msdrmdefs.h" #include "msdrmerror.h" // // Time to wait for "downloads" to complete // static const DWORD DW_WAIT_TIME_SECONDS = 60 * 1000; // // struct to hold the callback information // typedef struct Drm_Context { HANDLE hEvent; HRESULT hr; } DRM_CONTEXT, *PDRM_CONTEXT; // // Print the correct usage of this application // void PrintUsage() { wprintf( L"Usage:\n" ); wprintf( L"\n AcquireClientLicensor -U UserID [-A ActivationSvr] "\ L"[-L LicensingSvr]\n" ); wprintf( L" -U: specifies the UserID.\n" ); wprintf( L" example: user@yourdomain.com\n" ); wprintf( L" -A: specifies the Activation Server. (optional)\n" ); wprintf( L" example: http://localhost/_wmcs/certification\n" ); wprintf( L" -L: specifies the Licensing Server. (optional)\n" ); wprintf( L" example: http://localhost/_wmcs/licensing\n" ); } // // Parse the values passed in through the command line // HRESULT ParseCommandLine( int argc, __in_ecount( argc )WCHAR **argv, __deref_out_opt PWCHAR *pwszUserID, __deref_out PWCHAR *pwszActivationSvr, __deref_out PWCHAR *pwszLicensingSvr ) { HRESULT hr = S_OK; size_t uiUserIDLength = 0; size_t uiActSvrUrlLength = 0; size_t uiLicSvrUrlLength = 0; // // Initialize parameters // *pwszUserID = NULL; // // Check input parameters. // if ( ( 3 != argc ) && ( 5 != argc ) && ( 7 != argc ) ) { return E_INVALIDARG; } for( int i = 1; SUCCEEDED( hr ) && i < argc - 1; i ++ ) { if ( ( '-' != argv[ i ][ 0 ] ) && ( '/' != argv[ i ][ 0 ] ) ) { hr = E_INVALIDARG; break; } else if ( ( '-' == argv[ i + 1 ][ 0 ] ) || ( '/' == argv[ i + 1 ][ 0 ] ) ) { hr = E_INVALIDARG; break; } switch( toupper( argv[ i ][ 1 ] ) ) { // // User ID // case 'U': if ( wcsstr( argv[ i + 1 ], ( wchar_t* )L"@\0" ) == NULL ) { // // An invalid User ID was provided // hr = E_INVALIDARG; break; } // // Retrieve the length of the user ID // hr = StringCchLengthW( argv[ i + 1 ], STRSAFE_MAX_CCH, &uiUserIDLength ); if ( FAILED( hr ) ) { wprintf( L"StringCchLengthW failed. hr = 0x%x\n", hr ); break; } // // Allocate memory for the user ID // *pwszUserID = new WCHAR[ uiUserIDLength + 1 ]; if ( NULL == *pwszUserID ) { wprintf( L"Failed to allocate memory for pwszUserID.\n" ); hr = E_OUTOFMEMORY; break; } // // Copy the URL into the pwszUserID buffer // hr = StringCchCopyW( ( wchar_t* )*pwszUserID, uiUserIDLength + 1 , argv[ i + 1 ] ); if ( FAILED( hr ) ) { wprintf( L"StringCchCopyW failed. hr = 0x%x\n", hr ); break; } i++; break; case 'A': if ( ( _wcsnicmp( argv[ i + 1 ], L"http://", 7 ) != 0 ) && ( _wcsnicmp( argv[ i + 1 ], L"https://", 8 ) != 0 ) ) { wprintf( L"Invalid activation URL provided.\n" ); hr = E_INVALIDARG; break; } // // Retrieve the length of the activation server URL // hr = StringCchLengthW( argv[ i + 1 ], STRSAFE_MAX_CCH, &uiActSvrUrlLength ); if ( FAILED( hr ) ) { wprintf( L"StringCchLengthW failed. hr = 0x%x\n", hr ); break; } // // Allocate memory for the URL // *pwszActivationSvr = new WCHAR[ uiActSvrUrlLength + 1 ]; if( NULL == *pwszActivationSvr ) { wprintf( L"Failed to allocate memory "\ L"for pwszActivationSvr.\n" ); hr = E_OUTOFMEMORY; break; } // // Copy the URL into the pwszActivationSvr buffer // hr = StringCchCopyW( ( wchar_t* )*pwszActivationSvr, uiActSvrUrlLength + 1 , argv[ i + 1 ] ); if ( FAILED( hr ) ) { wprintf( L"StringCchCopyW failed. hr = 0x%x\n", hr ); break; } i++; break; case 'L': if ( ( _wcsnicmp( argv[ i + 1 ], L"http://", 7 ) != 0 ) && ( _wcsnicmp( argv[ i + 1 ], L"https://", 8 ) != 0 ) ) { wprintf( L"Invalid licensing URL provided.\n" ); hr = E_INVALIDARG; break; } // // Retrieve the length of the licensing server URL // hr = StringCchLengthW( argv[ i + 1 ], STRSAFE_MAX_CCH, &uiLicSvrUrlLength ); if ( FAILED( hr ) ) { wprintf( L"StringCchLengthW failed. hr = 0x%x\n", hr ); break; } // // Allocate memory for the URL // *pwszLicensingSvr = new WCHAR[ uiLicSvrUrlLength + 1 ]; if( NULL == *pwszLicensingSvr ) { wprintf( L"Failed to allocate memory "\ L"for pwszLicensingSvr.\n" ); hr = E_OUTOFMEMORY; break; } // // Copy the URL into the pwszLicensingSvr buffer // hr = StringCchCopyW( ( wchar_t* )*pwszLicensingSvr, uiLicSvrUrlLength + 1 , argv[ i + 1 ] ); if ( FAILED( hr ) ) { wprintf( L"StringCchCopyW failed. hr = 0x%x\n", hr ); break; } i++; break; default: hr = E_INVALIDARG; break; } } if ( NULL == *pwszUserID ) { wprintf( L"A user ID value is required.\n" ); hr = E_INVALIDARG; } return hr; } // // Callback function for asynchronous ADRMS client functions // HRESULT __stdcall StatusCallback( DRM_STATUS_MSG msg, HRESULT hr, void *pvParam, void *pvContext ) { PDRM_CONTEXT pContext = ( PDRM_CONTEXT )pvContext; if ( pContext ) { pContext->hr = hr; } else { return E_FAIL; } // // Set pvParam to NULL since we don't expect // a return value from the callback // pvParam = NULL; if ( FAILED( pContext->hr ) && pContext->hEvent ) { // // Signal the event // SetEvent( ( HANDLE )pContext->hEvent ); return S_OK; } // // Print the callback status message // switch( msg ) { case DRM_MSG_ACTIVATE_MACHINE: wprintf( L"\nCallback status msg = DRM_MSG_ACTIVATE_MACHINE " ); break; case DRM_MSG_ACTIVATE_GROUPIDENTITY: wprintf( L"\nCallback status msg = DRM_MSG_ACTIVATE_GROUPIDENTITY " ); break; case DRM_MSG_ACQUIRE_CLIENTLICENSOR: wprintf( L"\nCallback status msg = DRM_MSG_ACQUIRE_CLIENTLICENSOR " ); break; default: wprintf( L"\nDefault callback status msg = 0x%x ", msg ); break; } // // Print the callback error code // switch( pContext->hr ) { case S_DRM_ALREADY_ACTIVATED: wprintf( L"Callback hr = S_DRM_ALREADY_ACTIVATED\n" ); break; case S_DRM_CONNECTING: wprintf( L"Callback hr = S_DRM_CONNECTING\n" ); break; case S_DRM_CONNECTED: wprintf( L"Callback hr = S_DRM_CONNECTED\n" ); break; case S_DRM_INPROGRESS: wprintf( L"Callback hr = S_DRM_INPROGRESS\n" ); break; case S_DRM_COMPLETED: wprintf( L"Callback hr = S_DRM_COMPLETED\n" ); pContext->hr = S_OK; if ( pContext->hEvent ) { SetEvent( ( HANDLE )pContext->hEvent ); } break; case E_DRM_ACTIVATIONFAILED: wprintf( L"Callback hr = E_DRM_ACTIVATIONFAILED\n" ); break; case E_DRM_HID_CORRUPTED: wprintf( L"Callback hr = E_DRM_HID_CORRUPTED\n" ); break; case E_DRM_INSTALLATION_FAILED: wprintf( L"Callback hr = E_DRM_INSTALLATION_FAILED\n" ); break; case E_DRM_ALREADY_IN_PROGRESS: wprintf( L"Callback hr = E_DRM_ALREADY_IN_PROGRESS\n" ); break; case E_DRM_NO_CONNECT: wprintf( L"Callback hr = E_DRM_NO_CONNECT\n" ); break; case E_DRM_ABORTED: wprintf( L"Callback hr = E_DRM_ABORTED\n" ); break; case E_DRM_SERVER_ERROR: wprintf( L"Callback hr = E_DRM_SERVER_ERROR\n" ); break; case E_DRM_INVALID_SERVER_RESPONSE: wprintf( L"Callback hr = E_DRM_INVALID_SERVER_RESPONSE\n" ); break; case E_DRM_SERVER_NOT_FOUND: wprintf( L"Callback hr = E_DRM_SERVER_NOT_FOUND\n" ); break; case E_DRM_AUTHENTICATION_FAILED: wprintf( L"Callback hr = E_DRM_AUTHENTICATION_FAILED\n" ); break; case E_DRM_EMAIL_NOT_VERIFIED: wprintf( L"Callback hr = E_DRM_EMAIL_NOT_VERIFIED\n" ); break; case E_DRM_AD_ENTRY_NOT_FOUND: wprintf( L"Callback hr = E_DRM_AD_ENTRY_NOT_FOUND\n" ); break; case E_DRM_NEEDS_MACHINE_ACTIVATION: wprintf( L"Callback hr = E_DRM_NEEDS_MACHINE_ACTIVATION\n" ); break; case E_DRM_REQUEST_DENIED: wprintf( L"Callback hr = E_DRM_REQUEST_DENIED\n" ); break; case E_DRM_INVALID_EMAIL: wprintf( L"Callback hr = E_DRM_INVALID_EMAIL\n" ); break; case E_DRM_SERVICE_GONE: wprintf( L"Callback hr = E_DRM_SERVICE_GONE\n" ); break; case E_DRM_SERVICE_MOVED: wprintf( L"Callback hr = E_DRM_SERVICE_MOVED\n" ); break; case E_DRM_VALIDITYTIME_VIOLATION: wprintf( L"Callback hr = E_DRM_VALIDITYTIME_VIOLATION\n" ); break; case S_DRM_REQUEST_PREPARED: wprintf( L"Callback hr = S_DRM_REQUEST_PREPARED\n" ); break; case E_DRM_NO_LICENSE: wprintf( L"Callback hr = E_DRM_NO_LICENSE\n" ); break; case E_DRM_SERVICE_NOT_FOUND: wprintf( L"Callback hr = E_DRM_SERVICE_NOT_FOUND\n" ); break; default: wprintf( L"Default callback hr = 0x%x\n", hr ); pContext->hr = S_OK; if ( pContext->hEvent ) { SetEvent( ( HANDLE )pContext->hEvent ); } break; } return S_OK; } // // This function performs the following actions: // 1. Validate the parameters // 2. Create an event for the callback function // 3. Populate the wszURL member of the DRM_ACTSERV_INFO struct // with the activation server URL. This value can be from: // (a) a command line argument // (b) service discovery // 4. Activate the machine // 5. Wait for the callback to return // 6. Clean up and free memory HRESULT __stdcall DoMachineActivation( DRMHSESSION hClient, __in PWCHAR wszActivationSvr ) { HRESULT hr = E_FAIL; DRM_ACTSERV_INFO *pdasi = NULL; UINT uiStrLen = 0; size_t cchActivationSvr = 0; DWORD dwWaitResult; DRM_CONTEXT context; context.hEvent = NULL; // // 1. Validate the parameters // if ( NULL == hClient ) { wprintf( L"\nThe client session was NULL." ); hr = E_INVALIDARG; goto e_Exit; } // // 2. Create an event for the callback function // if ( NULL == ( context.hEvent = CreateEvent( NULL, FALSE, FALSE, NULL ) ) ) { wprintf( L"\ncontext.hEvent was NULL after the CreateEvent call" ); goto e_Exit; } // // Allocate memory for the DRM_ACTSERV_INFO structure for activation // pdasi = new DRM_ACTSERV_INFO; if ( NULL == pdasi ) { wprintf( L"\nMemory allocation failed for DRM_ACTSERV_INFO.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } pdasi->wszURL = NULL; // // 3. Copy the activation server URL into the wszURL member // of the DRM_ACTSERV_INFO struct // if ( NULL != wszActivationSvr ) { // // 3(a). Use the URL provided through the command line argument // hr = StringCchLengthW( wszActivationSvr, STRSAFE_MAX_CCH, &cchActivationSvr ); if ( FAILED( hr ) ) { wprintf( L"\nStringCchLengthW failed. hr = 0x%x.\n", hr ); goto e_Exit; } // // Allocate memory for the URL member of the DRM_ACTSERV_INFO structure // pdasi->wszURL = new WCHAR[ cchActivationSvr + 1 ]; if ( NULL == pdasi->wszURL ) { wprintf( L"\nMemory allocation failed for activation URL string.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } hr = StringCchCopyW( pdasi->wszURL, cchActivationSvr + 1, wszActivationSvr ); if ( FAILED( hr ) ) { wprintf( L"\nStringCchCopyW failed. hr = 0x%x.\n", hr ); goto e_Exit; } wprintf( L"\nMachine Activation server URL:\n%s\n", pdasi->wszURL ); } else { // // 3(b). Try to find the service location where activation // is available. // The first call is to get - // (a) whether there is a service location and // (b) if so, the size needed for a buffer to // hold the URL for the service. // hr = DRMGetServiceLocation( hClient, DRM_SERVICE_TYPE_ACTIVATION, DRM_SERVICE_LOCATION_ENTERPRISE, NULL, &uiStrLen, NULL ); if ( SUCCEEDED( hr ) ) { // // There is a service location; reserve space // for the URL. // pdasi->wszURL = new WCHAR[ uiStrLen ]; if ( NULL == pdasi->wszURL ) { wprintf( L"\nMemory allocation failed for activation "\ L"URL string.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } // // Call second time to get the actual service location // copied into the URL. // hr = DRMGetServiceLocation( hClient, DRM_SERVICE_TYPE_ACTIVATION, DRM_SERVICE_LOCATION_ENTERPRISE, NULL, &uiStrLen, pdasi->wszURL ); if ( FAILED( hr ) ) { wprintf( L"\nDRMGetServiceLocation (ENTERPRISE) failed. "\ L"hr = 0x%x\n", hr ); goto e_Exit; } wprintf( L"\nDRMGetServiceLocation (ENTERPRISE) succeeded.\n\n"\ L"Machine Activation server URL:\n%s\n", pdasi->wszURL ); } else { wprintf( L"\nDRMGetServiceLocation failed. hr = 0x%x. "\ L"\nPassing NULL server info to DRMActivate.\n", hr ); } } // // 4. Activate the machine // hr = DRMActivate( hClient, DRM_ACTIVATE_MACHINE | DRM_ACTIVATE_SILENT, 0, pdasi, ( VOID* )&context, NULL ); if ( FAILED( hr ) ) { wprintf( L"\nDRMActivate (DRM_ACTIVATE_MACHINE) "\ L"failed. hr = 0x%x\n", hr ); goto e_Exit; } // // 5. Wait for the callback to return // dwWaitResult = WaitForSingleObject( context.hEvent, DW_WAIT_TIME_SECONDS ); if ( WAIT_TIMEOUT == dwWaitResult ) { wprintf( L"\nWaitForSingleObject timed out." ); goto e_Exit; } if ( FAILED( context.hr ) ) { // // In case a failure was reported via the callback function // note it also. // wprintf( L"\nThe callback function returned a failure "\ L"code. hr = 0x%x\n", context.hr ); hr = context.hr; goto e_Exit; } wprintf( L"\nThe machine is now activated.\n" ); e_Exit: // // 5. Clean up and free memory // if ( NULL != pdasi ) { if ( NULL != pdasi->wszURL ) { delete [] pdasi->wszURL; } delete pdasi; } if ( NULL != context.hEvent ) { CloseHandle( context.hEvent ); } return hr; } // // This function performs the following actions: // 1. Validate the parameters // 2. Create an event for the callback function // 3. Populate the wszURL member of the DRM_ACTSERV_INFO struct with // the user activation server URL. This value can be from: // (a) a command line argument // (b) service discovery // 4. Activate the user // 5. Wait for the callback to return // 6. Clean up and free memory HRESULT __stdcall DoUserActivation( DRMHSESSION hClient, __in PWCHAR wszActivationSvr ) { HRESULT hr = E_FAIL; DRM_ACTSERV_INFO *pdasi = NULL; UINT uiStrLen = 0; size_t cchActivationSvr = 0; DWORD dwWaitResult; DRM_CONTEXT context; context.hEvent = NULL; // // 1. Validate the parameters // if ( NULL == hClient ) { wprintf( L"\nThe client session was NULL." ); hr = E_INVALIDARG; goto e_Exit; } // // 2. Create an event for the callback function // if ( NULL == ( context.hEvent = CreateEvent( NULL, FALSE, FALSE, NULL ) ) ) { wprintf( L"\ncontext.hEvent was NULL after the CreateEvent call" ); goto e_Exit; } // // Allocate memory for the DRM_ACTSERV_INFO structure for activation // pdasi = new DRM_ACTSERV_INFO; if ( NULL == pdasi ) { wprintf( L"\nMemory allocation failed for DRM_ACTSERV_INFO.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } pdasi->wszURL = NULL; // // 3. Copy the activation server URL into the wszURL member // of the DRM_ACTSERV_INFO struct // if ( NULL != wszActivationSvr ) { // // 3(a). Use the URL provided through the command line argument // hr = StringCchLengthW( wszActivationSvr, STRSAFE_MAX_CCH, &cchActivationSvr ); if ( FAILED( hr ) ) { wprintf( L"\nStringCchLengthW failed. hr = 0x%x.\n", hr ); goto e_Exit; } // // Allocate memory for the URL member of the DRM_ACTSERV_INFO structure // pdasi->wszURL = new WCHAR[ cchActivationSvr + 1 ]; if ( NULL == pdasi->wszURL ) { wprintf( L"\nMemory allocation failed for user "\ L"activation URL string.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } hr = StringCchCopyW( pdasi->wszURL, cchActivationSvr + 1, wszActivationSvr ); if ( FAILED( hr ) ) { wprintf( L"\nStringCchCopyW failed. hr = 0x%x.\n", hr ); goto e_Exit; } wprintf( L"\nUser Activation server URL:\n%s\n", pdasi->wszURL ); } else { // // 3(b). Try to find the service location where user activation // is available. // The first call is to get - // (a) whether there is a service location and // (b) if so, the size needed for a buffer to // hold the URL for the service. // hr = DRMGetServiceLocation( hClient, DRM_SERVICE_TYPE_CERTIFICATION, DRM_SERVICE_LOCATION_ENTERPRISE, NULL, &uiStrLen, NULL ); if ( SUCCEEDED( hr ) ) { // // There is a service location; reserve space // for the URL. // pdasi->wszURL = new WCHAR[ uiStrLen ]; if ( NULL == pdasi->wszURL ) { wprintf( L"\nMemory allocation failed for user activation "\ L"URL string.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } // // Call second time to get the actual service location // copied into the URL. // hr = DRMGetServiceLocation( hClient, DRM_SERVICE_TYPE_CERTIFICATION, DRM_SERVICE_LOCATION_ENTERPRISE, NULL, &uiStrLen, pdasi->wszURL ); if ( FAILED( hr ) ) { wprintf( L"\nDRMGetServiceLocation (ENTERPRISE) failed. "\ L"hr = 0x%x\n", hr ); goto e_Exit; } wprintf( L"\nDRMGetServiceLocation (ENTERPRISE) succeeded.\n\n"\ L"User Activation server URL:\n%s\n", pdasi->wszURL ); } else { wprintf( L"\nDRMGetServiceLocation failed. hr = 0x%x. "\ L"\nPassing NULL server info to DRMActivate.\n", hr ); } } // // 4. Activate the user // hr = DRMActivate( hClient, DRM_ACTIVATE_GROUPIDENTITY | DRM_ACTIVATE_SILENT, 0, pdasi, ( VOID* )&context, NULL ); if ( FAILED( hr ) ) { wprintf( L"\nDRMActivate (DRM_ACTIVATE_GROUPIDENTITY) "\ L"failed. hr = 0x%x\n", hr ); goto e_Exit; } // // 5. Wait for the callback to return // dwWaitResult = WaitForSingleObject( context.hEvent, DW_WAIT_TIME_SECONDS ); if ( WAIT_TIMEOUT == dwWaitResult ) { wprintf( L"\nWaitForSingleObject timed out." ); goto e_Exit; } if ( FAILED( context.hr ) ) { // // In case a failure was reported via the callback function // note it also. // wprintf( L"\nThe callback function returned a failure "\ L"code. hr = 0x%x\n", context.hr ); hr = context.hr; goto e_Exit; } wprintf( L"\nThe user is now activated.\n" ); e_Exit: // // 5. Clean up and free memory // if ( NULL != pdasi ) { if ( NULL != pdasi->wszURL ) { delete [] pdasi->wszURL; } delete pdasi; } if ( NULL != context.hEvent ) { CloseHandle( context.hEvent ); } return hr; } // // This sample will perform the following actions: // 1. Create a client session // 2. Determine if the machine needs to be activated // 3. Call DoMachineActivation to activate the machine if // it's not activated // 4. Determine if the user needs to be activated // 5. Call DoUserActivation to activate the user if the user // is not activated // 6. Create an event for the callback function // 7. If the licensing URL was not passed in via the command line, // find the licensing URL through service discovery // 8. Acquire the client licensor certificate // 9. Wait for the callback to return // 10. Clean up and free memory // int __cdecl wmain( int argc, __in_ecount( argc )WCHAR **argv ) { HRESULT hr = E_FAIL; DRMHSESSION hClient = NULL; HANDLE hEvent = NULL; PWCHAR wszActivationSvr = NULL; PWCHAR wszLicensingSvr = NULL; UINT uiStrLen = 0; PWCHAR wszUserId = NULL; DWORD dwWaitResult; DRM_CONTEXT context; context.hEvent = NULL; if ( FAILED ( ParseCommandLine( argc, argv, &wszUserId, &wszActivationSvr, &wszLicensingSvr ) ) ) { PrintUsage(); goto e_Exit; } wprintf( L"\nRunning sample AcquireClientLicensor...\n" ); // // 1. Create a client session // hr = DRMCreateClientSession( &StatusCallback, 0, DRM_DEFAULTGROUPIDTYPE_WINDOWSAUTH, wszUserId, &hClient ); if ( FAILED( hr ) ) { wprintf( L"\nDRMCreateClientSession failed. hr = 0x%x\n", hr ); goto e_Exit; } // // 2. Call DRMIsActivated to determine if the machine is already activated // hr = DRMIsActivated( hClient, DRM_ACTIVATE_MACHINE, NULL ); if ( E_DRM_NEEDS_MACHINE_ACTIVATION == hr ) { // // 3. Call DoMachineActivation to activate the machine if // it's not activated // hr = DoMachineActivation( hClient, wszActivationSvr ); if ( FAILED( hr ) ) { wprintf( L"\nDoMachineActivation failed. hr = 0x%x\n", hr ); goto e_Exit; } } else if ( hr == S_OK ) { wprintf( L"The machine is already activated.\n" ); } else { wprintf( L"\nDRMIsActivated returned an unexpected failure: 0x%x. "\ L"E_DRM_NEEDS_MACHINE_ACTIVATION was expected.\n", hr ); goto e_Exit; } // // 4. Call DRMIsActivated to determine if the user is // already activated. // hr = DRMIsActivated( hClient, DRM_ACTIVATE_GROUPIDENTITY, NULL ); if ( SUCCEEDED( hr ) ) { wprintf( L"The user is already activated.\n" ); } else if ( E_DRM_NEEDS_GROUPIDENTITY_ACTIVATION == hr ) { // // 5. Call DoUserActivation to activate the user if the user // is not activated // hr = DoUserActivation( hClient, wszActivationSvr ); if ( FAILED( hr ) ) { wprintf( L"\nDoUserActivation failed. hr = 0x%x\n", hr ); goto e_Exit; } } else if ( E_DRM_NEEDS_GROUPIDENTITY_ACTIVATION != hr ) { wprintf( L"\nDRMIsActivated returned an unexpected failure: 0x%x. "\ L"E_DRM_NEEDS_GROUPIDENTITY_ACTIVATION "\ L"was expected.\n", hr ); goto e_Exit; } // // 6. Create an event for the callback function. The StatusCallback // function registered in DRMCreateClientSession. This event will be // passed as a void pointer to DRMAcquireLicense. DRMAcquireLicense // simply passes back this pointer to the StatusCallback callback // function which knows that it is an event and will thus signal it // when completed. // if ( NULL == ( context.hEvent = CreateEvent( NULL, FALSE, FALSE, NULL ) ) ) { wprintf( L"\ncontext.hEvent was NULL after the CreateEvent call." ); goto e_Exit; } // // 7. If the licensing URL was not passed in via the command line, // find the licensing URL through service discovery // if ( NULL == wszLicensingSvr ) { // The first call is to get - // (a) whether there is a service location and // (b) if so, the size needed for a buffer to // hold the URL for the service. // hr = DRMGetServiceLocation( hClient, DRM_SERVICE_TYPE_CLIENTLICENSOR, DRM_SERVICE_LOCATION_ENTERPRISE, NULL, &uiStrLen, NULL ); if ( FAILED( hr ) ) { wprintf( L"DRMGetServiceLocation failed. hr = 0x%x\n", hr ); goto e_Exit; } wszLicensingSvr = new WCHAR[ uiStrLen ]; if ( NULL == wszLicensingSvr ) { wprintf( L"\nMemory allocation failed for licensing URL string.\n" ); hr = E_OUTOFMEMORY; goto e_Exit; } hr = DRMGetServiceLocation( hClient, DRM_SERVICE_TYPE_CLIENTLICENSOR, DRM_SERVICE_LOCATION_ENTERPRISE, NULL, &uiStrLen, wszLicensingSvr ); if ( FAILED( hr ) ) { wprintf( L"DRMGetServiceLocation failed. hr = 0x%x\n", hr ); goto e_Exit; } } wprintf( L"Licensing URL: %s\n", wszLicensingSvr ); // // 8. Acquire the client licensor certificate // hr = DRMAcquireLicense( hClient, 0, NULL, NULL, NULL, wszLicensingSvr, ( VOID* )&context ); if ( FAILED( hr ) ) { wprintf( L"DRMAcquireLicense failed. hr = 0x%x\n", hr ); goto e_Exit; } // // 9. Wait for the callback to return // dwWaitResult = WaitForSingleObject( context.hEvent, DW_WAIT_TIME_SECONDS ); if ( WAIT_TIMEOUT == dwWaitResult ) { wprintf( L"\nWaitForSingleObject timed out." ); goto e_Exit; } if ( FAILED( context.hr ) ) { // // In case a failure was reported via the callback function // note it also. // hr = context.hr; wprintf( L"\nThe callback function returned a failure "\ L"code. hr = 0x%x\n", context.hr ); goto e_Exit; } wprintf( L"\nThe client licensor certificate has been acquired.\n" ); e_Exit: // // 10. Clean up and free memory // if ( NULL != wszActivationSvr ) { delete [] wszActivationSvr; } if ( NULL != wszLicensingSvr ) { delete [] wszLicensingSvr; } if ( NULL != wszUserId ) { delete [] wszUserId; } if ( NULL != hClient ) { DRMCloseSession( hClient ); } if ( NULL != context.hEvent ) { CloseHandle( context.hEvent ); } if ( FAILED( hr ) ) { wprintf( L"\nAcquireClientLicensor failed. hr = 0x%x\n", hr ); } return hr; }
[ "ganboing@gmail.com" ]
ganboing@gmail.com
5e3b73671a4cb270edcd01a36576eb9c67791443
7579d827cb7b50b438dfd9ef6fa80ba2797848c9
/sources/plug_land/include/luna/wrappers/wrapper_proland_BasicGraph.h
9fc272efb1685e8d0709c68355b35860dbc4d89d
[]
no_license
roche-emmanuel/sgt
809d00b056e36b7799bbb438b8099e3036377377
ee3a550f6172c7d14179d9d171e0124306495e45
refs/heads/master
2021-05-01T12:51:39.983104
2014-09-08T03:35:15
2014-09-08T03:35:15
79,538,908
3
0
null
null
null
null
UTF-8
C++
false
false
19,375
h
#ifndef _WRAPPERS_WRAPPER_PROLAND_BASICGRAPH_H_ #define _WRAPPERS_WRAPPER_PROLAND_BASICGRAPH_H_ #include <plug_common.h> #include "lua/LuaObject.h" #include <W:/Cloud/Projects/sgt/sources/proland/sources/graph/proland/graph/BasicGraph.h> class wrapper_proland_BasicGraph : public proland::BasicGraph, public luna_wrapper_base { public: ~wrapper_proland_BasicGraph() { logDEBUG3("Calling delete function for wrapper proland_BasicGraph"); if(_obj.pushFunction("delete")) { //_obj.pushArg((proland::BasicGraph*)this); // No this argument or the object will be referenced again! _obj.callFunction<void>(); } }; wrapper_proland_BasicGraph(lua_State* L, lua_Table* dum) : proland::BasicGraph(), luna_wrapper_base(L) { register_protected_methods(L); if(_obj.pushFunction("buildInstance")) { _obj.pushArg((proland::BasicGraph*)this); _obj.callFunction<void>(); } }; // Private virtual methods: protected: // Protected virtual methods: // void ork::Object::doRelease() void doRelease() { if(_obj.pushFunction("doRelease")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<void>()); } return BasicGraph::doRelease(); }; // void proland::BasicGraph::removeNode(proland::NodeId id) void removeNode(proland::NodeId id) { if(_obj.pushFunction("removeNode")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&id); return (_obj.callFunction<void>()); } return BasicGraph::removeNode(id); }; // void proland::BasicGraph::removeCurve(proland::CurveId id) void removeCurve(proland::CurveId id) { if(_obj.pushFunction("removeCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&id); return (_obj.callFunction<void>()); } return BasicGraph::removeCurve(id); }; // void proland::BasicGraph::removeArea(proland::AreaId id) void removeArea(proland::AreaId id) { if(_obj.pushFunction("removeArea")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&id); return (_obj.callFunction<void>()); } return BasicGraph::removeArea(id); }; // void proland::BasicGraph::clean() void clean() { if(_obj.pushFunction("clean")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<void>()); } return BasicGraph::clean(); }; public: // Public virtual methods: // const char * ork::Object::toString() const char * toString() { if(_obj.pushFunction("toString")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<const char*>()); } return BasicGraph::toString(); }; // void proland::Graph::print(bool detailed = true) void print(bool detailed = true) { if(_obj.pushFunction("print")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(detailed); return (_obj.callFunction<void>()); } return BasicGraph::print(detailed); }; // void proland::Graph::setParent(proland::Graph * p) void setParent(proland::Graph * p) { if(_obj.pushFunction("setParent")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(p); return (_obj.callFunction<void>()); } return BasicGraph::setParent(p); }; // proland::Node * proland::Graph::findNode(ork::vec2d & pos) const proland::Node * findNode(ork::vec2d & pos) const { if(_obj.pushFunction("findNode")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&pos); return (_obj.callFunction<proland::Node*>()); } return BasicGraph::findNode(pos); }; // void proland::Graph::checkParams(int nodes, int curves, int areas, int curveExtremities, int curvePoints, int areaCurves, int subgraphs) void checkParams(int nodes, int curves, int areas, int curveExtremities, int curvePoints, int areaCurves, int subgraphs) { if(_obj.pushFunction("checkParams")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(nodes); _obj.pushArg(curves); _obj.pushArg(areas); _obj.pushArg(curveExtremities); _obj.pushArg(curvePoints); _obj.pushArg(areaCurves); _obj.pushArg(subgraphs); return (_obj.callFunction<void>()); } return BasicGraph::checkParams(nodes, curves, areas, curveExtremities, curvePoints, areaCurves, subgraphs); }; // void proland::Graph::checkDefaultParams(int nodes, int curves, int areas, int curveExtremities, int curvePoints, int areaCurves, int subgraphs) void checkDefaultParams(int nodes, int curves, int areas, int curveExtremities, int curvePoints, int areaCurves, int subgraphs) { if(_obj.pushFunction("checkDefaultParams")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(nodes); _obj.pushArg(curves); _obj.pushArg(areas); _obj.pushArg(curveExtremities); _obj.pushArg(curvePoints); _obj.pushArg(areaCurves); _obj.pushArg(subgraphs); return (_obj.callFunction<void>()); } return BasicGraph::checkDefaultParams(nodes, curves, areas, curveExtremities, curvePoints, areaCurves, subgraphs); }; // void proland::Graph::save(const string & file, bool saveAreas = true, bool isBinary = true, bool isIndexed = false) void save(const string & file, bool saveAreas = true, bool isBinary = true, bool isIndexed = false) { if(_obj.pushFunction("save")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(file); _obj.pushArg(saveAreas); _obj.pushArg(isBinary); _obj.pushArg(isIndexed); return (_obj.callFunction<void>()); } return BasicGraph::save(file, saveAreas, isBinary, isIndexed); }; // void proland::Graph::save(proland::FileWriter * fileWriter, bool saveAreas = true) void save(proland::FileWriter * fileWriter, bool saveAreas = true) { if(_obj.pushFunction("save")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(fileWriter); _obj.pushArg(saveAreas); return (_obj.callFunction<void>()); } return BasicGraph::save(fileWriter, saveAreas); }; // void proland::Graph::indexedSave(proland::FileWriter * fileWriter, bool saveAreas = true) void indexedSave(proland::FileWriter * fileWriter, bool saveAreas = true) { if(_obj.pushFunction("indexedSave")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(fileWriter); _obj.pushArg(saveAreas); return (_obj.callFunction<void>()); } return BasicGraph::indexedSave(fileWriter, saveAreas); }; // proland::Graph * proland::Graph::clip(const ork::box2d & clip, proland::Margin * margin) proland::Graph * clip(const ork::box2d & clip, proland::Margin * margin) { if(_obj.pushFunction("clip")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&clip); _obj.pushArg(margin); return (_obj.callFunction<proland::Graph*>()); } return BasicGraph::clip(clip, margin); }; // proland::CurvePtr proland::Graph::addCurvePart(proland::CurvePart & cp, set< proland::CurveId > * addedCurves, bool setParent = true) proland::CurvePtr addCurvePart(proland::CurvePart & cp, set< proland::CurveId > * addedCurves, bool setParent = true) { if(_obj.pushFunction("addCurvePart")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&cp); _obj.pushArg(addedCurves); _obj.pushArg(setParent); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::addCurvePart(cp, addedCurves, setParent); }; // void proland::Graph::movePoint(proland::CurvePtr c, int i, const ork::vec2d & p) void movePoint(proland::CurvePtr c, int i, const ork::vec2d & p) { if(_obj.pushFunction("movePoint")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&c); _obj.pushArg(i); _obj.pushArg(&p); return (_obj.callFunction<void>()); } return BasicGraph::movePoint(c, i, p); }; // void proland::Graph::movePoint(proland::CurvePtr c, int i, const ork::vec2d & p, set< proland::CurveId > & changedCurves) void movePoint(proland::CurvePtr c, int i, const ork::vec2d & p, set< proland::CurveId > & changedCurves) { if(_obj.pushFunction("movePoint")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&c); _obj.pushArg(i); _obj.pushArg(&p); _obj.pushArg(&changedCurves); return (_obj.callFunction<void>()); } return BasicGraph::movePoint(c, i, p, changedCurves); }; // proland::NodePtr proland::Graph::addNode(proland::CurvePtr c, int i, proland::Graph::Changes & changed) proland::NodePtr addNode(proland::CurvePtr c, int i, proland::Graph::Changes & changed) { if(_obj.pushFunction("addNode")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&c); _obj.pushArg(i); _obj.pushArg(&changed); return *(_obj.callFunction<proland::NodePtr*>()); } return BasicGraph::addNode(c, i, changed); }; // proland::CurvePtr proland::Graph::addCurve(ork::vec2d start, ork::vec2d end, proland::Graph::Changes & changed) proland::CurvePtr addCurve(ork::vec2d start, ork::vec2d end, proland::Graph::Changes & changed) { if(_obj.pushFunction("addCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&start); _obj.pushArg(&end); _obj.pushArg(&changed); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::addCurve(start, end, changed); }; // proland::CurvePtr proland::Graph::addCurve(proland::NodeId start, ork::vec2d end, proland::Graph::Changes & changed) proland::CurvePtr addCurve(proland::NodeId start, ork::vec2d end, proland::Graph::Changes & changed) { if(_obj.pushFunction("addCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&start); _obj.pushArg(&end); _obj.pushArg(&changed); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::addCurve(start, end, changed); }; // proland::CurvePtr proland::Graph::addCurve(proland::NodeId start, proland::NodeId end, proland::Graph::Changes & changed) proland::CurvePtr addCurve(proland::NodeId start, proland::NodeId end, proland::Graph::Changes & changed) { if(_obj.pushFunction("addCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&start); _obj.pushArg(&end); _obj.pushArg(&changed); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::addCurve(start, end, changed); }; // void proland::Graph::removeVertex(proland::CurvePtr & curve, int & selectedSegment, int & selectedPoint, proland::Graph::Changes & changed) void removeVertex(proland::CurvePtr & curve, int & selectedSegment, int & selectedPoint, proland::Graph::Changes & changed) { if(_obj.pushFunction("removeVertex")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&curve); _obj.pushArg(selectedSegment); _obj.pushArg(selectedPoint); _obj.pushArg(&changed); return (_obj.callFunction<void>()); } return BasicGraph::removeVertex(curve, selectedSegment, selectedPoint, changed); }; // proland::CurvePart * proland::Graph::createCurvePart(proland::CurvePtr p, int orientation, int start, int end) proland::CurvePart * createCurvePart(proland::CurvePtr p, int orientation, int start, int end) { if(_obj.pushFunction("createCurvePart")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&p); _obj.pushArg(orientation); _obj.pushArg(start); _obj.pushArg(end); return (_obj.callFunction<proland::CurvePart*>()); } return BasicGraph::createCurvePart(p, orientation, start, end); }; // proland::Graph * proland::Graph::createChild() proland::Graph * createChild() { if(_obj.pushFunction("createChild")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<proland::Graph*>()); } return BasicGraph::createChild(); }; // void proland::BasicGraph::clear() void clear() { if(_obj.pushFunction("clear")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<void>()); } return BasicGraph::clear(); }; // int proland::BasicGraph::getNodeCount() const int getNodeCount() const { if(_obj.pushFunction("getNodeCount")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<int>()); } return BasicGraph::getNodeCount(); }; // int proland::BasicGraph::getCurveCount() const int getCurveCount() const { if(_obj.pushFunction("getCurveCount")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<int>()); } return BasicGraph::getCurveCount(); }; // int proland::BasicGraph::getAreaCount() const int getAreaCount() const { if(_obj.pushFunction("getAreaCount")) { _obj.pushArg((proland::BasicGraph*)this); return (_obj.callFunction<int>()); } return BasicGraph::getAreaCount(); }; // proland::NodePtr proland::BasicGraph::getNode(proland::NodeId id) proland::NodePtr getNode(proland::NodeId id) { if(_obj.pushFunction("getNode")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&id); return *(_obj.callFunction<proland::NodePtr*>()); } return BasicGraph::getNode(id); }; // proland::CurvePtr proland::BasicGraph::getCurve(proland::CurveId id) proland::CurvePtr getCurve(proland::CurveId id) { if(_obj.pushFunction("getCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&id); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::getCurve(id); }; // proland::AreaPtr proland::BasicGraph::getArea(proland::AreaId id) proland::AreaPtr getArea(proland::AreaId id) { if(_obj.pushFunction("getArea")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&id); return *(_obj.callFunction<proland::AreaPtr*>()); } return BasicGraph::getArea(id); }; // proland::AreaPtr proland::BasicGraph::getChildArea(proland::AreaId parentId) proland::AreaPtr getChildArea(proland::AreaId parentId) { if(_obj.pushFunction("getChildArea")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&parentId); return *(_obj.callFunction<proland::AreaPtr*>()); } return BasicGraph::getChildArea(parentId); }; // void proland::BasicGraph::load(const string & file, bool loadSubgraphs = true) void load(const string & file, bool loadSubgraphs = true) { if(_obj.pushFunction("load")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(file); _obj.pushArg(loadSubgraphs); return (_obj.callFunction<void>()); } return BasicGraph::load(file, loadSubgraphs); }; // void proland::BasicGraph::load(proland::FileReader * fileReader, bool loadSubgraphs = true) void load(proland::FileReader * fileReader, bool loadSubgraphs = true) { if(_obj.pushFunction("load")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(fileReader); _obj.pushArg(loadSubgraphs); return (_obj.callFunction<void>()); } return BasicGraph::load(fileReader, loadSubgraphs); }; // void proland::BasicGraph::loadIndexed(proland::FileReader * fileReader, bool loadSubgraphs = true) void loadIndexed(proland::FileReader * fileReader, bool loadSubgraphs = true) { if(_obj.pushFunction("loadIndexed")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(fileReader); _obj.pushArg(loadSubgraphs); return (_obj.callFunction<void>()); } return BasicGraph::loadIndexed(fileReader, loadSubgraphs); }; // proland::NodePtr proland::BasicGraph::newNode(const ork::vec2d & p) proland::NodePtr newNode(const ork::vec2d & p) { if(_obj.pushFunction("newNode")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&p); return *(_obj.callFunction<proland::NodePtr*>()); } return BasicGraph::newNode(p); }; // proland::CurvePtr proland::BasicGraph::newCurve(proland::CurvePtr parent, bool setParent) proland::CurvePtr newCurve(proland::CurvePtr parent, bool setParent) { if(_obj.pushFunction("newCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&parent); _obj.pushArg(setParent); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::newCurve(parent, setParent); }; // proland::CurvePtr proland::BasicGraph::newCurve(proland::CurvePtr model, proland::NodePtr start, proland::NodePtr end) proland::CurvePtr newCurve(proland::CurvePtr model, proland::NodePtr start, proland::NodePtr end) { if(_obj.pushFunction("newCurve")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&model); _obj.pushArg(&start); _obj.pushArg(&end); return *(_obj.callFunction<proland::CurvePtr*>()); } return BasicGraph::newCurve(model, start, end); }; // proland::AreaPtr proland::BasicGraph::newArea(proland::AreaPtr parent, bool setParent) proland::AreaPtr newArea(proland::AreaPtr parent, bool setParent) { if(_obj.pushFunction("newArea")) { _obj.pushArg((proland::BasicGraph*)this); _obj.pushArg(&parent); _obj.pushArg(setParent); return *(_obj.callFunction<proland::AreaPtr*>()); } return BasicGraph::newArea(parent, setParent); }; // Protected non-virtual methods: // void proland::Graph::mergeNodes(proland::NodeId ida, proland::NodeId idb) void public_mergeNodes(proland::NodeId ida, proland::NodeId idb) { return proland::Graph::mergeNodes(ida, idb); }; // Protected non-virtual checkers: inline static bool _lg_typecheck_public_mergeNodes(lua_State *L) { if( lua_gettop(L)!=3 ) return false; if( !Luna<void>::has_uniqueid(L,2,72107044) ) return false; if( !Luna<void>::has_uniqueid(L,3,72107044) ) return false; return true; } // Protected non-virtual function binds: // void proland::Graph::public_mergeNodes(proland::NodeId ida, proland::NodeId idb) static int _bind_public_mergeNodes(lua_State *L) { if (!_lg_typecheck_public_mergeNodes(L)) { luaL_error(L, "luna typecheck failed in void proland::Graph::public_mergeNodes(proland::NodeId ida, proland::NodeId idb) function, expected prototype:\nvoid proland::Graph::public_mergeNodes(proland::NodeId ida, proland::NodeId idb)\nClass arguments details:\narg 1 ID = 72107044\narg 2 ID = 72107044\n\n%s",luna_dumpStack(L).c_str()); } proland::NodeId* ida_ptr=(Luna< proland::NodeId >::check(L,2)); if( !ida_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg ida in proland::Graph::public_mergeNodes function"); } proland::NodeId ida=*ida_ptr; proland::NodeId* idb_ptr=(Luna< proland::NodeId >::check(L,3)); if( !idb_ptr ) { luaL_error(L, "Dereferencing NULL pointer for arg idb in proland::Graph::public_mergeNodes function"); } proland::NodeId idb=*idb_ptr; wrapper_proland_BasicGraph* self=Luna< ork::Object >::checkSubType< wrapper_proland_BasicGraph >(L,1); if(!self) { luaL_error(L, "Invalid object in function call void proland::Graph::public_mergeNodes(proland::NodeId, proland::NodeId). Got : '%s'\n%s",typeid(Luna< ork::Object >::check(L,1)).name(),luna_dumpStack(L).c_str()); } self->public_mergeNodes(ida, idb); return 0; } void register_protected_methods(lua_State* L) { static const luaL_Reg wrapper_lib[] = { {"mergeNodes",_bind_public_mergeNodes}, {NULL,NULL} }; pushTable(); luaL_register(L, NULL, wrapper_lib); lua_pop(L, 1); }; }; #endif
[ "roche.emmanuel@gmail.com" ]
roche.emmanuel@gmail.com
07988b228ce4f7eac38098ec87acdc57b9bfa5a4
9f81d77e028503dcbb6d7d4c0c302391b8fdd50c
/google/cloud/kms/v1/key_management_connection_idempotency_policy.h
20ba6c910d1d0b0324d10eced4f5f39d9fafd164
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
googleapis/google-cloud-cpp
b96a6ee50c972371daa8b8067ddd803de95f54ba
178d6581b499242c52f9150817d91e6c95b773a5
refs/heads/main
2023-08-31T09:30:11.624568
2023-08-31T03:29:11
2023-08-31T03:29:11
111,860,063
450
351
Apache-2.0
2023-09-14T21:52:02
2017-11-24T00:19:31
C++
UTF-8
C++
false
false
5,237
h
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/cloud/kms/v1/service.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_KMS_V1_KEY_MANAGEMENT_CONNECTION_IDEMPOTENCY_POLICY_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_KMS_V1_KEY_MANAGEMENT_CONNECTION_IDEMPOTENCY_POLICY_H #include "google/cloud/idempotency.h" #include "google/cloud/version.h" #include <google/cloud/kms/v1/service.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace kms_v1 { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN class KeyManagementServiceConnectionIdempotencyPolicy { public: virtual ~KeyManagementServiceConnectionIdempotencyPolicy(); /// Create a new copy of this object. virtual std::unique_ptr<KeyManagementServiceConnectionIdempotencyPolicy> clone() const; virtual google::cloud::Idempotency ListKeyRings( google::cloud::kms::v1::ListKeyRingsRequest request); virtual google::cloud::Idempotency ListCryptoKeys( google::cloud::kms::v1::ListCryptoKeysRequest request); virtual google::cloud::Idempotency ListCryptoKeyVersions( google::cloud::kms::v1::ListCryptoKeyVersionsRequest request); virtual google::cloud::Idempotency ListImportJobs( google::cloud::kms::v1::ListImportJobsRequest request); virtual google::cloud::Idempotency GetKeyRing( google::cloud::kms::v1::GetKeyRingRequest const& request); virtual google::cloud::Idempotency GetCryptoKey( google::cloud::kms::v1::GetCryptoKeyRequest const& request); virtual google::cloud::Idempotency GetCryptoKeyVersion( google::cloud::kms::v1::GetCryptoKeyVersionRequest const& request); virtual google::cloud::Idempotency GetPublicKey( google::cloud::kms::v1::GetPublicKeyRequest const& request); virtual google::cloud::Idempotency GetImportJob( google::cloud::kms::v1::GetImportJobRequest const& request); virtual google::cloud::Idempotency CreateKeyRing( google::cloud::kms::v1::CreateKeyRingRequest const& request); virtual google::cloud::Idempotency CreateCryptoKey( google::cloud::kms::v1::CreateCryptoKeyRequest const& request); virtual google::cloud::Idempotency CreateCryptoKeyVersion( google::cloud::kms::v1::CreateCryptoKeyVersionRequest const& request); virtual google::cloud::Idempotency ImportCryptoKeyVersion( google::cloud::kms::v1::ImportCryptoKeyVersionRequest const& request); virtual google::cloud::Idempotency CreateImportJob( google::cloud::kms::v1::CreateImportJobRequest const& request); virtual google::cloud::Idempotency UpdateCryptoKey( google::cloud::kms::v1::UpdateCryptoKeyRequest const& request); virtual google::cloud::Idempotency UpdateCryptoKeyVersion( google::cloud::kms::v1::UpdateCryptoKeyVersionRequest const& request); virtual google::cloud::Idempotency UpdateCryptoKeyPrimaryVersion( google::cloud::kms::v1::UpdateCryptoKeyPrimaryVersionRequest const& request); virtual google::cloud::Idempotency DestroyCryptoKeyVersion( google::cloud::kms::v1::DestroyCryptoKeyVersionRequest const& request); virtual google::cloud::Idempotency RestoreCryptoKeyVersion( google::cloud::kms::v1::RestoreCryptoKeyVersionRequest const& request); virtual google::cloud::Idempotency Encrypt( google::cloud::kms::v1::EncryptRequest const& request); virtual google::cloud::Idempotency Decrypt( google::cloud::kms::v1::DecryptRequest const& request); virtual google::cloud::Idempotency RawEncrypt( google::cloud::kms::v1::RawEncryptRequest const& request); virtual google::cloud::Idempotency RawDecrypt( google::cloud::kms::v1::RawDecryptRequest const& request); virtual google::cloud::Idempotency AsymmetricSign( google::cloud::kms::v1::AsymmetricSignRequest const& request); virtual google::cloud::Idempotency AsymmetricDecrypt( google::cloud::kms::v1::AsymmetricDecryptRequest const& request); virtual google::cloud::Idempotency MacSign( google::cloud::kms::v1::MacSignRequest const& request); virtual google::cloud::Idempotency MacVerify( google::cloud::kms::v1::MacVerifyRequest const& request); virtual google::cloud::Idempotency GenerateRandomBytes( google::cloud::kms::v1::GenerateRandomBytesRequest const& request); }; std::unique_ptr<KeyManagementServiceConnectionIdempotencyPolicy> MakeDefaultKeyManagementServiceConnectionIdempotencyPolicy(); GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace kms_v1 } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_KMS_V1_KEY_MANAGEMENT_CONNECTION_IDEMPOTENCY_POLICY_H
[ "noreply@github.com" ]
noreply@github.com
dc6cb400e82e2d196df6711ad3a89c2e44dad9df
f28bb5e120511514ca22ada38dfbb43fe8c83b6f
/Kernel/IKernel.h
ac61bdbc3eda39de687df19e47e89f57fe253c21
[]
no_license
ninglei0114/cloud-plate-server
b7be5fbb82d33b6871f7124ae1fa312438ef118b
671cdb9787af547a659ccfa7f516f5c382e837eb
refs/heads/master
2022-02-02T18:41:00.548898
2019-07-20T14:01:32
2019-07-20T14:01:32
197,936,445
0
0
null
null
null
null
UTF-8
C++
false
false
276
h
#ifndef _IKERNEL_H #define _IKERNEL_H #include "INet.h" class IKernel { public: IKernel() {} virtual ~IKernel() {} public: virtual bool Open() =0; virtual void Close() = 0; virtual bool DealData(MySocket *pSock,char *szbuf) = 0; public: CNet *m_pNet; }; #endif
[ "ninglei0114@163.com" ]
ninglei0114@163.com
e840b6a8cedfbec375074f9cf9296a64b54c7529
f500ab7be9a435e89d03df4c46e400a7d3dbd03e
/Opponent.cpp
f01ae67568774143a611447dcf722b71d76de10b
[]
no_license
RyanSwann1/Test
514066413ab2c564ed918630bb3ae3d2a4d1df5d
5ba7266ed9ddb425584820c2f0d521459d79c885
refs/heads/master
2016-09-13T12:36:06.746450
2016-04-13T15:38:09
2016-04-13T15:38:09
56,164,345
0
0
null
null
null
null
UTF-8
C++
false
false
777
cpp
#include "Opponent.h" #include "TextureManager.h" #include "Game.h" const std::string m_textureID = "Opponent"; Opponent::Opponent() { sizeHeight = 80; sizeWidth = 25; //Starting position m_position.setX(450); m_position.setY(200); m_velocity.setX(3); m_velocity.setY(3); } Opponent::~Opponent() { } void Opponent::update() { if (m_position.m_x >= 0 && m_position.m_x <= Game::instance()->getPlayingFieldWidth() && m_position.m_y >= 0 && m_position.m_y <= Game::instance()->getPlayingFieldHeight()) { handleMovement(); } } void Opponent::draw() { //02084287520 } void Opponent::handleEvents() { } void Opponent::handleMovement() { } std::string Opponent::getTextureID() const { return m_textureID; }
[ "RyanSwann1992@gmail.com" ]
RyanSwann1992@gmail.com
3fed828bf3dd16698bf83cacb85ac91144928af8
9b741760afd8407ec5d89866fdd6ccab811439a7
/GasCounter_2/GasCounter_2/GasCounter_2.ino
43cae9bdd7cb7d38904de62beb98082621920444
[]
no_license
JohnOH/GasMetering
a883bab7e19b75a944dd83b4faab1804c3dfd0e0
a8404fecab51abe29bce0e6ac9c91feacbdacc29
refs/heads/master
2021-01-01T15:30:41.657987
2013-10-08T21:00:16
2013-10-08T21:00:16
13,334,129
2
0
null
null
null
null
UTF-8
C++
false
false
4,375
ino
// Pinched from jcw as basis for my gas meter counter // ATtiny85 measurement of peak-to-peak current at 50 Hz, w/ moving average. // 2011-10-06 <jcw@equi4.com> http://opensource.org/licenses/mit-license.php // // Note that this "sketch" is not for the ATmega328 but for the ATtiny84/85, // see http://jeelabs.org/2011/10/10/ac-current-detection-works/ #include <JeeLib.h> #include <avr/sleep.h> #include <avr/interrupt.h> #define ORDER 31 #define AIO1 7 // d7 #define DIO1 8 // d8 #define AIO2 9 // d9 #define DIO2 10 // d10 unsigned long inttime; // stored time of last interrupt unsigned long intinterval; // interval between interrupts byte oldintcount; unsigned int values[ORDER]; unsigned int vmin, vmax; // struct payload{ byte count; // packet count unsigned int intcnt; // interrupt count unsigned int time; // time between interrupts (ms) signed int temp; //getAvrTemp value byte vcc; //getVcc // 1.0V = 0, 1.8V = 40, 3.3V = 115, 5.0V = 200, 6.0V = 250 } payload; // byte lastTime; // ISR (PCINT0_vect) { unsigned long now; now = millis(); if (now < inttime) return; payload.time = now - (inttime - 50); inttime = now + 50; payload.intcnt++; } static void setPrescaler (uint8_t mode) { cli(); CLKPR = bit(CLKPCE); CLKPR = mode; sei(); } unsigned int getAvrTemp(void) { /* Tiny84 T = k * [(ADCH << 8) | ADCL] + TOS */ unsigned char high, low; ADMUX = (INTERNAL << 6) | B00100010; //Selecting the ADC8 channel by writing the MUX5:0 bits in ADMUX register to “100010” enables the temperature sensor. CLKPR = bit(CLKPCE); CLKPR = 4; // div 16 delayMicroseconds(62); CLKPR = bit(CLKPCE); CLKPR = 0; ADCSRA |= bit(ADSC); // Start a conversion for Temperature while (ADCSRA & bit(ADSC)); low = ADCL; // Must be read first as it locks high = ADCH; // read second and releases the lock return (high << 8) | low; } unsigned int getVcc(void) { // Select bandgap as ADC input ADMUX = (DEFAULT << 6) | 0x21; // Delay for ~1msec at 1MHz // Tiny84 = 0x21 CLKPR = bit(CLKPCE); CLKPR = 4; // div 16 delayMicroseconds(62); CLKPR = bit(CLKPCE); CLKPR = 0; // ADCSRA |= bit(ADSC); while (ADCSRA & bit(ADSC)); unsigned int adc = ADC; // Select A0 as ADC input ADMUX = (DEFAULT << 6) | 0; return (55UL * 1023UL) / (adc + 1) - 50 ; //return 1100UL * 1023UL / adc; // convert ADC readings to fit in one byte, i.e. 20 mV steps: // 1.0V = 0, 1.8V = 40, 3.3V = 115, 5.0V = 200, 6.0V = 250 // return (55U * 1023U) / (ADC + 1) - 50; } void setup () { setPrescaler(0); // div 1, i.e. speed up to 8 MHz // ADCSRA &= ~ bit(ADEN); // disable the ADC // bitSet(PRR, PRADC); // power down the ADC // Switch to ADC8 and analog reference INTERNAL Tiny84Internal 1.1V voltage reference ADCSRA |= bit(ADEN); // Tiny84 Enable ADC oldintcount = 0; payload.intcnt = 0; payload.count = 0; pinMode(DIO1, INPUT); //set the pin to input digitalWrite(DIO1, HIGH); //use the internal pullup resistor PCMSK0 |= (1<<PCINT2); // tell pin change mask to listen to (DIO1) GIMSK |= (1<<PCIE0); // enable PCINT interrupt in the general interrupt mask sei(); rf12_initialize(17, RF12_868MHZ, 212); rf12_sleep(RF12_SLEEP); // ADCSRA &= ~ bit(ADEN); // disable the ADC // PRR = bit(PRTIM1) | bit(PRUSI) | bit(PRADC); // only keep timer 0 going } void loop () { byte nextTime; set_sleep_mode(SLEEP_MODE_IDLE); sleep_mode(); // 6 = 8mins 48seconds // 7 = 32 seconds // 9 = 1min 3sec // 13 = 9mins 34sec // 14 = 34mins 38sec nextTime = millis() >> 14; // 13; // Watchdog every 18 hours if (oldintcount == payload.intcnt) // Has there been a DIO1 interrupt? { // No if (nextTime == lastTime) // Watchdog interrupted! return; } setPrescaler(0); // div 1, i.e. speed up to 8 MHz oldintcount = payload.intcnt; lastTime = nextTime; payload.count = payload.count + 1; // bitClear(PRR, PRUSI); // enable USI h/w // Is this needed? rf12_sleep(RF12_WAKEUP); payload.temp = getAvrTemp(); while (!rf12_canSend()) rf12_recvDone(); rf12_sendStart(0, &payload, sizeof payload); rf12_sendWait(1); rf12_sleep(RF12_SLEEP); // payload.vcc = getVcc(); // bitSet(PRR, PRUSI); // disable USI h/w // Is this needed? setPrescaler(15); // div 256, i.e. 1 or 8 MHz div 256 (8) = 32kHz }
[ "john@o-hare.net" ]
john@o-hare.net
9c9b9ce5e4c01ba55e2be1992933909db682bf88
a457a3f589e3cbb9291d7dcf19c3472baf61b2ba
/Task-03/code.cpp
696480223af3ea18402fbb4b1337da1daf354939
[]
no_license
vaishnavi-bholane/Practical-03
7200bc8edb907a205379b616d0cbb69d917c3dac
f05bc12430a4cfbbf763750f14cfa247dc6cc2ba
refs/heads/main
2023-08-25T01:57:45.998185
2021-10-05T12:48:44
2021-10-05T12:48:44
413,795,398
0
0
null
null
null
null
UTF-8
C++
false
false
105
cpp
#include<iostream> using namespace std; int main() { char a; cin>>a; cout<<a<<endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
9e429178782c1234fcde1a644dc671b3aa8aefac
47c19417c235e6dd6c26af02bec7b0ee755c1eea
/Rosero_Romel_Deber_WDT.ino
b0def7c70458b42a6970ee2c1c0d302c65397e86
[]
no_license
Romel-Rosero/Micros
984cdc35dd6d3dd45f49290096a1eef22f93b7cc
4b98c88e10dabec15e44fbb6359ce747187624c8
refs/heads/master
2020-09-01T22:34:43.088102
2020-02-05T03:58:43
2020-02-05T03:58:43
219,610,955
1
0
null
null
null
null
UTF-8
C++
false
false
1,862
ino
/* * Universidad Técnica del Norte * Facultad de Ingeniería en Ciencias Aplicadas * Carrera de Ingeniería en Electrónica y Redes de Comunicación * * Nombre: Romel Rosero Fecha: 04/02/2020 * Asignatura: Sistemas Microprocesados * * Realizar un programa que mediante comunicación serial ingrese el tiempo de reset del arduino de la siguiente forma: * A-> 1 s B-> 2s C-> 4s D-> 8s * Hay que tener en cuenta que el sistema puede ser re configurado la veces necesarias(interrupciones) * */ #include <avr/wdt.h> //libreria wdt #include <TimerOne.h> //libreria timer1 int i=0; char tiempo; void setup() { attachInterrupt (0,activacion,LOW); Serial.begin(9600); Serial.println("RESET"); } void loop() { } void activacion(){ Timer1.initialize(1000000); Timer1.attachInterrupt(conteo); Serial.println("Seleccione el tiempo de RESET:"); Serial.println("Recuerde que el tiempo de reset empieza a partir del segundo 20"); Serial.println("A para 1S"); Serial.println("B para 2S"); Serial.println("C para 4S"); Serial.println("D para 8S"); } void conteo(){ tipos(); } void tipos (){ switch(tiempo){ case 'A' : i++; Serial.println(i); if(i==20){ wdt_enable(WDTO_1S); } break; case 'B': i++; Serial.println(i); if(i==20){ wdt_enable(WDTO_2S); } break; case 'C': i++; Serial.println(i); if(i==20){ wdt_enable(WDTO_4S); } break; case 'D': i++; Serial.println(i); if(i==20){ wdt_enable(WDTO_8S); } break; } } void serialEvent(){ if (Serial.available()>0){ tiempo=Serial.read(); } }
[ "noreply@github.com" ]
noreply@github.com
b1d0077ff7af8bb74e2a94c62e953fe5cbe945fb
6687a5a53cb371d6f1274081fda28ce5fe7a3232
/Leetcode Weekly Contest/Weekly Contest 153/A.cpp
e2eaa87c40b9e94ef737f3b651542d0de44a48f7
[]
no_license
kugwzk/ACcode
40488bb7c20e5ad9dfeb4eb3a07c29b0acfee7d9
e3e0fe7cb3a9e1a871e769b5ccd7b8f9f78d0ea3
refs/heads/master
2021-01-17T12:59:53.003559
2020-08-17T07:48:28
2020-08-17T07:48:28
65,424,503
1
0
null
null
null
null
UTF-8
C++
false
false
433
cpp
class Solution { public: int distanceBetweenBusStops(vector<int>& distance, int start, int destination) { int sum = 0, need = 0; if(start>destination) swap(start, destination); for(int i=0;i<distance.size();i++) { sum+=distance[i]; if(i>=start&&i<destination) need+=distance[i]; } cout<<need<<" "<<sum<<endl; return min(need, sum-need); } };
[ "kugwzk@gmail.com" ]
kugwzk@gmail.com
64e6defd05e7cbb418e81596c669df0751a3d2c3
09cf13de96d0323235d62111eced8ab51904c5f6
/leetcode88/leetcode88.cpp
73b081b79ec2fa7e3ab31411c0c786796c56e7e8
[]
no_license
lovesunmoonlight/leetcode-solutions
4c8e6ce83c9282d2298ed14582c59572af6e224a
9e490fd6b5215ed6bb02e481020ee2056db3705c
refs/heads/master
2021-01-21T18:28:10.461560
2018-07-16T04:31:19
2018-07-16T04:31:19
92,048,152
1
0
null
null
null
null
GB18030
C++
false
false
959
cpp
// leetcode88.cpp : 定义控制台应用程序的入口点。 // Accepted // 合并两个有序序列 #include "stdafx.h" #include <iostream> #include <vector> #include <algorithm> #include <cstdlib> using namespace std; void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { vector<int> nums3; while (m&&n) { if (nums1[m-1] > nums2[n-1]) { nums3.push_back(nums1[m-1]); --m; } else if (nums1[m-1] < nums2[n-1]) { nums3.push_back(nums2[n-1]); --n; } else { nums3.push_back(nums1[m-1]); --m; nums3.push_back(nums2[n-1]); --n; } } while (m) { nums3.push_back(nums1[m-1]); --m; } while (n) { nums3.push_back(nums2[n-1]); --n; } nums1 = vector<int>(nums3.crbegin(), nums3.crend()); } int main() { vector<int> nums1 = { 1,2,3 }; vector<int> nums2 = { 4,5,6,6,7,8,8,9 }; merge(nums1,3,nums2,8); for (auto i : nums1) cout << i << " "; cout << endl; system("pause"); return 0; }
[ "lovesunmoonlight@gmail.com" ]
lovesunmoonlight@gmail.com
d1a5156394a9c4a83071197674ffdd32034f7bdb
fdb963647dc9317947943874a51f58c1240f994c
/project/source/Field/Place/FieldPlaceModel.h
1da42ffcdbe1aff4172ffde85e078fa33c83acdb
[ "MIT" ]
permissive
SomeTake/HF21MisotenH206
0f2e5e92a71ef4c89b43c4ebd8d3a0bf632f03b4
821d8d4ec8b40c236ac6b0e6e7ba5f89c06b950d
refs/heads/master
2020-07-25T07:44:09.728095
2020-01-17T10:15:03
2020-01-17T10:15:03
208,212,885
0
2
MIT
2020-01-17T08:00:14
2019-09-13T07:02:16
C++
SHIFT_JIS
C++
false
false
3,156
h
//===================================== // //FieldPlaceModel.h //機能:フィールド上のプレイスモデル //Author:GP12B332 21 立花雄太 // //===================================== #ifndef _FIELDPLACEMODEL_H_ #define _FIELDPLACEMODEL_H_ #include "../../../main.h" #include "../FieldConfig.h" #include "PlaceConfig.h" #include <vector> /************************************** マクロ定義 ***************************************/ /************************************** 前方宣言 ***************************************/ class PlaceActor; namespace Field::Model { /************************************** 前方宣言 ***************************************/ class RouteModel; /************************************** クラス定義 ***************************************/ class PlaceModel { public: //コンストラクタ、デストラクタ PlaceModel(PlaceType type, int x, int z); ~PlaceModel(); //座標取得 FieldPosition GetPosition() const; //ID取得 unsigned ID() const; //隣接プレイスの追加 void AddAdjacency(PlaceModel *adjacency, Adjacency type); //ルートを始められるか bool CanStartRoute() const; //道に変えられるか bool ChangeableRoad(Adjacency prev) const; //開拓可能なタイプか bool IsDevelopableType() const; //placeと隣接しているか Adjacency IsAdjacent(const PlaceModel* place) const; //連結できるタイプか bool IsConnectableType() const; //同じルートに属しているか bool IsSameRoute(PlaceModel* place) const; //空き地(Noneかつ周囲4マスに街がない bool IsVacant() const; //連結対象の取得 std::vector<PlaceModel*> GetConnectTargets() const; //TODO:連結対象の複数化 //端点となるPlaceの取得 std::vector<PlaceModel*> GetEdgeOpponents() const; //ルートモデルへの所属、離脱 void BelongRoute(std::shared_ptr<RouteModel> route); void BelongRoute(std::vector<std::shared_ptr<RouteModel>>& routes); void ExitRoute(std::shared_ptr<RouteModel> route); //タイプ判定、変更処理 bool IsType(PlaceType type) const; void SetType(PlaceType type); const PlaceType GetType() const; const PlaceType GetPrevType() const; //所属ルート取得 RouteModelPtr GetConnectingRoute() const; RouteContainer GetConnectingRoutes() const; //方向決定処理、取得処理 void AddDirection(Adjacency direction); void AddDirection(PlaceModel* place); std::vector<Adjacency> GetConnectingAdjacency() const; //橋を開発 void DevelopBridge(); #ifdef DEBUG_PLACEMODEL //デバッグ用描画処理 void DrawDebug(); #endif private: //ID static unsigned incrementID; unsigned uniqueID; //タイプ PlaceType type, prevType; //座標 const FieldPosition Position; //所属しているルートの参照コンテナ std::vector<std::shared_ptr<RouteModel>> belongRouteList; //隣接プレイス std::vector<PlaceModel*> adjacencies; //連結方向 std::vector<Adjacency> connectDirection; //橋の場合、開発済みか bool isDeveloppedBridge; }; } #endif
[ "yuta.tachibana0310@gmail.com" ]
yuta.tachibana0310@gmail.com
5890f0a2e3215a5b68e5f904d24b625701d814d1
5cff197db4afc23f3805fba1109f333c80f2ac01
/include/Zen/Plugin/extension_point.hpp
4630146d362f9ff39ffe8c4bc48de9e2203ffd49
[ "MIT" ]
permissive
hatboyzero/zen-plugin
de2fd94972844e1a8e5bbccaf7f5929dcc27b2b4
8b753c84f1e44c2a756ca1f8c5b00118941a4f88
refs/heads/master
2021-01-19T01:22:18.763904
2016-12-18T17:28:55
2016-12-18T17:28:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,980
hpp
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ // Zen Plugin Framework // // Copyright (C) 2001 - 2016 Raymond A. Richards //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #ifndef ZEN_PLUGIN_EXTENSION_POINT_HPP_INCLUDED #define ZEN_PLUGIN_EXTENSION_POINT_HPP_INCLUDED #include <Zen/Plugin/I_ClassFactory.hpp> #include <Zen/Plugin/I_ExtensionQuery.hpp> #include <Zen/Plugin/I_ExtensionPoint.hpp> #include <Zen/Plugin/I_ExtensionRegistry.hpp> #include <memory> #include <string> // for debugging #include <iostream> //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ namespace Zen { namespace Plugin { //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ template<typename tExtension_type, typename tFactory_type, typename tIndex_type = std::string> class extension_point : public I_ExtensionPoint { public: typedef tIndex_type index_type; typedef tExtension_type Extension_type; typedef tFactory_type Factory_type; typedef std::shared_ptr<Extension_type> pExtension_type; public: extension_point(const char* _namespace, const char* _extensionPointName) : m_namespace(_namespace) , m_extensionPointName(_extensionPointName) { } virtual ~extension_point() = default; const std::string& getNamespace() { return m_namespace; } const std::string& getExtensionPointName() { return m_extensionPointName; } template<class... Types> pExtension_type create(index_type _type, Types... args); protected: Factory_type* getFactory(index_type _type); private: const std::string m_namespace; const std::string m_extensionPointName; }; //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ template<typename tExtension_type, typename tFactory_type, typename tIndex_type> tFactory_type* extension_point<tExtension_type, tFactory_type, tIndex_type>::getFactory(tIndex_type _type) { // Create an extension query const I_ExtensionRegistry::pExtensionQuery_type pQuery = I_ExtensionRegistry::getSingleton().createQuery(); pQuery->setNamespace(getNamespace()); pQuery->setExtensionPoint(getExtensionPointName()); pQuery->setType(_type); // Get the extensions I_ExtensionRegistry::pExtension_type pExtension = I_ExtensionRegistry::getSingleton().findExtension(pQuery, [](I_ExtensionRegistry::pExtension_type _pExtension) -> bool { // Indicate that the first one is the correct one // (we'll deal with any actual filtering a later date) return true; } ); // if (pExtension) // { // I_ClassFactory& // classFactory = I_ExtensionRegistry::getSingleton().getClassFactory(pExtension); // return dynamic_cast<Factory_type*>(&classFactory); // } // else { return NULL; } } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ template<typename tExtension_type, typename tFactory_type, typename tIndex_type> template<class... Types> typename extension_point<tExtension_type, tFactory_type, tIndex_type>::pExtension_type extension_point<tExtension_type, tFactory_type, tIndex_type>::create(index_type _type, Types... args) { std::cout << "extension_point::create" << std::endl; auto* pFactory = getFactory(_type); std::cout << "Got factory" << std::endl; return pFactory->create(&args...); } //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ } // namespace Plugin } // namespace Zen //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #endif // !ZEN_PLUGIN_EXTENSION_POINT_HPP_INCLUDED
[ "linterra@gmail.com" ]
linterra@gmail.com
2196b00e828f868bdf116d39e4112d5f9cd84b25
ac014332f98bf8ed690d0d01e54a585869627396
/src/rpcserver.cpp
bed68299074ae1a6db599b5c38095d86c8cb0832
[ "MIT" ]
permissive
kalilinuxoo7/AXEL
25850f981c23ca8adbaaa76a3dc9d41220176ac9
1ef483254dcbab00f224bcd201021befb728a000
refs/heads/master
2022-03-26T12:44:01.097884
2019-12-24T18:23:57
2019-12-24T18:23:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
43,562
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018-2019 The AXEL Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "base58.h" #include "init.h" #include "main.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> #include <univalue.h> using namespace boost; using namespace boost::asio; using namespace std; static std::string strRPCUserColonPass; static bool fRPCRunning = false; static bool fRPCInWarmup = true; static std::string rpcWarmupStatus("RPC server started"); static CCriticalSection cs_rpcWarmup; //! These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static boost::asio::io_service::work* rpc_dummy_work = NULL; static std::vector<CSubNet> rpc_allow_subnets; //!< List of subnets to allow RPC connections from static std::vector<boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors; //std::vector<std::string> desktopRPCCommands{"dumpprivkey", "dumpwallet", "move", "multisend", "sendfrom", "sendmany", "sendtoaddress", "sendtoaddressix"}; void RPCTypeCheck(const UniValue& params, const list<UniValue::VType>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(UniValue::VType t, typesExpected) { if (params.size() <= i) break; const UniValue& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.isNull())))) { string err = strprintf("Expected type %s, got %s", uvTypeName(t), uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheckObj(const UniValue& o, const map<string, UniValue::VType>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, UniValue::VType)& t, typesExpected) { const UniValue& v = find_value(o, t.first); if (!fAllowNull && v.isNull()) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.isNull())))) { string err = strprintf("Expected type %s for %s, got %s", uvTypeName(t.second), t.first, uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } CAmount AmountFromValue(const UniValue& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 21000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); CAmount nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); } uint256 ParseHashV(const UniValue& v, string strName) { string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const UniValue& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const UniValue& v, string strName) { string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const UniValue& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } int ParseInt(const UniValue& o, string strKey) { const UniValue& v = find_value(o, strKey); if (v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, " + strKey + "is not an int"); return v.get_int(); } bool ParseBool(const UniValue& o, string strKey) { const UniValue& v = find_value(o, strKey); if (v.isBool()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, " + strKey + "is not a bool"); return v.get_bool(); } /** * Note: This interface may still be subject to change. */ string CRPCTable::help(string strCommand) const { string strRet; string category; set<rpcfn_type> setDone; vector<pair<string, const CRPCCommand*> > vCommands; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); sort(vCommands.begin(), vCommands.end()); BOOST_FOREACH (const PAIRTYPE(string, const CRPCCommand*) & command, vCommands) { const CRPCCommand* pcmd = command.second; string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) continue; /*if (std::find(desktopRPCCommands.begin(), desktopRPCCommands.end(), strMethod) != desktopRPCCommands.end()) { LogPrintf("ThreadRPCServer: help for prohibited command %s\n", strMethod); continue; } else { LogPrintf("ThreadRPCServer: help for NOT found prohibited command %s\n", strMethod); }*/ #endif try { UniValue params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") { if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; string firstLetter = category.substr(0, 1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } } strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0, strRet.size() - 1); return strRet; } UniValue help(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n"); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } UniValue stop(const UniValue& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "\nStop axel server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "axel server stopping"; } /** * Call Table */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode threadSafe reqWallet // --------------------- ------------------------ ----------------------- ---------- ---------- --------- /* Overall control/query calls */ {"control", "getinfo", &getinfo, true, false, false}, /* uses wallet if enabled */ {"control", "help", &help, true, true, false}, {"control", "stop", &stop, true, true, false}, /* P2P networking */ {"network", "getnetworkinfo", &getnetworkinfo, true, false, false}, {"network", "addnode", &addnode, true, true, false}, {"network", "getaddednodeinfo", &getaddednodeinfo, true, true, false}, {"network", "getconnectioncount", &getconnectioncount, true, false, false}, {"network", "getnettotals", &getnettotals, true, true, false}, {"network", "getpeerinfo", &getpeerinfo, true, false, false}, {"network", "ping", &ping, true, false, false}, /* Block chain and UTXO */ {"blockchain", "getblockchaininfo", &getblockchaininfo, true, false, false}, {"blockchain", "getbestblockhash", &getbestblockhash, true, false, false}, {"blockchain", "getblockcount", &getblockcount, true, false, false}, {"blockchain", "getblock", &getblock, true, false, false}, {"blockchain", "getblockhash", &getblockhash, true, false, false}, {"blockchain", "getblockheader", &getblockheader, false, false, false}, {"blockchain", "getchaintips", &getchaintips, true, false, false}, {"blockchain", "getdifficulty", &getdifficulty, true, false, false}, {"blockchain", "getmempoolinfo", &getmempoolinfo, true, true, false}, {"blockchain", "getrawmempool", &getrawmempool, true, false, false}, {"blockchain", "gettxout", &gettxout, true, false, false}, {"blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, false, false}, {"blockchain", "verifychain", &verifychain, true, false, false}, {"blockchain", "invalidateblock", &invalidateblock, true, true, false}, {"blockchain", "reconsiderblock", &reconsiderblock, true, true, false}, /* Mining */ {"mining", "getblocktemplate", &getblocktemplate, true, false, false}, {"mining", "getmininginfo", &getmininginfo, true, false, false}, {"mining", "getnetworkhashps", &getnetworkhashps, true, false, false}, {"mining", "prioritisetransaction", &prioritisetransaction, true, false, false}, {"mining", "submitblock", &submitblock, true, true, false}, {"mining", "reservebalance", &reservebalance, true, true, false}, #ifdef ENABLE_WALLET /* Coin generation */ {"generating", "getgenerate", &getgenerate, true, false, false}, {"generating", "gethashespersec", &gethashespersec, true, false, false}, {"generating", "setgenerate", &setgenerate, true, true, false}, #endif /* Raw transactions */ {"rawtransactions", "createrawtransaction", &createrawtransaction, true, false, false}, {"rawtransactions", "decoderawtransaction", &decoderawtransaction, true, false, false}, {"rawtransactions", "decodescript", &decodescript, true, false, false}, {"rawtransactions", "getrawtransaction", &getrawtransaction, true, false, false}, {"rawtransactions", "sendrawtransaction", &sendrawtransaction, false, false, false}, {"rawtransactions", "signrawtransaction", &signrawtransaction, false, false, false}, /* uses wallet if enabled */ /* Utility functions */ {"util", "createmultisig", &createmultisig, true, true, false}, {"util", "validateaddress", &validateaddress, true, false, false}, /* uses wallet if enabled */ {"util", "verifymessage", &verifymessage, true, false, false}, {"util", "estimatefee", &estimatefee, true, true, false}, {"util", "estimatepriority", &estimatepriority, true, true, false}, /* Not shown in help */ {"hidden", "invalidateblock", &invalidateblock, true, true, false}, {"hidden", "reconsiderblock", &reconsiderblock, true, true, false}, {"hidden", "setmocktime", &setmocktime, true, false, false}, /* axel features */ {"axel", "masternode", &masternode, true, true, false}, {"axel", "listmasternodes", &listmasternodes, true, true, false}, {"axel", "getmasternodecount", &getmasternodecount, true, true, false}, {"axel", "masternodeconnect", &masternodeconnect, true, true, false}, {"axel", "masternodecurrent", &masternodecurrent, true, true, false}, {"axel", "masternodedebug", &masternodedebug, true, true, false}, {"axel", "startmasternode", &startmasternode, true, true, false}, {"axel", "createmasternodekey", &createmasternodekey, true, true, false}, {"axel", "getmasternodeoutputs", &getmasternodeoutputs, true, true, false}, {"axel", "listmasternodeconf", &listmasternodeconf, true, true, false}, {"axel", "getmasternodestatus", &getmasternodestatus, true, true, false}, {"axel", "getmasternodewinners", &getmasternodewinners, true, true, false}, {"axel", "getmasternodescores", &getmasternodescores, true, true, false}, {"axel", "mnsync", &mnsync, true, true, false}, {"axel", "spork", &spork, true, true, false}, {"axel", "getpoolinfo", &getpoolinfo, true, true, false}, #ifdef ENABLE_WALLET {"axel", "obfuscation", &obfuscation, false, false, true}, /* not threadSafe because of SendMoney */ /* Wallet */ {"wallet", "addmultisigaddress", &addmultisigaddress, true, false, true}, {"wallet", "autocombinerewards", &autocombinerewards, false, false, true}, {"wallet", "backupwallet", &backupwallet, true, false, true}, #ifndef ENABLE_WEBWALLET {"wallet", "dumpprivkey", &dumpprivkey, true, false, true}, {"wallet", "dumpwallet", &dumpwallet, true, false, true}, #endif // ENABLE_WEBWALLET {"wallet", "bip38encrypt", &bip38encrypt, true, false, true}, {"wallet", "bip38decrypt", &bip38decrypt, true, false, true}, {"wallet", "encryptwallet", &encryptwallet, true, false, true}, {"wallet", "getaccountaddress", &getaccountaddress, true, false, true}, {"wallet", "getaccountkeypair", &getaccountkeypair, true, false, true}, {"wallet", "getaccount", &getaccount, true, false, true}, {"wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, false, true}, {"wallet", "getbalance", &getbalance, false, false, true}, {"wallet", "getnewaddress", &getnewaddress, true, false, true}, {"wallet", "getrawchangeaddress", &getrawchangeaddress, true, false, true}, {"wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, false, true}, {"wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, false, true}, {"wallet", "getstakingstatus", &getstakingstatus, false, false, true}, {"wallet", "getstakesplitthreshold", &getstakesplitthreshold, false, false, true}, {"wallet", "gettransaction", &gettransaction, false, false, true}, {"wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, false, true}, {"wallet", "getwalletinfo", &getwalletinfo, false, false, true}, {"wallet", "importprivkey", &importprivkey, true, false, true}, {"wallet", "importwallet", &importwallet, true, false, true}, {"wallet", "importaddress", &importaddress, true, false, true}, {"wallet", "keypoolrefill", &keypoolrefill, true, false, true}, {"wallet", "listaccounts", &listaccounts, false, false, true}, {"wallet", "listaddressgroupings", &listaddressgroupings, false, false, true}, {"wallet", "listlockunspent", &listlockunspent, false, false, true}, {"wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, false, true}, {"wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, false, true}, {"wallet", "listsinceblock", &listsinceblock, false, false, true}, {"wallet", "listtransactions", &listtransactions, false, false, true}, {"wallet", "listunspent", &listunspent, false, false, true}, {"wallet", "lockunspent", &lockunspent, true, false, true}, #ifndef ENABLE_WEBWALLET {"wallet", "move", &movecmd, false, false, true}, {"wallet", "multisend", &multisend, false, false, true}, {"wallet", "sendfrom", &sendfrom, false, false, true}, {"wallet", "sendmany", &sendmany, false, false, true}, {"wallet", "sendtoaddress", &sendtoaddress, false, false, true}, {"wallet", "sendtoaddressix", &sendtoaddressix, false, false, true}, #endif // ENABLE_WEBWALLET {"wallet", "setaccount", &setaccount, true, false, true}, {"wallet", "setstakesplitthreshold", &setstakesplitthreshold, false, false, true}, {"wallet", "settxfee", &settxfee, true, false, true}, {"wallet", "signmessage", &signmessage, true, false, true}, {"wallet", "walletlock", &walletlock, true, false, true}, {"wallet", "walletpassphrasechange", &walletpassphrasechange, true, false, true}, {"wallet", "walletpassphrase", &walletpassphrase, true, false, true}, #endif // ENABLE_WALLET }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand* pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand* CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0, 6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } void ErrorReply(std::ostream& stream, const UniValue& objError, const UniValue& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(NullUniValue, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address) { CNetAddr netaddr; // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) address = address.to_v6().to_v4(); if (address.is_v4()) { boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes(); netaddr.SetRaw(NET_IPV4, &bytes[0]); } else { boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes(); netaddr.SetRaw(NET_IPV6, &bytes[0]); } return netaddr; } bool ClientAllowed(const boost::asio::ip::address& address) { CNetAddr netaddr = BoostAsioToCNetAddr(address); BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) if (subnet.Match(netaddr)) return true; return false; } template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context& context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream<SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection* conn); //! Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, boost::shared_ptr<AcceptedConnection> conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection boost::shared_ptr<AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL)); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, _1)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, boost::shared_ptr<AcceptedConnection> conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast<AcceptedConnectionImpl<ip::tcp>*>(conn.get()); if (error) { // TODO: Actually handle errors LogPrintf("%s: Error: %s\n", __func__, error.message()); } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPError(HTTP_FORBIDDEN, false) << std::flush; conn->close(); } else { ServiceConnection(conn.get()); conn->close(); } } static ip::tcp::endpoint ParseEndpoint(const std::string& strEndpoint, int defaultPort) { std::string addr; int port = defaultPort; SplitHostPort(strEndpoint, port, addr); return ip::tcp::endpoint(asio::ip::address::from_string(addr), port); } void StartRPCThreads() { rpc_allow_subnets.clear(); rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost if (mapMultiArgs.count("-rpcallowip")) { const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH (string strAllow, vAllow) { CSubNet subnet(strAllow); if (!subnet.IsValid()) { uiInterface.ThreadSafeMessageBox( strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_allow_subnets.push_back(subnet); } } std::string strAllowed; BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) strAllowed += subnet.ToString() + " "; LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword()) { unsigned char rand_pwd[32]; GetRandBytes(rand_pwd, 32); uiInterface.ThreadSafeMessageBox(strprintf( _("To use axeld, or the -server option to axel-qt, you must set an rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=axelrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"axel Alert\" admin@foo.com\n"), GetConfigFile().string(), EncodeBase58(&rand_pwd[0], &rand_pwd[0] + 32)), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::SECURE); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl", false); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } std::vector<ip::tcp::endpoint> vEndpoints; bool bBindAny = false; int defaultPort = GetArg("-rpcport", BaseParams().RPCPort()); if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs { vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::loopback(), defaultPort)); vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::loopback(), defaultPort)); if (mapArgs.count("-rpcbind")) { LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); } } else if (mapArgs.count("-rpcbind")) // Specific bind address { BOOST_FOREACH (const std::string& addr, mapMultiArgs["-rpcbind"]) { try { vEndpoints.push_back(ParseEndpoint(addr, defaultPort)); } catch (const boost::system::system_error&) { uiInterface.ThreadSafeMessageBox( strprintf(_("Could not parse -rpcbind value %s as network address"), addr), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } } } else { // No specific bind address specified, bind to any vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::any(), defaultPort)); vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::any(), defaultPort)); // Prefer making the socket dual IPv6/IPv4 instead of binding // to both addresses seperately. bBindAny = true; } bool fListening = false; std::string strerr; std::string straddress; BOOST_FOREACH (const ip::tcp::endpoint& endpoint, vEndpoints) { try { asio::ip::address bindAddress = endpoint.address(); straddress = bindAddress.to_string(); LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", straddress, endpoint.port(), bBindAny); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address acceptor->set_option(boost::asio::ip::v6_only( !bBindAny || bindAddress != asio::ip::address_v6::any()), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); rpc_acceptors.push_back(acceptor); fListening = true; rpc_acceptors.push_back(acceptor); // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately if (bBindAny && bindAddress == asio::ip::address_v6::any() && !v6_only_error) break; } catch (boost::system::system_error& e) { LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", straddress, endpoint.port(), e.what()); strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), straddress, endpoint.port(), e.what()); } } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); fRPCRunning = true; } void StartDummyRPCThread() { if (rpc_io_service == NULL) { rpc_io_service = new asio::io_service(); /* Create dummy "work" to keep the thread from exiting when no timeouts active, * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */ rpc_dummy_work = new asio::io_service::work(*rpc_io_service); rpc_worker_group = new boost::thread_group(); rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); fRPCRunning = true; } } void StopRPCThreads() { if (rpc_io_service == NULL) return; // Set this to false first, so that longpolling loops will exit when woken up fRPCRunning = false; // First, cancel all timers and acceptors // This is not done automatically by ->stop(), and in some cases the destructor of // asio::io_service can hang if this is skipped. boost::system::error_code ec; BOOST_FOREACH (const boost::shared_ptr<ip::tcp::acceptor>& acceptor, rpc_acceptors) { acceptor->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message()); } rpc_acceptors.clear(); BOOST_FOREACH (const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) & timer, deadlineTimers) { timer.second->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message()); } deadlineTimers.clear(); rpc_io_service->stop(); cvBlockChange.notify_all(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_dummy_work; rpc_dummy_work = NULL; delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } bool IsRPCRunning() { return fRPCRunning; } void SetRPCWarmupStatus(const std::string& newStatus) { LOCK(cs_rpcWarmup); rpcWarmupStatus = newStatus; } void SetRPCWarmupFinished() { LOCK(cs_rpcWarmup); assert(fRPCInWarmup); fRPCInWarmup = false; } bool RPCIsInWarmup(std::string* outStatus) { LOCK(cs_rpcWarmup); if (outStatus) *outStatus = rpcWarmupStatus; return fRPCInWarmup; } void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func) { if (!err) func(); } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { assert(rpc_io_service != NULL); if (deadlineTimers.count(name) == 0) { deadlineTimers.insert(make_pair(name, boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service)))); } deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds)); deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func)); } class JSONRequest { public: UniValue id; string strMethod; UniValue params; JSONRequest() { id = NullUniValue; } void parse(const UniValue& valRequest); }; void JSONRequest::parse(const UniValue& valRequest) { // Parse request if (!valRequest.isObject()) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const UniValue& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method UniValue valMethod = find_value(request, "method"); if (valMethod.isNull()) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (!valMethod.isStr()) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod)); // Parse params UniValue valParams = find_value(request, "params"); if (valParams.isArray()) params = valParams.get_array(); else if (valParams.isNull()) params = UniValue(UniValue::VARR); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static UniValue JSONRPCExecOne(const UniValue& req) { UniValue rpc_result(UniValue::VOBJ); JSONRequest jreq; try { jreq.parse(req); UniValue result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id); } catch (const UniValue& objError) { rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const UniValue& vReq) { UniValue ret(UniValue::VARR); for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return ret.write() + "\n"; } static bool HTTPReq_JSONRPC(AcceptedConnection* conn, string& strRequest, map<string, string>& mapHeaders, bool fRun) { // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush; return false; } if (!HTTPAuthorized(mapHeaders)) { LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string()); /* Deter brute-forcing If this results in a DoS the user really shouldn't have their RPC port exposed. */ MilliSleep(250); conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush; return false; } JSONRequest jreq; try { // Parse request UniValue valRequest; if (!valRequest.read(strRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); // Return immediately if in warmup { LOCK(cs_rpcWarmup); if (fRPCInWarmup) throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus); } string strReply; // singleton request if (valRequest.isObject()) { jreq.parse(valRequest); UniValue result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, NullUniValue, jreq.id); // array of requests } else if (valRequest.isArray()) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, strReply.size()) << strReply << std::flush; } catch (const UniValue& objError) { ErrorReply(conn->stream(), objError, jreq.id); return false; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); return false; } return true; } void ServiceConnection(AcceptedConnection* conn) { bool fRun = true; while (fRun && !ShutdownRequested()) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE); // HTTP Keep-Alive is false; close connection immediately if ((mapHeaders["connection"] == "close") || (!GetBoolArg("-rpckeepalive", true))) fRun = false; // Process via JSON-RPC API if (strURI == "/") { if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun)) break; // Process via HTTP REST API } else if (strURI.substr(0, 6) == "/rest/" && GetBoolArg("-rest", false)) { if (!HTTPReq_REST(conn, strURI, mapHeaders, fRun)) break; } else { conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush; break; } } } UniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params) const { // Find method const CRPCCommand* pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); /*if (std::find(desktopRPCCommands.begin(), desktopRPCCommands.end(), strMethod) != desktopRPCCommands.end()) { LogPrintf("ThreadRPCServer: found prohibited command %s\n", strMethod); throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); } else { LogPrintf("ThreadRPCServer: NOT found prohibited command %s\n", strMethod); }*/ #endif // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute UniValue result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); #ifdef ENABLE_WALLET else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } while (true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if (!lockMain) { MilliSleep(50); continue; } result = pcmd->actor(params, false); break; } break; } } #else // ENABLE_WALLET else { LOCK(cs_main); result = pcmd->actor(params, false); } #endif // !ENABLE_WALLET } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } void CRPCTable::addDesktopWalletCommands() const { LogPrintf("ThreadRPCServer: add desktop wallet commands\n"); //desktopRPCCommands.clear(); } std::vector<std::string> CRPCTable::listCommands() const { std::vector<std::string> commandList; typedef std::map<std::string, const CRPCCommand*> commandMap; std::transform( mapCommands.begin(), mapCommands.end(), std::back_inserter(commandList), boost::bind(&commandMap::value_type::first,_1) ); return commandList; } std::string HelpExampleCli(string methodname, string args) { return "> axel-cli " + methodname + " " + args + "\n"; } std::string HelpExampleRpc(string methodname, string args) { return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:1944/\n"; } const CRPCTable tableRPC;
[ "vit.yermolenko@stoamigo.com" ]
vit.yermolenko@stoamigo.com
f6558b8795f15b8e10e1e1380cd158ea2852f4b5
1cc17e9f4c3b6fba21aef3af5e900c80cfa98051
/chrome/browser/ui/views/facebook_chat/chat_notification_popup.cc
b376a10ed98c983a23ee35a45abe4365a0a053ac
[ "BSD-3-Clause" ]
permissive
sharpglasses/BitPop
2643a39b76ab71d1a2ed5b9840217b0e9817be06
1fae4ecfb965e163f6ce154b3988b3181678742a
refs/heads/master
2021-01-21T16:04:02.854428
2013-03-22T02:12:27
2013-03-22T02:12:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,767
cc
// Copyright (c) 2012 House of Life Property Ltd. All rights reserved. // Copyright (c) 2012 Crystalnix <vgachkaylo@crystalnix.com> // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/facebook_chat/chat_notification_popup.h" #include "base/utf_string_conversions.h" #include "base/win/win_util.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "grit/theme_resources.h" #include "grit/ui_resources.h" #include "ui/base/animation/slide_animation.h" #include "ui/base/resource/resource_bundle.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/layout/fill_layout.h" #include "ui/views/widget/widget.h" //#include "grit/theme_resources.h" //#include "ui/base/resource/resource_bundle.h" using views::View; namespace { static const int kMaxNotifications = 20; static const int kNotificationLabelWidth = 180; static const int kNotificationLabelMaxHeight = 600; static const int kLabelPaddingRight = 18; static const SkColor kNotificationPopupBackgroundColor = SkColorSetRGB(0xc2, 0xec, 0xfc); static const int kNotificationBubbleAlpha = 200; } class NotificationPopupContent : public views::Label { public: NotificationPopupContent(ChatNotificationPopup *owner) : views::Label(), owner_(owner) { SetMultiLine(true); SetAllowCharacterBreak(true); SetHorizontalAlignment(views::Label::ALIGN_LEFT); //SkColor labelBgr = SkColorSetA(kNotificationPopupBackgroundColor, 0); SetAutoColorReadabilityEnabled(false); SetBackgroundColor(kNotificationPopupBackgroundColor); SetEnabledColor(SkColorSetRGB(0,0,0)); } virtual gfx::Size GetPreferredSize() { int height = GetHeightForWidth(kNotificationLabelWidth); if (height > kNotificationLabelMaxHeight) { height = kNotificationLabelMaxHeight; } gfx::Size prefsize(kNotificationLabelWidth, height); gfx::Insets insets = GetInsets(); prefsize.Enlarge(insets.width(), insets.height()); return prefsize; } void UpdateOwnText() { const ChatNotificationPopup::MessageContainer& msgs = owner_->GetMessages(); std::string concat = ""; int i = 0; for (ChatNotificationPopup::MessageContainer::const_iterator it = msgs.begin(); it != msgs.end(); it++, i++) { concat += *it; if (i != (int)msgs.size() - 1) concat += "\n\n"; } //SetText(L""); //owner_->SizeToContents(); // dirty hack to force the window redraw SetText(UTF8ToWide(concat)); owner_->SizeToContents(); } private: ChatNotificationPopup* owner_; }; class NotificationContainerView : public View { public: NotificationContainerView(ChatNotificationPopup *owner) : owner_(owner), label_(new NotificationPopupContent(owner)), close_button_(new views::ImageButton(owner)), close_button_bg_color_(0) { AddChildView(label_); // Add the Close Button. ResourceBundle& rb = ResourceBundle::GetSharedInstance(); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetImageSkiaNamed(IDR_CLOSE_BAR)); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetImageSkiaNamed(IDR_CLOSE_BAR_H)); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetImageSkiaNamed(IDR_CLOSE_BAR_P)); // Disable animation so that the red danger sign shows up immediately // to help avoid mis-clicks. //close_button_->SetAnimationDuration(0); AddChildView(close_button_); set_background(views::Background::CreateSolidBackground(kNotificationPopupBackgroundColor)); } virtual gfx::Size GetPreferredSize() { gfx::Size s = label_->GetPreferredSize(); s.Enlarge(kLabelPaddingRight, 0); return s; } virtual void Layout() { gfx::Rect ourBounds = bounds(); ourBounds.set_x(0); ourBounds.set_y(0); label_->SetBounds(ourBounds.x(), ourBounds.y(), ourBounds.width() - kLabelPaddingRight, ourBounds.height()); gfx::Size prefsize = close_button_->GetPreferredSize(); close_button_->SetBounds(ourBounds.width() - prefsize.width(), 0, prefsize.width(), prefsize.height()); } NotificationPopupContent* GetLabelView() { return label_; } private: ChatNotificationPopup* owner_; NotificationPopupContent* label_; views::ImageButton* close_button_; SkColor close_button_bg_color_; }; // static ChatNotificationPopup* ChatNotificationPopup::Show(views::View* anchor_view, BitpopBubbleBorder::ArrowLocation arrow_location) { ChatNotificationPopup* popup = new ChatNotificationPopup(); popup->set_anchor_view(anchor_view); popup->set_arrow_location(arrow_location); popup->set_color(kNotificationPopupBackgroundColor); popup->set_close_on_deactivate(false); popup->set_use_focusless(true); popup->set_move_with_anchor(true); popup->SetLayoutManager(new views::FillLayout()); //popup->AddChildView(popup->container_view()); //ui::ResourceBundle& bundle = ui::ResourceBundle::GetSharedInstance(); //views::Label* label = new views::Label(L"Hello, world!"); //label->SetFont(bundle.GetFont(ResourceBundle::MediumFont)); //label->SetBackgroundColor(SkColorSetRGB(0xff, 0xff, 0xff)); //label->SetEnabledColor(SkColorSetRGB(0xe3, 0xed, 0xf6)); //label->SetHorizontalAlignment(views::Label::ALIGN_LEFT); popup->AddChildView(popup->container_view()); BitpopBubbleDelegateView::CreateBubble(popup); popup->GetWidget()->ShowInactive(); return popup; } ChatNotificationPopup::ChatNotificationPopup() : BitpopBubbleDelegateView() { container_view_ = new NotificationContainerView(this); } void ChatNotificationPopup::PushMessage(const std::string& message) { if (messages_.size() >= kMaxNotifications) messages_.pop_front(); messages_.push_back(message); static_cast<NotificationContainerView*>(container_view_)->GetLabelView()->UpdateOwnText(); } std::string ChatNotificationPopup::PopMessage() { std::string res = messages_.front(); //if (messages_.size() == 1) // return res; messages_.pop_front(); if (messages_.size() == 0) GetWidget()->Close(); else static_cast<NotificationContainerView*>(container_view_)->GetLabelView()->UpdateOwnText(); return res; } const ChatNotificationPopup::MessageContainer& ChatNotificationPopup::GetMessages() { return this->messages_; } void ChatNotificationPopup::ButtonPressed(views::Button* sender, const views::Event& event) { //DCHECK(sender == close_button_); GetWidget()->Close(); } gfx::Size ChatNotificationPopup::GetPreferredSize() { if (this->child_count()) return this->child_at(0)->GetPreferredSize(); return gfx::Size(); }
[ "vgachkaylo@crystalnix.com" ]
vgachkaylo@crystalnix.com
be16060adc044e01c31e9c1f38f5a609bca5573c
8b8f2343a288aab7863ac1dc408b60152ed109b0
/libport-core/src/main/native/store/store.cc
0b155cecfc0d5cbb8c7a852619b6e6cac3ca3780
[ "BSD-2-Clause-Views" ]
permissive
jerryz920/libport
afed8bfd699e959faa4f6398d61e42516a459a9f
72c6534e8f064b5507a5c79766a13114478d3ffa
refs/heads/master
2021-01-02T08:52:59.034298
2018-05-05T19:32:12
2018-05-05T19:32:12
99,083,085
0
0
null
null
null
null
UTF-8
C++
false
false
3,357
cc
#include "store.h" #include "utils.h" #include <crypto++/sha.h> #include <crypto++/hex.h> #include <mutex> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> /// A simple implementation for persistency class FileStore : public StoreManager{ public: static constexpr int MAX_DIGEST_SZ = 2048; static constexpr const char *SYNC_DIR = "/var/lib/attguard"; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FileStore); FileStore(): FileStore(latte::utils::make_unique<CryptoPP::SHA256>()) {} FileStore(std::unique_ptr<CryptoPP::HashTransformation> hasher): StoreManager(), hasher_(std::move(hasher)) { if (hasher_->DigestSize() > MAX_DIGEST_SZ) { throw std::runtime_error("hash digest size larger than expected"); } } ~FileStore() { if (dirfd_ > 0) { close(dirfd_); } } bool add(const google::protobuf::Message &msg) override { /// copied twice, not elegant, we may use some other approach std::string s = msg.SerializeAsString(); std::array<uint8_t, MAX_DIGEST_SZ> local_digest; { std::lock_guard<std::mutex> g(sync_lock_); hasher_->CalculateDigest(&digest_buffer_[0], (uint8_t*) s.c_str(), s.size()); local_digest.swap(digest_buffer_); } std::string fname = digest_to_hex(&local_digest[0], hasher_->DigestSize()); return sync_file(fname, std::move(s)); } bool remove(const google::protobuf::Message &msg) override { std::string s = msg.SerializeAsString(); std::array<uint8_t, MAX_DIGEST_SZ> local_digest; { std::lock_guard<std::mutex> g(sync_lock_); hasher_->CalculateDigest(&digest_buffer_[0], (uint8_t*) s.c_str(), s.size()); local_digest.swap(digest_buffer_); } std::string fname = digest_to_hex(&local_digest[0], hasher_->DigestSize()); unlinkat(dirfd_, fname.c_str(), 0); return true; } private: void init() { dirfd_ = open(SYNC_DIR, O_DIRECTORY); if (dirfd_ < 0) { latte::log_err_throw("can not open sync directory ", SYNC_DIR, strerror(errno)); } } std::string digest_to_hex(uint8_t *data, size_t sz) { CryptoPP::HexEncoder encoder; encoder.Put(data, sz); encoder.MessageEnd(); std::string result(encoder.MaxRetrievable(), 0); encoder.Get((uint8_t*) &result[0], result.size()); return result; } bool sync_file(const std::string &fname, std::string data) { struct stat fmeta; if (fstatat(dirfd_, fname.c_str(), &fmeta, 0) == 0) { latte::log_err("file %s already existed", fname.c_str()); return false; } int fd = openat(dirfd_, fname.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0644); FILE* f = fdopen(fd, "r"); if (fwrite(data.c_str(), 1, data.size(), f) != data.size()) { if (ferror(f)) { latte::log_err("error in writing file %s\n", fname.c_str()); return false; } latte::log("partial data written to file %s\n"); } fclose(f); return true; } std::unique_ptr<CryptoPP::HashTransformation> hasher_; std::array<uint8_t, MAX_DIGEST_SZ> digest_buffer_; std::mutex sync_lock_; int dirfd_; };
[ "zhaiyan920@gmail.com" ]
zhaiyan920@gmail.com
9f54382d33b678449689d23c7d695a08f36a9656
399b5e377fdd741fe6e7b845b70491b9ce2cccfd
/LLVM_src/libcxx/test/std/utilities/time/time.cal/time.cal.ym/time.cal.ym.members/plus_minus_equal_month.pass.cpp
76f3b3355d2221c0cea85d738737565cfd9e02e5
[ "NCSA", "LLVM-exception", "MIT", "Apache-2.0" ]
permissive
zslwyuan/LLVM-9-for-Light-HLS
6ebdd03769c6b55e5eec923cb89e4a8efc7dc9ab
ec6973122a0e65d963356e0fb2bff7488150087c
refs/heads/master
2021-06-30T20:12:46.289053
2020-12-07T07:52:19
2020-12-07T07:52:19
203,967,206
1
3
null
2019-10-29T14:45:36
2019-08-23T09:25:42
C++
UTF-8
C++
false
false
2,508
cpp
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <chrono> // class year_month; // constexpr year_month& operator+=(const months& d) noexcept; // constexpr year_month& operator-=(const months& d) noexcept; #include <chrono> #include <type_traits> #include <cassert> #include "test_macros.h" template <typename D, typename Ds> constexpr bool testConstexpr(D d1) { if (static_cast<unsigned>((d1 ).month()) != 1) return false; if (static_cast<unsigned>((d1 += Ds{ 1}).month()) != 2) return false; if (static_cast<unsigned>((d1 += Ds{ 2}).month()) != 4) return false; if (static_cast<unsigned>((d1 += Ds{12}).month()) != 4) return false; if (static_cast<unsigned>((d1 -= Ds{ 1}).month()) != 3) return false; if (static_cast<unsigned>((d1 -= Ds{ 2}).month()) != 1) return false; if (static_cast<unsigned>((d1 -= Ds{12}).month()) != 1) return false; return true; } int main() { using month = std::chrono::month; using months = std::chrono::months; using year = std::chrono::year; using year_month = std::chrono::year_month; ASSERT_NOEXCEPT( std::declval<year_month&>() += std::declval<months>()); ASSERT_SAME_TYPE(year_month&, decltype(std::declval<year_month&>() += std::declval<months>())); ASSERT_NOEXCEPT( std::declval<year_month&>() -= std::declval<months>()); ASSERT_SAME_TYPE(year_month&, decltype(std::declval<year_month&>() -= std::declval<months>())); static_assert(testConstexpr<year_month, months>(year_month{year{1234}, month{1}}), ""); for (unsigned i = 0; i <= 10; ++i) { year y{1234}; year_month ym(y, month{i}); assert(static_cast<unsigned>((ym += months{2}).month()) == i + 2); assert(ym.year() == y); assert(static_cast<unsigned>((ym ).month()) == i + 2); assert(ym.year() == y); assert(static_cast<unsigned>((ym -= months{1}).month()) == i + 1); assert(ym.year() == y); assert(static_cast<unsigned>((ym ).month()) == i + 1); assert(ym.year() == y); } }
[ "tliang@connect.ust.hk" ]
tliang@connect.ust.hk
e7a11e4f6c5425e2b417df8e3c7dbdadaaad941d
3be90a39a5dd6ad85ea03fc968ce39376467253a
/src/popup_messages.h
39ed63818ca4548d7301b5e6c591a089d90b780a
[ "MIT" ]
permissive
suve/LD30-dex
3af443b83aecb0eaa94f1cfe2e986dd9a002de41
727d7592fd9aa5ac10f6584007ad1877a78c756c
refs/heads/master
2023-01-23T16:22:02.258777
2018-01-10T22:47:04
2018-01-10T22:47:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
944
h
#pragma once #include <vector> #include <string> #include <SFML/System/Vector2.hpp> #include <SFML/Graphics/Color.hpp> #include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Text.hpp> class PopupMessages: public sf::Drawable { public: static constexpr float DEFAULT_POPUP_TTL_S = 3.0f; static constexpr float POPUP_ASCEND_SPEED = 15.0f; static constexpr unsigned DEFAULT_POPUP_TEXT_SIZE = 20; struct Message { sf::Text text; float ttl_s; }; PopupMessages(); void add(const std::string& msg, const sf::Vector2f& pos, const sf::Color& color, float ttl_s = DEFAULT_POPUP_TTL_S); void update(float dt); void clear() { msgs.clear(); } protected: virtual void draw(sf::RenderTarget& rt, sf::RenderStates states) const; private: std::vector<Message> msgs; sf::Font font; unsigned textSize; };
[ "hukutizuviki+git@gmail.com" ]
hukutizuviki+git@gmail.com
182e5359662172049100844f823c8fa2ed4bfa78
f6f0885bd19f7fb115825f4f2a8eb075b2c5b4aa
/1486.cpp
3f7ec35e9b8516ed2970246afe61824edc43dead
[]
no_license
faiem/leetcode
5c6b3ebbc8df3fdbb019980e79916a989f9b8ceb
f8686b25b1b48a4ec4c0757ed67e61bc0a186d5f
refs/heads/main
2023-05-08T15:50:05.069027
2021-05-31T13:38:34
2021-05-31T13:38:34
357,337,376
0
0
null
null
null
null
UTF-8
C++
false
false
196
cpp
class Solution { public: int xorOperation(int n, int start) { int res = 0; for(int I=0;I<n;I++) { res ^= (start+I+I); } return res; } };
[ "faiem@overseasecurity.com" ]
faiem@overseasecurity.com
b628ee0d7749517a94d407b39f67d9de086d6e6f
9356b448967f99e2056488d6184b2fd79dbb0ffe
/input.cpp
a55dc4c20de8f59df365a2261b7bdca0d9261910
[]
no_license
fslees/team_sun
3c70c3885f784cd15507f845e19dbe0ab5381230
3315f378b5e48a6cb5a133e3d1147f14ee3dc4b6
refs/heads/master
2022-01-12T15:54:59.399166
2019-07-17T07:26:40
2019-07-17T07:26:40
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
6,794
cpp
//============================================================================= // // 入力処理 [input.cpp] // Author : AKIRA TANAKA // //============================================================================= #include "input.h" //***************************************************************************** // マクロ定義 //***************************************************************************** #define NUM_KEY_MAX (256) // キー最大数 //***************************************************************************** // プロトタイプ宣言 //***************************************************************************** HRESULT InitKeyboard(HINSTANCE hInst, HWND hWnd); void UninitKeyboard(void); HRESULT UpdateKeyboard(void); //***************************************************************************** // グローバル変数 //***************************************************************************** LPDIRECTINPUT8 g_pDInput = NULL; // IDirectInput8インターフェースへのポインタ LPDIRECTINPUTDEVICE8 g_pDIDevKeyboard = NULL; // IDirectInputDevice8インターフェースへのポインタ(キーボード) BYTE g_aKeyState[NUM_KEY_MAX]; // キーボードの押下状態を保持するワーク BYTE g_aKeyStateTrigger[NUM_KEY_MAX]; // キーボードのトリガー状態を保持するワーク BYTE g_aKeyStateRelease[NUM_KEY_MAX]; // キーボードのリリース状態を保持するワーク BYTE g_aKeyStateRepeat[NUM_KEY_MAX]; // キーボードのリピート状態を保持するワーク int g_aKeyStateRepeatCnt[NUM_KEY_MAX]; // キーボードのリピートカウンタ //============================================================================= // 入力処理の初期化 //============================================================================= HRESULT InitInput(HINSTANCE hInst, HWND hWnd) { HRESULT hr; if(!g_pDInput) { // DirectInputオブジェクトの作成 hr = DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&g_pDInput, NULL); } // キーボードの初期化 InitKeyboard(hInst, hWnd); return S_OK; } //============================================================================= // 入力処理の終了処理 //============================================================================= void UninitInput(void) { // キーボードの終了処理 UninitKeyboard(); if(g_pDInput) {// DirectInputオブジェクトの開放 g_pDInput->Release(); g_pDInput = NULL; } } //============================================================================= // 入力処理の更新処理 //============================================================================= void UpdateInput(void) { // キーボードの更新 UpdateKeyboard(); } //============================================================================= // キーボードの初期化処理 //============================================================================= HRESULT InitKeyboard(HINSTANCE hInst, HWND hWnd) { HRESULT hr; // デバイスオブジェクトを作成 hr = g_pDInput->CreateDevice(GUID_SysKeyboard, &g_pDIDevKeyboard, NULL); if(FAILED(hr) || g_pDIDevKeyboard == NULL) { MessageBox(hWnd, "キーボードがねぇ!", "警告!", MB_ICONWARNING); return hr; } // データフォーマットを設定 hr = g_pDIDevKeyboard->SetDataFormat(&c_dfDIKeyboard); if(FAILED(hr)) { MessageBox(hWnd, "キーボードのデータフォーマットを設定できませんでした。", "警告!", MB_ICONWARNING); return hr; } // 協調モードを設定(フォアグラウンド&非排他モード) hr = g_pDIDevKeyboard->SetCooperativeLevel(hWnd, (DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)); if(FAILED(hr)) { MessageBox(hWnd, "キーボードの協調モードを設定できませんでした。", "警告!", MB_ICONWARNING); return hr; } // キーボードへのアクセス権を獲得(入力制御開始) g_pDIDevKeyboard->Acquire(); return S_OK; } //============================================================================= // キーボードの終了処理 //============================================================================= void UninitKeyboard(void) { if(g_pDIDevKeyboard) {// デバイスオブジェクトの開放 g_pDIDevKeyboard->Release(); g_pDIDevKeyboard = NULL; } } //============================================================================= // キーボードの更新処理 //============================================================================= HRESULT UpdateKeyboard(void) { HRESULT hr; BYTE aKeyState[NUM_KEY_MAX]; // デバイスからデータを取得 hr = g_pDIDevKeyboard->GetDeviceState(sizeof(aKeyState), aKeyState); if(SUCCEEDED(hr)) { for(int nCntKey = 0; nCntKey < NUM_KEY_MAX; nCntKey++) { g_aKeyStateTrigger[nCntKey] = (g_aKeyState[nCntKey] ^ aKeyState[nCntKey]) & aKeyState[nCntKey]; g_aKeyStateRelease[nCntKey] = (g_aKeyState[nCntKey] ^ aKeyState[nCntKey]) & ~aKeyState[nCntKey]; g_aKeyStateRepeat[nCntKey] = g_aKeyStateTrigger[nCntKey]; if(aKeyState[nCntKey]) { g_aKeyStateRepeatCnt[nCntKey]++; if(g_aKeyStateRepeatCnt[nCntKey] >= 20) { g_aKeyStateRepeat[nCntKey] = aKeyState[nCntKey]; } } else { g_aKeyStateRepeatCnt[nCntKey] = 0; g_aKeyStateRepeat[nCntKey] = 0; } g_aKeyState[nCntKey] = aKeyState[nCntKey]; } } else { // キーボードへのアクセス権を取得 g_pDIDevKeyboard->Acquire(); } return S_OK; } //============================================================================= // キーボードのプレス状態を取得 //============================================================================= bool GetKeyboardPress(int nKey) { return (g_aKeyState[nKey] & 0x80) ? true: false; } //============================================================================= // キーボードのトリガー状態を取得 //============================================================================= bool GetKeyboardTrigger(int nKey) { return (g_aKeyStateTrigger[nKey] & 0x80) ? true: false; } //============================================================================= // キーボードのリピート状態を取得 //============================================================================= bool GetKeyboardRepeat(int nKey) { return (g_aKeyStateRepeat[nKey] & 0x80) ? true: false; } //============================================================================= // キーボードのリリ−ス状態を取得 //============================================================================= bool GetKeyboardRelease(int nKey) { return (g_aKeyStateRelease[nKey] & 0x80) ? true: false; }
[ "taiyo_tanaka33@yahoo.co.jp" ]
taiyo_tanaka33@yahoo.co.jp
f97f677823a31f42c9666f1093fab9e031d3a7dd
f9bea718229a5d2a131725f2f5369f01b3360d76
/src/bench/ccoins_caching.cpp
19de7175a21dacb487e86e33316d0cc890fbea1b
[ "MIT" ]
permissive
adammatlack/Ion-Core
eede33a1afc948c48b07d094485dba391b86d726
d7fc451745bb885ab91ef99dbb2de00e10710fcf
refs/heads/master
2021-01-11T21:11:35.279344
2017-01-17T18:20:56
2017-01-17T18:20:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,479
cpp
// Copyright (c) 2017 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 "bench.h" #include "coins.h" #include "policy/policy.h" #include "wallet/crypter.h" #include <vector> // FIXME: Dedup with SetupDummyInputs in test/transaction_tests.cpp. // // Helper: create two dummy transactions, each with // two outputs. The first has 11 and 50 CENT outputs // paid to a TX_PUBKEY, the second 21 and 22 CENT outputs // paid to a TX_PUBKEYHASH. // static std::vector<CMutableTransaction> SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsViewCache& coinsRet) { std::vector<CMutableTransaction> dummyTransactions; dummyTransactions.resize(2); // Add some keys to the keystore: CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(i % 2); keystoreRet.AddKey(key[i]); } // Create some dummy input transactions dummyTransactions[0].vout.resize(2); dummyTransactions[0].vout[0].nValue = 11 * CENT; dummyTransactions[0].vout[0].scriptPubKey << ToByteVector(key[0].GetPubKey()) << OP_CHECKSIG; dummyTransactions[0].vout[1].nValue = 50 * CENT; dummyTransactions[0].vout[1].scriptPubKey << ToByteVector(key[1].GetPubKey()) << OP_CHECKSIG; coinsRet.ModifyCoins(dummyTransactions[0].GetHash())->FromTx(dummyTransactions[0], 0); dummyTransactions[1].vout.resize(2); dummyTransactions[1].vout[0].nValue = 21 * CENT; dummyTransactions[1].vout[0].scriptPubKey = GetScriptForDestination(key[2].GetPubKey().GetID()); dummyTransactions[1].vout[1].nValue = 22 * CENT; dummyTransactions[1].vout[1].scriptPubKey = GetScriptForDestination(key[3].GetPubKey().GetID()); coinsRet.ModifyCoins(dummyTransactions[1].GetHash())->FromTx(dummyTransactions[1], 0); return dummyTransactions; } // Microbenchmark for simple accesses to a CCoinsViewCache database. Note from // laanwj, "replicating the actual usage patterns of the client is hard though, // many times micro-benchmarks of the database showed completely different // characteristics than e.g. reindex timings. But that's not a requirement of // every benchmark." // (https://github.com/bitcoin/bitcoin/issues/7883#issuecomment-224807484) static void CCoinsCaching(benchmark::State& state) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(&coinsDummy); std::vector<CMutableTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CMutableTransaction t1; t1.vin.resize(3); t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t1.vin[0].prevout.n = 1; t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[1].prevout.n = 0; t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[2].prevout.n = 1; t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vout.resize(2); t1.vout[0].nValue = 90 * CENT; t1.vout[0].scriptPubKey << OP_1; // Benchmark. while (state.KeepRunning()) { bool success = AreInputsStandard(t1, coins); assert(success); CAmount value = coins.GetValueIn(t1); assert(value == (50 + 21 + 22) * CENT); } } BENCHMARK(CCoinsCaching);
[ "empinelx@gmail.com" ]
empinelx@gmail.com
16bec38e539b8375558b68794e74da7cdd20c103
7426ebd6d9ef8366ea6ef1d2965b08205229ef54
/tools/deploy/torchscript_mask_rcnn.cpp
a09446d004efd35f5a7c216301721c0feb23db9b
[ "Apache-2.0" ]
permissive
PXX1110/detectron2
b2ae054f5a320b8650620af29557dd8d45c86b67
2106ed131507685f0a12369a26439bdfc411b78b
refs/heads/main
2023-08-28T07:18:56.028599
2021-11-15T09:40:47
2021-11-15T09:41:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,549
cpp
// Copyright (c) Facebook, Inc. and its affiliates. // @lint-ignore-every CLANGTIDY // This is an example code that demonstrates how to run inference // with a torchscript format Mask R-CNN model exported by ./export_model.py // using export method=tracing, caffe2_tracing & scripting. #include <opencv2/opencv.hpp> #include <iostream> #include <string> #include <c10/cuda/CUDAStream.h> #include <torch/csrc/autograd/grad_mode.h> #include <torch/csrc/jit/runtime/graph_executor.h> #include <torch/script.h> // only needed for export_method=tracing #include <torchvision/vision.h> // @oss-only // @fb-only: #include <torchvision/csrc/vision.h> using namespace std; c10::IValue get_caffe2_tracing_inputs(cv::Mat& img, c10::Device device) { const int height = img.rows; const int width = img.cols; // FPN models require divisibility of 32. // Tracing mode does padding inside the graph, but caffe2_tracing does not. assert(height % 32 == 0 && width % 32 == 0); const int channels = 3; auto input = torch::from_blob(img.data, {1, height, width, channels}, torch::kUInt8); // NHWC to NCHW input = input.to(device, torch::kFloat).permute({0, 3, 1, 2}).contiguous(); std::array<float, 3> im_info_data{height * 1.0f, width * 1.0f, 1.0f}; auto im_info = torch::from_blob(im_info_data.data(), {1, 3}).clone().to(device); return std::make_tuple(input, im_info); } c10::IValue get_tracing_inputs(cv::Mat& img, c10::Device device) { const int height = img.rows; const int width = img.cols; const int channels = 3; auto input = torch::from_blob(img.data, {height, width, channels}, torch::kUInt8); // HWC to CHW input = input.to(device, torch::kFloat).permute({2, 0, 1}).contiguous(); return input; } // create a Tuple[Dict[str, Tensor]] which is the input type of scripted model c10::IValue get_scripting_inputs(cv::Mat& img, c10::Device device) { const int height = img.rows; const int width = img.cols; const int channels = 3; auto img_tensor = torch::from_blob(img.data, {height, width, channels}, torch::kUInt8); // HWC to CHW img_tensor = img_tensor.to(device, torch::kFloat).permute({2, 0, 1}).contiguous(); c10::Dict dic = c10::Dict<std::string, torch::Tensor>(); dic.insert("image", img_tensor); return std::make_tuple(dic); } c10::IValue get_inputs(std::string export_method, cv::Mat& img, c10::Device device) { // Given an image, create inputs in the format required by the model. if (export_method == "tracing") return get_tracing_inputs(img, device); if (export_method == "caffe2_tracing") return get_caffe2_tracing_inputs(img, device); if (export_method == "scripting") return get_scripting_inputs(img, device); abort(); } struct MaskRCNNOutputs { at::Tensor pred_boxes, pred_classes, pred_masks, scores; int num_instances() const { return pred_boxes.sizes()[0]; } }; MaskRCNNOutputs get_outputs(std::string export_method, c10::IValue outputs) { // Given outputs of the model, extract tensors from it to turn into a // common MaskRCNNOutputs format. if (export_method == "tracing") { auto out_tuple = outputs.toTuple()->elements(); // They are ordered alphabetically by their field name in Instances return MaskRCNNOutputs{ out_tuple[0].toTensor(), out_tuple[1].toTensor(), out_tuple[2].toTensor(), out_tuple[3].toTensor()}; } if (export_method == "caffe2_tracing") { auto out_tuple = outputs.toTuple()->elements(); // A legacy order used by caffe2 models return MaskRCNNOutputs{ out_tuple[0].toTensor(), out_tuple[2].toTensor(), out_tuple[3].toTensor(), out_tuple[1].toTensor()}; } if (export_method == "scripting") { // With the ScriptableAdapter defined in export_model.py, the output is // List[Dict[str, Any]]. auto out_dict = outputs.toList().get(0).toGenericDict(); return MaskRCNNOutputs{ out_dict.at("pred_boxes").toTensor(), out_dict.at("pred_classes").toTensor(), out_dict.at("pred_masks").toTensor(), out_dict.at("scores").toTensor()}; } abort(); } int main(int argc, const char* argv[]) { if (argc != 4) { cerr << R"xx( Usage: ./torchscript_mask_rcnn model.ts input.jpg EXPORT_METHOD EXPORT_METHOD can be "tracing", "caffe2_tracing" or "scripting". )xx"; return 1; } std::string image_file = argv[2]; std::string export_method = argv[3]; assert( export_method == "caffe2_tracing" || export_method == "tracing" || export_method == "scripting"); torch::jit::getBailoutDepth() = 1; torch::autograd::AutoGradMode guard(false); auto module = torch::jit::load(argv[1]); assert(module.buffers().size() > 0); // Assume that the entire model is on the same device. // We just put input to this device. auto device = (*begin(module.buffers())).device(); cv::Mat input_img = cv::imread(image_file, cv::IMREAD_COLOR); auto inputs = get_inputs(export_method, input_img, device); // Run the network auto output = module.forward({inputs}); if (device.is_cuda()) c10::cuda::getCurrentCUDAStream().synchronize(); // run 3 more times to benchmark int N_benchmark = 3, N_warmup = 1; auto start_time = chrono::high_resolution_clock::now(); for (int i = 0; i < N_benchmark + N_warmup; ++i) { if (i == N_warmup) start_time = chrono::high_resolution_clock::now(); output = module.forward({inputs}); if (device.is_cuda()) c10::cuda::getCurrentCUDAStream().synchronize(); } auto end_time = chrono::high_resolution_clock::now(); auto ms = chrono::duration_cast<chrono::microseconds>(end_time - start_time) .count(); cout << "Latency (should vary with different inputs): " << ms * 1.0 / 1e6 / N_benchmark << " seconds" << endl; // Parse Mask R-CNN outputs auto rcnn_outputs = get_outputs(export_method, output); cout << "Number of detected objects: " << rcnn_outputs.num_instances() << endl; cout << "pred_boxes: " << rcnn_outputs.pred_boxes.toString() << " " << rcnn_outputs.pred_boxes.sizes() << endl; cout << "scores: " << rcnn_outputs.scores.toString() << " " << rcnn_outputs.scores.sizes() << endl; cout << "pred_classes: " << rcnn_outputs.pred_classes.toString() << " " << rcnn_outputs.pred_classes.sizes() << endl; cout << "pred_masks: " << rcnn_outputs.pred_masks.toString() << " " << rcnn_outputs.pred_masks.sizes() << endl; cout << rcnn_outputs.pred_boxes << endl; return 0; }
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
3b355b75637e187fa27c29a8789ddd5480b1112f
4b67f4e430679bd3bbe6e77c305b26faa9806bef
/arrays&mix/maxspprod.cpp
905af21266b08dea74bc70b0a80bc24b33cc380c
[]
no_license
1997priyam/Data-Structures
6a5339805c217bc51e4a21026ccae30a262eabe5
f3adb4aac0f9153aea6dd58822922927d1d5b9b7
refs/heads/master
2021-08-15T23:14:15.960649
2021-06-27T10:10:39
2021-06-27T10:10:39
201,605,017
3
1
null
2020-10-19T11:47:08
2019-08-10T08:54:19
C++
UTF-8
C++
false
false
761
cpp
#include<bits/stdc++.h> #include<iostream> #include<vector> #include<string> using namespace std; int maxSpecialProduct(vector<int> &A) { int maxprod = INT_MIN; for(int i=0; i<A.size(); i++){ int lsv = 0; int rsv = 0; for(int j=i-1; j>=0; j--){ if(A[j]>A[i]){ lsv = j; break; } } for(int k=i+1; k<A.size();k++){ if(A[k]>A[i]){ rsv = k; break; } } int max = lsv*rsv; if(max>maxprod){ maxprod = max; } } return maxprod; } int main(){ vector<int> A = {3,4,5,6,1,2,3,7,8,42,6,98,2}; int ans = maxSpecialProduct(A); cout<<"Answer: "<<ans; }
[ "1997priyam@gmail.com" ]
1997priyam@gmail.com
d5eee16ba24b87796d6e72a9c982138209acc0e4
e8ef31a4160aa305c29ea0f55f75602a573add15
/string_permutation.cc
135533313e95fcb48679c086efb851b2ba3e94c6
[]
no_license
xinwangus/string_tests
01d4a852a2b4aeb6779b59f28e0040343322892c
f7777842f35dac6a5a10e7e8c323f3a722192300
refs/heads/master
2021-01-20T19:39:30.666994
2021-01-20T15:53:43
2021-01-20T15:53:43
60,996,948
0
0
null
null
null
null
UTF-8
C++
false
false
2,320
cc
/* g++ -std=c++11 */ #include <string> #include <iostream> #include <deque> #include <assert.h> using namespace std; void permutation_recursive(const char* str, unsigned int len, deque<string>& out) { if ((str == 0) || (len == 0)) { return; } char head = str[0]; if (len == 1) { assert(out.empty()); assert(str); string tmp(&head, len); out.push_back(tmp); // cout << "Pushed " << tmp << endl; return; } // call recursively. permutation_recursive((str+1), (len-1), out); // out now has all permutations for the rest of string. // Post-processing. // take all out, one by one, and do the insert. int s = out.size(); for (int i = 0; i < s; i++) { string tmp = out.front(); out.pop_front(); // cout << "Poped " << tmp << endl; string tmp2; // insert to all possible slots. for (int j = 0; j < tmp.size(); j++) { tmp2 = tmp; tmp2.insert(j, &head, 1); out.push_back(tmp2); // cout << "Pushed " << tmp2 << endl; } // last string is to append to the end. string last = tmp.append(&head, 1); out.push_back(last); // cout << "Pushed Last " << last << endl; } // out now has all permutations for the string, str. } void permutation_recursive(string& s, deque<string>& out) { permutation_recursive(s.c_str(), s.size(), out); } /* this is a much better solution, avoids recursive calls */ void permutation_iterative(string& s, deque<string>& out) { if (s.size() == 0) { return; } for (auto itr = s.begin(); itr != s.end(); ++itr) { if (itr == s.begin()) { assert(out.empty()); out.push_back(string(&(*itr), 1)); continue; } // need to save off, as the out.size() // will change. int out_size = out.size(); for (int j = 0; j < out_size; j++) { string tmp = out.front(); out.pop_front(); string tmp2; for (int k = 0; k < tmp.size(); k++) { tmp2 = tmp; out.push_back(tmp2.insert(k, &(*itr), 1)); } tmp2 = tmp; out.push_back(tmp2.append(&(*itr), 1)); } // Loop invariant: // by now "out" has all permutations of the string // from beginning to the current itr position. } } int main() { string test("abcdef"); deque<string> out; //permutation_recursive(test, out); permutation_iterative(test, out); auto it = out.begin(); while (it != out.end()) { cout << *it++ << endl; } }
[ "xinwangus@users.noreply.github.com" ]
xinwangus@users.noreply.github.com
44923620627b6cdb8d1d0e6243c6a31263620d3e
cd15e3161fbb9924ae97146f703fb552fd2723f2
/Cpp/Codes/Practice/Interview/17_2 knightDialer.cpp
1fab09f8a6a7dcef08f3a399e9664e4fb85e2bc7
[ "MIT" ]
permissive
QuincyWork/AllCodes
f8953442f13f13cf2beec8f23697e89d4c3cbcbc
59fe045608dda924cb993dde957da4daff769438
refs/heads/master
2021-08-16T10:26:58.971769
2021-06-10T07:52:53
2021-06-10T07:52:53
103,636,470
0
1
null
null
null
null
GB18030
C++
false
false
1,674
cpp
#include <gtest/gtest.h> using namespace std; namespace IV17_2 { /* 国际象棋中的骑士可以按下图所示进行移动: . 这一次,我们将 “骑士” 放在电话拨号盘的任意数字键(如上图所示)上,接下来,骑士将会跳 N-1 步。每一步必须是从一个数字键跳到另一个数字键。 每当它落在一个键上(包括骑士的初始位置),都会拨出键所对应的数字,总共按下 N 位数字。 你能用这种方式拨出多少个不同的号码? 因为答案可能很大,所以输出答案模 10^9 + 7。 示例 1: 输入:1 输出:10 示例 2: 输入:2 输出:20 示例 3: 输入:3 输出:46 提示: 1 <= N <= 5000 */ class Solution { public: int knightDialer(int N) { vector<vector<int>> dp(N, vector<int>(10)); int MOD = 1000000007; vector<vector<int>> next { {4 , 6 },//0 {6 , 8 },//1 {7 , 9 },//2 {4 , 8 },//3 {3 , 9, 0 },//4 { },//5 {1 , 7 ,0 },//6 {2 , 6 },//7 {1 , 3 },//8 {2 , 4 },//9 }; // 当 N = 1 的时候,只有1种走法:停在原地 dp[0].assign(10, 1); for (int i = 1; i < N; ++i) { for (int j = 0; j <= 9; ++j) { for (int k = 0; k < next[j].size(); k++) { dp[i][j] += dp[i - 1][next[j][k]]; dp[i][j] %= MOD; } } } long ans = 0; for (int i = 0; i < 10; i++) { ans += dp[N-1][i]; } ans %= MOD; return (int)ans; } }; TEST(Interview, knightDialer) { Solution s; ASSERT_EQ(s.knightDialer(1), 10); ASSERT_EQ(s.knightDialer(2), 20); ASSERT_EQ(s.knightDialer(3), 46); } }
[ "huqh@pxinfosec.com" ]
huqh@pxinfosec.com
0834eadafd82fb928c5f8eecf3a35702e1b8f316
21bb2fa7dc31ff8ff2778fb622ec30a2d670ebc2
/CodeForces/Contest/Division 2/Div233/A.cpp
83d5827a57f13de873c1fd489a0f57094b2eee20
[]
no_license
shuvokr/CodeForces_Online_Contest
8caa8f4bd1fc4822527772a31de0143b1977c9f9
c4b5181767744c0c48066da75b849ff0fcca1db1
refs/heads/master
2021-01-20T19:57:08.165881
2016-12-04T15:52:48
2016-12-04T15:52:48
65,748,624
0
0
null
null
null
null
UTF-8
C++
false
false
3,011
cpp
/************************************ Shuvo Problem name : Problem ID : Problem algo : Note : *************************************/ /**********************************Templet start***********************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <string> #include <iostream> #include <sstream> #include <vector> #include <queue> #include <stack> #include <map> #include <list> #include <set> #include <algorithm> using namespace std; #define phl puts("Hello") #define sf scanf #define pf printf #define fo(i, n) for(i = 0; i < n; i++) #define of(i, n) for(i = n - 1; i >= 0; i--) #define CLR(n, v) memset(n, v, sizeof( n )) #define INF 1 << 30 #define pb push_back #define maxn 200+2 #define lim(v) v.begin(), v.end() #define sz(v) ((int)v,size()) #define equals(a, b) (fabs(a-b)<eps) #define white 0 #define black 1 const double PI = 2 * acos ( 0.0 ); const double eps = 1e-9; typedef long long lld; typedef unsigned long long llu; typedef pair<int, int> pi; typedef vector<int> vi; typedef vector<pi> vpi; template <class T> T jog(T a, T b) { return a + b; } template <class T> T bog(T a, T b) { return a - b; } template <class T> T gon(T a, T b) { return a * b; } template <class T> T sq(T x) {return x * x;} template <class T> T gcd( T a, T b ) { return b == 0 ? a : gcd(b, a % b); } template <class T> T lcm ( T a, T b ) { return ( a / gcd ( a, b ) ) * b; } template <class T> T power ( T a, T p ) { int res = 1, x = a; while ( p ) { if ( p & 1 ) res = res * x; x = x * x; p >>= 1; } return res;} template <class T> T cordinatlenth(T a, T b, T c, T d) { return sqrt( sq(a - c) + sq(b - d) ); } lld bigmod ( lld a, lld p, lld mod ) { lld res = 1, x = a; while ( p ) { if ( p & 1 ) res = ( res * x ) % mod; x = ( x * x ) % mod; p >>= 1; } return res; } int diraction1[] = {-1, 0, 0, 1, 1, -1, -1, 1}; int diraction2[] = {0, -1, 1, 0, 1, -1, 1, -1}; int horsed1[] = {-2, -2, -1, 1, 2, 2, 1, -1}; int horsed2[] = {1, -1, -2, -2, -1, 1, 2, 2}; void input(); /**************************Templet end*********************************/ int main() { //#ifdef localhost //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); //#endif input(); return 0; } void input() { int n, p, k; bool mr; scanf("%d %d %d", &n, &p, &k); mr = true; int tmp = p - k; if(tmp > 1) { printf("<<"); for(int i = tmp; i < p; i++) printf(" %d", i); } else { if(p == 1) printf("(1)"), mr = false; else printf("1"); for(int i = 2; i < p; i++) printf(" %d", i); } if( mr ) printf(" (%d)", p); int cou = 0; p++; while(cou < k && p <= n) { printf(" %d", p); p++; cou++; } if(p - 1 != n) printf(" >>"); puts(""); }
[ "Monkey 'sWorld" ]
Monkey 'sWorld
151a10c22ea7387952dcdc8dc437d4429f6612ba
dbef9fa1e78187bf06df4f9b25f3e19fc28638b5
/src/Btree/Test/MemoryMemo.cpp
0430924374334af45581ad41bbece8de4d1f776c
[]
no_license
YigaoFan/RPC
dd9001bb59669c0dacd0fea413e2b3fb0616d777
dd8dea093fc1c5e7907f27d74bd61fb96deafd62
refs/heads/master
2023-03-20T04:52:46.911602
2021-03-11T07:00:43
2021-03-11T07:00:43
158,654,698
0
0
null
null
null
null
UTF-8
C++
false
false
677
cpp
#include <iostream> #include "MemoryMemo.hpp" int MemoryMemo::Count = 0; MemoryMemo::MemoryMemo() : _value(MemoryMemo::Count++) { } MemoryMemo::MemoryMemo(MemoryMemo&& that) : _value(that._value) { that._hasValue = false; } MemoryMemo::MemoryMemo(MemoryMemo const& that) : MemoryMemo() { } MemoryMemo& MemoryMemo::operator= (MemoryMemo const& that) { this->_value = MemoryMemo::Count++; return *this; } MemoryMemo& MemoryMemo::operator= (MemoryMemo&& that) { this->_value = that._value; that._hasValue = false; return *this; } MemoryMemo::~MemoryMemo() { using ::std::cout; using ::std::endl; if (_hasValue) { cout << _value << " Destroyed" << endl; } }
[ "v-yifan@microsoft.com" ]
v-yifan@microsoft.com
3c5502626cfc38849650c513f1e39226a63e6a7c
261ff029c1355a8a1f74a46f76155bc44ca2f44b
/MyMap_Tool/Codes/Player.h
4984ac4047f030dcb7d0ff7bffad4c829c1c2ef9
[]
no_license
bisily/DirectX3D_Personal_-portfolio
39aa054f60228e703a6d942a7df94a9faaa7a00a
e06878690793d103273f2b50213a92bdfb923b33
refs/heads/master
2022-11-26T11:51:29.985373
2020-08-04T09:17:09
2020-08-04T09:17:09
284,932,529
0
0
null
null
null
null
UTF-8
C++
false
false
1,422
h
#ifndef Player_h__ #define Player_h__ #include "Defines.h" #include "GameObject.h" namespace Engine { class CDynamicMesh; class CTransform; class CRenderer; class CCalculator; class CCollider; class CCubeTex; class CNaviMesh; } class CPlayer : public Engine::CGameObject { private: explicit CPlayer(LPDIRECT3DDEVICE9 pGraphicDev); public: virtual ~CPlayer(void); public: virtual HRESULT Ready_Object(void); virtual Engine::_int Update_Object(const Engine::_float& fTimeDelta); virtual void Render_Object(void); void SetUp_Animation(Engine::_int iIndex); void SetPlay_Animation(bool bPlay) { bPlayAnimation = bPlay; } void SetUp_PlaySpeed(float fPlaySpeed) { m_fPlayrSpeed = fPlaySpeed; } private: HRESULT Add_Component(void); void Key_Check(const Engine::_float& fTimeDelta); void SetUp_OnTerrain(void); Engine::_vec3 PickUp_OnTerrain(void); private: Engine::CTransform* m_pTransCom = nullptr; Engine::CDynamicMesh* m_pMeshCom = nullptr; Engine::CRenderer* m_pRendererCom = nullptr; Engine::CCalculator* m_pCalculatorCom = nullptr; Engine::CCollider* m_pColliderCom = nullptr; Engine::CCubeTex* m_pColBuffer = nullptr; Engine::CNaviMesh* m_pNaviMeshCom = nullptr; bool bPlayAnimation = false; float m_fPlayrSpeed = 0.f; public: static CPlayer* Create(LPDIRECT3DDEVICE9 pGraphicDev); private: virtual void Free(void); }; #endif // Player_h__
[ "mnopw2@naver.com" ]
mnopw2@naver.com
4650252f13bb02298b31aed14b3e79810a084439
ae6f7442a4f6218a0a58efaa3b91dc4eb55a120c
/source/mfs-painters/multiframepainter/GIStage.h
549c0ab64ef4614ad823afc6bf9e962d20a186de
[ "MIT" ]
permissive
karyon/multiframesampling
5450a2dd89fc422b14b0da9649d6bf726cb9973f
5480dce4d0af4d99506e06849094ca617959ddb4
refs/heads/master
2021-01-21T18:21:23.760461
2016-12-15T10:33:03
2016-12-15T10:33:58
56,600,066
0
0
null
2016-04-19T13:40:42
2016-04-19T13:40:42
null
UTF-8
C++
false
false
2,768
h
#include <memory> #include <glm/glm.hpp> #include <globjects/base/ref_ptr.h> #include "RasterizationStage.h" #include "ModelLoadingStage.h" namespace globjects { class Program; class Framebuffer; class Texture; } namespace gloperate { class ScreenAlignedQuad; class OrthographicProjectionCapability; class AbstractViewportCapability; class AbstractCameraCapability; } class ImperfectShadowmap; class ModelLoadingStage; class VPLProcessor; class ClusteredShading; class GIStage { public: GIStage(ModelLoadingStage& modelLoadingStage, KernelGenerationStage& kernelGenerationStage); ~GIStage(); void initProperties(MultiFramePainter& painter); void initialize(); void process(); globjects::ref_ptr<globjects::Texture> faceNormalBuffer; globjects::ref_ptr<globjects::Texture> depthBuffer; globjects::ref_ptr<globjects::Texture> giBuffer; globjects::ref_ptr<globjects::Texture> giBlurTempBuffer; globjects::ref_ptr<globjects::Texture> giBlurFinalBuffer; std::unique_ptr<ImperfectShadowmap> ism; std::unique_ptr<VPLProcessor> vplProcessor; std::unique_ptr<ClusteredShading> clusteredShading; glm::vec3 lightPosition; glm::vec3 lightDirection; float lightIntensity; std::unique_ptr<RasterizationStage> rsmRenderer; gloperate::AbstractViewportCapability * viewport; gloperate::AbstractProjectionCapability * projection; gloperate::AbstractCameraCapability * camera; ModelLoadingStage& modelLoadingStage; protected: void render(); void blur(); void rebuildGIShader(); void rebuildBlurShaders(); void resizeTexture(int width, int height); globjects::ref_ptr<globjects::Framebuffer> m_fbo; globjects::ref_ptr<globjects::Framebuffer> m_blurTempFbo; globjects::ref_ptr<globjects::Framebuffer> m_blurFinalFbo; globjects::ref_ptr<globjects::Program> m_giProgram; globjects::ref_ptr<gloperate::ScreenAlignedQuad> m_blurXScreenAlignedQuad; globjects::ref_ptr<gloperate::ScreenAlignedQuad> m_blurYScreenAlignedQuad; std::unique_ptr<gloperate::OrthographicProjectionCapability> m_lightProjection; std::unique_ptr<gloperate::AbstractViewportCapability> m_lightViewport; std::unique_ptr<gloperate::AbstractCameraCapability> m_lightCamera; float giIntensityFactor; float vplClampingValue; int vplStartIndex; int vplEndIndex; bool scaleISMs; bool pointsOnlyIntoScaledISMs; float tessLevelFactor; bool usePushPull; bool enableShadowing; float sunCyclePosition; float sunCycleSpeed; bool moveLight; bool showVPLPositions; bool useInterleaving; bool shuffleLights; bool giShaderRebuildRequired; bool blurShaderRebuildRequired; };
[ "johannes.linke@posteo.de" ]
johannes.linke@posteo.de
b57a613fa12d07d46e220a2c85ed6b90d1bcfc00
fdc1525935154cef9a86b6f472aa727fe6787922
/686A.cpp
a18fa1c5865ac925074efef88c94e94af4d4e380
[]
no_license
starizwan/codeforces-riz
852f6a6817142df9de73cc2483fc37e09b1ec302
03cfc7432f54e3489bc026dbdf08de0f6787e534
refs/heads/main
2023-06-16T07:08:07.694954
2021-07-13T04:15:51
2021-07-13T04:15:51
370,784,898
0
0
null
null
null
null
UTF-8
C++
false
false
344
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, t, d = 0; long long int p; char ch; cin >> n >> p; for (int i = 0; i < n; ++i) { cin >> ch; cin >> t; if (ch == '-') { if (p-t >= 0) { p -= t; } else { d++; } } else if (ch == '+') { p += t; } } cout << p << " " << d << "\n"; return 0; }
[ "noreply@github.com" ]
noreply@github.com
5aa0d98b01216f70f05e1d0ec11b9001517bed18
09ddd2df75bce4df9e413d3c8fdfddb7c69032b4
/include/LFC/.svn/text-base/Certificate.h.svn-base
1d7a9da51ad3de4e716518f43b271d17880917df
[]
no_license
sigurdle/FirstProject2
be22e4824da8cd2cb5047762478050a04a4ac63b
dee78c62a1b95e55fcdf3bf2a9bc79c69705bf94
refs/heads/master
2021-01-16T18:45:41.042140
2020-08-18T16:57:13
2020-08-18T16:57:13
3,554,336
6
5
null
null
null
null
UTF-8
C++
false
false
205
namespace System { namespace Security { LFCEXT void ReadCertificate(IO::Stream& stream); LFCEXT void ReadTBSCertificate(IO::Stream& stream); LFCEXT void ReadAlgorithmIdentifier(IO::Stream& stream); } }
[ "sigurd.lerstad@gmail.com" ]
sigurd.lerstad@gmail.com
cd6127d8735c898fa84adc9bb952276206efe2f6
c4e5ca1e5488e9567dde44ba57b992786c18de8b
/src/test/bip32_tests.cpp
703492aa089e3ac3ba87d2f2090f7d92c4407f5c
[ "MIT" ]
permissive
stannumcoin/stannum
5a59eb83cb872102ae311b2b5832413f44de47bd
da0939d263f8ddabe78101e4d58ab0ab966f5c7d
refs/heads/master
2021-04-03T09:07:57.488943
2018-03-12T11:37:31
2018-03-12T11:37:31
124,705,449
2
5
null
null
null
null
UTF-8
C++
false
false
5,927
cpp
// Copyright (c) 2013-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/test/unit_test.hpp> #include "base58.h" #include "key.h" #include "uint256.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_stannum.h" #include <string> #include <vector> struct TestDerivation { std::string pub; std::string prv; unsigned int nChild; }; struct TestVector { std::string strHexMaster; std::vector<TestDerivation> vDerive; TestVector(std::string strHexMasterIn) : strHexMaster(strHexMasterIn) {} TestVector& operator()(std::string pub, std::string prv, unsigned int nChild) { vDerive.push_back(TestDerivation()); TestDerivation &der = vDerive.back(); der.pub = pub; der.prv = prv; der.nChild = nChild; return *this; } }; TestVector test1 = TestVector("000102030405060708090a0b0c0d0e0f") ("xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8", "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi", 0x80000000) ("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw", "xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7", 1) ("xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ", "xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs", 0x80000002) ("xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5", "xprv9z4pot5VBttmtdRTWfWQmoH1taj2axGVzFqSb8C9xaxKymcFzXBDptWmT7FwuEzG3ryjH4ktypQSAewRiNMjANTtpgP4mLTj34bhnZX7UiM", 2) ("xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV", "xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334", 1000000000) ("xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy", "xprvA41z7zogVVwxVSgdKUHDy1SKmdb533PjDz7J6N6mV6uS3ze1ai8FHa8kmHScGpWmj4WggLyQjgPie1rFSruoUihUZREPSL39UNdE3BBDu76", 0); TestVector test2 = TestVector("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542") ("xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB", "xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U", 0) ("xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH", "xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt", 0xFFFFFFFF) ("xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a", "xprv9wSp6B7kry3Vj9m1zSnLvN3xH8RdsPP1Mh7fAaR7aRLcQMKTR2vidYEeEg2mUCTAwCd6vnxVrcjfy2kRgVsFawNzmjuHc2YmYRmagcEPdU9", 1) ("xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon", "xprv9zFnWC6h2cLgpmSA46vutJzBcfJ8yaJGg8cX1e5StJh45BBciYTRXSd25UEPVuesF9yog62tGAQtHjXajPPdbRCHuWS6T8XA2ECKADdw4Ef", 0xFFFFFFFE) ("xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL", "xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc", 2) ("xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt", "xprvA2nrNbFZABcdryreWet9Ea4LvTJcGsqrMzxHx98MMrotbir7yrKCEXw7nadnHM8Dq38EGfSh6dqA9QWTyefMLEcBYJUuekgW4BYPJcr9E7j", 0); void RunTest(const TestVector &test) { std::vector<unsigned char> seed = ParseHex(test.strHexMaster); CExtKey key; CExtPubKey pubkey; key.SetMaster(&seed[0], seed.size()); pubkey = key.Neuter(); BOOST_FOREACH(const TestDerivation &derive, test.vDerive) { unsigned char data[74]; key.Encode(data); pubkey.Encode(data); // Test private key CBitcoinExtKey b58key; b58key.SetKey(key); BOOST_CHECK(b58key.ToString() == derive.prv); CBitcoinExtKey b58keyDecodeCheck(derive.prv); CExtKey checkKey = b58keyDecodeCheck.GetKey(); assert(checkKey == key); //ensure a base58 decoded key also matches // Test public key CBitcoinExtPubKey b58pubkey; b58pubkey.SetKey(pubkey); BOOST_CHECK(b58pubkey.ToString() == derive.pub); CBitcoinExtPubKey b58PubkeyDecodeCheck(derive.pub); CExtPubKey checkPubKey = b58PubkeyDecodeCheck.GetKey(); assert(checkPubKey == pubkey); //ensure a base58 decoded pubkey also matches // Derive new keys CExtKey keyNew; BOOST_CHECK(key.Derive(keyNew, derive.nChild)); CExtPubKey pubkeyNew = keyNew.Neuter(); if (!(derive.nChild & 0x80000000)) { // Compare with public derivation CExtPubKey pubkeyNew2; BOOST_CHECK(pubkey.Derive(pubkeyNew2, derive.nChild)); BOOST_CHECK(pubkeyNew == pubkeyNew2); } key = keyNew; pubkey = pubkeyNew; } } BOOST_FIXTURE_TEST_SUITE(bip32_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(bip32_test1) { RunTest(test1); } BOOST_AUTO_TEST_CASE(bip32_test2) { RunTest(test2); } BOOST_AUTO_TEST_SUITE_END()
[ "stannum@gmail.com" ]
stannum@gmail.com
f4bff7b8d563067594543def6be8da4cce92309e
8a6dc8c57cdfe2e8dd728f1ca22462010de7abb5
/src/storage/backend_manager.cpp
aa6ae7ca815589c113594a7d09344236bcf5250d
[ "Apache-2.0" ]
permissive
haojin2/peloton
3999c9620c548ed9b20745ea1a4437476bf26de4
fa7a1199a3e7b6df8123215b3cbee0ff0b664d9d
refs/heads/master
2021-01-13T09:16:55.017936
2018-01-11T19:36:57
2018-01-12T04:36:52
72,457,931
0
0
null
2016-10-31T16:54:57
2016-10-31T16:54:57
null
UTF-8
C++
false
false
15,253
cpp
//===----------------------------------------------------------------------===// // // Peloton // // backend_manager.cpp // // Identification: src/storage/backend_manager.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cpuid.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <iostream> #include <string> #include "common/exception.h" #include "common/logger.h" #include "common/macros.h" #include "common/internal_types.h" // #include "logging/logging_util.h" #include "storage/backend_manager.h" //===--------------------------------------------------------------------===// // GUC Variables //===--------------------------------------------------------------------===// // // Logging mode // extern peloton::LoggingType peloton_logging_mode; // // Flush mode (for NVM WBL) // extern int peloton_flush_mode; // // PCOMMIT latency (for NVM WBL) // extern int peloton_pcommit_latency; // PMEM file size size_t peloton_data_file_size = 0; namespace peloton { namespace storage { //===--------------------------------------------------------------------===// // INSTRUCTIONS //===--------------------------------------------------------------------===// // Source : https://github.com/pmem/nvml/blob/master/src/libpmem/pmem.c // 64B cache line size #define FLUSH_ALIGN ((uintptr_t)64) #define EAX_IDX 0 #define EBX_IDX 1 #define ECX_IDX 2 #define EDX_IDX 3 #ifndef bit_CLFLUSH #define bit_CLFLUSH (1 << 23) #endif #ifndef bit_PCOMMIT #define bit_PCOMMIT (1 << 22) #endif #ifndef bit_CLFLUSHOPT #define bit_CLFLUSHOPT (1 << 23) #endif #ifndef bit_CLWB #define bit_CLWB (1 << 24) #endif /* * The x86 memory instructions are new enough that the compiler * intrinsic functions are not always available. The intrinsic * functions are defined here in terms of asm statements for now. */ #define _mm_clflushopt(addr) \ asm volatile(".byte 0x66; clflush %0" : "+m"(*(volatile char *)addr)); #define _mm_clwb(addr) \ asm volatile(".byte 0x66; xsaveopt %0" : "+m"(*(volatile char *)addr)); #define _mm_pcommit() asm volatile(".byte 0x66, 0x0f, 0xae, 0xf8"); //===--------------------------------------------------------------------===// // CPU CHECK //===--------------------------------------------------------------------===// static inline void cpuid(unsigned func, unsigned subfunc, unsigned cpuinfo[4]) { __cpuid_count(func, subfunc, cpuinfo[EAX_IDX], cpuinfo[EBX_IDX], cpuinfo[ECX_IDX], cpuinfo[EDX_IDX]); } /* * is_cpu_genuine_intel -- checks for genuine Intel CPU */ int is_cpu_genuine_intel(void) { unsigned cpuinfo[4] = {0}; union { char name[0x20]; unsigned cpuinfo[3]; } vendor; PL_MEMSET(&vendor, 0, sizeof(vendor)); cpuid(0x0, 0x0, cpuinfo); vendor.cpuinfo[0] = cpuinfo[EBX_IDX]; vendor.cpuinfo[1] = cpuinfo[EDX_IDX]; vendor.cpuinfo[2] = cpuinfo[ECX_IDX]; return (strncmp(vendor.name, "GenuineIntel", sizeof(vendor.name))) == 0; } //===--------------------------------------------------------------------===// // INSTRUCTION CHECKS //===--------------------------------------------------------------------===// /* * is_cpu_clflush_present -- checks if CLFLUSH instruction is supported */ int is_cpu_clflush_present(void) { unsigned cpuinfo[4] = {0}; cpuid(0x1, 0x0, cpuinfo); int ret = (cpuinfo[EDX_IDX] & bit_CLFLUSH) != 0; return ret; } /* * is_cpu_clwb_present -- checks if CLWB instruction is supported */ int is_cpu_clwb_present(void) { unsigned cpuinfo[4] = {0}; if (!is_cpu_genuine_intel()) return 0; cpuid(0x7, 0x0, cpuinfo); int ret = (cpuinfo[EBX_IDX] & bit_CLWB) != 0; return ret; } /* * is_cpu_pcommit_present -- checks if PCOMMIT instruction is supported */ int is_cpu_pcommit_present(void) { unsigned cpuinfo[4] = {0}; if (!is_cpu_genuine_intel()) return 0; cpuid(0x7, 0x0, cpuinfo); int ret = (cpuinfo[EBX_IDX] & bit_PCOMMIT) != 0; return ret; } //===--------------------------------------------------------------------===// // FLUSH FUNCTIONS //===--------------------------------------------------------------------===// /* * flush_clflush -- (internal) flush the CPU cache, using clflush */ static inline void flush_clflush(const void *addr, size_t len) { uintptr_t uptr; // Loop through cache-line-size (typically 64B) aligned chunks // covering the given range. for (uptr = (uintptr_t)addr & ~(FLUSH_ALIGN - 1); uptr < (uintptr_t)addr + len; uptr += FLUSH_ALIGN) _mm_clflush((char *)uptr); } // // flush_clwb -- (internal) flush the CPU cache, using clwb // static inline void flush_clwb(const void *addr, size_t len) { // uintptr_t uptr; // // Loop through cache-line-size (typically 64B) aligned chunks // // covering the given range. // for (uptr = (uintptr_t)addr & ~(FLUSH_ALIGN - 1); // uptr < (uintptr_t)addr + len; uptr += FLUSH_ALIGN) { // _mm_clwb((char *)uptr); // } // } /* * pmem_flush() calls through Func_flush to do the work. Although * initialized to flush_clflush(), once the existence of the clflushopt * feature is confirmed by pmem_init() at library initialization time, * Func_flush is set to flush_clflushopt(). That's the most common case * on modern hardware that supports persistent memory. */ static void (*Func_flush)(const void *, size_t) = flush_clflush; // //===--------------------------------------------------------------------===// // // PREDRAIN FUNCTIONS // //===--------------------------------------------------------------------===// /* * predrain_fence_empty -- (internal) issue the pre-drain fence instruction */ static void predrain_fence_empty(void) { /* nothing to do (because CLFLUSH did it for us) */ } // /* // * predrain_fence_sfence -- (internal) issue the pre-drain fence instruction // */ // static void predrain_fence_sfence(void) { // _mm_sfence(); /* ensure CLWB or CLFLUSHOPT completes before PCOMMIT */ // } // * pmem_drain() calls through Func_predrain_fence to do the fence. Although // * initialized to predrain_fence_empty(), once the existence of the CLWB or // * CLFLUSHOPT feature is confirmed by pmem_init() at library initialization // * time, Func_predrain_fence is set to predrain_fence_sfence(). That's the // * most common case on modern hardware that supports persistent memory. static void (*Func_predrain_fence)(void) = predrain_fence_empty; // //===--------------------------------------------------------------------===// // // DRAIN FUNCTIONS // //===--------------------------------------------------------------------===// /* * drain_no_pcommit -- (internal) wait for PM stores to drain, empty version */ static void drain_no_pcommit(void) { Func_predrain_fence(); /* caller assumed responsibility for the rest */ } // // PCOMMIT helpers // #define CPU_FREQ_MHZ (2593) // static inline unsigned long read_tsc(void) { // unsigned long var; // unsigned int hi, lo; // asm volatile("rdtsc" : "=a"(lo), "=d"(hi)); // var = ((unsigned long long int)hi << 32) | lo; // return var; // } // static inline void cpu_pause() { __asm__ volatile("pause" ::: "memory"); } // static inline void pcommit(unsigned long lat) { // // Special case // if (lat == 0) return; // unsigned long etsc = read_tsc() + (unsigned long)(lat * CPU_FREQ_MHZ / // 1000); // while (read_tsc() < etsc) { // cpu_pause(); // } // } // /* // * drain_pcommit -- (internal) wait for PM stores to drain, pcommit version // */ // static void drain_pcommit(void) { // Func_predrain_fence(); // // pause if needed // pcommit(peloton_pcommit_latency); // // by default, this is zero // if (peloton_pcommit_latency == 0) { // _mm_pcommit(); // _mm_sfence(); // } // } /* * pmem_drain() calls through Func_drain to do the work. Although * initialized to drain_no_pcommit(), once the existence of the pcommit * feature is confirmed by pmem_init() at library initialization time, * Func_drain is set to drain_pcommit(). That's the most common case * on modern hardware that supports persistent memory. */ static void (*Func_drain)(void) = drain_no_pcommit; //===--------------------------------------------------------------------===// // STORAGE MANAGER //===--------------------------------------------------------------------===// #define DATA_FILE_LEN 1024 * 1024 * UINT64_C(512) // 512 MB #define DATA_FILE_NAME "peloton.pmem" // global singleton BackendManager &BackendManager::GetInstance(void) { static BackendManager backend_manager; return backend_manager; } BackendManager::BackendManager() : data_file_address(nullptr), data_file_len(0), data_file_offset(0) { // // Check if we need a data pool // if (logging::LoggingUtil::IsBasedOnWriteAheadLogging(peloton_logging_mode) // == // true || // peloton_logging_mode == LoggingType::INVALID) { // return; // } // // Check for instruction availability and flush mode // // (1 -- clflush or 2 -- clwb) // if (is_cpu_clwb_present() && peloton_flush_mode == 2) { // LOG_TRACE("Found clwb \n"); // Func_flush = flush_clwb; // Func_predrain_fence = predrain_fence_sfence; // } // if (is_cpu_pcommit_present()) { // LOG_TRACE("Found pcommit \n"); // Func_drain = drain_pcommit; // } // // Rest of this stuff is needed only for Write Behind Logging // int data_fd; // std::string data_file_name; // struct stat data_stat; // // Initialize file size // if (peloton_data_file_size != 0) // data_file_len = peloton_data_file_size * 1024 * 1024; // MB // else // data_file_len = DATA_FILE_LEN; // // Check for relevant file system // bool found_file_system = false; // switch (peloton_logging_mode) { // // Check for NVM FS for data // case LoggingType::NVM_WBL: { // int status = stat(NVM_DIR, &data_stat); // if (status == 0 && S_ISDIR(data_stat.st_mode)) { // data_file_name = std::string(NVM_DIR) + std::string(DATA_FILE_NAME); // found_file_system = true; // } // } break; // // Check for SSD FS for data // case LoggingType::SSD_WBL: { // int status = stat(SSD_DIR, &data_stat); // if (status == 0 && S_ISDIR(data_stat.st_mode)) { // data_file_name = std::string(SSD_DIR) + std::string(DATA_FILE_NAME); // found_file_system = true; // } // } break; // // Check for HDD FS // case LoggingType::HDD_WBL: { // int status = stat(HDD_DIR, &data_stat); // if (status == 0 && S_ISDIR(data_stat.st_mode)) { // data_file_name = std::string(HDD_DIR) + std::string(DATA_FILE_NAME); // found_file_system = true; // } // } break; // default: // break; // } // // Fallback to tmp directory if needed // if (found_file_system == false) { // int status = stat(TMP_DIR, &data_stat); // if (status == 0 && S_ISDIR(data_stat.st_mode)) { // data_file_name = std::string(TMP_DIR) + std::string(DATA_FILE_NAME); // } else { // throw Exception("Could not find temp directory : " + // std::string(TMP_DIR)); // } // } // LOG_TRACE("DATA DIR :: %s ", data_file_name.c_str()); // // Create a data file // if ((data_fd = open( // data_file_name.c_str(), O_CREAT | O_TRUNC | O_RDWR, // S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) < 0) { // perror(data_file_name.c_str()); // exit(EXIT_FAILURE); // } // // Allocate the data file // if ((errno = posix_fallocate(data_fd, 0, data_file_len)) != 0) { // perror("posix_fallocate"); // exit(EXIT_FAILURE); // } // // map the data file in memory // if ((data_file_address = mmap(NULL, data_file_len, PROT_READ | PROT_WRITE, // MAP_SHARED, data_fd, 0)) == MAP_FAILED) { // perror("mmap"); // exit(EXIT_FAILURE); // } // // close the pmem file -- it will remain mapped // close(data_fd); } BackendManager::~BackendManager() { LOG_TRACE("Allocation count : %ld \n", allocation_count); // // Check if we need a PMEM pool // if (peloton_logging_mode != LoggingType::NVM_WBL) return; // // sync and unmap the data file // if (data_file_address != nullptr) { // // sync the mmap'ed file to SSD or HDD // int status = msync(data_file_address, data_file_len, MS_SYNC); // if (status != 0) { // perror("msync"); // exit(EXIT_FAILURE); // } // if (munmap(data_file_address, data_file_len)) { // perror("munmap"); // exit(EXIT_FAILURE); // } // } } void *BackendManager::Allocate(BackendType type, size_t size) { // Update allocation count allocation_count++; switch (type) { case BackendType::MM: case BackendType::NVM: { return ::operator new(size); } break; case BackendType::SSD: case BackendType::HDD: { { size_t cache_data_file_offset = 0; // Lock the file data_file_spinlock.Lock(); // Check if within bounds if (data_file_offset < data_file_len) { cache_data_file_offset = data_file_offset; // Offset by the requested size data_file_offset += size; // Unlock the file data_file_spinlock.Unlock(); void *address = reinterpret_cast<char *>(data_file_address) + cache_data_file_offset; return address; } data_file_spinlock.Unlock(); throw Exception("no more memory available: offset : " + std::to_string(data_file_offset) + " length : " + std::to_string(data_file_len)); return nullptr; } } break; case BackendType::INVALID: default: { throw Exception("invalid backend: " + std::to_string(data_file_len)); return nullptr; } } } void BackendManager::Release(BackendType type, void *address) { switch (type) { case BackendType::MM: case BackendType::NVM: { ::operator delete(address); } break; case BackendType::SSD: case BackendType::HDD: { // Nothing to do here } break; case BackendType::INVALID: default: { // Nothing to do here break; } } } void BackendManager::Sync(BackendType type, void *address, size_t length) { switch (type) { case BackendType::MM: { // Nothing to do here } break; case BackendType::NVM: { // flush writes to NVM Func_flush(address, length); Func_drain(); clflush_count++; } break; case BackendType::SSD: case BackendType::HDD: { // sync the mmap'ed file to SSD or HDD int status = msync(data_file_address, data_file_len, MS_SYNC); if (status != 0) { perror("msync"); exit(EXIT_FAILURE); } msync_count++; } break; case BackendType::INVALID: default: { // Nothing to do here } break; } } } // namespace storage } // namespace peloton
[ "pavlo@cs.brown.edu" ]
pavlo@cs.brown.edu
3db31631b35855221dc4bd97ec5da61a0d9517e6
08a3622a4ae7f32b5dec5b8eadfce82dbf55b004
/d4/d4.cpp
3039dc88ccad93cd3e0af850acabcb82374201f5
[]
no_license
iamlockon/AoC_2019
fb4e747b9f1a092d0688d07c7b4ef96224d98a1f
15a210df24cc868524fd9d75414e4cb440a1e99a
refs/heads/master
2020-11-24T06:59:15.784841
2020-02-14T14:45:31
2020-02-14T14:45:31
228,019,853
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
cpp
#include <iostream> #include <string> using namespace std; bool isValid(const int i) { bool twoAdj = false; string s = to_string(i); for (int j = 0; j < s.size() - 1; j++) { if (s[j] == s[j+1]) twoAdj = true; if (s[j] > s[j+1]) return false; } return twoAdj; } bool isValid2(const int i) { bool onlyTwoAdj = false; string s = to_string(i); int j = 0; while (j < s.size() - 1) { int repeat = 0; while (s[j] == s[j+1]) { repeat++; j++; } if (repeat == 1) { onlyTwoAdj = true; } if (j+1 < s.size() && s[j] > s[j+1]) return false; j++; } return onlyTwoAdj; } void part1(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { if (isValid(i)) count++; } cout << "Ans to part1 is :" << count << endl; } void part2(int start, int end) { int count = 0; for (int i = start; i <= end; i++) { if (isValid2(i)) count++; } cout << "Ans to part2 is :" << count << endl; } int main() { int start = 234208; int end = 765869; part1(start, end); part2(start, end); return 0; }
[ "xdddxyyyxzzz123@gmail.com" ]
xdddxyyyxzzz123@gmail.com
e1ddf25ddfbf0d9e3da846f37e2f11cb657ca956
11b9bbc75a702fdd932b28efa3ac1cdd124703b2
/source/MarkovRandomFieldRegistrationFusion/Legacy/Registration-Propagation-Indirect-Statismo.h
39178c9eaadaf54826dcb87aca3f34fbfab2ff44
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
heartvalve/ETH-SegReg
687f8cdfe6b3a47f5d5e2422b88359a003b8d7c5
2ef5a785e302b40eb6b513ae9bd559b762fb0ab2
refs/heads/master
2021-01-17T23:05:36.068781
2015-09-04T14:19:35
2015-09-04T14:19:35
41,906,592
0
0
null
2015-09-04T08:58:38
2015-09-04T08:58:38
null
UTF-8
C++
false
false
26,448
h
#pragma once #include <stdio.h> #include <iostream> #include "ArgumentParser.h" #include "Log.h" #include <vector> #include <map> #include "itkImageRegionIterator.h" #include "TransformationUtils.h" #include "ImageUtils.h" #include "FilterUtils.hpp" #include <sstream> #include "ArgumentParser.h" #include <fstream> #include <sys/stat.h> #include <sys/types.h> #include "itkConstNeighborhoodIterator.h" #include "itkDisplacementFieldTransform.h" #include "itkNormalizedCorrelationImageToImageMetric.h" #include "itkMeanSquaresImageToImageMetric.h" #include "itkMattesMutualInformationImageToImageMetric.h" #include "itkNormalizedMutualInformationHistogramImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include <itkAddImageFilter.h> #include "itkGaussianImage.h" #include "itkVectorImageRepresenter.h" #include "itkImageRepresenter.h" #include "statismo_ITK/itkStatisticalModel.h" #include "statismo_ITK/itkPCAModelBuilder.h" #include "statismo_ITK/itkDataManager.h" #include "statismo_ITK/itkStatisticalDeformationModelTransform.h" #include "itkImageRegistrationMethod.h" #include "itkLBFGSOptimizer.h" #include "itkLBFGSBOptimizer.h" #include "itkPowellOptimizer.h" using namespace std; template <class ImageType> class RegistrationPropagationIndirectStatismo{ public: typedef typename ImageType::PixelType PixelType; static const unsigned int D=ImageType::ImageDimension; typedef typename ImageType::Pointer ImagePointerType; typedef typename ImageType::IndexType IndexType; typedef typename ImageType::PointType PointType; typedef typename ImageType::OffsetType OffsetType; typedef typename ImageType::SizeType SizeType; typedef typename ImageType::ConstPointer ImageConstPointerType; typedef typename ImageUtils<ImageType>::FloatImageType FloatImageType; typedef typename FloatImageType::Pointer FloatImagePointerType; typedef typename TransfUtils<ImageType>::DisplacementType DisplacementType; typedef typename TransfUtils<ImageType>::DeformationFieldType DeformationFieldType; typedef typename DeformationFieldType::Pointer DeformationFieldPointerType; typedef typename itk::ImageRegionIterator<ImageType> ImageIteratorType; typedef typename itk::ImageRegionIterator<FloatImageType> FloatImageIteratorType; typedef typename itk::ImageRegionIterator<DeformationFieldType> DeformationIteratorType; typedef typename itk::ConstNeighborhoodIterator<ImageType> ImageNeighborhoodIteratorType; typedef ImageNeighborhoodIteratorType * ImageNeighborhoodIteratorPointerType; typedef typename ImageNeighborhoodIteratorType::RadiusType RadiusType; typedef itk::VectorImageRepresenter<float, D, D> RepresenterType; typedef itk::PCAModelBuilder<RepresenterType> ModelBuilderType; typedef itk::StatisticalModel<RepresenterType> StatisticalModelType; typedef itk::DataManager<RepresenterType> DataManagerType; typedef itk::NormalizedCorrelationImageToImageMetric<ImageType, ImageType> MetricType; typedef typename itk::StatisticalDeformationModelTransform<RepresenterType, double, D> TransformType; typedef itk::LinearInterpolateImageFunction<ImageType, double> InterpolatorType; typedef itk::ImageRegistrationMethod<ImageType, ImageType> RegistrationFilterType; typedef itk::LBFGSOptimizer OptimizerType; //typedef itk::LBFGSBOptimizer OptimizerType; //typedef itk::PowellOptimizer OptimizerType; //enum MetricType {NONE,MAD,NCC,MI,NMI,MSD}; enum WeightingType {UNIFORM,GLOBAL,LOCAL}; protected: double m_sigma; RadiusType m_patchRadius; public: int run(int argc, char ** argv){ feenableexcept(FE_INVALID|FE_DIVBYZERO|FE_OVERFLOW); ArgumentParser * as=new ArgumentParser(argc,argv); string trueDefListFilename="",deformationFileList,imageFileList,atlasSegmentationFileList,supportSamplesListFileName="",outputDir=".",outputSuffix="",weightListFilename=""; int verbose=0; double pWeight=1.0; int radius=3; int maxHops=1; bool uniformUpdate=true; string metricName="NCC"; string weightingName="uniform"; bool lateFusion=false; bool dontCacheDeformations=false; bool graphCut=false; double smoothness=1.0; double alpha=0.5; m_sigma=30; bool gaussianReweight=false; //as->parameter ("A",atlasSegmentationFileList , "list of atlas segmentations <id> <file>", true); as->parameter ("T", deformationFileList, " list of deformations", true); as->parameter ("i", imageFileList, " list of images", true); as->parameter ("true", trueDefListFilename, " list of TRUE deformations", false); //as->parameter ("W", weightListFilename,"list of weights for deformations",false); //as->parameter ("metric", metricName,"metric to be used for global or local weighting, valid: NONE,SAD,MSD,NCC,MI,NMI",false); //as->parameter ("weighting", weightingName,"internal weighting scheme {uniform,local,global}. non-uniform will only work with metric != NONE",false); as->parameter ("s", m_sigma,"sigma for exp(- metric/sigma)",false); //as->parameter ("radius", radius,"patch radius for local metrics",false); as->parameter ("O", outputDir,"outputdirectory (will be created + no overwrite checks!)",false); //as->parameter ("radius", radius,"patch radius for NCC",false); as->parameter ("maxHops", maxHops,"maximum number of hops",false); as->parameter ("alpha", alpha,"update rate",false); as->option ("lateFusion", lateFusion,"fuse segmentations late. maxHops=1"); as->option ("dontCacheDeformations", dontCacheDeformations,"read deformations only when needed to save memory. higher IO load!"); as->option ("gaussianReweight", gaussianReweight,"Use reweighted mean for reconstruction"); // as->option ("graphCut", graphCut,"use graph cuts to generate final segmentations instead of locally maximizing"); //as->parameter ("smoothness", smoothness,"smoothness parameter of graph cut optimizer",false); as->parameter ("verbose", verbose,"get verbose output",false); as->help(); as->parse(); //late fusion is only well defined for maximal 1 hop. //it requires to explicitly compute all n!/(n-nHops) deformation paths to each image and is therefore infeasible for nHops>1 //also strange to implement if (lateFusion) maxHops==min(maxHops,1); for (unsigned int i = 0; i < ImageType::ImageDimension; ++i) m_patchRadius[i] = radius; mkdir(outputDir.c_str(),0755); logSetStage("IO"); logSetVerbosity(verbose); WeightingType weighting; map<string,ImagePointerType> *inputImages; typedef typename map<string, ImagePointerType>::iterator ImageListIteratorType; LOG<<"Reading input images."<<endl; inputImages = readImageList( imageFileList ); int nImages = inputImages->size(); LOGV(2)<<VAR(m_sigma)<<" "<<VAR(lateFusion)<<" "<<VAR(m_patchRadius)<<endl; if (dontCacheDeformations){ LOG<<"Reading deformation file names."<<endl; }else{ LOG<<"CACHING all deformations!"<<endl; } map< string, map <string, DeformationFieldPointerType> > deformationCache, trueDeformations; map< string, map <string, string> > deformationFilenames; map<string, map<string, float> > globalWeights; { ifstream ifs(deformationFileList.c_str()); while (!ifs.eof()){ string intermediateID,targetID,defFileName; ifs >> intermediateID; if (intermediateID!=""){ ifs >> targetID; ifs >> defFileName; if (inputImages->find(intermediateID)==inputImages->end() || inputImages->find(targetID)==inputImages->end() ){ LOG<<intermediateID<<" or "<<targetID<<" not in image database, skipping"<<endl; //exit(0); }else{ if (!dontCacheDeformations){ LOGV(3)<<"Reading deformation "<<defFileName<<" for deforming "<<intermediateID<<" to "<<targetID<<endl; deformationCache[intermediateID][targetID]=ImageUtils<DeformationFieldType>::readImage(defFileName); globalWeights[intermediateID][targetID]=1.0; }else{ LOGV(3)<<"Reading filename "<<defFileName<<" for deforming "<<intermediateID<<" to "<<targetID<<endl; deformationFilenames[intermediateID][targetID]=defFileName; globalWeights[intermediateID][targetID]=1.0; } } } } } if (trueDefListFilename!=""){ ifstream ifs(trueDefListFilename.c_str()); while (!ifs.eof()){ string intermediateID,targetID,defFileName; ifs >> intermediateID; if (intermediateID!=""){ ifs >> targetID; ifs >> defFileName; if (inputImages->find(intermediateID)==inputImages->end() || inputImages->find(targetID)==inputImages->end() ){ LOG<<intermediateID<<" or "<<targetID<<" not in image database, skipping"<<endl; //exit(0); }else{ if (!dontCacheDeformations){ LOGV(3)<<"Reading TRUE deformation "<<defFileName<<" for deforming "<<intermediateID<<" to "<<targetID<<endl; trueDeformations[intermediateID][targetID]=ImageUtils<DeformationFieldType>::readImage(defFileName); }else{ LOG<<"error, not caching true defs not implemented"<<endl; exit(0); } } } } } if (weightListFilename!=""){ ifstream ifs(weightListFilename.c_str()); while (!ifs.eof()){ string intermediateID,targetID; ifs >> intermediateID; ifs >> targetID; if (inputImages->find(intermediateID)==inputImages->end() || inputImages->find(targetID)==inputImages->end() ){ LOG << intermediateID<<" or "<<targetID<<" not in image database while reading weights, skipping"<<endl; }else{ ifs >> globalWeights[intermediateID][targetID]; } } } #define AVERAGE //#define LOCALWEIGHTING logSetStage("Zero Hop"); LOG<<"Computing"<<std::endl; for (int h=0;h<maxHops;++h){ map< string, map <string, DeformationFieldPointerType> > TMPdeformationCache; int circles=0; double globalResidual=0.0; double trueResidual=0.0; for (ImageListIteratorType sourceImageIterator=inputImages->begin();sourceImageIterator!=inputImages->end();++sourceImageIterator){ //iterate over sources string sourceID= sourceImageIterator->first; for (ImageListIteratorType targetImageIterator=inputImages->begin();targetImageIterator!=inputImages->end();++targetImageIterator){ //iterate over targets string targetID= targetImageIterator->first; if (targetID !=sourceID){ DeformationFieldPointerType deformationSourceTarget; if (dontCacheDeformations){ deformationSourceTarget=ImageUtils<DeformationFieldType>::readImage( deformationFilenames[sourceID][targetID]); } else{ deformationSourceTarget = deformationCache[sourceID][targetID]; } //initialize accumulators DeformationFieldPointerType avgIndirectDeformation, trueIndirectDeltaSourceTarget; avgIndirectDeformation=TransfUtils<ImageType>::createEmpty(deformationSourceTarget); trueIndirectDeltaSourceTarget=TransfUtils<ImageType>::createEmpty(deformationSourceTarget); ImagePointerType localCountsIndirect, localCountsTRUEIndirect; typename RepresenterType::Pointer representer = RepresenterType::New(); representer->SetReference(deformationSourceTarget); typename DataManagerType::Pointer dataManager = DataManagerType::New(); dataManager->SetRepresenter(representer); dataManager->AddDataset(deformationSourceTarget,""); int count=0; for (ImageListIteratorType intermediateImageIterator=inputImages->begin();intermediateImageIterator!=inputImages->end();++intermediateImageIterator){ //iterate over intermediates string intermediateID= intermediateImageIterator->first; if (targetID != intermediateID && sourceID!=intermediateID){ LOGV(3)<<VAR(sourceID)<<" "<<VAR(targetID)<<" "<<VAR(intermediateID)<<endl; //get all deformations for full circle DeformationFieldPointerType deformationSourceIntermed; DeformationFieldPointerType deformationIntermedTarget; if (dontCacheDeformations){ deformationSourceIntermed=ImageUtils<DeformationFieldType>::readImage(deformationFilenames[sourceID][intermediateID]); deformationIntermedTarget=ImageUtils<DeformationFieldType>::readImage(deformationFilenames[intermediateID][targetID]); } else{ deformationSourceIntermed = deformationCache[sourceID][intermediateID]; deformationIntermedTarget = deformationCache[intermediateID][targetID]; } //create mask of valid deformation region ImagePointerType mask=ImageType::New(); mask->SetRegions(deformationSourceTarget->GetLargestPossibleRegion()); mask->SetOrigin(deformationSourceTarget->GetOrigin()); mask->SetSpacing(deformationSourceTarget->GetSpacing()); mask->SetDirection(deformationSourceTarget->GetDirection()); mask->Allocate(); mask->FillBuffer(1); //compute indirect path DeformationFieldPointerType sourceTargetIndirect=TransfUtils<ImageType>::composeDeformations(deformationIntermedTarget,deformationSourceIntermed); //add to accumulator dataManager->AddDataset(sourceTargetIndirect,""); count++; circles++; }//if }//intermediate image LOGV(1)<<"Building PCA model"<<endl; typename ModelBuilderType::Pointer pcaModelBuilder = ModelBuilderType::New(); typename StatisticalModelType::Pointer model = pcaModelBuilder->BuildNewModel(dataManager->GetSampleData(), 0); LOGV(1)<<"done, now fitting model to data"<<endl; typename TransformType::Pointer transform = TransformType::New(); transform->SetStatisticalModel(model); transform->SetIdentity(); // Setting up the fitting typename OptimizerType::Pointer optimizer = OptimizerType::New(); optimizer->MinimizeOn(); //optimizer->MaximizeOff(); //optimizer->SetMaximumNumberOfFunctionEvaluations(100); typename MetricType::Pointer metric = MetricType::New(); typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); typename RegistrationFilterType::Pointer registration = RegistrationFilterType::New(); registration->SetInitialTransformParameters(transform->GetParameters()); registration->SetMetric(metric); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetInterpolator( interpolator ); registration->SetFixedImage( (*inputImages)[targetID] ); registration->SetFixedImageRegion((*inputImages)[targetID]->GetBufferedRegion() ); // seems to be necessary for the filter to work registration->SetMovingImage( (*inputImages)[sourceID] ); try { registration->Update(); } catch ( itk::ExceptionObject& o ) { std::cout << "caught exception " << o << std::endl; } LOGV(2)<<VAR(transform->GetCoefficients())<<endl; avgIndirectDeformation = model->DrawSample(transform->GetCoefficients()); LOGV(1)<<"done, storing result"<<endl; //store deformation ostringstream tmpSegmentationFilename; tmpSegmentationFilename<<outputDir<<"/registration-from-"<<sourceID<<"-TO-"<<targetID<<"-hop"<<h+1<<".mha"; ImageUtils<DeformationFieldType>::writeImage(tmpSegmentationFilename.str().c_str(),avgIndirectDeformation); if (!dontCacheDeformations){ TMPdeformationCache[sourceID][targetID]=avgIndirectDeformation; } #if 0 //2. compute difference DeformationFieldPointerType deltaNullSourceTarget=TransfUtils<ImageType>::subtract(deformationSourceTarget,avgIndirecDeformation); ostringstream weakEst; weakEst<<outputDir<<"/error-weakEstimate-from-"<<sourceID<<"-TO-"<<targetID<<"-hop"<<h<<".png"; ImageUtils<ImageType>::writeImage(weakEst.str().c_str(),FilterUtils<FloatImageType,ImageType>::truncateCast(TransfUtils<ImageType>::computeLocalDeformationNorm(deltaNullSourceTarget,m_sigma))); #endif //TMPdeformationCache[sourceID][targetID]=avgIndirecDeformation; //globalResidual+=1.0*averageResidual; if (trueDefListFilename!=""){ DeformationFieldPointerType trueErrorSourceTarget=TransfUtils<ImageType>::subtract(deformationCache[sourceID][targetID],trueDeformations[sourceID][targetID]); trueResidual+=TransfUtils<ImageType>::computeDeformationNorm(trueErrorSourceTarget,1); #if 0 ostringstream trueErrorST; trueErrorST<<outputDir<<"/error-TRUE-from-"<<sourceID<<"-TO-"<<targetID<<"-hop"<<h<<".png"; ImageUtils<ImageType>::writeImage(trueErrorST.str().c_str(),FilterUtils<FloatImageType,ImageType>::truncateCast(TransfUtils<ImageType>::computeLocalDeformationNorm(trueErrorSourceTarget,m_sigma))); #endif } }//if }//target images }//source images globalResidual/=circles; trueResidual/=circles; LOG<<VAR(circles)<<" "<<VAR(globalResidual)<<" "<<VAR(trueResidual)<<endl; #if 0 for (ImageListIteratorType sourceImageIterator=inputImages->begin();sourceImageIterator!=inputImages->end();++sourceImageIterator){ //iterate over sources string sourceID= sourceImageIterator->first; for (ImageListIteratorType targetImageIterator=inputImages->begin();targetImageIterator!=inputImages->end();++targetImageIterator){ //iterate over targets string targetID= targetImageIterator->first; if (targetID !=sourceID){ #if 0 ostringstream tmpdeformed; tmpdeformed<<outputDir<<"/deformed-from-"<<sourceID<<"-TO-"<<targetID<<"-hop"<<h<<".png"; ImageUtils<ImageType>::writeImage(tmpdeformed.str().c_str(),TransfUtils<ImageType>::warpImage((*inputImages)[sourceID],deformationCache[sourceID][targetID])); #endif if (!dontCacheDeformations){ deformationCache[sourceID][targetID]= TMPdeformationCache[sourceID][targetID]; } } } } #endif }//hops LOG<<"done"<<endl; LOG<<"done"<<endl; LOG<<"Storing output. and checking convergence"<<endl; for (ImageListIteratorType targetImageIterator=inputImages->begin();targetImageIterator!=inputImages->end();++targetImageIterator){ string id= targetImageIterator->first; } // return 1; }//run protected: map<string,ImagePointerType> * readImageList(string filename){ map<string,ImagePointerType> * result=new map<string,ImagePointerType>; ifstream ifs(filename.c_str()); if (!ifs){ LOG<<"could not read "<<filename<<endl; exit(0); } while( ! ifs.eof() ) { string imageID; ifs >> imageID; if (imageID!=""){ ImagePointerType img; string imageFileName ; ifs >> imageFileName; LOGV(3)<<"Reading image "<<imageFileName<< " with ID "<<imageID<<endl; img=ImageUtils<ImageType>::readImage(imageFileName); if (result->find(imageID)==result->end()) (*result)[imageID]=img; else{ LOG<<"duplicate image ID "<<imageID<<", aborting"<<endl; exit(0); } } } return result; } double localMAD(ImageNeighborhoodIteratorPointerType tIt, ImageNeighborhoodIteratorPointerType aIt,ImageNeighborhoodIteratorPointerType mIt){ double result=0; int count=0; for (unsigned int i=0;i<tIt->Size();++i){ if (mIt->GetPixel(i)){ result+=fabs(tIt->GetPixel(i)-aIt->GetPixel(i)); count++; } } if (!count) return 1.0; return exp(-result/count/m_sigma); } double localMSD(ImageNeighborhoodIteratorPointerType tIt, ImageNeighborhoodIteratorPointerType aIt,ImageNeighborhoodIteratorPointerType mIt){ double result=0; int count=0; for (unsigned int i=0;i<tIt->Size();++i){ if (mIt->GetPixel(i)){ double tmp=(tIt->GetPixel(i)-aIt->GetPixel(i)); result+=tmp*tmp; count++; } } if (!count) return 1.0; return exp(-result/count/(m_sigma*m_sigma)); } double localNCC(ImageNeighborhoodIteratorPointerType tIt, ImageNeighborhoodIteratorPointerType aIt,ImageNeighborhoodIteratorPointerType mIt){ double result=0; int count=0; double sff=0.0,smm=0.0,sfm=0.0,sf=0.0,sm=0.0; for (unsigned int i=0;i<tIt->Size();++i){ if (mIt->GetPixel(i)){ double f=tIt->GetPixel(i); double m= aIt->GetPixel(i); sff+=f*f; smm+=m*m; sfm+=f*m; sf+=f; sm+=m; count+=1; } } if (!count) return 0.5; else{ double NCC=0; sff -= ( sf * sf / count ); smm -= ( sm * sm / count ); sfm -= ( sf * sm / count ); if (smm*sff>0){ NCC=1.0*sfm/sqrt(smm*sff); } result=(1.0+NCC)/2; } return result; } double globalMAD(ImagePointerType target, ImagePointerType moving, DeformationFieldPointerType deformation){ std::pair<ImagePointerType,ImagePointerType> deformedMoving = TransfUtils<ImageType>::warpImageWithMask(moving,deformation); ImageIteratorType tIt(target,target->GetLargestPossibleRegion()); ImageIteratorType mIt(deformedMoving.first,deformedMoving.first->GetLargestPossibleRegion()); ImageIteratorType maskIt(deformedMoving.second,deformedMoving.second->GetLargestPossibleRegion()); tIt.GoToBegin();mIt.GoToBegin();maskIt.GoToBegin(); double result=0.0;int count=0; for (;!tIt.IsAtEnd();++tIt,++mIt,++maskIt){ if (maskIt.Get()){ result+=fabs(tIt.Get()-mIt.Get()); count++; } } if (count) return exp(-result/count/m_sigma); else return 0.0; } };//class
[ "tobiasgass@gmail.com" ]
tobiasgass@gmail.com
d0aa937f8cfc7762f02531fbe2c23d59fe74631a
ceed9ebb93891e24d49bf8e9cd959b046ae4e9d8
/src/qt/sendcoinsdialog.cpp
c4091f1b242285a387ef839734d5ff9bfa3b3590
[ "MIT" ]
permissive
bitcoininvestproject/BitcoinInvestCore
e55a4c96f31999fa20a8f006f2ecf70e51dcb6f9
ec42975bcd981d73e2f17983159fa39ff7660622
refs/heads/master
2020-08-08T03:04:44.963485
2019-11-21T18:46:30
2019-11-21T18:46:30
213,688,243
0
0
null
null
null
null
UTF-8
C++
false
false
38,851
cpp
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2019 The BitcoinInvest Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" #include "askpassphrasedialog.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "coincontroldialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "main.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "base58.h" #include "coincontrol.h" #include "ui_interface.h" #include "utilmoneystr.h" #include "wallet.h" #include <QMessageBox> #include <QScrollBar> #include <QSettings> #include <QTextDocument> SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::SendCoinsDialog), clientModel(0), model(0), fNewRecipientAllowed(true), fFeeMinimized(true) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&))); // UTXO Splitter connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int))); connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&))); // BitcoinInvest specific QSettings settings; if (!settings.contains("bUseSwiftTX")) settings.setValue("bUseSwiftTX", false); bool useSwiftTX = settings.value("bUseSwiftTX").toBool(); if (fLiteMode) { ui->checkSwiftTX->setVisible(false); CoinControlDialog::coinControl->useSwiftTX = false; } else { ui->checkSwiftTX->setChecked(useSwiftTX); CoinControlDialog::coinControl->useSwiftTX = useSwiftTX; } connect(ui->checkSwiftTX, SIGNAL(stateChanged(int)), this, SLOT(updateSwiftTX())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction* clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // init transaction fee section if (!settings.contains("fFeeSectionMinimized")) settings.setValue("fFeeSectionMinimized", true); if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nFeeRadio", 1); // custom if (!settings.contains("nFeeRadio")) settings.setValue("nFeeRadio", 0); // recommended if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nCustomFeeRadio", 1); // total at least if (!settings.contains("nCustomFeeRadio")) settings.setValue("nCustomFeeRadio", 0); // per kilobyte if (!settings.contains("nSmartFeeSliderPosition")) settings.setValue("nSmartFeeSliderPosition", 0); if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); if (!settings.contains("fPayOnlyMinFee")) settings.setValue("fPayOnlyMinFee", false); if (!settings.contains("fSendFreeTransactions")) settings.setValue("fSendFreeTransactions", false); ui->groupFee->setId(ui->radioSmartFee, 0); ui->groupFee->setId(ui->radioCustomFee, 1); ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true); ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0); ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1); ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true); ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt()); ui->customFee->setValue(settings.value("nTransactionFee").toLongLong()); ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool()); ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool()); minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool()); // If SwiftTX activated hide button 'Choose'. Show otherwise. ui->buttonChooseFee->setVisible(!useSwiftTX); } void SendCoinsDialog::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(updateSmartFeeLabel())); } } void SendCoinsDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); // fee section connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateSmartFeeLabel())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(updateGlobalFeeVariables())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); ui->customFee->setSingleStep(CWallet::minTxFee.GetFeePerK()); updateFeeSectionControls(); updateMinFeeLabel(); updateSmartFeeLabel(); updateGlobalFeeVariables(); } } SendCoinsDialog::~SendCoinsDialog() { QSettings settings; settings.setValue("fFeeSectionMinimized", fFeeMinimized); settings.setValue("nFeeRadio", ui->groupFee->checkedId()); settings.setValue("nCustomFeeRadio", ui->groupCustomFee->checkedId()); settings.setValue("nSmartFeeSliderPosition", ui->sliderSmartFee->value()); settings.setValue("nTransactionFee", (qint64)ui->customFee->value()); settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked()); settings.setValue("fSendFreeTransactions", ui->checkBoxFreeTx->isChecked()); delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if (!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); //UTXO splitter - address should be our own CBitcoinAddress address = entry->getValue().address.toStdString(); if (!model->isMine(address) && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work when sending to outside addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (entry) { if (entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if (!valid || recipients.isEmpty()) { return; } //set split block in model CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked; if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work with multiple addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (CoinControlDialog::coinControl->fSplitBlock) CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt()); QString strFunds = ""; QString strFee = ""; recipients[0].inputType = ALL_COINS; if (ui->checkSwiftTX->isChecked()) { recipients[0].useSwiftTX = true; strFunds += " "; strFunds += tr("using SwiftTX"); } else { recipients[0].useSwiftTX = false; } // Format confirmation message QStringList formatted; foreach (const SendCoinsRecipient& rcp, recipients) { // generate bold amount string QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append("</b> ").append(strFunds); // generate monospace address string QString address = "<span style='font-family: monospace;'>" + rcp.address; address.append("</span>"); QString recipientElement; if (!rcp.paymentRequest.IsInitialized()) // normal payment { if (rcp.label.length() > 0) // label with address { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label)); recipientElement.append(QString(" (%1)").arg(address)); } else // just address { recipientElement = tr("%1 to %2").arg(amount, address); } } else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant)); } else // insecure payment request { recipientElement = tr("%1 to %2").arg(amount, address); } if (CoinControlDialog::coinControl->fSplitBlock) { recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock)); } formatted.append(recipientElement); } fNewRecipientAllowed = false; // request unlock only if was locked or unlocked for staking: // this way we let users unlock by walletpassphrase or by menu // and make many transactions while unlocking through this dialog // will call relock WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus(); if (encStatus == model->Locked || encStatus == model->UnlockedForStakingOnly) { WalletModel::UnlockContext ctx(model->requestUnlock(AskPassphraseDialog::Context::Send_BTV, true)); if (!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } send(recipients, strFee, formatted); return; } // already unlocked or not encrypted at all send(recipients, strFee, formatted); } void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted) { // prepare transaction for getting txFee earlier WalletModelTransaction currentTransaction(recipients); WalletModel::SendCoinsReturn prepareStatus; if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl); else prepareStatus = model->prepareTransaction(currentTransaction); // process prepareStatus and on error generate message shown to user processSendCoinsReturn(prepareStatus, BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()), true); if (prepareStatus.status != WalletModel::OK) { fNewRecipientAllowed = true; return; } CAmount txFee = currentTransaction.getTransactionFee(); QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><br />%1"); if (txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><span style='color:#aa0000;'>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee)); questionString.append("</span> "); questionString.append(tr("are added as transaction fee")); questionString.append(" "); questionString.append(strFee); // append transaction size questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)"); } // add total amount in all subdivision units questionString.append("<hr />"); CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee; QStringList alternativeUnits; foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { if (u != model->getOptionsModel()->getDisplayUnit()) alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount)); } // Show total amount + all alternative units questionString.append(tr("Total Amount = <b>%1</b><br />= %2") .arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)) .arg(alternativeUnits.join("<br />= "))); // Limit number of displayed entries int messageEntries = formatted.size(); int displayedEntries = 0; for (int i = 0; i < formatted.size(); i++) { if (i >= MAX_SEND_POPUP_ENTRIES) { formatted.removeLast(); i--; } else { displayedEntries = i + 1; } } questionString.append("<hr />"); questionString.append(tr("<b>(%1 of %2 entries displayed)</b>").arg(displayedEntries).arg(messageEntries)); // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } // now send the prepared transaction WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user processSendCoinsReturn(sendStatus); if (sendStatus.status == WalletModel::OK) { accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while (ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateTabsAndLabels(); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry* SendCoinsDialog::addEntry() { SendCoinsEntry* entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateTabsAndLabels(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if (bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateTabsAndLabels() { setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->hide(); // If the last entry is about to be removed add an empty one if (ui->entries->count() == 1) addEntry(); entry->deleteLater(); updateTabsAndLabels(); } QWidget* SendCoinsDialog::setupTabChain(QWidget* prev) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->sendButton); QWidget::setTabOrder(ui->sendButton, ui->clearButton); QWidget::setTabOrder(ui->clearButton, ui->addButton); return ui->addButton; } void SendCoinsDialog::setAddress(const QString& address) { SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient& rv) { if (!fNewRecipientAllowed) return; SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setValue(rv); updateTabsAndLabels(); } bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv) { // Just paste the entry, all pre-checks // are done in paymentserver.cpp. pasteEntry(rv); return true; } void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); Q_UNUSED(watchBalance); Q_UNUSED(watchUnconfirmedBalance); Q_UNUSED(watchImmatureBalance); if (model && model->getOptionsModel()) { uint64_t bal = 0; bal = balance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), bal)); } } void SendCoinsDialog::updateDisplayUnit() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); coinControlUpdateLabels(); ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); updateMinFeeLabel(); updateSmartFeeLabel(); } void SendCoinsDialog::updateSwiftTX() { bool useSwiftTX = ui->checkSwiftTX->isChecked(); QSettings settings; settings.setValue("bUseSwiftTX", useSwiftTX); CoinControlDialog::coinControl->useSwiftTX = useSwiftTX; // If SwiftTX activated if (useSwiftTX) { // minimize the Fee Section (if open) minimizeFeeSection(true); // set the slider to the max ui->sliderSmartFee->setValue(24); } // If SwiftTX activated hide button 'Choose'. Show otherwise. ui->buttonChooseFee->setVisible(!useSwiftTX); // Update labels and controls updateFeeSectionControls(); updateSmartFeeLabel(); coinControlUpdateLabels(); } void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare) { bool fAskForUnlock = false; QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams; // Default to a warning message, override if error message is needed msgParams.second = CClientUIInterface::MSG_WARNING; // This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn. // WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins() // all others are used only in WalletModel::prepareTransaction() switch (sendCoinsReturn.status) { case WalletModel::InvalidAddress: msgParams.first = tr("The recipient address is not valid, please recheck."); break; case WalletModel::InvalidAmount: msgParams.first = tr("The amount to pay must be larger than 0."); break; case WalletModel::AmountExceedsBalance: msgParams.first = tr("The amount exceeds your balance."); break; case WalletModel::AmountWithFeeExceedsBalance: msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg); break; case WalletModel::DuplicateAddress: msgParams.first = tr("Duplicate address found, can only send to each address once per send operation."); break; case WalletModel::TransactionCreationFailed: msgParams.first = tr("Transaction creation failed!"); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::TransactionCommitFailed: msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::StakingOnlyUnlocked: // Unlock is only need when the coins are send if(!fPrepare) fAskForUnlock = true; else msgParams.first = tr("Error: The wallet was unlocked only to staking coins."); break; case WalletModel::InsaneFee: msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK())); break; // included to prevent a compiler warning. case WalletModel::OK: default: return; } // Unlock wallet if it wasn't fully unlocked already if(fAskForUnlock) { model->requestUnlock(AskPassphraseDialog::Context::Unlock_Full, false); if(model->getEncryptionStatus () != WalletModel::Unlocked) { msgParams.first = tr("Error: The wallet was unlocked only to staking coins. Unlock canceled."); } else { // Wallet unlocked return; } } emit message(tr("Send Coins"), msgParams.first, msgParams.second); } void SendCoinsDialog::minimizeFeeSection(bool fMinimize) { ui->labelFeeMinimized->setVisible(fMinimize); ui->buttonChooseFee->setVisible(fMinimize); ui->buttonMinimizeFee->setVisible(!fMinimize); ui->frameFeeSelection->setVisible(!fMinimize); ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0); fFeeMinimized = fMinimize; } void SendCoinsDialog::on_buttonChooseFee_clicked() { minimizeFeeSection(false); } void SendCoinsDialog::on_buttonMinimizeFee_clicked() { updateFeeMinimizedLabel(); minimizeFeeSection(true); } void SendCoinsDialog::setMinimumFee() { ui->radioCustomPerKilobyte->setChecked(true); ui->customFee->setValue(CWallet::minTxFee.GetFeePerK()); } void SendCoinsDialog::updateFeeSectionControls() { ui->sliderSmartFee->setEnabled(ui->radioSmartFee->isChecked() && !ui->checkSwiftTX->isChecked()); ui->labelSmartFee->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee2->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee3->setEnabled(ui->radioSmartFee->isChecked()); ui->labelFeeEstimation->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeNormal->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeFast->setEnabled(ui->radioSmartFee->isChecked()); ui->checkBoxMinimumFee->setEnabled(ui->radioCustomFee->isChecked()); ui->labelMinFeeWarning->setEnabled(ui->radioCustomFee->isChecked()); ui->radioCustomPerKilobyte->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->customFee->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); } void SendCoinsDialog::updateGlobalFeeVariables() { if (ui->radioSmartFee->isChecked()) { nTxConfirmTarget = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); payTxFee = CFeeRate(0); } else { nTxConfirmTarget = 25; payTxFee = CFeeRate(ui->customFee->value()); fPayAtLeastCustomFee = ui->radioCustomAtLeast->isChecked(); } fSendFreeTransactions = ui->checkBoxFreeTx->isChecked(); } void SendCoinsDialog::updateFeeMinimizedLabel() { if (!model || !model->getOptionsModel()) return; if (ui->checkSwiftTX->isChecked()) { ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), 1000000)); } else if (ui->radioSmartFee->isChecked()) ui->labelFeeMinimized->setText(ui->labelSmartFee->text()); else { ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + ((ui->radioCustomPerKilobyte->isChecked()) ? "/kB" : "")); } } void SendCoinsDialog::updateMinFeeLabel() { if (model && model->getOptionsModel()) ui->checkBoxMinimumFee->setText(tr("Pay only the minimum fee of %1").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB")); } void SendCoinsDialog::updateSmartFeeLabel() { if (!model || !model->getOptionsModel()) return; int nBlocksToConfirm = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); CFeeRate feeRate = mempool.estimateFee(nBlocksToConfirm); // if SwiftTX checked, display it in the label if (ui->checkSwiftTX->isChecked()) { ui->labelFeeEstimation->setText(tr("Estimated to get 6 confirmations near instantly with <b>SwiftTX</b>!")); ui->labelSmartFee2->hide(); } else if (feeRate <= CFeeRate(0)) // not enough data => minfee { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB"); ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...) ui->labelFeeEstimation->setText(""); } else { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); ui->labelSmartFee2->hide(); ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", nBlocksToConfirm)); } updateFeeMinimizedLabel(); } // UTXO splitter void SendCoinsDialog::splitBlockChecked(int state) { if (model) { CoinControlDialog::coinControl->fSplitBlock = (state == Qt::Checked); fSplitBlock = (state == Qt::Checked); ui->splitBlockLineEdit->setEnabled((state == Qt::Checked)); ui->labelBlockSizeText->setEnabled((state == Qt::Checked)); ui->labelBlockSize->setEnabled((state == Qt::Checked)); coinControlUpdateLabels(); } } //UTXO splitter void SendCoinsDialog::splitBlockLineEditChanged(const QString& text) { //grab the amount in Coin Control AFter Fee field QString qAfterFee = ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "").simplified().replace(" ", ""); //convert to CAmount CAmount nAfterFee; ParseMoney(qAfterFee.toStdString().c_str(), nAfterFee); //if greater than 0 then divide after fee by the amount of blocks CAmount nSize = nAfterFee; int nBlocks = text.toInt(); if (nAfterFee && nBlocks) nSize = nAfterFee / nBlocks; //assign to split block dummy, which is used to recalculate the fee amount more outputs CoinControlDialog::nSplitBlockDummy = nBlocks; //update labels ui->labelBlockSize->setText(QString::fromStdString(FormatMoney(nSize))); coinControlUpdateLabels(); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", "")); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Dust" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", "")); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); if (checked) coinControlUpdateLabels(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (state == Qt::Unchecked) { CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->clear(); } else // use this to re-validate an already entered address coinControlChangeEdited(ui->lineEditCoinControlChange->text()); ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString& text) { if (model && model->getAddressTableModel()) { // Default to no change address until verified CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); CBitcoinAddress addr = CBitcoinAddress(text.toStdString()); if (text.isEmpty()) // Nothing entered { ui->labelCoinControlChangeLabel->setText(""); } else if (!addr.IsValid()) // Invalid address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid BitcoinInvest address")); } else // Valid address { CPubKey pubkey; CKeyID keyid; addr.GetKeyID(keyid); if (!model->getPubKey(keyid, pubkey)) // Unknown change address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } else // Known change address { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); // Query label QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else ui->labelCoinControlChangeLabel->setText(tr("(no label)")); CoinControlDialog::coinControl->destChange = addr.Get(); } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "empiretoken@gmail.com" ]
empiretoken@gmail.com
d80b84b5b2d2982bb4228f3562dd2b02283e23cd
8f5bd8801e302d0d37945b0dc54d4aaf06404d29
/UVA/11118983_AC_0ms_0kB.cpp
ec3bab0e0ac95b3423b26ba0987c84dd52f1712e
[]
no_license
antanvir/Problem-Solving
6374e897e7369c829781598ab3e788ec9aabadf8
038de8c332fdc557fd860b9d2cf13b1f73d76059
refs/heads/master
2021-06-09T11:45:11.885874
2021-05-05T06:12:52
2021-05-05T06:12:52
131,049,259
0
0
null
null
null
null
UTF-8
C++
false
false
559
cpp
#include<stdio.h> int main(){ long int i,j,k,n,l,c=0; int a[50],tmp; scanf("%ld",&n); for(i=0;i<n;i++){ scanf("%ld",&l); for(j=0;j<l;j++){ scanf("%d",&a[j]); } for(k=0;k<l;k++){ for(j=k+1;j<l;j++){ if(a[k]>a[j]){ tmp=a[k]; a[k]=a[j]; a[j]=tmp; c++; } } } printf("Optimal train swapping takes %d swaps.\n",c); c=0; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
522c036f5ac71808d409f48c3d3a8daf1a4137f5
7ed8073075e7f5a1bb8abf16b8e03e31f96dd64a
/sgreader/mainwindow.h
4001be7a61dc1fa74dd01f57805750d3094a26b0
[ "MIT" ]
permissive
Strotus/citybuilding-tools
eaaf1f8312fdf20ae22bca9c50cf803ff2963934
22ba1cad2453e854bdba8752d257bd96922dfce0
refs/heads/master
2022-12-27T10:38:36.558198
2020-07-19T13:15:52
2020-07-19T13:15:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
930
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QtGui> // TODO: specify #include "sgfile.h" #include "sgimage.h" class QAction; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); //~MainWindow(); private slots: void openFile(); void saveFile(); void extractAll(); void treeSelectionChanged(); void help(); void licence(); void about(); private: void createChildren(); void createMenu(); void createActions(); void loadFile(const QString &filename); void loadImage(SgImage *image); void clearImage(); QTreeWidget *treeWidget; QLabel *imageLabel; QString filename; QString appname; QImage image; SgFile *sgFile; QAction *openAction; QAction *saveAction; QAction *extractAllAction; QAction *exitAction; QAction *helpAction; QAction *licenceAction; QAction *aboutAction; }; #endif /* MAINWINDOW_H */
[ "bvschaik@gmail.com" ]
bvschaik@gmail.com
2ed5d6048f8c1375d1dfb53bb5e5b95361197e3d
9fa216529e689f87abcb8f09bb612300a1acaf60
/thirdparty/nlohmann_json/docs/examples/json_pointer__back.cpp
dd3b210bf12a4345e1680eb0506172204a8d16bf
[ "MIT", "LicenseRef-scancode-free-unknown", "CC0-1.0", "Apache-2.0" ]
permissive
zouxianyu/query-pdb
e07a1f8298f62178df72061e89efbdd7f3321f78
8ecdeefa0ed9ebee09ab9463b2c02bbcc53ca283
refs/heads/master
2023-08-18T15:29:40.777726
2023-07-05T07:27:45
2023-07-05T07:27:45
599,970,245
99
39
MIT
2023-08-11T08:07:28
2023-02-10T09:36:01
C++
UTF-8
C++
false
false
421
cpp
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // different JSON Pointers json::json_pointer ptr1("/foo"); json::json_pointer ptr2("/foo/0"); // call empty() std::cout << "last reference token of \"" << ptr1 << "\" is \"" << ptr1.back() << "\"\n" << "last reference token of \"" << ptr2 << "\" is \"" << ptr2.back() << "\"" << std::endl; }
[ "2979121738@qq.com" ]
2979121738@qq.com
a573ae187cfefb42f4daedc4d1f79fab6a776723
72fe6173de3393f5ba110173bed3920e0cd4e013
/Kurs_26_Oct_Day57_IntergrateLighting/Objects/MeshSphere.cpp
4629ad05ae83fcc030320e66674024c73144a2df
[]
no_license
HannahJYoo/GitTest
84589c2c433edf61c5c3cd836883889762d41990
76df04ee58660007afe7f9ae447150f12852d22a
refs/heads/master
2020-04-03T15:04:00.410629
2018-10-30T08:18:30
2018-10-30T08:18:30
155,348,790
0
0
null
null
null
null
UTF-8
C++
false
false
2,468
cpp
#include "stdafx.h" #include "MeshSphere.h" #include "../Model/ModelMeshPart.h" MeshSphere::MeshSphere() : GameModel(Materials + L"Bevor/", L"Sphere.material", Models + L"Bevor/", L"Sphere.mesh") { /*shader = new Shader(Shaders + L"011_Sphere.hlsl"); for (Material* material : model->Materials()) { material->SetDiffuse(D3DXCOLOR(1, 0, 0, 1)); material->SetShader(shader); }*/ SetBoundingBox(); } MeshSphere::~MeshSphere() { SAFE_DELETE(shader); } void MeshSphere::Update() { __super::Update(); } void MeshSphere::Render() { __super::Render(); } void MeshSphere::SetBoundingBox() { float min = -std::numeric_limits<float>().infinity(), max = std::numeric_limits<float>().infinity(); D3DXVECTOR3 vecMin(max, max, max), vecMax(min, min, min); for (ModelMesh* modelMesh : model->Meshes()) { ModelBone* bone = modelMesh->ParentBone(); D3DXMATRIX w = bone->Global(); for (ModelMeshPart* part : modelMesh->Meshs()) { vector<VertexTextureNormalTangentBlend> vertices = part->Vertices(); for (VertexTextureNormalTangentBlend data : vertices) { D3DXVECTOR3 pos = data.Position; D3DXVec3TransformCoord(&pos, &pos, &w); if (vecMin.x > pos.x) vecMin.x = pos.x; if (vecMax.x < pos.x) vecMax.x = pos.x; if (vecMin.y > pos.y) vecMin.y = pos.y; if (vecMax.y < pos.y) vecMax.y = pos.y; if (vecMin.z > pos.z) vecMin.z = pos.z; if (vecMax.z < pos.z) vecMax.z = pos.z; } } } this->vecMin = vecMin; this->vecMax = vecMax; center = (vecMax + vecMin) / 2.0f; D3DXVECTOR3 temp = vecMax + center; if (temp.x < 0) temp.x *= -1; if (temp.y < 0) temp.y *= -1; if (temp.z < 0) temp.z *= -1; radius = max(temp.x, temp.y); radius = max(radius, temp.z); boundSize = temp * 2.0f; boundingBox.push_back(D3DXVECTOR3(vecMin.x, vecMin.y, vecMin.z)); boundingBox.push_back(D3DXVECTOR3(vecMin.x, vecMax.y, vecMin.z)); boundingBox.push_back(D3DXVECTOR3(vecMax.x, vecMin.y, vecMin.z)); boundingBox.push_back(D3DXVECTOR3(vecMax.x, vecMax.y, vecMin.z)); boundingBox.push_back(D3DXVECTOR3(vecMin.x, vecMin.y, vecMax.z)); boundingBox.push_back(D3DXVECTOR3(vecMin.x, vecMax.y, vecMax.z)); boundingBox.push_back(D3DXVECTOR3(vecMax.x, vecMin.y, vecMax.z)); boundingBox.push_back(D3DXVECTOR3(vecMax.x, vecMax.y, vecMax.z)); UINT indices[36]{ 0,1,2,2,1,3, 2,3,6,6,3,7, 6,7,5,5,7,4, 4,5,0,0,5,1, 1,5,3,3,5,7, 4,0,6,6,0,2 }; for (int i = 0; i < 36; i++) { boundingvertex.push_back(boundingBox[indices[i]]); } }
[ "36724816+HannahJYoo@users.noreply.github.com" ]
36724816+HannahJYoo@users.noreply.github.com
86b7a5ec8724e4ca4ddc804d2084c0cb0ac287ab
2e56ef022a63e60d733c17e7111d2627fdad5b18
/test_src/cpp/hierarchical_parallelism/reduction_add-complex_double/target_teams__parallel__for.cpp
249e759dcddfa2954ee74c02b912831baa737772
[ "MIT" ]
permissive
tob2/OvO
19d391d38ae4cb979fbf0d2d00a177e5d7922cb0
eed63e9824f686905bbdac3ff32393695477a5e7
refs/heads/master
2023-07-19T05:11:41.275902
2021-08-24T16:43:20
2021-08-24T16:43:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,124
cpp
#include <iostream> #include <cstdlib> #include <cmath> #include <complex> using std::complex; #ifdef _OPENMP #include <omp.h> #else int omp_get_num_teams() {return 1;} #endif bool almost_equal(complex<double> x, complex<double> gold, double rel_tol=1e-09, double abs_tol=0.0) { return std::abs(x-gold) <= std::max(rel_tol * std::max(std::abs(x), std::abs(gold)), abs_tol); } #pragma omp declare reduction(+: complex<double>: omp_out += omp_in) void test_target_teams__parallel__for() { const int N0 { 182 }; const complex<double> expected_value { N0 }; complex<double> counter_teams{}; #pragma omp target teams num_teams(182) reduction(+: counter_teams) { #pragma omp parallel reduction(+: counter_teams) #pragma omp for for (int i0 = 0 ; i0 < N0 ; i0++ ) { counter_teams = counter_teams + complex<double> { double { 1. } / omp_get_num_teams() }; } } if (!almost_equal(counter_teams, expected_value, 0.01)) { std::cerr << "Expected: " << expected_value << " Got: " << counter_teams << std::endl; std::exit(112); } } int main() { test_target_teams__parallel__for(); }
[ "tapplencourt@anl.gov" ]
tapplencourt@anl.gov
16f24d25c2e703796499f03543a3004b7490bbff
6d8c5e578ba64574257e229ede28d7ac3817ea44
/host/Host/MonitorMFC/MonitorMFCDoc.h
cfcc740d93e109f9191a4171b47bf312bf01174a
[]
no_license
suyuti/Hypercom
0771b4a1a88fdf0077799de6fb9146ae4884c998
fca325792378f83008d19f9f0f577e3f2ed6cb83
refs/heads/master
2021-01-13T01:28:46.126789
2015-02-26T20:39:25
2015-02-26T20:39:25
31,387,832
0
0
null
null
null
null
UTF-8
C++
false
false
660
h
// MonitorMFCDoc.h : interface of the CMonitorMFCDoc class // #pragma once #include "MonitorMFCSet.h" class CMonitorMFCDoc : public CDocument { protected: // create from serialization only CMonitorMFCDoc(); DECLARE_DYNCREATE(CMonitorMFCDoc) // Attributes public: CMonitorMFCSet m_MonitorMFCSet; // Operations public: // Overrides public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // Implementation public: virtual ~CMonitorMFCDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() };
[ "mehmet.dindar@SMART0178.smartmoss.local" ]
mehmet.dindar@SMART0178.smartmoss.local