text
stringlengths
8
6.88M
#ifndef _GEO_INFO #define _GEO_INFO #include <string> using std::string; class GeoInfo { public: GeoInfo(string _city); float lat; float lng; //string localtime; int offset; string address; private: bool getLatLng(); bool getTimeZone(); bool parseLatLng(); bool parseTimeZone(); //bool curl(string url); //bool parseXML(); string slat; string slng; string city; //char wr_buf[MAX_BUF+1]; //int wr_index; // Write any errors in here //static char errorBuffer[CURL_ERROR_SIZE]; // Write all expected data in here //static string buffer; }; #endif
#include <iostream> #include <cstring> #include <queue> using namespace std; int N, M, p1, p2; int info[101][101] = {0,}; int visited[101] = {0,}; queue<int> q; int bfs() { while( !q.empty() ) { int cur = q.front(); // printf("cur : %d \n", cur); q.pop(); if ( cur == p2 ) return visited[cur]; for(int i=1; i<=N; i++) { if ( info[cur][i] == 1 && visited[i] == 0 ) { // has child visited[i] = visited[cur]+1; q.push(i); } } for(int j=1; j<=N; j++) { if ( info[j][cur] == 1 && visited[j] ==0 ) { // has parent visited[j] = visited[cur]+1; q.push(j); } } } return -1; } int main(void) { scanf("%d", &N); scanf("%d %d", &p1, &p2); scanf("%d", &M); for(int i=0; i<M; i++) { int temp1, temp2; scanf("%d %d", &temp1, &temp2); // arr[temp1].push_back(temp2); info[temp1][temp2] = 1; } // print linked list // for(int i=0; i<N; i++) { // printf("idx : %d ", i); // list<int>::iterator itor; // for(itor=arr[i].begin(); itor!=arr[i].end(); itor++) { // printf(" -> %d ", *itor ); // } // printf("\n"); // } q.push(p1); int ans = bfs(); printf("%d", ans); }
#include "rule.h" using namespace std; namespace sbg { template<int n> Rule<n>::~Rule(){} template struct Rule<2>; template struct Rule<3>; }
#include <string> #include "ThrowCardProc.h" #include "HallManager.h" #include "Logger.h" #include "Room.h" #include "Configure.h" #include "ErrorMsg.h" #include "ProcessManager.h" #include "IProcess.h" #include "BaseClientHandler.h" #include "ProtocolServerId.h" REGISTER_PROCESS(CLIENT_MSG_THROW_CARD, ThrowCardProc) ThrowCardProc::ThrowCardProc() { this->name = "ThrowCardProc" ; } ThrowCardProc::~ThrowCardProc() { } int ThrowCardProc::doRequest(CDLSocketHandler* clientHandler, InputPacket* pPacket,Context* pt) { //_NOTUSED(pt); int cmd = pPacket->GetCmdType(); short seq = pPacket->GetSeqNum(); int uid = pPacket->GetUid(); int uid_b = pPacket->ReadInt(); int tid = pPacket->ReadInt(); short svid = tid >> 16; short realTid = tid & 0x0000FFFF; BaseClientHandler* hallhandler = reinterpret_cast<BaseClientHandler*> (clientHandler); if (uid != uid_b) { ULOGGER(E_LOG_ERROR, uid) << "fucking userid operator uid=" << uid_b; return sendErrorMsg(hallhandler, cmd, uid, 4, _EMSG_(4),seq); } _LOG_DEBUG_("==>[ThrowCardProc] [0x%04x] uid[%d]\n", cmd, uid); _LOG_DEBUG_("[DATA Parse] tid=[%d] svid=[%d] reallTid[%d]\n", tid, svid, realTid); Room* room = Room::getInstance(); Table* table = room->getTable(realTid); if(table == NULL) { _LOG_ERROR_("[ThrowCardProc] uid=[%d] tid=[%d] realTid=[%d] Table is NULL\n",uid, tid, realTid); return sendErrorMsg(hallhandler, cmd, uid, -2,_EMSG_(-2),seq); } Player* player = table->getPlayer(uid); if(player == NULL) { _LOG_ERROR_("[ThrowCardProc] uid=[%d] tid=[%d] realTid=[%d] Your not in This Table\n",uid, tid, realTid); return sendErrorMsg(hallhandler, cmd, uid, -1,_EMSG_(-1),seq); } if( ! player->isActive()) { _LOG_ERROR_("[ThrowCardProc] uid=[%d] tid=[%d] realTid=[%d] tm_nStatus=[%d] is not active\n",uid, tid, realTid, table->m_nStatus); return sendErrorMsg(hallhandler, cmd, uid, -11,_EMSG_(-11),seq); } if(player->m_bCardStatus == CARD_DISCARD) { _LOG_ERROR_("[ThrowCardProc] uid=[%d] tid=[%d] realTid=[%d] tm_nStatus=[%d] your cardstatus[%d] no card\n", uid, tid, realTid, table->m_nStatus, player->m_bCardStatus); return sendErrorMsg(hallhandler, cmd, uid, -21,_EMSG_(-21),seq); } if(table->m_bIsOverTimer) { _LOG_ERROR_("[ThrowCardProc] table is IsOverTimer uid=[%d] tid=[%d] realTid=[%d] Table Status=[%d]\n",uid, tid, realTid, table->m_nStatus); return sendErrorMsg(hallhandler, cmd, uid, 2,_EMSG_(2),seq); } _LOG_INFO_("[ThrowCardProc] Uid=[%d] GameID=[%s] m_lSumBetCoin=[%ld] currRound=[%d]\n", player->id, table->getGameID(), player->m_lSumBetCoin, table->m_bCurrRound); player->recordThrowCard(table->m_bCurrRound , player->m_lSumBetCoin); player->m_bCardStatus = CARD_DISCARD; player->is_discard = true; player->setActiveTime(time(NULL)); Player* nextplayer = NULL; if(table->m_nCurrBetUid == player->id) { nextplayer = table->getNextBetPlayer(player, OP_THROW); } else { //ๅค„็†ๅฝ“ๅ‰ไธๆ˜ฏๆญค็”จๆˆทไธ‹ๆณจ็š„ๆ—ถๅ€™ๅผƒ็‰Œ๏ผŒ็„ถๅŽๆ“ไฝœ็ฑปๅž‹็š„้—ฎ้ข˜ Player* currenter = table->getPlayer(table->m_nCurrBetUid); table->setPlayerOptype(currenter, 0); } if(player->m_nTabIndex == table->m_nFirstIndex) { table->setNextFirstPlayer(player); } if(table->iscanGameOver()) nextplayer = NULL; for(int i = 0; i < table->m_bMaxNum; ++i) { if(table->player_array[i]) { sendThrowInfoToPlayers(table->player_array[i], table, player, nextplayer,seq); } } if(table->iscanGameOver()) return table->gameOver(); return 0; } int ThrowCardProc::sendThrowInfoToPlayers(Player* player, Table* table, Player* throwcallplayer,Player* nextplayer, short seq) { int svid = Configure::getInstance()->m_nServerId; int tid = (svid << 16)|table->id; OutputPacket response; response.Begin(CLIENT_MSG_THROW_CARD, player->id); if(player->id == throwcallplayer->id) response.SetSeqNum(seq); response.WriteShort(0); response.WriteString(""); response.WriteInt(player->id); response.WriteShort(player->m_nStatus); response.WriteInt(tid); response.WriteShort(table->m_nStatus); response.WriteByte(table->m_bCurrRound); response.WriteInt(throwcallplayer->id); response.WriteInt64(throwcallplayer->m_lSumBetCoin); response.WriteInt64(throwcallplayer->m_lMoney); response.WriteInt64(table->m_lCurrBetMax); response.WriteInt(nextplayer ? nextplayer->id : 0); response.WriteInt64(player->m_lSumBetCoin); response.WriteInt64(player->m_lMoney); response.WriteShort(player->optype); response.WriteInt64(table->m_lSumPool); response.WriteInt64(player->m_AllinCoin); response.WriteByte(player->m_bCardStatus); response.End(); _LOG_DEBUG_("<==[ThrowCardProc] Push [0x%04x] to uid=[%d]\n", CLIENT_MSG_THROW_CARD, player->id); _LOG_DEBUG_("[Data Response] err=[0], errmsg[]\n"); _LOG_DEBUG_("[Data Response] uid=[%d]\n",player->id); _LOG_DEBUG_("[Data Response] m_nStatus=[%d]\n",player->m_nStatus); _LOG_DEBUG_("[Data Response] throwcallplayer=[%d]\n", throwcallplayer->id); _LOG_DEBUG_("[Data Response] m_bCurrRound=[%d]\n", table->m_bCurrRound); _LOG_DEBUG_("[Data Response] nextplayer=[%d]\n", nextplayer ? nextplayer->id : 0); _LOG_DEBUG_("[Data Response] optype=[%d]\n", player->optype); if(HallManager::getInstance()->sendToHall(player->m_nHallid, &response, false) < 0) _LOG_ERROR_("[BetCallProc] Send To Uid[%d] Error!\n", player->id); return 0; } int ThrowCardProc::doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket ,Context* pt ) { _NOTUSED(clientHandler); _NOTUSED(inputPacket); _NOTUSED(pt); return 0; }
/** * author: rasel kibria * created: 05.07.2020 **/ #include<bits/stdc++.h> using namespace std; int main() { int n, i; cin>>n; for(i=1; i<=n; i++) { if(n%i==0) { cout<<i<<"\n"; } } return 0; }
//Copyright 2011-2016 Tyler Gilbert; All Rights Reserved #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include "hal/Adc.hpp" using namespace hal; Adc::Adc(port_t port) : Periph(CORE_PERIPH_ADC, port){} int Adc::get_attr(adc_attr_t & attr){ return ioctl(I_ADC_GETATTR, &attr); } int Adc::set_attr(const adc_attr_t & attr){ return ioctl(I_ADC_SETATTR, (void*)&attr); }
/* ########################################################################################### // cNVMe - An Open Source NVMe Device Simulation - MIT License // Copyright 2017 - Intel Corporation // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT // OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. ############################################################################################ Identify.h - A header file for the NVMe Identify Commands */ #include "Types.h" // Defaults #define DEFAULT_MODEL "CNVMe Model Number" #define DEFAULT_SERIAL "CNVMe Serial Number" #define DEFAULT_FIRMWARE "00000001" #define DEFAULT_SUBMISSION_QUEUE_ENTRY_SIZE 6 // 2^6 = 64 #define DEFAULT_COMPLETION_QUEUE_ENTRY_SIZE 4 // 2^4 = 16 #define DEFAULT_MAX_NAMESPACES 1 #pragma once namespace cnvme { namespace identify { namespace structures { typedef struct IDENTIFY_POWER_STATE_DESCRIPTOR { UINT_16 MP; UINT_8 RSVD_16_23; UINT_8 MXPS : 1; UINT_8 NOPS : 1; UINT_8 RSVD_26_31 : 6; UINT_32 ENLAT; UINT_32 EXLAT; UINT_8 RRT : 5; UINT_8 RSVD_101_103 : 3; UINT_8 RRL : 5; UINT_8 RSVD_109_111 : 3; UINT_8 RWT : 5; UINT_8 RSVD_117_119 : 3; UINT_8 RWL : 5; UINT_8 RSVD_125_127 : 3; UINT_16 IDLP; UINT_8 RSVD_144_149 : 6; UINT_8 IPS : 2; UINT_8 RSVD_152_159; UINT_16 ACTP; UINT_8 APW : 3; UINT_8 RSVD_179_181 : 3; UINT_8 APS : 2; UINT_8 RSVD_184_255[9]; } IDENTIFY_POWER_STATE_DESCRIPTOR, *PIDENTIFY_POWER_STATE_DESCRIPTOR; static_assert(sizeof(IDENTIFY_POWER_STATE_DESCRIPTOR) == 32, "The identify power state descriptor is 32 bytes."); typedef struct IDENTIFY_CONTROLLER { UINT_16 VID; UINT_16 SSID; char SN[20]; char MN[40]; char FR[8]; UINT_8 RAB; UINT_32 IEEE : 24; UINT_32 CMIC : 8; UINT_8 MDTS; UINT_16 CNTLID; union { struct { UINT_32 MJR : 16; UINT_32 MNR : 8; UINT_32 TER : 8; }; UINT_32 VER; }; UINT_32 RTD3R; UINT_32 RTD3E; UINT_32 OAES; UINT_32 CTRATT; UINT_8 RSVD_100_111[12]; UINT_8 FGUID[16]; UINT_8 RSVD_128_239[112]; UINT_8 RSVD_240_255_MI[16]; union { struct { UINT_16 SecuritySupported : 1; UINT_16 FormatNVMSupported : 1; UINT_16 FirmwareDownloadAndCommitSupported : 1; UINT_16 NamespaceCommandsSupported : 1; UINT_16 DeviceSelfTestSupported : 1; UINT_16 DirectivesSupported : 1; UINT_16 NVMeMiSendAndReceiveSupported : 1; UINT_16 VirtualizationManagementSupported : 1; UINT_16 DoorbellBufferConfigSupported : 1; UINT_16 RSVD_OACS : 7; }; UINT_16 OACS; }; UINT_8 ACL; UINT_8 AERL; union { struct { UINT_8 FirstFirmwareSlotIsReadOnly : 1; UINT_8 NumberOfFirmwareSlots : 3; UINT_8 FirmwareActivationWithoutResetSupported : 1; UINT_8 RSVD_FRMW : 3; }; UINT_8 FRMW; }; union { struct { UINT_8 SMARTHealthLogOnNamespaceBasisSupported : 1; UINT_8 CommandsEffectsLogSupported : 1; UINT_8 ExtendedDataForGetLogPageSupported : 1; UINT_8 TelemetryLogsSupported : 1; UINT_8 RSVD_LPA : 4; }; UINT_8 LPA; }; UINT_8 ELPE; UINT_8 NPSS; UINT_8 AVSCC; UINT_8 APSTA; UINT_16 WCTEMP; UINT_16 CCTEMP; UINT_16 MTFA; UINT_32 HMPRE; UINT_32 HMMIN; UINT_8 TNVMCAP[16]; UINT_8 UNVMCAP[16]; UINT_32 RPMBS; UINT_16 EDSTT; UINT_8 DSTO; UINT_8 FWUG; UINT_16 KAS; UINT_16 HCTMA; UINT_16 MNTMT; UINT_16 MXTMT; union { struct{ UINT_32 CryptoEraseSanitizeSupported : 1; UINT_32 BlockEraseSanitizeSupported : 1; UINT_32 OverwriteSanitizeSupported : 1; UINT_32 RSVD_SANICAP : 29; }; UINT_32 SANICAP; }; UINT_8 RSVD_332_511[180]; union { struct { UINT_8 MaxSubmissionQueueEntrySize : 4; UINT_8 RequiredSubmissionQueueEntrySize : 4; }; UINT_8 SQES; }; union { struct { UINT_8 MaxCompletionQueueEntrySize : 4; UINT_8 RequiredCompletionQueueEntrySize : 4; }; UINT_8 CQES; }; UINT_16 MAXCMD; UINT_32 NN; union { struct { UINT_16 CompareSupported : 1; UINT_16 WriteUncorrectableSupported : 1; UINT_16 DatasetManagementSupported : 1; UINT_16 WriteZeroesSupported : 1; UINT_16 SaveFieldOfSetFeaturesSupported : 1; UINT_16 ReservationsSupported : 1; UINT_16 TimestampFeatureSupported : 1; UINT_16 RSVD_ONCS : 9; }; UINT_16 ONCS; }; UINT_16 FUSES; union { struct { UINT_8 FormatAppliesToAllNamespaces : 1; UINT_8 AllNamespacesErasedOnSecureErase : 1; UINT_8 CryptoEraseSupportedAsPartOfSecureErase : 1; UINT_8 RSVD_FNA : 5; }; UINT_8 FNA; }; UINT_8 VWC; UINT_16 AWUN; UINT_16 AWUPF; UINT_8 NVSCC; UINT_8 RSVD_531; UINT_16 ACWU; UINT_16 RSVD_534_535; UINT_32 SGLS; UINT_8 RSVD_540_767[228]; char SUBNQN[256]; UINT_8 RSVD_1024_1791[768]; UINT_8 RSVD_NVME_OVER_FABRICS[256]; IDENTIFY_POWER_STATE_DESCRIPTOR PSD[32]; UINT_8 VendorSpecific[1024]; } IDENTIFY_CONTROLLER, *PIDENTIFY_CONTROLLER; static_assert(sizeof(IDENTIFY_CONTROLLER) == 4096, "Identify controller should be 4096 bytes in size"); } } }
// BEGIN CUT HERE // PROBLEM STATEMENT // // In a Las Vegas casino, a new type of six-sided die is // being introduced. These dice may have any positive // integers written its sides, but no two sides of the same // die can contain the same number. For each die, the casino // owner wants the mean value of the numbers written on its // sides to not exceed M. // // // // Compute the total number of allowed dice. Two dice are // considered different if one can't be obtained from the // other using rotations. Since the resulting number may be // quite large, return it modulo 1000000007. // // // DEFINITION // Class:CustomDice // Method:countDice // Parameters:int // Returns:int // Method signature:int countDice(int M) // // // CONSTRAINTS // -M will be between 1 and 1000000, inclusive. // // // EXAMPLES // // 0) // 3 // // Returns: 0 // // The die with the smallest possible mean is {1,2,3,4,5,6}. // Its mean is 3.5, which is greater than M=3. // // 1) // 4 // // Returns: 210 // // There are 30 different dice with numbers {1,2,3,4,5,6} on // their sides, they each have a mean of 3.5. // There are 30 different dice with numbers {1,2,3,4,5,7} on // their sides, they each have a mean of 22/6=3.(6). // There are 60 different dice with {1,2,3,4,5,8} or // {1,2,3,4,6,7} on their sides, they each have a mean of // 23/6=3.8(3). // There are 90 different dice with {1,2,3,4,5,9}, // {1,2,3,4,6,8} or {1,2,3,5,6,7} on their sides, they each // have a mean of 24/6=4. // // 2) // 10 // // Returns: 863010 // // // // 3) // 50 // // Returns: 375588112 // // // // END CUT HERE #line 73 "CustomDice.cc" #include <string> #include <vector> #include <iostream> #include <sstream> #include <algorithm> #include <numeric> #include <functional> #include <map> #include <set> #include <cassert> #include <list> #include <deque> #include <iomanip> #include <cstring> #include <cmath> #include <cstdio> #include <cctype> using namespace std; #define fi(n) for(int i=0;i<(n);i++) #define fj(n) for(int j=0;j<(n);j++) #define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++) #define MOD 1000000007 typedef vector <int> VI; typedef vector <string> VS; typedef vector <VI> VVI; typedef long long ll; map<pair<int,int>, ll > memo[6]; int sum[] = { 0, 0, 1, 3, 6 , 10, 15, 21 }; ll go(int pos, int count, int less) { if (pos == 0) { if (count < less) return 1; return 0; } pair<int,int> t(count,less); if (memo[pos].count(t) > 0) return memo[pos][t]; int cu = count; int pr = pos; if (count >= less) { cu = less - 1; pr = pos + (count - cu); } ll &ret = memo[pos][t]; ret = 0; while (pos * cu > pr + sum[pos]) { ret = (ret + go(pos - 1, pr, cu)) % MOD; ++pr; --cu; } return ret; } class CustomDice { public: int countDice(int M) { int ma = 6 * M - 15; if (ma < 6) return 0; fi(6) memo[i].clear(); ll ret = 0; for(int i = 6; i <= ma; ++i) { ret = (ret + go(5, i, i + 1)) % MOD; } return (ret * 30) % MOD; } // 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(); } 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 int &Expected, const int &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 = 3; int Arg1 = 0; verify_case(0, Arg1, countDice(Arg0)); } void test_case_1() { int Arg0 = 4; int Arg1 = 210; verify_case(1, Arg1, countDice(Arg0)); } void test_case_2() { int Arg0 = 10; int Arg1 = 863010; verify_case(2, Arg1, countDice(Arg0)); } void test_case_3() { int Arg0 = 50; int Arg1 = 375588112; verify_case(3, Arg1, countDice(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CustomDice ___test; ___test.run_test(-1); } // END CUT HERE
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <queue> #include <set> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x),next(NULL){} }; void printLL(ListNode* head){ ListNode* temp = head; while(temp!=NULL){ cout<<temp->val<<"->"; temp = temp->next; } } ListNode* addNode(ListNode* head, int val){ if(head==NULL){ head = new ListNode(val); } else{ ListNode* temp = head; while(temp->next!=NULL){ temp = temp->next; } temp->next = new ListNode(val); } return head; } void print(vector<int>&v){ int n = v.size(); for(int i =0;i<n;i++){ cout<<v[i]<<" "; } } ListNode* RemoveDuplicate(ListNode* head){ ListNode* temp = head; vector<int> v; while(temp!=NULL){ int flag = 0; if(v.empty()){ v.push_back(temp->val); } else if(!v.empty()){ if(v[v.size()-1]!=temp->val){ v.push_back(temp->val); } else if(v[v.size()-1]==temp->val){ flag = 1; while(temp!=NULL&&v[v.size()-1]==temp->val){ temp = temp->next; } if(v.size()){ v.pop_back(); } } } if(flag==0){ temp = temp->next; } } // cout<<v.size()<<endl; ListNode* curr = head; if(v.size()){ curr->val = v[0]; for(int i =1;i<v.size();i++){ ListNode* t = (ListNode*)malloc(sizeof(ListNode)); t->val = v[i]; // cout<<v[i]<<endl; curr->next = t; curr = t; } curr->next = NULL; } else{ head = NULL; } return head; } int main(){ ListNode *head = NULL; // = new ListNode(); int n; cin>>n; for(int i =0;i<n;i++){ int val; cin>>val; head = addNode(head,val); } // printLL(head); head = RemoveDuplicate(head); printLL(head); }
#pragma once #include <PA9.h> class Palette{ private: u8 m_screen; void *m_data; u8 m_id; public: Palette(); Palette(u8 screen, void *paletteData); ~Palette(); void Set(u8 screen, void *paletteData); u8 Screen()const; void * PaletteData()const; u8 Id()const; bool Load(); bool Unload(); };
// Created on: 1997-07-28 // Created by: Pierre CHALAMET // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 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 _Graphic3d_TextureMap_HeaderFile #define _Graphic3d_TextureMap_HeaderFile #include <Graphic3d_TextureRoot.hxx> #include <Graphic3d_TypeOfTexture.hxx> #include <Graphic3d_LevelOfTextureAnisotropy.hxx> class TCollection_AsciiString; //! This is an abstract class for managing texture applyable on polygons. class Graphic3d_TextureMap : public Graphic3d_TextureRoot { DEFINE_STANDARD_RTTIEXT(Graphic3d_TextureMap, Graphic3d_TextureRoot) public: //! enable texture smoothing Standard_EXPORT void EnableSmooth(); //! Returns TRUE if the texture is smoothed. Standard_EXPORT Standard_Boolean IsSmoothed() const; //! disable texture smoothing Standard_EXPORT void DisableSmooth(); //! enable texture modulate mode. //! the image is modulate with the shading of the surface. Standard_EXPORT void EnableModulate(); //! disable texture modulate mode. //! the image is directly decal on the surface. Standard_EXPORT void DisableModulate(); //! Returns TRUE if the texture is modulate. Standard_EXPORT Standard_Boolean IsModulate() const; //! use this methods if you want to enable //! texture repetition on your objects. Standard_EXPORT void EnableRepeat(); //! use this methods if you want to disable //! texture repetition on your objects. Standard_EXPORT void DisableRepeat(); //! Returns TRUE if the texture repeat is enable. Standard_EXPORT Standard_Boolean IsRepeat() const; //! @return level of anisotropy texture filter. //! Default value is Graphic3d_LOTA_OFF. Standard_EXPORT Graphic3d_LevelOfTextureAnisotropy AnisoFilter() const; //! @param theLevel level of anisotropy texture filter. Standard_EXPORT void SetAnisoFilter (const Graphic3d_LevelOfTextureAnisotropy theLevel); protected: Standard_EXPORT Graphic3d_TextureMap(const TCollection_AsciiString& theFileName, const Graphic3d_TypeOfTexture theType); Standard_EXPORT Graphic3d_TextureMap(const Handle(Image_PixMap)& thePixMap, const Graphic3d_TypeOfTexture theType); }; DEFINE_STANDARD_HANDLE(Graphic3d_TextureMap, Graphic3d_TextureRoot) #endif // _Graphic3d_TextureMap_HeaderFile
#ifndef PLAYER_H #define PLAYER_H #include <QObject> #include <QString> #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QJsonParseError> #include <QVariantMap> #include <QVariantList> #include <QList> #include <QFile> #include "cards/card.h" #include "cards/deck.h" class MyTCPSocket; class Battle; class Player : public QObject { Q_OBJECT public: explicit Player(MyTCPSocket *client_, const QString &Alldata, QObject *parent = nullptr); ~Player(); MyTCPSocket *client; QString get_name()const; int get_totalgames()const; int get_victorygames()const; int get_drawgames()const; int get_defeatgames()const; int get_nextdeckname(); Battle* get_battle(); void wingame(); void losegame(); void drawgame(); QList<Card*>* get_cardlist(QString); bool update_deck(QString name, Card* leader, QList<Card*> *cardlist); QList<Deck*>& get_decks(); QList<Deck*>* get_decks_pointer(); void writetofile(); void battleover(); void startbattle(Battle*); signals: public slots: private: QString name; int totalgames, victorygames, drawgames, defeatgames; QList<Deck*> decks; int name_helper; Battle *battle; }; /* class Player : public QObject { Q_OBJECT public: explicit Player(MyTCPSocket *client_, QString Alldata, QObject *parent = nullptr); ~Player(); MyTCPSocket *client; QString name; signals: public slots: private: int totalgames, victorygames, drawgames,defeatgames; QList<Deck*> decks; };*/ #endif // PLAYER_H
#include <iostream> #include <istream> #include <fstream> #include <string> #include <vector> enum class CSVState { UnquotedField, QuotedField, QuotedQuote }; typedef std::vector<std::string> row_t; typedef std::vector<row_t> table_t; row_t readCSVRow(const std::string &row) { CSVState state = CSVState::UnquotedField; row_t fields {""}; size_t i = 0; // index of the current field for (char c : row) { switch (state) { case CSVState::UnquotedField: switch (c) { case ',': // end of field fields.push_back(""); i++; break; case '"': state = CSVState::QuotedField; break; default: fields[i].push_back(c); break; } break; case CSVState::QuotedField: switch (c) { case '"': state = CSVState::QuotedQuote; break; default: fields[i].push_back(c); break; } break; case CSVState::QuotedQuote: switch (c) { case ',': // , after closing quote fields.push_back(""); i++; state = CSVState::UnquotedField; break; case '"': // "" -> " fields[i].push_back('"'); state = CSVState::QuotedField; break; default: // end of quote state = CSVState::UnquotedField; break; } break; } } return fields; } /// Read CSV file, Excel dialect. Accept "quoted fields ""with quotes""" table_t readCSV(std::istream &in) { table_t table; std::string row; while (!in.eof()) { std::getline(in, row); if (in.bad() || in.fail()) { break; } auto fields = readCSVRow(row); table.push_back(fields); } return table; } void dump_table(const table_t& table) { int col, row = 0; for(row_t fields : table) { col = 0; for(std::string cell : fields) { std::cout << "(" << row << "," << col << "): " << cell << std::endl; col++; } row++; } } int main(int argc, char* argv[]) { std::filebuf fb; if(fb.open(argv[argc-1], std::ios::in)) { std::istream csv_in(&fb); table_t parsed = readCSV(csv_in); fb.close(); dump_table(parsed); } return 0; }
// cpu_vector.h // Ben Gamari // August 2009 #ifndef _CPU_VECTOR_H #define _CPU_VECTOR_H #include <malloc-stub.h> #include <stdlib.h> #include <string.h> #include "su3.h" #include "terminate.h" #include "generic_vector.h" #include "detail/template_vector_cpu.h" #include "complex.h" namespace qcd { template <typename T, int length_factor=1> struct cpu_buffer { typedef T TElement; typedef T* iterator; int length; TElement* data; cpu_buffer(int length) : length(length) { this->data = (TElement*) memalign(16, length_factor*length*sizeof(TElement)); if (this->data == NULL) { terminate_error(ERROR_MEMORY_ALLOCATION); exit(ERROR_MEMORY_ALLOCATION); } } ~cpu_buffer() { free(this->data); } void clear() { memset(data, 0, length_factor*length*sizeof(TElement)); } }; struct vector : generic_vector<cpu_buffer<wilson_vector> >, qcd::cpu::VectorCpu<double_complex> { vector(lattice_desc* desc, bool dirty=false) : generic_vector<cpu_buffer<wilson_vector> >(desc, desc->sites_on_node, dirty), qcd::cpu::VectorCpu<double_complex>(12*desc->sites_on_node, reinterpret_cast<double_complex*>(this->data)) {} using qcd::cpu::VectorCpu<double_complex>::operator = ; // this assignement operator masks the one from generic_vector vector& operator = (const vector& v) { qcd::cpu::VectorCpu<double_complex>::operator = (v); return *this;} private: vector(const vector&); }; struct chiralvector : generic_vector<cpu_buffer<su3_vector, 2> >, qcd::cpu::VectorCpu<double_complex> { chiralvector(lattice_desc* desc, bool dirty=false) : generic_vector<cpu_buffer<su3_vector, 2> >(desc, desc->sites_on_node, dirty), qcd::cpu::VectorCpu<double_complex>(6*desc->sites_on_node, reinterpret_cast<double_complex*>(this->data)) {} using qcd::cpu::VectorCpu<double_complex>::operator = ; // this assignement operator masks the one from generic_vector chiralvector& operator = (const chiralvector& v) { qcd::cpu::VectorCpu<double_complex>::operator = (v); return *this;} private: chiralvector(const chiralvector&); }; struct su3_field : generic_vector<cpu_buffer<su3_matrix, 4> > { su3_field(lattice_desc* desc, bool dirty=false) : generic_vector<cpu_buffer<su3_matrix, 4> >(desc, desc->sites_on_node, dirty) { } }; struct su3_matrix_field : generic_vector<cpu_buffer<su3_matrix, 1> > { su3_matrix_field(lattice_desc* desc, bool dirty=false) : generic_vector<cpu_buffer<su3_matrix, 1> >(desc, desc->sites_on_node, dirty) { } }; } // qcd namespace #endif
bool isAllZeroes(vector<int>& A){ for(int i = 0; i<A.size(); i++) if(A[i]!=0) return false; return true; } bool isAllPos(vector<int>& A){ for(int i = 0; i<A.size(); i++) if(A[i]<=0) return false; return true; } bool isAllNeg(vector<int>& A){ for(int i = 0; i<A.size(); i++) if(A[i]>=0) return false; return true; } vector<vector<int> > Solution::threeSum(vector<int>& A) { set<vector<int>> res; if(A.size()<3 || isAllPos(A) || isAllNeg(A)){ vector<vector<int>> v; return v; } if(isAllZeroes(A)){ vector<int> tmp(3, 0); vector<vector<int>> v; v.push_back(tmp); return v; } sort(A.begin(), A.end()); int i = 0, sum; while(i<A.size()-2){ int left = i+1; int right = A.size()-1; while(left<right){ sum = A[i]+A[left]+A[right]; if(sum==0){ res.insert((vector<int>{A[i], A[left], A[right]})); } if(sum<0) left++; else right--; } i++; } vector<vector<int>>v(res.begin(), res.end()); return v; }
// 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. #pragma once #include <functional> #include <list> #include <Logging/LoggerRef.h> #include <System/ContextGroup.h> #include <System/Dispatcher.h> #include <System/Event.h> #include <System/TcpListener.h> #include <System/Timer.h> #include "IP2pNodeInternal.h" #include "IStreamSerializable.h" #include "NetNodeConfig.h" #include "P2pInterfaces.h" #include "P2pNodeConfig.h" #include "P2pProtocolDefinitions.h" #include "PeerListManager.h" namespace cn { class P2pContext; class P2pConnectionProxy; class P2pNode : public IP2pNode, public IStreamSerializable, IP2pNodeInternal { public: P2pNode( const P2pNodeConfig& cfg, platform_system::Dispatcher& dispatcher, logging::ILogger& log, const crypto::Hash& genesisHash, PeerIdType peerId); ~P2pNode(); // IP2pNode virtual std::unique_ptr<IP2pConnection> receiveConnection() override; virtual void stop() override; // IStreamSerializable virtual void save(std::ostream& os) override; virtual void load(std::istream& in) override; // P2pNode void start(); void serialize(ISerializer& s); private: typedef std::unique_ptr<P2pContext> ContextPtr; typedef std::list<ContextPtr> ContextList; logging::LoggerRef logger; bool m_stopRequested; const P2pNodeConfig m_cfg; const PeerIdType m_myPeerId; const crypto::Hash m_genesisHash; const CORE_SYNC_DATA m_genesisPayload; platform_system::Dispatcher& m_dispatcher; platform_system::ContextGroup workingContextGroup; platform_system::TcpListener m_listener; platform_system::Timer m_connectorTimer; PeerlistManager m_peerlist; ContextList m_contexts; platform_system::Event m_queueEvent; std::deque<std::unique_ptr<IP2pConnection>> m_connectionQueue; // IP2pNodeInternal virtual const CORE_SYNC_DATA& getGenesisPayload() const override; virtual std::list<PeerlistEntry> getLocalPeerList() const override; virtual basic_node_data getNodeData() const override; virtual PeerIdType getPeerId() const override; virtual void handleNodeData(const basic_node_data& node, P2pContext& ctx) override; virtual bool handleRemotePeerList(const std::list<PeerlistEntry>& peerlist, time_t local_time) override; virtual void tryPing(P2pContext& ctx) override; // spawns void acceptLoop(); void connectorLoop(); // connection related void connectPeers(); void connectPeerList(const std::vector<NetworkAddress>& peers); bool isPeerConnected(const NetworkAddress& address); bool isPeerUsed(const PeerlistEntry& peer); ContextPtr tryToConnectPeer(const NetworkAddress& address); bool fetchPeerList(ContextPtr connection); // making and processing connections size_t getOutgoingConnectionsCount() const; void makeExpectedConnectionsCount(const PeerlistManager::Peerlist& peerlist, size_t connectionsCount); bool makeNewConnectionFromPeerlist(const PeerlistManager::Peerlist& peerlist); void preprocessIncomingConnection(ContextPtr ctx); void enqueueConnection(std::unique_ptr<P2pConnectionProxy> proxy); std::unique_ptr<P2pConnectionProxy> createProxy(ContextPtr ctx); }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef TIPS_NOTIFICATIONBAR_H #define TIPS_NOTIFICATIONBAR_H class OpWidget; #include "adjunct/quick_toolkit/widgets/OpToolbar.h" class TipsNotificationBar : public OpToolbar { protected: TipsNotificationBar(); virtual ~TipsNotificationBar(); public: static OP_STATUS Construct(TipsNotificationBar** obj, OpWidget *parent); OP_STATUS SetTips(const OpString &tip); OP_STATUS SetInfoImage(const char *image_name); //OpToolbar virtual void OnSettingsChanged(DesktopSettings* settings) { } virtual BOOL OnInputAction(OpInputAction* action); }; #endif // TIPS_NOTIFICATIONBAR_H
#include "caffe2/operators/locally_connected_op_util.h" namespace caffe2 { namespace lc_op_util { void SetColumnBufferShapeImpl( const int N, const int kernel_dim, const StorageOrder order, const std::vector<int>& output_image_dims, std::vector<int>* column_dims, std::vector<int>* column_transposed_dims, std::vector<int>* column_axes, std::vector<int>* column_transposed_axes) { const int n_column_dims = output_image_dims.size() + 2; column_dims->resize(n_column_dims); column_transposed_dims->resize(n_column_dims); column_axes->resize(n_column_dims); if (order == StorageOrder::NCHW) { for (int i = 0; i < n_column_dims - 2; ++i) { column_dims->at(i + 2) = output_image_dims[i]; column_transposed_dims->at(i) = output_image_dims[i]; column_axes->at(i) = i + 2; } column_dims->at(0) = N; column_dims->at(1) = kernel_dim; column_transposed_dims->at(n_column_dims - 2) = kernel_dim; column_transposed_dims->at(n_column_dims - 1) = N; column_axes->at(n_column_dims - 1) = 0; column_axes->at(n_column_dims - 2) = 1; } else { for (int i = 0; i < n_column_dims - 2; ++i) { column_dims->at(i + 1) = output_image_dims[i]; column_transposed_dims->at(i) = output_image_dims[i]; column_axes->at(i) = i + 1; } column_dims->at(0) = N; column_dims->at(n_column_dims - 1) = kernel_dim; column_transposed_dims->at(n_column_dims - 2) = N; column_transposed_dims->at(n_column_dims - 1) = kernel_dim; column_axes->at(n_column_dims - 2) = 0; column_axes->at(n_column_dims - 1) = n_column_dims - 1; } if (column_transposed_axes != nullptr) { column_transposed_axes->resize(n_column_dims); for (int i = 0; i < n_column_dims; ++i) { column_transposed_axes->at(column_axes->at(i)) = i; } } } } // namespace lc_op_util } // namespace caffe2
// // SplashScreen.hpp for SplashScreen.hpp in /home/deneub_s/cpp_indie_studio // // Made by Stanislas Deneubourg // Login <deneub_s@epitech.net> // // Started on Wed May 3 18:56:42 2017 Stanislas Deneubourg // Last update Wed May 31 14:37:58 2017 Stanislas Deneubourg // #ifndef SPLASH_SCREEN_HPP__ #define SPLASH_SCREEN_HPP__ #include "Interface/IModel.hpp" class SplashScreen : public IModel { private: irr::scene::ISceneManager *smgr; irr::video::IVideoDriver *driver; irr::IrrlichtDevice *device; irr::u32 lastFrame; irr::video::ITexture *irrlichtLogo; irr::video::ITexture *irrklangLogo; irr::gui::IGUIFont *font; public: SplashScreen(irr::scene::ISceneManager *smgr, irr::video::IVideoDriver *driver, irr::IrrlichtDevice *device); virtual ~SplashScreen(); virtual EventStatus launchModel(); virtual void setModelProperties(); }; #endif
/* * StorageManagerMCB.cpp * File implementing the class that manages SD storage * Author: Alex St. Clair * March 2018 * * Note: this class is implemented so that it can be used across multiple * instances. This means that all data members MUST be static. */ #include "StorageManagerMCB.h" bool StorageManagerMCB::sd_state = false; uint32_t StorageManagerMCB::boot_number = 0; String StorageManagerMCB::base_directory = ""; Log_Data_Info_t StorageManagerMCB::log_data_info[NUM_LOG_DATA] = { // num_writes | max_writes | num_files | file_prefix { 0 , 100 , 0 , "VMON_" }, // VMON_DATA { 0 , 100 , 0 , "IMON_" }, // IMON_DATA { 0 , 100 , 0 , "TEMP_" }, // TEMP_DATA { 0 , 20 , 0 , "ERR_" }, // ERR_DATA { 0 , 100 , 0 , "MOT_" } // MOTION_DATA }; // TODO: add timestamp to writes // Methods for SD logging ----------------------------------------------------- bool StorageManagerMCB::LogSD(uint8_t * log_data, int data_size, Log_Data_Type_t data_type) { if (!sd_state) { return false; } // TODO: implement binary data return false; } /* Will print ERR_DATA messages to the DEBUG_SERIAL terminal if PRINT_ERRORS is defined */ bool StorageManagerMCB::LogSD(String log_data, Log_Data_Type_t data_type) { if (data_type < 0 || data_type >= NUM_LOG_DATA) return false; String filename = base_directory + "/"; filename += log_data_info[data_type].file_prefix; filename += log_data_info[data_type].num_files; filename += ".txt"; #ifdef PRINT_ERRORS if (data_type == ERR_DATA) { Serial.println(log_data.c_str()); } #endif if (!sd_state) { return false; } file = SD.open(filename.c_str(), FILE_WRITE); if (!file) { Serial.println("Error opening log file"); return false; } log_data += "\n"; String final_log = String((float) millis() / 1000.0f); final_log += ','; final_log += log_data; uint16_t bytes_written = 0; uint16_t write_size = final_log.length(); bytes_written = file.write(final_log.c_str(), write_size); file.close(); // check if the next write should be to a new file if (++(log_data_info[data_type].num_writes) == log_data_info[data_type].max_writes) { log_data_info[data_type].num_writes = 0; log_data_info[data_type].num_files += 1; } return (bytes_written == write_size); } // Basic SD methods ----------------------------------------------------------- bool StorageManagerMCB::StartSD(uint32_t boot_num) { boot_number = boot_num; if (!sd_state) { if (!SD.begin(BUILTIN_SDCARD)) { Serial.println("Unable to start SD card"); sd_state = false; } else { Serial.println("Successfully started SD card"); sd_state = true; } } if (sd_state) { if (ConfigureDirectories()) { Serial.println("Created base directory for boot"); } else { Serial.println("Error creating base directory"); sd_state = false; } } return sd_state; } bool StorageManagerMCB::ConfigureDirectories(void) { if (!SD.exists(LOG_DATA_DIR)) { Serial.println("Making log data directory"); if (!SD.mkdir(LOG_DATA_DIR)) { Serial.println("ERR: unable to make log data directory"); return false; } } if (!SD.exists(FSW_DIR)) { Serial.println("Making FSW directory"); if (!SD.mkdir(FSW_DIR)) { Serial.println("ERR: unable to make FSW directory"); return false; } } base_directory = LOG_DATA_DIR "boot"; base_directory += String(boot_number); return SD.mkdir(base_directory.c_str()); } bool StorageManagerMCB::CheckSD(void) { return sd_state; } bool StorageManagerMCB::RemoveFile(const char * filename) { return (sd_state && SD.remove(filename)); } bool StorageManagerMCB::FileExists(const char * filename) { return (sd_state && SD.exists(filename)); } bool StorageManagerMCB::FileWrite(const char * filename, uint8_t * buffer, uint16_t write_size, bool seek_end, uint16_t position) { if (!sd_state) { return false; } file = SD.open(filename, FILE_WRITE); if (!file) { return false; } uint16_t bytes_written = 0; if (!seek_end) { file.seek(position); } bytes_written = file.write(buffer, write_size); file.close(); return (bytes_written == write_size); } uint16_t StorageManagerMCB::FileRead(const char * filename, uint8_t * buffer, uint16_t read_size, uint16_t position) { uint16_t bytes_read = 0; if (!sd_state) { return bytes_read; } file = SD.open(filename); if (file) { file.seek(position); bytes_read = file.read(buffer, read_size); file.close(); } return bytes_read; } // Serialization methods ------------------------------------------------------ bool StorageManagerMCB::WriteSD_int32(const char * filename, const int32_t val, bool seek_end, uint16_t position) { uint8_t buf[4] = {0, 0, 0, 0}; buf[0] = (uint8_t) (val >> 24); buf[1] = (uint8_t) (val >> 16); buf[2] = (uint8_t) (val >> 8); buf[3] = (uint8_t) (val); return FileWrite(filename, buf, 4, seek_end, position); } bool StorageManagerMCB::WriteSD_uint32(const char * filename, const uint32_t val, bool seek_end, uint16_t position) { uint8_t buf[4] = {0, 0, 0, 0}; buf[0] = (uint8_t) (val >> 24); buf[1] = (uint8_t) (val >> 16); buf[2] = (uint8_t) (val >> 8); buf[3] = (uint8_t) (val); return FileWrite(filename, buf, 4, seek_end, position); } bool StorageManagerMCB::ReadSD_int32(const char * filename, int32_t * result, uint16_t position) { uint8_t buf[4] = {0, 0, 0, 0}; if (FileRead(filename, buf, 4, position) == 4) { *result = ((int32_t) buf[0] << 24) | ((int32_t) buf[1] << 16) | ((int32_t) buf[2] << 8) | (int32_t) buf[3]; return true; } else { return false; } } bool StorageManagerMCB::ReadSD_uint32(const char * filename, uint32_t * result, uint16_t position) { uint8_t buf[4] = {0, 0, 0, 0}; if (FileRead(filename, buf, 4, position) == 4) { *result = ((uint32_t) buf[0] << 24) | ((uint32_t) buf[1] << 16) | ((uint32_t) buf[2] << 8) | (uint32_t) buf[3]; return true; } else { return false; } }
#ifndef CALCULATOR_H //์กฐ๊ฑด ์ปดํŒŒ์ผ๋ฌธ #define CALCULATOR_H //์กฐ๊ฑด ์ปดํŒŒ์ผ๋ฌธ class Calculator { public: //์™ธ๋ถ€์—์„œ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋„๋ก ํ•จ int x, y; //run()์—์„œ ๋‘ ๊ฐœ์˜ ์ •์ˆ˜๋ฅผ ์ž…๋ ฅ๋ฐ›๊ณ  ๋‹ค๋ฅธ ํŒŒ์ผ์—์„œ๋„ ์‚ฌ์šฉ๊ฐ€๋Šฅํ•˜๋„๋ก ์ €์žฅํ•  ๋ณ€์ˆ˜ void run(); //Calculator.cpp์—์„œ ๊ตฌํ˜„๋˜์–ด ์žˆ๋Š” ๊ณ„์‚ฐ๊ธฐ ์‹คํ–‰ํ•จ์ˆ˜ ์„ ์–ธ }; #endif //์กฐ๊ฑด ์ปดํŒŒ์ผ๋ฌธ Calculator.h๋ฅผ ์—ฌ๋Ÿฌ๋ฒˆ includeํ•ด๋„ ๋ฌธ์ œ ์—†๊ฒŒ ํ•˜๊ธฐ ์œ„ํ•จ
#ifdef USES_P066 //####################################################################################################### //#################################### Plugin 066: VEML6040 RGBW ############################## //####################################################################################################### // ESPEasy Plugin to scan color values (RGBW) with chip VEML6040 // written by Jochen Krapf (jk@nerd2nerd.org) // Datasheet: https://www.vishay.com/docs/84276/veml6040.pdf // Application Note: www.vishay.com/doc?84331 #define PLUGIN_066 #define PLUGIN_ID_066 66 #define PLUGIN_NAME_066 "Color - VEML6040 [TESTING]" #define PLUGIN_VALUENAME1_066 "R" #define PLUGIN_VALUENAME2_066 "G" #define PLUGIN_VALUENAME3_066 "B" #define PLUGIN_VALUENAME4_066 "W" #define VEML6040_ADDR 0x10 // #include <*.h> // no include needed #include <math.h> // no include needed boolean Plugin_066(byte function, struct EventStruct *event, String& string) { boolean success = false; switch (function) { case PLUGIN_DEVICE_ADD: { Device[++deviceCount].Number = PLUGIN_ID_066; Device[deviceCount].Type = DEVICE_TYPE_I2C; Device[deviceCount].Ports = 0; Device[deviceCount].VType = SENSOR_TYPE_QUAD; Device[deviceCount].PullUpOption = false; Device[deviceCount].InverseLogicOption = false; Device[deviceCount].FormulaOption = true; Device[deviceCount].ValueCount = 4; Device[deviceCount].SendDataOption = true; Device[deviceCount].TimerOption = true; Device[deviceCount].TimerOptional = false; Device[deviceCount].GlobalSyncOption = true; break; } case PLUGIN_GET_DEVICENAME: { string = F(PLUGIN_NAME_066); break; } case PLUGIN_GET_DEVICEVALUENAMES: { strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[0], PSTR(PLUGIN_VALUENAME1_066)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[1], PSTR(PLUGIN_VALUENAME2_066)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[2], PSTR(PLUGIN_VALUENAME3_066)); strcpy_P(ExtraTaskSettings.TaskDeviceValueNames[3], PSTR(PLUGIN_VALUENAME4_066)); break; } case PLUGIN_WEBFORM_LOAD: { int optionValues[1] = { VEML6040_ADDR }; addFormSelectorI2C(F("i2c_addr"), 1, optionValues, VEML6040_ADDR); //Only for display I2C address String optionsMode[6] = { F("40ms (16496)"), F("80ms (8248)"), F("160ms (4124)"), F("320ms (2062)"), F("640ms (1031)"), F("1280ms (515)") }; addFormSelector(F("Integration Time (Max Lux)"), F("itime"), 6, optionsMode, NULL, PCONFIG(1)); String optionsVarMap[6] = { F("R, G, B, W"), F("r, g, b, W - relative rgb [&#37;]"), F("r, g, b, W - relative rgb^Gamma [&#37;]"), F("R, G, B, Color Temperature [K]"), F("R, G, B, Ambient Light [Lux]"), F("Color Temperature [K], Ambient Light [Lux], Y, W") }; addFormSelector(F("Value Mapping"), F("map"), 6, optionsVarMap, NULL, PCONFIG(2)); success = true; break; } case PLUGIN_WEBFORM_SAVE: { //PCONFIG(0) = getFormItemInt(F("i2c_addr")); PCONFIG(1) = getFormItemInt(F("itime")); PCONFIG(2) = getFormItemInt(F("map")); success = true; break; } case PLUGIN_INIT: { VEML6040_Init(PCONFIG(1)); success = true; break; } case PLUGIN_READ: { float R, G, B, W; R = VEML6040_GetValue(0x08); G = VEML6040_GetValue(0x09); B = VEML6040_GetValue(0x0A); W = VEML6040_GetValue(0x0B); switch (PCONFIG(2)) { default: case 0: { UserVar[event->BaseVarIndex + 0] = R; UserVar[event->BaseVarIndex + 1] = G; UserVar[event->BaseVarIndex + 2] = B; UserVar[event->BaseVarIndex + 3] = W; break; } case 1: { UserVar[event->BaseVarIndex + 0] = Plugin_066_CalcRelW(R, W) * 100.0; UserVar[event->BaseVarIndex + 1] = Plugin_066_CalcRelW(G, W) * 100.0; UserVar[event->BaseVarIndex + 2] = Plugin_066_CalcRelW(B, W) * 100.0; UserVar[event->BaseVarIndex + 3] = W; break; } case 2: { UserVar[event->BaseVarIndex + 0] = pow(Plugin_066_CalcRelW(R, W), 0.4545) * 100.0; UserVar[event->BaseVarIndex + 1] = pow(Plugin_066_CalcRelW(G, W), 0.4545) * 100.0; UserVar[event->BaseVarIndex + 2] = pow(Plugin_066_CalcRelW(B, W), 0.4545) * 100.0; UserVar[event->BaseVarIndex + 3] = W; break; } case 3: { UserVar[event->BaseVarIndex + 0] = R; UserVar[event->BaseVarIndex + 1] = G; UserVar[event->BaseVarIndex + 2] = B; UserVar[event->BaseVarIndex + 3] = Plugin_066_CalcCCT(R, G, B); break; } case 4: { UserVar[event->BaseVarIndex + 0] = R; UserVar[event->BaseVarIndex + 1] = G; UserVar[event->BaseVarIndex + 2] = B; UserVar[event->BaseVarIndex + 3] = Plugin_066_CalcAmbientLight(G, PCONFIG(1)); break; } case 5: { UserVar[event->BaseVarIndex + 0] = Plugin_066_CalcCCT(R, G, B); UserVar[event->BaseVarIndex + 1] = Plugin_066_CalcAmbientLight(G, PCONFIG(1)); UserVar[event->BaseVarIndex + 2] = (R + G + B) / 3.0; //0.299*R + 0.587*G + 0.114*B; UserVar[event->BaseVarIndex + 3] = W; break; } } success = true; break; } } return success; } // VEML6040 ///////////////////////////////////////////////////////////// void VEML6040_setControlReg(byte data) { Wire.beginTransmission(VEML6040_ADDR); Wire.write(0); //command 0=control register Wire.write(data); //lsb Wire.write(0); //msb Wire.endTransmission(); } float VEML6040_GetValue(byte reg) { Wire.beginTransmission(VEML6040_ADDR); Wire.write(reg); Wire.endTransmission(false); Wire.requestFrom((uint8_t)VEML6040_ADDR, (uint8_t)0x2); if (Wire.available() == 2) { uint16_t lsb = Wire.read(); uint16_t msb = Wire.read(); return (float)((msb << 8) | lsb); } return -1.0; } void VEML6040_Init(byte it) { VEML6040_setControlReg(it << 4); // IT=it, TRIG=0, AF=0, SD=0 } float Plugin_066_CalcCCT(float R, float G, float B) { if (G == 0) return 0; float CCTi = (R - B) / G + 0.5; float CCT = 4278.6 * pow(CCTi, -1.2455); return CCT; } float Plugin_066_CalcAmbientLight(float G, byte it) { float Sensitivity[6] = { 0.25168, 0.12584, 0.06292, 0.03146, 0.01573, 0.007865 }; return G * Sensitivity[it]; } float Plugin_066_CalcRelW(float X, float W) { if (W == 0) return 0; return X / W; } #endif // USES_P066
// Created on: 1993-03-24 // Created by: JCV // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 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 _Geom2d_Point_HeaderFile #define _Geom2d_Point_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Geom2d_Geometry.hxx> #include <Standard_Real.hxx> class gp_Pnt2d; class Geom2d_Point; DEFINE_STANDARD_HANDLE(Geom2d_Point, Geom2d_Geometry) //! The abstract class Point describes the common //! behavior of geometric points in 2D space. //! The Geom2d package also provides the concrete //! class Geom2d_CartesianPoint. class Geom2d_Point : public Geom2d_Geometry { public: //! returns the Coordinates of <me>. Standard_EXPORT virtual void Coord (Standard_Real& X, Standard_Real& Y) const = 0; //! returns a non persistent copy of <me> Standard_EXPORT virtual gp_Pnt2d Pnt2d() const = 0; //! returns the X coordinate of <me>. Standard_EXPORT virtual Standard_Real X() const = 0; //! returns the Y coordinate of <me>. Standard_EXPORT virtual Standard_Real Y() const = 0; //! computes the distance between <me> and <Other>. Standard_EXPORT Standard_Real Distance (const Handle(Geom2d_Point)& Other) const; //! computes the square distance between <me> and <Other>. Standard_EXPORT Standard_Real SquareDistance (const Handle(Geom2d_Point)& Other) const; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(Geom2d_Point,Geom2d_Geometry) protected: private: }; #endif // _Geom2d_Point_HeaderFile
#include <iostream> #include <cmath> #define FOR(i,s,e) for(int (i)=(s); (i)<(e);(i)++) using namespace std; inline void SWAP(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int t, res; int x1,y1,r1; int x2,y2,r2; double d; cin >> t; FOR(i,0,t) { cin >> x1 >> y1 >> r1; cin >> x2 >> y2 >> r2; if (r1 > r2) { SWAP(&r1, &r2); } d = sqrt(pow((x1-x2), 2) + pow((y1-y2), 2)); if (d <= r2) { // ๋™์ผ์› if (x1 == x2 && y1 == y2 && r1 == r2) res = -1; // ํ•œ ์  else if (r1 + d == r2) res = 1; // ๋‘ ์  else if (r1 + d > r2) res = 2; // ๋งŒ๋‚˜์ง€ ์•Š์Œ else if (r1 + d < r2) res = 0; } else { // ๋งŒ๋‚˜์ง€ ์•Š์Œ if (r1 + r2 < d) res = 0; // ๋‘ ์  else if (r1 + r2 > d) res = 2; // ํ•œ ์  else if (r1 + r2 == d) res = 1; } cout << res << '\n'; } return 0; }
#include <iostream> #include <cstdlib> struct mult_div_table{ int product; float dividend; }; void check(int * rows, int * cols); mult_div_table** create_table(int rows, int cols); void populate_table(mult_div_table** table, int rows, int cols); void print_table(mult_div_table** table, int rows, int cols); void delete_table(mult_div_table** table, int rows, int cols);
// Created on: 1995-08-02 // Created by: Arnaud BOUZY/Odile Olivier // Copyright (c) 1995-1999 Matra Datavision // Copyright (c) 1999-2014 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 _AIS_Plane_HeaderFile #define _AIS_Plane_HeaderFile #include <AIS_InteractiveObject.hxx> #include <AIS_TypeOfPlane.hxx> #include <gp_Pnt.hxx> #include <Select3D_TypeOfSensitivity.hxx> class Geom_Plane; class Geom_Axis2Placement; //! Constructs plane datums to be used in construction of //! composite shapes. class AIS_Plane : public AIS_InteractiveObject { DEFINE_STANDARD_RTTIEXT(AIS_Plane, AIS_InteractiveObject) public: //! initializes the plane aComponent. If //! the mode aCurrentMode equals true, the drawing //! tool, "Drawer" is not initialized. Standard_EXPORT AIS_Plane(const Handle(Geom_Plane)& aComponent, const Standard_Boolean aCurrentMode = Standard_False); //! initializes the plane aComponent and //! the point aCenter. If the mode aCurrentMode //! equals true, the drawing tool, "Drawer" is not //! initialized. aCurrentMode equals true, the drawing //! tool, "Drawer" is not initialized. Standard_EXPORT AIS_Plane(const Handle(Geom_Plane)& aComponent, const gp_Pnt& aCenter, const Standard_Boolean aCurrentMode = Standard_False); //! initializes the plane aComponent, the //! point aCenter, and the minimum and maximum //! points, aPmin and aPmax. If the mode //! aCurrentMode equals true, the drawing tool, "Drawer" is not initialized. Standard_EXPORT AIS_Plane(const Handle(Geom_Plane)& aComponent, const gp_Pnt& aCenter, const gp_Pnt& aPmin, const gp_Pnt& aPmax, const Standard_Boolean aCurrentMode = Standard_False); Standard_EXPORT AIS_Plane(const Handle(Geom_Axis2Placement)& aComponent, const AIS_TypeOfPlane aPlaneType, const Standard_Boolean aCurrentMode = Standard_False); //! Same value for x and y directions Standard_EXPORT void SetSize (const Standard_Real aValue); //! Sets the size defined by the length along the X axis //! XVal and the length along the Y axis YVal. Standard_EXPORT void SetSize (const Standard_Real Xval, const Standard_Real YVal); Standard_EXPORT void UnsetSize(); Standard_EXPORT Standard_Boolean Size (Standard_Real& X, Standard_Real& Y) const; Standard_Boolean HasOwnSize() const { return myHasOwnSize; } //! Sets transform persistence for zoom with value of minimum size Standard_EXPORT void SetMinimumSize (const Standard_Real theValue); //! Unsets transform persistence zoom Standard_EXPORT void UnsetMinimumSize(); //! Returns true if transform persistence for zoom is set Standard_EXPORT Standard_Boolean HasMinimumSize() const; virtual Standard_Integer Signature() const Standard_OVERRIDE { return 7; } virtual AIS_KindOfInteractive Type() const Standard_OVERRIDE { return AIS_KindOfInteractive_Datum; } //! Returns the component specified in SetComponent. const Handle(Geom_Plane)& Component() { return myComponent; } //! Creates an instance of the plane aComponent. Standard_EXPORT void SetComponent (const Handle(Geom_Plane)& aComponent); //! Returns the settings for the selected plane //! aComponent, provided in SetPlaneAttributes. //! These include the points aCenter, aPmin, and aPmax Standard_EXPORT Standard_Boolean PlaneAttributes (Handle(Geom_Plane)& aComponent, gp_Pnt& aCenter, gp_Pnt& aPmin, gp_Pnt& aPmax); //! Allows you to provide settings other than default ones //! for the selected plane. These include: center point //! aCenter, maximum aPmax and minimum aPmin. Standard_EXPORT void SetPlaneAttributes (const Handle(Geom_Plane)& aComponent, const gp_Pnt& aCenter, const gp_Pnt& aPmin, const gp_Pnt& aPmax); //! Returns the coordinates of the center point. const gp_Pnt& Center() const { return myCenter; } //! Provides settings for the center theCenter other than (0, 0, 0). void SetCenter (const gp_Pnt& theCenter) { myCenter = theCenter; } //! Allows you to provide settings for the position and //! direction of one of the plane's axes, aComponent, in //! 3D space. The coordinate system used is //! right-handed, and the type of plane aPlaneType is one of: //! - AIS_ TOPL_Unknown //! - AIS_ TOPL_XYPlane //! - AIS_ TOPL_XZPlane //! - AIS_ TOPL_YZPlane}. Standard_EXPORT void SetAxis2Placement (const Handle(Geom_Axis2Placement)& aComponent, const AIS_TypeOfPlane aPlaneType); //! Returns the position of the plane's axis2 system //! identifying the x, y, or z axis and giving the plane a //! direction in 3D space. An axis2 system is a right-handed coordinate system. Standard_EXPORT Handle(Geom_Axis2Placement) Axis2Placement(); //! Returns the type of plane - xy, yz, xz or unknown. AIS_TypeOfPlane TypeOfPlane() { return myTypeOfPlane; } //! Returns the type of plane - xy, yz, or xz. Standard_Boolean IsXYZPlane() { return myIsXYZPlane; } //! Returns the non-default current display mode set by SetCurrentMode. Standard_Boolean CurrentMode() { return myCurrentMode; } //! Allows you to provide settings for a non-default //! current display mode. void SetCurrentMode (const Standard_Boolean theCurrentMode) { myCurrentMode = theCurrentMode; } //! Returns true if the display mode selected, aMode, is valid for planes. Standard_EXPORT virtual Standard_Boolean AcceptDisplayMode (const Standard_Integer aMode) const Standard_OVERRIDE; //! connection to <aCtx> default drawer implies a recomputation of Frame values. Standard_EXPORT virtual void SetContext (const Handle(AIS_InteractiveContext)& aCtx) Standard_OVERRIDE; //! Returns the type of sensitivity for the plane; Select3D_TypeOfSensitivity TypeOfSensitivity() const { return myTypeOfSensitivity; } //! Sets the type of sensitivity for the plane. void SetTypeOfSensitivity (Select3D_TypeOfSensitivity theTypeOfSensitivity) { myTypeOfSensitivity = theTypeOfSensitivity; } Standard_EXPORT virtual void ComputeSelection (const Handle(SelectMgr_Selection)& theSelection, const Standard_Integer theMode) Standard_OVERRIDE; Standard_EXPORT void SetColor (const Quantity_Color& aColor) Standard_OVERRIDE; Standard_EXPORT void UnsetColor() Standard_OVERRIDE; private: Standard_EXPORT virtual void Compute (const Handle(PrsMgr_PresentationManager)& thePrsMgr, const Handle(Prs3d_Presentation)& thePrs, const Standard_Integer theMode) Standard_OVERRIDE; Standard_EXPORT void ComputeFrame(); Standard_EXPORT void ComputeFields(); Standard_EXPORT void InitDrawerAttributes(); private: Handle(Geom_Plane) myComponent; Handle(Geom_Axis2Placement) myAx2; gp_Pnt myCenter; gp_Pnt myPmin; gp_Pnt myPmax; Standard_Boolean myCurrentMode; Standard_Boolean myAutomaticPosition; AIS_TypeOfPlane myTypeOfPlane; Standard_Boolean myIsXYZPlane; Standard_Boolean myHasOwnSize; Select3D_TypeOfSensitivity myTypeOfSensitivity; }; DEFINE_STANDARD_HANDLE(AIS_Plane, AIS_InteractiveObject) #endif // _AIS_Plane_HeaderFile
#include "max_flow.cpp" PyMODINIT_FUNC initmax_flow(void) { (void) Py_InitModule("max_flow", Methods); import_array(); }
// 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 "RpcServerConfig.h" #include "Common/CommandLine.h" #include "CryptoNoteConfig.h" namespace cn { namespace { const std::string DEFAULT_RPC_IP = "127.0.0.1"; const uint16_t DEFAULT_RPC_PORT = RPC_DEFAULT_PORT; const command_line::arg_descriptor<std::string> arg_rpc_bind_ip = { "rpc-bind-ip", "", DEFAULT_RPC_IP }; const command_line::arg_descriptor<uint16_t> arg_rpc_bind_port = { "rpc-bind-port", "", DEFAULT_RPC_PORT }; const command_line::arg_descriptor<std::string> arg_enable_cors = { "enable-cors", "Adds header 'Access-Control-Allow-Origin' to the daemon's RPC responses. Uses the value as domain. Use * for all", "" }; } RpcServerConfig::RpcServerConfig() : bindIp(DEFAULT_RPC_IP), bindPort(DEFAULT_RPC_PORT), enableCors("") { } std::string RpcServerConfig::getBindAddress() const { return bindIp + ":" + std::to_string(bindPort); } void RpcServerConfig::initOptions(boost::program_options::options_description& desc) { command_line::add_arg(desc, arg_rpc_bind_ip); command_line::add_arg(desc, arg_rpc_bind_port); command_line::add_arg(desc, arg_enable_cors); } void RpcServerConfig::init(const boost::program_options::variables_map &vm) { bool testnet = vm[command_line::arg_testnet_on.name].as<bool>(); bindIp = command_line::get_arg(vm, arg_rpc_bind_ip); bindPort = command_line::get_arg(vm, arg_rpc_bind_port); uint16_t argPort = command_line::get_arg(vm, arg_rpc_bind_port); bindPort = argPort; if (testnet) { bindPort = TESTNET_RPC_DEFAULT_PORT; if (!vm[arg_rpc_bind_port.name].defaulted()) { bindPort = argPort; } } enableCors = command_line::get_arg(vm, arg_enable_cors); } }
#include <Wire.h> #include "SparkFun_VEML6030_Ambient_Light_Sensor.h" #include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> #define LED_PIN 13 #define AL_ADDR 0x48 #define GAIN_SETTING .125 /* Possible values: .125; .25; 1 (unsafe); 2 (unsafe) */ #define INTEGRATION_MS_SETTING 800 /* Possible values: 25; 50; 100; 200; 400; 800; */ #define POLL_BACKOFF_MS 1000 /* how much to increase the poll duration when backing off */ #define POLL_DEFAULT_MS 1000 /* the default polling rate with zero backoff */ #define POLL_MAX_MS 10000 /* the maximum polling rate when fully backed-off */ #define POLL_FUZZ_LUX 10 /* the minimum cumulative change in lux before polling backoff resets */ #define MIN_LUX 80 #define MAX_LUX 120 #define LED_BEHAVIOR -1 /* 0: disabled; 1: flashes when unacceptable; -1: flashes when acceptable; */ #define BLE_SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914a" #define BLE_CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" SparkFun_Ambient_Light light(AL_ADDR); struct PollInfo { bool didLightChange; long pollDelay; }; long lastLuxVal = -2 * POLL_FUZZ_LUX; long lastPollDelay = POLL_DEFAULT_MS; BLEServer* pServer = NULL; BLECharacteristic* pCharacteristic = NULL; bool deviceConnected = false; bool oldDeviceConnected = false; uint32_t value = 0; enum DatapointProperty { DP_BEGIN_VERSION = 0x0, DP_LuxValue = 0x1, DP_MinLuxValue = 0x2, DP_MaxLuxValue = 0x3, DP_PollDuration = 0x4, DP_END_LENGTH = 0xFF }; class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { Serial.println("BLE device connected!"); deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { Serial.println("BLE device disconnected!"); deviceConnected = false; } }; void setup(){ pinMode(LED_PIN, OUTPUT); Wire.begin(); Serial.begin(115200); configureLightSensor(); configureBluetoothServer(); } void configureLightSensor() { if(light.begin()) Serial.println("Light sensor successfully enabled"); else Serial.println("ERROR: Light sensor not detected"); Serial.println("Reading settings..."); Serial.printf("Gain: %.3-5f\nIntegration Time: %-5d\n", light.readGain(), light.readIntegTime()); } void configureBluetoothServer() { BLEDevice::init("Light Monitor"); pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); BLEService *pService = pServer->createService(BLE_SERVICE_UUID); pCharacteristic = pService->createCharacteristic( BLE_CHARACTERISTIC_UUID, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_NOTIFY ); // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml pCharacteristic->addDescriptor(new BLE2902()); pService->start(); // Start advertising /* BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); pAdvertising->addServiceUUID(BLE_SERVICE_UUID); pAdvertising->setScanResponse(false); pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter */ BLEDevice::startAdvertising(); } void loop(){ long luxVal = light.readLight(); long savedLastPollDelay = lastPollDelay; struct PollInfo pollInfo = getPollDelay(luxVal); int luxAcceptability = isLuxValueAcceptable(luxVal); Serial.printf( "Ambient Light Reading:\n\t%-15s%s\n\t%-15s%d lux (%.2f foot-candles)\n\t%-15s%s\n\t%-15s%dms\n", "Status: ", luxAcceptability < 0 ? "TOO LOW" : luxAcceptability > 0 ? "TOO HIGH" : "OK", "Illuminance: ", luxVal, luxToFootCandles(luxVal), "Light changed: ", pollInfo.didLightChange ? "yes" : "no", "Next poll: ", pollInfo.pollDelay); // notify changed value if (deviceConnected) { serializeDatapoint(luxVal, MIN_LUX, MAX_LUX, savedLastPollDelay); } // disconnecting if (!deviceConnected && oldDeviceConnected) { delay(500); // give the bluetooth stack the chance to get things ready pServer->startAdvertising(); // restart advertising Serial.println("start advertising"); oldDeviceConnected = deviceConnected; } // connecting if (deviceConnected && !oldDeviceConnected) { // do stuff here on connecting oldDeviceConnected = deviceConnected; } delay(pollInfo.pollDelay); } float luxToFootCandles(long lux) { return lux / 10.7639 /* lux per footcandle */; } struct PollInfo getPollDelay(long luxValue) { long luxDelta = abs(lastLuxVal - luxValue); if (luxDelta > POLL_FUZZ_LUX) { lastLuxVal = luxValue; return ((struct PollInfo) {true, lastPollDelay = POLL_DEFAULT_MS}); } // don't set lastLuxVal, since that was the last measurement we really counted return ((struct PollInfo) {false, lastPollDelay = min<long>(lastPollDelay + POLL_BACKOFF_MS, POLL_MAX_MS) }); } int isLuxValueAcceptable(long luxValue) { int cmp = luxValue < MIN_LUX ? -1 : luxValue > MAX_LUX ? 1 : 0; int ledValue = cmp == 0 ? LED_BEHAVIOR == -1 ? HIGH : LOW : HIGH; digitalWrite(LED_PIN, ledValue); return cmp; } void serializeDatapoint(long luxValue, long minLuxValue, long maxLuxValue, long pollDuration) { long datapoints[][2] = { {(long)DP_BEGIN_VERSION, 0}, {(long)DP_LuxValue, luxValue}, {(long)DP_MinLuxValue, minLuxValue}, {(long)DP_MaxLuxValue, maxLuxValue}, {(long)DP_PollDuration, pollDuration}, {(long)DP_END_LENGTH, 4} }; for (int i = 0; i == 0 || datapoints[i-1][0] != DP_END_LENGTH; i++) { pCharacteristic->setValue((uint8_t*)(datapoints[i]), 2*sizeof(long)/(sizeof(uint8_t))); pCharacteristic->notify(); delay(10); } }
//-------------------------------------------------------- // CS 215 - Fall 2019 - Lab 8 //-------------------------------------------------------- // Author: Andrew Cassidy // Section: 401 // Function members for student class used in lab 8 //-------------------------------------------------------- #include"student.h" student::student() { // initialize name to empty string name = ""; // initialize all scores to zero for (int i = 0; i < MAX_SCORES; i++) scores[i] = 0; // initialize total scores to zero numScores = 0; // confirm constructor finished on object cout << "Constructed!\n"; } void student::setName(string newName) { name = newName; } string student::getName() { return name; } int student::GetNumScores() { return numScores; } void student::addScore(int newScore) { if (numScores == MAX_SCORES) cout << "MAX SCORES exceeded!\n"; else { scores[numScores] = newScore; numScores++; } } float student::getAvg() { if (numScores == 0) return 0.0; else { // add up the scores float total = 0; for (int i = 0; i < numScores; i++) total += scores[i]; // calc and return avg of all scores float avg = total / numScores; return avg; } } void student::print() { cout << "Name=" << name << " Avg=" << getAvg() << " #scores=" << numScores << " "; for (int i = 0; i < numScores; i++) cout << scores[i] << " "; cout << endl; }
#pragma once #include <gdiplus.h> class GdiplusInitializer { ULONG_PTR m_token; public: GdiplusInitializer() { Gdiplus::GdiplusStartupInput gdiplusStartupInput; Gdiplus::GdiplusStartup(&m_token, &gdiplusStartupInput, NULL); } ~GdiplusInitializer() { Gdiplus::GdiplusShutdown(m_token); } };
#pragma once #include "Effect.h" #include "../ShaderResouceView.h" #include "../CRenderContext.h" #include "../Camera.h" #include "../CPrimitive.h" #include "../CShader.h" #include "../Shader.h" class Sprite : Noncopyable { public: static const CVector2 DEFAULT_PIVOT; //!<ใƒ”ใƒœใƒƒใƒˆใ€‚ Sprite(); ~Sprite(); void Init(ID3D11ShaderResourceView* srv, float w, float h); /* *@brief ๅˆๆœŸๅŒ–ใ€‚ *@param texFilePath ใƒ†ใ‚ฏใ‚นใƒใƒฃใฎใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚นใ€‚ *@param w ็”ปๅƒใฎๅน…ใ€‚ *@param h ็”ปๅƒใฎ้ซ˜ใ•ใ€‚ */ void Init(const wchar_t* texFilePath, float w, float h); /* *@brief ๆ›ดๆ–ฐใ€‚ *@param[in] trans ๅนณ่กŒ็งปๅ‹•ใ€‚ *@param[in] rot ๅ›ž่ปขใ€‚ *@param[in] scale ๆ‹กๅคงใ€‚ *@param[in] pivot ๅŸบ็‚นใ€‚ * 0.5, 0.5ใง็”ปๅƒใฎไธญๅฟƒใŒๅŸบ็‚นใ€‚ * 0.0, 0.0ใง็”ปๅƒใฎๅทฆไธ‹ใ€‚ * 1.0, 1.0ใง็”ปๅƒใฎๅณไธŠใ€‚ * UnityใฎuGUIใซๆบ–ๆ‹ ใ€‚ */ void Update(const CVector3& trans, const CQuaternion& rot, const CVector3& scale, CVector2 pivot = { 0.5f, 0.5f }); /* *@brief ๆ็”ปใ€‚ */ void Draw(); void Draww(); void ChangeCameraProjMatrix(Camera::EnUpdateProjMatrixFunc cameraMode) { m_cameraMode = cameraMode; } void SetMulColor(const CVector4& col) { m_mulCol = col; } struct ConstantBuffer { CMatrix WVP; CVector4 mulCol; }; Camera::EnUpdateProjMatrixFunc m_cameraMode = Camera::enUpdateProjMatrixFunc_Ortho; ID3D11Buffer* m_vertexBuffer = NULL; ID3D11Buffer* m_indexBuffer = NULL; ID3D11DepthStencilState* m_depthStencilState = NULL; ID3D11DepthStencilState* spriteRender = NULL; ID3D11DepthStencilState* zspriteRender = NULL; ID3D11RasterizerState* rspriteRender = NULL; Effect m_effect; ID3D11ShaderResourceView* m_texture = NULL; ID3D11SamplerState* m_samplerState = NULL; CVector3 m_position = CVector3::Zero(); CQuaternion m_rotation = CQuaternion::Identity(); //ๅ›ž่ปข CVector3 m_scale = CVector3::One(); CMatrix m_world = CMatrix::Identity(); //ใƒฏใƒผใƒซใƒ‰่กŒๅˆ—ใ€‚ CVector2 m_size = CVector2::Zero(); //็”ปๅƒใฎใ‚ตใ‚คใ‚บใ€‚ ID3D11Buffer* m__cb = nullptr; //ๅฎšๆ•ฐใƒใƒƒใƒ•ใ‚กใ€‚ Shader m_vs; //้ ‚็‚นใ‚ทใ‚งใƒผใƒ€ใƒผใ€‚ Shader m_ps; //ใƒ”ใ‚ฏใ‚ปใƒซใ‚ทใ‚งใƒผใƒ€ใƒผใ€‚ Shader m_pss; //ใƒ”ใ‚ฏใ‚ปใƒซใ‚ทใ‚งใƒผใƒ€ใƒผใ€‚ CVector4 m_mulCol = CVector4::White; private: void InitCommon(float w, float h); /*! *@brief ๅฎšๆ•ฐใƒใƒƒใƒ•ใ‚กใฎๅˆๆœŸๅŒ–ใ€‚ */ void InitConstantBuffer(); void InitVertexBuffer(float w, float h); void InitIndexBuffer(); void InitSamplerState(); ID3D11BlendState* pBlendState = NULL; };
/* -*- Mode: c++; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) Opera Software ASA 1995 - 2004 * * class ES_CurrentURL */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/es_currenturl.h" #ifdef CRASHLOG_CAP_PRESENT const char *g_ecmaCurrentURL; ES_CurrentURL::ES_CurrentURL(ES_Runtime *runtime) { Initialize(runtime); } ES_CurrentURL::ES_CurrentURL(ES_Heap *heap) { Initialize(heap->GetFirstRuntime()); } ES_CurrentURL::~ES_CurrentURL() { buffer[0] = 0; g_ecmaCurrentURL = NULL; } void ES_CurrentURL::Initialize(ES_Runtime *runtime) { if (!runtime) buffer[0] = 0; else { unsigned length = es_minu(sizeof buffer - 19, runtime->url.Length()); op_memcpy(buffer, "CarakanCurrentURL=", 18); op_memcpy(buffer + 18, runtime->url.CStr(), length); buffer[18 + length] = 0; } g_ecmaCurrentURL = buffer; } #endif // CRASHLOG_CAP_PRESENT
#define BOOST_STACKTRACE_LINK #include <boost/stacktrace.hpp> #include <iostream> #include <string> void foo(const std::string &, double, bool) { std::cout << boost::stacktrace::stacktrace() << "\n"; } int main() { #ifdef BOOST_STACKTRACE_USE_BASIC std::cout << "Use BOOST_STACKTRACE_USE_BASIC\n"; #endif #ifdef BOOST_STACKTRACE_USE_ADDR2LINE std::cout << "Use BOOST_STACKTRACE_USE_ADDR2LINE\n"; #endif #ifdef BOOST_STACKTRACE_USE_BACKTRACE std::cout << "Use BOOST_STACKTRACE_USE_BACKTRACE\n"; #endif foo("hello", 42.42, true); return 0; }
/**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.14.1 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ static const unsigned char qt_resource_data[] = { // C:/Users/Imane/Documents/Steiner_Tree/logo.bmp 0x0,0x0,0x5,0x19, 0x0, 0x0,0x1a,0x3a,0x78,0x9c,0xed,0x98,0x7b,0x4c,0x5b,0x55,0x1c,0xc7,0xbb,0x64,0x7f, 0xf0,0x87,0xc9,0xf8,0xcf,0xc6,0x3f,0x1c,0x98,0x98,0x54,0x8d,0xd2,0xc5,0xc8,0x50, 0xe7,0x82,0xcb,0x5c,0x66,0xdc,0x3,0x9d,0x38,0x30,0x12,0x16,0xc,0x21,0xd9,0xcb, 0x2e,0x99,0xa4,0x51,0x17,0x9,0xc4,0xcc,0x90,0x45,0x16,0xa7,0x63,0x4e,0x37,0x62, 0xd4,0x28,0x8a,0xc1,0xc7,0x66,0x3,0xc,0x19,0x59,0xc7,0x18,0xf,0x59,0xa9,0x58, 0x1e,0x22,0xab,0x50,0xea,0xa0,0xae,0x50,0xfb,0xb8,0xb7,0x2f,0xfc,0xc2,0x69,0xe, 0x37,0xed,0xb9,0xa7,0xb7,0xb9,0x77,0x89,0x7f,0xf8,0xcb,0xb7,0xff,0xb4,0xf7,0x9c, 0xfb,0xb9,0xbf,0xe7,0xb9,0xdd,0xb2,0xf3,0x89,0x7b,0x74,0x2b,0x96,0x8f,0x8f,0x1, 0x9f,0xd,0xf8,0x3c,0x8c,0xcf,0x1a,0x9d,0x7e,0xe5,0xfb,0xb5,0x89,0xdf,0xa5,0xb6, 0xf4,0xdf,0xb3,0xff,0x99,0x94,0x59,0x7a,0x26,0xb7,0x18,0x2f,0xb1,0x47,0xf4,0xdd, 0xa2,0xae,0x43,0xc8,0xee,0x12,0x8b,0x6c,0x11,0x87,0x3f,0x4e,0x7e,0xea,0xbc,0xd4, 0x56,0xfc,0xc2,0x73,0x8f,0x3c,0x98,0x4b,0xb4,0x65,0x73,0xfe,0x67,0x9f,0x9e,0x13, 0x4,0x1,0x3f,0xdd,0x16,0x17,0x8e,0xdb,0xcf,0x96,0x76,0x1f,0xdd,0xde,0x51,0xf9, 0x62,0xd7,0x6b,0xb5,0xb6,0xf,0xff,0xf4,0xbb,0xb5,0x61,0xb2,0x78,0x62,0xe0,0x0, 0x8d,0x54,0x59,0x9d,0x42,0x93,0x2b,0x7a,0xfa,0x83,0x93,0x94,0x46,0x2a,0xd3,0xa1, 0xaa,0x7e,0x8f,0x1d,0x1c,0xa0,0x91,0x6a,0x57,0xe7,0xfe,0x76,0xd7,0x55,0xb5,0x4c, 0xf0,0x10,0x71,0x4f,0xaa,0x80,0x55,0x5a,0x56,0x4a,0x39,0x9e,0xdc,0x98,0x27,0xc5, 0x22,0xee,0x49,0x15,0xb0,0x94,0x78,0x8b,0xc7,0x64,0x9e,0x88,0x32,0x81,0x88,0x76, 0x35,0x5b,0x5f,0xdd,0x57,0x5a,0xff,0x6e,0xdd,0xfc,0xfc,0x1c,0x2e,0xf6,0xf9,0x16, 0xe1,0x39,0x7c,0x73,0xe4,0x14,0x1b,0x88,0x8,0x1,0x55,0xc5,0x54,0x38,0x10,0xe6, 0x30,0xe5,0x58,0x45,0xe6,0xaa,0xea,0x81,0x13,0x1c,0xa6,0x72,0xab,0x59,0x15,0x93, 0x5c,0xe0,0xa8,0x98,0xab,0xe4,0x2,0x47,0xa5,0x8a,0x9,0x25,0xc6,0x1,0x32,0xf6, 0x86,0x99,0xab,0x50,0x62,0x1c,0xa0,0x3,0xbd,0xb5,0xaa,0x98,0x1a,0x9c,0xd1,0xb5, 0xdf,0xce,0xc8,0x31,0x99,0xc6,0xa2,0xcc,0x55,0xad,0xce,0xe,0xe,0xd3,0x47,0x63, 0xcd,0xaa,0x98,0x6a,0x6a,0xde,0x42,0x11,0xdd,0x5b,0x76,0x30,0x15,0x8,0x61,0xf5, 0x46,0xd8,0xab,0xc4,0x58,0x18,0xce,0x60,0x2,0x3d,0x7d,0x68,0x1b,0x36,0x44,0x1d, 0x90,0x1e,0x96,0x31,0xd3,0xb1,0x37,0x5e,0x27,0x85,0x9d,0x97,0x67,0x58,0xf3,0xd3, 0xa2,0x14,0xc8,0xd0,0x23,0xe,0xf9,0xe2,0x9c,0x4d,0xff,0xa,0x7a,0x4c,0x7d,0xc7, 0x93,0x80,0x2a,0x7b,0x8e,0xed,0x2e,0xda,0x46,0xf6,0x44,0xb5,0x66,0xcc,0x44,0x81, 0xa0,0x93,0xef,0xd5,0x37,0x4e,0x47,0xd1,0xca,0x51,0x86,0xc8,0x30,0x4,0x34,0x14, 0xe3,0x6c,0xb8,0x6a,0x17,0xa6,0x2f,0xa3,0xf2,0x51,0x86,0xc8,0x30,0x4,0x14,0xfe, 0xfb,0xfa,0xab,0xcf,0xe9,0xb6,0x98,0x1,0x19,0x30,0x7d,0xd7,0xfa,0xd,0x5d,0x9, 0x38,0x45,0xf7,0x57,0x6c,0xe8,0xf2,0x74,0x10,0xc9,0x45,0x30,0x99,0x9,0xd,0x90, 0x36,0xe5,0xea,0xa3,0x87,0xb5,0x5,0x5a,0x5a,0x69,0xad,0xa0,0x21,0xfb,0x5b,0x2e, 0xfe,0xa0,0x88,0x9,0x1c,0xf4,0x39,0xb0,0x5e,0x73,0x26,0x18,0xe6,0x34,0xb9,0x5, 0xe6,0xb7,0x22,0x26,0x3a,0xe7,0xe5,0x1e,0x42,0xbd,0x21,0x64,0xd4,0x55,0x8a,0x98, 0x90,0x7a,0xa8,0x55,0x24,0xe3,0x1d,0x2,0x22,0x66,0xbd,0x72,0x19,0x77,0x41,0xe2, 0xf2,0x98,0xe6,0x16,0x62,0x87,0xcf,0x4,0x36,0x1e,0x59,0xbc,0xaf,0xc2,0x6b,0x3c, 0xb8,0x50,0x75,0xca,0xff,0xfb,0x2c,0xbb,0x25,0xaa,0x37,0x77,0x58,0x2c,0x99,0xb2, 0xeb,0x87,0xbb,0x75,0x83,0x1d,0xd9,0x37,0xba,0x8a,0x26,0x6d,0x8e,0x90,0x3f,0x99, 0xa9,0xdb,0x1e,0x6,0x7,0x68,0xa4,0x7a,0xa0,0x6a,0xa1,0x45,0x66,0xca,0xaa,0x31, 0xcb,0xa2,0x7,0x1c,0xa0,0x91,0x2a,0x6b,0xa8,0xb3,0xc9,0xe3,0x5a,0x65,0x82,0x87, 0x88,0x7b,0x52,0x5,0x2c,0x6d,0xbd,0x5,0xf,0x11,0xf7,0xa4,0xa,0x58,0xd4,0x5b, 0xba,0xfa,0x96,0x10,0x13,0x88,0x8,0x1,0xd5,0x90,0xc9,0xec,0x9a,0x60,0x2,0x11, 0x21,0xa0,0x9,0xa6,0x97,0xeb,0xff,0xe1,0x30,0x6d,0xae,0xd6,0xb2,0x1d,0x14,0x8e, 0xf,0x70,0x98,0x72,0xec,0xd6,0x4,0x93,0x5c,0xe0,0xa8,0x34,0x64,0x92,0xb,0x1c, 0x55,0x82,0x9,0x25,0xc6,0x1,0xda,0x51,0xe3,0xd3,0x90,0x9,0x25,0xc6,0x1,0x32, 0x3a,0x7a,0x13,0x4c,0xe7,0xdb,0x5,0xe,0x53,0xdd,0x97,0x41,0xd,0x99,0x1a,0x6e, 0x39,0x39,0x4c,0xa6,0xe9,0xb1,0x4,0x93,0x10,0x8e,0xc3,0x19,0x4c,0x20,0x84,0x75, 0x31,0xc0,0x3b,0x93,0x64,0x6a,0xa1,0x58,0xc,0xce,0x60,0x2,0x21,0xac,0xde,0x68, 0xe2,0x44,0xb6,0xdc,0x9f,0xa6,0xe7,0x63,0x7b,0xde,0x49,0x64,0xba,0x61,0x6b,0x2d, 0x5a,0xfe,0x43,0x9b,0x2a,0xb6,0x9a,0xe7,0x47,0x9c,0xda,0xb7,0xcd,0x29,0x31,0x58, 0x30,0xda,0x77,0xf7,0x9b,0xcb,0x53,0x35,0xb7,0x64,0x27,0x1,0x32,0x8c,0xf4,0xc, 0x5,0x56,0x93,0x64,0x75,0xb6,0x7c,0xd1,0x25,0xa0,0xf2,0xf3,0x37,0x3d,0x4b,0x26, 0x51,0xd3,0xf9,0x4f,0x34,0x7,0x22,0x86,0xa3,0x7,0x3d,0xb,0x21,0xc3,0x10,0x50, 0xf8,0x4f,0x7a,0x41,0xf2,0xbc,0xc3,0x9,0x30,0xed,0xf9,0x46,0xa5,0xd1,0x17,0x68, 0x8c,0x3c,0xe6,0x5,0xc9,0x4c,0xd2,0xa1,0x7d,0xee,0xe3,0xd3,0x77,0x82,0x29,0xe3, 0xf3,0xd3,0x92,0xe4,0x7c,0x3,0xf5,0xf7,0x5d,0xd3,0x16,0x88,0x6e,0x9e,0xc1,0x39, 0x73,0x69,0xc5,0x55,0xf4,0x14,0x85,0x33,0xa7,0x6b,0x66,0x5a,0x2b,0x20,0x64,0xd2, 0x63,0x1b,0xc,0x64,0x67,0xc0,0xc9,0x5d,0xc6,0x7e,0x47,0x0,0x7,0xf5,0x70,0x45, 0xf9,0x9e,0x71,0x67,0x49,0xff,0x88,0xbe,0xc7,0xa6,0xeb,0xfb,0x35,0x7b,0xf4,0x66, 0x51,0x50,0x70,0xa4,0xbd,0xbd,0x18,0x72,0x8f,0x5e,0x2f,0xb9,0x7e,0x41,0x7f,0xa5, 0x45,0x77,0xed,0xfb,0xec,0xdf,0x7a,0x8a,0x2,0x3e,0x7,0x7d,0xf5,0xc0,0x33,0x73, 0x92,0x55,0xf6,0x5d,0xa,0x51,0x23,0xcf,0xf4,0xa8,0x31,0x17,0x34,0x52,0xf5,0xe, 0x67,0xdd,0xfa,0xbb,0x89,0x3,0x74,0xdb,0x6d,0x1,0x7,0x68,0xa4,0xba,0xda,0x9a, 0xf5,0xfc,0x8e,0xc7,0x95,0xa4,0x4,0xef,0x9d,0xb3,0xbd,0xad,0xf9,0xa5,0xe2,0xf5, 0x27,0xde,0xbf,0x2b,0x89,0x89,0x60,0xc9,0x79,0xb,0x1e,0x22,0xee,0x49,0xd5,0xd9, 0xfa,0x75,0xfb,0xca,0x76,0xa7,0x3d,0xc4,0xf2,0x98,0x9c,0x6e,0x73,0x2a,0xd,0x15, 0x2,0xca,0x5c,0x75,0xd3,0x6e,0x66,0x2,0x11,0x21,0xa0,0x7c,0xa0,0x34,0x4c,0x23, 0x93,0x85,0x1c,0xa6,0x41,0x47,0xe,0x73,0xd5,0x70,0x77,0x21,0x87,0xa9,0xdf,0xc2, 0x5e,0xa5,0x94,0x89,0xe4,0xb5,0x9c,0xde,0xae,0x5b,0x87,0xcc,0xd8,0xfe,0xcc,0x53, 0x38,0xea,0x23,0x3f,0xd0,0x6c,0x48,0xb5,0x96,0x17,0xaf,0xe7,0x30,0x41,0xaa,0x98, 0x50,0x62,0x1c,0xa6,0xbd,0x7b,0xef,0x67,0xfe,0x9f,0x9,0x71,0x80,0x7e,0xb9,0x64, 0x54,0xc5,0x34,0x3b,0xd7,0xc0,0x61,0xfa,0xd1,0xf2,0x4a,0xd2,0xdf,0x98,0x10,0x4a, 0xb5,0xe9,0x4c,0x25,0x87,0xe9,0xf,0x9b,0x49,0x15,0x53,0x2c,0x1e,0xb2,0x8d,0x1b, 0x99,0x40,0x8,0x6b,0x24,0xea,0xc5,0x8b,0x32,0x5a,0x1f,0xc6,0x16,0x11,0x6,0x19, 0xba,0x62,0x2c,0x1a,0x82,0x33,0x98,0x40,0xa8,0xc7,0x48,0x38,0xfd,0xc1,0x35,0x4d, 0x74,0x5,0x71,0xca,0x3e,0x51,0x90,0x4,0x34,0x34,0x6a,0xf0,0x7,0x87,0x38,0xab, 0x42,0x81,0xa9,0x1b,0x3f,0x17,0x24,0x1,0xd,0xb6,0x19,0xfc,0x5e,0xde,0x2a,0xa5, 0x4c,0xc4,0xdc,0x9e,0x46,0x54,0x3e,0xca,0x10,0x19,0x86,0x80,0xc2,0x7f,0x4a,0x56, 0xcd,0x4e,0x36,0xa2,0xf2,0x51,0x86,0x68,0xe2,0x33,0xe3,0xd,0xf0,0x9f,0x92,0x55, 0xcb,0x4c,0xff,0x2,0xd9,0x57,0x24,0xe0, }; static const unsigned char qt_resource_name[] = { // Logo 0x0,0x4, 0x0,0x5,0x35,0xdf, 0x0,0x4c, 0x0,0x6f,0x0,0x67,0x0,0x6f, // logo.bmp 0x0,0x8, 0x5,0xe2,0x47,0x20, 0x0,0x6c, 0x0,0x6f,0x0,0x67,0x0,0x6f,0x0,0x2e,0x0,0x62,0x0,0x6d,0x0,0x70, }; static const unsigned char qt_resource_struct[] = { // : 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/Logo 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/Logo/logo.bmp 0x0,0x0,0x0,0xe,0x0,0x1,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0, 0x0,0x0,0x1,0x72,0xc8,0xc3,0x30,0x68, }; #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); #if defined(__ELF__) || defined(__APPLE__) static inline unsigned char qResourceFeatureZlib() { extern const unsigned char qt_resourceFeatureZlib; return qt_resourceFeatureZlib; } #else unsigned char qResourceFeatureZlib(); #endif #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources_logo)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources_logo)() { int version = 3; QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData) (version, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_logo)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_logo)() { int version = 3; version += QT_RCC_PREPEND_NAMESPACE(qResourceFeatureZlib()); QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData) (version, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_logo)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_logo)(); } } dummy; }
#include <iostream> #include <fstream> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include <math.h> #define pb push_back using namespace std; struct toado { int h, c; }; toado huong[5] = {-1, 0 , 0, 1 , 1, 0 , 0, -1}; char str[1111]; int flag[1111][1111]; void input() { scanf("%s", str); } int getHuong(char c, int hg) { if (c == 'N') return 0; if (c == 'E') return 1; if (c == 'S') return 2; if (c == 'W') return 3; if (c == 'C') return hg; if (c == 'B') return (hg + 2) % 4; if (c == 'R') return (hg + 1) % 4; return (hg + 3) % 4; } toado doMove(toado loc, int hg) { loc.h = loc.h + huong[hg].h; loc.c = loc.c + huong[hg].c; return loc; } float calDis(toado loc) { return sqrt(loc.h * loc.h + loc.c * loc.c); } void solve() { int len = strlen(str); int hg = 0; int countLos = 0; toado loc; loc.h = 0; loc.c = 0; memset(flag, 0, sizeof(flag)); flag[loc.h + 1000][loc.c + 1000] = 1; for (int i = 0; i < len; i++) { hg = getHuong(str[i], hg); loc = doMove(loc, hg); if (flag[loc.h + 1000][loc.c + 1000] == 1) { countLos++; } else { flag[loc.h + 1000][loc.c + 1000] = 1; } } printf("%.3f %d\n", calDis(loc), countLos); } int main() { int ntest; freopen("explore2.inp", "r", stdin); scanf("%d", &ntest); for (int itest = 0; itest < ntest; itest++) { input(); solve(); } return 0; }
#pragma once #include <memory> #include <cctype> class Symbol { public: Symbol(); ~Symbol(); bool parseValue(const std::string & value); std::shared_ptr<std::string> getValue(); private: std::shared_ptr<std::string> _symbol; }; Symbol::Symbol() { } Symbol::~Symbol() { } bool Symbol::parseValue(const std::string & value) { if (value.length() == 3) { _symbol = std::make_shared<std::string>(value); return true; } std::cerr << "ERROR!!! Symbol: " << value << std::endl; return false; } std::shared_ptr<std::string> Symbol::getValue() { return _symbol; }
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003-2010 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // ร˜yvind ร˜stlund // #include "core/pch.h" #include "adjunct/desktop_util/file_utils/filenameutils.h" #include "adjunct/desktop_util/filelogger/desktopfilelogger.h" #include "platforms/windows/win_handy.h" #include "platforms/windows/installer/HandleInfo.h" #include "platforms/windows/installer/InstallerWizard.h" #include "platforms/windows/installer/ProcessItem.h" #include "platforms/windows/windows_ui/winshell.h" #include <process.h> #include <Psapi.h> #include <Tlhelp32.h> using namespace NtDll; extern OpString g_spawnPath; struct GetFileNameThreadParam { NTSTATUS rc; IO_STATUS_BLOCK iob; HANDLE hFile; DWORD size; FILE_NAME_INFORMATION* file_name_info; }; enum { OB_TYPE_UNKNOWN = 0, OB_TYPE_TYPE = 1, OB_TYPE_DIRECTORY, OB_TYPE_SYMBOLIC_LINK, OB_TYPE_TOKEN, OB_TYPE_PROCESS, OB_TYPE_THREAD, OB_TYPE_UNKNOWN_7, OB_TYPE_EVENT, OB_TYPE_EVENT_PAIR, OB_TYPE_MUTANT, OB_TYPE_UNKNOWN_11, OB_TYPE_SEMAPHORE, OB_TYPE_TIMER, OB_TYPE_PROFILE, OB_TYPE_WINDOW_STATION, OB_TYPE_DESKTOP, OB_TYPE_SECTION, OB_TYPE_KEY, OB_TYPE_PORT, OB_TYPE_WAITABLE_PORT, OB_TYPE_UNKNOWN_21, OB_TYPE_UNKNOWN_22, OB_TYPE_UNKNOWN_23, OB_TYPE_UNKNOWN_24, OB_TYPE_IO_COMPLETION, OB_TYPE_FILE } SystemHandleType; static const uni_char* SystemHandleTypeStr[] = { UNI_L(""), UNI_L(""), UNI_L("Directory"), UNI_L("SymbolicLink"), UNI_L("Token"), UNI_L("Process"), UNI_L("Thread"), UNI_L("Unknown7"), UNI_L("Event"), UNI_L("EventPair"), UNI_L("Mutant"), UNI_L("Unknown11"), UNI_L("Semaphore"), UNI_L("Timer"), UNI_L("Profile"), UNI_L("WindowStation"), UNI_L("Desktop"), UNI_L("Section"), UNI_L("Key"), UNI_L("Port"), UNI_L("WaitablePort"), UNI_L("Unknown21"), UNI_L("Unknown22"), UNI_L("Unknown23"), UNI_L("Unknown24"), UNI_L("IoCompletion"), UNI_L("File") }; HandleInfo::HandleInfo() { } HandleInfo::~HandleInfo() { m_process_list.DeleteAll(); m_window_list.DeleteAll(); } OP_STATUS HandleInfo::Init() { if (!HASNtQuerySystemInformation() || !HASNtQueryObject() || !HASNtQueryInformationFile() || !HASNtQueryInformationProcess()) return OpStatus::ERR_NOT_SUPPORTED; return OpStatus::OK; } // From device file name to DOS filename OP_STATUS HandleInfo::GetFsFileName(const uni_char* device_file_name, OpString& fsFileName) { OP_ASSERT(device_file_name && "device_file_name should never be NULL"); if (!device_file_name) return OpStatus::ERR_NULL_POINTER; OP_STATUS rc = OpStatus::ERR; uni_char device_name[0x1000]; uni_char drive[3] = UNI_L("A:"); drive[2] = 0; // Iterating through the drive letters for (uni_char actDrive = UNI_L('A'); actDrive <= UNI_L('Z'); actDrive++) { drive[0] = actDrive; // Query the device for the drive letter if (QueryDosDevice(drive, device_name, 0x1000) != 0) { // Network drive? if (uni_strnicmp(_T("\\Device\\LanmanRedirector\\"), device_name, 25) == 0) { //Mapped network drive uni_char drive_letter; DWORD dwParam; uni_char shared_name[0x1000]; if (swscanf(device_name, UNI_L("\\Device\\LanmanRedirector\\;%c:%d\\%s"), &drive_letter, &dwParam, shared_name) != 3) continue; uni_strcpy(device_name, UNI_L("\\Device\\LanmanRedirector\\")); uni_strcat(device_name, shared_name); } // Is this the drive letter we are looking for? if (uni_strnicmp(device_name, device_file_name, uni_strlen(device_name)) == 0) { fsFileName.Set(drive); fsFileName.Append((uni_char*)(device_file_name + uni_strlen(device_name))); rc = OpStatus::OK; break; } } } return rc; } // From DOS file name to device file name OP_STATUS HandleInfo::GetDeviceFileName(const uni_char* fs_file_name, OpString& device_file_name) { OP_ASSERT(fs_file_name && "fs_file_name should never be NULL"); if (!fs_file_name || uni_strlen(fs_file_name) < 3) return OpStatus::ERR; OP_STATUS rc = OpStatus::ERR; uni_char drive[3]; // Get the drive letter // unfortunetaly it works only with DOS file names uni_strncpy(drive, fs_file_name, 2); drive[2] = 0; OpString device_name; RETURN_OOM_IF_NULL(device_name.Reserve(0x1000)); // Query the device for the drive letter if (QueryDosDevice(drive, device_name.CStr(), 0x1000) != 0) { if (device_name.Length() > 4 && device_name.CompareI("\\??\\", 4) == 0) { // If a drive has been mapped with SUBST, // it will have \??\ prepended on the device_name device_file_name.Set(device_name + 4); } else // Network drive? if (device_name.Length() > 26 && device_name.CompareI("\\Device\\LanmanRedirector\\", 25) == 0) { //Mapped network drive INT index = device_name.Find("\\", 26); if (index == KNotFound) return OpStatus::ERR; OpString shared_name; shared_name.Set(device_name.CStr() + index); device_name.Set("\\Device\\LanmanRedirector"); device_name.Append(shared_name); } // Set the device name, and add the file name, and the conversion is done. device_file_name.Set(device_name); device_file_name.Append(fs_file_name + 2); rc = OpStatus::OK; } return rc; } ProcessItem* HandleInfo::AddProcess(DWORD process_id, BOOL load_icon /*= TRUE*/) { UINT32 i = 0; UINT32 count = m_process_list.GetCount(); SHORT_PROCESS_INFO* process_info = NULL; while (i < count) { process_info = m_process_list.Get(i); if (process_info->process_id == process_id) { OpAutoPtr<ProcessItem> new_process_item(OP_NEW(ProcessItem, (process_id))); if (!new_process_item.get()) return NULL; // Path OpString path; if (OpStatus::IsError(new_process_item->SetProcessPath(process_info->process_path.CStr()))) return NULL; // Icon if (load_icon) { OpStatus::Ignore(new_process_item->LoadProcessIcon()); } // Title if (OpStatus::IsError(new_process_item->FindProcessTitle())) { UINT32 j = 0; WINDOW_INFO* window_info = m_window_list.Get(j); while (window_info && !new_process_item->GetProcessTitle()) { if (window_info->process_id == new_process_item->GetProcessID()) { if (OpStatus::IsError(new_process_item->SetProcessTitle(window_info->title.CStr()))) return NULL; } window_info = m_window_list.Get(++j); } } return new_process_item.release(); } i++; } return NULL; } BOOL HandleInfo::ProcessListHasID(DWORD pID) { INT32 i; INT32 count = m_process_list.GetCount(); for (i = 0; i < count; i++) { if (m_process_list.Get(i)->process_id == pID) return TRUE; } return FALSE; } OP_STATUS HandleInfo::IsFileInUse(const uni_char* file_name, OpVector<ProcessItem>& processes, const BOOL refresh_lists) { OP_NEW_DBG("IsFileInUse", "Winstaller"); if (!file_name) return OpStatus::ERR_NULL_POINTER; if (!m_process_list.GetCount() || refresh_lists) RETURN_IF_ERROR(GetProcessList()); if (!m_window_list.GetCount() || refresh_lists) OpStatus::Ignore(GetWindowList()); // // Remove installer instances (we don't want to terminate the installer) // SHORT_PROCESS_INFO* process = NULL; UINT32 i = 0; while ((process = m_process_list.Get(i)) != NULL) { if (IsInstaller(process->process_id)) m_process_list.Delete(i); else ++i; } // // See if we can find any module that is loaded into a process // BOOL match = FALSE; for (UINT32 i = 0; i < m_process_list.GetCount(); i++) { OpStatus::Ignore(IsModuleInUse(m_process_list.Get(i)->process_id, file_name, match)); if (match) { ProcessItem* process_name = AddProcess(m_process_list.Get(i)->process_id); if (process_name && OpStatus::IsError(processes.Add(process_name))) { OP_DELETE(process_name); return OpStatus::ERR_NO_MEMORY; } } } // // See if we can find any file handle that is locked // OpString handle_data; OpString device_file_name; RETURN_IF_ERROR(GetDeviceFileName(file_name, device_file_name)); PSEUDO_KERNEL_HANDLE pkh; SYSTEM_HANDLE_INFO_EX sinfo = {0}; pkh.query = IsSystemWinXP() ? SystemExtendedHandleInformation : SystemHandleInformation; OpAutoArray<BYTE> handles; RETURN_IF_ERROR(GetHandleList(pkh.query, handles, pkh.count)); if (pkh.query == SystemHandleInformation) pkh.info = &sinfo; for (UINT32 i = 0; i < pkh.count; i++) { if (pkh.query == SystemExtendedHandleInformation) pkh.info = (SYSTEM_HANDLE_INFO_EX*)&((SYSTEM_HANDLES_EX*)handles.get())->handles[i]; else { sinfo.process_id = (DWORD)(*(SYSTEM_HANDLE_INFO*)&((SYSTEM_HANDLES*)handles.get())->handles[i]).process_id; sinfo.handle = (DWORD)(*(SYSTEM_HANDLE_INFO*)&((SYSTEM_HANDLES*)handles.get())->handles[i]).handle; sinfo.handle_type = (DWORD)(*(SYSTEM_HANDLE_INFO*)&((SYSTEM_HANDLES*)handles.get())->handles[i]).handle_type; } #ifdef _DEBUG // Add Winstaller as a key in debug.txt to print out what process you are currently checking. static DWORD current_process = (DWORD)-1; if (current_process != pkh.info->process_id) { current_process = pkh.info->process_id; BOOL found = FALSE; for (UINT32 i = 0; i < m_process_list.GetCount(); i++) { if (current_process == m_process_list.Get(i)->process_id) { found = TRUE; OP_DBG(("Current process %S", m_process_list.Get(i)->process_name.CStr())); } } if (!found) { OP_DBG(("Current process %u", current_process)); } } #endif // DEBUG // For some reason sometimes the process id does not seem to be a valid process id at all. if (!ProcessListHasID(pkh.info->process_id)) continue; INT type = OB_TYPE_UNKNOWN; // Check if the handle is a file handle. if (OpStatus::IsError(GetType(pkh, type)) || type != OB_TYPE_FILE) continue; // Check if the handle contain some info about what file it belongs to. if (OpStatus::IsError(GetName(pkh, type, handle_data)) || handle_data.IsEmpty()) continue; // Check if the handle corresponds to the handle we are looking for. if (uni_stricmp(handle_data.CStr(), device_file_name.CStr()) != 0) continue; // We found one that matches. Add it to the list. ProcessItem* process_name = AddProcess(pkh.info->process_id); if (process_name && OpStatus::IsError(processes.Add(process_name))) { OP_DELETE(process_name); return OpStatus::ERR_NO_MEMORY; } } return OpStatus::OK; } OP_STATUS HandleInfo::GetHandleList(SYSTEM_INFORMATION_CLASS query, OpAutoArray<byte>& handles, DWORD& count) { count = 0; // Currently we only support two types of querries. OP_ASSERT(query == SystemHandleInformation || query == SystemExtendedHandleInformation); DWORD needed = 0; NTSTATUS ntstatus = NT_STATUS_INFO_LENGTH_MISMATCH; handles.reset(); if (!NT_SUCCESS(OPNtQuerySystemInformation(query, handles.get(), needed, &needed))) { // Just make sure we don't get stuck in an endless loop. // Or get an insane random high number as once seen. if (needed == 0 || needed > 0x1000000) needed = 1; do { handles.reset((BYTE*)(ULONG_PTR)OP_NEWA(byte, needed)); RETURN_OOM_IF_NULL(handles.get()); ZeroMemory(handles.get(), needed); ntstatus = OPNtQuerySystemInformation(query, handles.get(), needed, NULL); } while ((ntstatus == NT_STATUS_INFO_LENGTH_MISMATCH) && (needed < 0x1000000) && (needed *= 2)); } if (query == SystemExtendedHandleInformation) count = ((SYSTEM_HANDLES_EX*)handles.get())->count; else count = ((SYSTEM_HANDLES*)handles.get())->count; return NT_SUCCESS(ntstatus) && handles.get() ? OpStatus::OK : OpStatus::ERR; } OP_STATUS HandleInfo::GetProcessList() { m_process_list.DeleteAll(); // Take a snapshot of all processes in the system. OpAutoHANDLE process_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)); if (process_snapshot.get() == INVALID_HANDLE_VALUE) return OpStatus::ERR; // Set the size of the structure before using it. PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); // Retrieve information about the first process, // and exit if unsuccessful if (!Process32First(process_snapshot, &pe32)) return OpStatus::ERR; OP_STATUS status = OpStatus::OK; static const DWORD PATH_LEN = 0x1000; uni_char process_path[PATH_LEN]; // Now walk the snapshot of processes, and // display information about each process in turn do { // Retrieve the priority class. HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pe32.th32ProcessID); if (!process) continue; SHORT_PROCESS_INFO* info = OP_NEW(SHORT_PROCESS_INFO, ()); if (!info) { CloseHandle(process); return OpStatus::ERR_NO_MEMORY; } ZeroMemory(process_path, PATH_LEN); if (GetModuleFileNameEx(process, NULL, process_path, PATH_LEN) != 0) { info->process_path.Set(process_path); info->process_id = pe32.th32ProcessID; info->parent_process_id = pe32.th32ParentProcessID; info->process_name.Set(pe32.szExeFile); status = m_process_list.Add(info); } CloseHandle(process); } while(OpStatus::IsSuccess(status) && Process32Next(process_snapshot, &pe32)); return status; } OP_STATUS HandleInfo::GetParentProcessItem(DWORD process_id, OpAutoPtr<ProcessItem>& process) { OP_ASSERT(process.get() == NULL && "The auto pointer should not contain a ProcessItem at this time"); if (!m_process_list.GetCount()) RETURN_IF_ERROR(GetProcessList()); for (UINT32 i = 0; i < m_process_list.GetCount(); ++i) { if (process_id == m_process_list.Get(i)->process_id) { process = AddProcess(m_process_list.Get(i)->parent_process_id); RETURN_OOM_IF_NULL(process.get()); break; } } return OpStatus::OK; } OP_STATUS HandleInfo::GetChildProcessItems(DWORD process_id, OpVector<ProcessItem>& processes) { OP_ASSERT(processes.GetCount() == 0 && "The array should be empty."); if (!m_process_list.GetCount()) RETURN_IF_ERROR(GetProcessList()); for (UINT32 i = 0; i < m_process_list.GetCount(); ++i) { if (process_id == m_process_list.Get(i)->parent_process_id) { ProcessItem* process = AddProcess(m_process_list.Get(i)->process_id); RETURN_OOM_IF_NULL(process); RETURN_IF_ERROR(processes.Add(process)); } } return OpStatus::OK; } BOOL HandleInfo::IsInstaller(const DWORD process_id) { DWORD cur_pid = GetCurrentProcessId(); // Same process id if (cur_pid == process_id) return TRUE; // Check if this could be an installer, by checking if it has // the same path as the current process, which is always an installer/uninstaller. OpAutoPtr<ProcessItem> pi = AddProcess(process_id, FALSE); if (pi.get() && g_spawnPath.CompareI(pi->GetProcessPath()) != 0) return FALSE; // Is the parent (which means also installer [elevated/non-elevated]) OpAutoPtr<ProcessItem> p; OP_STATUS status = GetParentProcessItem(process_id, p); if (OpStatus::IsSuccess(status) && p.get()) { if (cur_pid == p->GetProcessID()) { return TRUE; } } // Is the child (which means also installer [elevated/non-elevated]) OpAutoVector<ProcessItem>p_list; status = GetChildProcessItems(process_id, p_list); if (OpStatus::IsSuccess(status)) { for (UINT32 i = 0; i < p_list.GetCount(); ++i) { if (cur_pid == p_list.Get(i)->GetProcessID()) { return TRUE; } } } return FALSE; } OP_STATUS HandleInfo::GetWindowList() { m_window_list.DeleteAll(); return EnumWindows(EnumWindowInfo, (LPARAM)this) == TRUE ? OpStatus::OK : OpStatus::ERR; } // This is the callback function for the GetWindowList() function. // It will be called once for every window open at the current time. // // BOOL CALLBACK HandleInfo::EnumWindowInfo(HWND hwnd, LPARAM lParam) { uni_char title[1024]; BOOL succeeded = TRUE; DWORD length = GetWindowText(hwnd, title , 1024); if (length > 0) { WINDOW_INFO* window_info = OP_NEW(WINDOW_INFO, ()); RETURN_FALSE_IF(!window_info); HandleInfo* handle_info = (HandleInfo*)lParam; if(OpStatus::IsSuccess(handle_info->m_window_list.Add(window_info))) { window_info->hwnd = hwnd; GetWindowThreadProcessId(hwnd, &window_info->process_id); if (OpStatus::IsError(window_info->title.Set(title))) succeeded = FALSE; } else { succeeded = FALSE; OP_DELETE(window_info); } } return succeeded; } // File related functions void HandleInfo::GetFileNameThread(PVOID pParam) { // This thread function for getting the filename // if access denied, we hang up in this function, // so if it times out we just kill this thread GetFileNameThreadParam* p = (GetFileNameThreadParam*)pParam; p->rc = OPNtQueryInformationFile(p->hFile, &p->iob, (PVOID)p->file_name_info, p->size, FileNameInformation); } OP_STATUS HandleInfo::GetFileName(PSEUDO_KERNEL_HANDLE& pkh, OpString& str, DWORD process_id) { HANDLE hRemoteProcess = NULL; GetFileNameThreadParam tp = {0}; tp.size = 0x2000; tp.file_name_info = (FILE_NAME_INFORMATION*)OP_NEWA(BYTE, tp.size); RETURN_OOM_IF_NULL(tp.file_name_info); ZeroMemory(tp.file_name_info, tp.size); // If this is a remote process, we need to duplicate the handle if (process_id != GetCurrentProcessId()) { // Open the process for handle duplication hRemoteProcess = ::OpenProcess(PROCESS_DUP_HANDLE, FALSE, process_id); RETURN_VALUE_IF_NULL(hRemoteProcess, OpStatus::ERR); // Duplicate the remote handle for our process if(!::DuplicateHandle(hRemoteProcess, (HANDLE)pkh.info->handle, GetCurrentProcess(), &tp.hFile, 0, FALSE, DUPLICATE_SAME_ACCESS)) { OP_DELETEA(tp.file_name_info); CloseHandle(hRemoteProcess); return OpStatus::ERR; } } else tp.hFile = (HANDLE)pkh.info->handle; HANDLE thread = (HANDLE)_beginthread(GetFileNameThread, 0, &tp); if (thread) { // Wait for finishing the thread if (WaitForSingleObject(thread, 100) == WAIT_TIMEOUT) { // Access denied // Terminate the thread TerminateThread(thread, 0); tp.rc = NT_STATUS_ACCESS_DENIED; } str.Set(tp.file_name_info->name, tp.file_name_info->name_len / sizeof(WCHAR)); OP_DELETEA(tp.file_name_info); } // If we opened a remote process, then close it. if (hRemoteProcess) CloseHandle(hRemoteProcess); // If we created a duplicated handle, then close it. if (tp.hFile && tp.hFile != (HANDLE)pkh.info->handle) CloseHandle(tp.hFile); switch(tp.rc) { case NT_STATUS_SUCCESS: return OpStatus::OK; case NT_STATUS_NOT_IMPLEMENTED: return OpStatus::ERR_NOT_SUPPORTED; case NT_STATUS_INVALID_INFO_CLASS: return OpStatus::ERR_BAD_FILE_NUMBER; case NT_STATUS_INVALID_DEVICE_REQUEST: return OpStatus::ERR; case NT_STATUS_INFO_LENGTH_MISMATCH: return OpStatus::ERR; case NT_STATUS_ACCESS_DENIED: return OpStatus::ERR_NO_ACCESS; case NT_STATUS_OBJECT_TYPE_MISMATCH: return OpStatus::ERR; default: return OpStatus::ERR; } } OP_STATUS HandleInfo::GetProcessId(HANDLE h, DWORD& process_id, DWORD remoteProcess_id) { OP_STATUS status = OpStatus::ERR; HANDLE handle; HANDLE hRemoteProcess = NULL; PROCESS_BASIC_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); process_id = 0; if (remoteProcess_id != GetCurrentProcessId()) { // Open the process for handle duplication hRemoteProcess = ::OpenProcess(PROCESS_DUP_HANDLE, FALSE, remoteProcess_id); RETURN_VALUE_IF_NULL(hRemoteProcess, OpStatus::ERR); // Duplicate the remote handle for our process if (!::DuplicateHandle(hRemoteProcess, h, GetCurrentProcess(), &handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { CloseHandle(hRemoteProcess); return status; } } else handle = h; // Get the process information if (NT_SUCCESS(OPNtQueryInformationProcess(handle, ProcessBasicInformation, &pi, sizeof(pi), NULL))) { process_id = pi.unique_process_id; status = OpStatus::OK; } if (hRemoteProcess) CloseHandle(hRemoteProcess); if (handle && handle != h) CloseHandle(handle); return status; } OP_STATUS HandleInfo::GetName(PSEUDO_KERNEL_HANDLE& pkh, INT type, OpString& str) { OP_STATUS status = OpStatus::ERR; HANDLE tmp_handle = NULL; DWORD dwId = 0; str.Empty(); if (pkh.info->process_id != GetCurrentProcessId()) { HANDLE hRemoteProcess = NULL; BOOL ret; // Open the process for handle duplication hRemoteProcess = ::OpenProcess(PROCESS_DUP_HANDLE, FALSE, pkh.info->process_id); RETURN_VALUE_IF_NULL(hRemoteProcess, OpStatus::ERR); ret = ::DuplicateHandle(hRemoteProcess, (HANDLE)pkh.info->handle, GetCurrentProcess(), &tmp_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hRemoteProcess); if (!ret) return status; } else tmp_handle = (HANDLE)pkh.info->handle; // let's be happy, handle is in our process space, so query the infos :) switch(type) { case OB_TYPE_PROCESS: GetProcessId(tmp_handle, dwId, GetCurrentProcessId()); str.AppendFormat(UNI_L("PID: 0x%X"), dwId); status = OpStatus::OK; break; case OB_TYPE_FILE: status = GetFileName(pkh, str, pkh.info->process_id); break; }; ULONG size = 0; char* buffer = NULL; // OBJECT_NAME_INFORMATION if (str.HasContent()) { OPNtQueryObject(tmp_handle, ObjectNameInformation, NULL, 0, &size); // let's try to use the default if (size == 0) size = 0x2000; buffer = OP_NEWA(char, size); if (buffer) { if (NT_SUCCESS(OPNtQueryObject(tmp_handle, ObjectNameInformation, buffer, size, NULL))) { UNICODE_STRING* uni_string = (UNICODE_STRING*)buffer; OP_ASSERT(uni_string->length <= uni_string->max_len && uni_string->length <= size); str.Set(uni_string->str, uni_string->length); status = OpStatus::OK; } OP_DELETEA(buffer); } else status = OpStatus::ERR; } if (tmp_handle && tmp_handle != (HANDLE)pkh.info->handle) CloseHandle(tmp_handle); return status; } OP_STATUS HandleInfo::GetTypeToken(PSEUDO_KERNEL_HANDLE& pkh, OpString& str) { HANDLE tmp_handle = NULL; OP_STATUS status = OpStatus::ERR; char* buffer = NULL; if (pkh.info->process_id != GetCurrentProcessId()) { BOOL ret = FALSE; HANDLE hRemoteProcess = NULL; // Open the process for handle duplication hRemoteProcess = ::OpenProcess(PROCESS_DUP_HANDLE, FALSE, pkh.info->process_id); RETURN_VALUE_IF_NULL(hRemoteProcess, OpStatus::ERR); // Duplicate the remote handle for our process ret = ::DuplicateHandle(hRemoteProcess, (HANDLE)pkh.info->handle, GetCurrentProcess(), &tmp_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); CloseHandle(hRemoteProcess); if (!ret) return status; } else tmp_handle = (HANDLE)pkh.info->handle; // On Xp GetFileType can end up in a race condition which deadlocks the thread. So on XP we have to use the undocumented NtQueryObject() instead. // On Vista there were in-depth design changes for the GetFileType() implemenation, so this kind of hang will not be seen in newer Operating Systems. // On the other hand NtQueryObject() function seems to end up in deadlocks when it encounters unnamed pipes on Vista/Win7, so there we have to use // GetFileType() first to determine if it is a pipe. if (IsSystemWinVista() && GetFileType(tmp_handle) == FILE_TYPE_PIPE) status = str.Set(UNI_L("Pipe")); else { const ULONG size = 1024; buffer = OP_NEWA(char, size); if (!buffer) status = OpStatus::ERR_NO_MEMORY; else { ZeroMemory(buffer, size); // Query the info size (type) if (NT_SUCCESS(OPNtQueryObject(tmp_handle, ObjectTypeInformation, buffer, size, NULL))) { OBJECT_TYPE_INFORMATION* obj_type_info = (OBJECT_TYPE_INFORMATION*)buffer; status = str.Set(obj_type_info->name.str); } } } if (tmp_handle && tmp_handle != (HANDLE)pkh.info->handle) CloseHandle(tmp_handle); if (buffer) OP_DELETEA(buffer); return str.HasContent() ? OpStatus::OK : status; } OP_STATUS HandleInfo::GetType(PSEUDO_KERNEL_HANDLE& pkh, INT& type) { OpString str_type; RETURN_IF_ERROR(GetTypeToken(pkh, str_type)); UINT32 count = ARRAY_SIZE(SystemHandleTypeStr); for (WORD i = 1; i < count; i++) { if (str_type.Compare(SystemHandleTypeStr[i]) == 0) { type = i; break; } } return OpStatus::OK; } OP_STATUS HandleInfo::GetModuleList(DWORD process_id, OpAutoArray<HMODULE>& modules, DWORD& count) { // Open process to read to query the module list OpAutoHANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id)); RETURN_VALUE_IF_NULL(hProcess.get(), OpStatus::ERR); DWORD needed = 0; // Get the number of modules if (EnumProcessModules(hProcess , NULL, 0, &needed) == 0) return OpStatus::ERR; OP_STATUS status = OpStatus::OK; // Make sure the needed memory to store the modules has not changed since we checked. do { count = needed / sizeof(HMODULE); modules.reset(OP_NEWA(HMODULE, (count))); RETURN_OOM_IF_NULL(modules.get()); // Get module handles if (EnumProcessModules(hProcess, modules.get(), needed, &needed) == 0) status = OpStatus::ERR; } while ((needed / sizeof(HMODULE)) > count); return status; } OP_STATUS HandleInfo::IsModuleInUse(DWORD process_id, const uni_char* file_path, BOOL& match) { match = FALSE; if (!file_path || !*file_path) return OpStatus::ERR_NULL_POINTER; // Open process to read the module list OpAutoHANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id)); RETURN_VALUE_IF_NULL(hProcess.get(), OpStatus::ERR); OP_STATUS status = OpStatus::OK; OpAutoArray<HMODULE> modules; DWORD count = 0; RETURN_IF_ERROR(GetModuleList(process_id, modules, count)); MODULE_INFO module_info; module_info.process_id = process_id; // Go through all the module handles for (DWORD i = 0; i < count; i++) { module_info.handle = modules[i]; // Get module full paths if (GetModuleFileNameEx(hProcess, modules[i], module_info.full_path, MAX_PATH)) { if (uni_stricmp(module_info.full_path, file_path) == 0) { match = TRUE; break; } } } return status; } OP_STATUS HandleInfo::IsOperaRunningAt(const uni_char* path, OpVector<ProcessItem>& processes, const BOOL refresh_lists) { if (!path) return OpStatus::ERR_NULL_POINTER; if (refresh_lists || !m_process_list.GetCount()) RETURN_IF_ERROR(GetProcessList()); // // Remove installer instances (we don't want to terminate the installer) // SHORT_PROCESS_INFO* process = NULL; UINT32 i = 0; while ((process = m_process_list.Get(i)) != NULL) { if (IsInstaller(process->process_id)) m_process_list.Delete(i); else ++i; } // // Go through all the processes and see if opera.exe is in use in that folder // OpString opera_exe_path; RETURN_IF_ERROR(opera_exe_path.Set(path)); if (opera_exe_path.FindI(UNI_L("\\opera.exe")) == KNotFound) RETURN_IF_ERROR(opera_exe_path.Append(UNI_L("\\opera.exe"))); else if (opera_exe_path.FindI(UNI_L("opera.exe")) == KNotFound) RETURN_IF_ERROR(opera_exe_path.Append(UNI_L("opera.exe"))); i = 0; SHORT_PROCESS_INFO* process_info = NULL; while (process_info = m_process_list.Get(i++)) { if (process_info->process_path.FindI(opera_exe_path.CStr()) == 0) { OpAutoPtr<ProcessItem> process_item = AddProcess(process_info->process_id); if (process_item.get()) { RETURN_IF_ERROR(processes.Add(process_item.get())); process_item.release(); } } } // // Go through all the modules of each process and see if opera.dll is in use in that folder // OpString opera_dll_path; RETURN_IF_ERROR(opera_dll_path.Set(path)); if (opera_exe_path.FindI(UNI_L("\\opera.dll")) == KNotFound) RETURN_IF_ERROR(opera_dll_path.Append(UNI_L("\\opera.dll"))); else if (opera_dll_path.FindI(UNI_L("opera.dll")) == KNotFound) RETURN_IF_ERROR(opera_dll_path.Append(UNI_L("opera.dll"))); BOOL match = FALSE; for (UINT32 i = 0; i < m_process_list.GetCount(); i++) { OpStatus::Ignore(IsModuleInUse(m_process_list.Get(i)->process_id, opera_dll_path, match)); if (match) { OpAutoPtr<ProcessItem> process_name = AddProcess(m_process_list.Get(i)->process_id); if (process_name.get()) { RETURN_IF_ERROR(processes.Add(process_name.get())); process_name.release(); } } } return OpStatus::OK; } OP_STATUS HandleInfo::GetOpenFileList(DWORD process_id, OpVector<OpString>& file_list) { if (!m_process_list.GetCount()) RETURN_IF_ERROR(GetProcessList()); // // Open process to read the module list into file_list // OpAutoHANDLE hProcess(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id)); RETURN_VALUE_IF_NULL(hProcess.get(), OpStatus::ERR); OpAutoArray<HMODULE> modules; DWORD count = 0; RETURN_IF_ERROR(GetModuleList(process_id, modules, count)); MODULE_INFO module_info; module_info.process_id = process_id; // Go through all the module handles for (DWORD i = 0; i < count; i++) { module_info.handle = modules[i]; // Get module full paths if (GetModuleFileNameEx(hProcess, modules[i], module_info.full_path, MAX_PATH)) { OpAutoPtr<OpString> str(OP_NEW(OpString,)); RETURN_OOM_IF_NULL(str.get()); RETURN_IF_ERROR(str->Set(module_info.full_path)); RETURN_IF_ERROR(file_list.Add(str.get())); str.release(); } } // // See if we can find any file handle that is locked // OpString handle_data; SYSTEM_HANDLE_INFO_EX sinfo = {0}; PSEUDO_KERNEL_HANDLE pkh; if (IsSystemWinXP()) pkh.query = SystemExtendedHandleInformation; else { pkh.query = SystemHandleInformation; pkh.info = &sinfo; } OpAutoArray<BYTE> handles; RETURN_IF_ERROR(GetHandleList(pkh.query, handles, pkh.count)); for (UINT32 i = 0; i < pkh.count; i++) { if (pkh.query == SystemExtendedHandleInformation) pkh.info = (SYSTEM_HANDLE_INFO_EX*)&((SYSTEM_HANDLES_EX*)handles.get())->handles[i]; else { sinfo.process_id = (DWORD)(*(SYSTEM_HANDLE_INFO*)&((SYSTEM_HANDLES*)handles.get())->handles[i]).process_id; sinfo.handle = (DWORD)(*(SYSTEM_HANDLE_INFO*)&((SYSTEM_HANDLES*)handles.get())->handles[i]).handle; sinfo.handle_type = (DWORD)(*(SYSTEM_HANDLE_INFO*)&((SYSTEM_HANDLES*)handles.get())->handles[i]).handle_type; } // Only search for thos process IDs that are equal to those sent in. if (pkh.info->process_id != process_id) continue; INT type = OB_TYPE_UNKNOWN; // Check if the handle is a file handle. if (OpStatus::IsError(GetType(pkh, type)) || type != OB_TYPE_FILE) continue; // Check if the handle contain some info about what file it belongs to. if (OpStatus::IsError(GetName(pkh, type, handle_data)) || handle_data.IsEmpty()) continue; OpAutoPtr<OpString> str(OP_NEW(OpString,)); RETURN_OOM_IF_NULL(str.get()); RETURN_IF_ERROR(str->Set(handle_data.CStr())); RETURN_IF_ERROR(GetFsFileName(handle_data.CStr(), *str.get())); RETURN_IF_ERROR(file_list.Add(str.get())); str.release(); } return OpStatus::OK; }
#include "WinCommon.h" #include "DXCommon.h" #include "Object.h" #include "Wing.h" Wing::Wing(void) { m_pVB = NULL; m_pVertex = NULL; m_bHeroMode = false; m_fAngle = 0.0f; m_fCollLength= 3.0f; for( int i = 0; i < SWG_MAX; ++i ) m_pMaskTexture[i] = NULL; m_TexState = SWG_NONE; } Wing::~Wing(void) { Release(); } enINITERROR Wing::Init( D3DXVECTOR3 vPos, D3DXVECTOR3 vRot, D3DXVECTOR3 vScale, float fSpeed, bool mode ) { m_vOrgPos = m_vPos = vPos; m_vOrgRot = m_vRot = vRot; m_vScale= vScale; m_fSpeed = fSpeed; m_bHeroMode = mode; D3DXMatrixIdentity(&m_mTM); D3DXMatrixIdentity(&m_mScale); D3DXMatrixIdentity(&m_mRot); D3DXMatrixIdentity(&m_mTrans); D3DXMatrixIdentity(&m_mInvScale); // ๋ณ€ํ™˜ํ–‰๋ ฌ // D3DXMatrixScaling(&m_mScale, m_vScale.x, m_vScale.y, m_vScale.z); D3DXMatrixRotationYawPitchRoll(&m_mRot, m_vRot.x, m_vRot.y, m_vRot.z); D3DXMatrixTranslation(&m_mTrans, m_vPos.x, m_vPos.y, m_vPos.z); D3DXMatrixInverse(&m_mInvScale, 0, &m_mScale); return InitVTX(); } enINITERROR Wing::InitVTX( void ) { D3DFVF_XYZ_NORMAL_TEX1 Vertices[] = { //๋‚ ๊ฐœ 1๋ฒˆ.(9์‹œ) { D3DXVECTOR3(-1, 0.20f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.978f }, { D3DXVECTOR3( 0, 0.20f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.472f }, { D3DXVECTOR3(-1, -0.30f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3(-1, -0.30f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3( 0, 0.20f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.472f }, { D3DXVECTOR3( 0, -0.30f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.472f }, //๋‚ ๊ฐœ 2๋ฒˆ.(3์‹œ) { D3DXVECTOR3(1, 0.30f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3(0, 0.30f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.472f }, { D3DXVECTOR3(1, -0.20f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.978f }, { D3DXVECTOR3(1, -0.20f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.978f }, { D3DXVECTOR3(0, 0.30f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.472f }, { D3DXVECTOR3(0, -0.20f, -0.01f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.472f }, //๋‚ ๊ฐœ 3๋ฒˆ.(12์‹œ) { D3DXVECTOR3(0.20f, 0.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.472f }, { D3DXVECTOR3(0.20f, 1.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.978f }, { D3DXVECTOR3(-0.30f, 1.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3(-0.30f, 1.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3( 0.20f, 0.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.710f, 0.472f }, { D3DXVECTOR3(-0.30f, 0.0f, 0.0f), D3DXVECTOR3( 0, 0, -1), 0.574f, 0.472f }, //๋‚ ๊ฐœ 4๋ฒˆ.(6์‹œ) { D3DXVECTOR3(-0.20f, -1.0f, 0.0f), D3DXVECTOR3( 0, 0, -1), 0.710f, 0.978f }, { D3DXVECTOR3(-0.20f, 0.0f, 0.0f), D3DXVECTOR3( 0, 0, -1), 0.710f, 0.472f }, { D3DXVECTOR3(0.30f, -1.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3(0.30f, -1.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.978f }, { D3DXVECTOR3(-0.20f, 0.0f, 0.0f), D3DXVECTOR3( 0, 0, -1), 0.710f, 0.472f }, { D3DXVECTOR3(0.30f, 0.0f, 0.0f), D3DXVECTOR3(0, 0, -1), 0.574f, 0.472f }, }; m_iVtxCnt = sizeof(Vertices) / (sizeof(D3DFVF_XYZ_NORMAL_TEX1)*3); int iVertexSize = sizeof(Vertices); m_pVertex = new D3DFVF_XYZ_NORMAL_TEX1[iVertexSize]; memcpy(m_pVertex, Vertices, iVertexSize); // ์ •์ ๋ฒ„ํผ ์ƒ์„ฑ if( FAILED(g_pDevice->CreateVertexBuffer( iVertexSize, // ์ •์ ๋ฒ„ํผ ํฌ๊ธฐ 0, // ๋ฒ„ํผ ์ฒ˜๋ฆฌ ์œ ํ˜• FVF_XYZ_NORMAL_TEX1, // ์ •์  ํ”Œ๋ ˆ๊ทธ D3DPOOL_MANAGED, // ์ •์  ๋ฒ„ํผ ์œ„์น˜ &m_pVB, // ์„ฑ๊ณต์‹œ ๋ฆฌํ„ด ํฌ์ธํ„ฐ NULL // ์˜ˆ์•ฝ )) ) { return INIT_D3D_VB_ERROR; } // ๋ฒ„ํผ ์ฑ„์šฐ๊ธฐ VOID* pBuff; if( FAILED(m_pVB->Lock(0, iVertexSize, (void**)&pBuff, 0)) ) { return INIT_D3D_LOCK_ERROR; } memcpy(pBuff, m_pVertex, iVertexSize); m_pVB->Unlock(); InitMaterial(); if( FAILED(D3DXCreateTextureFromFile(g_pDevice, "./Data/windmill.dds", &m_pTexture)) ) { MessageBox(NULL, "ํ…์Šค์ณ ๋กœ๋“œ ์‹คํŒจ.", "์—๋Ÿฌ", MB_ICONERROR | MB_OK); return INIT_D3D_TEXLOAD_FAIL; } // ๋งˆ์Šคํฌ๋งต ๋กœ๋”ฉ(๋ˆˆ์Œ“์ธ๋งต) if( FAILED(D3DXCreateTextureFromFile(g_pDevice, "./Data/windmill_snow1.jpg", &m_pMaskTexture[SWG_STEP1])) ) { MessageBox(NULL, "ํ…์Šค์ณ ๋กœ๋“œ ์‹คํŒจ.", "์—๋Ÿฌ", MB_ICONERROR | MB_OK); return INIT_D3D_TEXLOAD_FAIL; } if( FAILED(D3DXCreateTextureFromFile(g_pDevice, "./Data/windmill_snow2.jpg", &m_pMaskTexture[SWG_STEP2])) ) { MessageBox(NULL, "ํ…์Šค์ณ ๋กœ๋“œ ์‹คํŒจ.", "์—๋Ÿฌ", MB_ICONERROR | MB_OK); return INIT_D3D_TEXLOAD_FAIL; } if( FAILED(D3DXCreateTextureFromFile(g_pDevice, "./Data/windmill_snow3.jpg", &m_pMaskTexture[SWG_STEP3])) ) { MessageBox(NULL, "ํ…์Šค์ณ ๋กœ๋“œ ์‹คํŒจ.", "์—๋Ÿฌ", MB_ICONERROR | MB_OK); return INIT_D3D_TEXLOAD_FAIL; } return INIT_OK; } void Wing::InitMaterial( void ) { ZeroMemory(&m_mtr, sizeof(m_mtr)); m_mtr.Diffuse = m_mtr.Ambient = D3DXCOLOR(1, 1, 1, 1); } void Wing::Update( float dTime, D3DXMATRIX mParent, bool cw, bool first) { if( cw ) m_fAngle -= m_fSpeed * dTime; else m_fAngle += m_fSpeed * dTime; m_vRot.z = m_fAngle; D3DXMATRIX mResultParent; if( m_bHeroMode ) { if( g_pHero->GetUseWing() ) { // ์ด์•Œ ์žฅ์ „ ์ „์ด๋ผ๋ฉด if( g_pHero->GetBulletState() == Object::BT_READY ) { D3DXMatrixRotationYawPitchRoll(&m_mRot, m_vRot.y, m_vRot.x, m_vRot.z); mResultParent = mParent; } // ์ด์•Œ ๋ฐœ์‚ฌ else if( g_pHero->GetBulletState() == Object::BT_FIRE ) { mResultParent = mParent; // ์ฒซ ํ’์ฐจ๋งŒ ๋ฐœ์‚ฌ์‹œ์ผœ์ฃผ๋ฉด ๋‚˜๋จธ์ง€๋Š” ๊ณ„์ธต๊ตฌ์กฐ๋กœ ๋”ฐ๋ผ๊ฐ if( first ) { m_vPos += m_vDir * m_fSpeed * dTime * 5; // ์ผ์ •๊ฑฐ๋ฆฌ๊ฐ€ ์ง€๋‚˜๋ฉด BT_NORMAL ๋กœ ๋ณ€๊ฒฝ if( D3DXVec3Length(&(m_vPos - m_vHeroPos)) > 10 ) { g_pHero->SetBulletState(Object::BT_NORMAL); g_pHero->SetUseWing(); m_vPos = m_vOrgPos; m_vRot = m_vOrgRot; } BulletCollision(); // ์ถฉ๋Œ์ฒดํฌ D3DXMatrixTranslation(&m_mTrans, m_vPos.x, m_vPos.y, m_vPos.z); D3DXMatrixRotationYawPitchRoll(&m_mRot, m_vRot.y, m_vRot.x, m_vRot.z); } else D3DXMatrixRotationYawPitchRoll(&m_mRot, m_vRot.y, m_vRot.x, m_vRot.z); } } else { D3DXMatrixTranslation(&m_mTrans, m_vPos.x, m_vPos.y, m_vPos.z); D3DXMatrixRotationYawPitchRoll(&m_mRot, m_vRot.y, m_vRot.x, m_vRot.z); mResultParent = mParent; } } else { D3DXMatrixTranslation(&m_mTrans, m_vPos.x, m_vPos.y, m_vPos.z); D3DXMatrixRotationYawPitchRoll(&m_mRot, m_vRot.y, m_vRot.x, m_vRot.z); mResultParent = mParent; } m_mTM = m_mScale * m_mRot * m_mTrans * mResultParent; } // //์ถฉ๋Œ์ฒดํฌ // -> ๋ฐ˜์ง€๋ฆ„์„ ์ด์šฉํ•œ ๊ฑฐ๋ฆฌ์ฒดํฌ ์ถฉ๋Œ // void Wing::BulletCollision( void ) { for( int i = 0; i < TREE_MAX; ++i ) { if( m_pTree[i].GetTreeState() != Tree::TS_NORMAL ) continue; D3DXVECTOR3 vTreePos = m_pTree[i].m_vPos; // ์ถฉ๋ŒํŒ์ • if( D3DXVec3Length(&(vTreePos - m_vPos)) < m_fCollLength ) { D3DXVECTOR3 axis; D3DXVec3Cross(&axis, &(m_pTree[i].GetUpDir()), &m_vDir); m_pTree[i].SetCollAxis(axis); m_pTree[i].SetTreeState(Tree::TS_COLLISION); } } } void Wing::Render( D3DXMATRIX reflect, bool stencil ) { LPDIRECT3DTEXTURE9 pTex = NULL; //g_pDevice->SetTexture(0, m_pTexture); g_pDevice->SetMaterial(&m_mtr); g_pDevice->SetRenderState(D3DRS_LIGHTING, true); g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); g_pDevice->SetStreamSource( 0, m_pVB, 0, sizeof(D3DFVF_XYZ_NORMAL_TEX1) ); g_pDevice->SetFVF(FVF_XYZ_NORMAL_TEX1); if( !stencil ) g_pDevice->SetTransform(D3DTS_WORLD, &m_mTM); else g_pDevice->SetTransform(D3DTS_WORLD, &(m_mTM*reflect)); // ์•ŒํŒŒํ…Œ์ŠคํŒ… float alpha = 0.3f; g_pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); g_pDevice->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATER); g_pDevice->SetRenderState(D3DRS_ALPHAREF, (DWORD)(alpha * 255)); g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); g_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); g_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); // ๋ฉ€ํ‹ฐํ…์Šค์ฒ˜(๋งˆ์Šคํฌ๋งต) if( m_TexState != SWG_NONE ) { pTex = m_pMaskTexture[m_TexState]; // ============ stage 0 // 1-Mask g_pDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SUBTRACT); g_pDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_CONSTANT); g_pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, D3DXCOLOR(1,1,1,0)); g_pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_TEXTURE); g_pDevice->SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, 0); g_pDevice->SetTexture(0, g_bWireFrame ? NULL : pTex); // alpha g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_CONSTANT); // ============ stage 1 g_pDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE); g_pDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_pDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT); g_pDevice->SetTextureStageState(1, D3DTSS_TEXCOORDINDEX, 0); g_pDevice->SetTexture(1, g_bWireFrame ? NULL : m_pTexture); // alpha g_pDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_ADD); g_pDevice->SetTextureStageState(1, D3DTSS_ALPHAARG1, D3DTA_CURRENT); g_pDevice->SetTextureStageState(1, D3DTSS_ALPHAARG2, D3DTA_TEXTURE); // ============ stage 2 g_pDevice->SetTextureStageState(2, D3DTSS_COLOROP, D3DTOP_ADD); g_pDevice->SetTextureStageState(2, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_pDevice->SetTextureStageState(2, D3DTSS_COLORARG2, D3DTA_CURRENT); g_pDevice->SetTextureStageState(2, D3DTSS_TEXCOORDINDEX, 0); g_pDevice->SetTexture(2, g_bWireFrame ? NULL : pTex); // alpha g_pDevice->SetTextureStageState(2, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); g_pDevice->SetTextureStageState(2, D3DTSS_ALPHAARG1, D3DTA_CURRENT); // ============ stage 3 g_pDevice->SetTextureStageState(3, D3DTSS_COLOROP, D3DTOP_MODULATE); g_pDevice->SetTextureStageState(3, D3DTSS_COLORARG1, D3DTA_CURRENT); g_pDevice->SetTextureStageState(3, D3DTSS_COLORARG2, D3DTA_DIFFUSE); g_pDevice->SetTexture(3, NULL); // alpha g_pDevice->SetTextureStageState(3, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); g_pDevice->SetTextureStageState(3, D3DTSS_ALPHAARG1, D3DTA_CURRENT); g_pDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, m_iVtxCnt ); g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); g_pDevice->SetRenderState(D3DRS_LIGHTING, false); g_pDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE); g_pDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE); g_pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT); g_pDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); g_pDevice->SetTexture(0, NULL); // alpha g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); g_pDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); g_pDevice->SetTextureStageState(1, D3DTSS_ALPHAOP, D3DTOP_DISABLE); } else { pTex = m_pTexture; g_pDevice->SetTexture(0, g_bWireFrame ? NULL : pTex); g_pDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, m_iVtxCnt); g_pDevice->SetRenderState(D3DRS_LIGHTING, false); g_pDevice->SetTexture(0, NULL); } g_pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); g_pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO); g_pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); g_pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); if( g_bLightNormalRender ) RightLineDebugRender(); } void Wing::RightLineDebugRender( void ) { // ๋ฐฉํ–ฅ๋ผ์ธ ๊ทธ๋ฆฌ๊ธฐ // NORMAILLINEINFO info; for( int i = 0; i < m_iVtxCnt*3; ++i ) { ZeroMemory(&info, sizeof(info)); info.Lenth = 0.5f; info.mTM = m_mTM; info.vOrgPos= m_pVertex[i].vPos; info.vPos = D3DXVECTOR3(0,0,0); info.color = D3DXCOLOR(1,1,0,1); D3DXVec3TransformNormal(&info.vDir, &m_pVertex[i].vNormal, &m_mTM); NormalLineRender(info); } } void Wing::Release( void ) { SAFE_RELEASE(m_pTexture); SAFE_RELEASE(m_pVB); SAFE_DELETE_ARRAY(m_pVertex); for( int i = 0; i < SWG_MAX; ++i ) SAFE_RELEASE(m_pMaskTexture[i]); } void Wing::RenderStencil( D3DXVECTOR3 pos ) { // ํ‰๋ฉด ์ƒ์„ฑ D3DXPLANE plane; D3DXPlaneFromPointNormal(&plane, &pos, &D3DXVECTOR3(0, 1, 0)); // ๋ฐ˜์‚ฌ ํ–‰๋ ฌ ์ƒ์„ฑ D3DXMATRIX mReflect; D3DXMatrixReflect(&mReflect, &plane); // ์ตœ์ข… ํ–‰๋ ฌ D3DXMATRIX mTMReflect; D3DXMatrixMultiply(&mTMReflect, &m_mTM, &mReflect); // ๊ทธ๋ฆฌ๊ธฐ๋ชจ๋“œ ์„ค์ • g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); // ์ตœ์ข… ์›”๋“œ ํ–‰๋ ฌ ์„ค์ • g_pDevice->SetTransform(D3DTS_WORLD, &mTMReflect); Render(mTMReflect, true); //์˜ต์…˜ ๋ณต๊ตฌ. g_pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); }
#include <gtest/gtest.h> #include <string> using std::string; #include "../src/Utils.h" TEST(testUtils, parseInsertStatement){ Row* row = new Row; string target = "insert 1 username email@email.com"; parseInsertStatement(target, *row); EXPECT_EQ(1, row->id); EXPECT_STREQ("username", row->username); EXPECT_STREQ("email@email.com", row->email); // Second test row = new Row; target = "insert 2 vasya ema@company.com"; parseInsertStatement(target, *row); EXPECT_EQ(2, row->id); EXPECT_STREQ("vasya", row->username); EXPECT_STREQ("ema@company.com", row->email); }
#include <NPC.h> NPC::NPC() { if (!npcTexture.loadFromFile("E-100.png")) { std::string s("Error loading texture"); } npcSprite.setTexture(npcTexture); npcSprite.setPosition(300, 300); }; NPC::~NPC(){}; void NPC::initialize() { cout << "NPC initialize" << endl; } void NPC::update() { pos = npcSprite.getPosition(); npcSprite.setPosition(pos.x - 1, pos.y + 0); cout << "NPC updating" << endl; } void NPC::draw(sf::RenderWindow * t_window) { t_window->draw(npcSprite); cout << "NPC drawing" << endl; }
#include <iostream> #include <string> #include <fstream> #include <vector> #include <cstdio> #include <cstdlib> #include <string.h> #include "types.h" using namespace std; extern "C" void RayTraceImage(unsigned int*, int, int, int, float3, float3, float3, float3, float3, float3, float3, float3); extern "C" void bindTriangles(float*, unsigned int); void loadObj(const std::string filename, TriangleMesh &mesh, int scale) { std::ifstream in(filename.c_str()); if(!in.good()) { cout << "ERROR: loading obj:(" << filename << ") file is not good" << "\n"; exit(0); } char buffer[256], str[255]; float f1,f2,f3; while(!in.getline(buffer,255).eof()) { buffer[255]='\0'; //sscanf_s(buffer,"%s",str,255); memcpy(str, buffer, 255); // reading a vertex if (buffer[0]=='v' && (buffer[1]==' ' || buffer[1]==32) ) { if ( sscanf(buffer,"v %f %f %f",&f1,&f2,&f3)==3) { mesh.verts.push_back(make_float3(f1*scale,f2*scale,f3*scale)); } else { cout << "ERROR: vertex not in wanted format in OBJLoader" << "\n"; exit(-1); } } // reading FaceMtls else if (buffer[0]=='f' && (buffer[1]==' ' || buffer[1]==32) ) { TriangleFace f; int nt = sscanf(buffer,"f %d %d %d",&f.v[0],&f.v[1],&f.v[2]); if( nt!=3 ) { cout << "ERROR: I don't know the format of that FaceMtl" << "\n"; exit(-1); } mesh.faces.push_back(f); } } // calculate the bounding box mesh.bounding_box[0] = make_float3(1000000,1000000,1000000); mesh.bounding_box[1] = make_float3(-1000000,-1000000,-1000000); for(unsigned int i = 0; i < mesh.verts.size(); i++) { //update min value mesh.bounding_box[0].x = min(mesh.verts[i].x,mesh.bounding_box[0].x); mesh.bounding_box[0].y = min(mesh.verts[i].y,mesh.bounding_box[0].y); mesh.bounding_box[0].z = min(mesh.verts[i].z,mesh.bounding_box[0].z); //update max value mesh.bounding_box[1].x = max(mesh.verts[i].x,mesh.bounding_box[1].x); mesh.bounding_box[1].y = max(mesh.verts[i].y,mesh.bounding_box[1].y); mesh.bounding_box[1].z = max(mesh.verts[i].z,mesh.bounding_box[1].z); } cout << "obj file loaded: number of faces:" << mesh.faces.size() << " number of vertices:" << mesh.verts.size() << endl; cout << "obj bounding box: min:(" << mesh.bounding_box[0].x << "," << mesh.bounding_box[0].y << "," << mesh.bounding_box[0].z <<") max:" << mesh.bounding_box[1].x << "," << mesh.bounding_box[1].y << "," << mesh.bounding_box[1].z <<")" << endl; }
// Restaurant Tables.cpp : ๅฎšไน‰ๆŽงๅˆถๅฐๅบ”็”จ็จ‹ๅบ็š„ๅ…ฅๅฃ็‚นใ€‚ //codeforces 828A Restaurant Tables //ไธ€ไธช้ฅญๅบ—ๅชๆœ‰ไธ€ไบบๆกŒๅ’Œ2ไบบๆกŒ๏ผŒๅฆ‚ๆžœๆฅ็š„ไธชไบบๆ˜ฏ1ไบบๅˆ™ไผ˜ๅ…ˆๅฎ‰ๆŽ’1ไบบๆกŒๅไธ‹๏ผŒๅฆ‚ๆžœๆฒกๆœ‰ไธ€ไบบๆกŒๅˆ™ๅฎ‰ๆŽ’็ฉบ็š„2ไบบๆกŒ๏ผŒ //ๅฆ‚ๆžœๆฒกๆœ‰็ฉบ็š„2ไบบๆกŒๅˆ™ๅฎ‰ๆŽ’ๆ‹ผๆกŒ๏ผŒๅฆๅˆ™ๆ‹’็ปๆœๅŠก๏ผ›ๅฆ‚ๆžœๆฅ็š„ๆ˜ฏไธคไบบ๏ผŒๆœ‰็ฉบไฝ™็š„ไธคไบบๆกŒๅˆ™ๆไพ›ๆœๅŠก๏ผŒๅฆๅˆ™ๆ‹’็ปๆœๅŠกใ€‚ //็ป™ๅฎšๅฎขไบบไฟกๆฏไปฅๅŠไธ€ไบบๆกŒ็š„ๆ•ฐ็›ฎๅ’Œ2ไบบๆกŒ็š„ๆ•ฐ็›ฎ๏ผŒ้—ฎไผšๆœ‰ๅคšๅฐ‘ๅฎขไบบ่ขซๆ‹’็ปๆœๅŠกใ€‚ //่งฃ้ข˜ๆ€่ทฏ๏ผšๅ…ˆๅฎšไน‰ไธ€ไธชๅ˜้‡่ฎฐๅฝ•2ไบบๆกŒๅชๅไบ†1ไบบ็š„ๆ•ฐ้‡num2Only1๏ผŒๆฅไธ€็ป„ๅฎขไบบ๏ผŒๅ…ˆๅˆคๆ–ญไธ€ไธ‹ไป–ๆ˜ฏไธ€ไบบ่ฟ˜ๆ˜ฏไธคไบบใ€‚ // ๅฆ‚ๆžœๆ˜ฏ1ไบบ๏ผŒๅˆ™ๅ…ˆ็œ‹ไธ€ไธ‹ไธ€ไบบๆกŒๆ˜ฏไธๆ˜ฏๆœ‰็ฉบไฝ็ฝฎ๏ผŒๅฆ‚ๆžœไธ€ไบบๆกŒๆฒกๆœ‰็ฉบไฝ็ฝฎๅฐฑ็œ‹ไธ€ไธ‹ไบŒไบบๆกŒๆœ‰ๆฒกๆœ‰็ฉบไฝ็ฝฎ๏ผŒ // ๅฆ‚ๆžœไบŒไบบๆกŒไนŸๆฒกๆœ‰็ฉบไฝ็ฝฎๅˆ™ๅˆคๆ–ญ2ไบบๆกŒๅชๅไบ†1ไบบๆ˜ฏๅฆๆœ‰็ฉบไฝ๏ผŒๆœ‰ๅˆ™ๅฎ‰ๆŽ’ๆ— ๅˆ™ๆ‹’็ป๏ผ› // ๅฆ‚ๆžœๆ˜ฏ2ไบบ๏ผŒ็›ดๆŽฅ็œ‹2ไบบๆกŒๆœ‰ๆฒกๆœ‰๏ผŒๆฒกๆœ‰็›ดๆŽฅๆ‹’็ปๆœๅŠกใ€‚ #include<iostream> using namespace std; int main() { int n, a, b;//n็ป„ไบบ๏ผŒaๅผ ๅ•ไบบๆกŒ๏ผŒbๅผ ๅŒไบบๆกŒ cin >> n >> a >> b; int i; int mem[200005]; int num2only1 = 0; int num = 0; for (i = 0; i < n; i++) { cin >> mem[i]; if (mem[i] == 1) { if (a)//ๅ…ˆๅฎ‰ๆŽ’1ไบบ็ป„๏ผŒๆœ‰ๅ•ไบบๆกŒๆ—ถๅฎ‰ๆŽ’ๅœจๅ•ไบบๆกŒ { a -= 1; mem[i] = 0; } else if (a == 0 && b)//ๆฒกๆœ‰ๅ•ไบบๆกŒ๏ผŒๆœ‰ๅŒไบบๆกŒๆ—ถๅฎ‰ๆŽ’ๅœจๅŒไบบๆกŒ { b -= 1; mem[i] = 0; num2only1++; } else if (num2only1)//ๅฆ‚ๆžœๆฒกๆœ‰็ฉบไฝ™็š„ๅŒไบบๆกŒ๏ผŒๆœ‰ๅฏไปฅๆ‹ผๆกŒ็š„ๅฎ‰ๆŽ’ๆ‹ผๆกŒ { mem[i] = 0; num2only1--; } } else if(mem[i] == 2) { if (b) { b -= 1; mem[i] = 0; } } } for (i = 0; i < n; i++) { if (mem[i] == 1) num++; else if (mem[i] == 2) num += 2; } cout << num << endl; system("pause"); return 0; }
#pragma once #include "Renderer.h" class FrameBuffer { public: FrameBuffer(int width, int height); ~FrameBuffer(); void Bind(); void BindRenderBuffer(); void BindTexture(); void Unbind(); void UnbindRenderBuffer(); void UnbindTexture(); private: int m_Width; int m_Height; unsigned int m_RendererID; unsigned int m_TextureID; unsigned int m_RenderBufferID; };
// // Created by HHPP on 2020/4/29. // #include "Rectangular.h" #include "Point.h" #include <iostream> Rectangular::Rectangular() { for(int i=0;i<4;i++){ rec[i].set(0,0); } } void Rectangular::setPoint(int i, double newX, double newY) { rec[i].set(newX,newY); } double Rectangular::area() { double width=rec[1].getX()-rec[0].getX(); double height=rec[3].getY()-rec[0].getY(); return width*height; }
#include <avr/io.h> #include "display_SSD1309.h" displaySDD1309Sim::displaySDD1309Sim(i2cSim* i2c, int id) { i2c->registerDevice(id, DELEGATE(i2cMessageDelegate, displaySDD1309Sim, *this, processMessage)); lcd_data_pos = 0; } displaySDD1309Sim::~displaySDD1309Sim() { } void displaySDD1309Sim::processMessage(uint8_t* message, int length) { if (message[1] == 0x40) { //Data for(int n=2;n<length;n++) { lcd_data[lcd_data_pos] = message[n]; lcd_data_pos = (lcd_data_pos + 1) % 1024; } }else if (message[1] == 0x00) { //Command for(int n=2;n<length;n++) { if ((message[n] & 0xF0) == 0x00) { lcd_data_pos = (lcd_data_pos & 0xFF0) | (message[n] & 0x0F); }else if ((message[n] & 0xF0) == 0x10) { lcd_data_pos = (lcd_data_pos & 0xF8F) | ((message[n] & 0x07) << 4); }else if ((message[n] & 0xF0) == 0xB0) { lcd_data_pos = (lcd_data_pos & 0x07F) | ((message[n] & 0x0F) << 7); }else if (message[n] == 0x20) { /*LCD_COMMAND_SET_ADDRESSING_MODE*/ }else if (message[n] == 0x40) { /*Set start line*/ }else if (message[n] == 0x81) { /*LCD_COMMAND_CONTRAST*/ n++; }else if (message[n] == 0xA1) { /*Segment remap*/ }else if (message[n] == 0xA4) { /*LCD_COMMAND_FULL_DISPLAY_ON_DISABLE*/ }else if (message[n] == 0xA5) { /*LCD_COMMAND_FULL_DISPLAY_ON_ENABLE*/ }else if (message[n] == 0xA8) { /*Multiplex ratio*/ n++; }else if (message[n] == 0xC8) { /*COM scan output direction*/ }else if (message[n] == 0xD3) { /*Display offset*/ n++; }else if (message[n] == 0xD5) { /*Display clock divider/freq*/ n++; }else if (message[n] == 0xD9) { /*Precharge period*/ n++; }else if (message[n] == 0xDA) { /*COM pins hardware configuration*/ n++; }else if (message[n] == 0xDB) { /*VCOMH Deslect level*/ n++; }else if (message[n] == 0xFD) { /*LCD_COMMAND_LOCK_COMMANDS*/ n++; }else if (message[n] == 0xAE) { //Display OFF }else if (message[n] == 0xAF) { //Display ON }else{ printf("Unknown LCD CMD: %02x\n", message[n]); } } } } #define LCD_GFX_WIDTH 128 #define LCD_GFX_HEIGHT 64 void displaySDD1309Sim::draw(int x, int y) { drawRect(x, y, LCD_GFX_WIDTH + 2, LCD_GFX_HEIGHT + 2, 0xFFFFFF); drawRect(x+1, y+1, LCD_GFX_WIDTH, LCD_GFX_HEIGHT, 0x101010); for(int _y=0;_y<64;_y++) { for(int _x=0;_x<128;_x++) { if (lcd_data[_x + (_y/8) * LCD_GFX_WIDTH] & _BV(_y%8)) { drawRect(x+_x+1, y+_y+1, 1, 1, 0x8080FF); drawRect(x+_x+1, y+_y+1, 0, 1, 0x8080AF); drawRect(x+_x+1, y+_y+1, 1, 0, 0x8080AF); }else{ drawRect(x+_x+1, y+_y+1, 0, 1, 0x202020); drawRect(x+_x+1, y+_y+1, 1, 0, 0x202020); } } } /* SDL_LockSurface(screen); for(int y=0;y<64;y++) { for(int _y=0;_y<DRAW_SCALE;_y++) { uint32_t* pix = ((uint32_t*)screen->pixels) + screen->pitch / 4 * (y * DRAW_SCALE + _y + DRAW_SCALE); for(int _n=0;_n<DRAW_SCALE;_n++) *pix++ = 0xFFFFFF; for(int x=0;x<128;x++) { for(int _n=0;_n<DRAW_SCALE;_n++) { if (_n == 0 || _y == 0) *pix++ = (lcd_data[x + (y/8) * LCD_GFX_WIDTH] & _BV(y%8)) ? 0x8080AF : 0x101010; else *pix++ = (lcd_data[x + (y/8) * LCD_GFX_WIDTH] & _BV(y%8)) ? 0x8080FF : 0x202020; } } for(int _n=0;_n<DRAW_SCALE;_n++) *pix++ = 0xFFFFFF; } } for(int _y=0;_y<DRAW_SCALE;_y++) { uint32_t* pix = ((uint32_t*)screen->pixels) + screen->pitch / 4 * (_y); uint32_t* pix2 = ((uint32_t*)screen->pixels) + screen->pitch / 4 * (64 * DRAW_SCALE + _y + DRAW_SCALE); for(int x=0;x<130;x++) for(int _n=0;_n<DRAW_SCALE;_n++) { *pix++ = 0xFFFFFF; *pix2++ = 0xFFFFFF; } } SDL_UnlockSurface(screen); */ }
#ifndef TREE_PROPAGATOR_H #define TREE_PROPAGATOR_H #include <chuffed/globals/graph.h> #include <chuffed/support/union_find.h> #include <map> #include <queue> #include <set> #include <stack> #include <unordered_set> #include <vector> #define OTHER(o1, o2, a) (((a) == (o1)) ? (o2) : (o1)) // #define INFINITY 10000 typedef int edge_id; typedef int node_id; struct partialExpl { edge_id bridge; node_id cause1; node_id cause2; partialExpl() : cause2(-1) {} }; class TreePropagator : public GraphPropagator { public: struct CC { int count; std::vector<int> nodesIds; CC() : count(0) {} }; static std::vector<TreePropagator*> tree_propagators; protected: std::vector<std::vector<std::vector<int> > > nodes2edge; // fancy unionfind UF<Tint> uf; RerootedUnionFind<Tint> ruf; Tint nb_innodes; Tint nb_avn; std::unordered_set<int> newFixedN; std::unordered_set<int> newFixedE; bool* isTerminal; std::vector<int> in_edges; Tint in_edges_tsize; int in_edges_size; enum VType { VT_IN, VT_OUT, UNK }; std::vector<Tint> last_state_n; std::vector<Tint> last_state_e; edge_id findEdge(int u, int v, int idx = 0); void moveInEdgeToFront(int e); void _findAndBuildBridges(int u, int& count, std::stack<edge_id>& s, int depth[], int low[], std::vector<bool>& visited, int parent[], std::stack<node_id>& hits, std::vector<std::pair<edge_id, node_id> >& semiExpl, std::vector<partialExpl>& bridgeExpl, std::vector<partialExpl>& articuExpl); int articulations(int n, std::vector<bool>& reachable, int& count); bool reachable(int n, std::vector<bool>& blue, bool doDFS = false); virtual void unite(int u, int v); virtual bool cycle_detect(int edge); virtual void precycle_detect(int unk_edge); int newNodeCompleteCheckup_Count; bool newNodeCompleteCheckup; // std::vector<CC> keys; public: TreePropagator(vec<BoolView>& _vs, vec<BoolView>& _es, vec<vec<edge_id> >& _adj, vec<vec<int> >& _en); ~TreePropagator() override; void wakeup(int i, int c) override; bool propagate() override; void clearPropState() override; // Walks only on fixed edges == 1 void getCC(int node, std::vector<bool>& visited, CC* cc); void getAvailableCC(int node, std::vector<bool>& visited, CC* cc); virtual bool propagateNewNode(int node); virtual bool propagateRemNode(int node); virtual bool propagateNewEdge(int edge); virtual bool propagateRemEdge(int edge); void getUnkEdgesInCC(int r, std::vector<bool>& visited, std::unordered_set<edge_id>& unk); void DFSBlue(int r, std::vector<bool>& visited, int& count); void DFSPink(int r, std::vector<bool>& visited, std::vector<bool>& blue, std::unordered_set<int>& badEdges); void walkIsland(int r, std::vector<bool>& visited, int avoidBridge, bool isArt = false, int parent = -1); void walkBrokenBridges(int r, std::vector<bool>& reachable, std::vector<bool>& walked, std::vector<bool>& visited, int avoidBridge, std::vector<edge_id>& bridges, bool isArt = false, int parent = -1); virtual bool checkFinalSatisfied(); // virtual void getKeys(KSP* starting, vec<KSP*>& probs); // virtual void updateUF(KSP& ksp); // void _updateUF(KSP& ksp, int n, int& d, // std::vector<bool>& visited, // std::vector<int>& parent, // std::vector<int>& depth, // std::vector<int>& low, // std::stack<int>& seen // ); }; class ConnectedPropagator : public TreePropagator { protected: bool cycle_detect(int edge) override { return true; } void precycle_detect(int unk_edge) override {} void unite(int u, int v) override { if (uf.connected(u, v)) { return; } if (!getNodeVar(u).isFixed()) { uf.unite(u, v); ruf.unite(u, v); assert(ruf.isRoot(v)); } else { uf.unite(v, u); ruf.unite(v, u); assert(ruf.isRoot(u)); } } public: ConnectedPropagator(vec<BoolView>& _vs, vec<BoolView>& _es, vec<vec<edge_id> >& _adj, vec<vec<int> >& _en) : TreePropagator(_vs, _es, _adj, _en) {} bool checkFinalSatisfied() override { return true; /*TODO*/ } }; #endif
/* ============================= * | Name: Abhishek Mantha | * | Email: amantha@usc.edu | * | GitHub: abmantha | * | Date Submitted: 2/13/15 | * | HW 3 | * ============================== * * Filename: setint.cpp * * Directions from bits.usc.edu/cs104/assignments/hw3: * * Implement a basic Set class using your * LListInt implementation in Problem 2. * */ #include "../lib/setint.h" #include <cstdlib> #include <algorithm> #include <iostream> using namespace std; /* SetInt default constructor */ SetInt::SetInt() { iter_ = 0; } /* SetInt destructor */ SetInt::~SetInt() { } /* SetInt copy constructor * Utilizes LListInt assignment overload * and copy constructor. Return new SetInt. */ SetInt::SetInt(const SetInt& other) { this->list_ = other.list_; } /* Assignment= operator overload * Utilizes LListInt assignment overload * and copy constructor. Returns new SetInt. */ SetInt& SetInt::operator=(const SetInt& other) { if (this == &other) return *this; this->list_ = other.list_; return *this; } /* Returns the current number of items in the list */ int SetInt::size() const { return list_.size(); } /* Returns true if the list is empty, false otherwise */ bool SetInt::empty() const { return list_.empty(); } /* Inserts val so it appears at index, pos */ void SetInt::insert(const int& val) { if (!exists(val)) { list_.push_back(val); } } /* Remove the value at index, pos */ void SetInt::remove(const int& val) { if (exists(val)) { int pos = getIndex(val); list_.remove(pos); } } /* Returns true if the item is in the set */ bool SetInt::exists(const int& val) const { for (int i = 0; i < list_.size(); i++) { if (list_.get(i) == val) { return true; } } return false; } /* Return a pointer to the first item * and support future calls to next() */ int const* SetInt::first() { iter_ = 0; if (empty()) { return NULL; } int* head = &(list_.get(iter_)); iter_++; return head; } /* Return a pointer to the next item * after the previous call to next * and NULL if you reach the end */ int const* SetInt::next() { if (!empty()) { if (iter_ < list_.size()) { int* next = &(list_.get(iter_)); iter_++; return next; } } return NULL; } /* Returns another (new) set that contains * the union of this set and "other" */ SetInt SetInt::setUnion(const SetInt& other) const { //how to make more efficient??? SetInt s = other; for (int i = 0; i < list_.size(); i++) { int val = list_.get(i); if (!s.exists(val)) { s.insert(val); } } return s; } /* Returns another (new) set that contains * the intersection of this set and "other" */ SetInt SetInt::setIntersection(const SetInt& other) const { SetInt s; if (other.empty() && empty()) { return s; } if (other.empty() && !empty()) { s = *this; return s; } if (!other.empty() && empty()) { s = other; return s; } for (int i = 0; i < other.size(); i++) { int val = other.list_.get(i); if (exists(val)) { s.insert(val); } } return s; } /* Operator | overload. Returns new SetInt from * setUnion() */ SetInt SetInt::operator|(const SetInt& other) const { return setUnion(other); } /* Operator & overload. Returns new SetInt from * setIntersection() */ SetInt SetInt::operator&(const SetInt& other) const { return setIntersection(other); } /* Return the index of item with value val */ int SetInt::getIndex(int val) const { for (int i = 0; i < list_.size(); i++) { if (list_.get(i) == val) { return i; } } return -1; }
/* * @Description: back end ไปปๅŠก็ฎก็†๏ผŒ ๆ”พๅœจ็ฑป้‡Œไฝฟไปฃ็ ๆ›ดๆธ…ๆ™ฐ * @Author: Ren Qian * @Date: 2020-02-10 08:31:22 */ #ifndef LIDAR_LOCALIZATION_MAPPING_BACK_END_FRONT_END_FLOW_HPP_ #define LIDAR_LOCALIZATION_MAPPING_BACK_END_FRONT_END_FLOW_HPP_ #include <ros/ros.h> #include "lidar_localization/subscriber/cloud_subscriber.hpp" #include "lidar_localization/subscriber/odometry_subscriber.hpp" #include "lidar_localization/subscriber/loop_pose_subscriber.hpp" #include "lidar_localization/publisher/odometry_publisher.hpp" #include "lidar_localization/publisher/key_frame_publisher.hpp" #include "lidar_localization/publisher/key_frames_publisher.hpp" #include "lidar_localization/mapping/back_end/back_end.hpp" namespace lidar_localization { class BackEndFlow { public: BackEndFlow(ros::NodeHandle& nh, std::string cloud_topic, std::string odom_topic); bool Run(); bool ForceOptimize(); private: bool ReadData(); bool MaybeInsertLoopPose(); bool HasData(); bool ValidData(); bool UpdateBackEnd(); bool PublishData(); private: std::shared_ptr<CloudSubscriber> cloud_sub_ptr_; std::shared_ptr<OdometrySubscriber> gnss_pose_sub_ptr_; std::shared_ptr<OdometrySubscriber> laser_odom_sub_ptr_; std::shared_ptr<LoopPoseSubscriber> loop_pose_sub_ptr_; std::shared_ptr<OdometryPublisher> transformed_odom_pub_ptr_; std::shared_ptr<KeyFramePublisher> key_frame_pub_ptr_; std::shared_ptr<KeyFramePublisher> key_gnss_pub_ptr_; std::shared_ptr<KeyFramesPublisher> key_frames_pub_ptr_; std::shared_ptr<BackEnd> back_end_ptr_; std::deque<CloudData> cloud_data_buff_; std::deque<PoseData> gnss_pose_data_buff_; std::deque<PoseData> laser_odom_data_buff_; std::deque<LoopPose> loop_pose_data_buff_; PoseData current_gnss_pose_data_; PoseData current_laser_odom_data_; CloudData current_cloud_data_; }; } #endif
/* * Stopping Times * Copyright (C) Leonardo Marchetti 2011 <leonardomarchetti@gmail.com> */ #ifndef _FUNCTOR_2D_H_ #define _FUNCTOR_2D_H_ namespace StoppingTimes{ /* FP is a template for Floating Point types. */ template <typename FP> class Functor2D { public: Functor2D(); virtual ~Functor2D(); virtual FP operator()(FP x, FP y); protected: private: }; #include "functor2D.inl" } #endif // _FUNCTOR_2D_H_
/*********************************************************\ * Copyright (c) 2012-2018 The Unrimp Team * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*********************************************************/ #pragma once #include <map> #include <set> #include <string> #include <vector> class CommandLineArguments; class ExampleRunner { public: virtual int run(const CommandLineArguments &args) = 0; virtual ~ExampleRunner(); protected: typedef int(*RunnerMethod)(const char*); typedef std::map<std::string, RunnerMethod> AvailableExamplesMap; typedef std::set<std::string> AvailableRendererMap; typedef std::map<std::string, std::vector<std::string>> ExampleToSupportedRendererMap; ExampleRunner(); virtual void printUsage(const AvailableExamplesMap &knownExamples, const AvailableRendererMap &availableRenderer) = 0; virtual void showError(const std::string& errorMessage) = 0; int runExample(const std::string &rendererName, const std::string &exampleName); private: template<typename T> void addExample(const std::string& name, RunnerMethod runnerMethod, T const &supportedRendererList); protected: AvailableExamplesMap m_availableExamples; AvailableRendererMap m_availableRenderer; ExampleToSupportedRendererMap m_supportedRendererForExample; std::string m_defaultRendererName; std::string m_defaultExampleName; };
/** * @file Test_LinkedListOfInts.cpp * @author Jason Purinton * @Reference John Gibbons * @date 2018.11.4 **/ #include "Test_LinkedListOfInts.h" Test_LinkedListOfInts::Test_LinkedListOfInts(int numNodes) { } void Test_LinkedListOfInts::runTests(){ //Call to tests "tx()". Prints results and returns bool true==pass t1();//Is size zero? t2(); t3(); t4(); t5(); t6(); t7(); t8(); t9(); } bool Test_LinkedListOfInts::t1(){ m_testNum++; LinkedListOfInts list; printTestMessage(" isEmpty()= true for new list: "); if(list.isEmpty()== true){ m_bool= true; } else{ m_bool= false; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t2(){ m_testNum++; LinkedListOfInts list; printTestMessage(" isEmpty()= false one addFront() and one addBack; "); list.addFront(1); list.addBack(4); if(list.isEmpty()){ std::cout<<"LinkledList.size= "<<list.size()<<": "; m_bool= false; } else{ std::cout<<"LinkledList.size = "<<list.size()<<": "; m_bool= true; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t3(){ m_testNum++; LinkedListOfInts list; printTestMessage(" size()= 0 for new empty list? "); if(list.size()== 0){ std::cout<<"LinkledList.size= "<<list.size()<<": "; m_bool= true; } else{ std::cout<<"LinkledList.size= "<<list.size()<<": "; m_bool= false; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t4(){ m_testNum++; LinkedListOfInts list; printTestMessage(" size()= 5 for three addFront() and two addBack() "); list.addFront(1); list.addFront(2); list.addFront(3); list.addBack(4); list.addBack(5); if(list.size()== 5){ std::cout<<"LinkledList.size= "<<list.size()<<": "; m_bool= true; } else{ std::cout<<"LinkledList.size= "<<list.size()<<": "; m_bool= false; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t5(){ m_testNum++; LinkedListOfInts list; printTestMessage(" search() is correct index with 3 addFront and 2 addBack with multiples of the same value: "); list.addFront(-1); list.addFront(-1); list.addFront(0); list.addBack(1); list.addBack(1); if(list.search(-1) == false){ m_bool= false; } else if(list.search(0) == false){ m_bool= false; } else if(list.search(1) == false){ m_bool= false; } else if(list.search(4) == false){ m_bool= false; } else if(list.search(5) == false){ m_bool= false; } else if(list.search(-2) == true){ m_bool= false; } else if(list.search(2) == true){ m_bool= false; } else{ m_bool= true; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t6(){ m_testNum++; LinkedListOfInts list; printTestMessage(" addFront(3) to the front of list? "); list.addFront(1); list.addFront(2); int beforeFront= list.toVector()[0]; list.addFront(3); int afterFront= list.toVector()[0]; if(beforeFront== afterFront){ std::cout<<"Value of front before addFront()= "<<beforeFront<<", Value of front after addFront(3)= "<<list.toVector()[0]<<": "; m_bool= false; } else{ std::cout<<"Value of front before addFront()= "<<beforeFront<<", Value of front after addFront(3)= "<<list.toVector()[0]<<": "; m_bool= true; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t7(){ m_testNum++; LinkedListOfInts list; printTestMessage(" addBack(3) add 3 to the back of list? "); list.addBack(1); list.addBack(2); int beforeBack= list.toVector()[1]; list.addBack(3); int afterBack= list.toVector()[2]; if(beforeBack== afterBack){ std::cout<<"Value of back before addback()= "<<beforeBack<<", Value of back after addback(3)= "<<afterBack<<": "; m_bool= false; } else{ std::cout<<"Value of back before addback()= "<<beforeBack<<", Value of back after addback(3)= "<<afterBack<<": "; m_bool= true; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t8(){ m_testNum++; LinkedListOfInts list; printTestMessage(" removeFront() of list? "); list.addFront(1); list.addFront(2); list.addFront(3); int beforeFront= list.toVector()[0]; list.removeFront(); int afterFront= list.toVector()[0]; if(beforeFront== afterFront){ std::cout<<"Value of front before removeFront()= "<<beforeFront<<", Value of front after removeFront()= "<<afterFront<<": "; m_bool= false; } else{ std::cout<<"Value of front before removeFront()= "<<beforeFront<<", Value of front after removeFront(3)= "<<afterFront<<": "; m_bool= true; } printPassFail(m_bool); return m_bool; } bool Test_LinkedListOfInts::t9(){ m_testNum++; LinkedListOfInts list; printTestMessage(" removeBack() of list? "); list.addBack(1); list.addBack(2); list.addBack(3); int beforeBack= list.toVector()[2]; list.removeBack(); int afterBack= list.toVector()[2]; if(beforeBack== afterBack){ std::cout<<"Value of back before removeBack()= "<<beforeBack<<", Value of back after removeBack()= "<<afterBack<<": "; m_bool= false; } else{ std::cout<<"Value of back before removeBack()= "<<beforeBack<<", Value of back after removeBack()= "<<afterBack<<": "; m_bool= true; } printPassFail(m_bool); return m_bool; } void Test_LinkedListOfInts::printPassFail(bool isPassed) const { if(isPassed) std::cout<< "PASSED" << std::endl; else std::cout << "FAILED" << std::endl; } void Test_LinkedListOfInts::printTestMessage(std::string testDescription) const { std::cout << "Test " <<m_testNum<< testDescription; }
//็ฎ—ๆณ•:ๆ•ฐ่ฎบ/ๆฌงๆ‹‰ๅ‡ฝๆ•ฐ /* ๆฒฟ็€ๅฏน่ง’็บฟ ๅฐ†่ฟ™ไธชๆญฃๆ–นๅฝขๅˆ‡ๅผ€๏ผŒ ๅพ—ๅˆฐไธคไธช็›ด่ง’ไธ‰่ง’ๅฝขใ€‚ ๅ‘็Žฐ๏ผŒๅฎž้™…ไธŠ่ฆๆฑ‚็š„็ญ”ๆกˆ ๅคงๆฆ‚ๅฐฑๆ˜ฏๅœจ1ๅˆฐn็š„่Œƒๅ›ด้‡Œ ไธๅŒ็š„gcd๏ผˆi๏ผŒj๏ผ‰็š„ไธชๆ•ฐ๏ผŒ ๅฏนไบŽไธ€ไธช็‰นๅฎš็š„i๏ผŒ gcd๏ผˆi๏ผŒj๏ผ‰็š„ไธชๆ•ฐ ๅฐฑๆ˜ฏi-1็š„ๆฌงๆ‹‰ๅ‡ฝๆ•ฐๅ€ผใ€‚ ้‚ฃไนˆ่ฟ™ไธช้—ฎ้ข˜ ่ฝฌๅŒ–ๆˆไธบไบ†ๆฌงๆ‹‰ๅ‡ฝๆ•ฐ็š„็‰ˆๅญ้ข˜ใ€‚ */ #include<cstdio> using namespace std; int n,num; int phi[100010]={0,1}; int p[100010]; bool vis[100010]={1,1}; void prime(int n)//ๆฌงๆ‹‰็ญ›ๆฑ‚ๆฌงๆ‹‰ๅ‡ฝๆ•ฐๅ€ผ { for(int i=2;i<=n;i++) { if(!vis[i]) p[++num]=i,phi[i]=i-1;//่ดจๆ•ฐ็š„ๆฌงๆ‹‰ๅ‡ฝๆ•ฐๅ€ผ for(int j=1;j<=num;j++) { if(i*p[j]>=n) break; vis[i*p[j]]=1; if(i%p[j]==0) { phi[i*p[j]]=phi[i]*p[j];//ๅˆๆ•ฐ็š„ๆฌงๆ‹‰ๅ‡ฝๆ•ฐๅ€ผ break; } else phi[i*p[j]]=phi[i]*phi[p[j]];//็”ฑๆœ€ๅฐๅ…ฌๅ› ๅญๆฑ‚ๅพ—ๆฌงๆ‹‰ๅ‡ฝๆ•ฐๅ€ผ } } } signed main() { scanf("%d",&n); if(n==1) //n==1ๆ—ถ็š„็‰นๅˆค { printf("0"); return 0; } prime(n); int ans=0; for(int i=1;i<=n-1;i++)//ๆฑ‚ๅ’Œ ans+=phi[i]; printf("%d",ans*2+1);//่Žทๅพ—็ญ”ๆกˆ }
๏ปฟ//************************************************************************************************************* // // ใ‚ทใƒผใƒณ2Dๅ‡ฆ็†[Scene2D.cpp] // Author : Sekine Ikuto // //************************************************************************************************************* //------------------------------------------------------------------------------------------------------------- // ใ‚คใƒณใ‚ฏใƒซใƒผใƒ‰ใƒ•ใ‚กใ‚คใƒซ //------------------------------------------------------------------------------------------------------------- #include "Scene2D.h" #include "manager.h" #include "keyboard.h" #include "DebugProc.h" #include "..\mystd\utility.h" //------------------------------------------------------------------------------------------------------------- // ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ //------------------------------------------------------------------------------------------------------------- CScene2D::CScene2D(CScene::PRIORITY priority) : CScene(priority) { m_bDisp = true; m_UpdateFlags.data = 0; } //------------------------------------------------------------------------------------------------------------- // ใƒ‡ใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ //------------------------------------------------------------------------------------------------------------- CScene2D::~CScene2D() { } //------------------------------------------------------------------------------------------------------------- // ็”Ÿๆˆ //------------------------------------------------------------------------------------------------------------- CScene2D * CScene2D::Create(CScene::PRIORITY priority, D3DXVECTOR3 pos, D3DXVECTOR2 size, D3DXCOLOR col, float fRotation, ORIGINVERTEXTYPE OriginType, SETING_UV TexUVInfo) { CScene2D *ptr = new CScene2D(priority); ptr->SetColor(col); ptr->SetOriginType(OriginType); ptr->SetPosition(pos); ptr->SetRotation(fRotation); ptr->SetSize(size); ptr->Init(); return ptr; } //------------------------------------------------------------------------------------------------------------- // ๅˆๆœŸๅŒ– //------------------------------------------------------------------------------------------------------------- void CScene2D::Init(void) { // ๅค‰ๆ•ฐๅฎฃ่จ€ LPDIRECT3DDEVICE9 pDevice = CManager::GetRenderer().GetDevice(); m_bDisp = true; // ้ ‚็‚นใฎไฝœๆˆ this->MakeVatex(pDevice); } //------------------------------------------------------------------------------------------------------------- // ็ต‚ไบ† //------------------------------------------------------------------------------------------------------------- void CScene2D::Uninit(void) { if (m_pVtxBuff != NULL) { m_pVtxBuff->Release(); m_pVtxBuff = NULL; } } //------------------------------------------------------------------------------------------------------------- // ๆ›ดๆ–ฐ //------------------------------------------------------------------------------------------------------------- void CScene2D::Update(void) { if (m_UpdateFlags.data != 0) { UpdateVertex(m_UpdateFlags.pos, m_UpdateFlags.col, m_UpdateFlags.tex); m_UpdateFlags.data = 0; } } //------------------------------------------------------------------------------------------------------------- // ๆ็”ป //------------------------------------------------------------------------------------------------------------- void CScene2D::Draw(void) { // ใƒ‡ใƒใ‚คใ‚นใฎๅ–ๅพ— LPDIRECT3DDEVICE9 pDevice = CManager::GetRenderer().GetDevice(); // ้ ‚็‚นใƒใƒƒใƒ•ใ‚กใ‚’ใ‚นใƒˆใƒชใƒผใƒ ใซใƒใ‚คใƒณใƒ‰ pDevice->SetStreamSource(0, m_pVtxBuff, 0, sizeof(CRenderer::VERTEX_2D)); // ้ ‚็‚นใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆ่จญๅฎš pDevice->SetTexture(0, m_pTexture); // ใƒ†ใ‚ฏใ‚นใƒใƒฃใฎ่จญๅฎš pDevice->SetFVF(FVF_VERTEX_2D); if (m_bDisp) { // ใƒใƒชใ‚ดใƒณๆ็”ป pDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); } } //------------------------------------------------------------------------------------------------------------- // ้ ‚็‚นๆƒ…ๅ ฑใฎๆ›ดๆ–ฐ //------------------------------------------------------------------------------------------------------------- void CScene2D::UpdateVertex(bool bUpdatePos, bool bUpdateCol, bool bUpdateUVTex) { // ้ ‚็‚นๆƒ…ๅ ฑใธใฎใƒใ‚คใƒณใ‚ฟ CRenderer::VERTEX_2D *pVtx; // ้ ‚็‚นใƒ‡ใƒผใ‚ฟใฎ็ฏ„ๅ›ฒใƒญใƒƒใ‚ฏใ—ใ€้ ‚็‚นใƒใƒƒใƒ•ใ‚กใธใฎใƒใ‚คใƒณใ‚ฟๅ–ๅพ— m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0); if (bUpdatePos) { this->SetVatexPosition(pVtx); } if (bUpdateCol) { this->SetVatexColor(pVtx); } if (bUpdateUVTex) { this->SetVatexTexture(pVtx); } // ้ ‚็‚นใƒ‡ใƒผใ‚ฟใ‚’ใ‚ขใƒณใƒญใƒƒใ‚ฏ m_pVtxBuff->Unlock(); } //------------------------------------------------------------------------------------------------------------- // ้ ‚็‚นใฎๅŽŸ็‚นใฎๅค‰ๆ›ด //------------------------------------------------------------------------------------------------------------- void CScene2D::ChangeVertexOrigin(CONST ORIGINVERTEXTYPE OriginType) { // ๅŒใ˜ใ‚ฟใ‚คใƒ—ใ ใฃใŸๆ™‚ๅ‡ฆ็†ใ‚’ๆŠœใ‘ใ‚‹ if (m_OriginType == OriginType)return; // ้ ‚็‚นๆƒ…ๅ ฑใธใฎใƒใ‚คใƒณใ‚ฟ CRenderer::VERTEX_2D *pVtx; // ้ ‚็‚นใƒ‡ใƒผใ‚ฟใฎ็ฏ„ๅ›ฒใƒญใƒƒใ‚ฏใ—ใ€้ ‚็‚นใƒใƒƒใƒ•ใ‚กใธใฎใƒใ‚คใƒณใ‚ฟๅ–ๅพ— m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0); m_OriginType = OriginType; this->SetVatexPosition(pVtx); // ้ ‚็‚นใƒ‡ใƒผใ‚ฟใ‚’ใ‚ขใƒณใƒญใƒƒใ‚ฏ m_pVtxBuff->Unlock(); } //------------------------------------------------------------------------------------------------------------- // ใƒใƒƒใƒ•ใ‚กใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- LPDIRECT3DVERTEXBUFFER9 CScene2D::GetpVtxBuff(void) const { return m_pVtxBuff; } //------------------------------------------------------------------------------------------------------------- // ใƒใ‚คใƒณใƒ‰ใƒ†ใ‚ฏใ‚นใƒใƒฃ //------------------------------------------------------------------------------------------------------------- void CScene2D::BindTexture(LPDIRECT3DTEXTURE9 pTexture) { m_pTexture = pTexture; } //------------------------------------------------------------------------------------------------------------- // ๅŽŸ็‚นใ‚ฟใ‚คใƒ—ใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetOriginType(CONST ORIGINVERTEXTYPE OriginType) { m_OriginType = OriginType; } //------------------------------------------------------------------------------------------------------------- // ๅŽŸ็‚นใ‚ฟใ‚คใƒ—ใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- ORIGINVERTEXTYPE CScene2D::GetOriginType(void) const { return m_OriginType; } //------------------------------------------------------------------------------------------------------------- // ๅŽŸ็‚นใ‚ฟใ‚คใƒ—ๅ‚็…งใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- ORIGINVERTEXTYPE &CScene2D::GetOriginTypeRef(void) { return m_OriginType; } //------------------------------------------------------------------------------------------------------------- // ๅŽŸ็‚นใ‚ฟใ‚คใƒ—ใƒใ‚คใƒณใ‚ฟใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- ORIGINVERTEXTYPE *CScene2D::GetOriginTypePtr(void) { return &m_OriginType; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetPosition(CONST D3DXVECTOR3& pos) { m_pos = pos; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetPosition(const float x, const float y, const float z) { m_pos.x = x; m_pos.y = y; m_pos.z = z; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎXใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetPositionX(const float x) { m_pos.x = x; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎYใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetPositionY(const float y) { m_pos.y = y; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎZใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetPositionZ(const float z) { m_pos.z = z; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXVECTOR3 CScene2D::GetPosition(void) const { return m_pos; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎๅ‚็…งใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXVECTOR3 & CScene2D::GetPositionRef(void) { return m_pos; } //------------------------------------------------------------------------------------------------------------- // ไฝ็ฝฎใƒใ‚คใƒณใ‚ฟใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXVECTOR3 * CScene2D::GetPositionPtr(void) { return &m_pos; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetColor(CONST D3DXCOLOR& col) { m_col = col; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetColor(const float r, const float g, const float b, const float a) { m_col.r = r; m_col.g = g; m_col.b = b; m_col.a = a; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒRใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetColorR(const float r) { m_col.r = r; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒGใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetColorG(const float g) { m_col.g = g; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒBใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetColorB(const float b) { m_col.b = b; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒAใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetColorA(const float a) { m_col.a = a; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXCOLOR CScene2D::GetColor(void) const { return m_col; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒๅ‚็…งใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXCOLOR & CScene2D::GetColorRef(void) { return m_col; } //------------------------------------------------------------------------------------------------------------- // ่‰ฒใƒใ‚คใƒณใ‚ฟใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXCOLOR * CScene2D::GetColorPtr(void) { return &m_col; } //------------------------------------------------------------------------------------------------------------- // ๅคงใใ•ใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetSize(CONST D3DXVECTOR2& size) { m_size = size; } //------------------------------------------------------------------------------------------------------------- // ๅคงใใ•ใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetSize(const float x, const float y) { m_size.x = x; m_size.y = y; } //------------------------------------------------------------------------------------------------------------- // ๅคงใใ•Xใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetSizeX(const float x) { m_size.x = x; } //------------------------------------------------------------------------------------------------------------- // ๅคงใใ•Yใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetSizeY(const float y) { m_size.y = y; } //------------------------------------------------------------------------------------------------------------- // ๅคงใใ•ใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- D3DXVECTOR2 *CScene2D::GetSize(void) { return &m_size; } //------------------------------------------------------------------------------------------------------------- // ๅ›ž่ปข้‡ใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetRotation(float fRotation) { m_fRotation = fRotation; } //------------------------------------------------------------------------------------------------------------- // ๅ›ž่ปข้‡ใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- float CScene2D::GetRotation(void) { return m_fRotation; } //------------------------------------------------------------------------------------------------------------- // ๅ›ž่ปข้‡ๅ‚็…งใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- float & CScene2D::GetRotationRef(void) { return m_fRotation; } //------------------------------------------------------------------------------------------------------------- // ๅ›ž่ปข้‡ใƒใ‚คใƒณใ‚ฟใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- float * CScene2D::GetRotationPtr(void) { return &m_fRotation; } //------------------------------------------------------------------------------------------------------------- // ๆ็”ปใƒ•ใƒฉใ‚ฐใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetDisp(const bool bDisp) { m_bDisp = bDisp; } //------------------------------------------------------------------------------------------------------------- // ๆ็”ปใƒ•ใƒฉใ‚ฐใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- bool CScene2D::GetDisp(void) { return m_bDisp; } //------------------------------------------------------------------------------------------------------------- // ๆ็”ปใƒ•ใƒฉใ‚ฐๅ‚็…งใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- bool & CScene2D::GetDispRef(void) { return m_bDisp; } //------------------------------------------------------------------------------------------------------------- // ๆ็”ปใƒ•ใƒฉใ‚ฐใƒใ‚คใƒณใ‚ฟใฎๅ–ๅพ— //------------------------------------------------------------------------------------------------------------- bool * CScene2D::GetDispPtr(void) { return &m_bDisp; } //------------------------------------------------------------------------------------------------------------- // ้ ‚็‚นใฎไฝœๆˆ //------------------------------------------------------------------------------------------------------------- HRESULT CScene2D::MakeVatex(LPDIRECT3DDEVICE9 pDevice) { // ้ ‚็‚นใƒใƒƒใƒ•ใ‚กใฎ็”Ÿๆˆ pDevice->CreateVertexBuffer(sizeof(CRenderer::VERTEX_2D) * 4, D3DUSAGE_WRITEONLY, FVF_VERTEX_2D, // ้ ‚็‚นใƒ•ใ‚ฉใƒผใƒžใƒƒใƒˆ D3DPOOL_MANAGED, &m_pVtxBuff, NULL); // ้ ‚็‚นๆƒ…ๅ ฑใธใฎใƒใ‚คใƒณใ‚ฟ CRenderer::VERTEX_2D *pVtx; // ้ ‚็‚นใƒ‡ใƒผใ‚ฟใฎ็ฏ„ๅ›ฒใƒญใƒƒใ‚ฏใ—ใ€้ ‚็‚นใƒใƒƒใƒ•ใ‚กใธใฎใƒใ‚คใƒณใ‚ฟๅ–ๅพ— m_pVtxBuff->Lock(0, 0, (void**)&pVtx, 0); // ้ ‚็‚นไฝ็ฝฎใฎ่จญๅฎš SetVatexPosition(pVtx); // Z่ปธใฏไฝฟใ†ๅฟ…่ฆใชใ„ใฎใง0.0f pVtx[0].pos.z = pVtx[1].pos.z = pVtx[2].pos.z = pVtx[3].pos.z = 0.0f; // ๅŒๆฌกๅบงๆจ™ใฎ่จญๅฎš pVtx[0].rhw = pVtx[1].rhw = pVtx[2].rhw = pVtx[3].rhw = 1.0f; // ้ ‚็‚นใ‚ซใƒฉใƒผใฎ่จญๅฎš SetVatexColor(pVtx); // ใƒ†ใ‚ฏใ‚นใƒใƒฃๅบงๆจ™ SetVatexTexture(pVtx); // ้ ‚็‚นใƒ‡ใƒผใ‚ฟใ‚’ใ‚ขใƒณใƒญใƒƒใ‚ฏ m_pVtxBuff->Unlock(); return S_OK; } //------------------------------------------------------------------------------------------------------------- // ้ ‚็‚นไฝ็ฝฎใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetVatexPosition(CRenderer::VERTEX_2D * pVtx) { // ๅค‰ๆ•ฐๅฎฃ่จ€ D3DXVECTOR2 halfsize; // ๅŠๅˆ†ใฎๅคงใใ• float fInvRot = -m_fRotation; // ้€†ใฎๅ›ž่ปข float fSin_size_x = sinf(mystd::fHalf_PI - m_fRotation)*m_size.x; // sinๆ–นๅ‘ใฎxX่ปธใฎๅคงใใ•ใฎ่จˆ็ฎ—็ตๆžœ float fCos_size_x = cosf(mystd::fHalf_PI - m_fRotation)*m_size.x; // cosๆ–นๅ‘ใฎxX่ปธใฎๅคงใใ•ใฎ่จˆ็ฎ—็ตๆžœ // ๅŠๅˆ†ใฎๅคงใใ•ใ‚’ๆ ผ็ด mystd::Convert_to_half_size(halfsize, m_size); // ๅŽŸ็‚นใ‚ฟใ‚คใƒ—ใซๅฟœใ˜ใฆ้ ‚็‚น[0]ใฎไฝ็ฝฎใ‚’่จญๅฎšใ™ใ‚‹ switch (m_OriginType) { case ORIGINVERTEXTYPE_LOWERLEFT: pVtx[0].pos.x = m_pos.x + sinf(D3DX_PI - m_fRotation)*m_size.y; pVtx[0].pos.y = m_pos.y + cosf(D3DX_PI - m_fRotation)*m_size.y; break; case ORIGINVERTEXTYPE_LOWERCENTER: pVtx[0].pos.x = m_pos.x + sinf(D3DX_PI - m_fRotation)*m_size.y + sinf(-mystd::fHalf_PI - m_fRotation)*halfsize.x; pVtx[0].pos.y = m_pos.y + cosf(D3DX_PI - m_fRotation)*m_size.y + cosf(-mystd::fHalf_PI - m_fRotation)*halfsize.x; break; case ORIGINVERTEXTYPE_LOWERRIGHT: pVtx[0].pos.x = m_pos.x + sinf(D3DX_PI - m_fRotation)*m_size.y + sinf(-mystd::fHalf_PI - m_fRotation)*m_size.x; pVtx[0].pos.y = m_pos.y + cosf(D3DX_PI - m_fRotation)*m_size.y + cosf(-mystd::fHalf_PI - m_fRotation)*m_size.x; break; case ORIGINVERTEXTYPE_CENTERLEFT: pVtx[0].pos.x = m_pos.x + sinf(D3DX_PI - m_fRotation)*halfsize.y; pVtx[0].pos.y = m_pos.y + cosf(D3DX_PI - m_fRotation)*halfsize.y; break; case ORIGINVERTEXTYPE_CENTER: pVtx[0].pos.x = m_pos.x + sinf(D3DX_PI - m_fRotation)*halfsize.y + sinf(-mystd::fHalf_PI - m_fRotation)*halfsize.x; pVtx[0].pos.y = m_pos.y + cosf(D3DX_PI - m_fRotation)*halfsize.y + cosf(-mystd::fHalf_PI - m_fRotation)*halfsize.x; break; case ORIGINVERTEXTYPE_CENTERRIGHT: pVtx[0].pos.x = m_pos.x + sinf(D3DX_PI - m_fRotation)*halfsize.y + sinf(-mystd::fHalf_PI - m_fRotation)*m_size.x; pVtx[0].pos.y = m_pos.y + cosf(D3DX_PI - m_fRotation)*halfsize.y + cosf(-mystd::fHalf_PI - m_fRotation)*m_size.x; break; case ORIGINVERTEXTYPE_UPPERLEFT: pVtx[0].pos.x = m_pos.x; pVtx[0].pos.y = m_pos.y; break; case ORIGINVERTEXTYPE_UPPERCENTER: pVtx[0].pos.x = m_pos.x + sinf(-mystd::fHalf_PI - m_fRotation)*halfsize.x; pVtx[0].pos.y = m_pos.y + cosf(-mystd::fHalf_PI - m_fRotation)*halfsize.x; break; case ORIGINVERTEXTYPE_UPPERRIGHT: pVtx[0].pos.x = m_pos.x + sinf(-mystd::fHalf_PI - m_fRotation)*m_size.x; pVtx[0].pos.y = m_pos.y + cosf(-mystd::fHalf_PI - m_fRotation)*m_size.x; break; } // ้ ‚็‚น[2]ใฎ่จญๅฎš pVtx[2].pos.x = pVtx[0].pos.x + sinf(fInvRot)*m_size.y; pVtx[2].pos.y = pVtx[0].pos.y + cosf(fInvRot)*m_size.y; // ้ ‚็‚น[1]ใฎ่จญๅฎš pVtx[1].pos.x = pVtx[0].pos.x + fSin_size_x; pVtx[1].pos.y = pVtx[0].pos.y + fCos_size_x; // ้ ‚็‚น[3]ใฎ่จญๅฎš pVtx[3].pos.x = pVtx[2].pos.x + fSin_size_x; pVtx[3].pos.y = pVtx[2].pos.y + fCos_size_x; } //------------------------------------------------------------------------------------------------------------- // ้ ‚็‚นใ‚ซใƒฉใƒผใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetVatexColor(CRenderer::VERTEX_2D * pVtx) { pVtx[0].col = pVtx[1].col = pVtx[2].col = pVtx[3].col = m_col; } //------------------------------------------------------------------------------------------------------------- // ้ ‚็‚นใƒ†ใ‚ฏใ‚นใƒใƒฃๅบงๆจ™ใฎ่จญๅฎš //------------------------------------------------------------------------------------------------------------- void CScene2D::SetVatexTexture(CRenderer::VERTEX_2D * pVtx) { pVtx[0].tex = D3DXVECTOR2(0.0f, 0.0f); pVtx[1].tex = D3DXVECTOR2(1.0f, 0.0f); pVtx[2].tex = D3DXVECTOR2(0.0f, 1.0f); pVtx[3].tex = D3DXVECTOR2(1.0f, 1.0f); }
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file tests/Audit/syscall_rule_data.cpp * @author Aleksander Zdyb <a.zdyb@samsung.com> * @version 1.0 */ #include <gmock/gmock.h> #include <gtest/gtest.h> #include <Audit/SyscallRuleData.h> #include "FakeAuditWrapper.h" /** * @brief SyscallRuleData should call audit_rule_syscallbyname_data() * @test Scenario: * - call SyscallRuleData::get() * - check if audit_rule_syscallbyname_data() was called with proper args */ TEST(SyscallRuleData, no_values) { using ::testing::_; using ::testing::NiceMock; using ::testing::Return; using ::testing::StrEq; NiceMock<FakeAuditWrapper> auditApi; Audit::SyscallRuleData srd(auditApi); struct audit_rule_data *ruleData = reinterpret_cast<struct audit_rule_data *>(0x7E57); ON_CALL(auditApi, MAX_AUDIT_MESSAGE_LENGTH_CONST()).WillByDefault(Return(512)); EXPECT_CALL(auditApi, create_rule_data()).WillOnce(Return(ruleData)); EXPECT_CALL(auditApi, audit_rule_syscallbyname_data(ruleData, StrEq("all"))); srd.get(); } /** * @brief SyscallRuleData should call audit_rule_fieldpair_data() * @test Scenario: * - call SyscallRuleData::get() * - check if audit_rule_fieldpair_data() was called with proper args */ TEST(SyscallRuleData, some_values) { using ::testing::_; using ::testing::NiceMock; using ::testing::Pointee; using ::testing::Return; using ::testing::StrEq; const int AUDIT_FILTER_EXIT_CONST = 42; NiceMock<FakeAuditWrapper> auditApi; Audit::SyscallRuleData srd(auditApi); struct audit_rule_data *ruleData = reinterpret_cast<struct audit_rule_data *>(0x7E57); ON_CALL(auditApi, MAX_AUDIT_MESSAGE_LENGTH_CONST()).WillByDefault(Return(512)); EXPECT_CALL(auditApi, create_rule_data()).WillOnce(Return(ruleData)); EXPECT_CALL(auditApi, AUDIT_FILTER_EXIT_CONST()).Times(2) .WillRepeatedly(Return(AUDIT_FILTER_EXIT_CONST)); EXPECT_CALL(auditApi, audit_rule_fieldpair_data(Pointee(ruleData), StrEq("key1=value1"), AUDIT_FILTER_EXIT_CONST)) .WillOnce(Return(0)); EXPECT_CALL(auditApi, audit_rule_fieldpair_data(Pointee(ruleData), StrEq("key2=value2"), AUDIT_FILTER_EXIT_CONST)) .WillOnce(Return(0)); EXPECT_CALL(auditApi, audit_rule_syscallbyname_data(ruleData, StrEq("all"))); srd.addPair("key1", "value1"); srd.addPair("key2", "value2"); srd.get(); }
#pragma once #include "sound/sound.h" #include "script/script.h" namespace sound { class Sound : public script::ScriptedObject { public: Sound(SoundManager* manager, const string& name); virtual ~Sound(); const string& getName() { return m_name; } SoundManager* getManager() { return m_manager; } FMOD::Sound* getSound() { return m_sound; } static ScriptedObject::ScriptClass m_scriptClass; protected: // script functions JSObject* createScriptObject() { return NULL; } void destroyScriptObject() {} // members string m_name; JSObject* m_scriptObject; SoundManager* m_manager; FMOD::Sound* m_sound; }; }
/* =========================================================================== Copyright (C) 2017 waYne (CAM) =========================================================================== */ #pragma once #ifndef ELYSIUM_DATA_DBCOMMANDPOOL #define ELYSIUM_DATA_DBCOMMANDPOOL #ifndef ELYSIUM_DATA_IDATACOMMANDPOOL #include "IDataCommandPool.hpp" #endif #ifndef ELYSIUM_DATA_DBDATACONTEXT #include "DbDataContext.hpp" #endif /* #ifndef ELYSIUM_DATA_CACHING_USERDATACACHE #include "UserDataCache.hpp" #endif */ namespace Elysium { namespace Data { // forward declaration namespace Model { class EntityList; } /// <summary> /// Create one DbCommandPool per thread /// </summary> class EXPORT DbCommandPool : public IDataCommandPool { friend class Model::EntityList; public: DbCommandPool(DbDataContext* DataContext); ~DbCommandPool(); private: DbDataContext* _DataContext; int _EntityHandleCounter = 0; }; } } #endif
// wodAppUpdateEvents.cpp: implementation of the wodAppUpdateEvents class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "freesshdservice.h" #include "log.h" #include "ComBSTR2.h" #include "MessageDlg.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif #define HANDLER _Module.freeSSHdHandler ////////////////////////////////////////////////////////////////////// // ATL function info ////////////////////////////////////////////////////////////////////// #ifdef _ISFREEOPEN _ATL_FUNC_INFO INFO_CloseApp = {CC_STDCALL, VT_EMPTY, 0, 0}; _ATL_FUNC_INFO INFO_CheckDone = {CC_STDCALL, VT_EMPTY, 3, {VT_I4, VT_I4, VT_BSTR}}; _ATL_FUNC_INFO INFO_StateChange = {CC_STDCALL, VT_EMPTY, 1, {VT_I4}}; _ATL_FUNC_INFO INFO_UpdateDone = {CC_STDCALL, VT_EMPTY, 2, {VT_I4, VT_BSTR}}; _ATL_FUNC_INFO INFO_FileStart = {CC_STDCALL, VT_EMPTY, 1, {VT_DISPATCH}}; _ATL_FUNC_INFO INFO_FileProgress = {CC_STDCALL, VT_EMPTY, 3, {VT_DISPATCH, VT_I4, VT_I4}}; _ATL_FUNC_INFO INFO_FileDone = {CC_STDCALL, VT_EMPTY, 3, {VT_DISPATCH, VT_I4, VT_BSTR}}; _ATL_FUNC_INFO INFO_DownloadDone = {CC_STDCALL, VT_EMPTY, 2, {VT_I4, VT_BSTR}}; _ATL_FUNC_INFO INFO_PrevDetected = {CC_STDCALL, VT_EMPTY, 0, 0}; #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #ifdef _ISFREEOPEN wodAppUpdateEvents::wodAppUpdateEvents (WODAPPUPDATECOMLib::IwodAppUpdateComPtr pWodAppUpdateCom) { m_pWodAppUpdateCom = pWodAppUpdateCom; DispEventAdvise ( (IUnknown*)m_pWodAppUpdateCom); } wodAppUpdateEvents::~wodAppUpdateEvents () { DispEventUnadvise ( (IUnknown*)m_pWodAppUpdateCom); m_pWodAppUpdateCom.Release(); } ////////////////////////////////////////////////////////////////////// // Events ////////////////////////////////////////////////////////////////////// void _stdcall wodAppUpdateEvents::CloseApp() { } #endif #ifdef _ISFREEOPEN void _stdcall wodAppUpdateEvents::CheckDone(long NewFiles, long ErrorCode, BSTR ErrorText) #else void wodAppUpd_CheckDone(void *AppUpd, long NewFiles, long ErrorCode, char * ErrorText) #endif { if (ErrorCode == 0) { short iMessageCount = 0; #ifdef _ISFREEOPEN WODAPPUPDATECOMLib::IUpdMessagesPtr Messages; HANDLER.m_Update->get_Messages(&Messages); Messages->get_Count(&iMessageCount); #else WODAPPUPDCOMLib::AppUpd_Messages_GetCount(HANDLER.m_Update, &iMessageCount); #endif for (int i = 0; i < iMessageCount; i++) { CComBSTR2 bstrText, bstrCaption; long MessageID = 0; #ifdef _ISFREEOPEN WODAPPUPDATECOMLib::IUpdMessagePtr Message; Messages->get_Item(i, &Message); Message->get_Text(&bstrText); Message->get_Caption(&bstrCaption); Message->get_ID(&MessageID); #else void *message; char buff[16384]; int len = 16384; WODAPPUPDCOMLib::AppUpd_Messages_GetMessage(HANDLER.m_Update, i, &message); WODAPPUPDCOMLib::AppUpd_Message_GetID(message, &MessageID); WODAPPUPDCOMLib::AppUpd_Message_GetCaption(message, buff, &len); bstrCaption = buff; len = 16384; WODAPPUPDCOMLib::AppUpd_Message_GetText(message, buff, &len); bstrText = buff; #endif if (HANDLER.Config.UpdateLastMessageID < MessageID) { if (HANDLER.Config.UpdateDontPrompt) { char buff[10240] = "freeSSHd.com message: title=\""; strncat(buff, bstrCaption.ToString(), 5000); strncat(buff, "\" text=\"", 8); strncat(buff, bstrText.ToString(), 5000); strncat(buff, "\"", 3); WriteLog(buff); } else { CMessageDlg dlg; dlg.SetText(bstrText.ToString()); dlg.SetCaption(bstrCaption.ToString()); dlg.DoModal(); } HANDLER.Config.UpdateLastMessageID = MessageID; } } if (iMessageCount) HANDLER.SaveMessageID(); if (NewFiles) { if (HANDLER.Config.UpdateDontPrompt) { if (HANDLER.SSH_UserCount() || HANDLER.Telnet_UserCount()) if (MessageBox(NULL, "There are users connected. Do you want to proceed with updating?", "freeSSHd update", MB_YESNO) == IDNO) return; #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Download(); #else WODAPPUPDCOMLib::AppUpd_Download(HANDLER.m_Update); #endif } else if (MessageBox(NULL, "New version of freeSSHd is available. Download?", "freeSSHd update", MB_YESNO) == IDYES) #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Download(); #else WODAPPUPDCOMLib::AppUpd_Download(HANDLER.m_Update); #endif } else { if (HANDLER.m_StartupUpdate) WriteLog("Your freeSSHd is up-to-date."); else MessageBox(NULL, "Your freeSSHd is up-to-date.", "freeSSHd update", MB_OK); } } else MessageBox(NULL, "Error connecting to freeSSHd.com.", "freeSSHd update", MB_ICONERROR); } #ifdef _ISFREEOPEN void _stdcall wodAppUpdateEvents::StateChange(WODAPPUPDATECOMLib::UpdateStates OldState) { } void _stdcall wodAppUpdateEvents::UpdateDone(long ErrorCode, BSTR ErrorText) { } void _stdcall wodAppUpdateEvents::FileStart(WODAPPUPDATECOMLib::IUpdFile* File) { } void _stdcall wodAppUpdateEvents::FileProgress(WODAPPUPDATECOMLib::IUpdFile* File, long Position, long Total) { } void _stdcall wodAppUpdateEvents::FileDone(WODAPPUPDATECOMLib::IUpdFile* File, long ErrorCode, BSTR ErrorText) { } #endif #ifdef _ISFREEOPEN void _stdcall wodAppUpdateEvents::DownloadDone(long ErrorCode, BSTR ErrorText) #else void wodAppUpd_DownloadDone(void *AppUpd, long ErrorCode, char * ErrorText) #endif { if (ErrorCode == 0) { if (HANDLER.Config.UpdateDontPrompt) #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Update(); #else WODAPPUPDCOMLib::AppUpd_Update(HANDLER.m_Update); #endif else if (MessageBox(NULL, "Download successful. Replace now?", "freeSSHd update", MB_YESNO) == IDYES) #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Update(); #else WODAPPUPDCOMLib::AppUpd_Update(HANDLER.m_Update); #endif } else { if (!HANDLER.Config.UpdateDontPrompt) MessageBox(NULL, "There was an error downloading files.", "freeSSHd update", MB_ICONERROR); } } #ifdef _ISFREEOPEN void _stdcall wodAppUpdateEvents::PrevDetected() #else void wodAppUpd_PrevDetected(void *AppUpd) #endif { if (HANDLER.Config.UpdateDontPrompt) #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Update(); #else WODAPPUPDCOMLib::AppUpd_Update(HANDLER.m_Update); #endif else { if (MessageBox(NULL, "Previous download detected. Update now?", "freeSSHd update", MB_YESNO) == IDYES) #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Update(); #else WODAPPUPDCOMLib::AppUpd_Update(HANDLER.m_Update); #endif else #ifdef _ISFREEOPEN _Module.freeSSHdHandler.m_Update->Clear(); #else WODAPPUPDCOMLib::AppUpd_Clear(HANDLER.m_Update); #endif } }
#ifndef OP_SYSTEM_INFO_H #define OP_SYSTEM_INFO_H class OpSystemInfo { public: #if defined OPSYSTEMINFO_CPU_FEATURES enum CPUFeatures { CPU_FEATURES_NONE = 0 #if defined ARCHITECTURE_ARM , CPU_FEATURES_ARM_VFPV2 = (1 << 0) ///< ARM VFPv2 floating point , CPU_FEATURES_ARM_VFPV3 = (1 << 1) ///< ARM VFPv3 floating point , CPU_FEATURES_ARM_NEON = (1 << 2) ///< Support for ARM NEON SIMD instructions #elif defined ARCHITECTURE_IA32 , CPU_FEATURES_IA32_SSE2 = (1 << 0) , CPU_FEATURES_IA32_SSE3 = (1 << 1) , CPU_FEATURES_IA32_SSSE3 = (1 << 2) , CPU_FEATURES_IA32_SSE4_1 = (1 << 3) , CPU_FEATURES_IA32_SSE4_2 = (1 << 4) #endif }; /** Returns an bit-field of available CPU features. * * @return A bit-wise OR of the CPUFeature flags of features the platform * knows to be available on the CPU on which this method is queried. * * If more than one CPU is available only the features available on * all CPUs are returned. */ virtual unsigned int GetCPUFeatures() { # if defined ARCHITECTURE_ARM_VFP return CPU_FEATURES_ARM_VFPV3; # elif defined ARCHITECTURE_IA32 return CPU_FEATURES_IA32_SSE4_2; # else return CPU_FEATURES_NONE; # endif // ARCHITECTURE_ARM_VFP } #endif // OPSYSTEMINFO_CPU_FEATURES }; #endif
/* This programs indicates five digit Created by: Enang Emmanuel Eta Date: 19th May, 2015 */ #include <iostream> int main(){ int fivedigit; int first, second, third, fourth, fifth; std::cout << "enter the five digit integer: "; std::cin >> fivedigit; if(fivedigit < 10000) { std::cout << " Restructured to "; } if(fivedigit > 9999) { std::cout << "Restructured to "; } first = fivedigit/10000; second = (fivedigit/1000)%10; third = (fivedigit/100)%10; fourth = (fivedigit/10)%10; fifth = fivedigit%10; std::cout << first; std::cout << " " << second; std::cout << " " << third; std::cout << " " << fourth; std::cout << " " << fifth; return 0; }
#pragma once #include "mixer.hpp" namespace ugsdr { class BatchMixer : public Mixer<BatchMixer> { protected: friend class Mixer<BatchMixer>; template <typename UnderlyingType> static void Process(std::vector<std::complex<UnderlyingType>>& src_dst, double sampling_freq, double frequency, double phase = 0) { double scale = 1.0; if constexpr (std::is_integral_v<UnderlyingType>) scale = std::numeric_limits<UnderlyingType>::max(); double pi_2 = 8 * std::atan(1.0); thread_local static std::vector<std::complex<double>> c_exp; c_exp.resize(src_dst.size()); std::iota(c_exp.begin(), c_exp.end(), 0.0); std::transform(std::execution::par_unseq, c_exp.begin(), c_exp.end(), c_exp.begin(), [=](auto& val) { return val * pi_2 * frequency / sampling_freq + phase; }); std::transform(std::execution::par_unseq, c_exp.begin(), c_exp.end(), src_dst.begin(), src_dst.begin(), [](auto& exp_val, auto& src_val) { return src_val * std::complex<UnderlyingType>(exp_val); }); } public: BatchMixer(double sampling_freq, double frequency, double phase) : Mixer<BatchMixer>(sampling_freq, frequency, phase) {} }; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2002 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 "adjunct/quick/widgets/OpComposeEdit.h" #include "adjunct/quick_toolkit/widgets/OpLabel.h" #include "modules/pi/OpDragManager.h" #include "modules/dragdrop/dragdrop_data_utils.h" #include "modules/widgets/OpEdit.h" /*********************************************************************************** ** ** OpComposeEdit ** ***********************************************************************************/ DEFINE_CONSTRUCT(OpComposeEdit) OP_STATUS OpComposeEdit::Construct(OpComposeEdit** obj, const uni_char* menu) { if (!(*obj = OP_NEW(OpComposeEdit, (menu)))) return OpStatus::ERR_NO_MEMORY; return OpStatus::OK; } void OpComposeEdit::SetDropdown(const uni_char* menu) { m_dropdown_menu = menu; } BOOL OpComposeEdit::OnInputAction(OpInputAction* action) { switch(action->GetAction()) { case OpInputAction::ACTION_SHOW_EDIT_DROPDOWN: { OpInputAction new_action(OpInputAction::ACTION_SHOW_POPUP_MENU); new_action.SetActionDataString(m_dropdown_menu); new_action.SetActionMethod(action->GetActionMethod()); return g_input_manager->InvokeAction(&new_action, this); } } return OpEdit::OnInputAction(action); } void OpComposeEdit::OnDragDrop(OpDragObject* drag_object, const OpPoint& point) { if(drag_object->GetSource() && drag_object->GetSource()->GetType() == WIDGET_TYPE_COMPOSE_EDIT) { OpEdit* edit = static_cast<OpEdit*>(drag_object->GetSource()); if (edit && edit->IsEnabled()) { OpInputAction action(OpInputAction::ACTION_DELETE); edit->EditAction(&action); edit->SelectNothing(); } } OpString tmp; tmp.Set(DragDrop_Data_Utils::GetText(drag_object)); const uni_char* text = tmp.CStr(); while (text && (text[0] == ',' || text[0] == ';' || text[0] == ' ')) ++text; DragDrop_Data_Utils::SetText(drag_object, text); if (DragDrop_Data_Utils::GetText(drag_object) && GetTextLength() > 0) { OpString text; GetText(text); const uni_char* tmp = text.CStr() + text.Length() - 1; if (text.CStr() && *tmp != ',' && *tmp != ';' && *(tmp - 1) != ',' && *(tmp - 1) != ';') text.Append(UNI_L(", ")); text.Append(DragDrop_Data_Utils::GetText(drag_object)); SetText(text.CStr()); SetFocus(FOCUS_REASON_OTHER); } else { OpEdit::OnDragDrop(drag_object, point); } }
/* -*- 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 DOM_ANIMATIONEVENT_H #define DOM_ANIMATIONEVENT_H #ifdef CSS_ANIMATIONS #include "modules/dom/src/domevents/domevent.h" class DOM_AnimationEvent : public DOM_Event { protected: double elapsed_time; OpString animation_name; public: DOM_AnimationEvent(double el = 0) : elapsed_time(el) {} static OP_STATUS Make(DOM_Event*& event, double elapsed_time, const uni_char* animation_name, DOM_Runtime* runtime); virtual ES_GetState GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_ANIMATIONEVENT || DOM_Event::IsA(type); } DOM_DECLARE_FUNCTION(initAnimationEvent); enum { FUNCTIONS_ARRAY_SIZE = 2 }; }; #endif // CSS_ANIMATIONS #endif // !DOM_ANIMATIONEVENT_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2010 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Arjan van Leeuwen (arjanl) */ #ifndef QUICK_GRID_ROW_CREATOR_H #define QUICK_GRID_ROW_CREATOR_H #include "adjunct/ui_parser/ParserNode.h" class QuickGrid; class TypedObjectCollection; class ParserLogger; class QuickGridRowCreator { public: /** Create a row creator * @param sequence Sequence node that describes elements for row * @param log Log for errors */ QuickGridRowCreator(ParserNodeSequence sequence, ParserLogger& log, bool has_quick_window) : m_sequence(sequence), m_log(log), m_has_quick_window(has_quick_window) {} /** Instantiate a row * @param grid Grid to instantiate row into * @param collection Where to save named widgets to * @return OpStatus::OK on success, error codes otherwise */ OP_STATUS Instantiate(QuickGrid& grid, TypedObjectCollection& collection); private: ParserNodeSequence m_sequence; ParserLogger& m_log; bool m_has_quick_window; }; #endif // QUICK_GRID_ROW_CREATOR_H
#pragma once #include "Core\Entity.h" #include "Core\StrID.h" namespace Hourglass { class EntityManager { public: void Init(); void Shutdown(); /** * Get an available entity */ Entity* GetFree(); /** * Returns the First entity found with a given name * @param name - StrID that is serached for */ Entity* FindByName( StrID name ); /** * Returns the First entity found with a given tag * @param tag - StrID that is serached for */ Entity* FindByTag( StrID tag ); Entity* FindByInstanceID( int instanceId ); /** * Handles the destruction of this entity * @param entity - The entity to destroy */ void DestroyEntity( Entity* entity ); /** * Loads an entity from xml data */ void LoadFromXML( Entity* entity, tinyxml2::XMLElement* element ); /** * Loads an assembled entity from xml data */ void CreateAssembledFromXML( tinyxml2::XMLElement* element ); void ResetEntities(); void BroadcastMessage(hg::Message* msg); private: static const unsigned int s_kMaxEntities = 4096; Entity m_Entities[s_kMaxEntities]; std::vector<Entity*> m_AssembledEntities; }; extern EntityManager g_EntityManager; }
#include <iostream> #include <string> using namespace std; int main() { string t; cout << "Enter any thing and this will output the characters in that sentence or paragraph.\n"; cin >> t; string str (t); cout << "The size of str is " << str.length() << " bytes.\n"; return 0; }
#include <iostream> #include "date.h" using namespace std; int main() { Date date; date.setDate(2016,1,1); date.showDate(); return 0; }
#include <stdio.h> #include <iostream> #include <GL/glut.h> #include "./custom-headers/Point.h" #include "./openGL-comp/HelperDrawerMethod.h" #include "./algos/4-MidPointCircleAlgo.h" using namespace std; int pntX1, pntY1, r; void myInit(void) { glClearColor(1.0, 1.0, 1.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); gluOrtho2D(0, 500, 0, 500); glColor3f(0.0, 0.0, 0.0); } void myDisplay(void) { int offsetX = 250, offsetY = 250; // origin at (250,250) RGBColor color(0, 0, 0, 1); auto points = midPointCircleAlgo(r); drawPixels<int>(points, color, pntX1 + offsetX, pntY1 + offsetY, false); glFlush(); } int main(int argc, char **argv) { cout << "Enter the coordinates of the center:\n\n" << endl; cout << "X-coordinate : "; cin >> pntX1; cout << "\nY-coordinate : "; cin >> pntY1; cout << "\nEnter radius : "; cin >> r; glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(500, 500); glutInitWindowPosition(0, 0); glutCreateWindow("-- Midpoint Circle Drawing --"); myInit(); glutDisplayFunc(myDisplay); glutMainLoop(); return 0; }
#ifndef WALI_TESTS_NWA_int_client_info_HPP #define WALI_TESTS_NWA_int_client_info_HPP #include "opennwa/ClientInfo.hpp" namespace opennwa { struct IntClientInfo : ClientInfo { IntClientInfo * clone() { return new IntClientInfo(*this); } IntClientInfo(int n_) : n(n_) {} IntClientInfo(IntClientInfo const & other) : ClientInfo(other) , n(other.n) {} int n; }; } #endif
//function para testar o callback vindo de outro arquivo //callback funciona, posso fazer aqui outras classes que precisar eventualmente.
#pragma once #include<vector> #include<map> #include<memory> #include "PredicateValues.h" class PredicateVehicle; class VehicleData; class Situation; /** * A PredicateConstructor uses hystereses to transform raw data to predicate data. */ class PredicateConstructor { public: /** * Standard constructor. */ PredicateConstructor(); /** * Standard destructor. */ ~PredicateConstructor(); /** * For each vehicle the data transformed to predicates using hystereses and old data. * @param data Vector of VehicleData that will be transformed to predicates. * @return Map of the ID of the vehicle in the situation to the transformed PredicateVehicles */ std::vector<std::shared_ptr<PredicateVehicle>> transform(std::vector<std::unique_ptr<VehicleData>> data); private: //map of Simulation IDs to Predicates from the last step std::map<int, std::shared_ptr<PredicateVehicle>> lastPredicates; //uses old state and hystereses to find the new predicate RelX getXPosPredicate(PredicateVehicle const &oldData, VehicleData const &newData, VehicleData const &vut); //uses old state and hystereses to find the new predicate RelV getRelVPredicate(PredicateVehicle const &oldData, VehicleData const &newData, VehicleData const &vut); //creates a predicate without the old data or hystereses RelX getXPosPredicate(VehicleData const &newData, VehicleData const &vut); //creates a predicate without the old data or hystereses RelV getRelVPredicate(VehicleData const &newData, VehicleData const &vut); //uses old state and hystereses to find the new predicate Acc getAccPredicate(PredicateVehicle const &oldData, VehicleData const &vut); //creates a predicate without the old data or hystereses Acc getAccPredicate(VehicleData const &vut); //creates a predicate without the old data or hystereses LnChg getLnChgPredicate(VehicleData const &vut); };
/***************************************************************** Name :BT_traversal Author :srhuang Email :lukyandy3162@gmail.com History : 20190930 Initial Version *****************************************************************/ #include <iostream> #include <sstream> #include <queue> #include <stack> using namespace std; /*==============================================================*/ struct TreeNode{ int val; TreeNode *left; TreeNode *right; TreeNode() : val(-1), left(NULL), right(NULL) {} TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class BinaryTree{ private: void LevelorderConstruct(stringstream &ss); public: TreeNode *root; BinaryTree(const char *str); void preorderTraversalRecursion(TreeNode *parent); void inorderTraversalRecursion(TreeNode *parent); void postorderTraversalRecursion(TreeNode *parent); void levelorderTraversalIteration(TreeNode *parent); void preorderTraversalIteration(TreeNode *parent); void inorderTraversalIteration(TreeNode *parent); void postorderTraversalIteration(TreeNode *parent); void printGivenLevel(TreeNode *parent, int level); int height(TreeNode *parent); void levelorderTraversalRecursion(TreeNode *parent); }; BinaryTree::BinaryTree(const char *str) { stringstream ss; string temp; ss << str; getline(ss, temp, ','); root = new TreeNode(stoi(temp)); LevelorderConstruct(ss); } void BinaryTree::LevelorderConstruct(stringstream &ss) { queue<TreeNode*> q; TreeNode *current = root; string input; while(getline(ss, input, ',')){ //handle the left child if(input.compare("x")){ TreeNode *newNode = new TreeNode(stoi(input)); current->left = newNode; q.push(newNode); } if(!(getline(ss, input, ','))){ break; } if(input.compare("x")){ TreeNode *newNode = new TreeNode(stoi(input)); current->right = newNode; q.push(newNode); } current = q.front(); q.pop(); } } void BinaryTree::preorderTraversalRecursion(TreeNode *parent) { if(NULL == parent){ return; } //do the right things cout << " " << parent->val; preorderTraversalRecursion(parent->left); preorderTraversalRecursion(parent->right); } void BinaryTree::inorderTraversalRecursion(TreeNode *parent) { if(NULL == parent){ return; } inorderTraversalRecursion(parent->left); //do the right things cout << " " << parent->val; inorderTraversalRecursion(parent->right); } void BinaryTree::postorderTraversalRecursion(TreeNode *parent) { if(NULL == parent){ return; } postorderTraversalRecursion(parent->left); postorderTraversalRecursion(parent->right); //do the right things cout << " " << parent->val; } void BinaryTree::levelorderTraversalIteration(TreeNode *parent) { queue<TreeNode*> q; q.push(parent); while(!q.empty()){ TreeNode *current = q.front(); q.pop(); cout << " " << current->val; if(current->left) q.push(current->left); if(current->right) q.push(current->right); }//while } void BinaryTree::preorderTraversalIteration(TreeNode *parent) { if(NULL == parent) return; stack<TreeNode*> st; st.push(parent); while(!st.empty()){ TreeNode *current = st.top(); st.pop(); //do the right thing cout << " " << current->val; if(current->right) st.push(current->right); if(current->left) st.push(current->left); } } void BinaryTree::inorderTraversalIteration(TreeNode *parent) { stack<TreeNode*> st; TreeNode *current = parent; while(current || !st.empty()){ //step 1:reach the leftmost node while(current){ st.push(current); current = current->left; } //step 2:pop the stack current = st.top(); st.pop(); //step 3:do the right thing cout << " " << current->val; //step 4:handle the right child if need current = current->right; } } void BinaryTree::postorderTraversalIteration(TreeNode *parent) { if(NULL == parent) return; stack<TreeNode*> st; TreeNode *current = parent; do{ //step 1:reach the leftmost node while(current){ //push right child if(current->right) st.push(current->right); //push the current st.push(current); current = current->left; } //step 2:pop the stack current = st.top(); st.pop(); //step 3:handle the right child first if(current->right && !st.empty() && st.top() == current->right) { st.pop(); st.push(current); current = current->right; }else{//step 4:do the right thing cout << " " << current->val; //for next pop current = NULL; } }while(!st.empty()); } void BinaryTree::printGivenLevel(TreeNode *parent, int level) { if(NULL == parent){ return; } if(1 == level){ cout << " " << parent->val; }else if(level > 1){ printGivenLevel(parent->left, level-1); printGivenLevel(parent->right, level-1); } } int BinaryTree::height(TreeNode *parent) { if(NULL == parent){ return 0; } int left_height = height(parent->left); int right_height = height(parent->right); if(left_height > right_height) return (left_height+1); else return (right_height+1); } void BinaryTree::levelorderTraversalRecursion(TreeNode *parent) { int h = height(parent); for(int i=1; i<=h; i++){ printGivenLevel(parent, i); } } int main(int argc, char const *argv[]){ const char *input = "1,2,3,x,x,4,5,6,7"; BinaryTree BT(input); TreeNode *temp = BT.root->right; cout << "test : " << temp->right->val << endl; cout << "inorder :"; BT.inorderTraversalRecursion(BT.root); cout << endl; cout << "preorder :"; BT.preorderTraversalRecursion(BT.root); cout << endl; cout << "postorder :"; BT.postorderTraversalRecursion(BT.root); cout << endl; cout << "levelorder :"; BT.levelorderTraversalIteration(BT.root); cout << endl; cout << "inorder iteration :"; BT.inorderTraversalIteration(BT.root); cout << endl; cout << "preorder iteration :"; BT.preorderTraversalIteration(BT.root); cout << endl; cout << "postorder iteration :"; BT.postorderTraversalIteration(BT.root); cout << endl; cout << "levelorder :"; BT.levelorderTraversalRecursion(BT.root); cout << endl; return 0; } /*==============================================================*/
#include "Debug.h" #include "Game.h" #include "Util.h" #include "math/Vec2.h" #include "math/Vec3.h" //#include "Sound.h" #include <stdlib.h> #include <time.h> #include <math.h> #include <string> #include <AL/al.h> #include <AL/alc.h> using namespace gg; Game::Game(int width, int height) { _graphics = new Graphics(width, height); init(); writeLog("WIDTH: %d, HEIGHT: %d", Graphics::screenWidth, Graphics::screenHeight); } Game::~Game() { delete _graphics; delete _shader; } void Game::init() { //3D Shader* _shader3D = new Shader(Util::resourcePath + "Shaders/basicd.vert", Util::resourcePath + "Shaders/basicd.frag"); Texture* _tex = Texture::load(Util::resourcePath + "green.tga"); Texture* _sammichTex = Texture::load(Util::resourcePath + "axe.tga"); Texture* _heavyTex = Texture::load(Util::resourcePath + "pyro_flat.tga"); _heavy = new Mesh(_shader3D, Util::resourcePath + "pyro.obj", _heavyTex); _sammich = new Mesh(_shader3D, Util::resourcePath + "axe.obj", _sammichTex); //_cube = new Mesh(_shader3D, Util::resourcePath + "torus.obj", _tex); //_cube2 = new Mesh(_shader3D, Util::resourcePath + "monkey.obj", _tex); //_cube3 = new Mesh(_shader3D, Util::resourcePath + "torus.obj", _tex); _heavy->setPosition(0, 0, -10); _sammich->setPosition(0, 0, -10); //_cube->setPosition(0, 0, -10); //_cube2->setPosition(0, 0, -10); //_cube3->setPosition(0, 0, -10); _sammich->setScale(0.3f); _heavy->setScale(0.3f); //_cube->setScale(2); //_cube3->setScale(3.5f); //_cube->setScale(10); //_sound = Sound::load(Util::resourcePath + "ruby.ogg"); //_sound2 = Sound::load(Util::resourcePath + "hit.ogg"); _shader = new Shader(Util::resourcePath + "Shaders/basic.vert", Util::resourcePath + "Shaders/basic.frag"); renderTexture = new RenderTexture(); fps = 0; _timer = 0.0f; srand(time(NULL)); texture = Texture::load(Util::resourcePath + "green.tga"); _projection = Mat4( 2.0f / Graphics::screenWidth, 0, 0, 0, 0, 2.0f / Graphics::screenHeight, 0, 0, 0, 0, 0, 0, -1, -1, 0, 1); float nearZ = 2; float farZ = 100; float fov = 45.0f; float aspect = Graphics::aspectRatio; float f = 1/tan(fov/2.0f); _projection3D = Mat4( f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, -((farZ+nearZ)/(farZ-nearZ)), -1, 0, 0, -(2*farZ*nearZ/(farZ-nearZ)), 0); for(int i = 0; i < 10; i++) { Sprite sprite; sprite.entity = new SpriteEntity(Util::randomRange(0, Graphics::screenWidth), Util::randomRange(0, Graphics::screenHeight), 64, 64, texture, _shader); Vec2 dir = Vec2(Util::random() - Util::random(), Util::random() - Util::random()); dir.normalize(); sprite.direction = dir; sprite.speed = Util::randomRange(200, 300); sprite.entity->setProjectionMatrix(_projection); sprites.push_back(sprite); } sprite = new gg::SpriteEntity(0, 0, 128, 128, texture, _shader); sprite->setPosition(Graphics::screenWidth/2, Graphics::screenHeight/2); sprite->setProjectionMatrix(_projection); //_cube->setProjectionMatrix(_projection3D); //_cube2->setProjectionMatrix(_projection3D); //_cube3->setProjectionMatrix(_projection3D); _heavy->setProjectionMatrix(_projection3D); _sammich->setProjectionMatrix(_projection3D); //_sound->play(); } void Game::addSprite(int x, int y, int dirX, int dirY) { Sprite sprite; sprite.entity = new SpriteEntity(x, y, 64, 64, texture, _shader); sprite.entity->setProjectionMatrix(_projection); Vec2 dir = Vec2(dirX, dirY); dir.normalize(); sprite.direction = dir; sprite.speed = Util::randomRange(200, 300); sprites.push_back(sprite); //_sound2->play(); } void Game::update(float dt) { static float fpsTimer = 0; fpsTimer += dt; _timer += dt; if(fpsTimer > 1) { writeLog("FPS:%d, SPRITES:%d\n", fps, sprites.size()); fpsTimer = 0; fps = 0; } _shader->setUniform("time", _timer); for(int i = 0; i < sprites.size(); i++) { if (sprites[i].entity->getPosition().y < 0) { sprites[i].entity->setPosition(sprites[i].entity->getPosition().x, 0); sprites[i].direction.y *= -1; } else if (sprites[i].entity->getPosition().y > Graphics::screenHeight) { sprites[i].entity->setPosition(sprites[i].entity->getPosition().x, Graphics::screenHeight); sprites[i].direction.y *= -1; } if(sprites[i].entity->getPosition().x < 0) { sprites[i].entity->setPosition(0, sprites[i].entity->getPosition().y); sprites[i].direction.x *= -1; } else if (sprites[i].entity->getPosition().x > Graphics::screenWidth) { sprites[i].entity->setPosition(Graphics::screenWidth, sprites[i].entity->getPosition().y); sprites[i].direction.x *= -1; } sprites[i].entity->setPosition( sprites[i].entity->getPosition() + sprites[i].direction * sprites[i].speed * dt); sprites[i].entity->setRotationZ(sin(_timer*(i/10.0f))+(i/500.0f)); //sprites[i].entity->setScale(sin(_timer*((i/500.0f)*10)) + 1.5f); } //sprite->setRotation(_timer); //_cube2->setPosition(_cube2->getPosition() + Vec3(sin(_timer*3)/10, 0, cos(_timer*3)/10)); //_cube2->setRotation(_timer*10); //_cube->setRotation(_timer); //_cube3->setRotation(-_timer*3); _heavy->setRotationY(_timer); //_sammich->setPosition(_sammich->getPosition() + Vec3(sin(_timer*3)/5, 0, cos(_timer*3)/15)); _sammich->setPosition(Vec3(-3, 0, -10)); _sammich->setRotationY(_timer); //_cube->setScale(sin(_timer*7) + 1.5f); //_cube->setPosition(Vec3(sin(_timer)*2, _cube->getPosition().y, _cube->getPosition().z)); //sprite->setPosition(Vec3(sprite->getPosition().x, sprite->getPosition().y, sin(_timer)*100)); sprite->setScale(sin(_timer*7) + 1.5f); sprite->setRotationZ(_timer); fps++; } void Game::render() { _graphics->clear(0.2f, 0.2f, 0.2f); renderTexture->clear(Color(0.95f, 0.95f, 0.95f)); //renderTexture->draw(*_cube); //renderTexture->draw(*_cube2); //renderTexture->draw(*_cube3); renderTexture->draw(*_heavy); for(int i = 0; i < sprites.size(); i++) { //renderTexture->draw(*sprites[i].entity); } renderTexture->display(); //_cube->draw(); //_cube2->draw(); //_cube3->draw(); //sprite->draw(); //_heavy->draw(); _sammich->draw(); //_font->render(); }
// // Created by payaln on 03.03.2019. // #pragma once #include <G4UImessenger.hh> #include <G4UIcmdWithABool.hh> #include <G4UIcmdWithADouble.hh> #include <G4UIcmdWith3Vector.hh> #include <functional> #include <vector> #include <memory> #include <algorithm> #include <type_traits> #include "PrimaryPartGenerator.h" template <typename T> class GlobalMessenger : public G4UImessenger { public: explicit GlobalMessenger(T* subj); ~GlobalMessenger() override; void SetNewValue(G4UIcommand *command, G4String newValue) override; template <typename Arg> GlobalMessenger* AddCommand(G4String cmd, std::function<void(T*, Arg)> func, G4String description = ""); private: T* subject; G4UIdirectory* directory; struct CMD{ std::shared_ptr<G4UIcommand> cmd; std::function<void(T*, G4double)> func; }; struct CMDB{ std::shared_ptr<G4UIcommand> cmd; std::function<void(T*, G4bool)> func; }; std::vector<CMD> commands_d; std::vector<CMDB> commands_b; }; template <typename T> GlobalMessenger<T>::GlobalMessenger(T* subj) : subject(subj) { directory = new G4UIdirectory("/custom_cmd/"); directory->SetGuidance("custom settings"); } template <typename T> GlobalMessenger<T>::~GlobalMessenger() { delete directory; } template <typename T> void GlobalMessenger<T>::SetNewValue(G4UIcommand *command, G4String newValue) { { auto it = std::find_if(commands_d.begin(), commands_d.end(), [&command](const CMD &c) { return c.cmd.get() == command; }); if (it != commands_d.end()) { it->func(subject, G4UIcmdWithADouble::GetNewDoubleValue(newValue)); } } { auto it = std::find_if(commands_b.begin(), commands_b.end(), [&command](const CMDB &c) { return c.cmd.get() == command; }); if (it != commands_b.end()) { it->func(subject, G4UIcmdWithABool::GetNewBoolValue(newValue)); } } } template <typename T> template <typename Arg> GlobalMessenger<T>* GlobalMessenger<T>::AddCommand(G4String cmd, std::function<void(T*, Arg)> func, G4String description) { if (std::is_same<Arg, G4double>::value) { commands_d.push_back({std::move(std::shared_ptr<G4UIcommand>(new G4UIcmdWithADouble(G4String(directory->GetCommandPath() + cmd), this))), func}); commands_d.back().cmd->SetGuidance(description); } else if (std::is_same<Arg, G4bool>::value) { commands_b.push_back({std::move(std::shared_ptr<G4UIcommand>(new G4UIcmdWithABool(G4String(directory->GetCommandPath() + cmd), this))), func}); commands_b.back().cmd->SetGuidance(description); } return this; }
#ifndef BUFF_H #define BUFF_H #include "baseobject.h" class Buff : public BaseObject { Q_OBJECT public: Buff(QObject *parent = nullptr); Buff(int x, int y, int width, int height, const QString& imgPath, QObject *parent = nullptr); }; #endif // BUFF_H
#include "Fbo.h" #include <iostream> using namespace std; Fbo::Fbo(GLuint width, GLuint height, bool renderbuffer) : m_hasRenderbuffer(renderbuffer), m_width(width), m_height(height) { glGenFramebuffers(1, &m_fbo); glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); if (renderbuffer) { attachRenderbuffer(); } auto status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (renderbuffer) assert(status == GL_FRAMEBUFFER_COMPLETE); glBindFramebuffer(GL_FRAMEBUFFER, 0); GL_CHECK_ERROR("Fbo::Fbo() - ERROR: "); } Fbo::~Fbo() { if (m_hasRenderbuffer) glDeleteRenderbuffers(1, &m_depth); glDeleteFramebuffers(1, &m_fbo); } void Fbo::attachRenderbuffer() { glGenRenderbuffers(1, &m_depth); glBindRenderbuffer(GL_RENDERBUFFER, m_depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, m_width, m_height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depth); } void Fbo::clear() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Fbo::bind() const { glBindFramebuffer(GL_FRAMEBUFFER, m_fbo); } void Fbo::release() const { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void Fbo::resize(int width, int height) { m_width = width; m_height = height; for (auto& tex : m_textures) { tex->resize(width, height); } if (m_hasRenderbuffer) { glBindRenderbuffer(GL_RENDERBUFFER, m_depth); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, width, height); } if (m_depthTexture.get() != nullptr) { m_depthTexture->resize(width, height); } GL_CHECK_ERROR("Fbo::resize() - ERROR: "); } shared_ptr<Texture2D> Fbo::getTexture(unsigned int index) const { assert(index < m_textures.size()); return m_textures[index]; } void Fbo::addTexture(GLint internalFormat, GLenum format, GLenum type) { auto tex = std::make_shared<Texture2D>(m_width, m_height, internalFormat, format, type); m_textures.push_back(tex); GLuint attachment = m_textures.size() - 1; glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachment, GL_TEXTURE_2D, tex->getTextureId(), 0); m_colorAttachments.push_back(GL_COLOR_ATTACHMENT0 + m_colorAttachments.size()); } void Fbo::setDepthTexture(GLint internalFormat, GLenum format, GLenum type) { assert(m_depthTexture.get() == nullptr && m_hasRenderbuffer == false); // only set depth once! m_depthTexture = std::make_shared<Texture2D>(m_width, m_height, internalFormat, format, type); assert(m_depthTexture->isDepthTexture()); glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_depthTexture->getTextureId(), 0); } void Fbo::bindTexture(GLuint index, GLuint offset) const { assert(index < m_textures.size()); m_textures[index]->bindAt(offset); } void Fbo::bindTextures(GLuint offset) const { for (unsigned int i = 0; i < m_textures.size(); ++i) { m_textures[i]->bindAt(offset + i); } }
#include "../../headers.h" #include "PhillipsSpectrum.h" //------------------------------------------------------------------------------------------------- void PhillipsSpectrum::init(const Settings& settings) { settings_ = settings; // ะดะปะธะฝะฐ ะฒะพะปะฝั‹ ะฟั€ะธ ะทะฐะดะฐะฝะฝะพะน ัะบะพั€ะพัั‚ะธ ะฒะตั‚ั€ะฐ L_ = settings_.WindSpeed *settings_.WindSpeed/9.81; } //------------------------------------------------------------------------------------------------- double PhillipsSpectrum::getValue(double kx, double kz) { glm::vec2 K(kx, kz); double k = glm::length(K); // ะบะฒะฐะดั€ะฐั‚ ะผะพะดัƒะปั ะฒะตะบั‚ะพั€ะฐ k double k2 = k*k; // ะธะผะตะฝะฝะพ ั‚ะพั‡ะฝะพะต ัั€ะฐะฒะฝะตะฝะธะต if (k2 == 0.0) return 0.0; double v = settings_.A*exp(-1.0 / (k2*L_*L_)) / (k2*k2); // ัƒั‡ั‚ะตะผ ะฝะฐะฟั€ะฐะฒะปะตะฝะธะต ะฒะตั‚ั€ะฐ. ะญั‚ะพ ะพั‚ัะตั‡ะตั‚ ะฒะพะปะฝั‹, ะบะพั‚ะพั€ั‹ะต ะธะดัƒั‚ ะฟะตั€ะฟะตะฝะดะธะบัƒะปัั€ะฝะพ ะฝะฐะฟั€ะฐะฒะปะตะฝะธัŽ ะฒะตั‚ั€ะฐ. auto K1 = glm::normalize(K); double w = pow(glm::dot(K1, settings_.WindDirection), settings_.WindAlignment); v *= w; // - ะตั‰ะต ะฝัƒะถะฝะพ ะพั‚ัะตะบะฐั‚ัŒ ัะปะธัˆะบะพะผ ะผะฐะปะตะฝัŒะบะธะต ะฒะพะปะฝั‹ v *= exp(-k2*settings_.MinWaveLength*settings_.MinWaveLength); return v; }
#include "BaseController.h" #include "BaseParameter.h" #include "helpers.h" #include "pluginterfaces/base/ibstream.h" namespace Steinberg { namespace Vst { namespace residler { //----------------------------------------------------------------------------- BaseController::BaseController () : sampleRate (44100) , addBypassParameter (true) { for (int32 i = 0; i < kCountCtrlNumber; i++) midiCCParamID[i] = -1; } //----------------------------------------------------------------------------- tresult PLUGIN_API BaseController::initialize (FUnknown* context) { tresult res = EditControllerEx1::initialize (context); if (res == kResultOk) { UnitInfo uinfo; uinfo.id = kRootUnitId; uinfo.parentUnitId = kNoParentUnitId; uinfo.programListId = kPresetParam; UString name (uinfo.name, 128); name.fromAscii("Root"); addUnit (new Unit (uinfo)); if (addBypassParameter) { IndexedParameter* bypassParam = new IndexedParameter (USTRING("Bypass"), 0, 1, 0, ParameterInfo::kIsBypass | ParameterInfo::kCanAutomate, kBypassParam); bypassParam->setIndexString (0, UString128 ("off")); bypassParam->setIndexString (1, UString128 ("on")); parameters.addParameter (bypassParam); } } return res; } //----------------------------------------------------------------------------- int32 PLUGIN_API BaseController::getProgramListCount () { if (parameters.getParameter (kPresetParam)) return 1; return 0; } //----------------------------------------------------------------------------- tresult PLUGIN_API BaseController::getProgramListInfo (int32 listIndex, ProgramListInfo& info /*out*/) { Parameter* param = parameters.getParameter (kPresetParam); if (param && listIndex == 0) { info.id = kPresetParam; info.programCount = (int32)param->toPlain (1) + 1; UString name (info.name, 128); name.fromAscii("Presets"); return kResultTrue; } return kResultFalse; } //----------------------------------------------------------------------------- tresult PLUGIN_API BaseController::getProgramName (ProgramListID listId, int32 programIndex, String128 name /*out*/) { if (listId == kPresetParam) { Parameter* param = parameters.getParameter (kPresetParam); if (param) { ParamValue normalized = param->toNormalized (programIndex); param->toString (normalized, name); return kResultTrue; } } return kResultFalse; } //----------------------------------------------------------------------------- tresult PLUGIN_API BaseController::notify (IMessage* message) { if (strcmp (message->getMessageID(), "activated") == 0) { message->getAttributes()->getFloat ("SampleRate", sampleRate); return kResultTrue; } return EditControllerEx1::notify (message); } //----------------------------------------------------------------------------- tresult PLUGIN_API BaseController::setComponentState (IBStream* state) { int32 temp; state->read (&temp, sizeof (int32)); SWAP32_BE(temp); for (int32 i = 0; i < temp; i++) { ParamValue value; if (state->read (&value, sizeof (ParamValue)) == kResultTrue) { SWAP64_BE(value); setParamNormalized (i, value); } } int32 bypassState; if (state->read (&bypassState, sizeof (bypassState)) == kResultTrue) { Parameter* bypassParam = parameters.getParameter (kBypassParam); if (bypassParam) { SWAP32_BE(bypassState); bypassParam->setNormalized (bypassState); } } return kResultTrue; } //------------------------------------------------------------------------ tresult PLUGIN_API BaseController::getMidiControllerAssignment (int32 busIndex, int16 channel, CtrlNumber midiControllerNumber, ParamID& tag/*out*/) { if (busIndex == 0 && midiCCParamID[midiControllerNumber] != -1) { tag = midiCCParamID[midiControllerNumber]; return kResultTrue; } return kResultFalse; } //------------------------------------------------------------------------ tresult PLUGIN_API BaseController::queryInterface (const char* iid, void** obj) { QUERY_INTERFACE (iid, obj, IMidiMapping::iid, IMidiMapping) return EditControllerEx1::queryInterface (iid, obj); } }}} // namespaces
#ifndef __GRAPH__ #define __GRAPH__ #include <string> #include <vector> #include <utility> using namespace std; class Node { private: int codigo; int tipo; // 0 = professor, 1 = escola int v1; // se professor, v1 = nยบ de habilitacoes; se escola, v1 = habilitacao 1 desejada int v2; // hab2 desejadas, se escola vector<int> prefs; // preferencias, se professor public: bool free; bool free2; //segunda vaga, da escola int count; //contador pra saber por quais escolas o professor jรก foi recusado Node(); Node(int tipo); int getCodigo(); int getTipo(); int getHabilitacoes(); int getHab1(); int getHab2(); vector<int> getPrefs(); void setCodigo(int val); void setTipo(int val); void setHabilitacoes(int val); void setHab1(int val); void setHab2(int val); void setPrefs(vector<int> prefs); }; class Graph { private: vector<Node> graph; public: void txtInput(string file_name); vector<Node> getGraph(); vector<pair<Node,Node>> GaleShapley(); }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef OP_THREAD_TOOLS_H #define OP_THREAD_TOOLS_H /** @short Manager of thread-safe operations and communication with the main thread. * * Core supports multiple threads, but its concurrency design requires that * the thread-local variable g_component_manager is initialized and accessible * in each thread. When this is not viable, as is the case with threads spawned * by third party code, and for existing code that has not been ported to the * new design, this class may bridge the gap. * * This class provides means for safely posting messages to a Core or non-core * component from another thread than the thread in which a component manager * exists. Also, this class provides threadsafe memory allocation for environments * where the standard malloc implementation is not reentrant. */ class OpThreadTools { public: /** Create and return an OpThreadTools object. * * @param new_main_thread (output) Set to the object created * @return OK or ERR_NO_MEMORY. */ static OP_STATUS Create(OpThreadTools** new_main_thread); virtual ~OpThreadTools() {} /** Allocate memory in a thread-safe manner. * * May be called from any thread. If the malloc implementation used on * the platform is thread-safe, the implementation of this method should * probably just call malloc(). * * @param size Number of bytes to allocate * @return A pointer to the allocated memory, which is suitably aligned for * any kind of variable, or NULL if the request fails (typically out of * memory). This memory should only be freed using the Free() method. */ virtual void* Allocate(size_t size) = 0; /** Free memory allocated by Allocate() in a thread-safe manner. * * May be called from any thread. If the malloc implementation used on * the platform is thread-safe, the implementation of this method should * probably just call free(). * * @param memblock A pointer to the memory that is to be freed. This * pointer must have been returned by a previous call to Allocate(), unless * it is NULL, in which case no operation is performed. */ virtual void Free(void* memblock) = 0; /** Issue a call to g_main_message_handler->PostMessage() in the Opera main thread. * * This method is ambiguous in processes where multiple Opera components * exist, be that several on one thread, or spread across threads. The * method remains for compatibility purposes, and should only succeed * in processes where the choice of destination component is unambigous. * * This method may be implemented by wrapping its arguments in an OpLegacyMessage * delivered through SendMessageToMainThread(). * * This method may be called from any thread (including the Opera main * thread itself). This method must never block (will cause deadlocks). If * this method is not called from the Opera main thread, it must wake up * the main thread in some platform-specific manner and execute code there * that calls g_main_message_handler->PostMessage(). * * Aside from being passed to the g_main_message_handler->PostMessage(), the * parameter values has no meaning on the platform side. */ virtual OP_STATUS PostMessageToMainThread(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2, unsigned long delay = 0) = 0; /** Send a message to an Opera messenger in this process. * * This method may be called from any thread, and must never block. * * @param message The message to send. Its source and destination parameters * are correctly initialized by the caller. The callee assumes ownership * of the message, regardless of return value. * * @return See OpStatus. */ virtual OP_STATUS SendMessageToMainThread(OpTypedMessage* message) = 0; }; #endif // OP_THREAD_TOOLS_H
/* * Copyright (c) 2017 Ensign Energy Incorporated * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Ensign Energy Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Ensign Energy Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Ensign Energy Incorporated. */ #ifndef __DRILLING_CALIBRATION_STATE_SUBSCRIBER_H__ #define __DRILLING_CALIBRATION_STATE_SUBSCRIBER_H__ #include "subscriber.h" #include "base_data_types.h" #include "drilling_calibration.h" #include "drilling_calibrationSupport.h" class CDrillingCalibrationStateSubscriber : public TSubscriber< nec::control::DrillingCalibrationState > { public: typedef std::function<void(const nec::control::DrillingCalibrationState &data)> OnDataAvailableEvent; CDrillingCalibrationStateSubscriber(); ~CDrillingCalibrationStateSubscriber(); // Topic initialization bool Create(int32_t domain); void OnDataAvailable(OnDataAvailableEvent event); void OnDataDisposed(OnDataDisposedEvent event); void OnLivelinessChanged(OnLivelinessChangedEvent event); void OnSubscriptionMatched(OnSubscriptionMatchedEvent event); // Topic getters bool GetId(DataTypes::Uuid &id); bool GetTimestamp(DataTypes::Time &timestamp); bool GetWobProportional(double &wobProportional); bool GetWobIntegral(double &wobIntegral); bool GetDifferentialPressureProportional(double &differentialPressureProportional); bool GetDifferentialPressureIntegral(double &differentialPressureIntegral); bool GetTorqueProportional(double &torqueProportional); bool GetTorqueIntegral(double &torqueIntegral); bool GetMinWobProportional(double &minWobProportional); bool GetMaxWobProportional(double &maxWobProportional); bool GetMinWobIntegral(double &minWobIntegral); bool GetMaxWobIntegral(double &maxWobIntegral); bool GetMinDifferentialPressureProportional(double &minDifferentialPressureProportional); bool GetMaxDifferentialPressureProportional(double &maxDifferentialPressureProportional); bool GetMinDifferentialPressureIntegral(double &minDifferentialPressureIntegral); bool GetMaxDifferentialPressureIntegral(double &maxDifferentialPressureIntegral); bool GetMinTorqueProportional(double &minTorqueProportional); bool GetMaxTorqueProportional(double &maxTorqueProportional); bool GetMinTorqueIntegral(double &minTorqueIntegral); bool GetMaxTorqueIntegral(double &maxTorqueIntegral); // Topic status bool ValidData(); bool ValidSubscription(); protected: void DataAvailable(const nec::control::DrillingCalibrationState &data, const DDS::SampleInfo &sampleInfo); void DataDisposed(const DDS::SampleInfo &sampleInfo); void LivelinessChanged(const DDS::LivelinessChangedStatus &status); void SubscriptionMatched(const DDS::SubscriptionMatchedStatus &status); private: bool m_subscriptionMatched; nec::control::DrillingCalibrationState m_data; DDS::SampleInfo m_sampleInfo; OnDataAvailableEvent m_pOnDataAvailable; OnDataDisposedEvent m_pOnDataDisposed; OnLivelinessChangedEvent m_pOnLivelinessChanged; OnSubscriptionMatchedEvent m_pOnSubscriptionMatched; }; #endif // __DRILLING_CALIBRATION_STATE_SUBSCRIBER_H__
#include "StdAfx.h" #include "UIHelper.h" namespace ui { CPoint operator*(const CPoint& pt, float f) { return CPoint(pt.x * f, pt.y * f); } CPoint operator*(float f, const CPoint& pt) { return CPoint(pt.x * f, pt.y * f); } CPoint operator+(const CPoint& pt0, const CPoint& pt1) { return CPoint(pt0.x + pt1.x, pt0.y + pt1.y); } CPoint operator-(const CPoint& pt0, const CPoint& pt1) { return CPoint(pt0.x - pt1.x, pt0.y - pt1.y); } CPoint operator-(const CPoint& pt) { return CPoint(-pt.x, -pt.y); } int Dot(const CPoint& pt0, const CPoint& pt1) { return pt0.x * pt1.x + pt0.y * pt1.y; } CSize operator*(const CSize& sz, float f) { return CSize(sz.cx * f, sz.cy * f); } CSize operator*(float f, const CSize& sz) { return CSize(sz.cx * f, sz.cy * f); } CSize operator+(const CSize& sz0, const CSize& sz1) { return CSize(sz0.cx + sz1.cx, sz0.cy + sz1.cy); } CSize operator-(const CSize& sz0, const CSize& sz1) { return CSize(sz0.cx - sz1.cx, sz0.cy - sz1.cy); } CSize operator-(const CSize& sz) { return CSize(-sz.cx, -sz.cy); } CPoint LeftTop(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.left, rect.top); } CPoint LeftCenter(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.left, rect.top + ((rect.bottom - rect.top) >> 1)); } CPoint LeftBottom(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.left, rect.bottom); } CPoint TopCenter(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.left + ((rect.right - rect.left) >> 1), rect.top); } CPoint Center(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.left + ((rect.right - rect.left) >> 1), rect.top + ((rect.bottom - rect.top) >> 1)); } CPoint BottomCenter(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.left + ((rect.right - rect.left) >> 1), rect.bottom); } CPoint RightTop(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.right, rect.top); } CPoint RightCenter(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.right, rect.top + ((rect.bottom - rect.top) >> 1)); } CPoint RightBottom(Control* ctrl) { UiRect rect = ctrl->GetPos(); return CPoint(rect.right, rect.bottom); } inline static void MoveByDelta(Control* ctrl, UiRect& raw_rect, const CPoint& delta) { raw_rect.Offset(delta); ctrl->SetPos(raw_rect); } void MoveByDelta(Control* ctrl, const CPoint& delta) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, delta); } void MoveLeftTopTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.left, pt.y - rect.top)); } void MoveLeftCenterTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.left, pt.y - rect.top - ((rect.bottom - rect.top) >> 1))); } void MoveLeftBottomTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.left, pt.y - rect.bottom)); } void MoveTopCenterTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.left - ((rect.right - rect.left) >> 1), pt.y - rect.top)); } void MoveCenterTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.left - ((rect.right - rect.left) >> 1), pt.y - rect.top - ((rect.bottom - rect.top) >> 1))); } void MoveBottomCenterTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.left - ((rect.right - rect.left) >> 1), pt.y - rect.bottom)); } void MoveRightTopTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.right, pt.y - rect.top)); } void MoveRightCenterTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.right, pt.y - rect.top - ((rect.bottom - rect.top) >> 1))); } void MoveRightBottomTo(Control* ctrl, const CPoint& pt) { UiRect rect = ctrl->GetPos(); MoveByDelta(ctrl, rect, CPoint(pt.x - rect.right, pt.y - rect.bottom)); } CSize SizeOf(Control* ctrl) { return CSize(ctrl->GetWidth(), ctrl->GetHeight()); } }
#include <mutex> #include <condition_variable> /** * Make up for the lack of a std::semaphore in C++. */ class semaphore { public: explicit semaphore (int i); /** * Implement the semaphore "P" operation. * wait until count > 0, then acguire it * then decrement the count atomically */ void acquire(); /** * Implement the semaphore "V" operation. * atomically increment the count of semaphore * release one of waiting on thread */ void release(); private: std::mutex m_; //mutually exclude std::condition_variable cond_; // variable wake up on a condition int n_; };
//Project: RTC DS1302 module //Sketched by JIN-WOO KIM #include <stdio.h> #include <DS1302.h> #include <SimpleTimer.h> #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x27, 16, 2); const int kCePin = 5 ; //Chip Enable const int kIoPin = 6 ; //Input and Output const int kSclkPin = 7 ; //Serial clock int ledPin = 13; //Red led light int buzzerPin = 8; //Buzzer SimpleTimer timer; DS1302 rtc(kCePin, kIoPin, kSclkPin); String dayAsString(const Time::Day day) { switch (day) { case Time:: kSunday: return "Sunday"; case Time:: kMonday: return "Monday"; case Time:: kTuesday: return "Tuesday"; case Time:: kWednesday: return "Wednesday"; case Time:: kThursday: return "Thursday"; case Time:: kFriday: return "Friday"; case Time:: kSaturday: return "Saturday"; } return "(unkown day)"; } void setup() { pinMode(ledPin, OUTPUT); pinMode(buzzerPin, OUTPUT); Serial.begin(9600); lcd.begin(); lcd.backlight(); lcd.setCursor(0, 0); //first column, first row lcd.print("Hello World!"); delay(2000); lcd.clear(); rtc.writeProtect(false); rtc.halt(false); Time t(2020, 12, 15, 14, 17, 0, Time::kThursday); rtc.time(t); timer.setInterval(30000,beep); timer.setInterval(5000,blinkled); } void loop() { Time t = rtc.time(); const String day = dayAsString(t.day); char buf[50]; snprintf(buf, sizeof(buf), "%s %04d-%02d-%02d %02d:%02d:%02d", day.c_str(), t.yr, t.mon, t.date, t.hr, t.min, t.sec); Serial.println(buf); lcd.setCursor(0, 0); //first column, first row lcd.print(t.hr); lcd.print(":"); lcd.print(t.min / 10); lcd.print(t.min % 10); lcd.print(":"); lcd.print(t.sec / 10); lcd.print(t.sec % 10); lcd.setCursor(0, 1); //first column, second row lcd.print(t.mon / 10); lcd.print(t.mon % 10); lcd.print("/"); lcd.print(t.date / 10); lcd.print(t.date % 10); lcd.print("/"); lcd.print(t.yr / 10); lcd.print(t.yr % 10); delay(1000); digitalWrite(ledPin,LOW); noTone(buzzerPin); timer.run(); } void beep() { tone(buzzerPin,500); Serial.print("30 seconds over"); Serial.print("/"); } void blinkled() { digitalWrite(ledPin, HIGH); Serial.print("5 seconds over"); Serial.print("/"); }
// // util.cpp // BPNN // // Created by Lnrd on 2018/6/14. // Copyright ยฉ 2018ๅนด LNRD. All rights reserved. // #include "util.hpp" void split(vector<string>& v, const string& s, const string& c) { string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while(string::npos != pos2) { v.push_back(s.substr(pos1, pos2-pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if(pos1 != s.length()) v.push_back(s.substr(pos1)); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 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 WAND_SUPPORT #include "modules/wand/wand_module.h" #include "modules/wand/wandmanager.h" #include "modules/prefs/prefsmanager/collections/pc_core.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/libcrypto/include/CryptoMasterPasswordHandler.h" #ifdef HAS_COMPLEX_GLOBALS # define CONST_ECOM_ARRAY(name) const WandModule::ECOM_ITEM name[] = { # define CONST_ECOM_ENTRY(x,y) { x, y } # define CONST_ECOM_END(name, expected_len) }; # define CONST_ECOM_ARRAY_INIT(name) g_opera->wand_module.m_##name = name; #else # define CONST_ECOM_ARRAY(name) void init_##name () { WandModule::ECOM_ITEM *local = g_opera->wand_module.m_##name; int i=0; # define CONST_ECOM_ENTRY(x,y ) local[i].field_name = x; local[i].pref_id = y; i++ # define CONST_ECOM_END(name, expected_len) ; OP_ASSERT(i == expected_len);} # define CONST_ECOM_ARRAY_INIT(name) init_##name() #endif // HAS_COMPLEX_GLOBALS #ifdef WAND_ECOMMERCE_SUPPORT // Field name from the ECommerce RFC (RFC 3106) // FIELD NAME Min Notes // // ship to title Ecom_ShipTo_Postal_Name_Prefix 4 ( 1) // ship to first name Ecom_ShipTo_Postal_Name_First 15 // ship to middle name Ecom_ShipTo_Postal_Name_Middle 15 ( 2) // ship to last name Ecom_ShipTo_Postal_Name_Last 15 // ship to name suffix Ecom_ShipTo_Postal_Name_Suffix 4 ( 3) // ship to company name Ecom_ShipTo_Postal_Company 20 // ship to street line1 Ecom_ShipTo_Postal_Street_Line1 20 ( 4) // ship to street line2 Ecom_ShipTo_Postal_Street_Line2 20 ( 4) // ship to street line3 Ecom_ShipTo_Postal_Street_Line3 20 ( 4) // ship to city Ecom_ShipTo_Postal_City 22 // ship to state/province Ecom_ShipTo_Postal_StateProv 2 ( 5) // ship to zip/postal code Ecom_ShipTo_Postal_PostalCode 14 ( 6) // ship to country Ecom_ShipTo_Postal_CountryCode 2 ( 7) // ship to phone Ecom_ShipTo_Telecom_Phone_Number 10 ( 8) // ship to email Ecom_ShipTo_Online_Email 40 ( 9) // // bill to title Ecom_BillTo_Postal_Name_Prefix 4 ( 1) // bill to first name Ecom_BillTo_Postal_Name_First 15 // bill to middle name Ecom_BillTo_Postal_Name_Middle 15 ( 2) // bill to last name Ecom_BillTo_Postal_Name_Last 15 // bill to name suffix Ecom_BillTo_Postal_Name_Suffix 4 ( 3) // bill to company name Ecom_BillTo_Postal_Company 20 // bill to street line1 Ecom_BillTo_Postal_Street_Line1 20 ( 4) // bill to street line2 Ecom_BillTo_Postal_Street_Line2 20 ( 4) // bill to street line3 Ecom_BillTo_Postal_Street_Line3 20 ( 4) // bill to city Ecom_BillTo_Postal_City 22 // bill to state/province Ecom_BillTo_Postal_StateProv 2 ( 5) // bill to zip/postal code Ecom_BillTo_Postal_PostalCode 14 ( 6) // bill to country Ecom_BillTo_Postal_CountryCode 2 ( 7) // bill to phone Ecom_BillTo_Telecom_Phone_Number 10 ( 8) // bill to email Ecom_BillTo_Online_Email 40 ( 9) // // receipt to (32) // receipt to title Ecom_ReceiptTo_Postal_Name_Prefix 4 ( 1) // receipt to first name Ecom_ReceiptTo_Postal_Name_First 15 // receipt to middle name Ecom_ReceiptTo_Postal_Name_Middle 15 ( 2) // receipt to last name Ecom_ReceiptTo_Postal_Name_Last 15 // receipt to name suffix Ecom_ReceiptTo_Postal_Name_Suffix 4 ( 3) // receipt to company name Ecom_ReceiptTo_Postal_Company 20 // receipt to street line1 Ecom_ReceiptTo_Postal_Street_Line1 20 ( 4) // receipt to street line2 Ecom_ReceiptTo_Postal_Street_Line2 20 ( 4) // receipt to street line3 Ecom_ReceiptTo_Postal_Street_Line3 20 ( 4) // receipt to city Ecom_ReceiptTo_Postal_City 22 // receipt to state/province Ecom_ReceiptTo_Postal_StateProv 2 ( 5) // receipt to postal code Ecom_ReceiptTo_Postal_PostalCode 14 ( 6) // receipt to country Ecom_ReceiptTo_Postal_CountryCode 2 ( 7) // receipt to phone Ecom_ReceiptTo_Telecom_Phone_Number 10 ( 8) // receipt to email Ecom_ReceiptTo_Online_Email 40 ( 9) // // name on card Ecom_Payment_Card_Name 30 (10) // // card type Ecom_Payment_Card_Type 4 (11) // card number Ecom_Payment_Card_Number 19 (12) // card verification value Ecom_Payment_Card_Verification 4 (13) // card expire date day Ecom_Payment_Card_ExpDate_Day 2 (14) // card expire date month Ecom_Payment_Card_ExpDate_Month 2 (15) // card expire date year Ecom_Payment_Card_ExpDate_Year 4 (16) // // card protocols Ecom_Payment_Card_Protocol 20 (17) // // consumer order ID Ecom_ConsumerOrderID 20 (18) // // user ID Ecom_User_ID 40 (19) // user password Ecom_User_Password 20 (19) // // schema version Ecom_SchemaVersion 30 (20) // // wallet id Ecom_WalletID 40 (21) // // end transaction flag Ecom_TransactionComplete - (22) // // The following fields are used to communicate from the merchant to the // consumer: // // FIELD NAME Min Notes // // merchant home domain Ecom_Merchant 128 (23) // processor home domain Ecom_Processor 128 (24) // transaction identifier Ecom_Transaction_ID 128 (25) // transaction URL inquiry Ecom_Transaction_Inquiry 500 (26) // transaction amount Ecom_Transaction_Amount 128 (27) // transaction currency Ecom_Transaction_CurrencyCode 3 (28) // transaction date Ecom_Transaction_Date 80 (29) // transaction type Ecom_Transaction_Type 40 (30) // transaction signature Ecom_Transaction_Signature 160 (31) // // end transaction flag Ecom_TransactionComplete - (22) #define PREFS_NAMESPACE PrefsCollectionCore CONST_ECOM_ARRAY(eCom_items) CONST_ECOM_ENTRY( "ShipTo_Postal_Name_Prefix", 0 ), CONST_ECOM_ENTRY( "ShipTo_Postal_Name_First", PREFS_NAMESPACE::Firstname ), CONST_ECOM_ENTRY( "ShipTo_Postal_Name_Middle", 0 ), CONST_ECOM_ENTRY( "ShipTo_Postal_Name_Last", PREFS_NAMESPACE::Surname ), CONST_ECOM_ENTRY( "ShipTo_Postal_Name_Suffix", 0 ), CONST_ECOM_ENTRY( "ShipTo_Postal_Company", 0 ), CONST_ECOM_ENTRY( "ShipTo_Postal_Street_Line1", PREFS_NAMESPACE::Address ), CONST_ECOM_ENTRY( "ShipTo_Postal_Street_Line2", 0 ), CONST_ECOM_ENTRY( "ShipTo_Postal_Street_Line3", 0 ), CONST_ECOM_ENTRY( "ShipTo_Postal_City", PREFS_NAMESPACE::City ), CONST_ECOM_ENTRY( "ShipTo_Postal_StateProv", PREFS_NAMESPACE::State ), CONST_ECOM_ENTRY( "ShipTo_Postal_PostalCode", PREFS_NAMESPACE::Zip ), CONST_ECOM_ENTRY( "ShipTo_Postal_CountryCode", 0 ), CONST_ECOM_ENTRY( "ShipTo_Telecom_Phone_Number", PREFS_NAMESPACE::Telephone ), CONST_ECOM_ENTRY( "ShipTo_Online_Email", PREFS_NAMESPACE::EMail ), CONST_ECOM_ENTRY( "BillTo_Postal_Name_Prefix", 0 ), CONST_ECOM_ENTRY( "BillTo_Postal_Name_First", PREFS_NAMESPACE::Firstname ), CONST_ECOM_ENTRY( "BillTo_Postal_Name_Middle", 0 ), CONST_ECOM_ENTRY( "BillTo_Postal_Name_Last", PREFS_NAMESPACE::Surname ), CONST_ECOM_ENTRY( "BillTo_Postal_Name_Suffix", 0 ), CONST_ECOM_ENTRY( "BillTo_Postal_Company", 0 ), CONST_ECOM_ENTRY( "BillTo_Postal_Street_Line1", PREFS_NAMESPACE::Address ), CONST_ECOM_ENTRY( "BillTo_Postal_Street_Line2", 0 ), CONST_ECOM_ENTRY( "BillTo_Postal_Street_Line3", 0 ), CONST_ECOM_ENTRY( "BillTo_Postal_City", PREFS_NAMESPACE::City ), CONST_ECOM_ENTRY( "BillTo_Postal_StateProv", PREFS_NAMESPACE::State ), CONST_ECOM_ENTRY( "BillTo_Postal_PostalCode", PREFS_NAMESPACE::Zip ), CONST_ECOM_ENTRY( "BillTo_Postal_CountryCode", 0 ), CONST_ECOM_ENTRY( "BillTo_Telecom_Phone_Number", PREFS_NAMESPACE::Telephone ), CONST_ECOM_ENTRY( "BillTo_Online_Email", PREFS_NAMESPACE::EMail ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Name_Prefix", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Name_First", PREFS_NAMESPACE::Firstname ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Name_Middle", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Name_Last", PREFS_NAMESPACE::Surname ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Name_Suffix", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Company", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Street_Line1", PREFS_NAMESPACE::Address ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Street_Line2", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_Street_Line3", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_City", PREFS_NAMESPACE::City ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_StateProv", PREFS_NAMESPACE::State ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_PostalCode", PREFS_NAMESPACE::Zip ), CONST_ECOM_ENTRY( "ReceiptTo_Postal_CountryCode", 0 ), CONST_ECOM_ENTRY( "ReceiptTo_Telecom_Phone_Number", PREFS_NAMESPACE::Telephone ), CONST_ECOM_ENTRY( "ReceiptTo_Online_Email", PREFS_NAMESPACE::EMail ) // 45 entries above /*, CONST_ECOM_ENTRY( "Payment_Card_Name", 0 ), CONST_ECOM_ENTRY( "Payment_Card_Type", 0 ), CONST_ECOM_ENTRY( "Payment_Card_Number", 0 ), CONST_ECOM_ENTRY( "Payment_Card_Verification", 0 ), CONST_ECOM_ENTRY( "Payment_Card_ExpDate_Day", 0 ), CONST_ECOM_ENTRY( "Payment_Card_ExpDate_Month", 0 ), CONST_ECOM_ENTRY( "Payment_Card_ExpDate_Year", 0 ) */ CONST_ECOM_END(eCom_items, ECOM_ITEMS_LEN); #ifdef WAND_GUESS_COMMON_FORMFIELD_MEANING CONST_ECOM_ARRAY(common_items) // CONST_ECOM_ENTRY( "name", PREFS_NAMESPACE::Firstname ), // "username" used on many webmail // CONST_ECOM_ENTRY( "user", PREFS_NAMESPACE::Firstname ), // and NOT "pass" or "name" // CONST_ECOM_ENTRY( "login", PREFS_NAMESPACE::EMail ), // CONST_ECOM_ENTRY( "loginname", PREFS_NAMESPACE::EMail ), CONST_ECOM_ENTRY( "mail", PREFS_NAMESPACE::EMail ), // *NOTE* if the index of this changes, then GetECommerceItem must change. CONST_ECOM_ENTRY( "country", PREFS_NAMESPACE::Country ), CONST_ECOM_ENTRY( "zip", PREFS_NAMESPACE::Zip ), CONST_ECOM_ENTRY( "city", PREFS_NAMESPACE::City ), CONST_ECOM_ENTRY( "state", PREFS_NAMESPACE::State ), CONST_ECOM_ENTRY( "phone", PREFS_NAMESPACE::Telephone ) CONST_ECOM_END(common_items, ECOM_COMMON_ITEMS_LEN); #endif // WAND_GUESS_COMMON_FORMFIELD_MEANING #endif // WAND_ECOMMERCE_SUPPORT void WandModule::InitL(const OperaInitInfo& info) { wand_manager = OP_NEW_L(WandManager, ()); wand_manager->SetActive(g_pccore->GetIntegerPref(PrefsCollectionCore::EnableWand)); obfuscation_password = "\x83\x7D\xFC\x0F\x8E\xB3\xE8\x69\x73\xAF\xFF"; // Used to obfuscate data, even when master password is used (for example when reading/writing to disc) LEAVE_IF_NULL(wand_obfuscation_password = ObfuscatedPassword::Create((const UINT8*)obfuscation_password, op_strlen(obfuscation_password), FALSE)); #ifdef SYNC_HAVE_PASSWORD_MANAGER LEAVE_IF_ERROR(wand_manager->InitSync()); #endif // SYNC_HAVE_PASSWORD_MANAGER // This should be done later. Way later. #ifndef _MACINTOSH_ OpFile wand_file; g_pcfiles->GetFileL(PrefsCollectionFiles::WandFile, wand_file); wand_manager->Open(wand_file, TRUE, TRUE); #endif // If wand is not encrypted, its obfuscated. We start with an obfuscating password. if (!wand_manager->GetIsSecurityEncrypted()) LEAVE_IF_NULL(wand_encryption_password = ObfuscatedPassword::Create((const UINT8*)obfuscation_password, op_strlen(obfuscation_password), FALSE)); else wand_encryption_password = NULL; // If wand is encrypted, this will be set later when we ask the user for it. #ifdef WAND_ECOMMERCE_SUPPORT CONST_ECOM_ARRAY_INIT(eCom_items); # ifdef WAND_GUESS_COMMON_FORMFIELD_MEANING CONST_ECOM_ARRAY_INIT(common_items); # endif // WAND_GUESS_COMMON_FORMFIELD_MEANING #endif // WAND_ECOMMERCE_SUPPORT } void WandModule::Destroy() { OP_DELETE(wand_manager); wand_manager = NULL; OP_DELETE(wand_encryption_password); OP_DELETE(wand_obfuscation_password); } #endif // WAND_SUPPORT
#include<iostream> #include<cstring> #include<cstdio> #include<iomanip> using namespace std; int main() { int i=4; double d=4.0; string s = "HackerRank "; int val; double ans; string res,result; cin>>val>>ans; getline(cin>> ws,res); val=val+i; ans=ans+d; result=s+res; cout<<val<<"\n"<<fixed<<setprecision(1)<<ans<<"\n"<<result<<endl; return 0; }
#include<bits/stdc++.h> using namespace std; int count(int n){ //Base case if(n == 0){ return 0; } //Recursion int ans = count(n/10); //Calculation return ans + 1; } int main(){ int n; cout<<"Enter value of n: "<<endl; cin>>n; cout<<"No of digits: "<<endl; cout<<""<<count(n); return 0; }
#pragma once #include "color.h" #include "point.h" #include <string> class ButtonTheme { public: const Color fillColor = Color(255, 255, 255); const Color fontColor = Color(0, 0, 0); const int fontSize = 12; const Point<float> textOffset = Point<float>(4, 1); }; class SliderTheme { public: const Point<float> indicatorSize = Point<float>(10, 20); const Point<float> barSize = Point<float>(100, 5); const Color indicatorColor = Color(255, 255, 255); const Color barColor = Color(255, 255, 255); const Point<float> labelOffset = Point<float>(120, -5); const int fontSize = 12; const Color fontColor = Color(255, 255, 255); }; class CheckboxTheme { public: const float size = 20; const Point<float> labelOffset = Point<float>(30, 4); const Color boxColor = Color(255, 255, 255); const Color crossColor = Color(0, 0, 0); const int fontSize = 12; const Color fontColor = Color(255, 255, 255); }; class SelectboxTheme { public: const Color fontColor = Color(255, 255, 255); const Point<float> labelOffset = Point<float>(0, -20); const int fontSize = 12; const Point<float> buttonSize = Point<float>(15, 15); const float buttonGap = 10; const float textWidth = 150; const unsigned int maxStringSize = 21; const ButtonTheme *buttonTheme = new ButtonTheme(); }; struct AppConsts { const Point<int> windowSize = Point<int>(1200, 900); const std::string appTitle = "Hemisphere renderer"; const Point<int> toolbarPos = Point<int>(0, 0); const Point<int> toolbarSize = Point<int>(300, 900); const Point<int> canvasPos = Point<int>(300, 0); const Point<int> canvasSize = Point<int>(900, 900); const Color canvasColor = Color(0, 0, 0); const int framerateLimit = 30; const bool showFPS = true; const Point<float> fpsLabelPosition = Point<float>(1170, 0); const int fpsLabelFontSize = 20; const Color fpsLabelColor = Color(255, 0, 0); const Point<float> toolbarControlsOffset = Point<float>(20, 20); const int meshRadius = 320; const Point<int> meshPos = Point<int>(750, 450); const Point<int> relativeMeshPos = Point<int>(450, 450); const int meshZPos = 0; const Color meshEdgesColor = Color(255, 255, 255); const Point<int> textureExpectedSize = Point<int>(1008, 1008); const float spiralMovePeriodTime = 3.0; const float spiralMovePeriodDistance = 200; const float spiralMoveRange = 1200; const std::string spiralSliderLabel = "Toggle light spiral move"; const int minMeridianCount = 4; const int defaultMeridianCount = 32; const int maxMeridianCount = 32; const std::string meridianCountLabel = "Meridian count"; const int minParallelCount = 1; const int defaultParallelCount = 1; const int maxParallelCount = 8; const std::string parallelCountLabel = "Parallel count"; const float minKD = 0; const float defaultKD = 0.5; const float maxKD = 1; const std::string kdLabel = "KD factor"; const float minKS = 0; const float defaultKS = 0.5; const float maxKS = 1; const std::string ksLabel = "KS factor"; const int minM = 1; const int defaultM = 50; const int maxM = 100; const std::string mLabel = "M factor"; const float minK = 0; const float defaultK = 0.5; const float maxK = 1; const std::string kLabel = "K factor"; const bool defaultApproximateColoringMode = false; const std::string approxColoringLabel = "Approximate coloring mode"; const Color defaultLightColor = Color(255, 255, 255); const float minLightZPos = 320 * 1.5; const float defaultLightZPos = 320 * 5; const float maxLightZPos = 320 * 10; const std::string lightZPosLabel = "Light Z pos"; const std::string lightColorRLabel = "Light color R"; const std::string lightColorGLabel = "Light color G"; const std::string lightColorBLabel = "Light color B"; const bool defaultRenderMeshMode = true; const std::string renderMeshModeLabel = "Toggle mesh drawing"; const bool defaultSpiralMoveMode = true; const Color defaultTextureColor = Color(255, 255, 255); const Color defaultNormalMapColor = Color(0, 0, 0); const Point<float> verticesGrabTolerance = Point<float>(3, 3); const std::string textureSelectboxLabel = "Texture"; const std::string normalMapSelectboxLabel = "Normal map"; const float toolbarSmallGap = 40; const float toolbarBigGap = 70; const ButtonTheme *buttonTheme = new ButtonTheme(); const CheckboxTheme *checkboxTheme = new CheckboxTheme(); const SliderTheme *sliderTheme = new SliderTheme(); const SelectboxTheme *selectboxTheme = new SelectboxTheme(); };
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> //use dirt for testing #include "../blocks/BlockDirt.cpp" #include "world/block.cpp" #include "world/chunk.cpp" #include "world/world.cpp"
#include <iostream> #include <fstream> #include <vector> using namespace std; int main() { ifstream infile; infile.open("input/gunshots.in"); // calculate new region // right_side = R - num // left_side = R - num - num if not zero // same thing for y int t; infile >> t; for (int i = 0; i < t; i++){ int R, T, x, y, num_folds; infile >> R >> T >> x >> y >> num_folds; vector<vector<int>> folds; folds.push_back({0, R, 0, T}); for (int j = 0; j < num_folds; j++) { char dir; int num; infile >> dir >> num; if (num > R || num > T) { continue; } int right_side = R, left_side = 0, ls = 0, rs = T; if (dir == 'X') { left_side = (num - (R - num)); R = num; }else{ ls = num - (T - num); T = num; } int size = folds.size(); for (int k = 0; k < size; k++) { if (dir == 'X'){ right_side = R; folds.push_back({left_side, right_side, ls, rs}); }else{ rs = T; folds.push_back({left_side, right_side, ls, rs}); } } } int count = 0; if (x > R || y > T){ cout << count; return 0; } int size = folds.size(); for (int i = 0; i < size; i++){ if( x >= folds[0][0] && x <= folds[0][1] && y >= folds[0][2] && folds[0][3]){ count++; } } //for (vector<int> k : folds){ // for (int l : k){ // cout << l << " "; // } // cout << endl; //} cout << count << endl; } }
#include "MdLibrary.h" double MinimumDistance::minimumDistance(g_Vector &p1, g_Vector &p2, g_Vector &p3, g_Vector &p4, bool bSquared, double ** barycenters) { g_Vector u, v; double d2121; u = p2 - p1; v = p4 - p3; d2121 = u.Dot(u); return minimumDistance(p1, u, p3, v, d2121, bSquared, barycenters); } double MinimumDistance::minimumDistance(g_Vector &p1, g_Vector &u, g_Vector &p3, g_Vector &v, double d2121, bool bSquared, double ** barycenters) { double dMD = 0.0; g_Vector w; double d4343, d4321, d1343, d1321; double mu_a, mu_b, cl_a, cl_b; w = p1 - p3; d4343 = v.Dot(v); d4321 = v.Dot(u); d1343 = w.Dot(v); d1321 = w.Dot(u); mu_a = (d1343 * d4321 - d1321 * d4343) / (d2121 * d4343 - d4321 * d4321); mu_b = (d1343 + mu_a * d4321) / d4343; cl_a = max(0.0, mu_a); cl_a = min(1.0, cl_a); cl_b = max(0.0, mu_b); cl_b = min(1.0, cl_b); if(barycenters != NULL) { (*barycenters)[0] = 1.0 - cl_a; (*barycenters)[1] = cl_a; (*barycenters)[2] = 1.0 - cl_b; (*barycenters)[3] = cl_b; } if (bSquared) dMD = ((p1 + u * cl_a) - (p3 + v * cl_b)).SquaredLength(); else dMD = ((p1 + u * cl_a) - (p3 + v * cl_b)).Length(); return dMD; } double MinimumDistance::minimumDistance(g_Element & t1, g_Element & t2, int * returnSmallest, double ** barycenters) { double dist, minDist; double * tempBarycenters = new double[6]; g_NodeContainer nodes1, nodes2; nodes1 = t1.nodes(); nodes2 = t2.nodes(); g_Plane plane1(nodes1[0]->coordinate(), nodes1[1]->coordinate(), nodes1[2]->coordinate()); g_Plane plane2(nodes2[0]->coordinate(), nodes2[1]->coordinate(), nodes2[2]->coordinate()); dist = -1; if(barycenters != NULL) (*barycenters)[0] = (*barycenters)[1] = (*barycenters)[2] = (*barycenters)[3] = (*barycenters)[4] = (*barycenters)[5] = 0; if(returnSmallest != NULL) *returnSmallest = -1; if((nodes1[0] == nodes2[0]) || (nodes1[0] == nodes2[1]) || (nodes1[0] == nodes2[2]) || (nodes1[1] == nodes2[0]) || (nodes1[1] == nodes2[1]) || (nodes1[1] == nodes2[2]) || (nodes1[2] == nodes2[0]) || (nodes1[2] == nodes2[1]) || (nodes1[2] == nodes2[2])) minDist = dist = 0.0; if(dist == -1) { // Segment-segment distances: minDist = minimumDistance(nodes1[0]->coordinate(), nodes1[1]->coordinate(), nodes2[0]->coordinate(), nodes2[1]->coordinate(), false, &tempBarycenters); if(returnSmallest != NULL) *returnSmallest = 0; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[0]; (*barycenters)[1] = tempBarycenters[1]; (*barycenters)[2] = 0; (*barycenters)[3] = tempBarycenters[2]; (*barycenters)[4] = tempBarycenters[3]; (*barycenters)[5] = 0; } dist = minimumDistance(nodes1[0]->coordinate(), nodes1[1]->coordinate(), nodes2[1]->coordinate(), nodes2[2]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 1; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[0]; (*barycenters)[1] = tempBarycenters[1]; (*barycenters)[2] = 0; (*barycenters)[3] = 0; (*barycenters)[4] = tempBarycenters[2]; (*barycenters)[5] = tempBarycenters[3]; } } dist = minimumDistance(nodes1[0]->coordinate(), nodes1[1]->coordinate(), nodes2[2]->coordinate(), nodes2[0]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 2; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[0]; (*barycenters)[1] = tempBarycenters[1]; (*barycenters)[2] = 0; (*barycenters)[3] = tempBarycenters[3]; (*barycenters)[4] = 0; (*barycenters)[5] = tempBarycenters[2]; } } dist = minimumDistance(nodes1[1]->coordinate(), nodes1[2]->coordinate(), nodes2[0]->coordinate(), nodes2[1]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 3; if(barycenters != NULL) { (*barycenters)[0] = 0; (*barycenters)[1] = tempBarycenters[0]; (*barycenters)[2] = tempBarycenters[1]; (*barycenters)[3] = tempBarycenters[2]; (*barycenters)[4] = tempBarycenters[3]; (*barycenters)[5] = 0; } } dist = minimumDistance(nodes1[1]->coordinate(), nodes1[2]->coordinate(), nodes2[1]->coordinate(), nodes2[2]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 4; if(barycenters != NULL) { (*barycenters)[0] = 0; (*barycenters)[1] = tempBarycenters[0]; (*barycenters)[2] = tempBarycenters[1]; (*barycenters)[3] = 0; (*barycenters)[4] = tempBarycenters[2]; (*barycenters)[5] = tempBarycenters[3]; } } dist = minimumDistance(nodes1[1]->coordinate(), nodes1[2]->coordinate(), nodes2[2]->coordinate(), nodes2[0]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 5; if(barycenters != NULL) { (*barycenters)[0] = 0; (*barycenters)[1] = tempBarycenters[0]; (*barycenters)[2] = tempBarycenters[1]; (*barycenters)[3] = tempBarycenters[3]; (*barycenters)[4] = 0; (*barycenters)[5] = tempBarycenters[2]; } } dist = minimumDistance(nodes1[2]->coordinate(), nodes1[0]->coordinate(), nodes2[0]->coordinate(), nodes2[1]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 6; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[1]; (*barycenters)[1] = 0; (*barycenters)[2] = tempBarycenters[0]; (*barycenters)[3] = tempBarycenters[2]; (*barycenters)[4] = tempBarycenters[3]; (*barycenters)[5] = 0; } } dist = minimumDistance(nodes1[2]->coordinate(), nodes1[0]->coordinate(), nodes2[1]->coordinate(), nodes2[2]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 7; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[1]; (*barycenters)[1] = 0; (*barycenters)[2] = tempBarycenters[0]; (*barycenters)[3] = 0; (*barycenters)[4] = tempBarycenters[2]; (*barycenters)[5] = tempBarycenters[3]; } } dist = minimumDistance(nodes1[2]->coordinate(), nodes1[0]->coordinate(), nodes2[2]->coordinate(), nodes2[0]->coordinate(), false, &tempBarycenters); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 8; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[1]; (*barycenters)[1] = 0; (*barycenters)[2] = tempBarycenters[0]; (*barycenters)[3] = tempBarycenters[3]; (*barycenters)[4] = 0; (*barycenters)[5] = tempBarycenters[2]; } } // Point-plane distances: if(projectionInTriangle(t1, nodes2[0]->coordinate(), &tempBarycenters)) { dist = plane1.distanceToPoint(nodes2[0]->coordinate()); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 9; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[0]; (*barycenters)[1] = tempBarycenters[1]; (*barycenters)[2] = tempBarycenters[2]; (*barycenters)[3] = 1; (*barycenters)[4] = 0; (*barycenters)[5] = 0; } } } if(projectionInTriangle(t1, nodes2[1]->coordinate(), &tempBarycenters)) { dist = plane1.distanceToPoint(nodes2[1]->coordinate()); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 10; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[0]; (*barycenters)[1] = tempBarycenters[1]; (*barycenters)[2] = tempBarycenters[2]; (*barycenters)[3] = 0; (*barycenters)[4] = 1; (*barycenters)[5] = 0; } } } if(projectionInTriangle(t1, nodes2[2]->coordinate(), &tempBarycenters)) { dist = plane1.distanceToPoint(nodes2[2]->coordinate()); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 11; if(barycenters != NULL) { (*barycenters)[0] = tempBarycenters[0]; (*barycenters)[1] = tempBarycenters[1]; (*barycenters)[2] = tempBarycenters[2]; (*barycenters)[3] = 0; (*barycenters)[4] = 0; (*barycenters)[5] = 1; } } } if(projectionInTriangle(t2, nodes1[0]->coordinate(), &tempBarycenters)) { dist = plane2.distanceToPoint(nodes1[0]->coordinate()); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 12; if(barycenters != NULL) { (*barycenters)[0] = 1; (*barycenters)[1] = 0; (*barycenters)[2] = 0; (*barycenters)[3] = tempBarycenters[0]; (*barycenters)[4] = tempBarycenters[1]; (*barycenters)[5] = tempBarycenters[2]; } } } if(projectionInTriangle(t2, nodes1[1]->coordinate(), &tempBarycenters)) { dist = plane2.distanceToPoint(nodes1[1]->coordinate()); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 13; if(barycenters != NULL) { (*barycenters)[0] = 0; (*barycenters)[1] = 1; (*barycenters)[2] = 0; (*barycenters)[3] = tempBarycenters[0]; (*barycenters)[4] = tempBarycenters[1]; (*barycenters)[5] = tempBarycenters[2]; } } } if(projectionInTriangle(t2, nodes1[2]->coordinate(), &tempBarycenters)) { dist = plane2.distanceToPoint(nodes1[2]->coordinate()); if(dist < minDist) { minDist = dist; if(returnSmallest != NULL) *returnSmallest = 14; if(barycenters != NULL) { (*barycenters)[0] = 0; (*barycenters)[1] = 0; (*barycenters)[2] = 1; (*barycenters)[3] = tempBarycenters[0]; (*barycenters)[4] = tempBarycenters[1]; (*barycenters)[5] = tempBarycenters[2]; } } } } delete [] tempBarycenters; return minDist; } bool MinimumDistance::projectionInTriangle(g_Element t, g_Vector p, double ** barycenters) { int turn1, turn2, turn3; double dot; g_Plane plane(t.nodes()[0]->coordinate(), t.nodes()[1]->coordinate(), t.nodes()[2]->coordinate()); g_Vector projection = plane.project(p); dot = (t.nodes()[1]->coordinate()-t.nodes()[0]->coordinate()).Cross(projection-t.nodes()[1]->coordinate()).Dot(plane.normal()); if(dot < 0) turn1 = -1; else turn1 = 1; dot = (t.nodes()[2]->coordinate()-t.nodes()[1]->coordinate()).Cross(projection-t.nodes()[2]->coordinate()).Dot(plane.normal()); if(dot < 0) turn2 = -1; else turn2 = 1; dot = (t.nodes()[0]->coordinate()-t.nodes()[2]->coordinate()).Cross(projection-t.nodes()[0]->coordinate()).Dot(plane.normal()); if(dot < 0) turn3 = -1; else turn3 = 1; if(turn1 == turn2 && turn2 == turn3) { if(barycenters != NULL) { //compute barycentric coordinates of projection in t: double areaABC, areaPBC, areaPCA; g_Vector normal = (t.nodes()[1]->coordinate()-t.nodes()[0]->coordinate()).Cross(t.nodes()[2]->coordinate()-t.nodes()[0]->coordinate()); normal.Normalize(); // Compute twice area of triangle ABC areaABC = normal.Dot((t.nodes()[1]->coordinate()-t.nodes()[0]->coordinate()).Cross(t.nodes()[2]->coordinate()-t.nodes()[0]->coordinate())); // Compute barycentrics areaPBC = normal.Dot((t.nodes()[1]->coordinate()-projection).Cross(t.nodes()[2]->coordinate()-projection)); (*barycenters)[0] = areaPBC / areaABC; areaPCA = normal.Dot((t.nodes()[2]->coordinate()-projection).Cross(t.nodes()[0]->coordinate()-projection)); (*barycenters)[1] = areaPCA / areaABC; (*barycenters)[2] = 1.0 - (*barycenters)[0] - (*barycenters)[1]; } return true; } else return false; } bool MinimumDistance::intersect(g_Element & t1, g_Element & t2, double threshold) { g_NodeContainer nodes1, nodes2; g_Vector intersection; double tVal; bool computationOK; nodes1 = t1.nodes(); nodes2 = t2.nodes(); g_Plane plane1(nodes1[0]->coordinate(), nodes1[1]->coordinate(), nodes1[2]->coordinate()); g_Plane plane2(nodes2[0]->coordinate(), nodes2[1]->coordinate(), nodes2[2]->coordinate()); if((nodes1[0] == nodes2[0]) || (nodes1[0] == nodes2[1]) || (nodes1[0] == nodes2[2]) || (nodes1[1] == nodes2[0]) || (nodes1[1] == nodes2[1]) || (nodes1[1] == nodes2[2]) || (nodes1[2] == nodes2[0]) || (nodes1[2] == nodes2[1]) || (nodes1[2] == nodes2[2])) return true; computationOK = plane1.line_plane_intersection(nodes2[1]->coordinate()-nodes2[0]->coordinate(),nodes2[0]->coordinate(),intersection,tVal); if(computationOK) { if((0.0-threshold<=tVal) && (tVal<=1.0+threshold)) { if(projectionInTriangle(t1, intersection)) return true; } } else { if(intersectInPlane(t1, nodes2[0]->coordinate(), nodes2[1]->coordinate(), threshold)) return true; } computationOK = plane1.line_plane_intersection(nodes2[2]->coordinate()-nodes2[1]->coordinate(),nodes2[1]->coordinate(),intersection,tVal); if(computationOK) { if((0.0-threshold<=tVal) && (tVal<=1.0+threshold)) { if(projectionInTriangle(t1, intersection)) return true; } } else { if(intersectInPlane(t1, nodes2[1]->coordinate(), nodes2[2]->coordinate(), threshold)) return true; } computationOK = plane1.line_plane_intersection(nodes2[0]->coordinate()-nodes2[2]->coordinate(),nodes2[2]->coordinate(),intersection,tVal); if(computationOK) { if((0.0-threshold<=tVal) && (tVal<=1.0+threshold)) { if(projectionInTriangle(t1, intersection)) return true; } } else { if(intersectInPlane(t1, nodes2[2]->coordinate(), nodes2[0]->coordinate(), threshold)) return true; } if(plane1.distanceToPoint(nodes2[0]->coordinate()) < threshold) { if(projectionInTriangle(t1, nodes2[0]->coordinate())) return true; } if(plane1.distanceToPoint(nodes2[1]->coordinate()) < threshold) { if(projectionInTriangle(t1, nodes2[1]->coordinate())) return true; } if(plane1.distanceToPoint(nodes2[2]->coordinate()) < threshold) { if(projectionInTriangle(t1, nodes2[2]->coordinate())) return true; } computationOK = plane2.line_plane_intersection(nodes1[1]->coordinate()-nodes1[0]->coordinate(),nodes1[0]->coordinate(),intersection,tVal); if(computationOK) { if((0.0-threshold<=tVal) && (tVal<=1.0+threshold)) { if(projectionInTriangle(t2, intersection)) return true; } } else { if(intersectInPlane(t2, nodes1[0]->coordinate(), nodes1[1]->coordinate(), threshold)) return true; } computationOK = plane2.line_plane_intersection(nodes1[2]->coordinate()-nodes1[1]->coordinate(),nodes1[1]->coordinate(),intersection,tVal); if(computationOK) { if((0.0-threshold<=tVal) && (tVal<=1.0+threshold)) { if(projectionInTriangle(t2, intersection)) return true; } } else { if(intersectInPlane(t2, nodes1[1]->coordinate(), nodes1[2]->coordinate(), threshold)) return true; } computationOK = plane2.line_plane_intersection(nodes1[0]->coordinate()-nodes1[2]->coordinate(),nodes1[2]->coordinate(),intersection,tVal); if(computationOK) { if((0.0-threshold<=tVal) && (tVal<=1.0+threshold)) { if(projectionInTriangle(t2, intersection)) return true; } } else { if(intersectInPlane(t2, nodes1[2]->coordinate(), nodes1[0]->coordinate(), threshold)) return true; } if(plane2.distanceToPoint(nodes1[0]->coordinate()) < threshold) { if(projectionInTriangle(t2, nodes1[0]->coordinate())) return true; } if(plane2.distanceToPoint(nodes1[1]->coordinate()) < threshold) { if(projectionInTriangle(t2, nodes1[1]->coordinate())) return true; } if(plane2.distanceToPoint(nodes1[2]->coordinate()) < threshold) { if(projectionInTriangle(t2, nodes1[2]->coordinate())) return true; } return false; } bool MinimumDistance::intersectInPlane(g_Element & t, g_Vector & p1, g_Vector & p2, double threshold) { if(minimumDistance(t.nodes()[0]->coordinate(), t.nodes()[1]->coordinate(), p1, p2, false) < threshold) return true; if(minimumDistance(t.nodes()[1]->coordinate(), t.nodes()[2]->coordinate(), p1, p2, false) < threshold) return true; if(minimumDistance(t.nodes()[2]->coordinate(), t.nodes()[0]->coordinate(), p1, p2, false) < threshold) return true; return false; } double MinimumDistance::boundingBoxDist(g_Vector& p1, g_Vector& p2, g_Vector& p3, g_Vector& p4) { double dist, minDist; bool intersect = true; if(max(p1.x(), p2.x()) < min(p3.x(), p4.x())) intersect = false; else if(max(p3.x(), p4.x()) < min(p1.x(), p2.x())) intersect = false; else if(max(p1.y(), p2.y()) < min(p3.y(), p4.y())) intersect = false; else if(max(p3.y(), p4.y()) < min(p1.y(), p2.y())) intersect = false; else if(max(p1.z(), p2.z()) < min(p3.z(), p4.z())) intersect = false; else if(max(p3.z(), p4.z()) < min(p1.z(), p2.z())) intersect = false; if(intersect) return 0.0; minDist = -1; dist = fabs(min(p3.x(), p4.x()) - max(p1.x(), p2.x())); minDist = dist; dist = fabs(min(p1.x(), p2.x()) - max(p3.x(), p4.x())); if(dist < minDist) minDist = dist; dist = fabs(min(p3.y(), p4.y()) - max(p1.y(), p2.y())); if(dist < minDist) minDist = dist; dist = fabs(min(p1.y(), p2.y()) - max(p3.y(), p4.y())); if(dist < minDist) minDist = dist; dist = fabs(min(p3.z(), p4.z()) - max(p1.z(), p2.z())); if(dist < minDist) minDist = dist; dist = fabs(min(p1.z(), p2.z()) - max(p3.z(), p4.z())); if(dist < minDist) minDist = dist; return minDist; } void MinimumDistance::mdGrad_p1(g_Vector &p1, g_Vector &p2, g_Vector &p3, g_Vector &p4, g_Vector &grad) { g_Vector u, v, w, z; double d2121; double d4343, d4321, d1343, d1321; double numer_a, denom_a; double rcpDenom, rcpD4343; double mu_a, mu_b; double cl_a, cl_b; g_Vector del_numer, del_denom; g_Vector del_mu_a, del_mu_b; g_Vector del_cl_a, del_cl_b; g_Vector ones(1.0, 1.0, 1.0); g_Vector displace; double dMD, rcpDMD; u = p2 - p1; v = p4 - p3; w = p1 - p3; z = p2 + p3 - (p1 * 2); d2121 = u.Dot(u); d4343 = v.Dot(v); d4321 = v.Dot(u); d1343 = w.Dot(v); d1321 = w.Dot(u); if(fabs(d4343) < MD_DEFAULT_EPSILON) d4343 = MD_DEFAULT_EPSILON; rcpD4343 = 1.0 / d4343; numer_a = d1343 * d4321 - d1321 * d4343; denom_a = d2121 * d4343 - d4321 * d4321; if(fabs(denom_a) < MD_DEFAULT_EPSILON) denom_a = MD_DEFAULT_EPSILON; rcpDenom = 1.0 / denom_a; mu_a = numer_a * rcpDenom; mu_b = (d1343 + mu_a * d4321) * rcpD4343; cl_a = max(0.0, mu_a); cl_a = min(1.0, cl_a); cl_b = max(0.0, mu_b); cl_b = min(1.0, cl_b); displace = (p1 + u * cl_a) - (p3 + v * cl_b); dMD = displace.Length(); if (dMD < MD_DEFAULT_EPSILON) dMD = MD_DEFAULT_EPSILON; rcpDMD = 1.0 / dMD; del_numer = (v * v.Dot(z)) - z * d4343; del_denom = (v * d4321 - u * d4343) * 2; del_mu_a = (del_numer * denom_a - del_denom * numer_a) * (rcpDenom * rcpDenom); del_mu_b = (v * (1.0 - mu_a) + del_mu_a * d4321) * rcpD4343; if (mu_a <= 0.0 || mu_a >= 1.0) del_cl_a.Set(0.0, 0.0, 0.0); else del_cl_a = del_mu_a; if (mu_b <= 0.0 || mu_b >= 1.0) del_cl_b.Set(0.0, 0.0, 0.0); else del_cl_b = del_mu_b; double * matrix = new double[9]; double * addMatrix = new double[9]; initializeIdentity(matrix); matrixMultiply(del_cl_a, u, addMatrix); matrixAdd(matrix, addMatrix, matrix); initializeIdentity(addMatrix); scalarMultiply(-cl_a, addMatrix); matrixAdd(matrix, addMatrix, matrix); matrixMultiply(del_cl_b, v, addMatrix); scalarMultiply(-1.0, addMatrix); matrixAdd(matrix, addMatrix, matrix); scalarMultiply(rcpDMD, addMatrix); grad = matrixMultiply(matrix, displace); delete [] matrix; delete [] addMatrix; } void MinimumDistance::initializeIdentity(double *& matrix) { matrix[0] = matrix[4] = matrix[8] = 1.0; matrix[1] = matrix[2] = matrix[3] = matrix[5] = matrix[6] = matrix[7] = 0.0; } void MinimumDistance::matrixMultiply(g_Vector vec1, g_Vector vec2, double *& result) { result[0] = vec1.x()*vec2.x(); result[1] = vec1.y()*vec2.x(); result[2] = vec1.z()*vec2.x(); result[3] = vec1.x()*vec2.y(); result[4] = vec1.y()*vec2.y(); result[5] = vec1.z()*vec2.y(); result[6] = vec1.x()*vec2.z(); result[7] = vec1.y()*vec2.z(); result[8] = vec1.z()*vec2.z(); } g_Vector MinimumDistance::matrixMultiply(double *& matrix, g_Vector vec) { double x, y, z; x = matrix[0]*vec.x() + matrix[3] * vec.y() + matrix[6] * vec.z(); y = matrix[1]*vec.x() + matrix[4] * vec.y() + matrix[7] * vec.z(); z = matrix[2]*vec.x() + matrix[5] * vec.y() + matrix[8] * vec.z(); g_Vector result(x, y, z); return result; } void MinimumDistance::transposeMatrix(double *& matrix) { double swap; swap = matrix[1]; matrix[1] = matrix[3]; matrix[3] = swap; swap = matrix[2]; matrix[2] = matrix[6]; matrix[6] = swap; swap = matrix[5]; matrix[5] = matrix[7]; matrix[7] = swap; } void MinimumDistance::scalarMultiply(double scalarMultiplier, double *& result) { int i; for(i = 0; i < 9; i++) result[i] = scalarMultiplier * result[i]; } void MinimumDistance::matrixAdd(double *& mat1, double *& mat2, double *& result) { int i; for(i = 0; i < 9; i++) result[i] = mat1[i] + mat2[i]; } double MinimumDistance::evaluateSegments() { if(edges == NULL) return 0; else { double stress, dMD2; g_Node p1, p2, p3, p4; int i, j, numEdges; stress = 0.0; //compute MD energy for all pairs of edges numEdges = edges->numberOfItems(); for(i = 0; i < numEdges; i++) { p1 = (*edges)[i]->firstNode(); p2 = (*edges)[i]->lastNode(); for(j = i+1; j < numEdges; j++) { p3 = (*edges)[j]->firstNode(); p4 = (*edges)[j]->lastNode(); if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) continue; dMD2 = minimumDistance(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate()); if (dMD2 < MD_DEFAULT_EPSILON) dMD2 = MD_DEFAULT_EPSILON; stress += 1.0 / dMD2; } } return stress; } } void MinimumDistance::gradientSegments(double*& gradient) { if(edges == NULL) return; else { int i, j, numEdges, sampleSize, targetDim; double dist3; g_Node p1, p2, p3, p4; g_Vector grad; sampleSize = nodes->numberOfItems(); targetDim = 3; //compute gradient of MD energy for all pairs of edges for(i = 0; i < sampleSize * targetDim; i++) gradient[i] = 0.0; numEdges = edges->numberOfItems(); for(i = 0; i < numEdges; i++) { p1 = (*edges)[i]->firstNode(); p2 = (*edges)[i]->lastNode(); for(j = i+1; j < numEdges; j++) { p3 = (*edges)[j]->firstNode(); p4 = (*edges)[j]->lastNode(); if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) continue; MinimumDistance::mdGrad_p1(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate(), grad); dist3 = (max(pow(MinimumDistance::minimumDistance(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate(), false), 3.0),MD_DEFAULT_EPSILON)); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM IN "<<i<<" "<<j<<endl; } gradient[(p1.id()-1)*targetDim] += grad.x(); gradient[(p1.id()-1)*targetDim+1] += grad.y(); gradient[(p1.id()-1)*targetDim+2] += grad.z(); MinimumDistance::mdGrad_p1(p2.coordinate(), p1.coordinate(), p3.coordinate(), p4.coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM IN "<<i<<" "<<j<<endl; } gradient[(p2.id()-1)*targetDim] += grad.x(); gradient[(p2.id()-1)*targetDim+1] += grad.y(); gradient[(p2.id()-1)*targetDim+2] += grad.z(); MinimumDistance::mdGrad_p1(p3.coordinate(), p4.coordinate(), p1.coordinate(), p2.coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM IN "<<i<<" "<<j<<endl; } gradient[(p3.id()-1)*targetDim] += grad.x(); gradient[(p3.id()-1)*targetDim+1] += grad.y(); gradient[(p3.id()-1)*targetDim+2] += grad.z(); MinimumDistance::mdGrad_p1(p4.coordinate(), p3.coordinate(), p1.coordinate(), p2.coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM IN "<<i<<" "<<j<<endl; } gradient[(p4.id()-1)*targetDim] += grad.x(); gradient[(p4.id()-1)*targetDim+1] += grad.y(); gradient[(p4.id()-1)*targetDim+2] += grad.z(); } } } } double MinimumDistance::evaluateSegments(int id) { if(edges == NULL) return 0; else { int i, j, numEdges; double stress, dMD2; g_PEdgeContainer localCont; g_ElementContainer elems; g_PtrAdapter<g_PEdge *> adapt(localCont); g_Node p1, p2, p3, p4; g_Node * current; stress = 0.0; current = (*nodes)[id]; //find the edges adjacent to the node id: elems = current->elements(); for(i = 0; i < (int)elems.numberOfItems(); i++) { g_PEdgeContainer edgeCont = elems[i]->pEdges(); if((edgeCont[0]->firstNode().id() == current->id()) || (edgeCont[0]->lastNode().id() == current->id())) localCont.insert(edgeCont[0]); else delete edgeCont[0]; if((edgeCont[1]->firstNode().id() == current->id()) || (edgeCont[1]->lastNode().id() == current->id())) localCont.insert(edgeCont[1]); else delete edgeCont[1]; if((edgeCont[2]->firstNode().id() == current->id()) || (edgeCont[2]->lastNode().id() == current->id())) localCont.insert(edgeCont[2]); else delete edgeCont[2]; } adapt.removeDuplicates(); //compute MD energy for all pairs of edges numEdges = edges->numberOfItems(); for(i = 0; i < (int)localCont.numberOfItems(); i++) { p1 = localCont[i]->firstNode(); p2 = localCont[i]->lastNode(); for(j = 0; j < numEdges; j++) { p3 = (*edges)[j]->firstNode(); p4 = (*edges)[j]->lastNode(); if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) continue; dMD2 = MinimumDistance::minimumDistance(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate()); if (dMD2 < MD_DEFAULT_EPSILON) dMD2 = MD_DEFAULT_EPSILON; stress += 1.0 / dMD2; } } for(i = 0; i < (int)localCont.numberOfItems(); i++) delete localCont[i]; localCont.clear(); return stress; } } void MinimumDistance::gradientSegments(int id, double*& gradient) { if(edges == NULL) return; else { int i, j, numEdges, targetDim; double dist3; g_PEdgeContainer localCont; g_ElementContainer elems; g_Node * current; g_PtrAdapter<g_PEdge *> adapt(localCont); g_Node p1, p2, p3, p4; g_Vector grad; targetDim = 3; //compute gradient of MD energy for all pairs of edges for(i = 0; i < targetDim; i++) gradient[i] = 0.0; current = (*nodes)[id]; //find the edges adjacent to the node id: elems = current->elements(); for(i = 0; i < (int)elems.numberOfItems(); i++) { g_PEdgeContainer edgeCont = elems[i]->pEdges(); if((edgeCont[0]->firstNode().id() == current->id()) || (edgeCont[0]->lastNode().id() == current->id())) localCont.insert(edgeCont[0]); else delete edgeCont[0]; if((edgeCont[1]->firstNode().id() == current->id()) || (edgeCont[1]->lastNode().id() == current->id())) localCont.insert(edgeCont[1]); else delete edgeCont[1]; if((edgeCont[2]->firstNode().id() == current->id()) || (edgeCont[2]->lastNode().id() == current->id())) localCont.insert(edgeCont[2]); else delete edgeCont[2]; } adapt.removeDuplicates(); //compute MD energy for all pairs of edges numEdges = edges->numberOfItems(); for(i = 0; i < (int)localCont.numberOfItems(); i++) { p1 = localCont[i]->firstNode(); p2 = localCont[i]->lastNode(); if(p2.id() == current->id()) { p3 = p1; p1 = p2; p2 = p3; } for(j = 0; j < numEdges; j++) { p3 = (*edges)[j]->firstNode(); p4 = (*edges)[j]->lastNode(); if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) continue; MinimumDistance::mdGrad_p1(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate(), grad); dist3 = (max(pow(MinimumDistance::minimumDistance(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate(), false), 3.0),MD_DEFAULT_EPSILON)); grad = -2.0 * grad/dist3; gradient[0] += grad.x(); gradient[1] += grad.y(); gradient[2] += grad.z(); } } for(i = 0; i < (int)localCont.numberOfItems(); i++) delete localCont[i]; localCont.clear(); } } double MinimumDistance::getMaxStepSizeSegments() { if(edges == NULL) return 0; else { double minimum, dMD2; g_Node p1, p2, p3, p4; int i, j, numEdges; minimum = -1.0; //compute MD energy for all pairs of edges numEdges = edges->numberOfItems(); for(i = 0; i < numEdges; i++) { p1 = (*edges)[i]->firstNode(); p2 = (*edges)[i]->lastNode(); #pragma omp parallel for private(j, p3, p4, dMD2) for(j = i+1; j < numEdges; j++) { p3 = (*edges)[j]->firstNode(); p4 = (*edges)[j]->lastNode(); if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) continue; if((minimum == -1) || (boundingBoxDist(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate()) < minimum)) { dMD2 = minimumDistance(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate(), false); #pragma omp critical { if((minimum == -1) || (dMD2 < minimum)) minimum = dMD2; } } } } return minimum/3.0; } } double MinimumDistance::getMaxStepSizeSegments(int id) { if(edges == NULL) return 0; else { double minimum, dMD2; g_Node p1, p2, p3, p4; int i, j, numEdges, numElems; g_NodeContainer neighbors; g_PtrAdapter<g_Node *> adapter(neighbors); g_ElementContainer elements; minimum = -1.0; //compute MD energy for all pairs of edges numEdges = edges->numberOfItems(); p1 = *((*nodes)[id]); elements = p1.elements(); numElems = elements.numberOfItems(); for(i = 0; i < numElems; i++) { if(*(elements[i]->nodes()[0]) != p1) neighbors.insert(elements[i]->nodes()[0]); if(*(elements[i]->nodes()[1]) != p1) neighbors.insert(elements[i]->nodes()[1]); if(*(elements[i]->nodes()[2]) != p1) neighbors.insert(elements[i]->nodes()[2]); } adapter.removeDuplicates(); numElems = neighbors.numberOfItems(); for(i = 0; i < numElems; i++) { p2 = *(neighbors[i]); #pragma omp parallel for private(j, p3, p4, dMD2) for(j = 0; j < numEdges; j++) { p3 = (*edges)[j]->firstNode(); p4 = (*edges)[j]->lastNode(); if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) continue; if((minimum == -1) || (boundingBoxDist(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate()) < minimum)) { dMD2 = minimumDistance(p1.coordinate(), p2.coordinate(), p3.coordinate(), p4.coordinate(), false); #pragma omp critical { if((minimum == -1) || (dMD2 < minimum)) minimum = dMD2; } } } } return minimum/3.0; } } double MinimumDistance::evaluateTriangles() { if(meshElements == NULL) return 0; else { int i, j, numElems; double stress; numElems = meshElements->numberOfItems(); stress = 0.0; for(i = 0; i < numElems; i++) { for(j = i+1; j < numElems; j++) { if(((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[2])) continue; stress += 1.0/max(pow(minimumDistance((*(*meshElements)[i]), (*(*meshElements)[j])), 2), MD_DEFAULT_EPSILON); } } return stress; } } bool MinimumDistance::selfIntersection(double threshold) { if(meshElements == NULL) return false; else { int i, j, numElems; bool returnVal = false; numElems = meshElements->numberOfItems(); for(i = 0; i < numElems; i++) { for(j = i+1; j < numElems; j++) { if(((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[2])) continue; else if(intersect((*(*meshElements)[i]), (*(*meshElements)[j])), threshold) { returnVal = true; return returnVal; } } } return returnVal; } } void MinimumDistance::gradientTriangles(double*& gradient) { if(meshElements == NULL) return; else { int i, j, numElems, nNodes, index; nNodes = (int) nodes->numberOfItems(); numElems = meshElements->numberOfItems(); for(i = 0; i < nNodes*3; i++) gradient[i] = 0.0; for(i = 0; i < numElems; i++) { for(j = i+1; j < numElems; j++) { if(((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[2])) continue; minimumDistance((*(*meshElements)[i]), (*(*meshElements)[j]), &index); switch(index) { case 0: addSegmentGrad((*meshElements)[i]->nodes()[0], (*meshElements)[i]->nodes()[1], (*meshElements)[j]->nodes()[0], (*meshElements)[j]->nodes()[1], gradient); break; case 1: addSegmentGrad((*meshElements)[i]->nodes()[0], (*meshElements)[i]->nodes()[1], (*meshElements)[j]->nodes()[1], (*meshElements)[j]->nodes()[2], gradient); break; case 2: addSegmentGrad((*meshElements)[i]->nodes()[0], (*meshElements)[i]->nodes()[1], (*meshElements)[j]->nodes()[2], (*meshElements)[j]->nodes()[0], gradient); break; case 3: addSegmentGrad((*meshElements)[i]->nodes()[1], (*meshElements)[i]->nodes()[2], (*meshElements)[j]->nodes()[0], (*meshElements)[j]->nodes()[1], gradient); break; case 4: addSegmentGrad((*meshElements)[i]->nodes()[1], (*meshElements)[i]->nodes()[2], (*meshElements)[j]->nodes()[1], (*meshElements)[j]->nodes()[2], gradient); break; case 5: addSegmentGrad((*meshElements)[i]->nodes()[1], (*meshElements)[i]->nodes()[2], (*meshElements)[j]->nodes()[2], (*meshElements)[j]->nodes()[0], gradient); break; case 6: addSegmentGrad((*meshElements)[i]->nodes()[2], (*meshElements)[i]->nodes()[0], (*meshElements)[j]->nodes()[0], (*meshElements)[j]->nodes()[1], gradient); break; case 7: addSegmentGrad((*meshElements)[i]->nodes()[2], (*meshElements)[i]->nodes()[0], (*meshElements)[j]->nodes()[1], (*meshElements)[j]->nodes()[2], gradient); break; case 8: addSegmentGrad((*meshElements)[i]->nodes()[2], (*meshElements)[i]->nodes()[0], (*meshElements)[j]->nodes()[2], (*meshElements)[j]->nodes()[0], gradient); break; case 9: addPointPlaneGrad((*meshElements)[i], (*meshElements)[j]->nodes()[0], gradient); break; case 10: addPointPlaneGrad((*meshElements)[i], (*meshElements)[j]->nodes()[1], gradient); break; case 11: addPointPlaneGrad((*meshElements)[i], (*meshElements)[j]->nodes()[2], gradient); break; case 12: addPointPlaneGrad((*meshElements)[j], (*meshElements)[i]->nodes()[0], gradient); break; case 13: addPointPlaneGrad((*meshElements)[j], (*meshElements)[i]->nodes()[1], gradient); break; case 14: addPointPlaneGrad((*meshElements)[j], (*meshElements)[i]->nodes()[2], gradient); break; } } } } } void MinimumDistance::addPointPlaneGrad(g_Element * t, g_Node * p, double *& gradient, int id) { int index; double dist3; g_Vector grad, helpVec; double * matrix = new double[9]; g_NodeContainer nodes = t->nodes(); g_Vector normal = (nodes[1]->coordinate()-nodes[0]->coordinate()).Cross( nodes[2]->coordinate()-nodes[0]->coordinate()); if(normal.Length() < MD_DEFAULT_EPSILON) return; g_Plane plane(normal, nodes[0]->coordinate()); dist3 = max(pow(plane.distanceToPoint(p->coordinate()), 3), MD_DEFAULT_EPSILON); if(id == -1 || id == 0) { grad = normal; grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = p->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } if(id == -1 || id == 1) { helpVec = p->coordinate() - nodes[0]->coordinate(); matrix[0] = 0.0; matrix[4] = 0.0; matrix[8] = 0.0; matrix[1] = nodes[1]->coordinate().z()-nodes[2]->coordinate().z(); matrix[3] = -matrix[1]; matrix[2] = nodes[2]->coordinate().y()-nodes[1]->coordinate().y(); matrix[6] = -matrix[2]; matrix[5] = nodes[1]->coordinate().x()-nodes[2]->coordinate().x(); matrix[7] = -matrix[5]; grad = matrixMultiply(matrix, helpVec); grad = grad-normal; grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = nodes[0]->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } if(id == -1 || id == 2) { helpVec = p->coordinate() - nodes[0]->coordinate(); matrix[0] = 0.0; matrix[4] = 0.0; matrix[8] = 0.0; matrix[1] = nodes[2]->coordinate().z()-nodes[0]->coordinate().z(); matrix[3] = -matrix[1]; matrix[2] = nodes[0]->coordinate().y()-nodes[2]->coordinate().y(); matrix[6] = -matrix[2]; matrix[5] = nodes[2]->coordinate().x()-nodes[0]->coordinate().x(); matrix[7] = -matrix[5]; grad = matrixMultiply(matrix, helpVec); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = nodes[1]->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } if(id == -1 || id == 3) { helpVec = p->coordinate() - nodes[0]->coordinate(); matrix[0] = 0.0; matrix[4] = 0.0; matrix[8] = 0.0; matrix[1] = nodes[0]->coordinate().z()-nodes[1]->coordinate().z(); matrix[3] = -matrix[1]; matrix[2] = nodes[1]->coordinate().y()-nodes[0]->coordinate().y(); matrix[6] = -matrix[2]; matrix[5] = nodes[0]->coordinate().x()-nodes[1]->coordinate().x(); matrix[7] = -matrix[5]; grad = matrixMultiply(matrix, helpVec); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = nodes[2]->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } delete [] matrix; } void MinimumDistance::addSegmentGrad(g_Node * p1, g_Node * p2, g_Node * p3, g_Node * p4, double *& gradient, int id) { int index; double dist3; g_Vector grad; if((p1 == p3) || (p1 == p4) || (p2 == p3) || (p2 == p4)) return; dist3 = (max(pow(MinimumDistance::minimumDistance(p1->coordinate(), p2->coordinate(), p3->coordinate(), p4->coordinate(), false), 3.0),MD_DEFAULT_EPSILON)); if(id == -1 || id == 0) { MinimumDistance::mdGrad_p1(p1->coordinate(), p2->coordinate(), p3->coordinate(), p4->coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = p1->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } if(id == -1 || id == 1) { MinimumDistance::mdGrad_p1(p2->coordinate(), p1->coordinate(), p3->coordinate(), p4->coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = p2->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } if(id == -1 || id == 2) { MinimumDistance::mdGrad_p1(p3->coordinate(), p4->coordinate(), p1->coordinate(), p2->coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = p3->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } if(id == -1 || id == 3) { MinimumDistance::mdGrad_p1(p4->coordinate(), p3->coordinate(), p1->coordinate(), p2->coordinate(), grad); grad = -2.0 * grad/dist3; if((grad.x() != grad.x()) || (grad.y() != grad.y()) || (grad.z() != grad.z())) { cout<<"PROBLEM"<<endl; } if(id == -1) index = p4->id()-1; else index = 0; gradient[index*3] += grad.x(); gradient[index*3+1] += grad.y(); gradient[index*3+2] += grad.z(); } } double MinimumDistance::evaluateTriangles(int id) { if(meshElements == NULL) return 0; else { int i, j, numElems; double stress; g_ElementContainer localElems = (*nodes)[id]->elements(); numElems = meshElements->numberOfItems(); stress = 0.0; for(i = 0; i < (int)localElems.numberOfItems(); i++) { for(j = 0; j < numElems; j++) { if(((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[2])) continue; stress += 1.0/max(pow(minimumDistance((*(*meshElements)[j]), (*localElems[i])), 2), MD_DEFAULT_EPSILON); } } return stress; } } void MinimumDistance::gradientTriangles(int id, double*& gradient) { if(meshElements == NULL) return; else { int i, j, numElems, index, localIdx, helpIdx; gradient[0] = 0.0; gradient[1] = 0.0; gradient[2] = 0.0; g_ElementContainer localElems = (*nodes)[id]->elements(); numElems = meshElements->numberOfItems(); for(i = 0; i < (int)localElems.numberOfItems(); i++) { if(localElems[i]->nodes()[0] == (*nodes)[id]) localIdx = 0; else if(localElems[i]->nodes()[1] == (*nodes)[id]) localIdx = 1; else localIdx = 2; for(j = 0; j < numElems; j++) { if(((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[2])) continue; minimumDistance((*(*meshElements)[j]), (*localElems[i]), &index); switch(index) { case 0: if(localIdx != 2) { if(localIdx == 0) helpIdx = 2; if(localIdx == 1) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[0], (*meshElements)[j]->nodes()[1], localElems[i]->nodes()[0], localElems[i]->nodes()[1], gradient, helpIdx); } break; case 1: if(localIdx != 0) { if(localIdx == 1) helpIdx = 2; if(localIdx == 2) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[0], (*meshElements)[j]->nodes()[1], localElems[i]->nodes()[1], localElems[i]->nodes()[2], gradient, helpIdx); } break; case 2: if(localIdx != 1) { if(localIdx == 2) helpIdx = 2; if(localIdx == 0) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[0], (*meshElements)[j]->nodes()[1], localElems[i]->nodes()[2], localElems[i]->nodes()[0], gradient, helpIdx); } break; case 3: if(localIdx != 2) { if(localIdx == 0) helpIdx = 2; if(localIdx == 1) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[1], (*meshElements)[j]->nodes()[2], localElems[i]->nodes()[0], localElems[i]->nodes()[1], gradient, helpIdx); } break; case 4: if(localIdx != 0) { if(localIdx == 1) helpIdx = 2; if(localIdx == 2) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[1], (*meshElements)[j]->nodes()[2], localElems[i]->nodes()[1], localElems[i]->nodes()[2], gradient, helpIdx); } break; case 5: if(localIdx != 1) { if(localIdx == 2) helpIdx = 2; if(localIdx == 0) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[1], (*meshElements)[j]->nodes()[2], localElems[i]->nodes()[2], localElems[i]->nodes()[0], gradient, helpIdx); } break; case 6: if(localIdx != 2) { if(localIdx == 0) helpIdx = 2; if(localIdx == 1) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[2], (*meshElements)[j]->nodes()[0], localElems[i]->nodes()[0], localElems[i]->nodes()[1], gradient, helpIdx); } break; case 7: if(localIdx != 0) { if(localIdx == 1) helpIdx = 2; if(localIdx == 2) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[2], (*meshElements)[j]->nodes()[0], localElems[i]->nodes()[1], localElems[i]->nodes()[2], gradient, helpIdx); } break; case 8: if(localIdx != 1) { if(localIdx == 2) helpIdx = 2; if(localIdx == 0) helpIdx = 3; addSegmentGrad((*meshElements)[j]->nodes()[2], (*meshElements)[j]->nodes()[0], localElems[i]->nodes()[2], localElems[i]->nodes()[0], gradient, helpIdx); } break; case 9: if(localIdx == 0) addPointPlaneGrad((*meshElements)[j], localElems[i]->nodes()[0], gradient, 0); break; case 10: if(localIdx == 1) addPointPlaneGrad((*meshElements)[j], localElems[i]->nodes()[1], gradient, 0); break; case 11: if(localIdx == 2) addPointPlaneGrad((*meshElements)[j], localElems[i]->nodes()[2], gradient, 0); break; case 12: addPointPlaneGrad(localElems[i], (*meshElements)[j]->nodes()[0], gradient, localIdx+1); break; case 13: addPointPlaneGrad(localElems[i], (*meshElements)[j]->nodes()[1], gradient, localIdx+1); break; case 14: addPointPlaneGrad(localElems[i], (*meshElements)[j]->nodes()[2], gradient, localIdx+1); break; } } } } } double MinimumDistance::getMaxStepSizeTriangles() { if(meshElements == NULL) return 0; else { int i, j, numElems; double minimum, dist; numElems = meshElements->numberOfItems(); minimum = -1.0; for(i = 0; i < numElems; i++) { #pragma omp parallel for private (j, dist) for(j = i+1; j < numElems; j++) { if(((*meshElements)[j]->nodes()[0] == (*meshElements)[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[0] == (*meshElements)[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[0] == (*meshElements)[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[1] == (*meshElements)[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[1] == (*meshElements)[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[1] == (*meshElements)[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[2] == (*meshElements)[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[2] == (*meshElements)[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[2] == (*meshElements)[i]->nodes()[2])) continue; dist = minimumDistance((*(*meshElements)[i]), (*(*meshElements)[j])); #pragma omp critical { if((minimum == -1.0) || (dist < minimum)) minimum = dist; } } } return minimum / 3.0; } } double MinimumDistance::getMaxStepSizeTriangles(int id) { if(meshElements == NULL) return 0; else { int i, j, numElems; double minimum, dist; g_ElementContainer localElems = (*nodes)[id]->elements(); numElems = meshElements->numberOfItems(); minimum = -1.0; for(i = 0; i < (int)localElems.numberOfItems(); i++) { #pragma omp parallel for private(j, dist) for(j = 0; j < numElems; j++) { if(((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[0] == localElems[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[1] == localElems[i]->nodes()[2]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[0]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[1]) || ((*meshElements)[j]->nodes()[2] == localElems[i]->nodes()[2])) continue; dist = minimumDistance((*(*meshElements)[j]), (*localElems[i])); #pragma omp critical { if((minimum == -1) || (dist < minimum)) minimum = dist; } } } return minimum / 3.0; } } void MinimumDistance::updateNN() { if(meshElements == NULL) return; else { #if MEASURE_TIME int t = (int)time(0); #endif int i, j, numElems; double distance; nearestNeighbor.clear(); distNN.clear(); numElems = meshElements->numberOfItems(); nearestNeighbor.resize(numElems); distNN.resize(numElems); #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) nearestNeighbor[i] = -1; #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) distNN[i] = -1; for(i = 0; i < numElems; i++) { #pragma omp parallel for private(j, distance) for(j = i+1; j < numElems; j++) { if(((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[0] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[1] == (*meshElements)[j]->nodes()[2]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[0]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[1]) || ((*meshElements)[i]->nodes()[2] == (*meshElements)[j]->nodes()[2])) continue; distance = minimumDistance((*(*meshElements)[i]), (*(*meshElements)[j])); #pragma omp critical if((distNN[i] == -1) || (distance < distNN[i])) { distNN[i] = distance; nearestNeighbor[i] = j; } #pragma omp critical if((distNN[j] == -1) || (distance < distNN[j])) { distNN[j] = distance; nearestNeighbor[j] = i; } } } #if MEASURE_TIME cout<<"Time to execute MinimumDistance::updateNN() "<<(int)time(0)-t<<" s"<<endl; #endif } } void MinimumDistance::updateNNKdSpherical() { if(meshElements == NULL) return; else { #if MEASURE_TIME int t = (int)time(0); #endif int i, j, k, numElems, numNodes; double distance, radius; nearestNeighbor.clear(); distNN.clear(); numElems = meshElements->numberOfItems(); numNodes = nodes->numberOfItems(); nearestNeighbor.resize(numElems); distNN.resize(numElems); #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) nearestNeighbor[i] = -1; #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) distNN[i] = -1; //Find the longest edge length: for(i = 0; i < numElems; i++) { g_Element * elem = (* meshElements)[i]; for(j = 0; j < 3; j++) { distance = elem->nodes()[j]->coordinate().DistanceTo(elem->nodes()[(j+1)%3]->coordinate()); if(((i == 0)&&(j == 0)) || (distance > radius)) radius = distance; } } radius = 3.0/2.0 * radius; //Build a kd-tree for the nodes #if USE_ANN ANNpointArray dataPts; ANNpoint queryPt; ANNidxArray nnIdx; ANNkd_tree* kdTree; queryPt = annAllocPt(3); dataPts = annAllocPts(numNodes, 3); nnIdx = new ANNidx[numNodes]; for(i = 0; i < numNodes; i++) { dataPts[i][0] = (*nodes)[i]->coordinate().x(); dataPts[i][1] = (*nodes)[i]->coordinate().y(); dataPts[i][2] = (*nodes)[i]->coordinate().z(); } kdTree = new ANNkd_tree(dataPts, numNodes, 3); #else kdTree * kd = kdTree_create(); for(i = 0; i < numNodes; i++) { NODE * pNode = (NODE*)malloc(sizeof(NODE)); pNode->coordinate.x = (*nodes)[i]->coordinate().x(); pNode->coordinate.y = (*nodes)[i]->coordinate().y(); pNode->coordinate.z = (*nodes)[i]->coordinate().z(); pNode->local_id = i; kdTree_insert(kd, pNode); } #endif for(i = 0; i < numNodes; i++) { //Do spherical range searching and insert triangles into neighbors #if USE_ANN queryPt[0] = (*nodes)[i]->coordinate().x(); queryPt[1] = (*nodes)[i]->coordinate().y(); queryPt[2] = (*nodes)[i]->coordinate().z(); int numRange = kdTree->annkFRSearch(queryPt, radius*radius, numNodes, nnIdx); g_ElementContainer contToCheck; g_PtrAdapter<g_Element *> adapt(contToCheck); for(j = 0; j < numRange; j++) { contToCheck.append((*nodes)[nnIdx[j]]->elements()); } #else COORDINATE p; p.x = (*nodes)[i]->coordinate().x(); p.y = (*nodes)[i]->coordinate().y(); p.z = (*nodes)[i]->coordinate().z(); nodeQueue * neighbors = kdTree_spherical_range_search(kd, p, radius); g_ElementContainer contToCheck; g_PtrAdapter<g_Element *> adapt(contToCheck); for(j = 0; j < nodeQueue_numberOfItems(neighbors); j++) contToCheck.append((*nodes)[nodeQueue_remove(neighbors)->local_id]->elements()); #endif adapt.removeDuplicates(); int contNum = contToCheck.numberOfItems(); //Find nearest neighbor int numElemNeighbors = (*nodes)[i]->elements().numberOfItems(); for(j = 0; j < numElemNeighbors; j++) { int id1 = (*nodes)[i]->elements()[j]->id()-1; #pragma omp parallel for private(k, distance) for(k = 0; k < contNum; k++) { int id2 = contToCheck[k]->id()-1; if(id2 <= id1) continue; if(((*meshElements)[id1]->nodes()[0] == (*meshElements)[id2]->nodes()[0]) || ((*meshElements)[id1]->nodes()[0] == (*meshElements)[id2]->nodes()[1]) || ((*meshElements)[id1]->nodes()[0] == (*meshElements)[id2]->nodes()[2]) || ((*meshElements)[id1]->nodes()[1] == (*meshElements)[id2]->nodes()[0]) || ((*meshElements)[id1]->nodes()[1] == (*meshElements)[id2]->nodes()[1]) || ((*meshElements)[id1]->nodes()[1] == (*meshElements)[id2]->nodes()[2]) || ((*meshElements)[id1]->nodes()[2] == (*meshElements)[id2]->nodes()[0]) || ((*meshElements)[id1]->nodes()[2] == (*meshElements)[id2]->nodes()[1]) || ((*meshElements)[id1]->nodes()[2] == (*meshElements)[id2]->nodes()[2])) continue; distance = minimumDistance((*(*meshElements)[id1]), (*(*meshElements)[id2])); #pragma omp critical if((distNN[id1] == -1) || (distance < distNN[id1])) { distNN[id1] = distance; nearestNeighbor[id1] = id2; } #pragma omp critical if((distNN[id2] == -1) || (distance < distNN[id2])) { distNN[id2] = distance; nearestNeighbor[id2] = id1; } } } } //Delete kd-tree #if USE_ANN delete [] nnIdx; delete kdTree; annClose(); #else kdTree_destroy(kd); #endif #if MEASURE_TIME cout<<"Time to execute MinimumDistance::updateNN() "<<(int)time(0)-t<<" s"<<endl; #endif } } void MinimumDistance::updateNNKd() { if(meshElements == NULL) return; else { #if MEASURE_TIME int t = (int)time(0); #endif int i, j, k, numElems, numNodes; double distance; nearestNeighbor.clear(); distNN.clear(); numElems = meshElements->numberOfItems(); numNodes = nodes->numberOfItems(); nearestNeighbor.resize(numElems); distNN.resize(numElems); int * kValueElement = new int[numElems]; int * kValueNode = new int[numNodes]; #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) nearestNeighbor[i] = -1; #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) distNN[i] = -1; #pragma omp parallel for private(i) for(i = 0; i < numElems; i++) kValueElement[i] = 0; #pragma omp parallel for private(i) for(i = 0; i < numNodes; i++) kValueNode[i] = 0; //Find the k-values (number of required nearest neighbors) for(i = 0; i < numElems; i++) { if((*meshElements)[i]->nodes().numberOfItems() == 3) kValueElement[i] = (*meshElements)[i]->nodes()[0]->elements().numberOfItems() + (*meshElements)[i]->nodes()[1]->elements().numberOfItems() + (*meshElements)[i]->nodes()[2]->elements().numberOfItems() - 3 + 1; } for(i = 0; i < numNodes; i++) { for(j = 0; j < (*nodes)[i]->elements().numberOfItems(); j++) kValueNode[i] = max(kValueNode[i], kValueElement[(*nodes)[i]->elements()[j]->id()-1]); } //Build a kd-tree for the nodes ANNpointArray dataPts; ANNpoint queryPt; ANNidxArray nnIdx; ANNdistArray dists; ANNkd_tree* kdTree; queryPt = annAllocPt(3); dataPts = annAllocPts(numNodes, 3); nnIdx = new ANNidx[numNodes]; dists = new ANNdist[numNodes]; for(i = 0; i < numNodes; i++) { dataPts[i][0] = (*nodes)[i]->coordinate().x(); dataPts[i][1] = (*nodes)[i]->coordinate().y(); dataPts[i][2] = (*nodes)[i]->coordinate().z(); } kdTree = new ANNkd_tree(dataPts, numNodes, 3); for(i = 0; i < numNodes; i++) { //Do k-nearest neighbor search and insert triangles into neighbors queryPt[0] = (*nodes)[i]->coordinate().x(); queryPt[1] = (*nodes)[i]->coordinate().y(); queryPt[2] = (*nodes)[i]->coordinate().z(); kdTree->annkPriSearch(queryPt, kValueNode[i], nnIdx, dists); g_ElementContainer contToCheck; g_PtrAdapter<g_Element *> adapt(contToCheck); for(j = 0; j < kValueNode[i]; j++) { contToCheck.append((*nodes)[nnIdx[j]]->elements()); } adapt.removeDuplicates(); int contNum = contToCheck.numberOfItems(); //Find nearest neighbor int numElemNeighbors = (*nodes)[i]->elements().numberOfItems(); for(j = 0; j < numElemNeighbors; j++) { int id1 = (*nodes)[i]->elements()[j]->id()-1; #pragma omp parallel for private(k, distance) for(k = 0; k < contNum; k++) { int id2 = contToCheck[k]->id()-1; if(id2 <= id1) continue; if(((*meshElements)[id1]->nodes()[0] == (*meshElements)[id2]->nodes()[0]) || ((*meshElements)[id1]->nodes()[0] == (*meshElements)[id2]->nodes()[1]) || ((*meshElements)[id1]->nodes()[0] == (*meshElements)[id2]->nodes()[2]) || ((*meshElements)[id1]->nodes()[1] == (*meshElements)[id2]->nodes()[0]) || ((*meshElements)[id1]->nodes()[1] == (*meshElements)[id2]->nodes()[1]) || ((*meshElements)[id1]->nodes()[1] == (*meshElements)[id2]->nodes()[2]) || ((*meshElements)[id1]->nodes()[2] == (*meshElements)[id2]->nodes()[0]) || ((*meshElements)[id1]->nodes()[2] == (*meshElements)[id2]->nodes()[1]) || ((*meshElements)[id1]->nodes()[2] == (*meshElements)[id2]->nodes()[2])) continue; distance = minimumDistance((*(*meshElements)[id1]), (*(*meshElements)[id2])); #pragma omp critical if((distNN[id1] == -1) || (distance < distNN[id1])) { distNN[id1] = distance; nearestNeighbor[id1] = id2; } #pragma omp critical if((distNN[id2] == -1) || (distance < distNN[id2])) { distNN[id2] = distance; nearestNeighbor[id2] = id1; } } } } //Delete kd-tree delete [] kValueElement; delete [] kValueNode; delete [] nnIdx; delete [] dists; annDeallocPt(queryPt); annDeallocPts(dataPts); // delete kdTree; annClose(); #if MEASURE_TIME cout<<"Time to execute MinimumDistance::updateNN() "<<(int)time(0)-t<<" s"<<endl; #endif } } double MinimumDistance::evaluateTrianglesOneNN() { if(meshElements == NULL) return 0; else { #if MEASURE_TIME int t = (int)time(0); #endif int i, numElems; double stress; numElems = meshElements->numberOfItems(); stress = 0.0; updateNNKd(); for(i = 0; i < numElems; i++) { if(nearestNeighbor[i] == -1) continue; stress += 1.0/max(pow(distNN[i], 2), MD_DEFAULT_EPSILON); } #if MEASURE_TIME cout<<"Time to execute MinimumDistance::evaluateTrianglesOneNN() "<<(int)time(0)-t<<" s"<<endl; #endif return stress; } } void MinimumDistance::gradientTrianglesOneNN(double *& gradient) { if(meshElements == NULL) return; else { #if MEASURE_TIME int t = (int)time(0); #endif int i, numElems, nNodes, index; nNodes = (int) nodes->numberOfItems(); numElems = meshElements->numberOfItems(); #pragma omp parallel for private(i) for(i = 0; i < nNodes*3; i++) gradient[i] = 0.0; for(i = 0; i < numElems; i++) { if(nearestNeighbor[i] == -1) continue; minimumDistance((*(*meshElements)[i]), (*(*meshElements)[nearestNeighbor[i]]), &index); switch(index) { case 0: addSegmentGrad((*meshElements)[i]->nodes()[0], (*meshElements)[i]->nodes()[1], (*meshElements)[nearestNeighbor[i]]->nodes()[0], (*meshElements)[nearestNeighbor[i]]->nodes()[1], gradient); break; case 1: addSegmentGrad((*meshElements)[i]->nodes()[0], (*meshElements)[i]->nodes()[1], (*meshElements)[nearestNeighbor[i]]->nodes()[1], (*meshElements)[nearestNeighbor[i]]->nodes()[2], gradient); break; case 2: addSegmentGrad((*meshElements)[i]->nodes()[0], (*meshElements)[i]->nodes()[1], (*meshElements)[nearestNeighbor[i]]->nodes()[2], (*meshElements)[nearestNeighbor[i]]->nodes()[0], gradient); break; case 3: addSegmentGrad((*meshElements)[i]->nodes()[1], (*meshElements)[i]->nodes()[2], (*meshElements)[nearestNeighbor[i]]->nodes()[0], (*meshElements)[nearestNeighbor[i]]->nodes()[1], gradient); break; case 4: addSegmentGrad((*meshElements)[i]->nodes()[1], (*meshElements)[i]->nodes()[2], (*meshElements)[nearestNeighbor[i]]->nodes()[1], (*meshElements)[nearestNeighbor[i]]->nodes()[2], gradient); break; case 5: addSegmentGrad((*meshElements)[i]->nodes()[1], (*meshElements)[i]->nodes()[2], (*meshElements)[nearestNeighbor[i]]->nodes()[2], (*meshElements)[nearestNeighbor[i]]->nodes()[0], gradient); break; case 6: addSegmentGrad((*meshElements)[i]->nodes()[2], (*meshElements)[i]->nodes()[0], (*meshElements)[nearestNeighbor[i]]->nodes()[0], (*meshElements)[nearestNeighbor[i]]->nodes()[1], gradient); break; case 7: addSegmentGrad((*meshElements)[i]->nodes()[2], (*meshElements)[i]->nodes()[0], (*meshElements)[nearestNeighbor[i]]->nodes()[1], (*meshElements)[nearestNeighbor[i]]->nodes()[2], gradient); break; case 8: addSegmentGrad((*meshElements)[i]->nodes()[2], (*meshElements)[i]->nodes()[0], (*meshElements)[nearestNeighbor[i]]->nodes()[2], (*meshElements)[nearestNeighbor[i]]->nodes()[0], gradient); break; case 9: addPointPlaneGrad((*meshElements)[i], (*meshElements)[nearestNeighbor[i]]->nodes()[0], gradient); break; case 10: addPointPlaneGrad((*meshElements)[i], (*meshElements)[nearestNeighbor[i]]->nodes()[1], gradient); break; case 11: addPointPlaneGrad((*meshElements)[i], (*meshElements)[nearestNeighbor[i]]->nodes()[2], gradient); break; case 12: addPointPlaneGrad((*meshElements)[nearestNeighbor[i]], (*meshElements)[i]->nodes()[0], gradient); break; case 13: addPointPlaneGrad((*meshElements)[nearestNeighbor[i]], (*meshElements)[i]->nodes()[1], gradient); break; case 14: addPointPlaneGrad((*meshElements)[nearestNeighbor[i]], (*meshElements)[i]->nodes()[2], gradient); break; } } #if MEASURE_TIME cout<<"Time to execute MinimumDistance::gradientTrianglesOneNN(double *& gradient) "<<(int)time(0)-t<<" s"<<endl; #endif } } void MinimumDistance::updateNNKd(int id) { updateNNKd(); } double MinimumDistance::evaluateTrianglesOneNN(int id) { if(meshElements == NULL) return 0; else { #if MEASURE_TIME int t = (int)time(0); #endif int i, numElems; double stress; numElems = (*nodes)[id]->elements().numberOfItems(); stress = 0.0; updateNNKd(); for(i = 0; i < numElems; i++) { if(nearestNeighbor[(*nodes)[id]->elements()[i]->id()-1] == -1) continue; stress += 1.0/max(pow(distNN[(*nodes)[id]->elements()[i]->id()-1], 2), MD_DEFAULT_EPSILON); } #if MEASURE_TIME cout<<"Time to execute MinimumDistance::evaluateTrianglesOneNN() "<<(int)time(0)-t<<" s"<<endl; #endif return stress; } } void MinimumDistance::gradientTrianglesOneNN(int id, double *& gradient) { if(meshElements == NULL) return; else { int i, index, localIdx, helpIdx; gradient[0] = 0.0; gradient[1] = 0.0; gradient[2] = 0.0; g_Element * nearestEl; g_ElementContainer localElems = (*nodes)[id]->elements(); for(i = 0; i < (int)localElems.numberOfItems(); i++) { if(localElems[i]->nodes()[0] == (*nodes)[id]) localIdx = 0; else if(localElems[i]->nodes()[1] == (*nodes)[id]) localIdx = 1; else localIdx = 2; nearestEl = (*meshElements)[nearestNeighbor[localElems[i]->id()-1]]; minimumDistance(*(localElems[i]), *nearestEl, &index); switch(index) { case 0: if(localIdx != 2) { if(localIdx == 0) helpIdx = 2; if(localIdx == 1) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[0], nearestEl->nodes()[1], localElems[i]->nodes()[0], localElems[i]->nodes()[1], gradient, helpIdx); } break; case 1: if(localIdx != 0) { if(localIdx == 1) helpIdx = 2; if(localIdx == 2) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[0], nearestEl->nodes()[1], localElems[i]->nodes()[1], localElems[i]->nodes()[2], gradient, helpIdx); } break; case 2: if(localIdx != 1) { if(localIdx == 2) helpIdx = 2; if(localIdx == 0) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[0], nearestEl->nodes()[1], localElems[i]->nodes()[2], localElems[i]->nodes()[0], gradient, helpIdx); } break; case 3: if(localIdx != 2) { if(localIdx == 0) helpIdx = 2; if(localIdx == 1) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[1], nearestEl->nodes()[2], localElems[i]->nodes()[0], localElems[i]->nodes()[1], gradient, helpIdx); } break; case 4: if(localIdx != 0) { if(localIdx == 1) helpIdx = 2; if(localIdx == 2) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[1], nearestEl->nodes()[2], localElems[i]->nodes()[1], localElems[i]->nodes()[2], gradient, helpIdx); } break; case 5: if(localIdx != 1) { if(localIdx == 2) helpIdx = 2; if(localIdx == 0) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[1], nearestEl->nodes()[2], localElems[i]->nodes()[2], localElems[i]->nodes()[0], gradient, helpIdx); } break; case 6: if(localIdx != 2) { if(localIdx == 0) helpIdx = 2; if(localIdx == 1) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[2], nearestEl->nodes()[0], localElems[i]->nodes()[0], localElems[i]->nodes()[1], gradient, helpIdx); } break; case 7: if(localIdx != 0) { if(localIdx == 1) helpIdx = 2; if(localIdx == 2) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[2], nearestEl->nodes()[0], localElems[i]->nodes()[1], localElems[i]->nodes()[2], gradient, helpIdx); } break; case 8: if(localIdx != 1) { if(localIdx == 2) helpIdx = 2; if(localIdx == 0) helpIdx = 3; addSegmentGrad(nearestEl->nodes()[2], nearestEl->nodes()[0], localElems[i]->nodes()[2], localElems[i]->nodes()[0], gradient, helpIdx); } break; case 9: if(localIdx == 0) addPointPlaneGrad(nearestEl, localElems[i]->nodes()[0], gradient, 0); break; case 10: if(localIdx == 1) addPointPlaneGrad(nearestEl, localElems[i]->nodes()[1], gradient, 0); break; case 11: if(localIdx == 2) addPointPlaneGrad(nearestEl, localElems[i]->nodes()[2], gradient, 0); break; case 12: addPointPlaneGrad(localElems[i], nearestEl->nodes()[0], gradient, localIdx+1); break; case 13: addPointPlaneGrad(localElems[i], nearestEl->nodes()[1], gradient, localIdx+1); break; case 14: addPointPlaneGrad(localElems[i], nearestEl->nodes()[2], gradient, localIdx+1); break; } } } }
#ifndef CMAKE_IS_FUN # error Expect CMAKE_IS_FUN definition #endif #if CMAKE_IS != Fun # error Expect CMAKE_IS=Fun definition #endif template <bool test> struct CMakeStaticAssert; template <> struct CMakeStaticAssert<true> { }; static const char fun_string[] = CMAKE_IS_; #ifndef NO_SPACES_IN_DEFINE_VALUES static const char very_fun_string[] = CMAKE_IS_REALLY; #endif enum { StringLiteralTest1 = sizeof(CMakeStaticAssert<sizeof(CMAKE_IS_) == sizeof("Fun")>), #ifndef NO_SPACES_IN_DEFINE_VALUES StringLiteralTest2 = sizeof(CMakeStaticAssert<sizeof(CMAKE_IS_REALLY) == sizeof("Very Fun")>), #endif #ifdef TEST_GENERATOR_EXPRESSIONS StringLiteralTest3 = sizeof(CMakeStaticAssert<sizeof(LETTER_LIST1) == sizeof("A,B,C,D")>), StringLiteralTest4 = sizeof(CMakeStaticAssert<sizeof(LETTER_LIST2) == sizeof("A,,B,,C,,D")>), StringLiteralTest5 = sizeof(CMakeStaticAssert<sizeof(LETTER_LIST3) == sizeof("A,-B,-C,-D")>), StringLiteralTest6 = sizeof(CMakeStaticAssert<sizeof(LETTER_LIST4) == sizeof("A-,-B-,-C-,-D")>), StringLiteralTest7 = sizeof(CMakeStaticAssert<sizeof(LETTER_LIST5) == sizeof("A-,B-,C-,D")>) #endif }; #ifdef TEST_GENERATOR_EXPRESSIONS # ifndef CMAKE_IS_DECLARATIVE # error Expect declarative definition # endif # ifdef GE_NOT_DEFINED # error Expect not defined generator expression # endif # ifndef ARGUMENT # error Expected define expanded from list # endif # ifndef LIST # error Expected define expanded from list # endif # ifndef PREFIX_DEF1 # error Expect PREFIX_DEF1 # endif # ifndef PREFIX_DEF2 # error Expect PREFIX_DEF2 # endif # ifndef LINK_CXX_DEFINE # error Expected LINK_CXX_DEFINE # endif # ifndef LINK_LANGUAGE_IS_CXX # error Expected LINK_LANGUAGE_IS_CXX # endif # ifdef LINK_C_DEFINE # error Unexpected LINK_C_DEFINE # endif # ifdef LINK_LANGUAGE_IS_C # error Unexpected LINK_LANGUAGE_IS_C # endif // TEST_GENERATOR_EXPRESSIONS #endif #ifndef BUILD_IS_DEBUG # error "BUILD_IS_DEBUG not defined!" #endif #ifndef BUILD_IS_NOT_DEBUG # error "BUILD_IS_NOT_DEBUG not defined!" #endif // Check per-config definitions. #ifdef TEST_CONFIG_DEBUG # if !BUILD_IS_DEBUG # error "BUILD_IS_DEBUG false with TEST_CONFIG_DEBUG!" # endif # if BUILD_IS_NOT_DEBUG # error "BUILD_IS_NOT_DEBUG true with TEST_CONFIG_DEBUG!" # endif #else # if BUILD_IS_DEBUG # error "BUILD_IS_DEBUG true without TEST_CONFIG_DEBUG!" # endif # if !BUILD_IS_NOT_DEBUG # error "BUILD_IS_NOT_DEBUG false without TEST_CONFIG_DEBUG!" # endif #endif int main(int argc, char** argv) { return 0; }
#include "compiler/token_ids.hpp" namespace perseus { namespace detail { namespace token_id { std::ostream& operator<<( std::ostream& os, token_id token ) { switch( token ) { case whitespace: return os << "whitespace"; case comment: return os << "comment"; case string: return os << "string literal"; case decimal_integer: return os << "decimal integer literal"; case hexadecimal_integer: return os << "hexadecimal integer literal"; case binary_integer: return os << "binary integer literal"; case identifier: return os << "identifier"; case operator_identifier: return os << "operator identifier"; case if_: return os << "\"if\""; case else_: return os << "\"else\""; case while_: return os << "\"while\""; case return_: return os << "\"return\""; case function_: return os << "\"function\""; case true_: return os << "\"true\""; case false_: return os << "\"false\""; case let_: return os << "\"let\""; case mutable_: return os << "\"mutable\""; case impure_: return os << "\"impure\""; case colon: return os << "\":\""; case semicolon: return os << "\";\""; case dot: return os << "\".\""; case comma: return os << "\",\""; case equals: return os << "\"=\""; case backtick: return os << "\"`\""; case arrow_right: return os << "\"->\""; case paren_open: return os << "\"(\""; case paren_close: return os << "\")\""; case brace_open: return os << "\"{\""; case brace_close: return os << "\"}\""; case square_bracket_open: return os << "\"[\""; case square_bracket_close: return os << "\"]\""; case any: return os << "any"; default: return os << "token_id(0x" << std::hex << static_cast< unsigned int >( token ) << std::dec << ')'; } } } } }
#include "lilypadPins.h" #include "Music.h" #include "Light.h" #define GAME_START 1 #define MINI_WIN 2 #define MINI_LOSE 3 #define GAME_LOOP 4 #define PAUSE 5 #define WIN 6 #define LOSE 7 static const int maxTurns = 8; static const int reqForWin = 6; static const int numWhiteLights = 3; static const unsigned long gameSpeeds[8] = {300, 275, 250, 230, 220, 210, 200, 180}; float delayOffset = 0.75; Light whiteLights[3] = {Light(WHITE_1), Light(WHITE_2), Light(WHITE_3)}; Light winLight = Light(WHITE_4); Light rgbLight = Light(0); // Sky Blue, Magenta, Green, Red int colors[4][3] = {{13, 155, 200}, {224, 24, 184}, {12, 252, 0}, {255, 0, 0}}; #define SKY_BLUE 0 #define PINK 1 #define GREEN 2 #define RED 3 int currColor=-1; // winning static const int miniWinTime = 2000; static const int miniLoseTime = 2000; //Music & SFX Music music(BUZZER_PIN); // Vars to reinitialize every game int mainGameState = GAME_START; int currTurn = 0; int numWins = 0; unsigned long startTime; unsigned long lightSpeed; void setup() { Serial.begin(9600); // open the serial port at 9600 bps for Debug Output: rgbLight.setRGBPins(RGB_LED_RED, RGB_LED_GREEN, RGB_LED_BLUE); randomSeed(analogRead(0)); // initialize the pushbutton pin as an input: pinMode(BUTTON, INPUT_PULLUP); initGameLoop(); } void initGameLoop() { mainGameState = PAUSE; numWins = 0; currTurn = 0; startTime; lightSpeed=gameSpeeds[0]; music.init(); continueGameLoop(); } void continueGameLoop() { mainGameState = PAUSE; unsigned long delayx = gameSpeeds[currTurn]*delayOffset; startLightsArray(lightSpeed, delayx); Serial.write("light speed: "); Serial.println(lightSpeed); Serial.write("delayed by: "); Serial.println(delayx); Serial.write(" based on delayOffset being: "); Serial.println(delayOffset); setRandomRGB(); mainGameState = GAME_LOOP; } void loop() { switch(mainGameState) { case GAME_LOOP: { // if user is pressing the button if(digitalRead(BUTTON) == LOW) { // pressing button // if green, you win if(currColor==GREEN) { Serial.write("mini-win\n"); miniWin(); } else // else color is not green so you lose { Serial.write("mini-loss\n"); miniLose(); } return; } rgbLight.updateLED(); // loop thru lights & reset them if they're off int whiteLightsOff=0; for(int i=0; i<numWhiteLights; i++) { whiteLights[i].updateLED(); if(!whiteLights[i].isActive()){ whiteLightsOff++; } if(whiteLightsOff==numWhiteLights) { //restart lights startLightsArray(lightSpeed, lightSpeed*delayOffset); setRandomRGB(); return; } } break; } case MINI_WIN: { // if we're done celebrating if(!rgbLight.isActive()) { // decide if the game is over currTurn++; if(currTurn >= maxTurns) { gameComplete(); return; } //reset game at new speed lightSpeed = gameSpeeds[currTurn]; continueGameLoop(); } else { rgbLight.updateLED(); } break; } case MINI_LOSE: { // if we're done losing if(!rgbLight.isActive()) { // decide if the game is over currTurn++; if(currTurn >= maxTurns) { gameComplete(); return; } // reset game at slower speed lightSpeed = gameSpeeds[currTurn]; continueGameLoop(); } else rgbLight.updateLED(); break; } } } void gameComplete() { Serial.write("Game Complete"); // decide if they won or lost if(numWins > reqForWin) { win(); } else // they lost { lose(); } } void startLightsArray(int onTime, int betweenTime) { for(int i=0; i<numWhiteLights; i++) { whiteLights[i].whiteLEDOn(onTime, betweenTime*i); } } void setRandomRGB() { currColor = random(3); rgbLight.rgbLEDOn(colors[currColor][0], colors[currColor][1], colors[currColor][2], lightSpeed*numWhiteLights*(1+delayOffset)-lightSpeed*delayOffset, 0); if(currColor == GREEN) startTime=millis(); rgbLight.updateLED(); } void miniWin() { Serial.write("setting win state/n"); mainGameState = MINI_WIN; numWins++; setLightsOff(); // show green color rgbLight.rgbLEDOn(colors[GREEN][0], colors[GREEN][1], colors[GREEN][2], miniWinTime, 0); music.playUp(); } void win() { // play win music music.playWin(); initGameLoop(); } void lose() { music.playLose(); initGameLoop(); } void setLightsOff() { // turn off white leds for(int i=0; i<numWhiteLights; i++) whiteLights[i].setOff(); } void miniLose() { mainGameState = MINI_LOSE; setLightsOff(); rgbLight.rgbLEDOn(colors[RED][0], colors[RED][1], colors[RED][2], miniLoseTime, 0); // play lose music music.playDown(); } void debugOutputLights() { // dump debug info for(int p=0; p<numWhiteLights; p++) { Serial.write("light # "); Serial.print(p, DEC); Serial.write(" =======\n"); whiteLights[p].debugOutput(); Serial.write("\n"); } }
#include "stdafx.h" #include "Material.h" Material::Material(ComPtr<ID3D11Device> d3dDevice, string matName) { _name = matName; tex = make_shared<Texture>("WashedGravel"); shad = make_shared<Shader>(matName); shad->OnInitRenderer(d3dDevice); /**/ D3D11_INPUT_ELEMENT_DESC inputElementDesc[] { {"POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"TEXTURE", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 48, D3D11_INPUT_PER_VERTEX_DATA, 0} }; vector<byte> vertexShaderCode = Shader::ReadShaderByteCode("InputLayoutVS.cso"); Renderer::ThrowIfFailed( d3dDevice->CreateInputLayout(inputElementDesc, ARRAYSIZE(inputElementDesc), vertexShaderCode.data(), vertexShaderCode.size(), &_inputLayout) ); /**/ CD3D11_SAMPLER_DESC samplerDesc = CD3D11_SAMPLER_DESC(CD3D11_DEFAULT()); samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; d3dDevice->CreateSamplerState(&samplerDesc, &_samplerState); } string Material::GetName() { return _name; } void Material::SetupParams(ComPtr<ID3D11DeviceContext> d3dContext, shared_ptr<ObjectParams> &params) { ////_d3dContext->VSSetConstantBuffers(1, 1, _lightConstantBuffer.GetAddressOf()); d3dContext->PSSetSamplers(0, 1, _samplerState.GetAddressOf()); d3dContext->PSSetShaderResources(0, 1, params->baseColor.GetAddressOf()); d3dContext->PSSetSamplers(1, 1, _samplerState.GetAddressOf()); d3dContext->PSSetShaderResources(1, 1, params->normal.GetAddressOf()); d3dContext->PSSetSamplers(2, 1, _samplerState.GetAddressOf()); d3dContext->PSSetShaderResources(2, 1, params->height.GetAddressOf()); d3dContext->PSSetSamplers(3, 1, _samplerState.GetAddressOf()); d3dContext->PSSetShaderResources(3, 1, params->roughness.GetAddressOf()); } void Material::SetupMaterial(ComPtr<ID3D11DeviceContext> d3dContext) { /**/ d3dContext->IASetInputLayout(_inputLayout.Get()); /**/ shad->OnRender(d3dContext); }
// Copyright (c) 2020 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ORBIT_GL_GRAPH_TRACK_H #define ORBIT_GL_GRAPH_TRACK_H #include <limits> #include "ScopeTimer.h" #include "Track.h" class TimeGraph; class GraphTrack : public Track { public: explicit GraphTrack(TimeGraph* time_graph, std::string name); [[nodiscard]] Type GetType() const override { return kGraphTrack; } void Draw(GlCanvas* canvas, PickingMode /*picking_mode*/) override; [[nodiscard]] float GetHeight() const override; void AddValue(double value, uint64_t time); [[nodiscard]] double GetValueAtTime(uint64_t time, double default_value = 0) const; protected: std::map<uint64_t, double> values_; double min_ = std::numeric_limits<double>::max(); double max_ = std::numeric_limits<double>::lowest(); double value_range_ = 0; double inv_value_range_ = 0; std::string name_; }; #endif
#include "menuscreen.h" #include "utilities/constants.h" using namespace std; void MenuScreen::asciiArt(){ // Looks kinda funky because backslashes are escape characters // so I had to add another backslash where there already was one // CSci = Computer Scientist cout << string(LEFT_MARGIN, ' ') << " _________ _________ .__ " << endl; cout << string(LEFT_MARGIN, ' ') << " \\_ ___ \\ / _____/ ____ |__|" << endl; cout << string(LEFT_MARGIN, ' ') << " / \\ \\/ \\_____ \\_/ ___\\| |" << endl; cout << string(LEFT_MARGIN, ' ') << " \\ \\____/ \\ \\___| |" << endl; cout << string(LEFT_MARGIN, ' ') << " \\______ /_______ /\\___ >__|" << endl; cout << string(LEFT_MARGIN, ' ') << " \\/ \\/ \\/ " << endl; cout << string(LEFT_MARGIN, ' ') << " WELCOME TO THE" << endl; cout << string(LEFT_MARGIN, ' ') << "-~*^ COMPUTER SCIENTIST LIST PROGRAM! ^*~-" << endl << endl; } void MenuScreen::goodBye(){ system("CLS"); cout << string(9, '\n'); cout << string(17, ' ') << TL_CORNER << string(44, H_LINE) << TR_CORNER << endl; cout << string(17, ' ') << V_LINE << " ____ _ _ _ " << V_LINE << endl; cout << string(17, ' ') << V_LINE << " / ___| ___ ___ __| | |__ _ _ ___| |" << V_LINE << endl; cout << string(17, ' ') << V_LINE << "| | _ / _ \\ / _ \\ / _` | '_ \\| | | |/ _ \\ |" << V_LINE << endl; cout << string(17, ' ') << V_LINE << "| |_| | (_) | (_) | (_| | |_) | |_| | __/_|" << V_LINE << endl; cout << string(17, ' ') << V_LINE << " \\____|\\___/ \\___/ \\__,_|_.__/ \\__, |\\___(_)" << V_LINE << endl; cout << string(17, ' ') << V_LINE << " |___/ " << V_LINE << endl; cout << string(17, ' ') << BL_CORNER << string(44, H_LINE) << BR_CORNER << endl; cout << string(9, '\n'); } void MenuScreen::startingMessage(){ system("CLS"); asciiArt(); // Testing a new look for the menu windows :D cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ START MENU ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Print list " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Add to list " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Search/modify list " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (4) Link computer and pioneer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (5) Delete " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Quit " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::printListMenu(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ PRINT LIST ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Print Pioneers " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Print Computers " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Print Relations " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::sortPioneersMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SORT BY ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Sort by name " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Sort by year of birth " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Sort by year of death " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::filterByPioneerMessage(char& f, char& m, char& d, char& a){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ FILTER MENU ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Female [" << f << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Male [" << m << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Dead [" << d << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (4) Alive [" << a << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; if(f == ' ' && m == ' ' && d == ' ' && a == ' '){ cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) No filter " << V_LINE << endl; } else{ cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Finish filtering " << V_LINE << endl; } cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose filter options: "; } void MenuScreen::filterByComputerMessage(char& b, char& n, char& m, char& e, char& t){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ FILTER MENU ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Was built [" << b << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Was not built [" << n << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Mechanical [" << m << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (4) Electronic [" << e << "] " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (5) Transistor [" << t << "] " << V_LINE << endl; if(b == ' ' && n == ' ' && m == ' ' && e == ' ' && t == ' '){ cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) No filter " << V_LINE << endl; } else{ cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Finish filtering " << V_LINE << endl; } cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose filter options: "; } void MenuScreen::sortDirectionMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SORTING DIRECTION ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Sort ascending " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Sort descending " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::sortComputersMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SORT BY ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Sort by name " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Sort by type " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Sort by year of build " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::searchMenu(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SEARCH & MODIFY MENU ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Search Pioneer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Search Computer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Search Relation " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::searchPioneerMenu(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SEARCH/MODIFY PIONEERS ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Search by name " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Search by year of birth " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Search by year of death " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (4) Search by description " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::searchComputerMenu(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SEARCH/MODIFY COMPUTERS ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Search by name " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Search by year of build " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (3) Search by description " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::searchRelationMenu(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ SEARCH/MODIFY RELATIONS ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Find Computer/s related " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " to a Pioneer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Find Pioneer/s related " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " to a Computer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::addByMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ ADD MENU ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Pioneer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Computer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::deleteMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ DELETE MENU ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Delete Pioneer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Delete Computer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::deletePioMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ DELETE PIONEERS ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Delete Single Pioneer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Delete All Pioneers " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; } void MenuScreen::deleteCompMessage(){ system("CLS"); cout << string(9, '\n'); cout << string(LEFT_MARGIN, ' ') << TL_CORNER << string(37, H_LINE) << TR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " *~ DELETE COMPUTERS ~* " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << L_JOIN << string(37, H_LINE) << R_JOIN << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (1) Delete Single Computer " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (2) Delete All Computers " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << V_LINE << " (0) Back to Main Menu " << V_LINE << endl; cout << string(LEFT_MARGIN, ' ') << BL_CORNER << string(37, H_LINE) << BR_CORNER << endl; cout << string(LEFT_MARGIN, ' ') << " Choose menu item: "; }
#include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include <iostream> #include <stdlib.h> using namespace std; using namespace cv; /** Function Headers */ void on_low_r_thresh_trackbar(int, void *); void on_high_r_thresh_trackbar(int, void *); void on_low_g_thresh_trackbar(int, void *); void on_high_g_thresh_trackbar(int, void *); void on_low_b_thresh_trackbar(int, void *); void on_high_b_thresh_trackbar(int, void *); /** Global Variables */ int low_r=30, low_g=30, low_b=30; int high_r=100, high_g=100, high_b=100; /** @function main */ int main() { //! [mat] Mat frame, frame_threshold; //! [mat] //! [cap] VideoCapture cap(0); //! [cap] //! [window] namedWindow("Video Capture", WINDOW_NORMAL); namedWindow("Object Detection", WINDOW_NORMAL); //! [window] //! [trackbar] //-- Trackbars to set thresholds for RGB values createTrackbar("Low R","Object Detection", &low_r, 255, on_low_r_thresh_trackbar); createTrackbar("High R","Object Detection", &high_r, 255, on_high_r_thresh_trackbar); createTrackbar("Low G","Object Detection", &low_g, 255, on_low_g_thresh_trackbar); createTrackbar("High G","Object Detection", &high_g, 255, on_high_g_thresh_trackbar); createTrackbar("Low B","Object Detection", &low_b, 255, on_low_b_thresh_trackbar); createTrackbar("High B","Object Detection", &high_b, 255, on_high_b_thresh_trackbar); //! [trackbar] while((char)waitKey(1)!='q'){ //! [while] cap>>frame; if(frame.empty()) break; //-- Detect the object based on RGB Range Values inRange(frame,Scalar(low_b,low_g,low_r), Scalar(high_b,high_g,high_r),frame_threshold); //! [while] //! [show] //-- Show the frames imshow("Video Capture",frame); imshow("Object Detection",frame_threshold); //! [show] } return 0; } //! [low] /** @function on_low_r_thresh_trackbar */ void on_low_r_thresh_trackbar(int, void *) { low_r = min(high_r-1, low_r); setTrackbarPos("Low R","Object Detection", low_r); } //! [low] //! [high] /** @function on_high_r_thresh_trackbar */ void on_high_r_thresh_trackbar(int, void *) { high_r = max(high_r, low_r+1); setTrackbarPos("High R", "Object Detection", high_r); } //![high] /** @function on_low_g_thresh_trackbar */ void on_low_g_thresh_trackbar(int, void *) { low_g = min(high_g-1, low_g); setTrackbarPos("Low G","Object Detection", low_g); } /** @function on_high_g_thresh_trackbar */ void on_high_g_thresh_trackbar(int, void *) { high_g = max(high_g, low_g+1); setTrackbarPos("High G", "Object Detection", high_g); } /** @function on_low_b_thresh_trackbar */ void on_low_b_thresh_trackbar(int, void *) { low_b= min(high_b-1, low_b); setTrackbarPos("Low B","Object Detection", low_b); } /** @function on_high_b_thresh_trackbar */ void on_high_b_thresh_trackbar(int, void *) { high_b = max(high_b, low_b+1); setTrackbarPos("High B", "Object Detection", high_b); }
#include "../inc.h" #include <math.h> #include <initializer_list> #ifndef TEMPLATE_MATRIX #define TEMPLATE_MATRIX namespace Z_3D_LIB_FOR_EGE { template < int l, int m, typename T > class _matrix; template < typename T > class _matrix< 0, 0, T >; template < int l, int m, typename T > class _matrix { typedef _matrix< l, m, T > _Tself; protected : T v[l][m]; public : _Tself() { for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) v[i][j] = T(0); } _Tself(const T src[l][m]) { for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) v[i][j] = src[i][j]; } _Tself(const _Tself& src) { for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) v[i][j] = src[i][j]; } _Tself(const std::initializer_list< std::initializer_list< T > >& src) { int i = 0, j = 0; for (std::initializer_list< T > _src : src) { j = 0; for (T _s : _src) { v[i][j] = _s; j++; } i++; } } T* operator [] (const int opt) const { return const_cast< T* >(v[opt]); } _Tself& operator = (const _Tself& opt) { for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) v[i][j] = opt[i][j]; return *this; } bool operator == (const _Tself& opt) const { for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) if (v[i][j] != opt[i][j]) return false; return true; } bool operator != (const _Tself& opt) const { return !((*this) == opt); } _Tself operator + (const _Tself& opt) const { _Tself _t; for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) _t[i][j] = v[i][j] + opt[i][j]; return _t; } _Tself operator - (const _Tself& opt) const { _Tself _t(v); return opt * -1 + *this; } _Tself operator * (T opt) const { _Tself _t; for (int i = 0; i < l; i++) for (int j = 0; j < m; j++) _t[i][j] = opt * v[i][j]; return _t; } template < int n > _matrix < l, n, T > operator * (const _matrix < m, n, T >& opt) const { _matrix < l, n, T > _t; for (int i = 0; i < l; i++) for (int j = 0; j < n; j++) for (int k = 0; k < m; k++) _t[i][j] += v[i][k] * opt[k][j]; return _t; } _Tself operator / (T opt) const { _Tself _t(v); return _t * (T(1) / opt); } template < int o, int p > static _matrix < p, o, T > trans (const _matrix < o, p, T >& opt) { T _t[p][o]; for (int i = 0; i < o; i++) for (int j = 0; j < p; j++) _t[j][i] = opt[i][j]; return _matrix < p, o, T >(_t); } template <> static _matrix < 0, 0, T > trans (const _matrix < 0, 0, T >& opt) { throw ""; } }; template < typename T > class _matrix < 0, 0, T > { }; } #endif