text
stringlengths
8
6.88M
#include<bits/stdc++.h> using namespace std; class Student{ private: int age; public: int rno; //Default Constructor. Student(){ cout << "Default Constructor is Called !" << endl; } //Parameterized Constructor with one parameter. Student(int rno){ cout << "Parameterized Constructor with 1 parameter is called !" << endl; this -> rno = rno; //Here we have to use this keyword compulsory. } //Parameterized Constructor with two parameters. Student(int a,int r){ cout << "Parameterized Constructor with 2 parameter is called !" << endl; this -> age = a; //Here this keyword is optional. this -> rno = r; } void display(){ cout << age << " " << rno << endl; } }; int main(){ Student s1(101); s1.display(); Student* s2 = new Student(102); s2->display(); Student s3(30,1001); s3.display(); Student s4(1002); s4.display(); return 0; }
/*-----------------UDP客户端------------------------------------ ------------接受UDP服务器的广播并显示广播信息 ------------如果是“点名”命令,则回传自己的学号和姓名--------*/ #include "Winsock2.h" #include "stdio.h" #include "string.h" #pragma comment(lib,"wsock32.lib") #define SEND_PORT 3000 //发送端口 #define RECV_PORT 3001 //接收端口 SOCKET sock; sockaddr_in ServerAddr; //服务器地址 sockaddr_in ClientAddr; //客户端(本地)地址 void main() { int n; //-----------------------初始化套接字---------------------- WSADATA WSAData; if(WSAStartup(MAKEWORD(2,2), &WSAData)!=0) { printf("socket init fail!\n"); system("pause"); return; } //----------------------创建用于收发的套接字------------------ sock=socket(AF_INET,SOCK_DGRAM,0); if(sock==SOCKET_ERROR) { printf("socket create fail!\n"); WSACleanup(); system("pause"); return; } //---------------设置客户端(本地)地址--------------------- memset(&ClientAddr,0,sizeof(ClientAddr)); ClientAddr.sin_family=AF_INET; ClientAddr.sin_addr.s_addr=inet_addr("10.0.6.25");// INADDR_ANY; ClientAddr.sin_port=htons(RECV_PORT); //----------------绑定套接字到本地址------------------------- n=bind(sock,(struct sockaddr*)&ClientAddr,sizeof(ClientAddr)); if(n==SOCKET_ERROR) { printf("Bind error!\n"); system("pause"); return; } else { printf("Bind Address ok! \n"); } //----------------在指定端口侦听,并接受服务器广播的信息------------- char buf[1024]="\0"; int len; printf("Bengin receiving datas... \n"); while(1) //无限循环侦听 { memset(&buf,'\0',sizeof(buf)); //清空接收缓存区 memset(&ServerAddr,0,sizeof(ServerAddr)); //清空地址空间 len=sizeof(ServerAddr); //接受服务器广播信息 n=recvfrom(sock,buf,sizeof(buf),0,(struct sockaddr*)&ServerAddr,(int *)&len); if(n==SOCKET_ERROR) { printf("\n Get BROADCAST Data error! \n"); printf("\n The error code: %d \n",WSAGetLastError()); } else { //---------收到广播信息,则显示--------------------------- printf("\n Get BROADCAST Data:\"%s\n", buf,inet_ntoa(ServerAddr.sin_addr)); if( strcmp(buf,"/name") >=0) //如果是"点名"命令 { //------------设置服务器地址,准备回传-------------------- ServerAddr.sin_family=AF_INET; ServerAddr.sin_addr.s_addr=inet_addr("10.0.6.25"); ServerAddr.sin_port = htons(SEND_PORT); //------------回传自己的学号和姓名------------------------ memset(&buf,'\0',sizeof(buf)); strcpy(buf,"20151681310210 崔晨凯"); n=sendto(sock,buf,strlen(buf)+1,0,(struct sockaddr *)&ServerAddr,sizeof(ServerAddr)); if(n==SOCKET_ERROR) { printf(" Send back my name false!\n"); } else if(n==0) { printf(" Send back my name false 0 \n!"); } else if(n!=SOCKET_ERROR) { printf(" Send back my name success!\n"); } } } Sleep(1000); } getchar(); closesocket(sock); WSACleanup(); }
#include <iostream> #include <vector> #include <fstream> using namespace std; struct Muchie { int varf_i, varf_f; double cost; }; Muchie Muchie_minima( int m, Muchie *Muchii, int *vizitat ) { Muchie m_minim = {0,0,0}; int x, y; double cost_minim = 35000; for(int i = 0 ; i < m; i++ ) { Muchie curent = Muchii[i]; x = curent.varf_i; y = curent.varf_f; if((vizitat[x] == 0 && vizitat[y]==1) || (vizitat[x] == 1 && vizitat[y] ==0) ) if(curent.cost < cost_minim) { cost_minim = curent.cost; m_minim = curent; } } return m_minim; } void PRIM( int s, int n, int m,Muchie *muchii, vector <Muchie>& arbore_partial_de_cost_minim ) { int *vizitat, i, v; vizitat = new int[n+1]; for(i = 1 ; i <= n ; i++) vizitat[i] = 0; vizitat[s] = 1; for(i = 1 ; i < n ; i++) { Muchie minima = Muchie_minima(m, muchii, vizitat); arbore_partial_de_cost_minim.push_back(minima); vizitat[minima.varf_f] = 1; vizitat[minima.varf_i] = 1; } } void afis(Muchie m, ofstream &g) { g << "(" << m.varf_i<< ", " << m.varf_f << ") cost " << m.cost<<endl; } int main() { ifstream f("fis.in"); ofstream g("fis.out"); int n, m; f >> n >> m; int j, i, s ; Muchie *Muchii; Muchii = new Muchie[m]; for(i = 0 ; i < m ; i++) f >> Muchii[i].varf_i >> Muchii[i].varf_f >> Muchii[i].cost; f.close(); vector <Muchie> Arb_Part_Cost_Min; PRIM(s, n, m, Muchii, Arb_Part_Cost_Min); if(Arb_Part_Cost_Min.size() < n-1) { cout << "Graf neconex"; return 0; } else { double cost = 0; for( i = 0 ; i < Arb_Part_Cost_Min.size() ; i++) { afis(Arb_Part_Cost_Min[i],g); cost = cost + Arb_Part_Cost_Min[i].cost; } g << "Costul: " << cost; } g.close(); return 0; }
#ifndef SMS_RECEIVER_H_ #define SMS_RECEIVER_H_ // INCLUDES #include <e32base.h> #include <es_sock.h> // RSocketServ #include <f32file.h> // RFs // LIBS // esock.lib (RSocketServ), smsu.lib (TSmsAddr), gsmu.lib (CSmsBuffer), // efsrv.lib (RFs), estor.lib (RSmsSocketReadStream) // CAPS // NetworkServices (RSocket::Bind), ReadUserData (RSocket::Bind), // WriteUserData (RSocket::Bind) // FORWARD DECLARATIONS class MSmsReceiverObserver; // CLASS DECLARATION /** * CSmsReceiver class. * CSmsReceiver declaration. * */ class CSmsReceiver : public CActive { public: // Constructors and destructor /** * NewL() * Creates new CSmsReceiver object. * @param aObserver Reference to the MSmsReceiverObserver object. * @return Pointer to the created instance of CSmsReceiver. */ static CSmsReceiver* NewL(MSmsReceiverObserver& aObserver); /** * NewLC() * Creates new CSmsReceiver object. * @param aObserver Reference to the MSmsReceiverObserver object. * @return Pointer to the created instance of CSmsReceiver. */ static CSmsReceiver* NewLC(MSmsReceiverObserver& aObserver); /** * ~CSmsReceiver() * Destructor. */ ~CSmsReceiver(); protected: // From CActive /** * DoCancel() * Implements cancellation of an outstanding request. */ void DoCancel(); /** * RunL() * Handles an active objects request completion event. */ void RunL(); /** * RunError() * Handles a leave occurring in the request completion event handler RunL(). * @param aError The leave code. * @return KErrNone if error was handled, otherwise system-wide error. */ TInt RunError(TInt aError); private: // New functions /** * Start() * Starts waiting for the actual socket data. */ void Start(); public: // New functions /** * StartListeningL() * Starts listening for an incoming SMS. */ void StartListeningL(); /** * StopListening() * Stops listening. */ void StopListening(); private: // Constructors /** * CSmsReceiver() * Default C++ constructor. * @param aObserver Reference to the MSmsReceiverObserver object. */ CSmsReceiver(MSmsReceiverObserver& aObserver); /** * ConstructL() * Default EPOC constructor. */ void ConstructL(); private: // enum enum TSmsSocketEngineState { ESmsIdle, ESmsListening, ESmsSystemNotyfing }; private: // data MSmsReceiverObserver& iObserver; RSocketServ iSocketServ; RSocket iReadSocket; RFs iFs; TBool iWait; TPckgBuf<TUint> iBuf; TSmsSocketEngineState iState; }; #endif /*SMS_RECEIVER_H_*/
// MicroVoiceLiteDlg.h : 头文件 // #pragma once #include "afxwin.h" // CMicroVoiceLiteDlg 对话框 class CMicroVoiceLiteDlg : public CDialog { // 构造 public: CMicroVoiceLiteDlg(CWnd* pParent = NULL); // 标准构造函数 // 对话框数据 enum { IDD = IDD_MICROVOICELITE_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnDestroy(); afx_msg void OnTimer(UINT_PTR nIDEvent); afx_msg void OnBnClickedBntMakecall(); afx_msg void OnBnClickedBntRegister(); afx_msg void OnBnClickedBntDropcall(); afx_msg void OnBnClickedBntUnregister(); CEdit mUsername; CEdit mPassword; CEdit mHost; CEdit mDialNum; afx_msg void OnBnClickedCancel(); CStatic mStatus; CButton mHold; afx_msg void OnBnClickedCheckHold(); CButton mAGC; CButton mNR; afx_msg void OnBnClickedCheckAgc(); afx_msg void OnBnClickedCheckNr(); CButton mRecord; afx_msg void OnBnClickedCheckRecord(); CButton mAEC; afx_msg void OnBnClickedCheckAec(); CEdit mDTMF; afx_msg void OnBnClickedBntSendDtmf(); afx_msg void OnBnClickedButtonTest(); afx_msg void OnBnClickedButtonDtmf1(); afx_msg void OnBnClickedButtonDtmf2(); afx_msg void OnBnClickedButtonDtmf3(); afx_msg void OnBnClickedButtonDtmf4(); afx_msg void OnBnClickedButtonDtmf5(); afx_msg void OnBnClickedButtonDtmf6(); afx_msg void OnBnClickedButtonDtmf7(); afx_msg void OnBnClickedButtonDtmf8(); afx_msg void OnBnClickedButtonDtmf9(); afx_msg void OnBnClickedButtonDtmf10(); afx_msg void OnBnClickedButtonDtmf0(); afx_msg void OnBnClickedButtonDtmf11(); CComboBox mCamera; afx_msg void OnCbnSelchangeComboCamList(); CEdit mVideoWnd; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 1995-2007 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #ifdef VEGA_SUPPORT #include "modules/libvega/src/vegainteger.h" #ifndef VEGA_USE_FLOATS #if 1//!defined(HAVE_INT64) || defined(VEGA_USE_OWN_INT64) VG_INT64 int64_mulu(UINT32 a, UINT32 b) { unsigned a_hi = VG_HI16(a); unsigned a_lo = VG_LO16(a); unsigned b_hi = VG_HI16(b); unsigned b_lo = VG_LO16(b); unsigned tmp1 = a_lo * b_lo; unsigned w3 = VG_LO16(tmp1); unsigned k = VG_HI16(tmp1); unsigned tmp2 = a_hi * b_lo + k; unsigned w2 = VG_LO16(tmp2); unsigned w1 = VG_HI16(tmp2); unsigned tmp3 = a_lo * b_hi + w2; k = VG_HI16(tmp3); VG_INT64 res; res.hi = a_hi * b_hi + w1 + k; res.lo = (tmp3 << 16) + w3; return res; } VG_INT64 int64_muls(INT32 x, INT32 y) { /* multiply two 32-bit numbers to a 64-bit number */ BOOL positive = TRUE; if (x < 0) { x = -x; positive = FALSE; } if (y < 0) { y = -y; positive = !positive; } VG_INT64 res = int64_mulu(x, y); if (!positive) res = int64_neg(res); return res; } // number of of leading zero bits static int nlz(UINT32 x) { #if 0 // use smaller constants int n = 32; int c = 16; UINT32 y; #define NLZ_STEP \ y = x >> c; \ if (y != 0) { n -= c; x = y; } \ c >>= 1 NLZ_STEP; // 16 NLZ_STEP; // 8 NLZ_STEP; // 4 NLZ_STEP; // 2 NLZ_STEP; // 1 #undef NLZ_STEP return n - x; #else if (x == 0) return 32; int n = 0; if (x <= 0xffff) { n += 16; x <<= 16; } if (x <= 0xffffff) { n += 8; x <<= 8; } if (x <= 0xfffffff) { n += 4; x <<= 4; } if (x <= 0x3fffffff) { n += 2; x <<= 2; } if (x <= 0x7fffffff) { n += 1; } return n; #endif } UINT32 int64_divu32(VG_INT64 n, UINT32 d) { int shift = nlz(d); d <<= shift; unsigned d_hi = VG_HI16(d); unsigned d_lo = VG_LO16(d); n.hi <<= shift; n.hi |= (n.lo >> 32 - shift) & (-shift >> 31); n.lo <<= shift; unsigned lo_hi = VG_HI16(n.lo); unsigned lo_lo = VG_LO16(n.lo); unsigned quot_hi = n.hi / d_hi; unsigned rem = n.hi - quot_hi * d_hi; while (quot_hi >= 0x10000 || quot_hi * d_lo > (rem << 16) + lo_hi) { quot_hi--; rem += d_hi; if (rem >= 0x10000) break; } unsigned hl = (n.hi << 16) + lo_hi - quot_hi * d; unsigned quot_lo = hl / d_hi; rem = hl - quot_lo * d_hi; while (quot_lo >= 0x10000 || quot_lo * d_lo > (rem << 16) + lo_lo) { quot_lo--; rem += d_hi; if (rem >= 0x10000) break; } return (quot_hi << 16) + quot_lo; } INT32 int64_muldiv(INT32 a, INT32 b, INT32 c) { BOOL positive = TRUE; if (a < 0) { a = -a; positive = FALSE; } if (b < 0) { b = -b; positive = !positive; } if (c < 0) { c = -c; positive = !positive; } // a [32 bit] * b [32 bit] / c [32 bit] => res [32 bit] INT32 div_res = (INT32)int64_divu32(int64_mulu(a, b), c); if (!positive) div_res = -div_res; return div_res; } #endif // !HAVE_INT64 || VEGA_USE_OWN_INT64 // [a:b] / c VEGA_INT64 int128_divu64(VEGA_INT64 a, VEGA_INT64 b, VEGA_INT64 c) { for (unsigned i = 0; i < 64; ++i) { UINT32 t = (INT32)a.hi >> 31; // ~0 || 0 // a:b << 1 a = int64_shl(a, 1); a = int64_or_low(a, b.hi >> 31); b = int64_shl(b, 1); if (int64_gteq(int64_or(a, t, t), c)) { a = int64_sub(a, c); b = int64_or_low(b, 1); } } return b; } INT32 int64_isqrt(VG_INT64 v) { UINT32 root = 0; UINT32 rem_hi = 0; UINT32 rem_lo1 = INT64_HIU32(v); UINT32 rem_lo0 = INT64_LOU32(v); UINT32 count = 31; /* number of iterations */ do { rem_hi = (rem_hi << 2) | (rem_lo1 >> 30); rem_lo1 = (rem_lo1 << 2) | (rem_lo0 >> 30); rem_lo0 <<= 2; root <<= 1; UINT32 test_div = 2*root + 1; if (rem_hi >= test_div) { rem_hi -= test_div; root++; } } while (count-- != 0); return (INT32)root; } #endif // !VEGA_USE_FLOATS #endif // VEGA_SUPPORT
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "WalletUnconfirmedTransactions.h" #include "WalletLegacy/WalletLegacySerialization.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "Serialization/ISerializer.h" #include "Serialization/SerializationOverloads.h" using namespace crypto; namespace cn { inline TransactionOutputId getOutputId(const TransactionOutputInformation& out) { return std::make_pair(out.transactionPublicKey, out.outputInTransaction); } WalletUnconfirmedTransactions::WalletUnconfirmedTransactions(uint64_t uncofirmedTransactionsLiveTime): m_uncofirmedTransactionsLiveTime(uncofirmedTransactionsLiveTime) { } bool WalletUnconfirmedTransactions::serialize(ISerializer& s) { s(m_unconfirmedTxs, "transactions"); s(m_createdDeposits, "unconfirmedCreatedDeposits"); s(m_spentDeposits, "unconfirmedSpentDeposits"); if (s.type() == ISerializer::INPUT) { collectUsedOutputs(); } return true; } bool WalletUnconfirmedTransactions::deserializeV1(ISerializer& s) { s(m_unconfirmedTxs, "transactions"); if (s.type() == ISerializer::INPUT) { collectUsedOutputs(); } return true; } bool WalletUnconfirmedTransactions::findTransactionId(const Hash& hash, TransactionId& id) { return findUnconfirmedTransactionId(hash, id) || findUnconfirmedDepositSpendingTransactionId(hash, id); } bool WalletUnconfirmedTransactions::findUnconfirmedTransactionId(const crypto::Hash& hash, TransactionId& id) { auto it = m_unconfirmedTxs.find(hash); if (it == m_unconfirmedTxs.end()) { return false; } id = it->second.transactionId; return true; } bool WalletUnconfirmedTransactions::findUnconfirmedDepositSpendingTransactionId(const crypto::Hash& hash, TransactionId& id) { auto it = m_spentDeposits.find(hash); if (it == m_spentDeposits.end()) { return false; } id = it->second.transactionId; return true; } void WalletUnconfirmedTransactions::erase(const Hash& hash) { eraseUnconfirmedTransaction(hash) || eraseDepositSpendingTransaction(hash); } bool WalletUnconfirmedTransactions::eraseUnconfirmedTransaction(const crypto::Hash& hash) { auto it = m_unconfirmedTxs.find(hash); if (it == m_unconfirmedTxs.end()) { return false; } deleteUsedOutputs(it->second.usedOutputs); m_unconfirmedTxs.erase(it); return true; } bool WalletUnconfirmedTransactions::eraseDepositSpendingTransaction(const crypto::Hash& hash) { auto it = m_spentDeposits.find(hash); if (it == m_spentDeposits.end()) { return false; } m_spentDeposits.erase(it); return true; } void WalletUnconfirmedTransactions::add(const Transaction& tx, TransactionId transactionId, uint64_t amount, const std::vector<TransactionOutputInformation>& usedOutputs) { UnconfirmedTransferDetails& utd = m_unconfirmedTxs[getObjectHash(tx)]; utd.amount = amount; utd.sentTime = time(nullptr); utd.tx = tx; utd.transactionId = transactionId; uint64_t outsAmount = 0; // process used outputs utd.usedOutputs.reserve(usedOutputs.size()); for (const auto& out : usedOutputs) { auto id = getOutputId(out); utd.usedOutputs.push_back(id); m_usedOutputs.insert(id); outsAmount += out.amount; } utd.outsAmount = outsAmount; } void WalletUnconfirmedTransactions::updateTransactionId(const Hash& hash, TransactionId id) { auto it = m_unconfirmedTxs.find(hash); if (it != m_unconfirmedTxs.end()) { it->second.transactionId = id; } } void WalletUnconfirmedTransactions::addCreatedDeposit(DepositId id, uint64_t totalAmount) { m_createdDeposits[id] = totalAmount; } void WalletUnconfirmedTransactions::addDepositSpendingTransaction(const Hash& transactionHash, const UnconfirmedSpentDepositDetails& details) { assert(m_spentDeposits.count(transactionHash) == 0); m_spentDeposits.emplace(transactionHash, details); } void WalletUnconfirmedTransactions::eraseCreatedDeposit(DepositId id) { m_createdDeposits.erase(id); } uint64_t WalletUnconfirmedTransactions::countCreatedDepositsSum() const { uint64_t sum = 0; for (const auto& kv: m_createdDeposits) { sum += kv.second; } return sum; } uint64_t WalletUnconfirmedTransactions::countSpentDepositsProfit() const { uint64_t sum = 0; for (const auto& kv: m_spentDeposits) { sum += kv.second.depositsSum - kv.second.fee; } return sum; } uint64_t WalletUnconfirmedTransactions::countSpentDepositsTotalAmount() const { uint64_t sum = 0; for (const auto& kv: m_spentDeposits) { sum += kv.second.depositsSum; } return sum; } uint64_t WalletUnconfirmedTransactions::countUnconfirmedOutsAmount() const { uint64_t amount = 0; for (auto& utx: m_unconfirmedTxs) amount+= utx.second.outsAmount; return amount; } uint64_t WalletUnconfirmedTransactions::countUnconfirmedTransactionsAmount() const { uint64_t amount = 0; for (auto& utx: m_unconfirmedTxs) amount+= utx.second.amount; return amount; } bool WalletUnconfirmedTransactions::isUsed(const TransactionOutputInformation& out) const { return m_usedOutputs.find(getOutputId(out)) != m_usedOutputs.end(); } void WalletUnconfirmedTransactions::collectUsedOutputs() { UsedOutputsContainer used; for (const auto& kv : m_unconfirmedTxs) { used.insert(kv.second.usedOutputs.begin(), kv.second.usedOutputs.end()); } m_usedOutputs = std::move(used); } void WalletUnconfirmedTransactions::reset() { m_unconfirmedTxs.clear(); m_usedOutputs.clear(); } void WalletUnconfirmedTransactions::deleteUsedOutputs(const std::vector<TransactionOutputId>& usedOutputs) { for (const auto& output: usedOutputs) { m_usedOutputs.erase(output); } } std::vector<TransactionId> WalletUnconfirmedTransactions::deleteOutdatedTransactions() { std::vector<TransactionId> deletedTransactions; uint64_t now = static_cast<uint64_t>(time(nullptr)); assert(now >= m_uncofirmedTransactionsLiveTime); for (auto it = m_unconfirmedTxs.begin(); it != m_unconfirmedTxs.end();) { if (static_cast<uint64_t>(it->second.sentTime) <= now - m_uncofirmedTransactionsLiveTime) { deleteUsedOutputs(it->second.usedOutputs); deletedTransactions.push_back(it->second.transactionId); it = m_unconfirmedTxs.erase(it); } else { ++it; } } return deletedTransactions; } } /* namespace cn */
#include <iostream> #include <cstdio> #include <queue> #include <binary_search_tree.h> BST::~BST(){ CleanAll(); } void BST::CleanAll(){ if(root == NULL){ return; } std::queue<BSTNode*> printed_queue; printed_queue.push(root); while(!printed_queue.empty()){ BSTNode* current_node = printed_queue.front(); printed_queue.pop(); if(current_node->left_child != NULL){ printed_queue.push(current_node->left_child); } if(current_node->right_child != NULL){ printed_queue.push(current_node->right_child); } current_node->left_child = NULL; current_node->right_child = NULL; delete current_node; } } int BST::GetTreeSize(){ return size_of_tree; } void BST::Search(const int key, BSTNode* &return_node, BSTNode* &return_parent_node){ BSTNode* current_node = root; BSTNode* current_parrent_node = root->parent; while(current_node != NULL){ if(key == current_node->key){ break; }else if(key > current_node->key){ current_parrent_node = current_node; current_node = current_node->right_child; }else{ current_parrent_node = current_node; current_node = current_node->left_child; } } return_node = current_node; return_parent_node = current_parrent_node; } void BST::InsertArbitrary(const int key){ BSTNode* new_added_node = new BSTNode(key); if(size_of_tree == 0){ root = new_added_node; ++size_of_tree; }else{ BSTNode* found_node = NULL; BSTNode* found_parent_node = NULL; Search(key, found_node, found_parent_node); if(found_node == NULL){ if(key < found_parent_node->key){ found_parent_node->left_child = new_added_node; }else{ found_parent_node->right_child = new_added_node; } new_added_node->parent = found_parent_node; }else{ found_node->left_child = new_added_node; new_added_node->parent = found_node; } ++size_of_tree; } } void BST::InOrderTraverseEngine(BSTNode* current_node){ if(current_node != NULL){ InOrderTraverseEngine(current_node->left_child); std::cout<<current_node->key<<" "; InOrderTraverseEngine(current_node->right_child); } } void BST::InOrderTraverseSetEngine(BSTNode* current_node, int &set_index, const int* const L){ if(current_node != NULL){ InOrderTraverseSetEngine(current_node->left_child, set_index, L); current_node->key = L[set_index]; ++set_index; InOrderTraverseSetEngine(current_node->right_child, set_index, L); } } void BST::InOrderTraversePrint(){ InOrderTraverseEngine(root); std::cout<<std::endl; } void BST::PreOrderTraverseEngine(BSTNode* current_node){ if(current_node != NULL){ std::cout<<current_node->key<<" "; PreOrderTraverseEngine(current_node->left_child); PreOrderTraverseEngine(current_node->right_child); } } void BST::PreOrderTraversePrint(){ PreOrderTraverseEngine(root); std::cout<<std::endl; } void BST::PostOrderTraverseEngine(BSTNode* current_node){ if(current_node != NULL){ PostOrderTraverseEngine(current_node->left_child); PostOrderTraverseEngine(current_node->right_child); std::cout<<current_node->key<<" "; } } void BST::PostOrderTraversePrint(){ PostOrderTraverseEngine(root); std::cout<<std::endl; } void BST::LevelOrderTraversePrint(){ std::queue<BSTNode*> printed_queue; printed_queue.push(root); while(!printed_queue.empty()){ BSTNode* current_node = printed_queue.front(); printed_queue.pop(); std::cout<<current_node->key<<" "; if(current_node->left_child != NULL){ printed_queue.push(current_node->left_child); } if(current_node->right_child != NULL){ printed_queue.push(current_node->right_child); } } std::cout<<std::endl; } BSTNode* BST::SearchLeftMostEngine(BSTNode* current_node){ while((current_node != NULL) && (current_node->left_child != NULL)){ current_node = current_node->left_child; } return current_node; } BSTNode* BST::SearchRightMostEngine(BSTNode* current_node){ while((current_node != NULL) && (current_node->right_child != NULL)){ current_node = current_node->right_child; } return current_node; } void BST::SearchLeftMostPrint(){ BSTNode* leftest_node = SearchLeftMostEngine(root); if(leftest_node == NULL){ std::cout<<"smallest node not found."<<std::endl; }else{ std::cout<<"smallest = "<<leftest_node->key<<std::endl; } } void BST::SearchRightMostPrint(){ BSTNode* rightest_node = SearchRightMostEngine(root); if(rightest_node == NULL){ std::cout<<"biggest node not found."<<std::endl; }else{ std::cout<<"biggest = "<<rightest_node->key<<std::endl; } } BSTNode* BST::FindInOrderSuccessor(BSTNode* current_node){ BSTNode* inorder_successor_node = NULL; if(current_node->parent == NULL){ inorder_successor_node = SearchLeftMostEngine(current_node->right_child); }else{ if(current_node == current_node->parent->left_child){ if(current_node->right_child != NULL){ inorder_successor_node = SearchLeftMostEngine(current_node->right_child); }else{ inorder_successor_node = current_node->parent; } }else if(current_node == current_node->parent->right_child){ inorder_successor_node = current_node->right_child; } } return inorder_successor_node; } BSTNode* BST::FindInOrderPreDecessor(BSTNode* current_node){ BSTNode* inorder_predecessor_node = NULL; if(current_node->parent == NULL){ inorder_predecessor_node = SearchRightMostEngine(current_node->left_child); }else{ if(current_node == current_node->parent->right_child){ if(current_node->left_child != NULL){ inorder_predecessor_node = SearchRightMostEngine(current_node->left_child); }else{ inorder_predecessor_node = current_node->parent; } }else if(current_node == current_node->parent->left_child){ inorder_predecessor_node = current_node->left_child; } } return inorder_predecessor_node; } void BST::SearchInorderSuccessorOfSmallestPrint(){ BSTNode* smallest_node = SearchLeftMostEngine(root); if(smallest_node == NULL){ std::cout<<"not found smallest node in BST::SearchInorderSuccessorOfSmallestPrint"<<std::endl; return; } BSTNode* successor_of_smallest_node = FindInOrderSuccessor(smallest_node); if(successor_of_smallest_node == NULL){ std::cout<<"not found successor of smallest node in BST::SearchInorderSuccessorOfSmallestPrint"<<std::endl; return; } std::cout<<"successor of smallest = "<<successor_of_smallest_node->key<<std::endl; } void BST::SearchInorderPreDecessorOfBiggestPrint(){ BSTNode* biggest_node = SearchRightMostEngine(root); if(biggest_node == NULL){ std::cout<<"not found biggest node in BST::SearchInorderPreDecessorOfBiggestPrint"<<std::endl; return; } BSTNode* predecessor_of_biggest_node = FindInOrderPreDecessor(biggest_node); if(predecessor_of_biggest_node == NULL){ std::cout<<"not found predecessor of biggest node in BST::SearchInorderPreDecessorOfBiggestPrint"<<std::endl; return; } std::cout<<"predecessor of biggest = "<<predecessor_of_biggest_node->key<<std::endl; } void BST::DeleteArbitrary(const int key){ BSTNode* found_node = NULL; BSTNode* found_parent_node = NULL; Search(key, found_node, found_parent_node); if(found_node == NULL){ std::cout<<"cannot find the node with key = "<<key<<std::endl; return; } while(found_node!=NULL){ if(found_parent_node == NULL){//root BSTNode* successor_node = FindInOrderSuccessor(found_node); if(successor_node == successor_node->parent->left_child){ successor_node->parent->left_child = NULL; }else if(successor_node == successor_node->parent->right_child){ successor_node->parent->right_child = NULL; } found_node->key = successor_node->key; delete successor_node; }else{ if((found_node->left_child == NULL) && (found_node->right_child == NULL)){ if(found_node == found_parent_node->right_child){ found_parent_node->right_child = NULL; }else if(found_node == found_parent_node->left_child){ found_parent_node->left_child = NULL; } delete found_node; }else if((found_node->left_child != NULL) && (found_node->right_child != NULL)){ BSTNode* successor_node = FindInOrderSuccessor(found_node); if(successor_node == successor_node->parent->left_child){ successor_node->parent->left_child = NULL; }else if(successor_node == successor_node->parent->right_child){ successor_node->parent->right_child = NULL; } found_node->key = successor_node->key; delete successor_node; }else if((found_node->left_child == NULL) && (found_node->right_child != NULL)){ if(found_node == found_parent_node->right_child){ found_parent_node->right_child = found_node->right_child; }else if(found_node == found_parent_node->left_child){ found_parent_node->left_child = found_node->right_child; } delete found_node; }else{ if(found_node == found_parent_node->right_child){ found_parent_node->right_child = found_node->left_child; }else if(found_node == found_parent_node->left_child){ found_parent_node->left_child = found_node->left_child; } delete found_node; } } --size_of_tree; Search(key, found_node, found_parent_node); } } void BST::ConstructBSTUsingSorting(const int* const L, const int size){ int set_index = 0; BSTNode* root_node = new BSTNode; std::queue<BSTNode*> construct_queue; construct_queue.push(root_node); ++size_of_tree; root = root_node; while(!construct_queue.empty()){ int remain_num = size - size_of_tree; BSTNode* current_node = construct_queue.front(); construct_queue.pop(); if(remain_num >= 2){ BSTNode* left_node = new BSTNode; BSTNode* right_node = new BSTNode; current_node->left_child = left_node; current_node->left_child->parent = current_node; current_node->right_child = right_node; current_node->right_child->parent = current_node; size_of_tree += 2; construct_queue.push(left_node); construct_queue.push(right_node); }else if(remain_num == 1){ BSTNode* left_node = new BSTNode; current_node->left_child = left_node; current_node->left_child->parent = current_node; ++size_of_tree; construct_queue.push(left_node); }else{ break; } } //Inorder Traversal to put value into BST InOrderTraverseSetEngine(root, set_index, L); }
#include <bitset> #include <boost/log/trivial.hpp> #include "subgraph.hpp" int FindMaxIndependentSubGraph(const SubGraph &graph); int FindMaxIndependentSetInConnectedSubGraph(const SubGraph &graph) { if (graph.VerticesCount() < 2) { return 1; } auto degrees = graph.GetVerticesDegrees(); std::sort(degrees.begin(), degrees.end()); auto[degree, vertex] = degrees.front(); auto children = graph.GetChildren(vertex); int set = ~GetVertexId(vertex) & ~GetVertexSetFromVector(children); // 1 if (degree == 1) { int to = graph.GetChildren(vertex).front(); return 1 + FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(vertex) & ~GetVertexId(to))); } // 2 if (degree == 2) { // 2.1 if (degrees.back().first == 2) { return graph.VerticesCount() / 2; } // 2.2 if (graph.graph.HasEdge(children.front(), children.back())) { return 1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)); } // 2.3 return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(~GetVertexSetFromVector(graph.GetChildren(children.front())) & ~GetVertexSetFromVector(graph.GetChildren(children.back()))))); } // 3 if (degree == 3) { // 3.1 if (graph.graph.HasEdge(children[0], children[1]) && graph.graph.HasEdge(children[1], children[2]) && graph.graph.HasEdge(children[2], children[0])) { return 1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)); } // 3.2 for (int i = 0; i < 3; i++) { if (graph.graph.HasEdge(children[i], children[(i + 1) % 3]) && graph.graph.HasEdge(children[i], children[(i + 2) % 2])) { return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph( ~GetVertexSetFromVector(graph.GetChildren(children[(i + 1) % 3])) & ~GetVertexSetFromVector(graph.GetChildren(children[(i + 2) % 3]))))); } } // 3.3 std::vector<VertexSet> a(3); for (int i = 0; i < 3; i++) { a[i] = graph.set & ~GetVertexSetFromVector(children) & ~GetVertexSetFromVector(graph.GetChildren(children[i])); } VertexSet all_a = a[0] & a[1] & a[2]; for (int i = 0; i < 3; i++) { if (graph.graph.HasEdge(children[i], children[(i + 1) % 3])) { // 3.3.1 if ((VerticesCount(a[i] & a[(i + 2) % 3]) <= VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) && VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) == graph.VerticesCount() - 6) || (VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) <= VerticesCount(a[i] & a[(i + 2) % 3]) && VerticesCount(a[i] & a[(i + 2) % 3]) == graph.VerticesCount() - 6)) { return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[(i + 2) % 3]))); } // 3.3.2 return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 2) % 3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[(i + 1) % 3] & a[(i + 2) % 3])),}); } } // 3.4 // 3.4.1 if (VerticesCount(all_a) >= graph.VerticesCount() - 7) { return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))); } // 3.4.2 if (VerticesCount(all_a) == graph.VerticesCount() - 8 || VerticesCount(all_a) == graph.VerticesCount() - 9) { // 3.4.2.2 for (int i = 0; i < 3; i++) { if (VerticesCount(a[i] & a[(i + 1) % 3]) >= VerticesCount(all_a) + 2) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 1) % 3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } } // 3.4.2.1 return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))); } // 3.4.3 // 3.4.3.1 if (VerticesCount(a[0] & a[1]) <= VerticesCount(all_a) + 1 && VerticesCount(a[1] & a[2]) <= VerticesCount(all_a) + 1 && VerticesCount(a[2] & a[0]) <= VerticesCount(all_a) + 1) { return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))); } // 3.4.3.2 for (int i = 0; i < 3; i++) { if (VerticesCount(a[i] & a[(i + 1) % 3]) >= VerticesCount(all_a) + 2 && VerticesCount(a[i] & a[(i + 2) % 3]) <= VerticesCount(all_a) + 1 && VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) <= VerticesCount(all_a) + 1) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 1) % 3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } } // 3.4.3.3 for (int i = 0; i < 3; i++) { if (VerticesCount(a[i] & a[(i + 1) % 3]) >= VerticesCount(all_a) + 2 && VerticesCount(a[i] & a[(i + 2) % 3]) >= VerticesCount(all_a) + 2 && VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) <= VerticesCount(all_a) + 1) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 1) % 3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 2) % 3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } } // 3.4.3.4 std::vector<std::pair<Vertex, Vertex>> u(3); std::vector<VertexSet> Au(3); for (int i = 0; i < 3; i++) { u[i] = graph.GetSubGraph(a[i] & a[(i + 1) % 3] & ~a[(i + 2) % 3]).GetPair(); Au[i] = ~GetVertexSetFromVector(graph.GetChildren(u[i].first)) & ~GetVertexSetFromVector(graph.GetChildren(u[i].second)); } // 3.4.3.4.1 for (int i = 0; i < 3; i++) { if (VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) == VerticesCount(all_a) + 2 && graph.graph.HasEdge(u[i].first, u[i].second)) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 1) % 3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 2) % 3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } } // 3.4.3.4.2 if (VerticesCount(a[0] & a[1]) == VerticesCount(all_a) + 2 && VerticesCount(a[1] & a[2]) == VerticesCount(all_a) + 2 && VerticesCount(a[2] & a[0]) == VerticesCount(all_a) + 2) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a & Au[0])), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a & Au[1])), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a & Au[2])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } // 3.4.3.4.3 for (int i = 0; i < 3; i++) { if (VerticesCount(a[i] & a[(i + 1) % 3]) == VerticesCount(all_a) + 2 && VerticesCount(a[i] & a[(i + 2) % 3]) == VerticesCount(all_a) + 2 && VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) != VerticesCount(all_a) + 2) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a & Au[(i + 1) % 3])), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a & Au[(i + 2) % 3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[(i + 1) % 3] & a[(i + 2) % 3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } } // 3.4.3.4.4 for (int i = 0; i < 3; i++) { if (VerticesCount(a[i] & a[(i + 1) % 3]) != VerticesCount(all_a) + 2 && VerticesCount(a[i] & a[(i + 2) % 3]) != VerticesCount(all_a) + 2 && VerticesCount(a[(i + 1) % 3] & a[(i + 2) % 3]) == VerticesCount(all_a) + 2) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a & Au[i])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 1) % 3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 2) % 3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } } // 3.4.3.4.5 return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[0] & a[1])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[1] & a[2])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[2] & a[0])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(all_a))}); } // 4 if (degree == 4) { // 4.1 if (degrees.back().first == 4) { // 4.1.1 Vertex v = -1, w = -1; VertexSet Av, Aw; for (int i = 0; i < degrees.size() && degrees[i].first == 4 && v == -1; i++) { for (int j = degrees.size() - 1; j >= 0 && degrees[j].first != 4 && w == -1; j--) { if (!graph.graph.HasEdge(degrees[i].second, degrees[j].second) && VerticesCount(GetVertexSetFromVector(graph.GetChildren(degrees[i].second)) & GetVertexSetFromVector(graph.GetChildren(degrees[j].second))) >= 2) { v = degrees[i].second; Av = graph.set & ~GetVertexId(v) & ~GetVertexSetFromVector(graph.GetChildren(v)); w = degrees[j].second; Aw = graph.set & ~GetVertexId(w) & ~GetVertexSetFromVector(graph.GetChildren(w)); } } } if (v != -1) { // 4.1.1.1 if (VerticesCount(GetVertexSetFromVector(graph.GetChildren(v)) & GetVertexSetFromVector(graph.GetChildren(w))) >= 3) { return std::max(2 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(v) & ~GetVertexId(w)))); } // 4.1.1.2 auto[x, y] = graph.GetSubGraph(GetVertexSetFromVector(graph.GetChildren(v)) & ~GetVertexSetFromVector(graph.GetChildren(w))).GetPair(); VertexSet Ax = graph.set & ~GetVertexId(x) & ~GetVertexSetFromVector(graph.GetChildren(x)); VertexSet Ay = graph.set & ~GetVertexId(y) & ~GetVertexSetFromVector(graph.GetChildren(y)); auto[q, r] = graph.GetSubGraph(GetVertexSetFromVector(graph.GetChildren(w)) & ~GetVertexSetFromVector(graph.GetChildren(v))).GetPair(); VertexSet Aq = graph.set & ~GetVertexId(q) & ~GetVertexSetFromVector(graph.GetChildren(q)); VertexSet Ar = graph.set & ~GetVertexId(r) & ~GetVertexSetFromVector(graph.GetChildren(r)); // 4.1.1.2.1 if (graph.graph.HasEdge(x, y) && graph.graph.HasEdge(q, r)) { return std::max(2 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(v) & ~GetVertexId(w)))); } // 4.1.1.2.2 if (graph.graph.HasEdge(x, y) && !graph.graph.HasEdge(q, r)) { return std::max({2 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw & Aq & Ar)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(v) & ~GetVertexId(w)))}); } if (!graph.graph.HasEdge(x, y) && graph.graph.HasEdge(q, r)) { return std::max({2 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw & Ax & Ay)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(v) & ~GetVertexId(w)))}); } // 4.1.1.2.3 if (VerticesCount(Av & Aw & Ax & Ay) >= graph.VerticesCount() - 9 || VerticesCount(Av & Aw & Aq & Ar) >= graph.VerticesCount() - 9) { return std::max({3 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw & Aq & Ar)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw & Ax & Ay)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(v) & ~GetVertexId(w)))}); } // 4.1.1.2.4 return std::max({2 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw & Aq & Ar)), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(Av & Aw & Ax & Ay)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(v) & ~GetVertexId(w)))}); } // 4.1.2 std::vector<VertexSet> a(4); for (int i = 0; i < 4; i++) { a[i] = graph.set & ~GetVertexSetFromVector(graph.GetChildren(v)) & ~GetVertexSetFromVector(graph.GetChildren(children[i])); } v = degrees.front().second; Av = graph.set & ~GetVertexId(v) & ~GetVertexSetFromVector(graph.GetChildren(v)); // 4.1.2.1 for (int i = 0; i < 4; i++) { if (graph.graph.HasEdge(children[i], children[(i + 1) % 4]) && graph.graph.HasEdge(children[i], children[(i + 2) % 4]) && graph.graph.HasEdge(children[i], children[(i + 3) % 4])) { return 1; } } // 4.1.2.2 for (int i = 0; i < 4; i++) { if (!graph.graph.HasEdge(children[i], children[(i + 1) % 4]) && !graph.graph.HasEdge(children[i], children[(i + 2) % 4]) && !graph.graph.HasEdge(children[i], children[(i + 3) % 4]) && graph.graph.HasEdge(children[(i + 1) % 4], children[(i + 2) % 4]) && graph.graph.HasEdge(children[(i + 2) % 4], children[(i + 3) % 4]) && graph.graph.HasEdge(children[(i + 3) % 4], children[(i + 1) % 4])) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 1) % 4])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 2) % 4])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[i] & a[(i + 3) % 4]))}); } } // 4.1.2.3 std::vector<std::pair<int, int>> ids; for (int i = 0; i < 4; i++) { for (int j = i + 1; j < 4; j++) { ids.emplace_back(i, j); } } for (int i = 0; i < 3; i++) { if (graph.graph.HasEdge(children[ids[i].first], children[ids[i].second]) && graph.graph.HasEdge(children[ids[5 - i].first], children[ids[5 - i].second]) && !graph.graph.HasEdge(children[ids[(i + 1) % 3].first], children[ids[(i + 1) % 3].second]) && !graph.graph.HasEdge(children[ids[5 - (i + 1) % 3].first], children[ids[5 - (i + 1) % 3].second]) && !graph.graph.HasEdge(children[ids[(i + 2) % 3].first], children[ids[(i + 2) % 3].second]) && !graph.graph.HasEdge(children[ids[5 - (i + 2) % 3].first], children[ids[5 - (i + 2) % 3].second])) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].first] & a[ids[5 - i].first])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].first] & a[ids[5 - i].second])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].second] & a[ids[5 - i].first])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].second] & a[ids[5 - i].second]))}); } } // 4.1.2.4 for (int i = 0; i < 6; i++) { if (graph.graph.HasEdge(children[ids[i].first], children[ids[i].second])) { return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].first] & a[ids[5 - i].first])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].first] & a[ids[5 - i].second])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].second] & a[ids[5 - i].first])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[i].second] & a[ids[5 - i].second])), 2 + FindMaxIndependentSubGraph( graph.GetSubGraph(a[ids[5 - i].first] & a[ids[5 - i].second])), 3 + FindMaxIndependentSubGraph( graph.GetSubGraph( a[ids[i].first] & a[ids[5 - i].first] & a[ids[5 - i].second])), 3 + FindMaxIndependentSubGraph( graph.GetSubGraph( a[ids[i].second] & a[ids[5 - i].first] & a[ids[5 - i].second]))}); } } // 4.1.2.5 return std::max({1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[0] & a[1])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[0] & a[2])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[0] & a[3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[1] & a[2])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[1] & a[3])), 2 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[2] & a[3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[0] & a[1] & a[2])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[1] & a[2] & a[3])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[2] & a[3] & a[0])), 3 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[3] & a[0] & a[1])), 4 + FindMaxIndependentSubGraph(graph.GetSubGraph(a[0] & a[1] & a[2] & a[3]))}); } // 4.2 for (int i = 0; i < degrees.size() && degrees[i].first == 4; i++) { Vertex v = degrees[i].second; for (int j = degrees.size() - 1; j >= 0 && degrees[j].first != 4; j--) { Vertex w = degrees[j].second; if (graph.graph.HasEdge(degrees[i].second, degrees[j].first)) { return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(w) & ~GetVertexSetFromVector( graph.GetChildren(w)))), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(w)))); } } } } // 5 if (degrees.front().first == 5 && degrees.back().first == 5) { // 5.1 if (graph.VerticesCount() == 6) { return 1; } // 5.2 return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(vertex)))); } // 6 vertex = degrees.back().second; children = graph.GetChildren(vertex); set = ~GetVertexId(vertex) & ~GetVertexSetFromVector(children); return std::max(1 + FindMaxIndependentSubGraph(graph.GetSubGraph(set)), FindMaxIndependentSubGraph(graph.GetSubGraph(~GetVertexId(vertex)))); } int FindMaxIndependentSubGraph(const SubGraph &graph) { BOOST_LOG_TRIVIAL(info) << "Start finding max independent set"; BOOST_LOG_TRIVIAL(info) << "Vertices mask : " << std::bitset<MAX_VERTICES_COUNT>(graph.set); auto connected_sets = graph.GetConnectedSubGraphs(); BOOST_LOG_TRIVIAL(info) << "Connected subgraphs : " << connected_sets.size(); int result = 0; int set_id = 1; for (const auto &connected : connected_sets) { BOOST_LOG_TRIVIAL(info) << "Finding in " << set_id << " subgraph"; result += FindMaxIndependentSetInConnectedSubGraph(connected); set_id++; } BOOST_LOG_TRIVIAL(info) << "Independent set size: " << result << ", mask: " << std::bitset<MAX_VERTICES_COUNT>(graph.set); return result; }
#include "Transform2DComponent.hpp" Transform2DComponent::Transform2DComponent(Entity* parent) : Transform2DComponent(parent, {0.0F, 0.0F}, 0.0F, {1.0F, 1.0F}) {} Transform2DComponent::Transform2DComponent(Entity* parent, vec2 position) : Transform2DComponent(parent, position, 0.0F, {1.0F, 1.0F}) {} Transform2DComponent::Transform2DComponent(Entity* parent, vec2 position, f32 orientation) : Transform2DComponent(parent, position, orientation, {1.0F, 1.0F}) {} Transform2DComponent::Transform2DComponent(Entity * parent, vec2 position, f32 orientation, f32 scale) : Transform2DComponent(parent, position, orientation, {scale, scale}) {} Transform2DComponent::Transform2DComponent(Entity* parent, vec2 position, f32 orientation, vec2 scale) : Component(parent), position(position), orientation(orientation), scale(scale) {} void Transform2DComponent::update() {}
#include <QDataStream> #include <QByteArray> #include <QBuffer> #include "wevent.h" #include "wmessage.h" #include "wsetid.h" #include "wnickrequest.h" #include "wnickresponse.h" #include "wclientlist.h" #include <iostream> using std::cout; using std::endl; WEvent::WEvent(quint64 senderId_p, typeId eventType_p): eventType(eventType_p), senderId(senderId_p) { } WEvent::WEvent(typeId eventType_p): eventType(eventType_p), senderId(0) { } WEvent::typeId WEvent::getEventType() const { return eventType; } quint64 WEvent::getSenderId() const { return senderId; } QDataStream & WEvent::serialize(QDataStream& out) const { out << eventType << senderId; return out; } QDataStream & WEvent::deserialize(QDataStream& in) { in >> senderId; return in; } WEvent* WEvent::createFromQByteArray(const QByteArray & ba) { QDataStream ds(ba); WEvent *ret; int id; ds >> id; switch (id) { case WEvent::tWEvent: ret = new WEvent(); break; case WEvent::tWMessage: ret = new WMessage(); break; case WEvent::tWSetId: ret = new WSetId(); break; case WEvent::tWNickRequest: ret = new WNickRequest(); break; case WEvent::tWNickResponse: ret = new WNickResponse(); break; case WEvent::tWClientList: ret = new WClientList(); break; } ret->deserialize(ds); return ret; } QByteArray WEvent::serializeToQByteArray(WEvent* ev) { QByteArray ba; QBuffer bufo(&ba); bufo.open(QIODevice::WriteOnly); QDataStream ds(&bufo); ev->serialize(ds); bufo.close(); return ba; }
#ifndef CREQUESTXMLMESSAGE_H #define CREQUESTXMLMESSAGE_H #include "CMessage.h" #include <QObject> //ÇëÇóXMLÏûÏ¢ class CRequestXmlMessage : public CMessage { Q_OBJECT public: CRequestXmlMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent = 0); ~CRequestXmlMessage(); virtual void packedSendMessage(NetMessage& netMessage); virtual bool treatMessage(const NetMessage& netMessage, CMessageFactory* pFactory, SocketContext* clientSocket); }; #endif //CREQUESTXMLMESSAGE_H
// Replace all pi in a string with 3.14 using rec. #include<iostream> using namespace std; void replaceAllPi(char a[],int i) { // base case if(a[i]=='\0' || a[i+1]=='\0') return; // Look for pi for current location if(a[i]=='p' && a[i+1]=='i') { int j=i+2; // take j to the end of the array while(a[j]!='\0') j++; // shifting right to left while(j>=i+2) { a[j+2]=a[j]; j--; } // replace +recursive call for rem part a[i]='3'; a[i+1]='.'; a[i+2]='1'; a[i+3]='4'; replaceAllPi(a,i+4); } else replaceAllPi(a,i+1); } int main(int argc, char const *argv[]) { char arr[1000]; cin>>arr; replaceAllPi(arr,0); cout<<arr; return 0; }
// overlap_eigensystem_template_device.h // Andrei Alexandru // Dec 2003 #include "complex.h" #include "overlap.h" #include "../eigensystem/arnoldi.h" #include "cpu_vector.h" #include "layout.h" #include "defines.h" #include "small_eigenvalues.h" #include "random_vectors.h" #include "overlap_eigensystem_template.h" namespace qcd { typedef qcd::device_wilson_field dvector; // This routine will be used to guess the chiral sector // that has the zero modes: for example using the topological // charge defined in terms of few gauge loops. //this function passes returns the converged //vectors on the device int hermprojoverlapEigensys_small_mix( double error, int maxiter, double cutoff, int nextraevec, vec_eigen_pair<dvector> &doe, matmult<dvector> &zov, int chirality, vector &vecStart) { vec_eigen_pair<vector> oe(*(&doe.size), *vecStart.desc); // First find a number of small eigenvalues gamma5_projection(vecStart, vecStart, chirality); hermprojoverlap<dvector> hov(chirality, zov); device_matmult_adapter mult_d(hov, vecStart.desc); int nconverged = arnoldi_eigensystem(mult_d, vecStart, oe.eval, oe.evec, oe.size, nextraevec, error, maxiter, &resmaller, cutoff, SYM); for(int i=0; i< oe.size;i++) { copy_vector_to_device(*oe.evec[i],*doe.evec[i]); doe.eval[i] = oe.eval[i]; } return nconverged; } //this function passes returns the converged //vectors on the cpu int hermprojoverlapEigensys_small_mix( double error, int maxiter, double cutoff, int nextraevec, vec_eigen_pair<vector> &oe, matmult<dvector> &zov, int chirality, vector &vecStart) { // First find a number of small eigenvalues gamma5_projection(vecStart, vecStart, chirality); hermprojoverlap<dvector> hov(chirality, zov); device_matmult_adapter mult_d(hov, vecStart.desc); int nconverged = arnoldi_eigensystem(mult_d, vecStart, oe.eval, oe.evec, oe.size, nextraevec, error, maxiter, &resmaller, cutoff, SYM); return nconverged; } //restart for vectors returned on the device int hermprojoverlapEigensys_small_restart_mix( double error, int maxiter, int nextraevec, vec_eigen_pair<dvector> &doe, matmult<dvector> &zov, int chirality, int iseed) { hermprojoverlap<dvector> hov(chirality, zov); vector vecStart(doe.evec[0]->desc); vec_eigen_pair<vector> oe(*(&doe.size), *vecStart.desc); for(int i=0; i< oe.size;i++) { copy_vector_from_device(*doe.evec[i],*oe.evec[i]); oe.eval[i] = doe.eval[i]; } // just set the starting vector to the sum of eigenvectors // not ideal but it does speed up the convergence a bit for(int i=0; i<oe.size; ++i) vecStart = *oe.evec[i] + vecStart; double cutoff = 2*oe.eval[oe.size-1].real; // make it bigger than the largest one device_matmult_adapter mult_d(hov, vecStart.desc); int nconverged = arnoldi_eigensystem(mult_d, vecStart, oe.eval, oe.evec, oe.size, nextraevec, error, maxiter, &resmaller, cutoff, SYM); for(int i=0; i< oe.size;i++) { copy_vector_to_device(*oe.evec[i],*doe.evec[i]); doe.eval[i] = oe.eval[i]; } return nconverged; } //restart for vectors returned on the cpu int hermprojoverlapEigensys_small_restart_mix( double error, int maxiter, int nextraevec, vec_eigen_pair<vector> &oe, matmult<dvector> &zov, int chirality, int iseed) { hermprojoverlap<dvector> hov(chirality, zov); vector vecStart(oe.evec[0]->desc); // just set the starting vector to the sum of eigenvectors // not ideal but it does speed up the convergence a bit for(int i=0; i<oe.size; ++i) vecStart = *oe.evec[i] + vecStart; double cutoff = 2*oe.eval[oe.size-1].real; // make it bigger than the largest one device_matmult_adapter mult_d(hov, vecStart.desc); int nconverged = arnoldi_eigensystem(mult_d, vecStart, oe.eval, oe.evec, oe.size, nextraevec, error, maxiter, &resmaller, cutoff, SYM); return nconverged; } }
// // Created by 邦邦 on 2022/4/22. // #ifndef BB_TIME_H #define BB_TIME_H #include <thread> namespace bb{ class Time{ static void test_(const int &second){ //process_time/60 //距离现在的分钟数 //process_time/3600 //距离现在的小时数60*60 //process_time/86400 //距离现在的天数60*60*24 std::this_thread::sleep_for(std::chrono::hours(second)); //小时 std::this_thread::sleep_for(std::chrono::minutes(second)); //分钟 std::this_thread::sleep_for(std::chrono::seconds(second)); //秒 std::this_thread::sleep_for(std::chrono::milliseconds(second)); //毫秒 std::this_thread::sleep_for(std::chrono::microseconds(second)); //微秒 std::this_thread::sleep_for(std::chrono::nanoseconds(second)); //纳秒 } public: static void sleep(const int &second); //获取当前时间戳,自 1970-01-01 起的(秒) static time_t getTime(); //获取当前年、月、日、时间格式 static std::string getDate(const char format[]="%Y-%m-%d %H:%M:%S",const time_t &target_time=time(nullptr)); //获取当前时间,距离目标时间 static std::string getDateAuto(const time_t &target_time=0); }; } #endif //BB_TIME_H
class Category_51 { class ItemSilverBar { type = "trade_items"; buy[] = {1,"worth"}; sell[] = {1,"worth"}; }; class ItemSilverBar2oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {2,"worth"}; }; class ItemSilverBar3oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {3,"worth"}; }; class ItemSilverBar4oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {4,"worth"}; }; class ItemSilverBar5oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {5,"worth"}; }; class ItemSilverBar6oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {6,"worth"}; }; class ItemSilverBar7oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {7,"worth"}; }; class ItemSilverBar8oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {8,"worth"}; }; class ItemSilverBar9oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {9,"worth"}; }; class ItemSilverBar10oz { type = "trade_items"; buy[] = {10,"worth"}; sell[] = {10,"worth"}; }; class ItemBriefcaseS10oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {10,"worth"}; }; class ItemBriefcaseS20oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {20,"worth"}; }; class ItemBriefcaseS30oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {30,"worth"}; }; class ItemBriefcaseS40oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {40,"worth"}; }; class ItemBriefcaseS50oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {50,"worth"}; }; class ItemBriefcaseS60oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {60,"worth"}; }; class ItemBriefcaseS70oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {70,"worth"}; }; class ItemBriefcaseS80oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {80,"worth"}; }; class ItemBriefcaseS90oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {90,"worth"}; }; class ItemBriefcaseS100oz { type = "trade_items"; buy[] = {100,"worth"}; sell[] = {100,"worth"}; }; class ItemGoldBar { type = "trade_items"; buy[] = {100,"worth"}; sell[] = {100,"worth"}; }; class ItemGoldBar2oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {200,"worth"}; }; class ItemGoldBar3oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {300,"worth"}; }; class ItemGoldBar4oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {400,"worth"}; }; class ItemGoldBar5oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {500,"worth"}; }; class ItemGoldBar6oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {600,"worth"}; }; class ItemGoldBar7oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {700,"worth"}; }; class ItemGoldBar8oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {800,"worth"}; }; class ItemGoldBar9oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {900,"worth"}; }; class ItemGoldBar10oz { type = "trade_items"; buy[] = {1000,"worth"}; sell[] = {1000,"worth"}; }; class ItemBriefcase10oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {1000,"worth"}; }; class ItemBriefcase20oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {2000,"worth"}; }; class ItemBriefcase30oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {3000,"worth"}; }; class ItemBriefcase40oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {4000,"worth"}; }; class ItemBriefcase50oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {5000,"worth"}; }; class ItemBriefcase60oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {6000,"worth"}; }; class ItemBriefcase70oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {7000,"worth"}; }; class ItemBriefcase80oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {8000,"worth"}; }; class ItemBriefcase90oz { type = "trade_items"; buy[] = {-1,"worth"}; sell[] = {9000,"worth"}; }; class ItemBriefcase100oz { type = "trade_items"; buy[] = {10000,"worth"}; sell[] = {10000,"worth"}; }; class ItemTopaz { type = "trade_items"; buy[] = {15000,"worth"}; sell[] = {15000,"worth"}; }; class ItemObsidian { type = "trade_items"; buy[] = {20000,"worth"}; sell[] = {20000,"worth"}; }; class ItemSapphire { type = "trade_items"; buy[] = {25000,"worth"}; sell[] = {25000,"worth"}; }; class ItemAmethyst { type = "trade_items"; buy[] = {30000,"worth"}; sell[] = {30000,"worth"}; }; class ItemEmerald { type = "trade_items"; buy[] = {35000,"worth"}; sell[] = {35000,"worth"}; }; class ItemCitrine { type = "trade_items"; buy[] = {40000,"worth"}; sell[] = {40000,"worth"}; }; class ItemRuby { type = "trade_items"; buy[] = {45000,"worth"}; sell[] = {45000,"worth"}; }; };
#ifndef _TASK_QUEUE_I_ #define _IASK_QUEUE_I_ #include <list> #include <vector> using namespace std; namespace ff { typedef void(*task_func_t)(void *); class task_impl_i { public: virtual ~task_impl_i(){} virtual void run()=0; virtual task_impl_i *fork()=0; }; class task_impl_t:public task_impl_i { }; struct task_t { }; class task_queue_i { public: typedef list<task_t> task_list_t; public: virtual ~task_queue_i(){} }; } #endif
// $Id$ #ifndef MESSAGEQ_H #define MESSAGEQ_H #define MAX_MESSAGE_LENGTH 100 typedef struct MessageFormat { long message_type; char mess[MAX_MESSAGE_LENGTH]; } tMessageFormat; class CMessageQueue { public: CMessageQueue(); ~CMessageQueue(); void Send(tMessageFormat* message, int message_size); bool Receive(long message_type, tMessageFormat* message, int& message_size); private: int mID; }; #endif
#include "ObjLoader.h" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <map> #include <sstream> #include <GLGraphics/ResourceLoader.h> using namespace std; using namespace CGLA; using namespace Mesh; namespace Mesh { Vec3f to_vec3(istringstream &iss){ float x,y,z; if (iss.good()){ iss >> x; } if (iss.good()){ iss >> y; } if (iss.good()){ iss >> z; } return Vec3f(x,y,z); } Vec2f to_vec2(istringstream &iss){ float x,y; if (iss.good()){ iss >> x; } if (iss.good()){ iss >> y; } return Vec2f(x,y); } struct TriangleIndex{ int position; int normal; int uv; bool replace(std::string& str, const std::string& from, const std::string& to) { size_t start_pos = str.find(from); if(start_pos == std::string::npos) return false; str.replace(start_pos, from.length(), to); return true; } TriangleIndex(string p):position(-1),normal(-1),uv(-1) { // position/uv/normal replace(p, "//","/-1/"); stringstream ss(p); char buffer[50]; ss.getline(buffer,50, '/'); position = atoi(buffer); if (ss.good()){ ss.getline(buffer,50, '/'); uv = atoi(buffer); } if (ss.good()){ ss.getline(buffer,50, '/'); normal = atoi(buffer); } } // needed to use TriangleIndex as key in map bool operator <(const TriangleIndex& Rhs) const { return (position < Rhs.position) || (position == Rhs.position && normal < Rhs.normal) || (position == Rhs.position && normal == Rhs.normal && uv < Rhs.uv); } }; struct TriangleString{ TriangleIndex v0; TriangleIndex v1; TriangleIndex v2; int materialIndex; TriangleString(string v0, string v1, string v2, int materialIndex):v0(v0),v1(v1),v2(v2),materialIndex(materialIndex){ } TriangleIndex get(int index){ if (index == 0) { return v0; } else if (index == 1) { return v1; } return v2; } }; string get_path(const string& _filename) { // Make sure we only have slashes and not backslashes string filename = _filename; replace(filename.begin(),filename.end(),'\\','/'); // Find the last occurrence of slash. // Everything before is path. size_t n = filename.rfind("/"); if(n > filename.size()) return "./"; string pathname = ""; pathname.assign(filename,0,n); pathname.append("/"); return pathname; } vector<Material> load_material(const string& path, const string& filename){ const string materialSource = GLGraphics::ResourceLoader::load_text_resource(path+filename); vector<Material> materials; istringstream ifs(materialSource); char buf[512]; int nummaterials=-1; while(ifs.good()) { ifs.getline(buf,512); string line(buf); istringstream material_file(line); if (material_file.good() && line.length()>0){ string token; material_file >> token; switch(token[0]) { case 'n': // newmtl materials.push_back(Material()); ++nummaterials; if (material_file.good()){ material_file >> materials[nummaterials].name; } break; case 'N': switch(token[1]) { case 's': if (material_file.good()){ material_file >> materials[nummaterials].shininess; } materials[nummaterials].shininess *= 128.0f/1000.0f; break; case 'i': if (material_file.good()){ material_file >> materials[nummaterials].ior; } break; } break; case 'K': switch(token[1]) { case 'd': materials[nummaterials].diffuse = Vec4f(to_vec3(material_file),1.0); break; case 's': materials[nummaterials].specular = Vec4f(to_vec3(material_file)); break; case 'a': materials[nummaterials].ambient = Vec4f(to_vec3(material_file)); break; } break; case 'T': switch(token[1]) { case 'f': materials[nummaterials].transmission = Vec4f(to_vec3(material_file)); break; } break; case 'i': if (material_file.good()){ material_file >> materials[nummaterials].illum; } break; case 'm': // Map ... all maps are treated equally. if (material_file.good() && token == "map_Kd"){ string name; material_file >> name; string texname = GLGraphics::ResourceLoader::compute_resource_path(path + name); materials[nummaterials].tex_map.load(texname); materials[nummaterials].has_texture = true; } break; case '#': default: material_file.ignore(1024, '\n'); break; } } } return materials; } bool ObjLoader::load_object(const char * filename, vector<Vec3f> *outPositions, vector<vector<GLuint> > *outIndices, vector<Material> *outMaterials, vector<Vec3f> *outNormal, vector<Vec2f> *outUv, float scale){ vector<Vec3f> positions; vector<Vec3f> normals; vector<Vec2f> uvs; const string path = get_path(filename); string resource = GLGraphics::ResourceLoader::load_text_resource(filename); vector<TriangleString> triangles; map<string, int> materialIndexMap; // maps from material index to material name istringstream ifs(resource); unsigned int currentMaterialIndex = 0; char buffer[512]; while (ifs.good()){ ifs.getline(buffer,512); string line(buffer); istringstream iss(line); if (iss.good() && line.length()>0){ string token; iss >> token; if (token.compare("o")==0){ // does not support multiple objects } else if (token.compare("mtllib")==0){ // does not support multiple materials string matFilename; iss >> matFilename; vector<Material> materials = load_material(path, matFilename); for (unsigned int i=0;i< materials.size();i++){ size_t materialIndex = outMaterials->size(); outMaterials->push_back(materials[i]); string materialName = materials[i].name; materialIndexMap[materialName] = static_cast<int>(materialIndex); } } else if (token.compare("usemtl")==0){ // does not support multiple materials string name; iss >> name; map<string, int>::const_iterator namePos = materialIndexMap.find(name); if (namePos == materialIndexMap.end()){ cout << "Could not find material "<<name.c_str() << endl; currentMaterialIndex = 0; } else { currentMaterialIndex = materialIndexMap[name]; } } else if (token.compare("v")==0){ positions.push_back( to_vec3(iss)); } else if (token.compare("vn")==0){ normals.push_back( to_vec3(iss)); } else if (token.compare("vt")==0){ uvs.push_back( to_vec2(iss)); } else if (token.compare("f")==0){ vector<string> polygon; do { string index; iss >> index; if (index.length() > 0) { polygon.push_back(index); } } while (iss); // triangulate pologon TriangleString triangle(polygon[0], polygon[1], polygon[2], currentMaterialIndex); triangles.push_back(triangle); for (unsigned int i=3;i<polygon.size();i++){ TriangleString triangle2(polygon[i-1], polygon[i], polygon[0], currentMaterialIndex); triangles.push_back(triangle2); } } else if (token.compare("g")==0){ // group name not supported } else if (token.compare("s")==0){ // smooth shade. Always smooth shade } else if (token[0] == '#' || line.length() == 0){ // comment - ignore line } else { cout << "ObjLoader::Unsupported line:" << endl; cout <<"'"<< line.c_str() << "'"<<token.compare("#")<<int(token[0])<<endl; } } } if (outMaterials->size() == 0){ // ensure a single material object exist outMaterials->push_back(Material()); } map<TriangleIndex,int> cache; for (unsigned int i=0;i<triangles.size();i++){ TriangleString triangleString = triangles[i]; for (int j=0;j<3;j++){ TriangleIndex index = triangleString.get(j); map<TriangleIndex,int>::iterator cachedIndex = cache.find(index); if (cachedIndex != cache.end()) { (*outIndices)[triangleString.materialIndex].push_back(cachedIndex->second); } else { int vertexIndex = static_cast<int>(outPositions->size()); (*outPositions).push_back(positions[index.position-1] * scale); if (index.normal != -1 && outNormal != NULL){ (*outNormal).push_back(normals[index.normal-1]); } if (index.uv != -1 && outUv != NULL) { (*outUv).push_back(uvs[index.uv-1]); } while (triangleString.materialIndex >= (*outIndices).size()){ (*outIndices).push_back(vector<GLuint>()); } (*outIndices)[triangleString.materialIndex].push_back(vertexIndex); cache[index] = vertexIndex; } } } return true; } }
#include <string> #include <cmath> using namespace std; /** * Just find the regular pattern, - * and solve this problem by math equation; */ class Solution { public: #define INSPECT(s, pos) \ if (pos < s.length()) { \ result.append(1, s.at(pos)); \ } string convert(string s, int numRows) { if (numRows == 1) { return s; } else { string result; const int blockNum = floor(s.length() / 1.0 * (2 * (numRows - 1))); for (auto i = 1; i <= numRows; i++) { for (auto j = 1; j <= blockNum; j++) { const int offset = (2 * (numRows - 1)) * (j - 1); if (i == 1) { INSPECT(s, offset) } else if (i != numRows) { INSPECT(s, offset + (i - 1)) INSPECT(s, offset + (i - 1) + (2 + (numRows - i - 1) * 2)) } else { INSPECT(s, offset + (numRows - 1)) } } } return result; } } };
#include "marcadores.h" marcadores::marcadores(QWidget* parent) : QDialog(parent) { this->setWindowTitle("Marcadores"); } marcadores::~marcadores() { }
/* RABIN KARP ALGORITHM -> Rabin Karp Algorithm matches the hash value of pattern to hash value of substring of text sliding by one. -> here, we find the hash value of each substring by sliding by one in O(1) time. -> When the hash value Matches we compare the each character of pattern to text. -> In Average Case it runs in O(n+m) time and O(n*m) in worst case. -> here, we take prime numbers which treats given numbers in its base. */ #include <bits/stdc++.h> using namespace std; #define d 256 // no. of different characters #define q 101 // Prime number string text,pat; void rabinkarp() { int m,n,p,t,h,i,j; m=pat.size(); n=text.size(); p=0; // hash value for pattern t=0; // hash value for text h=1; // h contains pow(d,m-1)%q for(i=0;i<m-1;i++) { h=(h*d)%q; } // compute hash value for pattern and text for(i=0;i<m;i++) { p=(d*p+pat[i])%q; // current hash value= ((no. of diff. chars)*(previous hash value)+current pattern)%mod t=(d*t+text[i])%q; } for(i=0;i<=(n-m);i++) { if(t==p) { for(j=0;j<m;j++) { if(pat[j]!=text[i+j]) break; } if(j==m) { cout<<"Pattern found at index: "<<i<<endl; } } if(i<n-m) { t=(d*(t-text[i]*h)+text[i+m])%q; // current hash value= ((no. of diff. chars)*(previous hash value)+current pattern)%mod if(t<0) t+=q; } } } int main() { cin>>text>>pat; rabinkarp(); return 0; }
#include <Poco/Event.h> #include <Poco/Exception.h> #include <Poco/Thread.h> #include <exception> #include <cppunit/extensions/HelperMacros.h> #include "util/SequentialAsyncExecutor.h" #define MAX_WAIT_TIME 10000 // 10 seconds in ms using namespace std; using namespace Poco; namespace BeeeOn { class SequentialAsyncExecutorTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SequentialAsyncExecutorTest); CPPUNIT_TEST(testRunEmpty); CPPUNIT_TEST(testRunTwice); CPPUNIT_TEST(testOneTask); CPPUNIT_TEST(testOneThenRun); CPPUNIT_TEST(testThousandTasks); CPPUNIT_TEST(testThousandTasksThenRun); CPPUNIT_TEST_SUITE_END(); public: void testRunEmpty(); void testRunTwice(); void testOneTask(); void testOneThenRun(); void testThousandTasks(); void testThousandTasksThenRun(); }; CPPUNIT_TEST_SUITE_REGISTRATION(SequentialAsyncExecutorTest); /** * testRunEmpty - create, start and stop executor instance without * inserting any tasks to find any potential memory leaks using valgrind tool. */ void SequentialAsyncExecutorTest::testRunEmpty() { Thread t; SequentialAsyncExecutor executor; t.start(executor); executor.stop(); t.join(); } /** * testRunTwice - create then start and stop executor twice without * inserting any tasks to find any potential memory leaks using valgrind tool. */ void SequentialAsyncExecutorTest::testRunTwice() { Thread t; SequentialAsyncExecutor executor; t.start(executor); executor.stop(); t.join(); t.start(executor); executor.stop(); t.join(); } /** * testOneTask - create and start executor instance. Invoke it with one task and * wait for it to finish. * If task takes more then MAX_WAIT_TIME to finish its considered as failure. */ void SequentialAsyncExecutorTest::testOneTask() { Thread t; SequentialAsyncExecutor executor; Event finishEvent; t.start(executor); executor.invoke([&finishEvent]() {finishEvent.set();}); CPPUNIT_ASSERT(finishEvent.tryWait(MAX_WAIT_TIME)); executor.stop(); t.join(); } /** * testOneThenRun - create executor instance, invoke it with one task then start its thread. * Task should be able to finish within given time. * If task takes more then MAX_WAIT_TIME to finish its considered as failure. */ void SequentialAsyncExecutorTest::testOneThenRun() { Thread t; SequentialAsyncExecutor executor; Event finishEvent; executor.invoke([&finishEvent]() {finishEvent.set();}); t.start(executor); CPPUNIT_ASSERT(finishEvent.tryWait(MAX_WAIT_TIME)); executor.stop(); t.join(); } /** * testThousandTasks - create executor instance and start it. * Then invoke it thousand times and wait for tasks to finish. * If task takes more then MAX_WAIT_TIME to finish its considered as failure. */ void SequentialAsyncExecutorTest::testThousandTasks() { Thread t; SequentialAsyncExecutor executor; Event finishEvent; int results[1000]; t.start(executor); for(int i=0; i<1000; i++){ executor.invoke([&results, i]() {results[i] = i;}); } executor.invoke([&finishEvent]() {finishEvent.set();}); CPPUNIT_ASSERT(finishEvent.tryWait(MAX_WAIT_TIME)); for(int i=0; i<1000; i++) CPPUNIT_ASSERT(results[i] == i); executor.stop(); t.join(); } /** * testThousandTasks - create executor instance then invoke it thousand times. * After invoke-ing start its thread and wait for tasks to finish. * If task takes more then MAX_WAIT_TIME to finish its considered as failure. */ void SequentialAsyncExecutorTest::testThousandTasksThenRun() { Thread t; SequentialAsyncExecutor executor; Event finishEvent; int results[1000]; for (int i=0; i<1000; i++){ results[i] = 0; executor.invoke([&results, i]() {results[i] = i;}); } for (int i=0; i<1000; i++) { CPPUNIT_ASSERT(results[i] == 0); } executor.invoke([&finishEvent]() {finishEvent.set();}); t.start(executor); CPPUNIT_ASSERT(finishEvent.tryWait(MAX_WAIT_TIME)); for(int i=0; i<1000; i++) CPPUNIT_ASSERT(results[i] == i); executor.stop(); t.join(); } } // namespace BeeeOn
#include "pch.h" #include "DBUser.h" DBUser::DBUser() { } DBUser::~DBUser() { } BOOL DBUser::Begin(VOID) { CThreadSync Sync; mIsConnected = FALSE; ZeroMemory(ID, sizeof(WCHAR) * 32); return CPacketSession::Begin(); } BOOL DBUser::End(VOID) { CThreadSync Sync; mIsConnected = FALSE; ZeroMemory(ID, sizeof(CHAR) * 32); return CPacketSession::End(); } BOOL DBUser::Reload(SOCKET listenSocket) { CThreadSync Sync; End(); if (!Begin()) return FALSE; if (!CNetworkSession::Accept(listenSocket)) return FALSE; return TRUE; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef ACCESSIBLEDOCUMENT_H #define ACCESSIBLEDOCUMENT_H #ifdef ACCESSIBILITY_EXTENSION_SUPPORT #include "modules/accessibility/opaccessibleitem.h" #include "modules/hardcore/timer/optimer.h" class DocumentManager; class FramesDocument; class VisualDevice; class AccessibleElementManager; class OpWidget; /* The AccessibleDocument represents the accessibility node of the concept of a web page. Since the page itself never goes away, the accessibility node shouldn't either. To make this concept work, the AccessibleDocument essentially wraps the DocumentManager. By retaining the same node for the document when the DocumentManager changes the page, screen readers that had focus on the old page will automatically get moved to the new page. It really doesn't make sense from an acceesibility PoV to distinguish between an all-new document, or one that has merely fundamentally changed itself. */ class AccessibleDocument : public OpAccessibleItem, OpTimerListener { public: AccessibleDocument(OpAccessibleItem* parent, DocumentManager* doc_man); ~AccessibleDocument(); void DocumentUndisplayed(const FramesDocument* doc); void DocumentReflowed(const FramesDocument* doc); void DocumentLoaded(const FramesDocument* doc); void ElementRemoved(const FramesDocument* doc, const HTML_Element* element); void WidgetRemoved(const OpWidget* widget); void HighlightElement(HTML_Element* element); DocumentManager* GetDocumentManager(); FramesDocument* GetActiveDocument() const; VisualDevice* GetVisualDevice() const; HTML_Element* GetFocusElement(); void CreateAccessibleChildrenIfNeeded(); // OpAccessibilityExtensionListener virtual BOOL AccessibilityIsReady() const {return m_is_ready;} virtual BOOL AccessibilitySetFocus(); virtual OP_STATUS AccessibilityGetText(OpString& str); virtual OP_STATUS AccessibilityGetAbsolutePosition(OpRect &rect); virtual Accessibility::ElementKind AccessibilityGetRole() const; virtual Accessibility::State AccessibilityGetState(); virtual int GetAccessibleChildrenCount(); virtual OpAccessibleItem* GetAccessibleParent() {return m_parent;} virtual OpAccessibleItem* GetAccessibleChild(int); virtual int GetAccessibleChildIndex(OpAccessibleItem* child); virtual OpAccessibleItem* GetAccessibleChildOrSelfAt(int x, int y); virtual OpAccessibleItem* GetNextAccessibleSibling(); virtual OpAccessibleItem* GetPreviousAccessibleSibling(); virtual OpAccessibleItem* GetAccessibleFocusedChildOrSelf(); virtual OpAccessibleItem* GetLeftAccessibleObject(); virtual OpAccessibleItem* GetRightAccessibleObject(); virtual OpAccessibleItem* GetDownAccessibleObject(); virtual OpAccessibleItem* GetUpAccessibleObject(); virtual OP_STATUS GetAccessibleHeaders(int level, OpVector<OpAccessibleItem> &headers); virtual OP_STATUS GetAccessibleLinks(OpVector<OpAccessibleItem> &links); // OpTimerListener virtual void OnTimeOut(OpTimer* timer); private: OpAccessibleItem* m_parent; DocumentManager* m_doc_man; AccessibleElementManager* m_accessible_children; OpTimer m_reflow_timer; HTML_Element* m_highlight_element; mutable BOOL m_was_loading; BOOL m_fake_loading; BOOL m_is_ready; }; #endif // ACCESSIBILITY_EXTENSION_SUPPORT #endif // ACCESSIBLEDOCUMENT_H
#ifndef __GAME_SCENE_H__ #define __GAME_SCENE_H__ #include <cocos2d.h> #include "BackgroundLayer.h" #include "GameLayer.h" #include "OptionLayer.h" #include "StatusLayer.h" using namespace cocos2d; class GameScene : public Scene { public: GameScene(){} ~GameScene(){} virtual bool init(); CREATE_FUNC(GameScene); void restart(); }; #endif
/* * z_example.cpp * * Created on: 11 Feb 2013 * Author: lukasz.forynski * * This file contains eample uses of jsmnrpc_tiny and is a mix of C and C++ * (mostly for convenience). */ #include "jsmnrpc.h" #include <string.h> #include <iostream> #include <sstream> #include <ctime> #include <vector> #include <stdio.h> void rpc_handling_examples(char** argv); void extracting_json_examples(); void print_all_members_of_object(const std::string& input, int curr_pos, size_t object_len); int run_tests(); // ======== example JSON RPC handlers ========== // does not use any params void getTimeDate(jsmnrpc_request_info_t* info) { // (no need to parse arguments here) std::stringstream res; time_t curr_time; time(&curr_time); struct tm * now = localtime(&curr_time); if (jsmnrpc_create_result_prefix(info)) { char buffer[20]; jsmnrpc_string_t *response = &info->data->response; append_str_with_len(response, "\"", SIZE_MAX); append_str_with_len(response, i_to_str(now->tm_year + 1900, buffer), SIZE_MAX); append_str_with_len(response, i_to_str(now->tm_mon + 1, buffer), SIZE_MAX); append_str_with_len(response, i_to_str(now->tm_mday + 1, buffer), SIZE_MAX); append_str_with_len(response, "\"", SIZE_MAX); } } // uses named params void search(jsmnrpc_request_info_t* info) { jsmnrpc_token_list_t *tokens = &info->data->tokens; // could do it in 'C' (a.k.a.: hacking) // for named params- there are 'helper' functions to find and extract parameters by their name // (can be useful as this allows finding them regardless of their order in the original request. int param_0_token = jsmnrpc_get_value(tokens, info->params_value_token, 0, NULL); int last_name_value_token = jsmnrpc_get_value(tokens, param_0_token, 0, "last_name"); int age_value_token = jsmnrpc_get_value(tokens, param_0_token, 0, "age"); jsmnrpc_string_t last_name = jsmnrpc_get_string(tokens, last_name_value_token); jsmnrpc_string_t age = jsmnrpc_get_string(tokens, age_value_token); if (last_name.data && age.data && jsmnrpc_get_token_type(tokens, age_value_token) == JSMN_PRIMITIVE) { if (strncmp(last_name.data, "Python", last_name.length) == 0 && strncmp(age.data, "26", age.length) == 0) { jsmnrpc_create_result("\"Monty\"", info); } else { jsmnrpc_create_result("none", info); } } else { // return jsmnrpc_error (using error value) on failure jsmnrpc_create_error(jsmnrpc_err_invalid_params, NULL, info); } } void non_20_error_example(jsmnrpc_request_info_t* info) { std::string s; int error_occured = 1; std::stringstream msg; if (error_occured) { // manually construct the error code.. jsmnrpc_create_error(-32000, "SOmething went wrong..", info); // and past it as a string } else { jsmnrpc_create_result("\"OK\"", info); } } // uses the argument set in the jsmnrpc_instance::data::arg void use_argument(jsmnrpc_request_info_t* info) { std::stringstream msg; const char* param = (const char*)info->data->arg; char* res = 0; if (param) { msg << "\"" << param << "\""; jsmnrpc_create_result(msg.str().c_str(), info); } else { jsmnrpc_create_error(jsmnrpc_err_internal_error, NULL, info); } } // uses named parameters: 'first', 'second' and 'operation', // calculates result and forms the response. void calculate(jsmnrpc_request_info_t* info) { int first; int second; #if 0 int op_len = 0; const char* operation = rpc_extract_param_str("op", &op_len, info); if (operation && rpc_extract_param_int("first", &first, info) && rpc_extract_param_int("second", &second, info)) { std::stringstream result; result << "{" << "\"operation\": \"" << std::string(operation, op_len); result << "\", \"res\": "; switch (operation[0]) { case '*': result << first * second; break; case '+': result << first + second; break; case '-': result << first - second; break; case '/': result << first / second; break; } result << "}"; jsmnrpc_create_result(result.str().c_str(), info); } else { // return jsmnrpc_error (using error value) on failure jsmnrpc_create_error(jsmnrpc_err_invalid_params, NULL, info); } #endif } // uses position based params (i.e. extracts params based on their order) // and just replies their values as "first": <val0>, "second": <val1> ..etc.. void ordered_params(jsmnrpc_request_info_t* info) { #if 0 char* res = 0; // can use similar functions to extract parameters by their position // (i.e. if they are comma-separated, not-named parameters) int first; int third; int second_len = 0; const char* second = rpc_extract_param_str(1, &second_len, info); // zero-based second parameter if (second && rpc_extract_param_int(0, &first, info) && rpc_extract_param_int(2, &third, info)) { std::stringstream s; s << "{\"first\": " << first << ", "; s << "\"second\": \"" << std::string(second, second_len) << "\", "; s << "\"third\": " << third << "}"; res = jsmnrpc_create_result(s.str().c_str(), info); } else { // return jsmnrpc_error (using error value) on failure res = jsmnrpc_create_error(jsmnrpc_err_invalid_params, info); } return res; #endif } // demonstrates manual access to params within the request string void handleMessage(jsmnrpc_request_info_t* info) { #if 0 // of course info contains all information about the request. // input (request) string is in {info->data->request, info->data->request_len} // information about that data is already parsed, and params_start is offset // within the request to the beginning of string containing parameters. // info->params_len contains length of this string. // This can, if really needed, be used directly if extraction-aiding methods are not // applicable or one whishes to do it all manually. char params[64]; strncpy(params, info->data->request + info->params_start, info->params_len); params[info->params_len] = 0; printf(" ===> called handleMessage(%s, notif: %d)\n\n", params, info->info_flags); #endif // note : don't change response directly: using jsmnrpc_result() or jsmnrpc_error() // you can update response data with required data (and JSON tags will be appended // automatically return jsmnrpc_create_result("OK", info); } void send_back(jsmnrpc_request_info_t* info) { #if 0 int len = 0; const char* msg = rpc_extract_param_str("what", &len, info); if (msg) { std::string message(msg, len); message = "{\"res\": \"" + message + "\"}"; res = jsmnrpc_create_result(message.c_str(), info); } else { res = jsmnrpc_create_error(jsmnrpc_err_invalid_params, info); } #endif } // ==== example JSON RPC requests == const char* example_requests[] = { "{\"jsonrpc\": \"2.0\", \"method\": \"getTimeDate\", \"params\": none, \"id\": 10}", "{\"jsonrpc\": \"2.0\", \"method\": \"helloWorld\", \"params\": [\"Hello World\"], \"id\": 11}", "{\"method\": \"search\", \"params\": [{\"last_name\": \"Python\", \"age\": 26}], \"id\": 22}", "{\"jsonrpc\": \"2.0\", \"method\": \"search\", \"params\": [{\"last_n\": \"Python\"}], \"id\": 43}", "{\"jsonrpc\": \"2.0\", \"method\": \"search\", \"params\": [{\"last_name\": \"Doe\"}], \"id\": 54}", "{\"jsonrpc\": \"2.0\", \"thod\": \"search\", ", // not valid, but not whole object, will not be parsed.. "{\"method\": \"err_example\", \"params\": [], \"id\": 36}", // not valid "{\"jsonrpc\": \"2.0\", \"method\": \"use_param\", \"params\": [], \"id\": 37s}", "{\"jsonrpc\": \"2.0\", \"method\": \"calculate\", \"params\": [{\"first\": 128, \"second\": 32, \"op\": \"+\"}], \"id\": 38}", "{\"jsonrpc\": \"2.0\", \"method\": \"calculate\", \"params\": [{\"second\": 0x10, \"first\": 0x2, \"op\": \"*\"}], \"id\": 39}", "{\"jsonrpc\": \"2.0\", \"method\": \"calculate\", \"params\": [{\"first\": 128, \"second\": 32, \"op\": \"+\"}], \"id\": 40}", "{\"jsonrpc\": \"2.0\", \"method\": \"ordered_params\", \"params\": [128, \"the string\", 0x100], \"id\": 41}", "{\"method\": \"handleMessage\", \"params\": [\"user3\", \"sorry, gotta go now, ttyl\"], \"id\": null}", "{\"jsonrpc\": \"2.0\", \"method\": \"calculate\", \"params\": [{\"first\": -0x17, \"second\": -17, \"op\": \"+\"}], \"id\": 43}", "{\"jsonrpc\": \"2.0\", \"method\": \"calculate\", \"params\": [{\"first\": -0x32, \"second\": -055, \"op\": \"-\"}], \"id\": 44}", "{\"jsonrpc\": \"2.0\", \"method\": \"send_back\", \"params\": [{\"what\": \"{[{abcde}]}\"}], \"id\": 45}", "{\"jsonrpc\": \"2.0\", \"thod\": \"search\".. }", // not valid, but a whole object, jsonrpc will be parsed.. }; const int num_of_examples = sizeof(example_requests) / sizeof(char*); int main(int argc, char** argv) { rpc_handling_examples(argv); // examples on how tho register handlers, parse requests and responses. extracting_json_examples(); // examples on how to traverse (and extract all members of) a JSON object return run_tests(); // sanity tests. Note that they depend on some examples defined above.. } // define our storage (C-style) (*can also be allocated dynamically) #define MAX_NUM_OF_HANDLERS 32 jsmnrpc_handler_t storage_for_handlers[MAX_NUM_OF_HANDLERS]; #define RESPONSE_BUF_MAX_LEN 256 char response_buffer[RESPONSE_BUF_MAX_LEN]; #define REQUEST_TOKEN_MAX_LEN 256 jsmntok_t request_tokens[REQUEST_TOKEN_MAX_LEN]; void rpc_handling_examples(char** argv) { // create and initialise the instance jsmnrpc_instance_t rpc; jsmnrpc_init(&rpc, storage_for_handlers, MAX_NUM_OF_HANDLERS); // register our handlers jsmnrpc_register_handler(&rpc, "handleMessage", handleMessage); jsmnrpc_register_handler(&rpc, "getTimeDate", getTimeDate); jsmnrpc_register_handler(&rpc, "search", search); jsmnrpc_register_handler(&rpc, "err_example", non_20_error_example); jsmnrpc_register_handler(&rpc, "use_argument", use_argument); jsmnrpc_register_handler(&rpc, "calculate", calculate); jsmnrpc_register_handler(&rpc, "ordered_params", ordered_params); jsmnrpc_register_handler(&rpc, "send_back", send_back); // prepare and initialise request data jsmnrpc_data_t req_data; req_data.tokens.data = request_tokens; req_data.tokens.capacity = REQUEST_TOKEN_MAX_LEN; req_data.response.data = response_buffer; req_data.response.capacity = RESPONSE_BUF_MAX_LEN; req_data.arg = argv[0]; // now execute try it out with example requests defined above // printing request and response to std::out for (int i = 0; i < num_of_examples; i++) { // assign buffer from next example req_data.request.data = (char*)example_requests[i]; req_data.request.length = strlen(example_requests[i]); // and handle rpc request jsmnrpc_handle_request(&rpc, &req_data); std::cout << "\n" << i << ": " << "\n--> " << example_requests[i]; std::cout << "\n<-- " << req_data.response.data << "\n"; // try to extract response and print it (see extracting_json_examples() for more on extracting) { #if 0 int result_len = 0; const char* result_str = json_extract_member_str("result", &result_len, res_str, strlen(res_str)); if (result_str) { std::cout << "result was: " << std::string(result_str, result_len) << "\n"; for (int i = 0; ; i++) { int member_val_len = 0; const char* member_start = json_extract_member_str(i, &member_val_len, result_str, result_len); if (!member_val_len) { break; } std::cout << " result [" << i << "]: " << std::string(member_start, member_val_len) << "\n"; } } #endif } std::cout << "\n"; } } void extracting_json_examples() { std::cout << "\n\n ==== extracting_json_examples ====\n\n"; std::string input = "{\"jsonrpc\": \"2.0\", \"method\": \"getTimeDate\", \"params\": none, \"id\": 123}"; std::cout << "printing all members of: \n " << input << "\n\n"; print_all_members_of_object(input, 0, input.size()); input = "{[{\"first\": 128, \"second\": 32, \"op\": \"+\"}, {\"jsonrpc\": \"2.0\", \"method\": \"getTimeDate\"}]}"; std::cout << "printing all members of: \n " << input << "\n\n"; print_all_members_of_object(input, 0, input.size()); input = "{\"jsonrpc\": \"2.0\", \"method\": \"ordered_params\", \"params\": [128, \"the string\", 0x100], \"id\": 40}"; std::cout << "\n---\nprinting all members of: \n " << input << "\n\n"; print_all_members_of_object(input, 0, input.size()); std::cout << "\n\n ==== finding members by name ====\n"; std::string member_name = "jsonrpc"; int member_val_len = 0; #if 0 const char* member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; member_name = "params"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; member_name = "method"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; member_name = "id"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; input = "{\"result\": {\"operation\": \"*\", \"res\": 32}, \"error\": none, \"id\": 38}"; member_name = "result"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; member_name = "operation"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; member_name = "res"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; member_name = "operation"; member_start = json_extract_member_str(member_name.c_str(), &member_val_len, input.c_str(), input.size()); std::cout << member_name << " (found by name): " << std::string(member_start, member_val_len) << "\n"; std::cout << "\n\n ==== finding members by number (order) ==== \n"; input = "{{\"first\": 128, \"second\": 32, \"op\": \"+\"}, {\"jsonrpc\": \"2.0\", \"method\": \"getTimeDate\"}}"; std::cout << "JSON object: \n" << input << "\n\n"; for (int i = 0; ; i++) { member_start = json_extract_member_str(i, &member_val_len, input.c_str(), input.size()); if (!member_val_len) { break; } std::cout << " member #" << i << ": " << std::string(member_start, member_val_len) << "\n"; } input = example_requests[3]; std::cout << "\n\nJSON object: \n" << input << "\n\n"; for (int i = 0; ; i++) { member_start = json_extract_member_str(i, &member_val_len, input.c_str(), input.size()); if (!member_val_len) { break; } std::cout << " member #" << i << ": " << std::string(member_start, member_val_len) << "\n"; } #endif std::cout << "\n\n ==== extracting_json_examples (end) ====\n\n"; } // example function to show how to print recursively all sub-objects / lists within a JSON object void print_all_members_of_object(const std::string& input, int curr_pos, size_t object_len) { #if 0 json_token_info info; std::cout << "=> inside next sub-obj\n"; int object_pos_max_within_input = curr_pos + object_len; while (true) { curr_pos = json_find_next_member(curr_pos, input.c_str(), object_pos_max_within_input, &info); if (info.values_len == 0) { break; } std::cout << "next member is: ->"; std::cout << input.substr(info.name_start, info.name_len); std::cout << "<- value (at: " << info.values_start << ", len: " << info.values_len << "): "; std::cout << ">" << input.substr(info.values_start, info.values_len) << "<\n"; if (json_next_member_is_object_or_list(input.c_str(), &info)) { print_all_members_of_object(input, info.values_start + 1, info.values_len); } } std::cout << "<= end of next sub-obj\n"; #endif } // --------------- TEST CODE ----------------------------------- #include <stdexcept> #define TEST_COND_(_cond_, ...) \ { \ if(!(_cond_)) { \ std::stringstream s; \ s << "test error: assertion at line: " << __LINE__ << "\n"; \ s << " " << #_cond_ << "\n"; \ throw std::runtime_error(s.str()); \ } \ } // helper method: executes JSON rpc given example number and returns the response void handle_request_for_example(int example_number, jsmnrpc_data_t& req_data, jsmnrpc_instance& rpc) { req_data.request.data = (char*)example_requests[example_number]; req_data.request.length = strlen(example_requests[example_number]); req_data.request.capacity = 0; return jsmnrpc_handle_request(&rpc, &req_data); } int extract_token_offset(jsmnrpc_token_list_t *tokens, int root_token, const char* name) { return jsmnrpc_get_value(tokens, 0, -1, name); } int extract_token_offset(jsmnrpc_token_list_t *tokens, int root_token, int index) { return jsmnrpc_get_value(tokens, 0, index, NULL); } template <typename ParamType> std::string extract_str_param(ParamType param_name_or_pos, const std::string& res_str) { int str_size = 0; std::vector<jsmntok_t> token_vector; jsmnrpc_string_t str; jsmnrpc_token_list_t tokens; token_vector.resize(10000); str.length = (int)res_str.size(); str.capacity = 0; str.data = (char*)res_str.data(); tokens.data = token_vector.data(); tokens.capacity = (int)token_vector.size(); jsmnrpc_parse(&tokens, &str); int result_offset = -1; result_offset = extract_token_offset(&tokens, 0, param_name_or_pos); if (result_offset < 0) { return "undefined"; } jsmnrpc_string_t return_str = jsmnrpc_get_string(&tokens, result_offset); return std::string(return_str.data, return_str.length); } template <typename ParamType> int extract_int_param(ParamType param_name_or_pos, const std::string& res_str) { std::string result = extract_str_param(param_name_or_pos, res_str); return atoi(result.c_str()); } int run_tests() { jsmnrpc_instance_t rpc; jsmnrpc_init(&rpc, storage_for_handlers, MAX_NUM_OF_HANDLERS); // register our handlers jsmnrpc_register_handler(&rpc, "handleMessage", handleMessage); jsmnrpc_register_handler(&rpc, "getTimeDate", getTimeDate); jsmnrpc_register_handler(&rpc, "search", search); jsmnrpc_register_handler(&rpc, "err_example", non_20_error_example); jsmnrpc_register_handler(&rpc, "use_argument", use_argument); jsmnrpc_register_handler(&rpc, "calculate", calculate); jsmnrpc_register_handler(&rpc, "ordered_params", ordered_params); jsmnrpc_register_handler(&rpc, "send_back", send_back); try { jsmnrpc_data_t req_data; char* res_str = response_buffer; req_data.response.data = response_buffer; req_data.response.capacity = RESPONSE_BUF_MAX_LEN; req_data.tokens.data = request_tokens; req_data.tokens.capacity = REQUEST_TOKEN_MAX_LEN; handle_request_for_example(2, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_str_param("result", res_str) == "Monty"); // "result": "Monty" TEST_COND_(extract_str_param("error", res_str) == "null"); // "error": null TEST_COND_(extract_str_param("id", res_str) == "22"); // "id": 22 TEST_COND_(extract_int_param("id", res_str) == 22); // "id": 22 TEST_COND_(extract_str_param(3, res_str) == "undefined"); // not existing. handle_request_for_example(5, req_data, rpc); TEST_COND_(req_data.response.length > 2); std::cout << "=====> " << extract_str_param("id", res_str); TEST_COND_(extract_str_param("id", res_str) == "undefined"); // "id": undefined std::string error = extract_str_param("error", res_str); TEST_COND_(extract_int_param("code", error) == -32700); TEST_COND_(extract_str_param("message", error) == "Parse error"); handle_request_for_example(16, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_str_param("jsonrpc", res_str) == "2.0"); // "jsonrpc": "2.0" error = extract_str_param("error", res_str); TEST_COND_(extract_int_param("code", error) == -32700); handle_request_for_example(9, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_int_param("res", res_str) == 32); TEST_COND_(extract_str_param("operation", res_str) == "*"); handle_request_for_example(10, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_str_param("operation", res_str) == "+"); TEST_COND_(extract_int_param("res", res_str) == 160); handle_request_for_example(11, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_str_param("jsonrpc", res_str) == "2.0"); TEST_COND_(extract_int_param("first", res_str) == 128); TEST_COND_(extract_str_param("second", res_str) == "the string"); TEST_COND_(extract_int_param("third", res_str) == 256); std::string expected = "{\"first\": 128, \"second\": \"the string\", \"third\": 256}"; TEST_COND_(extract_str_param(0, res_str) == "2.0"); // the whole '0-param' part TEST_COND_(extract_str_param(1, res_str) == expected); // the whole '0-param' part TEST_COND_(extract_int_param(2, res_str) == 41); // "id": 41 // and result.. TEST_COND_(extract_int_param(0, expected) == 128); TEST_COND_(extract_str_param(1, expected) == "the string"); TEST_COND_(extract_int_param(2, expected) == 256); // tests negative value extraction (hex/dec/oct) etc. handle_request_for_example(13, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_int_param("res", res_str) == -40); handle_request_for_example(14, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_int_param("res", res_str) == -5); handle_request_for_example(15, req_data, rpc); TEST_COND_(req_data.response.length > 2); TEST_COND_(extract_str_param("res", res_str) == "{[{abcde}]}"); // if value in quotes, do not treat it as JSON // test batch requests.. std::string batch_request("["); batch_request += example_requests[8]; batch_request += ","; batch_request += example_requests[9]; batch_request += "]"; // prepare request buffer req_data.request.data = (char*)batch_request.c_str(); req_data.request.length = batch_request.size(); // and handle rpc request jsmnrpc_handle_request(&rpc, &req_data); std::cout << "\nbatch request:\n--> " << batch_request << "\n"; std::cout << "\n<-- " << res_str << "\n"; TEST_COND_(res_str); std::string batch_res = extract_str_param(0, res_str); // first batch item TEST_COND_(extract_int_param("res", batch_res) == 160); TEST_COND_(extract_str_param("operation", batch_res) == "+"); TEST_COND_(extract_int_param("id", batch_res) == 38); batch_res = extract_str_param(1, res_str); // second batch item TEST_COND_(extract_int_param("res", batch_res) == 32); TEST_COND_(extract_str_param("operation", batch_res) == "*"); TEST_COND_(extract_int_param("id", batch_res) == 39); batch_request = "[,233]"; // invalid requests in the batch.. // prepare request buffer req_data.request.data = (char*)batch_request.c_str(); req_data.request.length = batch_request.size(); // and handle rpc request jsmnrpc_handle_request(&rpc, &req_data); std::cout << "\nbatch request:\n--> " << batch_request << "\n"; std::cout << "\n<-- " << res_str << "\n"; TEST_COND_(req_data.response.length > 2); batch_res = extract_str_param(0, res_str); // first batch item TEST_COND_(extract_str_param("error", batch_res) == "{\"code\": -32600, \"message\": \"Invalid Request\"}"); TEST_COND_(extract_str_param("id", batch_res) == "none"); batch_res = extract_str_param(1, res_str); // second batch item TEST_COND_(extract_str_param("error", batch_res) == "{\"code\": -32600, \"message\": \"Invalid Request\"}"); TEST_COND_(extract_str_param("id", batch_res) == "none"); std::cout << "\n===== ALL TESTS PASSED =====\n\n"; } catch (const std::exception& e) { std::cout << "\n\n===== TESTING ERROR =====\n\n"; std::cerr << e.what() << "\n"; return 1; } return 0; }
#include <deque> #include <fstream> #include <iostream> #include <string> #include <dirent.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <tbb/parallel_for.h> using namespace std; int main() { ifstream fin; string dir, filepath; DIR *current_dir; struct dirent *dir_entry; struct stat filestat; // files and dirs deque<string> dirs; deque<string> files; // seed root dir dirs.push_back("/"); int iters = 0; while (dirs.size() > 0) { string current_dir_str = dirs.front(); dirs.pop_front(); current_dir = opendir(current_dir_str.c_str()); if (current_dir == NULL) { cout << "Error(" << errno << ") opening " << current_dir_str << endl; continue; } // Skip '.' and '..' entries else if ((current_dir_str == "..") or (current_dir_str == ".")) { continue; } while ((dir_entry = readdir(current_dir))) { iters++; if (iters > 1000){ return 0;} // Skip '.' and '..' entries string dirname = dir_entry->d_name; if ((dirname == ".") or (dirname == "..")) { continue; } string inode_path = current_dir_str + "/" + dir_entry->d_name; // If the file is a directory (or is in some way invalid) we'll skip it if (stat(inode_path.c_str(), &filestat) == -1) { perror("stat"); continue; } else if (S_ISDIR(filestat.st_mode)) { dirs.push_back(inode_path); cout << "Found a dir: " << inode_path << endl; } else { files.push_back(inode_path); cout << "Found a file: " << inode_path << endl; } } closedir(current_dir); } return 0; }
//======include header====== #include "Board.h" //======const section======= const char enemy = '%'; const char coin = '*'; const char player = '@'; //===============C-TORS=============== Board::Board() { curr_level = 0; std::string str; // temporary string which we push into the vector; std::ifstream file; std::string size; file.open("Board.txt"); // Board.txt has the all levels if (!file) { std::cout << "File didn't open\n"; exit(EXIT_FAILURE); } char N; int idex_of_levle = 0; while (file.peek() != EOF) { std::vector<std::string> m_vector_of_strings; // will hold 2D array of the map and its content std::vector<std::string> m_clean_vector_of_strings; getline(file,size); int index = 0; do { //reads each line from the Board.txt getline(file, str); // Line contains string of length > 0 then save it in vector if (str.size() > 0) { m_vector_of_strings.push_back(str); m_clean_vector_of_strings.push_back(str); } index++; } // Read the next line from File untill it reaches empty row. while (index <= stoi(size)); levels.push_back(m_vector_of_strings); levels_backup.push_back(m_vector_of_strings); for (int i = 0; i < m_vector_of_strings.size(); i++) { for (int j = 0; j < m_vector_of_strings[i].size(); j++) { if (m_vector_of_strings[i][j] == '@' || m_vector_of_strings[i][j] == '%' || m_vector_of_strings[i][j] == '*') m_clean_vector_of_strings[i][j] = ' '; } } levels_clean.push_back(m_clean_vector_of_strings); m_vector_of_strings.clear(); m_clean_vector_of_strings.clear(); } } //---------------------------------------------------------------------------- // reloads the level again void Board::relload_level() { levels[curr_level] = levels_backup[curr_level]; } //---------------------------------------------------------------------------- //===============Getters=============== // gets the location of the player, all the monster and all the coins void Board::get_locations(std::vector<Monster> & monsters, std::vector<Coins> & coins, Location & playerLocation ) { Location location(-1, -1); //default size in order to use it Coins new_coin(location); Monster new_monster(location); for (int i = 0; i < levels[curr_level].size(); i++) { for (int j = 0; j < levels[curr_level][i].size(); j++) { switch (levels[curr_level][i][j]) { case player: location.row = i; location.col = j; playerLocation = location; break; case coin: location.row = i; location.col = j; new_coin.relocate(location); coins.push_back(new_coin); break; case enemy: location.row = i; location.col = j; new_monster.relocate(location); monsters.push_back(new_monster); break; } } } } //---------------------------------------------------------------------------- char Board::return_char_from_default(Location location) const { return levels_backup[curr_level][location.row][location.col]; } // gets height int Board::get_height() const { return levels[curr_level].size(); } //---------------------------------------------------------------------------- // gets width int Board::get_width() const { return levels[curr_level][0].size(); } //---------------------------------------------------------------------------- //returns which char there is an a specific location char Board::get_char(Location location) const { return levels[curr_level][location.row][location.col]; } //---------------------------------------------------------------------------- // gets a specific char from the main board char Board::get_char(int row, int col) const { return levels[curr_level][row][col]; } //---------------------------------------------------------------------------- // get a specific char from then clean board char Board::get_clean_board_char(int row, int col) { return levels_clean[curr_level][row][col]; } //---------------------------------------------------------------------------- // gets the level int Board::get_level() { return curr_level + 1; } //---------------------------------------------------------------------------- // loads the next level void Board::load_next_level() { increase_level(); } //---------------------------------------------------------------------------- // prints the board void Board::print_board() { for (int i = 0; i < levels[curr_level].size(); i++) std::cout << " " << levels[curr_level][i] << std::endl; } //---------------------------------------------------------------------------- // replaces a char with a clean board void Board::replace_char(Location &location) { levels [curr_level][location.row][location.col] = levels_clean[curr_level][location.row][location.col]; } //---------------------------------------------------------------------------- // deletes a char and fill it with a space void Board::delete_char(Location& location) { levels[curr_level][location.row][location.col] = ' '; } //---------------------------------------------------------------------------- // add a specific char into a specific location void Board::add_char(Location location, char sign) { levels[curr_level][location.row][location.col] = sign; } //---------------------------------------------------------------------------- // clears the vector from holding any data void Board::clear_board() { for (int i = 0; i < levels[curr_level].size(); i++) { levels[curr_level][i].clear(); levels_clean[curr_level][i].clear(); } levels[curr_level].clear(); levels_clean[curr_level].clear(); } //---------------------------------------------------------------------------- // increases the level void Board::increase_level() { curr_level +=1; } //---------------------------------------------------------------------------- // checks if there are more levels bool Board::no_more_levels() { if ((curr_level +1) == levels.size()) return true; return false; } //---------------------------------------------------------------------------- //check if curr locaiton out of board boundries bool Board::out_of_boundrie(const Location& location) const { if (location.row <= 0) return true; else if (location.col > get_width()) return true; else if (location.col < 0) return true; else if (location.row >= get_width()) return true; return false; }
#include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/nonfree/features2d.hpp> #include <opencv2/nonfree/nonfree.hpp> #include <iostream> #include <jni.h> #include <android/log.h> #include <vector> #include <fstream> #include <string.h> using namespace cv; using namespace std; void GeaFeaFile(JNIEnv *env, jobject pObj,jstring file_path) { jclass sift_class=env->FindClass("com/skfeng/ndk/ExtractSiftFea"); jfieldID dirFID=env->GetStaticFieldID(sift_class,"SIFT_FEA_DIR_STRING","Ljava/lang/String;"); jstring fea_dir=(jstring)env->GetStaticObjectField(sift_class,dirFID); const char *c_fea_dir=env->GetStringUTFChars(fea_dir,0);//c_fea_dir中存放生成的fea文件所放的目录 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "c_fea_dir is: %s!",c_fea_dir); const char *rawString=env->GetStringUTFChars(file_path, 0);//rawString存放图片文件所在目录 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "rawString is: %s!",rawString); //路径格式"./image/rs_query.png",注意斜杠方向 // Don't forget to call `ReleaseStringUTFChars` when you're done. Mat img_1=imread(rawString,CV_LOAD_IMAGE_GRAYSCALE); if(!img_1.data)//如果数据为空 { __android_log_print(ANDROID_LOG_INFO, "extract_fea", "Mat img_1 is NULL!!!"); } __android_log_print(ANDROID_LOG_INFO, "extract_fea", "OPEN RIGHT!!!"); //第一步,用SIFT算子检测关键点 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "Before SIFT suanzi"); SiftFeatureDetector detector;//构造函数采用内部默认的 vector<KeyPoint> keypoints_1;//构造1个专门由点组成的点向量用来存储特征点 detector.detect(img_1,keypoints_1);//将img_1图像中检测到的特征点存储起来放在keypoints_1中 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "After SIFT suanzi"); SiftDescriptorExtractor extractor;//定义描述子对象 Mat descriptors_1;//存放特征向量的矩阵 extractor.compute(img_1,keypoints_1,descriptors_1);//计算特征向量 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "After compute the fea vector!"); __android_log_print(ANDROID_LOG_INFO, "extract_fea", "descriptors_1's rows is: %d",descriptors_1.rows); char x='/'; const char* ptr=strrchr(rawString,x);//ptr指向的内容变为/001.jpg char fea_absolute[200];//.fea文件的绝对路径,包含文件名称 sprintf(fea_absolute,"%s",c_fea_dir); char *tail=fea_absolute+strlen(fea_absolute); sprintf(tail,"%s",ptr); tail=fea_absolute+strlen(fea_absolute); sprintf(tail,"%s",".fea.xml");//路径生成完毕,格式为/storage/sdcard1/GraDesign/sift/e.jpg.fea.xml __android_log_print(ANDROID_LOG_INFO, "extract_fea", "fea file dir is:%s",fea_absolute); ptr++;//由/001.jpg变成001.jpg char *dot=strchr(ptr,'.'); *dot='_'; FileStorage fea_out; fea_out.open(fea_absolute,FileStorage::WRITE); fea_out<<ptr<<descriptors_1;//输出特征向量到文件 fea_out.release(); env->ReleaseStringUTFChars(fea_dir,c_fea_dir); env->ReleaseStringUTFChars(file_path,rawString); } void Gather_result(JNIEnv *env, jobject pObj,jobjectArray files_paths,jint len) { __android_log_print(ANDROID_LOG_INFO, "Gather_result", "Gather_result is called!"); jclass sift_class=env->FindClass("com/skfeng/ndk/ExtractSiftFea"); jfieldID dirFID=env->GetStaticFieldID(sift_class,"SIFT_FEA_DIR_STRING","Ljava/lang/String;"); jstring fea_dir=(jstring)env->GetStaticObjectField(sift_class,dirFID); const char *c_fea_dir=env->GetStringUTFChars(fea_dir,0); __android_log_print(ANDROID_LOG_INFO, "extract_fea", "c_fea_dir is: %s!",c_fea_dir); //const char *fea_absolute=new char[200]; FileStorage fout;//输出到Feas.xml Mat temp; for(int i=0;i<len;i++) { jstring string = (jstring)(env->GetObjectArrayElement(files_paths, i)); const char *rawString = env->GetStringUTFChars(string, 0); char x='/'; const char* ptr=strrchr(rawString,x);//ptr指向的内容变为/001.jpg char fea_absolute[200]; sprintf(fea_absolute,"%s",c_fea_dir); char *tail=fea_absolute+strlen(fea_absolute);//目录只是 /storage/sdcard1/GraDesign/sift char *tail_for_Feas=tail;//为生成/storage/sdcard1/GraDesign/sift/Feas.xml备份 sprintf(tail,"%s",ptr);//目录变为 /storage/sdcard1/GraDesign/sift/d.jpg tail=fea_absolute+strlen(fea_absolute); sprintf(tail,"%s",".fea.xml");//路径生成完毕,变为/storage/sdcard1/GraDesign/sift/d.jpg.fea.xml ptr++;//由/001.jpg变成001.jpg char *dot=strchr(ptr,'.'); *dot='_'; FileStorage fea_in; fea_in.open(fea_absolute,FileStorage::READ); fea_in[ptr]>>temp; fea_in.release(); sprintf(tail_for_Feas,"/Feas.xml");//生成/storage/sdcard1/GraDesign/sift/Feas.xml __android_log_print(ANDROID_LOG_INFO, "Gather_result", "Feas.xml's path is: %s!",fea_absolute); if(0==i) fout.open(fea_absolute,FileStorage::WRITE); fout<<ptr<<temp; } fout.release(); } void GeaFeaFiles(JNIEnv *env, jobject pObj,jobjectArray files_paths,jint len) { __android_log_print(ANDROID_LOG_INFO, "extract_fea", "extract_fea is called!"); jclass sift_class=env->FindClass("com/skfeng/ndk/ExtractSiftFea"); jfieldID dirFID=env->GetStaticFieldID(sift_class,"SIFT_FEA_DIR_STRING","Ljava/lang/String;"); jstring fea_dir=(jstring)env->GetStaticObjectField(sift_class,dirFID); const char *c_fea_dir=env->GetStringUTFChars(fea_dir,0); __android_log_print(ANDROID_LOG_INFO, "extract_fea", "c_fea_dir is: %s!",c_fea_dir); //const char *fea_absolute=new char[200]; FileStorage fout;//输出到Feas.xml for (int i=0; i<len; i++) { jstring string = (jstring)(env->GetObjectArrayElement(files_paths, i)); const char *rawString = env->GetStringUTFChars(string, 0); __android_log_print(ANDROID_LOG_INFO, "extract_fea", "rawString is: %s!",rawString); //路径格式"./image/rs_query.png",注意斜杠方向 // Don't forget to call `ReleaseStringUTFChars` when you're done. Mat img_1=imread(rawString,CV_LOAD_IMAGE_GRAYSCALE); if(!img_1.data)//如果数据为空 { __android_log_print(ANDROID_LOG_INFO, "extract_fea", "Mat img_1 is NULL!!!"); } __android_log_print(ANDROID_LOG_INFO, "extract_fea", "OPEN RIGHT!!!"); //第一步,用SIFT算子检测关键点 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "Before SIFT suanzi"); SiftFeatureDetector detector;//构造函数采用内部默认的 vector<KeyPoint> keypoints_1;//构造1个专门由点组成的点向量用来存储特征点 detector.detect(img_1,keypoints_1);//将img_1图像中检测到的特征点存储起来放在keypoints_1中 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "After SIFT suanzi"); SiftDescriptorExtractor extractor;//定义描述子对象 Mat descriptors_1;//存放特征向量的矩阵 extractor.compute(img_1,keypoints_1,descriptors_1);//计算特征向量 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "After compute the fea vector!"); __android_log_print(ANDROID_LOG_INFO, "extract_fea", "descriptors_1's rows is: %d",descriptors_1.rows); char x='/'; const char* ptr=strrchr(rawString,x);//ptr指向的内容变为/001.jpg char fea_absolute[200]; sprintf(fea_absolute,"%s",c_fea_dir); char *tail=fea_absolute+strlen(fea_absolute); sprintf(tail,"%s",ptr); tail=fea_absolute+strlen(fea_absolute); sprintf(tail,"%s",".fea");//路径生成完毕 __android_log_print(ANDROID_LOG_INFO, "extract_fea", "fea file dir is:%s",fea_absolute); ofstream fea_out; fea_out.open(fea_absolute); if(!fea_out.is_open()) { __android_log_print(ANDROID_LOG_INFO, "extract_fea", "Ofstream fails to open the file:%s",fea_absolute); } fea_out<<descriptors_1<<endl;//输出特征向量到文件 fea_out.close(); sprintf(fea_absolute,"%s",c_fea_dir); tail=fea_absolute+strlen(fea_absolute); sprintf(tail,"/Feas.xml"); if(0==i) fout.open(fea_absolute,FileStorage::WRITE); else fout.open(fea_absolute,FileStorage::APPEND); ptr++;//由/001.jpg变成001.jpg char *dot=strchr(ptr,'.'); *dot='_'; fout<<ptr<<descriptors_1; fout.release(); env->ReleaseStringUTFChars(string,rawString); } env->ReleaseStringUTFChars(fea_dir,c_fea_dir); } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* pVm, void* reserved) { JNIEnv* env; if (pVm->GetEnv((void **)&env, JNI_VERSION_1_6)) { return -1; } JNINativeMethod nm[3]; nm[0].name = "GeaFeaFiles"; nm[0].signature = "([Ljava/lang/String;I)V"; nm[0].fnPtr = (void*)GeaFeaFiles; nm[1].name = "Gather_result"; nm[1].signature = "([Ljava/lang/String;I)V"; nm[1].fnPtr = (void*)Gather_result; nm[2].name = "GeaFeaFile"; nm[2].signature = "(Ljava/lang/String;)V"; nm[2].fnPtr = (void*)GeaFeaFile; jclass cls = env->FindClass("com/skfeng/ndk/ExtractSiftFea"); if(cls==NULL) __android_log_print(ANDROID_LOG_INFO, "env->FindClass com/skfeng/ndk/ExtractSiftFea", "Failed!"); // Register methods with env->RegisterNatives. if(env->RegisterNatives(cls, nm, 3)<0) __android_log_print(ANDROID_LOG_INFO, "RegisterNatives", "RegisterNatives is failed!"); return JNI_VERSION_1_6; }
#pragma once #include "SingletonBase.h" // 전방 선언한 이유 // 원래 헤더에 include 하는게 좋은 방법이 아님 // 웬만해서는 헤더에 include 안하는게 좋음 /* GameNode에서 이미지 include 하고 이미지에서 게임노드 include 하면 왓다갓다 하게 되서 터짐 보통은 cpp에 선언 후 헤더에 전방 선언하는 방법을 씀 */ class GameNode; class SceneManager : public SingletonBase<SceneManager> { private: typedef map<string, GameNode*> mSceneList; private: static GameNode* _currentScene; // 현재 플레이 씬 mSceneList _mSceneList; // 씬 목록 public: SceneManager(); ~SceneManager(); void Init(); void Release(); void Update(); void Render(); GameNode* AddScene(string sceneName, GameNode* scene); HRESULT ChangeScene(string sceneName); }; #define SCENE SceneManager::GetSingleton() /* i++ -> i 실행 후 + 1 ++i -> +1 후 실행 */
// MyExtenDllDlg.cpp : 实现文件 // #include "stdafx.h" #include "MyExtenDll.h" #include "MyExtenDllDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMyExtenDllDlg 对话框 CMyExtenDllDlg::CMyExtenDllDlg(CWnd* pParent /*=NULL*/) : CDialogEx(CMyExtenDllDlg::IDD, pParent) , m_strInput(_T("")) , m_strOutput(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CMyExtenDllDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EINPUT, m_strInput); DDX_Text(pDX, IDC_EOUTPUT, m_strOutput); } BEGIN_MESSAGE_MAP(CMyExtenDllDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_CONTROL_RANGE(BN_CLICKED, IDC_BZERO, IDC_BDOT, OnBnClickedNumber) ON_CONTROL_RANGE(BN_CLICKED, IDC_BLOG, IDC_BCLEAR, OnBnClickedOperator) END_MESSAGE_MAP() // CMyExtenDllDlg 消息处理程序 BOOL CMyExtenDllDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMyExtenDllDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMyExtenDllDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CMyExtenDllDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMyExtenDllDlg::OnBnClickedNumber(UINT nID) { UpdateData(TRUE); switch (nID) { case IDC_BZERO:m_strInput += "0"; break; case IDC_BONE:m_strInput += "1"; break; case IDC_BTWO:m_strInput += "2"; break; case IDC_BTHREE:m_strInput += "3"; break; case IDC_BFOUR:m_strInput += "4"; break; case IDC_BFIVE:m_strInput += "5"; break; case IDC_BSIX:m_strInput += "6"; break; case IDC_BSEVEN:m_strInput += "7"; break; case IDC_BEIGHT:m_strInput += "8"; break; case IDC_BNINE:m_strInput += "9"; break; case IDC_BDOT:m_strInput += "."; break; default:break; } UpdateData(FALSE); } void CMyExtenDllDlg::OnBnClickedOperator(UINT nID) { UpdateData(TRUE); m_nData = _wtof(m_strInput);//CString转double CMyCompute* m_pCompute = new CMyCompute(m_nData); switch (nID) { case IDC_BLOG://对数运算 m_nResult = m_pCompute->MyLog(); break; case IDC_BSQUARE://平方运算 m_nResult = m_pCompute->MySquare(); break; case IDC_BCUBE://立方运算 m_nResult = m_pCompute->MyCube(); break; case IDC_BSQRT://开根号运算 m_nResult = m_pCompute->MySqrt(); break; case IDC_BCLEAR://清除输入 m_strInput = m_strOutput=_T(""); UpdateData(FALSE); break; } //设置输出窗口中的文本 CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EOUTPUT); char buffer[200]; sprintf_s(buffer, "%f", m_nResult);//double转char* WCHAR wszClassName1[256]; memset(wszClassName1, 0, sizeof(wszClassName1)); MultiByteToWideChar(CP_ACP, 0, buffer, strlen(buffer) + 1, wszClassName1, sizeof(wszClassName1) / sizeof(wszClassName1[0])); pEdit->SetWindowText(wszClassName1); }
#include "login.h" #include "ui_login.h" login::login(QWidget *parent) : QWidget(parent), ui(new Ui::login) { ui->setupUi(this); } login::~login() { delete ui; } void login::on_showhide_pressed() { ui->password->setEchoMode(QLineEdit::Normal); } void login::on_showhide_released() { ui->password->setEchoMode(QLineEdit::Password); } void login::on_loginbutton_clicked() { if(ui->username->text().isEmpty()){ ui->warning->setText("Username harus diisi !!"); ui->username->setFocus(); }else if(ui->password->text().isEmpty()){ ui->warning->setText("Password harus diisi !!"); ui->password->setFocus(); }else{ string username = ui->username->text().toUtf8().constData(); string password = ui->password->text().toUtf8().constData(); connection conn = connection(); QByteArray pass = QByteArray::fromStdString(password); conn.hash = new QCryptographicHash(QCryptographicHash::Sha1); conn.hash->addData(pass); pass = conn.hash->result().toHex(); delete conn.hash; if(conn.ok){ QSqlQuery query = QSqlQuery(conn.db); query.prepare("SELECT * FROM user WHERE username = :user"); query.bindValue(":user",QString::fromStdString(username)); query.exec(); if(query.next()){ if(query.value(2) == pass){ ui->warning->setText("Login Success"); m.resize(1366,768); this->close(); if(QGuiApplication::primaryScreen()->geometry().height() > 768 || QGuiApplication::primaryScreen()->geometry().width() > 1366) m.show(); else m.showMaximized(); //if login ok }else{ ui->warning->setText("Username atau Password salah !"); ui->username->clear(); ui->password->clear(); ui->username->setFocus(); } }else{ ui->warning->setText("Username atau Password salah !"); ui->username->clear(); ui->password->clear(); ui->username->setFocus(); } }else ui->warning->setText("DB Error"); conn.db.close(); } } void login::on_username_returnPressed() { this->on_loginbutton_clicked(); } void login::on_password_returnPressed() { this->on_loginbutton_clicked(); } void login::on_lupasandi_clicked() { f.setFixedSize(631,363); f.show(); } void login::on_tambahuser_clicked() { a.setFixedSize(631,363); a.show(); } void login::on_hapususer_clicked() { d.setFixedSize(631,363); d.show(); }
#pragma once class DropEgg : public GameObject { public: DropEgg(); ~DropEgg(); bool Start() override; void Update() override; void OnDestroy() override; MonsterID GetMonsterID() { return m_monsterId; } wchar_t* GetMonsterName(){ return m_monsterName; } void SetDropMonster(MonsterID id) { m_monsterId = id; } private: CEffect* ef = nullptr; CQuaternion rot = CQuaternion::Identity(); void NewMonster(); //Monster SkinModelRender* m_monster = nullptr; CVector3 m_monsterPos = { 0.f,-200.f,-200.f }; CVector3 m_modelScale = { 1.5f,1.5f ,1.5f }; CQuaternion m_monsterRot = CQuaternion::Identity(); AnimationClip m_animClip[1]; //Egg SkinModelRender* m_egg = nullptr; CVector3 m_eggPos = { 0.f,-100.f,-200.f }; CVector3 m_eggSca = CVector3::One(); CQuaternion m_eggRot = CQuaternion::Identity(); //efk CEffect* m_efk; //other float m_timer = 0.f; bool mflag_eggbig = true; float mf_eggSca = 1.f; bool mb_efk = false; bool m_isPlayedEffect = false; bool m_isPlayedBackEffect = false; bool m_isDisplayMonster = false; MonsterID m_monsterId; wchar_t m_monsterName[256] = { L"?" }; float m_eggTime = 0.f; };
#include <cmath> #include <vector> #include "lambert.h" std::vector<double> boundingVelocities(double grav_param, std::vector<double> r0, std::vector<double> rf, double dt, bool long_way) { // algorithm constants const int MAXITER = 1000; const double TOLERANCE = 1E-10; // switch to canonical units double scale = 1.0/pow(grav_param,1.0/3.0); r0[0] = r0[0]*scale; r0[1] = r0[1]*scale; r0[2] = r0[2]*scale; rf[0] = rf[0]*scale; rf[1] = rf[1]*scale; rf[2] = rf[2]*scale; // problem constants double r0_norm = sqrt(r0[0]*r0[0] + r0[1]*r0[1] + r0[2]*r0[2]); double rf_norm = sqrt(rf[0]*rf[0] + rf[1]*rf[1] + rf[2]*rf[2]); double df = acos((r0[0]*rf[0] + r0[1]*rf[1] + r0[2]*rf[2])/(r0_norm*rf_norm)); if(long_way) df = 2.0*M_PI - df; double k = r0_norm*rf_norm*(1.0-cos(df)); double l = r0_norm + rf_norm; double m = r0_norm*rf_norm*(1.0+cos(df)); double p_i = k/(l+sqrt(2.0*m)); double p_ii = k/(l-sqrt(2.0*m)); // initial estimate double p = (p_i + p_ii)/2.0; // f and g functions double f,g,fdot,gdot; // Newton-Raphson iteration for(int i = 0; i < MAXITER; ++i) { double t, dtdp; // deal with negative values of p if(p < 0.0) p = ((MAXITER-i-1)*p_i+(i+1)*p_ii)/(MAXITER+2); // deal with out-of-bounds p if(!long_way && p < p_i) p = ((i+1)*p_i+(MAXITER-i-1)*p_ii)/(MAXITER+2); if(long_way && p > p_ii) p = ((i+1)*p_i+(MAXITER-i-1)*p_ii)/(MAXITER+2); // compute the semi-major axis using the new p double a = m*k*p/((2*m-l*l)*p*p + 2*k*l*p-k*k); // compute the values of the f and g functions f = 1-rf_norm/p*(1-cos(df)); g = r0_norm*rf_norm*sin(df)/sqrt(p); fdot = sqrt(1.0/p)*tan(df/2.0)*((1.0-cos(df))/p-1/r0_norm-1/rf_norm); gdot = (1.0+fdot*g)/f; // compute the time-of-flight and its derivative with respect to p if(a > 0.0) { double cosE = 1.0-r0_norm/a*(1.0-f); double sinE = -r0_norm*rf_norm*fdot/sqrt(a); double E = atan2(sinE,cosE); if(E < 0.0) E += 2.0*M_PI; t = g + sqrt(a*a*a)*(E-sin(E)); dtdp = g/(2*p)-3/2*a*(t-g)*((k*k+(2*m-l*l)*p*p)/(m*k*p*p))+sqrt(a*a*a)*(2*k*sinE)/(p*(k-l*p)); } else { double coshF = 1.0-r0_norm/a*(1-f); double F = acosh(coshF); t = g + sqrt(-a*a*a)*(sinh(F)-F); dtdp = -g/(2*p)-3/2*a*(t-g)*((k*k+(2*m-l*l)*p*p)/(m*k*p*p))-sqrt(-a*a*a)*(2*k*sinh(F))/(p*(k-l*p)); } // iterate p = p - (dt-t)/dtdp; if(std::abs(dt-t) < TOLERANCE) break; } // compute and return the initial and final velocities std::vector<double> v(6); v[0] = (rf[0]-f*r0[0])/g; v[1] = (rf[1]-f*r0[1])/g; v[2] = (rf[2]-f*r0[2])/g; v[3] = fdot*r0[0]+gdot*v[0]; v[4] = fdot*r0[1]+gdot*v[1]; v[5] = fdot*r0[2]+gdot*v[2]; // return from canonical units v[0] = v[0]/scale; v[1] = v[1]/scale; v[2] = v[2]/scale; v[3] = v[3]/scale; v[4] = v[4]/scale; v[5] = v[5]/scale; return v; }
#include "MotorBike.h" void MotorBike::printPosition() { std::cout << "The motorbike's position is "; BaseObject::printPosition(); } void MotorBike::move(Position newPosition) { DynamicObject::move(newPosition); std::cout << "The motorbike has been moved to new position "; BaseObject::printPosition(); }
//Midterm Programming Test #include <iostream> //inclusion of support for doing input & output #include <cmath> //inclusion of support for doing random number generation #include <cctype> //inclusion of support for character conversion #include <vector> using namespace std; //declare access to standard stuff like cin, cout vector<int> list0, list1, list2; //Recursive exhaustive branching search for a mixture sequence // C[begin] , C[begin + 1], ..., C[end] //derive from // Sequence: A[begin] , A[begin + 1], ..., A[end] and // Sequence: B[begin] , B[begin + 1], ..., B[end] //such that // The sum of C[begin] , C[begin + 1], ..., C[end] equals targetSum bool mixtureSequenceSearch(int begin, int end, int targetSum) { if (begin > end) //Nothing further to incorporate { if (targetSum == 0) return true; else return false; } if (mixtureSequenceSearch(begin + 1, end, targetSum - list0[begin]) == true) { //There is a solution if we select A[begin] into the mixture sequence list2[begin] = list0[begin]; return true; } else if (mixtureSequenceSearch(begin + 1, end, targetSum - list1[begin]) == true) { //There is a solution if we select B[begin] into the mixture sequence list2[begin] = list1[begin]; return true; } else //There is no way to find a mixture sequence for that partial sum return false; } // Beginning of main function int main() { double myRandom; int i,j; int n; while (true) { // 2 Lists to find an answer. //list0 = { 69, 38, 46, 43, 37, 34, 28, 75 }; //list1 = { 64, 77, 55, 24, 69, 12, 22, 69 }; //list0 = { 61, 27, 43, 54, 37, 45, 28, 64, 60, 38, 40, 43, 37, 34, 28, 75, 62, 33, 43, 60 }; //list1 = { 75, 74, 44, 24, 58, 12, 33, 69, 64, 70, 55, 24, 69, 12, 22, 69, 69, 74, 38, 24 }; list0 = { 18, 29, 31, 42, 55, 66, 71, 85, 91, 103, 114, 128, 135, 140, 155, 81, 93, 17, 24, 65, 39, 27, 58, 19, 130, 141, 182, 153, 104, 115, 18, 29, 31, 42, 55, 66, 71, 85, 91, 103, 114, 128, 135, 140, 155 }; list1 = { 81, 93, 17, 24, 65, 39, 27, 58, 19, 130, 141, 182, 153, 104, 115, 18, 29, 31, 42, 55, 66, 71, 85, 91, 103, 114, 128, 135, 140, 155, 81, 93, 17, 24, 65, 39, 27, 58, 19, 130, 141, 182, 153, 104, 115 }; // Number of items per list. n = (int) list0.size(); // What Sum Are You Looking For? cout << "What sum are you looking for?" << endl; int sum = 99991; list2.resize(n); // Initialize the answer vector. if (mixtureSequenceSearch(0, n - 1, sum) == true) { cout << endl << endl << "Mixture sequence with a sum of " << sum << " found: " << endl; for (int i = 0; i < n; i++) cout << "C[" << i << "]=" << list2[i] << endl; } else { cout << endl << endl << "No solution found" << endl; } char quit; cout << endl << endl << "Do you want to quit?(Y or N)"; cin >> quit; if (quit == 'y' || quit == 'Y') break; } return 0; }
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (5e18); const int INF = (1<<28); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class StreetWalking { public: long long minTime(int X, int Y, int walkTime, int sneakTime) { long long resw = (long long)X*walkTime + (long long)Y*walkTime; long long ress = (long long)max(X,Y)*sneakTime + ( abs(X-Y)&1 ? walkTime-sneakTime : 0 ); long long ressw = (long long)min(X,Y)*sneakTime + (long long)abs(X-Y)*walkTime; return min(resw, min(ress, ressw)); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const long long &Expected, const long long &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arg0 = 4; int Arg1 = 2; int Arg2 = 3; int Arg3 = 10; long long Arg4 = 18LL; verify_case(0, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } void test_case_1() { int Arg0 = 4; int Arg1 = 2; int Arg2 = 3; int Arg3 = 5; long long Arg4 = 16LL; verify_case(1, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } void test_case_2() { int Arg0 = 2; int Arg1 = 0; int Arg2 = 12; int Arg3 = 10; long long Arg4 = 20LL; verify_case(2, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } void test_case_3() { int Arg0 = 25; int Arg1 = 18; int Arg2 = 7; int Arg3 = 11; long long Arg4 = 247LL; verify_case(3, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } void test_case_4() { int Arg0 = 24; int Arg1 = 16; int Arg2 = 12; int Arg3 = 10; long long Arg4 = 240LL; verify_case(4, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } void test_case_5() { int Arg0 = 10000000; int Arg1 = 50000000; int Arg2 = 800; int Arg3 = 901; long long Arg4 = 41010000000LL; verify_case(5, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } void test_case_6() { int Arg0 = 135; int Arg1 = 122; int Arg2 = 43; int Arg3 = 29; long long Arg4 = 3929LL; verify_case(6, Arg4, minTime(Arg0, Arg1, Arg2, Arg3)); } // END CUT HERE }; // BEGIN CUT HERE int main() { StreetWalking ___test; ___test.run_test(-1); } // END CUT HERE
/////////////////////////////////////////////////////////////////////////// // Copyright (C) 2009 Whit Armstrong // // // // This program is free software: you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation, either version 3 of the License, or // // (at your option) any later version. // // // // This program is distributed in the hope that it will be useful, // // but WITHOUT ANY WARRANTY; without even the implied warranty of // // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // // GNU General Public License for more details. // // // // You should have received a copy of the GNU General Public License // // along with this program. If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////////////// #ifndef MCMC_DETERMINISTIC_HPP #define MCMC_DETERMINISTIC_HPP #include <cppmc/mcmc.specialized.hpp> namespace CppMC { template<typename DataT, template<typename> class ArmaT> class MCMCDeterministic : public MCMCSpecialized<DataT,ArmaT> { public: MCMCDeterministic(const ArmaT<DataT>& initial_value): MCMCSpecialized<DataT,ArmaT>(initial_value) {} // deterministics only derive their logp from their parents double logp() const { return 0; } // do nothing, object must be updated after all other objects are jumped void jump() {} void update() { MCMCSpecialized<DataT,ArmaT>::value_ = eval(); } bool isDeterministc() const { return true; } bool isStochastic() const { return false; } // user must provide this function to update object virtual ArmaT<DataT> eval() const = 0; }; } // namespace CppMC #endif // MCMC_DETERMINISTIC_HPP
#include <stdio.h> #define MAX 45 int F[MAX]; int fibonacci(int n){ if(F[n] != -1) return F[n]; if(n == 0 || n == 1){ F[n] = 1; }else{ F[n] = fibonacci(n-1) + fibonacci(n-2); } return F[n]; } int main(void){ int n, f; scanf("%d", &n); for(int i=0; i<=n; i++){ F[i] = -1; } f = fibonacci(n); printf("%d\n", f); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2012 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Kajetan Switalski ** */ #include "core/pch.h" #ifdef USE_SPDY #include "modules/url/protocols/spdy/spdy_internal/spdy_settingscontroller.h" #include "modules/url/protocols/spdy/spdy_internal/spdy_common.h" #include "modules/url/protocols/spdy/spdy_internal/spdy_frameheaders.h" #include "modules/url/protocols/spdy/spdy_internal/spdy_settingsmanager.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" enum SpdySettingsFlags { SSF_NONE = 0, SSF_PERSIST, SSF_PERSISTED }; enum SpdySettingsControlFlags { SSCF_CLEAR_PERSISTED_SETTINGS = 1 }; enum SpdySettingsIds { SSI_UPLOAD_BANDWIDTH = 1, SSI_DOWNLOAD_BANDWIDTH, SSI_ROUND_TRIP_TIME, SSI_MAX_CONCURRENT_STREAMS, SSI_CURRENT_CWND, SSI_DOWNLOAD_RETRANS_RATE, SSI_INITIAL_WINDOW_SIZE }; const unsigned SettingsEntrySize = 8; class SettingsEntry { UINT32 flags_and_id; UINT32 value; public: UINT32 GetId(SpdyVersion version) const { if (version == SPDY_V2) // in spdy2 the id is little endian (it's the result of a bug in initial implementation) { UINT32 id = op_ntohl(flags_and_id) >> 8; UINT32 rotate16 = (id << 16) | (id >> 16); const UINT32 mask = 0xff00ff; return (((rotate16 >> 8) & mask) | ((rotate16 & mask) << 8)) >> 8; } else return op_ntohl(flags_and_id) & 0xffffff; } UINT8 GetFlags(SpdyVersion version) const { return version == SPDY_V2 ? op_ntohl(flags_and_id) & 0xff : op_ntohl(flags_and_id) >> 24; } UINT32 GetValue() const { return op_ntohl(value); } void SetId(SpdyVersion version, UINT32 id) { if (version == SPDY_V2) // in spdy2 the id is little endian (it's the result of a bug in initial implementation) { UINT32 rotate16 = (id << 16) | (id >> 16); const UINT32 mask = 0xff00ff; flags_and_id = op_htonl(op_ntohl(flags_and_id) & 0xff | (((rotate16 >> 8) & mask) | ((rotate16 & mask) << 8))); } else flags_and_id = op_htonl(op_ntohl(flags_and_id) & 0xff000000 | id); } void SetFlags(SpdyVersion version, UINT8 f) { if (version == SPDY_V2) flags_and_id = op_htonl(op_ntohl(flags_and_id) & 0xffffff00 | f); else flags_and_id = op_htonl(op_ntohl(flags_and_id) & 0xffffff | (f << 24)); } void SetValue(UINT32 v) { value = op_htonl(v); } SettingsEntry(SpdyVersion version, UINT32 id, UINT32 val, UINT8 flags) { SetValue(val); SetFlags(version, flags); SetId(version, id); } }; SpdySettingsController::SpdySettingsController(SpdyVersion version, ServerName_Pointer serverName, unsigned short port, BOOL privacyMode): leftToConsume(0), maxConcurrentStreams(0), uploadBandwidth(0), downloadBandwidth(0), roundTripTime(0), currentCwnd(0), downloadRetransRate(0), version(version), serverName(serverName), port(port), privateMode(privacyMode) { OP_ASSERT(version == SPDY_V2 || version == SPDY_V3); } void SpdySettingsController::InitL() { SPDY_LEAVE_IF_ERROR(hostport.AppendFormat("%s:%d", serverName->Name(), port)); if (!g_pcnet->GetIntegerPref(PrefsCollectionNetwork::SpdySettingsPersistence, serverName) #ifdef _ASK_COOKIE || serverName->GetAcceptCookies() == COOKIE_NONE #endif // _ASK_COOKIE ) privateMode = TRUE; OpData settingEntries; if (!privateMode && g_spdy_settings_manager) { AutoDeleteList<PersistedSetting> settings; g_spdy_settings_manager->GetPersistedSettingsL(hostport, settings); for (PersistedSetting *it = settings.First(); it; it = it->Suc()) { SettingsEntry entry(version, it->settingId, it->value, SSF_PERSISTED); SPDY_LEAVE_IF_ERROR(settingEntries.AppendCopyData(reinterpret_cast<char*>(&entry), SettingsEntrySize)); SetSetting(it->settingId, it->value); } } initialWindowSize = static_cast<UINT32>(g_pcnet->GetIntegerPref(PrefsCollectionNetwork::SpdyInitialWindowSize, serverName)); if (static_cast<UINT32>(g_pcnet->GetDefaultIntegerPref(PrefsCollectionNetwork::SpdyInitialWindowSize)) != initialWindowSize) { SettingsEntry entry(version, SSI_INITIAL_WINDOW_SIZE, initialWindowSize, SSF_NONE); SPDY_LEAVE_IF_ERROR(settingEntries.AppendCopyData(reinterpret_cast<char*>(&entry), SettingsEntrySize)); } if (!settingEntries.IsEmpty()) { SettingsFrameHeader sfh(version, settingEntries.Length() / SettingsEntrySize); SPDY_LEAVE_IF_ERROR(initialFrame.AppendCopyData(reinterpret_cast<char*>(&sfh), SettingsFrameHeader::GetSize())); SPDY_LEAVE_IF_ERROR(initialFrame.Append(settingEntries)); } } BOOL SpdySettingsController::HasNextFrame() const { return !initialFrame.IsEmpty(); } void SpdySettingsController::WriteNextFrameL(SpdyNetworkBuffer &target) { target.AppendCopyDataL(initialFrame); initialFrame.Clear(); } UINT8 SpdySettingsController::GetPriority() const { return 0xff; // settings frame has always the highest priority } void SpdySettingsController::SettingsFrameLoaded(const SettingsFrameHeader *settingsFrame) { leftToConsume = SettingsEntrySize * settingsFrame->GetNumberOfEntries(); if (!privateMode && settingsFrame->GetFlags() == SSCF_CLEAR_PERSISTED_SETTINGS && g_spdy_settings_manager) g_spdy_settings_manager->ClearPersistedSettingsL(hostport); } BOOL SpdySettingsController::SetSetting(UINT32 id, UINT32 value) { switch (id) { case SSI_UPLOAD_BANDWIDTH: uploadBandwidth = value; break; case SSI_DOWNLOAD_BANDWIDTH: downloadBandwidth = value; break; case SSI_ROUND_TRIP_TIME: roundTripTime = value; break; case SSI_MAX_CONCURRENT_STREAMS: maxConcurrentStreams = value; break; case SSI_CURRENT_CWND: currentCwnd = value; break; case SSI_DOWNLOAD_RETRANS_RATE: downloadRetransRate = value; break; case SSI_INITIAL_WINDOW_SIZE: initialWindowSize = value; break; default: OP_ASSERT(!"Not supported setting id!"); return FALSE; } return TRUE; } BOOL SpdySettingsController::ConsumeDataL(OpData &data) { size_t dataToRead = MIN(leftToConsume, data.Length()); leftToConsume -= dataToRead; OpData readData(data, 0, dataToRead); ANCHOR(OpData, readData); data.Consume(dataToRead); SPDY_LEAVE_IF_ERROR(buffer.Append(readData)); while (buffer.Length() >= SettingsEntrySize) { char buf[SettingsEntrySize]; /* ARRAY OK 2012-04-29 kswitalski */ buffer.CopyInto(buf, SettingsEntrySize); buffer.Consume(SettingsEntrySize); SettingsEntry *se = reinterpret_cast<SettingsEntry*>(buf); UINT32 id = se->GetId(version); UINT8 flags = se->GetFlags(version); UINT32 value = se->GetValue(); BOOL recognized = SetSetting(id, value); if (recognized && !privateMode && flags == SSF_PERSIST && g_spdy_settings_manager) g_spdy_settings_manager->PersistSettingL(hostport, id, value); } return leftToConsume != 0; } #endif // USE_SPDY
/** Kabuki SDK @file /.../Source/Kabuki_SDK-Impl/_G/Caption.h @author Cale McCollough @copyright Copyright 2016 Cale McCollough © @license Read accompanying /.../README.md or online at http://www.boost.org/LICENSE_1_0.txt */ #include "_G/Cell.h" #include "_G/Caption_f.h" namespace _G { Caption::Caption () : Entity_f (0,0,0,0) { lrMargin = 5; tbMargin = 5; captionText = new TextArea (0,0,0,0); SetBorderMode (Cell.FillRoundCorners); } Caption::Caption (int captOriginX, int captOriginY) : Entity_f (captOriginX, captOriginY,0,0) { origin.x = captOriginX; origin.y = captOriginY; captionText = new TextArea (origin.x, origin.y,0,0); SetBorderMode (Cell.FillRoundCorners); } void Caption::SetText (const std::string& newString) { } void Caption::Caption_f::SetVerticalMargin (int Value) { if (Value < 0) return; tbMargin = Value; } void Caption::Caption_f::SetHorizontalMargin (int Value) { if (Value < 0) return; lrMargin = Value; } void Caption_f::Update () { captionText.Set_left_edge (Left_edge_int () + lrMargin; captionText.Set_top_edge (Top_edge_int () + tbMargin; SetWidth (captionText.Left_edge_int () + lrMargin); SetHeight (captionText.Bottom_edge_int () + tbMargin); } void Caption_f::Draw (const Cell& C) { if (isVisible) return; Rectangle.Draw (C); captionText.Draw (C); } std::string Caption_f::ToString () { return captionText.ToString (); } }
#include "common.h" #include "CRequestXmlMessage.h" #include "Markup.h" #include "CMessageEventMediator.h" #include "NetClass.h" #include <QSettings> #include <QTextCodec> CRequestXmlMessage::CRequestXmlMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent) : CMessage(pMessageEventMediator, parent) { } CRequestXmlMessage::~CRequestXmlMessage() { } bool CRequestXmlMessage::packedSendMessage(NetMessage& netMessage) { CMarkup xml; xml.SetDoc("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"); xml.AddElem("Message"); xml.AddChildElem("Header"); xml.IntoElem(); xml.AddAttrib("MsgType", "EMSG_REQUESTXML_REQ"); xml.OutOfElem(); xml.AddChildElem("Info"); xml.IntoElem(); xml.AddAttrib("Id", MessageDataMediator->m_strNewId.toStdString().c_str()); xml.OutOfElem(); netMessage.msgBuffer = packXml(&xml); netMessage.msgLen = xml.GetDoc().length(); return true; } bool CRequestXmlMessage::treatMessage(const NetMessage& netMessage, CNetClt* pNet) { CMarkup xml; if(xml.SetDoc(netMessage.msgBuffer)) { int errCode = 0; QString errorInfo = ""; if(checkError(&xml, errCode, errorInfo)) { if(0 != errCode) { ClientLogger->AddLog(QString::fromLocal8Bit("RequestXml [%1] : \r\n[%2]").arg(errorInfo).arg(netMessage.msgBuffer)); emit NetClass->m_pMessageEventMediator->sigError(netMessage.msgHead, errorInfo); MessageDataMediator->setConnectMsgMapProperty(EMSG_REQUESTXML, true); return true; } } if(xml.FindChildElem("SvrInfo")) { xml.IntoElem(); QString strUpdateXMLPath = QString::fromStdString(xml.GetAttrib("UpdateXmlUrl")); QString strHelpInfoXMLPath = QString::fromStdString(xml.GetAttrib("HelpInfoXmlUrl")); QString strVersionCheckFile = QString::fromStdString(xml.GetAttrib("VersionCheckFileUrl")); //QString strTextMode = QString::fromStdString(xml.GetAttrib("TextMode")); xml.OutOfElem(); // if(strTextMode == "1" && !MessageDataMediator->m_bTextMode) yhb // {//开启测试模式 // ClientLogger->AddLog(QString::fromLocal8Bit("开启测试模式")); // MessageDataMediator->m_bTextMode = true; // QSettings settings(HKCU, QSettings::NativeFormat); // settings.setIniCodec(QTextCodec::codecForName("UTF-8")); // settings.setValue("Connect/TextMode", strTextMode); // } // else if(strTextMode != "1" && MessageDataMediator->m_bTextMode) // { // ClientLogger->AddLog(QString::fromLocal8Bit("关闭测试模式")); // MessageDataMediator->m_bTextMode = false; // QSettings settings(HKCU, QSettings::NativeFormat); // settings.setIniCodec(QTextCodec::codecForName("UTF-8")); // settings.setValue("Connect/TextMode", strTextMode); // } ClientLogger->AddLog(QString::fromLocal8Bit("从服务器获取的升级XML路径为[%1] 帮助信息XML路径为[%2] 客户端版本号比较文件路径为[%3]").arg(strUpdateXMLPath).arg(strHelpInfoXMLPath).arg(strVersionCheckFile)); emit NetClass->m_pMessageEventMediator->sigGetXml(strUpdateXMLPath, strHelpInfoXMLPath, strVersionCheckFile); } else { ClientLogger->AddLog(QString::fromLocal8Bit("RequestXml收到的消息错误, 无法被正确解析 : [%1]").arg(netMessage.msgBuffer)); emit NetClass->m_pMessageEventMediator->sigError(netMessage.msgHead, QString::fromLocal8Bit("收到的消息错误, 无法被正确解析")); MessageDataMediator->setConnectMsgMapProperty(EMSG_REQUESTXML, true); } } else { ClientLogger->AddLog(QString::fromLocal8Bit("RequestXml收到的消息错误, 无法被正确解析 : [%1]").arg(netMessage.msgBuffer)); emit NetClass->m_pMessageEventMediator->sigError(netMessage.msgHead, QString::fromLocal8Bit("收到的消息错误, 无法被正确解析")); MessageDataMediator->setConnectMsgMapProperty(EMSG_REQUESTXML, true); } return true; }
#include "kmp.h" #include "kmp_io.h" #include "kmp_wrapper_malloc.h" #include <sicm_low.h> static void *h_sicm; static sicm_device_list (*p_sicm_init)(void); static sicm_arena (*p_sicm_arena_create)(size_t, int, sicm_device_list *); static void (*p_sicm_arena_destroy)(sicm_arena arena); static sicm_device *(*p_sicm_arena_get_devices)(sicm_arena sa); static int (*p_sicm_arena_set_devices)(sicm_arena sa, sicm_device *dev); static void *(*p_sicm_arena_alloc)(sicm_arena sa, size_t sz); static void (*p_sicm_free)(void *ptr); static int (*p_sicm_device_page_size)(sicm_device *); static int kmp_sicm_init_allocator(kmp_allocator_t *al); static void *kmp_sicm_alloc(size_t size, kmp_allocator_t *al, int gtid); static void kmp_sicm_free(void *ptr, kmp_allocator_t *al, int gtid); static sicm_device_list kmp_sicm_devs; // all static sicm_device_list kmp_sicm_default_devs; static sicm_device_list kmp_sicm_large_cap_devs; static sicm_device_list kmp_sicm_const_devs; static sicm_device_list kmp_sicm_high_bw_devs; static sicm_device_list kmp_sicm_low_lat_devs; static void kmp_sicm_init_device_list(sicm_device_list *devs, int tag) { int n; n = 0; for(unsigned int i = 0; i < kmp_sicm_devs.count; i++) { sicm_device *dev = kmp_sicm_devs.devices[i]; if (dev->tag == tag && p_sicm_device_page_size(dev) == 4) n++; } devs->count = n; devs->devices = (sicm_device **) malloc(n * sizeof(sicm_device *)); n = 0; for(unsigned int i = 0; i < kmp_sicm_devs.count; i++) { sicm_device *dev = kmp_sicm_devs.devices[i]; if (dev->tag == tag && p_sicm_device_page_size(dev) == 4) { devs->devices[n] = dev; n++; } } } void __kmp_init_sicm() { #if KMP_OS_UNIX && KMP_DYNAMIC_LIB h_sicm = dlopen("libsicm.so", RTLD_LAZY); if (!h_sicm) { // printf("can't load libsicm.so: %s\n", dlerror()); KE_TRACE(25, ("can't load libsicm.so: %s\n", dlerror())); goto error; } p_sicm_init = (sicm_device_list (*)(void)) dlsym(h_sicm, "sicm_init"); p_sicm_arena_create = (sicm_arena (*)(size_t, int, sicm_device_list *)) dlsym(h_sicm, "sicm_arena_create"); p_sicm_arena_destroy = (void (*)(sicm_arena)) dlsym(h_sicm, "sicm_arena_destroy"); p_sicm_arena_get_devices = (sicm_device *(*)(sicm_arena sa)) dlsym(h_sicm, "sicm_arena_get_devices"); p_sicm_arena_set_devices = (int (*)(sicm_arena sa, sicm_device *dev)) dlsym(h_sicm, "sicm_arena_set_devices"); p_sicm_arena_alloc = (void *(*)(sicm_arena sa, size_t sz)) dlsym(h_sicm, "sicm_arena_alloc"); p_sicm_free = (void (*)(void *ptr)) dlsym(h_sicm, "sicm_free"); p_sicm_device_page_size = (int (*)(sicm_device *)) dlsym(h_sicm, "sicm_device_page_size"); if (!p_sicm_init || !p_sicm_arena_create || !p_sicm_arena_destroy || !p_sicm_arena_get_devices || !p_sicm_arena_set_devices || !p_sicm_arena_alloc || !p_sicm_free || !p_sicm_device_page_size) { printf("can't initialize SICM library\n"); KE_TRACE(25, ("can't initialize SICM library\n")); goto error; } KE_TRACE(25, ("__kmp_init_sicm: Initializing SICM support\n")); kmp_sicm_devs = p_sicm_init(); kmp_init_allocator_p = kmp_sicm_init_allocator; kmp_sicm_init_device_list(&kmp_sicm_default_devs, SICM_DRAM); // printf("__kmp_init_sicm: Default memspace: %d devices\n", kmp_sicm_default_devs.count); KE_TRACE(25, ("__kmp_init_sicm: Default memspace: %d devices\n", kmp_sicm_default_devs.count)); kmp_sicm_init_device_list(&kmp_sicm_large_cap_devs, SICM_OPTANE); // printf("__kmp_init_sicm: Large-capacity memspace: %d devices\n", kmp_sicm_large_cap_devs.count); KE_TRACE(25, ("__kmp_init_sicm: Large-capacity memspace: %d devices\n", kmp_sicm_large_cap_devs.count)); kmp_sicm_init_device_list(&kmp_sicm_const_devs, -1); // printf("__kmp_init_sicm: Const memspace: %d devices\n", kmp_sicm_const_devs.count); KE_TRACE(25, ("__kmp_init_sicm: Constant memspace: %d devices\n", kmp_sicm_const_devs.count)); kmp_sicm_init_device_list(&kmp_sicm_high_bw_devs, SICM_KNL_HBM); // printf("__kmp_init_sicm: High-bandwidth memspace: %d devices\n", kmp_sicm_high_bw_devs.count); KE_TRACE(25, ("__kmp_init_sicm: High-bandwidth memspace: %d devices\n", kmp_sicm_high_bw_devs.count)); kmp_sicm_init_device_list(&kmp_sicm_low_lat_devs, -1); // printf("__kmp_init_sicm: Low-latency memspace: %d devices\n", kmp_sicm_low_lat_devs.count); KE_TRACE(25, ("__kmp_init_sicm: Low-latency memspace: %d devices\n", kmp_sicm_low_lat_devs.count)); for(int i = 0; i < 9; i++) kmp_sicm_init_allocator(&kmp_standard_allocators[i]); KE_TRACE(25, ("__kmp_init_sicm: SICM library initialized\n")); return; error: #endif p_sicm_init = NULL; p_sicm_arena_create = NULL; p_sicm_arena_get_devices = NULL; p_sicm_arena_set_devices = NULL; p_sicm_arena_alloc = NULL; p_sicm_free = NULL; if (h_sicm) dlclose(h_sicm); h_sicm = NULL; return; } void __kmp_fini_sicm() { if (h_sicm) dlclose(h_sicm); p_sicm_init = NULL; p_sicm_arena_create = NULL; p_sicm_arena_get_devices = NULL; p_sicm_arena_set_devices = NULL; p_sicm_arena_alloc = NULL; p_sicm_free = NULL; h_sicm = NULL; } int kmp_sicm_init_allocator(kmp_allocator_t *al) { sicm_arena sa; sicm_device_list *devs; KMP_ASSERT(p_sicm_arena_create != NULL); al->aux = NULL; devs = NULL; if (al->memspace == omp_default_mem_space) { devs = &kmp_sicm_default_devs; } else if (al->memspace == omp_const_mem_space) { devs = &kmp_sicm_const_devs; } else if (al->memspace == omp_large_cap_mem_space) { devs = &kmp_sicm_large_cap_devs; } else if (al->memspace == omp_high_bw_mem_space) { devs = &kmp_sicm_high_bw_devs; } else if (al->memspace == omp_low_lat_mem_space) { devs = &kmp_sicm_low_lat_devs; } // printf("kmp_sicm_init_allocator: al %p memspace %p devs %d\n", al, al->memspace, devs!=NULL?devs->count:-1); if (devs == NULL) return -1; if (devs->count == 0) return -1; sa = p_sicm_arena_create(al->pool_size, 0, devs); if (sa == NULL) { // printf("kmp_sicm_init_allocator: can't create arena\n"); return -1; } al->alloc = kmp_sicm_alloc; al->free = kmp_sicm_free; al->aux = sa; return 0; } static void *kmp_sicm_alloc(size_t size, kmp_allocator_t *al, int) { sicm_arena sa; sa = (sicm_arena) al->aux; KMP_ASSERT(p_sicm_arena_alloc != NULL); return p_sicm_arena_alloc(sa, size); } static void kmp_sicm_free(void *ptr, kmp_allocator_t *al, int) { KMP_ASSERT(p_sicm_free != NULL); p_sicm_free(ptr); } void kmp_sicm_destroy_allocator(kmp_allocator_t *al) { sicm_arena sa; sa = al->aux; p_sicm_arena_destroy(sa); }
#include <iostream> #include <sstream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <unordered_map> #include <unordered_set> #include <string> #include <set> #include <stack> #include <cstdio> #include <cstring> #include <climits> #include <cstdlib> using namespace std; struct Node { int u, d; Node(){} Node(int u, int d):u(u),d(d){} bool operator<(const Node& rhs) const { return d > rhs.d; } }; int strToInt(const string& s, int offset) { if (s[0] == 'G') return stoi(s.substr(1)) + offset; else return stoi(s); } int main() { int n, m, k, ds, dist; string from, to; cin >> n >> m >> k >> ds; vector<vector<Node> > graph; graph.resize(n + m + 1); while (k--) { cin >> from >> to >> dist; graph[strToInt(from, n)].push_back(Node(strToInt(to, n), dist)); graph[strToInt(to, n)].push_back(Node(strToInt(from, n), dist)); } double res_min = 0, res_avg = INT_MAX; int res_index = -1; for (int i = n+1; i <= m+n; i++) { vector<int> d(n + m + 1, INT_MAX); vector<bool> visited(n + m + 1, false); priority_queue<Node> q; q.push(Node(i, 0)); d[i] = 0; while (!q.empty()) { Node node = q.top(); q.pop(); if (visited[node.u]) continue; visited[node.u] = true; for (auto item : graph[node.u]) { if (d[node.u] + item.d < d[item.u]) { d[item.u] = d[node.u] + item.d; q.push(Node(item.u, d[item.u])); } } } double sum = 0; int min_dis = INT_MAX, max_dis = 0; for (int i = 1; i <= n; i++) { sum += d[i]; min_dis = min(min_dis, d[i]); max_dis = max(max_dis, d[i]); } if (max_dis <= ds) { double avg = sum / n; if ((min_dis > res_min) || ((min_dis == res_min) && (avg < res_avg))) { res_index = i - n; res_min = min_dis; res_avg = avg; } } } if (res_index == -1) { printf("No Solution\n"); } else { printf("G%d\n%.1f %.1f\n", res_index, res_min, res_avg); } return 0; }
/** * created: 2013-4-9 15:29 * filename: FKLuaBase * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #pragma warning(disable:4127) //------------------------------------------------------------------------ #include "../Include/Script/FKLuaBase.h" #include "../Include/FKLogger.h" //------------------------------------------------------------------------ #define GLuaLog_WriteLog g_logger.error //------------------------------------------------------------------------ const luaL_reg lualibs[] = { {"base", luaopen_base}, {"io", luaopen_io}, #ifdef _DEBUG {"debug", luaopen_debug}, #endif {"string", luaopen_string}, {"math", luaopen_math}, {"table",luaopen_table}, #if (LUA_VERSION_NUM <501) {"loadlib", luaopen_loadlib}, #endif {NULL, NULL} }; //------------------------------------------------------------------------ void lua_log_debug(const char* log){ g_logger.debug("lua log: %s",log); } //------------------------------------------------------------------------ void lua_log_error(const char* log){ g_logger.error("lua log: %s",log); } //------------------------------------------------------------------------ void lua_log_info(const char* log){ g_logger.info("lua log: %s",log); } //------------------------------------------------------------------------ void lua_log_force(const char* log){ g_logger.forceLog(zLogger::zINFO,"lua log: %s",log); } //------------------------------------------------------------------------ const char* lua_timetostr(time_t time1,const char* sformat){ if (sformat==NULL || sformat[0]==0){ return timetostr(time1,NULL,0,"%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d"); }else{ return timetostr(time1); } } //------------------------------------------------------------------------ time_t lua_strtotime(const char * szTime,const char* sformat) { if (sformat==NULL || sformat[0]==0){ return strtotime(szTime,"%4d-%2d-%2d %2d:%2d:%2d"); }else{ return strtotime(szTime); } } //------------------------------------------------------------------------ int lua_nowtime(){ return ((int)time(NULL)); } //------------------------------------------------------------------------ void init_cld_lib_func(lua_State* L){ using namespace luabind; module (L) [ def("glog_d",&lua_log_debug), def("glog_e",&lua_log_error), def("glog_i",&lua_log_info), def("glog_f",&lua_log_force), def("nowtime",&lua_nowtime), def("timetostr",&lua_timetostr), def("strtotime",&lua_strtotime) ]; } //------------------------------------------------------------------------ DWORD CLuaVM::dwThreadsId=0; //------------------------------------------------------------------------ CLuaVM::CLuaVM(bool bOpenStdLib) : m_ErrFn(0) , m_nParseStatus(-1) { m_luaState = lua_open(); g_logger.forceLog( zLogger::zFATAL, "[%s]LUASTATE [%x]", __FUNC_LINE__, m_luaState ); if(bOpenStdLib) OpenStdLib(); luabind::open(m_luaState); init_cld_lib_func(m_luaState); } //------------------------------------------------------------------------ CLuaVM::~CLuaVM(){ g_logger.forceLog( zLogger::zFATAL, "[%s]LUASTATE [%x]", __FUNC_LINE__, m_luaState ); lua_close(m_luaState); } //------------------------------------------------------------------------ void CLuaVM::OpenStdLib(){ assert(m_luaState); extern const luaL_reg lualibs[]; const luaL_reg *lib = lualibs; for (; lib->func; lib++){ lib->func(m_luaState); lua_settop(m_luaState, 0); } } //------------------------------------------------------------------------ bool CLuaVM::Do() { if (m_nParseStatus == 0) { m_nParseStatus = lua_pcall(m_luaState, 0, LUA_MULTRET, 0); } if (m_nParseStatus != 0) { lua_getglobal(m_luaState, "_ALERT"); if (lua_isfunction(m_luaState, -1)) { lua_insert(m_luaState, -2); lua_call(m_luaState, 1, 0); }else { const char* msg; msg = lua_tostring(m_luaState, -2); if (msg == NULL) msg = "(error with no message)"; g_logger.error("CATCHED Lua EXCEPTION -> err: %s",msg); lua_pop(m_luaState, 2); } } return m_nParseStatus == 0; } //------------------------------------------------------------------------ bool CLuaVM::DoFile(const char* filename) { if ( (m_nParseStatus = luaL_loadfile(m_luaState, filename)) == 0 ) { return Do(); }else{ const char* errmsg=(const char*)lua_tostring(m_luaState, -1); if(errmsg==NULL){errmsg="";}; lua_pop(m_luaState, 1); g_logger.error("CATCHED Lua EXCEPTION -> err: %s",errmsg); } return false; } //------------------------------------------------------------------------ bool CLuaVM::DoString(const char* buffer) { g_logger.forceLog( zLogger::zFATAL, "dostring lua" ); if ( (m_nParseStatus = luaL_loadbuffer(m_luaState,buffer,strlen(buffer),"LuaWrap")) == 0 ){ g_logger.forceLog( zLogger::zFATAL, "[%s]CALLED LUASTATE[%x]",__FUNC_LINE__, m_luaState ); return Do(); }else{ const char* errmsg=(const char*)lua_tostring(m_luaState, -1); if(errmsg==NULL){errmsg="";}; lua_pop(m_luaState, 1); g_logger.error("CATCHED Lua EXCEPTION -> err: %s",errmsg); } return false; } //------------------------------------------------------------------------ bool CLuaVM::DoBuffer(const char* buffer, size_t size) { g_logger.forceLog( zLogger::zFATAL, "dobuffer lua" ); if ( (m_nParseStatus = luaL_loadbuffer(m_luaState,buffer,size,"LuaWrap")) == 0 ){ return Do(); }else{ const char* errmsg=(const char*)lua_tostring(m_luaState, -1); if(errmsg==NULL){errmsg="";}; lua_pop(m_luaState, 1); g_logger.error("CATCHED Lua EXCEPTION -> err: %s",errmsg); } return false; } //------------------------------------------------------------------------ bool CLuaVM::VCall_LuaStr(const char* callstr) { if (dwThreadsId!=GetCurrentThreadId()){ g_logger.forceLog( zLogger::zFATAL, vformat("线程不同 原线程ID[%d] 当前线程ID[%d]",dwThreadsId,GetCurrentThreadId())); dwThreadsId=GetCurrentThreadId(); } if(callstr[0]=='+') { return DoString(&callstr[1]); } else { char* pchar_param[10]; char szfuncname[256]={0}; int param_count=0; _BUILDLUASTR_(callstr,count_of(pchar_param),szfuncname,pchar_param,param_count); if (param_count>=0) { _VCALL_BUILDLUASTR_(szfuncname,param_count,pchar_param[0],pchar_param[1],pchar_param[2],pchar_param[3],pchar_param[4], pchar_param[5],pchar_param[6],pchar_param[7],pchar_param[8],pchar_param[9]) } else { g_logger.error("VCall_LuaStr(%s) 参数字符串解析失败!",callstr); } return false; } } //------------------------------------------------------------------------ bool CLuaVM::LoadFileToBuffer(lua_State *L, const char *filename,char* szbuffer,int &maxlen,bool& loadlocal) { return false; } //------------------------------------------------------------------------
/* * **************************************************************************** * * * * * Copyright 2008, xWorkshop Inc. * * * All rights reserved. * * * Redistribution and use in source and binary forms, with or without * * * modification, are permitted provided that the following conditions are * * * met: * * * * Redistributions of source code must retain the above copyright * * * notice, this list of conditions and the following disclaimer. * * * * Redistributions in binary form must reproduce the above * * * copyright notice, this list of conditions and the following disclaimer * * * in the documentation and/or other materials provided with the * * * distribution. * * * * Neither the name of xWorkshop Inc. nor the names of its * * * contributors may be used to endorse or promote products derived from * * * this software without specific prior written permission. * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * * * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * * * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * * * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * * * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * * * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * * * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * * * Author: stoneyrh@163.com * * * * * **************************************************************************** */ #ifndef _X_TCP_SERVER_H_ #define _X_TCP_SERVER_H_ #include "xnetwork.hxx" #include "xerror_code.hxx" #include "xtcp_io_object.hxx" #include "xsignal.hxx" namespace xws { class xtcp_server { public: typedef xsignal<void (xtcp_io_object_ptr&)> connection_established_sig_t; xtcp_server(xio_service& io_service); virtual ~xtcp_server(); xio_service& io_service() { return io_service_; } connection_established_sig_t& connection_established_sig() { return connection_established_sig_; } virtual bool start(const xtcp_endpoint& endpoint = xtcp_endpoint(xaddress_v4::any(), 8693)); // 8693 looks like xage private: void start_accept(); void on_accept(xtcp_io_object_ptr& io_object, const xerror_code& error_code); private: xio_service& io_service_; xtcp_acceptor acceptor_; connection_established_sig_t connection_established_sig_; }; } #endif
#ifndef SetupConstruction_h #define SetupConstruction_h 1 /*! @file SetupConstruction.hh @brief Defines mandatory user class SetupConstruction. @date September, 2015 @author (D. Flechas dcflechasg@unal.edu.co) @version 1.0 In this header file, the 'physical' setup is defined: materials, geometries and positions. This class defines the experimental hall used in the toolkit. */ #include "globals.hh" #include "G4VUserDetectorConstruction.hh" #include "G4ThreeVector.hh" class G4LogicalVolume; class G4Region; class G4Material; class SetupMessenger; class Materials; /*! @brief This mandatory user class defines the geometry. It is responsible for @li Construction of geometry \sa Construct() */ class SetupConstruction : public G4VUserDetectorConstruction { public: //! Constructor SetupConstruction(); //! Destructor ~SetupConstruction(); public: //! Construct geometry of the setup G4VPhysicalVolume* Construct(); //! Update geometry void UpdateGeometry(); private: void ConstructSetup(void); void ConstructSetup_TEST(void); public: //! \name some simple set & get functions //@{ //! Get the number of sensitive volumes inline G4int GetTotalDetectorNumber() const {return DetectorCounter;}; //! Get the maximum number of sensitive volumes inline G4int GetMaximumNumberOfDetectors() const {return MaximumNumberOfDetectors;}; //@} private: //! \name Construction routines //@{ //! Declare the volumes already constructed as 'sensitive' void Sensibilize(); //! Add detectors to the DetectorCounter void Add2DetectorCounter(G4int added) { DetectorCounter+=added;}; void ResetDetectorCounter() { DetectorCounter=0;}; //! Our Materials List Materials* materials; public: //// Plate void SetPlate_Material(G4String mat) {Plate_Material = mat; }; void SetPlate_thickness(G4double val) {Plate_thickness = val; }; //! Materials defined in Materials.hh G4Material* FindMaterial(G4String mat); //!! Variables private: // Plate G4String Plate_Material; G4double Plate_thickness; private: //! Defining a region for the detector messenger where special \e cuts can be defined G4Region* BSDdetectorRegion; G4Region* PSDdetectorRegion; G4Region* ControlVolRegion; //! string used for naming purposes char string_name[30]; //! \name shared data between routines //!@{ //! Physical Global mother volume G4VPhysicalVolume* physiWorld; //! Logical Global mother volume G4LogicalVolume* logicWorld; //! Maximum number of detectors than can be created: one per each detector type G4int MaximumNumberOfDetectors; //! Counts the number of detectors defined G4int DetectorCounter; //! Construction flag G4bool constructed; //! //! \name UI Messenger //@{ //! Setup messenger to change the geometry SetupMessenger * messenger; //@} }; #endif // end SetupConstruction_h
#pragma once namespace settings { class Setting; static const int FLAG_VIRTUAL = 1; static const int FLAG_READONLY = 2; static const int FLAG_MANAGE_MEM = 4; typedef bool (* setFunction)(Setting* setting, void* value); typedef bool (* getFunction)(Setting* setting, void** value); enum { TYPE_STRING, TYPE_INT, TYPE_FLOAT, TYPE_VECTOR, TYPE_USERDEF }; class Setting { public: Setting() {}; ~Setting() { free(name); }; char* name; setFunction set; getFunction get; U8 type; U32 flags; void* data; }; void init(void); void release(void); void addsetting(char* name, U8 type, U32 flags, setFunction setter, getFunction getter, void* data); void delsetting(char* name); Setting* findsetting(char* name); void dump(char* pattern = NULL, bool sort = true); bool setstring(char*name, char* value); char* getstring(char*name); bool setint(char*name, int value); int getint(char*name); bool setfloat(char*name, float value); float getfloat(char*name); bool string_setter(Setting* setting, void* value); bool string_getter(Setting* setting, void** value); bool int_setter(Setting* setting, void* value); bool int_getter(Setting* setting, void** value); bool float_setter(Setting* setting, void* value); bool float_getter(Setting* setting, void** value); };
#include "SdLongNameFile.h" // Search for the first file in a directory given by is base class // // parameters: // SdBaseFile * dirPath : the directory we want to scan // // return: // true if found, false if not boolean SdLongNameFile::first( SdBaseFile * dirPath ) { p_sdbf = dirPath; p_sdbf->rewind(); return next(); } // Search for the first file in a directory given by his long name // // parameters: // char * lnPath : the long name of directory we want to scan // // return: // true if found, false if not boolean SdLongNameFile::first( char * lnPath, size_t lenLnPath ) { char shortPath[MAX_SHORTPATH]; if( ! long2shortPath( shortPath, lnPath, MAX_SHORTPATH, lenLnPath )) return false; sd.chdir( shortPath ); p_sdbf = sd.vwd(); p_sdbf->rewind(); return next(); } boolean SdLongNameFile::next() { uint8_t offset[] = {1, 3, 5, 7, 9, 14, 16, 18, 20, 22, 24, 28, 30}; uint8_t lfnIn = 130; uint8_t i; uint8_t ndir; uint8_t sum; uint8_t test; bool haveLong = false; while( p_sdbf->read( &dir_ln, 32 ) == 32 ) { if( DIR_IS_LONG_NAME( &dir_ln ) ) { if( ! haveLong ) { if(( dir_ln.name[0] & 0XE0 ) != 0X40 ) continue; ndir = dir_ln.name[0] & 0X1F; test = dir_ln.creationTimeTenths; haveLong = true; lfnIn = 130; long_name[ lfnIn ] = 0; } else if( dir_ln.name[0] != --ndir || test != dir_ln.creationTimeTenths ) { haveLong = false; continue; } char *p = (char*) & dir_ln; if( lfnIn > 0 ) { lfnIn -= 13; for( i = 0; i < 13; i++ ) long_name[ lfnIn + i ] = p[ offset[ i ]]; } } else if( DIR_IS_FILE_OR_SUBDIR( &dir_ln ) && dir_ln.name[0] != DIR_NAME_DELETED && dir_ln.name[0] != DIR_NAME_FREE && ( ! hideP || dir_ln.name[0] != 0x2E )) { if( haveLong ) { for( sum = i = 0; i < 11; i++ ) sum = (((sum & 1) << 7) | ((sum & 0xfe) >> 1)) + dir_ln.name[i]; if( sum != test || ndir != 1 ) haveLong = false; } if( haveLong ) { for( i = 0; lfnIn + i <= 130 ; i++ ) long_name[i] = long_name[lfnIn + i]; return true; } // else if( dir.reservedNT ) // return "Reserved NT"; else { SdFile::dirName( dir_ln, long_name ); return true; } } else { if( dir_ln.name[0] == DIR_NAME_FREE ) break; haveLong = false; } } long_name[ 0 ] = 0; return false; } // Get the long name of the file // // return: // pointer to the string that contain the long name char * SdLongNameFile::longName() { return long_name; } // Search for a file given by his long name // in a directory given by is short name // // parameters: // SdBaseFile * dirPath : the directory (short name) we want to scan // char * lnFile : the long name of the file // size_t lLnFile : the length of the long name file. If 0 (default), // calculated with strlen( lnFile ) // // return: // true if found, false if not boolean SdLongNameFile::search( SdBaseFile * dirPath, char * lnFile, size_t lLnFile ) { if( lLnFile == 0 ) lLnFile = strlen( lnFile ); boolean ok = first( dirPath ); while( ok ) { if( strncmp( long_name, lnFile, lLnFile ) == 0 ) return true; ok = next(); } return false; } boolean SdLongNameFile::search( char * lfnFile ) { char * psep = strrchr( lfnFile, '/' ); // if lfnFile ends with '/', this is a path without file name, // so point to first file if( psep == strrchr( lfnFile, 0 ) - 1 ) return first( lfnFile ); boolean ok = first( lfnFile, psep - lfnFile + 1 ); while( ok ) { if( strcmp( long_name, psep + 1 ) == 0 ) return true; ok = next(); } return false; } // Convert a 'long name' path to a 'short name' path // // parameters: // char * snPath (out) : where to store the 'short name' path // char * lnPath : the 'long name' path we want to convert // Must be absolute path (begin with /) // size_t lSnPath : the length of snPath string // size_t lLnPath : the length of the long name path. If 0 (default), // calculated with strlen( lnPath ) // // return: // true, if convertion is done boolean long2shortPath( char * snPath, char * lnPath, size_t lSnPath, size_t lLnPath ) { SdLongNameFile sdlnf; char * dir0 = lnPath + 1; char * dir1; char * dir2 = lnPath + ( lLnPath == 0 ? strlen( lnPath ) : lLnPath ); char * snPathEnd; strcpy( snPath, "/" ); while( dir0 < dir2 ) // strlen( dir0 ) > 0 ) { dir1 = strchr( dir0, '/' ); if( dir1 == 0 || dir1 > dir2 ) { dir1 = dir2; // strrchr( dir0, 0 ); if( dir1 == dir0 ) return true; } if( lSnPath <= strlen( snPath ) + 8 ) // not enough space in snPath return false; snPathEnd = strrchr( snPath, 0 ); // point to the end of snPath sd.chdir( snPath ); if( ! sdlnf.search( sd.vwd(), dir0, dir1 - dir0 )) return false; SdFile::dirName( sdlnf.dir(), snPathEnd ); // copy short name to snPathEnd if( dir1 >= dir2 || dir1[0] != '/' ) return true; strcat( snPath, "/" ); dir0 = dir1 + 1; } return true; }
#include <string> #include <cctype> #include <vector> #include <stdexcept> template <class T> std::string to_str(T&& x){ std::ostringstream buf; buf << x; return buf.str(); } template <class... Types> std::string format(std::string x, Types&&... t){ std::vector<std::string> args = {to_str(std::forward<Types>(t))...}; std::string result; std::istringstream in(x); char buf; while(in.read(&buf, 1)){ if(buf == '{'){ int k; in >> k; if(k+1 > args.size()) throw std::runtime_error(""); result += args[k]; in >> buf; if(buf != '}') throw std::runtime_error(""); }else{ if(buf == '}') throw std::runtime_error(""); result += buf; } } return result; }
#ifndef G2O_TARGET_TYPES_6D_HPP_ #define G2O_TARGET_TYPES_6D_HPP_ #include <g2o/core/base_vertex.h> #include <g2o/core/base_binary_edge.h> #include <g2o/core/base_unary_edge.h> #include <Eigen/Core> using namespace g2o; typedef Eigen::Matrix<double,6,1> Vector6d; typedef Eigen::Matrix<double,6,6> Matrix6d; // This header file specifies a set of types for the different // tracking examples; note that class VertexPosition3D : public g2o::BaseVertex<3, Eigen::Vector3d> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW VertexPosition3D() { } virtual void setToOriginImpl() { _estimate.setZero(); } virtual void oplusImpl(const double* update) { _estimate[0] += update[0]; _estimate[1] += update[1]; _estimate[2] += update[2]; } virtual bool read(std::istream& /*is*/) { return false; } virtual bool write(std::ostream& /*os*/) const { return false; } }; class PositionVelocity3DEdge { }; class VertexPositionVelocity3D : public g2o::BaseVertex<6, Vector6d> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW VertexPositionVelocity3D() { } virtual void setToOriginImpl() { _estimate.setZero(); } virtual void oplusImpl(const double* update) { for (int k = 0; k < 6; k++) _estimate[k] += update[k]; } virtual bool read(std::istream& /*is*/) { return false; } virtual bool write(std::ostream& /*os*/) const { return false; } }; // The odometry which links pairs of nodes together class TargetOdometry3DEdge : public g2o::BaseBinaryEdge<6, Eigen::Vector3d, VertexPositionVelocity3D, VertexPositionVelocity3D> { public: TargetOdometry3DEdge(double dt, double noiseSigma) { _dt = dt; double q = noiseSigma * noiseSigma; double dt2 = dt * dt; // Process noise covariance matrix; this assumes an "impulse" // noise model; we add a small stabilising term on the diagonal to make it invertible Matrix6d Q=Matrix6d::Zero(); Q(0, 0) = Q(1,1) = Q(2,2) = dt2*dt2*q/4 + 1e-4; Q(0, 3) = Q(1, 4) = Q(2, 5) = dt*dt2*q/2; Q(3, 3) = Q(4,4) = Q(5,5) = dt2 * q + 1e-4; Q(3, 0) = Q(4, 1) = Q(5, 2) = dt*dt2*q/2; setInformation(Q.inverse()); } /** set the estimate of the to vertex, based on the estimate of the from vertex in the edge. */ virtual void initialEstimate(const g2o::OptimizableGraph::VertexSet& from, g2o::OptimizableGraph::Vertex* to){ assert(from.size() == 1); const VertexPositionVelocity3D* vi = static_cast<const VertexPositionVelocity3D*>(*from.begin()); VertexPositionVelocity3D* vj = static_cast<VertexPositionVelocity3D*>(to); Vector6d viEst=vi->estimate(); Vector6d vjEst=viEst; for (int m = 0; m < 3; m++) { vjEst[m] += _dt * (vjEst[m+3] + 0.5 * _dt * _measurement[m]); } for (int m = 0; m < 3; m++) { vjEst[m+3] += _dt * _measurement[m]; } vj->setEstimate(vjEst); } /** override in your class if it's not possible to initialize the vertices in certain combinations */ virtual double initialEstimatePossible(const g2o::OptimizableGraph::VertexSet& from, g2o::OptimizableGraph::Vertex* to) { //only works on sequential vertices const VertexPositionVelocity3D* vi = static_cast<const VertexPositionVelocity3D*>(*from.begin()); return (to->id() - vi->id() == 1) ? 1.0 : -1.0; } void computeError() { const VertexPositionVelocity3D* vi = static_cast<const VertexPositionVelocity3D*>(_vertices[0]); const VertexPositionVelocity3D* vj = static_cast<const VertexPositionVelocity3D*>(_vertices[1]); for (int k = 0; k < 3; k++) { _error[k] = vi->estimate()[k] + _dt * (vi->estimate()[k+3] + 0.5 * _dt * _measurement[k]) - vj->estimate()[k]; } for (int k = 3; k < 6; k++) { _error[k] = vi->estimate()[k] + _dt * _measurement[k-3]- vj->estimate()[k]; } } virtual bool read(std::istream& /*is*/) { return false; } virtual bool write(std::ostream& /*os*/) const { return false; } private: double _dt; }; // The GPS class GPSObservationEdgePositionVelocity3D : public g2o::BaseUnaryEdge<3, Eigen::Vector3d, VertexPositionVelocity3D> { public: GPSObservationEdgePositionVelocity3D(const Eigen::Vector3d& measurement, double noiseSigma) { setMeasurement(measurement); setInformation(Eigen::Matrix3d::Identity() / (noiseSigma*noiseSigma)); } void computeError() { const VertexPositionVelocity3D* v = static_cast<const VertexPositionVelocity3D*>(_vertices[0]); for (int k = 0; k < 3; k++) { _error[k] = v->estimate()[k] - _measurement[k]; } } virtual bool read(std::istream& /*is*/) { return false; } virtual bool write(std::ostream& /*os*/) const { return false; } }; #endif // __TARGET_TYPES_6D_HPP__
#pragma once #include <map> class DResource; class DManager { public: std::map<std::string, DResource *> m_mapResource; public: DManager(); virtual ~DManager(); DResource *Create(std::string name); DResource *Find(std::string name); void Delete(std::string name); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 ** ** Copyright (C) 1995-1999 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/dom/src/domglobaldata.h" #include "modules/dom/src/opatom.h" OpAtom DOM_StringToAtom(const uni_char *string) { int lo = 0, hi = OP_ATOM_ABSOLUTELY_LAST_ENUM - 1; const char *const *names = g_DOM_atomNames; while (hi >= lo) { int index = (lo + hi) >> 1; const char *n1 = names[index]; const uni_char *n2 = string; while (*n1 && *n2 && *n1 == *n2) ++n1, ++n2; int r = *n1 - *n2; if (r == 0) return (OpAtom) index; else if (r < 0) lo = index + 1; else hi = index - 1; } return OP_ATOM_UNASSIGNED; } Markup::AttrType DOM_AtomToHtmlAttribute(OpAtom atom) { unsigned value = (g_DOM_atomData[atom] & 0xffff0000) >> 16; if (value == USHRT_MAX) return Markup::HA_NULL; else return static_cast<Markup::AttrType>(value); } #ifdef SVG_DOM Markup::AttrType DOM_AtomToSvgAttribute(OpAtom atom) { unsigned short value = g_DOM_SVG_atomData[atom]; if (value == USHRT_MAX) return Markup::HA_NULL; else return static_cast<Markup::AttrType>(value); } #endif // SVG_DOM int DOM_AtomToCssProperty(OpAtom atom) { unsigned value = g_DOM_atomData[atom] & 0xffff; if (value == USHRT_MAX) return -1; else return (int) value; } const char *DOM_AtomToString(OpAtom atom) { return g_DOM_atomNames[atom]; } #include "modules/dom/src/opatomdata.h" #include "modules/dom/src/opatom.cpp.inc"
#ifndef __CCGREEPAYMENT_H__ #define __CCGREEPAYMENT_H__ #include <string.h> #include "GreeExtensionMacros.h" #include "cocoa/CCString.h" #include "cocoa/CCArray.h" NS_CC_GREE_EXT_BEGIN class CCGreePayment; class CCGreePaymentDelegate { public: virtual void paymentRequestSuccess(CCGreePayment *payment, int responseCode, CCString* paymentId){}; virtual void paymentRequestCancel(CCGreePayment *payment, int responseCode, CCString* paymentId){}; virtual void paymentRequestFailure(CCGreePayment *payment, int responseCode, CCString *paymentId, CCString *response){}; virtual void paymentRequestOpened(CCGreePayment *payment){}; virtual void paymentRequestClosed(CCGreePayment *payment){}; virtual void paymentVerifySuccess(int responseCode, CCString* paymentId){}; virtual void paymentVerifyCancel(int responseCode, CCString* paymentId){}; virtual void paymentVerifyFailure(int responseCode, CCString *paymentId, CCString *response){}; }; class CCGreePaymentItem : public CCObject { public: CCGreePaymentItem(void* obj); ~CCGreePaymentItem(); static CCGreePaymentItem *create(const char *itemId, const char* itemName, double unitPrice, int quantity); void setImageUrl(const char *url); void setDescription(const char *desc); CCString *getItemId(); CCString *getItemName(); double getUnitPrice(); int getQuantity(); CCString *getImageUrl(); CCString *getDescription(); void* getPaymentItemObject(); private: void* mPaymentItemObj; }; class CCGreePayment : public CCObject { public: CCGreePayment(void* obj, CCString *message, CCArray *items); ~CCGreePayment(); static CCGreePayment* create(const char *message, CCArray *items); static void verify(const char *paymentId); void request(); void setCallbackUrl(const char *url); CCString *getPaymentMessage(); CCArray *getPaymentItems(); // Callback void handlePaymentRequestOnSuccess(int responseCode, const char* paymentId); void handlePaymentRequestOnCancel(int responseCode, const char* paymentId); void handlePaymentRequestOnFailure(int responseCode, const char* paymentId, const char* response); void handleDialogOpened(void); void handleDialogClosed(void); static void handlePaymentVerifyOnSuccess(int responseCode, const char* paymentId); static void handlePaymentVerifyOnCancel(int responseCode, const char* paymentId); static void handlePaymentVerifyOnFailure(int responseCode, const char* paymentId, const char* response); private: void* mPaymentObj; CCString *mMessage; CCArray *mItems; }; NS_CC_GREE_EXT_END #endif
#include "reorderingbuffer.h" #include <iostream> #include <algorithm> using namespace std; #include <unistd.h> void ReorderingBuffer::addBlock(uint32_t stream_idx, uint32_t global_idx, std::shared_ptr<trevi::SourceBlock> sb) { // If the idx is far enough, reset buffer and start clean... // If the current buffer size is less than max window size, then we can insert anyway... // Drop blocks until ok... while( _buffer.size() >= _windowSize ) { _outputQueue.push_back( _buffer.front().block ); _buffer.pop_front(); } insert( stream_idx, global_idx, sb ); #ifdef USE_LOG dump(); #endif } bool ReorderingBuffer::available() { return _outputQueue.size() > 0; } std::shared_ptr<trevi::SourceBlock> ReorderingBuffer::pop() { std::shared_ptr<trevi::SourceBlock> ret = nullptr; if( _outputQueue.size() > 0 ) { ret = _outputQueue.front(); _outputQueue.pop_front(); } return ret; } void ReorderingBuffer::insert(uint32_t stream_idx, uint32_t global_idx, std::shared_ptr<trevi::SourceBlock> sb) { trevi::DecodeOutput deco; deco.block = sb; deco.stream_idx = stream_idx; deco.global_idx = global_idx; _buffer.push_back( deco ); std::sort( _buffer.begin(), _buffer.end(), trevi::DecodeOutputComparator() ); } void ReorderingBuffer::dump() { cerr << "~~~~ REORDERING BUFFER:" << endl; for( int i = 0; i < _buffer.size(); ++i ) { cerr << "[" << _buffer[i].global_idx << "] "; } cerr << endl; // usleep(100000); }
#pragma once #include <ionir/construct/construct.h> namespace ionir { template<typename T = Construct> // requires std::derived_from<T, Construct> // TODO: Cannot work in the current system because ConstructWithParent<T> is used where T is a forward decl. struct ConstructWithParent : Construct { ConstructWithParent(ionshared::Ptr<T> parent, ConstructKind kind) : Construct(kind, std::nullopt, parent) { // } ionshared::Ptr<T> getUnboxedParent() { if (!ionshared::util::hasValue(this->parent)) { throw std::runtime_error("Parent is nullptr"); } return this->parent->get()->template dynamicCast<T>(); } }; }
// // Window.cpp // Odin.MacOSX // // Created by Daniel on 05/06/15. // Copyright (c) 2015 DG. All rights reserved. // #include <assert.h> #include "Window.h" #include "Monitor.h" namespace odin { namespace io { Window::Window() { } WindowHandle* Window::getHandle() const { return m_handle; } void Window::setWidth(int width) { setSize(width, getSize().y); } int Window::getWidth() const { return getSize().x; } void Window::setHeight(int height) { setSize(getSize().x, height); } int Window::getHeight() const { return getSize().y; } void Window::setSize(int width, int height) { m_width = width; m_height = height; if(m_handle) lib::setWindowSize(m_handle, width, height); } math::ivec2 Window::getSize() const { return math::ivec2(m_width, m_height); } void Window::setTitle(std::string title) { if (title == m_title) return; m_title = std::move(title); if(m_handle) lib::setWindowTitle(m_handle, title); } const std::string& Window::getTitle() const { return m_title; } void Window::setPosition(int x, int y) const { assert(m_handle); lib::setWindowPosition(m_handle, x, y); } void Window::getPosition(int& x, int& y) const { assert(m_handle); lib::getWindowPosition(m_handle, x, y); } void Window::getFramebufferSize(int& width, int& height) const { assert(m_handle); lib::getWindowFramebufferSize(m_handle, width, height); } void Window::iconify() const { assert(m_handle); lib::iconifyWindow(m_handle); } void Window::restore() const { assert(m_handle); lib::restoreWindow(m_handle); } void Window::show() const { assert(m_handle); lib::showWindow(m_handle); } void Window::hide() const { assert(m_handle); lib::hideWindow(m_handle); } bool Window::isFocused() const { assert(m_handle); return lib::isWindowFocused(m_handle); } bool Window::isIconified() const { assert(m_handle); return lib::isWindowIconified(m_handle); } bool Window::isVisible() const { assert(m_handle); return lib::isWindowVisible(m_handle); } bool Window::isResizable() const { assert(m_handle); return lib::isWindowResizable(m_handle); } bool Window::isDecorated() const { assert(m_handle); return lib::isWindowDecorated(m_handle); } void Window::setFullscreen(bool value) { //assert(cHandle.pHandle); m_isFullscreen = value; //myDestroy(cHandle.pHandle); // destroy window //MonitorHandle monitor = myGetPrimaryMonitor(); // get primary monitor //create(monitor); // create fullscreen window } bool Window::isFullscreen() const { return m_isFullscreen; } bool Window::shouldClose() const { if(m_handle) return lib::shouldWindowClose(m_handle); else return false; } void Window::swapBuffers() const { assert(m_handle); lib::swapBuffers(m_handle); } void Window::makeCurrent() const { assert(m_handle); lib::makeWindowCurrent(m_handle); } void Window::create(const CreationHints &hints) { create(nullptr, hints); } void Window::create(Monitor* monitor, const CreationHints &hints) { assert(!m_handle); if (m_handle != nullptr) throw std::runtime_error("Window already created"); // apply hints lib::applyCreationHints(hints); // no shared context if(m_isFullscreen) { assert(monitor); m_handle = lib::createWindow(m_width, m_height, m_title.c_str(), monitor->getHandle(), nullptr); } else { // not running fullscreen, so no specific monitor associated m_handle = lib::createWindow(m_width, m_height, m_title.c_str(), nullptr, nullptr); } if (m_handle == nullptr) throw std::runtime_error("Could not create window"); } void Window::destroy() { assert(m_handle); lib::destroyWindow(m_handle); } } }
/* * H_DetectorConstruction.h * * Created on: Oct 2, 2018 * Author: vsevolod */ #ifndef H_DETECTORCONSTRUCTION_H_ #define H_DETECTORCONSTRUCTION_H_ #include <G4VUserDetectorConstruction.hh> #include "H_SensitiveDetector.h" #include "G4Material.hh" #include "G4NistManager.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4Trd.hh" #include "G4Trap.hh" #include "G4Cons.hh" #include "G4ExtrudedSolid.hh" #include "G4VSolid.hh" #include "G4UnionSolid.hh" #include "G4MultiUnion.hh" #include "G4SubtractionSolid.hh" #include "G4LogicalVolume.hh" #include "G4ThreeVector.hh" #include "G4RotationMatrix.hh" #include "G4Transform3D.hh" #include "G4PVPlacement.hh" #include "G4AssemblyVolume.hh" #include "G4VisAttributes.hh" #include "G4OpticalSurface.hh" #include "G4LogicalSkinSurface.hh" #include "G4Color.hh" #include "G4TwoVector.hh" #include "G4SDManager.hh" #include "globals.hh" #include "HConst.hh" class H_DetectorConstruction: public G4VUserDetectorConstruction { public: H_DetectorConstruction(); virtual ~H_DetectorConstruction(); public: G4VPhysicalVolume* Construct(); void ConstructSDandField(); void DefineMateials(); G4VPhysicalVolume* DefineVolumes(); H_SensitiveDetector *SDB2; H_SensitiveDetector *SDB1; H_SensitiveDetector *SDB0; H_SensitiveDetector *SDF1; H_SensitiveDetector *SDF2; H_SensitiveDetector *HSD; G4LogicalVolume *HStationB2Log; G4LogicalVolume *HStationB1Log; G4LogicalVolume *HStationB0Log; G4LogicalVolume *HStationF1Log; G4LogicalVolume *HStationF2Log; private: G4Material *LHCbMaterial; G4Material *BPMaterial; G4Material *worldMaterial; G4Material *ScintMaterial; G4Material *Vacuum; }; #endif /* H_DETECTORCONSTRUCTION_H_ */
//http://codeforces.com/problemset/problem/446/A #include <iostream> using namespace std; int main() { int n, a[100000], l[100000], r[100000], ans; cin >> n; for(int i = 0; i < n; i++) cin >> a[i]; if(n<=2) { cout<<n<<'\n'; return 0; } l[0] = 1; ans = 1; //find length of strictly increaing sequences for(int i = 1; i < n; i++) l[i] = (a[i] > a[i - 1] ? l[i-1] + 1 : 1), ans = max(ans , l[i-1] + 1); //find length of strictly incresing sequences from end r[n - 1] = 1; for(int i = n - 2; i > -1; i--) r[i] = (a[i] < a[i + 1] ? r[i + 1] + 1 : 1), ans = max(ans, r[i + 1] + 1); //ans for current element is sum of strictly increasing sequences just before and after it for(int i = 1; i < n - 1; i++) if (a[i + 1] - a[i - 1] >= 2) ans = max(ans, l[i - 1] + 1 + r[i + 1]); cout << ans << endl; }
#include<iostream> using namespace std; int main() { int a,b,c; for(a = 5; a >= 1; a--) { for(b = a; b >= 1; b--) { cout<<" "; } for(c = 1; c <= a; c++) { cout<<"*"<<" "; } cout<<"\n"; } return 0; }
// // Created by root on 25/05/19. // #ifndef SFML_TEST_4_PLAYER_H #define SFML_TEST_4_PLAYER_H #include <SFML/Graphics.hpp> #include "Animation.h" #include "Collider.h" #pragma once class Player { private: sf::RectangleShape body; Animation playerAnimation; unsigned int row; float speed; bool faceRight; sf::Vector2f velocity; bool canjump; float jumpheight; public: static constexpr float VIEW_HEIGHT = 200.0f; static constexpr float VIEW_WIDHT = 512.0f; Player(sf::Texture* tx,sf::Vector2u imageCount,float switchTime, float speed, float jumpheight); ~Player(); void Update(float deltaTime); //encarregada de fazer a atualização de quadros, chamando playerAnimation.Update e passando alguns valores contidos no objeto void Draw (sf::RenderWindow& window); //ao inves de retornar à main o player para ser desenhado, isso ja é feito no proprio objeto, apenas chamando uma classe sf::Vector2f getPosition(){ return body.getPosition();} Collider* getColider(){Collider* collider = new Collider(&body); return collider;} void onCollision(sf::Vector2f direction); }; #endif //SFML_TEST_4_PLAYER_H
#include <fstream> #include "psef23_2_opt.h" int main() { ofstream in_pix("input_pixels_regression_result_psef23_2_opt.txt"); ofstream fout("regression_result_psef23_2_opt.txt"); HWStream<hw_uint<32> > in_update_0_read; HWStream<hw_uint<32> > psef23_2_update_0_write; // Loading input data // cmap : { in_update_0[root = 0, in_0, in_1] -> in_off_chip[0, 0] : 0 <= in_0 <= 963 and 0 <= in_1 <= 1086 } // read map: { in_off_chip[0, 0] -> in_update_0[root = 0, in_0, in_1] : 0 <= in_0 <= 963 and 0 <= in_1 <= 1086 } // rng : { in_update_0[root = 0, in_0, in_1] : 0 <= in_0 <= 963 and 0 <= in_1 <= 1086 } for (int i = 0; i < 1047868; i++) { hw_uint<32> in_val; set_at<0*16, 32, 16>(in_val, 2*i + 0); in_pix << in_val << endl; set_at<1*16, 32, 16>(in_val, 2*i + 1); in_pix << in_val << endl; in_update_0_read.write(in_val); } psef23_2_opt(in_update_0_read, psef23_2_update_0_write); for (int i = 0; i < 1036800; i++) { hw_uint<32> actual = psef23_2_update_0_write.read(); auto actual_lane_0 = actual.extract<0*16, 15>(); fout << actual_lane_0 << endl; auto actual_lane_1 = actual.extract<1*16, 31>(); fout << actual_lane_1 << endl; } in_pix.close(); fout.close(); return 0; }
#include "programwindowimage.h" //#define IM_WIDTH 720 //#define IM_HEIGHT 576 #define IM_WIDTH 1000 #define IM_HEIGHT 650 ProgramWindowImage::ProgramWindowImage(QStringList fileNames, QWidget *parent): ProgramWindow(parent), imageNames(fileNames) { frame_count = imageNames.size(); printf("Images count : %d\n", frame_count); on_nextButton_clicked(); preloadFrames(0,120); int imWidth = std::min(IM_WIDTH, curr_frame.cols); int imHeight = std::min(IM_HEIGHT, curr_frame.rows); ui->mainFrame->setFixedSize(imWidth + 2, imHeight + 23); ui->bannersListWidget->setViewMode(QListWidget::IconMode); ui->bannersListWidget->setIconSize(QSize(200,200)); ui->framesListWidget->setViewMode(QListWidget::IconMode); ui->framesListWidget->setIconSize(QSize(100,80)); ui->framesListWidget->setFixedHeight(120); ui->framesListWidget->setWrapping(false); ui->framesListWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Right way: //setCentralWidget(ui->gridLayoutWidget); //adjustSize(); //but it cause "black widget init" bug, so: resize(imWidth + 280, imHeight + 260); ui->createBannerButton->setEnabled(false); ui->detectButton->setEnabled(false); ui->minuteSb->setMinimum(0); if (frame_count < 120) { ui->minuteSb->setMaximum(1); ui->minuteSb->setEnabled(false); }else ui->minuteSb->setMaximum(frame_count / 120); ui->timeEdit->setVisible(false); ui->checkStartSb->setMaximum(frame_count - 1); ui->checkStartSb->setValue(0); ui->checkFinishSb->setMaximum(frame_count - 1); ui->checkFinishSb->setValue(frame_count - 1); ui->gotoFrameSb->setMaximum(frame_count - 1); params->partPolicy = 1; params->fTypeIndex = 3; } void ProgramWindowImage::readCurrentFrame() { if (curr_frame_num < frame_count && curr_frame_num >= 0) { curr_frame = cv::imread(imageNames[curr_frame_num].toStdString()); int imWidth = std::min(IM_WIDTH, curr_frame.cols); int imHeight = std::min(IM_HEIGHT, curr_frame.rows); initScale = double(imWidth) / curr_frame.cols; } else std::cout << "WARNING: assert(0 <= curr_frame_num < frame_count)\n"; }
#include "pch.hpp" #include "map.hpp" #include "grid.hpp" using yama::map; class map::impl_t { public: impl_t(int const Width, int const Height) : category_ {Width, Height} { } void clear() { category_.clear(); } tile_category get_category(int x, int y) const { return category_(x, y); } void set_category(int x, int y, tile_category const value) { category_(x, y) = value; } bool is_valid_position(int x, int y) const { return category_.is_valid_index(x, y); } int width() const { return category_.width(); } int height() const { return category_.height(); } private: grid<tile_category> category_; }; ///////////////////// map::map(map&& other) : impl_ {std::move(other.impl_)} { } map& map::operator=(map&& rhs) { std::swap(impl_, rhs.impl_); return *this; } map::map(yama::map_size const Width, yama::map_size const Height) : impl_ {std::make_unique<impl_t>(Width, Height)} { } map::~map() { } void map::clear() { impl_->clear(); } yama::tile_category map::get_category_(int const x, int const y) const { return impl_->get_category(x, y); } void map::set_category_(int x, int y, yama::tile_category value) { impl_->set_category(x, y, value); } bool map::is_valid_position(int x, int y) const { return impl_->is_valid_position(x, y); } int map::width() const { return impl_->width(); } int map::height() const { return impl_->height(); }
#ifndef hhAnalysis_multilepton_EvtHistManager_hh_4l_h #define hhAnalysis_multilepton_EvtHistManager_hh_4l_h /** \class EvtHistManager_hh_4l * * Book and fill histograms for event-level quantities in the 4l category * of the HH->tttt, WWtt, and WWWW analysis * * \author Christian Veelken, Tallinn * */ #include "tthAnalysis/HiggsToTauTau/interface/HistManagerBase.h" // HistManagerBase class EvtHistManager_hh_4l : public HistManagerBase { public: EvtHistManager_hh_4l(const edm::ParameterSet &cfg); ~EvtHistManager_hh_4l() {} /// book and fill histograms void bookHistograms(TFileDirectory &dir) override; void fillHistograms(int numElectrons, int numMuons, int numJets, int numJetsPtGt40, int numBJets_loose, int numBJets_medium, double dihiggsVisMass, double dihiggsMass, double HT, double STMET, double lep1_pt, double lep2_pt, double lep3_pt, double lep4_pt, double lep1_conePt, double lep2_conePt, double lep3_conePt, double lep4_conePt, double lep1_eta, double lep2_eta, double lep3_eta, double lep4_eta, double lep1_phi, double lep2_phi, double lep3_phi, double lep4_phi, double maxPtSum_pair1_pt, double maxPtSum_pair1_eta, double maxPtSum_pair1_phi, double maxPtSum_pair1_deltaEtaLep1, double maxPtSum_pair1_deltaPhiLep1, double maxPtSum_pair1_deltaEta, double maxPtSum_pair1_deltaPhi, double maxPtSum_pair1_deltaR, double maxPtSum_pair1_deltaPt, double maxPtSum_pair1_m, double maxPtSum_pair2_pt, double maxPtSum_pair2_eta, double maxPtSum_pair2_phi, double maxPtSum_pair2_deltaEtaLep1, double maxPtSum_pair2_deltaPhiLep1, double maxPtSum_pair2_deltaEta, double maxPtSum_pair2_deltaPhi, double maxPtSum_pair2_deltaR, double maxPtSum_pair2_deltaPt, double maxPtSum_pair2_m, double maxSubleadPt_pair1_pt, double maxSubleadPt_pair1_eta, double maxSubleadPt_pair1_phi, double maxSubleadPt_pair1_deltaEtaLep1, double maxSubleadPt_pair1_deltaPhiLep1, double maxSubleadPt_pair1_deltaEta, double maxSubleadPt_pair1_deltaPhi, double maxSubleadPt_pair1_deltaR, double maxSubleadPt_pair1_deltaPt, double maxSubleadPt_pair1_m, double maxSubleadPt_pair2_pt, double maxSubleadPt_pair2_eta, double maxSubleadPt_pair2_phi, double maxSubleadPt_pair2_deltaEtaLep1, double maxSubleadPt_pair2_deltaPhiLep1, double maxSubleadPt_pair2_deltaEta, double maxSubleadPt_pair2_deltaPhi, double maxSubleadPt_pair2_deltaR, double maxSubleadPt_pair2_deltaPt, double maxSubleadPt_pair2_m, double minDeltaRSum_pair1_pt, double minDeltaRSum_pair1_eta, double minDeltaRSum_pair1_phi, double minDeltaRSum_pair1_deltaEtaLep1, double minDeltaRSum_pair1_deltaPhiLep1, double minDeltaRSum_pair1_deltaEta, double minDeltaRSum_pair1_deltaPhi, double minDeltaRSum_pair1_deltaR, double minDeltaRSum_pair1_deltaPt, double minDeltaRSum_pair1_m, double minDeltaRSum_pair2_pt, double minDeltaRSum_pair2_eta, double minDeltaRSum_pair2_phi, double minDeltaRSum_pair2_deltaEtaLep1, double minDeltaRSum_pair2_deltaPhiLep1, double minDeltaRSum_pair2_deltaEta, double minDeltaRSum_pair2_deltaPhi, double minDeltaRSum_pair2_deltaR, double minDeltaRSum_pair2_deltaPt, double minDeltaRSum_pair2_m, double minSubclosestDeltaR_pair1_pt, double minSubclosestDeltaR_pair1_eta, double minSubclosestDeltaR_pair1_phi, double minSubclosestDeltaR_pair1_deltaEtaLep1, double minSubclosestDeltaR_pair1_deltaPhiLep1, double minSubclosestDeltaR_pair1_deltaEta, double minSubclosestDeltaR_pair1_deltaPhi, double minSubclosestDeltaR_pair1_deltaR, double minSubclosestDeltaR_pair1_deltaPt, double minSubclosestDeltaR_pair1_m, double minSubclosestDeltaR_pair2_pt, double minSubclosestDeltaR_pair2_eta, double minSubclosestDeltaR_pair2_phi, double minSubclosestDeltaR_pair2_deltaEtaLep1, double minSubclosestDeltaR_pair2_deltaPhiLep1, double minSubclosestDeltaR_pair2_deltaEta, double minSubclosestDeltaR_pair2_deltaPhi, double minSubclosestDeltaR_pair2_deltaR, double minSubclosestDeltaR_pair2_deltaPt, double minSubclosestDeltaR_pair2_m, double MET, double METPhi, double METDeltaPhiLep1, double MET_LD, double HTmiss, int lep1_isElectron, int lep1_charge, int lep2_isElectron, int lep2_charge, int lep3_isElectron, int lep3_charge, int lep4_isElectron, int lep4_charge, int leptonChargeSum, int electronChargeSum, int muonChargeSum, int nSFOS, double evtWeight); const TH1 *getHistogram_EventCounter() const; private: TH1 *histogram_numElectrons_; TH1 *histogram_numMuons_; TH1 *histogram_numJets_; TH1 *histogram_numJetsPtGt40_; TH1 *histogram_numBJets_loose_; TH1 *histogram_numBJets_medium_; TH1 *histogram_dihiggsVisMass_; TH1 *histogram_dihiggsMass_; TH1 *histogram_HT_; TH1 *histogram_STMET_; TH1 *histogram_EventCounter_; TH1 *histogram_lep1_pt_; TH1 *histogram_lep2_pt_; TH1 *histogram_lep3_pt_; TH1 *histogram_lep4_pt_; TH1 *histogram_lep1_conePt_; TH1 *histogram_lep2_conePt_; TH1 *histogram_lep3_conePt_; TH1 *histogram_lep4_conePt_; TH1 *histogram_lep1_eta_; TH1 *histogram_lep2_eta_; TH1 *histogram_lep3_eta_; TH1 *histogram_lep4_eta_; TH1 *histogram_lep1_phi_; TH1 *histogram_lep2_phi_; TH1 *histogram_lep3_phi_; TH1 *histogram_lep4_phi_; TH1 *histogram_maxPtSum_pair1_pt_; TH1 *histogram_maxPtSum_pair1_eta_; TH1 *histogram_maxPtSum_pair1_phi_; TH1 *histogram_maxPtSum_pair1_deltaEtaLep1_; TH1 *histogram_maxPtSum_pair1_deltaPhiLep1_; TH1 *histogram_maxPtSum_pair1_deltaEta_; TH1 *histogram_maxPtSum_pair1_deltaPhi_; TH1 *histogram_maxPtSum_pair1_deltaR_; TH1 *histogram_maxPtSum_pair1_deltaPt_; TH1 *histogram_maxPtSum_pair1_m_; TH1 *histogram_maxPtSum_pair2_pt_; TH1 *histogram_maxPtSum_pair2_eta_; TH1 *histogram_maxPtSum_pair2_phi_; TH1 *histogram_maxPtSum_pair2_deltaEtaLep1_; TH1 *histogram_maxPtSum_pair2_deltaPhiLep1_; TH1 *histogram_maxPtSum_pair2_deltaEta_; TH1 *histogram_maxPtSum_pair2_deltaPhi_; TH1 *histogram_maxPtSum_pair2_deltaR_; TH1 *histogram_maxPtSum_pair2_deltaPt_; TH1 *histogram_maxPtSum_pair2_m_; TH1 *histogram_maxSubleadPt_pair1_pt_; TH1 *histogram_maxSubleadPt_pair1_eta_; TH1 *histogram_maxSubleadPt_pair1_phi_; TH1 *histogram_maxSubleadPt_pair1_deltaEtaLep1_; TH1 *histogram_maxSubleadPt_pair1_deltaPhiLep1_; TH1 *histogram_maxSubleadPt_pair1_deltaEta_; TH1 *histogram_maxSubleadPt_pair1_deltaPhi_; TH1 *histogram_maxSubleadPt_pair1_deltaR_; TH1 *histogram_maxSubleadPt_pair1_deltaPt_; TH1 *histogram_maxSubleadPt_pair1_m_; TH1 *histogram_maxSubleadPt_pair2_pt_; TH1 *histogram_maxSubleadPt_pair2_eta_; TH1 *histogram_maxSubleadPt_pair2_phi_; TH1 *histogram_maxSubleadPt_pair2_deltaEtaLep1_; TH1 *histogram_maxSubleadPt_pair2_deltaPhiLep1_; TH1 *histogram_maxSubleadPt_pair2_deltaEta_; TH1 *histogram_maxSubleadPt_pair2_deltaPhi_; TH1 *histogram_maxSubleadPt_pair2_deltaR_; TH1 *histogram_maxSubleadPt_pair2_deltaPt_; TH1 *histogram_maxSubleadPt_pair2_m_; TH1 *histogram_minDeltaRSum_pair1_pt_; TH1 *histogram_minDeltaRSum_pair1_eta_; TH1 *histogram_minDeltaRSum_pair1_phi_; TH1 *histogram_minDeltaRSum_pair1_deltaEtaLep1_; TH1 *histogram_minDeltaRSum_pair1_deltaPhiLep1_; TH1 *histogram_minDeltaRSum_pair1_deltaEta_; TH1 *histogram_minDeltaRSum_pair1_deltaPhi_; TH1 *histogram_minDeltaRSum_pair1_deltaR_; TH1 *histogram_minDeltaRSum_pair1_deltaPt_; TH1 *histogram_minDeltaRSum_pair1_m_; TH1 *histogram_minDeltaRSum_pair2_pt_; TH1 *histogram_minDeltaRSum_pair2_eta_; TH1 *histogram_minDeltaRSum_pair2_phi_; TH1 *histogram_minDeltaRSum_pair2_deltaEtaLep1_; TH1 *histogram_minDeltaRSum_pair2_deltaPhiLep1_; TH1 *histogram_minDeltaRSum_pair2_deltaEta_; TH1 *histogram_minDeltaRSum_pair2_deltaPhi_; TH1 *histogram_minDeltaRSum_pair2_deltaR_; TH1 *histogram_minDeltaRSum_pair2_deltaPt_; TH1 *histogram_minDeltaRSum_pair2_m_; TH1 *histogram_minSubclosestDeltaR_pair1_pt_; TH1 *histogram_minSubclosestDeltaR_pair1_eta_; TH1 *histogram_minSubclosestDeltaR_pair1_phi_; TH1 *histogram_minSubclosestDeltaR_pair1_deltaEtaLep1_; TH1 *histogram_minSubclosestDeltaR_pair1_deltaPhiLep1_; TH1 *histogram_minSubclosestDeltaR_pair1_deltaEta_; TH1 *histogram_minSubclosestDeltaR_pair1_deltaPhi_; TH1 *histogram_minSubclosestDeltaR_pair1_deltaR_; TH1 *histogram_minSubclosestDeltaR_pair1_deltaPt_; TH1 *histogram_minSubclosestDeltaR_pair1_m_; TH1 *histogram_minSubclosestDeltaR_pair2_pt_; TH1 *histogram_minSubclosestDeltaR_pair2_eta_; TH1 *histogram_minSubclosestDeltaR_pair2_phi_; TH1 *histogram_minSubclosestDeltaR_pair2_deltaEtaLep1_; TH1 *histogram_minSubclosestDeltaR_pair2_deltaPhiLep1_; TH1 *histogram_minSubclosestDeltaR_pair2_deltaEta_; TH1 *histogram_minSubclosestDeltaR_pair2_deltaPhi_; TH1 *histogram_minSubclosestDeltaR_pair2_deltaR_; TH1 *histogram_minSubclosestDeltaR_pair2_deltaPt_; TH1 *histogram_minSubclosestDeltaR_pair2_m_; TH1 *histogram_MET_; TH1 *histogram_METPhi_; TH1 *histogram_METDeltaPhiLep1_; TH1 *histogram_MET_LD_; TH1 *histogram_HTmiss_; TH1 *histogram_lep1_isElectron_; TH1 *histogram_lep1_charge_; TH1 *histogram_lep2_isElectron_; TH1 *histogram_lep2_charge_; TH1 *histogram_lep3_isElectron_; TH1 *histogram_lep3_charge_; TH1 *histogram_lep4_isElectron_; TH1 *histogram_lep4_charge_; TH1 *histogram_leptonChargeSum_; TH1 *histogram_electronChargeSum_; TH1 *histogram_muonChargeSum_; TH1 *histogram_nSFOS_; }; #endif
#pragma once #include <utility> #include "../type_list/type_list.hpp" // in general, assume a functor template<typename Function> struct function_signature : function_signature< decltype(&Function::operator()) > {}; // match function pointers template<typename Result, typename... Args> struct function_signature<Result(*)(Args...)> { typedef type_list<Result,Args...> type; }; // match member functions template<typename Result, typename Class, typename... Args> struct function_signature<Result(Class::*)(Args...)> { typedef type_list<Result,Args...> type; }; template<typename Function> struct function_result : type_list_head< typename function_signature<Function>::type > {}; template<typename Function> struct function_parameters : type_list_tail< typename function_signature<Function>::type > {}; template<unsigned int i, typename Function> struct function_parameter : type_list_element< i, typename function_parameters<Function>::type > {}; namespace detail { namespace function_traits_detail { struct bar {}; struct test1 { int operator()(bar); }; static_assert(std::is_same<function_signature<test1>::type, type_list<int,bar>>::value, "problem with test1"); struct test2 { int operator()(int, bar); }; static_assert(std::is_same<function_result<test2>::type, int>::value, "problem with test2"); static_assert(std::is_same<function_parameters<test2>::type, type_list<int,bar>>::value, "problem with test2"); struct test3 { int operator()(); }; static_assert(std::is_same<function_parameters<test3>::type, type_list<>>::value, "problem with test3"); struct test4 { void operator()(int, float, double, char); }; static_assert(std::is_same<function_parameter<0,test4>::type, int>::value, "problem with test4"); static_assert(std::is_same<function_parameter<1,test4>::type, float>::value, "problem with test4"); static_assert(std::is_same<function_parameter<2,test4>::type, double>::value, "problem with test4"); static_assert(std::is_same<function_parameter<3,test4>::type, char>::value, "problem with test4"); } // end function_traits_detail } // end detail
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2009 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #ifdef MEDIA_JIL_PLAYER_SUPPORT #include "modules/dom/src/domjil/domjilaudioplayer.h" DOM_JILAudioPlayer::DOM_JILAudioPlayer() { } DOM_JILAudioPlayer::~DOM_JILAudioPlayer() { } OP_STATUS DOM_JILAudioPlayer::Make(DOM_JILAudioPlayer*& jil_audio_player, DOM_Runtime* runtime) { jil_audio_player = OP_NEW(DOM_JILAudioPlayer, ()); return DOMSetObjectRuntime(jil_audio_player, runtime, runtime->GetPrototype(DOM_Runtime::JIL_AUDIOPLAYER_PROTOTYPE), "AudioPlayer"); } /* static */ int DOM_JILAudioPlayer::open(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(jilaudioplayer, DOM_TYPE_JIL_AUDIOPLAYER, DOM_JILAudioPlayer); return jilaudioplayer->Open(argv, argc, return_value, origining_runtime); } /* static */int DOM_JILAudioPlayer::play(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(jilaudioplayer, DOM_TYPE_JIL_AUDIOPLAYER, DOM_JILAudioPlayer); DOM_CHECK_ARGUMENTS_JIL("n"); return jilaudioplayer->Play(argv, argc, return_value, origining_runtime); } /* static */ int DOM_JILAudioPlayer::stop(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(jilaudioplayer, DOM_TYPE_JIL_AUDIOPLAYER, DOM_JILAudioPlayer); return jilaudioplayer->Stop(argv, argc, return_value, origining_runtime); } /* static */ int DOM_JILAudioPlayer::pause(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(jilaudioplayer, DOM_TYPE_JIL_AUDIOPLAYER, DOM_JILAudioPlayer); return jilaudioplayer->Pause(argv, argc, return_value, origining_runtime); } /* static */ int DOM_JILAudioPlayer::resume(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(jilaudioplayer, DOM_TYPE_JIL_AUDIOPLAYER, DOM_JILAudioPlayer); return jilaudioplayer->Resume(argv, argc, return_value, origining_runtime); } #ifdef SELFTEST /* static */ int DOM_JILAudioPlayer::getState(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(jilaudioplayer, DOM_TYPE_JIL_AUDIOPLAYER, DOM_JILAudioPlayer); return jilaudioplayer->GetState(argv, argc, return_value, origining_runtime); } #endif // SELFTEST #include "modules/dom/src/domglobaldata.h" DOM_FUNCTIONS_START(DOM_JILAudioPlayer) DOM_FUNCTIONS_WITH_SECURITY_RULE_A1(DOM_JILAudioPlayer, DOM_JILAudioPlayer::open, "open", "s-", "AudioPlayer.open", 0) DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILAudioPlayer, DOM_JILAudioPlayer::play, "play", "n-", "AudioPlayer.play") DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILAudioPlayer, DOM_JILAudioPlayer::stop, "stop", "", "AudioPlayer.stop") DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILAudioPlayer, DOM_JILAudioPlayer::pause, "pause", "", "AudioPlayer.pause") DOM_FUNCTIONS_WITH_SECURITY_RULE(DOM_JILAudioPlayer, DOM_JILAudioPlayer::resume, "resume", "", "AudioPlayer.resume") #ifdef SELFTEST DOM_FUNCTIONS_FUNCTION(DOM_JILAudioPlayer, DOM_JILAudioPlayer::getState, "getState", "") #endif // SELFTEST DOM_FUNCTIONS_END(DOM_JILAudioPlayer) #endif // MEDIA_JIL_PLAYER_SUPPORT
#pragma once // AnalySet 对话框 class AnalySet : public CDialog { DECLARE_DYNAMIC(AnalySet) public: AnalySet(CWnd* pParent = NULL); // 标准构造函数 virtual ~AnalySet(); // 对话框数据 enum { IDD = IDD_ANALYSET }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: // 开始时间 CTime begin; // 结束时间 CTime end; // 文件夹路径 CString folder; // 选中的时次 int checked_times; afx_msg void OnBnClickedOk(); afx_msg void OnBnClickedFloderset(); };
#ifndef _U_KEY_TRANSLATE_H_ #define _U_KEY_TRANSLATE_H_ #define kMaskOutCommand 0xFE00 // we need the modifiers without the command key #define kMaskOutOption 0xF700 // we need the modifiers without the option key #define kMaskVirtualKey 0x0000FF00 // get virtual key from event message for // KeyTrans #define kMaskASCII1 0x00FF0000 // get the key out of the ASCII1 byte #define kMaskASCII2 0x000000FF // get the key out of the ASCII2 byte #if defined(VER_BETA) //#define DEBUG_UNI_KEYSTROKES #endif #ifdef DEBUG_UNI_KEYSTROKES # warning "THIS BUILD CONTAINS KEYBOARD DEBUG CODE!" #endif class UKeyTranslate { public: static OP_STATUS GetUnicharFromVirtualKey(UInt32 virtualKeyCode, uni_char &outUniChar, UInt8 modifierKeyState = 0); }; #endif // _U_KEY_TRANSLATE_H_
#pragma once #include "IComponent.h" #include "Core\ComponentRegister.h" #include "Behavior\IBehavior.h" namespace Hourglass { class BehaviorTree : public IComponent { public: virtual void LoadFromXML( tinyxml2::XMLElement* data ); void SetRoot( IBehavior* root ); void DestroyRoot(); virtual void Update(); virtual void Shutdown(); virtual int GetTypeID() const { return s_TypeID; } /** * Make a copy of this component */ virtual IComponent* MakeCopyDerived() const; static uint32_t s_TypeID; private: IBehavior* m_Root = nullptr; uint32_t m_FirstTick : 1; }; }
#pragma once #include "Object.h" #include "Button.h" class HUD { private: Object hudBackground; Object hudCherry; Object hudStrawberry; Object hudOrange; Object* hudLives; std::string* hudScoreID; Rect* hudScoreRect; std::string hudXID; Rect hudXRect[3]; std::string hudStrawberryID; Rect hudStrawberryRect; std::string hudCherryID; Rect hudCherryRect; std::string hudOrangeID; Rect hudOrangeRect; std::string hudSpaceStartID1; Rect hudSpaceStartRect1; std::string hudSpaceStartID2; Rect hudSpaceStartRect2; std::string hudSpacePauseID1; Rect hudSpacePauseRect1; std::string hudSpacePauseID2; Rect hudSpacePauseRect2; std::string hudSpacePauseID3; Rect hudSpacePauseRect3; Object hudTransparent; public: Button hudSound; int strawberryCount; int cherryCount; int orangeCount; HUD(); void Update(); void UpdateScoreInfo(int _playerScore); void DisableStart(); void EnablePause(); void DisablePause(); void Draw(int _lives); ~HUD(); };
#pragma once #include <QWidget> #include <QHBoxLayout> #include <QLabel> #include <vector> #include <utility> #include <QTimer> #include <QtWinExtras> #include <QDebug> #include "raw_input.h" #include "mouse-widget.h" class DeviceVisualizer : public QWidget { Q_OBJECT public: devinfo_vec devices; std::vector<DeviceWidget *> label_ptrs; QHBoxLayout * layout; DeviceWidget * mouse, * kb; DeviceVisualizer():mouse(nullptr),kb(nullptr) { resize(800, 200); show(); if (QtWin::isCompositionEnabled()) { QtWin::extendFrameIntoClientArea(this, -1, -1, -1, -1); setAttribute(Qt::WA_TranslucentBackground, true); setAttribute(Qt::WA_NoSystemBackground, false); setStyleSheet("DeviceVisualizer { background: transparent; }"); } layout = new QHBoxLayout(this); this->setLayout(layout); } public slots: void onKeyboardEvent(DevHandle handle,unsigned short, bool pressed) { KeyboardWidget * wgt = nullptr; if(handle == nullptr) { wgt = dynamic_cast<KeyboardWidget*>(mouse); } else { for(DeviceWidget * i : label_ptrs) { if(i->devhandle() == handle) wgt = dynamic_cast<KeyboardWidget*>(i); } } if(!wgt) { qDebug() << "RECEIVED INPUT FOR UNKNOWN DEVICE"; return; } if(!pressed) wgt->incClick(); } void onMouseEvent(DevHandle handle, const ButtonStates & bs,WheelState ws) { MouseWidget * wgt = nullptr; if(handle == nullptr) { wgt = dynamic_cast<MouseWidget*>(mouse); } else { for(DeviceWidget * i : label_ptrs) { if(i->devhandle() == handle) wgt = dynamic_cast<MouseWidget*>(i); } } if(!wgt) { qDebug() << "RECEIVED INPUT FOR UNKNOWN DEVICE"; return; } wgt->setWheelState(ws); wgt->setButtonStates(bs); wgt->update(); } void updateDeviceList(const devinfo_vec & list) { qDebug() << "UPDATE DEV LIST WGT"; devices = list; setUpdatesEnabled(false); if(mouse)delete mouse; if(kb)delete kb; for(auto * lbl : label_ptrs) { delete lbl; }; label_ptrs.clear(); label_ptrs.reserve(list.size() + 1); mouse = new MouseWidget(this); layout->addWidget(mouse); mouse->setName("SENDINPUT Mouse"); mouse->setHandle(nullptr); kb = new KeyboardWidget(this); layout->addWidget(kb); kb->setName("SENDINPUT Keyboard"); kb->setHandle(nullptr); for(devinfo & dev : devices) { if(dev.rimType == RimDevType::RimMouse) { DeviceWidget * label = new MouseWidget(this); label_ptrs.push_back(label); label->setName(dev.name); label->setHandle( dev.handle ); layout->addWidget(label); } else if(dev.rimType == RimDevType::RimKeyboard) { DeviceWidget * label = new KeyboardWidget(this); label_ptrs.push_back(label); label->setName(dev.name); label->setHandle( dev.handle ); layout->addWidget(label); } } setUpdatesEnabled(true); } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef TEXT_EDIT_ELEMENT_OF_INTEREST_H #define TEXT_EDIT_ELEMENT_OF_INTEREST_H #include "modules/widgets/finger_touch/complexform_element_of_interest.h" class HTML_Element; class TextEditElementOfInterest : public ComplexFormElementOfInterest { public: TextEditElementOfInterest(HTML_Element* html_element) : ComplexFormElementOfInterest(html_element) {} protected: // Implementing OpWidgetListener: virtual void OnChange(OpWidget *widget, BOOL changed_by_mouse); virtual void OnChangeWhenLostFocus(OpWidget *widget); private: virtual OP_STATUS MakeClone(BOOL expanded); // Implementing ElementOfInterest virtual BOOL DoIsSuitable(unsigned int max_elm_size); }; #endif // TEXT_EDIT_ELEMENT_OF_INTEREST_H
#include <iostream> #include <cstdlib> #include <limits> using namespace std; const int N=6; // wierzcho³ki -2 int inf = 99999; void wypelnij(int t[N][N]) { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { t[i][j]=inf; } t[i][i]=0; } } void print(int t[N][N]) { cout<<" "; for(int i=1;i<N-1;i++) { cout<<i<<" "; } cout<<endl; cout<<"--------------------------"<<endl; for(int i=1;i<N-1;i++) { cout<<i<<" |"; for(int j=1;j<N-1;j++) { if(t[i][j]==inf) { cout<<" "<<"oo"; continue; } cout<<" "<<t[i][j]; } cout<<endl; } } void floyd(int t[N][N]) { for(int k=1;k<N;k++) { for(int i=1;i<N;i++) { for(int j=1;j<N;j++) { t[i][j]=min(t[i][j],t[i][k]+t[k][j]); } } } } int main() { int t[N][N]; wypelnij(t); t[1][3]=-2; t[2][1]=4; t[2][3]=3; t[3][4]=2; t[4][2]=-1; floyd(t); print(t); }
#include <unistd.h> #include <cstdio> #include <cstdlib> #include <cstring> #include "librtf.h" int main( int argc, char** argv ) { // Set RTF document font and color table char font_list[] = "Times New Roman;Arial;"; char color_list[] = "0;0;0;255;0;0;192;192;192;255;255;255"; char fname[] = "Sample.rtf"; RTF_DOCUMENT_FORMAT docfmt = { RTF_DOCUMENTVIEWKIND_PAGE, 100, 12240, 15840, 180, 180, 144, 144, false, 0, true }; // Open RTF file printf( "Creating %s ... ", fname ); fflush( stdout ); if ( librtf::open( fname, font_list, color_list, &docfmt ) == RTF_ERROR ) { printf( "Failed.\n" ); return 0; } printf( "Ok.\n" ); librtf::write_documentformat(); // Write paragraph text librtf::start_paragraph( "First section:", false ); // Format paragraph RTF_PARAGRAPH_FORMAT* pf = librtf::get_paragraphformat(); pf->paragraphTabs = true; pf->TABS.tabKind = RTF_PARAGRAPHTABKIND_RIGHT; pf->TABS.tabLead = RTF_PARAGRAPHTABLEAD_DOT; pf->TABS.tabPosition = 7200; // Write paragraph text librtf::start_paragraph( "This is new paragraph text", true ); // Write paragraph tabbed text pf->paragraphTabs = false; pf->tabbedText = true; librtf::start_paragraph( "Some tabbed text", false ); pf->tabbedText = false; // Format paragraph pf->firstLineIndent = 360; // Write paragraph text pf->paragraphTabs = true; librtf::start_paragraph( "This is another paragraph text", true ); // Write paragraph tabbed text pf->paragraphTabs = false; pf->tabbedText = true; librtf::start_paragraph( "Some more tabbed text", false ); pf->tabbedText = false; // Format paragraph pf->firstLineIndent = 0; pf->CHARACTER.italicCharacter = true; // Write paragraph text librtf::start_paragraph( "This is new paragraph text", true ); // Create new section librtf::start_section(); // Format paragraph pf->spaceBefore = 120; pf->paragraphAligment = RTF_PARAGRAPHALIGN_CENTER; pf->CHARACTER.italicCharacter = false; pf->CHARACTER.foregroundColor = 1; // Write paragraph text librtf::start_paragraph( "Second section:", false ); // Format paragraph pf->spaceBefore = 0; pf->CHARACTER.foregroundColor = 0; // Write paragraph text librtf::start_paragraph( "Plain paragraph text", true ); // Create new section librtf::start_section(); // Format paragraph pf->spaceBefore = 120; pf->paragraphAligment = RTF_PARAGRAPHALIGN_RIGHT; pf->CHARACTER.underlineCharacter = 17; // Write paragraph text librtf::start_paragraph( "Third section:", false ); // Format paragraph pf->spaceBefore = 0; pf->CHARACTER.boldCharacter = true; pf->CHARACTER.subscriptCharacter = true; pf->CHARACTER.underlineCharacter = 0; // Write paragraph text librtf::start_paragraph( "Plain paragraph text", true ); // Create new section librtf::start_section(); // Format paragraph pf->spaceBefore = 120; pf->paragraphAligment = RTF_PARAGRAPHALIGN_LEFT; pf->paragraphBorders = true; pf->BORDERS.borderKind = RTF_PARAGRAPHBORDERKIND_BOX; pf->BORDERS.borderType = RTF_PARAGRAPHBORDERTYPE_ENGRAVE; pf->BORDERS.borderWidth = 0; pf->BORDERS.borderColor = 0; pf->BORDERS.borderSpace = 120; pf->CHARACTER.boldCharacter = false; pf->CHARACTER.subscriptCharacter = false; pf->CHARACTER.superscriptCharacter = true; // Write paragraph text librtf::start_paragraph( "Fourth section:", false ); // Create new section librtf::start_section(); // Format paragraph pf->spaceBefore = 120; pf->paragraphBorders = false; pf->paragraphAligment = RTF_PARAGRAPHALIGN_LEFT; pf->paragraphShading = true; pf->SHADING.shadingIntensity = 0; pf->SHADING.shadingType = RTF_PARAGRAPHSHADINGTYPE_FILL; pf->SHADING.shadingFillColor = 0; pf->SHADING.shadingBkColor = 2; pf->CHARACTER.fontNumber = 1; pf->CHARACTER.fontSize = 20; pf->CHARACTER.superscriptCharacter = false; // Write paragraph text librtf::start_paragraph( "Fifth section:", false ); // Format paragraph pf->paragraphShading = false; // Write paragraph text (empty paragraphs) librtf::start_paragraph( " ", true ); librtf::start_paragraph( " ", true ); // Format section RTF_SECTION_FORMAT* sf = librtf::get_sectionformat(); sf->cols = true; sf->colsDistance = 720; sf->colsLineBetween = true; sf->colsNumber = 2; // Create new section librtf::start_section(); // Format paragraph pf->paragraphShading = false; pf->spaceBefore = 0; // Write paragraph text librtf::start_paragraph( "Column text is here as an example of what this library can do...", false ); // Format paragraph pf->paragraphBreak = RTF_PARAGRAPHBREAK_COLUMN; // Write paragraph text librtf::start_paragraph( "Also, it can be very powerful tool in right hands...", false ); // Format section sf->cols = false; // Create new section librtf::start_section(); // Format paragraph pf->paragraphAligment = RTF_PARAGRAPHALIGN_CENTER; pf->paragraphBreak = 0; pf->spaceBefore = 360; pf->spaceAfter = 360; // Load image (*.bmp, *.jpg, *.gif) librtf::load_image("Picture.jpg", 50, 50); // Format section sf->cols = true; sf->colsDistance = 360; sf->colsLineBetween = false; sf->colsNumber = 2; // Create new section librtf::start_section(); // Format paragraph pf->paragraphNums = true; pf->paragraphAligment = RTF_PARAGRAPHALIGN_CENTER; pf->spaceBefore = 0; pf->spaceAfter = 0; pf->NUMS.numsLevel = 11; pf->NUMS.numsSpace = 360; pf->NUMS.numsChar = char(0x95); // Write paragraph text (bulleted) librtf::start_paragraph( "Bulleted text1", false ); librtf::start_paragraph( "Bulleted text2", true ); librtf::start_paragraph( "Bulleted text3", true ); librtf::start_paragraph( "Bulleted text4", true ); librtf::start_paragraph( "Bulleted text5", true ); // Format paragraph pf->paragraphBreak = 2; // Write paragraph text librtf::start_paragraph( " ", true ); // Format paragraph pf->paragraphBreak = 0; pf->NUMS.numsLevel = 3; librtf::start_paragraph( "Numbered text1", false ); librtf::start_paragraph( "Numbered text2", true ); librtf::start_paragraph( "Numbered text3", true ); librtf::start_paragraph( "Numbered text4", true ); librtf::start_paragraph( "Numbered text5", true ); // Format paragraph pf->paragraphBreak = 0; pf->paragraphNums = false; // Write paragraph text librtf::start_paragraph( " ", true ); // Format paragraph pf->spaceBefore = 360; pf->spaceAfter = 360; // Write paragraph text librtf::start_paragraph( " ", true ); // Format section sf->cols = false; // Create new section librtf::start_section(); // Format paragraph pf->spaceBefore = 0; pf->spaceAfter = 0; // Format table row RTF_TABLEROW_FORMAT* rf = librtf::get_tablerowformat(); rf->rowAligment = RTF_ROWTEXTALIGN_CENTER; rf->marginTop = 120; rf->marginBottom = 120; rf->marginLeft = 120; rf->marginRight = 120; // Start table row librtf::start_tablerow(); // Format table cell RTF_TABLECELL_FORMAT* cf = librtf::get_tablecellformat(); cf->textVerticalAligment = RTF_CELLTEXTALIGN_CENTER; cf->textDirection = RTF_CELLTEXTDIRECTION_LRTB; cf->borderBottom.border = true; cf->borderBottom.BORDERS.borderType = RTF_PARAGRAPHBORDERTYPE_STHICK; cf->borderBottom.BORDERS.borderWidth = 5; cf->borderLeft.border = true; cf->borderLeft.BORDERS.borderType = RTF_PARAGRAPHBORDERTYPE_STHICK; cf->borderLeft.BORDERS.borderWidth = 5; cf->borderRight.border = true; cf->borderRight.BORDERS.borderType = RTF_PARAGRAPHBORDERTYPE_STHICK; cf->borderRight.BORDERS.borderWidth = 30; cf->borderTop.border = true; cf->borderTop.BORDERS.borderType = RTF_PARAGRAPHBORDERTYPE_STHICK; cf->borderTop.BORDERS.borderWidth = 5; cf->cellShading = true; cf->SHADING.shadingType = RTF_CELLSHADINGTYPE_FILL; cf->SHADING.shadingBkColor = 3; // Start table cell librtf::start_tablecell(2000); // Format table cell cf->borderLeft.BORDERS.borderWidth = 30; cf->borderRight.BORDERS.borderWidth = 5; // Start table cell cf->SHADING.shadingBkColor = 2; librtf::start_tablecell(4000); // Format paragraph pf->tableText = true; pf->paragraphAligment = RTF_PARAGRAPHALIGN_JUSTIFY; // Write paragraph text librtf::start_paragraph( "This is table cell text...", false ); librtf::start_paragraph( "These paragraphs are enclosed in table cell", true ); // End table cell librtf::end_tablecell(); // Write paragraph text pf->CHARACTER.boldCharacter = true; librtf::start_paragraph( "This text is in another cell...", false ); librtf::start_paragraph( "You must define correct cell right margin in order to see the text", true ); pf->CHARACTER.boldCharacter = false; // End table cell librtf::end_tablecell(); // End table row librtf::end_tablerow(); // Start table row librtf::start_tablerow(); // Format table cell cf->borderLeft.BORDERS.borderWidth = 5; cf->SHADING.shadingBkColor = 3; // Start table cell librtf::start_tablecell(4000); cf->cellShading = false; // Write paragraph text librtf::start_paragraph( "This text is in another row, and these cells are merged...", false ); pf->tableText = false; // End table cell librtf::end_tablecell(); // End table row librtf::end_tablerow(); // Close RTF file printf( "Closing file ... " ); if ( librtf::close() == RTF_SUCCESS ) { printf( "Ok.\n" ); } else { printf( "Error.\n" ); } return 0; }
#pragma once #include "ofMain.h" #include "ofxProfiler.h" #include "ofxSquash.h" class ofApp : public ofBaseApp{ public: void setup(); };
/** ****************************************************************************** * Copyright (c) 2019 - ~, SCUT-RobotLab Development Team * @file dr16.h * @author Zelong.Xu 8762322@qq.com * @brief Code for DJI-DR16 driver in embedded software system. ****************************************************************************** * @attention * * if you had modified this file, please make sure your code does not have any * bugs, update the version Number, write dowm your name and the date. The most * important thing is make sure the users will have clear and definite under- * standing through your new brief. * * <h2><center>&copy; Copyright (c) 2019 - ~, SCUT-RobotLab Development Team. * All rights reserved.</center></h2> ****************************************************************************** */ #ifndef _DR16_H_ #define _DR16_H_ #ifdef __cplusplus /* Includes ------------------------------------------------------------------*/ #include <stdint.h> #include <stddef.h> /* Private macros ------------------------------------------------------------*/ /* 键位宏定义 */ #define _W 0 #define _S 1 #define _A 2 #define _D 3 #define _SHIFT 4 #define _CTRL 5 #define _Q 6 #define _E 7 #define _R 8 #define _F 9 #define _G 10 #define _Z 11 #define _X 12 #define _C 13 #define _V 14 #define _B 15 #define _Mouse_L 16 #define _Mouse_R 17 /* Private type --------------------------------------------------------------*/ /** @brief DR16数据包内容 */ #pragma pack(1) struct DR16_DataPack_Typedef { uint64_t ch0:11; uint64_t ch1:11; uint64_t ch2:11; uint64_t ch3:11; uint64_t s2:2; uint64_t s1:2; int64_t x:16; int64_t y:16; int64_t z:16; uint64_t press_l:8; uint64_t press_r:8; uint64_t key:16; }; #pragma pack() /** @brief 手柄上面两挡位开关状态 */ enum SW_Status_Typedef { NONE = 0, UP = 1, MID = 3, DOWN = 2, }; /** @brief 按键类型定义 */ struct Key_Typedef { bool isPressed; /*<! 是否按下 */ bool isTriggered; /*<! 是否触发过函数,用来执行点击事件 */ }; /** @brief 连接状态 */ #ifndef __LinkageStatus_DEFINED #define __LinkageStatus_DEFINED enum LinkageStatus_Typedef { Connection_Lost = 0U, Connection_Established, }; #endif typedef void(*CLICK_EXCE)(void); /*<! 单击执行函数 */ /* Exported macros -----------------------------------------------------------*/ #define Ignore_Limit 0.05 /*<! 线性死区,手柄或鼠标的归一化后的绝对值小于此值时自动视为0 */ /* Exported types ------------------------------------------------------------*/ /* DR16类型 */ class DR16_Classdef { private: LinkageStatus_Typedef Status; /*<! 连接状态 */ uint8_t detecting_flag; /*<! 检测操作标志位*/ uint32_t last_check_time; /*<! 上一次在线检测时间*/ DR16_DataPack_Typedef DataPack; /*<! 数据包*/ float RX_Norm,RY_Norm,LX_Norm,LY_Norm,MouseX_Norm,MouseY_Norm,MouseZ_Norm; /*<! 两个摇杆四个方向与鼠标三个方向速度归一化后的值*/ Key_Typedef Key[18]; /*<! 16个键的相关信息*/ CLICK_EXCE Click_Fun[18]; /*<! 单击执行函数 */ float MouseCoefficient; /*<! 鼠标动作乘的系数*/ void Key_Process(void); /*<! 按键处理*/ public: /* Exported function declarations --------------------------------------------*/ DR16_Classdef(); void DataCapture(DR16_DataPack_Typedef* captureData); uint64_t GetCh0(void); uint64_t GetCh1(void); uint64_t GetCh2(void); uint64_t GetCh3(void); SW_Status_Typedef GetS2(void); SW_Status_Typedef GetS1(void); int64_t GetMouseX(void); int64_t GetMouseY(void); int64_t GetMouseZ(void); uint64_t GetPress_L(void); uint64_t GetPress_R(void); uint64_t Getkey(void); /*归一化后的通道0123、鼠标XYZ值*/ float Get_RX_Norm(void); float Get_RY_Norm(void); float Get_LX_Norm(void); float Get_LY_Norm(void); float Get_MouseX_Norm(void); float Get_MouseY_Norm(void); float Get_MouseZ_Norm(void); /*用于判断某个按键是否按下,按下之后的回调函数*/ bool IsKeyPress(int _key); void Register_Click_Fun(int _Key, CLICK_EXCE Fun_Ptr); void Exce_Click_Fun(); /*连接状态相关操作*/ void Check_Link(uint32_t current_check_time); void SetStatus(LinkageStatus_Typedef para_status); LinkageStatus_Typedef GetStatus(void); }; #endif #endif /************************ COPYRIGHT(C) SCUT-ROBOTLAB **************************/
// Count inversions // Multiset O(n^2) [distance is O(N)] // Balanced BST O(NlogN) // Mergesort O(NlogN) class Solution { public: void merge(vector<int> &left, vector<int> &right, vector<int> &nums){ int i = 0, j = 0, k = 0; while(i < left.size() || j < right.size()){ if(i == left.size()){ nums[k] = right[j]; j++; } else if(j == right.size()){ nums[k] = left[i]; i++; } else if(left[i] < right[j]){ nums[k] = left[i]; i++; } else{ nums[k] = right[j]; j++; } k++; } } int solve(vector<int> &nums){ int n = nums.size(); if(!n || n == 1) return 0; int mid = (n-1)/2; int cnt = 0; vector<int> left, right; for(int i = 0; i <= mid; i++){ left.push_back(nums[i]); if(mid+1+i < n) right.push_back(nums[mid+i+1]); } cnt += solve(left); cnt += solve(right); int i = 0, j = 0; while(i < left.size()){ while(j < right.size() && 1LL*2*right[j] < 1LL * left[i]){ j++; } cnt += j; i++; } merge(left,right,nums); return cnt ; } int reversePairs(vector<int>& nums) { return solve(nums); } };
/* 191020 LG codepro - [19년도_2차] 안테나설치 - 조건 나열해서 식 완성하기! -> 빠트린 조건 확인 */ #include <iostream> using namespace std; int arr[25];//안테나 커버리지 값을 저장할 배열 int N;//설치할 안테나의 갯수 //작성할 함수 int Antenna_Count(double p1, double p2) { int i, cnt=0; double sum=0; double upper_len,len; len = (p2>p1) ? p2 - p1 : p1-p2; //cout<<" len : "<<len<<endl; upper_len = len; for(i = 0; i < N; i++) { sum += (double)arr[i]; } if((upper_len > sum + 0.3) || upper_len==0 || (p1<0 && p2<0) || (p1>0&&p2>0) ) return -1; sum = 0; for(i = 0; i < N;i++) { if( sum+0.3 < upper_len ) { sum +=(double)arr[i]; //cout<<" sum : "<<(double)sum + 0.3 <<" upper_len : "<<upper_len<<endl; cnt++; } else { break; } } //cout<<" cnt : "<<cnt<<endl; return cnt; } int main(void) { int sol; double point_1, point_2; //입력받는부분 cin >> N; for (int i = 0; i < N; i++){ cin >> arr[i]; } cin >> point_1 >> point_2; //설치갯수 판단 sol = Antenna_Count(point_1, point_2); if (sol == -1) cout << "Impossible" << endl; else cout << sol << endl; return 0; }
void setup() { Serial.begin(115200); } char parse1 = char(0x0a); void loop() { String text = "absdcecrvd dfasfegrg fdfsdfdsfdsgd"; String arr_A[4]; int parseArr[3]; int text_length = text.length(); Split(text, " "); Serial.print(); } static Split(String sData, char cSeparator) { int nCount = 0; int nGetIndex = 0 ; //임시저장 String sTemp = ""; //원본 복사 String sCopy = sData; while(true) { //구분자 찾기 nGetIndex = sCopy.indexOf(cSeparator); //리턴된 인덱스가 있나? if(-1 != nGetIndex) { //있다. //데이터 넣고 sTemp = sCopy.substring(0, nGetIndex); Serial.println( sTemp ); //뺀 데이터 만큼 잘라낸다. sCopy = sCopy.substring(nGetIndex + 1); } else { //없으면 마무리 한다. Serial.println( sCopy ); break; } //다음 문자로~ ++nCount; } }
#include <stdio.h> #include <iostream> #include <math.h> #include <algorithm> #include <memory.h> #include <set> #include <map> #include <queue> #include <deque> #include <string> #include <string.h> #include <vector> typedef long long ll; typedef long double ld; typedef unsigned long long ull; const ld PI = acos(-1.); using namespace std; const int N = 555666; struct cell { ll l, r; int id; cell(ll al = 0, ll ar = 0, int aid = 0) : l(al) , r(ar) , id(aid) {} bool operator<(const cell& A) const { return l < A.l; } } evs[N]; int ke; int n, m; int p[N]; int main() { freopen("intelligent.in", "r", stdin); freopen("intelligent.out", "w", stdout); scanf("%d", &n); while (n) { ke = 0; for (int i = 1; i <= n; ++i) { long long d; scanf("%I64d%d", &d, p + i); ++p[i]; evs[ke++] = cell(d, d, i); } scanf("%d", &m); while (m--) { ll s, t; scanf("%I64d%I64d", &s, &t); evs[ke++] = cell(s, t, -1); } evs[ke++] = cell(0, 0, -1); sort(evs, evs + ke); vector<int> ans; priority_queue< pair<int, int> > q; for (int i = ke - 1; i >= 1; --i) { ll r = evs[i].l - 1; if (evs[i].id != -1) { q.push(make_pair(-p[ evs[i].id ], evs[i].id)); r++; } ll l = evs[i - 1].r + 1; ll cnt = r - l + 1; while (cnt && !q.empty()) { pair<int, int> T = q.top(); q.pop(); ll days = min(cnt, ll(-T.first)); if (days == -T.first) { ans.push_back(T.second); } else { q.push(make_pair(days + T.first, T.second)); } cnt -= days; } } printf("%d\n", ans.size()); sort(ans.begin(), ans.end()); for (int i = 0; i < ans.size(); ++i) { printf("%d ", ans[i]); } puts(""); scanf("%d", &n); } return 0; }
#include<bits/stdc++.h> using namespace std; const double pi=acos(-1.0); const double eps=1e-8; //double类型的数,判断符号 int cmp(double x){ if(fabs(x)<eps) return 0; if(x>0) return 1; return -1; } //二维点类,可进行向量运算 //计算平方 inline double sqr(double x){ return x*x; } struct point{ double x,y; point(){} point(double a,double b):x(a),y(b){} void input(){ scanf("%lf%lf",&x,&y); } friend point operator + (const point &a,const point &b){ return point(a.x+b.x,a.y+b.y); } friend point operator - (const point &a,const point &b){ return point(a.x-b.x,a.y-b.y); } friend bool operator == (const point &a,const point &b){ return cmp(a.x-b.x)==0&&cmp(a.y-b.y)==0; } friend point operator * (const point &a,const double &b){ return point(a.x*b,a.y*b); } friend point operator * (const double &a,const point &b){ return point(a*b.x,a*b.y); } friend point operator / (const point &a,const double &b){ return point(a.x/b,a.y/b); } double norm(){ return sqrt(sqr(x)+sqr(y)); } }; //计算向量叉积 double det(const point &a,const point &b){ return a.x*b.y-a.y*b.x; } //计算向量点积 double dot(const point &a,const point &b){ return a.x*b.x+a.y*b.y; } //计算两点距离 double dist(const point &a,const point &b){ return (a-b).norm(); } //op绕原点逆时针旋转A弧度 point rotate_point(const point &p,double A){ double tx=p.x,ty=p.y; return point(tx*cos(A)-ty*sin(A),tx*sin(A)+ty*cos(A)); } point res; //线段类 struct line{ point a,b; int index; line(){} line(point x,point y,int ind):a(x),b(y),index(ind){} }; //用两个点a,b生成的线段或直线 line point_make_line(const point a,const point b,int index){ return line(a,b,index); } //求p到线段st的距离 double dis_point_segment(const point p,const point s,const point t){ if(cmp(dot(p-s,t-s))<0) return (p-s).norm(); if(cmp(dot(p-t,s-t))<0) return (p-t).norm(); return fabs(det(s-p,t-p)/dist(s,t)); } //求p到线段st的垂足,保存在cp中 void PointProjLine(const point p,const point s,const point t,point &cp){ double r=dot((t-s),(p-s))/dot(t-s,t-s); cp=s+r*(t-s); } //判断p是否在线段st上(包括端点) bool PointOnSegment(point p,point s,point t){ return cmp(det(p-s,t-s))==0 && cmp(dot(p-s,p-t))<=0; } //判断a,b是否平行 bool parallel(line a,line b){ return !cmp(det(a.a-a.b,b.a-b.b)); } //判断a,b是否相交,如果相交则返回true且交点保存在res中 bool line_make_point(line a,line b){ if(parallel(a,b)) return false; double s1=det(a.a-b.a,b.b-b.a); double s2=det(a.b-b.a,b.b-b.a); res=(s1*a.b-s2*a.a)/(s1-s2); return true; } //将直线a沿法向量平移距离len得到的直线 //line move_d(line a,const double &len){ // point d=a.b-a.a; // d=d/d.norm(); // d=rotate_point(d,pi/2); // return line(a.a+d*len,a.b+d*len); //} /////////////////////////////////////////////////// bool judge(line a,line b){ if(parallel(a,b)&&(PointOnSegment(a.a,b.a,b.b)||PointOnSegment(a.b,b.a,b.b)||PointOnSegment(b.a,a.a,a.b)||PointOnSegment(b.b,a.a,a.b))) return true; if(line_make_point(a,b)){ if(PointOnSegment(res,a.a,a.b)&&PointOnSegment(res,b.a,b.b)) return true; else return false; }else return false; } point a,b; vector<line> v; int main(){ // freopen("in.txt", "r", stdin); // freopen("out.txt", "w", stdout); int n; while(scanf("%d",&n)&&n){ v.clear(); int cnt=1; while(n--){ scanf("%lf%lf%lf%lf",&a.x,&a.y,&b.x,&b.y); line l=point_make_line(a,b,cnt); int sz=v.size(); for(int i=0; i<sz; i++) { if(judge(l,v[i])) { auto it=v.begin()+i; v.erase(it); i--; sz--; } } v.push_back(l); cnt++; } int sz=v.size(); printf("Top sticks:"); for(int i=0; i<sz-1; i++) printf(" %d,",v[i].index); printf(" %d.\n",v[sz-1].index); } return 0; }
#include <iostream> using namespace std; int main(){ int a,b,c,d; d = 0; cin >> a >> b >> c; if(a > b) d = a; else d = b; if(d > c) d = d; else d = c; cout << d << " eh o maior" << endl; return 0; }
#define SEA 0 #define LAND 1 #define NON_VISITED 0 #define VISITED 1 #include <iostream> using namespace std; int nResult; int W, H; int dx[8] = { -1, -1, 0, 1, 1, 1, 0, -1 }; int dy[8] = { 0, 1, 1, 1, 0, -1, -1, -1 }; int nMap[50][50]; int nChecked[50][50]; void DFS(int nStartY, int nStartX) { nChecked[nStartY][nStartX] = true; for (int i = 0; i < 8; i++) { int ny = nStartY + dy[i]; int nx = nStartX + dx[i]; if (ny >= 0 && ny < H && nx >= 0 && nx < W) { if (NON_VISITED == nChecked[ny][nx] && LAND == nMap[ny][nx]) { DFS(ny, nx); } } } } int main() { while (1) { // 사이즈 입력 cin >> W >> H; // 0, 0 이면 입력 종료 if (0 == W && 0 == H) { break; } // 초기화 과정 nResult = 0; for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { nMap[y][x] = 0; nChecked[y][x] = 0; } } // 입력 과정 for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { cin >> nMap[y][x]; } } // DFS과정 for (int y = 0; y < H; y++) { for (int x = 0; x < W; x++) { if ( LAND == nMap[y][x] && NON_VISITED == nChecked[y][x]) { DFS(y, x); nResult++; } } } cout << nResult << endl; } return 0; }
#include<iostream> #include<cstring> using namespace std; int main() { int str[10]; memset(str, 8, sizeof(str)); for (int i = 0; i < 10; i ++) { // for (int i = 0; i < strlen(str); i ++) { cout << str[i] << " "; } cout << endl; return 0; }
#pragma once #include <vector> using namespace std; class DiceRollingFacility { private: int number_of_rolls; //0index is for 1, 1index is for 2... //3,4 and 5 indices are for black dice values vector<int> number_of_Getting_each_value; public: DiceRollingFacility(); int rollDice(); //console output void printPercentage_of_Getting_each_value(); void testDice(); };
// Fill out your copyright notice in the Description page of Project Settings. #include "Hypoxia.h" #include "HypoxiaMonster.h" // Sets default values AHypoxiaMonster::AHypoxiaMonster() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; MonsterSound = CreateDefaultSubobject<UComplexAudioComponent>(FName("Monster Sound")); MonsterSound->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void AHypoxiaMonster::BeginPlay() { Super::BeginPlay(); MonsterSound->SetAttenuationSettings(SoundAttenuation); IdleSoundTimer = IdleSoundDelay + FMath::RandRange(0.f, 1.0f) * IdleSoundDelayRandomness; } // Called every frame void AHypoxiaMonster::Tick( float DeltaTime ) { Super::Tick( DeltaTime ); IdleSoundTimer -= DeltaTime; if (IdleSoundTimer <= 0) { MonsterSound->SetSound(IdleSound); MonsterSound->Play(); IdleSoundTimer = IdleSoundDelay + FMath::RandRange(0.f, 1.0f) * IdleSoundDelayRandomness; } } // Called to bind functionality to input void AHypoxiaMonster::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void AHypoxiaMonster::PlayDetectSound() { MonsterSound->SetSound(DetectSound); MonsterSound->Play(); IdleSoundTimer = 10000.f; }
#include <string> #include <cmath> #include <fstream> #include <iostream> #include <sstream> #include <list> #include <algorithm> #include <set> #include <map> #include <stack> #include <queue> #include <numeric> #include <bitset> #include <deque> //#include <random> #include <string.h> #include <stdlib.h> #include <vector> const long long LINF = (1e18); const int INF = (1<<28); const int sINF = (1<<23); const int MOD = 1000000007; const double EPS = 1e-6; using namespace std; class PalindromePermutations { public: double palindromeProbability(string word) { int N = (int)word.size(); double f[55]; f[0] = 1.0; for (int i=1; i<=N; ++i) f[i] = i * f[i-1]; double p = f[N/2], q = f[N]; int odd = 0; for (char c = 'a'; c <= 'z'; ++c) { int t = (int)count(word.begin(), word.end(), c); if (t&1) ++odd; p /= f[(t/2)]; q /= f[t]; } if (odd > 1 || ( odd != (N&1) ) ) return 0.0; return p / q; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "haha"; double Arg1 = 0.3333333333333333; verify_case(0, Arg1, palindromeProbability(Arg0)); } void test_case_1() { string Arg0 = "xxxxy"; double Arg1 = 0.2; verify_case(1, Arg1, palindromeProbability(Arg0)); } void test_case_2() { string Arg0 = "xxxx"; double Arg1 = 1.0; verify_case(2, Arg1, palindromeProbability(Arg0)); } void test_case_3() { string Arg0 = "abcde"; double Arg1 = 0.0; verify_case(3, Arg1, palindromeProbability(Arg0)); } void test_case_4() { string Arg0 = "hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhff"; double Arg1 = 0.025641025641025637; verify_case(4, Arg1, palindromeProbability(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { PalindromePermutations ___test; ___test.run_test(-1); } // END CUT HERE
#include <ESP8266WiFi.h> // Importa a Biblioteca ESP8266WiFi #include <PubSubClient.h> // Importa a Biblioteca PubSubClient // WIFI const char* SSID = " "; // SSID da Rede const char* PASSWORD = " "; // Senha da Rede // MQTT const char* BROKER_MQTT = "iot.eclipse.org"; // IP/URL DO BROKER MQTT int BROKER_PORT = 1883; // Porta do Broker MQTT //defines gerais #define ID_MQTT "HomeAut" //id mqtt (para identificação de sessão) #define ENDERECO_MODULO 1 //endereço deste módulo #define ENDERECO_MODULO_STR "001" //endereço deste módulo #define TOPICO_SUBSCRIBE "MQTTHomeIOTEnvia" //tópico MQTT de escuta #define TOPICO_PUBLISH "MQTTHomeIOTRecebe" //tópico MQTT de envio de informações para Broker //mapeamento de pinos do NodeMCU #define D0 16 #define D1 5 #define D2 4 #define D3 0 #define D4 2 #define D5 14 #define D6 12 #define D7 13 #define D8 15 #define D9 3 #define D10 1 //Variáveis e objetos globais WiFiClient espClient; // Cria o objeto espClient PubSubClient MQTT(espClient); // Instancia o Cliente MQTT passando o objeto espClient char EstadoSaida1; char EstadoSaida2; char EstadoSaida3; char EstadoSaida4; //Prototypes void initSerial(); void initWiFi(); void initMQTT(); void mqtt_callback(char* topic, byte* payload, unsigned int length); void VerificaConexoesWiFIEMQTT(void); void EnviaEstadoOutputsMQTT(void); void InitOutputs(void); void AtuaSaida(String saida, String acao); /* * Implementações das funções */ void setup() { pinMode(D0, OUTPUT); pinMode(D1, OUTPUT); pinMode(D2, OUTPUT); pinMode(D3, OUTPUT); InitOutputs(); initSerial(); initWiFi(); initMQTT(); } //Função: inicializa comunicação serial //Parâmetros: nenhum //Retorno: nenhum void initSerial() { Serial.begin(115200); } //Função: inicializa e conecta-se na rede WiFi desejada //Parâmetros: nenhum //Retorno: nenhum void initWiFi() { delay(10); Serial.println(); Serial.print("Conectando-se em: "); Serial.println(SSID); WiFi.begin(SSID, PASSWORD); // Conecta na Rede Wireless while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } Serial.println(); Serial.print("Conectado na Rede "); Serial.print(SSID); Serial.println(" | IP "); Serial.println(WiFi.localIP()); } //Função: inicializa parâmetros de conexão MQTT(endereço do broker, porta e seta função de callback) //Parâmetros: nenhum //Retorno: nenhum void initMQTT() { MQTT.setServer(BROKER_MQTT, BROKER_PORT); MQTT.setCallback(mqtt_callback); //atribui função de callback (função chamada quando qualquer informação de um dos tópicos subescritos chega) } //Função: função de callback (chamada toda vez que uma informação de um dos tópicos subescritos chega) //Parâmetros: nenhum //Retorno: nenhum void mqtt_callback(char* topic, byte* payload, unsigned int length) { String msg; for(int i = 0; i < length; i++) { char c = (char)payload[i]; msg += c; } //faz o parse da string String Modulo = msg.substring(0, 3); String Saida = msg.substring(4, 6); String Acao = msg.substring(7, 9); if (Modulo.equals(ENDERECO_MODULO_STR)) AtuaSaida(Saida,Acao); } //Função: atua nas saidas //Parâmetros: saida que deseja atiuar e ação (ligar ou desligar) //Retorno: nenhum void AtuaSaida(String saida, String acao) { if (saida.equals("01")) { if (acao.equals("L")) { digitalWrite(D0, HIGH); EstadoSaida1 = '1'; } if (acao.equals("D")) { digitalWrite(D0, LOW); EstadoSaida1 = '0'; } return; } if (saida.equals("02")) { if (acao.equals("L")) { digitalWrite(D1, HIGH); EstadoSaida2 = '1'; } if (acao.equals("D")) { digitalWrite(D1, LOW); EstadoSaida2 = '0'; } return; } if (saida.equals("03")) { if (acao.equals("L")) { digitalWrite(D2, HIGH); EstadoSaida3 = '1'; } if (acao.equals("D")) { digitalWrite(D2, LOW); EstadoSaida3 = '0'; } return; } if (saida.equals("04")) { if (acao.equals("L")) { digitalWrite(D3, HIGH); EstadoSaida4 = '1'; } if (acao.equals("D")) { digitalWrite(D3, LOW); EstadoSaida4 = '0'; } return; } } //Função: reconecta-se ao broker MQTT (caso ainda não esteja conectado ou em caso de a conexão cair) // em caso de sucesso na conexão ou reconexão, o subscribe dos tópicos é refeito. //Parâmetros: nenhum //Retorno: nenhum void reconnectMQTT() { while (!MQTT.connected()) { Serial.print("Tentando se conectar ao Broker MQTT: "); Serial.println(BROKER_MQTT); if (MQTT.connect(ID_MQTT)) { Serial.println("Conectado"); MQTT.subscribe(TOPICO_SUBSCRIBE); } else { Serial.println("Falha ao Reconectar"); Serial.println("Tentando se reconectar em 2 segundos"); delay(2000); } } } //Função: reconecta-se ao WiFi //Parâmetros: nenhum //Retorno: nenhum void recconectWiFi() { while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } } //Função: verifica o estado das conexões WiFI e ao broker MQTT. Em caso de desconexão (qualquer uma das duas), a conexão é refeita. //Parâmetros: nenhum //Retorno: nenhum void VerificaConexoesWiFIEMQTT(void) { if (!MQTT.connected()) reconnectMQTT(); //se não há conexão com o Broker, a conexão é refeita recconectWiFi(); //se não há conexão com o WiFI, a conexão é refeita } //Função: envia ao Broker o estado atual de todos os outputs //Parâmetros: nenhum //Retorno: nenhum void EnviaEstadoOutputsMQTT(void) { char payloadChar[13]; int EnderecoModulo = ENDERECO_MODULO; char payload[11]; sprintf(payloadChar,"%03d>%c>%c>%c>%c", EnderecoModulo, EstadoSaida1, EstadoSaida2, EstadoSaida3, EstadoSaida4); memcpy(payload,payloadChar,11); Serial.println("- Estado das saidas enviado ao broker!"); MQTT.publish(TOPICO_PUBLISH, payloadChar); delay(1000); } //Função: inicializa todos os outputs em nível lógico baixo //Parâmetros: nenhum //Retorno: nenhum void InitOutputs(void) { digitalWrite(D0, LOW); digitalWrite(D1, LOW); digitalWrite(D2, LOW); digitalWrite(D3, LOW); EstadoSaida1 = '0'; EstadoSaida2 = '0'; EstadoSaida3 = '0'; EstadoSaida4 = '0'; } //programa principal void loop() { //garante funcionamento das conexões WiFi e ao broker MQTT VerificaConexoesWiFIEMQTT(); //envia o status de todos os outputs para o Broker no protocolo esperado EnviaEstadoOutputsMQTT(); //keep-alive da comunicação com broker MQTT MQTT.loop(); }
// Copyright (c) 2016-2019 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Aspect_VKeySet_HeaderFile #define _Aspect_VKeySet_HeaderFile #include <Aspect_VKey.hxx> #include <NCollection_Array1.hxx> #include <OSD_Timer.hxx> #include <Standard_Mutex.hxx> #include <Standard_Transient.hxx> //! Structure defining key state. class Aspect_VKeySet : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Aspect_VKeySet, Standard_Transient) public: //! Main constructor. Standard_EXPORT Aspect_VKeySet(); //! Return active modifiers. Aspect_VKeyFlags Modifiers() const { Standard_Mutex::Sentry aLock (myLock); return myModifiers; } //! Return timestamp of press event. double DownTime (Aspect_VKey theKey) const { Standard_Mutex::Sentry aLock (myLock); return myKeys[theKey].TimeDown; } //! Return timestamp of release event. double TimeUp (Aspect_VKey theKey) const { Standard_Mutex::Sentry aLock (myLock); return myKeys[theKey].TimeUp; } //! Return TRUE if key is in Free state. bool IsFreeKey (Aspect_VKey theKey) const { Standard_Mutex::Sentry aLock (myLock); return myKeys[theKey].KStatus == KeyStatus_Free; } //! Return TRUE if key is in Pressed state. bool IsKeyDown (Aspect_VKey theKey) const { Standard_Mutex::Sentry aLock (myLock); return myKeys[theKey].KStatus == KeyStatus_Pressed; } //! Return mutex for thread-safe updates. //! All operations in class implicitly locks this mutex, //! so this method could be used only for batch processing of keys. Standard_Mutex& Mutex() { return myLock; } public: //! Reset the key state into unpressed state. Standard_EXPORT void Reset(); //! Press key. //! @param theKey key pressed //! @param theTime event timestamp Standard_EXPORT void KeyDown (Aspect_VKey theKey, double theTime, double thePressure = 1.0); //! Release key. //! @param theKey key pressed //! @param theTime event timestamp Standard_EXPORT void KeyUp (Aspect_VKey theKey, double theTime); //! Simulate key up/down events from axis value. Standard_EXPORT void KeyFromAxis (Aspect_VKey theNegative, Aspect_VKey thePositive, double theTime, double thePressure); //! Return duration of the button in pressed state. //! @param theKey key to check //! @param theTime current time (for computing duration from key down time) //! @param theDuration key press duration //! @return TRUE if key was in pressed state bool HoldDuration (Aspect_VKey theKey, double theTime, double& theDuration) { double aPressure = -1.0; return HoldDuration (theKey, theTime, theDuration, aPressure); } //! Return duration of the button in pressed state. //! @param theKey key to check //! @param theTime current time (for computing duration from key down time) //! @param theDuration key press duration //! @param thePressure key pressure //! @return TRUE if key was in pressed state Standard_EXPORT bool HoldDuration (Aspect_VKey theKey, double theTime, double& theDuration, double& thePressure); private: //! Key state. enum KeyStatus { KeyStatus_Free, //!< free status KeyStatus_Pressed, //!< key is in pressed state KeyStatus_Released, //!< key has been just released (transient state before KeyStatus_Free) }; //! Structure defining key state. struct KeyState { KeyState() : TimeDown (0.0), TimeUp (0.0), Pressure (1.0), KStatus (KeyStatus_Free) {} void Reset() { KStatus = KeyStatus_Free; TimeDown = 0.0; TimeUp = 0.0; Pressure = 1.0; } double TimeDown; //!< time of key press event double TimeUp; //!< time of key release event double Pressure; //!< key pressure KeyStatus KStatus; //!< key status }; private: NCollection_Array1<KeyState> myKeys; //!< keys state mutable Standard_Mutex myLock; //!< mutex for thread-safe updates Aspect_VKeyFlags myModifiers; //!< active modifiers }; #endif // _Aspect_VKeySet_HeaderFile
#include <iostream> #include <cstdio> #include <algorithm> #include <vector> #include <functional> #include <queue> #include <string> #include <cstring> #include <numeric> #include <cstdlib> #include <cmath> using namespace std; typedef long long ll; #define INF 10e10 #define rep(i,n) for(int i=0; i<n; i++) #define REP_R(i,n,m) for(int i=m; i<n; i++) #define MAX 100 int N; ll Y; int main() { cin >> N >> Y; int flag = false; int x,y,z; // i: 10000, j: 5000, k: 1000 for (int i = 0; i <= N; i++) { x = i; for (int j = 0; j <= N - i; j++) { int k = (N - i) - j; ll tt = i * 10000 + j * 5000 + k * 1000; if (tt == Y) { flag = true; y = j; z = k; break; } } if (flag) { printf("%d %d %d\n", x,y,z); return 0; } } cout << "-1 -1 -1" << endl; }
// https://practice.geeksforgeeks.org/problems/subset-with-sum-divisible-by-m/0 #include <iostream> #include <cstring> using namespace std; bool checkAns(int n, int m, int a[]) { if (n > m) return true; bool dp[m], temp[m]; memset(dp, 0, m); for (int i = 1; i <= n; i++) { if (dp[0]) return true; memset(temp, 0, m); for (int j = 0; j < m; j++) { if (dp[j] == true) if (dp[(j + a[i]) % m] == false) { temp[(j + a[i]) % m] = true; } } for (int j = 0; j < m; j++) if (temp[j]) dp[j] = true; dp[a[i] % m] = true; } return dp[0]; } int main() { int t, n, m, a[1001]; cin >> t; while (t--) { cin >> n >> m; for (int i = 1; i <= n; i++) cin >> a[i]; cout << checkAns(n, m, a) << endl; } }
#include <gl/glui.h> #include <iostream> int window_width = 512; int window_height = 512; void reshape (int w, int h); void mouse (int button, int state, int x, int y); void motion (int x, int y); void pmotion (int x, int y); void keyboard (unsigned char key, int x, int y); void special (int key, int x, int y); void entry (int state); void reshape (int w, int h) { // Stay updated with the window width and height window_width = w; window_height = h; if (h<w) glViewport( (w-h)/2 , 0, h, h); else glViewport(0, (h-w)/2, w, w); // Print current width and height on the screen printf ("Window Width: %d, Window Height: %d.\n", window_width, window_height); } void mouse (int button, int state, int x, int y) { switch (button) { // Left Button Clicked case GLUT_LEFT_BUTTON: switch (state) { // Pressed case GLUT_DOWN: printf ("Mouse Left Button Pressed (Down)...\n"); break; // Released case GLUT_UP: printf ("Mouse Left Button Released (Up)...\n"); break; } break; // Middle Button clicked case GLUT_MIDDLE_BUTTON: switch (state) { // Pressed case GLUT_DOWN: printf ("Mouse Middle Button Pressed (Down)...\n"); break; // Released case GLUT_UP: printf ("Mouse Middle Button Released (Up)...\n"); break; } break; // Right Button Clicked case GLUT_RIGHT_BUTTON: switch (state) { // Pressed case GLUT_DOWN: printf ("Mouse Right Button Pressed (Down)...\n"); break; // Released case GLUT_UP: printf ("Mouse Right Button Released (Up)...\n"); break; } break; } } void motion (int x, int y) { // Print the mouse drag position printf ("Mouse Drag Position: %d, %d.\n", x, y); } void pmotion (int x, int y) { // Print mouse move positopn printf ("Mouse Move Position: %d, %d.\n", x, y); } void keyboard (unsigned char key, int x, int y) { // Print what key the user is hitting printf ("User is hitting the '%c' key.\n", key); printf ("ASCII code is %d.\n", key); switch (key) { // User hits A key case 'a': break; // User hits Shift + A key case 'A': break; // User hits Enter case '\r': printf ("User is hitting the Return key.\n"); break; // User hits Space case ' ': printf ("User is hitting the Space key.\n"); break; // User hits back space case 8: printf ("User is hitting the Back Space key.\n"); break; // User hits ESC key case 27: exit (1); break; } glutPostRedisplay (); } void special (int key, int x, int y) { switch (key) { case GLUT_KEY_F1 : printf ("F1 function key.\n"); break; case GLUT_KEY_F2 : printf ("F2 function key. \n"); break; case GLUT_KEY_F3 : printf ("F3 function key. \n"); break; case GLUT_KEY_F4 : printf ("F4 function key. \n"); break; case GLUT_KEY_F5 : printf ("F5 function key. \n"); break; case GLUT_KEY_F6 : printf ("F6 function key. \n"); break; case GLUT_KEY_F7 : printf ("F7 function key. \n"); break; case GLUT_KEY_F8 : printf ("F8 function key. \n"); break; case GLUT_KEY_F9 : printf ("F9 function key. \n"); break; case GLUT_KEY_F10 : printf ("F10 function key. \n"); break; case GLUT_KEY_F11 : printf ("F11 function key. \n"); break; case GLUT_KEY_F12 : printf ("F12 function key. \n"); break; case GLUT_KEY_LEFT : printf ("Left directional key. \n"); break; case GLUT_KEY_UP : printf ("Up directional key. \n"); break; case GLUT_KEY_RIGHT : printf ("Right directional key. \n"); break; case GLUT_KEY_DOWN : printf ("Down directional key. \n"); break; case GLUT_KEY_PAGE_UP : printf ("Page up directional key. \n"); break; case GLUT_KEY_PAGE_DOWN : printf ("Page down directional key. \n"); break; case GLUT_KEY_HOME : printf ("Home directional key. \n"); break; case GLUT_KEY_END : printf ("End directional key. \n"); break; case GLUT_KEY_INSERT : printf ("Inset directional key. \n"); break; } glutPostRedisplay (); } void entry (int state) { // Notify that this is a GLUT Callback printf ("GLUT: "); // Notify theat we entered the window if (state == GLUT_ENTERED) printf ("Mouse entered GLUT window...\n"); // Notify that we left the window else if (state == GLUT_LEFT) printf ("Mouse left GLUT window...\n"); }
// // Rock.cpp // GetRock // // Created by zhusu on 15/3/11. // // #include "Rock.h" #include "AudioController.h" Rock* Rock::create(const char* name,int hp) { Rock* rock = new Rock(); if(rock && rock->init(name,hp)) { rock->autorelease(); return rock; } CC_SAFE_DELETE(rock); return NULL; } Rock::Rock():_hp(5),_maxHp(_hp) { } Rock::~Rock() { } bool Rock::init(const char* name,int hp) { if(!Actor::init(name)) { return false; } _hp = _maxHp = hp; this->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(Rock::movementCallback)); return true; } void Rock::setNowAnim() { int indext = (_maxHp-_hp)*4/_maxHp; playWithIndex(indext); } void Rock::movementCallback(CCArmature * armature, MovementEventType type, const char * name) { if (type == COMPLETE) { if (strcmp(name,"Animation5") == 0) { setState(STATE_DEAD); } } } void Rock::dis() { subHp(_hp); } void Rock::subHp() { subHp(1); } void Rock::subHp(int hp) { if (_hp>0) { _hp-=hp; if (_hp<=0) { _hp = 0; AUDIO->playSfx("music/rockbroken"); }else{ AUDIO->playSfx("music/rockrebound"); } setNowAnim(); } } int Rock::getHp() const { return _hp; }
/* ID: stevenh6 TASK: milk6 LANG: C++ */ #define problemname "milk6" #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using db = double; using pi = pair<int, int>; using pl = pair<ll, ll>; using pd = pair<db, db>; using vi = vector<int>; using vb = vector<bool>; using vl = vector<ll>; using vd = vector<db>; using vs = vector<string>; using vpi = vector<pi>; using vpl = vector<pl>; using vpd = vector<pd>; #define FOR(i, a, b) for (int i = (a); i < (b); ++i) #define FOR0(i, a) FOR(i, 0, a) #define RFOR(i, a, b) for (int i = (b)-1; i >= (a); --i) #define RFOR0(i, a) RFOR(i, 0, a) #define pb push_back; ofstream fout; ifstream fin; // End of template int n, m; int si[1001], ei[1001], ci[1001]; int flow[33][33], breadth[33], q[33]; int source, sink; int fflow(int now, int high) { if (now == n) { return high; } FOR(i, 1, n + 1) { if (breadth[now] == breadt[i] - 1 && flow[now][i] > 0) { int recur = fflow(i, min(high, flow[now][i])); if (recur > 0) { flow[now][i] -= recur; flow[i][now] += recur; //augmented flow return recur; } } } return 0; } bool bfs() { memset(breadth, 0, sizeof(breadth)); source = 0; sink = 1; q[0] = 1; breadth[1] = 1; while (source < sink) { int tmp = q[source]; source++; FOR(i, 1, n + 1) { if (flow[tmp][i] && !breadth[i]) { q[sink++] = i; breadth[i] = breadth[tmp] + 1; } } } return !breadth[n]; } void solve() { cin >> n >> m; FOR0(i, m) { cin >> si[i] >> ei[i] >> ci[i]; flow[si[i]][ei[i]] = ci[i]; } int maxflow = 0; while (bfs()) { maxflow += fflow(1, INT_MAX); } } int main() { ios_base::sync_with_stdio(); cin.tie(0); freopen(problemname ".in", "r", stdin); freopen(problemname ".out", "w", stdout); solve(); return 0; }
#include<iostream> #include<string.h> using namespace std; int score(char a) { int i; i=a-'0'; if(a=='X') return 10; else if(a=='/') return 10; else { return i; } } void makeline(char* a) { int k=0; char *b; b=(char*)calloc(strlen(a)+1,sizeof(char)); for(int i=0;i<strlen(a);i++) if(a[i]!=' ') { b[k]=a[i]; k++; } b[k]='\0'; strcpy(a,b); free(b); } int main() { char input[100]; int output=0; int i,j,k=0,count; while(1) { output=0; cin.getline(input,100); if(strcmp("Game Over",input)==0) break; count=0; makeline(input); for(j=0;j<strlen(input);) { if(count!=9) { if(input[j]!='X'&&input[j+1]!='/') { output+=score(input[j])+score(input[j+1]); count++; j+=2; } else if(input[j]=='X') { if(input[j+2]!='/') { output+=score(input[j])+score(input[j+1])+score(input[j+2]); j++; count++; } else { output+=score(input[j])+score(input[j+2]); j++; count++; } } else if(input[j+1]=='/') { output+=score(input[j+1])+score(input[j+2]); j+=2; count++; } } else { if(input[j]=='X') { if(input[j+2]!='/') { output+=score(input[j])+score(input[j+1])+score(input[j+2]); break; } else { output+=score(input[j])+score(input[j+2]); break; } } else if(input[j+1]=='/') { output+=score(input[j+1])+score(input[j+2]); break; } else { output+=score(input[j])+score(input[j+1]); break; } } } cout<<output<<endl; } return 0; }
#ifndef GAME_HPP #define GAME_HPP #define CASPER 2 #define SPEED 5000 //#include "pac.hpp" class Game { public: Game(void); Game(std::vector<char*>, int, int); Game(Game const &); ~Game(void); Game const &operator=(Game const &); void start(void); void print_map(); void getScore(); //////getters private: WINDOW * _win; std::vector<char*> map; int height; int width; Casper cas[CASPER]; Pacman Pac; int mv; int mvCas; int scoreToWin; }; #endif
#pragma once #include "GcVSListBox.h" #include "GcMediateObject.h" class GcCollisionList : public GcVSListBox, public GcMediateObject { protected: Gn2DAVData* mpAVData; Gt2DSequence* mpSequence; public: GcCollisionList(void); ~GcCollisionList(void); void ResetData(Gt2DSequence* pSequence); CString GetMakeName(gtuint i, int iType); protected: virtual void CreateNewItem(); virtual BOOL RemoveItem(int iIndex); };
#include<iostream> using namespace std; int main(void){ int a[10] = {0}; int i = 10; int j = 3; cout << a[i/j]; }