blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
4fe4f7066deb6a49e0683e1a9cde1d209c1b8bff
eeb949f6fe65b1177ac7426a937ef96b0d4d1e22
/srcanamdw/appdep/src/appdep_getters.cpp
96a81531c64e695a0988201fe19578e167d9550e
[]
no_license
SymbianSource/oss.FCL.sftools.ana.staticanamdw
bd2d6b6208f473aa03e2a23c1f7d8679c235c11d
f2f134dfc41d34af79e682c1d78a6c45a14206b0
refs/heads/master
2020-12-24T12:28:54.126034
2010-02-18T06:59:02
2010-02-18T06:59:02
72,998,870
0
0
null
null
null
null
UTF-8
C++
false
false
23,583
cpp
/* * Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: Utility functions for getting data via 3rd party tools * */ #include "appdep.hpp" // ---------------------------------------------------------------------------------------------------------- // Note that in C/C++ code \ has been replaced with \\ and " with \". // ---------------------------------------------------------------------------------------------------------- void GetImportTableWithPetran(const string& petran_location, binary_info& b_info) { vector<dependency> deps; vector<string> tempVector; // init defaults b_info.binary_format = UNKNOWN; b_info.uid1 = UNKNOWN; b_info.uid2 = UNKNOWN; b_info.uid3 = UNKNOWN; b_info.secureid = NOT_VALID; b_info.vendorid = NOT_VALID; b_info.capabilities = 0; b_info.min_heap_size = 0; b_info.max_heap_size = 0; b_info.stack_size = 0; // execute petran string cmd; if (_cl_use_gcce || _cl_use_rvct) cmd = petran_location + " -dump hi \"" + b_info.directory + b_info.filename + "\" " + CERR_TO_NULL; else cmd = petran_location + " \"" + b_info.directory + b_info.filename + "\" " + CERR_TO_NULL; //cerr << cmd << endl; ExecuteCommand(cmd, tempVector); // get binary format, assuming it's the first line which begings with EPOC for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^(EPOC.+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); TrimAll(ms1); b_info.binary_format = ms1; break; } } // get uids for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Uids:\\s+(\\S+)\\s+(\\S+)\\s+(\\S+).+"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); string ms2(matches[2].first, matches[2].second); string ms3(matches[3].first, matches[3].second); b_info.uid1 = "0x"+ms1; b_info.uid2 = "0x"+ms2; b_info.uid3 = "0x"+ms3; break; } } // get secure id for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Secure\\sID:\\s+(\\S+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); b_info.secureid = "0x"+ms1; break; } } // get vendor id for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Vendor\\sID:\\s+(\\S+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); b_info.vendorid = "0x"+ms1; break; } } // get capabilities for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Capabilities:\\s+\\S+\\s+(\\S+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); b_info.capabilities = Str2Int("0x"+ms1); break; } } // get min heap size for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Min\\sHeap\\sSize:\\s+(\\S+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); b_info.min_heap_size = Str2Int("0x"+ms1); break; } } // get max heap size for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Max\\sHeap\\sSize:\\s+(\\S+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); b_info.max_heap_size = Str2Int("0x"+ms1); break; } } // get stack size for (unsigned int j=0; j<tempVector.size() && j<100; j++) { boost::regex re("^Stack\\sSize:\\s+(\\S+)"); boost::cmatch matches; if (boost::regex_match(tempVector.at(j).c_str(), matches, re)) { string ms1(matches[1].first, matches[1].second); b_info.stack_size = Str2Int("0x"+ms1); break; } } // finally get the dependency information for (unsigned int j=0; j<tempVector.size(); j++) { // first find where the import table begins, example: // Offset of import address table (relative to code section): 00005660 if (tempVector.at(j).find("Offset of import", 0) != string::npos) { // continue looping while (j<tempVector.size()-1) { j++; // now find denpendency entry, examples: // 68 imports from euser{000a0000}[100039e5].dll // 1 imports from COMMONENGINE[100058fe].DLL // 3 imports from drtrvct2_2{000a0000}.dll // 27 imports from libdbus-utils{000a0000}[20010154].dll boost::regex re1("^(\\d+)\\simports\\sfrom\\s([\\w\\-]+)\\S*(\\.\\w+).*"); boost::cmatch matches1; if (boost::regex_match(tempVector.at(j).c_str(), matches1, re1)) { // match found string ms1(matches1[1].first, matches1[1].second); // number in the beginning string ms2(matches1[2].first, matches1[2].second); // first part of filename string ms3(matches1[3].first, matches1[3].second); // extension of filename unsigned int number_of_imports = Str2Int(ms1); vector<import> imps; // imports string filename = ms2+ms3; // get position of the filename in import libaries int lib_pos = -1; for (unsigned int x=0; x<_all_import_library_infos.size(); x++) { if (StringICmpFileNamesWithoutExtension(_all_import_library_infos.at(x).filename, filename) == 0) { lib_pos = x; break; } } // read ordinal numbers for (unsigned int k=0; k<number_of_imports; k++) { j++; import imp; imp.is_vtable = false; imp.vtable_offset = 0; string ordinal_data = tempVector.at(j); TrimAll(ordinal_data); // check if it's virtual data string::size_type pos = ordinal_data.find(" offset by", 0); if (pos == string::npos) { // regular entry, just get the ordinal number imp.funcpos = Str2Int(ordinal_data); imp.is_vtable = false; imp.vtable_offset = 0; } else { // this is a virtual table entry imp.funcpos = Str2Int(ordinal_data.substr(0, pos)); imp.is_vtable = true; imp.vtable_offset = Str2Int(ordinal_data.substr(pos+11, ordinal_data.length()-pos-1)); } // get the function name if (lib_pos >= 0) { if (imp.funcpos-1 < _all_import_library_infos.at(lib_pos).symbol_table.size()) imp.funcname = _all_import_library_infos.at(lib_pos).symbol_table.at(imp.funcpos-1); else imp.funcname = "BC break: This ordinal position is not in the import library!"; } else { imp.funcname = "Import library not found!"; } // Checking for possible duplicate imported function ordinals. import compare[] = { imp }; vector<import>::iterator it = find_first_of(imps.begin(), imps.end(), compare, compare+1, ImportFunctionsHasSameOrdinal); if(it == imps.end()) { // No duplicate detected. Appending ordinal data to the array. imps.push_back(imp); } } // append to the vector dependency dep; dep.filename = filename; dep.imports = imps; deps.push_back( dep ); } } break; //for (int j=0; j<tempVector.size(); j++) } } // for (int j=0; j<tempVector.size(); j++) // store the dependencies array b_info.dependencies = deps; } // ---------------------------------------------------------------------------------------------------------- bool ImportFunctionsHasSameOrdinal(import imp1, import imp2) { return (imp1.funcpos == imp2.funcpos); } // ---------------------------------------------------------------------------------------------------------- void GetSymbolTableWithNM(const string& nm_location, const string& lib_directory, const string& lib_name, vector<string>& symbol_table) { symbol_table.clear(); vector<string> tempVector; vector<ordinal> ordinals; // execute nm string cmd = nm_location + " --demangle \"" + lib_directory + lib_name + "\""; ExecuteCommand(cmd, tempVector); // parse the results of the command for (unsigned int j=0; j<tempVector.size(); j++) { // first check if we have found the beginning of a block boost::cmatch matches1; boost::cmatch matches2; boost::cmatch matches3; bool match1 = false; bool match2 = false; bool match3 = false; // Symbian OS 6.1 LIB file, example: ds00001.o: boost::regex re1("^ds(\\d+)\\.o\\:"); match1 = boost::regex_match(tempVector.at(j).c_str(), matches1, re1); if (!match1) { // Symbian OS 7.x-8.x LIB file, example: C:/DOCUME~1/mattlait/LOCALS~1/Temp/1/d1000s_00001.o: boost::regex re2("^\\S*s_(\\d+)\\.o\\:"); match2 = boost::regex_match(tempVector.at(j).c_str(), matches2, re2); if (!match2) { // Symbian OS 9.x LIB file, example: AGENTDIALOG{000a0000}-14.o: boost::regex re3("^\\S*\\{000a0000\\}-(\\d+)\\.o\\:"); match3 = boost::regex_match(tempVector.at(j).c_str(), matches3, re3); } } if (match1 || match2 || match3) { // now get the ordinal number string ordNum; if (match1) { string ms(matches1[1].first, matches1[1].second); ordNum = ms; } else if (match2) { string ms(matches2[1].first, matches2[1].second); ordNum = ms; } else if (match3) { string ms(matches3[1].first, matches3[1].second); ordNum = ms; } // now start looking for the line with the export name // eg: 00000000 T CUserActivityManager::RunL(void) while (j<tempVector.size()-1) { j++; boost::regex re4("^\\d+\\sT\\s(.*)$"); boost::cmatch matches4; if (boost::regex_match(tempVector.at(j).c_str(), matches4, re4)) { // now we have a full entry string ms(matches4[1].first, matches4[1].second); // append to the ordinal list ordinals.push_back(ordinal(Str2Int(ordNum), ms)); break; } } } // (match1 || match2) } // for (int j=0; j<tempVector.size(); j++) // convert the ordinal list into a symbol table ConvertOrdinalListIntoSymbolTable(ordinals, symbol_table, lib_directory+lib_name); } // ---------------------------------------------------------------------------------------------------------- void GetSymbolTableWithReadelf(const string& readelf_location, const string& cfilt_location, const string& lib_directory, const string& lib_name, vector<string>& symbol_table) { symbol_table.clear(); vector<string> tempVector; vector<ordinal> ordinals; // execute readelf // note: 2>NUL is used here to redirect standard error output to NULL since readelf seems to output lots of unwanted warning messages string cmd = readelf_location + " -s -W \"" + lib_directory + lib_name + "\" " + CERR_TO_NULL; ExecuteCommand(cmd, tempVector); // parse the results of the command for (unsigned int j=0; j<tempVector.size(); j++) { boost::cmatch matches1; // example: // 1: 00000000 4 NOTYPE GLOBAL DEFAULT 1 _ZN13CSpdiaControl10DrawShadowER9CWindowGcRK5TSize@@SpdCtrl{000a0000}[10005986].dll boost::regex re1("^\\s*(\\d+)\\:.+GLOBAL.+\\d+\\s+(.*)\\@\\@.*"); if (boost::regex_match(tempVector.at(j).c_str(), matches1, re1)) { // match found string ms1(matches1[1].first, matches1[1].second); string ms2(matches1[2].first, matches1[2].second); // append to the ordinal list ordinals.push_back(ordinal(Str2Int(ms1), ms2)); } } // for (int j=0; j<tempVector.size(); j++) // convert the ordinal list into a symbol table ConvertOrdinalListIntoSymbolTable(ordinals, symbol_table, lib_directory+lib_name); // finally demangle all function names since it's not done in this case automatically DemangleOrdinalsInSymbolTable(cfilt_location, symbol_table); } // ---------------------------------------------------------------------------------------------------------- void GetSymbolTableWithArmar(const string& armar_location, const string& cfilt_location, const string& lib_directory, const string& lib_name, vector<string>& symbol_table) { symbol_table.clear(); vector<string> tempVector; vector<ordinal> ordinals; // execute armar string cmd = armar_location + " --zs \"" + lib_directory + lib_name + "\""; ExecuteCommand(cmd, tempVector); // parse the results of the command for (unsigned int j=0; j<tempVector.size(); j++) { // find the entries, example: // _ZN13TAgnWeeklyRptC1Ev from AGNMODEL{000a0000}-187.o at offset 158366 boost::regex re1("(\\S*)\\s+from\\s.*-(\\d+)\\.o.*"); boost::cmatch matches1; if (boost::regex_match(tempVector.at(j).c_str(), matches1, re1)) { // match found string ms1(matches1[2].first, matches1[2].second); string ms2(matches1[1].first, matches1[1].second); // append to the ordinal list ordinals.push_back(ordinal(Str2Int(ms1), ms2)); } } // for (int j=0; j<tempVector.size(); j++) // convert the ordinal list into a symbol table ConvertOrdinalListIntoSymbolTable(ordinals, symbol_table, lib_directory+lib_name); // finally demangle all function names since it's not done in this case automatically DemangleOrdinalsInSymbolTable(cfilt_location, symbol_table); } // ---------------------------------------------------------------------------------------------------------- void GetSymbolTableWithFromelf(const string& fromelf_location, const string& cfilt_location, const string& lib_directory, const string& lib_name, vector<string>& symbol_table) { symbol_table.clear(); vector<string> tempVector; vector<ordinal> ordinals; // execute fromelf string cmd = fromelf_location + " -s \"" + lib_directory + lib_name + "\""; ExecuteCommand(cmd, tempVector); // parse the results of the command for (unsigned int j=0; j<tempVector.size(); j++) { // first find the start of the symbol table // ** Section #5 '.version' (SHT_GNU_versym) boost::regex re1("^.*(SHT_GNU_versym).*"); boost::cmatch matches1; if (boost::regex_match(tempVector.at(j).c_str(), matches1, re1)) { //int previous_ordinal = 0; while (j<tempVector.size()-1) { j++; // now find the entries, examples: // 7 _ZNK17CPbkContactEngine9FsSessionEv 2 PbkEng{000a0000}[101f4cce].dll // 8 _ZN17CPbkContactEngine19CreateEmptyContactLEv // 2 PbkEng{000a0000}[101f4cce].dll // notice that line can be spread to two lines so make sure we don't accidentally get a wrong line // first parse out any unwanted lines boost::regex re2("^\\s*\\d+\\s+\\S+\\.\\w+$"); boost::cmatch matches2; if (boost::regex_match(tempVector.at(j).c_str(), matches2, re2)) { continue; } // now it should be the wanted line boost::regex re3("^\\s*(\\d+)\\s*(\\S*).*"); boost::cmatch matches3; if (boost::regex_match(tempVector.at(j).c_str(), matches3, re3)) { // match found string ms1(matches3[1].first, matches3[1].second); string ms2(matches3[2].first, matches3[2].second); // append to the ordinal list ordinals.push_back(ordinal(Str2Int(ms1), ms2)); } } //while (j<tempVector.size()) } //if (boost::regex_match(tempVector.at(j).c_str(), matches1, re1)) } // for (int j=0; j<tempVector.size(); j++) // convert the ordinal list into a symbol table ConvertOrdinalListIntoSymbolTable(ordinals, symbol_table, lib_directory+lib_name); // finally demangle all function names since it's not done in this case automatically DemangleOrdinalsInSymbolTable(cfilt_location, symbol_table); } // ---------------------------------------------------------------------------------------------------------- void ConvertOrdinalListIntoSymbolTable(const vector<ordinal>& ordinals, vector<string>& symbol_table, const string& lib_path) { // remove any invalid ordinals from the list vector<ordinal> ordinalVectorCopy; ordinalVectorCopy.reserve(ordinals.size()); for (unsigned int i=0; i<ordinals.size(); i++) { if (ordinals.at(i).funcpos <= 0 && ordinals.at(i).funcpos > 32000) { cerr << "Error: Invalid ordinal " << ordinals.at(i).funcname << " @ " << Int2Str(ordinals.at(i).funcpos) << endl; } else { ordinalVectorCopy.push_back(ordinals.at(i)); } } // sort the ordinal list sort(ordinalVectorCopy.begin(), ordinalVectorCopy.end(), OrdinalCompare); // now check that there are no missing ordinals in the list unsigned int previous_ordnumber = 0; unsigned int current_ordnumber = 1; for (unsigned int i=0; i<ordinalVectorCopy.size(); i++) { // get the current ordinal number current_ordnumber = ordinalVectorCopy.at(i).funcpos; // the current ordinal number obviously should be one bigger than the previous one if ( current_ordnumber != previous_ordnumber+1 ) { // append a dummy ordinal to the list ordinalVectorCopy.insert(ordinalVectorCopy.begin()+i, ordinal(i+1, "UnknownOrdinal-"+Int2Str(i+1))); current_ordnumber = i+1; } // remember the previous ordinal number previous_ordnumber = current_ordnumber; // if the ordinal list is corrupted, it may lead to an infinite loop if (i>25000) { cerr << endl << "Something went horribly wrong when trying to parse " << lib_path << ". Aborting." << endl; exit(10); } } // finally copy data from the ordinal list to the symbol table if (symbol_table.size() < ordinalVectorCopy.size()) { symbol_table.reserve(ordinalVectorCopy.size()); } for (unsigned int i=0; i<ordinalVectorCopy.size(); i++) { symbol_table.push_back( ordinalVectorCopy.at(i).funcname ); } } // ---------------------------------------------------------------------------------------------------------- void DemangleOrdinalsInSymbolTable(const string& cfilt_location, vector<string>& symbol_table) { ofstream f(_tempfile_location.c_str(), ios::trunc); if (f.is_open()) { // create a temp file which contain all the function names for (unsigned int k=0; k<symbol_table.size(); k++) { f << symbol_table.at(k) << endl; } f.close(); // execute cfilt vector<string> cfilt_result_set; string cmd = cfilt_location + " < " + _tempfile_location; ExecuteCommand(cmd, cfilt_result_set); // check that all functions exist and then replace the symbol table with demangled functions if (cfilt_result_set.size() == symbol_table.size()) { symbol_table = cfilt_result_set; } } else { f.close(); } } // ---------------------------------------------------------------------------------------------------------- bool OrdinalCompare(const ordinal& left, const ordinal& right) { return left.funcpos < right.funcpos; } // ----------------------------------------------------------------------------------------------------------
[ "none@none" ]
[ [ [ 1, 631 ] ] ]
c32799ec7ecc03cc4bf60c55c005ea954267f1f1
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/Dependencies/Xerces/include/xercesc/util/XMLStringTokenizer.hpp
1046792f1ab9567a60a941d9caff1cf5084fa377
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
7,466
hpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /* * $Id: XMLStringTokenizer.hpp 176026 2004-09-08 13:57:07Z peiyongz $ */ #if !defined(XMLSTRINGTOKENIZER_HPP) #define XMLSTRINGTOKENIZER_HPP #include <xercesc/util/RefArrayVectorOf.hpp> #include <xercesc/util/XMLString.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * The string tokenizer class breaks a string into tokens. * * The XMLStringTokenizer methods do not distinguish among identifiers, * numbers, and quoted strings, nor do they recognize and skip comments * * A XMLStringTokenizer object internally maintains a current position within * the string to be tokenized. Some operations advance this current position * past the characters processed. */ class XMLUTIL_EXPORT XMLStringTokenizer :public XMemory { public: // ----------------------------------------------------------------------- // Public Constructors // ----------------------------------------------------------------------- /** @name Constructors */ //@{ /** * Constructs a string tokenizer for the specified string. The tokenizer * uses the default delimiter set, which is "\t\n\r\f": the space * character, the tab character, the newline character, the * carriage-return character, and the form-feed character. Delimiter * characters themselves will not be treated as tokens. * * @param srcStr The string to be parsed. * @param manager Pointer to the memory manager to be used to * allocate objects. * */ XMLStringTokenizer(const XMLCh* const srcStr, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); /** * Constructs a string tokenizer for the specified string. The characters * in the delim argument are the delimiters for separating tokens. * Delimiter characters themselves will not be treated as tokens. * * @param srcStr The string to be parsed. * @param delim The set of delimiters. * @param manager Pointer to the memory manager to be used to * allocate objects. */ XMLStringTokenizer(const XMLCh* const srcStr , const XMLCh* const delim , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager); //@} // ----------------------------------------------------------------------- // Public Destructor // ----------------------------------------------------------------------- /** @name Destructor. */ //@{ ~XMLStringTokenizer(); //@} // ----------------------------------------------------------------------- // Management methods // ----------------------------------------------------------------------- /** @name Management Function */ //@{ /** * Tests if there are more tokens available from this tokenizer's string. * * Returns true if and only if there is at least one token in the string * after the current position; false otherwise. */ bool hasMoreTokens(); /** * Calculates the number of times that this tokenizer's nextToken method * can be called to return a valid token. The current position is not * advanced. * * Returns the number of tokens remaining in the string using the current * delimiter set. */ int countTokens(); /** * Returns the next token from this string tokenizer. * * Function allocated, function managed (fafm). The calling function * does not need to worry about deleting the returned pointer. */ XMLCh* nextToken(); //@} private: // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- XMLStringTokenizer(const XMLStringTokenizer&); XMLStringTokenizer& operator=(const XMLStringTokenizer&); // ----------------------------------------------------------------------- // CleanUp methods // ----------------------------------------------------------------------- void cleanUp(); // ----------------------------------------------------------------------- // Helper methods // ----------------------------------------------------------------------- bool isDelimeter(const XMLCh ch); // ----------------------------------------------------------------------- // Private data members // // fOffset // The current position in the parsed string. // // fStringLen // The length of the string parsed (for convenience). // // fString // The string to be parsed // // fDelimeters // A set of delimeter characters // // fTokens // A vector of the token strings // ----------------------------------------------------------------------- int fOffset; int fStringLen; XMLCh* fString; XMLCh* fDelimeters; RefArrayVectorOf<XMLCh>* fTokens; MemoryManager* fMemoryManager; }; // --------------------------------------------------------------------------- // XMLStringTokenizer: CleanUp methods // --------------------------------------------------------------------------- inline void XMLStringTokenizer::cleanUp() { fMemoryManager->deallocate(fString);//delete [] fString; fMemoryManager->deallocate(fDelimeters);//delete [] fDelimeters; delete fTokens; } // --------------------------------------------------------------------------- // XMLStringTokenizer: Helper methods // --------------------------------------------------------------------------- inline bool XMLStringTokenizer::isDelimeter(const XMLCh ch) { return XMLString::indexOf(fDelimeters, ch) == -1 ? false : true; } // --------------------------------------------------------------------------- // XMLStringTokenizer: Management methods // --------------------------------------------------------------------------- inline int XMLStringTokenizer::countTokens() { if (fStringLen == 0) return 0; int tokCount = 0; bool inToken = false; for (int i= fOffset; i< fStringLen; i++) { if (isDelimeter(fString[i])) { if (inToken) { inToken = false; } continue; } if (!inToken) { tokCount++; inToken = true; } } // end for return tokCount; } XERCES_CPP_NAMESPACE_END #endif /** * End of file XMLStringTokenizer.hpp */
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 228 ] ] ]
c827facc7dd612213fda514cb33c53dd36852a88
c08d8f66d4ae94110f925145d8d2240af5e90ce7
/LTE_MATLAB/TX_Modules/TX_Scrambling_Module/test/C++/scrambling.cpp
8e7ce43c4a2376dc0c1154477af062b504c942ae
[]
no_license
lv111111/TD-LTE
41dcb983128275b2179178087467ca86d97c75b4
1408f35c0b363badfbb3f841865e3d01672fc882
refs/heads/master
2021-05-28T16:27:33.772219
2011-11-22T10:17:56
2011-11-22T10:17:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
869
cpp
#include <stdlib.h> #include <math.h> #include <mex.h> void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { mwSize len_output_seq; double n_RNTI; double q; double n_subframe; double n_cellID; double N_C; unsigned char *gold_seq; /* Check for proper number of arguments */ if ((nrhs != 6 )||(nlhs < 1)||(nlhs > 2)) { mexErrMsgTxt("Incorrect usage!"); } else { /* Get input parameters */ len_output_seq = (mwSize) (*mxGetPr(prhs[0])); n_RNTI = *mxGetPr(prhs[1]); q = *mxGetPr(prhs[2]); n_subframe = *mxGetPr(prhs[3]); n_cellID = *mxGetPr(prhs[4]); N_C = *mxGetPr(prhs[5]); /* create the output vector */ plhs[0] = mxCreateLogicalMatrix(1, len_output_seq); gold_seq = mxGetPr(plhs[0]); gold_seq[0] = 1; } }
[ [ [ 1, 40 ] ] ]
38ac0afe38ef45c336b8ca71234760bc7fb76f20
a31e04e907e1d6a8b24d84274d4dd753b40876d0
/MortTools/Types/Value.h
97a01bf468655bcc856ca3b75b83aa8e4930ad8a
[]
no_license
RushSolutions/jscripts
23c7d6a82046dafbba3c4e060ebe3663821b3722
869cc681f88e1b858942161d9d35f4fbfedcfd6d
refs/heads/master
2021-01-10T15:31:24.018830
2010-02-26T07:41:17
2010-02-26T07:41:17
47,889,373
0
0
null
null
null
null
UTF-8
C++
false
false
1,782
h
// Value.h: interface for the CValue class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_VALUE_H__15CB419D_731B_4B66_ABE1_67B8EFA95662__INCLUDED_) #define AFX_VALUE_H__15CB419D_731B_4B66_ABE1_67B8EFA95662__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define VALUE_NULL 0 // unused #define VALUE_LONG 1 // integer value #define VALUE_DOUBLE 2 // float value #define VALUE_STRING 3 // string value #define VALUE_MAP 4 // Map value ("arrays") #define VALUE_PTR 5 // internal pointer (e.g. internal CArrays) #define VALUE_CHAR 6 // char value #include "mortstring.h" class CMapStrToValue; class CValue { protected: BYTE type; union { //TCHAR c; long l; double d; const void *p; } value; BOOL referredPtr; CStr string; public: CValue(); CValue( const CValue &other ); CValue( TCHAR ); CValue( long ); CValue( double ); CValue( LPCTSTR ); ~CValue(); void Clear(); BOOL IsNull() const; BYTE GetType() const; BOOL IsDouble() const; BOOL IsValidNumber() const; TCHAR operator= ( const TCHAR cValue ); long operator= ( const long lValue ); double operator= ( const double dValue ); LPCTSTR operator= ( const TCHAR* sValue ); CValue& operator= ( const CValue& value ); //const void* operator= ( const void* pValue ); void SetPtr( void *ptr, LPCTSTR desc = NULL ); void CopyFrom( const CValue& value ); CMapStrToValue* GetMap(); operator TCHAR() const; operator long() const; operator double() const; operator CStr&(); operator LPCTSTR(); operator const void*() const; }; #endif // !defined(AFX_VALUE_H__15CB419D_731B_4B66_ABE1_67B8EFA95662__INCLUDED_)
[ "frezgo@c2805876-21d7-11df-8c35-9da929d3dec4" ]
[ [ [ 1, 75 ] ] ]
aa41043201222d5c2a49d7b80cb08091d583cff9
3f37de877cbd9a426e0b1dd26a290553bcaab109
/sources/pathfinder.cpp
22cbe30be12a413957485128a9fd68fe8632a43e
[]
no_license
Birdimol/GreenPlague
f698ba87a7325fd015da619146cb93057e94fe44
1675ec597247be9f09e30a3ceac01a7d7ec1af43
refs/heads/master
2016-09-09T18:57:25.414142
2011-10-19T06:08:15
2011-10-19T06:08:15
2,480,187
1
0
null
null
null
null
ISO-8859-1
C++
false
false
19,672
cpp
#include "pathfinder.hpp" #include "tools.hpp" #include <limits> #define NBRE_MAX_ITERATION 250 #define LARGEUR_UNITE 8 bool operator==(Point const& a, Point const& b) { if((a.x == b.x) && (a.y == b.y)) { return true; } else { return false; } } bool operator!=(Point const& a, Point const& b) { if((a.x != b.x) || (a.y != b.y)) { return true; } else { return false; } } Pathfinder::Pathfinder(vector<int> carte_, int largeur_, int hauteur_, int taille_case_,Map* map_) { carte = carte_; largeur = largeur_; hauteur = hauteur_; taille_case = taille_case_; map = map_; } bool Pathfinder::contient(vector<Point> tableau,int x,int y) { int taille = tableau.size(); if(taille == 0) { return false; } for(int a = taille; a>-1 ;a--) { if(tableau[a].x == x && tableau[a].y == y) { return true; } } return false; } bool Pathfinder::existe_pas_dans_vector(int x, int y,vector<Point> points_deja_verifies) { int size = points_deja_verifies.size(); for(int i=0; i< size;i++) { if(points_deja_verifies[i].x == x && points_deja_verifies[i].y == y) { return false; } } return true; } vector<Point> Pathfinder::calcul_path(Point depart,Point arrivee) { sf::Clock Clock; Clock.Reset(); //vecteur qui va contenir le parcourt vector<Point> parcourt; int demi_case = taille_case/2; //on vérifie si le chemin va rencontrer des obstacles ou non if(!traverse_mur(depart.x*taille_case+demi_case,depart.y*taille_case+demi_case,arrivee.x*taille_case+demi_case,arrivee.y*taille_case+demi_case)) { parcourt.push_back(arrivee); parcourt.push_back(depart); return parcourt; } //il y a des obstacles, en route pour le calcul ! int x = 0; int y = 0; //on initialise la case minimum a une très haute valeur afin qu'elle soit remplacée Case minimum(9999,9999); for(x=0;x<((int)carte.size());x++) { carte_distances.push_back(Case()); carte_distances[x].F = -1; carte_distances[x].G = -1; carte_distances[x].H = -1; } //initialisation de la première case int temp = depart.x + depart.y*largeur; carte_distances[temp].H = distance_entre_2_point(depart,arrivee); carte_distances[temp].G = 0; carte_distances[temp].F = carte_distances[temp].G + carte_distances[temp].H; vector<Point> points_deja_verifies; Point actuel(depart.x,depart.y); Point point_temp(0,0); int numero_case_actuelle = actuel.x + actuel.y*largeur; points_deja_verifies.push_back(depart); for(x=0;x<3;x++) { for(y=0;y<3;y++) { //si c'est dans la map if(actuel.x + (x-1) < largeur && actuel.x + (x-1) > -1 && actuel.y + (y-1) < largeur && actuel.y + (y-1) > -1 && carte[actuel.x + (x-1) + ((actuel.y + (y-1))*largeur)] != 1) { if((!(x == 1 && y == 1 )) && (!(x == 0 && y == 0 )) && (!(x == 2 && y == 0 )) && (!(x == 0 && y == 2 )) && (!(x == 2 && y == 2 ))) { point_temp.x = actuel.x + (x-1); point_temp.y = actuel.y + (y-1); int numero_case_temp = point_temp.x + point_temp.y*largeur; if(carte_distances[numero_case_temp].G == -1 || carte_distances[numero_case_temp].G > (carte_distances[numero_case_actuelle].G + distance_entre_2_point(actuel,point_temp))) { carte_distances[numero_case_temp].G = (carte_distances[numero_case_temp].G + distance_entre_2_point(actuel,point_temp)); carte_distances[numero_case_temp].H = distance_entre_2_point(point_temp,arrivee); carte_distances[numero_case_temp].F = carte_distances[numero_case_temp].G+carte_distances[numero_case_temp].H; carte_distances[numero_case_temp].set_parent(actuel.x,actuel.y); //cout << "nouveau parent pour " << point_temp.x << ", " << point_temp.y << " : " << actuel.x << ", " << actuel.y << endl; } } } } } int nombre_iterations = 0; //cout << "temps ecoule au debut de la boucle : " << Clock.GetElapsedTime() << endl; while(nombre_iterations < NBRE_MAX_ITERATION && actuel != arrivee) { //on initialise le point minimum à une grande valeur, supérieure au maximum possible sur la map minimum.F = 999999; //cout << "recherche du point minimum" << endl; for(x=0;x<largeur;x++) { for(y=0;y<hauteur;y++) { //optimisation int numero_temp = x + y*largeur; if(carte_distances[numero_temp].F != -1) { if(minimum.F > carte_distances[numero_temp].F) { if(existe_pas_dans_vector(x,y,points_deja_verifies)) { //cout << "Nouveau minimum "<< x << ", " << y << " : " << carte_distances[x + y*largeur].F << endl; minimum = carte_distances[numero_temp]; point_temp.x = x; point_temp.y = y; } } } } } points_deja_verifies.push_back(point_temp); actuel = point_temp; //cout << "checking sur la case minimum trouvee : " << actuel.x << ", " << actuel.y << endl; for(x=0;x<3;x++) { for(y=0;y<3;y++) { int numero_case = actuel.x + actuel.y*largeur; //si le point est dans la map if(actuel.x + (x-1) < largeur && actuel.x + (x-1) > -1 && actuel.y + (y-1) < hauteur && actuel.y + (y-1) > -1 && carte[actuel.x + (x-1) + ((actuel.y + (y-1))*largeur)] != 1) { //si la case en diagonale est accessible if( ((!(x == 1 && y == 1 )) && (!(x == 0 && y == 0 )) && (!(x == 2 && y == 0 )) && (!(x == 0 && y == 2 )) && (!(x == 2 && y == 2 ))) || //en haut a gauche on vérifie la case au dessus et a gauche (x == 0 && y == 0 && carte[numero_case -1 ] != 1 && carte[numero_case-largeur] != 1 ) || (x == 2 && y == 2 && carte[numero_case+1] != 1 && carte[numero_case+largeur] != 1 ) || (x == 0 && y == 2 && carte[numero_case-1] != 1 && carte[numero_case+largeur] != 1 ) || (x == 2 && y == 0 && carte[numero_case+1] != 1 && carte[numero_case-largeur] != 1 ) ) { point_temp.x = actuel.x + (x-1); point_temp.y = actuel.y + (y-1); int numero_case_temp = point_temp.x + point_temp.y*largeur; if(carte_distances[numero_case_temp].G == -1 || carte_distances[numero_case_temp].G > (carte_distances[numero_case_temp].G + distance_entre_2_point(actuel,point_temp))) { carte_distances[numero_case_temp].G = (carte_distances[numero_case_temp].G + distance_entre_2_point(actuel,point_temp)); carte_distances[numero_case_temp].H = distance_entre_2_point(point_temp,arrivee); carte_distances[numero_case_temp].F = carte_distances[numero_case_temp].G+carte_distances[numero_case_temp].H; carte_distances[numero_case_temp].set_parent(actuel.x,actuel.y); //points_deja_verifies.push_back(point_temp); } } } } } //cout << "Fin d'iteration, retour a la recherche de minimum." ; nombre_iterations++; //cout << " iterations : " << nombre_iterations << endl; } //si on a trouvé une route if(actuel == arrivee) { // point_temp = arrivee; while(point_temp != depart) { parcourt.push_back(point_temp); point_temp = carte_distances[point_temp.x + point_temp.y*largeur].parent; } parcourt.push_back(depart); } else { //on a pas trouve alors on se rend sur la case trouvee dans l'algo qui etait la plus proche de l'arrivee (donc H minimum); int size = carte_distances.size(); float minimum = 99999999; Point tempo; for(int g=0;g<size;g++) { if(carte_distances[g].H < minimum && carte_distances[g].H > -1 && carte[g] != 1 ) // ET QUE LA CASE EST LIBRE !!! { tempo.x = g%largeur; tempo.y = floor(g/largeur); if(!(Tools::contient_point(map->get_liste_case_occupee(),tempo))) { minimum = carte_distances[g].H; arrivee.x = tempo.x; arrivee.y = tempo.y; } } } point_temp = arrivee; while(point_temp != depart) { parcourt.push_back(point_temp); point_temp = carte_distances[point_temp.x + point_temp.y*largeur].parent; } parcourt.push_back(depart); } int taille_parcourt = parcourt.size(); //si on a trouve un chemin, on simplifie la trajectoire if(taille_parcourt > 0) { int repere_precedent = taille_parcourt-1; vector<Point> inutiles; for(int z = taille_parcourt-1;z>-1;z--) { if(z!= 0 && z != taille_parcourt-1) { //cout << "test x1("<< parcourt[repere_precedent].x <<") = " << parcourt[repere_precedent].x*25+12.5 << ", x2("<< parcourt[z-1].x <<") = " << parcourt[z-1].x*25+12.5 << endl; float x1 = parcourt[repere_precedent].x*taille_case+demi_case; float x2 = parcourt[z-1].x*taille_case+demi_case; float y1 = parcourt[repere_precedent].y*taille_case+demi_case; float y2 = parcourt[z-1].y*taille_case+demi_case; //optimisation on utilise que les 2 lignes exterieures :: if((!traverse_mur(x1,y1,x2,y2))&&(!traverse_mur(x3,y3,x4,y4))&&(!traverse_mur(x5,y5,x6,y6))) if(!traverse_mur(x1,y1,x2,y2)) { //cout << "Pas de mur entre le repere " << parcourt[repere_precedent].x << ", " << parcourt[repere_precedent].y << " et la case " << parcourt[z-1].x << ", " << parcourt[z-1].y << endl; //cout << "case " << parcourt[z].x << ", " << parcourt[z].y << " inutile dans le parcourt." << endl << endl; inutiles.push_back(parcourt[z]); } else { //cout << "Mur entre la case " << parcourt[repere_precedent].x << ", " << parcourt[repere_precedent].y << " et la case " << parcourt[z-1].x << ", " << parcourt[z-1].y << endl << endl; repere_precedent = z; } } //parcourt[z].afficher(); } int suppression = 1; int a_supprimer = 0; while(suppression == 1) { suppression = 0; for(int z = taille_parcourt-1;z>-1;z--) { if(contient(inutiles,parcourt[z].x,parcourt[z].y)) { suppression = 1; a_supprimer = z; } } if(suppression) { parcourt.erase(parcourt.begin()+a_supprimer); } } } carte_distances.clear(); return parcourt; } bool Pathfinder::traverse_mur(float x1,float y1,float x2,float y2) { float x3; float y3; float x4; float y4; float x5; float y5; float x6; float y6; float angle; //vertical if(x1==x2) { x3 = x1+LARGEUR_UNITE; y3 = y1; x4 = x2+LARGEUR_UNITE; y4 = y2; x5 = x1-LARGEUR_UNITE; y5 = y1; x6 = x2-LARGEUR_UNITE; y6 = y2; } //horizontal else if(y1==y2) { x3 = x1; y3 = y1+LARGEUR_UNITE; x4 = x2; y4 = y2+LARGEUR_UNITE; x5 = x1; y5 = y1-LARGEUR_UNITE; x6 = x2; y6 = y2-LARGEUR_UNITE; } else { float a = ((float)x2-(float)x1); float b = ((float)y1-(float)y2); angle = a/b; //cout << " a : "<< a << "/" << b << " angle : " << angle << " distance : " << sqrt((5*(angle))*(5*(angle))+(5*(angle))*(5*(angle))) << endl; a = -LARGEUR_UNITE / sqrt(1 + angle*angle); b = a*angle; x3 = x1 + a; y3 = y1 + b; x4 = x2 + a; y4 = y2 + b; x5 = x1 - a; y5 = y1 - b; x6 = x2 - a; y6 = y2 - b; } //on check pour les 3 lignes créées for(int i=0;i<3;i++) { if(i==1) { x1=x3; y1=y3; x2=x4; y2=y4; } if(i==2) { x1=x5; y1=y5; x2=x6; y2=y6; } if(x2 < x1) { float xtemp = x1; float ytemp = y1; x1 = x2; y1 = y2; x2 = xtemp; y2 = ytemp; } float x,y; vector<Point> liste_mur; liste_mur = map->get_liste_mur(); int size = liste_mur.size(); for(int a=0; a<size;a++) { int i = liste_mur[a].y; int j = liste_mur[a].x; y = i * taille_case; x = j * taille_case; //si c'est un mur if(carte[(j)+i*largeur] == 1) { //cout << "case " << i << ", " << j << "(" <<((i)+j*largeur) << ") est un mur."<< endl; //il y a possibilité de chevauchement if(x1 <= x+taille_case && x2 >= x) { float x_min=x; float x_max=x+taille_case; //cout << "possibilite de chevauchement entre : " << x_min << ", et : " << x_max << endl; if(x1 > x) { x_min = x1; } if(x2 < x+taille_case) { x_max = x2; } //il faut maintenant savoir la valeur de la droite en x_min et x_max float y_min = y1+((y1 - y2)/(x1 - x2))*(x_min - x1); float y_max = y1+((y1 - y2)/(x1 - x2))*(x_max - x1); if(x1 == x2) { y_min = y1; y_max = y2; } if(!((y_min > y+taille_case && y_max > y+taille_case) || (y_min < y && y_max < y))) { //cout << x1 << ", " << y1 << " -> " << x2 << ", " << y2 << " traverse un mur." << endl; return 1; } } } } } return 0; } float Pathfinder::distance_entre_2_point(Point a,Point b) { float diffx = a.x - b.x; float diffy = a.y - b.y; if(diffx < 0) { diffx *= -1; } if(diffy < 0) { diffy *= -1; } float temp = sqrt((diffx * diffx)+(diffy * diffy)); return temp; } void Pathfinder::afficher_parcourt(vector<int> carte_vector, int largeur_carte, int hauteur_carte, Point depart, Point arrivee, vector<Point> parcourt) { sf::RenderWindow App(sf::VideoMode(largeur_carte*taille_case, hauteur_carte*taille_case, 32), "SFML Graphics"); App.SetFramerateLimit(60); float temoin = App.GetFrameTime(); float ElapsedTime = App.GetFrameTime(); sf::Color couleur(0,0,0); sf::Color couleur2(70,70,235); sf::Shape Line = sf::Shape::Line(0, 0, 100, 100, 1, couleur2); int taille_parcourt = parcourt.size(); sf::Image icase_vide; sf::Sprite scase_vide; icase_vide.LoadFromFile("case_vide.png"); scase_vide.SetImage(icase_vide); sf::Image imur; sf::Sprite smur; imur.LoadFromFile("mur.png"); smur.SetImage(imur); sf::Image idepart; sf::Sprite sdepart; idepart.LoadFromFile("depart.png"); sdepart.SetImage(idepart); sf::Image iarrivee; sf::Sprite sarrivee; iarrivee.LoadFromFile("arrivee.png"); sarrivee.SetImage(iarrivee); sf::Image ipassage; sf::Sprite spassage; ipassage.LoadFromFile("passage.png"); spassage.SetImage(ipassage); int compte =0; while(temoin + 60 > ElapsedTime && App.IsOpened()) { sf::Event Event; while (App.GetEvent(Event)) { if (Event.Type == sf::Event::Closed) App.Close(); } if (App.GetInput().IsKeyDown(sf::Key::Escape)) { App.Close(); } App.Clear(couleur); int taille_map = ((int)carte_vector.size()); for(int a=0;a < taille_map;a++) { if((a%largeur_carte) == depart.x && floor(a/largeur_carte) == depart.y) { sdepart.SetPosition((a%largeur_carte)*taille_case,floor(a/largeur_carte)*taille_case); App.Draw(sdepart); } else if((a%largeur_carte) == arrivee.x && floor(a/largeur_carte) == arrivee.y) { sarrivee.SetPosition((a%largeur_carte)*taille_case,floor(a/largeur_carte)*taille_case); App.Draw(sarrivee); } else if(contient(parcourt,(a%largeur_carte),floor(a/largeur_carte))) { spassage.SetPosition((a%largeur_carte)*taille_case,floor(a/largeur_carte)*taille_case); App.Draw(spassage); } else if(carte_vector[a]==0) { scase_vide.SetPosition((a%largeur_carte)*taille_case,floor(a/largeur_carte)*taille_case); App.Draw(scase_vide); } else { smur.SetPosition((a%largeur_carte)*taille_case,floor(a/largeur_carte)*taille_case); App.Draw(smur); } } if(taille_parcourt > 0) { for(int z = taille_parcourt-1;z>-1;z--) { if(z != 0) { Line = sf::Shape::Line(parcourt[z-1].x*taille_case+taille_case/2, parcourt[z-1].y*taille_case+taille_case/2, parcourt[z].x*taille_case+taille_case/2, parcourt[z].y*taille_case+taille_case/2, 1, couleur2); App.Draw(Line); } } } App.Display(); ElapsedTime += App.GetFrameTime(); compte++; } }
[ [ [ 1, 1 ], [ 4, 4 ], [ 7, 31 ], [ 33, 37 ], [ 39, 74 ], [ 78, 78 ], [ 80, 80 ], [ 82, 82 ], [ 90, 90 ], [ 100, 107 ], [ 113, 118 ], [ 120, 132 ], [ 135, 135 ], [ 140, 148 ], [ 150, 159 ], [ 164, 164 ], [ 175, 187 ], [ 191, 191 ], [ 201, 203 ], [ 206, 206 ], [ 212, 218 ], [ 220, 225 ], [ 227, 234 ], [ 255, 255 ], [ 265, 279 ], [ 284, 284 ], [ 287, 300 ], [ 302, 322 ], [ 325, 329 ], [ 338, 338 ], [ 340, 340 ], [ 366, 366 ], [ 371, 371 ], [ 374, 374 ], [ 377, 377 ], [ 380, 380 ], [ 413, 413 ], [ 416, 416 ], [ 420, 420 ], [ 422, 422 ], [ 433, 433 ], [ 443, 443 ], [ 449, 449 ], [ 454, 454 ], [ 472, 602 ] ], [ [ 2, 3 ], [ 5, 6 ], [ 32, 32 ], [ 38, 38 ], [ 75, 77 ], [ 79, 79 ], [ 81, 81 ], [ 83, 89 ], [ 91, 99 ], [ 108, 112 ], [ 119, 119 ], [ 133, 134 ], [ 136, 139 ], [ 149, 149 ], [ 160, 163 ], [ 165, 174 ], [ 188, 190 ], [ 192, 200 ], [ 204, 205 ], [ 207, 211 ], [ 219, 219 ], [ 226, 226 ], [ 235, 254 ], [ 256, 264 ], [ 280, 283 ], [ 285, 286 ], [ 301, 301 ], [ 323, 324 ], [ 330, 337 ], [ 339, 339 ], [ 341, 365 ], [ 367, 370 ], [ 372, 373 ], [ 375, 376 ], [ 378, 379 ], [ 381, 412 ], [ 414, 415 ], [ 417, 419 ], [ 421, 421 ], [ 423, 432 ], [ 434, 442 ], [ 444, 448 ], [ 450, 453 ], [ 455, 471 ] ] ]
ccd9f3be1abc84a5e96b6eefd615dcbb4de474be
59166d9d1eea9b034ac331d9c5590362ab942a8f
/FrustumTerrainShader/TerrainShader/DynamicGroupLevel32768Node.cpp
79567f3665f14686bc353a39740320e32d5f911c
[]
no_license
seafengl/osgtraining
5915f7b3a3c78334b9029ee58e6c1cb54de5c220
fbfb29e5ae8cab6fa13900e417b6cba3a8c559df
refs/heads/master
2020-04-09T07:32:31.981473
2010-09-03T15:10:30
2010-09-03T15:10:30
40,032,354
0
3
null
null
null
null
WINDOWS-1251
C++
false
false
7,079
cpp
#include "DynamicGroupLevel32768Node.h" #include <osg/Geometry> #include <iostream> DynamicGroupLevel32768Node::DynamicGroupLevel32768Node() : m_iCount( 0 ) { //зарезервировать память для 32 узлов m_vData.resize( 32 ); //группа узлов m_rootNode = new osg::Group; //инициализировать геометрию патчей земной поверхности InitGeodes(); //узел динамически меняет количество потомков m_rootNode->setDataVariance( osg::Object::DYNAMIC ); } void DynamicGroupLevel32768Node::InitGeodes() { //инициализировать геометрию патчей земной поверхности for ( int i = 0 ; i < m_vData.size() ; ++i ) { //добавить узел геометрии m_vData[ i ].m_Geode = new osg::Geode; //добавить uniform m_vData[ i ].m_unfOffset = new osg::Uniform( m_vData[ i ].m_sOffset.c_str() , osg::Vec3( 0,0,0) ); m_vData[ i ].m_unfColorP = new osg::Uniform( m_vData[ i ].m_sColorP.c_str() , osg::Vec3( 0.5,0.25,0 ) ); m_vData[ i ].m_unfColorS = new osg::Uniform( m_vData[ i ].m_sColorS.c_str() , osg::Vec3( 1,1,1 ) ); m_vData[ i ].m_unfKofScale = new osg::Uniform( m_vData[ i ].m_sKofScale.c_str() , 512.0f ); m_vData[ i ].m_unfDist = new osg::Uniform( m_vData[ i ].m_sDist.c_str() , 32768.0f * DIST_SCALE ); m_vData[ i ].m_unfTexCoordAdd = new osg::Uniform( m_vData[ i ].m_sTexCoordAdd.c_str() , 2.0f ); m_vData[ i ].m_unfTexCoordScale = new osg::Uniform( m_vData[ i ].m_sTexCoordScale.c_str() , -128.0f ); //добавить геометрию в i'ый узел AddGeometry( i ); //настроить параметры необходимые в шейдере SetupShaderParam( i ); m_rootNode->addChild( m_vData[ i ].m_Geode.get() ); } } void DynamicGroupLevel32768Node::ResetRootNode() { //удалить всех потомков корневого узла m_iCount = 0; m_rootNode->removeChildren( 0 , m_rootNode->getNumChildren() ); } void DynamicGroupLevel32768Node::AddGeometry( int i ) { //добавить геометрию в i'ый узел //создать объект для хранения в нем геометрии osg::ref_ptr< osg::Geometry > geom = new osg::Geometry; //создать массив вершин geom->setVertexArray( CreateVertexArray( 0 , 0 , 64 + 64 , 32768 ).get() ); std::vector< unsigned short > m_vIndex; //заполнить вектор индексами FillIndexVector( m_vIndex , 64 + 64 ); geom->addPrimitiveSet( new osg::DrawElementsUShort( osg::PrimitiveSet::TRIANGLE_STRIP, m_vIndex.size() / GEOM_DIV , &m_vIndex[ 0 ] ) ); osg::BoundingBox bbox( 0, 0, 0, 512 * 512 , 512 * 512 , 64 ); geom->setInitialBound( bbox ); //добавить рисуемую геометрию m_vData[ i ].m_Geode->addDrawable( geom.get() ); } void DynamicGroupLevel32768Node::SetupShaderParam( int i ) { //настроить параметры необходимые в шейдере //формирование сцены с шейдером osg::StateSet* ss = m_vData[ i ].m_Geode->getOrCreateStateSet(); //добавление uniform'а для задания смещения патча ss->addUniform( m_vData[ i ].m_unfOffset.get() ); ss->addUniform( m_vData[ i ].m_unfColorP.get() ); ss->addUniform( m_vData[ i ].m_unfColorS.get() ); ss->addUniform( m_vData[ i ].m_unfKofScale.get() ); ss->addUniform( m_vData[ i ].m_unfDist.get() ); ss->addUniform( m_vData[ i ].m_unfTexCoordAdd.get() ); ss->addUniform( m_vData[ i ].m_unfTexCoordScale.get() ); } osg::ref_ptr<osg::Vec4Array> DynamicGroupLevel32768Node::CreateVertexArray( int x , int y , int sizeC , int scaleC ) { //создать массив вершин osg::ref_ptr<osg::Vec4Array> v = new osg::Vec4Array; //kof = 512.0f float kof = (float)scaleC / (float)( sizeC - 64 ); kof = 1.0; //номер ячейки в которой будет сдвиг int iQuad = ( sizeC - 64 ) / 64 + 1; //смещение по Y int iY = 0; //Заполнение массива points for (int i = 0 ; i < sizeC ; ++i ) { //момент когда надо сдвигать на 1 по Y int shift = iQuad * ( iY + 1 ); //если i совпадает с iHalf то сместиться на 1 вниз if ( i == shift ) ++iY; //смещение по X int iX = 0; for (int j = 0 ; j < sizeC ; ++j ) { //момент когда надо сдвигать на 1 по Y int shift = iQuad * ( iX + 1 ); //если j совпадает с iHalf то сместиться на 1 в лево if ( j == shift ) ++iX; v->push_back( osg::Vec4( x + ( j - iX ) * kof , y + ( i - iY ) * kof , iX , iY ) ); } } return v.get(); } void DynamicGroupLevel32768Node::FillIndexVector( std::vector< unsigned short > &m_vIndex , int sizeC ) { //заполнить вектор индексами //заполнить вектор индексами m_vIndex.push_back( 0 ); m_vIndex.push_back( sizeC ); int count = sizeC - 1; int ind = 0; while( count > 0 ) { for( int i = 0 ; i < count ; i++ ) { ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] + 1 ); ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] + 1 ); } ind = m_vIndex.size() - 3; m_vIndex.push_back( m_vIndex[ ind ] ); count--; for( int i = 0 ; i< count ; i++ ) { ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] + sizeC ); ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] + sizeC ); } ind = m_vIndex.size() - 3; m_vIndex.push_back( m_vIndex[ ind ] ); for( int i = 0 ; i < count ; i++ ) { ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] - 1 ); ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] - 1 ); } ind = m_vIndex.size() - 3; m_vIndex.push_back( m_vIndex[ ind ] ); count--; for( int i=0 ; i < count ; i++ ) { ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] - sizeC ); ind = m_vIndex.size() - 2; m_vIndex.push_back( m_vIndex[ ind ] - sizeC ); } ind = m_vIndex.size() - 3; m_vIndex.push_back( m_vIndex[ ind ] ); } } void DynamicGroupLevel32768Node::AddPatch( float x , float y ) { //добавить патч геометрии из буффера в корневой узел //обновить данные в uniform'e m_vData[ m_iCount ].m_unfOffset->set( osg::Vec3( x , y , 0.0f ) ); //добавить очередной узел из буффера m_rootNode->addChild( m_vData[ m_iCount ].m_Geode.get() ); ++m_iCount; } void DynamicGroupLevel32768Node::PrintSize() { //вывести количество узлов для отрисовки std::cout << m_rootNode->getNumChildren() << " "; }
[ "asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b" ]
[ [ [ 1, 216 ] ] ]
46cbdfbe3aee96422e15cf7bc5ef47a04c9b7dfc
3e69b159d352a57a48bc483cb8ca802b49679d65
/branches/bokeoa-scons/common/edaappl.cpp
6de7ce4a629cf01a631b6398e73c713b6eed7089
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
UTF-8
C++
false
false
15,791
cpp
/***************/ /* edaappl.cpp */ /***************/ /* ROLE: methodes relative a la classe winEDA_App, communes aux environements window et linux */ #define EDA_BASE #define COMMON_GLOBL #include "fctsys.h" #include <wx/image.h> #include "wx/html/htmlwin.h" #include "wx/fs_zip.h" #include "wxstruct.h" #include "macros.h" #include "gr_basic.h" #include "common.h" #include "worksheet.h" #include "id.h" #include "bitmaps.h" #include "Language.xpm" #ifdef __WINDOWS__ /* Icons for language choice (only for Windows)*/ #include "Lang_Default.xpm" #include "Lang_En.xpm" #include "Lang_Es.xpm" #include "Lang_Fr.xpm" #include "Lang_Pt.xpm" #include "Lang_It.xpm" #include "Lang_De.xpm" #include "Lang_Sl.xpm" #include "Lang_Hu.xpm" #endif #define FONT_DEFAULT_SIZE 10 /* Default font size. The real font size will be computed at run time */ #ifdef __WINDOWS__ #define SETBITMAPS(icon) item->SetBitmaps(apply_xpm, (icon)) #else #define SETBITMAPS(icon) #endif /*****************************/ /* Constructeur de WinEDA_App */ /*****************************/ WinEDA_App::WinEDA_App(void) { m_Checker = NULL; m_MainFrame = NULL; m_PcbFrame = NULL; m_ModuleEditFrame = NULL; // Edition des modules SchematicFrame = NULL; // Edition des Schemas LibeditFrame = NULL; // Edition des composants ViewlibFrame = NULL; // Visualisation des composants m_CvpcbFrame = NULL; m_GerberFrame = NULL; // ecran de visualisation GERBER m_LastProjectMaxCount = 10; m_HtmlCtrl = NULL; m_EDA_CommonConfig = NULL; m_EDA_Config = NULL; m_Env_Defined = FALSE; m_LanguageId = wxLANGUAGE_DEFAULT; m_Language_Menu = NULL; m_Locale = NULL; /* Init de variables globales d'interet general: */ g_FloatSeparator = '.'; // Nombres flottants = 0.1 par exemple } /*****************************/ /* Destructeur de WinEDA_App */ /*****************************/ WinEDA_App::~WinEDA_App(void) { SaveSettings(); /* delete data non directement geree par wxAppl */ delete g_Prj_Config; delete m_EDA_Config; delete m_EDA_CommonConfig; delete g_StdFont; delete g_DialogFont; delete g_ItalicFont; delete g_FixedFont; delete g_MsgFont; delete DrawPen; delete DrawBrush; if ( m_Checker ) delete m_Checker; delete m_Locale; } /**************************************************/ void WinEDA_App::InitEDA_Appl(const wxString & name) /***************************************************/ { wxString ident; wxString EnvLang; ident = name + wxT("-") + wxGetUserId(); m_Checker = new wxSingleInstanceChecker(ident); /* Init environnement (KICAD definit le chemin de kicad ex: set KICAD=d:\kicad) */ m_Env_Defined = wxGetEnv( wxT("KICAD"), &m_KicadEnv); if ( m_Env_Defined ) // m_KicadEnv doit finir par "/" ou "\" { m_KicadEnv.Replace(WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP); if ( m_KicadEnv.Last() != '/' ) m_KicadEnv += UNIX_STRING_DIR_SEP; } /* Prepare On Line Help */ m_HelpFileName = name + wxT(".html"); // Init parametres pour configuration SetVendorName(wxT("kicad")); SetAppName(name); m_EDA_Config = new wxConfig(name); m_EDA_CommonConfig = new wxConfig(wxT("kicad_common")); /* Creation des outils de trace */ DrawPen = new wxPen( wxT("GREEN"), 1, wxSOLID); DrawBrush = new wxBrush(wxT("BLACK"), wxTRANSPARENT); /* Creation des fontes utiles */ g_StdFontPointSize = FONT_DEFAULT_SIZE; g_MsgFontPointSize = FONT_DEFAULT_SIZE; g_DialogFontPointSize = FONT_DEFAULT_SIZE; g_FixedFontPointSize = FONT_DEFAULT_SIZE; g_StdFont = new wxFont(g_StdFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL); g_MsgFont = new wxFont(g_StdFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL); g_DialogFont = new wxFont(g_DialogFontPointSize, wxFONTFAMILY_ROMAN, wxNORMAL, wxNORMAL); g_ItalicFont = new wxFont(g_DialogFontPointSize, wxFONTFAMILY_ROMAN, wxFONTSTYLE_ITALIC, wxNORMAL); g_FixedFont = new wxFont(g_FixedFontPointSize, wxFONTFAMILY_MODERN, wxNORMAL, wxNORMAL); /* installation des gestionnaires de visu d'images (pour help) */ wxImage::AddHandler(new wxPNGHandler); wxImage::AddHandler(new wxGIFHandler); wxImage::AddHandler(new wxJPEGHandler); wxFileSystem::AddHandler(new wxZipFSHandler); // Analyse command line & init binary path SetBinDir(); // Internationalisation: chargement du Dictionnaire de kicad m_EDA_CommonConfig->Read(wxT("Language"), &m_LanguageId, wxLANGUAGE_DEFAULT); bool succes = SetLanguage(TRUE); if ( ! succes ) { } if ( atof("0,1") ) g_FloatSeparator = ','; // Nombres flottants = 0,1 else g_FloatSeparator = '.'; } /*****************************************/ void WinEDA_App::InitOnLineHelp(void) /*****************************************/ /* Init On Line Help */ { wxString fullfilename = FindKicadHelpPath(); fullfilename += wxT("kicad.hhp"); if ( wxFileExists(fullfilename) ) { m_HtmlCtrl = new wxHtmlHelpController(wxHF_TOOLBAR | wxHF_CONTENTS | wxHF_PRINT | wxHF_OPEN_FILES /*| wxHF_SEARCH */); m_HtmlCtrl->UseConfig(m_EDA_Config); m_HtmlCtrl->SetTitleFormat( wxT("Kicad Help") ); m_HtmlCtrl->AddBook(fullfilename); } } /*******************************/ bool WinEDA_App::SetBinDir(void) /*******************************/ /* Analyse la ligne de commande pour retrouver le chemin de l'executable Sauve en WinEDA_App::m_BinDir le repertoire de l'executable */ { /* Calcul du chemin ou se trouve l'executable */ #ifdef __UNIX__ /* Sous LINUX ptarg[0] ne donne pas le chemin complet de l'executable, il faut le retrouver par la commande "which <filename> si aucun chemin n'est donne */ FILE * ftmp; #define TMP_FILE "/tmp/kicad.tmp" char Line[1024]; char FileName[1024]; wxString str_arg0; int ii; FileName[0] = 0; str_arg0 = argv[0]; if( strchr( (const char *)argv[0],'/') == NULL ) /* pas de chemin */ { sprintf( FileName, "which %s > %s", CONV_TO_UTF8(str_arg0), TMP_FILE); ii = system(FileName); if( (ftmp = fopen(TMP_FILE, "rt")) != NULL ) { fgets(Line,1000,ftmp); fclose(ftmp); remove(TMP_FILE); } m_BinDir = CONV_FROM_UTF8(Line); } else m_BinDir = argv[0]; #else m_BinDir = argv[0]; #endif m_BinDir.Replace(WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP); while ( m_BinDir.Last() != '/' ) m_BinDir.RemoveLast(); return TRUE; } /*********************************/ void WinEDA_App::GetSettings(void) /*********************************/ /* Lit les infos utiles sauvees lors de la derniere utilisation du logiciel */ { wxString Line, Ident; unsigned ii; m_HelpSize.x = 500; m_HelpSize.y = 400; if ( m_EDA_CommonConfig ) { m_LanguageId = m_EDA_CommonConfig->Read(wxT("Language"), wxLANGUAGE_DEFAULT); g_EditorName = m_EDA_CommonConfig->Read(wxT("Editor")); } if ( ! m_EDA_Config ) return; for ( ii = 0; ii < 10; ii++ ) { Ident = wxT("LastProject"); if ( ii ) Ident << ii; if( m_EDA_Config->Read(Ident, &Line) ) m_LastProject.Add(Line); } g_StdFontPointSize = m_EDA_Config->Read(wxT("SdtFontSize"), FONT_DEFAULT_SIZE); g_MsgFontPointSize = m_EDA_Config->Read(wxT("MsgFontSize"), FONT_DEFAULT_SIZE); g_DialogFontPointSize = m_EDA_Config->Read(wxT("DialogFontSize"), FONT_DEFAULT_SIZE); g_FixedFontPointSize = m_EDA_Config->Read(wxT("FixedFontSize"), FONT_DEFAULT_SIZE); Line = m_EDA_Config->Read(wxT("SdtFontType"), wxEmptyString); if ( ! Line.IsEmpty() ) g_StdFont->SetFaceName(Line); ii = m_EDA_Config->Read(wxT("SdtFontStyle"), wxFONTFAMILY_ROMAN); g_StdFont->SetStyle(ii); ii = m_EDA_Config->Read(wxT("SdtFontWeight"), wxNORMAL); g_StdFont->SetWeight(ii); g_StdFont->SetPointSize(g_StdFontPointSize); Line = m_EDA_Config->Read(wxT("MsgFontType"), wxEmptyString); if ( ! Line.IsEmpty() ) g_MsgFont->SetFaceName(Line); ii = m_EDA_Config->Read(wxT("MsgFontStyle"), wxFONTFAMILY_ROMAN); g_MsgFont->SetStyle(ii); ii = m_EDA_Config->Read(wxT("MsgFontWeight"), wxNORMAL); g_MsgFont->SetWeight(ii); g_MsgFont->SetPointSize(g_MsgFontPointSize); Line = m_EDA_Config->Read(wxT("DialogFontType"), wxEmptyString); if ( ! Line.IsEmpty() ) g_DialogFont->SetFaceName(Line); ii = m_EDA_Config->Read(wxT("DialogFontStyle"), wxFONTFAMILY_ROMAN); g_DialogFont->SetStyle(ii); ii = m_EDA_Config->Read(wxT("DialogFontWeight"), wxNORMAL); g_DialogFont->SetWeight(ii); g_DialogFont->SetPointSize(g_DialogFontPointSize); g_FixedFont->SetPointSize(g_FixedFontPointSize); m_EDA_Config->Read(wxT("ShowPageLimits"), & g_ShowPageLimits); if( m_EDA_Config->Read(wxT("WorkingDir"), &Line) ) { if ( wxDirExists(Line) ) wxSetWorkingDirectory(Line); } m_EDA_Config->Read( wxT("BgColor"), &g_DrawBgColor); } /**********************************/ void WinEDA_App::SaveSettings(void) /**********************************/ { unsigned int ii; if( m_EDA_Config == NULL ) return; m_EDA_Config->Write(wxT("SdtFontSize"), g_StdFontPointSize); m_EDA_Config->Write(wxT("SdtFontType"), g_StdFont->GetFaceName()); m_EDA_Config->Write(wxT("SdtFontStyle"), g_StdFont->GetStyle()); m_EDA_Config->Write(wxT("SdtFontWeight"), g_StdFont->GetWeight()); m_EDA_Config->Write(wxT("MsgFontSize"), g_MsgFontPointSize); m_EDA_Config->Write(wxT("MsgFontType"), g_MsgFont->GetFaceName()); m_EDA_Config->Write(wxT("MsgFontStyle"), g_MsgFont->GetStyle()); m_EDA_Config->Write(wxT("MsgFontWeight"), g_MsgFont->GetWeight()); m_EDA_Config->Write(wxT("DialogFontSize"), g_DialogFontPointSize); m_EDA_Config->Write(wxT("DialogFontType"), g_DialogFont->GetFaceName()); m_EDA_Config->Write(wxT("DialogFontStyle"), g_DialogFont->GetStyle()); m_EDA_Config->Write(wxT("DialogFontWeight"), g_DialogFont->GetWeight()); m_EDA_Config->Write(wxT("FixedFontSize"), g_FixedFontPointSize); m_EDA_Config->Write(wxT("ShowPageLimits"), g_ShowPageLimits); m_EDA_Config->Write(wxT("WorkingDir"), wxGetCwd()); for( ii = 0; ii < 10; ii++ ) { wxString msg = wxT("LastProject"); if ( ii ) msg << ii; if ( ii < m_LastProject.GetCount() ) m_EDA_Config->Write(msg, m_LastProject[ii]); else m_EDA_Config->Write(msg, wxEmptyString); } } /*********************************************/ bool WinEDA_App::SetLanguage(bool first_time) /*********************************************/ /* Set the dictionary file name for internationalization the files are in kicad/internat/xx or kicad/internat/xx_XX and are named kicad.mo */ { wxString DictionaryName( wxT("kicad")); // dictionary file name without extend (full name is kicad.mo) wxString BaseDictionaryPath( wxT("internat")); // Real path is kicad/internat/xx_XX or kicad/internat/xx wxString dic_path; if ( m_Locale != NULL ) delete m_Locale; m_Locale = new wxLocale(); m_Locale->Init(m_LanguageId); dic_path = ReturnKicadDatasPath() + BaseDictionaryPath; m_Locale->AddCatalogLookupPathPrefix(dic_path); if ( ! first_time ) { if ( m_EDA_CommonConfig ) m_EDA_CommonConfig->Write( wxT("Language"), m_LanguageId); } if ( ! m_Locale->IsLoaded(DictionaryName) ) m_Locale->AddCatalog(DictionaryName); SetLanguageList(NULL); if ( atof("0,1") ) g_FloatSeparator = ','; // Nombres flottants = 0,1 else g_FloatSeparator = '.'; return m_Locale->IsOk(); } /**************************************************/ void WinEDA_App::SetLanguageIdentifier(int menu_id) /**************************************************/ /* return in m_LanguageId the language id (wxWidgets language identifier) from menu id (internal menu identifier) */ { switch (menu_id) { case ID_LANGUAGE_ITALIAN: m_LanguageId = wxLANGUAGE_ITALIAN; break; case ID_LANGUAGE_PORTUGUESE: m_LanguageId = wxLANGUAGE_PORTUGUESE; break; case ID_LANGUAGE_RUSSIAN: m_LanguageId = wxLANGUAGE_RUSSIAN; break; case ID_LANGUAGE_DUTCH: m_LanguageId = wxLANGUAGE_DUTCH; break; case ID_LANGUAGE_SPANISH: m_LanguageId = wxLANGUAGE_SPANISH; break; case ID_LANGUAGE_ENGLISH: m_LanguageId = wxLANGUAGE_ENGLISH; break; case ID_LANGUAGE_FRENCH: m_LanguageId = wxLANGUAGE_FRENCH; break; case ID_LANGUAGE_SLOVENIAN: m_LanguageId = wxLANGUAGE_SLOVENIAN; break; case ID_LANGUAGE_HUNGARIAN: m_LanguageId = wxLANGUAGE_HUNGARIAN ; break; default: m_LanguageId = wxLANGUAGE_DEFAULT; break; } } /*********************************************************/ wxMenu * WinEDA_App::SetLanguageList(wxMenu * MasterMenu) /*********************************************************/ /* Create menu list for language choice. */ { wxMenuItem * item; if ( m_Language_Menu == NULL ) { m_Language_Menu = new wxMenu; item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_DEFAULT, _("Default"), wxEmptyString, wxITEM_CHECK ); SETBITMAPS(lang_def_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_ENGLISH, wxT("English"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_en_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_FRENCH, _("French"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_fr_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_SPANISH, _("Spanish"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_es_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_PORTUGUESE, _("Portuguese"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_pt_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_ITALIAN, _("Italian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_it_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_DUTCH, _("Dutch"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_de_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_SLOVENIAN, _("Slovenian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_sl_xpm); m_Language_Menu->Append(item); item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_HUNGARIAN, _("Hungarian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_hu_xpm); m_Language_Menu->Append(item); #if 0 item = new wxMenuItem(m_Language_Menu, ID_LANGUAGE_RUSSIAN, _("Russian"), wxEmptyString, wxITEM_CHECK); SETBITMAPS(lang_ru_xpm); m_Language_Menu->Append(item); #endif } m_Language_Menu->Check(ID_LANGUAGE_HUNGARIAN, FALSE); m_Language_Menu->Check(ID_LANGUAGE_SLOVENIAN, FALSE); m_Language_Menu->Check(ID_LANGUAGE_ITALIAN, FALSE); m_Language_Menu->Check(ID_LANGUAGE_PORTUGUESE, FALSE); m_Language_Menu->Check(ID_LANGUAGE_DUTCH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_SPANISH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_FRENCH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_ENGLISH, FALSE); m_Language_Menu->Check(ID_LANGUAGE_DEFAULT, FALSE); switch ( m_LanguageId ) { case wxLANGUAGE_RUSSIAN: m_Language_Menu->Check(ID_LANGUAGE_RUSSIAN, TRUE); break; case wxLANGUAGE_DUTCH: m_Language_Menu->Check(ID_LANGUAGE_DUTCH, TRUE); break; case wxLANGUAGE_FRENCH: m_Language_Menu->Check(ID_LANGUAGE_FRENCH, TRUE); break; case wxLANGUAGE_ENGLISH: m_Language_Menu->Check(ID_LANGUAGE_ENGLISH, TRUE); break; case wxLANGUAGE_SPANISH: m_Language_Menu->Check(ID_LANGUAGE_SPANISH, TRUE); break; case wxLANGUAGE_PORTUGUESE: m_Language_Menu->Check(ID_LANGUAGE_PORTUGUESE, TRUE); break; case wxLANGUAGE_ITALIAN: m_Language_Menu->Check(ID_LANGUAGE_ITALIAN, TRUE); break; case wxLANGUAGE_SLOVENIAN: m_Language_Menu->Check(ID_LANGUAGE_SLOVENIAN, TRUE); case wxLANGUAGE_HUNGARIAN: m_Language_Menu->Check(ID_LANGUAGE_SLOVENIAN, TRUE); break; default: m_Language_Menu->Check(ID_LANGUAGE_DEFAULT, TRUE); break; } if ( MasterMenu ) { ADD_MENUITEM_WITH_HELP_AND_SUBMENU(MasterMenu, m_Language_Menu, ID_LANGUAGE_CHOICE, _("Language"), wxT("For test only, use Default setup for normal use"), language_xpm); } return m_Language_Menu; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 563 ] ] ]
cff1248d0eec9e739fe0135b13fb77dc93b8b95b
97f1be9ac088e1c9d3fd73d76c63fc2c4e28749a
/3dc/avp/win95/AvpReg.cpp
3edd58e6dbd38a2a864acdb03c54c028287f5826
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
SR-dude/AvP-Wine
2875f7fd6b7914d03d7f58e8f0ec4793f971ad23
41a9c69a45aacc2c345570ba0e37ec3dc89f4efa
refs/heads/master
2021-01-23T02:54:33.593334
2011-09-17T11:10:07
2011-09-17T11:10:07
2,375,686
1
0
null
null
null
null
UTF-8
C++
false
false
1,669
cpp
#include <windows.h> #include <stdio.h> #include "avpreg.hpp" extern "C" { char* AvpCDPath=0; extern char const * SecondTex_Directory; extern char * SecondSoundDir; void GetPathFromRegistry() { HKEY hKey; if(AvpCDPath) { delete AvpCDPath; AvpCDPath=0; } if ( ERROR_SUCCESS == RegOpenKeyEx ( HKEY_LOCAL_MACHINE, "Software\\Fox Interactive\\Aliens vs Predator\\1.00", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, &hKey ) ) { char szBuf[MAX_PATH+1]; DWORD dwType = REG_NONE; DWORD dwSize = sizeof szBuf; if ( ERROR_SUCCESS == RegQueryValueEx ( hKey, const_cast<char *>("Source Path"), 0, &dwType, reinterpret_cast<LPBYTE>(szBuf), &dwSize ) && REG_SZ == dwType ) { int length=strlen(szBuf); if(length) { AvpCDPath=new char[length+1]; strcpy(AvpCDPath,szBuf); } } RegCloseKey(hKey); } //now set second texture directory if(!SecondTex_Directory) { char* directory; if(AvpCDPath) { directory=new char[strlen(AvpCDPath)+10]; sprintf(directory,"%sGraphics",AvpCDPath); } else { directory=new char[40]; strcpy(directory,"\\\\bob\\textures\\avp_graphics"); } *(char**)&SecondTex_Directory=directory; } //and the second sound directory if(!SecondSoundDir) { char* directory; if(AvpCDPath) { directory=new char[strlen(AvpCDPath)+20]; sprintf(directory,"%ssound\\",AvpCDPath); } else { directory=new char[40]; strcpy(directory,"\\\\bob\\vss\\avp\\sound\\"); } SecondSoundDir=directory; } } };
[ "a_jagers@ANTHONYJ.(none)" ]
[ [ [ 1, 100 ] ] ]
8e21dc7530afe68fdd8a068ad4eb0afc4ea847af
c436a5d7cdbebc04e5d202c6bb3c83448a5db529
/QtOgre/source/GraphicsSettingsWidget.cpp
99342f2f7bb46aaf1a8dcd276c57e36151b7764d
[ "Zlib" ]
permissive
pvdk/QtOgreFramework
89132be5c0ea4f11a43abf4632577ebb21a0b10a
e32bafae2b0c1a8af9700efea61ff351866bb1d5
refs/heads/master
2021-01-23T08:15:38.575879
2010-11-15T21:39:06
2010-11-15T21:39:06
1,680,419
0
1
null
null
null
null
UTF-8
C++
false
false
3,570
cpp
#include "GraphicsSettingsWidget.h" #include "Application.h" #include <QSettings> namespace QtOgre { GraphicsSettingsWidget::GraphicsSettingsWidget(QWidget *parent) :AbstractSettingsWidget(parent) { setupUi(this); } void GraphicsSettingsWidget::disableFirstTimeOnlySettings(void) { mOpenGLRadioButton->setEnabled(false); mDirect3D9RadioButton->setEnabled(false); mAllowPerfHUDCheckBox->setEnabled(false); mEnableGammaCorrectionCheckBox->setEnabled(false); mFSSAFactorSpinBox->setEnabled(false); mFSSAFactorLabel->setEnabled(false); mEnableVerticalSyncCheckBox->setEnabled(false); } void GraphicsSettingsWidget::readFromSettings(void) { // ---------- Render System Settings ---------- mOpenGLRadioButton->setEnabled(qApp->isOpenGLAvailable()); mDirect3D9RadioButton->setEnabled(qApp->isDirect3D9Available()); QString renderSystem = mSettings->value("Graphics/RenderSystem").toString(); //Doing OpenGL last here means that is it is the default. mDirect3D9RadioButton->setChecked(mDirect3D9RadioButton->isEnabled() && (renderSystem.compare("Direct3D9 Rendering Subsystem") == 0)); mOpenGLRadioButton->setChecked(mOpenGLRadioButton->isEnabled() && (renderSystem.compare("OpenGL Rendering Subsystem") == 0)); // ---------- Window Settings ---------- QStringList windowModes = mSettings->value("Graphics/WindowModes").toStringList(); int selectedWindowMode = mSettings->value("Graphics/SelectedWindowMode", 0).toInt(); if(windowModes.size() > selectedWindowMode) //Make sure it's a valid index. { mWindowModeComboBox->insertItems(0, windowModes); mWindowModeComboBox->setCurrentIndex(selectedWindowMode); } // ---------- Advanced Settings ---------- mAllowPerfHUDCheckBox->setChecked(mSettings->value("Graphics/AllowPerfHUD", false).toBool()); mEnableGammaCorrectionCheckBox->setChecked(mSettings->value("Graphics/EnableGammaCorrection", false).toBool()); mFSSAFactorSpinBox->setValue(mSettings->value("Graphics/FSSAFactor", 0).toInt()); mEnableVerticalSyncCheckBox->setChecked(mSettings->value("Graphics/EnableVerticalSync", false).toBool()); } void GraphicsSettingsWidget::writeToSettings(void) { // ---------- Render System Settings ---------- if(mOpenGLRadioButton->isChecked()) { mSettings->setValue("Graphics/RenderSystem", "OpenGL Rendering Subsystem"); } else if(mDirect3D9RadioButton->isChecked()) { mSettings->setValue("Graphics/RenderSystem", "Direct3D9 Rendering Subsystem"); } else { //This can happen if neither render system is available, although we should have been warned earlier? Application::showErrorMessageBox("A valid render system has not been selected"); } // ---------- Window Settings ---------- mSettings->setValue("Graphics/SelectedWindowMode", mWindowModeComboBox->currentIndex()); //Advanced Settings mSettings->setValue("Graphics/AllowPerfHUD", mAllowPerfHUDCheckBox->isChecked()); mSettings->setValue("Graphics/EnableGammaCorrection", mEnableGammaCorrectionCheckBox->isChecked()); mSettings->setValue("Graphics/FSSAFactor", mFSSAFactorSpinBox->value()); mSettings->setValue("Graphics/EnableVerticalSync", mEnableVerticalSyncCheckBox->isChecked()); } void GraphicsSettingsWidget::on_mDirect3D9RadioButton_toggled(bool checked) { //PerfHUD is only available when using the Direct3D9 render system mAllowPerfHUDCheckBox->setEnabled(checked); if(!checked) { mAllowPerfHUDCheckBox->setChecked(false); } } }
[ "esuvs@2eb06014-c84b-0410-ad17-af83cdd4cbf1", "kardoon@2eb06014-c84b-0410-ad17-af83cdd4cbf1" ]
[ [ [ 1, 4 ], [ 7, 90 ] ], [ [ 5, 6 ], [ 91, 91 ] ] ]
e0ceab72cdbee518ad5cad862f860c31bd2ba795
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/statechart/test/TuTest.cpp
715eb7dc83fd307df20511fcb8d0dc93134bb58e
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
911
cpp
////////////////////////////////////////////////////////////////////////////// // Copyright 2005-2006 Andreas Huber Doenni // Distributed under the Boost Software License, Version 1.0. (See accompany- // ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ////////////////////////////////////////////////////////////////////////////// #include "TuTest.hpp" #include <boost/statechart/simple_state.hpp> #include <boost/statechart/in_state_reaction.hpp> #include <stdexcept> struct Initial : sc::simple_state< Initial, TuTest > { void Whatever( const EvX & ) {} typedef sc::in_state_reaction< EvX, Initial, &Initial::Whatever > reactions; }; void TuTest::initiate() { sc::state_machine< TuTest, Initial >::initiate(); } void TuTest::unconsumed_event( const sc::event_base & ) { throw std::runtime_error( "Event was not consumed!" ); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 35 ] ] ]
c4f92b1d0598e67e8a41e66be9fe64f5cd726999
3e69b159d352a57a48bc483cb8ca802b49679d65
/tags/release-2005-12-22/eeschema/dangling_ends.cpp
d92d9cbdeca971f638c12a5f341f3ea4953f2cf8
[]
no_license
BackupTheBerlios/kicad-svn
4b79bc0af39d6e5cb0f07556eb781a83e8a464b9
4c97bbde4b1b12ec5616a57c17298c77a9790398
refs/heads/master
2021-01-01T19:38:40.000652
2006-06-19T20:01:24
2006-06-19T20:01:24
40,799,911
0
0
null
null
null
null
ISO-8859-1
C++
false
false
11,577
cpp
/*********************/ /* dangling_ends.cpp */ /*********************/ #include "fctsys.h" #include "gr_basic.h" #include "common.h" #include "program.h" #include "libcmp.h" #include "general.h" #include "netlist.h" /* Definitions generales liees au calcul de netliste */ #include "protos.h" enum End_Type { UNKNOWN = 0, WIRE_START_END, WIRE_END_END, BUS_START_END, BUS_END_END, JUNCTION_END, PIN_END, LABEL_END, ENTRY_END, SHEET_LABEL_END }; class DanglingEndHandle { public: const void * m_Item; wxPoint m_Pos; int m_Type; DanglingEndHandle * m_Pnext; DanglingEndHandle(int type) { m_Item = NULL; m_Type = type; m_Pnext = NULL; } }; DanglingEndHandle * ItemList; static void TestWireForDangling(EDA_DrawLineStruct * DrawRef, WinEDA_SchematicFrame * frame, wxDC * DC); void TestLabelForDangling(DrawTextStruct * label, WinEDA_SchematicFrame * frame, wxDC * DC); DanglingEndHandle * RebuildEndList(EDA_BaseStruct *DrawList); /**********************************************************/ bool SegmentIntersect(int Sx1, int Sy1, int Sx2, int Sy2, int Px1, int Py1) /**********************************************************/ /* Retourne TRUE si le point P est sur le segment S. Le segment est suppose horizontal ou vertical. */ { int Sxmin, Sxmax, Symin, Symax; if (Sx1 == Sx2) /* Line S is vertical. */ { Symin = MIN(Sy1, Sy2); Symax = MAX(Sy1, Sy2); if (Px1 != Sx1) return FALSE; if (Py1 >= Symin && Py1 <= Symax) return TRUE; else return FALSE; } else if (Sy1 == Sy2) /* Line S is horizontal. */ { Sxmin = MIN(Sx1, Sx2); Sxmax = MAX(Sx1, Sx2); if (Py1 != Sy1) return FALSE; if (Px1 >= Sxmin && Px1 <= Sxmax) return TRUE; else return FALSE; } else return FALSE; // Segments quelconques } /******************************************************************************/ void WinEDA_SchematicFrame::TestDanglingEnds(EDA_BaseStruct *DrawList, wxDC *DC) /******************************************************************************/ /* Met a jour les membres m_Dangling des wires, bus, labels */ { EDA_BaseStruct * DrawItem; const DanglingEndHandle * DanglingItem, * nextitem; if ( ItemList ) for ( DanglingItem = ItemList; DanglingItem != NULL; DanglingItem = nextitem) { nextitem = DanglingItem->m_Pnext; delete DanglingItem; } ItemList = RebuildEndList(DrawList); // Controle des elements for ( DrawItem = DrawList; DrawItem != NULL; DrawItem= DrawItem->Pnext) { switch( DrawItem->m_StructType ) { case DRAW_GLOBAL_LABEL_STRUCT_TYPE: case DRAW_LABEL_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawLabelStruct*)DrawItem) TestLabelForDangling(STRUCT, this, DC); break; break; case DRAW_SEGMENT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((EDA_DrawLineStruct*)DrawItem) if( STRUCT->m_Layer == LAYER_WIRE) { TestWireForDangling(STRUCT, this, DC); break; } if( STRUCT->m_Layer == LAYER_NOTES) break; if( STRUCT->m_Layer == LAYER_BUS) { STRUCT->m_StartIsDangling = STRUCT->m_EndIsDangling = FALSE; break; } break; } } } /********************************************************************/ LibDrawPin * WinEDA_SchematicFrame::LocatePinEnd(EDA_BaseStruct *DrawList, const wxPoint & pos) /********************************************************************/ /* Teste si le point de coordonnées pos est sur l'extrémité d'une PIN retourne un pointeur sur la pin NULL sinon */ { EDA_SchComponentStruct * DrawLibItem; LibDrawPin * Pin; wxPoint pinpos; Pin = LocateAnyPin(DrawList,pos, &DrawLibItem); if( ! Pin ) return NULL; pinpos = Pin->m_Pos; if(DrawLibItem == NULL ) pinpos.y = -pinpos.y; else { int x1 = pinpos.x, y1 = pinpos.y; pinpos.x = DrawLibItem->m_Pos.x + DrawLibItem->m_Transform[0][0] * x1 + DrawLibItem->m_Transform[0][1] * y1; pinpos.y = DrawLibItem->m_Pos.y + DrawLibItem->m_Transform[1][0] * x1 + DrawLibItem->m_Transform[1][1] * y1; } if( (pos.x == pinpos.x) && (pos.y == pinpos.y) ) return Pin; return NULL; } /****************************************************************************/ void TestWireForDangling(EDA_DrawLineStruct * DrawRef, WinEDA_SchematicFrame * frame, wxDC * DC) /****************************************************************************/ { DanglingEndHandle * terminal_item; bool Sdangstate = TRUE, Edangstate = TRUE; for ( terminal_item = ItemList; terminal_item != NULL; terminal_item = terminal_item->m_Pnext) { if ( terminal_item->m_Item == DrawRef ) continue; if ( (DrawRef->m_Start.x == terminal_item->m_Pos.x) && (DrawRef->m_Start.y == terminal_item->m_Pos.y) ) Sdangstate = FALSE; if ( (DrawRef->m_End.x == terminal_item->m_Pos.x) && (DrawRef->m_End.y == terminal_item->m_Pos.y) ) Edangstate = FALSE; if ( (Sdangstate == FALSE) && (Edangstate == FALSE) ) break; } if ( (Sdangstate != DrawRef->m_StartIsDangling) || (Edangstate != DrawRef->m_EndIsDangling) ) { if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, DrawRef, XOR_MODE); DrawRef->m_StartIsDangling = Sdangstate; DrawRef->m_EndIsDangling = Edangstate; if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, DrawRef, GR_DEFAULT_DRAWMODE); } } /********************************************************/ void TestLabelForDangling(DrawTextStruct * label, WinEDA_SchematicFrame * frame, wxDC * DC) /********************************************************/ { DanglingEndHandle * terminal_item; bool dangstate = TRUE; for ( terminal_item = ItemList; terminal_item != NULL; terminal_item = terminal_item->m_Pnext) { if ( terminal_item->m_Item == label ) continue; switch( terminal_item->m_Type ) { case PIN_END: case LABEL_END: case SHEET_LABEL_END: if ( (label->m_Pos.x == terminal_item->m_Pos.x) && (label->m_Pos.y == terminal_item->m_Pos.y) ) dangstate = FALSE; break; case WIRE_START_END: case BUS_START_END: dangstate = ! SegmentIntersect(terminal_item->m_Pos.x, terminal_item->m_Pos.y, terminal_item->m_Pnext->m_Pos.x, terminal_item->m_Pnext->m_Pos.y, label->m_Pos.x, label->m_Pos.y); terminal_item = terminal_item->m_Pnext; break; case UNKNOWN: case JUNCTION_END: case ENTRY_END: case WIRE_END_END: case BUS_END_END: break; } if (dangstate == FALSE) break; } if ( dangstate != label->m_IsDangling ) { if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, label, XOR_MODE); label->m_IsDangling = dangstate; if ( DC ) RedrawOneStruct(frame->DrawPanel,DC, label, GR_DEFAULT_DRAWMODE); } } /****************************************************/ wxPoint ReturnPinPhysicalPosition( LibDrawPin * Pin, EDA_SchComponentStruct * DrawLibItem) /****************************************************/ /* Retourne la position physique de la pin, qui dépend de l'orientation du composant */ { wxPoint PinPos = Pin->m_Pos; if(DrawLibItem == NULL ) PinPos.y = -PinPos.y; else { int x = Pin->m_Pos.x, y = Pin->m_Pos.y; PinPos.x = DrawLibItem->m_Pos.x + DrawLibItem->m_Transform[0][0] * x + DrawLibItem->m_Transform[0][1] * y; PinPos.y = DrawLibItem->m_Pos.y + DrawLibItem->m_Transform[1][0] * x + DrawLibItem->m_Transform[1][1] * y; } return PinPos; } /***********************************************************/ DanglingEndHandle * RebuildEndList(EDA_BaseStruct *DrawList) /***********************************************************/ { DanglingEndHandle * StartList = NULL, *item, *lastitem = NULL; EDA_BaseStruct * DrawItem; for ( DrawItem = DrawList; DrawItem != NULL; DrawItem = DrawItem->Pnext) { switch( DrawItem->m_StructType ) { case DRAW_LABEL_STRUCT_TYPE: break; case DRAW_GLOBAL_LABEL_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawGlobalLabelStruct*)DrawItem) item = new DanglingEndHandle(LABEL_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; break; case DRAW_SEGMENT_STRUCT_TYPE: #undef STRUCT #define STRUCT ((EDA_DrawLineStruct*)DrawItem) if( STRUCT->m_Layer == LAYER_NOTES ) break; if( (STRUCT->m_Layer == LAYER_BUS) || (STRUCT->m_Layer == LAYER_WIRE) ) { item = new DanglingEndHandle((STRUCT->m_Layer == LAYER_BUS) ? BUS_START_END : WIRE_START_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Start; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; item = new DanglingEndHandle((STRUCT->m_Layer == LAYER_BUS) ? BUS_END_END : WIRE_END_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_End; lastitem->m_Pnext = item; lastitem = item; } break; case DRAW_JUNCTION_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawJunctionStruct*)DrawItem) item = new DanglingEndHandle(JUNCTION_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; break; case DRAW_BUSENTRY_STRUCT_TYPE: #undef STRUCT #define STRUCT ((DrawBusEntryStruct*)DrawItem) item = new DanglingEndHandle(ENTRY_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; item = new DanglingEndHandle(ENTRY_END); item->m_Item = DrawItem; item->m_Pos = STRUCT->m_End(); lastitem->m_Pnext = item; lastitem = item; break; case DRAW_LIB_ITEM_STRUCT_TYPE: { #undef STRUCT #define STRUCT ((EDA_SchComponentStruct*)DrawItem) EDA_LibComponentStruct * Entry; Entry = FindLibPart( STRUCT->m_ChipName, wxEmptyString, FIND_ROOT); if( Entry == NULL ) break; LibEDA_BaseStruct * DrawLibItem = Entry->m_Drawings; for ( ; DrawLibItem != NULL; DrawLibItem = DrawLibItem->Next()) { if(DrawLibItem->m_StructType != COMPONENT_PIN_DRAW_TYPE) continue; LibDrawPin * Pin = (LibDrawPin *) DrawLibItem; if( Pin->m_Unit && DrawLibItem->m_Unit && (DrawLibItem->m_Unit != Pin->m_Unit) ) continue; if( Pin->m_Convert && DrawLibItem->m_Convert && (DrawLibItem->m_Convert != Pin->m_Convert) ) continue; item = new DanglingEndHandle(PIN_END); item->m_Item = Pin; item->m_Pos = ReturnPinPhysicalPosition( Pin,STRUCT); if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; } break; } case DRAW_SHEET_STRUCT_TYPE: { #undef STRUCT #define STRUCT ((DrawSheetStruct*)DrawItem) DrawSheetLabelStruct * pinsheet = STRUCT->m_Label; while(pinsheet) { item = new DanglingEndHandle(SHEET_LABEL_END); item->m_Item = pinsheet; item->m_Pos = pinsheet->m_Pos; if ( lastitem ) lastitem->m_Pnext = item; else StartList = item; lastitem = item; pinsheet = (DrawSheetLabelStruct*)pinsheet->Pnext; } break; } } } return StartList; }
[ "bokeoa@244deca0-f506-0410-ab94-f4f3571dea26" ]
[ [ [ 1, 409 ] ] ]
90f4dd807c1bf020ebf40465af5ba9f01a2edcaf
a973de8deb092f2cd88282154467b59883344486
/SPlayer/tags/id3/writer.h
b9caaecc8a9fe8d7707375325af9fa8f1d0ab26f
[]
no_license
daemongloom/bldgan
4a56432c964cbfcdec8557ceefd1eda5c03d4640
862677cc83b705c13b44de359973a1fc2315eaa4
refs/heads/master
2020-01-21T03:42:41.043408
2009-01-05T06:52:41
2009-01-05T06:52:41
32,198,688
0
0
null
null
null
null
UTF-8
C++
false
false
3,659
h
// -*- C++ -*- // $Id: writer.h,v 1.8 2002/07/02 22:11:10 t1mpy Exp $ // id3lib: a software library for creating and manipulating id3v1/v2 tags // Copyright 1999, 2000 Scott Thomas Haug // This library is free software; you can redistribute it and/or modify it // under the terms of the GNU Library General Public License as published by // the Free Software Foundation; either version 2 of the License, or (at your // option) any later version. // // This library is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public // License for more details. // // You should have received a copy of the GNU Library General Public License // along with this library; if not, write to the Free Software Foundation, // Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // The id3lib authors encourage improvements and optimisations to be sent to // the id3lib coordinator. Please see the README file for details on where to // send such submissions. See the AUTHORS file for a list of people who have // contributed to id3lib. See the ChangeLog file for a list of changes to // id3lib. These files are distributed with id3lib at // http://download.sourceforge.net/id3lib/ #ifndef _ID3LIB_WRITER_H_ #define _ID3LIB_WRITER_H_ #include "id3/globals.h" //has <stdlib.h> "id3/sized_types.h" class ID3_CPP_EXPORT ID3_Writer { public: typedef uint32 size_type; typedef uint8 char_type; typedef uint32 pos_type; typedef int32 off_type; typedef int16 int_type; static const int_type END_OF_WRITER; /** Close the writer. Any further actions on the writer should fail. **/ virtual void close() = 0; /** Flush the writer. **/ virtual void flush() = 0; /** Return the beginning position in the writer **/ virtual pos_type getBeg() { return static_cast<pos_type>(0); } /** Return the first position that can't be written to. A return value of ** -1 indicates no (reasonable) limit to the writer. **/ virtual pos_type getEnd() { return static_cast<pos_type>(-1); } /** Return the next position that will be written to */ virtual pos_type getCur() = 0; /** Return the number of bytes written **/ virtual size_type getSize() { return this->getCur() - this->getBeg(); } /** Return the maximum number of bytes that can be written **/ virtual size_type getMaxSize() { return this->getEnd() - this->getBeg(); } /** Write a single character and advance the internal position. Note that ** the interal position may advance more than one byte for a single ** character write. Returns END_OF_WRITER if there isn't a character to ** write. **/ virtual int_type writeChar(char_type ch) { if (this->atEnd()) { return END_OF_WRITER; } this->writeChars(&ch, 1); return ch; } /** Write up to \c len characters into buf and advance the internal position ** accordingly. Returns the number of characters write into buf. Note that ** the value returned may be less than the number of bytes that the internal ** position advances, due to multi-byte characters. **/ virtual size_type writeChars(const char_type buf[], size_type len) = 0; virtual size_type writeChars(const char buf[], size_type len) { return this->writeChars(reinterpret_cast<const char_type *>(buf), len); } virtual bool atEnd() { return this->getCur() >= this->getEnd(); } }; #endif /* _ID3LIB_WRITER_H_ */
[ [ [ 1, 98 ] ] ]
44328023bb2f33c1933bdb7139e2f7a4df0e9b88
c1a2953285f2a6ac7d903059b7ea6480a7e2228e
/deitel/ch04/Ex04_05/ex04_05.cpp
8fee31f5876f0b965da7202137e564a918b59e77
[]
no_license
tecmilenio/computacion2
728ac47299c1a4066b6140cebc9668bf1121053a
a1387e0f7f11c767574fcba608d94e5d61b7f36c
refs/heads/master
2016-09-06T19:17:29.842053
2008-09-28T04:27:56
2008-09-28T04:27:56
50,540
4
3
null
null
null
null
UTF-8
C++
false
false
1,612
cpp
// Exercise 4.5 Solution: ex04_05.cpp // Calculate the sum of the integers from 1 to 10. #include <iostream> using std::cout; using std::endl; int main() { int sum; // stores sum of integers 1 to 10 int x; // counter x = 1; // count from 1 sum = 0; // initialize sum while ( x <= 10 ) // loop 10 times { sum += x; // add x to sum ++x; // increment x } // end while cout << "The sum is: " << sum << endl; return 0; // indicate successful termination } // end main /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
[ [ [ 1, 39 ] ] ]
7d4eb8a17f88943edc67aefdfaea48a3dfce6928
e66af70846aa964441407290c0bdae324a49dad2
/opencollada/common/libBuffer/include/CommonFWriteBufferFlusher.h
aee6542694046c6d7f180d6469d0ac313acab5b5
[ "MIT" ]
permissive
hyperlogic/q3bsp2dae
53263ed6a53fc29bb48750be4ec17c89a048de49
c206390bc9d26adecc20b7cfc2365627df97ffc6
refs/heads/master
2021-01-19T03:13:14.506277
2011-12-07T05:38:12
2011-12-07T05:38:12
2,908,802
0
0
null
null
null
null
UTF-8
C++
false
false
2,666
h
/* Copyright (c) 2009 NetAllied Systems GmbH This file is part of Common libBuffer. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COMMON_FWRITEBUFFERFLUSHER_H__ #define __COMMON_FWRITEBUFFERFLUSHER_H__ #include "CommonIBufferFlusher.h" #if (defined(WIN64) || defined(_WIN64) || defined(__WIN64__)) || (defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)) # include <unordered_map> #else # include <tr1/unordered_map> #endif /* size_t for gcc, may want to move this include some place else - campbell */ #ifdef __GNUC__ # include <cstdlib> /* size_t */ # include <cstdio> /* FILE */ #endif #if (defined(__GNUC__) && !defined(__STRICT_ANSI__)) || (__STDC_VERSION__ >= 199901L) typedef int64_t __int64; #endif namespace Common { class FWriteBufferFlusher : public IBufferFlusher { private: typedef __int64 FilePosType; typedef std::tr1::unordered_map<MarkId, FilePosType > MarkIdToFilePos; public: static const size_t DEFAUL_BUFFER_SIZE = 64*1024; private: /** The buffer size of the stream.*/ size_t mBufferSize; /** The buffer of the stream.*/ char *mBuffer; /** The stream to write the data to.*/ FILE* mStream; /** The error code of fopen_s.*/ int mError; MarkId mLastMarkId; MarkIdToFilePos mMarkIds; public: FWriteBufferFlusher( const char* fileName, size_t bufferSize = DEFAUL_BUFFER_SIZE, const char* mode="wb" ); FWriteBufferFlusher( const wchar_t* fileName, size_t bufferSize = DEFAUL_BUFFER_SIZE, const wchar_t* mode=L"wb" ); virtual ~FWriteBufferFlusher(); /** The error code of fopen_s.*/ int getError() const { return mError; } /** Receives and handles @a length bytes starting at @a buffer. @return True on success, false otherwise.*/ virtual bool receiveData( const char* buffer, size_t length); /** Flushes all the data previously received by receiveData.*/ virtual bool flush(); /** Internal method that @return FILE* */ FILE* _getFileHandle() const { return mStream; } void startMark(); IBufferFlusher::MarkId endMark(); bool jumpToMark(IBufferFlusher::MarkId markId, bool keepMarkId = false); private: /** Disable default copy ctor. */ FWriteBufferFlusher( const FWriteBufferFlusher& pre ); /** Disable default assignment operator. */ const FWriteBufferFlusher& operator= ( const FWriteBufferFlusher& pre ); }; } // namespace COMMON #endif // __COMMON_FWRITEBUFFERFLUSHER_H__
[ [ [ 1, 93 ] ] ]
d831640bfe87f45f8ca200d121b37bb5cfb75a76
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ClientShellDLL/ClientShellShared/FastList.h
1c07a2c44df987c258f768ca0e319fec66635cb2
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
12,115
h
//---------------------------------------------------------- // // MODULE : FASTLIST.H // // PUROSE : CFastList definition file // // CREATED : 10 / 27 / 1996 // //---------------------------------------------------------- #ifndef __FASTLIST_H_ #define __FASTLIST_H_ // Includes.... template <class T> struct CFastListNode { public: // Constructor CFastListNode() { m_pPrev = NULL; m_pNext = NULL; } // Accessors CFastListNode* GetPrev() { return m_pPrev; } CFastListNode* GetNext() { return m_pNext; } T GetData() { return m_Data; } CFastListNode *m_pPrev; CFastListNode *m_pNext; T m_Data; }; template <class T> class CFastList { public: // Constructor CFastList(); CFastList(int nTotalElem); // Destructor ~CFastList() { Term(); } // Member Functions void Term(BOOL bDeAlloc = TRUE); BOOL AddHead(T data); BOOL AddTail(T data); BOOL InsertAfter(CFastListNode<T> *pNode, T data); BOOL InsertBefore(CFastListNode<T> *pNode, T data); T RemoveHead(); T RemoveTail(); void Remove(CFastListNode<T> *pNode); void Remove(T data); void RemoveAll() { Term(); } CFastListNode<T>* Find(T data); T Get(DWORD dwIndex); int GetIndex(T data); // Accessors CFastListNode<T>* GetBlock() { return m_pBlock; } CFastListNode<T>* GetHead() { return m_pHead; } CFastListNode<T>* GetTail() { return m_pTail; } DWORD GetSize() { return m_nSize; } private: // Member Functions void AllocMem(int nTotalElem); // Member Variables CFastListNode<T> *m_pBlock; CFastListNode<T> *m_pFreeList; CFastListNode<T> *m_pHead; CFastListNode<T> *m_pTail; DWORD m_nSize; DWORD m_nTotalElem; BOOL m_bAllocated; }; //---------------------------------------------------------- // // FUNCTION : CFastList() // // PURPOSE : Standard constructor // //---------------------------------------------------------- template <class T> inline CFastList<T>::CFastList() { m_pBlock = NULL; m_pHead = NULL; m_pTail = NULL; m_nSize = 0; // Allocate the memory AllocMem(100); } //---------------------------------------------------------- // // FUNCTION : CFastList() // // PURPOSE : Standard constructor // //---------------------------------------------------------- template <class T> inline CFastList<T>::CFastList(int nTotalElem) { m_pBlock = NULL; m_pHead = NULL; m_pTail = NULL; m_nSize = 0; // Allocate the memory AllocMem(nTotalElem); } //---------------------------------------------------------- // // FUNCTION : CFastList::Term() // // PURPOSE : Terminates a CFastList // //---------------------------------------------------------- template <class T> inline void CFastList<T>::Term(BOOL bDeAlloc) { if (m_pBlock) debug_deletea(m_pBlock); m_pBlock = NULL; m_pHead = NULL; m_pTail = NULL; m_pFreeList = NULL; m_nSize = 0; if (!bDeAlloc) AllocMem(m_nTotalElem); } //---------------------------------------------------------- // // FUNCTION : CFastList::AddHead() // // PURPOSE : Adds an element to the head of the array // //---------------------------------------------------------- template <class T> inline BOOL CFastList<T>::AddHead(T data) { if (!m_pHead) { m_pHead = debug_new(CFastListNode); if (!m_pRoot) return FALSE; m_pHead->m_Data = data; if (!m_pTail) m_pTail = m_pHead; } else { CFastListNode *pNewNode = debug_new(CFastListNode); if (!pNewNode) return FALSE; m_pHead->m_pPrev = pNewNode; pNewNode->m_pNext = m_pHead; pNewNode->m_Data = data; m_pHead = pNewNode; } m_nSize ++; // Success !! return TRUE; } //---------------------------------------------------------- // // FUNCTION : CFastList::AddTail() // // PURPOSE : Adds an element to the tail of the array // //---------------------------------------------------------- template <class T> inline BOOL CFastList<T>::AddTail(T data) { if (!m_pTail) { m_pTail = m_pFreeList; if (!m_pTail) return FALSE; m_pFreeList = m_pFreeList->m_pNext; m_pFreeList->m_pPrev = NULL; m_pTail->m_pPrev = NULL; m_pTail->m_pNext = NULL; m_pTail->m_Data = data; if (!m_pHead) m_pHead = m_pTail; } else { CFastListNode<T> *pNewNode = m_pFreeList; if (!pNewNode) return FALSE; m_pFreeList = m_pFreeList->m_pNext; m_pFreeList->m_pPrev = NULL; pNewNode->m_pPrev = NULL; pNewNode->m_pNext = NULL; m_pTail->m_pNext = pNewNode; pNewNode->m_pPrev = m_pTail; pNewNode->m_Data = data; m_pTail = pNewNode; } m_nSize ++; // Success !! return TRUE; } //---------------------------------------------------------- // // FUNCTION : CFastList::InsertAfter() // // PURPOSE : Inserts an element into the list // //---------------------------------------------------------- template <class T> inline BOOL CFastList<T>::InsertAfter(CFastListNode<T> *pNode, T data) { CFastListNode<T> *pNewNode = m_pFreeList; if (!pNewNode) return FALSE; m_pFreeList = m_pFreeList->m_pNext; m_pFreeList->m_pPrev = NULL; pNewNode->m_pNext = NULL; pNewNode->m_pPrev = NULL; // Copy in data pNewNode->m_Data = data; pNewNode->m_pPrev = pNode; if (pNode->m_pNext) { pNewNode->m_pNext = pNode->m_pNext; pNode->m_pNext->m_pPrev = pNewNode; } else { m_pTail = pNewNode; } pNode->m_pNext = pNewNode; m_nSize ++; // Success !! return TRUE; } //---------------------------------------------------------- // // FUNCTION : CFastList::InsertBefore() // // PURPOSE : Inserts an element into the list // //---------------------------------------------------------- template <class T> inline BOOL CFastList<T>::InsertBefore(CFastListNode<T> *pNode, T data) { CFastListNode<T> *pNewNode = m_pFreeList; if (!pNewNode) return FALSE; m_pFreeList = m_pFreeList->m_pNext; m_pFreeList->m_pPrev = NULL; pNewNode->m_pNext = pNode; if (pNode->m_pPrev) { pNewNode->m_pPrev = pNode->m_pPrev; } else { m_pHead = pNewNode; } pNode->m_pPrev = pNewNode; m_nSize ++; // Success !! return TRUE; } //---------------------------------------------------------- // // FUNCTION : CFastList::RemoveHead() // // PURPOSE : Removes head element // //---------------------------------------------------------- template <class T> inline T CFastList<T>::RemoveHead() { CFastListNode<T> *pNode; T Data; if (m_pHead) { pNode = m_pHead; Data = m_pHead->m_Data; m_pHead = m_pHead->m_pNext; if (!m_pHead) { // List is empty.. m_pTail = NULL; } else { if (m_pHead->m_pNext) { // Correct link m_pHead->m_pNext->m_pPrev = m_pHead; } } pNode->m_pNext = m_pFreeList->m_pNext; pNode->m_pPrev = m_pFreeList; m_pFreeList->m_pNext = pNode; m_nSize --; } return Data; } //---------------------------------------------------------- // // FUNCTION : CFastList::RemoveTail() // // PURPOSE : Removes head element // //---------------------------------------------------------- template <class T> inline T CFastList<T>::RemoveTail() { CFastListNode<T> *pNode; T Data; if (m_pTail) { pNode = m_pTail; Data = m_pTail->m_Data; if (m_pTail->m_pPrev) { m_pTail = m_pTail->m_pPrev; } else { // List is empty.. m_pHead = NULL; m_pTail = NULL; } m_nSize --; pNode->m_pNext = m_pFreeList->m_pNext; pNode->m_pPrev = m_pFreeList; m_pFreeList->m_pNext = pNode; } return Data; } //---------------------------------------------------------- // // FUNCTION : CFastList::Remove() // // PURPOSE : Removes an element from the list // //---------------------------------------------------------- template <class T> inline void CFastList<T>::Remove(CFastListNode<T> *pNode) { CFastListNode<T> *pPrev = pNode->m_pPrev; CFastListNode<T> *pNext = pNode->m_pNext; if ((pPrev) && (pNext)) { pPrev->m_pNext = pNext; pNext->m_pPrev = pPrev; } if ((!pPrev) && (pNext)) { pNext->m_pPrev = NULL; m_pHead = pNext; } if ((pPrev) && (!pNext)) { pPrev->m_pNext = NULL; m_pTail = pPrev; } if ((!pPrev) && (!pNext)) { m_pTail = NULL; m_pHead = NULL; } // Delete link pNode->m_pNext = m_pFreeList->m_pNext; pNode->m_pPrev = m_pFreeList; m_pFreeList->m_pNext = pNode; m_nSize --; } //---------------------------------------------------------- // // FUNCTION : CFastList::Remove() // // PURPOSE : Removes an element from the list (SLOW) // //---------------------------------------------------------- template <class T> inline void CFastList<T>::Remove(T data) { CFastListNode<T> *pNode = m_pHead; if (!pNode) return; while (pNode) { if (pNode->m_Data == data) { Remove(pNode); return; } pNode = pNode->m_pNext; } } //---------------------------------------------------------- // // FUNCTION : CFastList::Find() // // PURPOSE : Finds a data element in the list // //---------------------------------------------------------- template <class T> inline CFastListNode<T>* CFastList<T>::Find(T data) { CFastListNode<T> *pNode = m_pHead; if (!pNode) return NULL; while (pNode) { if (pNode->m_Data == data) { return pNode; } pNode = pNode->m_pNext; } return NULL; } //---------------------------------------------------------- // // FUNCTION : CFastList::Get() // // PURPOSE : Returns data for a given index // //---------------------------------------------------------- template <class T> inline T CFastList<T>::Get(DWORD dwIndex) { CFastListNode<T> *pNode = m_pHead; if (!pNode) return NULL; for (DWORD i = 0; i < dwIndex; i ++) { pNode = pNode->GetNext(); } return pNode->GetData(); } //---------------------------------------------------------- // // FUNCTION : CFastList::GetIndex() // // PURPOSE : Returns an index for a given pointer // //---------------------------------------------------------- template <class T> inline int CFastList<T>::GetIndex(T data) { int i = 0; CFastListNode<T> *pNode = m_pHead; if (!pNode) return NULL; while (pNode) { if (pNode->m_Data == data) { return i; } pNode = pNode->m_pNext; i ++; } return -1; } //------------------------------------------------------------------ // // FUNCTION : Alloc() // // PURPOSE : Allocates memory block for list and links it // //------------------------------------------------------------------ template <class T> inline void CFastList<T>::AllocMem(int nTotalElem) { if (m_pBlock) debug_deletea(m_pBlock); m_pBlock = debug_newa(CFastListNode<T>, nTotalElem); m_nTotalElem = nTotalElem; m_pFreeList = m_pBlock; // Link up all the nodes CFastListNode<T> *pStart = m_pBlock; pStart->m_pPrev = NULL; pStart->m_pNext = pStart + 1; pStart ++; for (int i = 1; i < nTotalElem - 1; i ++) { pStart->m_pNext = pStart + 1; pStart->m_pPrev = pStart - 1; pStart ++; } pStart->m_pPrev = pStart - 1; pStart->m_pNext = NULL; } #endif
[ [ [ 1, 589 ] ] ]
2b17774f129d2575a631a6e516fa072ad49e19e9
d1bd1841896c1258db2dec354006faf8e8915984
/src/TrayIcon.cpp
58968f169d23286dc394de6987cd19d5f449366e
[]
no_license
crawford/Drink-Client
99740b894a5f2ec1e335fb964fd5116ea7bc351f
6c1a7c5a77b097b057ef93c46b6320df0fea5a53
refs/heads/master
2021-01-18T19:18:17.920447
2010-08-29T14:31:30
2010-08-29T14:31:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,117
cpp
#include "TrayIcon.h" #include <QMenu> #include <QAction> #include <QApplication> TrayIcon::TrayIcon(QString user, QString pass) : QObject(), icon(this) { username = user; password = pass; #ifdef Q_OS_WIN icon.setIcon(QIcon(":/Icons/images/soda_32.png")); #endif #ifdef Q_OS_MAC icon.setIcon(QIcon(":/Icons/images/soda_16_bw.png")); #endif icon.setContextMenu(createMenu()); icon.setToolTip("Drink Client"); win = new FrmClient(username, password, 0, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowTitleHint | Qt::WindowSystemMenuHint); } void TrayIcon::show() { icon.show(); showWindow(); } QMenu* TrayIcon::createMenu() { QMenu *menu = new QMenu(); QAction *quit = new QAction("Quit", this); QAction *show = new QAction("Show Selections...", this); connect(quit, SIGNAL(triggered()), qApp, SLOT(quit())); connect(show, SIGNAL(triggered()), this, SLOT(showWindow())); menu->addAction(show); menu->addAction(quit); menu->setDefaultAction(show); return menu; } void TrayIcon::showWindow() { win->show(); }
[ [ [ 1, 46 ] ] ]
334920d58e4614f363614dc02fb8c91f51ff846e
8534420818cbc7db514760f820b5bd4614289a63
/wxSphinxLocalIndexer/wxSphinxIndexer.cpp
c5cbae1fd6da3203d1cf3e486494c39fdd65a608
[]
no_license
BishopGIS/wxsphinx
b0a9dc4ba77d6d61f1a34e9cb8ad11298d6ed3ca
16a825fa6993dc310e60c10e7e40d7948edc38bb
refs/heads/master
2020-05-18T10:40:37.840592
2010-01-08T19:08:57
2010-01-08T19:08:57
32,631,398
0
0
null
null
null
null
UTF-8
C++
false
false
6,663
cpp
#include "wxSphinxIndexer.h" #include <map> #include "wx/strconv.h" wxSphinxIndexer::wxSphinxIndexer(bool bQuiet, wxXmlNode *pConf, wxSQLite3Database *pdb, wxSphinxFactories* pFactories) { m_bQuiet = bQuiet; m_pDB = pdb; m_pConf = pConf; m_pFactories = pFactories; } wxSphinxIndexer::~wxSphinxIndexer(void) { } bool wxSphinxIndexer::Start(long nMaxCount) { std::vector<long> delete_arr; //1. create header wxFprintf(stdout, wxT("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")); wxFprintf(stdout, wxT("<sphinx:docset>\n\n")); wxFprintf(stdout, wxT("<sphinx:schema>\n")); wxFprintf(stdout, wxT("<sphinx:field name=\"content\"/>\n")); wxFprintf(stdout, wxT("<sphinx:attr name=\"accessed\" type=\"timestamp\"/>\n")); wxFprintf(stdout, wxT("<sphinx:attr name=\"last_updated\" type=\"timestamp\"/>\n")); wxFprintf(stdout, wxT("<sphinx:attr name=\"created\" type=\"timestamp\"/>\n")); wxFprintf(stdout, wxT("<sphinx:attr name=\"is_deleted\" type=\"bool\"/>\n")); wxFprintf(stdout, wxT("<sphinx:attr name=\"size\" type=\"int\"/>\n")); wxFprintf(stdout, wxT("</sphinx:schema>\n")); //2. connect DB wxSQLite3ResultSet set = m_pDB->ExecuteQuery(wxString::Format(wxT("SELECT oid, path, dt_changed, dt_indexed, deleted, module FROM %s WHERE type = %u"), TABLE_NAME, wxEnumSphinxFile)); //3. run throw DB recordset long nCounter = 0; while (set.NextRow()) { long oid = set.GetInt(0, -1); wxString path = set.GetString(1); wxDateTime changed((time_t)set.GetInt(2)); wxDateTime indexed((time_t)set.GetInt(3)); bool deleted = set.GetBool(4); wxString module = set.GetString(5); IwxSphinxObjectFactory *Factory = m_pFactories->GetFactory(module); if(Factory == NULL) continue; wxFileName name(path); if(name.IsDir()) continue; deleted = !wxFileName::FileExists( path ); wxDateTime dtAccess, dtMod(wxDateTime::Now()), dtCreate; if(!deleted ) name.GetTimes(&dtAccess, &dtMod, &dtCreate); if(!indexed.IsValid() || indexed < dtMod) { if(nCounter == nMaxCount) break; //check long wxDateTime start = wxDateTime::Now(); wxString out = Factory->GetCData(path); wxTimeSpan span = wxDateTime::Now() - start; if(out.IsEmpty() && out == wxString(wxT("empty"))) { wxLogError(_("Error parse file (%u) '%s'"), oid, path.c_str()); continue; } wxFprintf(stdout, wxT("<sphinx:document id=\"%u\">\n"), oid); if(deleted) { wxFprintf(stdout, wxT("<is_deleted>true</is_deleted>\n"), oid); //mark to delete row from db delete_arr.push_back(oid); } else { wxLogMessage(_("Proceeding... document %u - path '%s'"), nCounter, path.c_str()); wxFprintf(stdout, wxT("<is_deleted>false</is_deleted>\n"), oid); //check path if archive search ":" wxFprintf(stdout, wxT("<accessed>%u</accessed>\n"), dtAccess.GetTicks()); wxFprintf(stdout, wxT("<last_updated>%u</last_updated>\n"), dtMod.GetTicks()); wxFprintf(stdout, wxT("<created>%u</created>\n"), dtCreate.GetTicks()); wxFprintf(stdout, wxT("<size>%u</size>\n"), name.GetSize().ToULong()); wxFprintf(stdout, wxT("<content><![CDATA[%s]]></content>\n"), out.c_str()); int nMaxWaitSec = wxAtoi(m_pConf->GetPropVal(wxT("maxwaitsec"), wxT("60"))); if(span.GetSeconds().ToLong() > nMaxWaitSec) { wxLogMessage(_("Max wait exceed (%u sec.)"), span.GetSeconds().ToLong()); try { m_pDB->ExecuteUpdate(wxString::Format(wxT("UPDATE %s SET dt_indexed = %u, datatext = '%s' WHERE oid = %u"), TABLE_NAME, wxDateTime::Now().GetTicks(), out.c_str(), oid));//datatext nodedata } catch( wxSQLite3Exception &rErr ) { wxLogError(rErr.GetMessage()); } } else { m_pDB->ExecuteUpdate(wxString::Format(wxT("UPDATE %s SET dt_indexed = %u WHERE oid = %u"), TABLE_NAME, wxDateTime::Now().GetTicks(), oid)); } } //4. print out data wxFprintf(stdout, wxT("</sphinx:document>\n\n")); nCounter++; } } wxFprintf(stdout, wxT("</sphinx:docset>\n")); //delete oid's for(size_t i = 0; i < delete_arr.size(); i++) { m_pDB->ExecuteUpdate(wxString::Format(wxT("DELETE FROM %s WHERE oid = %u"), TABLE_NAME, delete_arr[i])); } return true; } bool wxSphinxIndexer::ShowDetails(long nIndex) { //1. connect DB wxString sQuere = wxString::Format(wxT("SELECT path, module, datatext FROM %s WHERE oid = %u"), TABLE_NAME, nIndex); wxSQLite3ResultSet set = m_pDB->ExecuteQuery(sQuere); //2. run throw DB recordset if(set.NextRow()) { wxString path = set.GetString(0); wxString module = set.GetString(1); wxString datatext = set.GetString(2); IwxSphinxObjectFactory *pFactory = m_pFactories->GetFactory(module); if(pFactory == NULL) return false; wxFileName name(path); wxString sTitle = name.GetName(); wxDateTime dtAccess, dtMod, dtCreate; name.GetTimes(&dtAccess, &dtMod, &dtCreate); wxString times = wxString::Format(_("Access %s, Modify %s, Create %s"), dtAccess.Format(_("%d-%m-%Y %H:%M:%S")).c_str(), dtMod.Format(_("%d-%m-%Y %H:%M:%S")).c_str(), dtCreate.Format(_("%d-%m-%Y %H:%M:%S")).c_str()); bool bDataTextIsEmpty = datatext.IsEmpty(); wxDateTime start = wxDateTime::Now(); if(bDataTextIsEmpty) { datatext = pFactory->GetCData(path); } wxTimeSpan span = wxDateTime::Now() - start; int nMaxWaitSec = wxAtoi(m_pConf->GetPropVal(wxT("maxwaitsec"), wxT("60"))); if(bDataTextIsEmpty && span.GetSeconds().ToLong() > nMaxWaitSec) { wxLogMessage(_("Max wait exceed (%u sec.)"), span.GetSeconds().ToLong()); try { m_pDB->ExecuteUpdate(wxString::Format(wxT("UPDATE %s SET datatext = '%s' WHERE oid = %u"), TABLE_NAME, datatext.c_str(), nIndex)); } catch( wxSQLite3Exception &rErr ) { wxLogError(rErr.GetMessage()); } } int nMaxSize = wxAtoi(m_pConf->GetPropVal(wxT("maxtext"), wxT("2048"))); if(datatext.Len() > nMaxSize) datatext = datatext.Left(nMaxSize); datatext.Replace(wxT("\n"), wxT(" ")); wxFprintf(stdout, wxT("%s\n%s\n%s\n%s\n"), path.c_str(), sTitle.c_str(), times.c_str(), datatext.c_str()); } return true; }
[ "bishop.gis@dbcdddfc-c008-11de-ac5a-05e7513655e2" ]
[ [ [ 1, 182 ] ] ]
a27363266e8159f1a38c5b001d1ba9aa9e56fd45
16d8b25d0d1c0f957c92f8b0d967f71abff1896d
/OblivionOnline/FakeD3D.h
cc67cb61bac7ff0a2cbafbabe111e7c7e9899ce6
[]
no_license
wlasser/oonline
51973b5ffec0b60407b63b010d0e4e1622cf69b6
fd37ee6985f1de082cbc9f8625d1d9307e8801a6
refs/heads/master
2021-05-28T23:39:16.792763
2010-05-12T22:35:20
2010-05-12T22:35:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,439
h
#pragma once /* Copyright(c) 2007-2010 Julian Bangert This file is part of OblivionOnline. OblivionOnline is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. OblivionOnline is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Linking OblivionOnline statically or dynamically with other modules is making a combined work based on OblivionOnline. Thus, the terms and conditions of the GNU General Public License cover the whole combination. In addition, as a special exception, the copyright holders of OblivionOnline give you permission to combine OblivionOnline program with free software programs or libraries that are released under the GNU LGPL and with code included in the standard release of Oblivion Script Extender by Ian Patterson (OBSE) under the OBSE license (or modified versions of such code, with unchanged license). You may copy and distribute such a system following the terms of the GNU GPL for OblivionOnline and the licenses of the other code concerned, provided that you include the source code of that other code when and as the GNU GPL requires distribution of source code. Note that people who make modified versions of OblivionOnline are not obligated to grant this special exception for their modified versions; it is their choice whether to do so. The GNU General Public License gives permission to release a modified version without this exception; this exception also makes it possible to release a modified version which carries forward this exception. */ #ifndef _FAKED3D_H #define _FAKED3D_H #include <d3d9.h> #include "main.h" #include "UserInterface.h" #include "D3DHook.h" extern bool g_bRenderGUI; class MyDirect3DDevice9 : public IDirect3DDevice9 { public: // We need d3d so that we'd use a pointer to MyDirect3D9 instead of the original IDirect3D9 implementor // in functions like GetDirect3D9 MyDirect3DDevice9(IDirect3D9* d3d, IDirect3DDevice9* device) { m_d3d = d3d; m_device = device; } /*** IUnknown methods ***/ STDMETHOD(QueryInterface)(THIS_ REFIID riid, void** ppvObj) { return m_device->QueryInterface(riid, ppvObj); } STDMETHOD_(ULONG,AddRef)(THIS) { return m_device->AddRef(); } STDMETHOD_(ULONG,Release)(THIS) { ULONG count = m_device->Release(); if(0 == count) delete this; return count; } /*** IDirect3DDevice9 methods ***/ STDMETHOD(TestCooperativeLevel)(THIS) { return m_device->TestCooperativeLevel(); } STDMETHOD_(UINT, GetAvailableTextureMem)(THIS) { return m_device->GetAvailableTextureMem(); } STDMETHOD(EvictManagedResources)(THIS) { return m_device->EvictManagedResources(); } STDMETHOD(GetDirect3D)(THIS_ IDirect3D9** ppD3D9) { // Let the device validate the incoming pointer for us HRESULT hr = m_device->GetDirect3D(ppD3D9); if(SUCCEEDED(hr)) *ppD3D9 = m_d3d; return hr; } STDMETHOD(GetDeviceCaps)(THIS_ D3DCAPS9* pCaps) { return m_device->GetDeviceCaps(pCaps); } STDMETHOD(GetDisplayMode)(THIS_ UINT iSwapChain,D3DDISPLAYMODE* pMode) { return m_device->GetDisplayMode(iSwapChain, pMode); } STDMETHOD(GetCreationParameters)(THIS_ D3DDEVICE_CREATION_PARAMETERS *pParameters) { return m_device->GetCreationParameters(pParameters); } STDMETHOD(SetCursorProperties)(THIS_ UINT XHotSpot,UINT YHotSpot,IDirect3DSurface9* pCursorBitmap) { return m_device->SetCursorProperties(XHotSpot, YHotSpot, pCursorBitmap); } STDMETHOD_(void, SetCursorPosition)(THIS_ int X,int Y,DWORD Flags) { m_device->SetCursorPosition(X, Y, Flags); } STDMETHOD_(BOOL, ShowCursor)(THIS_ BOOL bShow) { return m_device->ShowCursor(bShow); } STDMETHOD(CreateAdditionalSwapChain)(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DSwapChain9** pSwapChain) { return m_device->CreateAdditionalSwapChain(pPresentationParameters, pSwapChain); } STDMETHOD(GetSwapChain)(THIS_ UINT iSwapChain,IDirect3DSwapChain9** pSwapChain) { return m_device->GetSwapChain(iSwapChain, pSwapChain); } STDMETHOD_(UINT, GetNumberOfSwapChains)(THIS) { return m_device->GetNumberOfSwapChains(); } STDMETHOD(Reset)(THIS_ D3DPRESENT_PARAMETERS* pPresentationParameters) { return m_device->Reset(pPresentationParameters); } STDMETHOD(Present)(THIS_ CONST RECT* pSourceRect,CONST RECT* pDestRect,HWND hDestWindowOverride,CONST RGNDATA* pDirtyRegion) { BeginScene(); static IDirect3DStateBlock9 *state = NULL; if(bUIInitialized) { if(g_bRenderGUI) { //save state CreateStateBlock(D3DSBT_ALL,&state); //render CEGUI::System::getSingleton().renderGUI(); //restore state state->Apply(); state->Release(); } } if(gClient) gClient->RunFrame(); //gClient->GetServerStream()->Send(); EndScene(); return m_device->Present(pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion); } STDMETHOD(GetBackBuffer)(THIS_ UINT iSwapChain,UINT iBackBuffer,D3DBACKBUFFER_TYPE Type,IDirect3DSurface9** ppBackBuffer) { return m_device->GetBackBuffer(iSwapChain, iBackBuffer, Type, ppBackBuffer); } STDMETHOD(GetRasterStatus)(THIS_ UINT iSwapChain,D3DRASTER_STATUS* pRasterStatus) { return m_device->GetRasterStatus(iSwapChain, pRasterStatus); } STDMETHOD(SetDialogBoxMode)(THIS_ BOOL bEnableDialogs) { return m_device->SetDialogBoxMode(bEnableDialogs); } STDMETHOD_(void, SetGammaRamp)(THIS_ UINT iSwapChain,DWORD Flags,CONST D3DGAMMARAMP* pRamp) { return m_device->SetGammaRamp(iSwapChain, Flags, pRamp); } STDMETHOD_(void, GetGammaRamp)(THIS_ UINT iSwapChain,D3DGAMMARAMP* pRamp) { return m_device->GetGammaRamp(iSwapChain, pRamp); } STDMETHOD(CreateTexture)(THIS_ UINT Width,UINT Height,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DTexture9** ppTexture,HANDLE* pSharedHandle) { return m_device->CreateTexture(Width, Height, Levels, Usage, Format, Pool, ppTexture, pSharedHandle); } STDMETHOD(CreateVolumeTexture)(THIS_ UINT Width,UINT Height,UINT Depth,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DVolumeTexture9** ppVolumeTexture,HANDLE* pSharedHandle) { return m_device->CreateVolumeTexture(Width, Height, Depth, Levels, Usage, Format, Pool, ppVolumeTexture, pSharedHandle); } STDMETHOD(CreateCubeTexture)(THIS_ UINT EdgeLength,UINT Levels,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DCubeTexture9** ppCubeTexture,HANDLE* pSharedHandle) { return m_device->CreateCubeTexture(EdgeLength, Levels, Usage, Format, Pool, ppCubeTexture, pSharedHandle); } STDMETHOD(CreateVertexBuffer)(THIS_ UINT Length,DWORD Usage,DWORD FVF,D3DPOOL Pool,IDirect3DVertexBuffer9** ppVertexBuffer,HANDLE* pSharedHandle) { return m_device->CreateVertexBuffer(Length, Usage, FVF, Pool, ppVertexBuffer, pSharedHandle); } STDMETHOD(CreateIndexBuffer)(THIS_ UINT Length,DWORD Usage,D3DFORMAT Format,D3DPOOL Pool,IDirect3DIndexBuffer9** ppIndexBuffer,HANDLE* pSharedHandle) { return m_device->CreateIndexBuffer(Length, Usage, Format, Pool, ppIndexBuffer, pSharedHandle); } STDMETHOD(CreateRenderTarget)(THIS_ UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Lockable,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) { return m_device->CreateRenderTarget(Width, Height, Format, MultiSample, MultisampleQuality, Lockable, ppSurface, pSharedHandle); } STDMETHOD(CreateDepthStencilSurface)(THIS_ UINT Width,UINT Height,D3DFORMAT Format,D3DMULTISAMPLE_TYPE MultiSample,DWORD MultisampleQuality,BOOL Discard,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) { return m_device->CreateDepthStencilSurface(Width, Height, Format, MultiSample, MultisampleQuality, Discard, ppSurface, pSharedHandle); } STDMETHOD(UpdateSurface)(THIS_ IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestinationSurface,CONST POINT* pDestPoint) { return m_device->UpdateSurface(pSourceSurface, pSourceRect, pDestinationSurface, pDestPoint); } STDMETHOD(UpdateTexture)(THIS_ IDirect3DBaseTexture9* pSourceTexture,IDirect3DBaseTexture9* pDestinationTexture) { return m_device->UpdateTexture(pSourceTexture, pDestinationTexture); } STDMETHOD(GetRenderTargetData)(THIS_ IDirect3DSurface9* pRenderTarget,IDirect3DSurface9* pDestSurface) { return m_device->GetRenderTargetData(pRenderTarget, pDestSurface); } STDMETHOD(GetFrontBufferData)(THIS_ UINT iSwapChain,IDirect3DSurface9* pDestSurface) { return m_device->GetFrontBufferData(iSwapChain, pDestSurface); } STDMETHOD(StretchRect)(THIS_ IDirect3DSurface9* pSourceSurface,CONST RECT* pSourceRect,IDirect3DSurface9* pDestSurface,CONST RECT* pDestRect,D3DTEXTUREFILTERTYPE Filter) { return m_device->StretchRect(pSourceSurface, pSourceRect, pDestSurface, pDestRect, Filter); } STDMETHOD(ColorFill)(THIS_ IDirect3DSurface9* pSurface,CONST RECT* pRect,D3DCOLOR color) { return m_device->ColorFill(pSurface, pRect, color); } STDMETHOD(CreateOffscreenPlainSurface)(THIS_ UINT Width,UINT Height,D3DFORMAT Format,D3DPOOL Pool,IDirect3DSurface9** ppSurface,HANDLE* pSharedHandle) { return m_device->CreateOffscreenPlainSurface(Width, Height, Format, Pool, ppSurface, pSharedHandle); } STDMETHOD(SetRenderTarget)(THIS_ DWORD RenderTargetIndex,IDirect3DSurface9* pRenderTarget) { return m_device->SetRenderTarget(RenderTargetIndex, pRenderTarget); } STDMETHOD(GetRenderTarget)(THIS_ DWORD RenderTargetIndex,IDirect3DSurface9** ppRenderTarget) { return m_device->GetRenderTarget(RenderTargetIndex, ppRenderTarget); } STDMETHOD(SetDepthStencilSurface)(THIS_ IDirect3DSurface9* pNewZStencil) { return m_device->SetDepthStencilSurface(pNewZStencil); } STDMETHOD(GetDepthStencilSurface)(THIS_ IDirect3DSurface9** ppZStencilSurface) { return m_device->GetDepthStencilSurface(ppZStencilSurface); } STDMETHOD(BeginScene)(THIS) { return m_device->BeginScene(); } STDMETHOD(EndScene)(THIS) { return m_device->EndScene(); } STDMETHOD(Clear)(THIS_ DWORD Count,CONST D3DRECT* pRects,DWORD Flags,D3DCOLOR Color,float Z,DWORD Stencil) { return m_device->Clear(Count, pRects, Flags, Color, Z, Stencil); } STDMETHOD(SetTransform)(THIS_ D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix) { return m_device->SetTransform(State, pMatrix); } STDMETHOD(GetTransform)(THIS_ D3DTRANSFORMSTATETYPE State,D3DMATRIX* pMatrix) { return m_device->GetTransform(State, pMatrix); } STDMETHOD(MultiplyTransform)(THIS_ D3DTRANSFORMSTATETYPE State,CONST D3DMATRIX* pMatrix) { return m_device->MultiplyTransform(State, pMatrix); } STDMETHOD(SetViewport)(THIS_ CONST D3DVIEWPORT9* pViewport) { return m_device->SetViewport(pViewport); } STDMETHOD(GetViewport)(THIS_ D3DVIEWPORT9* pViewport) { return m_device->GetViewport(pViewport); } STDMETHOD(SetMaterial)(THIS_ CONST D3DMATERIAL9* pMaterial) { return m_device->SetMaterial(pMaterial); } STDMETHOD(GetMaterial)(THIS_ D3DMATERIAL9* pMaterial) { return m_device->GetMaterial(pMaterial); } STDMETHOD(SetLight)(THIS_ DWORD Index,CONST D3DLIGHT9* pLight) { return m_device->SetLight(Index, pLight); } STDMETHOD(GetLight)(THIS_ DWORD Index,D3DLIGHT9* pLight) { return m_device->GetLight(Index, pLight); } STDMETHOD(LightEnable)(THIS_ DWORD Index,BOOL Enable) { return m_device->LightEnable(Index, Enable); } STDMETHOD(GetLightEnable)(THIS_ DWORD Index,BOOL* pEnable) { return m_device->GetLightEnable(Index, pEnable); } STDMETHOD(SetClipPlane)(THIS_ DWORD Index,CONST float* pPlane) { return m_device->SetClipPlane(Index, pPlane); } STDMETHOD(GetClipPlane)(THIS_ DWORD Index,float* pPlane) { return m_device->GetClipPlane(Index, pPlane); } STDMETHOD(SetRenderState)(THIS_ D3DRENDERSTATETYPE State,DWORD Value) { return m_device->SetRenderState(State, Value); } STDMETHOD(GetRenderState)(THIS_ D3DRENDERSTATETYPE State,DWORD* pValue) { return m_device->GetRenderState(State, pValue); } STDMETHOD(CreateStateBlock)(THIS_ D3DSTATEBLOCKTYPE Type,IDirect3DStateBlock9** ppSB) { return m_device->CreateStateBlock(Type, ppSB); } STDMETHOD(BeginStateBlock)(THIS) { return m_device->BeginStateBlock(); } STDMETHOD(EndStateBlock)(THIS_ IDirect3DStateBlock9** ppSB) { return m_device->EndStateBlock(ppSB); } STDMETHOD(SetClipStatus)(THIS_ CONST D3DCLIPSTATUS9* pClipStatus) { return m_device->SetClipStatus(pClipStatus); } STDMETHOD(GetClipStatus)(THIS_ D3DCLIPSTATUS9* pClipStatus) { return m_device->GetClipStatus(pClipStatus); } STDMETHOD(GetTexture)(THIS_ DWORD Stage,IDirect3DBaseTexture9** ppTexture) { return m_device->GetTexture(Stage, ppTexture); } STDMETHOD(SetTexture)(THIS_ DWORD Stage,IDirect3DBaseTexture9* pTexture) { return m_device->SetTexture(Stage, pTexture); } STDMETHOD(GetTextureStageState)(THIS_ DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD* pValue) { return m_device->GetTextureStageState(Stage, Type, pValue); } STDMETHOD(SetTextureStageState)(THIS_ DWORD Stage,D3DTEXTURESTAGESTATETYPE Type,DWORD Value) { return m_device->SetTextureStageState(Stage, Type, Value); } STDMETHOD(GetSamplerState)(THIS_ DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD* pValue) { return m_device->GetSamplerState(Sampler, Type, pValue); } STDMETHOD(SetSamplerState)(THIS_ DWORD Sampler,D3DSAMPLERSTATETYPE Type,DWORD Value) { return m_device->SetSamplerState(Sampler, Type, Value); } STDMETHOD(ValidateDevice)(THIS_ DWORD* pNumPasses) { return m_device->ValidateDevice(pNumPasses); } STDMETHOD(SetPaletteEntries)(THIS_ UINT PaletteNumber,CONST PALETTEENTRY* pEntries) { return m_device->SetPaletteEntries(PaletteNumber, pEntries); } STDMETHOD(GetPaletteEntries)(THIS_ UINT PaletteNumber,PALETTEENTRY* pEntries) { return m_device->GetPaletteEntries(PaletteNumber, pEntries); } STDMETHOD(SetCurrentTexturePalette)(THIS_ UINT PaletteNumber) { return m_device->SetCurrentTexturePalette(PaletteNumber); } STDMETHOD(GetCurrentTexturePalette)(THIS_ UINT *PaletteNumber) { return m_device->GetCurrentTexturePalette(PaletteNumber); } STDMETHOD(SetScissorRect)(THIS_ CONST RECT* pRect) { return m_device->SetScissorRect(pRect); } STDMETHOD(GetScissorRect)(THIS_ RECT* pRect) { return m_device->GetScissorRect(pRect); } STDMETHOD(SetSoftwareVertexProcessing)(THIS_ BOOL bSoftware) { return m_device->SetSoftwareVertexProcessing(bSoftware); } STDMETHOD_(BOOL, GetSoftwareVertexProcessing)(THIS) { return m_device->GetSoftwareVertexProcessing(); } STDMETHOD(SetNPatchMode)(THIS_ float nSegments) { return m_device->SetNPatchMode(nSegments); } STDMETHOD_(float, GetNPatchMode)(THIS) { return m_device->GetNPatchMode(); } STDMETHOD(DrawPrimitive)(THIS_ D3DPRIMITIVETYPE PrimitiveType,UINT StartVertex,UINT PrimitiveCount) { return m_device->DrawPrimitive(PrimitiveType, StartVertex, PrimitiveCount); } STDMETHOD(DrawIndexedPrimitive)(THIS_ D3DPRIMITIVETYPE PrimitiveType,INT BaseVertexIndex,UINT MinVertexIndex,UINT NumVertices,UINT startIndex,UINT primCount) { return m_device->DrawIndexedPrimitive(PrimitiveType, BaseVertexIndex, MinVertexIndex, NumVertices, startIndex, primCount); } STDMETHOD(DrawPrimitiveUP)(THIS_ D3DPRIMITIVETYPE PrimitiveType,UINT PrimitiveCount,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) { return m_device->DrawPrimitiveUP(PrimitiveType, PrimitiveCount, pVertexStreamZeroData, VertexStreamZeroStride); } STDMETHOD(DrawIndexedPrimitiveUP)(THIS_ D3DPRIMITIVETYPE PrimitiveType,UINT MinVertexIndex,UINT NumVertices,UINT PrimitiveCount,CONST void* pIndexData,D3DFORMAT IndexDataFormat,CONST void* pVertexStreamZeroData,UINT VertexStreamZeroStride) { return m_device->DrawIndexedPrimitiveUP(PrimitiveType, MinVertexIndex, NumVertices, PrimitiveCount, pIndexData, IndexDataFormat, pVertexStreamZeroData, VertexStreamZeroStride); } STDMETHOD(ProcessVertices)(THIS_ UINT SrcStartIndex,UINT DestIndex,UINT VertexCount,IDirect3DVertexBuffer9* pDestBuffer,IDirect3DVertexDeclaration9* pVertexDecl,DWORD Flags) { return m_device->ProcessVertices(SrcStartIndex, DestIndex, VertexCount, pDestBuffer, pVertexDecl, Flags); } STDMETHOD(CreateVertexDeclaration)(THIS_ CONST D3DVERTEXELEMENT9* pVertexElements,IDirect3DVertexDeclaration9** ppDecl) { return m_device->CreateVertexDeclaration(pVertexElements, ppDecl); } STDMETHOD(SetVertexDeclaration)(THIS_ IDirect3DVertexDeclaration9* pDecl) { return m_device->SetVertexDeclaration(pDecl); } STDMETHOD(GetVertexDeclaration)(THIS_ IDirect3DVertexDeclaration9** ppDecl) { return m_device->GetVertexDeclaration(ppDecl); } STDMETHOD(SetFVF)(THIS_ DWORD FVF) { return m_device->SetFVF(FVF); } STDMETHOD(GetFVF)(THIS_ DWORD* pFVF) { return m_device->GetFVF(pFVF); } STDMETHOD(CreateVertexShader)(THIS_ CONST DWORD* pFunction,IDirect3DVertexShader9** ppShader) { return m_device->CreateVertexShader(pFunction, ppShader); } STDMETHOD(SetVertexShader)(THIS_ IDirect3DVertexShader9* pShader) { return m_device->SetVertexShader(pShader); } STDMETHOD(GetVertexShader)(THIS_ IDirect3DVertexShader9** ppShader) { return m_device->GetVertexShader(ppShader); } STDMETHOD(SetVertexShaderConstantF)(THIS_ UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount) { return m_device->SetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHOD(GetVertexShaderConstantF)(THIS_ UINT StartRegister,float* pConstantData,UINT Vector4fCount) { return m_device->GetVertexShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHOD(SetVertexShaderConstantI)(THIS_ UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount) { return m_device->SetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHOD(GetVertexShaderConstantI)(THIS_ UINT StartRegister,int* pConstantData,UINT Vector4iCount) { return m_device->GetVertexShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHOD(SetVertexShaderConstantB)(THIS_ UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount) { return m_device->SetVertexShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHOD(GetVertexShaderConstantB)(THIS_ UINT StartRegister,BOOL* pConstantData,UINT BoolCount) { return m_device->GetVertexShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHOD(SetStreamSource)(THIS_ UINT StreamNumber,IDirect3DVertexBuffer9* pStreamData,UINT OffsetInBytes,UINT Stride) { return m_device->SetStreamSource(StreamNumber, pStreamData, OffsetInBytes, Stride); } STDMETHOD(GetStreamSource)(THIS_ UINT StreamNumber,IDirect3DVertexBuffer9** ppStreamData,UINT* pOffsetInBytes,UINT* pStride) { return m_device->GetStreamSource(StreamNumber, ppStreamData, pOffsetInBytes, pStride); } STDMETHOD(SetStreamSourceFreq)(THIS_ UINT StreamNumber,UINT Setting) { return m_device->SetStreamSourceFreq(StreamNumber, Setting); } STDMETHOD(GetStreamSourceFreq)(THIS_ UINT StreamNumber,UINT* pSetting) { return m_device->GetStreamSourceFreq(StreamNumber, pSetting); } STDMETHOD(SetIndices)(THIS_ IDirect3DIndexBuffer9* pIndexData) { return m_device->SetIndices(pIndexData); } STDMETHOD(GetIndices)(THIS_ IDirect3DIndexBuffer9** ppIndexData) { return m_device->GetIndices(ppIndexData); } STDMETHOD(CreatePixelShader)(THIS_ CONST DWORD* pFunction,IDirect3DPixelShader9** ppShader) { return m_device->CreatePixelShader(pFunction, ppShader); } STDMETHOD(SetPixelShader)(THIS_ IDirect3DPixelShader9* pShader) { return m_device->SetPixelShader(pShader); } STDMETHOD(GetPixelShader)(THIS_ IDirect3DPixelShader9** ppShader) { return m_device->GetPixelShader(ppShader); } STDMETHOD(SetPixelShaderConstantF)(THIS_ UINT StartRegister,CONST float* pConstantData,UINT Vector4fCount) { return m_device->SetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHOD(GetPixelShaderConstantF)(THIS_ UINT StartRegister,float* pConstantData,UINT Vector4fCount) { return m_device->GetPixelShaderConstantF(StartRegister, pConstantData, Vector4fCount); } STDMETHOD(SetPixelShaderConstantI)(THIS_ UINT StartRegister,CONST int* pConstantData,UINT Vector4iCount) { return m_device->SetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHOD(GetPixelShaderConstantI)(THIS_ UINT StartRegister,int* pConstantData,UINT Vector4iCount) { return m_device->GetPixelShaderConstantI(StartRegister, pConstantData, Vector4iCount); } STDMETHOD(SetPixelShaderConstantB)(THIS_ UINT StartRegister,CONST BOOL* pConstantData,UINT BoolCount) { return m_device->SetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHOD(GetPixelShaderConstantB)(THIS_ UINT StartRegister,BOOL* pConstantData,UINT BoolCount) { return m_device->GetPixelShaderConstantB(StartRegister, pConstantData, BoolCount); } STDMETHOD(DrawRectPatch)(THIS_ UINT Handle,CONST float* pNumSegs,CONST D3DRECTPATCH_INFO* pRectPatchInfo) { return m_device->DrawRectPatch(Handle, pNumSegs, pRectPatchInfo); } STDMETHOD(DrawTriPatch)(THIS_ UINT Handle,CONST float* pNumSegs,CONST D3DTRIPATCH_INFO* pTriPatchInfo) { return m_device->DrawTriPatch(Handle, pNumSegs, pTriPatchInfo); } STDMETHOD(DeletePatch)(THIS_ UINT Handle) { return m_device->DeletePatch(Handle); } STDMETHOD(CreateQuery)(THIS_ D3DQUERYTYPE Type,IDirect3DQuery9** ppQuery) { return m_device->CreateQuery(Type, ppQuery); } private: IDirect3DDevice9* m_device; IDirect3D9* m_d3d; }; class MyDirect3D9 : public IDirect3D9 { public: MyDirect3D9(IDirect3D9* d3d) : m_d3d(d3d) { } /*** IUnknown methods ***/ HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObj) { return m_d3d->QueryInterface(riid, ppvObj); } ULONG STDMETHODCALLTYPE AddRef() { return m_d3d->AddRef(); } ULONG STDMETHODCALLTYPE Release() { ULONG count = m_d3d->Release(); if(0 == count) delete this; return count; } /*** IDirect3D9 methods ***/ HRESULT STDMETHODCALLTYPE RegisterSoftwareDevice(void* pInitializeFunction) { return m_d3d->RegisterSoftwareDevice(pInitializeFunction); } UINT STDMETHODCALLTYPE GetAdapterCount() { return m_d3d->GetAdapterCount(); } HRESULT STDMETHODCALLTYPE GetAdapterIdentifier( UINT Adapter,DWORD Flags,D3DADAPTER_IDENTIFIER9* pIdentifier) { return m_d3d->GetAdapterIdentifier(Adapter, Flags, pIdentifier); } UINT STDMETHODCALLTYPE GetAdapterModeCount( UINT Adapter,D3DFORMAT Format) { return m_d3d->GetAdapterModeCount(Adapter, Format); } HRESULT STDMETHODCALLTYPE EnumAdapterModes( UINT Adapter,D3DFORMAT Format,UINT Mode,D3DDISPLAYMODE* pMode) { return m_d3d->EnumAdapterModes(Adapter, Format, Mode, pMode); } HRESULT STDMETHODCALLTYPE GetAdapterDisplayMode( UINT Adapter,D3DDISPLAYMODE* pMode) { return m_d3d->GetAdapterDisplayMode(Adapter, pMode); } HRESULT STDMETHODCALLTYPE CheckDeviceType( UINT Adapter,D3DDEVTYPE DevType,D3DFORMAT AdapterFormat,D3DFORMAT BackBufferFormat,BOOL bWindowed) { return m_d3d->CheckDeviceType(Adapter, DevType, AdapterFormat, BackBufferFormat, bWindowed); } HRESULT STDMETHODCALLTYPE CheckDeviceFormat( UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,DWORD Usage,D3DRESOURCETYPE RType,D3DFORMAT CheckFormat) { return m_d3d->CheckDeviceFormat(Adapter, DeviceType, AdapterFormat, Usage, RType, CheckFormat); } HRESULT STDMETHODCALLTYPE CheckDeviceMultiSampleType( UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SurfaceFormat,BOOL Windowed,D3DMULTISAMPLE_TYPE MultiSampleType,DWORD* pQualityLevels) { return m_d3d->CheckDeviceMultiSampleType(Adapter, DeviceType, SurfaceFormat, Windowed, MultiSampleType, pQualityLevels); } HRESULT STDMETHODCALLTYPE CheckDepthStencilMatch( UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT AdapterFormat,D3DFORMAT RenderTargetFormat,D3DFORMAT DepthStencilFormat) { return m_d3d->CheckDepthStencilMatch(Adapter, DeviceType, AdapterFormat, RenderTargetFormat, DepthStencilFormat); } HRESULT STDMETHODCALLTYPE CheckDeviceFormatConversion( UINT Adapter,D3DDEVTYPE DeviceType,D3DFORMAT SourceFormat,D3DFORMAT TargetFormat) { return m_d3d->CheckDeviceFormatConversion(Adapter, DeviceType, SourceFormat, TargetFormat); } HRESULT STDMETHODCALLTYPE GetDeviceCaps( UINT Adapter,D3DDEVTYPE DeviceType,D3DCAPS9* pCaps) { return m_d3d->GetDeviceCaps(Adapter, DeviceType, pCaps); } HMONITOR STDMETHODCALLTYPE GetAdapterMonitor( UINT Adapter) { return m_d3d->GetAdapterMonitor(Adapter); } HRESULT STDMETHODCALLTYPE CreateDevice( UINT Adapter,D3DDEVTYPE DeviceType,HWND hFocusWindow,DWORD BehaviorFlags,D3DPRESENT_PARAMETERS* pPresentationParameters,IDirect3DDevice9** ppReturnedDeviceInterface) { HRESULT hr = m_d3d->CreateDevice(Adapter, DeviceType, hFocusWindow, BehaviorFlags, pPresentationParameters, ppReturnedDeviceInterface); if(SUCCEEDED(hr)) { // Return our device OblivionDirect3D9Device = *ppReturnedDeviceInterface; *ppReturnedDeviceInterface = new MyDirect3DDevice9(this, *ppReturnedDeviceInterface); } return hr; } private: IDirect3D9* m_d3d; }; #endif
[ "masterfreek64@2644d07b-d655-0410-af38-4bee65694944", "obliviononline@2644d07b-d655-0410-af38-4bee65694944" ]
[ [ [ 1, 3 ], [ 5, 44 ], [ 46, 159 ], [ 172, 172 ], [ 176, 802 ] ], [ [ 4, 4 ], [ 45, 45 ], [ 160, 171 ], [ 173, 175 ] ] ]
ca2e6ccef7b0d32a92d668d1472fbf220a53c598
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_data_structures/app_properties/juce_ApplicationProperties.cpp
316fee590502719ab53fdc05dac4f56d1866130d
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
3,272
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== ApplicationProperties::ApplicationProperties() : commonSettingsAreReadOnly (0) { } ApplicationProperties::~ApplicationProperties() { closeFiles(); } //============================================================================== void ApplicationProperties::setStorageParameters (const PropertiesFile::Options& newOptions) { options = newOptions; } //============================================================================== void ApplicationProperties::openFiles() { // You need to call setStorageParameters() before trying to get hold of the properties! jassert (options.applicationName.isNotEmpty()); if (options.applicationName.isNotEmpty()) { PropertiesFile::Options o (options); if (userProps == nullptr) { o.commonToAllUsers = false; userProps = new PropertiesFile (o); } if (commonProps == nullptr) { o.commonToAllUsers = true; commonProps = new PropertiesFile (o); } userProps->setFallbackPropertySet (commonProps); } } PropertiesFile* ApplicationProperties::getUserSettings() { if (userProps == nullptr) openFiles(); return userProps; } PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) { if (commonProps == nullptr) openFiles(); if (returnUserPropsIfReadOnly) { if (commonSettingsAreReadOnly == 0) commonSettingsAreReadOnly = commonProps->save() ? -1 : 1; if (commonSettingsAreReadOnly > 0) return userProps; } return commonProps; } bool ApplicationProperties::saveIfNeeded() { return (userProps == nullptr || userProps->saveIfNeeded()) && (commonProps == nullptr || commonProps->saveIfNeeded()); } void ApplicationProperties::closeFiles() { userProps = nullptr; commonProps = nullptr; } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 109 ] ] ]
3f2ac5200e005374fe79f925af0909830c2efa6a
d39595c0c12a46ece1b1b41c92a9adcf7fe277ee
/main.cpp
7a3a927bd3c6ea25c1afefc70914c15db6844bc0
[]
no_license
pandabear41/Breakout
e89b85708b960e7dd83c22df1552141b1c937af9
64967248274055117b3cf709c084818039ec8278
refs/heads/master
2021-01-17T05:55:34.279752
2011-07-15T05:08:02
2011-07-15T05:08:02
2,039,821
0
0
null
null
null
null
UTF-8
C++
false
false
560
cpp
#include <time.h> #include "GameEngine.h" #include "IntroState.h" using namespace std; int main(int argc, char **argv) { // To get random number srand((unsigned) time(NULL)); // Start game. GameEngine* engine = new GameEngine(320, 240, false); // Begin IntroState AbstractGameState* state = new IntroState(); engine->setState(state); engine->setTickInterval(30); engine->setRenderInterval(30); // Keep alive engine->loop(); delete engine; engine = NULL; return 0; }
[ [ [ 1, 31 ] ] ]
6b7adc2d20b2060a1b7ad3ca2f09c52618d8fd06
3c22e8879c8060942ad1ba4a28835d7963e10bce
/trunk/scintilla/src/RESearch.cxx
5e7ae0f696435b6bc036e32cee8f6b0d09b2db74
[ "LicenseRef-scancode-scintilla" ]
permissive
svn2github/NotepadPlusPlus
b17f159f9fe6d8d650969b0555824d259d775d45
35b5304f02aaacfc156269c4b894159de53222ef
refs/heads/master
2021-01-22T09:05:19.267064
2011-01-31T01:46:36
2011-01-31T01:46:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,592
cxx
// Scintilla source code edit control /** @file RESearch.cxx ** Regular expression search library. **/ /* * regex - Regular expression pattern matching and replacement * * By: Ozan S. Yigit (oz) * Dept. of Computer Science * York University * * Original code available from http://www.cs.yorku.ca/~oz/ * Translation to C++ by Neil Hodgson [email protected] * Removed all use of register. * Converted to modern function prototypes. * Put all global/static variables into an object so this code can be * used from multiple threads, etc. * Some extensions by Philippe Lhoste PhiLho(a)GMX.net * * These routines are the PUBLIC DOMAIN equivalents of regex * routines as found in 4.nBSD UN*X, with minor extensions. * * These routines are derived from various implementations found * in software tools books, and Conroy's grep. They are NOT derived * from licensed/restricted software. * For more interesting/academic/complicated implementations, * see Henry Spencer's regexp routines, or GNU Emacs pattern * matching module. * * Modification history removed. * * Interfaces: * RESearch::Compile: compile a regular expression into a NFA. * * const char *RESearch::Compile(const char *pattern, int length, * bool caseSensitive, bool posix) * * Returns a short error string if they fail. * * RESearch::Execute: execute the NFA to match a pattern. * * int RESearch::Execute(characterIndexer &ci, int lp, int endp) * * RESearch::Substitute: substitute the matched portions in a new string. * * int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) * * re_fail: failure routine for RESearch::Execute. (no longer used) * * void re_fail(char *msg, char op) * * Regular Expressions: * * [1] char matches itself, unless it is a special * character (metachar): . \ [ ] * + ^ $ * and ( ) if posix option. * * [2] . matches any character. * * [3] \ matches the character following it, except: * - \a, \b, \f, \n, \r, \t, \v match the corresponding C * escape char, respectively BEL, BS, FF, LF, CR, TAB and VT; * Note that \r and \n are never matched because Scintilla * regex searches are made line per line * (stripped of end-of-line chars). * - if not in posix mode, when followed by a * left or right round bracket (see [7]); * - when followed by a digit 1 to 9 (see [8]); * - when followed by a left or right angle bracket * (see [9]); * - when followed by d, D, s, S, w or W (see [10]); * - when followed by x and two hexa digits (see [11]. * Backslash is used as an escape character for all * other meta-characters, and itself. * * [4] [set] matches one of the characters in the set. * If the first character in the set is "^", * it matches the characters NOT in the set, i.e. * complements the set. A shorthand S-E (start dash end) * is used to specify a set of characters S up to * E, inclusive. S and E must be characters, otherwise * the dash is taken literally (eg. in expression [\d-a]). * The special characters "]" and "-" have no special * meaning if they appear as the first chars in the set. * To include both, put - first: [-]A-Z] * (or just backslash them). * examples: match: * * [-]|] matches these 3 chars, * * []-|] matches from ] to | chars * * [a-z] any lowercase alpha * * [^-]] any char except - and ] * * [^A-Z] any char except uppercase * alpha * * [a-zA-Z] any alpha * * [5] * any regular expression form [1] to [4] * (except [7], [8] and [9] forms of [3]), * followed by closure char (*) * matches zero or more matches of that form. * * [6] + same as [5], except it matches one or more. * Both [5] and [6] are greedy (they match as much as possible). * * [7] a regular expression in the form [1] to [12], enclosed * as \(form\) (or (form) with posix flag) matches what * form matches. The enclosure creates a set of tags, * used for [8] and for pattern substitution. * The tagged forms are numbered starting from 1. * * [8] a \ followed by a digit 1 to 9 matches whatever a * previously tagged regular expression ([7]) matched. * * [9] \< a regular expression starting with a \< construct * \> and/or ending with a \> construct, restricts the * pattern matching to the beginning of a word, and/or * the end of a word. A word is defined to be a character * string beginning and/or ending with the characters * A-Z a-z 0-9 and _. Scintilla extends this definition * by user setting. The word must also be preceded and/or * followed by any character outside those mentioned. * * [10] \l a backslash followed by d, D, s, S, w or W, * becomes a character class (both inside and * outside sets []). * d: decimal digits * D: any char except decimal digits * s: whitespace (space, \t \n \r \f \v) * S: any char except whitespace (see above) * w: alphanumeric & underscore (changed by user setting) * W: any char except alphanumeric & underscore (see above) * * [11] \xHH a backslash followed by x and two hexa digits, * becomes the character whose Ascii code is equal * to these digits. If not followed by two digits, * it is 'x' char itself. * * [12] a composite regular expression xy where x and y * are in the form [1] to [11] matches the longest * match of x followed by a match for y. * * [13] ^ a regular expression starting with a ^ character * $ and/or ending with a $ character, restricts the * pattern matching to the beginning of the line, * or the end of line. [anchors] Elsewhere in the * pattern, ^ and $ are treated as ordinary characters. * * * Acknowledgements: * * HCR's Hugh Redelmeier has been most helpful in various * stages of development. He convinced me to include BOW * and EOW constructs, originally invented by Rob Pike at * the University of Toronto. * * References: * Software tools Kernighan & Plauger * Software tools in Pascal Kernighan & Plauger * Grep [rsx-11 C dist] David Conroy * ed - text editor Un*x Programmer's Manual * Advanced editing on Un*x B. W. Kernighan * RegExp routines Henry Spencer * * Notes: * * This implementation uses a bit-set representation for character * classes for speed and compactness. Each character is represented * by one bit in a 256-bit block. Thus, CCL always takes a * constant 32 bytes in the internal nfa, and RESearch::Execute does a single * bit comparison to locate the character in the set. * * Examples: * * pattern: foo*.* * compile: CHR f CHR o CLO CHR o END CLO ANY END END * matches: fo foo fooo foobar fobar foxx ... * * pattern: fo[ob]a[rz] * compile: CHR f CHR o CCL bitset CHR a CCL bitset END * matches: fobar fooar fobaz fooaz * * pattern: foo\\+ * compile: CHR f CHR o CHR o CHR \ CLO CHR \ END END * matches: foo\ foo\\ foo\\\ ... * * pattern: \(foo\)[1-3]\1 (same as foo[1-3]foo) * compile: BOT 1 CHR f CHR o CHR o EOT 1 CCL bitset REF 1 END * matches: foo1foo foo2foo foo3foo * * pattern: \(fo.*\)-\1 * compile: BOT 1 CHR f CHR o CLO ANY END EOT 1 CHR - REF 1 END * matches: foo-foo fo-fo fob-fob foobar-foobar ... */ #include <stdlib.h> #include "CharClassify.h" #include "RESearch.h" // Shut up annoying Visual C++ warnings: #ifdef _MSC_VER #pragma warning(disable: 4514) #endif #ifdef SCI_NAMESPACE using namespace Scintilla; #endif #define OKP 1 #define NOP 0 #define CHR 1 #define ANY 2 #define CCL 3 #define BOL 4 #define EOL 5 #define BOT 6 #define EOT 7 #define BOW 8 #define EOW 9 #define REF 10 #define CLO 11 #define END 0 /* * The following defines are not meant to be changeable. * They are for readability only. */ #define BLKIND 0370 #define BITIND 07 const char bitarr[] = { 1, 2, 4, 8, 16, 32, 64, '\200' }; #define badpat(x) (*nfa = END, x) /* * Character classification table for word boundary operators BOW * and EOW is passed in by the creator of this object (Scintilla * Document). The Document default state is that word chars are: * 0-9, a-z, A-Z and _ */ RESearch::RESearch(CharClassify *charClassTable) { failure = 0; charClass = charClassTable; Init(); } RESearch::~RESearch() { Clear(); } void RESearch::Init() { sta = NOP; /* status of lastpat */ bol = 0; for (int i = 0; i < MAXTAG; i++) pat[i] = 0; for (int j = 0; j < BITBLK; j++) bittab[j] = 0; } void RESearch::Clear() { for (int i = 0; i < MAXTAG; i++) { delete []pat[i]; pat[i] = 0; bopat[i] = NOTFOUND; eopat[i] = NOTFOUND; } } bool RESearch::GrabMatches(CharacterIndexer &ci) { bool success = true; for (unsigned int i = 0; i < MAXTAG; i++) { if ((bopat[i] != NOTFOUND) && (eopat[i] != NOTFOUND)) { unsigned int len = eopat[i] - bopat[i]; pat[i] = new char[len + 1]; if (pat[i]) { for (unsigned int j = 0; j < len; j++) pat[i][j] = ci.CharAt(bopat[i] + j); pat[i][len] = '\0'; } else { success = false; } } } return success; } void RESearch::ChSet(unsigned char c) { bittab[((c) & BLKIND) >> 3] |= bitarr[(c) & BITIND]; } void RESearch::ChSetWithCase(unsigned char c, bool caseSensitive) { if (caseSensitive) { ChSet(c); } else { if ((c >= 'a') && (c <= 'z')) { ChSet(c); ChSet(static_cast<unsigned char>(c - 'a' + 'A')); } else if ((c >= 'A') && (c <= 'Z')) { ChSet(c); ChSet(static_cast<unsigned char>(c - 'A' + 'a')); } else { ChSet(c); } } } const unsigned char escapeValue(unsigned char ch) { switch (ch) { case 'a': return '\a'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; } return 0; } static int GetHexaChar(unsigned char hd1, unsigned char hd2) { int hexValue = 0; if (hd1 >= '0' && hd1 <= '9') { hexValue += 16 * (hd1 - '0'); } else if (hd1 >= 'A' && hd1 <= 'F') { hexValue += 16 * (hd1 - 'A' + 10); } else if (hd1 >= 'a' && hd1 <= 'f') { hexValue += 16 * (hd1 - 'a' + 10); } else return -1; if (hd2 >= '0' && hd2 <= '9') { hexValue += hd2 - '0'; } else if (hd2 >= 'A' && hd2 <= 'F') { hexValue += hd2 - 'A' + 10; } else if (hd2 >= 'a' && hd2 <= 'f') { hexValue += hd2 - 'a' + 10; } else return -1; return hexValue; } /** * Called when the parser finds a backslash not followed * by a valid expression (like \( in non-Posix mode). * @param pattern: pointer on the char after the backslash. * @param incr: (out) number of chars to skip after expression evaluation. * @return the char if it resolves to a simple char, * or -1 for a char class. In this case, bittab is changed. */ int RESearch::GetBackslashExpression( const char *pattern, int &incr) { // Since error reporting is primitive and messages are not used anyway, // I choose to interpret unexpected syntax in a logical way instead // of reporting errors. Otherwise, we can stick on, eg., PCRE behavior. incr = 0; // Most of the time, will skip the char "naturally". int c; int result = -1; unsigned char bsc = *pattern; if (!bsc) { // Avoid overrun result = '\\'; // \ at end of pattern, take it literally return result; } switch (bsc) { case 'a': case 'b': case 'n': case 'f': case 'r': case 't': case 'v': result = escapeValue(bsc); break; case 'x': { unsigned char hd1 = *(pattern + 1); unsigned char hd2 = *(pattern + 2); int hexValue = GetHexaChar(hd1, hd2); if (hexValue >= 0) { result = hexValue; incr = 2; // Must skip the digits } else { result = 'x'; // \x without 2 digits: see it as 'x' } } break; case 'd': for (c = '0'; c <= '9'; c++) { ChSet(static_cast<unsigned char>(c)); } break; case 'D': for (c = 0; c < MAXCHR; c++) { if (c < '0' || c > '9') { ChSet(static_cast<unsigned char>(c)); } } break; case 's': ChSet(' '); ChSet('\t'); ChSet('\n'); ChSet('\r'); ChSet('\f'); ChSet('\v'); break; case 'S': for (c = 0; c < MAXCHR; c++) { if (c != ' ' && !(c >= 0x09 && c <= 0x0D)) { ChSet(static_cast<unsigned char>(c)); } } break; case 'w': for (c = 0; c < MAXCHR; c++) { if (iswordc(static_cast<unsigned char>(c))) { ChSet(static_cast<unsigned char>(c)); } } break; case 'W': for (c = 0; c < MAXCHR; c++) { if (!iswordc(static_cast<unsigned char>(c))) { ChSet(static_cast<unsigned char>(c)); } } break; default: result = bsc; } return result; } const char *RESearch::Compile(const char *pattern, int length, bool caseSensitive, bool posix) { char *mp=nfa; /* nfa pointer */ char *lp; /* saved pointer */ char *sp=nfa; /* another one */ char *mpMax = mp + MAXNFA - BITBLK - 10; int tagi = 0; /* tag stack index */ int tagc = 1; /* actual tag count */ int n; char mask; /* xor mask -CCL/NCL */ int c1, c2, prevChar; if (!pattern || !length) { if (sta) return 0; else return badpat("No previous regular expression"); } sta = NOP; const char *p=pattern; /* pattern pointer */ for (int i=0; i<length; i++, p++) { if (mp > mpMax) return badpat("Pattern too long"); lp = mp; switch (*p) { case '.': /* match any char */ *mp++ = ANY; break; case '^': /* match beginning */ if (p == pattern) *mp++ = BOL; else { *mp++ = CHR; *mp++ = *p; } break; case '$': /* match endofline */ if (!*(p+1)) *mp++ = EOL; else { *mp++ = CHR; *mp++ = *p; } break; case '[': /* match char class */ *mp++ = CCL; prevChar = 0; i++; if (*++p == '^') { mask = '\377'; i++; p++; } else mask = 0; if (*p == '-') { /* real dash */ i++; prevChar = *p; ChSet(*p++); } if (*p == ']') { /* real brace */ i++; prevChar = *p; ChSet(*p++); } while (*p && *p != ']') { if (*p == '-') { if (prevChar < 0) { // Previous def. was a char class like \d, take dash literally prevChar = *p; ChSet(*p); } else if (*(p+1)) { if (*(p+1) != ']') { c1 = prevChar + 1; i++; c2 = static_cast<unsigned char>(*++p); if (c2 == '\\') { if (!*(p+1)) // End of RE return badpat("Missing ]"); else { i++; p++; int incr; c2 = GetBackslashExpression(p, incr); i += incr; p += incr; if (c2 >= 0) { // Convention: \c (c is any char) is case sensitive, whatever the option ChSet(static_cast<unsigned char>(c2)); prevChar = c2; } else { // bittab is already changed prevChar = -1; } } } if (prevChar < 0) { // Char after dash is char class like \d, take dash literally prevChar = '-'; ChSet('-'); } else { // Put all chars between c1 and c2 included in the char set while (c1 <= c2) { ChSetWithCase(static_cast<unsigned char>(c1++), caseSensitive); } } } else { // Dash before the ], take it literally prevChar = *p; ChSet(*p); } } else { return badpat("Missing ]"); } } else if (*p == '\\' && *(p+1)) { i++; p++; int incr; int c = GetBackslashExpression(p, incr); i += incr; p += incr; if (c >= 0) { // Convention: \c (c is any char) is case sensitive, whatever the option ChSet(static_cast<unsigned char>(c)); prevChar = c; } else { // bittab is already changed prevChar = -1; } } else { prevChar = static_cast<unsigned char>(*p); ChSetWithCase(*p, caseSensitive); } i++; p++; } if (!*p) return badpat("Missing ]"); for (n = 0; n < BITBLK; bittab[n++] = 0) *mp++ = static_cast<char>(mask ^ bittab[n]); break; case '*': /* match 0 or more... */ case '+': /* match 1 or more... */ if (p == pattern) return badpat("Empty closure"); lp = sp; /* previous opcode */ if (*lp == CLO) /* equivalence... */ break; switch (*lp) { case BOL: case BOT: case EOT: case BOW: case EOW: case REF: return badpat("Illegal closure"); default: break; } if (*p == '+') for (sp = mp; lp < sp; lp++) *mp++ = *lp; *mp++ = END; *mp++ = END; sp = mp; while (--mp > lp) *mp = mp[-1]; *mp = CLO; mp = sp; break; case '\\': /* tags, backrefs... */ i++; switch (*++p) { case '<': *mp++ = BOW; break; case '>': if (*sp == BOW) return badpat("Null pattern inside \\<\\>"); *mp++ = EOW; break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': n = *p-'0'; if (tagi > 0 && tagstk[tagi] == n) return badpat("Cyclical reference"); if (tagc > n) { *mp++ = static_cast<char>(REF); *mp++ = static_cast<char>(n); } else return badpat("Undetermined reference"); break; default: if (!posix && *p == '(') { if (tagc < MAXTAG) { tagstk[++tagi] = tagc; *mp++ = BOT; *mp++ = static_cast<char>(tagc++); } else return badpat("Too many \\(\\) pairs"); } else if (!posix && *p == ')') { if (*sp == BOT) return badpat("Null pattern inside \\(\\)"); if (tagi > 0) { *mp++ = static_cast<char>(EOT); *mp++ = static_cast<char>(tagstk[tagi--]); } else return badpat("Unmatched \\)"); } else { int incr; int c = GetBackslashExpression(p, incr); i += incr; p += incr; if (c >= 0) { *mp++ = CHR; *mp++ = static_cast<unsigned char>(c); } else { *mp++ = CCL; mask = 0; for (n = 0; n < BITBLK; bittab[n++] = 0) *mp++ = static_cast<char>(mask ^ bittab[n]); } } } break; default : /* an ordinary char */ if (posix && *p == '(') { if (tagc < MAXTAG) { tagstk[++tagi] = tagc; *mp++ = BOT; *mp++ = static_cast<char>(tagc++); } else return badpat("Too many () pairs"); } else if (posix && *p == ')') { if (*sp == BOT) return badpat("Null pattern inside ()"); if (tagi > 0) { *mp++ = static_cast<char>(EOT); *mp++ = static_cast<char>(tagstk[tagi--]); } else return badpat("Unmatched )"); } else { unsigned char c = *p; if (!c) // End of RE c = '\\'; // We take it as raw backslash if (caseSensitive || !iswordc(c)) { *mp++ = CHR; *mp++ = c; } else { *mp++ = CCL; mask = 0; ChSetWithCase(c, false); for (n = 0; n < BITBLK; bittab[n++] = 0) *mp++ = static_cast<char>(mask ^ bittab[n]); } } break; } sp = lp; } if (tagi > 0) return badpat((posix ? "Unmatched (" : "Unmatched \\(")); *mp = END; sta = OKP; return 0; } /* * RESearch::Execute: * execute nfa to find a match. * * special cases: (nfa[0]) * BOL * Match only once, starting from the * beginning. * CHR * First locate the character without * calling PMatch, and if found, call * PMatch for the remaining string. * END * RESearch::Compile failed, poor luser did not * check for it. Fail fast. * * If a match is found, bopat[0] and eopat[0] are set * to the beginning and the end of the matched fragment, * respectively. * */ int RESearch::Execute(CharacterIndexer &ci, int lp, int endp) { unsigned char c; int ep = NOTFOUND; char *ap = nfa; bol = lp; failure = 0; Clear(); switch (*ap) { case BOL: /* anchored: match from BOL only */ ep = PMatch(ci, lp, endp, ap); break; case EOL: /* just searching for end of line normal path doesn't work */ if (*(ap+1) == END) { lp = endp; ep = lp; break; } else { return 0; } case CHR: /* ordinary char: locate it fast */ c = *(ap+1); while ((lp < endp) && (ci.CharAt(lp) != c)) lp++; if (lp >= endp) /* if EOS, fail, else fall thru. */ return 0; default: /* regular matching all the way. */ while (lp < endp) { ep = PMatch(ci, lp, endp, ap); if (ep != NOTFOUND) break; lp++; } break; case END: /* munged automaton. fail always */ return 0; } if (ep == NOTFOUND) return 0; bopat[0] = lp; eopat[0] = ep; return 1; } /* * PMatch: internal routine for the hard part * * This code is partly snarfed from an early grep written by * David Conroy. The backref and tag stuff, and various other * innovations are by oz. * * special case optimizations: (nfa[n], nfa[n+1]) * CLO ANY * We KNOW .* will match everything upto the * end of line. Thus, directly go to the end of * line, without recursive PMatch calls. As in * the other closure cases, the remaining pattern * must be matched by moving backwards on the * string recursively, to find a match for xy * (x is ".*" and y is the remaining pattern) * where the match satisfies the LONGEST match for * x followed by a match for y. * CLO CHR * We can again scan the string forward for the * single char and at the point of failure, we * execute the remaining nfa recursively, same as * above. * * At the end of a successful match, bopat[n] and eopat[n] * are set to the beginning and end of subpatterns matched * by tagged expressions (n = 1 to 9). */ extern void re_fail(char *,char); #define isinset(x,y) ((x)[((y)&BLKIND)>>3] & bitarr[(y)&BITIND]) /* * skip values for CLO XXX to skip past the closure */ #define ANYSKIP 2 /* [CLO] ANY END */ #define CHRSKIP 3 /* [CLO] CHR chr END */ #define CCLSKIP 34 /* [CLO] CCL 32 bytes END */ int RESearch::PMatch(CharacterIndexer &ci, int lp, int endp, char *ap) { int op, c, n; int e; /* extra pointer for CLO */ int bp; /* beginning of subpat... */ int ep; /* ending of subpat... */ int are; /* to save the line ptr. */ while ((op = *ap++) != END) switch (op) { case CHR: if (ci.CharAt(lp++) != *ap++) return NOTFOUND; break; case ANY: if (lp++ >= endp) return NOTFOUND; break; case CCL: if (lp >= endp) return NOTFOUND; c = ci.CharAt(lp++); if (!isinset(ap,c)) return NOTFOUND; ap += BITBLK; break; case BOL: if (lp != bol) return NOTFOUND; break; case EOL: if (lp < endp) return NOTFOUND; break; case BOT: bopat[*ap++] = lp; break; case EOT: eopat[*ap++] = lp; break; case BOW: if ((lp!=bol && iswordc(ci.CharAt(lp-1))) || !iswordc(ci.CharAt(lp))) return NOTFOUND; break; case EOW: if (lp==bol || !iswordc(ci.CharAt(lp-1)) || iswordc(ci.CharAt(lp))) return NOTFOUND; break; case REF: n = *ap++; bp = bopat[n]; ep = eopat[n]; while (bp < ep) if (ci.CharAt(bp++) != ci.CharAt(lp++)) return NOTFOUND; break; case CLO: are = lp; switch (*ap) { case ANY: while (lp < endp) lp++; n = ANYSKIP; break; case CHR: c = *(ap+1); while ((lp < endp) && (c == ci.CharAt(lp))) lp++; n = CHRSKIP; break; case CCL: while ((lp < endp) && isinset(ap+1,ci.CharAt(lp))) lp++; n = CCLSKIP; break; default: failure = true; //re_fail("closure: bad nfa.", *ap); return NOTFOUND; } ap += n; while (lp >= are) { if ((e = PMatch(ci, lp, endp, ap)) != NOTFOUND) return e; --lp; } return NOTFOUND; default: //re_fail("RESearch::Execute: bad nfa.", static_cast<char>(op)); return NOTFOUND; } return lp; } /* * RESearch::Substitute: * substitute the matched portions of the src in dst. * * & substitute the entire matched pattern. * * \digit substitute a subpattern, with the given tag number. * Tags are numbered from 1 to 9. If the particular * tagged subpattern does not exist, null is substituted. */ int RESearch::Substitute(CharacterIndexer &ci, char *src, char *dst) { unsigned char c; int pin; int bp; int ep; if (!*src || !bopat[0]) return 0; while ((c = *src++) != 0) { switch (c) { case '&': pin = 0; break; case '\\': c = *src++; if (c >= '0' && c <= '9') { pin = c - '0'; break; } default: *dst++ = c; continue; } if ((bp = bopat[pin]) != 0 && (ep = eopat[pin]) != 0) { while (ci.CharAt(bp) && bp < ep) *dst++ = ci.CharAt(bp++); if (bp < ep) return 0; } } *dst = '\0'; return 1; }
[ "donho@9e717b3d-e3cd-45c4-bdc4-af0eb0386351" ]
[ [ [ 1, 987 ] ] ]
ba1c02ded3309b434e7e9ccc2d536eba6ec2e8cb
40b507c2dde13d14bb75ee1b3c16b4f3f82912d1
/extensions/sqlite/driver/SqQuery.cpp
fce5ae07f50c6718659c0f9f61b76f6151e8b296
[]
no_license
Nephyrin/-furry-octo-nemesis
5da2ef75883ebc4040e359a6679da64ad8848020
dd441c39bd74eda2b9857540dcac1d98706de1de
refs/heads/master
2016-09-06T01:12:49.611637
2008-09-14T08:42:28
2008-09-14T08:42:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,042
cpp
/** * vim: set ts=4 : * ============================================================================= * SourceMod SQLite Extension * Copyright (C) 2004-2007 AlliedModders LLC. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, AlliedModders LLC gives you permission to link the * code of this program (as well as its derivative works) to "Half-Life 2," the * "Source Engine," the "SourcePawn JIT," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, AlliedModders LLC grants * this exception to all derivative works. AlliedModders LLC defines further * exceptions, found in LICENSE.txt (as of this writing, version JULY-31-2007), * or <http://www.sourcemod.net/license.php>. * * Version: $Id$ */ #include "SqQuery.h" SqQuery::SqQuery(SqDatabase *parent, sqlite3_stmt *stmt) : m_pParent(parent), m_pStmt(stmt), m_pResults(NULL), m_AffectedRows(0), m_InsertID(0) { m_ParamCount = sqlite3_bind_parameter_count(m_pStmt); m_ColCount = sqlite3_column_count(m_pStmt); m_pParent->IncReferenceCount(); } SqQuery::~SqQuery() { delete m_pResults; sqlite3_finalize(m_pStmt); m_pParent->Close(); } IResultSet *SqQuery::GetResultSet() { return m_pResults; } bool SqQuery::FetchMoreResults() { /* We never have multiple result sets */ return false; } void SqQuery::Destroy() { delete this; } bool SqQuery::BindParamFloat(unsigned int param, float f) { /* SQLite is 1 indexed */ param++; if (param > m_ParamCount) { return false; } return (sqlite3_bind_double(m_pStmt, param, (double)f) == SQLITE_OK); } bool SqQuery::BindParamNull(unsigned int param) { /* SQLite is 1 indexed */ param++; if (param > m_ParamCount) { return false; } return (sqlite3_bind_null(m_pStmt, param) == SQLITE_OK); } bool SqQuery::BindParamString(unsigned int param, const char *text, bool copy) { /* SQLite is 1 indexed */ param++; if (param > m_ParamCount) { return false; } return (sqlite3_bind_text(m_pStmt, param, text, -1, copy ? SQLITE_TRANSIENT : SQLITE_STATIC) == SQLITE_OK); } bool SqQuery::BindParamInt(unsigned int param, int num, bool signd/* =true */) { /* SQLite is 1 indexed */ param++; if (param > m_ParamCount) { return false; } return (sqlite3_bind_int(m_pStmt, param, num) == SQLITE_OK); } bool SqQuery::BindParamBlob(unsigned int param, const void *data, size_t length, bool copy) { /* SQLite is 1 indexed */ param++; if (param > m_ParamCount) { return false; } return (sqlite3_bind_blob(m_pStmt, param, data, length, copy ? SQLITE_TRANSIENT : SQLITE_STATIC) == SQLITE_OK); } sqlite3_stmt *SqQuery::GetStmt() { return m_pStmt; } bool SqQuery::Execute() { int rc; /* If we don't have a result set and we have a column count, * create a result set pre-emptively. This is in case there * are no rows in the upcoming result set. */ if (!m_pResults && m_ColCount) { m_pResults = new SqResults(this); } /* If we've got results, throw them away */ if (m_pResults) { m_pResults->ResetResultCount(); } /* Fetch each row, if any */ while ((rc = sqlite3_step(m_pStmt)) == SQLITE_ROW) { /* This should NEVER happen but we're being safe. */ if (!m_pResults) { m_pResults = new SqResults(this); } m_pResults->PushResult(); } sqlite3 *db = m_pParent->GetDb(); if (rc != SQLITE_OK && rc != SQLITE_DONE && rc == sqlite3_errcode(db)) { /* Something happened... */ m_LastErrorCode = rc; m_LastError.assign(sqlite3_errmsg(db)); m_AffectedRows = 0; m_InsertID = 0; } else { m_LastErrorCode = SQLITE_OK; m_AffectedRows = (unsigned int)sqlite3_changes(db); m_InsertID = (unsigned int)sqlite3_last_insert_rowid(db); } /* Reset everything for the next execute */ sqlite3_reset(m_pStmt); sqlite3_clear_bindings(m_pStmt); return (m_LastErrorCode == SQLITE_OK); } const char *SqQuery::GetError(int *errCode/* =NULL */) { if (errCode) { *errCode = m_LastErrorCode; } return m_LastError.c_str(); } unsigned int SqQuery::GetAffectedRows() { return m_AffectedRows; } unsigned int SqQuery::GetInsertID() { return m_InsertID; }
[ [ [ 1, 2 ], [ 4, 5 ], [ 7, 7 ], [ 11, 11 ], [ 16, 16 ], [ 19, 19 ], [ 28, 205 ] ], [ [ 3, 3 ], [ 6, 6 ], [ 8, 10 ], [ 12, 15 ], [ 17, 18 ], [ 20, 27 ] ] ]
d8db15af2260a1640b5cae55850b871e784e082c
282057a05d0cbf9a0fe87457229f966a2ecd3550
/EIBServer/src/ServerConfig.cpp
cdad6ed5341cfb5be72433e53529952d51421923
[]
no_license
radtek/eibsuite
0d1b1c826f16fc7ccfd74d5e82a6f6bf18892dcd
4504fcf4fa8c7df529177b3460d469b5770abf7a
refs/heads/master
2021-05-29T08:34:08.764000
2011-12-06T20:42:06
2011-12-06T20:42:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,007
cpp
#include "ServerConfig.h" CServerConfig::CServerConfig(void) : _load_ok(false) { } CServerConfig::~CServerConfig(void) { } bool CServerConfig::Load(const CString& file_name) { _load_ok = false; Init(); if(!this->LoadFromFile(file_name)) { throw CEIBException(ConfigFileError,"Config file Not Exist."); } list<CConfigBlock>::iterator it; for (it = _conf.begin();it != _conf.end();it++) { CConfigBlock& block = (CConfigBlock&)*it; if(block.GetName() == GENERAL_BLOCK_NAME) { LoadGeneralBlock(block.GetParams(),file_name); } } _load_ok = true; return true; } bool CServerConfig::Save(const CString& file_name) { if(!_load_ok){ //we didn't load the file properly --> we should change it but let the user do it return true; } list<CConfigBlock>::iterator it_blocks; if(_conf.size() == 0){ CConfigBlock gen_block; CString b_name = GENERAL_BLOCK_NAME; gen_block.SetName(b_name); _conf.insert(_conf.end(),gen_block); } for ( it_blocks=_conf.begin() ; it_blocks != _conf.end(); it_blocks++ ) { CConfigBlock& block = (CConfigBlock&)*it_blocks; if(block.GetName() == GENERAL_BLOCK_NAME) { SaveGeneralBlock(block); } } this->SaveToFile(file_name); return true; } void CServerConfig::Init() { #define CONF_ENTRY(var_type, method_name, user_string, def_val) \ this->_##method_name = def_val; #include "GeneralConf.h" #undef CONF_ENTRY } void CServerConfig::SaveGeneralBlock(CConfigBlock& block) { CConfParam pv; #define CONF_ENTRY(var_type, method_name, user_string, def_val) \ ParamToString(pv.GetValue(),this->_##method_name); \ pv.SetName(user_string); \ block.Update(pv); #include "GeneralConf.h" #undef CONF_ENTRY } void CServerConfig::LoadGeneralBlock(list<CConfParam>& params, const CString& file_name) { list<CConfParam>::iterator it; for (it = params.begin();it != params.end();it++) { CConfParam& pv = (CConfParam&)*it; #define CONF_ENTRY(var_type, method_name, user_string, def_val) \ if (pv.GetName() == user_string){ \ ParamFromString(pv.GetValue(), this->_##method_name); \ pv.SetValid(true);\ } #include "GeneralConf.h" #undef CONF_ENTRY } for (it = params.begin();it != params.end();it++) { CConfParam& pv = (CConfParam&)*it; if(!pv.IsValid()){ CString err_str = "Unknown parameter \""; err_str += pv.GetName(); err_str += "\" in file "; err_str += file_name; throw CEIBException(ConfigFileError,err_str); } } } void CServerConfig::ToXml(CDataBuffer& xml_str) { //CXmlNode conf_node = _doc.RootElement().InsertChild(CONFIG_XML); #define CONF_ENTRY(var_type, method_name, user_string, def_val) \ {CXmlElement elem = _doc.RootElement().InsertChild(user_string);\ elem.SetValue(this->Get##method_name());} #include "GeneralConf.h" #undef CONF_ENTRY _doc.ToString(xml_str); } void CServerConfig::FromXml(const CDataBuffer& xml_str) { }
[ [ [ 1, 127 ] ] ]
63a9beaeb7734f623a8b1e62aeb02e57c4061526
7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3
/src/option/MDITabDialog.h
ac60ba237e2c7037d94e8a14e6dca9edd921f4e7
[]
no_license
plus7/DonutG
b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6
2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b
refs/heads/master
2020-06-01T15:30:31.747022
2010-08-21T18:51:01
2010-08-21T18:51:01
767,753
1
2
null
null
null
null
SHIFT_JIS
C++
false
false
9,530
h
/** * @file MDITabDialog.h * @brief donutのオプション : タブバー */ #pragma once #include "../MDITabCtrl.h" class CMDITabPropertyPage : public CInitPropertyPageImpl< CMDITabPropertyPage > , public CWinDataExchange< CMDITabPropertyPage > { public: // Constants enum { IDD = IDD_PROPPAGE_MDITAB }; private: // Data members int m_nAddPos; int m_nMultiLine; int m_nWheel; int m_nFixedSize; int m_nAnchorColor; int m_nRadioRightClick; int m_nRadioDoubleClick; int m_nRadioXClick; int m_nRadioOnClose; int m_nAddLinkRight; int m_nFixedSizeX; int m_nFixedSizeY; int m_nMaxTextLength; CMDITabCtrl* m_pMDITab; BOOL m_bInit; HMENU m_hMenu; int m_nLastCurSel; int m_nXCmd; int m_nDCmd; int m_nRCmd; int m_nMouseDownSelect; int m_nCtrlTabMDI; //+++ CTRL(+SHIFT)+TABでの移動をMDIの順番にする場合on public: // DDX map BEGIN_DDX_MAP( CMDITabPropertyPage ) DDX_CHECK ( IDC_CHECK_WHEEL , m_nWheel ) DDX_CHECK ( IDC_CHECK_MDITAB_MULTILINE , m_nMultiLine ) DDX_CHECK ( IDC_CHECK_MDITAB_FIXEDSIZE , m_nFixedSize ) DDX_CHECK ( IDC_CHECK_MDITAB_ANCHORCOLOR , m_nAnchorColor ) DDX_CHECK ( IDC_CHECK_ADDLINKACTIVERIGHT , m_nAddLinkRight ) DDX_CHECK ( IDC_CHECK_CTRLTAB_MDI , m_nCtrlTabMDI ) //+++ DDX_INT_RANGE ( IDC_EDIT_MDITAB_FIXEDSIZEX , m_nFixedSizeX, 1, 500 ) DDX_INT_RANGE ( IDC_EDIT_MDITAB_FIXEDSIZEY , m_nFixedSizeY, 1, 500 ) DDX_CBINDEX ( IDC_COMBO_MDITAB_ADDPOS , m_nAddPos ) DDX_CBINDEX ( IDC_COMBO_MDITAB_RIGHTCLICK , m_nRadioRightClick ) DDX_CBINDEX ( IDC_COMBO_MDITAB_DOUBLECLICK , m_nRadioDoubleClick ) DDX_CBINDEX ( IDC_COMBO_MDITAB_MCLICK , m_nRadioXClick ) DDX_CBINDEX ( IDC_COMBO_ONCLOSE , m_nRadioOnClose ) DDX_INT_RANGE ( IDC_EDIT_TABTEXTMAX , m_nMaxTextLength, 1, 255 ) DDX_CHECK ( IDC_CHECK_MOUSEDOWNSELECT , m_nMouseDownSelect ) END_DDX_MAP() public: // Constructor CMDITabPropertyPage(CMDITabCtrl *pMDITab, HMENU hMenu) : m_pMDITab(pMDITab) , m_bInit(FALSE) , m_hMenu(hMenu) { DWORD dwExStyle = m_pMDITab->GetMDITabExtendedStyle(); m_nWheel = (dwExStyle & MTB_EX_WHEEL ) != 0; m_nFixedSize = (dwExStyle & MTB_EX_FIXEDSIZE ) != 0; m_nMultiLine = (dwExStyle & MTB_EX_MULTILINE ) != 0; m_nAnchorColor = (dwExStyle & MTB_EX_ANCHORCOLOR ) != 0; m_nAddLinkRight = (dwExStyle & MTB_EX_ADDLINKACTIVERIGHT ) != 0; m_nMouseDownSelect = (dwExStyle & MTB_EX_MOUSEDOWNSELECT ) != 0; m_nCtrlTabMDI = (dwExStyle & MTB_EX_CTRLTAB_MDI ) != 0; //+++ CSize sizeItem = m_pMDITab->GetItemSize(); m_nFixedSizeX = sizeItem.cx; m_nFixedSizeY = sizeItem.cy; m_nMaxTextLength = m_pMDITab->GetMaxTabItemTextLength(); m_nLastCurSel = 1; if (dwExStyle & MTB_EX_RIGHTCLICKCLOSE ) m_nRadioRightClick = 1; else if (dwExStyle & MTB_EX_RIGHTCLICKREFRESH) m_nRadioRightClick = 2; else if (dwExStyle & MTB_EX_RIGHTCLICKCOMMAND) m_nRadioRightClick = 4; // minit else m_nRadioRightClick = 0; if (dwExStyle & MTB_EX_DOUBLECLICKCLOSE ) m_nRadioDoubleClick = 1; else if (dwExStyle & MTB_EX_DOUBLECLICKREFRESH) m_nRadioDoubleClick = 2; else if (dwExStyle & MTB_EX_DOUBLECLICKNLOCK ) m_nRadioDoubleClick = 3; // UDT DGSTR else if (dwExStyle & MTB_EX_DOUBLECLICKCOMMAND) m_nRadioDoubleClick = 5; // minit else m_nRadioDoubleClick = 0; if (dwExStyle & MTB_EX_XCLICKCLOSE ) m_nRadioXClick = 1; else if (dwExStyle & MTB_EX_XCLICKREFRESH ) m_nRadioXClick = 2; else if (dwExStyle & MTB_EX_XCLICKNLOCK ) m_nRadioXClick = 3; // UDT DGSTR else if (dwExStyle & MTB_EX_XCLICKCOMMAND ) m_nRadioXClick = 5; // minit else m_nRadioXClick = 0; if (dwExStyle & MTB_EX_RIGHTACTIVEONCLOSE) m_nRadioOnClose = 1; else if (dwExStyle & MTB_EX_LEFTACTIVEONCLOSE ) m_nRadioOnClose = 2; else m_nRadioOnClose = 0; if (dwExStyle & MTB_EX_ADDLEFT ) m_nAddPos = 1; else if (dwExStyle & MTB_EX_ADDRIGHTACTIVE ) m_nAddPos = 2; else if (dwExStyle & MTB_EX_ADDLEFTACTIVE ) m_nAddPos = 3; else m_nAddPos = 0; m_nXCmd = m_pMDITab->m_nXClickCommand; m_nDCmd = m_pMDITab->m_nDClickCommand; m_nRCmd = m_pMDITab->m_nRClickCommand; } // Overrides BOOL OnSetActive() { if (!m_bInit) { CmbUpdate(); m_bInit = TRUE; } SetModified(TRUE); return DoDataExchange(FALSE); } BOOL OnKillActive() { return DoDataExchange(TRUE); } BOOL OnApply() { if ( DoDataExchange(TRUE) ) { DWORD dwExtendedStyle = 0; if (m_nWheel /*== 1*/) dwExtendedStyle |= MTB_EX_WHEEL; if (m_nMultiLine /*== 1*/) dwExtendedStyle |= MTB_EX_MULTILINE; if (m_nFixedSize /*== 1*/) dwExtendedStyle |= MTB_EX_FIXEDSIZE; if (m_nAnchorColor /*== 1*/) dwExtendedStyle |= MTB_EX_ANCHORCOLOR; if (m_nAddLinkRight /*== 1*/) dwExtendedStyle |= MTB_EX_ADDLINKACTIVERIGHT; if (m_nMouseDownSelect /*== 1*/) dwExtendedStyle |= MTB_EX_MOUSEDOWNSELECT; if (m_nCtrlTabMDI ) dwExtendedStyle |= MTB_EX_CTRLTAB_MDI; switch (m_nRadioRightClick) { case 1: dwExtendedStyle |= MTB_EX_RIGHTCLICKCLOSE; break; case 2: dwExtendedStyle |= MTB_EX_RIGHTCLICKREFRESH; break; case 4: dwExtendedStyle |= MTB_EX_RIGHTCLICKCOMMAND; break; // minit } switch (m_nRadioDoubleClick) { case 1: dwExtendedStyle |= MTB_EX_DOUBLECLICKCLOSE; break; case 2: dwExtendedStyle |= MTB_EX_DOUBLECLICKREFRESH; break; case 3: dwExtendedStyle |= MTB_EX_DOUBLECLICKNLOCK; break; // UDT DGSTR case 5: dwExtendedStyle |= MTB_EX_DOUBLECLICKCOMMAND; break; // minit } switch (m_nRadioXClick) { case 1: dwExtendedStyle |= MTB_EX_XCLICKCLOSE; break; case 2: dwExtendedStyle |= MTB_EX_XCLICKREFRESH; break; case 3: dwExtendedStyle |= MTB_EX_XCLICKNLOCK; break; // UDT DGSTR case 5: dwExtendedStyle |= MTB_EX_XCLICKCOMMAND; break; // minit } switch (m_nRadioOnClose) { case 1: dwExtendedStyle |= MTB_EX_RIGHTACTIVEONCLOSE; break; case 2: dwExtendedStyle |= MTB_EX_LEFTACTIVEONCLOSE; break; } switch (m_nAddPos) { case 1: dwExtendedStyle |= MTB_EX_ADDLEFT; break; case 2: dwExtendedStyle |= MTB_EX_ADDRIGHTACTIVE; break; case 3: dwExtendedStyle |= MTB_EX_ADDLEFTACTIVE; break; } m_pMDITab->SetItemSize( CSize(m_nFixedSizeX, m_nFixedSizeY) ); m_pMDITab->SetMaxTabItemTextLength(m_nMaxTextLength); m_pMDITab->SetMDITabExtendedStyle(dwExtendedStyle); m_pMDITab->m_nXClickCommand = m_nXCmd; m_pMDITab->m_nDClickCommand = m_nDCmd; m_pMDITab->m_nRClickCommand = m_nRCmd; return TRUE; } else { return FALSE; } } private: void CmbUpdate() { CComboBox cmbR = GetDlgItem(IDC_COMBO_MDITAB_RIGHTCLICK); CComboBox cmbD = GetDlgItem(IDC_COMBO_MDITAB_DOUBLECLICK); CComboBox cmbX = GetDlgItem(IDC_COMBO_MDITAB_MCLICK); CString strCmd = _T("コマンド ..."); cmbR.AddString(strCmd); cmbD.AddString(strCmd); cmbX.AddString(strCmd); CString strDesc; if (m_pMDITab->m_nRClickCommand) { CToolTipManager::LoadToolTipText(m_pMDITab->m_nRClickCommand, strDesc); cmbR.AddString(strDesc); } if (m_pMDITab->m_nXClickCommand) { CToolTipManager::LoadToolTipText(m_pMDITab->m_nXClickCommand, strDesc); cmbX.AddString(strDesc); } if (m_pMDITab->m_nDClickCommand) { CToolTipManager::LoadToolTipText(m_pMDITab->m_nDClickCommand, strDesc); cmbD.AddString(strDesc); } } public: // Message map and handlers BEGIN_MSG_MAP( CMDITabPropertyPage ) CHAIN_MSG_MAP ( CInitPropertyPageImpl<CMDITabPropertyPage> ) //COMMAND_ID_HANDLER_EX ( IDC_BUTTON_MDITAB_FONT, OnFont ) COMMAND_HANDLER_EX ( IDC_COMBO_MDITAB_RIGHTCLICK , CBN_SELCHANGE, OnCmbSelChange ) COMMAND_HANDLER_EX ( IDC_COMBO_MDITAB_DOUBLECLICK, CBN_SELCHANGE, OnCmbSelChange ) COMMAND_HANDLER_EX ( IDC_COMBO_MDITAB_MCLICK , CBN_SELCHANGE, OnCmbSelChange ) END_MSG_MAP() private: void OnCmbSelChange(UINT /*code*/, int id, HWND /*hWnd*/) { if ( (id != IDC_COMBO_MDITAB_RIGHTCLICK ) && (id != IDC_COMBO_MDITAB_DOUBLECLICK) && (id != IDC_COMBO_MDITAB_MCLICK ) ) return; CComboBox cmb = GetDlgItem(id); if ( !::IsWindow(cmb.m_hWnd) ) return; int index = cmb.GetCurSel(); int count = cmb.GetCount(); if (index == CB_ERR) return; CString strSel; cmb.GetLBText(index, strSel); if ( strSel == _T("コマンド ...") ) { CCommandSelectDialog dlg(m_hMenu); if (dlg.DoModal() != IDOK || dlg.GetCommandID() == 0) { if (id == IDC_COMBO_MDITAB_RIGHTCLICK) cmb.SetCurSel(m_nRadioRightClick); if (id == IDC_COMBO_MDITAB_DOUBLECLICK) cmb.SetCurSel(m_nRadioDoubleClick); if (id == IDC_COMBO_MDITAB_MCLICK) cmb.SetCurSel(m_nRadioXClick); return; } DWORD dwCommand = (DWORD) dlg.GetCommandID(); if (dwCommand) { if (index == count - 2) cmb.DeleteString(count - 1); CString strDesc; CToolTipManager::LoadToolTipText(dwCommand, strDesc); cmb.SetCurSel( cmb.AddString(strDesc) ); if (id == IDC_COMBO_MDITAB_RIGHTCLICK) m_nRCmd = dwCommand; else if (id == IDC_COMBO_MDITAB_DOUBLECLICK) m_nDCmd = dwCommand; else if (id == IDC_COMBO_MDITAB_MCLICK) m_nXCmd = dwCommand; } } } };
[ [ [ 1, 298 ] ] ]
2f54f4f8021ca237761c2f285f901feae02a7cec
d752d83f8bd72d9b280a8c70e28e56e502ef096f
/Extensions/CUDA/EpochCUDA/CUDA Wrapper/Initialization.cpp
5b0ba28c3741995ff806539327ef5d55e825d2b9
[]
no_license
apoch/epoch-language.old
f87b4512ec6bb5591bc1610e21210e0ed6a82104
b09701714d556442202fccb92405e6886064f4af
refs/heads/master
2021-01-10T20:17:56.774468
2010-03-07T09:19:02
2010-03-07T09:19:02
34,307,116
0
0
null
null
null
null
UTF-8
C++
false
false
1,489
cpp
// // The Epoch Language Project // CUDA Interoperability Library // // Central one-time initialization of the CUDA drivers // #include "pch.h" #include "CUDA Wrapper/Module.h" #include "Code Generation/EASMToCUDA.h" #include <cuda.h> // We create a single context per process; this variable holds the handle to that context CUcontext ContextHandle = 0; // // Invoke the CUDA driver's initialization logic // bool InitializeCUDA() { // We delay-load the CUDA DLL so we have a chance to trap any failures // and respond by deactivating the language extension. All delay-load // failures come in the form of SEH exceptions, so we wrap our first // call into the DLL with a SEH handler to ensure the process doesn't // get nuked if anything goes wrong. __try { if(cuInit(0) != CUDA_SUCCESS) return false; CUdevice devicehandle; int devicecount = 0; cuDeviceGetCount(&devicecount); if(devicecount <= 0) return false; if(cuDeviceGet(&devicehandle, 0) != CUDA_SUCCESS) return false; if(cuCtxCreate(&ContextHandle, CU_CTX_MAP_HOST, devicehandle) != CUDA_SUCCESS) return false; CUDALibraryLoaded = true; CUDAAvailableForExecution = true; return true; } __except(EXCEPTION_EXECUTE_HANDLER) { return false; } } // // Shut down and clean up the CUDA driver // void ShutdownCUDA() { Module::ReleaseAllModules(); if(CUDALibraryLoaded) cuCtxDestroy(ContextHandle); }
[ "[email protected]", "don.apoch@localhost" ]
[ [ [ 1, 11 ], [ 13, 25 ], [ 56, 56 ], [ 58, 66 ], [ 69, 70 ] ], [ [ 12, 12 ], [ 26, 55 ], [ 57, 57 ], [ 67, 68 ] ] ]
35e8af067829a54c8dbfdde95a6daf7a5bdc9ef9
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/ouan-tests/TestInput/OrbitCameraController.cpp
8e879d199361a03f00445d6a68fb8256b51e9661
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
#include "OrbitCameraController.h" #include <cassert> #include <OgreSceneManager.h> #include <OgreCamera.h> #include <OgreSceneNode.h> OrbitCameraController::OrbitCameraController( Ogre::Camera* camera ) : m_camera( camera ) , m_lookAtNode( NULL ) , m_yawNode( NULL ) , m_pitchNode( NULL ) { assert( camera != NULL ); assert( camera->getParentNode() == NULL ); Ogre::SceneManager* sceneManager = camera->getSceneManager(); m_lookAtNode = sceneManager->getRootSceneNode()->createChildSceneNode(); m_yawNode = m_lookAtNode->createChildSceneNode(); m_pitchNode = m_yawNode->createChildSceneNode(); m_pitchNode->attachObject( camera ); } OrbitCameraController::~OrbitCameraController() { } void OrbitCameraController::setLookAtPosition( const float x, const float y, const float z ) { m_lookAtNode->setPosition( x, y, z ); } void OrbitCameraController::resetOrientation() { m_yawNode->resetOrientation(); m_pitchNode->resetOrientation(); } void OrbitCameraController::setOrientation( const float yawDegrees, const float pitchDegrees ) { resetOrientation(); addOrientation( yawDegrees, pitchDegrees ); } void OrbitCameraController::addOrientation( const float yawDegrees, const float pitchDegrees ) { m_yawNode->yaw( Ogre::Degree( yawDegrees ) ); m_pitchNode->pitch( Ogre::Degree( pitchDegrees ) ); } void OrbitCameraController::setDistance( const float distance ) { m_camera->setPosition( 0, 0, distance ); } void OrbitCameraController::addDistance( const float distance ) { m_camera->setPosition( m_camera->getPosition() + Ogre::Vector3( 0, 0, distance ) ); }
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 62 ] ] ]
320a67cb5248c366f756f3578c216374bbc37d9a
4b61c42390888ca65455051932ddc9f6996b0db4
/Quaternion.h
4d74058e374868bc4cc76a13afc11ca4faf84405
[]
no_license
miyabiarts/math
916558fb152c67286931494a62909a5bcdf1be0b
eceefff9604f58559eb000876172c4fc3e3ced7c
refs/heads/master
2016-09-06T16:21:14.864762
2011-04-18T13:48:04
2011-04-18T13:48:04
1,630,636
0
0
null
null
null
null
UTF-8
C++
false
false
9,564
h
#pragma once #include <cmath> template< typename T > struct Vector3; template< typename T > struct Matrix4; //! Quaternion template <typename T = double> struct Quaternion { Quaternion< T >(); Quaternion< T >( T x,T y,T z,T w ); Quaternion< T >( const Quaternion< T > &q ); Quaternion< T > &operator =( const Quaternion< T > &q ); Quaternion< T > operator +() const; Quaternion< T > operator -() const; Quaternion< T > operator +( const Quaternion< T > &q ) const; Quaternion< T > operator -( const Quaternion< T > &q ) const; Quaternion< T > operator *( const Quaternion< T > &q ) const; Quaternion< T > operator *( T s ) const; Quaternion< T > operator /( T s ) const; Quaternion< T >& operator +=( const Quaternion< T > &q ); Quaternion< T >& operator -=( const Quaternion< T > &q ); Quaternion< T >& operator *=( const Quaternion< T > &q ); Quaternion< T >& operator *=( T s ); Quaternion< T >& operator /=( T s ); bool operator ==( const Quaternion< T > &q ) const; bool operator !=( const Quaternion< T > &q ) const; // static function /*! @brief create identity quaternion */ static void identity( Quaternion< T > &q ); /*! @brief normalize quoternion */ static Quaternion< T > &normalize( Quaternion< T > &q, const Quaternion< T > &q0 ); /*! @brief calculate length */ static T length( const Quaternion< T > &q ); /*! @brief calculate norm */ static T norm( const Quaternion< T > &q ); /*! @brief calculate conjugate quoternion */ static Quaternion< T > &conjugate( Quaternion< T > &q, const Quaternion< T > &q0 ); /*! @brief calculate inverse quoternion */ static Quaternion< T > &inverse( Quaternion< T > &q, const Quaternion< T > &q0 ); /*! @brief create yaw-pitch-roll rotation */ static Quaternion< T > &rotation( Quaternion< T > &q, T yaw, T pitch, T roll ); /*! @brief create any-axis rotation */ static Quaternion< T > &rotationAxis( Quaternion< T > &q, const Vector3< T > &axis, T rad ); /*! @brief convert to matrix */ static Matrix4< T > &toMatrix( Matrix4< T > &m, const Quaternion< T > &q ); /*! @brief linear interpolation */ template< typename T2 > static Quaternion< T > slerp( Quaternion< T > &q, const Quaternion< T > &q1, const Quaternion< T > &q2, T2 t ); union { struct { T x, y, z, w; }; T v[ 4 ]; }; }; // template< typename T > inline Quaternion< T >::Quaternion() { x = y = z = 0; w = 1; } // template< typename T > inline Quaternion< T >::Quaternion( T x, T y, T z, T w ) { this->x = x; this->y = y; this->z = z; this->w = w; } // template< typename T > inline Quaternion< T >::Quaternion( const Quaternion< T > &q ) { x = q.x; y = q.y; z = q.z; w = q.w; } // template< typename T > inline Quaternion< T > &Quaternion< T >::operator =( const Quaternion< T > &q ) { if( this == &q ) return *this; x = q.x; y = q.y; z = q.z; w = q.w; return *this; } // template< typename T > inline Quaternion< T > Quaternion< T >::operator +() const { return Quaternion< T >( x, y, z, w ); } // template< typename T > inline Quaternion< T > Quaternion< T >::operator -() const { return Quaternion< T >( -x, -y, -z, -w ); } // template< typename T > inline Quaternion< T > Quaternion< T >::operator +( const Quaternion< T > &q ) const { return Quaternion< T >( x + q.x, y + q.y, z + q.z, w + q.w ); } // template< typename T > inline Quaternion< T > Quaternion< T >::operator -( const Quaternion< T > &q ) const { return Quaternion< T >( x - q.x, y - q.y, z - q.z, w - q.w ); } // template< typename T > inline Quaternion< T > Quaternion< T >::operator *( const Quaternion< T > &q ) const { Quaternion< T > t; t.x = -( y * q.z - z * q.y) + w * q.x + x * q.w; t.y = -( z * q.x - x * q.z) + w * q.y + y * q.w; t.z = -( x * q.y - y * q.x) + w * q.z + z * q.w; t.w = w * q.w - x * q.x - y * q.y - z * q.z; return t; } // template< typename T > inline Quaternion< T > Quaternion< T >::operator *( T s ) const { return Quaternion< T >( x * s, y * s, z * s, w * s ); } // template< typename T > inline Quaternion< T > Quaternion< T >::operator /( T s ) const { T f = 1.0 / s; return operator *( f ); } // template< typename T > inline Quaternion< T > operator *( T s, const Quaternion< T > &q ) { return Quaternion< T >( q.x * s, q.y * s, q.z * s, q.w * s ); } // template< typename T > inline Quaternion< T > &Quaternion< T >::operator +=( const Quaternion< T > &q ) { x += q.x; y += q.y; z += q.z; w += q.w; return *this; } // template< typename T > inline Quaternion< T > &Quaternion< T >::operator -=( const Quaternion< T > &q ) { x -= q.x; y -= q.y; z -= q.z; w -= q.w; return *this; } // template< typename T > inline Quaternion< T > &Quaternion< T >::operator *=( const Quaternion< T > &q ) { Quaternion< T > t; t.x = -( y * q.z - z * q.y) + w * q.x + x * q.w; t.y = -( z * q.x - x * q.z) + w * q.y + y * q.w; t.z = -( x * q.y - y * q.x) + w * q.z + z * q.w; t.w = w * q.w - x * q.x - y * q.y - z * q.z; *this = t; return *this; } // template< typename T > inline Quaternion< T > &Quaternion< T >::operator *=( T s ) { x *= s; y *= s; z *= s; w *= s; return *this; } // template< typename T > inline Quaternion< T > &Quaternion< T >::operator /=(T s) { T f = 1.0f/s; return operator*=(f); } // template< typename T > inline bool Quaternion< T >::operator ==( const Quaternion< T > &q ) const { return ( x==q.x && y==q.y && z==q.z && w == q.w ); } // template< typename T > inline bool Quaternion< T >::operator !=( const Quaternion< T > &q ) const { return !( operator==( q ) ); } // template< typename T > inline void Quaternion< T >::identity( Quaternion< T > &q ) { q.x = q.y = q.z = 0; q.w = 1; } // template< typename T > inline Quaternion< T > &Quaternion< T >::normalize( Quaternion< T > &q, const Quaternion< T > &q0 ) { T l = length( q0 ); if( l == 0.0 ) { q = Quaternion< T >(); return q; } q = q0 / l; return q; } // template< typename T > inline T Quaternion< T >::length( const Quaternion< T > &q ) { return sqrt( q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w ); } // template< typename T > inline T Quaternion< T >::norm( const Quaternion< T > &q ) { return q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w; } #include "Matrix4.h" template< typename T > Quaternion< T > &Quaternion< T >::conjugate( Quaternion< T > &q, const Quaternion< T > &q0 ) { q = Quaternion< T >( -q0.x, -q0.y, -q0.z, q0.w ); return q; } template< typename T > Quaternion< T > &Quaternion< T >::inverse( Quaternion< T > &q, const Quaternion< T > &q0 ) { T l = length( q0 ); if( l == 0 ) { q = Quaternion< T >(); return q; } conjugate( q, q0 ); q /= l; return q; } template< typename T > Quaternion< T > &Quaternion< T >::rotation( Quaternion< T > &q, T yaw, T pitch, T roll ) { Quaternion< T > qy,qp,qr; Matrix4< T > mrx,mry,mrz; rotationAxis(qp,Vector3< T >( 1, 0, 0 ), pitch ); rotationAxis(qy,Vector3< T >( 0, 1, 0 ), yaw ); rotationAxis(qr,Vector3< T >( 0, 0, 1 ), roll ); q = qr * qp * qy; return q; } template< typename T > Quaternion< T > &Quaternion< T >::rotationAxis( Quaternion< T > &q, const Vector3< T > &axis, T rad ) { T a = static_cast< T >( sin( static_cast< double >( rad ) / 2.0 ) ); q.x = axis.x * a; q.y = axis.y * a; q.z = axis.z * a; q.w = static_cast< T >( cos( static_cast< double >( rad ) / 2 ) ); normalize( q, q ); return q; } template< typename T > Matrix4< T > &Quaternion< T >::toMatrix( Matrix4< T > &m, const Quaternion< T > &q ) { m._11 = 1 - 2 * ( q.y * q.y + q.z * q.z ); m._12 = 2 * ( q.x * q.y + q.z * q.w ); m._13 = 2 * ( q.z * q.x - q.w * q.y ); m._14 = 0; m._21 = 2 * ( q.x * q.y - q.z * q.w ); m._22 = 1 - 2 * ( q.z * q.z + q.x * q.x ); m._23 = 2 * ( q.y * q.z + q.w * q.x ); m._24 = 0; m._31 = 2 * ( q.z * q.x + q.w * q.y ); m._32 = 2 * ( q.y * q.z - q.x * q.w ); m._33 = 1 - 2 * ( q.y * q.y + q.x * q.x ); m._34 = 0; m._41 = m._42 = m._43 = 0; m._44 = 1; return m; } template< typename T, typename T2 > static Quaternion< T > slerp( Quaternion< T > &q, const Quaternion< T > &q1, const Quaternion< T > &q2, T2 t ) { double a = static_cast< double >( q1.x * q2.x + q1.y * q2.y + q1.z * q2.z + q1.w * q2.w ); double b = 1.0 - a * a; if( b == 0.0 ) { q = q1; } else { double a2 = acos( a ); double b2 = sqrt( b ); double c = a2 * t; double t0 = sin( a2 - c ) / b2; double t1 = sin( c ) / b2; q = q1 * t0 + q2 * t1; } return q; } /*! output stream */ template< typename T > std::ostream &operator<<( std::ostream &os, const Quaternion< T > &q ) { os << q.x << ", " << q.y << ", " << q.z << ", " << q.w; return os; } typedef Quaternion< unsigned char > QuaternionUC; typedef Quaternion< int > QuaternionI; typedef Quaternion< float > QuaternionF; typedef Quaternion< double > QuaternionD;
[ [ [ 1, 423 ] ] ]
c19896637c68c29f1ce67918720ec87f2398a7d5
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/libs/lith/lithbaselist.cpp
22f513cd4c5727d35b1724bcab3683a39cef16b8
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
/**************************************************************************** ; ; MODULE: LithBaseList (.CPP) ; ; PURPOSE: ; ; HISTORY: 04/19/98 [blb] (made from BaseList in Shared) ; ; NOTICE: Copyright (c) 199, MONOLITH, Inc. ; ****************************************************************************/ //#ifdef _WINDOWS //#include "windows.h" //#endif #include "lithbaselist.h"
[ [ [ 1, 18 ] ] ]
0369ba8e8a073e4e7ce580164db1d482b2149726
677f7dc99f7c3f2c6aed68f41c50fd31f90c1a1f
/SolidSBCCliSvc/stdafx.cpp
bbdbd08dce661ab22e4c6c03978b70ffba1b681d
[]
no_license
M0WA/SolidSBC
0d743c71ec7c6f8cfe78bd201d0eb59c2a8fc419
3e9682e90a22650e12338785c368ed69a9cac18b
refs/heads/master
2020-04-19T14:40:36.625222
2011-12-02T01:50:05
2011-12-02T01:50:05
168,250,374
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
// stdafx.cpp : source file that includes just the standard includes // SolidSBCCliSvc.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "admin@bd7e3521-35e9-406e-9279-390287f868d3" ]
[ [ [ 1, 8 ] ] ]
f0442f4f26baa4f963eff796a3a85cd6c8bb3bbf
ea6b169a24f3584978f159ec7f44184f9e84ead8
/source/reflect/string/StringBlock.cc
4b67a6232d63783dd8fa25ce3cebb987133b5d78
[]
no_license
sparecycles/reflect
e2051e5f91a7d72375dd7bfa2635cf1d285d8ef7
bec1b6e6521080ad4d932ee940073d054c8bf57f
refs/heads/master
2020-06-05T08:34:52.453196
2011-08-18T16:33:47
2011-08-18T16:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,977
cc
#include <reflect/string/StringBlock.h> namespace reflect { namespace string { StringBlock::StringBlock() { } void StringBlock::Load(const Fragment &data) { mStringData.reserve(data.size()); for(Fragment::size_type index = 0; index < data.size(); ) { ConstString item(data.data() + index); index += item.length() + 1; AddString(item); } } BlockString StringBlock::FindString(const Fragment &in) const { bool found; String::size_type sort_index = FindSortIndex(in, found); if(found) { BlockString result = FromIndex(mStringOffsets[sort_index]); return result; } else { return BlockString(); } } BlockString StringBlock::AddString(const Fragment &in) { bool found; String::size_type sort_index = FindSortIndex(in, found); if(found) { return FromIndex(mStringOffsets[sort_index]); } else { int offset = int(mStringData.size()); mStringData += in; mStringData += '\0'; mStringOffsets.insert(mStringOffsets.begin() + int(sort_index), offset); return FromIndex(offset); } } const char *StringBlock::GetStringData(int index) const { return mStringData.data() + index; } BlockString StringBlock::FromIndex(int index) const { return BlockString(this, index); } String::size_type StringBlock::FindSortIndex(const Fragment &string, bool &success) const { std::vector<int>::size_type low = 0, high = mStringOffsets.size(); while(low < high) { std::vector<int>::size_type mid = (low + high) / 2; int cmp = string.compare(GetStringData(mStringOffsets[mid])); if(cmp < 0) { high = mid; } else if(cmp > 0) { low = mid + 1; } else { success = true; return String::size_type(mid); } } success = false; return String::size_type(low); } const char *StringBlock::data() { return mStringData.data(); } StringBlock::size_type StringBlock::size() { return mStringData.size(); } } }
[ [ [ 1, 107 ] ] ]
802cb1a8b2a54298337737d15ad21c682ffcd689
580738f96494d426d6e5973c5b3493026caf8b6a
/Include/Vcl/sqlconst.hpp
02f9b4034d290402ebb2d3462861428f4775d023
[]
no_license
bravesoftdz/cbuilder-vcl
6b460b4d535d17c309560352479b437d99383d4b
7b91ef1602681e094a6a7769ebb65ffd6f291c59
refs/heads/master
2021-01-10T14:21:03.726693
2010-01-11T11:23:45
2010-01-11T11:23:45
48,485,606
2
1
null
null
null
null
UTF-8
C++
false
false
12,520
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'SqlConst.pas' rev: 6.00 #ifndef SqlConstHPP #define SqlConstHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Sqlconst { //-- type declarations ------------------------------------------------------- typedef AnsiString SqlConst__1[19]; //-- var, const, procedure --------------------------------------------------- #define DRIVERS_KEY "Installed Drivers" #define CONNECTIONS_KEY "Installed Connections" #define DRIVERNAME_KEY "DriverName" #define HOSTNAME_KEY "HostName" #define ROLENAME_KEY "RoleName" #define DATABASENAME_KEY "Database" #define MAXBLOBSIZE_KEY "BlobSize" #define VENDORLIB_KEY "VendorLib" #define DLLLIB_KEY "LibraryName" #define GETDRIVERFUNC_KEY "GetDriverFunc" #define AUTOCOMMIT_KEY "AutoCommit" #define BLOCKINGMODE_KEY "BlockingMode" #define WAITONLOCKS_KEY "WaitOnLocks" #define COMMITRETAIN_KEY "CommitRetain" #define TRANSISOLATION_KEY "%s TransIsolation" #define SQLDIALECT_KEY "SqlDialect" #define SQLLOCALE_CODE_KEY "LocaleCode" #define ERROR_RESOURCE_KEY "ErrorResourceFile" #define SQLSERVER_CHARSET_KEY "ServerCharSet" #define SREADCOMMITTED "readcommited" #define SREPEATREAD "repeatableread" #define SDIRTYREAD "dirtyread" #define SDRIVERREG_SETTING "Driver Registry File" #define SCONNECTIONREG_SETTING "Connection Registry File" #define szUSERNAME "USER_NAME" #define szPASSWORD "PASSWORD" #define SLocaleCode "LCID" #define ROWSETSIZE_KEY "RowsetSize" #define OSAUTHENTICATION "Os Authentication" #define SDriverConfigFile "dbxdrivers.ini" #define SConnectionConfigFile "dbxconnections.ini" #define SDBEXPRESSREG_SETTING "\\Software\\Borland\\DBExpress" extern PACKAGE System::ResourceString _SLoginError; #define Sqlconst_SLoginError System::LoadResourceString(&Sqlconst::_SLoginError) extern PACKAGE System::ResourceString _SMonitorActive; #define Sqlconst_SMonitorActive System::LoadResourceString(&Sqlconst::_SMonitorActive) extern PACKAGE System::ResourceString _SMissingConnection; #define Sqlconst_SMissingConnection System::LoadResourceString(&Sqlconst::_SMissingConnection) extern PACKAGE System::ResourceString _SDatabaseOpen; #define Sqlconst_SDatabaseOpen System::LoadResourceString(&Sqlconst::_SDatabaseOpen) extern PACKAGE System::ResourceString _SDatabaseClosed; #define Sqlconst_SDatabaseClosed System::LoadResourceString(&Sqlconst::_SDatabaseClosed) extern PACKAGE System::ResourceString _SMissingSQLConnection; #define Sqlconst_SMissingSQLConnection System::LoadResourceString(&Sqlconst::_SMissingSQLConnection) extern PACKAGE System::ResourceString _SConnectionNameMissing; #define Sqlconst_SConnectionNameMissing System::LoadResourceString(&Sqlconst::_SConnectionNameMissing) extern PACKAGE System::ResourceString _SEmptySQLStatement; #define Sqlconst_SEmptySQLStatement System::LoadResourceString(&Sqlconst::_SEmptySQLStatement) extern PACKAGE System::ResourceString _SNoParameterValue; #define Sqlconst_SNoParameterValue System::LoadResourceString(&Sqlconst::_SNoParameterValue) extern PACKAGE System::ResourceString _SNoParameterType; #define Sqlconst_SNoParameterType System::LoadResourceString(&Sqlconst::_SNoParameterType) extern PACKAGE System::ResourceString _SParameterTypes; #define Sqlconst_SParameterTypes System::LoadResourceString(&Sqlconst::_SParameterTypes) extern PACKAGE System::ResourceString _SDataTypes; #define Sqlconst_SDataTypes System::LoadResourceString(&Sqlconst::_SDataTypes) extern PACKAGE System::ResourceString _SResultName; #define Sqlconst_SResultName System::LoadResourceString(&Sqlconst::_SResultName) extern PACKAGE System::ResourceString _SNoTableName; #define Sqlconst_SNoTableName System::LoadResourceString(&Sqlconst::_SNoTableName) extern PACKAGE System::ResourceString _SNoSqlStatement; #define Sqlconst_SNoSqlStatement System::LoadResourceString(&Sqlconst::_SNoSqlStatement) extern PACKAGE System::ResourceString _SNoDataSetField; #define Sqlconst_SNoDataSetField System::LoadResourceString(&Sqlconst::_SNoDataSetField) extern PACKAGE System::ResourceString _SNoCachedUpdates; #define Sqlconst_SNoCachedUpdates System::LoadResourceString(&Sqlconst::_SNoCachedUpdates) extern PACKAGE System::ResourceString _SMissingDataBaseName; #define Sqlconst_SMissingDataBaseName System::LoadResourceString(&Sqlconst::_SMissingDataBaseName) extern PACKAGE System::ResourceString _SMissingDataSet; #define Sqlconst_SMissingDataSet System::LoadResourceString(&Sqlconst::_SMissingDataSet) extern PACKAGE System::ResourceString _SMissingDriverName; #define Sqlconst_SMissingDriverName System::LoadResourceString(&Sqlconst::_SMissingDriverName) extern PACKAGE System::ResourceString _SPrepareError; #define Sqlconst_SPrepareError System::LoadResourceString(&Sqlconst::_SPrepareError) extern PACKAGE System::ResourceString _SObjectNameError; #define Sqlconst_SObjectNameError System::LoadResourceString(&Sqlconst::_SObjectNameError) extern PACKAGE System::ResourceString _SSQLDataSetOpen; #define Sqlconst_SSQLDataSetOpen System::LoadResourceString(&Sqlconst::_SSQLDataSetOpen) extern PACKAGE System::ResourceString _SNoActiveTrans; #define Sqlconst_SNoActiveTrans System::LoadResourceString(&Sqlconst::_SNoActiveTrans) extern PACKAGE System::ResourceString _SActiveTrans; #define Sqlconst_SActiveTrans System::LoadResourceString(&Sqlconst::_SActiveTrans) extern PACKAGE System::ResourceString _SDllLoadError; #define Sqlconst_SDllLoadError System::LoadResourceString(&Sqlconst::_SDllLoadError) extern PACKAGE System::ResourceString _SDllProcLoadError; #define Sqlconst_SDllProcLoadError System::LoadResourceString(&Sqlconst::_SDllProcLoadError) extern PACKAGE System::ResourceString _SConnectionEditor; #define Sqlconst_SConnectionEditor System::LoadResourceString(&Sqlconst::_SConnectionEditor) extern PACKAGE System::ResourceString _SCommandTextEditor; #define Sqlconst_SCommandTextEditor System::LoadResourceString(&Sqlconst::_SCommandTextEditor) extern PACKAGE System::ResourceString _SMissingDLLName; #define Sqlconst_SMissingDLLName System::LoadResourceString(&Sqlconst::_SMissingDLLName) extern PACKAGE System::ResourceString _SMissingDriverRegFile; #define Sqlconst_SMissingDriverRegFile System::LoadResourceString(&Sqlconst::_SMissingDriverRegFile) extern PACKAGE System::ResourceString _STableNameNotFound; #define Sqlconst_STableNameNotFound System::LoadResourceString(&Sqlconst::_STableNameNotFound) extern PACKAGE System::ResourceString _SNoCursor; #define Sqlconst_SNoCursor System::LoadResourceString(&Sqlconst::_SNoCursor) extern PACKAGE System::ResourceString _SMetaDataOpenError; #define Sqlconst_SMetaDataOpenError System::LoadResourceString(&Sqlconst::_SMetaDataOpenError) extern PACKAGE System::ResourceString _SErrorMappingError; #define Sqlconst_SErrorMappingError System::LoadResourceString(&Sqlconst::_SErrorMappingError) extern PACKAGE System::ResourceString _SStoredProcsNotSupported; #define Sqlconst_SStoredProcsNotSupported System::LoadResourceString(&Sqlconst::_SStoredProcsNotSupported) extern PACKAGE System::ResourceString _SPackagesNotSupported; #define Sqlconst_SPackagesNotSupported System::LoadResourceString(&Sqlconst::_SPackagesNotSupported) extern PACKAGE System::ResourceString _SDBXUNKNOWNERROR; #define Sqlconst_SDBXUNKNOWNERROR System::LoadResourceString(&Sqlconst::_SDBXUNKNOWNERROR) extern PACKAGE System::ResourceString _SDBXNOCONNECTION; #define Sqlconst_SDBXNOCONNECTION System::LoadResourceString(&Sqlconst::_SDBXNOCONNECTION) extern PACKAGE System::ResourceString _SDBXNOMETAOBJECT; #define Sqlconst_SDBXNOMETAOBJECT System::LoadResourceString(&Sqlconst::_SDBXNOMETAOBJECT) extern PACKAGE System::ResourceString _SDBXNOCOMMAND; #define Sqlconst_SDBXNOCOMMAND System::LoadResourceString(&Sqlconst::_SDBXNOCOMMAND) extern PACKAGE System::ResourceString _SDBXNOCURSOR; #define Sqlconst_SDBXNOCURSOR System::LoadResourceString(&Sqlconst::_SDBXNOCURSOR) extern PACKAGE System::ResourceString _SNOMEMORY; #define Sqlconst_SNOMEMORY System::LoadResourceString(&Sqlconst::_SNOMEMORY) extern PACKAGE System::ResourceString _SINVALIDFLDTYPE; #define Sqlconst_SINVALIDFLDTYPE System::LoadResourceString(&Sqlconst::_SINVALIDFLDTYPE) extern PACKAGE System::ResourceString _SINVALIDHNDL; #define Sqlconst_SINVALIDHNDL System::LoadResourceString(&Sqlconst::_SINVALIDHNDL) extern PACKAGE System::ResourceString _SINVALIDTIME; #define Sqlconst_SINVALIDTIME System::LoadResourceString(&Sqlconst::_SINVALIDTIME) extern PACKAGE System::ResourceString _SNOTSUPPORTED; #define Sqlconst_SNOTSUPPORTED System::LoadResourceString(&Sqlconst::_SNOTSUPPORTED) extern PACKAGE System::ResourceString _SINVALIDXLATION; #define Sqlconst_SINVALIDXLATION System::LoadResourceString(&Sqlconst::_SINVALIDXLATION) extern PACKAGE System::ResourceString _SINVALIDPARAM; #define Sqlconst_SINVALIDPARAM System::LoadResourceString(&Sqlconst::_SINVALIDPARAM) extern PACKAGE System::ResourceString _SOUTOFRANGE; #define Sqlconst_SOUTOFRANGE System::LoadResourceString(&Sqlconst::_SOUTOFRANGE) extern PACKAGE System::ResourceString _SSQLPARAMNOTSET; #define Sqlconst_SSQLPARAMNOTSET System::LoadResourceString(&Sqlconst::_SSQLPARAMNOTSET) extern PACKAGE System::ResourceString _SEOF; #define Sqlconst_SEOF System::LoadResourceString(&Sqlconst::_SEOF) extern PACKAGE System::ResourceString _SINVALIDUSRPASS; #define Sqlconst_SINVALIDUSRPASS System::LoadResourceString(&Sqlconst::_SINVALIDUSRPASS) extern PACKAGE System::ResourceString _SINVALIDPRECISION; #define Sqlconst_SINVALIDPRECISION System::LoadResourceString(&Sqlconst::_SINVALIDPRECISION) extern PACKAGE System::ResourceString _SINVALIDLEN; #define Sqlconst_SINVALIDLEN System::LoadResourceString(&Sqlconst::_SINVALIDLEN) extern PACKAGE System::ResourceString _SINVALIDXISOLEVEL; #define Sqlconst_SINVALIDXISOLEVEL System::LoadResourceString(&Sqlconst::_SINVALIDXISOLEVEL) extern PACKAGE System::ResourceString _SINVALIDTXNID; #define Sqlconst_SINVALIDTXNID System::LoadResourceString(&Sqlconst::_SINVALIDTXNID) extern PACKAGE System::ResourceString _SDUPLICATETXNID; #define Sqlconst_SDUPLICATETXNID System::LoadResourceString(&Sqlconst::_SDUPLICATETXNID) extern PACKAGE System::ResourceString _SDRIVERRESTRICTED; #define Sqlconst_SDRIVERRESTRICTED System::LoadResourceString(&Sqlconst::_SDRIVERRESTRICTED) extern PACKAGE System::ResourceString _SLOCALTRANSACTIVE; #define Sqlconst_SLOCALTRANSACTIVE System::LoadResourceString(&Sqlconst::_SLOCALTRANSACTIVE) extern PACKAGE System::ResourceString _SMultiConnNotSupported; #define Sqlconst_SMultiConnNotSupported System::LoadResourceString(&Sqlconst::_SMultiConnNotSupported) extern PACKAGE System::ResourceString _SConfFileMoveError; #define Sqlconst_SConfFileMoveError System::LoadResourceString(&Sqlconst::_SConfFileMoveError) extern PACKAGE System::ResourceString _SMissingConfFile; #define Sqlconst_SMissingConfFile System::LoadResourceString(&Sqlconst::_SMissingConfFile) extern PACKAGE System::ResourceString _SObjectViewNotTrue; #define Sqlconst_SObjectViewNotTrue System::LoadResourceString(&Sqlconst::_SObjectViewNotTrue) extern PACKAGE System::ResourceString _SDriverNotInConfigFile; #define Sqlconst_SDriverNotInConfigFile System::LoadResourceString(&Sqlconst::_SDriverNotInConfigFile) extern PACKAGE System::ResourceString _SObjectTypenameRequired; #define Sqlconst_SObjectTypenameRequired System::LoadResourceString(&Sqlconst::_SObjectTypenameRequired) extern PACKAGE System::ResourceString _SCannotCreateFile; #define Sqlconst_SCannotCreateFile System::LoadResourceString(&Sqlconst::_SCannotCreateFile) extern PACKAGE System::ResourceString _SDlgFilterTxt; #define Sqlconst_SDlgFilterTxt System::LoadResourceString(&Sqlconst::_SDlgFilterTxt) extern PACKAGE System::ResourceString _SLogFileFilter; #define Sqlconst_SLogFileFilter System::LoadResourceString(&Sqlconst::_SLogFileFilter) extern PACKAGE AnsiString DbxError[19]; } /* namespace Sqlconst */ using namespace Sqlconst; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // SqlConst
[ "bitscode@7bd08ab0-fa70-11de-930f-d36749347e7b" ]
[ [ [ 1, 203 ] ] ]
00f924e859513c4cad30d15f69632b0fda7181bf
37d9f986509f12388d96e35b3f810e29f6984f29
/FinanceiroFuncoes.cpp
e9639b47ec21db9091e7b2112efbc13111acadc3
[]
no_license
GraduacaoUEL/planilha-uel
3843b68a0fc0a53bc1d5a315a1058c0a203d92a2
8a478dc5cb7f6a19c5ca757cb5fbcebabfe5d964
refs/heads/master
2021-01-01T15:30:06.896359
2009-11-09T01:37:08
2009-11-09T01:37:08
32,278,006
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,530
cpp
/* * Financeiro.cpp * * Created on: 01/11/2009 * Author: helioalb */ #include "FinanceiroFuncoes.h" FinanceiroFuncoes::FinanceiroFuncoes() { } /* FinanceiroFuncoes::~FinanceiroFuncoes() { fclose(fin); } */ void FinanceiroFuncoes::entrada() { int op, sn; char descricao[30]; float valor; struct Financeiro f; do { system("cls"); printf("Escolha o tipo de entrada\n\n\n"); printf("( 1 ) Deposito\n"); printf("( 2 ) Vendas ao cliente\n"); printf("( 3 ) Voltar\n\n"); fflush(stdin); scanf("%d", &op); } while (op < 1 || op > 3); if (op == 1) { system("cls"); printf("Digite o valor do deposito => "); fflush(stdin); scanf("%f", &f.entradav); printf("Faca uma breve descricao da operacao => "); fflush(stdin); gets(f.descricao); system("cls"); printf("Confirma o deposito? (1)Sim (2)Nao => "); fflush(stdin); scanf("%d", &sn); if (sn == 1) { if ((sld = fopen("saldo.fin", "rb")) == NULL) { sld = fopen("saldo.fin", "wb"); valor = 0.0; } if((fin = fopen("fin_in.fin", "ab")) == NULL) { printf("Erro ao abrir o arquivo fin_in.fin\n"); exit(1); } fwrite(&f, sizeof(struct Financeiro), 1, fin); fflush(fin); getchar(); entrada(); } else { entrada(); } } else if (op == 2) { system("cls"); printf("Digite o valor da venda => "); //Implementar cliente system("cls"); printf("Confirma a venda? (1)Sim (2)Nao => "); fflush(stdin); scanf("%d", &sn); if(sn == 1) { printf("Venda realizada com sucesso.\n\n"); } else { entrada(); } } } void FinanceiroFuncoes::historicoEntrada() { Financeiro f; if((fin = fopen("fin_in.fin", "rb")) == NULL) { printf("Não existem registros\n"); if((fin = fopen("fin_in.fin", "wb")) == NULL) { printf("Erro ao criar arquivo\n"); exit(1); } } fseek(fin, 0, SEEK_SET); fflush(fin); fflush(stdin); fflush(stdout); system("cls"); printf("\t\tDeposito\t\tDescricao\t\t"); while ((fread(&f, sizeof(Financeiro), 1, fin)) == 1) { printf("\n\t\t%f\t\t ", f.entradav); printf("%s\n", f.descricao); } getchar(); } void FinanceiroFuncoes::saida() { int sn; char descricao[30]; struct Financeiro f; system("cls"); printf("Digite o valor da saida => "); fflush(stdin); scanf("%f", &f.saidav); printf("Faca uma breve descricao da operacao => "); fflush(stdin); gets(f.descricao); system("cls"); printf("Confirma a saida? (1)Sim / (2)Nao => "); fflush(stdin); scanf("%d", &sn); if(sn == 1) { if((fin = fopen("fin_out.fin", "ab")) == NULL) { printf("Erro ao abrir o arquivo financeiro.fin\n"); exit(1); } fwrite(&f, sizeof(struct Financeiro), 1, fin); printf("Saida realizada com sucesso.\n\n"); fflush(fin); getchar(); } } void FinanceiroFuncoes::historicoSaida() { Financeiro f; if((fin = fopen("fin_out.fin", "rb")) == NULL) { printf("Não existem registros\n"); if((fin = fopen("fin_out.fin", "wb")) == NULL) { printf("Erro ao criar arquivo\n"); exit(1); } } fseek(fin, 0, SEEK_SET ); fflush(fin); fflush(stdin); fflush(stdout); system("cls"); printf("\t\tSaida\t\tDescricao\t\t"); while ((fread(&f, sizeof(Financeiro), 1, fin)) == 1) { printf("\n\t\t%f\t\t ", f.saidav); printf("%s\n", f.descricao); } getchar(); }
[ "hayato.fujii@78584900-b35c-11de-997e-c5eb2a8ae348" ]
[ [ [ 1, 210 ] ] ]
cf62a7fa1016e0cc3ec067db719bf89ef2170eab
3761dcce2ce81abcbe6d421d8729af568d158209
/include/cybergarage/upnp/xml/StateVariableData.h
7be26cb0f9a3438933e241037341e27979e641c4
[ "BSD-3-Clause" ]
permissive
claymeng/CyberLink4CC
af424e7ca8529b62e049db71733be91df94bf4e7
a1a830b7f4caaeafd5c2db44ad78fbb5b9f304b2
refs/heads/master
2021-01-17T07:51:48.231737
2011-04-08T15:10:49
2011-04-08T15:10:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,684
h
/****************************************************************** * * CyberLink for C++ * * Copyright (C) Satoshi Konno 2002-2003 * * File: StateVariableData.h * * Revision; * * 07/20/03 * - first revision * ******************************************************************/ #ifndef _CLINK_STATEVARIABLEDATA_H_ #define _CLINK_STATEVARIABLEDATA_H_ #include <string> #include <cybergarage/xml/Node.h> #include <cybergarage/xml/NodeData.h> namespace CyberLink { class QueryResponse; class QueryListener; class StateVariableData : public CyberXML::NodeData { std::string value; QueryResponse *queryRes; QueryListener *queryListener; //////////////////////////////////////////////// // Constructor //////////////////////////////////////////////// public: StateVariableData(); ~StateVariableData(); //////////////////////////////////////////////// // value //////////////////////////////////////////////// public: const char *getValue() { return value.c_str(); } void setValue(const char *val) { value = (val != NULL) ? val : ""; } //////////////////////////////////////////////// // QueryListener //////////////////////////////////////////////// public: QueryListener *getQueryListener() { return queryListener; } void setQueryListener(QueryListener *listener) { queryListener = listener; } //////////////////////////////////////////////// // QueryResponse //////////////////////////////////////////////// public: QueryResponse *getQueryResponse() { return queryRes; } void setQueryResponse(QueryResponse *res); }; } #endif
[ "skonno@b944b01c-6696-4570-ab44-a0e08c11cb0e" ]
[ [ [ 1, 92 ] ] ]
e29a4799d9d45d983a2d1ca1bbe48f688356bcdf
9c62af23e0a1faea5aaa8dd328ba1d82688823a5
/rl/branches/persistence2/engine/rules/include/CreatureControllerManager.h
7f5778c6e514e22c5d591e225aa429d6e0a221f1
[ "ClArtistic", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
jacmoe/dsa-hl-svn
55b05b6f28b0b8b216eac7b0f9eedf650d116f85
97798e1f54df9d5785fb206c7165cd011c611560
refs/heads/master
2021-04-22T12:07:43.389214
2009-11-27T22:01:03
2009-11-27T22:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,507
h
/* This source file is part of Rastullahs Lockenpracht. * Copyright (C) 2003-2008 Team Pantheon. http://www.team-pantheon.de * * This program is free software; you can redistribute it and/or modify * it under the terms of the Clarified Artistic License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Clarified Artistic License for more details. * * You should have received a copy of the Clarified Artistic License * along with this program; if not you can get it here * http://www.jpaulmorrison.com/fbp/artistic2.htm. */ #ifndef __MovingCreatureManager_H__ #define __MovingCreatureManager_H__ #include "RulesPrerequisites.h" #include "GameTask.h" #include "PhysicsGenericContactCallback.h" #include "SaveGameData.h" #include <vector> #include <map> namespace rl { class Creature; class CreatureController; /// This class manages CreatureControllers, which provide an API for moving the creature /// around in the scene. /// CreatureControllers are created on demand and a reference is kept here, so that no more /// than one CreatureController is created per Creature. class _RlRulesExport CreatureControllerManager : public GameTask, public Ogre::Singleton<CreatureControllerManager>, public PhysicsGenericContactCallback { public: CreatureControllerManager(); ~CreatureControllerManager(); /// Returns a CreatureController that can be used to control given Creature. /// There is only one controller per Creature at a given time. /// If no such controller exists yet, it is created. CreatureController* getCreatureController(Creature* creature); std::list<CreatureController*> getAllCreatureController() const; /// This function detaches a controller attached to the given Creature, if any. void detachController(Creature* creature); void run(Ogre::Real elapsedTime); // override from GameTask const Ogre::String& getName() const; // Newton Contact Callback void userProcess(OgreNewt::ContactJoint &contactJoint, Ogre::Real timestep, int threadid); protected: typedef std::map<Creature*, CreatureController*> ControllerMap; ControllerMap mControllers; }; } #endif
[ "timm@4c79e8ff-cfd4-0310-af45-a38c79f83013" ]
[ [ [ 1, 69 ] ] ]
7265839f1c5f3753ca898623daee31a7149cf549
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/inc/entity/nentity.h
4938b8d7a587cada5800104381dad7c9e8ae4e7f
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,136
h
#ifndef N_ENTITY_H #define N_ENTITY_H //------------------------------------------------------------------------------ /** @ingroup NebulaEntitySystem @brief Main header for entities @author Mateu Batle (c) 2005 Conjurer Services, S.A. */ //------------------------------------------------------------------------------ #include "entity/nentityobject.h" #include "entity/nentityclass.h" #include "entity/ncomponentobject.h" #include "entity/ncomponentclass.h" #include "entity/nclassentityclass.h" #include "entity/nclasscomponentclass.h" #include "entity/nclasscomponentobject.h" #include "entity/ncomponentclassserver.h" #include "entity/ncomponentobjectserver.h" #include "entity/ncmdprotonativecppcomponentclass.h" #include "entity/ncmdprotonativecppcomponentobject.h" #include "kernel/nmacros.h" //------------------------------------------------------------------------------ void n_initcmds_nEntityClass(nClass * cl); void n_initcmds_nEntityObject(nClass * cl); //------------------------------------------------------------------------------ #define N_CMDARG_COMPONENT_OBJECT(TYPE) \ class TYPE; \ template <> \ inline \ const char * nGetSignatureStr< TYPE * >() \ { \ return "o"; \ }; \ template <> \ inline \ void \ nGetCmdArg< TYPE * >( nCmd * cmd, TYPE * & ret )\ { \ nObject * obj = static_cast<nObject*> (cmd->In()->GetO()); \ n_assert2(obj->IsA("nentityobject"), "Script command expecting entity object argument"); \ nEntityObject * ent = static_cast<nEntityObject *> (obj); \ ret = ent->GetComponent<TYPE>(); \ }; \ template <> \ inline \ void \ nSetCmdArg< TYPE * >( nCmd * cmd, TYPE * const & val ) \ { \ cmd->Out()->SetO(static_cast<nObject *> (val->GetEntityObject())); \ }; #define N_CMDARG_COMPONENT_CLASS(TYPE) \ class TYPE; \ template <> \ inline \ const char * nGetSignatureStr<TYPE * >() \ { \ return "o"; \ }; \ template <> \ inline \ void \ nGetCmdArg( nCmd * cmd, TYPE * & ret ) \ { \ nObject * obj = static_cast<nObject*> (cmd->In()->GetO()); \ if(obj->IsA("nentityobject")) \ { \ nEntityObject * ent = static_cast<nEntityObject *> (obj); \ ret = ent->GetClassComponent<TYPE>(); \ } \ else if(obj->IsA("nentityclass")) \ { \ nEntityClass * ent = static_cast<nEntityClass *> (obj); \ ret = ent->GetComponent<TYPE>(); \ } \ else \ { \ n_assert2_always("Script command expecting entity object/class argument"); \ } \ }; \ template <> \ inline \ void \ nSetCmdArg( nCmd * cmd, TYPE * const & val ) \ { \ cmd->Out()->SetO(static_cast<nObject *> (val->GetEntityClass())); \ }; //------------------------------------------------------------------------------ /** @def NCOMPONENT_DECLARE(COMPNAME) @brief Declaration of component objects and classes @param COMPNAME Name of the component object C++ class @param SUPERCLASS Name of the parent component object C++ class */ #define NCOMPONENT_DECLARE(COMPNAME,SUPERCLASS) \ public: \ static const nComponentId & GetComponentIdStatic() \ { \ static const nComponentId componentId(#COMPNAME); \ return componentId; \ } \ virtual const nComponentId & GetComponentId() const \ { \ return GetComponentIdStatic(); \ } \ static const nComponentId & GetParentComponentIdStatic() \ { \ return SUPERCLASS::GetComponentIdStatic(); \ } \ virtual const nComponentId & GetParentComponentId() const \ { \ return GetParentComponentIdStatic(); \ } \ protected: \ typedef COMPNAME ScriptClass_; \ typedef COMPNAME ComponentType_; \ typedef SUPERCLASS ParentComponentType_; \ private: //------------------------------------------------------------------------------ /** @ingroup NebulaEntitySystem nNebulaComponentObject() creates a Nebula component object with script interface (you'll have to provide a function void n_initcmds(nClass*)). It takes the C name of the component object: @code nNebulaComponentObject(ncTransform); @endcode */ #define nNebulaComponentObject(CLASS,SUPERCLASS) \ extern nClassComponentObject * n_init_ ## CLASS(const char * name, nComponentObjectServer * cos); \ extern void * n_create_ ## CLASS(); \ extern void n_initcmds_ ## CLASS(nClass *); \ nClassComponentObject * n_init_ ## CLASS(const char * name, nComponentObjectServer * cos) \ { \ nClassComponentObject * clazz = n_new(nClassComponentObject(name, n_create_ ## CLASS, true)); \ clazz->SetProperName(#CLASS); \ clazz->SetInstanceSize(sizeof(CLASS)); \ cos->AddClass(CLASS::GetParentComponentIdStatic(), clazz); \ n_initcmds_ ## CLASS(clazz); \ return clazz; \ } \ void* n_create_ ## CLASS() { return n_new(CLASS()); }; #define nNebulaComponentObjectAbstract(CLASS,SUPERCLASS) \ extern nClassComponentObject * n_init_ ## CLASS(const char * name, nComponentObjectServer * cos); \ extern void * n_create_ ## CLASS(); \ extern void n_initcmds_ ## CLASS(nClass *); \ nClassComponentObject * n_init_ ## CLASS(const char * name, nComponentObjectServer * cos) \ { \ nClassComponentObject * clazz = n_new(nClassComponentObject(name, n_create_ ## CLASS, true)); \ clazz->SetProperName(#CLASS); \ clazz->SetInstanceSize(0); \ cos->AddClass(CLASS::GetParentComponentIdStatic(), clazz); \ n_initcmds_ ## CLASS(clazz); \ return clazz; \ } \ void* n_create_ ## CLASS() { n_assert2_always("error, component cannot be instanced"); return 0; }; //------------------------------------------------------------------------------ /** @ingroup NebulaEntitySystem nNebulaComponentClass() creates a Nebula component class with script interface (you'll have to provide a function void n_initcmds_ClassName(nClass*)). It takes the C name of the component class: @code nNebulaComponentClass(ncTransformClass); @endcode */ #define nNebulaComponentClass(CLASS,SUPERCLASS) \ extern nClassComponentClass * n_init_ ## CLASS(const char * name, nComponentClassServer * ccs); \ extern void * n_create_ ## CLASS(); \ extern void n_initcmds_ ## CLASS(nClass *); \ nClassComponentClass * n_init_ ## CLASS(const char * name, nComponentClassServer * ccs) \ { \ nClassComponentClass * clazz = n_new(nClassComponentClass(name, n_create_ ## CLASS, true)); \ clazz->SetProperName(#CLASS); \ clazz->SetInstanceSize(sizeof(CLASS)); \ ccs->AddClass(CLASS::GetParentComponentIdStatic(), clazz); \ n_initcmds_ ## CLASS(clazz); \ return clazz; \ } \ void* n_create_ ## CLASS() { return n_new(CLASS()); }; //------------------------------------------------------------------------------ #define NSCRIPTCMD_TEMPLATE_COMP(TEMPLATE,FourCC,NAME,TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM) \ { \ char ncmd_signature[N_MAXPATH]; \ unsigned int fourcc = FourCC; \ typedef TEMPLATE< ScriptClass_, TR, TYPELIST_ ## NUMINPARAM ## INPARAM, TYPELIST_ ## NUMOUTPARAM ## OUTPARAM> \ TCmdProtoNativeCPP; \ TCmdProtoNativeCPP::Traits::CalcPrototype(ncmd_signature, #NAME); \ fourcc = TCmdProtoNativeCPP::Traits::CalcFourCC(#NAME, fourcc); \ TCmdProtoNativeCPP * val = \ n_new( TCmdProtoNativeCPP( \ ncmd_signature,fourcc,&ScriptClass_::MemberName,ScriptClass_::GetComponentIdStatic()) \ ); \ cl->AddCmd(val); \ } #define NSCRIPT_ADDCMD_COMPCLASS(FourCC,TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM) \ NSCRIPTCMD_TEMPLATE_COMP(nCmdProtoNativeCPPComponentClass,FourCC,MemberName,TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM) #define NSCRIPT_ADDCMD_COMPOBJECT(FourCC,TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM) \ NSCRIPTCMD_TEMPLATE_COMP(nCmdProtoNativeCPPComponentObject,FourCC,MemberName,TR,MemberName,NUMINPARAM,INPARAM,NUMOUTPARAM,OUTPARAM) #define NCOMPONENT_ADDSIGNAL(MemberName) \ cl->AddSignal(n_new(ScriptClass_::TSignal ## MemberName(#MemberName))); //------------------------------------------------------------------------------ /** nNebulaEntityClass creates code for C++ native classes, but there is only one of this (nEntityClass) @param CLASS C++ entity class @param SUPERCLASSNAME C++ superclass of the entity class */ #define nNebulaEntityClass(CLASS, SUPERCLASS) \ extern nClass* n_init_ ## CLASS(const char * name, nKernelServer* kernelServer); \ extern void* n_create_ ## CLASS(); \ extern void n_initcmds_ ## CLASS(nClass *); \ nClass* n_init_ ## CLASS(const char * name, nKernelServer* kernelServer) { \ nClassEntityClass * clazz = n_new(nClassEntityClass(name, kernelServer, n_create_ ## CLASS, true)); \ clazz->SetProperName(#CLASS); \ clazz->SetInstanceSize(sizeof(nEntityClass)); \ kernelServer->AddClass(SUPERCLASS, clazz); \ n_initcmds_nEntityClass(clazz); \ return clazz; \ }; \ void* n_create_ ## CLASS() { return n_new(nEntityClass()); }; //------------------------------------------------------------------------------ /** @deprecated nNebulaEntityObject was the way to go before having automatic generation of component glue up code in the entity. Now not needed @param CLASS C++ entity class @param SUPERCLASSNAME string with the nClass name of the superclass @param NCLASSENTITYCLASS string with the name of the entity class */ #define nNebulaEntityObject(CLASS,SUPERNCLASS,NCLASSENTITYCLASS) \ extern nClass* n_init_ ## CLASS(const char *, nKernelServer* kernelServer); \ extern void* n_create_ ## CLASS(); \ extern void n_initcmds_ ## CLASS(nClass *); \ nClass* n_init_ ## CLASS(const char * name, nKernelServer* kernelServer) { \ nString fullName(name); \ fullName = "/" + fullName; \ nClass * cl = kernelServer->FindClass(SUPERNCLASS); \ while(0 != cl) { \ fullName = cl->GetName() + fullName; \ fullName = "/" + fullName; \ cl = cl->GetSuperClass(); \ } \ fullName = "/sys" + fullName; \ cl = kernelServer->FindClass(NCLASSENTITYCLASS); \ cl->AddRef(); \ nEntityClass * entClass = static_cast<nEntityClass *> (nKernelServer::Instance()->New(NCLASSENTITYCLASS, fullName.Get())); \ entClass->nClass::InitClass(name, nKernelServer::Instance(), n_create_ ## CLASS, true); \ entClass->nClass::SetProperName(#CLASS); \ entClass->nClass::SetInstanceSize(sizeof(CLASS)); \ kernelServer->AddClass(SUPERNCLASS, entClass); \ n_initcmds_nEntityObject(entClass); \ return entClass; \ } \ void* n_create_ ## CLASS() { return n_new(CLASS()); } //------------------------------------------------------------------------------ /** Define a function returning a list of the component ids needed for a given class. This function is only used at startup time for configuring the native entity classes & objects. The NGAME version skips the edit components. */ #define _NENTITY_COMPID(NUMITEMS,LIST,NUM) nComponentId(N_SELECTSTR(NUMITEMS,LIST,NUM)), #ifndef NGAME #define NENTITY_COMPLIST(CLASS, NUMCOMP, COMPLIST, NUMCOMPEDIT, COMPLISTEDIT) \ const nComponentId * n_complist_ ## CLASS() { \ static const nComponentId comps[] = { \ N_REPEAT(_NENTITY_COMPID, NUMCOMPEDIT, COMPLISTEDIT) \ N_REPEAT(_NENTITY_COMPID, NUMCOMP, COMPLIST) \ compIdInvalid }; \ return comps; \ } #else #define NENTITY_COMPLIST(CLASS, NUMCOMP, COMPLIST, NUMCOMPEDIT, COMPLISTEDIT) \ const nComponentId * n_complist_ ## CLASS() { \ static const nComponentId comps[] = { \ N_REPEAT(_NENTITY_COMPID, NUMCOMP, COMPLIST) \ compIdInvalid }; \ return comps; \ } #endif //------------------------------------------------------------------------------ /** */ #define NENTITYCLASS_DEFINE(CLASS, NSUPERCLASS, NUMCOMP, COMPLIST, NUMCOMPEDIT, COMPLISTEDIT) \ NENTITY_COMPLIST(CLASS, NUMCOMP, COMPLIST, NUMCOMPEDIT, COMPLISTEDIT) \ void* n_create_ ## CLASS(); \ extern nClass* n_init_ ## CLASS(const char * name, nKernelServer * kernelServer); \ nClass* n_init_ ## CLASS(const char * name, nKernelServer * kernelServer) { \ nClassEntityClass * clazz = n_new(nClassEntityClass(name, kernelServer, n_create_ ## CLASS, true)); \ clazz->SetProperName(#CLASS); \ const nComponentId * compList = n_complist_ ## CLASS(); \ clazz->SetupComponents( compList ); \ clazz->SetInstanceSize(sizeof(nEntityClass)); \ nString superClassName(# NSUPERCLASS); \ superClassName.ToLower(); \ kernelServer->AddClass(superClassName.Get(), clazz); \ n_initcmds_nEntityClass(clazz); \ return clazz; \ } \ void* n_create_ ## CLASS() { return n_new(nEntityClass()); } //------------------------------------------------------------------------------ /** */ #define NENTITYOBJECT_DEFINE(CLASS,SUPERCLASS,ENTITYCLASS,NUMCOMP,COMPLIST,NUMCOMPEDIT,COMPLISTEDIT) \ NENTITY_COMPLIST(CLASS, NUMCOMP, COMPLIST, NUMCOMPEDIT, COMPLISTEDIT) \ void* n_create_ ## CLASS(); \ extern nClass* n_init_ ## CLASS(const char * name, nKernelServer * kernelServer); \ nClass* n_init_ ## CLASS(const char * name, nKernelServer* kernelServer) { \ nString fullName(name); \ fullName = "/" + fullName; \ nString supernclass(#SUPERCLASS); \ supernclass.ToLower(); \ nClass * cl = kernelServer->FindClass(supernclass.Get()); \ while(0 != cl) { \ fullName = cl->GetName() + fullName; \ fullName = "/" + fullName; \ cl = cl->GetSuperClass(); \ } \ fullName = "/sys" + fullName; \ nString nclassentityclass(#ENTITYCLASS); \ nclassentityclass.ToLower(); \ cl = kernelServer->FindClass(nclassentityclass.Get()); \ cl->AddRef(); \ nEntityClass * entClass = static_cast<nEntityClass *> (nKernelServer::Instance()->New(nclassentityclass.Get(), fullName.Get(), false)); \ entClass->nClass::InitClass(name, nKernelServer::Instance(), n_create_ ## CLASS, true); \ entClass->nClass::SetProperName(#CLASS); \ entClass->nClass::SetInstanceSize(sizeof(nEntityObject)); \ entClass->InitInstance(nObject::NewInstance); \ const nComponentId * compList = n_complist_ ## CLASS(); \ entClass->SetupComponents( compList ); \ kernelServer->AddClass(supernclass.Get(), entClass); \ n_initcmds_nEntityObject(entClass); \ return entClass; \ } \ void* n_create_ ## CLASS() { return n_new(nEntityObject()); } //------------------------------------------------------------------------------ #endif //N_ENTITY_H
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 365 ] ] ]
ce212aea6dcb0991be0f73d58b2e6c08ea44d085
c0f109c4f8b48a7471b395206748d0b04a9d369a
/LRT11_2/Components/DriveTrain/VectorDrive.h
750a8d3a3aef54400dc4b8df6b302ac9a230571d
[]
no_license
Team846/code-2011
fb95198e6c9700c169354d9a21050b982d0378ee
28189fea06d1e5f2ef7e490d592acbab013e7d92
refs/heads/master
2021-04-30T23:04:23.842757
2011-11-09T03:54:38
2011-11-09T03:54:38
68,422,847
0
0
null
null
null
null
UTF-8
C++
false
false
645
h
#ifndef VECTOR_DRIVE_H_ #define VECTOR_DRIVE_H_ #include "..\..\General.h" #include "..\..\Util\RunningSum.h" #include "RateControlDrive.h" #include "DBSDrive.h" class VectorDrive : public RateControlDrive { public: VectorDrive(); virtual void Configure(); DriveCommand Drive(float heading, float fwd); void SetCurrentHeadingAsZero(); private: float zeroHeading; float pGainHeadingLowGear; float pGainHeadingHighGear; RunningSum headingRunningError; const static float TURN_DECAY = 0.87; // (1/2)^(1/5) =~ 0.87 int normalizeHeading(int heading); }; #endif
[ "brianaxelrod@8c3036a0-8766-4673-8ad9-b43f491d8da9" ]
[ [ [ 1, 33 ] ] ]
44b21c02ff65fc63a8c6aad722602023635bdced
3c4f5bd6d7ac3878c181fb05ab41c1d755ddf343
/XClipboardStack.h
ae620ab0e347fefed120ae4d239414e6b456a68b
[]
no_license
imcooder/public
1078df18c1459e67afd1200346dd971ea3b71933
be947923c6e2fbd9c993a41115ace3e32dad74bf
refs/heads/master
2021-05-28T08:43:00.027020
2010-07-24T07:39:51
2010-07-24T07:39:51
32,301,120
2
1
null
null
null
null
GB18030
C++
false
false
1,773
h
/******************************************************************** Copyright (c) 2002-2003 汉王科技有限公司. 版权所有. 文件名称: XClipboardStack.h 文件内容: 版本历史: 1.0 作者: xuejuntao [email protected] 2008/09/25 *********************************************************************/ #ifndef HWX_CLIPBOARDSTACK_H #define HWX_CLIPBOARDSTACK_H #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Ext_Type.h" #include <list> #include <stack> /* #define CF_TEXT 1 #define CF_BITMAP 2 #define CF_METAFILEPICT 3 #define CF_SYLK 4 #define CF_DIF 5 #define CF_TIFF 6 #define CF_OEMTEXT 7 #define CF_DIB 8 #define CF_PALETTE 9 #define CF_PENDATA 10 #define CF_RIFF 11 #define CF_WAVE 12 #define CF_UNICODETEXT 13 #define CF_ENHMETAFILE 14 #if(WINVER >= 0x0400) #define CF_HDROP 15 #define CF_LOCALE 16 #define CF_MAX 17 #endif // WINVER >= 0x0400 #define CF_OWNERDISPLAY 0x0080 #define CF_DSPTEXT 0x0081 #define CF_DSPBITMAP 0x0082 #define CF_DSPMETAFILEPICT 0x0083 #define CF_DSPENHMETAFILE 0x008E */ class CXClipboardStack { public: BOOL Push(); BOOL Pop(); BOOL Empty(); public: CXClipboardStack(); ~CXClipboardStack(); protected: typedef struct tagClipboardDataPiece { UINT m_nFormat; TCHAR m_szFormatName[MAX_PATH]; HANDLE m_hData; tagClipboardDataPiece(); ~tagClipboardDataPiece(); void Release(); }XClipboardDataPiece, *LPXClipboardDataPiece; std::stack<std::list<LPXClipboardDataPiece> *> m_stkClipboard; }; #endif
[ "jtxuee@716a2f10-c84c-11dd-bf7c-81814f527a11" ]
[ [ [ 1, 69 ] ] ]
71e4486cc45548c437f5397b8ebdf9ceb11d8ccc
b393b4bae5dc99c8f9927a12fa41f96a0da16414
/PathFinding/ProjectP/World.cpp
4bed60d794bc888f0f3cd984be6df36b686574d7
[]
no_license
TambourineReindeer/propop
d6749db5cb656bc9961865e9ddf9a00bf3aeb227
2c986765c73654c7fb3020a1a68be668ba5fda10
refs/heads/master
2021-01-20T11:32:10.387190
2010-10-28T15:06:45
2010-10-28T15:06:45
56,489,521
1
0
null
null
null
null
ISO-8859-13
C++
false
false
3,657
cpp
#include "StdAfx.h" #include "World.h" CWorld::CWorld(void) { m_iNumOfPlaces = 0; } CWorld::CWorld(int iNumOfPlaces) { theWorld.resize(iNumOfPlaces); m_iNumOfPlaces = iNumOfPlaces; } CWorld::~CWorld(void) { } bool CWorld::AddPlace(CPlace place) { try { theWorld.push_back(place); m_iNumOfPlaces++; return true; } catch ( ... ) { return false; } } CPlace* CWorld::GetPlaceAtPos(float x, float y) { for (int i=0; i<(int)theWorld.size(); i++) { if ((theWorld[i].m_fPosX == x) && (theWorld[i].m_fPosY == y)) return &theWorld[i]; } return NULL; } bool CWorld::DeletePlaceAtPos(float x, float y) { for (int i=0; i<(int)theWorld.size(); i++) { if ((theWorld[i].m_fPosX == x) && (theWorld[i].m_fPosY == y)) { theWorld.erase(theWorld.begin() + i); return true; } } return false; } bool CWorld::IsAccessiblePlace(float x, float y, CCharacter chr) { for (int i=0; i<(int)theWorld.size(); i++) { if ((theWorld[i].m_fPosX == x) && (theWorld[i].m_fPosY == y)) { CPlace::PlaceType placetype = theWorld[i].GetType(); if ((placetype == CPlace::PTNone) || (placetype == CPlace::PTWall) || ((placetype == CPlace::PTMountain) && (theWorld[i].GetAltitude() > chr.m_fMaxAltitude)) || ((placetype == CPlace::PTWater) && (theWorld[i].GetAltitude() < chr.m_fMinAltitude))) { return false; } else { return true; } } } return false; } bool CWorld::Save(string filename) { ofstream* pmyFile = new ofstream; // On the heap pmyFile->open(filename.c_str(), ios_base::binary | ios_base::trunc); pmyFile->write((char*)"WV1", 3); // World Version 1 pmyFile->write((char*)&m_iNumOfPlaces, sizeof(int)); for (int i=0; i<(int)theWorld.size(); i++) { theWorld[i].Save( pmyFile ); } pmyFile->close(); delete pmyFile; return true; } bool CWorld::Load(string filename) { ifstream* pmyFile = new ifstream; // On the heap pmyFile->open(filename.c_str(), ios_base::binary); char szMagic[4] = ""; pmyFile->read(szMagic, 3); if (strcmp(szMagic, "WV1")==0) { int iNumOfPlaces; pmyFile->read((char*)&iNumOfPlaces, sizeof(int)); for (int i=0; i<iNumOfPlaces; i++) { CPlace pl; pl.Load(pmyFile); this->AddPlace(pl); } } pmyFile->close(); return true; } // // FUNZIONE: BuildPathForCharacter(CCharacter *character, CPlace *to) // // SCOPO: Restituisce il percorso (un array di CPlace) pił breve dal CPlace attuale di // <character> a <to> tenendo conto delle caratteristiche di <character>. // // COMMENTI: Implementa l'algoritmo A* // Rif.: http://www.policyalmanac.org/games/aStarTutorial.htm // // CPlace* CWorld::BuildPathForCharacter(CCharacter *character, CPlace *to) { return NULL; } vector<CPlace> CWorld::GetPlaceNeighbors(CPlace pl) { vector<CPlace> vec; CPlace *p = GetPlaceAtPos(pl.m_fPosX - 1, pl.m_fPosY - 1); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX , pl.m_fPosY - 1); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX + 1, pl.m_fPosY - 1); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX - 1, pl.m_fPosY ); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX + 1, pl.m_fPosY ); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX - 1, pl.m_fPosY + 1); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX , pl.m_fPosY + 1); if (p != NULL) vec.push_back(*p); p = GetPlaceAtPos(pl.m_fPosX + 1, pl.m_fPosY + 1); if (p != NULL) vec.push_back(*p); return vec; }
[ [ [ 1, 151 ] ] ]
a533537ff2caddad91025304bb3d6a3c845f6d87
9403771fd823bda79027cbe7f06c6449c1a44d32
/matlab/code-others/demaret-rangecod/bitstr.cpp
9b23f5a6703c310367b0465192e270ecdfa0b474
[]
no_license
fethallah/geodesics4meshes
32d8cc31378a106281f11ca139be9c1b452ebbfa
5fb5e3fc76bb205b8446dda408b3d1078b37cb96
refs/heads/master
2021-01-10T00:54:36.697357
2010-05-07T11:39:01
2010-05-07T11:39:01
33,808,580
2
1
null
null
null
null
UTF-8
C++
false
false
7,970
cpp
#include <iostream> #include <fstream> #include "bitstr.h" using namespace std; //Default constructor BitStream::BitStream() { Buffer = 0; tToStartBit(); Counter = 0; } // Destructor BitStream::~BitStream() { } // Read the current bit in the stream unsigned int BitStream::ReadCurrentBit() { unsigned int bit = (Mask == (Mask & Buffer)); return bit; } void BitStream::tToStartBit() { // Current bit position initialized with the Most Significant Bit of the Buffer BitPos = sizeof(unsigned char)*8-1; // Mask placed on the Most Significant Bit of the Buffer Mask = 1 << BitPos; } // Position the current bit to the least significant bit in // the buffer void BitStream::tToEndBit() { // Current bit position initialized with the Low Significant Bit of the Buffer BitPos = 0; // Mask placed on the Most Significant Bit of the Buffer Mask = 1; } // Write a bit in the stream // Warning : Bit is uunsigned int but must be 0 or 1 void BitStream::WriteCurrentBit(unsigned int Bit) { if (Bit == 0) Buffer &= (~Mask); else if (Bit == 1) Buffer |= Mask; } // Write a bit in the stream void WriteCurrentBit(unsigned char Bit) { WriteCurrentBit((unsigned int) Bit); } // Moving to the next buffer bit unsigned int BitStream::ToNextBit() { Counter++; if (BitPos == 0) { tToStartBit(); return 1; } else { BitPos--; Mask >>= 1; return 0; } } // Moves to the previous buffer bit unsigned int BitStream::ToPreviousBit() { Counter--; if (BitPos == 7) { tToEndBit(); return 1; } else { BitPos++; Mask <<= 1; return 0; } } // Returns counter of the bitstream unsigned int BitStream::GetCounter() { return Counter; } // Functions specific to WBitStream class //Default constructor WBitStream::WBitStream() : BitStream() { pStream = 0; } // Purpose : Constructor with the file name to open for writing WBitStream::WBitStream(const char* pFileName) : BitStream() { // Opends the stream (writing) pStream = new ofstream(pFileName,ios::binary); pStream->seekp(0); } // Destructor WBitStream::~WBitStream() { delete pStream; } // Save value to bitstream with ui_NbBitdsUsed bits (the size is checked) // Return FALSE if an error occured int WBitStream::SaveValue(unsigned int NbBitsUsed, unsigned int ValueToEncode, char* pc_ErrorMessage/*=0*/) { int b_Error = (unsigned int)(1 << NbBitsUsed) <= ValueToEncode; if (b_Error) { cout << "Error in header saving"; if (pc_ErrorMessage) cout << " :\n While saving "<< *pc_ErrorMessage; cout << endl; } else WriteBits(ValueToEncode, NbBitsUsed); return !b_Error; } // Stuff the end of buffer with a given value void WBitStream::Stuff(unsigned int Bit) { do { WriteCurrentBit(Bit); } while (!ToNextBit()); pStream->put(Buffer); Buffer = 0; }; // Write a bit to the output stream void WBitStream::WriteBit(unsigned int Bit) { WriteCurrentBit(Bit); if (ToNextBit()) { pStream->put(Buffer); Buffer = 0; } } // Write a bit to the ouput stream void WBitStream::WriteBit(unsigned char Bit) { WriteBit((unsigned int) Bit); } // : Write bits on the file // Warning we must have : NbBits <= sizeof(unsigned int)*8 void WBitStream::WriteBits(unsigned int Word, unsigned int NbBits) { unsigned int WordMask = 1; unsigned int CurrentPos; unsigned int BitVal; for (CurrentPos = 0; CurrentPos < NbBits; CurrentPos++) { BitVal = ((Word & WordMask) == WordMask); WriteBit(BitVal); WordMask <<= 1; } } void WBitStream::WriteFloat(float Value) { float* pValue = &Value; unsigned int *ptmp = (unsigned int *)pValue; WriteBits(*ptmp,sizeof(unsigned int)*8); } void WBitStream::WriteDouble(double d_Value) { double* pValue = &d_Value; unsigned int *ptmp = (unsigned int *)pValue; WriteBits(*ptmp,sizeof(unsigned int)*8); ptmp++; WriteBits(*ptmp,sizeof(unsigned int)*8); } void WBitStream::WriteByte(unsigned char Byte) { if (BitPos < 7) { Stuff(0); pStream->flush(); } pStream->put(Byte); Counter += 8; } void WBitStream::WriteSignBits(int SignWord, unsigned int NbBits) { if (SignWord >= 0) WriteBit((unsigned char)0); else WriteBit((unsigned char)1); int PosWord; if (SignWord<0) PosWord = - SignWord; else PosWord = SignWord; WriteBits((unsigned int)PosWord, NbBits); } // Flush the buffer to the output stream void WBitStream::Flush() { pStream->flush(); } // These are the functions specific to RBitStream // Default constructor RBitStream::RBitStream() :BitStream() { piStream = 0; } // Constructor with the file name to open for writing RBitStream::RBitStream(const char* pFileName) :BitStream() { // Open the stream for writing piStream = new ifstream(pFileName,ios::binary); // Initializes position piStream->seekg(0); vFillBuffer(); } // Destructor RBitStream::~RBitStream() { delete piStream; } void RBitStream::LoadValue(unsigned int NbBitsUsed, unsigned int & ValueToRead) { int b_Error = Eof(); if (b_Error) cout << "Error in loading" << endl; else ReadBits(ValueToRead,NbBitsUsed); } // Detect the end of the file int RBitStream::Eof() { return piStream->eof(); } // Reading a bit and return it unsigned int RBitStream::ReadBit() { unsigned int Bit = ReadCurrentBit(); if (ToNextBit()) vFillBuffer(); return Bit; } // reading a bit and check the end of file int RBitStream::ReadBit(unsigned int& Bit) { Bit = ReadCurrentBit(); if (ToNextBit()) { if (!vFillBuffer()) return (0); } return (1); } // Read bits from the file // Warning you must have : ui_NbBits <= sizeof(unsigned int)*8 unsigned int RBitStream::ReadBits(unsigned int NbBits) { unsigned int Word; unsigned int EffectNbBits; EffectNbBits= ReadBits(Word,NbBits); if (EffectNbBits != NbBits) { cout << "ReadBits: Nb bits effectively read: " << EffectNbBits << endl; } return Word; } // Read bits from the file float RBitStream::ReadFloat() { unsigned int ToRead; ReadBits(ToRead,sizeof(unsigned int)*8); float* pValue = (float*) &ToRead; return (*pValue); } // Read bits from the file double RBitStream::ReadDouble() { unsigned int ToRead[2]; ReadBits(ToRead[0],sizeof(unsigned int)*8); ReadBits(ToRead[1],sizeof(unsigned int)*8); double* pValue = (double*) ToRead; return (*pValue); } // Read bits from the file unsigned char RBitStream::ReadChar() { unsigned char Value; if (BitPos < 7) { while (!ToNextBit()); vFillBuffer(); Value = Buffer; vFillBuffer(); } else { Value = Buffer; vFillBuffer(); } Counter += 8; return Value; } // Read bits from the file int RBitStream::ReadSignBits(unsigned int NbBits) { int Value; int Sign; if (ReadBit() == 0) Sign = 1; else Sign = -1; Value = ReadBits(NbBits); return Value * Sign; } // Read bits from the file // Warning we must have : NbBits <= sizeof(unsigned int)*8) unsigned int RBitStream::ReadBits(unsigned int & Word, unsigned int NbBits) { unsigned int WordMask = 1; unsigned int BitPos; unsigned int BitVal; unsigned int GoOn = (NbBits > 0); Word = 0; BitPos = 0; while (GoOn) { GoOn = ReadBit(BitVal); // the reading is valid if (BitVal == 1) Word|=WordMask; WordMask <<= 1; BitPos++; if (BitPos >= NbBits) GoOn = 0; } return BitPos; } // Fill the buffer unsigned int RBitStream::vFillBuffer() { if (!(piStream->get(Buffer))) { Buffer = 0; return 0; } return 1; }
[ "gabriel.peyre@a6734f8e-26ab-11df-90c7-81228a7a91d5" ]
[ [ [ 1, 444 ] ] ]
4156a51a83851c4858be3bc8e343093ff5ecd6d6
b22c254d7670522ec2caa61c998f8741b1da9388
/dependencies/OpenSceneGraph/include/osgSim/LightPointNode
7b8746e5e011827a840fa5be443544b68e437248
[]
no_license
ldaehler/lbanet
341ddc4b62ef2df0a167caff46c2075fdfc85f5c
ecb54fc6fd691f1be3bae03681e355a225f92418
refs/heads/master
2021-01-23T13:17:19.963262
2011-03-22T21:49:52
2011-03-22T21:49:52
39,529,945
0
1
null
null
null
null
UTF-8
C++
false
false
3,490
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #ifndef OSGSIM_LIGHTPOINTNODE #define OSGSIM_LIGHTPOINTNODE 1 #include <osgSim/Export> #include <osgSim/LightPoint> #include <osgSim/LightPointSystem> #include <osg/Node> #include <osg/NodeVisitor> #include <osg/BoundingBox> #include <osg/Quat> #include <osg/Vec4> #include <vector> #include <set> namespace osgSim { class OSGSIM_EXPORT LightPointNode : public osg::Node { public : typedef std::vector< LightPoint > LightPointList; LightPointNode(); /** Copy constructor using CopyOp to manage deep vs shallow copy.*/ LightPointNode(const LightPointNode&,const osg::CopyOp& copyop=osg::CopyOp::SHALLOW_COPY); META_Node(osgSim,LightPointNode); virtual void traverse(osg::NodeVisitor& nv); unsigned int getNumLightPoints() const { return _lightPointList.size(); } unsigned int addLightPoint(const LightPoint& lp); void removeLightPoint(unsigned int pos); LightPoint& getLightPoint(unsigned int pos) { return _lightPointList[pos]; } const LightPoint& getLightPoint(unsigned int pos) const { return _lightPointList[pos]; } void setLightPointList(const LightPointList& lpl) { _lightPointList=lpl; } LightPointList& getLightPointList() { return _lightPointList; } const LightPointList& getLightPointList() const { return _lightPointList; } void setMinPixelSize(float minPixelSize) { _minPixelSize = minPixelSize; } float getMinPixelSize() const { return _minPixelSize; } void setMaxPixelSize(float maxPixelSize) { _maxPixelSize = maxPixelSize; } float getMaxPixelSize() const { return _maxPixelSize; } void setMaxVisibleDistance2(float maxVisibleDistance2) { _maxVisibleDistance2 = maxVisibleDistance2; } float getMaxVisibleDistance2() const { return _maxVisibleDistance2; } void setLightPointSystem( osgSim::LightPointSystem* lps) { _lightSystem = lps; } osgSim::LightPointSystem* getLightPointSystem() { return _lightSystem.get(); } void setPointSprite(bool enable=true) { _pointSprites = enable; } bool getPointSprite() const { return _pointSprites; } virtual osg::BoundingSphere computeBound() const; protected: ~LightPointNode() {} // used to cache the bouding box of the lightpoints as a tighter // view frustum check. mutable osg::BoundingBox _bbox; LightPointList _lightPointList; float _minPixelSize; float _maxPixelSize; float _maxVisibleDistance2; osg::ref_ptr<osgSim::LightPointSystem> _lightSystem; bool _pointSprites; }; } #endif
[ "vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13" ]
[ [ [ 1, 113 ] ] ]
7db60a8733541e17ef78e4da8a17a50e0e2b0f70
1db5ea1580dfa95512b8bfa211c63bafd3928ec5
/WorkerManager.cpp
5aebc492a16a620a43f46f53c0c113c46331123b
[]
no_license
armontoubman/scbatbot
3b9dd4532fbb78406b41dd0d8f08926bd710ad7b
bee2b0bf0281b8c2bd6edc4c10a597041ea4be9b
refs/heads/master
2023-04-18T12:08:13.655631
2010-09-17T23:03:26
2010-09-17T23:03:26
361,411,133
0
0
null
null
null
null
UTF-8
C++
false
false
11,563
cpp
#include <WorkerManager.h> #include <BaseManager.h> #include <RectangleArray.h> #include <BuildOrderManager.h> #include <algorithm> #include "Util.h" using namespace BWAPI; using namespace std; using namespace Util; WorkerManager::WorkerManager(Arbitrator::Arbitrator<Unit*,double>* arbitrator) { this->arbitrator = arbitrator; this->baseManager = NULL; this->buildOrderManager = NULL; this->lastSCVBalance = 0; this->WorkersPerGas = 3; this->mineralRate = 0; this->gasRate = 0; this->autoBuild = false; this->autoBuildPriority = 80; } void WorkerManager::setBaseManager(BaseManager* baseManager) { this->baseManager = baseManager; } void WorkerManager::setBuildOrderManager(BuildOrderManager* buildOrderManager) { this->buildOrderManager = buildOrderManager; } void WorkerManager::onOffer(set<Unit*> units) { for(set<Unit*>::iterator u = units.begin(); u != units.end(); u++) { if ((*u)->getType().isWorker() && !this->mineralOrder.empty()) { arbitrator->accept(this, *u); WorkerData temp; this->desiredWorkerCount[this->mineralOrder[this->mineralOrderIndex].first]++; this->currentWorkers[this->mineralOrder[this->mineralOrderIndex].first].insert(*u); temp.newResource = this->mineralOrder[this->mineralOrderIndex].first; this->mineralOrderIndex = (this->mineralOrderIndex+1) % mineralOrder.size(); workers.insert(make_pair(*u,temp)); } else arbitrator->decline(this, *u, 0); } } void WorkerManager::onRevoke(Unit* unit, double bid) { this->onRemoveUnit(unit); } void WorkerManager::updateWorkerAssignments() { //determine current worker assignments //also workers that are mining from resources that dont belong to any of our bases will be set to free for(map<Unit*,WorkerData >::iterator w = this->workers.begin(); w != this->workers.end(); w++) { if (w->second.newResource != NULL) { if (resourceBase.find(w->second.newResource) == resourceBase.end()) w->second.newResource = NULL; else currentWorkers[w->second.newResource].insert(w->first); } } // get free workers set<Unit*> freeWorkers; for(map<Unit*,WorkerData>::iterator w = this->workers.begin(); w != this->workers.end(); w++) { if (w->second.newResource == NULL) freeWorkers.insert(w->first); else { // free workers that are too far away from their resources if (w->first->getDistance(w->second.newResource)>32*10) { freeWorkers.insert(w->first); //erase worker from resource's current workers set currentWorkers[w->second.newResource].erase(w->first); } } } // free workers from resources with too many workers for(map<Unit*,int>::iterator i = desiredWorkerCount.begin(); i != desiredWorkerCount.end(); i++) if (i->second < (int)currentWorkers[i->first].size()) { // desired worker count is less than the current worker count for this resource, so lets remove some workers. int amountToRemove = currentWorkers[i->first].size() - i->second; for(int j = 0; j < amountToRemove; j++) { Unit* worker = *currentWorkers[i->first].begin(); freeWorkers.insert(worker); workers[worker].newResource = NULL; currentWorkers[i->first].erase(worker); } } vector< Unit* > workerUnit; vector< Unit* > taskUnit; map<int,int> assignment; for(set<Unit*>::iterator i=freeWorkers.begin();i!=freeWorkers.end();i++) workerUnit.push_back(*i); // assign workers to resources that need more workers for(map<Unit*,int>::iterator i = desiredWorkerCount.begin(); i != desiredWorkerCount.end(); i++) if (i->second>(int)currentWorkers[i->first].size()) for(int j=(int)currentWorkers[i->first].size();j<i->second;j++) taskUnit.push_back(i->first); //construct cost matrix //currently just uses euclidean distance, but walking distance would be more accurate RectangleArray<double> cost(workerUnit.size(),taskUnit.size()); for(int w=0;w<(int)workerUnit.size();w++) for(int t=0;t<(int)taskUnit.size();t++) cost[w][t]=workerUnit[w]->getDistance(taskUnit[t]); //calculate assignment for workers and tasks (resources) assignment=computeAssignments(cost); //use assignment for(map<int,int>::iterator a=assignment.begin();a!=assignment.end();a++) { Unit* worker=workerUnit[a->first]; Unit* resource=taskUnit[a->second]; workers[worker].newResource = resource; currentWorkers[resource].insert(worker); } } bool mineralCompare (const pair<Unit*, int> i, const pair<Unit*, int> j) { return (i.second>j.second); } void WorkerManager::rebalanceWorkers() { mineralOrder.clear(); desiredWorkerCount.clear(); currentWorkers.clear(); resourceBase.clear(); int remainingWorkers = this->workers.size(); optimalWorkerCount = 0; // iterate over all the resources of each active base for(set<Base*>::iterator b = this->basesCache.begin(); b != this->basesCache.end(); b++) { set<Unit*> baseMinerals = (*b)->getMinerals(); vector< std::pair<Unit*,int> > baseMineralOrder; for(set<Unit*>::iterator m = baseMinerals.begin(); m != baseMinerals.end(); m++) { resourceBase[*m] = *b; desiredWorkerCount[*m] = 0; baseMineralOrder.push_back(std::make_pair(*m,(*m)->getResources() - 2*(int)(*m)->getPosition().getDistance((*b)->getBaseLocation()->getPosition()))); optimalWorkerCount+=2; } sort(baseMineralOrder.begin(), baseMineralOrder.end(), mineralCompare); for(int i=0;i<(int)baseMineralOrder.size();i++) { Unit* mineral=baseMineralOrder[i].first; mineralOrder.push_back(make_pair(mineral, mineral->getResources() - 2*(int)mineral->getPosition().getDistance((*b)->getBaseLocation()->getPosition())-3000*i)); } set<Unit*> baseGeysers = (*b)->getGeysers(); for(set<Unit*>::iterator g = baseGeysers.begin(); g != baseGeysers.end(); g++) { optimalWorkerCount+=3; resourceBase[*g] = *b; desiredWorkerCount[*g]=0; if(remainingWorkers < 4)//always save some workers for minerals continue; if ((*g)->getType().isRefinery() && (*g)->getPlayer()==Broodwar->self() && (*g)->isCompleted()) { for(int w=0;w<this->WorkersPerGas && remainingWorkers>0;w++) { desiredWorkerCount[*g]++; remainingWorkers--; } } } } //if no resources exist, return if (!mineralOrder.empty()) { //order minerals by score (based on distance and resource amount) sort(mineralOrder.begin(), mineralOrder.end(), mineralCompare); //calculate optimal worker count for each mineral patch mineralOrderIndex = 0; while(remainingWorkers > 0) { desiredWorkerCount[mineralOrder[mineralOrderIndex].first]++; remainingWorkers--; mineralOrderIndex = (mineralOrderIndex + 1) % mineralOrder.size(); } } //update the worker assignments so the actual workers per resource is the same as the desired workers per resource updateWorkerAssignments(); if (this->autoBuild) { BWAPI::UnitType workerType=BWAPI::Broodwar->self()->getRace().getWorker(); if (this->buildOrderManager->getPlannedCount(workerType)<optimalWorkerCount) { this->buildOrderManager->build(optimalWorkerCount,workerType,this->autoBuildPriority); } } } void WorkerManager::update() { //bid a constant value of 10 on all completed workers set<Unit*> myPlayerUnits=Broodwar->self()->getUnits(); for(set<Unit*>::iterator u = myPlayerUnits.begin(); u != myPlayerUnits.end(); u++) { if ((*u)->isCompleted() && (*u)->getType().isWorker()) { arbitrator->setBid(this, *u, 10); } } //rebalance workers when necessary set<Base*> bases = this->baseManager->getActiveBases(); if (Broodwar->getFrameCount() > lastSCVBalance + 5*24 || bases != this->basesCache || lastSCVBalance == 0) { this->basesCache = bases; lastSCVBalance = Broodwar->getFrameCount(); this->rebalanceWorkers(); } //order workers to gather from their assigned resources this->mineralRate=0; this->gasRate=0; for(map<Unit*,WorkerData>::iterator u = workers.begin(); u != workers.end(); u++) { Unit* i = u->first; if (u->second.resource!=NULL) { if (u->second.resource->getType()==UnitTypes::Resource_Mineral_Field) mineralRate+=8/180.0; else gasRate+=8/180.0; } //switch current resource to newResource when appropiate if (u->second.resource == NULL || (i->getTarget() != NULL && !i->getTarget()->getType().isResourceDepot())) u->second.resource = u->second.newResource; Unit* resource = u->second.resource; if (i->getOrder() == Orders::MoveToMinerals || i->getOrder() == Orders::WaitForMinerals || i->getOrder() == Orders::MoveToGas || i->getOrder() == Orders::WaitForGas || i->getOrder() == Orders::PlayerGuard) if ((i->getTarget()==NULL || !i->getTarget()->exists() || !i->getTarget()->getType().isResourceDepot()) && i->getTarget() != resource) i->rightClick(resource); if (i->isCarryingGas() || i->isCarryingMinerals()) { if (i->getOrder() == Orders::ReturnGas || i->getOrder() == Orders::ReturnMinerals || (i->getOrder() == Orders::PlayerGuard && BWAPI::Broodwar->getFrameCount()>u->second.lastFrameSpam+BWAPI::Broodwar->getLatency()*2)) { u->second.lastFrameSpam=BWAPI::Broodwar->getFrameCount(); Base* b=this->baseManager->getBase(BWTA::getNearestBaseLocation(i->getTilePosition())); if (b!=NULL) { Unit* center = b->getResourceDepot(); if (i->getTarget()==NULL || !i->getTarget()->exists() || i->getTarget()!=center || (center->isCompleted() && i->getOrder() == Orders::PlayerGuard)) i->rightClick(center); } } } } } string WorkerManager::getName() const { return "Worker Manager"; } string WorkerManager::getShortName() const { return "Work"; } void WorkerManager::onRemoveUnit(Unit* unit) { if (unit->getType().isWorker()) workers.erase(unit); if (unit->getType().isResourceContainer()) { map<Unit*,set<Unit*> >::iterator c=currentWorkers.find(unit); if (c==currentWorkers.end()) return; for(set<Unit*>::iterator i=c->second.begin();i!=c->second.end();i++) { std::map<Unit*,WorkerData>::iterator j=workers.find(*i); if (j!=workers.end()) { if (j->second.resource==unit) j->second.resource=NULL; if (j->second.newResource==unit) j->second.newResource=NULL; } } } } void WorkerManager::setWorkersPerGas(int count) { this->WorkersPerGas=count; } double WorkerManager::getMineralRate() const { return this->mineralRate; } double WorkerManager::getGasRate() const { return this->gasRate; } int WorkerManager::getOptimalWorkerCount() const { return this->optimalWorkerCount; } void WorkerManager::enableAutoBuild() { this->autoBuild=true; } void WorkerManager::disableAutoBuild() { this->autoBuild=false; } void WorkerManager::setAutoBuildPriority(int priority) { this->autoBuildPriority = priority; }
[ "armontoubman@a850bb65-3c1a-43af-a1ba-18f3eb5da290" ]
[ [ [ 1, 337 ] ] ]
5e1faa49735989edbcfddb135395647d838bce0b
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/WorkLayer/Log.cpp
7633679fef119aedbda3c3ebdc005d5c37d7a4a1
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,565
cpp
//this file is part of eMule //Copyright (C)2002-2006 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //This program is free software; you can redistribute it and/or //modify it under the terms of the GNU General Public License //as published by the Free Software Foundation; either //version 2 of the License, or (at your option) any later version. // //This program is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU General Public License //along with this program; if not, write to the Free Software //Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. #include "stdafx.h" #include <io.h> #include <share.h> //#include "emule.h" #include "Log.h" #include "OtherFunctions.h" #include "Preferences.h" //#include "emuledlg.h" #include "StringConversion.h" #include "GlobalVariable.h" #include "UIMessage.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif void LogV(UINT uFlags, LPCTSTR pszFmt, va_list argp) { AddLogTextV(uFlags, DLP_DEFAULT, pszFmt, argp); } /////////////////////////////////////////////////////////////////////////////// // void Log(LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(LOG_DEFAULT, pszFmt, argp); va_end(argp); } void LogError(LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(LOG_ERROR, pszFmt, argp); va_end(argp); } void LogWarning(LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(LOG_WARNING, pszFmt, argp); va_end(argp); } /////////////////////////////////////////////////////////////////////////////// // void Log(UINT uFlags, LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(uFlags, pszFmt, argp); va_end(argp); } void LogError(UINT uFlags, LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(uFlags | LOG_ERROR, pszFmt, argp); va_end(argp); } void LogWarning(UINT uFlags, LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(uFlags | LOG_WARNING, pszFmt, argp); va_end(argp); } /////////////////////////////////////////////////////////////////////////////// // void DebugLog(LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(LOG_DEBUG, pszFmt, argp); va_end(argp); } void DebugLogError(LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(LOG_DEBUG | LOG_ERROR, pszFmt, argp); va_end(argp); } void DebugLogWarning(LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(LOG_DEBUG | LOG_WARNING, pszFmt, argp); va_end(argp); } /////////////////////////////////////////////////////////////////////////////// // void DebugLog(UINT uFlags, LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(uFlags | LOG_DEBUG, pszFmt, argp); va_end(argp); } void DebugLogError(UINT uFlags, LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(uFlags | LOG_DEBUG | LOG_ERROR, pszFmt, argp); va_end(argp); } void DebugLogWarning(UINT uFlags, LPCTSTR pszFmt, ...) { va_list argp; va_start(argp, pszFmt); LogV(uFlags | LOG_DEBUG | LOG_WARNING, pszFmt, argp); va_end(argp); } /////////////////////////////////////////////////////////////////////////////// // void AddLogLine(bool bAddToStatusBar, LPCTSTR pszLine, ...) { ASSERT(pszLine != NULL); va_list argptr; va_start(argptr, pszLine); AddLogTextV(LOG_DEFAULT | (bAddToStatusBar ? LOG_STATUSBAR : 0), DLP_DEFAULT, pszLine, argptr); va_end(argptr); } void AddDebugLogLine(bool bAddToStatusBar, LPCTSTR pszLine, ...) { ASSERT(pszLine != NULL); va_list argptr; va_start(argptr, pszLine); AddLogTextV(LOG_DEBUG | (bAddToStatusBar ? LOG_STATUSBAR : 0), DLP_DEFAULT, pszLine, argptr); va_end(argptr); } void AddDebugLogLine(EDebugLogPriority Priority, bool bAddToStatusBar, LPCTSTR pszLine, ...) { // loglevel needs to be merged with LOG_WARNING and LOG_ERROR later // (which only means 3 instead of 5 levels which you can select in the preferences) // makes no sense to implement two different priority indicators // // untill there is some time todo this, It will convert DLP_VERYHIGH to ERRORs // and DLP_HIGH to LOG_WARNING in order to be able using the Loglevel and color indicator ASSERT(pszLine != NULL); va_list argptr; va_start(argptr, pszLine); uint32 nFlag = 0; if (Priority == DLP_VERYHIGH) nFlag = LOG_ERROR; else if (Priority == DLP_HIGH) nFlag = LOG_WARNING; AddLogTextV(LOG_DEBUG | nFlag | (bAddToStatusBar ? LOG_STATUSBAR : 0), Priority, pszLine, argptr); va_end(argptr); } void AddLogTextV(UINT uFlags, EDebugLogPriority dlpPriority, LPCTSTR pszLine, va_list argptr) { ASSERT(pszLine != NULL); if ((uFlags & LOG_DEBUG) && !thePrefs.GetVerbose() && dlpPriority >= thePrefs.GetVerboseLogPriority()) return; //Xman Anti-Leecher-Log if ((uFlags & LOG_LEECHER) && !thePrefs.GetAntiLeecherLog()) return; //Xman end TCHAR szLogLine[1000]; if (_vsntprintf(szLogLine, ARRSIZE(szLogLine), pszLine, argptr) == -1) szLogLine[ARRSIZE(szLogLine) - 1] = _T('\0'); if(CGlobalVariable::m_hListenWnd) UINotify(WM_ADD_LOGTEXT, uFlags, (LPARAM)new CString(szLogLine)); // Comment UI /*if (theApp.emuledlg) theApp.emuledlg->AddLogText(uFlags, szLogLine); else*/ /*if(SendMessage(CGlobalVariable::m_hListenWnd, WM_ADD_LOGTEXT, uFlags, (LPARAM)szLogLine)==0)*/ else { TRACE(_T("App Log: %s\n"), szLogLine); TCHAR szFullLogLine[1060]; int iLen = _sntprintf(szFullLogLine, ARRSIZE(szFullLogLine), _T("%s: %s\r\n"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), szLogLine); if (iLen >= 0) { //Xman Anti-Leecher-Log //Xman Code Improvement if (!((uFlags & LOG_DEBUG) || (uFlags & LOG_LEECHER))) { if (thePrefs.GetLog2Disk()) theLog.Log(szFullLogLine, iLen); } else if (thePrefs.GetVerbose()) // && ((uFlags & LOG_DEBUG) || thePrefs.GetFullVerbose())) { if (thePrefs.GetDebug2Disk()) theVerboseLog.Log(szFullLogLine, iLen); } //Xman end } } } /////////////////////////////////////////////////////////////////////////////// // CLogFile CLogFile::CLogFile() { (void)m_strFilePath; m_uMaxFileSize = (UINT)-1; m_uBytesWritten = 0; m_tStarted = 0; m_fp = NULL; m_bInOpenCall = false; ASSERT( Unicode == 0 ); m_eFileFormat = Unicode; } CLogFile::~CLogFile() { Close(); } const CString& CLogFile::GetFilePath() const { return m_strFilePath; } bool CLogFile::SetFilePath(LPCTSTR pszFilePath) { if (IsOpen()) return false; m_strFilePath = pszFilePath; return true; } void CLogFile::SetMaxFileSize(UINT uMaxFileSize) { if (uMaxFileSize == 0) uMaxFileSize = (UINT)-1; else if (uMaxFileSize < 0x10000) uMaxFileSize = 0x10000; m_uMaxFileSize = uMaxFileSize; } bool CLogFile::SetFileFormat(ELogFileFormat eFileFormat) { if (eFileFormat != Unicode && eFileFormat != Utf8){ ASSERT(0); return false; } if (m_fp != NULL) return false; // can't change file format on-the-fly m_eFileFormat = eFileFormat; return true; } bool CLogFile::IsOpen() const { return m_fp != NULL; } bool CLogFile::Create(LPCTSTR pszFilePath, UINT uMaxFileSize, ELogFileFormat eFileFormat) { Close(); m_strFilePath = pszFilePath; m_uMaxFileSize = uMaxFileSize; m_eFileFormat = eFileFormat; return Open(); } bool CLogFile::Open() { if (m_fp != NULL) return true; m_fp = _tfsopen(m_strFilePath, _T("a+b"), _SH_DENYWR); if (m_fp != NULL) { m_tStarted = time(NULL); m_uBytesWritten = _filelength(fileno(m_fp)); if (m_uBytesWritten == 0) { if (m_eFileFormat == Unicode) { // write Unicode byte-order mark 0xFEFF fputwc(0xFEFF, m_fp); } else { ASSERT( m_eFileFormat == Utf8 ); ; // could write UTF-8 header.. } } else if (m_uBytesWritten >= sizeof(WORD)) { // check for Unicode byte-order mark 0xFEFF WORD wBOM; if (fread(&wBOM, sizeof(wBOM), 1, m_fp) == 1) { if (wBOM == 0xFEFF && m_eFileFormat == Unicode) { // log file already in Unicode format fseek(m_fp, 0, SEEK_END); // actually not needed because file is opened in 'Append' mode.. } else if (wBOM != 0xFEFF && m_eFileFormat != Unicode) { // log file already in UTF-8 format fseek(m_fp, 0, SEEK_END); // actually not needed because file is opened in 'Append' mode.. } else { // log file does not have the required format, create a new one (with the req. format) ASSERT( (m_eFileFormat==Unicode && wBOM!=0xFEFF) || (m_eFileFormat==Utf8 && wBOM==0xFEFF) ); ASSERT( !m_bInOpenCall ); if (!m_bInOpenCall) // just for safety { m_bInOpenCall = true; StartNewLogFile(); m_bInOpenCall = false; } } } } } return m_fp != NULL; } bool CLogFile::Close() { if (m_fp == NULL) return true; bool bResult = (fclose(m_fp) == 0); m_fp = NULL; m_tStarted = 0; m_uBytesWritten = 0; return bResult; } bool CLogFile::Log(LPCTSTR pszMsg, int iLen) { if (m_fp == NULL) return false; size_t uWritten; if (m_eFileFormat == Unicode) { // don't use 'fputs' + '_filelength' -- gives poor performance size_t uToWrite = ((iLen == -1) ? _tcslen(pszMsg) : (size_t)iLen)*sizeof(TCHAR); uWritten = fwrite(pszMsg, 1, uToWrite, m_fp); } else { TUnicodeToUTF8<2048> utf8(pszMsg, iLen); uWritten = fwrite((LPCSTR)utf8, 1, utf8.GetLength(), m_fp); } bool bResult = !ferror(m_fp); m_uBytesWritten += uWritten; if (m_uBytesWritten >= m_uMaxFileSize) StartNewLogFile(); else fflush(m_fp); return bResult; } bool CLogFile::Logf(LPCTSTR pszFmt, ...) { if (m_fp == NULL) return false; va_list argp; va_start(argp, pszFmt); TCHAR szMsg[1024]; _vsntprintf(szMsg, ARRSIZE(szMsg), pszFmt, argp); TCHAR szFullMsg[1060]; int iLen = _sntprintf(szFullMsg, ARRSIZE(szFullMsg), _T("%s: %s\r\n"), CTime::GetCurrentTime().Format(thePrefs.GetDateTimeFormat4Log()), szMsg); va_end(argp); return Log(szFullMsg, iLen); } void CLogFile::StartNewLogFile() { time_t tStarted = m_tStarted; Close(); TCHAR szDateLogStarted[40]; _tcsftime(szDateLogStarted, ARRSIZE(szDateLogStarted), _T("%Y.%m.%d %H.%M.%S"), localtime(&tStarted)); TCHAR szDrv[_MAX_DRIVE]; TCHAR szDir[_MAX_DIR]; TCHAR szNam[_MAX_FNAME]; TCHAR szExt[_MAX_EXT]; _tsplitpath(m_strFilePath, szDrv, szDir, szNam, szExt); CString strLogBakNam; strLogBakNam = szNam; strLogBakNam += _T(" - "); strLogBakNam += szDateLogStarted; TCHAR szLogBakFilePath[MAX_PATH]; _tmakepathlimit(szLogBakFilePath, szDrv, szDir, strLogBakNam, szExt); if (_trename(m_strFilePath, szLogBakFilePath) != 0) _tremove(m_strFilePath); Open(); } //Xman Anti-Leecher-Log void AddLeecherLogLine(bool bAddToStatusBar, LPCTSTR pszLine, ...) { ASSERT(pszLine != NULL); va_list argptr; va_start(argptr, pszLine); AddLogTextV(LOG_LEECHER | (bAddToStatusBar ? LOG_STATUSBAR : 0), DLP_DEFAULT, pszLine, argptr); va_end(argptr); } //Xman end
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 463 ] ] ]
213b5e63e765bd4143bdf5849d13b703ea453b6c
c95a83e1a741b8c0eb810dd018d91060e5872dd8
/Game/ObjectDLL/ObjectShared/VolumeEffect.cpp
301dbf7d60af4767be1f65240bc90bd0a9c094d8
[]
no_license
rickyharis39/nolf2
ba0b56e2abb076e60d97fc7a2a8ee7be4394266c
0da0603dc961e73ac734ff365bfbfb8abb9b9b04
refs/heads/master
2021-01-01T17:21:00.678517
2011-07-23T12:11:19
2011-07-23T12:11:19
38,495,312
1
0
null
null
null
null
UTF-8
C++
false
false
1,735
cpp
// ----------------------------------------------------------------------- // // // MODULE : VolumeEffect.cpp // // PURPOSE : Volume effect implementation: // - base class for a volume based effects // - axis-aligned volume // // CREATED : 1/3/02 // // (c) 2002 Monolith Productions, Inc. All Rights Reserved // ----------------------------------------------------------------------- // #include "stdafx.h" #include "VolumeEffect.h" #include "DEditColors.h" LINKFROM_MODULE( VolumeEffect ); BEGIN_CLASS(VolumeEffect) ADD_DEDIT_COLOR( VolumeEffect ) ADD_VECTORPROP_VAL_FLAG(Dims, 128.0f, 128.0f, 128.0f, PF_DIMS) END_CLASS_DEFAULT_FLAGS(VolumeEffect, BaseClass, NULL, NULL, CF_ALWAYSLOAD) VolumeEffect::VolumeEffect() : BaseClass(OT_NORMAL) { m_vDims.Init( 128.0f, 128.0f, 128.0f ); } VolumeEffect::~VolumeEffect() { } uint32 VolumeEffect::EngineMessageFn( uint32 messageID, void* pData, LTFLOAT fData ) { switch( messageID ) { case MID_PRECREATE: { ObjectCreateStruct* pOCS = (ObjectCreateStruct*)pData; if( !pOCS ) break; if( fData == PRECREATE_WORLDFILE ) { ReadProp( pOCS ); } } break; case MID_INITIALUPDATE: InitialUpdate(); break; case MID_UPDATE: break; case MID_SAVEOBJECT: break; case MID_LOADOBJECT: break; case MID_TOUCHNOTIFY: break; } return BaseClass::EngineMessageFn( messageID, pData, fData ); } bool VolumeEffect::ReadProp( ObjectCreateStruct* pOCS ) { if( !pOCS ) return false; g_pLTServer->GetPropVector( "Dims", &m_vDims ); return true; } void VolumeEffect::InitialUpdate( void ) { SetNextUpdate( m_hObject, UPDATE_NEVER ); }
[ [ [ 1, 87 ] ] ]
a22a6cd6c53f22762ef9ea00449fc4e9e7317609
c5534a6df16a89e0ae8f53bcd49a6417e8d44409
/trunk/nGENE Proj/ForceFieldShapeCapsule.h
02fd0f91f122f93114d8dbc109cfd464875dec11
[]
no_license
svn2github/ngene
b2cddacf7ec035aa681d5b8989feab3383dac012
61850134a354816161859fe86c2907c8e73dc113
refs/heads/master
2023-09-03T12:34:18.944872
2011-07-27T19:26:04
2011-07-27T19:26:04
78,163,390
2
0
null
null
null
null
UTF-8
C++
false
false
1,450
h
/* --------------------------------------------------------------------------- This source file is part of nGENE Tech. Copyright (c) 2006- Wojciech Toman This program is free software. File: ForceFieldShapeCapsule.h Version: 0.02 --------------------------------------------------------------------------- */ #pragma once #ifndef __INC_FORCEFIELDSHAPECAPSULE_H_ #define __INC_FORCEFIELDSHAPECAPSULE_H_ #include "Prerequisities.h" #include "PrerequisitiesPhysX.h" #include "ForceFieldShape.h" #include "ForceFieldShapeFactory.h" #include "TypeInfo.h" namespace nGENE { /** Capsule shape. */ class nGENEDLL ForceFieldShapeCapsule: public ForceFieldShape { EXPOSE_TYPE private: /// PhysX capsule descriptor NxCapsuleForceFieldShapeDesc* m_pCapsuleDesc; public: ForceFieldShapeCapsule(); ~ForceFieldShapeCapsule(); void init(); void cleanup(); /** Sets radius and height of the capsule. @param _dims radius is stored in 'x' and height in 'y'. */ void setDimensions(const Vector3& _dims); void setLocalPos(const Vector3& _pos); NxForceFieldShapeDesc* getForceFieldShapeDesc(); }; /// Factory to be used for creating box shapes. class nGENEDLL ForceFieldCapsuleShapeFactory: public ForceFieldShapeFactory { public: ForceFieldCapsuleShapeFactory(); ~ForceFieldCapsuleShapeFactory(); ForceFieldShape* createShape(); }; } #endif
[ "Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57" ]
[ [ [ 1, 66 ] ] ]
1f5b6ca0c45fca222b162275196e259779e4ce78
10bac563fc7e174d8f7c79c8777e4eb8460bc49e
/core/detail/tcp_pkt_sender_t.cpp
b3f8c97cdc99a4f1b1f8004c3ea32e15a81c84b7
[]
no_license
chenbk85/alcordev
41154355a837ebd15db02ecaeaca6726e722892a
bdb9d0928c80315d24299000ca6d8c492808f1d5
refs/heads/master
2021-01-10T13:36:29.338077
2008-10-22T15:57:50
2008-10-22T15:57:50
44,953,286
0
1
null
null
null
null
UTF-8
C++
false
false
2,951
cpp
#include "tcp_pkt_sender_t.hpp" namespace all { namespace core { namespace detail { tcp_pkt_sender_t::tcp_pkt_sender_t(boost::asio::ip::tcp::socket& socket) : m_socket(socket) { } void tcp_pkt_sender_t::set_error_callback(boost::function <void (const boost::system::error_code&)> error_callback) { m_error_callback = error_callback; } void tcp_pkt_sender_t::send_packet(net_packet_ptr_t packet) { const net_packet_header_t packet_header = packet->get_header(); //all::core::uint8_sarr header_buffer = packet_header.get_header(); //m_out_header_buffer.assign(reinterpret_cast <const char*> (header_buffer.get()), net_packet_header_t::HEADER_LENGTH); //m_out_data_buffer.assign(packet->get_buffer().get(), packet_header.get_packet_size()); //printf("packet data: %s\n", m_out_data_buffer.c_str()); //std::vector<boost::asio::const_buffer> buffers; // buffers.push_back(boost::asio::buffer(m_out_header_buffer)); //buffers.push_back(boost::asio::buffer(m_out_data_buffer)); //boost::asio::async_write(m_socket, // buffers, // boost::bind(&tcp_pkt_sender_t::handle_write, // this, // boost::asio::placeholders::error, // boost::asio::placeholders::bytes_transferred)); std::string* out_data_buffer_ptr = new std::string(reinterpret_cast <char*> (packet_header.get_header().get()), net_packet_header_t::HEADER_LENGTH); *out_data_buffer_ptr += std::string(packet->get_buffer().get(), packet_header.get_packet_size()); boost::asio::async_write(m_socket, boost::asio::buffer(*out_data_buffer_ptr), boost::bind(&tcp_pkt_sender_t::handle_write, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred, out_data_buffer_ptr)); } void tcp_pkt_sender_t::handle_write(const boost::system::error_code& error, std::size_t bytes_transferred, std::string* buffer_ptr) { if (!error) { all::core::BOOST_SLEEP(1); } else { printf("Error in tcp_pkt_sender_t::handle_write:\n %s", error.message().c_str()); if (m_error_callback) m_error_callback(error); } delete buffer_ptr; } void tcp_pkt_sender_t::send_packet_blk(net_packet_ptr_t packet) { const net_packet_header_t packet_header = packet->get_header(); all::core::uint8_sarr header_buffer = packet_header.get_header(); m_out_header_buffer.assign(reinterpret_cast <const char*> (header_buffer.get()), net_packet_header_t::HEADER_LENGTH); m_out_data_buffer.assign(packet->get_buffer().get(), packet_header.get_packet_size()); //printf("packet data: %s\n", m_out_data_buffer.c_str()); std::vector<boost::asio::const_buffer> buffers; buffers.push_back(boost::asio::buffer(m_out_header_buffer)); buffers.push_back(boost::asio::buffer(m_out_data_buffer)); boost::asio::write(m_socket, buffers); } }}} //namespaces
[ "stefano.marra@1c7d64d3-9b28-0410-bae3-039769c3cb81", "andrea.carbone@1c7d64d3-9b28-0410-bae3-039769c3cb81" ]
[ [ [ 1, 60 ], [ 62, 76 ], [ 78, 85 ] ], [ [ 61, 61 ], [ 77, 77 ] ] ]
b76c69d482bf93da5af8989ae8042a4298212082
cd0987589d3815de1dea8529a7705caac479e7e9
/webkit/WebKit2/Shared/WebPreferencesStore.cpp
e30f639292eb874809565c474f47b7ddf877b5ca
[]
no_license
azrul2202/WebKit-Smartphone
0aab1ff641d74f15c0623f00c56806dbc9b59fc1
023d6fe819445369134dee793b69de36748e71d7
refs/heads/master
2021-01-15T09:24:31.288774
2011-07-11T11:12:44
2011-07-11T11:12:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,840
cpp
/* * Copyright (C) 2010 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "WebPreferencesStore.h" #include "FontSmoothingLevel.h" namespace WebKit { static bool hasXSSAuditorEnabledTestRunnerOverride; static bool xssAuditorEnabledTestRunnerOverride; WebPreferencesStore::WebPreferencesStore() : javaScriptEnabled(true) , loadsImagesAutomatically(true) , pluginsEnabled(true) , offlineWebApplicationCacheEnabled(false) , localStorageEnabled(true) , xssAuditorEnabled(true) , fontSmoothingLevel(FontSmoothingLevelMedium) , minimumFontSize(1) , minimumLogicalFontSize(9) , defaultFontSize(16) , defaultFixedFontSize(13) , standardFontFamily("Times") , cursiveFontFamily("Apple Chancery") , fantasyFontFamily("Papyrus") , fixedFontFamily("Courier") , sansSerifFontFamily("Helvetica") , serifFontFamily("Times") { } void WebPreferencesStore::encode(CoreIPC::ArgumentEncoder* encoder) const { encoder->encode(javaScriptEnabled); encoder->encode(loadsImagesAutomatically); encoder->encode(pluginsEnabled); encoder->encode(offlineWebApplicationCacheEnabled); encoder->encode(localStorageEnabled); encoder->encode(xssAuditorEnabled); encoder->encode(fontSmoothingLevel); encoder->encode(minimumFontSize); encoder->encode(minimumLogicalFontSize); encoder->encode(defaultFontSize); encoder->encode(defaultFixedFontSize); encoder->encode(standardFontFamily); encoder->encode(cursiveFontFamily); encoder->encode(fantasyFontFamily); encoder->encode(fixedFontFamily); encoder->encode(sansSerifFontFamily); encoder->encode(serifFontFamily); } bool WebPreferencesStore::decode(CoreIPC::ArgumentDecoder* decoder, WebPreferencesStore& s) { if (!decoder->decode(s.javaScriptEnabled)) return false; if (!decoder->decode(s.loadsImagesAutomatically)) return false; if (!decoder->decode(s.pluginsEnabled)) return false; if (!decoder->decode(s.offlineWebApplicationCacheEnabled)) return false; if (!decoder->decode(s.localStorageEnabled)) return false; if (!decoder->decode(s.xssAuditorEnabled)) return false; if (!decoder->decode(s.fontSmoothingLevel)) return false; if (!decoder->decode(s.minimumFontSize)) return false; if (!decoder->decode(s.minimumLogicalFontSize)) return false; if (!decoder->decode(s.defaultFontSize)) return false; if (!decoder->decode(s.defaultFixedFontSize)) return false; if (!decoder->decode(s.standardFontFamily)) return false; if (!decoder->decode(s.cursiveFontFamily)) return false; if (!decoder->decode(s.fantasyFontFamily)) return false; if (!decoder->decode(s.fixedFontFamily)) return false; if (!decoder->decode(s.sansSerifFontFamily)) return false; if (!decoder->decode(s.serifFontFamily)) return false; if (hasXSSAuditorEnabledTestRunnerOverride) s.xssAuditorEnabled = xssAuditorEnabledTestRunnerOverride; return true; } void WebPreferencesStore::overrideXSSAuditorEnabledForTestRunner(bool enabled) { hasXSSAuditorEnabledTestRunnerOverride = true; xssAuditorEnabledTestRunnerOverride = enabled; } void WebPreferencesStore::removeTestRunnerOverrides() { hasXSSAuditorEnabledTestRunnerOverride = false; } } // namespace WebKit
[ [ [ 1, 131 ] ] ]
42793e903fdb456db30223b7f5d35af888103c19
6e563096253fe45a51956dde69e96c73c5ed3c18
/dhnetsdk/dvr/mutex.h
3a401f4e9fbb2316dde522e972879c355a0d2ef6
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
842
h
#ifndef MUTEX_H #define MUTEX_H #ifdef WIN32 #include <windows.h> /* class CCriticalSection { public: CCriticalSection() { InitializeCriticalSection(&m_sec); } ~CCriticalSection() { DeleteCriticalSection(&m_sec); } public: void Lock() { EnterCriticalSection(&m_sec); } void Unlock() { LeaveCriticalSection(&m_sec); } protected: CRITICAL_SECTION m_sec; }; */ class CCSLock { public: CCSLock(CRITICAL_SECTION& cs):m_cs(cs) { EnterCriticalSection(&m_cs); } ~CCSLock() { LeaveCriticalSection(&m_cs); } private: CRITICAL_SECTION& m_cs; }; #else #include <pthread.h> #endif class DEVMutex { public: DEVMutex(); ~DEVMutex(); int Lock(); int UnLock(); private: #ifdef WIN32 CRITICAL_SECTION m_critclSection; #else pthread_mutex_t m_mutex; #endif }; #endif
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 65 ] ] ]
34896d8152d9293e9b9068015a589f732fdd8541
e743f7cb85ebc6710784a39e2941e277bd359508
/directmidi/CDirectBase.h
bd28d4ea35db74fc325b6c6cf26713df1de3bed7
[]
no_license
aidinabedi/directmidi4unity
8c982802de97855fcdaab36709c6b1c8eb0b2e52
8c3e33e7b44c3fe248e0718e4b8f9e2260d9cd8f
refs/heads/master
2021-01-20T15:30:16.131068
2009-12-03T08:37:36
2009-12-03T08:37:36
90,773,445
1
0
null
null
null
null
WINDOWS-1250
C++
false
false
9,087
h
/* ____ _ ____ _____ _____ ______ __ __ _ ____ _ | _ \ | || _ \| __// __//_ _/ | \/ || || _ \ | | | |_| || || |> /| _| | <__ | | | |\/| || || |_| || | |____/ |_||_|\_\|____\\____/ |_| |_| |_||_||____/ |_| //////////////////////////////////////////////////////////////////////// This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Copyright (c) 2002-2004 by Carlos Jiménez de Parga All rights reserved. For any suggestion or failure report, please contact me by: e-mail: [email protected] Note: I would appreciate very much if you could provide a brief description of your project, as well as any report on bugs or errors. This will help me improve the code for the benefit of your application and the other users /////////////////////////////////////////////////////////////////////// Version: 2.3b Module : CDirectBase.h Purpose: Defines the header implementation for the library classes Created: CJP / 02-08-2002 History: CJP / 20-02-2004 Date format: Day-month-year Update: 20/09/2002 1. Improved class destructors 2. Check member variables for NULL values before performing an operation 3. Restructured the class system 4. Better method to enumerate and select MIDI ports 5. Adapted the external thread to a virtual function 6. SysEx reception and sending enabled 7. Added flexible conversion functions 8. Find out how to activate the Microsoft software synth. 9. Added DLS support Update: 25/03/2003 10. Added exception handling 11. Fixed bugs with channel groups 12. Redesigned class hierarchy 13. DirectMidi wrapped in the directmidi namespace 14. UNICODE/MBCS support for instruments and ports 15. Added DELAY effect to software synthesizer ports 16. Project released under GNU (General Public License) terms Update: 03/10/2003 17. Redesigned class interfaces 18. Safer input port termination thread 19. New CMasterClock class 20. DLS files can be loaded from resources 21. DLS instruments note range support 22. New CSampleInstrument class added to the library 23. Direct download of samples to wave-table memory 24. .WAV file sample format supported 25. New methods added to the output port class 26. Fixed small bugs Update: 20/02/2004 27. Added new DirectMusic classes for Audio handling 28. Improved CMidiPort class with internal buffer run-time resizing 29. 3D audio positioning */ #ifndef CDIRECTBASE_H #define CDIRECTBASE_H // Some required DX headers #include <dmusicc.h> #include <dmusici.h> #include <dmksctrl.h> #include <dmdls.h> #include <windows.h> #include <process.h> #include <tchar.h> #include ".\\dsutil\\dsutil.h" #pragma warning(disable:4786) // STL list #include <vector> #include <list> // Defines utility macros #ifndef SAFE_RELEASE #define SAFE_RELEASE(p) { if(p) {(p)->Release(); (p) = NULL;} } #endif #ifndef SAFE_DELETE #define SAFE_DELETE(p) { if(p) {delete (p); (p) = NULL;} } #endif #ifndef SAFE_DELETE_ARRAY #define SAFE_DELETE_ARRAY(p) { if(p) {delete[] (p); (p)=NULL;} } #endif namespace directmidi { const long DM_FAILED = -1; // Byte constants to activate synthesizer effect (only if supported) const BYTE SET_NOEFFECT = 0x0; const BYTE SET_REVERB = 0x1; const BYTE SET_CHORUS = 0x2; const BYTE SET_DELAY = 0x4; // Reserved constants for internal operations const BYTE MIDI_STRUCTURED = 3; const BYTE SHIFT_8 = 8; const BYTE SHIFT_16 = 16; const BYTE BITMASK = 15; // >>>>>> Main status bytes of the MIDI message system <<<<<< // Note off event const BYTE NOTE_OFF = 0x80; // Note on event const BYTE NOTE_ON = 0x90; // Program change const BYTE PATCH_CHANGE = 0xC0; // Polyphonic Key Pressure (Aftertouch) const BYTE POLY_PRESSURE = 0xA0; // Control Change const BYTE CONTROL_CHANGE = 0xB0; //Channel Pressure (After-touch). const BYTE CHANNEL_PREASURE = 0xD0; // Pitch Wheel Change const BYTE PITCH_BEND = 0xE0; // >>>>> System Common messages <<<<<< // Start of exclusive const BYTE START_SYS_EX = 0xF0; // End of exclusive const BYTE END_SYS_EX = 0xF7; // Song position pointer const BYTE SONG_POINTER = 0xF2; // Song select const BYTE SONG_SELECT = 0xF3; // Tune request const BYTE TUNE_REQUEST = 0xF6; // >>>>>> System Real-Time Messages <<<<<< // Timing clock const BYTE TIMING_CLOCK = 0xF8; // Reset const BYTE RESET = 0xFF; // Active sensing const BYTE ACTIVE_SENSING = 0xFE; // Start the sequence const BYTE START = 0xFA; // Stop the sequence const BYTE STOP = 0xFC; const BOOL DM_LOAD_FROM_FILE = TRUE; const BOOL DM_USE_MEMORY = FALSE; // Infoport structure typedef struct INFOPORT { TCHAR szPortDescription[DMUS_MAX_DESCRIPTION]; //Port description string in MBCS/UNICODE chars DWORD dwFlags; // Port characteristics DWORD dwClass; // Class of port (Input/Output) DWORD dwType; // Type of port (See remarks) DWORD dwMemorySize; // Amount of memory available to store DLS instruments DWORD dwMaxAudioChannels; // Maximum number of audio channels that can be rendered by the port DWORD dwMaxVoices; // Maximum number of voices that can be allocated when this port is opened DWORD dwMaxChannelGroups ; // Maximum number of channel groups supported by this port DWORD dwSampleRate; // Desired Sample rate in Hz; DWORD dwEffectFlags; // Flags indicating what audio effects are available on the port DWORD dwfShare; // Exclusive/shared mode DWORD dwFeatures; // Miscellaneous capabilities of the port GUID guidSynthGUID; // Identifier of the port } *LPINFOPORT; // Instrument Info structure typedef struct INSTRUMENTINFO { TCHAR szInstName[MAX_PATH]; // Name of the instruments in MBCS/UNICODE chars DWORD dwPatchInCollection; // Position of the instrument in the collection } *LPINSTRUMENTINFO; // Clock info structure typedef struct CLOCKINFO { DMUS_CLOCKTYPE ctType; GUID guidClock; // Clock GUID TCHAR szClockDescription[DMUS_MAX_DESCRIPTION]; DWORD dwFlags; } *LPCLOCKINFO; // Synthesizer stats typedef struct SYNTHSTATS { DWORD dwSize; DWORD dwValidStats; DWORD dwVoices; DWORD dwTotalCPU; DWORD dwCPUPerVoice; DWORD dwLostNotes; DWORD dwFreeMemory; long lPeakVolume; DWORD dwSynthMemUse; } *LPSYNTHSTATS; // Region structure typedef struct REGION { RGNRANGE RangeKey; RGNRANGE RangeVelocity; } *LPREGION; // Articulation parameters structure typedef struct ARTICPARAMS { DMUS_LFOPARAMS LFO; DMUS_VEGPARAMS VolEG; DMUS_PEGPARAMS PitchEG; DMUS_MSCPARAMS Misc; } *LPARTICPARAMS; TCENT TimeCents(double nTime); PCENT PitchCents(double nFrequency); GCENT GainCents(double nVoltage,double nRefVoltage); PCENT PercentUnits(double nPercent); void DM_ASSERT(TCHAR strMembrFunc[],int nLine,BOOL Param1, BOOL Param2 = false, BOOL Param3 = false); void DM_ASSERT_HR(TCHAR strMembrFunc[],int nLine,HRESULT hr); // CDMusicException definition class CDMusicException { TCHAR m_strErrorBuf[512], m_strMessage[256]; // Error output strings protected: void CopyMsg(LPCTSTR strDefMsg,LPCTSTR strDescMsg); void ObtainErrorString(); public: HRESULT m_hrCode; // The HRESULT return value TCHAR m_strMethod[128]; // The method where the DirectMusic function failed int m_nLine; // The line where the DirectMusic call failed CDMusicException(LPCTSTR lpMemberFunc,HRESULT hr,int nLine) throw(); LPCTSTR ErrorToString() throw(); // Returns the error definition LPCTSTR GetErrorDescription() throw(); // Returns the complete error description }; // Class prototypes class CInstrument; class CCollection; class CDLSLoader; class CMidiPort; class CReceiver; class CInputPort; class COutputPort; class CDirectMusic; class CSampleInstrument; class CMasterClock; class CSegment; class CPerformance; class CAPathPerformance; class CPortPerformance; class CAudioPath; class CSegment; class C3DSegment; class C3DListener; class C3DBuffer; } #endif
[ [ [ 1, 332 ] ] ]
148b791c6a74c7c368c1fd45f7a224868cf3c6b5
36fea6c98ecabcd5e932f2b7854b3282cdb571ee
/dialogsearch.h
b4cfbc637b1b6eece97520dacfae3a1e6615f183
[]
no_license
doomfrawen/visualcommand
976adaae69303d8b4ffc228106a1db9504e4a4e4
f7bc1d590444ff6811f84232f5c6480449228e19
refs/heads/master
2016-09-06T17:40:57.775379
2009-07-28T22:48:23
2009-07-28T22:48:23
32,345,504
0
0
null
null
null
null
UTF-8
C++
false
false
428
h
#ifndef DIALOGSEARCH_H #define DIALOGSEARCH_H #include <QtGui/QDialog> namespace Ui { class DialogSearch; } class DialogSearch : public QDialog { Q_OBJECT Q_DISABLE_COPY(DialogSearch) public: explicit DialogSearch(QWidget *parent = 0); virtual ~DialogSearch(); protected: virtual void changeEvent(QEvent *e); private: Ui::DialogSearch *m_ui; }; #endif // DIALOGSEARCH_H
[ "flouger@13a168e0-7ae3-11de-a146-1f7e517e55b8" ]
[ [ [ 1, 24 ] ] ]
fdf2df40ab48c6018bf9688956e7d054df846606
f55665c5faa3d79d0d6fe91fcfeb8daa5adf84d0
/Depend/MyGUI/Plugins/Plugin_AwesomiumWidget/Plugin.h
ad21e49cb04183b2f5d3430d3ef41c45393c07cc
[]
no_license
lxinhcn/starworld
79ed06ca49d4064307ae73156574932d6185dbab
86eb0fb8bd268994454b0cfe6419ffef3fc0fc80
refs/heads/master
2021-01-10T07:43:51.858394
2010-09-15T02:38:48
2010-09-15T02:38:48
47,859,019
2
1
null
null
null
null
WINDOWS-1251
C++
false
false
817
h
/*! @file @author Albert Semenov @date 10/2009 */ #ifndef __PLUGIN_H__ #define __PLUGIN_H__ #include "AwesomiumWidget.h" #include "MyGUI_Plugin.h" /*! Test plugin to demonstrate possibilities of plugins for MyGUI */ namespace plugin { class Plugin : public MyGUI::IPlugin { public: Plugin(); ~Plugin(); public: //! Initialization virtual void initialize(); //! Installation virtual void install(); //! Shut down virtual void shutdown(); //! Uninstall virtual void uninstall(); //! Get name virtual const std::string& getName() const; private: // фабрики виджетов Awesomium::AwesomiumWidgetFactory* mFactory; static const std::string LogSection; }; } // namespace plugin #endif // __PLUGIN_H__
[ "albertclass@a94d7126-06ea-11de-b17c-0f1ef23b492c" ]
[ [ [ 1, 52 ] ] ]
7ed8ea8bf8a64017541d1d9d84ec6b6d503edc6d
cb1c6c586d769f919ed982e9364d92cf0aa956fe
/examples/TRTRenderTest/RenderTest.h
f15b9dec6f15b5e0beadf4e6042b34c475080a86
[]
no_license
jrk/tinyrt
86fd6e274d56346652edbf50f0dfccd2700940a6
760589e368a981f321e5f483f6d7e152d2cf0ea6
refs/heads/master
2016-09-01T18:24:22.129615
2010-01-07T15:19:44
2010-01-07T15:19:44
462,454
3
0
null
null
null
null
UTF-8
C++
false
false
1,673
h
//===================================================================================================================== // // RenderTest.h // // Part of the TinyRT Raytracing Library. // Author: Joshua Barczak // // Copyright 2008 Joshua Barczak. All rights reserved. // See Doc/LICENSE.txt for terms and conditions. // //===================================================================================================================== #ifndef _RENDERTEST_H_ #define _RENDERTEST_H_ #include "TinyRT.h" using namespace TinyRT; #include "TestRaycaster.h" #include "ViewpointGenerator.h" #include <string> //===================================================================================================================== /// \brief Rendering test harness //===================================================================================================================== class RenderTest { public: struct Options { uint32 nImageSize; ///< Size of images to render uint32 nTileSize; ///< Organize pixels in NxN tiles std::string dumpFilePrefix; ///< Path and filename prefix for image files. If non-empty, then images will be dumped std::string goldImagePrefix; ///< Path and filename prefix for 'gold' images. If non-empty, gold image testing is done }; RenderTest( TestRaycaster* pRC, ViewpointGenerator* pViews, const Options& rOpts ); ~RenderTest(); virtual void Run( ); private: Options m_opts; TestRaycaster* m_pRaycaster; ViewpointGenerator* m_pViewpoints; }; #endif // _TRT_DERTEST_H_
[ "jbarcz1@6ce04321-59f9-4392-9e3f-c0843787e809" ]
[ [ [ 1, 53 ] ] ]
5fe0aa03e70b7e34882fe0d877eafaacb35bcc6c
4d91ca4dcaaa9167928d70b278b82c90fef384fa
/CedeCryptViewer/CedeCrypt/CedeCrypt/DynStringList.h
1d181738d9e611b88d867b909f7a47be58577560
[]
no_license
dannydraper/CedeCryptClassic
13ef0d5f03f9ff3a9a1fe4a8113e385270536a03
5f14e3c9d949493b2831710e0ce414a1df1148ec
refs/heads/master
2021-01-17T13:10:51.608070
2010-10-01T10:09:15
2010-10-01T10:09:15
63,413,327
0
0
null
null
null
null
UTF-8
C++
false
false
484
h
#include <windows.h> #include <malloc.h> #include <io.h> #include <direct.h> #include <stdio.h> class DynStringList { public: DynStringList (); ~DynStringList (); void Clear (); void AddItem (LPCSTR szItem); LPCSTR GetItem (long iLoc); BOOL DoesExist (LPCSTR szItem); int GetNumItems (); void RemoveLastItem (); private: char *dynlist; BYTE *dynpointers; long dynlistsize; long dynpointerssize; long curpointer; long numitems; };
[ "ddraper@f12373e4-23ff-6a4a-9817-e77f09f3faef" ]
[ [ [ 1, 25 ] ] ]
00ec730cb5c944abec773fd4dd4dfa3b0d5fee1d
cc336f796b029620d6828804a866824daa6cc2e0
/cximage/CxImage/ximawbmp.h
0bb1936623a384f25f31af3ba85577b68aa84ca6
[]
no_license
tokyovigilante/xbmc-sources-fork
84fa1a4b6fec5570ce37a69d667e9b48974e3dc3
ac3c6ef8c567f1eeb750ce6e74c63c2d53fcde11
refs/heads/master
2021-01-19T10:11:37.336476
2009-03-09T20:33:58
2009-03-09T20:33:58
29,232
2
0
null
null
null
null
UTF-8
C++
false
false
2,167
h
/* * File: ximawbmp.h * Purpose: WBMP Image Class Loader and Writer */ /* === C R E D I T S & D I S C L A I M E R S ============== * CxImageWBMP (c) 12/Jul/2002 <[email protected]> * Permission is given by the author to freely redistribute and include * this code in any program as long as this credit is given where due. * * CxImage version 5.80 29/Sep/2003 * See the file history.htm for the complete bugfix and news report. * * COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY * OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES * THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE * OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED * CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT * THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY * SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL * PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. * * Use at your own risk! * ========================================================== */ #if !defined(__ximaWBMP_h) #define __ximaWBMP_h #include "ximage.h" #if CXIMAGE_SUPPORT_WBMP class CxImageWBMP: public CxImage { #pragma pack(1) typedef struct tagWbmpHeader { BYTE Type; // 0 BYTE FixHeader; // 0 BYTE ImageWidth; // Image Width BYTE ImageHeight; // Image Height } WBMPHEADER; #pragma pack() public: CxImageWBMP(): CxImage(CXIMAGE_FORMAT_WBMP) {} // bool Load(const char * imageFileName){ return CxImage::Load(imageFileName,CXIMAGE_FORMAT_WBMP);} // bool Save(const char * imageFileName){ return CxImage::Save(imageFileName,CXIMAGE_FORMAT_WBMP);} bool Decode(CxFile * hFile); bool Encode(CxFile * hFile); bool Decode(FILE *hFile) { CxIOFile file(hFile); return Decode(&file); } bool Encode(FILE *hFile) { CxIOFile file(hFile); return Encode(&file); } }; #endif #endif
[ "jmarshallnz@568bbfeb-2a22-0410-94d2-cc84cf5bfa90" ]
[ [ [ 1, 58 ] ] ]
9031e48b32597f4a966cea432bac0e6db1cce992
28aa23d9cb8f5f4e8c2239c70ef0f8f6ec6d17bc
/mytesgnikrow --username hotga2801/Project/MotionAdaboost/Develop/hbp/classColourClassifier.h
3ca87b46cda023b66482ab2017edb1d67f210a13
[]
no_license
taicent/mytesgnikrow
09aed8836e1297a24bef0f18dadd9e9a78ec8e8b
9264faa662454484ade7137ee8a0794e00bf762f
refs/heads/master
2020-04-06T04:25:30.075548
2011-02-17T13:37:16
2011-02-17T13:37:16
34,991,750
0
0
null
null
null
null
UTF-8
C++
false
false
1,943
h
/*************************************************************************** classColourClassifier.h used to classify the type and distribution of colours begin : Thu Feb 19 2004 copyright : (C) 2004 by Bob Mottram email : [email protected] ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #ifndef CLASS_COLOURCLASSIFIER_H #define CLASS_COLOURCLASSIFIER_H /** *@author Bob Mottram */ #include "stdafx.h" #include <afxwin.h> /// <summary> /// This class stores a list of commonly observed colours. It is used to classify clothing typically worn by individuals. /// </summary> class classColourClassifier { private: //bounding box int top_x, top_y, bottom_x, bottom_y; long total_pixels; bool sorted; //colour info int NoOfGroups; long colour_group[100][5]; //sort the groups by no of hits void sort(); public: //the tollerance within which a colour is classified as belonging to a group int tollerance; void clear(); void update(int r, int g, int b, int x, int y); void getGroupColour(int index, int &r, int &g, int &b, int &coverage); classColourClassifier(); ~classColourClassifier(); }; #endif
[ "hotga2801@ecd9aaca-b8df-3bf4-dfa7-576663c5f076" ]
[ [ [ 1, 62 ] ] ]
671230052f7510029223301145d43ea4c7d2f162
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testmsgqueue/src/tmsgqueueserver.cpp
1d4f6d394522a9c1ff68f871e0ed0a0adcfd32b5
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
7,481
cpp
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /* * ============================================================================== * Name : tmsgqueueserver.cpp * Part of : testmsgqueue * * Description : ?Description * Version: 0.5 * */ #include <c32comm.h> #if defined (__WINS__) #define PDD_NAME _L("ECDRV") #else #define PDD_NAME _L("EUART1") #define PDD2_NAME _L("EUART2") #define PDD3_NAME _L("EUART3") #define PDD4_NAME _L("EUART4") #endif #define LDD_NAME _L("ECOMM") /** * @file * * Pipe test server implementation */ #include "tmsgqueueserver.h" #include "tmsgqueue.h" _LIT(KServerName, "tmsgqueue"); CMsgqueueTestServer::CMsgqueueTestServer() { } CMsgqueueTestServer::~CMsgqueueTestServer() { } CMsgqueueTestServer* CMsgqueueTestServer::NewL() { CMsgqueueTestServer *server = new(ELeave) CMsgqueueTestServer(); CleanupStack::PushL(server); TRAPD(err,server->ConstructL(KServerName)); if(err != KErrNone) { CleanupStack::PopAndDestroy(server); server = NULL; User::Leave(err); } CleanupStack::Pop(server); return server; } static void InitCommsL() { TInt ret = User::LoadPhysicalDevice(PDD_NAME); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); #ifndef __WINS__ ret = User::LoadPhysicalDevice(PDD2_NAME); ret = User::LoadPhysicalDevice(PDD3_NAME); ret = User::LoadPhysicalDevice(PDD4_NAME); #endif ret = User::LoadLogicalDevice(LDD_NAME); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); ret = StartC32(); User::LeaveIfError(ret == KErrAlreadyExists?KErrNone:ret); } LOCAL_C void MainL() { // Leave the hooks in for platform security #if (defined __DATA_CAGING__) RProcess().DataCaging(RProcess::EDataCagingOn); RProcess().SecureApi(RProcess::ESecureApiOn); #endif //InitCommsL(); CActiveScheduler* sched=NULL; sched=new(ELeave) CActiveScheduler; CActiveScheduler::Install(sched); CMsgqueueTestServer* server = NULL; // Create the CTestServer derived server __UHEAP_MARK; TRAPD(err, server = CMsgqueueTestServer::NewL()); if(!err) { // Sync with the client and enter the active scheduler RProcess::Rendezvous(KErrNone); sched->Start(); } delete server; server = NULL; __UHEAP_MARKEND; delete sched; sched = NULL; } /** * Server entry point * @return Standard Epoc error code on exit */ TInt main() { //__UHEAP_MARK; CTrapCleanup* cleanup = CTrapCleanup::New(); if(cleanup == NULL) { return KErrNoMemory; } TRAPD(err,MainL()); if(err!=KErrNone) { } delete cleanup; //__UHEAP_MARKEND; return KErrNone; } CTestStep* CMsgqueueTestServer::CreateTestStep(const TDesC& aStepName) { CTestStep* testStep = NULL; // This server creates just one step but create as many as you want // They are created "just in time" when the worker thread is created // install steps if(aStepName == KMessageQueueCreate) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KMessageQueueControl) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest2) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest3) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest4) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest5) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest6) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest7) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest8) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest9) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest10) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest11) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest12) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest13) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest14) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest15) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest16) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest17) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KIntgTest6_1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsggettest1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsggettest2) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsggettest3) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsggettest4) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsggettest5) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsggettest6) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == KMsggetCreateKey) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgctltest1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgctltest2) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgctltest3) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgctltest4) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgctltest5) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgsndtest1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgsndtest2) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgsndtest3) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgsndtest4) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgsndtest5) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgsndtest6) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgrcvtest1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgrcvtest2) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgrcvtest3) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kmsgrcvtest4) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Ksndrcvtest1) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Ksndrcvtest2) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Ksndrcvtest3) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Ksndrcvtest4) { testStep = new CTestMsgqueue(aStepName); } if(aStepName == Kthsndrcvtest1) { testStep = new CTestMsgqueue(aStepName); } return testStep; }
[ "none@none" ]
[ [ [ 1, 345 ] ] ]
5da010d60204e6b6415e34321f72069bdebf3c59
74c8da5b29163992a08a376c7819785998afb588
/NetAnimal/addons/pa/ParticleUniverse/src/ParticleUniverseRendererTokens.cpp
377e8a4c504063ccbb0f45c3edc816caa33f7840
[]
no_license
dbabox/aomi
dbfb46c1c9417a8078ec9a516cc9c90fe3773b78
4cffc8e59368e82aed997fe0f4dcbd7df626d1d0
refs/heads/master
2021-01-13T14:05:10.813348
2011-06-07T09:36:41
2011-06-07T09:36:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,309
cpp
/* ----------------------------------------------------------------------------------------------- This source file is part of the Particle Universe product. Copyright (c) 2010 Henry van Merode Usage of this program is licensed under the terms of the Particle Universe Commercial License. You can find a copy of the Commercial License in the Particle Universe package. ----------------------------------------------------------------------------------------------- */ #include "ParticleUniversePCH.h" #ifndef PARTICLE_UNIVERSE_EXPORTS #define PARTICLE_UNIVERSE_EXPORTS #endif #include "ParticleUniverseRendererTokens.h" #include "ParticleUniverseRenderer.h" #include "ParticleRenderers/ParticleUniverseBillboardRenderer.h" namespace ParticleUniverse { /************************************************************************** * RendererSetTranslator *************************************************************************/ void RendererSetTranslator::translate(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { Ogre::ObjectAbstractNode* obj = reinterpret_cast<Ogre::ObjectAbstractNode*>(node.get()); ParticleRenderer* renderer = Ogre::any_cast<ParticleRenderer*>(obj->parent->context); // Run through properties for(Ogre::AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { if((*i)->type == Ogre::ANT_PROPERTY) { Ogre::PropertyAbstractNode* prop = reinterpret_cast<Ogre::PropertyAbstractNode*>((*i).get()); if (prop->name == token[TOKEN_RENDERER_TEXCOORDS_DEFINE]) { // Property: render_queue_group if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_TEXCOORDS_DEFINE], VAL_VECTOR4)) { Ogre::Vector4 val; if(getVector4(prop->values.begin(), prop->values.end(), &val)) { renderer->addTextureCoords(val.x, val.y, val.z, val.w); } } } } else { errorUnexpectedToken(compiler, *i); } } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- /************************************************************************** * RendererTranslator *************************************************************************/ RendererTranslator::RendererTranslator() :mRenderer(0) { } //------------------------------------------------------------------------- void RendererTranslator::translate(Ogre::ScriptCompiler* compiler, const Ogre::AbstractNodePtr &node) { Ogre::ObjectAbstractNode* obj = reinterpret_cast<Ogre::ObjectAbstractNode*>(node.get()); Ogre::ObjectAbstractNode* parent = obj->parent ? reinterpret_cast<Ogre::ObjectAbstractNode*>(obj->parent) : 0; // The name of the obj is the type of the Renderer // Remark: This can be solved by using a listener, so that obj->values is filled with type + name. Something for later Ogre::String type; if(!obj->name.empty()) { type = obj->name; } else { compiler->addError(Ogre::ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line); return; } // Get the factory ParticleRendererFactory* particleRendererFactory = ParticleSystemManager::getSingletonPtr()->getRendererFactory(type); if (!particleRendererFactory) { compiler->addError(Ogre::ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line); return; } // Create the Renderer mRenderer = ParticleSystemManager::getSingletonPtr()->createRenderer(type); if (!mRenderer) { compiler->addError(Ogre::ScriptCompiler::CE_INVALIDPARAMETERS, obj->file, obj->line); return; } if (!obj->parent->context.isEmpty()) { ParticleTechnique* technique = Ogre::any_cast<ParticleTechnique*>(obj->parent->context); technique->setRenderer(mRenderer); } else { // It is an alias mRenderer->setAliasName(parent->name); ParticleSystemManager::getSingletonPtr()->addAlias(mRenderer); } // Set it in the context obj->context = Ogre::Any(mRenderer); // Run through properties for(Ogre::AbstractNodeList::iterator i = obj->children.begin(); i != obj->children.end(); ++i) { // No properties of its own if((*i)->type == Ogre::ANT_PROPERTY) { Ogre::PropertyAbstractNode* prop = reinterpret_cast<Ogre::PropertyAbstractNode*>((*i).get()); if (prop->name == token[TOKEN_RENDERER_Q_GROUP]) { // Property: render_queue_group if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_Q_GROUP], VAL_UINT)) { Ogre::uint val = 0; if(getUInt(prop->values.front(), &val)) { mRenderer->setRenderQueueGroup(val); } } } else if (prop->name == token[TOKEN_RENDERER_SORTING]) { // Property: sorting if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_SORTING], VAL_BOOL)) { bool val = 0; if(getBoolean(prop->values.front(), &val)) { mRenderer->setSorted(val); } } } else if (prop->name == token[TOKEN_RENDERER_TEXCOORDS_ROWS]) { // Property: texture_coords_rows if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_TEXCOORDS_ROWS], VAL_UINT)) { Ogre::uint val = 0; if(getUInt(prop->values.front(), &val)) { mRenderer->setTextureCoordsRows(val); } } } else if (prop->name == token[TOKEN_RENDERER_TEXCOORDS_COLUMNS]) { // Property: texture_coords_columns if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_TEXCOORDS_COLUMNS], VAL_UINT)) { Ogre::uint val = 0; if(getUInt(prop->values.front(), &val)) { mRenderer->setTextureCoordsColumns(val); } } } else if (prop->name == token[TOKEN_RENDERER_USE_SOFT_PARTICLES]) { // Property: use_soft_particles if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_USE_SOFT_PARTICLES], VAL_BOOL)) { bool val = 0; if(getBoolean(prop->values.front(), &val)) { mRenderer->setUseSoftParticles(val); } } } else if (prop->name == token[TOKEN_RENDERER_SOFT_PARTICLES_CONTRAST_POWER]) { // Property: soft_particles_contrast_power if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_SOFT_PARTICLES_CONTRAST_POWER], VAL_REAL)) { Ogre::Real val = 0; if(getReal(prop->values.front(), &val)) { mRenderer->setSoftParticlesContrastPower(val); } } } else if (prop->name == token[TOKEN_RENDERER_SOFT_PARTICLES_SCALE]) { // Property: soft_particles_scale if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_SOFT_PARTICLES_SCALE], VAL_REAL)) { Ogre::Real val = 0; if(getReal(prop->values.front(), &val)) { mRenderer->setSoftParticlesScale(val); } } } else if (prop->name == token[TOKEN_RENDERER_SOFT_PARTICLES_DELTA]) { // Property: soft_particles_delta if (passValidateProperty(compiler, prop, token[TOKEN_RENDERER_SOFT_PARTICLES_DELTA], VAL_REAL)) { Ogre::Real val = 0; if(getReal(prop->values.front(), &val)) { mRenderer->setSoftParticlesDelta(val); } } } else if (particleRendererFactory->translateChildProperty(compiler, *i)) { // Parsed the property by another translator; do nothing } else { errorUnexpectedProperty(compiler, prop); } } else if((*i)->type == Ogre::ANT_OBJECT) { Ogre::ObjectAbstractNode* child = reinterpret_cast<Ogre::ObjectAbstractNode*>((*i).get()); if (child->cls == token[TOKEN_RENDERER_TEXCOORDS_SET]) { // Property: soft_particles_delta RendererSetTranslator rendererSetTranslator; rendererSetTranslator.translate(compiler, *i); } else if (particleRendererFactory->translateChildObject(compiler, *i)) { // Parsed the object by another translator; do nothing } else { processNode(compiler, *i); } } else { errorUnexpectedToken(compiler, *i); } } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- void ParticleRendererWriter::write(ParticleScriptSerializer* serializer, const IElement* element) { // Cast the element to a ParticleRenderer const ParticleRenderer* renderer = static_cast<const ParticleRenderer*>(element); // Write base attributes if (renderer->getRenderQueueGroup() != ParticleRenderer::DEFAULT_RENDER_QUEUE_GROUP) serializer->writeLine( token[TOKEN_RENDERER_Q_GROUP], Ogre::StringConverter::toString(renderer->getRenderQueueGroup()), 12); if (renderer->isSorted() != ParticleRenderer::DEFAULT_SORTED) serializer->writeLine( token[TOKEN_RENDERER_SORTING], Ogre::StringConverter::toString(renderer->isSorted()), 12); if (renderer->getTextureCoordsRows() != ParticleRenderer::DEFAULT_TEXTURECOORDS_ROWS) serializer->writeLine( token[TOKEN_RENDERER_TEXCOORDS_ROWS], Ogre::StringConverter::toString(renderer->getTextureCoordsRows()), 12); if (renderer->getTextureCoordsColumns() != ParticleRenderer::DEFAULT_TEXTURECOORDS_COLUMNS) serializer->writeLine( token[TOKEN_RENDERER_TEXCOORDS_COLUMNS], Ogre::StringConverter::toString(renderer->getTextureCoordsColumns()), 12); const Ogre::vector<Ogre::FloatRect*>::type uvList = renderer->getTextureCoords(); if (!uvList.empty()) { serializer->writeLine(token[TOKEN_RENDERER_TEXCOORDS_SET], 12); serializer->writeLine("{", 12); Ogre::vector<Ogre::FloatRect*>::type::const_iterator it; Ogre::vector<Ogre::FloatRect*>::type::const_iterator itEnd = uvList.end(); for (it = uvList.begin(); it != itEnd; ++it) { serializer->writeLine(token[TOKEN_RENDERER_TEXCOORDS_DEFINE], Ogre::StringConverter::toString(*it), 12); } serializer->writeLine("}", 12); } if (renderer->getUseSoftParticles() != ParticleRenderer::DEFAULT_USE_SOFT_PARTICLES) serializer->writeLine( token[TOKEN_RENDERER_USE_SOFT_PARTICLES], Ogre::StringConverter::toString(renderer->getUseSoftParticles()), 12); if (renderer->getSoftParticlesContrastPower() != ParticleRenderer::DEFAULT_SOFT_PARTICLES_CONTRAST_POWER) serializer->writeLine( token[TOKEN_RENDERER_SOFT_PARTICLES_CONTRAST_POWER], Ogre::StringConverter::toString(renderer->getSoftParticlesContrastPower()), 12); if (renderer->getSoftParticlesScale() != ParticleRenderer::DEFAULT_SOFT_PARTICLES_SCALE) serializer->writeLine( token[TOKEN_RENDERER_SOFT_PARTICLES_SCALE], Ogre::StringConverter::toString(renderer->getSoftParticlesScale()), 12); if (renderer->getSoftParticlesDelta() != ParticleRenderer::DEFAULT_SOFT_PARTICLES_DELTA) serializer->writeLine( token[TOKEN_RENDERER_SOFT_PARTICLES_DELTA], Ogre::StringConverter::toString(renderer->getSoftParticlesDelta()), 12); } }
[ [ [ 1, 298 ] ] ]
787989439f614792aa6f5847cc2e9a8b6a322821
8fb9ccf49a324a586256bb08c22edc92e23affcf
/src/Effects/Reverb/ReverbEngine.h
d5973169b1079dca178a6c91d1f84ea72bb9bdac
[]
no_license
eriser/tal-noisemak3r
76468c98db61dfa28315284b4a5b1acfeb9c1ff6
1043c8f237741ea7beb89b5bd26243f8891cb037
refs/heads/master
2021-01-18T18:29:56.446225
2010-08-05T20:51:35
2010-08-05T20:51:35
62,891,642
1
0
null
null
null
null
UTF-8
C++
false
false
3,090
h
/* ============================================================================== This file is part of Tal-Reverb by Patrick Kunz. Copyright(c) 2005-2009 Patrick Kunz, TAL Togu Audio Line, Inc. http://kunz.corrupt.ch This file may be licensed under the terms of of the GNU General Public License Version 2 (the ``GPL''). Software distributed under the License is distributed on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the GPL for the specific language governing rights and limitations. You should have received a copy of the GPL along with this program. If not, go to http://www.gnu.org/licenses/gpl.html or write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ============================================================================== */ #if !defined(__ReverbEngine_h) #define __ReverbEngine_h #include "Reverb.h" #include "AudioUtils.h" #include "Params.h" #include "NoiseGenerator.h" class ReverbEngine { public: float *param; Reverb* reverb; NoiseGenerator *noiseGenerator; float dry; float wet; float stereoWidth; AudioUtils audioUtils; ReverbEngine(float sampleRate) { Params *params= new Params(); this->param= params->parameters; initialize(sampleRate); } ~ReverbEngine() { delete reverb; delete noiseGenerator; } void setDry(float dry) { this->dry = audioUtils.getLogScaledVolume(dry, 1.0f); } void setWet(float wet) { this->wet = audioUtils.getLogScaledVolume(wet, 1.0f); } void setDecayTime(float decayTime) { reverb->setDecayTime(decayTime); } void setPreDelay(float preDelay) { reverb->setPreDelay(preDelay); } void setLowCut(float value) { reverb->setLowCut(value); } void setHighCut(float value) { reverb->setHighCut(value); } void setStereoWidth(float stereoWidth) { this->stereoWidth = stereoWidth; } void setStereoMode(float stereoMode) { reverb->setStereoMode(stereoMode > 0.0f ? true : false); } void setSampleRate(float sampleRate) { initialize(sampleRate); } void initialize(float sampleRate) { reverb = new Reverb((int)sampleRate); noiseGenerator = new NoiseGenerator(sampleRate); dry = 1.0f; wet = 0.5f; stereoWidth = 1.0f; } void process(float *sampleL, float *sampleR) { if (wet > 0.0f) { float noise = noiseGenerator->tickNoise() * 0.000000001f; *sampleL += noise; *sampleR += noise; float drysampleL = *sampleL; float drysampleR = *sampleR; reverb->process(sampleL, sampleR); // Process Stereo float wet1 = wet * (stereoWidth * 0.5f + 0.5f); float wet2 = wet * ((1.0f - stereoWidth) * 0.5f); float resultL = *sampleL * wet1 + *sampleR * wet2 + drysampleL * dry; float resultR = *sampleR * wet1 + *sampleL * wet2 + drysampleR * dry; *sampleL = resultL; *sampleR = resultR; } } }; #endif
[ "patrickkunzch@1672e8fc-9579-4a43-9460-95afed9bdb0b" ]
[ [ [ 1, 140 ] ] ]
6c5446feb5822a3d8e4830ec63aa52bcdc3c565a
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Intersection/Wm4IntrCircle3Plane3.h
a7dd1bbdd5427b59e843fe0e792f2c910cc048ba
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
2,131
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4INTRCIRCLE3PLANE3_H #define WM4INTRCIRCLE3PLANE3_H #include "Wm4FoundationLIB.h" #include "Wm4Intersector.h" #include "Wm4Circle3.h" #include "Wm4Plane3.h" namespace Wm4 { template <class Real> class WM4_FOUNDATION_ITEM IntrCircle3Plane3 : public Intersector<Real,Vector3<Real> > { public: IntrCircle3Plane3 (const Circle3<Real>& rkCircle, const Plane3<Real>& rkPlane); // object access const Circle3<Real>& GetCircle () const; const Plane3<Real>& GetPlane () const; // static intersection queries virtual bool Test (); virtual bool Find (); // Information about the intersection set. Only get the specific object // of intersection corresponding to the intersection type. If the type // is IT_POINT, use GetPoint(i). If the type is IT_OTHER, the set is a // circle, so use GetIntersectionCircle(), which returns the circle // object. int GetQuantity () const; const Vector3<Real>& GetPoint (int i) const; const Circle3<Real>& GetIntersectionCircle () const; protected: using Intersector<Real,Vector3<Real> >::IT_EMPTY; using Intersector<Real,Vector3<Real> >::IT_POINT; using Intersector<Real,Vector3<Real> >::IT_PLANE; using Intersector<Real,Vector3<Real> >::IT_OTHER; using Intersector<Real,Vector3<Real> >::m_iIntersectionType; // the objects to intersect const Circle3<Real>& m_rkCircle; const Plane3<Real>& m_rkPlane; // information about the intersection set int m_iQuantity; Vector3<Real> m_akPoint[2]; }; typedef IntrCircle3Plane3<float> IntrCircle3Plane3f; typedef IntrCircle3Plane3<double> IntrCircle3Plane3d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 68 ] ] ]
e1d78428eddaed82521f5704b2f3c4371dce3ec2
68bfdfc18f1345d1ff394b8115681110644d5794
/Examples/Example01/TextureLoaderBlp.h
0d8c3f91172a62ff73e3abe7c71dd4db76b484f8
[]
no_license
y-gupta/glwar3
43afa1efe475d937ce0439464b165c745e1ec4b1
bea5135bd13f9791b276b66490db76d866696f9a
refs/heads/master
2021-05-28T12:20:41.532727
2010-12-09T07:52:12
2010-12-09T07:52:12
32,911,819
1
0
null
null
null
null
UTF-8
C++
false
false
2,592
h
#pragma once //+----------------------------------------------------------------------------- //| Included files //+----------------------------------------------------------------------------- #include "TextureLoader.h" //+----------------------------------------------------------------------------- //| Constants //+----------------------------------------------------------------------------- CONST INT MAX_NR_OF_BLP_MIP_MAPS = 16; //+----------------------------------------------------------------------------- //| Blp header structure //+----------------------------------------------------------------------------- struct BLP_HEADER { BLP_HEADER() { MagicNumber= '1PLB'; Compression = 0; Flags = 0; Width = 0; Height = 0; PictureType = 0; PictureSubType = 0; ZeroMemory(Offset, MAX_NR_OF_BLP_MIP_MAPS * sizeof(DWORD)); ZeroMemory(Size, MAX_NR_OF_BLP_MIP_MAPS * sizeof(DWORD)); } DWORD MagicNumber; DWORD Compression; DWORD Flags; DWORD Width; DWORD Height; DWORD PictureType; DWORD PictureSubType; DWORD Offset[MAX_NR_OF_BLP_MIP_MAPS]; DWORD Size[MAX_NR_OF_BLP_MIP_MAPS]; }; //+----------------------------------------------------------------------------- //| Blp RGBA structure //+----------------------------------------------------------------------------- struct BLP_RGBA { UCHAR Red; UCHAR Green; UCHAR Blue; UCHAR Alpha; }; //+----------------------------------------------------------------------------- //| Blp pixel structure //+----------------------------------------------------------------------------- struct BLP_PIXEL { UCHAR Index; }; //+----------------------------------------------------------------------------- //| Texture loader blp class //+----------------------------------------------------------------------------- class TEXTURE_LOADER_BLP : public TEXTURE_LOADER { public: CONSTRUCTOR TEXTURE_LOADER_BLP(); DESTRUCTOR ~TEXTURE_LOADER_BLP(); virtual BOOL Save(TEXTURE& Texture, CONST std::string& FileName, BUFFER& Buffer); virtual BOOL Load(TEXTURE& Texture, CONST std::string& FileName, BUFFER& Buffer); protected: static BOOL LoadCompressed(TEXTURE& Texture, BLP_HEADER& Header, BUFFER& Buffer); static BOOL LoadUncompressed(TEXTURE& Texture, BLP_HEADER& Header, BUFFER& Buffer); }; //+----------------------------------------------------------------------------- //| Global objects //+----------------------------------------------------------------------------- extern TEXTURE_LOADER_BLP TextureLoaderBlp;
[ "sihan6677@deb3bc48-0ee2-faf5-68d7-13371a682d83" ]
[ [ [ 1, 88 ] ] ]
3b99edec11c20ebd899b09f1decac9dd9a8ed28b
35231241243cb13bd3187983d224e827bb693df3
/branches/umptesting/MPReader/polygons.cpp
b676c67b6a0bab722c4ae5ca6dbf3c586f0566b6
[]
no_license
casaretto/cgpsmapper
b597aa2775cc112bf98732b182a9bc798c3dd967
76d90513514188ef82f4d869fc23781d6253f0ba
refs/heads/master
2021-05-15T01:42:47.532459
2011-06-25T23:16:34
2011-06-25T23:16:34
1,943,334
2
2
null
2019-06-11T00:26:40
2011-06-23T18:31:36
C++
WINDOWS-1250
C++
false
false
4,074
cpp
#include "polygons.h" void PolyProcess::detectMasterAndHoles(MPPoly* poly) { /* if( poly-> vector<TinyPolygon *>::iterator i; vector<TinyPolygon *>::iterator outer_element; if( Region.size() == 1 ) return; outer_element = Region.begin(); for( i = Region.begin(); i != Region.end(); i++ ) { (*i)->GetExtent(); if( i != outer_element ) { //sprawdzenie punktów if( IsHoleOf(outer_element,i) ) { //(*outer_element)->hole = false; (*i)->hole = true; } else { (*i)->hole = false; outer_element = i; } } } */ } /* bool ImportSHP::IsHoleOf(const vector<TinyPolygon*>::iterator& outer, const vector<TinyPolygon*>::iterator& inner) { vector<TinyCoordinates>::iterator t_cord; if( (*outer)->Area < 1.e-10f || (*outer)->Area < (*inner)->Area || (*inner)->MinNS < (*outer)->MinNS || (*inner)->MinWE < (*outer)->MinWE || (*inner)->MaxNS > (*outer)->MaxNS || (*inner)->MaxWE > (*outer)->MaxWE ) return false; for( t_cord = (*inner)->Nodes.begin(); t_cord < (*inner)->Nodes.end(); t_cord++ ) { const int iContains = PolygonContainsPt ( (*outer)->Nodes, (*t_cord) ); if (iContains < 0) return false; else if (iContains > 0) return true; } return false; } int ImportSHP::PolygonContainsPt ( const vector<TinyCoordinates>& _polygon, const TinyCoordinates& _p ) { size_t cc = 0; //x - we //y - ne int iLastTouchingLinkSide = 0; size_t cFirstPoint = 0; bool bFirstPointPassed = false; size_t cNodesWithEqualY = 0; const size_t cPoints = _polygon.size (); for (size_t cPoint = 1; cPoint != cFirstPoint + 1 || ! bFirstPointPassed; ++ cPoint) { // Get the first point of leg. size_t cPoint0 = cPoint - 1; while (cPoint0 >= cPoints) cPoint0 -= cPoints; const TinyCoordinates & p0 = _polygon [cPoint0]; // Get the second point of leg. while (cPoint >= cPoints) cPoint -= cPoints; const TinyCoordinates & p1 = _polygon [cPoint]; if (p0 == p1) { // Infinite loop protection. ++ cNodesWithEqualY; if (cNodesWithEqualY > cPoints) return -1; continue; } if ( (p0.ns < _p.ns && _p.ns < p1.ns) || (p0.ns > _p.ns && _p.ns > p1.ns) ) { // Leg crosses point's latitude. const double x = p0.we + (_p.ns - p0.ns)*(p1.we - p0.we)/(p1.ns - p0.ns); if (x == _p.we) // Leg crosses the point. return 0; else if (x < _p.we) // Leg passes under the point. ++ cc; bFirstPointPassed = true; } else if (p0.ns == _p.ns && p1.ns == _p.ns) { // Leg is entirely within point's latitude. if ( (p0.we <= _p.we && p1.we >= _p.we) || (p0.we >= _p.we && p1.we <= _p.we) ) // Leg crosses the point. return 0; if (cFirstPoint == cPoint - 1 && p1.we < _p.we) // There was no any link that crosses point's latitude or finishes at it yet. ++ cFirstPoint; // Infinite loop protection. assert (p0.ns == p1.ns); ++ cNodesWithEqualY; if (cNodesWithEqualY > cPoints) return -1; } else if (p0.ns != _p.ns && p1.ns == _p.ns) { // Leg finishes at point's latitude. if (p1.we == _p.we) // Leg crosses the point. return 0; else if (p1.we < _p.we) // Remember last touching leg side. iLastTouchingLinkSide = p0.ns < _p.ns ? -1 : 1; bFirstPointPassed = true; } else if (p0.ns == _p.ns && p1.ns != _p.ns) { // Leg starts at point's latitude. if (p0.we == _p.we) // Leg crosses the point. return 0; else if (p0.we < _p.we) if (iLastTouchingLinkSide == 0) // There was no touching leg yet. // We should loop through the polygon 'till this point. cFirstPoint = cPoint; else if ( iLastTouchingLinkSide == -1 && p1.ns > _p.ns || iLastTouchingLinkSide == 1 && p1.ns < _p.ns ) // This links with previous touching leg together cross point's latitude. ++ cc; } else // Leg does not cross point's latitude. bFirstPointPassed = true; } return (cc & 0x1) ? 1 : -1; } */
[ "marrud@ad713ecf-6e55-4363-b790-59b81426eeec" ]
[ [ [ 1, 148 ] ] ]
1b6d80fbf0d2e1d453c383c9e2e959035ad97dc1
b957e10ed5376dbe85c07bdef1f510f641984a1a
/md2.h
ca631ecdd865ac0188c461af0a92ab7c6ebc445d
[]
no_license
alexjshank/motors
063245c206df936a886f72a22f0f15c78e1129cb
7193b729466d8caece267f0b8ddbf16d99c13f8a
refs/heads/master
2016-09-10T15:47:20.906269
2009-11-04T18:41:21
2009-11-04T18:41:21
33,394,870
0
0
null
null
null
null
UTF-8
C++
false
false
4,997
h
/* these headers and some code adapted from http://tfc.duke.free.fr/old/models/md2.htm ... which i guess makes this whole project gpl 2... but this is just for personal use so theres no need to release anything or what not... right... babbling again*/ #include "library.h" #include "vector.h" #include <map> #include <string> using std::string; #ifndef __MD2__H__ #define __MD2__H__ // Md2 header struct Md2Header_t { int ident; // Magic number, "IDP2" int version; // Md2 format version, should be 8 int skinwidth; // Texture width int skinheight; // Texture height int framesize; // Size of a frame, in bytes int num_skins; // Number of skins int num_vertices; // Number of vertices per frame int num_st; // Number of texture coords int num_tris; // Number of triangles int num_glcmds; // Number of OpenGL commands int num_frames; // Number of frames int offset_skins; // offset to skin data int offset_st; // offset to texture coords int offset_tris; // offset to triangle data int offset_frames; // offset to frame data int offset_glcmds; // offset to OpenGL commands int offset_end; // offset to the end of the file }; // Skin data struct Md2Skin_t { char name[64]; // Texture's filename }; // Texture coords. struct Md2TexCoord_t { short s; short t; }; // Triangle data struct Md2Triangle_t { unsigned short vertex[3]; // Triangle's vertex indices unsigned short st[3]; // Texture coords. indices }; // Vertex data struct Md2Vertex_t { unsigned char v[3]; // Compressed vertex position unsigned char normalIndex; // Normal vector index }; // Frame data struct Md2Frame_t { // Destructor ~Md2Frame_t () { delete [] verts; } Vector scale; // Scale factors Vector translate; // Translation vector char name[16]; // Frame name Md2Vertex_t *verts; // Frames's vertex list }; // OpenGL command packet struct Md2Glcmd_t { float s; // S texture coord. float t; // T texture coord. int index; // Vertex index }; // Animation infos struct Md2Anim_t { int start; // first frame index int end; // last frame index }; ///////////////////////////////////////////////////////////////////////////// // // class Model_MD2 -- MD2 Model Data Class. // ///////////////////////////////////////////////////////////////////////////// class Model_MD2 : public LibraryObject { public: // Constructors/destructor Model_MD2() { type = 1; } Model_MD2 (const string &filename); ~Model_MD2 (); public: // Internal types typedef std::map<std::string, int> SkinMap; typedef std::map<std::string, Md2Anim_t> AnimMap; public: // Public interface bool loadTexture (const string &filename); void setTexture (const string &filename); void renderFrameImmediate (int frame); void drawModelItpImmediate (int frameA, int frameB, float interp); void renderFrameWithGLcmds (int frame); void drawModelItpWithGLcmds (int frameA, int frameB, float interp); void setScale (float scale) { _scale = scale; } // Accessors const SkinMap &skins () const { return _skinIds; } const AnimMap &anims () const { return _anims; } private: // Internal functions void setupAnimations (); private: // Member variables // Constants static Vector _kAnorms[162]; static int _kMd2Ident; static int _kMd2Version; // Model data Md2Header_t _header; Md2Skin_t *_skins; Md2TexCoord_t *_texCoords; Md2Triangle_t *_triangles; Md2Frame_t *_frames; int *_glcmds; float _scale; int _tex; SkinMap _skinIds; AnimMap _anims; }; class Md2Object { public: // Public internal types/enums enum Md2RenderMode { kDrawImmediate = 0, kDrawGLcmds, }; public: // Constructor/destructor Md2Object (); Md2Object (Model_MD2 *model); ~Md2Object (); public: // Public interface void drawObjectItp (bool animated, Md2RenderMode renderMode); void drawObjectFrame (float frame, Md2RenderMode renderMode); void animate (int startFrame, int endFrame, float percent); void animate (float percent); void setModel (Model_MD2 *model); void setScale (float scale) { _scale = scale; } void setAnim (const string &name); void setPosition (Vector pos) { position = pos; } void setRotation (Vector rot) { rotation = rot; } // Accessors const Model_MD2 *model () const { return _model; } float scale () const { return _scale; } const string &currentAnim () const { return _currentAnim; } private: // Member variables Model_MD2 *_model; Vector position,rotation; int _currFrame; int _nextFrame; float _interp; float _percent; float _scale; // Animation data Md2Anim_t *_animInfo; string _currentAnim; }; #endif
[ "alexjshank@0c9e2a0d-1447-0410-93de-f5a27bb8667b" ]
[ [ [ 1, 221 ] ] ]
a16e218310b7ec631fd23319de1ee241c06a81e9
b2155efef00dbb04ae7a23e749955f5ec47afb5a
/include/libOEMsg/OEMsgObjectAttach.h
f521ececf0f71d3728af33c478f4ea1e1db2c88c
[]
no_license
zjhlogo/originengine
00c0bd3c38a634b4c96394e3f8eece86f2fe8351
a35a83ed3f49f6aeeab5c3651ce12b5c5a43058f
refs/heads/master
2021-01-20T13:48:48.015940
2011-04-21T04:10:54
2011-04-21T04:10:54
32,371,356
1
0
null
null
null
null
UTF-8
C++
false
false
690
h
/*! * \file OEMsgObjectAttach.h * \date 10-24-2010 8:29:56 * * * \author zjhlogo ([email protected]) */ #ifndef __OEMSGOBJECTATTACH_H__ #define __OEMSGOBJECTATTACH_H__ #include "../libOEBase/IOEMsg.h" #include "../libOEBase/IOEObject.h" #include "../OECore/IOENode.h" class COEMsgObjectAttach : public IOEMsg { public: COEMsgObjectAttach(IOENode* pNode); COEMsgObjectAttach(COEDataBufferRead* pDBRead); virtual ~COEMsgObjectAttach(); IOENode* GetNode(); protected: virtual bool FromBuffer(COEDataBufferRead* pDBRead); virtual bool ToBuffer(COEDataBufferWrite* pDBWrite); private: IOENode* m_pNode; }; #endif // __OEMSGOBJECTATTACH_H__
[ "zjhlogo@fdcc8808-487c-11de-a4f5-9d9bc3506571" ]
[ [ [ 1, 33 ] ] ]
bf226623397c43e883ca0d01ecc248ec56338ccc
252e638cde99ab2aa84922a2e230511f8f0c84be
/mainlib/src/AboutForm.cpp
2a2f0e3fd4e7bb8669a0a5a5bf4ca250d91c87b3
[]
no_license
openlab-vn-ua/tour
abbd8be4f3f2fe4d787e9054385dea2f926f2287
d467a300bb31a0e82c54004e26e47f7139bd728d
refs/heads/master
2022-10-02T20:03:43.778821
2011-11-10T12:58:15
2011-11-10T12:58:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,842
cpp
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "StdTool.h" #include "AboutForm.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TTourAboutForm *TourAboutForm; //--------------------------------------------------------------------------- __fastcall TTourAboutForm::TTourAboutForm(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TTourAboutForm::CloseButtonClick(TObject *Sender) { FunctionArgUsedSkip(Sender); Close(); } //--------------------------------------------------------------------------- void __fastcall TTourAboutForm::FormCreate(TObject *Sender) { DWORD Handle; DWORD Size; FunctionArgUsedSkip(Sender); Size = GetFileVersionInfoSize(Application->ExeName.c_str(), &Handle); if (Size != 0) { char *BufferStrPtr; BufferStrPtr = (char*)GlobalAlloc(GMEM_FIXED, Size); if(GetFileVersionInfo(Application->ExeName.c_str(), Handle, Size, BufferStrPtr)!=0) { char *ValueBuffer; UINT ValueLength; VerQueryValue(BufferStrPtr, "\\VarFileInfo\\Translation", &(void*)ValueBuffer, &ValueLength); if ( ValueLength >= 4) { AnsiString CharSet; CharSet = IntToHex((int)MAKELONG(*(int*)(ValueBuffer + 2), *(int*) ValueBuffer), 8); /* if (VerQueryValue(BufferStrPtr, AnsiString("\\StringFileInfo\\" + CharSet +"\\ProductName").c_str(), &(void*)ValueBuffer, &Len)!=0) { ApplicationNameLabel->Caption = ApplicationNameLabel->Caption + ValueBuffer; } */ if (VerQueryValue(BufferStrPtr, AnsiString("\\StringFileInfo\\" + CharSet + "\\FileVersion").c_str(), &(void*)ValueBuffer, &ValueLength)!=0) { VersionLabel->Caption = VersionLabel->Caption + ValueBuffer; // VersionLabel->Caption=ValueBuffer; } /* if (VerQueryValue(BufferStrPtr, AnsiString("\\StringFileInfo\\" + CharSet + "\\LegalCopyright").c_str(), &(void*)ValueBuffer, &Len)!=0) { CopyrightLabel->Caption = CopyrightLabel->Caption + ValueBuffer; // Copyright->Caption=ValueBuffer; } if (VerQueryValue(BufferStrPtr, AnsiString("\\StringFileInfo\\" + CharSet + "\\CompanyName").c_str(), &(void*)ValueBuffer, &Len)!=0) { CompanyNameLabel->Caption = CompanyNameLabel->Caption + ValueBuffer; // Company->Caption=ValueBuffer; } */ } } GlobalFree(BufferStrPtr); } } //---------------------------------------------------------------------------
[ [ [ 1, 114 ] ] ]
801b6d097aa150f10caef7417646340568e531e7
05f4bd87bd001ab38701ff8a71d91b198ef1cb72
/TPTaller/TP3/src/FrenoTejo.cpp
2c1228dc37324c89b77ce49d04f8b0a4be0330d7
[]
no_license
oscarcp777/tpfontela
ef6828a57a0bc52dd7313cde8e55c3fd9ff78a12
2489442b81dab052cf87b6dedd33cbb51c2a0a04
refs/heads/master
2016-09-01T18:40:21.893393
2011-12-03T04:26:33
2011-12-03T04:26:33
35,110,434
0
0
null
null
null
null
UTF-8
C++
false
false
972
cpp
// FrenoTejo.cpp: implementation of the FrenoTejo class. // ////////////////////////////////////////////////////////////////////// #include "FrenoTejo.h" #include "Escenario.h" #include "Define.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// FrenoTejo::FrenoTejo() { } int getTipoBonus(){ return FRENO_TEJO; } int FrenoTejo::aplicar(){ Tejo* tejo = Escenario::obtenerInstancia()->getTejo(); int decUnTercioVelocidad=tejo->getVelocidad()- tejo->getVelocidadDefault()/3; int decMax = (1/3)*tejo->getVelocidadDefault(); if(decUnTercioVelocidad<decMax) //si ya se aplico, no se puede volver a aplicar el bonus return -1; tejo->setVelocidad(decUnTercioVelocidad); return 0; } FrenoTejo::~FrenoTejo() { if(DEBUG_DESTRUCTOR==1) std::cout<<" entro al destructor de FrenoTejo"<<endl; }
[ "rdubini@a1477896-89e5-11dd-84d8-5ff37064ad4b" ]
[ [ [ 1, 39 ] ] ]
e926bfb7752decf953cd43997eb6d69f01dbaea7
b2d46af9c6152323ce240374afc998c1574db71f
/cursovideojuegos/theflostiproject/3rdParty/boost/libs/date_time/test/testgeneric_period.cpp
2d7f98ae208cdf7a91176a50f4dd440044312194
[]
no_license
bugbit/cipsaoscar
601b4da0f0a647e71717ed35ee5c2f2d63c8a0f4
52aa8b4b67d48f59e46cb43527480f8b3552e96d
refs/heads/master
2021-01-10T21:31:18.653163
2011-09-28T16:39:12
2011-09-28T16:39:12
33,032,640
0
0
null
null
null
null
UTF-8
C++
false
false
6,662
cpp
/* Copyright (c) 2002,2003 CrystalClear Software, Inc. * Use, modification and distribution is subject to the * Boost Software License, Version 1.0. (See accompanying * file LICENSE-1.0 or http://www.boost.org/LICENSE-1.0) * Author: Bart Garst */ #include <iostream> #include "boost/date_time/period.hpp" #include "boost/date_time/testfrmwk.hpp" /*! duration_rep parameter for period requires a func unit() that * returns the smallest unit of measure for this type. This minimal * class fulfills that, and other, requirements */ template<class int_type> class duration_type { public: duration_type(int_type a = 0) : _val(a) {} static int_type unit() { return 1; } int_type get_rep() { return _val; } bool operator==(duration_type<int_type> rhs) { return _val == rhs._val; } bool operator<(duration_type<int_type> rhs) { return _val < rhs._val; } bool operator>(duration_type<int_type> rhs) { return _val > rhs._val; } private: int_type _val; }; //! To enable things like "cout << period.length()" template<class int_type> inline std::ostream& operator<<(std::ostream& os, duration_type<int_type> dt){ os << dt.get_rep(); return os; } //! this operator is needed because period adds a duration_rep to a point_rep template<class int_type> inline int_type operator+(int i, duration_type<int_type> dt){ return i + dt.get_rep(); } int main(){ using namespace boost::date_time; typedef period<int, duration_type<int> > a_period; /*** check all functions - normal periods ***/ a_period p1(1, duration_type<int>(9)); check("Different constructors", p1 == a_period(1, 10)); check("First", p1.begin() == 1); check("Last", p1.last() == 9); check("End", p1.end() == 10); check("Length", p1.length() == 9); check("is_null (not)", !p1.is_null()); { a_period p1(1, 10); check("First", p1.begin() == 1); check("Last", p1.last() == 9); check("End", p1.end() == 10); check("Length", p1.length() == 9); check("is_null (not)", !p1.is_null()); } a_period p2(5, 30); check("First", p2.begin() == 5); check("Last", p2.last() == 29); check("End", p2.end() == 30); check("Length", p2.length() == 25); check("is_null (not)", !p2.is_null()); a_period p3(35, 81); check("Operator ==", p1 == a_period(1,10)); check("Operator !=", p1 != p2); check("Operator <", p1 < p3); check("Operator >", p3 > p2); { a_period p(1,10); p.shift(5); check("Shift (right)", p == a_period(6,15)); p.shift(-15); check("Shift (left)", p == a_period(-9,0)); } check("Contains rep", p2.contains(20)); check("Contains rep (not)", !p2.contains(2)); check("Contains period", p1.contains(a_period(2,8))); check("Contains period (not)", !p1.contains(p3)); check("Intersects", p1.intersects(p2)); check("Intersects", p2.intersects(p1)); check("Adjacent", p1.is_adjacent(a_period(-5,1))); check("Adjacent", p1.is_adjacent(a_period(10,20))); check("Adjacent (not)", !p1.is_adjacent(p3)); check("Is before", p1.is_before(15)); check("Is after", p3.is_after(15)); check("Intersection", (p1.intersection(p2) == a_period(5,10))); check("Intersection", (p1.intersection(p3).is_null())); check("Merge", p1.merge(p2) == a_period(1,30) ); check("Merge", p1.merge(p3).is_null()); check("Span", p3.span(p1) == a_period(1, 81)); /*** zero length period ***/ // treat a zero length period as a point a_period zero_len(3,duration_type<int>(0)); check("Same beg & end != zero_length", a_period(1,1) != a_period(1, duration_type<int>(0))); check("2 point (zero length) == 1 point zero length", a_period(3,4) == zero_len); check("Is Before zero period", zero_len.is_before(5)); check("Is After zero period (not)", !zero_len.is_after(5)); check("Is Before zero period (not)", !zero_len.is_before(-5)); check("Is After zero period", zero_len.is_after(-5)); check("is_null (not)", !zero_len.is_null()); check("Contains rep (not)", !zero_len.contains(20)); check("Contains rep", zero_len.contains(3)); check("Contains period (not)", !zero_len.contains(a_period(5,8))); check("Contains period", p1.contains(zero_len)); check("Intersects", zero_len.intersects(p1)); check("Intersects", p1.intersects(zero_len)); check("Adjacent", zero_len.is_adjacent(a_period(-10,3))); check("Adjacent", zero_len.is_adjacent(a_period(4,10))); check("Adjacent", a_period(-10,3).is_adjacent(zero_len)); check("Adjacent", a_period(4,10).is_adjacent(zero_len)); check("Intersection", (zero_len.intersection(p1) == zero_len)); check("Span", zero_len.span(p2) == a_period(3,30)); /*** invalid period ***/ a_period null_per(5,1); check("Is Before invalid period (always false)", !null_per.is_before(7)); check("Is After invalid period (always false)", !null_per.is_after(7)); check("Is Before invalid period (always false)", !null_per.is_before(-5)); check("Is After invalid period (always false)", !null_per.is_after(-5)); check("is_null", null_per.is_null()); check("Contains rep larger (always false)", !null_per.contains(20)); check("Contains rep in-between (always false)", !null_per.contains(3)); check("Contains period (not)", !null_per.contains(a_period(7,9))); check("Contains period", p1.contains(null_per)); check("Intersects", null_per.intersects(p1)); check("Intersects", p1.intersects(null_per)); check("Adjacent", null_per.is_adjacent(a_period(-10,5))); check("Adjacent", null_per.is_adjacent(a_period(1,10))); // what should this next one do? //check("Intersection", (null_per.intersection(p1) == zero_len)); check("Span", null_per.span(p3) == a_period(5,81)); { std::cout << std::endl; a_period p1(0, duration_type<int>(-1)); check("First", p1.begin() == 0); check("Last", p1.last() == -1); check("End", p1.end() == 0); check("Length", p1.length() == -1); check("is_null", p1.is_null()); } { std::cout << std::endl; a_period p1(0, 0); check("First", p1.begin() == 0); check("Last", p1.last() == -1); check("End", p1.end() == 0); check("Length", p1.length() == -1); check("is_null", p1.is_null()); } { std::cout << std::endl; a_period p1(0, duration_type<int>(0)); check("First", p1.begin() == 0); check("Last", p1.last() == 0); check("End", p1.end() == 1); check("Length", p1.length() == 0); check("is_null (not)", !p1.is_null()); } return printTestStats(); }
[ "ohernandezba@71d53fa2-cca5-e1f2-4b5e-677cbd06613a" ]
[ [ [ 1, 187 ] ] ]
301ed9bd981423153d39117b0f061b2cebb69ec2
6bdb3508ed5a220c0d11193df174d8c215eb1fce
/Codes/Obsolete/UIMarkupTextLayout.cpp
e252ab020e5d7160d133cf3fd2a2e9ef44743e91
[]
no_license
halak/halak-plusplus
d09ba78640c36c42c30343fb10572c37197cfa46
fea02a5ae52c09ff9da1a491059082a34191cd64
refs/heads/master
2020-07-14T09:57:49.519431
2011-07-09T14:48:07
2011-07-09T14:48:07
66,716,624
0
0
null
null
null
null
UHC
C++
false
false
17,479
cpp
#include <Halak/PCH.h> #include <Halak/UIMarkupTextLayout.h> #include <Halak/Assert.h> #include <Halak/DrawingContext.h> #include <Halak/Font.h> #include <Halak/FontString.h> #include <Halak/Math.h> #include <Halak/NumericLimits.h> #include <Halak/SpriteRenderer.h> #include <Halak/UIMarkupText.h> #include <Halak/Internal/Glyph.h> namespace Halak { UIMarkupTextLayout::UIMarkupTextLayout() : markupText(nullptr), align(LeftMiddlePoint), boundary(NumericLimits::MaxFloat), font(), numberOfContents(0), displayContentLength(NumericLimits::FloatNaN), layoutChanged(true), size(Vector2::Zero) { } UIMarkupTextLayout::UIMarkupTextLayout(const String& text) : markupText(text.IsEmpty() == false ? new UIMarkupText(text) : nullptr), align(LeftMiddlePoint), boundary(NumericLimits::MaxFloat), font(), numberOfContents(0), displayContentLength(NumericLimits::FloatNaN), layoutChanged(true), size(Vector2::Zero) { } UIMarkupTextLayout::UIMarkupTextLayout(const UIMarkupTextLayout& original) : markupText(original.markupText ? new UIMarkupText(*original.markupText) : nullptr), align(original.align), boundary(original.boundary), font(original.font), numberOfContents(original.numberOfContents), displayContentLength(original.displayContentLength), layoutChanged(original.layoutChanged), size(original.size) { Copy(lines, original.lines); } UIMarkupTextLayout::~UIMarkupTextLayout() { delete markupText; DeleteAllLines(); } void UIMarkupTextLayout::Draw(DrawingContext& context) { if (layoutChanged) { layoutChanged = false; UpdateLayout(); } SpriteRenderer* renderer = context.GetSpriteRenderer(); float remainingLength = GetDisplayContentLength(); for (LineCollection::iterator itLine = lines.begin(); itLine != lines.end() && remainingLength > 0.0f; itLine++) { Line* line = (*itLine); for (BlockCollection::iterator it = line->Blocks.begin(); it != line->Blocks.end() && remainingLength > 0.0f; it++) { (*it)->Draw(renderer, remainingLength); } } } const String& UIMarkupTextLayout::GetText() const { if (markupText) return markupText->GetOriginalText(); else { static const String EmptyString; return EmptyString; } } void UIMarkupTextLayout::SetText(const String& value) { if (GetText() != value) { UIMarkupText* deletingText = nullptr; std::swap(deletingText, markupText); delete deletingText; if (value.IsEmpty() == false) markupText = new UIMarkupText(value); layoutChanged = true; } } const UIMarkupText& UIMarkupTextLayout::GetMarkupText() const { if (markupText) return *markupText; else return UIMarkupText::Empty; } Vector2 UIMarkupTextLayout::GetSize() { if (layoutChanged) { layoutChanged = true; UpdateLayout(); } return size; } UIMarkupTextLayout::Alignment UIMarkupTextLayout::GetAlign() const { return align; } void UIMarkupTextLayout::SetAlign(Alignment value) { if (GetAlign() != value) { align = value; layoutChanged = true; } } float UIMarkupTextLayout::GetBoundary() const { return boundary; } void UIMarkupTextLayout::SetBoundary(float value) { value = Math::Max(value, 0.0f); if (GetBoundary() != value) { boundary = value; layoutChanged = true; } } FontPtr UIMarkupTextLayout::GetFont() const { return font; } void UIMarkupTextLayout::SetFont(FontPtr value) { if (GetFont() != value) { font = value; layoutChanged = true; } } int UIMarkupTextLayout::GetNumberOfContents() { if (layoutChanged) { layoutChanged = true; UpdateLayout(); } return numberOfContents; } float UIMarkupTextLayout::GetDisplayContentLength() { if (displayContentLength != displayContentLength) // is NaN return static_cast<float>(GetNumberOfContents()); else return displayContentLength; } void UIMarkupTextLayout::SetDisplayContentLength(float value) { displayContentLength = value; } UIMarkupTextLayout& UIMarkupTextLayout::operator = (const UIMarkupTextLayout& original) { if (markupText) { UIMarkupText* deletingText = nullptr; std::swap(deletingText, markupText); delete deletingText; } DeleteAllLines(); if (original.markupText) markupText = new UIMarkupText(*original.markupText); else markupText = nullptr; align = original.align; boundary = original.boundary; font = original.font; numberOfContents = original.numberOfContents; displayContentLength = original.displayContentLength; layoutChanged = original.layoutChanged; Copy(lines, original.lines); size = original.size; return *this; } bool UIMarkupTextLayout::operator == (const UIMarkupTextLayout& right) const { if ((markupText != nullptr && right.markupText == nullptr) || (markupText == nullptr && right.markupText != nullptr) || (markupText && right.markupText && (*markupText) != (*right.markupText))) return false; return align == right.align && boundary == right.boundary && font == right.font && displayContentLength == right.displayContentLength; } bool UIMarkupTextLayout::operator != (const UIMarkupTextLayout& right) const { return !operator == (right); } void UIMarkupTextLayout::UpdateLayout() { DeleteAllLines(); if (markupText == nullptr || font == nullptr) return; numberOfContents = 0; LayoutContext context(this); const UIMarkupText::PhraseCollection& phrases = GetMarkupText().GetPhrases(); for (UIMarkupText::PhraseCollection::const_iterator it = phrases.begin(); it != phrases.end(); it++) { switch ((*it)->GetType()) { case UIMarkupText::TextPhraseType: { const UIMarkupText::TextPhrase* item = static_cast<const UIMarkupText::TextPhrase*>(*it); const String& originalText = GetMarkupText().GetOriginalText(); TextBlock* textBlock = new TextBlock(originalText.Substring(item->GetIndex(), item->GetLength()), context.GetFont()); numberOfContents += textBlock->GetNumberOfGlyphs(); context.Push(textBlock); } break; case UIMarkupText::NewLinePhraseType: context.Wrap(); break; case UIMarkupText::ColorPhraseType: { const UIMarkupText::ColorPhrase* item = static_cast<const UIMarkupText::ColorPhrase*>(*it); Color color = Color(255, 255, 255, 255); if (item->HasColor()) color = item->GetColor(); else color = context.GetFont()->GetColor(); if (context.GetFont()->GetColor() != color) { FontPtr newFont = FontPtr(new Font(*context.GetFont())); newFont->SetColor(color); context.SetFont(newFont); } } break; case UIMarkupText::ContentPhraseType: { const UIMarkupText::ContentPhrase* item = static_cast<const UIMarkupText::ContentPhrase*>(*it); } break; } } size = Vector2::Zero; for (LineCollection::const_iterator it = lines.begin(); it != lines.end(); it++) { size.X = Math::Max(size.X, (*it)->Size.X); size.Y += (*it)->Size.Y; } } void UIMarkupTextLayout::DeleteAllLines() { LineCollection deletingLines; deletingLines.swap(lines); for (LineCollection::iterator it = deletingLines.begin(); it != deletingLines.end(); it++) delete (*it); } void UIMarkupTextLayout::Copy(LineCollection& target, const LineCollection& original) { HKAssert(target.empty()); target.reserve(original.size()); for (LineCollection::const_iterator it = original.begin(); it != original.end(); it++) target.push_back(new Line(*(*it))); } //////////////////////////////////////////////////////////////////////////////////////////////////// UIMarkupTextLayout::Block::~Block() { } UIMarkupTextLayout::Block* UIMarkupTextLayout::Block::Divide(float /*cutWidth*/) { return nullptr; } //////////////////////////////////////////////////////////////////////////////////////////////////// UIMarkupTextLayout::TextBlock::TextBlock(const String& text, FontPtr font) : text(text), font(font), fontString(new FontString(font, text)) { Size = font->Measure(*fontString); } UIMarkupTextLayout::TextBlock::~TextBlock() { delete fontString; } UIMarkupTextLayout::TextBlock* UIMarkupTextLayout::TextBlock::Clone() const { return new TextBlock(*this); } void UIMarkupTextLayout::TextBlock::Draw(SpriteRenderer* renderer, float& outLength) { renderer->DrawString(Position, *fontString, outLength, NumericLimits::MaxFloat); outLength -= static_cast<float>(GetNumberOfGlyphs()); } UIMarkupTextLayout::TextBlock* UIMarkupTextLayout::TextBlock::Divide(float cutWidth) { float width = 0.0f; const FontString::GlyphCollection& glyphs = fontString->GetRegularGlyphs(); for (FontString::GlyphCollection::size_type i = 0; i < glyphs.size(); i++) { width += font->GetSpacing() * glyphs[i]->GetAdvance().X; if (width >= cutWidth) { // 나눌필요가 없으면 그냥 바로 nullptr을 반환합니다. if (i == 0) return nullptr; const int index = fontString->ConvertToOriginalIndex(i); // 넘어간 순간 그 문자부터 나눕니다. TextBlock* textBlock = new TextBlock(fontString->GetOriginal().Substring(index), font); // 기존 Block을 축소시킵니다. text = text.Substring(0, index); delete fontString; fontString = new FontString(font, text); Size = font->Measure(*fontString); return textBlock; } } return nullptr; } int UIMarkupTextLayout::TextBlock::GetNumberOfGlyphs() const { return static_cast<int>(fontString->GetRegularGlyphs().size()); } //////////////////////////////////////////////////////////////////////////////////////////////////// UIMarkupTextLayout::Line::Line() : Size(Vector2::Zero) { } UIMarkupTextLayout::Line::Line(const Line& original) : Size(original.Size) { Blocks.reserve(original.Blocks.size()); for (BlockCollection::const_iterator it = original.Blocks.begin(); it != original.Blocks.end(); it++) Blocks.push_back((*it)->Clone()); } UIMarkupTextLayout::Line::~Line() { BlockCollection deletingBlocks; deletingBlocks.swap(Blocks); for (BlockCollection::iterator it = deletingBlocks.begin(); it != deletingBlocks.end(); it++) delete (*it); } void UIMarkupTextLayout::Line::UpdateSize(float defaultHeight) { Vector2 size = Vector2(0.0f, defaultHeight); for (BlockCollection::const_iterator it = Blocks.begin(); it != Blocks.end(); it++) { const Block* item = (*it); size.X += item->Offset.X + item->Size.X; size.Y = Math::Max(size.Y, item->Offset.Y + item->Size.Y); } Size = size; } void UIMarkupTextLayout::Line::AdjustBlocks(float y, float boundary, Alignment align) { // ASSERT : this->Size는 정상. // ASSERT : 각 Block들의 Size는 정상. // 가로축을 정렬합니다. float xAxis = 0.0f; switch (align) { case LeftTopPoint: case LeftBottomPoint: case LeftMiddlePoint: xAxis = 0.0f; break; case CenterTopPoint: case CenterBottomPoint: case CenterPoint: xAxis = (boundary - Size.X) * 0.5f; break; case RightTopPoint: case RightBottomPoint: case RightMiddlePoint: xAxis = boundary - Size.X; break; } // 세로축을 정렬합니다. switch (align) { case LeftTopPoint: case RightTopPoint: case CenterTopPoint: { const float yAxis = y; for (BlockCollection::iterator it = Blocks.begin(); it != Blocks.end(); it++) (*it)->Position.Y = yAxis; } break; case LeftMiddlePoint: case RightMiddlePoint: case CenterPoint: { const float yAxis = y + (Size.Y * 0.5f); for (BlockCollection::iterator it = Blocks.begin(); it != Blocks.end(); it++) (*it)->Position.Y = yAxis - ((*it)->Size.Y * 0.5f); } break; case LeftBottomPoint: case RightBottomPoint: case CenterBottomPoint: { const float yAxis = y + Size.Y; for (BlockCollection::iterator it = Blocks.begin(); it != Blocks.end(); it++) (*it)->Position.Y = yAxis - (*it)->Size.Y; } break; } for (BlockCollection::iterator it = Blocks.begin(); it != Blocks.end(); it++) { (*it)->Position.X = xAxis; xAxis += (*it)->Size.X; } } //////////////////////////////////////////////////////////////////////////////////////////////////// UIMarkupTextLayout::LayoutContext::LayoutContext(UIMarkupTextLayout* layout) : layout(layout), line(nullptr), position(Vector2::Zero), font(layout->GetFont()) { Wrap(); } UIMarkupTextLayout::LayoutContext::~LayoutContext() { line->UpdateSize(font->GetLineHeight()); line->AdjustBlocks(position.Y, layout->GetBoundary(), layout->GetAlign()); } void UIMarkupTextLayout::LayoutContext::Push(Block* item) { // ASSERT : item->Offset, item->Size는 정상. Block* nextLineItem = nullptr; if (position.X + item->Offset.X + item->Size.X > layout->GetBoundary()) { nextLineItem = item->Divide(layout->GetBoundary() - position.X); if (nextLineItem == nullptr) Wrap(); } line->Blocks.push_back(item); position.X += item->Offset.X + item->Size.X; if (nextLineItem) { Wrap(); Push(nextLineItem); } } void UIMarkupTextLayout::LayoutContext::Wrap() { if (line) { line->UpdateSize(font->GetLineHeight()); line->AdjustBlocks(position.Y, layout->GetBoundary(), layout->GetAlign()); position.X = 0.0f; position.Y += line->Size.Y; } line = new Line(); layout->lines.push_back(line); } FontPtr UIMarkupTextLayout::LayoutContext::GetFont() const { return font; } void UIMarkupTextLayout::LayoutContext::SetFont(FontPtr value) { font = value; } }
[ [ [ 1, 553 ] ] ]
023cafa540f09103f96c71d7354fe6e37e122216
c5ecda551cefa7aaa54b787850b55a2d8fd12387
/src/SpeedMeter.cpp
e98c1f47adfe9dae1cf0340faab61020b056e38b
[]
no_license
firespeed79/easymule
b2520bfc44977c4e0643064bbc7211c0ce30cf66
3f890fa7ed2526c782cfcfabb5aac08c1e70e033
refs/heads/master
2021-05-28T20:52:15.983758
2007-12-05T09:41:56
2007-12-05T09:41:56
null
0
0
null
null
null
null
GB18030
C++
false
false
3,898
cpp
// SpeedMeter.cpp : 实现文件 // #include "stdafx.h" #include "SpeedMeter.h" #include ".\speedmeter.h" #include "UtilUI.h" #define MAINCOLORVALUE 224 // CSpeedMeter IMPLEMENT_DYNAMIC(CSpeedMeter, CWnd) CSpeedMeter::CSpeedMeter() { m_nMin = 0; m_nMax = 100; m_nStep = 1; m_bInit = true; m_crDownload = RGB(27, 171, 89);//绿色 m_crUpload = RGB(232, 136, 29);//红色//RGB(0, 224, 0); m_pOldBMP = NULL; } CSpeedMeter::~CSpeedMeter() { if(m_pOldBMP) { m_MemDC.SelectObject(m_pOldBMP); } } BEGIN_MESSAGE_MAP(CSpeedMeter, CWnd) ON_WM_PAINT() ON_WM_SIZE() END_MESSAGE_MAP() // CSpeedMeter 消息处理程序 void CSpeedMeter::AddValues(UINT uUpdatarate, UINT uDownDatarate, bool bRedraw) { m_UpdataList.AddTail(uUpdatarate); m_DownloadList.AddTail(uDownDatarate); if(GetSafeHwnd()) { AddValues2Graph(uUpdatarate, uDownDatarate); if(bRedraw) { Invalidate(); } } } void CSpeedMeter::AddValues2Graph(UINT uUpdatarate, UINT uDowndatarate) { if(m_MemDC.GetSafeHdc()) { CRect rClient; GetClientRect(&rClient); int iWidth = rClient.Width(); int iHeight = rClient.Height(); int iNewWidth = iWidth - m_nStep; if(uUpdatarate > m_nMax) { uUpdatarate = m_nMax; //设置上限,防止过大 } if(uDowndatarate > m_nMax) { uDowndatarate = m_nMax; //设置上限,防止过大 } double dUpdatarate = (double)iHeight * uUpdatarate / m_nMax; double dDowndatarate = (double)iHeight * uDowndatarate / m_nMax; //四舍五入,这里是五入 UINT nRndUpdatarate = (UINT)dUpdatarate; if(dUpdatarate - nRndUpdatarate >= 0.5) { nRndUpdatarate++; } //四舍五入,这里是五入 UINT nRndDowndatarate = (UINT)dDowndatarate; if(dDowndatarate - nRndDowndatarate >= 0.5) { nRndDowndatarate++; } m_MemDC.BitBlt(0, 0, iNewWidth, iHeight, &m_MemDC, m_nStep, 0, SRCCOPY); CRect rect(iNewWidth, 0, iNewWidth + m_nStep, iHeight); DrawParentBk(GetSafeHwnd(), m_MemDC.GetSafeHdc(), &rect); m_MemDC.SetPixel(iWidth - 1, iHeight - nRndUpdatarate, m_crUpload); m_MemDC.SetPixel(iWidth - 1, iHeight - nRndDowndatarate, m_crDownload); while(m_UpdataList.GetCount() > rClient.Width()) { m_UpdataList.RemoveHead(); m_DownloadList.RemoveHead(); } } } void CSpeedMeter::SetRange(UINT nMin, UINT nMax, bool bDelete) { m_nMin = nMin; m_nMax = nMax; ResetGraph(bDelete); } void CSpeedMeter::GetRange(UINT& nMax, UINT& nMin) { nMax = m_nMax; nMin = m_nMin; } void CSpeedMeter::ResetGraph(bool bDelete) { if(bDelete) { m_UpdataList.RemoveAll(); m_DownloadList.RemoveAll(); } m_bInit = true; Invalidate(); } void CSpeedMeter::OnPaint() { CPaintDC dc(this); CRect rtClient; GetClientRect(&rtClient); if(m_bInit) { m_bInit = false; ReCreateGraph(&dc); } dc.BitBlt(0, 0, rtClient.Width(), rtClient.Height(), &m_MemDC, 0,0, SRCCOPY); } void CSpeedMeter::ReCreateGraph(CDC* pDC) { CRect rClient; GetClientRect(&rClient); if(m_pOldBMP) { m_MemDC.SelectObject(m_pOldBMP); } if(m_MemBMP.GetSafeHandle()) { m_MemBMP.DeleteObject(); } if(m_MemDC.GetSafeHdc()) { m_MemDC.DeleteDC(); } m_MemDC.CreateCompatibleDC(pDC); m_MemBMP.CreateCompatibleBitmap(pDC, rClient.Width(), rClient.Height()); m_pOldBMP = m_MemDC.SelectObject(&m_MemBMP); DrawParentBk(GetSafeHwnd(), m_MemDC.GetSafeHdc()); POSITION pos1 = m_UpdataList.GetHeadPosition(); POSITION pos2 = m_DownloadList.GetHeadPosition(); while(pos1 != NULL && pos2 != NULL) { AddValues2Graph(m_UpdataList.GetNext(pos1), m_DownloadList.GetNext(pos2)); } } void CSpeedMeter::OnSize(UINT nType, int cx, int cy) { CWnd::OnSize(nType, cx, cy); m_bInit = true; Invalidate(); }
[ "LanceFong@4a627187-453b-0410-a94d-992500ef832d" ]
[ [ [ 1, 199 ] ] ]
c2ec6e5c921ae70d689bf02c9b615d05f43233d1
823e34ee3931091af33fbac28b5c5683a39278e4
/NetworkTalkClient/NetworkTalkClientDlg.h
857fadf8dad8f80c0d8acccceb5934ea73039126
[]
no_license
tangooricha/tangoorichas-design-for-graduation
aefdd0fdf0e8786308c22311f2598ad62b3f5be8
cf227651b9baa0deb5748a678553b145a3ce6803
refs/heads/master
2020-06-06T17:48:37.691814
2010-04-14T07:22:23
2010-04-14T07:22:23
34,887,842
0
0
null
null
null
null
UTF-8
C++
false
false
1,533
h
// NetworkTalkClientDlg.h : header file // #if !defined(AFX_NETWORKTALKCLIENTDLG_H__FDD80709_1857_44BB_9B03_84FA9A797522__INCLUDED_) #define AFX_NETWORKTALKCLIENTDLG_H__FDD80709_1857_44BB_9B03_84FA9A797522__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #define WM_RECVDATA WM_USER+1 ///////////////////////////////////////////////////////////////////////////// // CNetworkTalkClientDlg dialog class CNetworkTalkClientDlg : public CDialog { // Construction public: CNetworkTalkClientDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CNetworkTalkClientDlg) enum { IDD = IDD_NETWORKTALKCLIENT_DIALOG }; CString m_serverIPAddress; CString m_recvText; CString m_sendText; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CNetworkTalkClientDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: HICON m_hIcon; // Generated message map functions //{{AFX_MSG(CNetworkTalkClientDlg) virtual BOOL OnInitDialog(); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); afx_msg void OnBtnSend(); //}}AFX_MSG afx_msg LRESULT OnRecvData(WPARAM,LPARAM); DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_NETWORKTALKCLIENTDLG_H__FDD80709_1857_44BB_9B03_84FA9A797522__INCLUDED_)
[ "[email protected]@91cf4698-544a-0410-9e3e-f171e2291419" ]
[ [ [ 1, 54 ] ] ]
f7756c207a4546ba1c59fbed032d51eb134e65cd
3a43abdec058da0fd3543ae682b5d0968f38b2f0
/mikrolab5/stdafx.cpp
148d9f85eb818734dbe91b634c38cc1a68e2366a
[]
no_license
thebruno/bruno-ja-project
bb4a20aeef47baf044cca1f753209bb05eb723c8
0629bd6349e3b01fc2727fd54ed0ed3ee3ec960b
refs/heads/master
2016-09-06T01:11:04.357017
2008-03-18T23:59:07
2008-03-18T23:59:07
32,205,777
0
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
// stdafx.cpp : source file that includes just the standard includes // mikrolab5.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "konrad.balys@c17f3e5a-c547-0410-a969-25eb5a120115" ]
[ [ [ 1, 8 ] ] ]
a28b4671901c10b9b605f5f59a954463478947d3
5ed707de9f3de6044543886ea91bde39879bfae6
/ASBasketball/ASFUtil/Source/ASBasketballUtilManager.cpp
fe010f8d6e5dc9a7d51250fcfa612ee741919718
[]
no_license
grtvd/asifantasysports
9e472632bedeec0f2d734aa798b7ff00148e7f19
76df32c77c76a76078152c77e582faa097f127a8
refs/heads/master
2020-03-19T02:25:23.901618
1999-12-31T16:00:00
2018-05-31T19:48:19
135,627,290
0
0
null
null
null
null
UTF-8
C++
false
false
4,308
cpp
/* ASBasketballUtilManager.cpp */ /******************************************************************************/ /******************************************************************************/ #include "CBldVCL.h" #pragma hdrstop #include "CommMisc.h" #include "ASBasketballStatFileLoader.h" #include "ASBasketballStatSummaryBuilder.h" #include "ASBasketballDraftRanking.h" #include "ASBasketballUtilManager.h" namespace asbasketball { /******************************************************************************/ /* Choices */ const int chc_LoadOffensiveStats = 1; const int chc_CalculateSummaryStats = 2; const int chc_CreateDefaultDraftRanking = 3; const int chc_ResetTeamDraftRanking = 4; const int chc_CreateCompAccounts = 5; const int chc_AddParticToLeague = 6; /* Comp Account Info */ static CompAccountInfo gCompAccountInfo[] = { // Email Manager, Region Team { NULL, "Popovich", "San Antonio", "Spurs" }, { NULL, "Van Gundy", "New York", "Knicks" }, { NULL, "Bird", "Indiana", "Pacers" }, { NULL, "Dunleavy", "Portland", "Trail Blazers" }, { NULL, "Brown", "Philadelphia", "76ers" }, { NULL, "Jackson", "Los Angeles", "Lakers" }, { NULL, "Wilkens", "Altanta", "Hawks" }, { NULL, "Sloan", "Utah", "Jazz" }, { NULL, "Riley", "Miami", "Heat" }, { NULL, "Rivers", "Orlando", "Magic" }, }; /******************************************************************************/ /******************************************************************************/ void ASBasketballUtilManager::promptChoices() { printf("1. Load Offensive Stats\n"); printf("2. Calculate Season Summary Stats\n"); printf("3. Create Default Draft Ranking\n"); printf("4. Reset Team Draft Ranking\n"); printf("5. Create Comp Accounts\n"); printf("6. Add Partic To League\n"); } /******************************************************************************/ bool ASBasketballUtilManager::doesChoiceNeedTransaction(int choice) { if(choice == chc_CreateCompAccounts) return(false); return(ASFantasyUtilManager::doesChoiceNeedTransaction(choice)); } /******************************************************************************/ void ASBasketballUtilManager::doChoice(int choice) { if(choice == chc_LoadOffensiveStats) { TStatPeriod statPeriod = promptStatPeriod(); bool addNewPlayers = promptYesNo("Should unknown players be added (Y/N)?"); StatFileLoaderPtr loader = OffGameStatFileLoader::newInstance(DirSpec(),TDateTime(), statPeriod,addNewPlayers); loadStat(loader); } else if(choice == chc_CalculateSummaryStats) { ASBasketballStatSummaryBuilder builder; TStatPeriod statPeriod = promptStatPeriod(); if(statPeriod == stp_SeasonToDate) { tag::TDate tAsOfDate = promptDate("Enter 'as of' date (m/d/y): "); builder.standAloneBuildAllPlayersForThisSeason( ConvertTDatetoTDateTime(tAsOfDate)); } else builder.standAloneBuildAllPlayersForStatPeriod(statPeriod); } else if(choice == chc_CreateDefaultDraftRanking) { ASBasketballDraftRankingBuilder builder; builder.build(); } else if(choice == chc_ResetTeamDraftRanking) { long tempLong = promptInteger("Enter TeamID of Draft Ranking to Reset (0=cancel): "); if(tempLong != 0) ASFantasyDraftRankingReseter::reset(tempLong); } else if(choice == chc_CreateCompAccounts) { createCompAccounts(); } else if(choice == chc_AddParticToLeague) { addParticToLeague(); } else printf("Invalid Entry!\n"); } /******************************************************************************/ int ASBasketballUtilManager::getNumCompAccountInfo() { return(sizeof(gCompAccountInfo) / sizeof(*gCompAccountInfo)); } /******************************************************************************/ const CompAccountInfo* ASBasketballUtilManager::getCompAccountInfo(int offset) { return(&gCompAccountInfo[offset]); } /******************************************************************************/ }; //namespace asbasketball /******************************************************************************/ /******************************************************************************/
[ [ [ 1, 143 ] ] ]
7634d951f7364b23e5d7a82eaf7c0485142a06b8
6e563096253fe45a51956dde69e96c73c5ed3c18
/Sockets/HttpdCookies.cpp
56dcf53cbc28dc651e3d89bb96f35767001bb7de
[]
no_license
15831944/phoebemail
0931b76a5c52324669f902176c8477e3bd69f9b1
e10140c36153aa00d0251f94bde576c16cab61bd
refs/heads/master
2023-03-16T00:47:40.484758
2010-10-11T02:31:02
2010-10-11T02:31:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,717
cpp
/** \file HttpdCookies.cpp */ /* Copyright (C) 2003-2009 Anders Hedstrom This library is made available under the terms of the GNU GPL, with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. If you would like to use this library in a closed-source application, a separate license agreement is available. For information about the closed-source license agreement for the C++ sockets library, please visit http://www.alhem.net/Sockets/license.html and/or email [email protected]. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #ifdef _MSC_VER #pragma warning(disable:4786) #endif #include "Parse.h" #include "HTTPSocket.h" #include "HttpdCookies.h" #ifdef SOCKETS_NAMESPACE namespace SOCKETS_NAMESPACE { #endif #ifdef _DEBUG #define DEB(x) x; fflush(stderr); #else #define DEB(x) #endif HttpdCookies::HttpdCookies() { } HttpdCookies::HttpdCookies(const std::string& s) { Parse *pa = new Parse(s,";"); std::string slask = pa -> getword(); while (slask.size()) { Parse *pa2 = new Parse(slask,"="); std::string name = pa2 -> getword(); std::string value = pa2 -> getword(); delete pa2; m_cookies.push_back(std::pair<std::string, std::string>(name, value)); // slask = pa -> getword(); } delete pa; } void HttpdCookies::add(const std::string& s) { Parse *pa = new Parse(s,";"); DEB(fprintf(stderr, "Parse cookie: %s\n", s.c_str());) std::string slask = pa -> getword(); while (slask.size()) { Parse *pa2 = new Parse(slask,"="); std::string name = pa2 -> getword(); std::string value = pa2 -> getword(); delete pa2; m_cookies.push_back(std::pair<std::string, std::string>(name, value)); // slask = pa -> getword(); } delete pa; } HttpdCookies::~HttpdCookies() { } bool HttpdCookies::getvalue(const std::string& name,std::string& buffer) const { for (cookie_v::const_iterator it = m_cookies.begin(); it != m_cookies.end(); ++it) { const std::pair<std::string, std::string>& ref = *it; if (!strcasecmp(ref.first.c_str(),name.c_str())) { buffer = ref.second; return true; } } buffer = ""; return false; } void HttpdCookies::replacevalue(const std::string& name,const std::string& value) { for (cookie_v::iterator it = m_cookies.begin(); it != m_cookies.end(); ++it) { std::pair<std::string, std::string>& ref = *it; if (!strcasecmp(ref.first.c_str(),name.c_str())) { ref.second = value; return; } } m_cookies.push_back(std::pair<std::string, std::string>(name, value)); } void HttpdCookies::replacevalue(const std::string& name,long l) { replacevalue(name, Utility::l2string(l)); } void HttpdCookies::replacevalue(const std::string& name,int i) { replacevalue(name, Utility::l2string(i)); } size_t HttpdCookies::getlength(const std::string& name) const { for (cookie_v::const_iterator it = m_cookies.begin(); it != m_cookies.end(); ++it) { const std::pair<std::string, std::string>& ref = *it; if (!strcasecmp(ref.first.c_str(),name.c_str())) { return ref.second.size(); } } return 0; } void HttpdCookies::setcookie(HTTPSocket *sock, const std::string& domain, const std::string& path, const std::string& name, const std::string& value) { char *str = new char[name.size() + value.size() + domain.size() + path.size() + 100]; // set-cookie response if (domain.size()) { sprintf(str, "%s=%s; domain=%s; path=%s; expires=%s", name.c_str(), value.c_str(), domain.c_str(), path.c_str(), expiredatetime().c_str()); } else { sprintf(str, "%s=%s; path=%s; expires=%s", name.c_str(), value.c_str(), path.c_str(), expiredatetime().c_str()); } sock -> AddResponseHeader("Set-cookie", str); delete[] str; replacevalue(name, value); } void HttpdCookies::setcookie(HTTPSocket *sock, const std::string& domain, const std::string& path, const std::string& name, long value) { char *str = new char[name.size() + domain.size() + path.size() + 100]; char dt[80]; // set-cookie response if (domain.size()) { sprintf(str, "%s=%ld; domain=%s; path=%s; expires=%s", name.c_str(), value, domain.c_str(), path.c_str(), expiredatetime().c_str()); } else { sprintf(str, "%s=%ld; path=%s; expires=%s", name.c_str(), value, path.c_str(), expiredatetime().c_str()); } sock -> AddResponseHeader("Set-cookie", str); delete[] str; sprintf(dt, "%ld", value); replacevalue(name, dt); } void HttpdCookies::setcookie(HTTPSocket *sock, const std::string& domain, const std::string& path, const std::string& name, int value) { char *str = new char[name.size() + domain.size() + path.size() + 100]; char dt[80]; // set-cookie response if (domain.size()) { sprintf(str, "%s=%d; domain=%s; path=%s; expires=%s", name.c_str(), value, domain.c_str(), path.c_str(), expiredatetime().c_str()); } else { sprintf(str, "%s=%d; path=%s; expires=%s", name.c_str(), value, path.c_str(), expiredatetime().c_str()); } sock -> AddResponseHeader("Set-cookie", str); delete[] str; sprintf(dt, "%d", value); replacevalue(name, dt); } const std::string& HttpdCookies::expiredatetime() const { time_t t = time(NULL); struct tm tp; #ifdef _WIN32 memcpy(&tp, gmtime(&t), sizeof(tp)); #else gmtime_r(&t, &tp); #endif const char *days[7] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; const char *months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; char dt[100]; sprintf(dt, "%s, %02d-%s-%04d %02d:%02d:%02d GMT", days[tp.tm_wday], tp.tm_mday, months[tp.tm_mon], tp.tm_year + 1910, tp.tm_hour, tp.tm_min, tp.tm_sec); m_date = dt; return m_date; } void HttpdCookies::Reset() { while (!m_cookies.empty()) { m_cookies.erase(m_cookies.begin()); } m_date = ""; } #ifdef SOCKETS_NAMESPACE } #endif
[ "guoqiao@a83c37f4-16cc-5f24-7598-dca3a346d5dd" ]
[ [ [ 1, 271 ] ] ]
e494c6fd18e85df9e5b1ab4059c71eefec843919
47f2ee8c2ec135b02b960387a0cb42126e5028ec
/PlasmaGL/src/plglSpawnPtMgr.h
4c4a96fefdf2aa87d9b60d7d0d1c510138e8e38f
[]
no_license
nsundin/PlasmaViewer
010beca29ac98fdea73b9741973403cfa764d301
b482c0481b28d4506be72e5f8da4aa23b98d5489
refs/heads/master
2020-06-04T05:25:54.050496
2010-03-07T08:34:37
2010-03-07T08:34:37
12,849,019
1
0
null
null
null
null
UTF-8
C++
false
false
1,007
h
#ifndef PLGLSPAWNPTMGR_H #define PLGLSPAWNPTMGR_H #include "PRP/Object/plSceneObject.h" #include "PRP/Object/plCoordinateInterface.h" #include "PRP/Modifier/plSpawnModifier.h" #include "ResManager/plResManager.h" #include "Math/hsMatrix44.h" #include "Util/plString.h" #include "Util/hsTArray.hpp" #include "plglCamera2.h" #include <math.h> class plglSpawnPtMgr { public: plglSpawnPtMgr(); void init(plResManager* rm); void AttemptToSetPlayerToLinkPointDefault(plglCamera2 &cam); void UpdateSpawnPoints(); void NextSpawnPoint(plglCamera2 &cam); void PrevSpawnPoint(plglCamera2 &cam); bool SetSpawnPoint(plString name, plglCamera2 &cam); private: plResManager* rm; template <class T> T *getModifierOfType(plSceneObject *sObj, T*(type)(plCreatable *pCre)); void SetSpawnPoint(int idxc, plglCamera2 &cam); bool SceneObjectHasSpawnMod(plSceneObject* sObj); hsTArray<plKey> SpawnPoints; int curSpawnPoint; }; #endif
[ "lontahv@46d49313-71c2-4fea-ab98-6c881a270271" ]
[ [ [ 1, 35 ] ] ]
51e7f2b5191421911d5d99a317e848fbb5f18ead
36d0ddb69764f39c440089ecebd10d7df14f75f3
/プログラム/Ngllib/include/Ngl/EffectOutputDesc.h
0d827a70d15108623ad4fe9682d861620dd07fcc
[]
no_license
weimingtom/tanuki-mo-issyo
3f57518b4e59f684db642bf064a30fc5cc4715b3
ab57362f3228354179927f58b14fa76b3d334472
refs/heads/master
2021-01-10T01:36:32.162752
2009-04-19T10:37:37
2009-04-19T10:37:37
48,733,344
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,001
h
/*******************************************************************************/ /** * @file EffectOutputDesc.h. * * @brief エフェクト出力記述子構造体定義. * * @date 2008/07/04. * * @version 1.00. * * @author Kentarou Nishimura. */ /******************************************************************************/ #ifndef _NGL_EFFECTOUTPUTDESC_H_ #define _NGL_EFFECTOUTPUTDESC_H_ #include <string> namespace Ngl{ /** * @struct EffectOutputDesc. * @brief エフェクト出力記述子構造体 */ struct EffectOutputDesc { /** マテリアルデータをエフェクトに出力するか */ bool isOutMaterial; /** テクスチャデータをエフェクトに出力するか */ bool isOutTexture; /** 頂点カラーデータをエフェクトに出力するか */ bool isOutVertexColor; /** テクスチャー出力名 */ std::string textureName; /** マテリアル環境光カラー出力名 */ std::string matAmbientName; /** マテリアル拡散反射光カラー出力名 */ std::string matDiffuseName; /** マテリアル鏡面反射光カラー出力名 */ std::string matSpecularName; /** マテリアル放射光カラー出力名 */ std::string matEmissiveName; /** 放射光カラー出力名 */ std::string matShininessName; /*=========================================================================*/ /** * @brief コンストラクタ * * @param[in] なし. */ EffectOutputDesc(): isOutMaterial( true ), isOutTexture( true ), isOutVertexColor( true ), textureName( "g_BaseMap" ), matAmbientName( "g_MaterialAmbient" ), matDiffuseName( "g_MaterialDiffuse" ), matSpecularName( "g_MaterialSpecular" ), matEmissiveName( "g_MaterialEmissive" ), matShininessName( "g_MaterialShininess" ) {} }; } // namespace Ngl #endif /*===== EOF ==================================================================*/
[ "rs.drip@aa49b5b2-a402-11dd-98aa-2b35b7097d33" ]
[ [ [ 1, 80 ] ] ]
4d4202d5d4439e49ecf0aeea441a0e227ac8d481
09ea547305ed8be9f8aa0dc6a9d74752d660d05d
/smf/smfcredentialmgr/smfcredmgrclient/smfcredmgrclientsession.cpp
cb22243ef09a69b3a5d57f7e90a528e96c773bc6
[]
no_license
SymbianSource/oss.FCL.sf.mw.socialmobilefw
3c49e1d1ae2db8703e7c6b79a4c951216c9c5019
7020b195cf8d1aad30732868c2ed177e5459b8a8
refs/heads/master
2021-01-13T13:17:24.426946
2010-10-12T09:53:52
2010-10-12T09:53:52
72,676,540
0
0
null
null
null
null
UTF-8
C++
false
false
2,390
cpp
/** * Copyright (c) 2010 Sasken Communication Technologies Ltd. * All rights reserved. * This component and the accompanying materials are made available * under the terms of the "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html" * * Initial Contributors: * Pritam Roy Biswas, Sasken Communication Technologies Ltd - Initial contribution * * Description: * Client-side handle to a session with a server. Derives from RSessionBase to * create a communicating channel with the server. * */ #include "smfcredmgrclientsession.h" // The number of connection attempts. const TInt KConnectAttempts = 2; // Global Functions static TInt StartServer() { RProcess server; TInt r = server.Create(KCredMgrServerName, KNullDesC); if (r != KErrNone) { return r; } TRequestStatus stat = KRequestPending; server.Rendezvous(stat); if (stat != KRequestPending) server.Kill(0); else server.Resume(); User::WaitForRequest(stat); TExitType et = server.ExitType(); TInt code = stat.Int(); r = (et == EExitPanic) ? KErrGeneral : code; server.Close(); return KErrNone; } RSmfCredMgrClientSession::RSmfCredMgrClientSession() { } TInt RSmfCredMgrClientSession::connectToServer() { TInt retry = KConnectAttempts; TInt r = 0; for (;;) { r = CreateSession(KCredMgrServerName, Version(), 1); if (r == KErrNone) { break; } else if (r != KErrNotFound && r != KErrServerTerminated) { return r; } if (--retry == 0) { return r; } r = StartServer(); if (r != KErrNone && r != KErrAlreadyExists) { return r; //error } } return r; } TVersion RSmfCredMgrClientSession::Version() const { return (TVersion(KSecureServMajorVersionNumber, KSecureServMinorVersionNumber, KSecureServBuildVersionNumber)); } void RSmfCredMgrClientSession::Close() { RSessionBase::Close(); } void RSmfCredMgrClientSession::RequestAsyncService( TCredentialServerRequestID aRequestType, TRequestStatus& aStatus) { SendReceive(aRequestType, aStatus); } TInt RSmfCredMgrClientSession::RequestService( TCredentialServerRequestID aRequestType, const TIpcArgs &aArgs) { return SendReceive(aRequestType, aArgs); }
[ "[email protected]", "none@none" ]
[ [ [ 1, 103 ], [ 105, 106 ], [ 108, 109 ] ], [ [ 104, 104 ], [ 107, 107 ] ] ]
86beb37e50b9ed34fbc6982d8fcfbf09bdb479d6
9a48be80edc7692df4918c0222a1640545384dbb
/Libraries/Boost1.40/libs/wave/samples/preprocess_pragma_output/preprocess_pragma_output.cpp
3953965053acfddb03dfb872d1d26c0348bec161
[ "BSL-1.0" ]
permissive
fcrick/RepSnapper
05e4fb1157f634acad575fffa2029f7f655b7940
a5809843f37b7162f19765e852b968648b33b694
refs/heads/master
2021-01-17T21:42:29.537504
2010-06-07T05:38:05
2010-06-07T05:38:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,491
cpp
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Example demonstrating how to preprocess the token stream generated by a #pragma directive http://www.boost.org/ Copyright (c) 2001-2009 Hartmut Kaiser. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #include <iostream> #include <fstream> #include <string> #include <vector> /////////////////////////////////////////////////////////////////////////////// // Include Wave itself #include <boost/wave.hpp> /////////////////////////////////////////////////////////////////////////////// // Include the lexer stuff #include <boost/wave/cpplexer/cpp_lex_token.hpp> // token class #include <boost/wave/cpplexer/cpp_lex_iterator.hpp> // lexer class /////////////////////////////////////////////////////////////////////////////// // Include special preprocessing hooks #include "preprocess_pragma_output.hpp" /////////////////////////////////////////////////////////////////////////////// // main entry point int main(int argc, char *argv[]) { if (2 != argc) { std::cerr << "Usage: preprocess_pragma_output infile" << std::endl; return -1; } // current file position is saved for exception handling boost::wave::util::file_position_type current_position; try { // Open and read in the specified input file. std::ifstream instream(argv[1]); std::string instring; if (!instream.is_open()) { std::cerr << "Could not open input file: " << argv[1] << std::endl; return -2; } instream.unsetf(std::ios::skipws); instring = std::string(std::istreambuf_iterator<char>(instream.rdbuf()), std::istreambuf_iterator<char>()); // The template boost::wave::cpplexer::lex_token<> is the token type to be // used by the Wave library. typedef boost::wave::cpplexer::lex_token<> token_type; // The template boost::wave::cpplexer::lex_iterator<> is the lexer type to // be used by the Wave library. typedef boost::wave::cpplexer::lex_iterator<token_type> lex_iterator_type; // This is the resulting context type to use. typedef boost::wave::context< std::string::iterator, lex_iterator_type, boost::wave::iteration_context_policies::load_file_to_string, preprocess_pragma_output_hooks> context_type; // The preprocessor iterator shouldn't be constructed directly. It is // to be generated through a wave::context<> object. This wave:context<> // object is to be used additionally to initialize and define different // parameters of the actual preprocessing (not done here). // // The preprocessing of the input stream is done on the fly behind the // scenes during iteration over the context_type::iterator_type stream. context_type ctx (instring.begin(), instring.end(), argv[1]); // analyze the input file context_type::iterator_type first = ctx.begin(); context_type::iterator_type last = ctx.end(); while (first != last) { current_position = (*first).get_position(); std::cout << (*first).get_value(); ++first; } } catch (boost::wave::cpp_exception const& e) { // some preprocessing error std::cerr << e.file_name() << "(" << e.line_no() << "): " << e.description() << std::endl; return 2; } catch (std::exception const& e) { // use last recognized token to retrieve the error position std::cerr << current_position.get_file() << "(" << current_position.get_line() << "): " << "exception caught: " << e.what() << std::endl; return 3; } catch (...) { // use last recognized token to retrieve the error position std::cerr << current_position.get_file() << "(" << current_position.get_line() << "): " << "unexpected exception caught." << std::endl; return 4; } return 0; }
[ "metrix@Blended.(none)" ]
[ [ [ 1, 115 ] ] ]
9914737221e2ccd23c016a728dae1e292e0e901f
27c6eed99799f8398fe4c30df2088f30ae317aff
/bomFileReader/tag/bfr-1.0.0/mainwindow.h
2c49c126eee59fd92126f0e39db2baf7b4d19cea
[]
no_license
lit-uriy/ysoft
ae67cd174861e610f7e1519236e94ffb4d350249
6c3f077ff00c8332b162b4e82229879475fc8f97
refs/heads/master
2021-01-10T08:16:45.115964
2009-07-16T00:27:01
2009-07-16T00:27:01
51,699,806
0
0
null
null
null
null
UTF-8
C++
false
false
645
h
/*! * \file mainwindow.h * \brief Интерфейс класса "MainWindow". */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "ui_mainwindow.h" /** Класс MainWindow является ... . * Этот класс ... */ class MainWindow : public QWidget, public Ui::MainWindow { Q_OBJECT public: MainWindow(QWidget *p_parent = 0); private slots: void slotOpenFileDialog(); void slotOpenFileQuick(); private: void setCurrentPath(QString f_name); void parseBom(QString f_name); private: QString file_name; QString db_name; QString root_path; }; #endif //MAINWINDOW_H
[ "lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330" ]
[ [ [ 1, 38 ] ] ]
7a59ccbda5d128db4b882527bc58ac2252c21460
b4d726a0321649f907923cc57323942a1e45915b
/Launcher/OGLDisp.cpp
66f18d7e85220466d2efbf8a1827e804939fc548
[]
no_license
chief1983/Imperial-Alliance
f1aa664d91f32c9e244867aaac43fffdf42199dc
6db0102a8897deac845a8bd2a7aa2e1b25086448
refs/heads/master
2016-09-06T02:40:39.069630
2010-10-06T22:06:24
2010-10-06T22:06:24
967,775
2
0
null
null
null
null
UTF-8
C++
false
false
4,857
cpp
// OGLDisp.cpp : implementation file // #include "stdafx.h" #include "launcher.h" #include "OGLDisp.h" #include "win32func.h" typedef struct { int xres; int yres; int cdepth; } ModeOGL; const int NUM_OGL_MODES = 24; ModeOGL ogl_modes[NUM_OGL_MODES] = { 1600, 1200, 32, 1600, 1024, 32, 1600, 900, 32, 1360, 768, 32, 1280, 1024, 32, 1280, 960, 32, 1280, 768, 32, 1280, 720, 32, 1152, 864, 32, 1024, 768, 32, 800, 600, 32, 640, 480, 32, 1600, 1200, 16, 1600, 1024, 16, 1600, 900, 16, 1360, 768, 16, 1280, 1024, 16, 1280, 960, 16, 1280, 768, 16, 1280, 720, 16, 1152, 864, 16, 1024, 768, 16, 800, 600, 16, 640, 480, 16, }; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // COGLDisp dialog COGLDisp::COGLDisp(CWnd* pParent /*=NULL*/) : CDialog(COGLDisp::IDD, pParent) { //{{AFX_DATA_INIT(COGLDisp) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_allow_only_standard_modes = true; } void COGLDisp::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(COGLDisp) DDX_Control(pDX, IDC_ALLOW_NON_SMODES, m_show_all_modes_checkbox); DDX_Control(pDX, IDC_OGL_RES, m_res_list); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(COGLDisp, CDialog) //{{AFX_MSG_MAP(COGLDisp) ON_BN_CLICKED(IDC_ALLOW_NON_SMODES, OnAllowNonSmodes) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // COGLDisp message handlers BOOL COGLDisp::OnInitDialog() { CDialog::OnInitDialog(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } /** * The user has chosen to accept these settings * * @param char *reg_path - Registry path that any settings should be saved to */ void COGLDisp::OnApply(char *reg_path) { int index = m_res_list.GetCurSel(); if( index == CB_ERR) { MessageBox("Failed to set graphic mode"); return; } int current = m_res_list.GetItemData(index); char videocard[100]; sprintf(videocard, "OGL-(%dx%d)x%d bit", ogl_modes[current].xres, ogl_modes[current].yres, ogl_modes[current].cdepth); if(reg_set_sz(reg_path, "Videocard", videocard) == false) { MessageBox("Failed to set graphic mode"); } } void COGLDisp::UpdateResList(unsigned int requested_width, unsigned int requested_height, int requested_cdepth) { int selected_sel = 0; int count = 0; m_res_list.ResetContent(); for(int i = 0; i < NUM_OGL_MODES; i++) { bool non_standard_match = (ogl_modes[i].xres == requested_width && ogl_modes[i].yres == requested_height && ogl_modes[i].cdepth == requested_cdepth); // ignore invalid modes unless we have an exact match (user picked non standard mode last time) if(m_allow_only_standard_modes && !non_standard_match) { // Just the standard modes if( !(ogl_modes[i].xres == 1024 && ogl_modes[i].yres == 768) && !(ogl_modes[i].xres == 640 && ogl_modes[i].yres == 480)) { continue; } } else { // Anything above the minimum if( !(ogl_modes[i].xres == 640 && ogl_modes[i].yres == 480) && (ogl_modes[i].xres < 800 || ogl_modes[i].yres < 600)) { continue; } } char mode_string[20]; sprintf(mode_string, "%d x %d x %d", ogl_modes[i].xres, ogl_modes[i].yres, ogl_modes[i].cdepth); // Store the index int index = m_res_list.InsertString(count, mode_string); m_res_list.SetItemData(index, i); if( requested_width == ogl_modes[i].xres && requested_height == ogl_modes[i].yres && requested_cdepth == ogl_modes[i].cdepth) { selected_sel = count; } count++; } if(selected_sel < 0) selected_sel = 0; m_res_list.SetCurSel(selected_sel); } void COGLDisp::LoadSettings(char *reg_path) { unsigned int width, height; int cdepth; char videocard_string[MAX_PATH]; // Lets get those video card settings if(reg_get_sz(reg_path, "Videocard", videocard_string, MAX_PATH) == false) return; if(sscanf(videocard_string, "OGL-(%dx%d)x%d bit", &width, &height, &cdepth) != 3) return; UpdateResList(width, height, cdepth); } void COGLDisp::OnAllowNonSmodes() { m_allow_only_standard_modes = !m_show_all_modes_checkbox.GetCheck(); UpdateResList(); if(!m_allow_only_standard_modes) { MessageBox("IA OGL will run under non standard modes but it is not fully supported so expect bugs." " Also your monitor may not support all the resolutions you are offered","Warning",MB_ICONWARNING); } }
[ [ [ 1, 211 ] ] ]
39b39ce03835bd7bfd84481dad824af2221cfe04
e537c879c7f7777d649121eee4b3f1fbff1e07c8
/modules/LogManGui/src/LogManGui_Appui.cpp
51aa8cc2827900c73f682c0431ab3b2060f1b3a7
[]
no_license
SymbiSoft/logman-for-symbian
1181007a28a6d798496bb7e1107d1bce366becdd
cd0de1cf1afef03df09622e3d1db6c8bddbd324b
refs/heads/master
2021-01-10T15:04:55.032082
2010-05-11T13:26:07
2010-05-11T13:26:07
48,182,126
0
0
null
null
null
null
UTF-8
C++
false
false
10,670
cpp
// INCLUDE FILES #include <avkon.hrh> #include <aknnotewrappers.h> #include <stringloader.h> #include <LogManGui.rsg> #include <f32file.h> #include <s32file.h> #include <hlplch.h> // Launch help //#include "LogManGui_0xAF111111.hlp.hrh" #include "LogManGui.hrh" #include "LogManGui.pan" #include "LogManGui_Appui.h" #include "LogManGui_Appview.h" #include "LogManGui_Application.h" #include "LogManGui_Utils.h" #include "LogMan.h" #include "logmanutils.h" void CLogManAppUi::HandleForegroundEventL(TBool aForeground) { LOGMAN_SENDLOGF( "HandleForegroundEventL %d", aForeground ) UpdateServiceInfoL( ); } void CLogManAppUi::UpdateServiceInfoL() { LOGMAN_SENDLOG( "UpdateServiceInfoL" ) // Check if LogMan service is running RProcess logginServerProcess; TFindServer findMyServer(KLoggingServer); TFullName servername; TInt result = findMyServer.Next(servername); if (result != KErrNone) { iAppView->iLogManServiceInfo.iRunning = EFalse; iAppView->iLogManServiceInfo.iConnected = EConnectionNone; iAppView->iLogManServiceInfo.iPort = 0; iAppView->iLogManServiceInfo.iPortName.Copy(KEmptyStr); } else { RLogMan log; User::LeaveIfError(log.Connect()); CleanupClosePushL(log); iAppView->iLogManServiceInfo.iConnected = log.ConnectionStatus(); iAppView->iLogManServiceInfo.iRunning = ETrue; iAppView->iLogManServiceInfo.iPort = log.Port(); iAppView->iLogManServiceInfo.iPortName.Copy(log.PortName()); iAppView->iLogManServiceInfo.iBytesSent = log.BytesSent(); CleanupStack::PopAndDestroy(&log); } iAppView->DrawNow(); } void CLogManAppUi::StartSocketServer(RLogMan& aLogMan) { aLogMan.StartSocketServer(); } void CLogManAppUi::ConnectSocketServer(RLogMan& aLogMan) { aLogMan.ConnectSocketServer(); } void CLogManAppUi::ConnectSerial(RLogMan& aLogMan) { // Connect TInt err = aLogMan.ConnectSerial(); iAppView->iLogManServiceInfo.iConnectionError = err; if (err != KErrNone) { iAppView->iLogManServiceInfo.iConnected = EConnectionNone; _LIT(KConnectFailed, "Service failed to connect serial."); // Stringify the error code. TName errcode; _LIT(KStrErrNotFound, "KErrNotFound"); _LIT(KStrErrTimedOut, "KErrTimedOut"); _LIT(KStrErrInUse, "KErrInUse"); _LIT(KStrErrNotSupported, "KErrNotSupported"); _LIT(KStrErrAccessDenied, "KErrAccessDenied"); _LIT(KStrPermissionDenied, "KErrPermissionDenied"); _LIT(KStrErrLocked, "KErrLocked"); switch (err) { case KErrTimedOut: errcode.Copy(KStrErrTimedOut); break; case KErrInUse: errcode.Copy(KStrErrInUse); break; case KErrNotFound: errcode.Copy(KStrErrNotFound); break; case KErrNotSupported: errcode.Copy(KStrErrNotSupported); break; case KErrAccessDenied: errcode.Copy(KStrErrAccessDenied); break; case KErrPermissionDenied: errcode.Copy(KStrPermissionDenied); break; case KErrLocked: errcode.Copy(KStrErrLocked); break; default: // Not mapped, show the numeric code then. errcode.Num(err); } _LIT(KErrorFmt, "Error:%S"); TName tmp; tmp.Format(KErrorFmt, &errcode); CEikonEnv::Static()->InfoWinL(KConnectFailed, tmp); } } void CLogManAppUi::DynInitMenuPaneL(TInt aResourceId, CEikMenuPane* aMenuPane) { if (aResourceId == R_SHELL_SUBMENU) { RLogMan log; log.Connect(); TBool enabled = log.ShellEnabled(); aMenuPane->SetItemDimmed(ELogManMenuEnableShell, enabled); aMenuPane->SetItemDimmed(ELogManMenuDisableShell, !enabled); } } void CLogManAppUi::HandleCommandL(TInt aCommand) { // Handle here to avoid connection to RLogMan unnecesarily if (aCommand == ELogServCmdMenuUpdateInfo) { UpdateServiceInfoL(); return; } switch (aCommand) { case EEikCmdExit: case EAknSoftkeyExit: Exit(); return; } RLogMan log; User::LeaveIfError(log.Connect()); CleanupClosePushL(log); switch (aCommand) { case ELogServCmdMenuMainConnect: { ConnectSerial(log); break; } case ELogManMenuEnableShell: { log.SetShellEnabled(ETrue); break; } case ELogManMenuDisableShell: { log.SetShellEnabled(EFalse); break; } case ELogServCmdMenuMainListenSocketServer: { StartSocketServer(log); break; } case ELogServCmdMenuMainConnectSocketServer: { _LIT(KHostQueryTxt, "Enter address of remote host"); TPortName host = log.Host(); if (GenericTextQueryL(KHostQueryTxt, host)) { // TODO: Parse port. if( log.SetHost(host) == KErrNone) { ConnectSocketServer(log); } } break; } case ELogServCmdMenuMainDisconnect: { log.DisconnectSerial(); break; } case ELogServCmdMenuMainStartService: { // Started by Connect // _LIT( KServiceStartedNoteMsg, "LogMan service process started" ); // CEikonEnv::Static()->InfoWinL(KServiceStartedNoteMsg, KEmptyStr ); } break; case ELogServCmdMenuMainCloseService: { log.StopService(); // _LIT( KServiceStoppedNoteMsg, "LogMan service process closed" ); // CEikonEnv::Static()->InfoWinL(KServiceStoppedNoteMsg, KEmptyStr ); } break; case ELogServCmdMenuMainSendTest: { _LIT8(KTestMsg8, "This is 8-bit test message\n"); _LIT(KTestMsg16, "This is 16-bit test message\n"); log.Write(KTestMsg8); log.Write(KTestMsg16); _LIT8(KTestFormattedMsg8, "This is %d-bit formatted message\n"); _LIT(KTestFormattedMsg16, "This is %d-bit formatted message\n"); log.Writef(KTestFormattedMsg8, EFalse, 8); log.Writef(KTestFormattedMsg16, EFalse, 16); _LIT8(KTestStaticMsg8, "This is 8-bit message sent using static Log\n"); _LIT(KTestStaticMsg16, "This is 16-bit message sent using static Log\n"); RLogMan::Log(KTestStaticMsg8); RLogMan::Log(KTestStaticMsg16); _LIT8(KTestStaticFormattedMsg8, "This is %d-bit formatted message sent using static Log\n"); _LIT(KTestStaticFormattedMsg16, "This is %d-bit formatted message sent using static Log\n"); RLogMan::Log(KTestStaticFormattedMsg8, EFalse, 8); RLogMan::Log(KTestStaticFormattedMsg16, EFalse, 16); log.Log(_L("Testing memory info logging\n")); log.Log(_L("StackInfo\n")); log.StackInfo(); log.Log(_L("HeapInfo\n")); log.HeapInfo(); log.Log(_L("MemoryInfo\n")); log.MemoryInfo(); } break; case ELogServCmdMenuMainSendTestAsync: { _LIT8(KTestMsg8Async, "This is 8-bit asynchronous test message\n"); _LIT(KTestMsg16Async, "This is 16-bit asynchronous test message\n"); log.Write(KTestMsg8Async, ETrue); log.Write(KTestMsg16Async, ETrue); _LIT8(KAsynchronous8, "asynchronous"); _LIT16(KAsynchronous16, "asynchronous"); _LIT8(KTestFormattedMsg8Async, "This is %d-bit %S formatted message\n"); _LIT16(KTestFormattedMsg16Async, "This is %d-bit %S formatted message\n"); log.Writef(KTestFormattedMsg8Async, ETrue, 8, &KAsynchronous8); log.Writef(KTestFormattedMsg16Async, ETrue, 16, &KAsynchronous16); _LIT8(KTestStaticMsg8, "This is 8-bit asynchronous message sent using static Log\n"); _LIT16(KTestStaticMsg16, "This is 16-bit asynchronous message sent using static Log\n"); RLogMan::Log(KTestStaticMsg8); RLogMan::Log(KTestStaticMsg16); _LIT8(KTestStaticFormattedMsg8, "This is %d-bit %S formatted message sent using static Log\n"); _LIT16(KTestStaticFormattedMsg16, "This is %d-bit %S formatted message sent using static Log\n"); RLogMan::Log(KTestStaticFormattedMsg8, ETrue, 8, &KAsynchronous8); RLogMan::Log(KTestStaticFormattedMsg16, ETrue, 16, &KAsynchronous16); } break; case ELogServCmdMenuMainLoadSerial: { _LIT(KModuleQueryTxt, "Give serial module to load"); TFullName module; if (GenericTextQueryL(KModuleQueryTxt, module)) { log.LoadModule(module); } } break; case ELogServCmdMenuMainSetPortName: { _LIT(KModuleQueryTxt, "Enable serial port"); TPortName portname = log.PortName(); if (GenericTextQueryL(KModuleQueryTxt, portname)) { log.SetPortName(portname); // Refresh connection log.DisconnectSerial(); ConnectSerial(log); } } break; case ELogServCmdMenuMainSetPort: { _LIT(KModuleQueryTxt, "Set port"); TInt port = log.Port(); if (GenericNumberQueryL(KModuleQueryTxt, port)) { log.SetPort(port); // Refresh connection log.DisconnectSerial(); ConnectSerial(log); } } case ELogManGui_CmdHelp: { CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL(); HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf); } break; break; default: Panic(ELoggingServerGuiUi); break; } switch (aCommand) { // Don't update service info with these case EEikCmdExit: case EAknSoftkeyExit: break; default: UpdateServiceInfoL(); } CleanupStack::PopAndDestroy(&log); } void CLogManAppUi::HandleStatusPaneSizeChange() { iAppView->SetRect(ClientRect()); iAppView->DrawNow(); } /* CArrayFix<TCoeHelpContext>* CLoggingServerGuiAppUi::HelpContextL() const { #warning "Please see comment about help and UID3..." // Note: Help will not work if the application uid3 is not in the // protected range. The default uid3 range for projects created // from this template (0xE0000000 - 0xEFFFFFFF) are not in the protected range so that they // can be self signed and installed on the device during testing. // Once you get your official uid3 from Symbian Ltd. and find/replace // all occurrences of uid3 in your project, the context help will // work. // CArrayFixFlat<TCoeHelpContext>* array = new(ELeave)CArrayFixFlat<TCoeHelpContext>(1); // CleanupStack::PushL(array); // array->AppendL(TCoeHelpContext(KUidLoggingServerGuiApp, KGeneral_Information)); // CleanupStack::Pop(array); // return array; return NULL; } */ // ============================ Construction =============================== void CLogManAppUi::ConstructL() { // Initialise app UI with standard value. LOGMAN_SENDLINE(BaseConstructL(CAknAppUi::EAknEnableSkin);) LOGMAN_SENDLOG( "After BaseConstructL" ) // Create view object iAppView = CLoggingServerGuiAppView::NewL( ClientRect() ); UpdateServiceInfoL(); } CLogManAppUi::CLogManAppUi() { // No implementation required } CLogManAppUi::~CLogManAppUi() { LOGMAN_SENDLOG( "CLoggingServerGuiAppUi" ) if ( iAppView ) { delete iAppView; iAppView = NULL; } } // ============================ End of construction ============================
[ "jtoivola@localhost", "Jussi Toivola@localhost" ]
[ [ [ 1, 19 ], [ 21, 25 ], [ 27, 39 ], [ 41, 49 ], [ 51, 61 ], [ 64, 67 ], [ 74, 76 ], [ 79, 81 ], [ 84, 129 ], [ 145, 172 ], [ 187, 190 ], [ 205, 239 ], [ 241, 360 ], [ 362, 385 ], [ 387, 398 ], [ 400, 403 ], [ 405, 413 ] ], [ [ 20, 20 ], [ 26, 26 ], [ 40, 40 ], [ 50, 50 ], [ 62, 63 ], [ 68, 73 ], [ 77, 78 ], [ 82, 83 ], [ 130, 144 ], [ 173, 186 ], [ 191, 204 ], [ 240, 240 ], [ 361, 361 ], [ 386, 386 ], [ 399, 399 ], [ 404, 404 ] ] ]
6677f33ddcbf20169c7ca0b6cacded9fdbcea62e
a21de044e9c5b4ed3777817cabb728c62f7315fc
/ocean_domination/Island.cpp
9bd2291f3f6966707f280d726f7c520aa43c225d
[]
no_license
alyshamsy/oceandomination
9470889b9f051086b047f7dbc7e6de4f289d2da9
3580c399537045c8ad0817bc7a9d81d24c85a925
refs/heads/master
2020-03-30T05:30:08.981859
2011-05-12T15:47:06
2011-05-12T15:47:06
32,115,468
0
0
null
null
null
null
UTF-8
C++
false
false
2,611
cpp
#include "Island.h" Island::Island() { } Island::~Island() { } int Island::InitializeIsland(Vector location, char island_type) { this->health = 100; this->under_attack = false; if(island_type == 'L') { this->island_radius = large_island_radius; } else if(island_type == 'M') { this->island_radius = medium_island_radius; } else if(island_type == 'S') { this->island_radius = small_island_radius; } if(island_type == 'L') { this->defence_radius = large_island_defence_radius; } else if(island_type == 'M') { this->defence_radius = medium_island_defence_radius; } else if(island_type == 'S') { this->defence_radius = small_island_defence_radius; } this->location = location; if(island_type == 'L') { this->island_ammo_location.x = location.x + 10.0; this->island_ammo_location.y = 20.0 + 3.0; this->island_ammo_location.z = location.z - 4.0; } else if(island_type == 'M') { this->island_ammo_location.x = location.x + 6.0; this->island_ammo_location.y = 10.0 + 3.0; this->island_ammo_location.z = location.z - 2.0; } else if(island_type == 'S') { this->island_ammo_location.x = location.x + 4.0; this->island_ammo_location.y = 5.0 + 3.0; this->island_ammo_location.z = location.z - 1.0; } this->island_type = island_type; this->weapon_fire = false; this->weapon_rotation_angle = 0.0; return 0; } void Island::UpdateHealth(int health) { this->health = health; } void Island::UpdateUnderAttack( bool under_attack) { this->under_attack = under_attack; } void Island::UpdateWeaponFire(bool weapon_fire) { this->weapon_fire = weapon_fire; } void Island::UpdateWeaponRotationAngle(float weapon_rotation_angle) { this->weapon_rotation_angle = weapon_rotation_angle; } void Island::UpdateAmmoLocation(Vector island_ammo_location) { this->island_ammo_location = island_ammo_location; } void Island::ResetAmmoLocation() { if(this->island_type == 'L') { this->island_ammo_location.x = this->location.x + 10.0; this->island_ammo_location.y = 20.0 + 3.0; this->island_ammo_location.z = this->location.z - 4.0; } else if(this->island_type == 'M') { this->island_ammo_location.x = this->location.x + 6.0; this->island_ammo_location.y = 10.0 + 3.0; this->island_ammo_location.z = this->location.z - 2.0; } else if(this->island_type == 'S') { this->island_ammo_location.x = this->location.x + 4.0; this->island_ammo_location.y = 5.0 + 3.0; this->island_ammo_location.z = this->location.z - 1.0; } } void Island::CreateHealthBar() { }
[ "aly.shamsy@b23e3eda-3cbb-b783-0003-8fc1c118d970" ]
[ [ [ 1, 94 ] ] ]
1358657739cc7612d7453c93e7e3cfc6c4697cec
9a33169387ec29286d82e6e0d5eb2a388734c969
/3DBipedRobot/Comm.h
9ebe4f554a3955daa93ffd998f15238b9e534154
[]
no_license
cecilerap/3dbipedrobot
a62773a6db583d66c80f9b8ab78d932b163c8dd9
83c8f972e09ca8f16c89fc9064c55212d197d06a
refs/heads/master
2021-01-10T13:28:09.532652
2009-04-24T03:03:13
2009-04-24T03:03:13
53,042,363
0
0
null
null
null
null
UHC
C++
false
false
3,429
h
//Comm.h //Rs232c를 하기위한 클래스 헤더 // 2001년 3월 26일 (주) 마이크로 로보트 S/W팀 정웅식 // #ifndef __COMM_H__ #define __COMM_H__ #define COM_MAXBLOCK 4095 #define COM_MAXPORTS 6 // Flow control flags #define FC_DTRDSR 0x01 #define FC_RTSCTS 0x02 #define FC_XONXOFF 0x04 // ascii definitions #define ASCII_BEL 0x07 #define ASCII_BS 0x08 #define ASCII_LF 0x0A #define ASCII_CR 0x0D #define ASCII_XON 0x11 #define ASCII_XOFF 0x13 #define ASCII_STX 0x02 #define ASCII_ETX 0xFE #define WM_RECEIVEDATA WM_USER+100 ///////////////////////////////////////////////////////////////////////////// // CComm window #define ZERO_MEMORY(s) ::ZeroMemory(&s, sizeof(s)) // flow control #define FC_DTRDSR 0x01 #define FC_RTSCTS 0x02 #define FC_XONXOFF 0x04 #define FC_NONE 0x00 #define ASCII_XON 0x11 #define ASCII_XOFF 0x13 // registry stuff #define CS_REGKEY_SETTINGS _T("통신환경") #define CS_REGENTRY_PORT _T("PORT") #define CS_REGENTRY_PARITY _T("PARITY") #define CS_REGENTRY_BAUD _T("BAUD") #define CS_REGENTRY_DATABITS _T("DATABITS") #define CS_REGENTRY_STOPBITS _T("STOPBITS") #define CS_REGENTRY_FLOW _T("FLOW") #pragma pack(push,1) typedef struct _TTYSTRUCT { BYTE byCommPort; // zero based port - 3 or higher implies TELNET BYTE byXonXoff; BYTE byByteSize; BYTE byFlowCtrl; BYTE byParity; BYTE byStopBits; DWORD dwBaudRate; } TTYSTRUCT, *LPTTYSTRUCT; #pragma pack(pop,1) // 통신프로토콜 Table extern BYTE _nFlow[4]; // 통신 데이타 사이즈 테이블 extern int _nDataValues[2]; // 통신 속도 Table extern int _nBaudRates[12]; // 통신 정지 비트 Table extern BYTE _nStopBits[2]; class CComm : public CObject { DECLARE_DYNCREATE( CComm ) public: HANDLE idComDev ; //컴포트 디바이스 연결 핸들 BOOL fConnected; //컴포트가 연결되면 1로 설정 BYTE abIn[ COM_MAXBLOCK + 1] ; //컴포트에서 들어오는 데이타 HWND m_hwnd; //메세지를 전달할 윈도우 플러그 BOOL bTxEmpty; // TX용 데이터가 모두 송신 되었을 경우 TRUE로 전환된다. // Construction public: CComm( ); //컴포트를 열고 연결을 시도한다. BOOL OpenCommPort(LPTTYSTRUCT lpTTY); //comm 포트를 해제한다. BOOL DestroyComm(); //컴포트에서 데이타를 받는다. int ReadCommBlock( LPSTR data, int len); //컴포트에 데이타를 넣는다. BOOL WriteCommBlock( LPSTR data, DWORD len); //포트를 연결한다. BOOL SetupConnection(LPTTYSTRUCT lpTTY); //연결을 해제한다. BOOL CloseConnection( ); //읽은 데이타를 버퍼에 저장한다. void SetReadData(LPSTR data, int nLen); //메시지를 보낼 윈도우 핸들을 설정한다. void SetHwnd(HWND hwnd); void EscapeCommFunction(DWORD dwFunc) ; // Attributes public: OVERLAPPED osWrite, osRead; // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CComm) //}}AFX_VIRTUAL // Implementation public: virtual ~CComm(); // Generated message map functions // DECLARE_MESSAGE_MAP() protected: }; ///////////////////////////////////////////////////////////////////////////// #endif
[ "t2wish@463fb1f2-0299-11de-9d1d-173cc1d06e3c" ]
[ [ [ 1, 137 ] ] ]
d181493669be1063f7d1e51c99c230b86c4ebf87
a2904986c09bd07e8c89359632e849534970c1be
/topcoder/grafixClick.cpp
cda22c5fcc3f2d5fe63a954736ad3d7999c09bb4
[]
no_license
naturalself/topcoder_srms
20bf84ac1fd959e9fbbf8b82a93113c858bf6134
7b42d11ac2cc1fe5933c5bc5bc97ee61b6ec55e5
refs/heads/master
2021-01-22T04:36:40.592620
2010-11-29T17:30:40
2010-11-29T17:30:40
444,669
1
0
null
null
null
null
UTF-8
C++
false
false
4,004
cpp
// BEGIN CUT HERE // END CUT HERE #line 5 "grafixClick.cpp" #include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <iostream> #include <memory> #include <string> #include <vector> #include <algorithm> #include <numeric> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> using namespace std; #define forv(i, v) for (int i = 0; i < (int)(v.size()); ++i) #define fors(i, s) for (int i = 0; i < (int)(s.length()); ++i) #define all(a) a.begin(), a.end() class grafixClick { public: vector <int> checkSaveButton(vector <int> mR, vector <int> mC) { vector <int> ret; return ret; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const vector <int> &Expected, const vector <int> &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: " << print_array(Expected) << endl; cerr << "\tReceived: " << print_array(Received) << endl; } } void test_case_0() { int Arr0[] = {20, 39, 100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {99, 50, 200}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 0, 1 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(0, Arg2, checkSaveButton(Arg0, Arg1)); } void test_case_1() { int Arr0[] = {0, 100, 399}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 200, 599}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(1, Arg2, checkSaveButton(Arg0, Arg1)); } void test_case_2() { int Arr0[] = {30}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {75}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 0 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(2, Arg2, checkSaveButton(Arg0, Arg1)); } void test_case_3() { int Arr0[] = {10, 20, 30, 30, 30, 30, 34, 35, 345}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10, 20, 30, 50, 60, 80, 34, 35, 345}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 3, 4, 5 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(3, Arg2, checkSaveButton(Arg0, Arg1)); } void test_case_4() { int Arr0[] = {57, 28, 18, 25, 36, 12, 33, 44, 13, 32, 32, 51, 11, 27, 8, 51, 17, 34, 10, 16, 47, 57, 20, 57, 32, 14, 13, 37, 10, 16, 49, 37, 52, 8, 18, 44, 50, 43, 11, 1, 21, 22, 17, 35, 28, 53, 56, 16, 11, 44}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {146, 22, 41, 88, 123, 99, 43, 110, 25, 64, 141, 110, 70, 34, 99, 103, 60, 64, 142, 109, 133, 144, 72, 68, 25, 32, 21, 140, 30, 105, 32, 72, 114, 97, 35, 131, 103, 110, 133, 81, 125, 36, 76, 78, 77, 47, 50, 94, 22, 20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = { 3, 9, 17, 22, 31, 43, 44 }; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); verify_case(4, Arg2, checkSaveButton(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { grafixClick ___test; ___test.run_test(-1); } // END CUT HERE
[ "shin@CF-7AUJ41TT52JO.(none)" ]
[ [ [ 1, 71 ] ] ]
92a37ab8efd195cbd6fc21ad204099df17bce2b4
6bb2059d8bb8e3a4488e6d11e5b551360771fb30
/menu.h
96224d71a43d15a96b6e023213df8cfd9be23e8f
[]
no_license
rusetski-k/digraph-editor
c937ea4726a7598cabd629dd17b0c8db098295ae
e69f1fe65db60b755dc754354a00d709bbc7c4d9
refs/heads/master
2021-01-01T17:58:14.234871
2010-06-17T18:43:31
2010-06-17T18:43:31
32,140,529
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
h
#ifndef MENU_H #define MENU_H #include <QMainWindow> class QAction; class QGraphicsItem; class QGraphicsRectItem; class QGraphicsScene; class QGraphicsView; class Canvas; class SettingsDialog; class Menu : public QMainWindow { Q_OBJECT public: Menu(); private slots: void updateActions(); // void del(); // void saveDoc(); // void openDoc(); void newDoc(); void closeCanv(); void proAction(); // void ExportGif(); private: void createActions(); void createMenus(); void createToolBars(); QMenu *fileMenu; QMenu *editMenu; QToolBar *fileToolBar; QToolBar *graphToolBar; QToolBar *editToolBar; QAction *exitAction; QAction *NewAction; QAction *OpenAction; QAction *SaveAction; QAction *ExportAction; QAction *CloseAction; QAction *UndoAction; QAction *RedoAction; QAction *ZoomInAction; QAction *ZoomOutAction; QAction *Settings; QAction *NodeAction; QAction *ArcAction; SettingsDialog *dialog; Canvas *canvas; QGraphicsScene *scene; QGraphicsView *view; }; #endif // MENU_H
[ "[email protected]@632ee13a-2aea-38c2-448e-2c165370dd98" ]
[ [ [ 1, 65 ] ] ]
1b9c8f90d77ed8314318e5313bc73afc08f5ef84
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.6/cbear.berlios.de/windows/com/static/new.hpp
c4627b68bc423c01475ddbe4af47293e6ab397ba
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
3,183
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CBEAR_BERLIOS_DE_WINDOWS_COM_STATIC_NEW_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_COM_STATIC_NEW_HPP_INCLUDED #include <cbear.berlios.de/windows/com/static/interface_list.hpp> namespace cbear_berlios_de { namespace windows { namespace com { namespace static_ { template<class T> class implementation: public T::template implementation_t<implementation<T> >, public interface_list<T, typename T::interface_list_t> { public: typedef typename T::template implementation_t<implementation> base_t; typedef interface_list<T, typename T::interface_list_t> interface_list_t; typedef com::pointer<implementation> pointer_t; implementation() { } template<class P> implementation(const P &P_): base_t(P_) { } static typename pointer_t::move_t this_pointer(base_t &B) { return move::copy(pointer_t::cpp_in_cast( &static_cast<implementation &>(B))); } // ::IUnknown #if 1 ulong_t __stdcall AddRef() { return this->Counter.increment(); } ulong_t __stdcall Release() { ulong_t R = this->Counter.decrement(); if(!R) { delete this; return 0; } return R; } hresult::internal_type __stdcall QueryInterface( const uuid::internal_type &U, void **PP) { iunknown &P = iunknown::cpp_out(reinterpret_cast<iunknown::c_out_t>(PP)); P = this->interface_list_t::query_interface(uuid::cpp_in(&U)); return P ? hresult::s_ok: hresult::e_nointerface; } #endif private: atomic::wrap<ulong_t> Counter; }; template<class T> typename pointer<implementation<T> >::move_t new_() { typedef implementation<T> implementation_t; typedef pointer<implementation_t> pointer_t; return move::copy(pointer_t::cpp_in(new implementation_t())); } template<class T, class P> typename pointer<implementation<T> >::move_t new_(const P &P_) { typedef implementation<T> implementation_t; typedef pointer<implementation_t> pointer_t; return move::copy(pointer_t::cpp_in(new implementation_t(P_))); } } } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 119 ] ] ]
3e832e70b66930d12383df2164d3e592369a96dc
2b80036db6f86012afcc7bc55431355fc3234058
/src/core/audio/IAnalyzer.h
454781f55c482e853b22301a4304357ca9a8060e
[ "BSD-3-Clause" ]
permissive
leezhongshan/musikcube
d1e09cf263854bb16acbde707cb6c18b09a0189f
e7ca6a5515a5f5e8e499bbdd158e5cb406fda948
refs/heads/master
2021-01-15T11:45:29.512171
2011-02-25T14:09:21
2011-02-25T14:09:21
null
0
0
null
null
null
null
ISO-8859-9
C++
false
false
3,968
h
////////////////////////////////////////////////////////////////////////////// // Copyright © 2007, Daniel Önnerby // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the author nor the names of other contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////////// #pragma once #include <core/config.h> #include <core/ITrack.h> #include <core/audio/IBuffer.h> ////////////////////////////////////////////////////////////////////////////// namespace musik { namespace core { namespace audio { ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////// ///\brief ///The main interface for a analyzer plugin /// ///A analyzer plugin will be executed from the Indexer ///after all tags has been read. The plugin will first be ///called with the Start method, and if that method returns true ///a audio::Stream will be opened and the whole track will be ///decoded and passed on to the Analyze method (or until the Analyze method ///returns false). Finally the End method will be called where the ///the plugin can make changes to the tracks metadata. ////////////////////////////////////////// class IAnalyzer { public: ////////////////////////////////////////// ///\brief ///Destroy the object ////////////////////////////////////////// virtual void Destroy() = 0; ////////////////////////////////////////// ///\brief ///Start analyzing the track. Returns true if ///the analyzing should continue. ////////////////////////////////////////// virtual bool Start(musik::core::ITrack *track) = 0; ////////////////////////////////////////// ///\brief ///Analyze a buffer ////////////////////////////////////////// virtual bool Analyze(musik::core::ITrack *track,IBuffer *buffer) = 0; ////////////////////////////////////////// ///\brief ///Called when the whole track has been analyzed. ///If this call makes changes to the track it should ///return true. ////////////////////////////////////////// virtual bool End(musik::core::ITrack *track) = 0; }; ////////////////////////////////////////////////////////////////////////////// } } } //////////////////////////////////////////////////////////////////////////////
[ "[email protected]@6a861d04-ae47-0410-a6da-2d49beace72e", "onnerby@6a861d04-ae47-0410-a6da-2d49beace72e", "urioxis@6a861d04-ae47-0410-a6da-2d49beace72e" ]
[ [ [ 1, 42 ], [ 56, 56 ], [ 61, 61 ], [ 68, 68 ], [ 74, 74 ], [ 82, 87 ] ], [ [ 43, 54 ], [ 57, 60 ], [ 62, 67 ], [ 69, 73 ], [ 75, 81 ] ], [ [ 55, 55 ] ] ]
291532b9573f52bd2bbbb9e43f6809e26b4ed244
0b1111e870b496aae0d6210806eebf1c942c9d3a
/LinearAlgebra/TIdentityMatrix.h
afdb4a6eab9306a94d6d4066b3b0dcb9b23b67ee
[ "WTFPL" ]
permissive
victorliu/Templated-Numerics
8ca3fabd79435fa40e95e9c8c944ecba42a0d8db
35ca6bb719615d5498a450a2d58e2aa2bb7ef5f9
refs/heads/master
2016-09-05T16:32:22.250276
2009-12-30T07:48:03
2009-12-30T07:48:03
318,857
3
1
null
null
null
null
UTF-8
C++
false
false
1,021
h
#ifndef _TIDENTITY_MATRIX_H_ #define _TIDENTITY_MATRIX_H_ #define USING_TIDENTITY_MATRIX #include "MatrixInterfaces.h" template <typename NumericType> class TIdentityMatrix : public ReadableMatrix<NumericType>{ size_t rows; TIdentityMatrix& operator=(const TIdentityMatrix &M){ return *this; } public: typedef NumericType value_type; typedef ReadableMatrix<value_type> non_view_type; typedef ReadableMatrix<value_type> readable_matrix; typedef WritableMatrix<value_type> non_writable_matrix; TIdentityMatrix():rows(0){} TIdentityMatrix(size_t r):rows(r){} TIdentityMatrix(const TIdentityMatrix &M):rows(M.rows){} virtual ~TIdentityMatrix(){} void Resize(size_t nRows){ rows = nRows; } size_t Rows() const{ return rows; } size_t Cols() const{ return rows; } value_type operator[](size_t row) const{ return value_type(1); } value_type operator()(size_t row, size_t col) const{ return (row == col) ? value_type(1) : value_type(0); } }; #endif // _TIDENTITY_MATRIX_H_
[ [ [ 1, 31 ] ] ]
66de94d7e994071561a8f4eb2cfa26dce51630a6
5095bbe94f3af8dc3b14a331519cfee887f4c07e
/Shared/SEGReport/XmlFileReader.h
168283ce1c2d788e8a72372fd6c888fd2914fae5
[]
no_license
sativa/apsim_development
efc2b584459b43c89e841abf93830db8d523b07a
a90ffef3b4ed8a7d0cce1c169c65364be6e93797
refs/heads/master
2020-12-24T06:53:59.364336
2008-09-17T05:31:07
2008-09-17T05:31:07
64,154,433
0
0
null
null
null
null
UTF-8
C++
false
false
553
h
//--------------------------------------------------------------------------- #ifndef XmlFileReaderH #define XmlFileReaderH #include <db.hpp> class XMLNode; class DataContainer; //--------------------------------------------------------------------------- // this function reads all xml data from a file //--------------------------------------------------------------------------- void processXmlFileReader(DataContainer& parent, const XMLNode& properties, TDataSet& result); #endif
[ "hol353@8bb03f63-af10-0410-889a-a89e84ef1bc8" ]
[ [ [ 1, 15 ] ] ]
39558bdcb1775557cc4215a3ae0c19b87c418022
9a5db9951432056bb5cd4cf3c32362a4e17008b7
/FacesCapture/branches/FaceCompare/RemoteImaging/faceRecognitionDLL/faceRecognition.cpp
5309d45f87a4d9e04959cbddea7feda1ff0d1225
[]
no_license
miaozhendaoren/appcollection
65b0ede264e74e60b68ca74cf70fb24222543278
f8b85af93f787fa897af90e8361569a36ff65d35
refs/heads/master
2021-05-30T19:27:21.142158
2011-06-27T03:49:22
2011-06-27T03:49:22
null
0
0
null
null
null
null
GB18030
C++
false
false
12,498
cpp
/******************************************************************* * Face Recognition Module * DESCRIPTION: * face data base * /__________faceNum___________\ * \ / * / \ image1 image2 image3 ... imageN * | image1 image2 image3 ... imageN * | image1 image2 image3 ... imageN * | image1 image2 image3 ... imageN * imageLen image1 image2 image3 ... imageN * | image1 image2 image3 ... imageN * | image1 image2 image3 ... imageN * \ / image1 image2 image3 ... imageN * The output (similarity, float type) is stored at similarityResultPtr one by one * | similarity#1 | similarity#2 | similarity#i | similarity#N | * NOTE: similarity result#i is the similarity btw image to be recoginized and i-th train face image * AUTHOR: * Zeng Yinhui, [email protected] * HISTORY: * <10/21/2009><Zeng Yinhui> Init Version. * <10/24/2009><Zeng Yinhui> Updated the similarity definition * <11/03/2009><Zeng Yinhui> Updated the interface *******************************************************************/ #include <stdio.h> #include <iostream> #include <limits> #include <complex> #include <algorithm> #include <vector> #include <math.h> #include <fstream> #include "Matrix.h" #include "EigenvalueVector.h" //header for eigen //openCV to pre-process img, such as img resize //#define SKIP_INCLUDES //#include <afxwin.h> //#include "stdafx.h" #include "cv.h" #include "highgui.h" #include "cxcore.h" using namespace std; /*macro definition */ #define ORIGINAL_IMG_WIDTH 200 #define ORIGINAL_IMG_HEIGHT 200 #define ORIGINAL_IMG_LEN (ORIGINAL_IMG_WIDTH*ORIGINAL_IMG_HEIGHT) struct similarityMat { float similarity; char *fileName; }; /*global variable definition */ string gc_imgSearchPattern = "C:\\faceRecognition\\faceSample\\*.jpg"; string gc_faceSampleRoot = "C:\\faceRecognition\\faceSample\\"; string gc_eigenVectorFile = "C:\\faceRecognition\\data\\EigenVector.txt"; string gc_AverageValueFile = "C:\\faceRecognition\\data\\AverageValue.txt"; string gc_SampleCoefficientFile = "C:\\faceRecognition\\data\\SampleCoefficient.txt"; string gc_FileNameFile = "C:\\faceRecognition\\data\\FileName.txt"; char** gc_sampleFileName;//定义样本的文件名 int gi_sampleCount; matrixf* meanVectorPtr; matrixf* trainedEigenSpaceMatPtr; matrixf* signatureFaceDBPtr; /*local function definition */ bool smallFront (int i,int j) { return (i<j); } bool bigFront (int i,int j) { return (i>j); } void myLog(char* myLog) { } #define TIMELOG(X) //myLog(X) //return sample count extern "C" int _declspec(dllexport) FaceTraining(int imgWidth=20, int imgHeight=20, int eigenNum=40) { //read image samples to get the number and file list. WIN32_FIND_DATA FindFileData; HANDLE hFind; int sampleCount = 0;//训练样本的图片个数 TIMELOG("enter face training..."); FILE* fp; if (!(fp=fopen(gc_FileNameFile.c_str(),"w"))) { throw "File Can't be opened"; } string path; hFind = FindFirstFile(gc_imgSearchPattern.c_str(), &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { sampleCount++; path = gc_faceSampleRoot + FindFileData.cFileName; fprintf(fp,"%s\n", path.c_str()); } while (::FindNextFile(hFind, &FindFileData )) { path = gc_faceSampleRoot + FindFileData.cFileName; fprintf(fp,"%s\n", path.c_str()); sampleCount++;//遍历得到训练样本图片的总数 } FindClose(hFind); fclose(fp); TIMELOG("load img samples to faceDBPtr..."); //load img samples to faceDBPtr if (!(fp=fopen(gc_FileNameFile.c_str(),"r"))) { return -1; } int i=0; IplImage *bigImg; IplImage *smallImg; smallImg = cvCreateImage(cvSize(imgWidth, imgHeight), 8, 1); int smallImgLen = imgHeight*imgWidth; int height = smallImg->height; int width = smallImg->width; int step = smallImg->widthStep; matrixf faceDBMat(smallImgLen,sampleCount); for (i=0;i<sampleCount;i++) { char sPath[200]; fscanf(fp,"%s\n",sPath); bigImg = cvLoadImage(sPath, 0); assert(bigImg != NULL); cvResize(bigImg, smallImg, CV_INTER_LINEAR); //resize image to small size cvReleaseImage(&bigImg); uchar *smallImgData = (uchar*)smallImg->imageData; for (int h=0; h<height; h++) { for (int w=0; w<width; w++) { faceDBMat(h*step+w,i) = smallImgData[h*step+w]; } } } fclose(fp); cvReleaseImage(&smallImg); TIMELOG("calc eigen vector/value..."); //calc eigen vector/value //calc the mean matrix matrixf meanVector(smallImgLen,1); //store mean result matrixf oneVector(1,sampleCount);// matrixf meanMat(smallImgLen,sampleCount);//every column is same: meanVector matrixf faceDBzmMat(smallImgLen,sampleCount); oneVector =0*oneVector; oneVector -=-1;// oneVector = oneVector + 1; MatrixMean(faceDBMat,meanVector,2);//calc mean along with column meanMat = meanVector * oneVector; meanMat = -meanMat; faceDBzmMat = faceDBMat + meanMat; // remove mean matrixf faceDBzmMatT(sampleCount,smallImgLen);//transpose matrix MatrixTranspose(faceDBzmMat,faceDBzmMatT); matrixf eigInMat(sampleCount,sampleCount); matrixf eigVectorMat(sampleCount,sampleCount); eigInMat = faceDBzmMatT * faceDBzmMat;//////////////////////////////////////////////////////////////////////////take too much time //calc the eigen. //diagonal cell in eigInMat is eigValue. //eigVectoreMat store the eig vector //EigenvalueVectorRealSymmetryJacobiB(eigInMat,eigVectorMat,(float)0.00000000001); EigenvalueVectorRealSymmetryJacobi(eigInMat,eigVectorMat,(float)0.00000000001,200); ////////////////////////////////////////////////////////////////////////// matrixf eigVectorFinalMat(smallImgLen,sampleCount); //V=single(vzm)*V; eigVectorFinalMat = faceDBzmMat * eigVectorMat;//////////////////////////////////////////////////////////////////////////too much time here float* eigValue = new float[sampleCount]; for(i=0;i<sampleCount;i++){ eigValue[i] = eigInMat(i,i); } vector<float> eigOriginalVector(eigValue,eigValue+sampleCount); //store eigValue into vector in order to be easy to find. vector<float> eigSortVector(eigValue,eigValue+sampleCount); //store eigValue into vector in order to be easy to find. vector<float>::iterator eigSortIt; //sort eigValue by big one in front sort(eigSortVector.begin(), eigSortVector.end(),bigFront); //pick up the eigNum eigVectors of largest eigvalue //store to trainedEigenSpaceMat, eigenNum eigen vectors are picked up. //V=V(:,end:-1:end-(N-1)); matrixf trainedEigenSpaceMat(smallImgLen,eigenNum); eigSortIt = eigSortVector.begin(); int offset=0; for(i=0;i<eigenNum;i++){ offset = find(eigOriginalVector.begin(),eigOriginalVector.end(),*(eigSortVector.begin()+i))-eigOriginalVector.begin();//search n-th biggest eigen value. for(int row=0;row<smallImgLen;row++){ trainedEigenSpaceMat(row,i) = eigVectorFinalMat(row,offset);//pick up the eigen vector with n-th biggest eigen value. } } //calc signature for each face image //Each row in signatureFaceDB is the signature for one image. matrixf signatureFaceDB(sampleCount,eigenNum); signatureFaceDB = faceDBzmMatT * trainedEigenSpaceMat; TIMELOG("store eigen vector/value/train image path to file..."); //store eigen vector/value/train image path to file //store mean value, smallImgLen lines if (!(fp=fopen(gc_AverageValueFile.c_str(),"w"))) { return false; } else { for (i=0;i<smallImgLen;i++) { fprintf(fp,"%f\n",meanVector(i,0)); } } fclose(fp); //store eigen vector, smallImgLen*eigenNum if (!(fp=fopen(gc_eigenVectorFile.c_str(),"w"))) { return false; } else { for (int row=0;row<smallImgLen;row++) { for (int col=0;col<eigenNum;col++) { fprintf(fp,"%12.8f ",trainedEigenSpaceMat(row,col)); } fprintf(fp,"\n"); } } fclose(fp); //store coefficient that sample in eigen vector, smallImgLen*eigenNum if (!(fp=fopen(gc_SampleCoefficientFile.c_str(),"w"))) { return false; } else { for (int row=0;row<sampleCount;row++) { for (int col=0;col<eigenNum;col++) { fprintf(fp,"%12.8f ",signatureFaceDB(row,col)); } fprintf(fp,"\n"); } } fclose(fp); TIMELOG("training is done"); return sampleCount; } extern "C" bool _declspec(dllexport) InitData( int sampleCount, int imgLen=400, int eigenNum=40) { cout<<__LINE__<<endl; meanVectorPtr = new matrixf(imgLen,1); //store mean result trainedEigenSpaceMatPtr = new matrixf(imgLen,eigenNum); signatureFaceDBPtr = new matrixf (sampleCount,eigenNum); FILE* fp; int i; cout<<__LINE__<<endl; gc_sampleFileName = new char*[sampleCount]; gi_sampleCount = sampleCount; if (!(fp=fopen(gc_FileNameFile.c_str(),"r"))) { return false; } for (i=0;i<sampleCount;i++) { gc_sampleFileName[i] = new char[200]; fscanf(fp,"%s\n",gc_sampleFileName[i]); } fclose(fp); cout<<__LINE__<<"---------"<<gc_AverageValueFile.c_str()<< endl; //load eigen vector/value/train image path to file //load mean value, smallImgLen lines if (!(fp=fopen(gc_AverageValueFile.c_str(),"r"))) { cout<<__LINE__<<endl; assert(false); } else { for (i=0;i<imgLen;i++) { fscanf(fp,"%f\n", &((*meanVectorPtr)(i,0))); } } fclose(fp); cout<<__LINE__<<endl; //MatrixLinePrint(*meanVectorPtr); //load eigen vector, smallImgLen*eigenNum if (!(fp=fopen(gc_eigenVectorFile.c_str(),"r"))) { assert(false); } else { for (int row=0;row<imgLen;row++) { for (int col=0;col<eigenNum;col++) { fscanf(fp,"%f ",&((*trainedEigenSpaceMatPtr)(row,col))); } } } fclose(fp); //load coefficient that sample in eigen vector, smallImgLen*eigenNum if (!(fp=fopen(gc_SampleCoefficientFile.c_str(),"r"))) { assert(false); } else { for (int row=0;row<sampleCount;row++) { for (int col=0;col<eigenNum;col++) { fscanf(fp,"%f ",&((*signatureFaceDBPtr)(row,col))); } //fscanf(fp,"\n"); } } fclose(fp); TIMELOG("IniData End"); //MatrixLinePrint(*signatureFaceDBPtr); return true; } extern "C" void _declspec(dllexport) FaceRecognition(float*currentFace, int sampleCount, similarityMat* similarityPtr, int imgLen, int eigenNum=40) { TIMELOG("Entry FaceRecognition"); //fill the image to be recognized into matrix matrixf imageMat(currentFace,imgLen, 1); //calc signature for image needing to be recognized matrixf signatureImage(1,eigenNum); matrixf imageZmMat(imgLen, 1); matrixf imageZmMatT(1,imgLen); imageZmMat = imageMat - (*meanVectorPtr); //col vector of imageLen,p=r-m; MatrixTranspose(imageZmMat,imageZmMatT); signatureImage = imageZmMatT * (*trainedEigenSpaceMatPtr); //s=single(p)'*V; float deltaSum=0.0; float myMin=(float)3.40282e+038;//numeric_limits<float>::max(); float myMax=(float)1.17549e-038;//numeric_limits<float>::min(); int faceIndex=0; //calc the normalized delta btw image and face data base image. for(faceIndex=0;faceIndex<sampleCount;faceIndex++){ //fetch signature of one face, store to signatureTem deltaSum = 0.0; for(int j=0;j<eigenNum;j++){ deltaSum += fabs((*signatureFaceDBPtr)(faceIndex,j) - signatureImage(0,j)); } //store sum of absolute of the delta btw signatureImage & signatureFaceDB similarityPtr[faceIndex].similarity = deltaSum; //store max/min myMin = Min(myMin,deltaSum); myMax = Max(myMax,deltaSum); } //calc the percents on every trained face image: %=(face[i]-min)/(max-min) for(faceIndex=0;faceIndex<sampleCount;faceIndex++) { if (myMin<110000000) { similarityPtr[faceIndex].similarity = 1 - (similarityPtr[faceIndex].similarity-myMin) / (myMax-myMin); } else { similarityPtr[faceIndex].similarity = 0.0; } //similarityPtr[faceIndex].similarity = 1 - (similarityPtr[faceIndex].similarity-myMin) / (myMax-myMin); similarityPtr[faceIndex].fileName = gc_sampleFileName[faceIndex]; } TIMELOG("End FaceRecognition"); } extern "C" void _declspec(dllexport) FreeData() { for (int i=0;i<gi_sampleCount;i++) { delete []gc_sampleFileName[i]; } delete []gc_sampleFileName; delete meanVectorPtr; delete trainedEigenSpaceMatPtr; delete signatureFaceDBPtr; } //end
[ "shenbinsc@cbf8b9f2-3a65-11de-be05-5f7a86268029" ]
[ [ [ 1, 439 ] ] ]
ff2bbf9441ac979f098aeea42053183eb668d008
e2e49023f5a82922cb9b134e93ae926ed69675a1
/tools/aoslcpp/source/aosl/event_input.cpp
4e9a4abd1f0e5579b2851329b6042b68c7aaff49
[]
no_license
invy/mjklaim-freewindows
c93c867e93f0e2fe1d33f207306c0b9538ac61d6
30de8e3dfcde4e81a57e9059dfaf54c98cc1135b
refs/heads/master
2021-01-10T10:21:51.579762
2011-12-12T18:56:43
2011-12-12T18:56:43
54,794,395
1
0
null
null
null
null
UTF-8
C++
false
false
5,835
cpp
// Copyright (C) 2005-2010 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema // to C++ data binding compiler, in the Proprietary License mode. // You should have received a proprietary license from Code Synthesis // Tools CC prior to generating this code. See the license text for // conditions. // // Begin prologue. // #define AOSLCPP_SOURCE // // End prologue. #include <xsd/cxx/pre.hxx> #include "aosl/event_input.hpp" #include <xsd/cxx/xml/dom/wildcard-source.hxx> #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> #include <xsd/cxx/tree/comparison-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; static const ::xsd::cxx::tree::comparison_plate< 0, char > comparison_plate_init; } namespace aosl { // Event_input // Event_input:: Event_input (const MoveType& move, const KeyType& key, const ValueType& value) : ::aosl::Event_input_base (move), key_ (key, ::xml_schema::Flags (), this), value_ (value, ::xml_schema::Flags (), this) { } Event_input:: Event_input (const Event_input& x, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::aosl::Event_input_base (x, f, c), key_ (x.key_, f, this), value_ (x.value_, f, this) { } Event_input:: Event_input (const ::xercesc::DOMElement& e, ::xml_schema::Flags f, ::xml_schema::Container* c) : ::aosl::Event_input_base (e, f | ::xml_schema::Flags::base, c), key_ (f, this), value_ (f, this) { if ((f & ::xml_schema::Flags::base) == 0) { ::xsd::cxx::xml::dom::parser< char > p (e, false, true); this->parse (p, f); } } void Event_input:: parse (::xsd::cxx::xml::dom::parser< char >& p, ::xml_schema::Flags f) { this->::aosl::Event_input_base::parse (p, f); p.reset_attributes (); while (p.more_attributes ()) { const ::xercesc::DOMAttr& i (p.next_attribute ()); const ::xsd::cxx::xml::qualified_name< char > n ( ::xsd::cxx::xml::dom::name< char > (i)); if (n.name () == "key" && n.namespace_ ().empty ()) { ::std::auto_ptr< KeyType > r ( KeyTraits::create (i, f, this)); this->key_.set (r); continue; } if (n.name () == "value" && n.namespace_ ().empty ()) { ::std::auto_ptr< ValueType > r ( ValueTraits::create (i, f, this)); this->value_.set (r); continue; } } if (!key_.present ()) { throw ::xsd::cxx::tree::expected_attribute< char > ( "key", ""); } if (!value_.present ()) { throw ::xsd::cxx::tree::expected_attribute< char > ( "value", ""); } } Event_input* Event_input:: _clone (::xml_schema::Flags f, ::xml_schema::Container* c) const { return new class Event_input (*this, f, c); } Event_input:: ~Event_input () { } static const ::xsd::cxx::tree::type_factory_initializer< 0, char, Event_input > _xsd_Event_input_type_factory_init ( "event_input", "artofsequence.org/aosl/1.0"); static const ::xsd::cxx::tree::comparison_initializer< 0, char, Event_input > _xsd_Event_input_comparison_init; bool operator== (const Event_input& x, const Event_input& y) { if (!(static_cast< const ::aosl::Event_input_base& > (x) == static_cast< const ::aosl::Event_input_base& > (y))) return false; if (!(x.key () == y.key ())) return false; if (!(x.value () == y.value ())) return false; return true; } bool operator!= (const Event_input& x, const Event_input& y) { return !(x == y); } } #include <ostream> #include <xsd/cxx/tree/std-ostream-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::std_ostream_plate< 0, char > std_ostream_plate_init; } namespace aosl { ::std::ostream& operator<< (::std::ostream& o, const Event_input& i) { o << static_cast< const ::aosl::Event_input_base& > (i); o << ::std::endl << "key: " << i.key (); o << ::std::endl << "value: " << i.value (); return o; } static const ::xsd::cxx::tree::std_ostream_initializer< 0, char, Event_input > _xsd_Event_input_std_ostream_init; } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace aosl { } #include <ostream> #include <xsd/cxx/tree/error-handler.hxx> #include <xsd/cxx/xml/dom/serialization-source.hxx> #include <xsd/cxx/tree/type-serializer-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_serializer_plate< 0, char > type_serializer_plate_init; } namespace aosl { void operator<< (::xercesc::DOMElement& e, const Event_input& i) { e << static_cast< const ::aosl::Event_input_base& > (i); // key // { ::xercesc::DOMAttr& a ( ::xsd::cxx::xml::dom::create_attribute ( "key", e)); a << i.key (); } // value // { ::xercesc::DOMAttr& a ( ::xsd::cxx::xml::dom::create_attribute ( "value", e)); a << i.value (); } } static const ::xsd::cxx::tree::type_serializer_initializer< 0, char, Event_input > _xsd_Event_input_type_serializer_init ( "event_input", "artofsequence.org/aosl/1.0"); } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
[ "klaim@localhost" ]
[ [ [ 1, 266 ] ] ]
940b104e52bd0a961d7806d55981ac6bad775a83
60b2972eb20ef17074b4cc1cedd3cbf60fa42f4b
/src/BoundedQueue.h
1ed4475e5fe2f2042548b4b2b8e4bab4ade8c600
[]
no_license
gregsymons/boundedqueuekata
af296cc1f1346bcf2ff61f47f12e519ad99c02aa
46dd773940db76b6ed2d53c88ee9c8babad7ea4f
refs/heads/master
2021-01-16T18:19:35.852008
2010-06-23T22:17:40
2010-06-23T22:17:40
690,271
0
1
null
null
null
null
UTF-8
C++
false
false
959
h
#ifndef __bounded_queue_h_ #define __bounded_queue_h_ #include <queue> #include "QueueControl.h" template <typename T> class BoundedQueue { public: BoundedQueue(QueueControl& producer, QueueControl& consumer, size_t bound = 100) : consumer(consumer), producer(producer), bound(bound) { producer.Resume(); consumer.Pause(); }; void enqueue(const T& item) { q.push(item); if (q.size() == 1) { consumer.Resume(); } if (q.size() > bound) { producer.Pause(); } }; const T& dequeue() { const T& item = q.front(); q.pop(); if (q.size() == 0) { consumer.Pause(); } return item; } private: QueueControl& consumer; QueueControl& producer; size_t bound; std::queue<T> q; }; #endif
[ "greg@Symons-Linux1.(none)" ]
[ [ [ 1, 50 ] ] ]
2cc5123394922003b0b4f27494e8f33fb9460cda
7b4c786d4258ce4421b1e7bcca9011d4eeb50083
/Learning OpenCV/Chapter 6 - Image Transforms/Ch6_Test_Convolution.cpp
e309329a36e9dac57893447a9e5bca47ee0c9347
[]
no_license
lzq123218/guoyishi-works
dbfa42a3e2d3bd4a984a5681e4335814657551ef
4e78c8f2e902589c3f06387374024225f52e5a92
refs/heads/master
2021-12-04T11:11:32.639076
2011-05-30T14:12:43
2011-05-30T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,602
cpp
//////////////////////////////////////////// // Date: 2009-11-05 // Author: Yishi Guo // Chapter: 6 Image Transforms // Content: cvFilter2D //////////////////////////////////////////// #include "cv.h" #include "highgui.h" #include <iostream.h> void output_mat( CvMat* mat ) { int rows = mat->rows; int cols = mat->cols; int i, j; for ( i = 0; i < rows; ++i ) { for ( j = 0; j < cols; ++j ) { cout << cvmGet( mat, i, j ) << " "; } cout << endl; } } int main( int argc, char** argv ) { if ( argc < 2 ) { return -1; } else { // Get Martix of Kernel // CvMat *kernel = cvCreateMat( 3, 3, CV_32FC1 ); cvZero( kernel ); // For debug // output_mat( kernel ); cvmSet( kernel, 1, 0, 1 ); cvmSet( kernel, 1, 2, -1); // For debug // output_mat( kernel ); // Get Image // IplImage* src = cvLoadImage( argv[1], CV_LOAD_IMAGE_GRAYSCALE ); if ( !src ) { return -1; } IplImage* dst = cvCreateImage( cvGetSize(src), src->depth, src->nChannels ); cvFilter2D( src, dst, kernel ); const char* src_window_name = "Ch6 Test Convolution src"; const char* dst_window_name = "Ch6 Test Convolution dst"; cvNamedWindow( src_window_name, CV_WINDOW_AUTOSIZE ); cvNamedWindow( dst_window_name, CV_WINDOW_AUTOSIZE ); cvShowImage( src_window_name, src ); cvShowImage( dst_window_name, dst ); cvWaitKey(0); cvReleaseMat( &kernel ); cvReleaseImage( &src ); cvReleaseImage( &dst ); cvDestroyWindow( src_window_name ); cvDestroyWindow( dst_window_name ); } return 0; }
[ "baicaibang@70501136-4834-11de-8855-c187e5f49513" ]
[ [ [ 1, 69 ] ] ]
5bbbc1b8de0788a652cf0b768366ab0bda008179
1e976ee65d326c2d9ed11c3235a9f4e2693557cf
/VariousPage.cpp
03a5f7f0fe7aed8621a997dcd18bfa0f5d03d0f9
[]
no_license
outcast1000/Jaangle
062c7d8d06e058186cb65bdade68a2ad8d5e7e65
18feb537068f1f3be6ecaa8a4b663b917c429e3d
refs/heads/master
2020-04-08T20:04:56.875651
2010-12-25T10:44:38
2010-12-25T10:44:38
19,334,292
3
0
null
null
null
null
UTF-8
C++
false
false
1,423
cpp
// /* // * // * Copyright (C) 2003-2010 Alexandros Economou // * // * This file is part of Jaangle (http://www.jaangle.com) // * // * This Program is free software; you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation; either version 2, or (at your option) // * any later version. // * // * This Program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with GNU Make; see the file COPYING. If not, write to // * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. // * http://www.gnu.org/copyleft/gpl.html // * // */ #include "stdafx.h" #include "TeenSpirit.h" #include "VariousPage.h" // CVariousPage dialog IMPLEMENT_DYNAMIC(CVariousPage, CPropertyPage) CVariousPage::CVariousPage() : CPropertyPage(CVariousPage::IDD) { } CVariousPage::~CVariousPage() { } void CVariousPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CVariousPage, CPropertyPage) END_MESSAGE_MAP() // CVariousPage message handlers
[ "outcast1000@dc1b949e-fa36-4f9e-8e5c-de004ec35678" ]
[ [ [ 1, 53 ] ] ]
118102a3a8d303e17c9fcf697ba38fec910cce40
1dba10648f60dea02c9be242c668f3488ae8dec4
/program/src/preview_mgr.h
152d01dd6d076b38f284e34f42b456295b2459e4
[]
no_license
hateom/si-air
f02ffc8ba9fac9777d12a40627f06044c92865f0
2094c98a04a6785078b4c8bcded8f8b4450c8b92
refs/heads/master
2021-01-15T17:42:12.887029
2007-01-21T17:48:48
2007-01-21T17:48:48
32,139,237
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,793
h
/******************************************************************** Projekt z przedmiotu : Sztuczna Inteligencja i Sensoryka stworzono: 17:12:2006 16:51 plik: preview_mgr autorzy: Tomasz Huczek, Andrzej Jasiński cel: *********************************************************************/ #ifndef __PREVIEW_MGR_H__ #define __PREVIEW_MGR_H__ ////////////////////////////////////////////////////////////////////////// #include <qobject.h> #include <vector> #include "prevform.h" #include "../../modules/module_base/src/types.h" ////////////////////////////////////////////////////////////////////////// /// makro ulatwiajace korzystanie z obiektu globalnego #define sPreviewMgr PreviewMgr::singleton() ////////////////////////////////////////////////////////////////////////// /// klasa zarzadzajaca oknami podgladu class PreviewMgr: public QObject { Q_OBJECT public: PreviewMgr(); ~PreviewMgr(); /// rejestruj okno podgladu /// \return id okna podgladu int register_preview(); /// renderuj ramke obrazu int render_frame( int preview, frame_data * frame ); /// zamknij okno podgladu int close_preview( int preview ); /// zamknij wszytkie okna podgladu int close_all(); void show_window( int win, bool on_off ); static PreviewMgr * singleton(); void reset_positions(); public slots: void in_mouse_select( int sx, int sy, int sw, int sh ); void preview_closed( int id ); signals: void mouse_select( int sx, int sy, int sw, int sh ); void preview_closed(); private: void set_win_pos( PrevForm * prv ); std::vector<PrevForm*> prev_list; int visible; }; ////////////////////////////////////////////////////////////////////////// #endif // __PREVIEW_MGR_H__
[ "tomasz.huczek@9b5b1781-be22-0410-ac8e-a76ce1d23082" ]
[ [ [ 1, 73 ] ] ]
ca03bb352981689bfdd67b13ea7650d8b2deacea
ad8046a7c792e31fab898fa13a7693ff34ef2b83
/eFilm/CustomeMessageExample/eFilmHISRISInterface/StdAfx.cpp
aad3d299001cd15ee877a3bf1e9ad0f04fc75431
[]
no_license
alibinjamil/datamedris
df5f205775e78b76f15155c27e316f81beba1660
3f4711ef3c43e21870261bfbcab7fbafd369e114
refs/heads/master
2016-08-12T06:06:00.915112
2010-12-22T08:47:14
2010-12-22T08:47:14
44,970,197
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
// stdafx.cpp : source file that includes just the standard includes // eFilmHISRISInterface.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ [ [ 1, 8 ] ] ]
5699b666a9611841c8a2c94d109aa27015adbd3f
3ec03fa7bb038ea10801d09a685b9561f827928b
/js_hotkey/stdafx.cpp
c9ade1d4a7575573993336ff216bfcb69d4913fa
[]
no_license
jbreams/njord
e2354f2013af0d86390ae7af99a419816ee417cb
ef7ff45fa4882fe8d2c6cabfa7691e2243fe8341
refs/heads/master
2021-01-24T17:56:32.048502
2009-12-15T18:57:32
2009-12-15T18:57:32
38,331,688
1
0
null
null
null
null
UTF-8
C++
false
false
296
cpp
// stdafx.cpp : source file that includes just the standard includes // js_hotkey.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "jreams@1c42f586-7543-11de-ba67-499d525147dd" ]
[ [ [ 1, 8 ] ] ]
eb542b221235759c97abbc60af57e90129ccfdda
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/mpl/map/aux_/at_impl.hpp
f9d522fce2a78ed62e7f278692abd388694ccf7f
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
3,623
hpp
#ifndef BOOST_MPL_MAP_AUX_AT_IMPL_HPP_INCLUDED #define BOOST_MPL_MAP_AUX_AT_IMPL_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2003-2004 // Copyright David Abrahams 2003-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/boost/boost/boost/mpl/map/aux_/at_impl.hpp,v $ // $Date: 2005/12/05 17:59:21 $ // $Revision: 1.7 $ #include <boost/mpl/at_fwd.hpp> #include <boost/mpl/long.hpp> #include <boost/mpl/map/aux_/tag.hpp> #include <boost/mpl/aux_/order_impl.hpp> #include <boost/mpl/aux_/overload_names.hpp> #include <boost/mpl/aux_/type_wrapper.hpp> #include <boost/mpl/aux_/ptr_to_ref.hpp> #include <boost/mpl/aux_/static_cast.hpp> #include <boost/mpl/aux_/config/typeof.hpp> #include <boost/mpl/aux_/config/ctps.hpp> #if !defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES) # include <boost/mpl/eval_if.hpp> # include <boost/mpl/pair.hpp> # include <boost/mpl/void.hpp> # include <boost/mpl/aux_/config/static_constant.hpp> #endif namespace boost { namespace mpl { #if defined(BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES) template< typename Map, typename Key > struct m_at { typedef aux::type_wrapper<Key> key_; typedef __typeof__( BOOST_MPL_AUX_OVERLOAD_CALL_VALUE_BY_KEY( Map , BOOST_MPL_AUX_STATIC_CAST(key_*, 0) ) ) type; }; template<> struct at_impl< aux::map_tag > { template< typename Map, typename Key > struct apply : aux::wrapped_type< typename m_at< Map , Key >::type > { }; }; // agurt 31/jan/04: two-step implementation for the sake of GCC 3.x template< typename Map, long order > struct item_by_order_impl { typedef __typeof__( BOOST_MPL_AUX_OVERLOAD_CALL_ITEM_BY_ORDER( Map , BOOST_MPL_AUX_STATIC_CAST(long_<order>*, 0) ) ) type; }; template< typename Map, long order > struct item_by_order : aux::wrapped_type< typename item_by_order_impl<Map,order>::type > { }; #else // BOOST_MPL_CFG_TYPEOF_BASED_SEQUENCES # if !defined(BOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION) template< typename Map, long n > struct m_at { typedef void_ type; }; # else template< long n > struct m_at_impl { template< typename Map > struct result_ { typedef void_ type; }; }; template< typename Map, long n > struct m_at { typedef typename m_at_impl<n>::result_<Map>::type type; }; # endif template<> struct at_impl< aux::map_tag > { template< typename Map, typename Key > struct apply { typedef typename m_at< Map, (x_order_impl<Map,Key>::value - 2) >::type item_; typedef typename eval_if< is_void_<item_> , void_ , second<item_> >::type type; }; }; template< typename Map, long order > struct is_item_masked { BOOST_STATIC_CONSTANT(bool, value = sizeof( BOOST_MPL_AUX_OVERLOAD_CALL_IS_MASKED( Map , BOOST_MPL_AUX_STATIC_CAST(long_<order>*, 0) ) ) == sizeof(aux::yes_tag) ); }; template< typename Map, long order > struct item_by_order { typedef typename eval_if_c< is_item_masked<Map,order>::value , void_ , m_at<Map,(order - 2)> >::type type; }; #endif }} #endif // BOOST_MPL_SET_AUX_AT_IMPL_HPP_INCLUDED
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 144 ] ] ]
8a92c4f9f19ed6b7f8e06fbfd06516cd2a965cab
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/boost/multi_index/hashed_index.hpp
58e6e56b191d5f281613a932f87afd0011f51a83
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
ISO-8859-1
C++
false
false
31,048
hpp
/* Copyright 2003-2007 Joaquín M López Muñoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * See http://www.boost.org/libs/multi_index for library home page. */ #ifndef BOOST_MULTI_INDEX_HASHED_INDEX_HPP #define BOOST_MULTI_INDEX_HASHED_INDEX_HPP #if defined(_MSC_VER)&&(_MSC_VER>=1200) #pragma once #endif #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <algorithm> #include <boost/call_traits.hpp> #include <boost/detail/allocator_utilities.hpp> #include <boost/detail/no_exceptions_support.hpp> #include <boost/detail/workaround.hpp> #include <boost/limits.hpp> #include <boost/mpl/push_front.hpp> #include <boost/multi_index/detail/access_specifier.hpp> #include <boost/multi_index/detail/auto_space.hpp> #include <boost/multi_index/detail/bucket_array.hpp> #include <boost/multi_index/detail/hash_index_iterator.hpp> #include <boost/multi_index/detail/modify_key_adaptor.hpp> #include <boost/multi_index/detail/safe_ctr_proxy.hpp> #include <boost/multi_index/detail/safe_mode.hpp> #include <boost/multi_index/detail/scope_guard.hpp> #include <boost/multi_index/hashed_index_fwd.hpp> #include <boost/tuple/tuple.hpp> #include <cstddef> #include <functional> #include <utility> #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) #include <boost/serialization/nvp.hpp> #endif #if defined(BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING) #define BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT \ detail::scope_guard BOOST_JOIN(check_invariant_,__LINE__)= \ detail::make_obj_guard(*this,&hashed_index::check_invariant_); \ BOOST_JOIN(check_invariant_,__LINE__).touch(); #else #define BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT #endif namespace boost{ namespace multi_index{ namespace detail{ /* hashed_index adds a layer of hashed indexing to a given Super */ /* Most of the implementation of unique and non-unique indices is * shared. We tell from one another on instantiation time by using * these tags. */ struct hashed_unique_tag{}; struct hashed_non_unique_tag{}; template< typename KeyFromValue,typename Hash,typename Pred, typename SuperMeta,typename TagList,typename Category > class hashed_index: BOOST_MULTI_INDEX_PROTECTED_IF_MEMBER_TEMPLATE_FRIENDS SuperMeta::type #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) #if BOOST_WORKAROUND(BOOST_MSVC,<1300) ,public safe_ctr_proxy_impl< hashed_index_iterator< hashed_index_node<typename SuperMeta::type::node_type>, bucket_array<typename SuperMeta::type::final_allocator_type> >, hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category> > #else ,public safe_mode::safe_container< hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category> > #endif #endif { #if defined(BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING)&&\ BOOST_WORKAROUND(__MWERKS__,<=0x3003) /* The "ISO C++ Template Parser" option in CW8.3 has a problem with the * lifetime of const references bound to temporaries --precisely what * scopeguards are. */ #pragma parse_mfunc_templ off #endif typedef typename SuperMeta::type super; protected: typedef hashed_index_node< typename super::node_type> node_type; typedef bucket_array< typename super::final_allocator_type> bucket_array_type; public: /* types */ typedef typename KeyFromValue::result_type key_type; typedef typename node_type::value_type value_type; typedef KeyFromValue key_from_value; typedef Hash hasher; typedef Pred key_equal; typedef tuple<std::size_t, key_from_value,hasher,key_equal> ctor_args; typedef typename super::final_allocator_type allocator_type; typedef typename allocator_type::pointer pointer; typedef typename allocator_type::const_pointer const_pointer; typedef typename allocator_type::reference reference; typedef typename allocator_type::const_reference const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) #if BOOST_WORKAROUND(BOOST_MSVC,<1300) typedef safe_mode::safe_iterator< hashed_index_iterator< node_type,bucket_array_type>, safe_ctr_proxy< hashed_index_iterator< node_type,bucket_array_type> > > iterator; #else typedef safe_mode::safe_iterator< hashed_index_iterator< node_type,bucket_array_type>, hashed_index> iterator; #endif #else typedef hashed_index_iterator< node_type,bucket_array_type> iterator; #endif typedef iterator const_iterator; typedef iterator local_iterator; typedef const_iterator const_local_iterator; typedef TagList tag_list; protected: typedef typename super::final_node_type final_node_type; typedef tuples::cons< ctor_args, typename super::ctor_args_list> ctor_args_list; typedef typename mpl::push_front< typename super::index_type_list, hashed_index>::type index_type_list; typedef typename mpl::push_front< typename super::iterator_type_list, iterator>::type iterator_type_list; typedef typename mpl::push_front< typename super::const_iterator_type_list, const_iterator>::type const_iterator_type_list; typedef typename super::copy_map_type copy_map_type; #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) typedef typename super::index_saver_type index_saver_type; typedef typename super::index_loader_type index_loader_type; #endif private: #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) #if BOOST_WORKAROUND(BOOST_MSVC,<1300) typedef safe_ctr_proxy_impl< hashed_index_iterator< node_type, bucket_array_type>, hashed_index> safe_super; #else typedef safe_mode::safe_container< hashed_index> safe_super; #endif #endif typedef typename call_traits<value_type>::param_type value_param_type; typedef typename call_traits< key_type>::param_type key_param_type; public: /* construct/destroy/copy * Default and copy ctors are in the protected section as indices are * not supposed to be created on their own. No range ctor either. */ hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& operator=( const hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& x) { this->final()=x.final(); return *this; } allocator_type get_allocator()const { return this->final().get_allocator(); } /* size and capacity */ bool empty()const{return this->final_empty_();} size_type size()const{return this->final_size_();} size_type max_size()const{return this->final_max_size_();} /* iterators */ iterator begin() { return make_iterator( node_type::from_impl(buckets.at(first_bucket)->next())); } const_iterator begin()const { return make_iterator( node_type::from_impl(buckets.at(first_bucket)->next())); } iterator end(){return make_iterator(header());} const_iterator end()const{return make_iterator(header());} /* modifiers */ std::pair<iterator,bool> insert(value_param_type x) { BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; std::pair<final_node_type*,bool> p=this->final_insert_(x); return std::pair<iterator,bool>(make_iterator(p.first),p.second); } iterator insert(iterator position,value_param_type x) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_IS_OWNER(position,*this); BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; std::pair<final_node_type*,bool> p=this->final_insert_( x,static_cast<final_node_type*>(position.get_node())); return make_iterator(p.first); } template<typename InputIterator> void insert(InputIterator first,InputIterator last) { BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; iterator hint=end(); for(;first!=last;++first)hint=insert(hint,*first); } iterator erase(iterator position) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_DEREFERENCEABLE_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_IS_OWNER(position,*this); BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; this->final_erase_(static_cast<final_node_type*>(position++.get_node())); return position; } size_type erase(key_param_type k) { BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; size_type s=0; std::size_t buc=buckets.position(hash(k)); hashed_index_node_impl* x=buckets.at(buc); hashed_index_node_impl* y=x->next(); while(y!=x){ if(eq(k,key(node_type::from_impl(y)->value()))){ bool b; do{ hashed_index_node_impl* z=y->next(); b=z!=x&&eq( key(node_type::from_impl(y)->value()), key(node_type::from_impl(z)->value())); this->final_erase_( static_cast<final_node_type*>(node_type::from_impl(y))); y=z; ++s; }while(b); break; } y=y->next(); } return s; } iterator erase(iterator first,iterator last) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(first); BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(last); BOOST_MULTI_INDEX_CHECK_IS_OWNER(first,*this); BOOST_MULTI_INDEX_CHECK_IS_OWNER(last,*this); BOOST_MULTI_INDEX_CHECK_VALID_RANGE(first,last); BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; while(first!=last){ first=erase(first); } return first; } bool replace(iterator position,value_param_type x) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_DEREFERENCEABLE_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_IS_OWNER(position,*this); BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; return this->final_replace_( x,static_cast<final_node_type*>(position.get_node())); } template<typename Modifier> bool modify(iterator position,Modifier mod) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_DEREFERENCEABLE_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_IS_OWNER(position,*this); BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) /* MSVC++ 6.0 optimizer on safe mode code chokes if this * this is not added. Left it for all compilers as it does no * harm. */ position.detach(); #endif return this->final_modify_( mod,static_cast<final_node_type*>(position.get_node())); } template<typename Modifier> bool modify_key(iterator position,Modifier mod) { BOOST_MULTI_INDEX_CHECK_VALID_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_DEREFERENCEABLE_ITERATOR(position); BOOST_MULTI_INDEX_CHECK_IS_OWNER(position,*this); BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; return modify( position,modify_key_adaptor<Modifier,value_type,KeyFromValue>(mod,key)); } void clear() { BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; this->final_clear_(); } void swap(hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& x) { BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; this->final_swap_(x.final()); } /* observers */ key_from_value key_extractor()const{return key;} hasher hash_function()const{return hash;} key_equal key_eq()const{return eq;} /* lookup */ /* Internally, these ops rely on const_iterator being the same * type as iterator. */ template<typename CompatibleKey> iterator find(const CompatibleKey& k)const { return find(k,hash,eq); } template< typename CompatibleKey,typename CompatibleHash,typename CompatiblePred > iterator find( const CompatibleKey& k, const CompatibleHash& hash,const CompatiblePred& eq)const { std::size_t buc=buckets.position(hash(k)); hashed_index_node_impl* x=buckets.at(buc); hashed_index_node_impl* y=x->next(); while(y!=x){ if(eq(k,key(node_type::from_impl(y)->value()))){ return make_iterator(node_type::from_impl(y)); } y=y->next(); } return end(); } template<typename CompatibleKey> size_type count(const CompatibleKey& k)const { return count(k,hash,eq); } template< typename CompatibleKey,typename CompatibleHash,typename CompatiblePred > size_type count( const CompatibleKey& k, const CompatibleHash& hash,const CompatiblePred& eq)const { size_type res=0; std::size_t buc=buckets.position(hash(k)); hashed_index_node_impl* x=buckets.at(buc); hashed_index_node_impl* y=x->next(); while(y!=x){ if(eq(k,key(node_type::from_impl(y)->value()))){ do{ ++res; y=y->next(); }while(y!=x&&eq(k,key(node_type::from_impl(y)->value()))); break; } y=y->next(); } return res; } template<typename CompatibleKey> std::pair<iterator,iterator> equal_range(const CompatibleKey& k)const { return equal_range(k,hash,eq); } template< typename CompatibleKey,typename CompatibleHash,typename CompatiblePred > std::pair<iterator,iterator> equal_range( const CompatibleKey& k, const CompatibleHash& hash,const CompatiblePred& eq)const { std::size_t buc=buckets.position(hash(k)); hashed_index_node_impl* x=buckets.at(buc); hashed_index_node_impl* y=x->next(); while(y!=x){ if(eq(k,key(node_type::from_impl(y)->value()))){ hashed_index_node_impl* y0=y; do{ y=y->next(); }while(y!=x&&eq(k,key(node_type::from_impl(y)->value()))); if(y==x){ do{ ++y; }while(y==y->next()); y=y->next(); } return std::pair<iterator,iterator>( make_iterator(node_type::from_impl(y0)), make_iterator(node_type::from_impl(y))); } y=y->next(); } return std::pair<iterator,iterator>(end(),end()); } /* bucket interface */ size_type bucket_count()const{return buckets.size();} size_type max_bucket_count()const{return static_cast<size_type>(-1);} size_type bucket_size(size_type n)const { size_type res=0; hashed_index_node_impl* x=buckets.at(n); hashed_index_node_impl* y=x->next(); while(y!=x){ ++res; y=y->next(); } return res; } size_type bucket(key_param_type k)const { return buckets.position(hash(k)); } local_iterator begin(size_type n) { return const_cast<const hashed_index*>(this)->begin(n); } const_local_iterator begin(size_type n)const { hashed_index_node_impl* x=buckets.at(n); hashed_index_node_impl* y=x->next(); if(y==x)return end(); return make_iterator(node_type::from_impl(y)); } local_iterator end(size_type n) { return const_cast<const hashed_index*>(this)->end(n); } const_local_iterator end(size_type n)const { hashed_index_node_impl* x=buckets.at(n); if(x==x->next())return end(); do{ ++x; }while(x==x->next()); return make_iterator(node_type::from_impl(x->next())); } /* hash policy */ float load_factor()const{return static_cast<float>(size())/bucket_count();} float max_load_factor()const{return mlf;} void max_load_factor(float z){mlf=z;calculate_max_load();} void rehash(size_type n) { BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT; if(size()<max_load&&n<=bucket_count())return; size_type bc =(std::numeric_limits<size_type>::max)(); float fbc=static_cast<float>(1+size()/mlf); if(bc>fbc){ bc=static_cast<size_type>(fbc); if(bc<n)bc=n; } unchecked_rehash(bc); } BOOST_MULTI_INDEX_PROTECTED_IF_MEMBER_TEMPLATE_FRIENDS: hashed_index(const ctor_args_list& args_list,const allocator_type& al): super(args_list.get_tail(),al), key(tuples::get<1>(args_list.get_head())), hash(tuples::get<2>(args_list.get_head())), eq(tuples::get<3>(args_list.get_head())), buckets(al,header()->impl(),tuples::get<0>(args_list.get_head())), mlf(1.0), first_bucket(buckets.size()) { calculate_max_load(); } hashed_index( const hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& x): super(x), #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) safe_super(), #endif key(x.key), hash(x.hash), eq(x.eq), buckets(x.get_allocator(),header()->impl(),x.buckets.size()), mlf(x.mlf), max_load(x.max_load), first_bucket(x.first_bucket) { /* Copy ctor just takes the internal configuration objects from x. The rest * is done in subsequent call to copy_(). */ } ~hashed_index() { /* the container is guaranteed to be empty by now */ } #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) iterator make_iterator(node_type* node) { return iterator(node,&buckets,this); } const_iterator make_iterator(node_type* node)const { return const_iterator( node, &const_cast<bucket_array_type&>(buckets), const_cast<hashed_index*>(this)); } #else iterator make_iterator(node_type* node) { return iterator(node,&buckets); } const_iterator make_iterator(node_type* node)const { return const_iterator(node,&const_cast<bucket_array_type&>(buckets)); } #endif void copy_( const hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& x, const copy_map_type& map) { for(hashed_index_node_impl* begin_org=x.buckets.begin(), * begin_cpy=buckets.begin(), * end_org=x.buckets.end(); begin_org!=end_org;++begin_org,++begin_cpy){ hashed_index_node_impl* next_org=begin_org->next(); hashed_index_node_impl* cpy=begin_cpy; while(next_org!=begin_org){ cpy->next()= static_cast<node_type*>( map.find( static_cast<final_node_type*>( node_type::from_impl(next_org))))->impl(); next_org=next_org->next(); cpy=cpy->next(); } cpy->next()=begin_cpy; } super::copy_(x,map); } node_type* insert_(value_param_type v,node_type* x) { reserve(size()+1); std::size_t buc=find_bucket(v); hashed_index_node_impl* pos=buckets.at(buc); if(!link_point(v,pos,Category()))return node_type::from_impl(pos); node_type* res=static_cast<node_type*>(super::insert_(v,x)); if(res==x){ link(x,pos); if(first_bucket>buc)first_bucket=buc; } return res; } node_type* insert_(value_param_type v,node_type* position,node_type* x) { reserve(size()+1); std::size_t buc=find_bucket(v); hashed_index_node_impl* pos=buckets.at(buc); if(!link_point(v,pos,Category()))return node_type::from_impl(pos); node_type* res=static_cast<node_type*>(super::insert_(v,position,x)); if(res==x){ link(x,pos); if(first_bucket>buc)first_bucket=buc; } return res; } void erase_(node_type* x) { unlink(x); first_bucket=buckets.first_nonempty(first_bucket); super::erase_(x); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) detach_iterators(x); #endif } void delete_all_nodes_() { for(hashed_index_node_impl* x=buckets.begin(),*x_end=buckets.end(); x!=x_end;++x){ hashed_index_node_impl* y=x->next(); while(y!=x){ hashed_index_node_impl* z=y->next(); this->final_delete_node_( static_cast<final_node_type*>(node_type::from_impl(y))); y=z; } } } void clear_() { super::clear_(); buckets.clear(); first_bucket=buckets.size(); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) safe_super::detach_dereferenceable_iterators(); #endif } void swap_( hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& x) { std::swap(key,x.key); std::swap(hash,x.hash); std::swap(eq,x.eq); buckets.swap(x.buckets); std::swap(mlf,x.mlf); std::swap(max_load,x.max_load); std::swap(first_bucket,x.first_bucket); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) safe_super::swap(x); #endif super::swap_(x); } bool replace_(value_param_type v,node_type* x) { if(eq(key(v),key(x->value()))){ return super::replace_(v,x); } hashed_index_node_impl* y=prev(x); unlink_next(y); BOOST_TRY{ std::size_t buc=find_bucket(v); hashed_index_node_impl* pos=buckets.at(buc); if(link_point(v,pos,Category())&&super::replace_(v,x)){ link(x,pos); if(first_bucket>buc){ first_bucket=buc; } else if(first_bucket<buc){ first_bucket=buckets.first_nonempty(first_bucket); } return true; } link(x,y); return false; } BOOST_CATCH(...){ link(x,y); BOOST_RETHROW; } BOOST_CATCH_END } bool modify_(node_type* x) { unlink(x); std::size_t buc; hashed_index_node_impl* pos; BOOST_TRY { buc=find_bucket(x->value()); pos=buckets.at(buc); if(!link_point(x->value(),pos,Category())){ first_bucket=buckets.first_nonempty(first_bucket); super::erase_(x); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) detach_iterators(x); #endif return false; } } BOOST_CATCH(...){ first_bucket=buckets.first_nonempty(first_bucket); super::erase_(x); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) detach_iterators(x); #endif BOOST_RETHROW; } BOOST_CATCH_END BOOST_TRY{ if(super::modify_(x)){ link(x,pos); if(first_bucket>buc){ first_bucket=buc; } else if(first_bucket<buc){ first_bucket=buckets.first_nonempty(first_bucket); } return true; } first_bucket=buckets.first_nonempty(first_bucket); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) detach_iterators(x); #endif return false; } BOOST_CATCH(...){ first_bucket=buckets.first_nonempty(first_bucket); #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) detach_iterators(x); #endif BOOST_RETHROW; } BOOST_CATCH_END } #if !defined(BOOST_MULTI_INDEX_DISABLE_SERIALIZATION) /* serialization */ template<typename Archive> void save_( Archive& ar,const unsigned int version,const index_saver_type& sm)const { ar<<serialization::make_nvp("position",buckets); super::save_(ar,version,sm); } template<typename Archive> void load_(Archive& ar,const unsigned int version,const index_loader_type& lm) { ar>>serialization::make_nvp("position",buckets); super::load_(ar,version,lm); } #endif #if defined(BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING) /* invariant stuff */ bool invariant_()const { if(size()==0||begin()==end()){ if(size()!=0||begin()!=end())return false; } else{ size_type s0=0; for(const_iterator it=begin(),it_end=end();it!=it_end;++it,++s0){} if(s0!=size())return false; size_type s1=0; for(size_type buc=0;buc<bucket_count();++buc){ size_type ss1=0; for(const_local_iterator it=begin(buc),it_end=end(buc); it!=it_end;++it,++ss1){ if(find_bucket(*it)!=buc)return false; } if(ss1!=bucket_size(buc))return false; s1+=ss1; } if(s1!=size())return false; } if(first_bucket!=buckets.first_nonempty(0))return false; return super::invariant_(); } /* This forwarding function eases things for the boost::mem_fn construct * in BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT. Actually, * final_check_invariant is already an inherited member function of index. */ void check_invariant_()const{this->final_check_invariant_();} #endif private: node_type* header()const{return this->final_header();} std::size_t find_bucket(value_param_type v)const { return bucket(key(v)); } bool link_point( value_param_type v,hashed_index_node_impl*& pos,hashed_unique_tag) { hashed_index_node_impl* x=pos->next(); while(x!=pos){ if(eq(key(v),key(node_type::from_impl(x)->value()))){ pos=x; return false; } x=x->next(); } return true; } bool link_point( value_param_type v,hashed_index_node_impl*& pos,hashed_non_unique_tag) { hashed_index_node_impl* prev=pos; hashed_index_node_impl* x=pos->next(); while(x!=pos){ if(eq(key(v),key(node_type::from_impl(x)->value()))){ pos=prev; return true; } prev=x; x=x->next(); } return true; } void link(node_type* x,hashed_index_node_impl* pos) { hashed_index_node_impl::link(x->impl(),pos); }; void link(hashed_index_node_impl* x,hashed_index_node_impl* pos) { hashed_index_node_impl::link(x,pos); }; void unlink(node_type* x) { hashed_index_node_impl::unlink(x->impl()); }; static hashed_index_node_impl* prev(node_type* x) { return hashed_index_node_impl::prev(x->impl()); } static void unlink_next(hashed_index_node_impl* x) { hashed_index_node_impl::unlink_next(x); } void calculate_max_load() { float fml=static_cast<float>(mlf*bucket_count()); max_load=(std::numeric_limits<size_type>::max)(); if(max_load>fml)max_load=static_cast<size_type>(fml); } void reserve(size_type n) { if(n>max_load){ size_type bc =(std::numeric_limits<size_type>::max)(); float fbc=static_cast<float>(1+n/mlf); if(bc>fbc)bc =static_cast<size_type>(fbc); unchecked_rehash(bc); } } void unchecked_rehash(size_type n) { bucket_array_type buckets1(get_allocator(),header()->impl(),n); auto_space<std::size_t,allocator_type> hashes(get_allocator(),size()); std::size_t i=0; hashed_index_node_impl* x=buckets.begin(); hashed_index_node_impl* x_end=buckets.end(); for(;x!=x_end;++x){ hashed_index_node_impl* y=x->next(); while(y!=x){ hashes.data()[i++]=hash(key(node_type::from_impl(y)->value())); y=y->next(); } } i=0; x=buckets.begin(); for(;x!=x_end;++x){ hashed_index_node_impl* y=x->next(); while(y!=x){ hashed_index_node_impl* z=y->next(); std::size_t buc1=buckets1.position(hashes.data()[i++]); hashed_index_node_impl* x1=buckets1.at(buc1); link(y,x1); y=z; } } buckets.swap(buckets1); calculate_max_load(); first_bucket=buckets.first_nonempty(0); } #if defined(BOOST_MULTI_INDEX_ENABLE_SAFE_MODE) void detach_iterators(node_type* x) { iterator it=make_iterator(x); safe_mode::detach_equivalent_iterators(it); } #endif key_from_value key; hasher hash; key_equal eq; bucket_array_type buckets; float mlf; size_type max_load; std::size_t first_bucket; #if defined(BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING)&&\ BOOST_WORKAROUND(__MWERKS__,<=0x3003) #pragma parse_mfunc_templ reset #endif }; /* specialized algorithms */ template< typename KeyFromValue,typename Hash,typename Pred, typename SuperMeta,typename TagList,typename Category > void swap( hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& x, hashed_index<KeyFromValue,Hash,Pred,SuperMeta,TagList,Category>& y) { x.swap(y); } } /* namespace multi_index::detail */ /* sequenced index specifiers */ template<typename Arg1,typename Arg2,typename Arg3,typename Arg4> struct hashed_unique { typedef typename detail::hashed_index_args< Arg1,Arg2,Arg3,Arg4> index_args; typedef typename index_args::tag_list_type::type tag_list_type; typedef typename index_args::key_from_value_type key_from_value_type; typedef typename index_args::hash_type hash_type; typedef typename index_args::pred_type pred_type; template<typename Super> struct node_class { typedef detail::hashed_index_node<Super> type; }; template<typename SuperMeta> struct index_class { typedef detail::hashed_index< key_from_value_type,hash_type,pred_type, SuperMeta,tag_list_type,detail::hashed_unique_tag> type; }; }; template<typename Arg1,typename Arg2,typename Arg3,typename Arg4> struct hashed_non_unique { typedef typename detail::hashed_index_args< Arg1,Arg2,Arg3,Arg4> index_args; typedef typename index_args::tag_list_type::type tag_list_type; typedef typename index_args::key_from_value_type key_from_value_type; typedef typename index_args::hash_type hash_type; typedef typename index_args::pred_type pred_type; template<typename Super> struct node_class { typedef detail::hashed_index_node<Super> type; }; template<typename SuperMeta> struct index_class { typedef detail::hashed_index< key_from_value_type,hash_type,pred_type, SuperMeta,tag_list_type,detail::hashed_non_unique_tag> type; }; }; } /* namespace multi_index */ } /* namespace boost */ #undef BOOST_MULTI_INDEX_HASHED_INDEX_CHECK_INVARIANT #endif
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 1075 ] ] ]
ed8dcde754d68da7d4bf260fece4b15461c3b0d8
1b2f699e2299c66ef41e261ffe27bdf5602805f7
/tags/3.1.92/libs_air/jp/progression/core/includes/ButtonComp_contextMenu.inc
bd868d93ebf4efabd97f5be2badc4bc38ddade53
[]
no_license
Dsnoi/progression-flash
aefd0c9405f437f0afbc34a0e4566805a9d9c709
5472c983c4ddfed998a7852277d2e72ffbb9e2c6
refs/heads/master
2016-09-05T20:04:32.875776
2011-12-05T04:21:22
2011-12-05T04:21:22
39,943,479
0
0
null
null
null
null
UTF-8
C++
false
false
103
inc
private function _initContextMenu():void { } private function __disposeContextMenu():void { }
[ "niumjp@afee6dea-b6cd-11dd-893d-d98698f66bbf" ]
[ [ [ 1, 5 ] ] ]
5da4ef62506cb853bae78a494760e6dccbccc227
b14d5833a79518a40d302e5eb40ed5da193cf1b2
/cpp/extern/xercesc++/2.6.0/src/xercesc/validators/datatype/TimeDatatypeValidator.cpp
449a7453d394b1b0ed3434fe94398a150584ce2c
[ "Apache-2.0" ]
permissive
andyburke/bitflood
dcb3fb62dad7fa5e20cf9f1d58aaa94be30e82bf
fca6c0b635d07da4e6c7fbfa032921c827a981d6
refs/heads/master
2016-09-10T02:14:35.564530
2011-11-17T09:51:49
2011-11-17T09:51:49
2,794,411
1
0
null
null
null
null
UTF-8
C++
false
false
6,493
cpp
/* * Copyright 2001,2004 The Apache Software Foundation. * * 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. */ /* * $Id: TimeDatatypeValidator.cpp,v 1.15 2004/09/08 13:56:53 peiyongz Exp $ * $Log: TimeDatatypeValidator.cpp,v $ * Revision 1.15 2004/09/08 13:56:53 peiyongz * Apache License Version 2.0 * * Revision 1.14 2003/12/23 21:50:36 peiyongz * Absorb exception thrown in getCanonicalRepresentation and return 0, * only validate when required * * Revision 1.13 2003/12/19 23:02:25 cargilld * More memory management updates. * * Revision 1.12 2003/12/17 00:18:39 cargilld * Update to memory management so that the static memory manager (one used to call Initialize) is only for static data. * * Revision 1.11 2003/12/11 21:40:24 peiyongz * support for Canonical Representation for Datatype * * Revision 1.10 2003/11/28 18:53:07 peiyongz * Support for getCanonicalRepresentation * * Revision 1.9 2003/11/06 15:30:07 neilg * first part of PSVI/schema component model implementation, thanks to David Cargill. This covers setting the PSVIHandler on parser objects, as well as implementing XSNotation, XSSimpleTypeDefinition, XSIDCDefinition, and most of XSWildcard, XSComplexTypeDefinition, XSElementDeclaration, XSAttributeDeclaration and XSAttributeUse. * * Revision 1.8 2003/10/02 19:21:06 peiyongz * Implementation of Serialization/Deserialization * * Revision 1.7 2003/10/01 16:32:41 neilg * improve handling of out of memory conditions, bug #23415. Thanks to David Cargill. * * Revision 1.6 2003/08/14 03:00:11 knoaman * Code refactoring to improve performance of validation. * * Revision 1.5 2003/05/18 14:02:07 knoaman * Memory manager implementation: pass per instance manager. * * Revision 1.4 2003/05/15 18:53:27 knoaman * Partial implementation of the configurable memory manager. * * Revision 1.3 2002/12/18 14:17:55 gareth * Fix to bug #13438. When you eant a vector that calls delete[] on its members you should use RefArrayVectorOf. * * Revision 1.2 2002/11/04 14:53:28 tng * C++ Namespace Support. * * Revision 1.1.1.1 2002/02/01 22:22:42 peiyongz * sane_include * * Revision 1.3 2001/11/15 17:09:23 peiyongz * catch(...) only. (the invoker need to cath XMLException to display proper message) * * Revision 1.2 2001/11/14 22:02:25 peiyongz * rethrow exception with original error message. * * Revision 1.1 2001/11/07 19:18:52 peiyongz * DateTime Port * */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/validators/datatype/TimeDatatypeValidator.hpp> #include <xercesc/util/OutOfMemoryException.hpp> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // Constructors and Destructor // --------------------------------------------------------------------------- TimeDatatypeValidator::TimeDatatypeValidator(MemoryManager* const manager) :DateTimeValidator(0, 0, 0, DatatypeValidator::Time, manager) { setOrdered(XSSimpleTypeDefinition::ORDERED_PARTIAL); } TimeDatatypeValidator::TimeDatatypeValidator( DatatypeValidator* const baseValidator , RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager) :DateTimeValidator(baseValidator, facets, finalSet, DatatypeValidator::Time, manager) { init(enums, manager); } TimeDatatypeValidator::~TimeDatatypeValidator() {} DatatypeValidator* TimeDatatypeValidator::newInstance ( RefHashTableOf<KVStringPair>* const facets , RefArrayVectorOf<XMLCh>* const enums , const int finalSet , MemoryManager* const manager ) { return (DatatypeValidator*) new (manager) TimeDatatypeValidator(this, facets, enums, finalSet, manager); } // // caller need to release the date created here // XMLDateTime* TimeDatatypeValidator::parse(const XMLCh* const content, MemoryManager* const manager) { XMLDateTime *pRetDate = new (manager) XMLDateTime(content, manager); try { pRetDate->parseTime(); } catch(const OutOfMemoryException&) { throw; } catch (...) { delete pRetDate; throw; } return pRetDate; } void TimeDatatypeValidator::parse(XMLDateTime* const pDate) { pDate->parseTime(); } const XMLCh* TimeDatatypeValidator::getCanonicalRepresentation(const XMLCh* const rawData , MemoryManager* const memMgr , bool toValidate) const { MemoryManager* toUse = memMgr? memMgr : fMemoryManager; if (toValidate) { TimeDatatypeValidator* temp = (TimeDatatypeValidator*) this; try { temp->checkContent(rawData, 0, false, toUse); } catch (...) { return 0; } } try { XMLDateTime aDateTime(rawData, toUse); aDateTime.parseTime(); return aDateTime.getTimeCanonicalRepresentation(toUse); } catch (...) { return 0; } } /*** * Support for Serialization/De-serialization ***/ IMPL_XSERIALIZABLE_TOCREATE(TimeDatatypeValidator) void TimeDatatypeValidator::serialize(XSerializeEngine& serEng) { DateTimeValidator::serialize(serEng); } XERCES_CPP_NAMESPACE_END /** * End of file TimeDatatypeValidator::cpp */
[ [ [ 1, 197 ] ] ]
946e5a5e300287c6963c819be7f37066000f8ba4
b03c23324d8f048840ecf50875b05835dedc8566
/engin3d/src/Utility/Debug.h
ae0547519303df04c79ee1ce4d194a20e2fcf40c
[]
no_license
carlixyz/engin3d
901dc61adda54e6098a3ac6637029efd28dd768e
f0b671b1e75a02eb58a2c200268e539154cd2349
refs/heads/master
2018-01-08T16:49:50.439617
2011-06-16T00:13:26
2011-06-16T00:13:26
36,534,616
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
h
#ifndef MY_DEBUG_H #define MY_DEBUG_H // "arranged" By CarliXYZ taking lots of bits from here and there, too mixed up to say nothing // tip: the next lines are equivalent, just keeped for the taste of everyone // Debug.ToOutput() << something; // Debug::ToOutput() << something; // Debug() << something; #include <sstream> #include <windows.h> #include <fstream> class Debug { public: static Debug &ToOutput(void); // Use Debug::ToOuput() << something << etc << etc ; static std::fstream & ToFile(const char *FileName); // Use Debug::ToOuput( "FileName.txt" ) << something << etc ; static void ToOutput(const char *format, ...); // Use Debug::ToOuput( "something %i <%f> ", etc, etc ); static void ToMsgBox(const char *format, ...); // same as the last one but sending it to a Windows MessageBox template <class T> inline Debug &operator << (const T & t) // templates needs definitions in headers { static std::ostringstream oss; // create a stream oss << t; // insert value to stream OutputDebugString( oss.str().c_str() ); // Target Output stream return *this; } inline Debug &operator << (Debug &(*function)(Debug &dbgInstance)) { return function (*this); }// Modifiers implementions static Debug &Endl (Debug &dbgInstance); // Use Debug() << Debug::Endl << something << Debug::Endl ; // and so on.. }; #endif // MY_DEBUG_H // TO DO: Fix some acumulation Stream problem with << operator that repeats the last input // and Add some ToFile( name.xml, string, ...) Foo
[ [ [ 1, 40 ] ] ]
a1b5f2f9e945584ca844082b75aa728639547e99
073dfce42b384c9438734daa8ee2b575ff100cc9
/RCF/src/RCF/RCF_1.cpp
18b5b7242f02ede723216870533aee2e55d602c6
[]
no_license
r0ssar00/iTunesSpeechBridge
a489426bbe30ac9bf9c7ca09a0b1acd624c1d9bf
71a27a52e66f90ade339b2b8a7572b53577e2aaf
refs/heads/master
2020-12-24T17:45:17.838301
2009-08-24T22:04:48
2009-08-24T22:04:48
285,393
1
0
null
null
null
null
UTF-8
C++
false
false
426
cpp
//****************************************************************************** // RCF - Remote Call Framework // Copyright (c) 2005 - 2009, Jarl Lindrud. All rights reserved. // Consult your license for conditions of use. // Version: 1.1 // Contact: jarl.lindrud <at> gmail.com //****************************************************************************** #define RCF_CPP_WHICH_SECTION 1 #include "RCF.cpp"
[ [ [ 1, 11 ] ] ]