blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
08463b22d13e1beafa325fdb0e6ec98c1ea40edb
21ede326b6cfcf5347ca6772d392d3acca80cfa0
/chromeos/components/proximity_auth/webui/proximity_auth_ui.cc
5e26689f4242e3419fed7f6b8ec473984c6fbb88
[ "BSD-3-Clause" ]
permissive
csagan5/kiwi
6eaab0ab4db60468358291956506ad6f889401f8
eb2015c28925be91b4a3130b3c2bee2f5edc91de
refs/heads/master
2020-04-04T17:06:54.003121
2018-10-24T08:20:01
2018-10-24T08:20:01
156,107,399
2
0
null
null
null
null
UTF-8
C++
false
false
3,357
cc
proximity_auth_ui.cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chromeos/components/proximity_auth/webui/proximity_auth_ui.h" #include <memory> #include "chromeos/components/proximity_auth/webui/proximity_auth_webui_handler.h" #include "chromeos/components/proximity_auth/webui/url_constants.h" #include "chromeos/grit/chromeos_resources.h" #include "chromeos/services/device_sync/public/cpp/device_sync_client.h" #include "chromeos/services/multidevice_setup/public/mojom/constants.mojom.h" #include "components/grit/components_resources.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "content/public/browser/web_ui_data_source.h" #include "services/service_manager/public/cpp/connector.h" namespace proximity_auth { ProximityAuthUI::ProximityAuthUI( content::WebUI* web_ui, ProximityAuthClient* proximity_auth_client, chromeos::device_sync::DeviceSyncClient* device_sync_client) : ui::MojoWebUIController(web_ui, true /* enable_chrome_send */) { content::WebUIDataSource* source = content::WebUIDataSource::Create(kChromeUIProximityAuthHost); source->SetDefaultResource(IDR_PROXIMITY_AUTH_INDEX_HTML); source->AddResourcePath("common.css", IDR_PROXIMITY_AUTH_COMMON_CSS); source->AddResourcePath("webui.js", IDR_PROXIMITY_AUTH_WEBUI_JS); source->AddResourcePath("logs.js", IDR_PROXIMITY_AUTH_LOGS_JS); source->AddResourcePath("proximity_auth.html", IDR_PROXIMITY_AUTH_PROXIMITY_AUTH_HTML); source->AddResourcePath("proximity_auth.css", IDR_PROXIMITY_AUTH_PROXIMITY_AUTH_CSS); source->AddResourcePath("proximity_auth.js", IDR_PROXIMITY_AUTH_PROXIMITY_AUTH_JS); source->AddResourcePath("pollux.html", IDR_PROXIMITY_AUTH_POLLUX_HTML); source->AddResourcePath("pollux.css", IDR_PROXIMITY_AUTH_POLLUX_CSS); source->AddResourcePath("pollux.js", IDR_PROXIMITY_AUTH_POLLUX_JS); source->AddResourcePath( "chromeos/services/multidevice_setup/public/mojom/" "multidevice_setup.mojom.js", IDR_MULTIDEVICE_SETUP_MOJOM_JS); source->AddResourcePath( "chromeos/services/multidevice_setup/public/mojom/" "multidevice_setup_constants.mojom.js", IDR_MULTIDEVICE_SETUP_CONSTANTS_MOJOM_JS); content::BrowserContext* browser_context = web_ui->GetWebContents()->GetBrowserContext(); content::WebUIDataSource::Add(browser_context, source); web_ui->AddMessageHandler(std::make_unique<ProximityAuthWebUIHandler>( proximity_auth_client, device_sync_client)); AddHandlerToRegistry(base::BindRepeating( &ProximityAuthUI::BindMultiDeviceSetup, base::Unretained(this))); } ProximityAuthUI::~ProximityAuthUI() = default; void ProximityAuthUI::BindMultiDeviceSetup( chromeos::multidevice_setup::mojom::MultiDeviceSetupRequest request) { service_manager::Connector* connector = content::BrowserContext::GetConnectorFor( web_ui()->GetWebContents()->GetBrowserContext()); DCHECK(connector); connector->BindInterface(chromeos::multidevice_setup::mojom::kServiceName, std::move(request)); } } // namespace proximity_auth
fe611919c1e253daceb4c3a749171a183d6c2cb4
ceefe89653cf68a56a02212db07d7e7050a0c68d
/src/game/gameplay/Grid.cpp
b2938469a85972b7767f393271fe45913f3484c2
[ "MIT" ]
permissive
maunovaha/CppTicTacToe
9dedac5f2774468df833d3dbd35112df4ea70f7c
2afd78ddcdd8b4e2a2b796ea294fa6da1e5deb1a
refs/heads/master
2023-08-09T19:53:02.444433
2023-07-07T12:32:22
2023-07-07T12:32:22
220,467,287
2
0
MIT
2019-12-30T17:33:58
2019-11-08T12:58:09
C++
UTF-8
C++
false
false
3,257
cpp
Grid.cpp
#include "Grid.h" #include "GridSlot.h" #include "Chip.h" #include "../../engine/ui/Image.h" #include <memory> #include <cassert> namespace game::gameplay { using namespace engine; Grid::Grid(const math::Point& position, const int size) : scene::GameObject{position} { static constexpr auto SPRITE_SHEET = "assets/textures/SpriteSheet.png"; auto backgroundImageClip = std::make_unique<math::Rect>(0, 0, 360, 360); auto backgroundImage = std::make_unique<ui::Image>(SPRITE_SHEET, std::move(backgroundImageClip)); addComponent(std::move(backgroundImage)); static constexpr int GRID_SLOT_SIZE = 120; // Move to GridSlot (?) const int gridSlotCount = size * size; for (int i = 0; i < gridSlotCount; ++i) { const int gridSlotX = (i % size) * GRID_SLOT_SIZE; const int gridSlotY = (i / size) * GRID_SLOT_SIZE; const math::Point gridSlotPosition = {gridSlotX, gridSlotY}; addChild(std::make_unique<GridSlot>(gridSlotPosition)); } } int Grid::getGridSlotCount() const { return getChildCount(); } bool Grid::isFull() const { const int gridSlotCount = getGridSlotCount(); int freeGridSlotCount = gridSlotCount; for (int gridSlotIndex = 0; gridSlotIndex < gridSlotCount; ++gridSlotIndex) { GridSlot* gridSlot = static_cast<GridSlot*>(getChild(gridSlotIndex)); if (!gridSlot->isFree()) { --freeGridSlotCount; } } return freeGridSlotCount == 0; } // Returns binary representation of this grid "state" in which value of "1" means that // grid slot is taken and "0" means it is still free. // // E.g. when the grid has the following state and player chip type is "X" // X, X, X // empty, O, O // empty, empty, empty // // X XX O O // | || | | // This method will return: 0b0000'0001'1100'0000 // // Hence, ofc. because the grid has only 9 slots, 7 bits from the left will be unused even when // the grid is completelty full. uint16_t Grid::toBinary(const ChipType playerChipType) const { assert(getGridSlotCount() == 9); // This method is working only with 3x3 grid atm. uint16_t binaryGrid = 0b0; const int gridSlotCount = getGridSlotCount(); for (int gridSlotIndex = 0; gridSlotIndex < gridSlotCount; ++gridSlotIndex) { GridSlot* gridSlot = static_cast<GridSlot*>(getChild(gridSlotIndex)); Chip* placedChip = gridSlot->getChip(); if (placedChip && placedChip->getChipType() == playerChipType) { // Shifts number "1" to left to proper position, because we want to read current // state of the grid in binary from left to right. binaryGrid += (1 << ((gridSlotCount - 1) - gridSlotIndex)); } } // Uncomment this if you want to debug things.. // // std::string binaryStr = "0b"; // const int bitCount = 16; // uint16_t // for (int i = 0; i < bitCount; ++i) { // const int bs = (bitCount - 1) - i; // binaryStr += std::to_string(static_cast<int>((binaryGrid & (1 << bs)) >> bs)); // } // std::cout << "The current grid state in binary: " << binaryStr << std::endl; return binaryGrid; } }
285d7449447f4a1c9a3b9e1c34323fc8c81595a9
ec4f748331b081ee73e6406fa947b5f085d48410
/f6_arv_operatoroverlasting/operator_overloading_stream2.cpp
205ce40daec76b80ad88c6e9a9e8b27d734d3023
[]
no_license
peder82/cpp_v2014
6b868cd34d2124b284cc1715dfe10a91301849ed
2babd30ee153ee93051364922511295063ba385f
refs/heads/master
2020-12-30T17:32:40.049320
2014-06-11T21:03:41
2014-06-11T21:03:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
519
cpp
operator_overloading_stream2.cpp
#include <iostream> using namespace std; class int_pair{ int left; int right; public: int_pair(int l,int r): left(l),right(r){} int operator[](unsigned int i){ if(i==0) return left; return right; } string to_string(){ return "("+std::to_string(left)+","+std::to_string(right)+")"; } }; ostream& operator<<(ostream& s,int_pair p){ s << p.to_string(); return s; } int main(){ int_pair p1(1,42); cout << p1[0] << endl; cout << p1[985] << endl; cout << p1 << endl; }
c7af1d99516dfc6a39cffd87ed95b3efdd392c93
6f98d9de9b276c8b6fb61c1c548a575a109abbe4
/fsacount.cpp
00ac8cbd7a67e5cea80946440550b8797c15bac6
[]
no_license
PlumpMath/maf
d0c2e293ff8d4c04a82c8e155d996bb03bee3240
a86f3b07c1b46c37c20b0d048ffba308e9f0fcf9
refs/heads/master
2021-01-23T12:33:36.962333
2016-08-23T15:34:18
2016-08-23T15:34:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,789
cpp
fsacount.cpp
/* Copyright 2008,2009,2010 Alun Williams This file is part of MAF. MAF 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. MAF 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 MAF. If not, see <http://www.gnu.org/licenses/>. */ // $Log: fsacount.cpp $ // Revision 1.5 2010/06/10 13:56:59Z Alun // All tabs removed again // Revision 1.4 2010/05/11 07:49:48Z Alun // help changed // Revision 1.3 2009/09/12 18:47:18Z Alun // printf() style functions cleaned up considerably // code now compiles cleanly in g++ both 32-bit and 64-bit // all tabs removed from source files // Language_Size data type introduced and used where appropriate // // Revision 1.2 2007/12/20 23:25:43Z Alun // #include <limits.h> #include <stdlib.h> #include "mafword.h" #include "fsa.h" #include "container.h" #include "maf_so.h" int main(int argc,char ** argv); static int inner(Container * container,String filename,String word1,String word2, State_ID nis,unsigned log_level); int main(int argc,char ** argv) { int i = 1; bool bad_usage = false; const char * word1 = ""; const char * word2 = ""; char * file1 = 0; Container & container = *Container::create(); Standard_Options so(container,SO_STDIN); State_ID is = -1; #define cprintf container.error_output while (i < argc && !bad_usage) { if (argv[i][0] == '-') { String arg = argv[i]; if (arg.is_equal("-is")) { if (i+1 == argc) bad_usage = true; else is = atoi(argv[i+1]); i += 2; } else if (!so.recognised(argv,i)) bad_usage = true; } else if (!so.use_stdin && file1 == 0) file1 = argv[i++]; else if (!*word1) word1 = argv[i++]; else if (!*word2) word2 = argv[i++]; else bad_usage = true; } int exit_code = 1; if (!bad_usage && ((file1 !=0) ^ so.use_stdin)) exit_code = inner(&container,file1,word1,word2,is,so.log_level); else { cprintf("Usage: fsacount [loglevel] [-is n] -i | input_file [word1] [word2]\n" "where either stdin (if you specify -i), or input_file" " (otherwise), contains a\nGASP FSA.\n" "If you specify word1, or, in the case of a 2-variable FSA, word1" " and word2,\nthen instead fsacount counts the size of the" " intersection between the accepted\nlanguage and the set of" " words, or word pairs, that begin with the specified\n" "word(s).\n" "[KBMAG] The -is n option changes the FSA so that its initial" " state is n.\n"); so.usage(); } delete &container; return exit_code; } /**/ static int inner(Container * container,String filename,String word1, String word2,State_ID nis,unsigned log_level) { FSA_Simple * fsa = FSA_Factory::create(filename,container); Language_Size answer = 0; if (fsa) { State_ID si = -1; if (nis != -1) { if (!fsa->is_valid_state(nis)) { container->error_output("Invalid state specified with -is option\n"); return 1; } fsa->set_single_initial(nis); fsa->change_flags(0,GFF_TRIM|GFF_MINIMISED|GFF_ACCESSIBLE); FSA_Simple * fsa_temp = FSA_Factory::minimise(*fsa); delete fsa; fsa = fsa_temp; } if (*word1 || *word2) { Ordinal_Word *ow1 = fsa->base_alphabet.parse(word1,WHOLE_WORD,0,*container); Ordinal_Word *ow2 = fsa->base_alphabet.parse(word2,WHOLE_WORD,0,*container); if (fsa->is_product_fsa()) si = fsa->read_product(*ow1,*ow2); else si = fsa->read_word(*ow1); delete ow1; delete ow2; } answer = fsa->language_size(true,si); if (answer == LS_INFINITE) container->progress(1,"The accepted language is infinite\n"); else if (answer == LS_HUGE) container->progress(1,"The accepted language is finite," " but too large to calculate\n"); else container->progress(1,"The accepted language contains " FMT_LS " words\n", answer); if (log_level == 0) if (answer >= LS_HUGE) container->result("%ld\n",(long) answer); else container->result(FMT_LS "\n",answer); delete fsa; } return answer != LS_HUGE ? 0 : 2; }
afb52f553acbf0eeb8170ae2d0b1dfac3c993151
8f4538a52c4837825a22e072ab7d38e8142a61b1
/2017_cs01/vj/w1d2e.cpp
df8a4b25506d8e70c75c1cd7240a82f202f84cff
[]
no_license
heymind/practise
9c3c99ce63e8026c5078c29e163d82e8ce191bbe
9e9800938fcd111242033940650cb87874fe4070
refs/heads/master
2021-04-26T23:04:24.942706
2018-03-05T13:59:05
2018-03-05T13:59:05
123,927,461
0
0
null
null
null
null
UTF-8
C++
false
false
634
cpp
w1d2e.cpp
#include <algorithm> #include <iostream> #include <iterator> #include <map> #include <sstream> #include <string> using namespace std; int main() { string s; int n; map<string, int> m; do { cin >> n; if (n == 0) return 0; while (n--) { cin >> s; m[s]++; } int max = 0; for (map<string, int>::iterator it = m.begin(); it != m.end(); it++) { if (it->second > max) { max = it->second; s = it->first; } } cout << s << endl; m.clear(); } while (true); }
73dd6e74ab93859c3ae25439f91d79e58a78f2b0
1c52a71a1d6851842a13ff193771aed24e46318c
/codeforces/658-B/658-B-17024006.cpp
c7f60103a931e5e0b64ac19f9da5dc86dd8d71e7
[]
no_license
nimxor/competitive_progeamming
d19654b94478aa59ff2103b4433e613f1fdf5ff6
7caf1353a2e8fc3d423cc9711228fbb4fd1e9a97
refs/heads/master
2021-01-19T03:28:52.056161
2017-04-05T14:02:33
2017-04-05T14:02:33
87,314,559
0
0
null
null
null
null
UTF-8
C++
false
false
1,285
cpp
658-B-17024006.cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define mset(m,v) memset(m,v,sizeof(m)) #define iter(a,it) for(auto it: a) #define f(it,o) f(aut(it, (o).begin()); it != (o).end(); ++ it) #define tr(cont, it) for(typeof(cont.begin()) it = cont.begin(); it != cont.end(); it++) #define dbg(x) cout<< #x << ": " << (x) << endl; #define all(o) (o).begin(), (o).end() #define UNIQUE(c) (c).resize(unique(all(c)) - (c).begin()) // use with vectors #define present(cont, e) (cont.find(e) != cont.end()) // find for set/map #define vpresent(cont, e) (find(all(cont),e) != cont.end()) //find for vectors #define pb push_back #define mp make_pair #define sz(x) (x.size()) #define vii vector<pair<int,int>> #define pii pair<int,int> map<int,int> m; int main() { int n,k,q,i,j; cin>>n>>k>>q; int a[n]; for(i=0;i<n;i++) cin>>a[i]; int x,y; map<int,int> :: reverse_iterator it; while(q--) { cin>>x>>y; if(x==1) m.insert(mp(a[y-1],y)); else { int cnt=0,f=0; for(it=m.rbegin();it!=m.rend();it++) { if(cnt>=k) break; if(it->second == y) { f=1; cout<<"YES"<<endl; break; } cnt++; } if(f==0) cout<<"NO"<<endl; } } return 0; }
b3407ddb8d29b3985bbb1d9b5834c4b74a3e8236
6779af59ff6a886b58efaf38bd417edda613a0f2
/Spell.h
0d53b728b2205cac9c0ce15068ee229376e9648a
[]
no_license
AdvaLynn/Sorcery
6db49e3ae0a7262cd51fba7ad0418a4b1e74cfe1
7ed3030fbe831780b29703812414982e9988fa5f
refs/heads/master
2022-04-09T21:47:06.042050
2020-01-16T17:32:03
2020-01-16T17:32:03
118,697,802
0
0
null
null
null
null
UTF-8
C++
false
false
298
h
Spell.h
#ifndef SPELL_H #define SPELL_H #include <string> #include <memory> #include "Card.h" class Spell; typedef std::shared_ptr<Spell> SpellPtr; class Spell : public Card { protected: Spell(std::string name, std::string descript, bool owner, int origCost); public: virtual ~Spell(); }; #endif
d948dd9d9dd609355a9aeed4714b42674c21057b
00aea0af71ea42d3fc98f78da4252aa832a25e51
/SpaceTalk/SpaceTalk/Planet.h
9ea0e6165c4209648d655fcc45067a467d18a2c2
[]
no_license
tectronics/dysnomia
adfe2dcc5162a35c8650e530fa26938b8ae2f8ec
a496d4044e5e2f01c121d608dac088b95b988619
refs/heads/master
2018-01-11T15:15:21.764562
2012-10-12T00:12:01
2012-10-12T00:12:01
49,559,357
0
0
null
null
null
null
UTF-8
C++
false
false
489
h
Planet.h
#pragma once #include "OrbitalElement.h" #include "ScriptedMesh.h" class Planet : public OrbitalElement, public ScriptedMesh { public: Planet(const std::string &planetName, OrbitalElement *parent = 0); Planet(lua_State *L); ~Planet(); int setParent(lua_State *L); virtual const std::string write(const bool &create) const; static const char className[]; static Luna<Planet>::RegType methods[]; private: ISceneNode *clouds; IBillboardSceneNode *backdrop; };
829f94252db9587538625848d5b8607bb94b7922
2019ba40b35efea95e384451913e771451e0e17e
/Hydropiekłowstąpienie/FileReader.cpp
1c89160bc2d0882a584b9daa5e85f8f4d8dd0a52
[]
no_license
adam13049582/Hydropieklowstapienie2
22d0d724292796394d41bf7a595041820b8b445a
8536015bafca50b12a8133b405c10869ed65ddb7
refs/heads/master
2022-12-12T07:53:33.718842
2020-09-07T18:25:24
2020-09-07T18:25:24
253,272,265
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
1,370
cpp
FileReader.cpp
#include <iostream> #include "FileReader.h" #include <fstream> #include <algorithm> #include "ConfigModel.h" #include <string> #include <list> #include <vector> /// <summary> /// Metoda pobierająca dane z konfiguracji ///<returns> lista obiektów wczytanych z konfiguracji</returns> /// </summary> list<ConfigModel> FileReader::configRead() { std::ifstream cFile("config2.txt"); list<ConfigModel> config; if (cFile.is_open()) { try { std::string line; while (getline(cFile, line)) { line.erase(std::remove_if(line.begin(), line.end(), isspace), line.end()); if (line[0] == '#' || line.empty()) continue; auto delimiterPos = line.find("="); auto name = line.substr(0, delimiterPos); auto value = line.substr(delimiterPos + 1); ConfigModel conf; conf.key = name; conf.value = value; config.push_back(conf); } } catch (const std::exception & e) { std::cout << " a standard exception was caught when reading from file, with message '" << e.what() << "'\n"; } } else { std::cerr << "Couldn't open config file for reading.\n"; } return config; }
9609bef88117b7469523bacd7f4178165b5af539
fa8c099b20c480abef033342147570f0a9c76d54
/Base/Source/ElementalObject.cpp
a15531e461fc4acb8fd9ac6b7fa11aab64047aea
[]
no_license
TemplarDon/SP3
b312fd1c6c6b926912648b15f196936f2ae8b90a
155c7f973e58eab42c9243a8a69eeb0cb69655a3
refs/heads/master
2020-04-06T06:54:13.984488
2016-09-01T10:36:07
2016-09-01T10:36:07
65,668,853
0
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
ElementalObject.cpp
#include "ElementalObject.h" ElementalObject::ElementalObject() : m_CurrElement(NO_ELEMENT) { } ElementalObject::~ElementalObject() { } ELEMENT ElementalObject::GetElement() { return m_CurrElement; } void ElementalObject::SetElement(ELEMENT SetElement) { m_CurrElement = SetElement; }
13828dd87e7a9db304a746a26f2f31325be0d55c
bc18d10f510ec9f3d4165172da61afb357626826
/hw2/Graph_2483.hpp
8547c8b0b557d984cbe22d86585219aa8dfbb5a9
[]
no_license
RaphAbb/peercode
3cb48f73a1c673f714ba8416fc6be43271f89054
01c11cfc2247fa900577efee3fbed40d545b518f
refs/heads/master
2020-04-26T15:59:42.030818
2019-02-20T03:56:40
2019-02-20T03:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
29,079
hpp
Graph_2483.hpp
#ifndef CME212_GRAPH_HPP #define CME212_GRAPH_HPP /** @file Graph.hpp * @brief An undirected graph type */ #include <algorithm> #include <vector> #include <cassert> #include <unordered_map> #include <map> #include <set> #include "CME212/Util.hpp" #include "CME212/Point.hpp" /** @class Graph * @brief A template for 3D undirected graphs. * * Users can add and retrieve nodes and edges. Edges are unique (there is at * most one edge between any pair of distinct nodes). */ template <typename V, typename E> class Graph { typedef V node_value_type; typedef E edge_value_type; public: // // PUBLIC TYPE DEFINITIONS // /** Type of this graph. */ using graph_type = Graph; /** Predeclaration of Node type. */ class Node; /** Synonym for Node (following STL conventions). */ using node_type = Node; /** Predeclaration of Edge type. */ class Edge; /** Synonym for Edge (following STL conventions). */ using edge_type = Edge; /** Type of node iterators, which iterate over all graph nodes. */ class NodeIterator; /** Synonym for NodeIterator */ using node_iterator = NodeIterator; /** Type of edge iterators, which iterate over all graph edges. */ class EdgeIterator; /** Synonym for EdgeIterator */ using edge_iterator = EdgeIterator; /** Type of incident iterators, which iterate incident edges to a node. */ class IncidentIterator; /** Synonym for IncidentIterator */ using incident_iterator = IncidentIterator; /** Type of indexes and sizes. Return type of Graph::Node::index(), Graph::num_nodes(), Graph::num_edges(), and argument type of Graph::node(size_type) */ using size_type = unsigned; /* Pair of nodes */ typedef std::pair<size_type, size_type> NodePair; // // CONSTRUCTORS AND DESTRUCTOR // /** Construct an empty graph. */ Graph() : nodes_(), edges_(), idmap_(), edgemap_(), next_uid_(0), size_(0), num_edges_(0) {} /** Default destructor */ ~Graph() = default; // // NODES // /** @class Graph::Node * @brief Class representing the graph's nodes. * * Node objects are used to access information about the Graph's nodes. */ class Node : private totally_ordered<Node> { public: /** Construct an invalid node. * * Valid nodes are obtained from the Graph class, but it * is occasionally useful to declare an @i invalid node, and assign a * valid node to it later. For example: * * @code * Graph::node_type x; * if (...should pick the first node...) * x = graph.node(0); * else * x = some other node using a complicated calculation * do_something(x); * @endcode */ Node() { this->G_ = nullptr; } /** Return this node's position. */ const Point& position() const { // Find the position by UID return this->G_->nodes_[this->uid_].point; } /** Return this node's index, a number in the range [0, graph_size). */ size_type index() const { // Invalid node if (this->G_ == nullptr) { std::cerr << "ERROR: This node does not belong to a graph."; exit(1); } // Find the index by UID return this->G_->idmap_[this->uid_]; } /** * @brief Get the value of the Node. * @return A reference to the Node's value. * @pre The Node belongs to a graph. */ node_value_type& value() { return this->G_->nodes_[this->index()].value; } /** * @brief Get the value of the Node. * @return A constant reference to the Node's value. * @pre The Node is a valid node, i.e. it belongs to a graph. */ const node_value_type& value() const { return this->G_->nodes_[this->index()].value; } /** * @brief Get the number of nodes adjacent to the current Node. * @return The number of adjacent Nodes. * @pre The Node is a valid node, i.e. it belongs to a graph. */ size_type degree() const { return this->G_->nodes_[this->index()].adj_list.size(); } /** * @brief Get the position of the Node. */ Point& position() { return this->G_->nodes_[this->index()].point; } /** * @brief Create an iterator pointing to the first Edge incident * to the Node. * @return An IncidentIterator pointing to the first Edge * incident to the Node. * @pre The Node is a valid node, i.e. it belongs to a graph. */ incident_iterator edge_begin() const { IncidentIterator iit {this->G_, this, 0}; return iit; } /** * @brief Create an iterator pointing one element beyond the last * Edge incident to the Node. * @return An IncidentIterator pointing one element beyond the last * Edge incident to the Node. * @pre The Node is a valid node, i.e. it belongs to a graph. */ incident_iterator edge_end() const { IncidentIterator iit {this->G_, this, this->degree()}; return iit; } /** Test whether this node and @a n are equal. * * Equal nodes have the same graph and the same index. */ bool operator==(const Node& n) const { if (n.uid_ == this->uid_ and n.G_ == this->G_) { return true; } return false; } /** Test whether this node is less than @a n in a global order. * * This ordering function is useful for STL containers such as * std::map<>. It need not have any geometric meaning. * * The node ordering relation must obey trichotomy: For any two nodes x * and y, exactly one of x == y, x < y, and y < x is true. */ bool operator<(const Node& n) const { // Node from another graph if (this->G_ < n.G_) { return true; } if (this->uid_ < n.uid_) { return true; } return false; } private: // Allow Graph to access Node's private member data and functions. friend class Graph; // Point to the owner of this node Graph* G_; // Uniquely identify a node size_type uid_; // Private constructor for Graph to construct a valid Node object. Node(const Graph* G, size_type uid) : G_(const_cast<Graph*>(G)), uid_(uid) {} }; /** Return the number of nodes in the graph. * * Complexity: O(1). */ size_type size() const { return this->size_; } /** Synonym for size(). */ size_type num_nodes() const { return size(); } /** Add a node to the graph, returning the added node. * @param[in] position The new node's position * @post new num_nodes() == old num_nodes() + 1 * @post result_node.index() == old num_nodes() * * Complexity: O(1) amortized operations. */ Node add_node(const Point& position, const node_value_type& val = node_value_type()) { // Build internal node for storage internal_node in; in.point = position; in.value = val; in.adj_list = std::vector<size_type>(); in.uid = this->next_uid_; // Add internal node this->nodes_.insert(std::make_pair(this->size_, in)); // Add to ID map this->idmap_.insert(std::make_pair(this->next_uid_, this->size_)); // Increment next UID this->next_uid_ += 1; // Increment size of Graph this->size_ += 1; // Return valid node return Node(this, this->next_uid_- 1); } /** Determine if a Node belongs to this Graph * @return True if @a n is currently a Node of this Graph * * Complexity: O(1). */ bool has_node(const Node& n) const { if (n.G_ == this and idmap_.count(n.uid_)) { return true; } return false; } /** Return the node with index @a i. * @pre 0 <= @a i < num_nodes() * @post result_node.index() == i * * Complexity: O(1). */ Node node(size_type i) const { // Find correct UID size_type uid = this->nodes_.at(i).uid; // Return a node with the correct UID return Node(this, uid); } // // EDGES // /** @class Graph::Edge * @brief Class representing the graph's edges. * * Edges are order-insensitive pairs of nodes. Two Edges with the same nodes * are considered equal if they connect the same nodes, in either order. */ class Edge : private totally_ordered<Edge> { public: /** Construct an invalid Edge. */ Edge() { this->G_ = nullptr; } /** Return a node of this Edge */ Node node1() const { return Node(this->G_, this->nodepair_.first); } /** Return the other node of this Edge */ Node node2() const { return Node(this->G_, this->nodepair_.second); } /** Test whether this edge and @a e are equal. * * Equal edges represent the same undirected edge between two nodes. */ bool operator==(const Edge& e) const { if (this->G_ == e.G_ and std::min(nodepair_.first, nodepair_.second) == std::min(e.nodepair_.first, e.nodepair_.second) and std::max(nodepair_.first, nodepair_.second) == std::max(e.nodepair_.first, e.nodepair_.second)) { return true; } return false; } /** Test whether this edge is less than @a e in a global order. * * This ordering function is useful for STL containers such as * std::map<>. It need not have any interpretive meaning. */ bool operator<(const Edge& e) const { // Edge from another graph if (this->G_ < e.G_) { return true; } // Min and max node IDs for each edge size_type min1, min2, max1, max2; min1 = std::min(this->nodepair_.first, this->nodepair_.second); min2 = std::min(e.nodepair_.first, e.nodepair_.second); max1 = std::max(this->nodepair_.first, this->nodepair_.second); max2 = std::max(e.nodepair_.first, e.nodepair_.second); if (min1 < min2) { return true; } else if (min1 == min2) { if (max1 < max2) { return true; } } return false; } /** Get the constant edge length */ double length() const { return euclidean_dist( this->node1().position(), this->node2().position()); } /** Get the value of the Edge */ edge_value_type& value() { return this->G_->edges_.at(this->index()).value; } const edge_value_type& value() const { return this->G_->edges_.at(this->index()).value; } private: // Allow Graph to access Edge's private member data and functions. friend class Graph; // Private data members Graph* G_; NodePair nodepair_; // Return index of this edge size_type index() { NodePair nodepair = std::make_pair( std::min(this->nodepair_.first, this->nodepair_.second), std::max(this->nodepair_.first, this->nodepair_.second)); return this->G_->edgemap_.at(nodepair); } // Private constructor for Graph to construct a valid Edge object Edge(const Graph* G, NodePair nodepair) : G_(const_cast<Graph*>(G)), nodepair_(nodepair) {} }; /** Return the total number of edges in the graph. * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ size_type num_edges() const { return this->num_edges_; } /** Return the edge with index @a i. * @pre 0 <= @a i < num_edges() * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ Edge edge(size_type i) const { // Get node UIDs from index i return Edge(this, this->edges_.at(i).nodepair); } /** Test whether two nodes are connected by an edge. * @pre @a a and @a b are valid nodes of this graph * @return True if for some @a i, edge(@a i) connects @a a and @a b. * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ bool has_edge(const Node& a, const Node& b) const { // Check if nodes are the same if (a == b) { return false; } // Check if nodes are in the graph if (!has_node(a) or !has_node(b)) { return false; } // Iterate over nodes adjacent to a size_type idx_a = this->idmap_.at(a.uid_); for (size_type i = 0; i < a.degree(); ++i) { if (this->nodes_.at(idx_a).adj_list[i] == b.uid_) { return true; } } return false; } /** Add an edge to the graph, or return the current edge if it already exists. * @pre @a a and @a b are distinct valid nodes of this graph * @return an Edge object e with e.node1() == @a a and e.node2() == @a b * @post has_edge(@a a, @a b) == true * @post If old has_edge(@a a, @a b), new num_edges() == old num_edges(). * Else, new num_edges() == old num_edges() + 1. * * Can invalidate edge indexes -- in other words, old edge(@a i) might not * equal new edge(@a i). Must not invalidate outstanding Edge objects. * * Complexity: No more than O(num_nodes() + num_edges()), hopefully less */ Edge add_edge(const Node& a, const Node& b) { // Check if nodes are in the graph if (! has_node(a) or ! has_node(b)) { std::cerr << "ERROR: Nodes a and b must belong to this graph."; exit(1); } // Create pair of node UIDs NodePair nodepair = std::make_pair( std::min(a.uid_, b.uid_), std::max(a.uid_, b.uid_)); // Check if edge is in the graph (if so, return that edge) if (has_edge(a, b)) { // return Edge(); return Edge(this, nodepair); } //// Add edge to graph internal_edge e; e.nodepair = nodepair; e.value = edge_value_type(); // Add to list of edges this->edges_.insert(std::make_pair(this->num_edges_, e)); // Add to the edge map this->edgemap_.insert(std::make_pair(nodepair, this->num_edges_)); // Update number of edges this->num_edges_ += 1; // Update adjacency lists this->nodes_[a.uid_].adj_list.push_back(b.uid_); this->nodes_[b.uid_].adj_list.push_back(a.uid_); // New edge return Edge(this, nodepair); } /** Remove all nodes and edges from this graph. * @post num_nodes() == 0 && num_edges() == 0 * * Invalidates all outstanding Node and Edge objects. */ void clear() { // Reset all internal data structures this->nodes_ = Nodes(); this->edges_ = Edges(); this->idmap_ = NIDMap(); this->edgemap_ = EIDMap(); this->next_uid_ = 0; this->size_ = 0; this->num_edges_ = 0; } /** * @brief Remove a node from the graph * @param n Node to be removed * * @pre Node _n_ is a member of the graph * @post num_nodes() and size() have decreased by 1 * @post has_node(n) returns false * @post All edges incident to node _n_ are removed from the graph * * Complexity: O(k * (num_edges() + num_edges()) where k is the * maximum degree of a node in the graph */ size_type remove_node (const Node& n) { if (!has_node(n)) { return 0; } // Remove all incident edges for (IncidentIterator iit = n.edge_begin(); iit != n.edge_end();) { remove_edge((*iit)); } // Get node index size_type index = this->idmap_[n.uid_]; // Remove from nodes_ this->nodes_.erase(index); // Remove node n from idmap this->idmap_.erase(n.uid_); // Re-index the last node size_type last_idx = this->num_nodes() - 1; if (index < last_idx) { // Last node in the graph internal_node last_node = this->nodes_.at(last_idx); // Swap the last node with the current node this->nodes_.erase(last_idx); this->nodes_.insert(std::make_pair(index, last_node)); this->idmap_.at(last_node.uid) = index; } // Decrement graph size this->size_ = this->size_ - 1; return 1; } /** * @brief Remove a node from the graph * @param n_it node iterator indexed to the node to be removed * * @pre (*n_it) is a member of the graph * @post num_nodes() and size() have decreased by 1 * @post All edges incident to the node are removed from the graph * @post _n_it_ points to the next node * * Complexity: O(k * (num_edges() + num_edges()) where k is the * maximum degree of a node in the graph */ node_iterator remove_node (node_iterator n_it ) { Node n = (*n_it); remove_node(n); return(n_it); } /** * @brief Remove an edge from the graph. * @param a One node of the edge to be removed. * @param b The other node of the edge to be removed. * * @pre has_edge(a, b) returns true (i.e. the graph contains the edge) * @post num_edges() has decreased by 1 * @post has_edge(a, b) returns false * * Complexity: Average case O(1), worst case O(num_edges). */ size_type remove_edge (const Node& a, const Node& b) { if (!has_edge(a, b)) { return 0; } // Create pair of node UIDs NodePair nodepair = std::make_pair( std::min(a.uid_, b.uid_), std::max(a.uid_, b.uid_)); // Get edge index size_type index = this->edgemap_.at(nodepair); // Remove edges from edges_ this->edges_.erase(index); // Re-index the last edge size_type last_idx = this->num_edges_ - 1; if (index < last_idx) { // Node pair of the last edge in the graph internal_edge last_edge = this->edges_.at(last_idx); // Re-index this->edgemap_.at(last_edge.nodepair) = index; this->edges_.erase(last_idx); this->edges_.insert(std::make_pair(index, last_edge)); } // Remove edge from edgemap_ this->edgemap_.erase(nodepair); // Update number of edges this->num_edges_ -= 1; // Remove nodes from adjacency lists remove_adj(a, b); return 1; } // Remove nodes a and b from each others' adjacency lists void remove_adj (const Node& a, const Node& b) { std::vector<size_type>& adj1 = this->nodes_[this->idmap_[a.uid_]].adj_list; adj1.erase(std::remove(adj1.begin(), adj1.end(), b.uid_), adj1.end()); std::vector<size_type>& adj2 = this->nodes_[this->idmap_[b.uid_]].adj_list; adj2.erase(std::remove(adj2.begin(), adj2.end(), a.uid_), adj2.end()); } /** * @brief Remove an edge from the graph. * @param e The edge to be removed. * * @pre has_edge(e.node1(), e.node2()) returns true (i.e. the graph * contains the edge. * @post num_edges() has decreased by 1 * @post has_edge(e.node1(), e.node2()) returns false * * Complexity: Average case O(1), worst case O(num_edges) */ size_type remove_edge (const Edge& e) { return remove_edge(e.node1(), e.node2()); } /** * @brief Remove an edge from the graph. * @param e_it Edge iterator indexed to the edge to be removed. * * @pre _e_it_ is indexed to a valid edge * @post num_edges() has decreased by 1 * @post _e_it_ is indexed to the next edge (unordered) * * Complexity: Average case O(1), worst case O(num_edges) */ edge_iterator remove_edge (edge_iterator e_it ) { Edge e = (*e_it); remove_edge(e); return(e_it); } // // Node Iterator // /** @class Graph::NodeIterator * @brief Iterator class for nodes. A forward iterator. */ class NodeIterator : private totally_ordered<NodeIterator> { public: // These type definitions let us use STL's iterator_traits. using value_type = Node; // Element type using pointer = Node*; // Pointers to elements using reference = Node&; // Reference to elements using difference_type = std::ptrdiff_t; // Signed difference using iterator_category = std::input_iterator_tag; // Weak Category, Proxy /** Construct an invalid NodeIterator. */ NodeIterator() {} /** * @brief Dereference the NodeIterator. * @return The Node at the current position of the NodeIterator. * * @pre The NodeIterator is indexed to a valid Node; that is, * node_begin() <= index < node_end() */ Node operator*() const { size_type uid = this->G_->nodes_.at(this->index_).uid; return Node(this->G_, uid); } /** * @brief Increment the NodeIterator. * @return A reference to a NodeIterator pointing to the next Node * in the Graph. * * @pre The NodeIterator is indexed to a valid Node; that is, * node_begin() <= index < node_end(). * @post The NodeIterator is indexed to a valid Node, or to the position * beyond the last Node in the Graph: * node_begin() <= index <= node_end(). */ NodeIterator& operator++(){ this->index_ += 1; return *this; } /** * @brief Check equality against another NodeIterator object. * * @param n A NodeIterator to compare against. * @return A boolean result of equality comparison. * @pre NodeIterators _this_ and _n_ must be valid NodeIterator objects. * * Equal NodeIterator objects have the same graph and the same index. */ bool operator==(const NodeIterator& n) const { bool same_graph = ( this->G_ == n.G_ ); bool same_index = ( this->index_ == n.index_ ); return (same_index && same_graph); } private: friend class Graph; const Graph* G_; size_type index_; /** Construct a valid NodeIterator */ NodeIterator(const Graph* G, size_type index) : G_(const_cast<Graph*>(G)), index_(index) {} }; /** * @brief Create an iterator pointing to the first Node in a Graph. * @return A NodeIterator object pointing to the Node with index 0. */ node_iterator node_begin() const { return node_iterator(this, 0); } /** * @brief Create an iterator pointing past the last Node in a Graph. * @return A NodeIterator object pointing one position past the last * Node in the graph. */ node_iterator node_end() const { return node_iterator(this, this->size()); } // // Incident Iterator // /** @class Graph::IncidentIterator * @brief Iterator class for edges incident to a node. A forward iterator. */ class IncidentIterator : private totally_ordered<IncidentIterator> { public: // These type definitions let us use STL's iterator_traits. using value_type = Edge; // Element type using pointer = Edge*; // Pointers to elements using reference = Edge&; // Reference to elements using difference_type = std::ptrdiff_t; // Signed difference using iterator_category = std::input_iterator_tag; // Weak Category, Proxy /** Construct an invalid IncidentIterator. */ IncidentIterator() : G_{nullptr}, node_{nullptr} {} /** * @brief Dereference the IncidentIterator. * @return Edge at the current index of the IncidentIterator. * @pre The IncidentIterator is indexed to a valid Edge; that is, * edge_begin() <= index < edge_end() */ Edge operator*() const { // Get UID of current adjacent node size_type adj_uid = this->G_->nodes_.at(this->node_->index()).adj_list[this->p_]; // Build the edge NodePair nodepair = std::make_pair(this->node_->uid_, adj_uid); return Edge(this->G_, nodepair); } /** * @brief Increment the IncidentIterator. * @return A reference to a IncidentIterator pointing to the next Edge * incident to the source Node. * * @pre The IncidentIterator is indexed to a valid Edge; that is, * edge_begin() <= index < edge_end(). * @post The IncidentIterator is indexed to a valid Edge, or to the * first position past the last edge incident Edge: * edge_begin() <= index <= edge_end(). */ IncidentIterator& operator++() { this->p_ += 1; return *this; } /** * @brief Check equality against another IncidentIterator object. * * @param iit A IncidentIterator to compare against. * @return A boolean result of equality comparison. * @pre NodeIterators _this_ and _iit_ must be valid IncidentIterator * objects. * * Equal IncidentIterator objects have the same graph, the same * Node, and the same position within that Node's adjacency list. */ bool operator==(const IncidentIterator& iit) const { bool same_graph = ( this->G_ == iit.G_); bool same_node = ( this->node_ == iit.node_); bool same_index = ( this->p_ == iit.p_); return (same_graph && same_node && same_index); } private: friend class Graph; /** Private function to create a valid incident iterator */ IncidentIterator(const Graph* G, const Node* node, size_type p) : G_{const_cast<Graph*>(G)}, node_{node}, p_{p} {} const Graph* G_; // Pointer to a graph const Node* node_; // Pointer to a node size_type p_; // Position in the adjacency list }; // // Edge Iterator // /** @class Graph::EdgeIterator * @brief Iterator class for edges. A forward iterator. */ class EdgeIterator : private totally_ordered<EdgeIterator> { public: // These type definitions let us use STL's iterator_traits. using value_type = Edge; // Element type using pointer = Edge*; // Pointers to elements using reference = Edge&; // Reference to elements using difference_type = std::ptrdiff_t; // Signed difference using iterator_category = std::input_iterator_tag; // Weak Category, Proxy /** Construct an invalid EdgeIterator. */ EdgeIterator() { } /** * @brief Dereference the EdgeIterator. * @return The Edge at the current position of the EdgeIterator. * @pre The EdgeIterator is indexed to a valid Edge; that is, * edge_begin() <= index < edge_end() */ Edge operator*() const { Edge e {this->G_, this->G_->edges_.at(this->index_).nodepair}; return e; } /** * @brief Increment the EdgeIterator. * @return A reference to a EdgeIterator pointing to the next Edge * in the Graph. * * @pre The EdgeIterator is indexed to a valid Edge; that is, * edge_begin() <= index < edge_end(). * @post The EdgeIterator is indexed to a valid Edge, or to the * first position past the last edge Edge in the Graph: * edge_begin() <= index <= edge_end(). */ EdgeIterator& operator++() { this->index_ += 1; return *this; } /** * @brief Check equality against another EdgeIterator object. * * @param e A EdgeIterator to compare against. * @return A boolean result of equality comparison. * @pre NodeIterators _this_ and _e_ must be valid EdgeIterator * objects. * * Equal EdgeIterator objects have the same graph, and the same * index to an Edge. */ bool operator==(const EdgeIterator& e) const { bool same_graph = ( this->G_ == e.G_ ); bool same_index = ( this->index_ == e.index_ ); return (same_index && same_graph); } private: friend class Graph; const Graph* G_; size_type index_; EdgeIterator(const Graph* G, size_type index) : G_(const_cast<Graph*>(G)), index_(index) {} }; /** * @brief Create an iterator pointing to the first Edge in the Graph. * @return An IncidentIterator pointing to the Edge with index 0. */ edge_iterator edge_begin() const { return edge_iterator(this, 0); } /** * @brief Create an iterator pointing past the last Edge in a Graph. * @return An EdgeIterator object pointing one position past the last * Edge in the graph. */ edge_iterator edge_end() const { return edge_iterator(this, this->num_edges_); } private: /* Container for storing node data */ typedef struct internal_node { Point point; // The position of the node in (x, y, z) node_value_type value; // Value of the node size_type uid; // The unique identifcation for a node std::vector<size_type> adj_list; // List of all adjacent nodes } internal_node; /* Container for storing edge data */ typedef struct internal_edge { NodePair nodepair; // Two nodes edge_value_type value; // Value of the edge } internal_edge; /* Map from node index to node */ typedef std::unordered_map<size_type, internal_node> Nodes; /* Map from node UID to node index */ typedef std::unordered_map<size_type, size_type> NIDMap; /* Map from edge index to edge nodes */ typedef std::unordered_map< size_type, internal_edge> Edges; /* Map from node pair to edge index */ typedef std::map<NodePair, size_type> EIDMap; Nodes nodes_; Edges edges_; NIDMap idmap_; EIDMap edgemap_; // Next unique UID for a node size_type next_uid_; // Number of nodes in the graph size_type size_; // Number of edges in the graph size_type num_edges_; }; #endif // CME212_GRAPH_HPP
cb99e3427f8efa750d55b9f0505364bbbc85ae5c
933af872ebec221981aece11df35082eb5ead78e
/src/utils/bindingchecker.cpp
d3f7b0a77b3b7fe97048218af9a01575bf328565
[ "MIT" ]
permissive
ContentsViewer/qdoc-example
5fed49199154fb7f01a87b93212bfbe941a8d237
139c331663e935b5ac632d0efcf871b2dec2ebe9
refs/heads/master
2023-04-22T01:55:24.521552
2021-05-21T15:34:26
2021-05-21T15:34:26
369,578,725
0
0
null
null
null
null
UTF-8
C++
false
false
712
cpp
bindingchecker.cpp
#include "bindingchecker.h" #include <QDebug> /*! \class BindingChecker */ /*! \fn BindingChecker::BindingChecker(QObject *parent) */ BindingChecker::BindingChecker(QObject *parent) : QObject(parent) , m_someVar("123") { qDebug() << "I'm been created!"; } void BindingChecker::anotherFunction() { qDebug() << "Another function!"; } QString BindingChecker::someVar() { return m_someVar; } QString BindingChecker::getSomeVar() { return m_someVar; } void BindingChecker::callMe() { qDebug() << "I'm being called!"; } void BindingChecker::setSomeVar(QString newVar) { if (m_someVar != newVar) { m_someVar = newVar; emit someVarChanged(); } }
93e87521395d6d7ecf80cd04f4f7260afc0f2da9
d30e5ddeb7f51782cdb82bbbfbed7610174e5cd1
/C++/Algorithms/Dynamic Programming/matrixChainMultiplication.cpp
b4cccf4fd7cac51b3cf413fd5d6acbaa34eaa668
[ "MIT" ]
permissive
ucverma/hacktoberfest2020-1
c235a1f259593326b81c470ef37b5f78b9594b92
c00d871213b6ace1ee46d1e28bed7ced68ae46e5
refs/heads/main
2023-01-03T10:36:54.549176
2020-10-15T06:20:30
2020-10-15T06:20:30
304,228,144
0
0
MIT
2020-10-15T06:16:22
2020-10-15T06:16:21
null
UTF-8
C++
false
false
674
cpp
matrixChainMultiplication.cpp
#include<bits/stdc++.h> using namespace std; int t[10001][10001]; int MCM(vector<int> &arr, int i, int j){ if(i + 1 >= j){ return 0; } if(t[i][j] != -1) return t[i][j]; int mn = INT_MAX; for(int k = i + 1; k <= j - 1; k++){ mn = min(mn, (MCM(arr, i, k) + MCM(arr, k, j) + arr[i] * arr[k] * arr[j])); } return t[i][j] = mn; } int main(){ memset(t, -1, sizeof(t)); vector<int> arr = {40, 20, 30, 10, 30}; // 26000 vector<int> arr2 = {10, 30, 5, 60}; // 4500 // cout<<MCM(arr, 0, arr.size() - 1)<<"\n"; cout<<MCM(arr2, 0, arr2.size() - 1)<<"\n"; return 0; }
4bf2efd00d9f584d1cc45a7e5ffba655b2727d16
061ec60f27a52a2a02363b443a2c30fe878bd88b
/include/dawn-gfx/VertexDecl.h
be1ee38c91dd958de831c606736f8ca325ca4f1f
[ "MIT" ]
permissive
dgavedissian/dawn-gfx
2c6a2bd53932dd753b972817cda313e92f488901
cdb0b2f6cf9c2df5712ec49195549f40313860ea
refs/heads/develop
2020-09-28T08:33:36.448580
2020-01-27T15:49:19
2020-01-27T15:49:19
226,734,703
5
1
MIT
2020-01-27T15:49:20
2019-12-08T21:30:55
C++
UTF-8
C++
false
false
1,928
h
VertexDecl.h
/* * Dawn Graphics * Written by David Avedissian (c) 2017-2020 (git@dga.dev) */ #pragma once #include "Base.h" #include <vector> #include <utility> #include <cstddef> #include <dga/hash_combine.h> namespace dw { namespace gfx { // Vertex Declaration. class DW_API VertexDecl { public: enum class Attribute { Position, Normal, Colour, TexCoord0, Tangent }; enum class AttributeType { Float, Uint8 }; VertexDecl(); ~VertexDecl() = default; VertexDecl& begin(); // TODO: Combine type, count and normalised, so it's a compiler error if the user gets these wrong. // TODO: Alternatively, combine type and normalised, and make count an enum. VertexDecl& add(Attribute attribute, usize count, AttributeType type, bool normalised = false); VertexDecl& end(); bool operator==(const VertexDecl& other) const; bool operator!=(const VertexDecl& other) const; u16 stride() const; bool empty() const; // TODO: Remove this weird encoding magic. Not sure why it's like this. static u16 encodeAttributes(Attribute attribute, usize count, AttributeType type, bool normalised); static void decodeAttributes(u16 encoded_attribute, Attribute& attribute, usize& count, AttributeType& type, bool& normalised); static u16 attributeTypeSize(AttributeType type); // Attribute: 7 // Count: 3 // AttributeType: 5 // Normalised: 1 std::vector<std::pair<u16, byte*>> attributes_; u16 stride_; }; } // namespace gfx } // namespace dw template <> struct std::hash<dw::gfx::VertexDecl> { std::size_t operator()(const dw::gfx::VertexDecl& decl) const { std::size_t hash = 0; dga::hashCombine(hash, decl.stride_); for (const auto& entry : decl.attributes_) { dga::hashCombine(hash, entry.first, entry.second); } return hash; } };
0ecaca33d226eb142afcd9854b78194229b016b5
e741f43e6f28669f1330faa422bbf44c496b63b4
/hw/01_Complexity/algorithms/fastchoose.cc
bcebec1c7034686ecf9d6d11d94e05c904c6ad06
[]
no_license
StevensDeptECE/CPE593
d5ee7816a42d9db112a9618fb95c14922ccd8e75
3ca8115e84287a2afd18d27976720c159ab056a2
refs/heads/master
2023-04-26T21:07:47.252333
2023-04-19T01:25:09
2023-04-19T01:25:09
102,521,068
50
51
null
2023-03-05T17:45:52
2017-09-05T19:22:17
C++
UTF-8
C++
false
false
600
cc
fastchoose.cc
#include <iostream> constexpr double nan = 0.0/0.0; double choose(uint32_t n, uint32_t r) { const uint32_t nmax=500, rmax = nmax/2; static double memo[nmax][rmax] = {0}; if (n > nmax || r > nmax) return nan; if (memo[n][r] != 0) return memo[n][r]; uint32_t bottom = min(r, n-r); double num = 1, den = 1; for (uint32_t i = bottom; i > 0; i--) { num *= n--; den *= i; } return memo[n][r] = num/den; } int main() { double sum = 0; constexpr uint32_t n = 100000000; // 100 million times for (uint32_t i = 0; i < n; i++) { sum += choose(n,r); } cout << sum << '\n'; return 0; }
200a6a02ef021cc40525e924ebab64349d2f13df
125ae0adb562478b184bbb35d40f2c43b335415c
/UI/Widgets/tFeatureFrame.cpp
9b96adba37edc7f51045c7abce7aaa8df2250381
[]
no_license
dulton/53_hero
ff49ce6096c379931d7649b654c5fa76de4630de
48057fe05e75f57b500a395e6ff8ff9c06da6895
refs/heads/master
2020-02-25T04:19:18.632727
2016-05-20T03:44:44
2016-05-20T03:44:44
62,197,327
3
2
null
2016-06-29T05:11:41
2016-06-29T05:11:38
null
WINDOWS-1252
C++
false
false
1,433
cpp
tFeatureFrame.cpp
/*****************************************************/ // Copyright © 2007-2012 Navico // Confidential and proprietary. All rights reserved. /*****************************************************/ /*! \class tCheckBox \brief A tCheckBox has a check state toggled by Enter key \todo - consider reimp style to draw a bigger checkbox */ #include <StdAfx.h> #include "tFeatureFrame.h" #include "UI/tNOSStyle.h" #include <Core/Assert.h> //============================================================================= //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- tFeatureFrame::tFeatureFrame( QWidget* pParent ) : QWidget( pParent ) { if( style()->styleHint( NSH( tNOSStyle::NSH_FeatureFramePaintsOpaque ) ) != 0 ) { setAttribute( Qt::WA_OpaquePaintEvent ); } } //----------------------------------------------------------------------------- //! //----------------------------------------------------------------------------- void tFeatureFrame::paintEvent( QPaintEvent* /*pEvent*/ ) { tNOSStyle* nosStyle = qobject_cast<tNOSStyle*>( style() ); if( nosStyle == 0 ) { Assert( nosStyle ); return; } QPainter painter( this ); QStyleOption opt; opt.initFrom( this ); nosStyle->DrawFeatureFrame( &opt, &painter, this ); }
86d2060f73c8f3c9a80b8e66784e543ed7c60ddb
6f669b18324c36833bff97b0398863743dfef12c
/PL0Compiler/SyntaxAnalyzer/syntaxAnalyzer.cpp
19fef86a172a03caa9ea2c283402f2061e261bbd
[]
no_license
RainbowYou/PL0Compiler
1276b2317695f9e000fd2972280a2c8e5ef6f371
bb8606a29bda446e1f0746f669edae09b41e7e17
refs/heads/master
2016-09-15T05:59:58.610377
2016-01-10T03:09:54
2016-01-10T03:09:54
47,538,934
7
1
null
null
null
null
UTF-8
C++
false
false
17,668
cpp
syntaxAnalyzer.cpp
/**************************************************************************** * U N R E G I S T E R E D C O P Y * * You are on day 11 of your 30 day trial period. * * This file was produced by an UNREGISTERED COPY of Parser Generator. It is * for evaluation purposes only. If you continue to use Parser Generator 30 * days after installation then you are required to purchase a license. For * more information see the online help or go to the Bumble-Bee Software * homepage at: * * http://www.bumblebeesoftware.com * * This notice must remain present in the file. It cannot be removed. ****************************************************************************/ /**************************************************************************** * syntaxAnalyzer.cpp * C++ source file generated from syntaxAnalyzer.y. * * Date: 12/16/15 * Time: 21:53:01 * * AYACC Version: 2.07 ****************************************************************************/ #include <yywcpars.h> // namespaces #ifdef YYSTDCPPLIB using namespace std; #endif #ifdef YYNAMESPACE using namespace yl; #endif #line 1 ".\\syntaxAnalyzer.y" /*Date: 2015��12��14��*/ #include <iostream> #include <cstring> #include "wordAnalyzer.h" #line 45 "syntaxAnalyzer.cpp" // repeated because of possible precompiled header #include <yywcpars.h> // namespaces #ifdef YYSTDCPPLIB using namespace std; #endif #ifdef YYNAMESPACE using namespace yl; #endif #include ".\syntaxAnalyzer.h" ///////////////////////////////////////////////////////////////////////////// // constructor YYPARSERNAME::YYPARSERNAME() { yytables(); #line 21 ".\\syntaxAnalyzer.y" // place any extra initialisation code here #line 69 "syntaxAnalyzer.cpp" } ///////////////////////////////////////////////////////////////////////////// // destructor YYPARSERNAME::~YYPARSERNAME() { // allows virtual functions to be called properly for correct cleanup yydestroy(); #line 26 ".\\syntaxAnalyzer.y" // place any extra cleanup code here #line 83 "syntaxAnalyzer.cpp" } #ifndef YYSTYPE #define YYSTYPE int #endif #ifndef YYSTACK_SIZE #define YYSTACK_SIZE 100 #endif #ifndef YYSTACK_MAX #define YYSTACK_MAX 0 #endif /**************************************************************************** * N O T E * * If the compiler generates a YYPARSERNAME error then you have not declared * the name of the parser. The easiest way to do this is to use a name * declaration. This is placed in the declarations section of your YACC * source file and is introduced with the %name keyword. For instance, the * following name declaration declares the parser myparser: * * %name myparser * * For more information see help. ****************************************************************************/ // yyattribute #ifdef YYDEBUG void YYFAR* YYPARSERNAME::yyattribute1(int index) const { YYSTYPE YYFAR* p = &((YYSTYPE YYFAR*)yyattributestackptr)[yytop + index]; return p; } #define yyattribute(index) (*(YYSTYPE YYFAR*)yyattribute1(index)) #else #define yyattribute(index) (((YYSTYPE YYFAR*)yyattributestackptr)[yytop + (index)]) #endif void YYPARSERNAME::yystacktoval(int index) { yyassert(index >= 0); *(YYSTYPE YYFAR*)yyvalptr = ((YYSTYPE YYFAR*)yyattributestackptr)[index]; } void YYPARSERNAME::yyvaltostack(int index) { yyassert(index >= 0); ((YYSTYPE YYFAR*)yyattributestackptr)[index] = *(YYSTYPE YYFAR*)yyvalptr; } void YYPARSERNAME::yylvaltoval() { *(YYSTYPE YYFAR*)yyvalptr = *(YYSTYPE YYFAR*)yylvalptr; } void YYPARSERNAME::yyvaltolval() { *(YYSTYPE YYFAR*)yylvalptr = *(YYSTYPE YYFAR*)yyvalptr; } void YYPARSERNAME::yylvaltostack(int index) { yyassert(index >= 0); ((YYSTYPE YYFAR*)yyattributestackptr)[index] = *(YYSTYPE YYFAR*)yylvalptr; } void YYFAR* YYPARSERNAME::yynewattribute(int count) { yyassert(count >= 0); return new YYFAR YYSTYPE[count]; } void YYPARSERNAME::yydeleteattribute(void YYFAR* attribute) { delete[] (YYSTYPE YYFAR*)attribute; } void YYPARSERNAME::yycopyattribute(void YYFAR* dest, const void YYFAR* src, int count) { for (int i = 0; i < count; i++) { ((YYSTYPE YYFAR*)dest)[i] = ((YYSTYPE YYFAR*)src)[i]; } } #ifdef YYDEBUG void YYPARSERNAME::yyinitdebug(void YYFAR** p, int count) const { yyassert(p != NULL); yyassert(count >= 1); YYSTYPE YYFAR** p1 = (YYSTYPE YYFAR**)p; for (int i = 0; i < count; i++) { p1[i] = &((YYSTYPE YYFAR*)yyattributestackptr)[yytop + i - (count - 1)]; } } #endif void YYPARSERNAME::yyaction(int action) { } void YYPARSERNAME::yytables() { yyattribute_size = sizeof(YYSTYPE); yysstack_size = YYSTACK_SIZE; yystack_max = YYSTACK_MAX; #ifdef YYDEBUG static const yywsymbol_t YYNEARFAR YYBASED_CODE symbol[] = { { L"$end", 0 }, { L"\'+\'", 43 }, { L"\'-\'", 45 }, { L"\'=\'", 61 }, { L"error", 65536 }, { L"IDENTIFIER", 65537 }, { L"UINT", 65538 }, { L"ADDOPERATOR", 65539 }, { L"MULOPERATOR", 65540 }, { L"RELOPERATOR", 65541 }, { L"CONST", 65542 }, { L"VAR", 65543 }, { L"PROCEDURE", 65544 }, { L"ODD", 65545 }, { L"IF", 65546 }, { L"THEN", 65547 }, { L"WHILE", 65548 }, { L"DO", 65549 }, { L"CALL", 65550 }, { L"BEGIN", 65551 }, { L"END", 65552 }, { L"READ", 65553 }, { L"WRITE", 65554 }, { L"COMMA", 65555 }, { L"SEMICOLON", 65556 }, { L"ASSIGN", 65557 }, { L"LP", 65558 }, { L"RP", 65559 }, { NULL, 0 } }; yysymbol = symbol; static const wchar_t* const YYNEARFAR YYBASED_CODE rule[] = { L"$accept: prog", L"prog: partProg", L"partProg: sentence", L"partProg: constDec sentence", L"partProg: constDec varDec sentence", L"partProg: constDec varDec proDec sentence", L"constDec: CONST constDef moreConstDef SEMICOLON", L"moreConstDef: COMMA constDef", L"moreConstDef: COMMA constDef moreConstDef", L"moreConstDef:", L"constDef: IDENTIFIER \'=\' UINT", L"varDec: VAR IDENTIFIER moreIdentifier SEMICOLON", L"moreIdentifier: COMMA IDENTIFIER", L"moreIdentifier: COMMA IDENTIFIER moreIdentifier", L"moreIdentifier:", L"proDec: proHead partProg moreProDec SEMICOLON", L"proHead: PROCEDURE IDENTIFIER SEMICOLON", L"moreProDec: SEMICOLON proDec", L"moreProDec: SEMICOLON proDec moreProDec", L"moreProDec:", L"sentence: assignSen", L"sentence: conditionSen", L"sentence: whileSen", L"sentence: proCallSen", L"sentence: reuniteSen", L"sentence: readSen", L"sentence: writeSen", L"sentence:", L"assignSen: IDENTIFIER ASSIGN expr", L"expr: item moreItem", L"expr: \'+\' item moreItem", L"expr: \'-\' item moreItem", L"moreItem: ADDOPERATOR item", L"moreItem: ADDOPERATOR item moreItem", L"moreItem:", L"item: factor moreFactor", L"factor: IDENTIFIER", L"factor: UINT", L"factor: LP expr RP", L"moreFactor: MULOPERATOR factor", L"moreFactor: MULOPERATOR factor moreFactor", L"moreFactor:", L"condition: expr RELOPERATOR expr", L"condition: ODD expr", L"conditionSen: IF condition THEN sentence", L"whileSen: WHILE condition DO sentence", L"proCallSen: CALL IDENTIFIER", L"reuniteSen: BEGIN sentence moreSentence END", L"moreSentence: SEMICOLON sentence", L"moreSentence: SEMICOLON sentence moreSentence", L"moreSentence:", L"readSen: READ LP IDENTIFIER moreIdentifier RP", L"writeSen: WRITE LP expr moreExpr RP", L"moreExpr: COMMA expr", L"moreExpr: COMMA expr moreExpr", L"moreExpr:" }; yyrule = rule; #endif static const yywreduction_t YYNEARFAR YYBASED_CODE reduction[] = { { 0, 1, -1 }, { 1, 1, -1 }, { 2, 1, -1 }, { 2, 2, -1 }, { 2, 3, -1 }, { 2, 4, -1 }, { 3, 4, -1 }, { 4, 2, -1 }, { 4, 3, -1 }, { 4, 0, -1 }, { 5, 3, -1 }, { 6, 4, -1 }, { 7, 2, -1 }, { 7, 3, -1 }, { 7, 0, -1 }, { 8, 4, -1 }, { 9, 3, -1 }, { 10, 2, -1 }, { 10, 3, -1 }, { 10, 0, -1 }, { 11, 1, -1 }, { 11, 1, -1 }, { 11, 1, -1 }, { 11, 1, -1 }, { 11, 1, -1 }, { 11, 1, -1 }, { 11, 1, -1 }, { 11, 0, -1 }, { 12, 3, -1 }, { 13, 2, -1 }, { 13, 3, -1 }, { 13, 3, -1 }, { 14, 2, -1 }, { 14, 3, -1 }, { 14, 0, -1 }, { 15, 2, -1 }, { 16, 1, -1 }, { 16, 1, -1 }, { 16, 3, -1 }, { 17, 2, -1 }, { 17, 3, -1 }, { 17, 0, -1 }, { 18, 3, -1 }, { 18, 2, -1 }, { 19, 4, -1 }, { 20, 4, -1 }, { 21, 2, -1 }, { 22, 4, -1 }, { 23, 2, -1 }, { 23, 3, -1 }, { 23, 0, -1 }, { 24, 5, -1 }, { 25, 5, -1 }, { 26, 2, -1 }, { 26, 3, -1 }, { 26, 0, -1 } }; yyreduction = reduction; yytokenaction_size = 115; static const yywtokenaction_t YYNEARFAR YYBASED_CODE tokenaction[] = { { 63, YYAT_SHIFT, 1 }, { 103, YYAT_SHIFT, 25 }, { 103, YYAT_SHIFT, 26 }, { 100, YYAT_SHIFT, 96 }, { 80, YYAT_SHIFT, 23 }, { 63, YYAT_SHIFT, 2 }, { 80, YYAT_SHIFT, 24 }, { 97, YYAT_SHIFT, 101 }, { 52, YYAT_ERROR, 0 }, { 63, YYAT_SHIFT, 3 }, { 52, YYAT_ERROR, 0 }, { 63, YYAT_SHIFT, 4 }, { 39, YYAT_SHIFT, 1 }, { 63, YYAT_SHIFT, 5 }, { 63, YYAT_SHIFT, 6 }, { 96, YYAT_SHIFT, 61 }, { 63, YYAT_SHIFT, 7 }, { 63, YYAT_SHIFT, 8 }, { 92, YYAT_SHIFT, 80 }, { 39, YYAT_SHIFT, 61 }, { 90, YYAT_SHIFT, 78 }, { 39, YYAT_SHIFT, 3 }, { 103, YYAT_SHIFT, 28 }, { 39, YYAT_SHIFT, 4 }, { 10, YYAT_SHIFT, 1 }, { 39, YYAT_SHIFT, 5 }, { 39, YYAT_SHIFT, 6 }, { 83, YYAT_SHIFT, 95 }, { 39, YYAT_SHIFT, 7 }, { 39, YYAT_SHIFT, 8 }, { 10, YYAT_SHIFT, 38 }, { 82, YYAT_SHIFT, 94 }, { 81, YYAT_SHIFT, 93 }, { 10, YYAT_SHIFT, 3 }, { 0, YYAT_SHIFT, 1 }, { 10, YYAT_SHIFT, 4 }, { 79, YYAT_SHIFT, 91 }, { 10, YYAT_SHIFT, 5 }, { 10, YYAT_SHIFT, 6 }, { 0, YYAT_SHIFT, 2 }, { 10, YYAT_SHIFT, 7 }, { 10, YYAT_SHIFT, 8 }, { 78, YYAT_SHIFT, 90 }, { 0, YYAT_SHIFT, 3 }, { 62, YYAT_SHIFT, 1 }, { 0, YYAT_SHIFT, 4 }, { 76, YYAT_SHIFT, 56 }, { 0, YYAT_SHIFT, 5 }, { 0, YYAT_SHIFT, 6 }, { 73, YYAT_SHIFT, 52 }, { 0, YYAT_SHIFT, 7 }, { 0, YYAT_SHIFT, 8 }, { 72, YYAT_SHIFT, 50 }, { 62, YYAT_SHIFT, 3 }, { 56, YYAT_SHIFT, 1 }, { 62, YYAT_SHIFT, 4 }, { 66, YYAT_SHIFT, 43 }, { 62, YYAT_SHIFT, 5 }, { 62, YYAT_SHIFT, 6 }, { 61, YYAT_SHIFT, 83 }, { 62, YYAT_SHIFT, 7 }, { 62, YYAT_SHIFT, 8 }, { 60, YYAT_SHIFT, 78 }, { 56, YYAT_SHIFT, 3 }, { 55, YYAT_SHIFT, 1 }, { 56, YYAT_SHIFT, 4 }, { 59, YYAT_SHIFT, 80 }, { 56, YYAT_SHIFT, 5 }, { 56, YYAT_SHIFT, 6 }, { 58, YYAT_SHIFT, 78 }, { 56, YYAT_SHIFT, 7 }, { 56, YYAT_SHIFT, 8 }, { 57, YYAT_SHIFT, 77 }, { 55, YYAT_SHIFT, 3 }, { 54, YYAT_SHIFT, 1 }, { 55, YYAT_SHIFT, 4 }, { 48, YYAT_SHIFT, 70 }, { 55, YYAT_SHIFT, 5 }, { 55, YYAT_SHIFT, 6 }, { 46, YYAT_SHIFT, 50 }, { 55, YYAT_SHIFT, 7 }, { 55, YYAT_SHIFT, 8 }, { 45, YYAT_SHIFT, 50 }, { 54, YYAT_SHIFT, 3 }, { 6, YYAT_SHIFT, 1 }, { 54, YYAT_SHIFT, 4 }, { 44, YYAT_SHIFT, 67 }, { 54, YYAT_SHIFT, 5 }, { 54, YYAT_SHIFT, 6 }, { 43, YYAT_SHIFT, 21 }, { 54, YYAT_SHIFT, 7 }, { 54, YYAT_SHIFT, 8 }, { 42, YYAT_SHIFT, 65 }, { 6, YYAT_SHIFT, 3 }, { 38, YYAT_SHIFT, 60 }, { 6, YYAT_SHIFT, 4 }, { 36, YYAT_SHIFT, 58 }, { 6, YYAT_SHIFT, 5 }, { 6, YYAT_SHIFT, 6 }, { 35, YYAT_SHIFT, 56 }, { 6, YYAT_SHIFT, 7 }, { 6, YYAT_SHIFT, 8 }, { 33, YYAT_SHIFT, 55 }, { 32, YYAT_SHIFT, 54 }, { 31, YYAT_SHIFT, 52 }, { 30, YYAT_SHIFT, 50 }, { 29, YYAT_SHIFT, 49 }, { 22, YYAT_SHIFT, 43 }, { 21, YYAT_SHIFT, 42 }, { 11, YYAT_ACCEPT, 0 }, { 8, YYAT_SHIFT, 37 }, { 7, YYAT_SHIFT, 36 }, { 5, YYAT_SHIFT, 34 }, { 4, YYAT_SHIFT, 27 }, { 1, YYAT_SHIFT, 20 } }; yytokenaction = tokenaction; static const yywstateaction_t YYNEARFAR YYBASED_CODE stateaction[] = { { -65503, 1, YYAT_REDUCE, 27 }, { -65443, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_DEFAULT, 43 }, { 0, 0, YYAT_DEFAULT, 4 }, { -65432, 1, YYAT_DEFAULT, 80 }, { -65425, 1, YYAT_ERROR, 0 }, { -65453, 1, YYAT_REDUCE, 27 }, { -65447, 1, YYAT_ERROR, 0 }, { -65448, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_REDUCE, 1 }, { -65513, 1, YYAT_REDUCE, 27 }, { 109, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_REDUCE, 2 }, { 0, 0, YYAT_REDUCE, 24 }, { 0, 0, YYAT_REDUCE, 25 }, { 0, 0, YYAT_REDUCE, 20 }, { 0, 0, YYAT_REDUCE, 23 }, { 0, 0, YYAT_REDUCE, 21 }, { 0, 0, YYAT_REDUCE, 26 }, { 0, 0, YYAT_REDUCE, 22 }, { 0, 0, YYAT_DEFAULT, 80 }, { 47, 1, YYAT_ERROR, 0 }, { -65448, 1, YYAT_REDUCE, 9 }, { 0, 0, YYAT_DEFAULT, 52 }, { 0, 0, YYAT_DEFAULT, 52 }, { 0, 0, YYAT_REDUCE, 36 }, { 0, 0, YYAT_REDUCE, 37 }, { 0, 0, YYAT_DEFAULT, 80 }, { 0, 0, YYAT_DEFAULT, 80 }, { -65435, 1, YYAT_ERROR, 0 }, { -65434, 1, YYAT_REDUCE, 34 }, { -65436, 1, YYAT_REDUCE, 41 }, { -65444, 1, YYAT_ERROR, 0 }, { -65447, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_REDUCE, 46 }, { -65457, 1, YYAT_REDUCE, 50 }, { -65441, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_DEFAULT, 80 }, { -65443, 1, YYAT_ERROR, 0 }, { -65525, 1, YYAT_REDUCE, 27 }, { 0, 0, YYAT_REDUCE, 3 }, { 0, 0, YYAT_REDUCE, 28 }, { -65446, 1, YYAT_ERROR, 0 }, { -65448, 1, YYAT_ERROR, 0 }, { -65470, 1, YYAT_ERROR, 0 }, { -65457, 1, YYAT_REDUCE, 34 }, { -65460, 1, YYAT_REDUCE, 34 }, { 0, 0, YYAT_REDUCE, 43 }, { -65483, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_DEFAULT, 80 }, { 0, 0, YYAT_DEFAULT, 52 }, { 0, 0, YYAT_REDUCE, 29 }, { -35, 1, YYAT_DEFAULT, 80 }, { 0, 0, YYAT_REDUCE, 35 }, { -65463, 1, YYAT_REDUCE, 27 }, { -65473, 1, YYAT_REDUCE, 27 }, { -65483, 1, YYAT_REDUCE, 27 }, { -65480, 1, YYAT_ERROR, 0 }, { -65486, 1, YYAT_REDUCE, 14 }, { -65489, 1, YYAT_REDUCE, 55 }, { -65493, 1, YYAT_REDUCE, 14 }, { -65478, 1, YYAT_ERROR, 0 }, { -65493, 1, YYAT_REDUCE, 27 }, { -65537, 1, YYAT_REDUCE, 27 }, { 0, 0, YYAT_REDUCE, 4 }, { 0, 0, YYAT_REDUCE, 10 }, { -65499, 1, YYAT_REDUCE, 7 }, { 0, 0, YYAT_REDUCE, 6 }, { 0, 0, YYAT_REDUCE, 30 }, { 0, 0, YYAT_REDUCE, 31 }, { 0, 0, YYAT_REDUCE, 38 }, { 0, 0, YYAT_REDUCE, 42 }, { -65487, 1, YYAT_REDUCE, 32 }, { -65491, 1, YYAT_REDUCE, 39 }, { 0, 0, YYAT_REDUCE, 44 }, { 0, 0, YYAT_REDUCE, 45 }, { -65510, 1, YYAT_REDUCE, 48 }, { 0, 0, YYAT_REDUCE, 47 }, { -65495, 1, YYAT_ERROR, 0 }, { -65523, 1, YYAT_ERROR, 0 }, { -39, 1, YYAT_DEFAULT, 103 }, { -65527, 1, YYAT_ERROR, 0 }, { -65525, 1, YYAT_ERROR, 0 }, { -65529, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_REDUCE, 5 }, { 0, 0, YYAT_DEFAULT, 100 }, { 0, 0, YYAT_REDUCE, 8 }, { 0, 0, YYAT_REDUCE, 33 }, { 0, 0, YYAT_REDUCE, 40 }, { 0, 0, YYAT_REDUCE, 49 }, { -65535, 1, YYAT_REDUCE, 12 }, { 0, 0, YYAT_REDUCE, 51 }, { -65537, 1, YYAT_REDUCE, 53 }, { 0, 0, YYAT_REDUCE, 52 }, { 0, 0, YYAT_REDUCE, 11 }, { 0, 0, YYAT_REDUCE, 16 }, { -65529, 1, YYAT_ERROR, 0 }, { -65549, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_REDUCE, 13 }, { 0, 0, YYAT_REDUCE, 54 }, { -65553, 1, YYAT_ERROR, 0 }, { 0, 0, YYAT_REDUCE, 15 }, { 0, 0, YYAT_REDUCE, 18 }, { -65536, 1, YYAT_ERROR, 0 } }; yystateaction = stateaction; yynontermgoto_size = 60; static const yywnontermgoto_t YYNEARFAR YYBASED_CODE nontermgoto[] = { { 63, 85 }, { 63, 10 }, { 62, -1 }, { 62, -1 }, { 39, 62 }, { 39, 63 }, { 100, 102 }, { 39, 64 }, { 10, 39 }, { 63, 12 }, { 63, 15 }, { 62, 84 }, { 80, 92 }, { 10, 40 }, { 80, 30 }, { 92, 99 }, { 4, 29 }, { 63, 17 }, { 63, 19 }, { 63, 16 }, { 63, 13 }, { 4, 33 }, { 63, 14 }, { 63, 18 }, { 96, 100 }, { 96, 63 }, { 50, 72 }, { 50, 31 }, { 0, 11 }, { 0, 9 }, { 90, 98 }, { 85, 97 }, { 76, 89 }, { 73, 88 }, { 72, 87 }, { 66, 86 }, { 60, 82 }, { 59, 81 }, { 58, 79 }, { 56, 76 }, { 55, 75 }, { 54, 74 }, { 52, 73 }, { 49, 71 }, { 46, 69 }, { 45, 68 }, { 43, 66 }, { 37, 59 }, { 35, 57 }, { 31, 53 }, { 30, 51 }, { 28, 48 }, { 27, 47 }, { 24, 46 }, { 23, 45 }, { 22, 44 }, { 20, 41 }, { 6, 35 }, { 3, 32 }, { 2, 22 } }; yynontermgoto = nontermgoto; static const yywstategoto_t YYNEARFAR YYBASED_CODE stategoto[] = { { 27, 63 }, { 0, -1 }, { 54, -1 }, { 40, 4 }, { 3, 80 }, { 0, -1 }, { 46, 62 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 2, 62 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 43, 80 }, { 0, -1 }, { 51, -1 }, { 39, 50 }, { 38, 50 }, { 0, -1 }, { 0, -1 }, { 39, 80 }, { 38, 80 }, { 0, -1 }, { 36, -1 }, { 32, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 25, -1 }, { 0, -1 }, { 34, 80 }, { 0, -1 }, { -4, 62 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 41, -1 }, { 0, -1 }, { 31, -1 }, { 30, -1 }, { 0, -1 }, { 0, -1 }, { 30, 80 }, { 11, -1 }, { 0, -1 }, { 26, -1 }, { 0, -1 }, { 30, 62 }, { 29, 62 }, { 28, 62 }, { 0, -1 }, { 31, -1 }, { 11, -1 }, { 29, -1 }, { 0, -1 }, { 0, 63 }, { -2, -1 }, { 0, -1 }, { 0, -1 }, { 31, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 20, -1 }, { 16, -1 }, { 0, -1 }, { 0, -1 }, { 9, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { -1, 50 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 21, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 23, -1 }, { 0, -1 }, { -11, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { 16, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 }, { -4, -1 }, { 0, -1 }, { 0, -1 }, { 0, -1 } }; yystategoto = stategoto; yydestructorptr = NULL; yytokendestptr = NULL; yytokendest_size = 0; yytokendestbaseptr = NULL; yytokendestbase_size = 0; } #line 129 ".\\syntaxAnalyzer.y" // programs section int main(void) { int n = 1; wordAnalyzer lexer; syntaxAnalyzer parser; if (parser.yycreate(&lexer)) { if (lexer.yycreate(&parser)) { n = parser.yyparse(); } } return n; } void yyerror(char* s) { fprintf(stderr,"%s\n",s); } int yywrap() { return 1; }
ca9c629ede75f3ef6ae14541571d00e4c8cffa4a
265620eb6a8de39b6eaf28c909b34e3bd25117ba
/HeatPreCal.cpp
0c6bb9686de55dc1c57c22ddb75d5e676484ece6
[]
no_license
isliulin/uesoft-AutoIPED
7e6f4d961ddc899b5f3c990f67beaca947ba4ff0
c11e3ea3a7d08faa462bc731e142844d4d4c3ed9
refs/heads/master
2022-01-13T15:32:45.190482
2013-09-30T08:33:08
2013-09-30T08:33:08
null
0
0
null
null
null
null
GB18030
C++
false
false
119,401
cpp
HeatPreCal.cpp
// HeatPreCal.cpp: implementation of the CHeatPreCal class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "AutoIPED.h" #include "HeatPreCal.h" #include "ParseExpression.h" #include "vtot.h" #include <math.h> #include <stdlib.h> #include "AutoIPEDView.h" #include "EDIBgbl.h" #include "EditOriginalData.h" #include "CalcThickBase.h" #include "uematerial.h" //打开材料库。输入许用应用,弹性模量。膨胀系数 //extern BOOL InputMaterialParameter(CString strDlgCaption, CString strMaterialName, int TableID); extern CAutoIPEDApp theApp; BOOL InputMaterialParameter(CString strDlgCaption, CString strMaterialName, int TableID) { // 使用动态库进行显示 CUeMaterial MatDlg; MatDlg.SetCodeID(1); // 规范 MatDlg.SetMaterialTableToOpen( TableID ); MatDlg.SetDlgCaption(strDlgCaption); // 对话框标题 MatDlg.SetShowMaterial(TRUE); // 显示新旧材料对照表 MatDlg.SetMaterialConnection( theApp.m_pConMaterial ); // 材料数据库的连接 MatDlg.SetCurMaterialName( strMaterialName ); // 当前显示的材料 MatDlg.AddCustomMaterialToDB( NULL ); return TRUE; } //#import"c:\program files\common files\system\ado\msado15.dll" \ // no_namespace rename("EOF","adoEOF") #define GRAVITY_ACCELERATION 9.807 //#define D_MAXTEMP 50000.0 // #define OPENATABLE(INTERFACE,TABLENAME) \ _RecordsetPtr INTERFACE; \ OpenAProjectTable(INTERFACE,#TABLENAME); \ #define OPENASSISTANTPROJECTTABLE(INTERFACE,TABLENAME) \ _RecordsetPtr INTERFACE; \ OpenAssistantProjectTable(INTERFACE,#TABLENAME); \ #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CHeatPreCal::CHeatPreCal() { m_AssistantConnection = NULL; m_ProjectName=_T(""); ch_cal=2; } CHeatPreCal::~CHeatPreCal() { } //------------------------------------------------------------------ // DATE :[2005/04/29] // Author :ZSY // Parameter(s) : // Return : // Remark :将当前要计算的原始数据赋给选择的计算方法的类成员变量. //------------------------------------------------------------------ void CHeatPreCal::InitOriginalToMethod() { #define INITDATA(CLASSN) CLASSN::D0 = D0;\ CLASSN::in_mat = in_mat;\ CLASSN::out_mat = out_mat;\ CLASSN::pro_mat = pro_mat;\ CLASSN::pro_name = pro_name;\ CLASSN::in_a0 = in_a0;\ CLASSN::in_a1 = in_a1;\ CLASSN::in_a2 = in_a2;\ CLASSN::in_ratio = in_ratio;\ CLASSN::out_a0 = out_a0;\ CLASSN::out_a1 = out_a1;\ CLASSN::out_a2 = out_a2;\ CLASSN::out_ratio = out_ratio;\ CLASSN::ts = temp_ts;\ CLASSN::tb = temp_tb;\ CLASSN::ta = Temp_env;\ CLASSN::t = Temp_pip;\ CLASSN::Mhours = Mhours;\ CLASSN::Yong = Yong;\ CLASSN::heat_price = heat_price;\ CLASSN::in_price = in_price;\ CLASSN::out_price = out_price;\ CLASSN::pro_price = pro_price;\ CLASSN::S = S;\ CLASSN::in_dens = in_dens;\ CLASSN::out_dens = out_dens;\ CLASSN::pro_dens = pro_dens;\ CLASSN::speed_wind = speed_wind;\ CLASSN::m_nID = m_nID;\ CLASSN::co_alf = co_alf;\ CLASSN::ALPHA = co_alf;\ CLASSN::strPlace = strPlace;\ CLASSN::m_HotRatio = m_HotRatio;\ CLASSN::m_CoolRatio = m_CoolRatio;\ CLASSN::MaxTs = MaxTs;\ CLASSN::hour_work = hour_work;\ CLASSN::hedu = hedu;\ CLASSN::m_dMaxD0 = m_dMaxD0;\ CLASSN::distan = distan;\ CLASSN::in_tmax = in_tmax;\ CLASSN::m_MaxHeatDensityRatio=m_HotRatio;\ CLASSN::m_thick1Start = m_thick1Start;\ CLASSN::m_thick1Max = m_thick1Max;\ CLASSN::m_thick1Increment = m_thick1Increment;\ CLASSN::m_thick2Start = m_thick2Start;\ CLASSN::m_thick2Max = m_thick2Max;\ CLASSN::m_thick2Increment = m_thick2Increment;\ CLASSN::m_pRsHeatLoss = m_pRsHeatLoss;\ CLASSN::m_pRsHeat_alfa = m_pRsHeat_alfa;\ CLASSN::m_pRsCongeal = m_pRsCongeal;\ CLASSN::m_pRsSubterranean = m_pRsSubterranean;\ CLASSN::m_pRsFaceResistance = m_pRsFaceResistance;\ CLASSN::m_pRsLSo = m_pRsLSo;\ CLASSN::thick = thick_2;\ CLASSN::thick1 = thick_1;\ CLASSN::thick2 = thick_2;\ CLASSN::pi_thi = pi_thi;\ CLASSN::dQ = 0.0;\ CLASSN::nMethodIndex = nMethodIndex;\ CLASSN::nAlphaIndex = m_nIndexAlpha;\ CLASSN::nTaIndex = nTaIndex;\ CLASSN::B = B;\ CLASSN::strExceptionInfo = ""; /* //防冻结保温计算时,新增加的一些参数. #define INITCONGEALDATA(CLASSN) \ CLASSN::Kr = Kr;\ CLASSN::taofr = taofr;\ CLASSN::tfr = tfr;\ CLASSN::V = V;\ CLASSN::ro = ro;\ CLASSN::C = C;\ CLASSN::Vp = Vp;\ CLASSN::rop = rop;\ CLASSN::Cp = Cp;\ CLASSN::Hfr = Hfr;\ CLASSN::dFlux = dFlux; */ } //根据厚度计算外表面温度. void CHeatPreCal::temp_plain_one(double &thick_t, double &ts) { double ts1,condu_r_t,condu_out_t; ts=(Temp_pip-Temp_env)/2.0+Temp_env; while(TRUE) { condu_r_t=in_a0+in_a1*(ts+Temp_pip)/2.0+in_a2*(ts+Temp_pip)*(ts+Temp_pip)/4.0; condu_out_t=co_alf; ts1=thick_t*Temp_env/1000.0/condu_r_t+Temp_pip/condu_out_t; ts1=ts1/(thick_t/1000.0/condu_r_t+1.0/condu_out_t); if(fabs(ts-ts1)<0.1) break; ts=ts1; } return; } void CHeatPreCal::temp_pip_one(double &thick_t, double &ts) { double ts1,condu_r_t,condu_out_t,D1_t; ts=(Temp_pip-Temp_env)/2.0+Temp_env; D1_t=D0+thick_t*2.0; while(TRUE) { // * the following line is corrected in next step condu_out_t=co_alf; condu_r_t=in_a0+in_a1*(ts+Temp_pip)/2.0+in_a2*(ts+Temp_pip)*(ts+Temp_pip)/4.0; ts1=1.0/condu_r_t*log(D1_t/D0)*Temp_env+2000.0*Temp_pip/condu_out_t/D1_t; ts1=ts1/(log(D1_t/D0)/condu_r_t+2000.0/condu_out_t/D1_t); if (fabs(ts-ts1)<0.1) break; ts=ts1; } return; } void CHeatPreCal::temp_plain_com(double &thick1_t, double &thick2_t, double &ts, double &tb) { double tb1,ts1,condu_out_t,condu_r1_t; double condu_r2_t; ts=(Temp_pip-Temp_env)/3.0+Temp_env; tb=(Temp_pip-Temp_env)/3.0*2.0+Temp_env; while(TRUE) { // * the following line is corrected in next step condu_out_t=co_alf; condu_r1_t=in_a0+in_a1*(Temp_pip+tb)/2.0+in_a2*(Temp_pip+tb)*(Temp_pip+tb)/4.0; condu_r2_t=out_a0+out_a1*(tb+ts)/2.0+out_a2*(tb+ts)*(tb+ts)/4.0; ts1=thick1_t*Temp_env/1000.0/condu_r1_t+thick2_t*Temp_env/1000.0/condu_r2_t+Temp_pip/condu_out_t; ts1=ts1/(thick1_t/1000.0/condu_r1_t+thick2_t/1000.0/condu_r2_t+1.0/condu_out_t); tb1=thick1_t*Temp_env/1000.0/condu_r1_t+thick2_t*Temp_pip/1000.0/condu_r2_t+Temp_pip/condu_out_t; tb1=tb1/(thick1_t/1000.0/condu_r1_t+thick2_t/1000.0/condu_r2_t+1.0/condu_out_t); if ((fabs(ts-ts1)<0.1)&&(fabs(tb-tb1)<0.1)) break; ts=ts1; tb=tb1; } return; } void CHeatPreCal::temp_pip_com(double &thick1_t, double &thick2_t, double &ts, double &tb) { double tb1,ts1,condu_r1_t,condu_out_t,D1_t,D2_t; double condu_r2_t; ts=(Temp_pip-Temp_env)/3.0+Temp_env; tb=(Temp_pip-Temp_env)/3.0*2.0+Temp_env; D1_t=D0+2.0*thick1_t; D2_t=D1_t+2.0*thick2_t; while(TRUE) { // * the following line is corrected in next step condu_out_t=co_alf; condu_r1_t=in_a0+in_a1*(Temp_pip+tb)/2.0+in_a2*(Temp_pip+tb)*(Temp_pip+tb)/4.0; condu_r2_t=out_a0+out_a1*(tb+ts)/2.0+out_a2*(tb+ts)*(tb+ts)/4.0; ts1=Temp_env*log(D1_t/D0)/condu_r1_t+Temp_env*log(D2_t/D1_t)/condu_r2_t+2000.0*Temp_pip/condu_out_t/D2_t; ts1=ts1/(log(D1_t/D0)/condu_r1_t+log(D2_t/D1_t)/condu_r2_t+2000.0/condu_out_t/D2_t); tb1=Temp_env*log(D1_t/D0)/condu_r1_t+Temp_pip*log(D2_t/D1_t)/condu_r2_t+2000.0*Temp_pip/condu_out_t/D2_t; tb1=tb1/(log(D1_t/D0)/condu_r1_t+log(D2_t/D1_t)/condu_r2_t+2000.0/condu_out_t/D2_t); if ((fabs(ts-ts1)<0.1)&&(fabs(tb-tb1)<0.1)) break; ts=ts1; tb=tb1; } return; } ////////////////////////////////////////// //模 块 名: support.prg // //功 能: 计算支吊架间距 // //上级模块: C_ANALYS // //下级模块: // //引 用 库: (6) a_pipe, // // (8)a_elas // //修改日期: // /////////////////////////////////////////// void CHeatPreCal::SUPPORT(double &dw, double &s, double &temp, double &wei1,double &wei2,double &lmax, CString &v, CString &cl,BOOL &pg,CString &st, double &t0) { //管径,壁厚,温度, 无水单重,有水单重, 间距, //卷册号,材质,汽水标识,冷态温度,环境温度 /* double d=0,w=0,i=0; double elastic; double l1,l2; double stres_t0=0.0,stres_t1=0.0,stress=0.0,stress3=0.0; double circle=0,l3,maxl12; CString k,mk; CString TempStr; _variant_t TempValue; CString strDlgCaption; int TableID; cl.TrimLeft(); cl.TrimRight(); SetMapValue(CString(_T("S")),&S); //将记录集IRecPipe改为成员的。每次计算只打开一次。 //目的:提高速度。 ZSY 2005/4/8 // OPENASSISTANTPROJECTTABLE(IRecPipe,A_PIPE); /* try { IRecPipe->MoveFirst(); while(!IRecPipe->adoEOF) { TempValue=IRecPipe->GetCollect(_variant_t("PIPE_DW")); tempVtf = vtof(TempValue); if(fabs(tempVtf - dw) > 1E-6) { IRecPipe->MoveNext(); continue; } TempValue=IRecPipe->GetCollect(_variant_t("PIPE_S")); tempVtf = vtof(TempValue); if(fabs(tempVtf - s) > 1E-6) { IRecPipe->MoveNext(); continue; } GetTbValue(IRecPipe,_variant_t("PIPE_I"),i); GetTbValue(IRecPipe,_variant_t("PIPE_W"),w); break; } } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } if(IRecPipe->adoEOF) { d=(dw-2*s); w=pi*(dw*dw*dw*dw/10000-d*d*d*d/10000)/(dw/10*32); i=w*dw/20; } */ //管道断面惯性矩(PIPE_I) 厘米^4 //管道断面抗弯矩(PIPE_W) 厘米^3 //从管道参数库中查找对应外径和壁厚的记录。 /* if( 0 == GetPipeWeithAndWaterWeith(IRecPipe,dw,s,"PIPE_I",i,"PIPE_W",w) ) { d=(dw-2*s); //管道断面抗弯矩(PIPE_W) 厘米^3 w=pi*(dw*dw*dw*dw/10000-d*d*d*d/10000)/(dw/10*32); //管道断面惯性矩(PIPE_I) 厘米^4 i=w*dw/20; } */ /* //AutoIPED7.0已经采用新的方法计算许用应力、弹性模量 //即利用动态库函数从 material.mdb中查找许用应力/弹性模量,查出的单位是MPa,kN/mm2 stress3=CCalcDll.GetMaterialSIGMAt(cl,(float)t0,(float)s)/GRAVITY_ACCELERATION; CString strDlgCaption, strMaterialName, *pStrArr; int TableID, MatNum; if( stress3 < 0 ) { if( FindMaterialNameOldOrNew(cl, pStrArr, MatNum) ) //查找新旧材料对照表. { strMaterialName = pStrArr[0]; delete[] pStrArr; } else { strMaterialName = cl; } TableID = 0; strDlgCaption.Format(_T("请输入 %s 在环境温度下的许用应力(MPa):"),strMaterialName); //输入数据 InputMaterialParameter(strDlgCaption, strMaterialName, TableID); //再找一次 stress3=CCalcDll.GetMaterialSIGMAt(cl,(float)t0,(float)s)/GRAVITY_ACCELERATION; } stress=CCalcDll.GetMaterialSIGMAt(cl,(float)temp,(float)s)/GRAVITY_ACCELERATION; if( stress < 0 ) { if( FindMaterialNameOldOrNew(cl, pStrArr, MatNum) ) //查找新旧材料对照表. { strMaterialName = pStrArr[0]; delete[] pStrArr; } else { strMaterialName = cl; } TableID = 0; strDlgCaption.Format(_T("请输入 %s 在 %f ℃下的许用应力(MPa):"),strMaterialName,temp); // strMaterialName = cl; //输入数据 InputMaterialParameter(strDlgCaption, strMaterialName, TableID); stress=CCalcDll.GetMaterialSIGMAt(cl,(float)temp,(float)s)/GRAVITY_ACCELERATION; } // elastic=CCalcDll.GetMaterialEt(cl,(float)temp)/GRAVITY_ACCELERATION*100000; if( elastic < 0 ) { if( FindMaterialNameOldOrNew(cl, pStrArr, MatNum) ) //查找新旧材料对照表. { strMaterialName = pStrArr[0]; delete[] pStrArr; } else { strMaterialName = cl; } TableID = 1; strDlgCaption.Format(_T("请输入 %s 在 %f ℃下的弹性模量(kN/mm2)"),strMaterialName,temp); // strMaterialName = cl; //输入数据 InputMaterialParameter(strDlgCaption, strMaterialName, TableID); elastic=CCalcDll.GetMaterialEt(cl,(float)temp)/GRAVITY_ACCELERATION*100000; } // ***应力 stress // ***弹性模量 elastic BOOL IsFind=FALSE; //当没有数据,由用户输入时才循环一次 while( 1 ) { //将记录集IRec改为成员的。每次计算只打开一次。 //目的:提高速度。 ZSY 2005/4/8 // OPENASSISTANTPROJECTTABLE(IRec,A_C09); m_pRs_a_c09->MoveFirst(); if(LocateFor(m_pRs_a_c09,_variant_t("PIPE_MAT"),CFoxBase::EQUAL,_variant_t(cl))) { try { GetTbValue(m_pRs_a_c09,_variant_t("PIPE_C"),circle); break; } catch(_com_error &e) { TempStr.Format(_T("在\"环向焊缝应力系数库(A_C09)\"的PIPE_MAT=%s时读取数据有错"),cl); Exception::SetAdditiveInfo(TempStr); ReportExceptionErrorLV2(e); throw; } } else { // 如果上面找不到可能是因为材料的新旧名称 // CString *pMatNameArr; int Num; if(FindMaterialNameOldOrNew(cl,pMatNameArr,Num)) { while(Num>0) { Num--; strMaterialName = pMatNameArr[Num]; //zsy if(LocateFor(m_pRs_a_c09,_variant_t("PIPE_MAT"),CFoxBase::EQUAL,_variant_t(pMatNameArr[Num]))) { try { GetTbValue(m_pRs_a_c09,_variant_t("PIPE_C"),circle); IsFind=TRUE; break; } catch(_com_error &e) { TempStr.Format(_T("在\"环向焊缝应力系数库(A_C09)\"的PIPE_MAT=%s时读取数据有错"),cl); Exception::SetAdditiveInfo(TempStr); ReportExceptionErrorLV2(e); throw; } } } delete[] pMatNameArr; } if(IsFind==FALSE) { if( strMaterialName.IsEmpty() ) { strMaterialName = cl; } TableID = 3; strDlgCaption.Format(_T("请输入 %s 的环向焊缝应力系数:"),strMaterialName); //输入数据 InputMaterialParameter(strDlgCaption, strMaterialName, TableID); IsFind = TRUE; } else { break; } } } //while(1) if(st==_T("水管")) { if(pg==_T("Y") || pg==_T("y")) { l1=sqrt(w*circle*stress/wei2)*2.0; } else { l1=sqrt(w*circle*stress/wei2)*2.24; } l2=0.0241*pow((elastic*i/wei2),(1.0/3.0)); lmax=min(l1,l2); } else if(st==_T("汽管")) { if(pg==_T("Y") || pg==_T("y")) { l1=sqrt(w*circle*stress/wei1)*2.0; l3=sqrt(w*circle*stress3/wei2)*2.0; } else { l1=sqrt(w*circle*stress/wei1)*2.24; l3=sqrt(w*circle*stress3/wei2)*2.24; } l2=0.0241*pow((elastic*i/wei1),(1.0/3.0)); maxl12=min(l1,l2); lmax=min(maxl12,l3); } else { lmax=0; } */ } ////////////////////////////////////// //economic Pip thickness calculation// ////////////////////////////////////// void CHeatPreCal::pip_com(double &thick1_resu, double &thick2_resu, double &tb_resu, double &ts_resu) { double condu1_r,condu2_r,condu_out,cost_q,cost_s,cost_tot,cost_min,thick1,thick2,tb,ts; double D1,D2; // double MaxTb = in_tmax*m_HotRatio; //结合面允许最大温度=外保温材料的最大温度 * 一个系数(规程规定为0.9). double MaxTb = in_tmax;//结合面允许最大温度,从保温材料参数库(a_mat)中取MAT_TMAX字段,可修改该字段控制界面温度值. double nYearVal, nSeasonVal, Q; double QMax; //允许最大散热密度 bool flg=true; //进行散热密度的判断 thick1_resu=0; thick2_resu=0; cost_min=0; /* //应该没有温度的限制 if (Temp_pip<350.0) { return; } */ //选项中选择了判断散热密度,则查表。 if(bIsHeatLoss) { //查表获得介质温度允许的最大散热密度 if( !GetHeatLoss(m_pRsHeatLoss, Temp_pip, nYearVal, nSeasonVal, QMax) ) { } } //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 //从保温厚度规则表thicknessRegular获得 // for(thick1=m_thick1Start;thick1<=m_thick1Max;thick1+=m_thick1Increment) { for(thick2=m_thick2Start;thick2<=m_thick2Max;thick2+=m_thick2Increment) { // do temp_pip_com with thick1,thick2,ts,tb temp_pip_com(thick1,thick2,ts,tb); condu1_r=in_a0+in_a1*(Temp_pip+tb)/2.0+in_a2*(Temp_pip+tb)*(Temp_pip+tb)/4.0; condu2_r=out_a0+out_a1*(tb+ts)/2.0+out_a2*(tb+ts)*(tb+ts)/4.0; condu_out=co_alf; D1=2*thick1+D0; D2=2*thick2+D1; cost_q=7.2*pi*Mhours*heat_price*Yong*fabs(Temp_pip-Temp_env)*1e-6 /(1.0/condu1_r*log(D1/D0)+1.0/condu2_r*log(D2/D1)+2000.0/condu_out/D2); cost_s=(pi/4.0*(D1*D1-D0*D0)*in_price*1e-6+pi/4.0*(D2*D2-D1*D1)*out_price*1e-6 +pi*D2*pro_price*1e-3)*S; cost_tot=cost_q+cost_s; //tb<350) if((ts<MaxTs && tb<MaxTb) && (fabs(cost_min)<1E-6 || cost_min>cost_tot)) { flg = true; //选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式: //(介质温度-环境温度)/((外保温层外径/2000.0)*(1.0/内保温材料导热率*ln(内保温层外径/管道外径) + 1.0/外保温材料导热率*ln(外保温层外径/内保温层外径) ) + 1/传热系数) Q = (Temp_pip-Temp_env) / ( (D2/2000.0) * (1.0/condu1_r*log(D1/D0)+1.0/condu2_r*log(D2/D1)) + 1.0/co_alf ); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { cost_min=cost_tot; thick1_resu=thick1; thick2_resu=thick2; ts_resu=ts; tb_resu=tb;// } } } } return; } //////////////////////////////////////////////////// // economic plain thickness for complex calculation// ///////////////////////////////////////////////////// void CHeatPreCal::plain_com(double &thick1_resu, double &thick2_resu, double &tb_resu, double &ts_resu) { double condu1_r,condu2_r,condu_out,cost_q,cost_s,cost_tot,cost_min,thick1,thick2,tb,ts; // double MaxTb = in_tmax*m_HotRatio;//结合面允许最大温度=外保温材料的最大温度 * 一个系数(规程规定为0.9). double MaxTb = in_tmax;//结合面允许最大温度,从保温材料参数库(a_mat)中取MAT_TMAX字段,可修改该字段进行控制界面温度值. double MaxTs; //外表面允许最大温度 //对于防烫伤保温,保温结构外表面温度不应超过60摄氏度。 if( Temp_env <= 27 ) { //环境温度不高于27摄氏度时,设备和管道保温结构外表面温度不应超过50摄氏度; MaxTs = 50; } else { //环境温度高于27摄氏度时,保温结构外表面温度可比环境温度高25x摄氏度。 MaxTs = Temp_env + 25; } double nYearVal, nSeasonVal, Q; //保温结构外表面散热密度 double QMax; //允许最大散热密度 bool flg=true; //进行散热密度的判断 thick1_resu=0; thick2_resu=0; cost_min=0; //选项中选择了判断散热密度,则查表。 if(bIsHeatLoss) { //查表获得介质温度允许的最大散热密度 if( !GetHeatLoss(m_pRsHeatLoss, Temp_pip, nYearVal, nSeasonVal, QMax) ) { } } //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 //从保温厚度规则表thicknessRegular获得 for(thick1=m_thick1Start;thick1<=m_thick1Max;thick1+=m_thick1Increment) { for(thick2=m_thick2Start;thick2<=m_thick2Max;thick2+=m_thick2Increment) { // do temp_plain_com with thick1,thick2,ts,tb temp_plain_com(thick1,thick2,ts,tb); condu1_r=in_a0+in_a1*(Temp_pip+tb)/2.0+in_a2*(Temp_pip+tb)*(Temp_pip+tb)/4.0; condu2_r=out_a0+out_a1*(tb+ts)/2.0+out_a2*(tb+ts)*(tb+ts)/4.0; condu_out=co_alf; cost_q=3.6*Mhours*heat_price*Yong*fabs(Temp_pip-Temp_env)*1e-6 /(thick1/1000.0/condu1_r+thick2/1000.0/condu2_r+1.0/condu_out); cost_s=(thick1/1000.0*in_price+thick2/1000.0*out_price+pro_price)*S; cost_tot=cost_q+cost_s; if((ts<MaxTs && tb<MaxTb)) //ts<50 && tb<350 { if(fabs(cost_min)<1E-6 ) {//第一次 flg = true; //选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式: //(介质温度-环境温度)/(内保温厚/1000/内保温材料导热率 + 外保温厚/1000/外保温材料导热率 + 1/传热系数) Q = (Temp_pip-Temp_env)/(thick1/1000.0/condu1_r+thick2/1000.0/condu2_r+1.0/co_alf); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { cost_min=cost_tot; thick1_resu=thick1; thick2_resu=thick2; ts_resu=ts; tb_resu=tb; } // InsertToReckonCost(ts,tb,thick1,thick2,cost_tot,true); } else {//不是第一次 if(cost_min>cost_tot) { flg = true; //选选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式: //(介质温度-环境温度)/(内保温厚/1000/内保温材料导热率 + 外保温厚/1000/外保温材料导热率 + 1/传热系数) Q = (Temp_pip-Temp_env)/(thick1/1000.0/condu1_r+thick2/1000.0/condu2_r+1.0/co_alf); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { //前次费用大于本次费用 cost_min=cost_tot; thick1_resu=thick1; thick2_resu=thick2; ts_resu=ts; tb_resu=tb; } // InsertToReckonCost(ts,tb,thick1,thick2,cost_tot,false); } else {//前次费用小于本次费用 } } } } } return; } ////////////////////////////////////// //economic Pip thickness calculation// ////////////////////////////////////// void CHeatPreCal::pip_one(double &thick_resu, double &ts_resu) { double condu_r,condu_out,cost_q,cost_s,cost_tot,cost_min,thick,ts; double D1; double nYearVal, nSeasonVal, Q; double QMax; //允许最大散热密度 bool flg=true; //进行散热密度的判断 thick_resu=0; ts_resu=0; cost_min=0; //选项中选择了判断散热密度,则查表。 if(bIsHeatLoss) { //查表获得介质温度允许的最大散热密度 if( !GetHeatLoss(m_pRsHeatLoss, Temp_pip, nYearVal, nSeasonVal, QMax) ) { } } //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 //从保温厚度规则表thicknessRegular获得 // for(thick=m_thick2Start;thick<=m_thick2Max;thick+=m_thick2Increment) { // do temp_pip_one with thick,ts temp_pip_one(thick,ts); condu_r=in_a0+in_a1*(ts+Temp_pip)/2.0+in_a2*(ts+Temp_pip)*(ts+Temp_pip)/4.0; condu_out=co_alf; D1=2.0*thick+D0; cost_q=7.2*pi*Mhours*heat_price*Yong*fabs(Temp_pip-Temp_env)*1e-6 /(1.0/condu_r*log(D1/D0)+2000.0/condu_out/D1); cost_s=(pi/4.0*(D1*D1-D0*D0)*in_price*1e-6+pi*D1*pro_price*1e-3)*S; cost_tot=cost_q+cost_s; if(ts<MaxTs && (cost_tot<cost_min || fabs(cost_min)<1E-6)) { flg = true; //选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式: //(介质温度-环境温度)/((保温层外径/2000.0/材料导热率*ln(保温层外径/管道外径)) + 1/传热系数) Q = (Temp_pip-Temp_env)/(D1/2000.0/condu_r*log(D1/D0) + 1.0/co_alf); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { cost_min=cost_tot; thick_resu=thick; ts_resu=ts; } } } return; } ///////////////////////////////////////// //economic plain thickness calculation // //main program // //////////////////////////////////////// void CHeatPreCal::plain_one(double &thick_resu, double &ts_resu) { double condu_r,condu_out,cost_q,cost_s,cost_tot,cost_min,thick,ts; double nYearVal, nSeasonVal, Q ; double QMax; //允许最大散热密度 bool flg=true; //进行散热密度的判断 thick_resu=0; ts_resu=0; cost_min=0; //选项中选择了判断散热密度,则查表。 if(bIsHeatLoss) { //查表获得介质温度允许的最大散热密度 if( !GetHeatLoss(m_pRsHeatLoss, Temp_pip, nYearVal, nSeasonVal, QMax) ) { } } //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 //从保温厚度规则表thicknessRegular获得 // for(thick=m_thick2Start;thick<=m_thick2Max;thick+=m_thick2Increment) { // do temp_plain_one with thick,ts temp_plain_one(thick,ts); condu_r=in_a0+in_a1*(ts+Temp_pip)/2.0+in_a2*(ts+Temp_pip)*(ts+Temp_pip)/4.0; condu_out=co_alf; cost_q=3.6*Mhours*heat_price*Yong*fabs(Temp_pip-Temp_env)*1e-6 /((thick/1000.0/condu_r)+1.0/condu_out); cost_s=(thick/1000*in_price+pro_price)*S; cost_tot=cost_q+cost_s; if((cost_tot<cost_min || fabs(cost_min)<1E-6) && ts<MaxTs) { flg = true; //选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式: //(介质温度-环境温度)/(当前保温厚/(1000*材料导热率) + 1/传热系数) Q = (Temp_pip-Temp_env) / (thick / (1000*condu_r) + 1.0 / co_alf); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { cost_min=cost_tot; thick_resu=thick; ts_resu=ts; } } } return; } //------------------------------------保温计算------------------------------------------ ////////////////////////////////////////////////////////////// // C_ANALYS // ///////////////////////////////////////////////////////////// ///////////////////////////////////// //模 块 名: c_analys.prg // //功 能: 保温结构经济厚度计算 // //上级模块: MAIN_MENU // //下级模块: * // // SUPPORT* // //引 用 库: (1)pre_calc, // // (3)a_mat, // // (6)a_pipe, // // (8)a_stress,a_elas // //修改日期: // ///////////////////////////////////// void CHeatPreCal::C_ANALYS() { _variant_t TempValue; double thick_1,thick_2,temp_ts,temp_ts1,temp_tb; double pre_v1,pre_v2,pro_v,pro_wei; double pro_conduct; double pro_thi,pi_thi; double pre_wei1,pre_wei2; double d1,d2,d3,p_wei,w_wei,no_w,with_w,face_area; double a_config_hour; double dAmount; //数量. double tempVtf; long rec; long ERR; int IsStop; HRESULT hr; BOOL pi_pg=FALSE; //压力标识,大于3.92MPa为TRUE,否则为FALSE CString tempVts; CString pi_mat,mark,vol,steam; CString pi_site; CString last_mod; CString unit; CString strPlace; //安装地点。(室内或室外) CString TempStr; //临时的,输出到屏幕的字符串 CString cPipeType; //管道或设备的类型,为卷册号最后一个字符. CString strMedium; //介质名称 int nMethodIndex=0; //计算方法的索引值 int nTaIndex=0; //环境温度的取值索引 bool bNoCalInThi; //是否计算内保温层厚度 bool bNoCalPreThi; //是否计算外保温层厚度 double Temp_dew_point = 23; // 露点温度 double Temp_coefficient = 1; // 不同的规范增加的不同系数 double dUnitLoss; double dAreaLoss; BOOL bIsReCalc = FALSE; // 如果是保冷计算,是否需要重新用表面温度法校验外表面温度的值,和厚度 ch_cal=GetChCal(); if(ch_cal==4) { return; } // *注册 OPENATABLE(IRecordset,PASS); if(!LocateFor(IRecordset,_variant_t("PASS_MOD1"), CFoxBase::EQUAL,_variant_t("C_ANALYS"))) { TempStr.Format("无法在PASS表中的\"PASS_MOD1\"字段找到C_ANALYS \n有可能数据表为空或未添加数据"); ExceptionInfo(TempStr); return; } try { GetTbValue(IRecordset,_variant_t("PASS_LAST1"),last_mod); } catch(_com_error &e) { TempStr.Format(_T("在\"PASS表\"的PASS_MOD1=C_ANALYS时读取PASS_LAST1数据有错")); Exception::SetAdditiveInfo(TempStr); ReportExceptionErrorLV2(e); throw; } if(!LocateFor(IRecordset,_variant_t("PASS_MOD1"), CFoxBase::EQUAL,_variant_t(last_mod))) { TempStr.Format("无法在PASS表中的\"PASS_MOD1\"字段找到%s \r\n有可能数据表为空或未添加数据",last_mod); ExceptionInfo(TempStr); return; } TempValue=IRecordset->GetCollect(_variant_t("PASS_MARK1")); if(TempValue!=_variant_t("T")) { this->MessageBox(_T("不能计算, 必须先进行原始数据编辑!")); IRecordset->Close(); return; } IRecordset->Close(); CString sql; if (ch_cal==1) { try { //将C_PASS字段全部赋'Y' sql = "UPDATE [PRE_CALC] SET C_PASS='Y' WHERE EnginID='"+EDIBgbl::SelPrjID+"' "; theApp.m_pConnection->Execute(_bstr_t(sql), NULL, adCmdText ); OPENATABLE(IRecordset2,PRE_CALC); if(IRecordset2->adoEOF && IRecordset2->BOF) { ExceptionInfo(_T("原始数据表为空\n")); return; } start_num=1; IRecordset2->MoveLast(); stop_num=RecNo(IRecordset2); IRecordset2->Close(); } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } } else if(ch_cal==2) { try { //首先将C_PASS字段全部清空。 sql = "UPDATE [PRE_CALC] SET C_PASS='' WHERE EnginID='"+EDIBgbl::SelPrjID+"' "; theApp.m_pConnection->Execute(_bstr_t(sql), NULL, adCmdText ); sql = "SELECT * FROM [PRE_CALC] WHERE EnginID='"+EDIBgbl::SelPrjID+"' ORDER BY ID ASC"; _RecordsetPtr pRsCalc; pRsCalc.CreateInstance(__uuidof(Recordset)); pRsCalc->Open(_variant_t(sql), (IDispatch*)GetConnect(), adOpenStatic, adLockOptimistic, adCmdText); if(pRsCalc->adoEOF && pRsCalc->BOF) { ExceptionInfo(_T("原始数据表为空\n")); return; } start_num=1; pRsCalc->MoveLast(); stop_num=RecNo(pRsCalc); if( FALSE == RangeDlgshow(start_num,stop_num) ) { return; } //然后在指定的范围内,将C_PASS字段赋'Y' ReplaceAreaValue(pRsCalc, "c_pass", "Y", start_num, stop_num); pRsCalc->Close(); } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } } else if(ch_cal==3) { try { _RecordsetPtr IRecordset2; IRecordset2.CreateInstance(__uuidof(Recordset)); int iIsStop=0; //首先将C_PASS字段全部清空。 sql = "UPDATE [PRE_CALC] SET C_PASS='' WHERE EnginID='"+EDIBgbl::SelPrjID+"' "; theApp.m_pConnection->Execute(_bstr_t(sql), NULL, adCmdText ); // sql.Format(_T("SELECT c_pass,id,c_vol,c_name1,c_size,c_pi_thi,c_temp,c_name2, \ c_name3,c_pre_thi,c_place,c_mark ,EnginID FROM PRE_CALC where EnginID='%s' ORDER BY id ASC"),GetProjectName()); IRecordset2->CursorLocation = adUseClient; IRecordset2->Open(_variant_t(sql),_variant_t((IDispatch*)GetConnect()), adOpenDynamic,adLockOptimistic,adCmdText); SelectToCal(IRecordset2,&iIsStop); //MessageBox("在欲计算的记录C_PASS字段处输入'Y'"); IRecordset2->Close(); if(iIsStop) { return; } } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } } OPENATABLE(IRecConfig,A_CONFIG); if(IRecConfig->adoEOF && IRecConfig->BOF) { ExceptionInfo(_T("保温设计常数库(A_CONFIG)不能为空\n")); return; } try { IRecConfig->MoveFirst(); GetTbValue(IRecConfig,_variant_t("单位制"),unit); unit.MakeUpper(); GetTbValue(IRecConfig,_variant_t("主汽热价"),heat_price); GetTbValue( IRecConfig, _variant_t("年费用率"), S ); // by zsy 2007.01.11 GetTbValue(IRecConfig,_variant_t("年运行小时"),a_config_hour); m_dMaxD0 = vtof(IRecConfig->GetCollect(_variant_t("平壁与圆管的分界外径")) ); if( m_dMaxD0 <= 0 ) { //当分界外径不合理时,赋一个默认值. m_dMaxD0 = 2000; } } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } if(unit != _T("SI")) { //内部公式全部使用国际单位制计算,西南院程序公式使用工程制计算. //而西南院的放热系数ALPHA采用的是国际单位制,两者不一致计算结果有错误. heat_price=heat_price/4.1868; } IRecConfig->Close(); if( IRecCalc == NULL ) { hr=IRecCalc.CreateInstance(__uuidof(Recordset)); } TempStr.Format(_T("SELECT * FROM PRE_CALC WHERE EnginID='%s' ORDER BY ID ASC"),this->GetProjectName()); try { if(IRecCalc->State == adStateOpen) { IRecCalc->Close(); } IRecCalc->Open(_variant_t(TempStr),_variant_t((IDispatch*)GetConnect()), adOpenStatic,adLockOptimistic,adCmdText); EDIBgbl::pRsCalc = IRecCalc; //将原始数据的记录集可以在其他方法中使用. IRecCalc->MoveFirst(); } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } OPENATABLE(IRecMat,A_mat); if(IRecMat->adoEOF && IRecMat->BOF) { // ExceptionInfo(_T("保温材料参数库(A_MAT)不能为空\n")); // return; } //打开标准的材料库.(工程名为空的记录) OpenAProjectTable(m_pRs_CodeMat,"A_MAT",""); //打开防冻计算时新增数据的表。 OpenAProjectTable(m_pRsCongeal,"pre_calc_congeal",GetProjectName()); // 打开埋地管道保温计算时新增加的数据表 OpenAProjectTable(m_pRsSubterranean, "Pre_calc_Subterranean", GetProjectName()); // //将记录集IRecPipe改为成员的。每次计算只打开一次。 //目的:提高速度。 //打开管道参数库。 if(!OpenAssistantProjectTable(IRecPipe, "A_PIPE") ) { return; } //打开保温结构外表面允许最大散热密度 //在IPEDcode.mdb库中。 if( !OpenAssistantProjectTable(m_pRsHeatLoss, "HeatLoss") ) { return ; } //打开管道/设置外表面传热系数. if( !OpenAssistantProjectTable(m_pRsCon_Out, "CON_OUT")) { return ; } //打开计算放热系数时的计算公式。 if( !OpenAssistantProjectTable(m_pRsHeat_alfa, "放热系数取值表") ) { return ; } //打开保护材料的黑度 if( !OpenAssistantProjectTable(m_pRs_a_Hedu, "a_hedu") ) { return ; } // 土壤的导热系数 if( !OpenAssistantProjectTable(m_pRsLSo, "土壤的导热系数")) return; /* // 保温层外表面向周围空气的放热阻 if ( !OpenAssistantProjectTable(m_pRsFaceResistance, "Resistance") ) { return; } */ // 获得气象参数的露点温度 GetWeatherProperty( "Td_DewPoint", Temp_dew_point ); CCalcThickBase *lpMethodClass; // 指向不同方法对应的类 bool bIsPlane; // 保温对象类型的标志,true--平面,false--管道 //获得 //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 //从保温厚度规则表(thicknessRegular)中取出上面的值。 if( !GetThicknessRegular() ) { return ; } //保温界面温度不应超过外层保温材料最高使用温度的比例. if( !this->GetConstantDefine("ConstantDefine", "Ratio_MaxHotTemp", TempStr) ) { m_HotRatio = 1; //默认的值 }else { m_HotRatio = _tcstod(TempStr, NULL); } //保冷界面温度不应超过外层保冷材料最高使用温度的比例. if( !this->GetConstantDefine("ConstantDefine", "Ratio_MaxCoolTemp", TempStr) ) { m_CoolRatio = 1; //默认的值 }else { m_CoolRatio = _tcstod(TempStr, NULL); } // 外表面允许最大温度 if (!GetConstantDefine("ConstantDefine","FaceMaxTemp",TempStr)) { MaxTs = 50; }else { MaxTs = strtod(TempStr,NULL); } // 保冷时,规定为露点温度增加的一个常数 if ( !GetConstantDefine( "ConstantDefine", "DeltaTsd", Temp_coefficient ) ) { Temp_coefficient = 1; } // 如果是重新自动选择保温结构 if( giInsulStruct == 1 ) { if(IDYES==AfxMessageBox(IDS_REALLYAUTOSELALLMAT,MB_YESNO+MB_DEFBUTTON2+MB_ICONQUESTION)) { CEditOriginalData Original; Original.SetCurrentProjectConnect(theApp.m_pConnection); Original.SetPublicConnect(theApp.m_pConnectionCODE); Original.SetProjectID(EDIBgbl::SelPrjID); if( !Original.AutoSelAllMat() ) { return; } } } MinimizeAllWindow(); // 最小化所有的浏览窗口 Say(_T("开始保温计算 ")); // 进入循环体 while(!IRecCalc->adoEOF) { try { GetTbValue(IRecCalc,_variant_t("c_pass"),TempStr); if( TempStr.CompareNoCase("Y") ) { IRecCalc->MoveNext(); continue; } //原始数据的序号 m_nID = vtoi(IRecCalc->GetCollect(_variant_t("ID"))); // ***查有关材料价格、导热系数计算公式(或值) // &&外层保温材料 GetTbValue(IRecCalc,_variant_t("c_name2"),out_mat); out_mat.TrimRight(); // &&内层保温材料 GetTbValue(IRecCalc,_variant_t("c_name_in"),in_mat); in_mat.TrimRight(); // &&保护层材料 GetTbValue(IRecCalc,_variant_t("c_name3"),pro_mat); pro_mat.TrimRight(); //在黑度表中查找保护材料的黑度的时候。 //保护材料名称,是去掉后面括号的名称.如"铝皮(0.75)"则该值为"铝皮" pro_name = pro_mat; if( -1 != pro_name.Find("(",0) ) { pro_name = pro_name.Mid( 0, pro_name.Find("(",0) ); } } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在读取\"原始数据表(PRE_CALC)\"中出错\r\n"), m_nID); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } // ***单层保温 if (out_mat.IsEmpty()) { TempStr.Format(_T("原始数据序号为%d的记录,没有外保温材料!"),m_nID); ExceptionInfo(TempStr); IRecCalc->MoveNext(); continue; } if (pro_mat.IsEmpty()) { TempStr.Format(_T("原始数据序号为%d的记录,没有保护层材料!"),m_nID); ExceptionInfo(TempStr); IRecCalc->MoveNext(); continue; } try { if (!(IRecMat->adoEOF && IRecMat->BOF)) { IRecMat->MoveFirst(); } } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } if(!LocateFor(IRecMat,_variant_t("MAT_NAME"),CFoxBase::EQUAL, _variant_t(out_mat))) { //在当前工程的材料库中没找到,则去标准库中找(工程名为空).找到就将标准库中的材料增加到当前的工程中来 if (!FindStandardMat(IRecMat,out_mat)) { TempStr.Format(_T("原始数据序号为%d的记录无法在\"保温材料参数库(A_MAT)\"中的\"材料名称\"字段") _T("找到%s\r\n有可能数据表为空或未添加数据"), m_nID,out_mat); ExceptionInfo(TempStr); IRecCalc->MoveNext(); continue; } } try { //价格 GetTbValue(IRecMat,_variant_t("MAT_PRIC"),in_price); //外层保温材料的最高使用温度 //GetTbValue(IRecMat,_variant_t("MAT_TEMP"),in_tmax); //"MAT_TMAX"字段是"复合面允许最高温度" GetTbValue(IRecMat,_variant_t("MAT_TMAX"),in_tmax); if (in_tmax <= 0) { //若复合面允许最高温度未设置 double dTemp = vtof(IRecMat->GetCollect(_variant_t("MAT_TEMP"))); in_tmax = dTemp / 2;//复合面允许最高温度设置外层保温材料的最高使用温度的1/2 if (in_tmax <= 0) { //若外层保温材料的最高使用温度未设置,则复合面允许最高温度默认为350C。 in_tmax = 350; } } //导热系数基数 GetTbValue(IRecMat,_variant_t("MAT_A0"),in_a0); //导热系数一次项系数 GetTbValue(IRecMat,_variant_t("MAT_A"),in_a1); //导热系数二次项系数 GetTbValue(IRecMat,_variant_t("MAT_A1"),in_a2); //容重 GetTbValue(IRecMat,_variant_t("MAT_DENS"),in_dens); // 导热系数增加的比率 GetTbValue( IRecMat, _variant_t("MAT_RATIO"), in_ratio); //内部公式全部使用国际单位制计算,西南院程序公式使用工程制计算. //而西南院的放热系数ALPHA采用的是国际单位制,两者不一致计算结果有错误. if(unit != _T("SI")) { in_a0/=0.8598; in_a1/=0.8598; in_a2/=0.8598; } } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在读取\"保温材料参数库(A_MAT)\"中") _T("材料名称=%s时出错\r\n"),m_nID,out_mat); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } IRecMat->MoveFirst(); //查找保护材料的数据 if(!LocateFor(IRecMat,_variant_t("MAT_NAME"),CFoxBase::EQUAL, _variant_t(pro_mat))) { //在当前工程的材料库中没找到,则去标准库中找(工程名为空).找到就将标准库中的材料增加到当前的工程中来 if (!FindStandardMat(IRecMat, pro_mat)) { TempStr.Format(_T("原始数据序号为%d的记录无法在\"保温材料参数库(A_MAT)\"中的\"材料名称\"字段") _T("找到%s\r\n有可能数据表为空或未添加数据"), m_nID,pro_mat); ExceptionInfo(TempStr); IRecCalc->MoveNext(); continue; } } try { //价格 GetTbValue(IRecMat,_variant_t("MAT_PRIC"),pro_price); //导热系数基数 GetTbValue(IRecMat,_variant_t("MAT_A0"),pro_conduct); //容重 GetTbValue(IRecMat,_variant_t("MAT_DENS"),pro_dens); } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在读取\"保温材料参数库(A_MAT)\"中") _T("材料名称=%s时出错\n"),m_nID,pro_mat); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } //复合保温 in_mat.TrimRight(); if (!in_mat.IsEmpty()) { //将前面获得的外保温材料的参数赋给外保温材料的变量 out_a0 = in_a0; out_a1 = in_a1; out_a2 = in_a2; out_price = in_price; out_dens = in_dens; out_ratio = in_ratio; //查找内保温材料 IRecMat->MoveFirst(); if(!LocateFor(IRecMat,_variant_t("MAT_NAME"),CFoxBase::EQUAL, _variant_t(in_mat))) { //在当前工程的材料库中没找到,则去标准库中找(工程名为空).找到就将标准库中的材料增加到当前的工程中来 if (!FindStandardMat(IRecMat, in_mat)) { TempStr.Format(_T("原始数据序号为%d的记录无法在\"保温材料参数库(A_MAT)\"中的\"材料名称\"字段") _T("找到%s\r\n有可能数据表为空或未添加数据"), m_nID,in_mat); ExceptionInfo(TempStr); IRecCalc->MoveNext(); continue; } } try { //价格 GetTbValue(IRecMat,_variant_t("MAT_PRIC"),in_price); //导热系数基数 GetTbValue(IRecMat,_variant_t("MAT_A0"),in_a0); //导热系数一次项系数 GetTbValue(IRecMat,_variant_t("MAT_A"),in_a1); //导热系数二次项系数 GetTbValue(IRecMat,_variant_t("MAT_A1"),in_a2); //容重 GetTbValue(IRecMat,_variant_t("MAT_DENS"),in_dens); // 导热系数增加的比率,如果为保冷(1.5 - 1.7) GetTbValue( IRecMat, _variant_t("MAT_RATIO"), in_ratio ); //内部公式全部使用国际单位制计算,西南院程序公式使用工程制计算. //而西南院的放热系数ALPHA采用的是国际单位制,两者不一致计算结果有错误. if(unit != _T("SI")) { in_a0/=0.8598; in_a1/=0.8598; in_a2/=0.8598; } } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在读取\"保温材料参数库(A_MAT)\"中") _T("材料名称=%s时出错\r\n"),m_nID,in_mat); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } } try { //热价比主汽价 GetTbValue(IRecCalc,_variant_t("c_price"),Yong); //设计温度 GetTbValue(IRecCalc,_variant_t("c_temp"),Temp_pip); //外径 GetTbValue(IRecCalc,_variant_t("c_size"),D0); // Modifier zsy 2007.01.11 // 年费用率应该直接用常数据库中的数据. // //年费用率 // GetTbValue(IRecCalc,_variant_t("c_rate"),S); //年运行小时 GetTbValue(IRecCalc,_variant_t("c_hour"),Mhours); //判断运行工况 if( Mhours >= a_config_hour ) { hour_work = 1; //年运行工况 } else { hour_work = 0; //季节运行工况. } //环境温度 GetTbValue(IRecCalc,_variant_t("c_con_temp"),Temp_env); //环境温度的取值索引 nTaIndex = vtoi(IRecCalc->GetCollect(_variant_t("c_Env_Temp_Index"))); //风速 GetTbValue(IRecCalc,_variant_t("c_wind"),speed_wind); if (speed_wind < 0) { speed_wind = 0; } //保护层厚 GetTbValue(IRecCalc,_variant_t("c_pro_thi"),pro_thi); //壁厚 GetTbValue(IRecCalc,_variant_t("c_pi_thi"),pi_thi); //管道材质 GetTbValue(IRecCalc,_variant_t("c_pi_mat"),pi_mat); //压力标示 //GetTbValue(IRecCalc,_variant_t("c_pg"),pi_pg); //管内压力 m_dPipePressure = vtof(IRecCalc->GetCollect(_variant_t("c_Pressure"))); if (m_dPipePressure <= 3.92) // 用于管道上计算支吊架间距的参数 { pi_pg = TRUE; } else{ pi_pg = FALSE; } //备注 GetTbValue(IRecCalc,_variant_t("c_mark"),mark); //卷册号 GetTbValue(IRecCalc,_variant_t("c_vol"),vol); //管道或设备的类型,为卷册号最后一个字符. cPipeType = vol.Right(1); //汽管或水管的标示.主要用于计算管道上支吊架的间距。 GetTbValue(IRecCalc,_variant_t("c_steam"),steam); //安装地点. strPlace = vtos(IRecCalc->GetCollect(_variant_t("c_place"))); //获得计算放热系数的公式,的索引. m_nIndexAlpha = vtoi(IRecCalc->GetCollect(_variant_t("c_Alfa_Index"))); //数量 dAmount = vtof(IRecCalc->GetCollect(_variant_t("c_amount"))); //计算方法的索引值 nMethodIndex = vtoi(IRecCalc->GetCollect(_variant_t("C_CalcMethod_Index"))); // switch( bIsReCalc ) { case 1: nMethodIndex = nSurfaceTemperatureMethod; // 设置重新使用外表面温度法校核。 bIsReCalc = FALSE; // 只有当前的一条记录才校核 break; default: ; // 不改变计算方法 } //是否计算内保温层厚度 bNoCalInThi = vtob(IRecCalc->GetCollect(_variant_t("c_CalInThi"))); //是否计算外保温层厚度 bNoCalPreThi = vtob(IRecCalc->GetCollect(_variant_t("c_CalPreThi"))); //外表温度 temp_ts = vtof(IRecCalc->GetCollect(_variant_t("c_tb3"))); //内层保温厚 thick_1 = vtof(IRecCalc->GetCollect(_variant_t("c_in_thi"))); //外层保温厚 thick_2 = vtof(IRecCalc->GetCollect(_variant_t("c_pre_thi"))); //沿风速方向的平壁宽度 B = vtof(IRecCalc->GetCollect(_variant_t("c_B"))); if (B <= 0) { //默认值 B = 1000; } //介质名称 strMedium = vtos(IRecCalc->GetCollect(_variant_t("c_Medium"))); m_dMediumDensity = GetMediumDensity(strMedium); //根据介质名,查找其密度 } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在读取\"原始数据库(PRE_CALC)\"中时出错\r\n"),m_nID); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } ERR=0; //查找设备和管道保温结构外表面传热系数. try { if(pro_mat.Find(_T("抹面")) != -1) //保护材料为抹面时. { GetAlfaValue(m_pRsCon_Out, "out_dia", "con2", D0, co_alf); } else { GetAlfaValue(m_pRsCon_Out, "out_dia", "con1", D0, co_alf); } } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在读取\"con_out表\"中时出错\r\n"),m_nID); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } //用一个成员的记录指针,在计算之前就打开表[a_hedu] m_pRs_a_Hedu->MoveFirst(); //保护材料的黑度 if(LocateFor(m_pRs_a_Hedu,_variant_t("c_name"),CFoxBase::EQUAL, _variant_t(pro_name))==TRUE) { TempValue=m_pRs_a_Hedu->GetCollect(_variant_t("n_hedu")); hedu=TempValue; } else { hedu=0.23; //默认镀锌铁皮对应的黑度 } if(Yong*Temp_pip<-0.001) { TempStr.Format(_T("出现错误在记录: %d"),RecNo(IRecCalc)); AfxMessageBox(TempStr); ERR=1; } if(D0*in_price*in_a0*S*Mhours*speed_wind*pro_thi*pi_thi<0) { TempStr.Format(_T("序号为 %d 的记录,出现原则性错误! "),RecNo(IRecCalc)); AfxMessageBox(TempStr); ERR=1; } if(ERR==1) { if( IDYES == AfxMessageBox("是否停止计算?", MB_YESNO ) ) { return; } else { IRecCalc->MoveNext(); continue; } } // 确定保温对象类型 if( D0 >= m_dMaxD0 ) { //平面 bIsPlane = true; } else { //管道 bIsPlane = false; } switch( nMethodIndex ) { case nSurfaceTemperatureMethod: //外表面温度法计算保温厚度 //外表面温度为已知 INITDATA(CCalcThick_FaceTemp); //初始各成员值。将当前记录的原始数据传入到计算方法的类中 lpMethodClass = (CCalcThick_FaceTemp *)this; break; case nHeatFlowrateMethod: //允许散热密度法计算保温厚度 INITDATA(CCalcThick_HeatDensity); // lpMethodClass = (CCalcThick_HeatDensity *)this; break; case nPreventCongealMethod: //防冻结(热平衡)法计算保温厚度 INITDATA(CCalcThick_PreventCongeal) // lpMethodClass = (CCalcThick_PreventCongeal *)this; break; case nSubterraneanMethod: // 埋地管道保温计算方法 short nType; short nPipeCount; GetSubterraneanTypeAndPipeCount(m_nID, nType, nPipeCount); switch(nType) { case 1: // 有管沟通行 case 2: // 有管沟不通行 INITDATA(CCalcThick_SubterraneanObstruct); lpMethodClass = (CCalcThick_SubterraneanObstruct*)this; break; case 0: // 埋地的无管沟直埋 default: INITDATA(CCalcThick_SubterraneanNoChannel); //. lpMethodClass = (CCalcThick_SubterraneanNoChannel*)this; } if (nPipeCount <= 1) { in_mat = ""; // 内保温材料对应埋地的第二根管道的保温材料名称 } bIsPlane = false; // 埋地计算方法,只有管道的保温的计算公式 break; default: //if( nMethodIndex == nEconomicalThicknessMethod ) //默认为经济法计算保温厚 INITDATA(CCalcThick_Economy); //初始各成员值。将当前记录的原始数据传入到计算方法的类中. lpMethodClass = (CCalcThick_Economy *)this; } if( nMethodIndex == nSurfaceTemperatureMethod ) { //外表面温度法计算保温厚度 //外表面温度为已知 INITDATA(CCalcThick_FaceTemp); //初始各成员值。将当前记录的原始数据传入到计算方法的类中 lpMethodClass = (CCalcThick_FaceTemp *)this; } else if( nMethodIndex == nHeatFlowrateMethod ) { //允许散热密度法计算保温厚度 INITDATA(CCalcThick_HeatDensity); //初始各成员值。将当前记录的原始数据传入到计算方法的类中 lpMethodClass = (CCalcThick_HeatDensity *)this; } else if ( nMethodIndex == nPreventCongealMethod ) { //防冻结(热平衡)法计算保温厚度 INITDATA(CCalcThick_PreventCongeal); //初始各成员值。将当前记录的原始数据传入到计算方法的类中 lpMethodClass = (CCalcThick_PreventCongeal *)this; } else //if( nMethodIndex == nEconomicalThicknessMethod ) { //默认为经济法计算保温厚 INITDATA(CCalcThick_Economy); //初始各成员值。将当前记录的原始数据传入到计算方法的类中. lpMethodClass = (CCalcThick_Economy *)this; } //计算前,先将各变量初始化 temp_tb = 0.0; //保温内外层界面温度 pre_wei1 = pre_wei2 = pro_wei = 0.0; //保温内外层、保护层重量 p_wei = w_wei = with_w = no_w = 0.0; pre_v1 = pre_v2 = pro_v = 0.0; //保温内外层体积 distan = 0.0; //支吊架间距 face_area = 1; //如果是平面时,则为1, 否则为管道将重新计算. thick_3 = pro_thi; //thick_3=保护厚 in_mat.TrimRight(); if( !in_mat.IsEmpty() )//为复合保温 { if( bIsPlane ) { //复合保温平壁. //计算保温厚. 2005.05.24 if ( bNoCalInThi || bNoCalPreThi ) //输入保温层厚度 { // 根据已知的保温厚度,计算外表面温度,和界面温度 lpMethodClass->CalcPlain_Com_InputThick(thick_1,thick_2,temp_tb,temp_ts); } else { // 保温厚度没有输入,需要计算 lpMethodClass->CalcPlain_Com(thick_1,thick_2,temp_tb,temp_ts); ////////////////////////////////////////////////////////////////////////// // 放热系数在计算之前就确定好是查表还是按公式计算 [11/17/2005] /* while(1) { temp_ts1 = temp_ts; //根据用户选择的公式重新计算放热系数. 成功返回1. if( CalcAlfaValue(temp_ts, D0+2*thick_1+2*thick_2) ) { //根据新的放热系数,再计算保温厚. lpMethodClass->CalcPlain_Com(thick_1,thick_2,temp_tb,temp_ts); if( fabs(temp_ts1-temp_ts) <= TsDiff) { break; } } else { //计算放热系数时,出错.或者是用查表所得的值去计算厚度,不需要再循环. break; } } */ } //输出到屏幕的字符串 TempStr.Format(_T("平壁 \t记录号 \t温度 \t内层保温厚 \t外层保温厚 \t结合面温度 \t外表面温度 \r\n") _T("\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f"), m_nID,Temp_pip,thick_1,thick_2,temp_tb,temp_ts); pre_v1=thick_1/1000; //内保温层的体积. pre_v2=thick_2/1000; //外保温层的体积. pro_v=thick_3/1000; //保护层的体积 pre_wei1=pre_v1*in_dens; //内保温层的重量 pre_wei2=pre_v2*out_dens; pro_wei=pro_v*out_dens; //end if ( 复合保温平壁 ) } else { //复合保温管道 if ( bNoCalPreThi || bNoCalInThi ) //2005.05.24 { //指定保温厚度,计算外表面温度和界面温度 lpMethodClass->CalcPipe_Com_InputThick(thick_1,thick_2,temp_tb,temp_ts); } else { //复合保温管道 lpMethodClass->CalcPipe_Com(thick_1,thick_2,temp_tb,temp_ts); /* while(1) { temp_ts1 = temp_ts; if( CalcAlfaValue(temp_ts, D0+2*thick_1+2*thick_2) ) { //根据新的放热系数,再计算保温厚. lpMethodClass->CalcPipe_Com(thick_1,thick_2,temp_tb,temp_ts); if( fabs(temp_ts1-temp_ts) <= TsDiff ) { break; } } else { //计算放热系数时,出错.或者是用查表所得的值去计算厚度,不需要再循环. break; } } */ } //输出到屏幕的字符串 TempStr.Format(_T("管道 \t记录号 \t温度 \t直径 \t内层保温厚 \t外层保温厚 \t结合面温度 \t外表面温度 \r\n") _T("\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f"), m_nID,Temp_pip,D0,thick_1,thick_2,temp_tb,temp_ts); //求体积和重量 d1=D0+2*thick_1; d2=d1+2*thick_2; d3=d2+2*pro_thi; pre_v1=pi/4*(d1*d1-D0*D0)/1E6; pre_wei1=pre_v1*in_dens; pre_v2=pi/4*(d2*d2-d1*d1)/1E6; pre_wei2=pre_v2*out_dens; pro_v=pi/4*(d3*d3-d2*d2)/1E6; pro_wei=pro_v*pro_dens; //在管道参数库中获得指定外径和壁厚的管重和水重 if( !GetPipeWeithAndWaterWeith(IRecPipe,D0,pi_thi,"PIPE_WEI",p_wei,"WATER_WEI",w_wei) ) { //在管道参数库中没有找到对应外径的记录. //重新计算 p_wei=pi/4*7850*(D0*D0-(D0-2*pi_thi)*(D0-2*pi_thi))/1000000; w_wei=pi/4*(D0-2*pi_thi)*(D0-2*pi_thi)/1000; } //无水单重 no_w=p_wei+pre_wei1+pre_wei2+pro_wei; //有水单重 with_w=no_w+w_wei; //外表面积 face_area=pi*d3/1000; //管道或设备类型不为S,M,O if( cPipeType.CompareNoCase(_T("S")) && cPipeType.CompareNoCase(_T("M")) && cPipeType.CompareNoCase(_T("O")) ) { p_wei=w_wei=no_w=with_w=0; } //***仅汽水管道、油管道算间距 distan=0; //if( !cPipeType.CompareNoCase(_T("S")) || !cPipeType.CompareNoCase(_T("M")) || !cPipeType.CompareNoCase(_T("O")) ) //{ try { distan = GetSupportSpan(D0,pi_thi,pi_mat,m_dPipePressure,m_dMediumDensity, Temp_pip,no_w-p_wei); } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为%d的记录在计算时出错\r\n"), m_nID); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } TempStr.Format(_T("管道 \t记录号 \t间距Lmax\t温度 \t直径 \t内层保温厚 \t外层保温厚 \t结合面温度 \t外表面温度 \r\n") _T("\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f"), m_nID,distan,Temp_pip,D0,thick_1,thick_2,temp_tb,temp_ts); //} }// end (复合保温管道) } else//单层保温 { temp_tb = 0; // 单层没有界面温度 thick_1 = 0; // 单层没有内保温厚度 if( bIsPlane )//单层保温平壁 { if ( bNoCalPreThi || bNoCalInThi ) //手工输入保温层厚度 { //根据保温厚度,计算外表面温度 lpMethodClass->CalcPlain_One_InputThick(thick_2,temp_ts); } else { lpMethodClass->CalcPlain_One(thick_2,temp_ts); /* while(1) { temp_ts1 = temp_ts; //根据新的放热系数,再计算保温厚. if( CalcAlfaValue(temp_ts, D0+2*thick_2) ) { lpMethodClass->CalcPlain_One(thick_2,temp_ts); if( fabs(temp_ts1-temp_ts) <= TsDiff) { break; } } else { //计算放热系数时,出错.或者是用查表所得的值去计算厚度,不需要再循环. break; } } */ } //输出到屏幕的字符串 TempStr.Format(_T("平壁 \t记录号 \t温度 \t保温厚 \t外表面温度 \r\n") _T("\t%d\t%.2f\t%.2f\t%.2f"), m_nID,Temp_pip,thick_2,temp_ts); pre_v2=thick_2/1000; //计算保温层体积 pro_v=pro_thi/1000; //保护层体积 pre_wei2=pre_v2*in_dens;//保温层重量 pro_wei=pro_v*pro_dens; //end if (单层保温平壁) } else {//单层保温管道 if ( bNoCalPreThi || bNoCalInThi ) { //根据保温厚度,计算外表面温度. lpMethodClass->CalcPipe_One_InputThick(thick_2,temp_ts); } else { lpMethodClass->CalcPipe_One(thick_2,temp_ts); /* while(1) { //根据新的放热系数,再计算保温厚. temp_ts1 = temp_ts; if( CalcAlfaValue(temp_ts, D0+2*thick_2) ) { lpMethodClass->CalcPipe_One(thick_2,temp_ts); if( fabs(temp_ts1-temp_ts) <= TsDiff ) { break; } } else { //计算放热系数时,出错.或者是用查表所得的值去计算厚度,不需要再循环. break; } } */ } TempStr.Format(_T("管道 \t记录号 \t温度 \t直径 \t保温厚 \t外表面温度 \r\n") _T("\t%d\t%.2f\t%.2f\t%.2f\t%.2f"), m_nID,Temp_pip,D0,thick_2,temp_ts); //计算体积与重量 d1=D0+2*thick_2; d3=D0+2*thick_2+2*pro_thi; pre_v2=pi/4*(d1*d1-D0*D0)/1000000; pre_wei2=pre_v2*in_dens; pro_v=pi/4*(d3*d3-d1*d1)/1000000; pro_wei=pro_v*pro_dens; //在管道参数库中获得指定外径和壁厚的管重和水重 if( !GetPipeWeithAndWaterWeith(IRecPipe,D0,pi_thi,"PIPE_WEI",p_wei,"WATER_WEI",w_wei) ) { //在管道参数库中没有找到对应外径的记录. //重新计算 p_wei=pi/4*7850*(D0*D0-(D0-2*pi_thi)*(D0-2*pi_thi))/1000000; // w_wei=pi/4*(D0-2*D0)*(D0-2*D0)/1000; // FoxPro中的公式 w_wei = pi / 4 * ( D0 - 2 * pi_thi ) * ( D0 - 2 * pi_thi ) / 1000; } //无水单重 no_w=p_wei+pre_wei2+pro_wei; //有水单重 with_w=no_w+w_wei; //外表面积 face_area=pi*(D0+2*thick_2+2*pro_thi)/1000; //如果管道类型不为汽水管道或油管道 if( cPipeType.CompareNoCase(_T("S")) && cPipeType.CompareNoCase(_T("M")) && cPipeType.CompareNoCase(_T("O")) ) { p_wei=w_wei=no_w=with_w=0; } //***仅汽水管道或油管道算间距 distan=0; //if( !cPipeType.CompareNoCase(_T("S")) || !cPipeType.CompareNoCase(_T("M")) || !cPipeType.CompareNoCase(_T("O")) ) //{ try { distan = GetSupportSpan(D0,pi_thi,pi_mat,m_dPipePressure,m_dMediumDensity, Temp_pip,no_w-p_wei); } catch(_com_error &e) { TempStr.Format(_T("原始数据序号为 %d 的记录在计算时出错\r\n"), m_nID); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } TempStr.Format(_T("管道 \t记录号 \t间距Lmax\t温度 \t直径 \t保温厚 \t外表面温度 \r\n") _T("\t%d\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f"), m_nID,distan,Temp_pip,D0,thick_2, temp_ts); //} }// end (单层保温管道) }//end 单层 if ( !bNoCalPreThi && !bNoCalInThi ) // 指定的保温厚度 { if ( Temp_pip < Temp_env ) { // 这种在不同的行业,计算方法 if ( nMethodIndex != nSurfaceTemperatureMethod ) { if ( temp_ts < Temp_dew_point + Temp_coefficient ) // 露点温度加一个修正值(不同的规范可能会有所不同,1-3℃) { //IRecCalc->PutCollect( _variant_t("c_CalcMethod_Index"), _variant_t((long)nSurfaceTemperatureMethod) ); IRecCalc->PutCollect( _variant_t("c_tb3"), _variant_t(Temp_dew_point + Temp_coefficient)); bIsReCalc = 1; // 使用表面温度法重新校核 TempStr.Format("提示: 序号为 %d 的记录在计算时,使用了外表面温度法进行校核!\r\n", m_nID); ExceptionInfo( TempStr ); // 保存前一次计算的中间值 IRecCalc->Update(); continue; } } } } //将字符串显示到屏幕上。(写入到文档中) DisplayRes(TempStr); //显示错误信息 if ( lpMethodClass->GetExceptionInfo(TempStr) ) { if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); } //是否停止运算 IsStop=1; Cancel(&IsStop); if(IsStop==0) { return; } dUnitLoss = lpMethodClass->dQ; if (dUnitLoss < 0) { dUnitLoss = 0; } dAreaLoss = dUnitLoss * face_area * dAmount; //---------------------------- //将计算的结果写入到数据库中 try { //内保温厚 IRecCalc->PutCollect(_variant_t("c_in_thi"),_variant_t(thick_1)); //外保温厚/单层的保温层厚度 IRecCalc->PutCollect(_variant_t("c_pre_thi"),_variant_t(thick_2)); //外表面温度 IRecCalc->PutCollect(_variant_t("c_tb3"),_variant_t(temp_ts)); //界面温度 IRecCalc->PutCollect(_variant_t("c_ts"),_variant_t(temp_tb)); //单位散热密度 IRecCalc->PutCollect(_variant_t("c_HeatFlowrate"),_variant_t(dUnitLoss)); //热损失=外表面积*数量*单位散热密度 IRecCalc->PutCollect(_variant_t("c_lost"),_variant_t(dAreaLoss)); //保温结构投资年总费用 IRecCalc->PutCollect(_variant_t("c_srsb"),_variant_t((double)0)); //精确值对应保温结构投资年总费用 IRecCalc->PutCollect(_variant_t("cal_srsb"),_variant_t((double)0)); //外表温层厚度精确值 IRecCalc->PutCollect(_variant_t("cal_thi"),_variant_t((double)0)); //内保温层单位重量 IRecCalc->PutCollect(_variant_t("c_in_wei"),_variant_t(pre_wei1)); //外保温层单位重量/单层的保温层单重 IRecCalc->PutCollect(_variant_t("c_pre_wei"),_variant_t(pre_wei2)); //保护层单位重量 IRecCalc->PutCollect(_variant_t("c_pro_wei"),_variant_t(pro_wei)); //管道单重 IRecCalc->PutCollect(_variant_t("c_pipe_wei"),_variant_t(p_wei)); //水单重 IRecCalc->PutCollect(_variant_t("c_wat_wei"),_variant_t(w_wei)); //有水单重 IRecCalc->PutCollect(_variant_t("c_with_wat"),_variant_t(with_w)); //无水单重 IRecCalc->PutCollect(_variant_t("c_no_wat"),_variant_t(no_w)); //外表面积 IRecCalc->PutCollect(_variant_t("c_area"),_variant_t(face_area)); //内保温层单位体积 IRecCalc->PutCollect(_variant_t("c_v_in"),_variant_t(pre_v1)); //外保温层单位体积/单层的保温层单位体积 IRecCalc->PutCollect(_variant_t("c_v_pre"),_variant_t(pre_v2)); //保护层单位体积 IRecCalc->PutCollect(_variant_t("c_v_pro"),_variant_t(pro_v)); //管道支吊架间距 IRecCalc->PutCollect(_variant_t("c_distan"),_variant_t(distan)); IRecCalc->Update(); } catch(_com_error &e) { ReportExceptionErrorLV2(e); throw; } IRecCalc->MoveNext(); continue; //以下代码为老版本的,现在没有用到. //删除,没有影响 by ligb on 2010.06.15 }//ENDDO //计算保温材料的全体积. this->E_Predat_Cubage(); // Say(_T("计算完毕!")); // CLOSE DATA OPENATABLE(IRecPass,PASS); // LOCATE FOR pass_mod1="C_ANALYS" if(!LocateFor(IRecPass,_variant_t("PASS_MOD1"),CFoxBase::EQUAL, _variant_t("C_ANALYS"))) { TempStr.Format(_T("无法在PASS表中的\"PASS_MOD1\"字段找到C_ANALYS \r\n有可能数据表为空或未添加数据")); ExceptionInfo(TempStr); return; } // rec=RECNO() rec=RecNo(IRecPass); IRecPass->MoveFirst(); // REPL NEXT rec pass_mark1 WITH "T" ReplNext(IRecPass,_variant_t("PASS_MARK1"),_variant_t("T"),rec); // SKIP IRecPass->MoveNext(); // REPL NEXT 130 pass_mark1 WITH "F" ReplNext(IRecPass,_variant_t("PASS_MARK1"),_variant_t("T"),130); // USE // RETURN IRecPass->Close(); IRecCalc->Close(); IRecMat->Close(); IRecPipe->Close(); } void CHeatPreCal::SetChCal(int Ch) { ch_cal=Ch; } int CHeatPreCal::GetChCal() { return ch_cal; } //////////////////////////////////////////////////////////// // // 在需要指定计算的‘开始’与‘结束’范围时调用 // // Start 需要计算的起始位置 // End 需要计算的结束位置 // BOOL CHeatPreCal::RangeDlgshow(long &Start,long &End) { AfxMessageBox("范围对话框"); return TRUE; } /////////////////////////////////////////////////////////// // // 当需要选择需要计算的数据时调用 // // IRecordset 传入一张表的记录集合 // // 在这张表的C_PASS的字段输入Y,这条记录将会被计算 // void CHeatPreCal::SelectToCal(_RecordsetPtr &IRecordset,int *pIsStop) { } //////////////////////////////////////////////////// // // 设置工程名(ID) // // Name[in] 工程的ID号 // void CHeatPreCal::SetProjectName(CString &Name) { m_ProjectName=Name; } ///////////////////////////////////////////////////// // // 返回工程名(ID) // CString& CHeatPreCal::GetProjectName() { return m_ProjectName; } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // // 打开某个工程的表的记录 // // IRecordsetPtr[out] 返回需要打开的表的记录集 // pTableName[in] 需要打开的表名 // pProjectName[in] 需打开的工程名(ID) // // 如果函数成功返回TRUE,否则返回FALSE // // 调用此函数前需 SetConnect 设置数据库的连接 // BOOL CHeatPreCal::OpenAProjectTable(_RecordsetPtr &IRecordset, LPCTSTR pTableName, LPCTSTR pProjectName) { CString SQL; if(GetConnect()==NULL) { ReportExceptionErrorLV1(_T("连接不可用")); return FALSE; } if(pTableName==NULL) { ReportExceptionErrorLV1(_T("表名不可用")); return FALSE; } if(pProjectName==NULL) { SQL.Format(_T("SELECT * FROM %s WHERE EnginID='%s'"),pTableName,m_ProjectName); } else if(pProjectName==_T("")) { SQL.Format(_T("SELECT * FROM %s where EnginID is NULL"),pTableName); } else { SQL.Format(_T("SELECT * FROM %s WHERE EnginID='%s'"),pTableName,pProjectName); } try { IRecordset.CreateInstance(__uuidof(Recordset)); IRecordset->Open(_variant_t(SQL),_variant_t((IDispatch*)GetConnect()), adOpenStatic,adLockOptimistic,adCmdText); } catch(_com_error &e) { ReportExceptionErrorLV1(e); return FALSE; } return TRUE; } ////////////////////////////////////////////// // // 判断是否停止计算时调用此函数 // // pState[out]当pState返回0时则停止计算, // 否则继续运算。 // void CHeatPreCal::Cancel(int *pState) { if(pState) { *pState=1; } } ////////////////////////////////////////////////// // // 设置辅助数据库的连接 // // IConnection[in] 数据库的连接的智能指针的引用 // void CHeatPreCal::SetAssistantDbConnect(_ConnectionPtr &IConnection) { m_AssistantConnection=IConnection; } /////////////////////////////////////////////////////// // //返回辅助数据库的连接 // _ConnectionPtr& CHeatPreCal::GetAssistantDbConnect() { return m_AssistantConnection; } ///////////////////////////////////////////////////////////////////////////////////// // // 打开辅助数据库的表 // // IRecordset[out] 返回以打开表的记录集的智能指针 // pTableName[in] 需打开的表名 // // 函数成功返回TRUE,否则返回FALSE // BOOL CHeatPreCal::OpenAssistantProjectTable(_RecordsetPtr &IRecordset, LPCTSTR pTableName) { CString SQL; if(GetAssistantDbConnect()==NULL) { ReportExceptionErrorLV1(_T("连接不可用")); return FALSE; } if(pTableName==NULL) { ReportExceptionErrorLV1(_T("表名不可用")); return FALSE; } SQL.Format(_T("SELECT * FROM %s"),pTableName); try { if ( IRecordset == NULL ) IRecordset.CreateInstance(__uuidof(Recordset)); if ( IRecordset->State == adStateOpen ) IRecordset->Close(); IRecordset->Open(_variant_t(SQL),_variant_t((IDispatch*)GetAssistantDbConnect()), adOpenStatic,adLockOptimistic,adCmdText); } catch(_com_error &e) { ReportExceptionErrorLV1(e); return FALSE; } return TRUE; } ///////////////////////////////////////////////////////////// // // 设置Material数据库的路径 // // pMaterialPath[in] 数据库所在的文件夹 // void CHeatPreCal::SetMaterialPath(LPCTSTR pMaterialPath) { HRESULT hr; CString strSQL; BOOL IsPathChange=FALSE; //数据库路径与以前的路径是否相同 CString FullDbFilePath; CalSupportSpan.m_strMaterialDbPath = m_MaterialPath+"Material.mdb"; //计算支吊架间距 CalSupportSpan.m_pConMaterial = theApp.m_pConMaterial; m_IMaterialCon = theApp.m_pConMaterial; return ; try { if(pMaterialPath==NULL) { if(m_IMaterialCon==NULL) { return; } else if(m_IMaterialCon->State & adStateOpen) { m_IMaterialCon->Close(); } return; } if(m_MaterialPath==pMaterialPath) IsPathChange=TRUE; m_MaterialPath=pMaterialPath; // CCalcDll.m_MaterialPath=m_MaterialPath+"material.mdb"; FullDbFilePath=m_MaterialPath+"material.mdb"; if(m_IMaterialCon==NULL) { hr=m_IMaterialCon.CreateInstance(__uuidof(Connection)); if(FAILED(hr)) return; } if(m_IMaterialCon->State==adStateClosed) { strSQL = _T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+FullDbFilePath+"'"); m_IMaterialCon->Open(_bstr_t(strSQL),"","",-1); return; } if(IsPathChange==FALSE) return; strSQL =_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='"+FullDbFilePath+"'"); m_IMaterialCon->Close(); m_IMaterialCon->Open(_bstr_t(strSQL),"","",-1); } catch(_com_error &e) { ReportExceptionErrorLV1(e); return; } } //////////////////////////////////////////////////////// // // 返回Material数据库所在的文件夹 // LPCTSTR CHeatPreCal::GetMaterialPath() { return m_MaterialPath; } /////////////////////////////////////////////////////////////////////////////////////////// // // 从Material数据库中的CL_OLD_NEW表中寻找与MatName材料名相对应的材料。 // 先找与MatName对应的新材料,如果未找到再找与MatName对应的旧材料名 // // MatName[in] 输入寻找与之对应的材料名 // pFindName[out] 返回找到的材料名的数组 // Num[out] pFindName的数组大小 // // 如果函数成功找到返回TRUE,否则返回FALSE // 如果返回TRUE,pFindName需用delete释放内存。 // 如果返回FALSE,pFindName与Num将无意义 // BOOL CHeatPreCal::FindMaterialNameOldOrNew(LPCTSTR MatName, CString *&pFindName, int &Num) { int FindNum=0; CString MatStr; CString SQL; _RecordsetPtr IRecord; if(m_IMaterialCon==NULL || m_IMaterialCon->State==adStateClosed || MatName==NULL) return FALSE; MatStr=MatName; MatStr.TrimLeft(); MatStr.TrimRight(); if(MatStr.IsEmpty()) return FALSE; try { IRecord.CreateInstance(__uuidof(Recordset)); SQL.Format(_T("SELECT NEWCL FROM Material_OLD_NEW WHERE OLD='%s'"),MatStr); IRecord->Open(_variant_t(SQL),_variant_t((IDispatch*)m_IMaterialCon), adOpenStatic,adLockOptimistic,adCmdText); if(IRecord->adoEOF && IRecord->BOF) { SQL.Format(_T("SELECT OLD FROM Material_OLD_NEW WHERE NEWCL='%s'"),MatStr); IRecord->Close(); IRecord->Open(_variant_t(SQL),_variant_t((IDispatch*)m_IMaterialCon), adOpenStatic,adLockOptimistic,adCmdText); if(IRecord->adoEOF && IRecord->BOF) return FALSE; } IRecord->MoveFirst(); FindNum=0; while(!IRecord->adoEOF) { FindNum++; IRecord->MoveNext(); } pFindName=new CString[FindNum]; Num=FindNum; IRecord->MoveFirst(); FindNum=0; while(!IRecord->adoEOF) { GetTbValue(IRecord,_variant_t((short)0),pFindName[FindNum]); FindNum++; IRecord->MoveNext(); } } catch(_com_error &e) { ReportExceptionErrorLV1(e); return FALSE; } return TRUE; } //功能: //根据单体积,计算全体积. // bool CHeatPreCal::E_Predat_Cubage() { CString sql; CString amou,v_pre,v_in,tv_pre,tv_in,tv_pro,v_pro; double f_v_pre,f_amou,f_v_in,f_v_pro,amount,pro_thi; _variant_t num,varTemp; _RecordsetPtr m_pRecordset; m_pRecordset.CreateInstance(__uuidof(Recordset)); sql.Format(_T("SELECT * FROM pre_calc where EnginID='%s'"),EDIBgbl::SelPrjID); try { m_pRecordset->Open(_variant_t(sql), theApp.m_pConnection.GetInterfacePtr(), // 获取库接库的IDispatch指针 adOpenDynamic, adLockOptimistic, adCmdText); while(!m_pRecordset->adoEOF) { // 不须要叛断序号, // num=m_pRecordset->GetCollect("c_num"); // if (num.vt != VT_NULL && num.vt != VT_EMPTY) { GetTbValue(m_pRecordset,_variant_t("c_amount"),amount); m_pRecordset->PutCollect(_variant_t("c_amou"),_variant_t(amount)); GetTbValue(m_pRecordset,_variant_t("c_amou"),f_amou); GetTbValue(m_pRecordset,_variant_t("c_v_pre"),f_v_pre); GetTbValue(m_pRecordset,_variant_t("c_v_in"),f_v_in); tv_pre.Format(_T("%f"),f_v_pre*f_amou); tv_in.Format(_T("%f"),f_v_in*f_amou); m_pRecordset->PutCollect("c_tv_pre",_variant_t(tv_pre)); m_pRecordset->PutCollect("c_tv_in",_variant_t(tv_in)); GetTbValue(m_pRecordset,_variant_t("c_pro_thi"),pro_thi); if(pro_thi > 5.0) { GetTbValue(m_pRecordset,_variant_t("c_v_pro"),f_v_pro); tv_pro.Format("%f",f_v_pro*f_amou); m_pRecordset->PutCollect("c_tv_pro",_variant_t(tv_pro)); } else { m_pRecordset->PutCollect("c_tv_pro",_variant_t("0")); } m_pRecordset->Update(); }// if(num.vt!=VT_NULL) m_pRecordset->MoveNext(); }//while(!m_pRecordset->adoEOF) } catch(_com_error &e) { ReportExceptionError(e); return false; } return true; } // short CHeatPreCal::GetThicknessRegular() { //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 CString strSQL,strMessage; _variant_t var; _RecordsetPtr pRs; pRs.CreateInstance(__uuidof(Recordset)); try { strSQL = "SELECT * FROM [thicknessRegular] WHERE EnginID='"+EDIBgbl::SelPrjID+"' "; pRs->Open(_variant_t(strSQL), GetConnect().GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if( pRs->GetRecordCount() > 0 ) { var = pRs->GetCollect(_variant_t("thick1Start")); //内层保温允许最小厚度 m_thick1Start = vtoi( var ); var = pRs->GetCollect(_variant_t("thick1Max")); //内层保温允许最大厚度 m_thick1Max = vtoi( var ); var = pRs->GetCollect(_variant_t("thick1Increment")); //内层保温厚度最小增量 m_thick1Increment = vtoi( var ); var = pRs->GetCollect(_variant_t("thick2Start")); //外层保温允许最小厚度 m_thick2Start = vtoi( var ); var = pRs->GetCollect(_variant_t("thick2Max")); //外层保温允许最大厚度 m_thick2Max = vtoi( var ); var = pRs->GetCollect(_variant_t("thick2Increment"));//外层保温厚度最小增量 m_thick2Increment = vtoi( var ); //检查数据的正确性。 if( (m_thick1Max<m_thick1Start) )//|| () || || fabs(m_thick2Increment) <= 1e-6) { strMessage.Format("内层保温允许最大厚度%dmm小于内层保温允许最小厚度%dmm",m_thick1Max,m_thick1Start); AfxMessageBox(strMessage); return false; } if(m_thick2Max < m_thick2Start) { strMessage.Format("外层保温允许最大厚度%dmm小于外层保温允许最小厚度%dmm",m_thick2Max,m_thick2Start); AfxMessageBox(strMessage); return false; } if( m_thick1Increment <= 1e-6 ) { strMessage.Format("内层保温厚度最小增量%dmm太小.",m_thick1Increment); AfxMessageBox(strMessage); return false; } if( m_thick2Increment <= 1e-6 ) { strMessage.Format("外层保温厚度最小增量%dmm太小.",m_thick2Increment); AfxMessageBox(strMessage); return false; } if( m_thick1Start <= 1e-6 ) { strMessage.Format("内层保温允许最小厚度%dmm太小.",m_thick1Start); AfxMessageBox(strMessage); return false; } if( m_thick2Start <= 1e-6 ) { strMessage.Format("外层保温允许最小厚度%dmm太小.",m_thick2Start); AfxMessageBox(strMessage); return false; } if( m_thick1Max <= 1e-6 ) { strMessage.Format("内层保温允许最大厚度%dmm太小.",m_thick1Max); AfxMessageBox(strMessage); return false; } if( m_thick2Max <= 1e-6 ) { strMessage.Format("外层保温允许最大厚度%dmm太小.",m_thick2Max); AfxMessageBox(strMessage); return false; } } else { if( IDNO == AfxMessageBox("保温厚度规则库中没有记录,是否按默认的数据进行计算?",MB_YESNO) ) { return false; } m_thick1Start = 30; //内层保温允许最小厚度 m_thick1Max= 300; //内层保温允许最大厚度 m_thick1Increment=10; //内层保温厚度最小增量 m_thick2Start = 30; //外层保温允许最小厚度 m_thick2Max = 300; //外层保温允许最大厚度 m_thick2Increment=10; //外层保温厚度最小增量 //将默认的数据写入到数据库中。 strSQL.Format("INSERT INTO [thicknessRegular] (thick1Start,thick1Max ,thick1Increment ,thick2Start ,thick2Max ,thick2Increment ,EnginID )\ VALUES(%d,%d,%d,%d,%d,%d,'%s') ",m_thick1Start,m_thick1Max,m_thick1Increment,m_thick2Start,m_thick2Max,m_thick2Increment,EDIBgbl::SelPrjID); theApp.m_pConnection->Execute(_bstr_t(strSQL), NULL, adCmdText ); } } catch(_com_error& e) { ReportExceptionError(e); return false; } return true; } // // bool CHeatPreCal::InsertToReckonCost(double &ts, double &tb, double &thick1, double &thick2, double &cost_min, bool bIsFirst) { CString strSQL; _RecordsetPtr pRs; pRs.CreateInstance(__uuidof(Recordset)); try { //当为第一次时,先清空所有的记录. if( bIsFirst ) { try { strSQL = "DELETE * FROM [ReckonCost]"; theApp.m_pConnection->Execute(_bstr_t(strSQL),NULL,adCmdText); } catch(_com_error& e) { //没有该表时, 则创建. if( e.Error() == DB_E_NOTABLE ) { strSQL = "CREATE TABLE [ReckonCost] (ts double, tb double,thick1 double,thick2 double,cost_min double)"; theApp.m_pConnection->Execute(_bstr_t(strSQL), NULL, adCmdText); } } } //插入一条记录。 strSQL.Format("INSERT INTO [ReckonCost] VALUES(%f,%f,%f,%f,%f)",ts,tb,thick1,thick2,cost_min); theApp.m_pConnection->Execute(_bstr_t(strSQL),NULL,adCmdText); } catch(_com_error& e) { ReportExceptionError(e); return false; } return true; } //////////////////////// //根据介质温度,取保温结构外表面允许最大散热密度 bool CHeatPreCal::GetHeatLoss(_RecordsetPtr& pRs,double &t/*温度*/, double &YearRun/*年运行*/, double &SeasonRun/*季节运行*/, double &QMax/*最大散热密度,根据运行小时数确定工况,(年运行或季节运行)*/) { try { YearRun = SeasonRun = QMax= 0; if( pRs->adoEOF && pRs->BOF ) { //没有记录. return false; } // double nTempCur, nTempPre, nYearCur, nYearPre, nSeasonCur, nSeasonPre; bool bFirst = true; for(pRs->MoveFirst(); !pRs->adoEOF; pRs->MoveNext() ) { nTempCur = vtof(pRs->GetCollect(_variant_t("t"))); nYearCur = vtof(pRs->GetCollect(_variant_t("YearRun"))); nSeasonCur = vtof(pRs->GetCollect(_variant_t("SeasonRun"))); if( nTempCur >= t ) //当前记录的温度值大于或等于要查找的温度. { if( bFirst ) //当为第一条记录时 { YearRun = nYearCur; SeasonRun = nSeasonCur; if( hour_work ) { //年运行工况 QMax = nYearCur; } else { //季节运行工况 QMax = nSeasonCur; } if( fabs(QMax) < 1e-6 ) //如果允许最大散热密度为0时(即,没有限制), 返回一个常数. { QMax = D_MAXTEMP; } return true; } else { YearRun = (t-nTempPre)/(nTempCur-nTempPre)*(nYearCur-nYearPre)+nYearPre; SeasonRun = (t-nTempPre)/(nTempCur-nTempPre)*(nSeasonCur-nSeasonPre)+nSeasonPre; if( hour_work ) { //年运行工况 QMax = nYearCur; } else { //季节运行工况 QMax = nSeasonCur; } if( fabs(QMax) < 1e-6 ) //如果允许最大散热密度为0时(即,没有限制), 返回一个常数. { QMax = D_MAXTEMP; } return true; } } else { //记住当前的值 nTempPre = nTempCur; nYearPre = nYearCur; nSeasonPre = nSeasonCur; } bFirst = false; } //取最后一条记录的值 if( pRs->adoEOF ) { YearRun = nYearCur; SeasonRun = nSeasonCur; if( hour_work ) { //年运行工况 QMax = nYearCur; } else { //季节运行工况 QMax = nSeasonCur; } if( fabs(QMax) < 1e-6 ) //如果允许最大散热密度为0时(即,没有限制), 返回一个常数. { QMax = D_MAXTEMP; } return true; } } catch(_com_error& e) { ReportExceptionError(e); return false; } return true; } // // 从常量,常数库里取出数据. bool CHeatPreCal::GetConstantDefine(CString strTblName, CString ConstName, CString &ConstValue) { _RecordsetPtr pRs; pRs.CreateInstance(__uuidof(Recordset)); CString strSQL; strTblName.TrimRight(); strSQL = "SELECT * FROM ["+strTblName+"] "; try { pRs->Open(_variant_t(strSQL), theApp.m_pConnectionCODE.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if( pRs->GetRecordCount() <= 0) { return false; } strSQL = "ConstantDefine_Name='"+ConstName+"' " ; pRs->Find(_bstr_t(strSQL), NULL, adSearchForward); if( !pRs->adoEOF ) { ConstValue = vtos(pRs->GetCollect("ConstantDefine_VALUE")); return true; } else return false; } catch(_com_error& e) { ReportExceptionError( e); return false; } return true; } // 在常量,常数库里取出数据. bool CHeatPreCal::GetConstantDefine(CString strTblName, CString ConstName, double &dConstValue) { CString strConstValue; if( GetConstantDefine(strTblName, ConstName, strConstValue) ) { dConstValue = strtod( strConstValue, NULL ); return true; } return false; } //功能: //计算保温结构外表面传热系数. //参数: //dTs,外表面温度. //dD1,保温层外径. double CHeatPreCal::CalcAlfaValue(double dTs, double dD1) { CString sSQL, //存放SQL语句. sVariableName, //表中的变量名。 sTmp, //临时变量 sFormula, //计算放热系数的公式 sIndex; //将整数索引转换为字符串,临时的 double dTmpVal; CString sCalTblName = "tmpCalcInsulThick";//临时计算中间结果的表名. try { //查找计算外表面传热系数的公式. //{{如果公式为空,则是查表获得放热系数的.直接返回. if(m_pRsHeat_alfa->GetRecordCount() <= 0 ) { //不存在记录时. return 0; } sIndex.Format("%d", m_nIndexAlpha); sSQL = "Index= "+sIndex+" "; m_pRsHeat_alfa->MoveFirst(); m_pRsHeat_alfa->Find(_bstr_t(sSQL), NULL, adSearchForward); if( !m_pRsHeat_alfa->adoEOF ) { //定位到了给定索引值的记录. //提出计算放热系数的公式 sFormula = vtos(m_pRsHeat_alfa->GetCollect(_variant_t("Formula")) ); if( sFormula.IsEmpty() ) { //没有计算公式的情况,查表取得放热系数。 //查表已在计算每条记录的开始(初始化时)进行。 return 0; } } else { //表中不存在该索引值对应的记录. return 0; } //}} } catch(_com_error& e) { AfxMessageBox(e.Description()); return 0; } _RecordsetPtr pRsTmp; //临时的记录集. _RecordsetPtr pRsTmpVal; //保存结果的记录。 pRsTmp.CreateInstance(__uuidof(Recordset)); pRsTmpVal.CreateInstance(__uuidof(Recordset)); try { //先清空表中的所有记录。 // theApp.m_pConWorkPrj->Execute(_bstr_t("DELETE * FROM ["+sCalTblName+"] "), NULL, adCmdText); //初始计算公式中的其他变量值 sSQL = "SELECT * FROM ["+sCalTblName+"] "; pRsTmp->Open(_variant_t(sSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if( pRsTmp->GetRecordCount() <= 0 ) { //如果第一次使用该表,则新增加一条记录. pRsTmp->AddNew(); } else { //以后只改变第一条记录的值 pRsTmp->MoveFirst(); } //外表面温度 pRsTmp->PutCollect(_variant_t("ts"), _variant_t(dTs)); //保温层外径,(当为复合保温时, 应代入D2) pRsTmp->PutCollect(_variant_t("D1"), _variant_t(dD1)); //环境温度 pRsTmp->PutCollect(_variant_t("ta"), _variant_t(this->Temp_env)); //风速 pRsTmp->PutCollect(_variant_t("W"), _variant_t(this->speed_wind)); //沿风速方向的平壁宽度。 pRsTmp->PutCollect(_variant_t("B"), _variant_t(this->D0)); //保护层材料黑度 pRsTmp->PutCollect(_variant_t("Epsilon"), _variant_t(this->hedu)); //管道外径。 pRsTmp->PutCollect(_variant_t("D0"), _variant_t(this->D0)); //管道与平壁的分界值。 pRsTmp->PutCollect(_variant_t("Dmax"), _variant_t(this->m_dMaxD0)); pRsTmp->Update(); pRsTmp->Close(); // for(m_pRsHeat_alfa->MoveFirst(); !m_pRsHeat_alfa->adoEOF; m_pRsHeat_alfa->MoveNext()) { sVariableName = vtos(m_pRsHeat_alfa->GetCollect(_variant_t("Variable_Name_Desc"))); if( !sVariableName.IsEmpty() && sVariableName.CompareNoCase("ALPHA") ) { //计算放热系数的中间公式。 sTmp = vtos(m_pRsHeat_alfa->GetCollect(_variant_t("Formula"))); sSQL = "UPDATE ["+sCalTblName+"] SET "+sVariableName+" = "+sTmp+" "; theApp.m_pConWorkPrj->Execute(_bstr_t(sSQL), NULL, adCmdText); } } sSQL = "SELECT ("+sFormula+") AS val FROM ["+sCalTblName+"] "; pRsTmpVal->Open(_variant_t(sSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); //放热系数值 dTmpVal = vtof( pRsTmpVal->GetCollect(_variant_t("val"))); if( dTmpVal > 0 ) { this->co_alf = dTmpVal; return 1; //用公式计算出了一个有效的放热系数.成功返回 } } catch(_com_error) { return false; } return 0; } //功能: //在一个表中根据指定的数据,求差值。 //例如:根据保温层外径,与材料的类型。 //获得室内的设备或管道保温结构外表面传热系数。 // bool CHeatPreCal::GetAlfaValue(_RecordsetPtr pRs, CString sSearchFieldName, CString sValFieldName, double dCompareVal,double& dAlfaVal) { dAlfaVal = 0.0; //如果表中没有记录,或字段名为空时,返回值为0。 if( pRs->adoEOF && pRs->BOF ) { return false; } sValFieldName.TrimLeft(); sValFieldName.TrimRight(); if( sValFieldName.IsEmpty() || sSearchFieldName.IsEmpty() ) { //要查找的字段名,或关键字段名为空。 return false; } double dCurDia, //当前的外保温厚。 dPreDia, //前一次的外保温厚 dCurValue, //本次查找到的值。 dPreValue; //前一次的值 bool bFirst = true; //标记查找的次数. for(pRs->MoveFirst(); !pRs->adoEOF; pRs->MoveNext()) { dCurDia = vtof(pRs->GetCollect(_variant_t(sSearchFieldName))); dCurValue = vtof(pRs->GetCollect(_variant_t(sValFieldName))); if( dCurDia >= dCompareVal ) { if( bFirst ) { //第一次时。 dAlfaVal = dCurValue; return true; } else { //求差值. dAlfaVal = (dCompareVal-dPreDia)/(dCurDia-dPreDia)*(dCurValue-dPreValue)+dPreValue; return true; } } else { //保存当前的值,继续往下查找。 dPreDia = dCurDia; dPreValue = dCurValue; } bFirst = false; } //没有找到满足条件的记录。取最后一条记录的值。 if(pRs->adoEOF) { dAlfaVal = dCurValue; return true; } return true; } ///////////// //功能: //传入计算保温厚度的公式,初始各参数,并计算. //计算成功返回1.否则为0. //参数: //strFormula 保温厚度计算公式. //strTsFormula 外表面温度计算公式 //strQFormula 散热密度计算公式 //thick1 保温厚(内层。) //thick2 外层保温厚 short CHeatPreCal::CalcInsulThick(CString strThickFormula,CString strThickFormula2,CString strTbFormula, CString strTsFormula, CString strQFormula ,double &dThick1, double &dThick2) { CString strTmp, //临时变量 strSQL; //存入SQL语句. double thick1, //内保温厚 thick2,//外保温厚 thick, //单层保温厚. ts, //外表面温度。 tb; //界面温度 double condu_r, condu1_r,condu2_r,condu_out,cost_q,cost_s,cost_tot, cost_min=0;//最少的价格. double D1, D2; double nYearVal, nSeasonVal, Q; //保温结构外表面散热密度 double QMax; //允许最大散热密度 bool flg=true; //进行散热密度的判断 // double MaxTb = in_tmax*m_HotRatio;//结合面允许最大温度=外保温材料的最大温度 * 一个系数(规程规定为0.9). double MaxTb = in_tmax;//结合面允许最大温度,从保温材料参数库(a_mat)中取MAT_TMAX字段,可修改该字段进行控制界面温度值. if( strThickFormula.IsEmpty() ) //计算保温厚的公式为空 { return 0; } //选项中选择了判断散热密度,则查表。 if(bIsHeatLoss) { //查表获得介质温度允许的最大散热密度 if( !GetHeatLoss(m_pRsHeatLoss, Temp_pip, nYearVal, nSeasonVal, QMax) ) { } } // _RecordsetPtr pRsTmp; //初始当前的中间变量的记录集. _RecordsetPtr pRsTmpVal; //保存结果的记录。 CString strCalTblName = "tmpCalcInsulThick";//临时计算中间结果的表名. pRsTmp.CreateInstance(__uuidof(Recordset)); pRsTmpVal.CreateInstance(__uuidof(Recordset)); try { //先清空表中的所有记录。 // theApp.m_pConWorkPrj->Execute(_bstr_t("DELETE * FROM ["+sCalTblName+"] "), NULL, adCmdText); //初始计算公式中的其他变量值 strSQL = "SELECT * FROM ["+strCalTblName+"] "; pRsTmp->Open(_variant_t(strSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if( pRsTmp->GetRecordCount() <= 0 ) { //如果第一次使用该表,则新增加一条记录. pRsTmp->AddNew(); } else { //以后只改变第一条记录的值 pRsTmp->MoveFirst(); } //初始计算保温厚度时要用到的,各个中间变量. //保温结构外表面温度 // pRsTmp->PutCollect(_variant_t("ts"), _variant_t(dTs)); //复合保温内外层界面处温度 pRsTmp->PutCollect(_variant_t("tb"), _variant_t()); //保温层外径,(当为复合保温时, 应代入D2) // pRsTmp->PutCollect(_variant_t("D1"), _variant_t(dD1)); //环境温度 pRsTmp->PutCollect(_variant_t("ta"), _variant_t(this->Temp_env)); //风速 pRsTmp->PutCollect(_variant_t("W"), _variant_t(this->speed_wind)); //沿风速方向的平壁宽度。 pRsTmp->PutCollect(_variant_t("B"), _variant_t(this->D0)); //保护层材料黑度 pRsTmp->PutCollect(_variant_t("Epsilon"), _variant_t(this->hedu)); //管道外径。 pRsTmp->PutCollect(_variant_t("D0"), _variant_t(this->D0)); //管道与平壁的分界值。 pRsTmp->PutCollect(_variant_t("Dmax"), _variant_t(this->m_dMaxD0)); //计算保温厚度时用到的其它参数。 // //隔热材料制品导热系系数,W/(m*C) pRsTmp->PutCollect(_variant_t("lamda"), _variant_t()); //热价 pRsTmp->PutCollect(_variant_t("Ph"), _variant_t()); //介质拥质系数. pRsTmp->PutCollect(_variant_t("Ae"), _variant_t()); //设备和管道温度 pRsTmp->PutCollect(_variant_t("t"), _variant_t(this->Temp_pip)); //年运行时间 pRsTmp->PutCollect(_variant_t("tao"), _variant_t()); //保温层单位造价,复合保温内层单位造价 pRsTmp->PutCollect(_variant_t("P1"), _variant_t()); //复合保温外层单位造价 pRsTmp->PutCollect(_variant_t("P2"), _variant_t()); //保护层单位造价 pRsTmp->PutCollect(_variant_t("P3"), _variant_t()); //保温工程投资贷款年分摊率 pRsTmp->PutCollect(_variant_t("S"), _variant_t()); //复合保温外层外径 pRsTmp->PutCollect(_variant_t("D2"), _variant_t()); //保温结构外表面散热密度 pRsTmp->PutCollect(_variant_t("Q"), _variant_t()); //圆周率 pRsTmp->PutCollect(_variant_t("pi"), _variant_t((double)3.1415927)); //管道通过支吊架处的热(或冷)损失的附加系数,可取1.05 ~ 1.15 pRsTmp->PutCollect(_variant_t("Kr"), _variant_t((double)1.1)); //防冻结管道允许液停留时间 pRsTmp->PutCollect(_variant_t("taofr"), _variant_t()); //介质在管内冻结温度 pRsTmp->PutCollect(_variant_t("tfr"), _variant_t()); //每米管长介质体积 pRsTmp->PutCollect(_variant_t("V"), _variant_t()); //介质密度 pRsTmp->PutCollect(_variant_t("ro"), _variant_t()); //介质的比热 pRsTmp->PutCollect(_variant_t("C"), _variant_t()); //每米管长管壁体积 pRsTmp->PutCollect(_variant_t("Vp"), _variant_t()); //管材密度 pRsTmp->PutCollect(_variant_t("rop"), _variant_t()); //管材的比热 pRsTmp->PutCollect(_variant_t("Cp"), _variant_t()); //介质溶解热 pRsTmp->PutCollect(_variant_t("Hfr"), _variant_t()); //保温层厚度。 pRsTmp->PutCollect(_variant_t("delta"), _variant_t()); //复合保温内层厚度 pRsTmp->PutCollect(_variant_t("delta1"), _variant_t()); //复合保温外层厚度 pRsTmp->PutCollect(_variant_t("delta2"), _variant_t()); // pRsTmp->Update(); //开始计算 //计算内层保温厚的公式为空时.作为单层处理。 if( strThickFormula2.IsEmpty() ) { //计算内层保温厚的公式为空时.作为单层处理。 //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //从保温厚度规则表thicknessRegular获得 // for(thick=m_thick2Start;thick<=m_thick2Max;thick+=m_thick2Increment) { // do temp_pip_one with thick,ts temp_pip_one(thick,ts); condu_r=in_a0+in_a1*(ts+Temp_pip)/2.0+in_a2*(ts+Temp_pip)*(ts+Temp_pip)/4.0; condu_out=co_alf; D1=2.0*thick+D0; cost_q=7.2*pi*Mhours*heat_price*Yong*fabs(Temp_pip-Temp_env)*1e-6 /(1.0/condu_r*log(D1/D0)+2000.0/condu_out/D1); cost_s=(pi/4.0*(D1*D1-D0*D0)*in_price*1e-6+pi*D1*pro_price*1e-3)*S; cost_tot=cost_q+cost_s; pRsTmp->PutCollect(_variant_t("ALPHA"), _variant_t(condu_out)); //隔热材料制品导热系系数,W/(m*C) pRsTmp->PutCollect(_variant_t("lamda"), _variant_t(condu_r)); //保温层的外径 pRsTmp->PutCollect(_variant_t("D1"), _variant_t(D1)); try { // //保温层厚度。 pRsTmp->PutCollect(_variant_t("delta"), _variant_t(thick)); //保温结构外表面温度 pRsTmp->PutCollect(_variant_t("ts"), _variant_t(ts)); //复合保温内外层界面处温度 tb = ts; pRsTmp->PutCollect(_variant_t("tb"), _variant_t(tb)); pRsTmp->Update();//更新; //求外表面温度,如果是双层加上界面温度。 //strSQL = "SELECT ("+strTsFormula+") AS TSVal FROM ["+strCalTblName+"] "; strSQL = "UPDATE ["+strCalTblName+"] SET ts= ("+strTsFormula+") "; theApp.m_pConWorkPrj->Execute(_bstr_t(strSQL), NULL, adCmdText); //求得本次厚度的散热密度 //公式: //从数据库中获得,根据保温结构取得相应的计算公式 strSQL = "UPDATE ["+strCalTblName+"] SET Q=("+strQFormula+") "; theApp.m_pConWorkPrj->Execute(_bstr_t(strSQL), NULL, adCmdText); } catch(_com_error& e) { AfxMessageBox ( e.Description() ); } if(ts<MaxTs && (cost_tot<cost_min || fabs(cost_min)<1E-6)) { flg = true; //选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式:为了兼容保冷计算,温度差应取绝对值 by ligb on 2010.06.14 //(介质温度-环境温度)/((保温层外径/2000.0/材料导热率*ln(保温层外径/管道外径)) + 1/传热系数) Q = fabs(Temp_pip-Temp_env)/(D1/2000.0/condu_r*log(D1/D0) + 1.0/co_alf); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { cost_min=cost_tot; } } } } else { //test //thick1内层保温厚度。thick2外层保温厚度 //thick1Start内层保温允许最小厚度,thick1Max内层保温允许最大厚度,thick1Increment内层保温厚度最小增量 //thick2Start外层保温允许最小厚度,thick2Max外层保温允许最大厚度,thick2Increment外层保温厚度最小增量 //从保温厚度规则表thicknessRegular获得 // theApp.m_pConWorkPrj->BeginTrans(); //开始事务. for(thick1=m_thick1Start;thick1<=m_thick1Max;thick1+=m_thick1Increment) { for(thick2=m_thick2Start;thick2<=m_thick2Max;thick2+=m_thick2Increment) { temp_pip_com(thick1,thick2,ts,tb); condu1_r=in_a0+in_a1*(Temp_pip+tb)/2.0+in_a2*(Temp_pip+tb)*(Temp_pip+tb)/4.0; condu2_r=out_a0+out_a1*(tb+ts)/2.0+out_a2*(tb+ts)*(tb+ts)/4.0; condu_out=co_alf; D1=2*thick1+D0; D2=2*thick2+D1; //test {{ //计算保温结构外表面传热系数. condu_out = CalcAlfaValue(ts, tb); if( fabs(condu_out) < 1e-1 ) { //为零时用查表所得的传热系数. condu_out = co_alf; } pRsTmp->PutCollect(_variant_t("ALPHA"), _variant_t(condu_out)); //隔热材料制品导热系系数,W/(m*C) pRsTmp->PutCollect(_variant_t("lamda"), _variant_t(condu1_r)); //隔热材料制品导热系系数,W/(m*C) pRsTmp->PutCollect(_variant_t("lamda1"), _variant_t(condu1_r)); //隔热材料制品导热系系数,W/(m*C) pRsTmp->PutCollect(_variant_t("lamda2"), _variant_t(condu2_r)); //test }} //复合保温结构的内层保温外径 pRsTmp->PutCollect(_variant_t("D1"), _variant_t(D1)); //复合保温结构的外层保温外径 pRsTmp->PutCollect(_variant_t("D2"), _variant_t(D2)); cost_q=7.2*pi*Mhours*heat_price*Yong*fabs(Temp_pip-Temp_env)*1e-6 /(1.0/condu1_r*log(D1/D0)+1.0/condu2_r*log(D2/D1)+2000.0/condu_out/D2); cost_s=(pi/4.0*(D1*D1-D0*D0)*in_price*1e-6+pi/4.0*(D2*D2-D1*D1)*out_price*1e-6 +pi*D2*pro_price*1e-3)*S; cost_tot=cost_q+cost_s; try { // //保温层厚度。 pRsTmp->PutCollect(_variant_t("delta"), _variant_t(thick1)); //复合保温内层厚度 pRsTmp->PutCollect(_variant_t("delta1"), _variant_t(thick1)); //复合保温外层厚度 pRsTmp->PutCollect(_variant_t("delta2"), _variant_t(thick2)); //保温结构外表面温度 pRsTmp->PutCollect(_variant_t("ts"), _variant_t(ts)); //复合保温内外层界面处温度 pRsTmp->PutCollect(_variant_t("tb"), _variant_t(tb)); pRsTmp->Update();//更新; //求外表面温度,如果是双层加上界面温度。 //strSQL = "SELECT ("+strTsFormula+") AS TSVal FROM ["+strCalTblName+"] "; strSQL = "UPDATE ["+strCalTblName+"] SET ts= ("+strTsFormula+") "; theApp.m_pConWorkPrj->Execute(_bstr_t(strSQL), NULL, adCmdText); //求得本次厚度的散热密度 //公式: //从数据库中获得,根据保温结构取得相应的计算公式 strSQL = "UPDATE ["+strCalTblName+"] SET Q=("+strQFormula+") "; theApp.m_pConWorkPrj->Execute(_bstr_t(strSQL), NULL, adCmdText); //求保温厚度 /**/ // strSQL = "UPDATE ["+strCalTblName+"] SET delta=("+strThickFormula+") "; // theApp.m_pConWorkPrj->Execute(_bstr_t(strSQL), NULL, adCmdText); /* //求外表面温度,如果是双层加上界面温度。 strSQL = "SELECT ("+strTsFormula+") AS TSVal FROM ["+strCalTblName+"] "; if(pRsTmpVal->State == adStateOpen) { pRsTmpVal->Close(); } pRsTmpVal->Open(_bstr_t(strSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if(pRsTmpVal->GetRecordCount() <= 0 ) { //计算外表面温度失败。 pRsTmp->PutCollect(_variant_t("ts"), _variant_t((double)35)); } else { ts = vtof(pRsTmpVal->GetCollect(_T("TSVal"))); pRsTmp->PutCollect(_variant_t("ts"), _variant_t(ts)); } //求界面温度。tb if( !strTbFormula.IsEmpty() ) { strSQL = "SELECT ("+strTbFormula+") AS TBVal FROM ["+strCalTblName+"] "; if(pRsTmpVal->State == adStateOpen) { pRsTmpVal->Close(); } pRsTmpVal->Open(_bstr_t(strSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if(pRsTmpVal->GetRecordCount() <= 0 ) { //计算界面温度失败 pRsTmp->PutCollect(_variant_t("tb"), _variant_t((double)35)); } else { tb = vtof(pRsTmpVal->GetCollect(_T("TBVal"))); pRsTmp->PutCollect(_variant_t("tb"),_variant_t(tb)); } } //求得本次厚度的散热密度 //公式: //从数据库中获得,根据保温结构取得相应的计算公式 strSQL = "SELECT ("+strQFormula+") AS QVal FROM ["+strCalTblName+"] "; if(pRsTmpVal->State == adStateOpen) { pRsTmpVal->Close(); } pRsTmpVal->Open(_bstr_t(strSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if(pRsTmpVal->GetRecordCount() <= 0 ) { //计算散热密度失败。 //赋一个默认的值,查找数据库所得。 pRsTmp->PutCollect(_variant_t("Q"), _variant_t(QMax)); } else { Q = vtof(pRsTmpVal->GetCollect(_T("QVal"))); pRsTmp->PutCollect(_variant_t("Q"), _variant_t(Q)); } //求保温厚度 strSQL = "SELECT ("+strThickFormula+") AS Thick FROM ["+strCalTblName+"] "; if( pRsTmpVal->State == adStateOpen) { pRsTmpVal->Close(); } pRsTmpVal->Open(_bstr_t(strSQL), theApp.m_pConWorkPrj.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if( pRsTmpVal->GetRecordCount() <= 0 ) { return 0; } dThick1 = vtof(pRsTmpVal->GetCollect(_T("Thick"))); /* */ } catch(_com_error& e) { AfxMessageBox(e.Description()); return 0; } //tb<350) if((ts<MaxTs && tb<MaxTb) && (fabs(cost_min)<1E-6 || cost_min>cost_tot)) { flg = true; //选项中选择的判断散热密度,就进行比较. if(bIsHeatLoss) { //求得本次厚度的散热密度 //公式: //(介质温度-环境温度)/((外保温层外径/2000.0)*(1.0/内保温材料导热率*ln(内保温层外径/管道外径) + 1.0/外保温材料导热率*ln(外保温层外径/内保温层外径) ) + 1/传热系数) Q = (Temp_pip-Temp_env) / ( (D2/2000.0) * (1.0/condu1_r*log(D1/D0)+1.0/condu2_r*log(D2/D1)) + 1.0/co_alf ); if(fabs(QMax) <= 1E-6 || Q <= QMax) { //当前厚度满足允许最大散热规则. flg = true; } else { flg = false; } } //满足条件. if( flg ) { cost_min=cost_tot; dThick1=thick1; dThick2=thick2; // ts_resu=ts; // tb_resu=tb;// } } } } // theApp.m_pConWorkPrj->CommitTrans(); //提交事务. // theApp.m_pConWorkPrj->RollbackTrans(); }//双层保温 } catch(_com_error& e) { AfxMessageBox(e.Description()); return false; } return 1; } //功能: //获得计算当前记录的计算保温厚的公式.计算外表面温度的公式,计算散热密度的公式 // nFormulaIndex //结构对应的公式索引. // strFormula, //返回计算公式. int CHeatPreCal::GetCalcFormula(int nFormulaIndex, CString &strFormula, CString& strTsFormula, CString& strQFormula) { CString strTmp, //临时变量 strSQL; //存入SQL语句. int nMethod=0; //计算方法索引。 try { //在原始数据库中获得计算方法的索引。 nMethod = vtoi(IRecCalc->GetCollect(_T("c_Method_Index"))); if(m_pRsCalcThick->GetRecordCount() <= 0 ) { return 0; } m_pRsCalcThick->Filter = (long)adFilterNone; strSQL.Format("InsulationCalcMethodIndex=%d AND Index=%d",nMethod,nFormulaIndex); m_pRsCalcThick->Filter = variant_t(strSQL); if( !m_pRsCalcThick->adoEOF ) { //找到保温计算方法对应的公式. strFormula = vtos(m_pRsCalcThick->GetCollect(_T("Formula"))); if( strFormula.IsEmpty() ) { //计算的公式为空 return 0; } } else { return 0; //找不到保温计算方法所对应的公式. } //查找求外表面ts值的计算公式 m_pRsCalcThick->Filter = (long)adFilterNone; //设为一个常数,规定20为计算外表面温度的方法的索引. nMethod = 20; strSQL.Format("InsulationCalcMethodIndex=%d AND Index=%d",nMethod,nFormulaIndex); m_pRsCalcThick->Filter = _variant_t(strSQL); if(m_pRsCalcThick->GetRecordCount() <= 0 ) { return 0; } strTsFormula = vtos(m_pRsCalcThick->GetCollect(_T("Formula"))); // //查找计算散热密度(Q)的计算公式 m_pRsCalcThick->Filter = (long)adFilterNone; //设为一个常数,规定21为计算散热密度的方法的索引. nMethod = 21; strSQL.Format("InsulationCalcMethodIndex=%d AND Index=%d",nMethod, nFormulaIndex); m_pRsCalcThick->Filter = _variant_t(strSQL); if(m_pRsCalcThick->GetRecordCount() <= 0 ) { return 0; } strQFormula = vtos(m_pRsCalcThick->GetCollect(_variant_t("Formula"))); //取消所有的过滤 m_pRsCalcThick->Filter = (long)adFilterNone; } catch(_com_error& e) { AfxMessageBox(e.Description()); return 0; } return 1; } //----------------------------------------------------- //功能: //在管道参数库中根据管道外径和壁厚,获得相应的管重,和水重. short CHeatPreCal::GetPipeWeithAndWaterWeith(_RecordsetPtr &pRs, const double dPipe_Dw, const double dPipe_S, CString strField1, double &dValue1,CString strField2, double &dValue2) { try { if(pRs == NULL || pRs->State == adStateClosed || pRs->GetRecordCount() <= 0 ) { //记录集为空 return 0; } CString strFilter; strFilter.Format("PIPE_DW=%f AND PIPE_S=%f",dPipe_Dw, dPipe_S); pRs->Filter = (long)adFilterNone; //删除当前筛选条件并恢复查看的所有记录。 pRs->Filter = _variant_t(strFilter); //筛选出满足外径和壁厚的记录. while(!pRs->adoEOF) { try { //定位到外径和壁厚对应的记录 // dValue1 = vtof(pRs->GetCollect(_variant_t(strField1) )); //取出给定字段名对应的值 dValue2 = vtof(pRs->GetCollect(_variant_t(strField2) )); pRs->Filter = (long)adFilterNone; //删除当前筛选条件并恢复查看的所有记录。 return 1; } catch(_com_error &e) { CString TempStr; TempStr.Format(_T("原始数据序号为%d的记录在读取\"管道参数库(A_PIPE)\"中时出错\r\n"), m_nID ); if(Exception::GetAdditiveInfo()) { TempStr+=Exception::GetAdditiveInfo(); } ExceptionInfo(TempStr); Exception::SetAdditiveInfo(NULL); ReportExceptionErrorLV2(e); IRecCalc->MoveNext(); continue; } } } catch(_com_error &e) { ReportExceptionErrorLV2(e); pRs->Filter = (long)adFilterNone; //删除当前筛选条件并恢复查看的所有记录。 return 0; } //没有长到符合外径和壁厚的记录 pRs->Filter = (long)adFilterNone; //删除当前筛选条件并恢复查看的所有记录。 return 0; } //------------------------------------------------------------------ // DATE :[2005/08/02] // Parameter(s) : // Return : // Remark :在规范库中设置常数表中指定项的值. //------------------------------------------------------------------ BOOL CHeatPreCal::SetConstantDefine(CString strTblName, CString ConstName, _variant_t ConstValue) { _RecordsetPtr pRs; pRs.CreateInstance(__uuidof(Recordset)); CString strSQL; strTblName.TrimRight(); strSQL = "SELECT * FROM ["+strTblName+"] "; try { pRs->Open(_variant_t(strSQL), theApp.m_pConnectionCODE.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if( pRs->GetRecordCount() <= 0) { return false; } strSQL = "ConstantDefine_Name='"+ConstName+"' " ; pRs->Find(_bstr_t(strSQL), NULL, adSearchForward); if( !pRs->adoEOF ) { pRs->PutCollect(_variant_t("ConstantDefine_VALUE"),ConstValue); pRs->Update(); return true; } else { return false; } } catch(_com_error& e) { ReportExceptionError( e); return false; } return TRUE; } //在标准库中查找保温材料 BOOL CHeatPreCal::FindStandardMat(_RecordsetPtr& pRsCurMat,CString strMaterialName) { try { if (NULL == m_pRs_CodeMat || m_pRs_CodeMat->State != adStateOpen || (m_pRs_CodeMat->adoEOF && m_pRs_CodeMat->BOF)) { return FALSE; } m_pRs_CodeMat->MoveFirst(); if (!LocateFor(m_pRs_CodeMat,_variant_t("MAT_NAME"),CFoxBase::EQUAL, _variant_t(strMaterialName))) { return FALSE; } pRsCurMat->AddNew(); pRsCurMat->Update(); for (long i=0, nFieldCount=m_pRs_CodeMat->Fields->GetCount(); i < nFieldCount; i++) { pRsCurMat->PutCollect(_variant_t(i),m_pRs_CodeMat->GetCollect(_variant_t(i))); } pRsCurMat->PutCollect(_variant_t("EnginID"),_variant_t(m_ProjectName)); pRsCurMat->Update(); } catch (_com_error& e) { AfxMessageBox(e.Description()); return FALSE; } return TRUE; } //------------------------------------------------------------------ // DATE :[2005/09/13] // Parameter(s) : // Return : // Remark :根据介质名称获得其介质的密度 //------------------------------------------------------------------ double CHeatPreCal::GetMediumDensity(const CString strMediumName, CString* pMediumName) { double dMediumDensity = 0.0; //介质密度 CString strSQL; //SQL语句 if (strMediumName.IsEmpty()) { return 0.0; } try { _RecordsetPtr pRs; pRs.CreateInstance(__uuidof(Recordset)); strSQL = "SELECT * FROM [MediumSpec] WHERE MediumID IN (SELECT MediumID FROM [MediumAlias] WHERE MediumAlias='"+strMediumName+"') "; pRs->Open(_variant_t(strSQL), theApp.m_pConMedium.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if (pRs->adoEOF && pRs->BOF) { //不用别名,直接在介质密度表中查找. pRs->Close(); strSQL = "SELECT * FROM [MediumSpec] WHERE MediumName='"+strMediumName+"' "; pRs->Open(_variant_t(strSQL), theApp.m_pConMedium.GetInterfacePtr(), adOpenStatic, adLockOptimistic, adCmdText); if (pRs->adoEOF && pRs->BOF) { return 0.0; } }// dMediumDensity = vtof( pRs->GetCollect(_variant_t("Density")) ); if ( pMediumName != NULL ) { *pMediumName = vtos( pRs->GetCollect(_variant_t("MediumName"))); } } catch (_com_error& e) { AfxMessageBox(e.Description()); return 0.0; } return dMediumDensity; } //------------------------------------------------------------------ // DATE :[2005/09/15] // Parameter(s) :dw: 管道的外径 // :s: 壁厚 // :dMediumDensity:管道内介质的密度 // :temp: 介质的温度 // :dInsuWei: 保温材料的重量 // Return :根据标准计算出的间距 // Remark :使用动态库计算支吊架的间距 //------------------------------------------------------------------ double CHeatPreCal::GetSupportSpan(const double dw, const double s, const CString strMaterialName,const double dPressure,const double dMediumDensity, const double temp, const double dInsuWei) { double dLmax = 0.0; //支吊架的间距 CString strDlgCaption; //对话框的标题 double LmaxR=0.0; double LmaxS=0.0; double fQ=0.0; double fQp=0.0; int TableID = -1; BOOL bCalFlag; //动态库计算的返回标志 BOOL bPreviousFlag=-120; //前一次的计算标志 BOOL pg; if (3.92 < dPressure) //压力 pg = true; else pg = false; CalSupportSpan.SetMaterialCODE( EDIBgbl::sCur_CodeNO ); // 本工程设置的材料规范号 for (int nCont=1; nCont <= 4; nCont++) //如果计算没出错,则直接返回,否则增加了材料的属性,则重新计算一次 { //计算支吊架间距 if (0) { }else { //默认电力行业 bCalFlag = CalSupportSpan.CalcSupportSpan(dw,s,dMediumDensity,temp,dInsuWei, strMaterialName,pg,2,LmaxR,LmaxS,fQ,fQp); } dLmax = min(LmaxR,LmaxS); //刚性条件与强度条件中最小的一个值 if (-1 == bCalFlag) { //指定的材料没有应力系数 TableID = 0; strDlgCaption.Format(_T("请输入 %s 在 %f ℃下的许用应力(MPa):"),strMaterialName,temp); InputMaterialParameter(strDlgCaption,strMaterialName,TableID); }else if (-2 == bCalFlag) { //指定的材料没有弹性模量 TableID = 1; strDlgCaption.Format(_T("请输入 %s 在 %f ℃下的弹性模量(KN/mm2)"),strMaterialName,temp); InputMaterialParameter(strDlgCaption,strMaterialName,TableID); }else if (-3 == bCalFlag) { //指定的材料没有环向焊缝应力系数 TableID = 4; strDlgCaption.Format(_T("请输入 %s 的环向焊缝应力系数:"),strMaterialName); //输入数据 InputMaterialParameter(strDlgCaption,strMaterialName,TableID); }else { //计算成功 break; } // if(bPreviousFlag != bCalFlag) //如果没有相应材料的属性,一种属性最多输入两次。 bPreviousFlag = bCalFlag; else break; } return (dLmax<0)?0:dLmax; } //------------------------------------------------------------------ // DATE :[2006/01/09] // Parameter(s) :strVariableName[in] 气象参数的属性名 // :dRValue[out] 对应的气象值 // Return : // Remark : 获得气象属性值 //------------------------------------------------------------------ void CHeatPreCal::GetWeatherProperty(CString strVariableName, double &dRValue) { if ( strVariableName.IsEmpty() ) return; try { if ( !OpenAssistantProjectTable( m_pRsWeather, "Ta_Variable" ) ) { return; } if ( m_pRsWeather->adoEOF && m_pRsWeather->BOF ) { return; } CString strSQL; strSQL = " Ta_Variable_Name='"+strVariableName+"' "; m_pRsWeather->MoveFirst(); m_pRsWeather->Find( _bstr_t( strSQL ), NULL, adSearchForward ); if ( !m_pRsWeather->adoEOF && !m_pRsWeather->BOF ) { dRValue = vtof( m_pRsWeather->GetCollect( _variant_t( "Ta_Variable_VALUE" ) ) ); } } catch (_com_error& e) { AfxMessageBox( e.Description() ); return ; } } //------------------------------------------------------------------ // Parameter(s) : m_nID[in] 记录号 // Return : 埋地保温类型 // Remark : 当前保温记录的埋地类型 //------------------------------------------------------------------ // BOOL CHeatPreCal::GetSubterraneanTypeAndPipeCount(const long m_nID, short& nType, short& nPipeCount) const { nType = 0; nPipeCount = 1; try { if (NULL == m_pRsSubterranean || (m_pRsSubterranean->GetState() == adStateClosed) || (m_pRsSubterranean->GetadoEOF() && m_pRsSubterranean->GetBOF())) { return FALSE; } CString strSQL; m_pRsSubterranean->MoveFirst(); strSQL.Format("ID=%d", m_nID); m_pRsSubterranean->Find(_bstr_t(strSQL), 0, adSearchForward); if (!m_pRsSubterranean->GetadoEOF()) { nType = vtoi(m_pRsSubterranean->GetCollect(_variant_t(_T("c_lay_mark")))); nPipeCount = vtoi(m_pRsSubterranean->GetCollect(_variant_t(_T("c_Pipe_Count")))); } } catch (_com_error& e) { AfxMessageBox(e.Description()); return FALSE; } return TRUE; }
a4c05dff88476b26f501953e887f73ec03491b59
6d088ec295b33db11e378212d42d40d5a190c54c
/contrib/brl/bseg/bvpl/pro/processes/bvpl_convert_direction_to_hue_process.cxx
13bba8169fff6a5f3ec7a92708abb2c60567ada2
[]
no_license
vxl/vxl
29dffd5011f21a67e14c1bcbd5388fdbbc101b29
594ebed3d5fb6d0930d5758630113e044fee00bc
refs/heads/master
2023-08-31T03:56:24.286486
2023-08-29T17:53:12
2023-08-29T17:53:12
9,819,799
224
126
null
2023-09-14T15:52:32
2013-05-02T18:32:27
C++
UTF-8
C++
false
false
3,231
cxx
bvpl_convert_direction_to_hue_process.cxx
// This is brl/bseg/bvpl/pro/processes/bvpl_convert_direction_to_hue_process.cxx #include <iostream> #include <string> #include <bprb/bprb_func_process.h> //: // \file // \brief A process for converting direction to hue // \author Vishal Jain // \date July 7, 2009 // // \verbatim // Modifications // <none yet> // \endverbatim #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif #include <bprb/bprb_parameters.h> #include <bvxm/grid/bvxm_voxel_grid_base.h> #include <bvxm/grid/bvxm_voxel_grid.h> #include <bvpl/kernels/bvpl_kernel_factory.h> #include <bvpl/bvpl_direction_to_color_map.h> #include "vnl/vnl_float_4.h" namespace bvpl_convert_direction_to_hue_process_globals { constexpr unsigned n_inputs_ = 5; constexpr unsigned n_outputs_ = 1; } //: set input and output types bool bvpl_convert_direction_to_hue_process_cons(bprb_func_process& pro) { using namespace bvpl_convert_direction_to_hue_process_globals; // This process has 5 inputs and 1 output std::vector<std::string> input_types_(n_inputs_); unsigned i=0; input_types_[i++]="bvxm_voxel_grid_base_sptr"; //the inpud grid input_types_[i++]="bvpl_kernel_vector_sptr"; // a vector of kernels input_types_[i++]="vcl_string"; //path to output grid input_types_[i++]="vcl_string"; //output file for map input_types_[i++]="vcl_string"; //"peano" or "random" std::vector<std::string> output_types_(n_outputs_); i=0; output_types_[i++]="bvxm_voxel_grid_base_sptr"; //the output grid return pro.set_input_types(input_types_) && pro.set_output_types(output_types_); } //: Execute the process bool bvpl_convert_direction_to_hue_process(bprb_func_process& pro) { using namespace bvpl_convert_direction_to_hue_process_globals; // check number of inputs if (pro.input_types().size() != n_inputs_) { std::cout << pro.name() << "The number of inputs should be " << n_inputs_ << std::endl; return false; } bvxm_voxel_grid_base_sptr grid_base = pro.get_input<bvxm_voxel_grid_base_sptr>(0); bvpl_kernel_vector_sptr kernel = pro.get_input<bvpl_kernel_vector_sptr>(1); std::string output_world_dir = pro.get_input<std::string>(2); std::string map_output_file = pro.get_input<std::string>(3); std::string type_of_map = pro.get_input<std::string>(4); if (!grid_base.ptr()) { std::cerr << "In bvpl_convert_direction_to_hue_process -- input grid is not valid!\n"; return false; } auto *grid = dynamic_cast< bvxm_voxel_grid<vnl_float_4 >* >(grid_base.ptr()); if (grid) { std::vector<vgl_point_3d<double> > direction_samples; bvpl_generate_direction_samples_from_kernels(kernel,direction_samples); //std::map<vgl_point_3d<double>,float,point_3d_cmp> colors; //bvpl_direction_to_color_map(direction_samples,colors); bvxm_voxel_grid<vnl_float_4 > * out_grid = new bvxm_voxel_grid<vnl_float_4 >(output_world_dir, grid->grid_size()); bvpl_direction_to_color_map color_map(direction_samples,type_of_map); bvpl_convert_grid_to_hsv_grid(grid,out_grid,color_map ); pro.set_output_val<bvxm_voxel_grid_base_sptr>(0, out_grid); color_map.make_svg_color_map(map_output_file); return true; } else { std::cerr << "datatype not supported\n"; } return false; }
d356e31c2e0cbef11e9d83e2156a3a9f4eb88d2c
b4e836646dc07a07b57746c149dc58d94eae0563
/GameOverLayer.cpp
6781ecc2c1abaca1a37f4c93b76b66acd5a26649
[]
no_license
Lipu-Z/Find_Rabbit
f085abae7137aaa7897c0304c2ecbd8aac73ef0d
2bbb2ac472d8a44a665064e08f4ef486d7e4cc6f
refs/heads/master
2020-06-05T03:34:56.638589
2015-08-21T09:09:56
2015-08-21T09:09:56
39,252,471
0
0
null
null
null
null
UTF-8
C++
false
false
116
cpp
GameOverLayer.cpp
// // GameOverLayer.cpp // findrabbit // // Created by Lipu Zhong on 15/7/28. // // #include "GameOverLayer.h"
3fbbd075dfdec053eb4fe10875038ee303eddc19
4c0aaa21705a9f1726133b5b524d6c3596aa9642
/DZ31.3/DZ31.3/dz31.3.cpp
9698104a22a1e12a4cce1d6cc8b4643d3f7350ba
[]
no_license
mrjeck/cpp
407f3308ccea56e8d8546e331cce13bb60627af5
762993646ea3d89e662efe660b313cef6cdf66a8
refs/heads/master
2020-12-30T10:12:42.253606
2015-09-26T18:02:57
2015-09-26T18:02:57
34,620,448
0
0
null
null
null
null
UTF-8
C++
false
false
1,676
cpp
dz31.3.cpp
#include <iostream> #include <cstdlib> #include <cstring> #include <string> #define PI 3.14 using namespace std; class Circle { protected: double radius; public: Circle(double _radius):radius(_radius) {} virtual ~Circle() {} virtual double GetRadius() { return radius; } virtual double GetPer() { return 2*PI*radius; } virtual void SetInfo(double _radius){radius=_radius;} }; class Square { protected: double a; public: Square(double _a):a(_a) {} virtual ~Square() {} double GetA() { return a; } virtual double GetArea(){return a*a; } virtual void SetInfo(double _a) { a=_a; } }; class CinS:public Circle, public Square { public: CinS(double _radius, double _a):Circle(_radius),Square(_a) {} ~CinS(){} virtual void SetInfo(double _radius, double _a) { a=_a; radius=_a/2; } double GetRadius(){return radius; } double GetArea(){return PI*(radius*radius); } double GetPer(){return 2*PI*radius; } }; int main() { Circle Ob1(0); int s=0; cout<<"Enter radius of the circle\n"; cin>>s; Ob1.SetInfo(s); cout<<"For circle with radius: "<< Ob1.GetRadius() <<'\n'; cout<<"Perimetr: "<< Ob1.GetPer() <<'\n'; cout<<"\n"; Square Ob2(0); int d=0; cout<<"Enter side of the square\n"; cin>>d; Ob2.SetInfo(d); cout<<"For square with side: "<< Ob2.GetA() <<'\n'; cout<<"Area is: "<< Ob2.GetArea() <<'\n'; cout<<"\n"; CinS Ob3(0,0); int f=0; cout<<"Enter side of square\n"; cin>>f; Ob3.SetInfo(f/2,f); cout<<"For square with side: "<< Ob3.GetA() <<" and circle with radius: "<< Ob3.GetRadius() <<'\n'; cout<<"Perimetr of circle is: "<< Ob3.GetPer() <<'\n'; cout<<"Area of circle is: "<< Ob3.GetArea() <<'\n'; return 0; }
0c7554c6bb52749ff5906569b03ff772dee32aa7
d7f371477273e2bfab05e443e92db95bd5891f73
/ClickBall/ranking.h
a3a85c5a92ac56a9840504d9ae79e6dbb8d530bc
[]
no_license
WebsterBolek/ClickBall
e7d51c1dc232064460dcc79023455aa82accd1d7
2079d71693276ee0620dba83999533fb18a220fa
refs/heads/master
2020-04-06T23:53:15.759574
2019-01-23T12:39:29
2019-01-23T12:39:29
157,884,444
0
0
null
2018-12-05T14:15:18
2018-11-16T15:16:14
C++
UTF-8
C++
false
false
285
h
ranking.h
#ifndef RANKING_H #define RANKING_H #include <QGraphicsTextItem> #include "dialog.h" class Ranking: public QGraphicsTextItem{ public: Ranking(QGraphicsItem * parent=0); void punkt(); int pokazranking(); private: int ranking; }; #endif // RANKING_H
bc4bb4d06095fa350ab2976a3ce6aead8878ff46
5cc2cc7628b07aa737b0191c7e374eb88455aa98
/qtdeclarative5-mango-utils-0.0.1/Mango/Utils/window.h
3a4b60edf67c24f7b00fb6fa5c27422c9f7fc798
[]
no_license
JosephMillsAtWork/qtpublic
42454bfebd77e28c9e11b7f6317c947e70c283eb
430681d2ffc8b91f3abceeca809d6a621e4c3baa
refs/heads/master
2021-01-10T16:39:13.257950
2015-06-02T20:38:58
2015-06-02T20:38:58
36,760,292
4
0
null
null
null
null
UTF-8
C++
false
false
464
h
window.h
#ifndef WINDOW_H #define WINDOW_H #include <QtCore/QObject> #include <QtQuick/QQuickWindow> class Window : public QObject { Q_OBJECT Q_PROPERTY(int surfaceRole READ surfaceRole WRITE setSurfaceRole NOTIFY surfaceRoleChanged) public: explicit Window(QObject *parent = 0); int surfaceRole() const; void setSurfaceRole(int surfaceRole); Q_SIGNALS: void surfaceRoleChanged(int); private: QQuickWindow* m_window; }; #endif // WINDOW_H
4be971ad10fe9dea91cec1bd78c3a4846d2bd688
6237b142e8009ff93641dbf65f19add2788e6149
/Render/Render/Game.h
29880904e3da35fba5a0f84ea8ca5120fc91135b
[]
no_license
adharsh/Render
190c7e3a08b637c49dd600f719896f1b0c0537df
af33501fcd0057763628bc068d3b46da13abfa47
refs/heads/master
2021-09-15T02:06:24.931920
2018-05-24T02:35:23
2018-05-24T02:35:23
80,696,466
1
0
null
null
null
null
UTF-8
C++
false
false
675
h
Game.h
#pragma once namespace ginkgo { class Window; class Layer; class Camera; class CubeMap; class PhongShader; class ReflectionShader; class Text; class ScreenBuffer; class LensLayer; class LensShader; class Game { private: bool isGameOver; private: Window& window; Layer* layer; Camera* camera; CubeMap* skybox; ReflectionShader* reflectionShader; PhongShader* phongShader; Text* text; ScreenBuffer* screen; LensShader* lensShader; LensLayer* lensLayer; public: Game(Window& window); void input(double dt); void update(double dt); void render(); void postProcessing(); bool gameOver() { return isGameOver; } }; }
c10838e6a3838f93d94e6a89933aa0aab4a55a94
c14500adc5ce57e216123138e8ab55c3e9310953
/contrib/Netgen/libsrc/include/csg.hpp
ffd45ef0bf4fb948a3efd2432eb8e7b6c111900c
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.0-or-later", "LicenseRef-scancode-generic-exception", "GPL-1.0-or-later", "LicenseRef-scancode-proprietary-license", "GPL-2.0-only", "GPL-2.0-or-later", "LicenseRef-scancode-other-copyleft", "MIT", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-only" ]
permissive
ResonanceGroup/GMSH304
8c8937ed3839c9c85ab31c7dd2a37568478dc08e
a07a210131ee7db8c0ea5e22386270ceab44a816
refs/heads/master
2020-03-14T23:58:48.751856
2018-05-02T13:51:09
2018-05-02T13:51:09
131,857,142
0
1
MIT
2018-05-02T13:51:10
2018-05-02T13:47:05
null
UTF-8
C++
false
false
26
hpp
csg.hpp
#include "../csg/csg.hpp"
2f1ed3c7e9c5bae30aba34f18a2db86a618899b8
8c82771633dab5feaa1954378d1862e004be2c99
/tdproject/newproject.cpp
dbfaa632a82bb84a127b845ed38a99c0ce9c6fbe
[]
no_license
SankaW57/ClientManagementApp
7effa081192af6a666aa82f24e1fe22f0c568f74
4f332f47564c595cd152add3a8623f0b6a80aa4f
refs/heads/master
2022-06-20T03:53:32.815413
2020-05-01T06:44:34
2020-05-01T06:44:34
260,396,435
0
0
null
null
null
null
UTF-8
C++
false
false
215
cpp
newproject.cpp
#include "newproject.h" #include "ui_newproject.h" NewProject::NewProject(QWidget *parent) : QDialog(parent), ui(new Ui::NewProject) { ui->setupUi(this); } NewProject::~NewProject() { delete ui; }
af293a046ad24498297ea92cfd4592c5fb5ee702
dc1541e6cd6b090bc936d91a20bb073cea21404e
/uri/uri2552.cpp
05ae67d632ffa511b5cda515d0f6b5136997ad80
[]
no_license
lvirgili/programming_challenges
f9a92b5beefd08ccfc34b85d6a0c14cf00c40f0b
2bed6d73c27b09da9c5e80973c881249ece008a8
refs/heads/master
2021-05-16T02:57:04.560437
2017-11-05T00:41:51
2017-11-05T00:41:51
4,745,914
4
0
null
null
null
null
UTF-8
C++
false
false
639
cpp
uri2552.cpp
#include <bits/stdc++.h> using namespace std; int main() { int n, m; while (cin >> n >> m) { int b[n + 2][m + 2]; memset(b, 0, sizeof b); for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { cin >> b[i][j]; } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= m; ++j) { if (b[i][j] == 1) cout << 9; else { cout << b[i-1][j] + b[i+1][j] + b[i][j-1] + b[i][j+1]; } } cout << endl; } } return 0; }
2cac4992194c9d90b67b288315eb339685ad3f43
b0f08154e3eebc7d8465efc57597e52d08d69c18
/unit_tests/loaddb/test_loaddb.hpp
13d258a249585dd8540daa08e890a5b336031e10
[ "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CUBRID/cubrid
8f71a0010243b72e43ba887d229210650f4e901e
3b952af33230839a1b561a78ecd4b773374b66f8
refs/heads/develop
2023-08-18T19:16:30.987583
2023-08-18T08:18:05
2023-08-18T08:18:05
52,080,367
287
294
NOASSERTION
2023-09-14T21:29:09
2016-02-19T10:25:32
C
UTF-8
C++
false
false
960
hpp
test_loaddb.hpp
/* * Copyright 2008 Search Solution Corporation * Copyright 2016 CUBRID Corporation * * 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. * */ /* * test_loaddb.hpp - implementation for loaddb parse tests */ #ifndef _TEST_LOADDB_PASRE_HPP_ #define _TEST_LOADDB_PASRE_HPP_ namespace test_loaddb { void test_parse_with_multiple_threads (); void test_parse_reusing_driver (); }; // namespace test_loaddb #endif //_TEST_LOADDB_PASRE_HPP_
9ccdee4a2cd5e3429c3d644d2e58fb7344389826
5f2c1792902470aac75db8a46e643a93d8a75cd4
/core/smp.cpp
abe7b84f311c7f1a2c7933c993bb85e962009c0d
[]
no_license
irqlevel/kstor
055d6a0e3b280e9b812fcccb33d05ac473c4dd30
41fdf43f6981e455d3c058947d2a4e879370bbce
refs/heads/master
2018-03-11T07:05:44.358556
2017-03-24T22:02:57
2017-03-24T22:02:57
60,274,460
4
1
null
null
null
null
UTF-8
C++
false
false
1,583
cpp
smp.cpp
#include "smp.h" #include "atomic.h" namespace Core { int Smp::GetCpuId() { return get_kapi()->smp_processor_id(); } void Smp::PreemptDisable() { get_kapi()->preempt_disable(); } void Smp::PreemptEnable() { get_kapi()->preempt_enable(); } void Smp::LockOnlineCpus() { get_kapi()->get_online_cpus(); } void Smp::UnlockOnlineCpus() { get_kapi()->put_online_cpus(); } void Smp::CallFunctionOtherCpus(void (*function)(void *data), void *data, bool wait) { get_kapi()->smp_call_function(function, data, wait); } void Smp::CountCpus(void *data) { Atomic *counter = static_cast<Atomic *>(data); counter->Inc(); } void Smp::Pause() { } void Smp::BlockAndWait(void *data) { struct BlockAndWait *bw = static_cast<struct BlockAndWait *>(data); bw->Counter->Inc(); while (bw->Block->Get()) { Pause(); } } void Smp::CallFunctionCurrCpuOnly(void (*function)(void *data), void *data) { Atomic counter, block; LockOnlineCpus(); PreemptDisable(); CallFunctionOtherCpus(&Smp::CountCpus, static_cast<void *>(&counter), true); int nrCpus = counter.Get(); counter.Set(0); block.Set(1); struct BlockAndWait bw; bw.Counter = &counter; bw.Block = &block; CallFunctionOtherCpus(&Smp::BlockAndWait, static_cast<struct BlockAndWait *>(&bw), false); while (counter.Get() != nrCpus) { Pause(); } function(data); block.Set(0); PreemptEnable(); UnlockOnlineCpus(); } }
3b43fe44f8b2f5cf17b0824ca1fe06f674330e8f
49022e7430be70ab6880c28b759f9c68e1e2edf8
/Faceless/Game/Player.h
d45cc9318883c93f3333aadd5688176099cb56d6
[]
no_license
f3db43f4g443/SimpleSample11
61a634afa664676f94bf51f58c38640ee7ee1b64
e6aa0ceb34843defd0433b09f42f2de036d443d7
refs/heads/master
2022-03-10T18:21:42.698566
2022-02-18T06:42:18
2022-02-18T06:42:18
68,726,252
0
1
null
2021-04-15T18:51:36
2016-09-20T15:30:41
C++
UTF-8
C++
false
false
1,427
h
Player.h
#pragma once #include "Attribute.h" #include "Character.h" class CPlayer : public CCharacter { friend void RegisterGameClasses(); public: enum { ePlayerCommand_EndPhase, ePlayerCommand_Move, ePlayerCommand_FaceEdit, ePlayerCommand_Action, ePlayerCommand_SelectTargetLevelGrid, ePlayerCommand_SelectTargetFaceGrid, ePlayerCommand_Count, }; CPlayer( const SClassCreateContext& context ); virtual void OnAddedToStage() override; virtual void OnRemovedFromStage() override; virtual void MovePhase( CTurnBasedContext* pContext ) override; virtual void EmotePhase( CTurnBasedContext* pContext ) override; virtual void BattlePhase( CTurnBasedContext* pContext ) override; virtual bool SelectTargetLevelGrid( CTurnBasedContext* pContext ) override; virtual TVector2<int32> SelectTargetFaceGrid( CTurnBasedContext* pContext ) override; void PlayerCommand( uint32 iEvent, void* pContext ) { m_onPlayerCommand.Trigger( iEvent, pContext ); } void PlayerCommandEndPhase(); void PlayerCommandMove( uint8 nDir ); bool PlayerCommandFaceEditItem( CFaceEditItem* pItem, const TVector2<int32>& pos ); bool PlayerCommandAction( class COrgan* pOrgan ); void PlayerCommandSelectTargetLevelGrid( const TVector2<int32>& grid ); void PlayerCommandSelectTargetFaceGrid( const TVector2<int32>& grid ); protected: virtual void OnTick() override; private: CEventTrigger<ePlayerCommand_Count> m_onPlayerCommand; };
f757436a3f6d62ee1ed9159285a383cff0964fef
721fbc6aaf88ffdd8066614d07c275b82b52f520
/src/debug/debug.h
c89360954c31b18b7119798730e885d0d4dde356
[]
no_license
kaludis/Woogine
bc7b84f4016653eab511f5c53d2619050c6a1369
348fea906f9d635e8c872cbc568dbfe9949d0f71
refs/heads/master
2021-01-10T09:39:12.896053
2016-03-20T10:42:00
2016-03-20T10:42:00
53,473,928
0
0
null
null
null
null
UTF-8
C++
false
false
1,465
h
debug.h
#pragma once #include <cstdio> namespace utils { namespace debug { void check_error(const char* file, int line, const char* func); } /* namespace debug */ } /* namespace utils */ #ifdef DEBUG #define CHECK_ERR() utils::debug::check_error(__FILE__, __LINE__, __func__) #else #define CHECK_ERR() #endif // DEBUG #ifdef DEBUG #define DEBUG_MSG(fmt, ...) \ do { fprintf(stdout, "%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__); } while (0) #define DEBUG_MSGWARN(fmt, ...) \ do { fprintf(stdout, "[WARNING]%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__); } while (0) #define DEBUG_MSGERR(fmt, ...) \ do { fprintf(stdout, "[ERROR]%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__); } while (0) #define DEBUG_PRINT(fmt, ...) \ do { fprintf(stdout, "%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__, __VA_ARGS__); } while (0) #define DEBUG_PRINT_WARN(fmt, ...) \ do { fprintf(stderr, "[WARNING]%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__, __VA_ARGS__); } while (0) #define DEBUG_PRINT_ERR(fmt, ...) \ do { fprintf(stderr, "[ERROR]%s:%d:%s(): " fmt, __FILE__, \ __LINE__, __func__, __VA_ARGS__); } while (0) #else #define DEBUG_MSG(fmt, ...) #define DEBUG_MSGWARN(fmt, ...) #define DEBUG_MSGERR(fmt, ...) #define DEBUG_PRINT(fmt, ...) #define DEBUG_PRINT_WARN(fmt, ...) #define DEBUG_PRINT_ERR(fmt, ...) #endif // DEBUG #define UNUSED(arg) (void)(arg) #define BUFFER_OFFSET(idx) \ (static_cast<char*>(0) + idx)
ff4e1c576c6c04d4fc8182b58657248cc459fb92
94e8e0d10dd993cb08785d1bab6aafc1055f509d
/Utils/samples/ClassUtls/Thread.h
464fe05bace1cacf888384f55d4b79750c8d518b
[]
no_license
albertomila/continous-formation
1d416170d2ad85ad1e2ea5eef0f2436cd299c716
e3a57f0fc22dc16b1e9cce1ed100795ca664359d
refs/heads/master
2020-06-14T00:46:23.147271
2019-07-08T18:38:54
2019-07-08T18:38:54
194,838,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,162
h
Thread.h
#pragma once #include <windows.h> class Thread { public: Thread (); virtual ~Thread (); bool CreateThread (); int IsCreated (){ return (this->hThread != NULL); } DWORD Timeout; HANDLE GetThreadHandle (){ return this->hThread; } DWORD GetThreadId (){ return this->hThreadId; } HANDLE GetMainThreadHandle (){ return this->hMainThread; } DWORD GetMainThreadId (){ return this->hMainThreadId; } protected: //overrideable virtual unsigned long Process (void* parameter) = 0; DWORD hThreadId; HANDLE hThread; DWORD hMainThreadId; HANDLE hMainThread; private: static int runProcess (void* Param); }; struct param { Thread* pThread; }; /* ///ExampleProcess.h class ExampleProcess : public Thread { public: ExampleProcess(void); ~ExampleProcess(void); unsigned long Process (void* parameter); }; ///ExampleProcess.cpp unsigned long ScreenMenuLoader::Process (void* parameter) { if (::GetCurrentThreadId () == this->hMainThreadId) { return 0; } else { //put of the new process here return 0; } } ///main.cpp ExampleProcess* exampleProcess = new ExampleProcess(); exampleProcess->CreateThread(); */
f714952b3620e7a89b0a86fa400fccb24aa5c1cf
d897efddba1087bac262d1fdb3131d73b15cb59b
/labs-C00217717/Project 1/Project1/include/Ball.h
a1a119704e2c87d2f437df25bf6e481bd4a7cbe5
[]
no_license
EoinAM/ProgrammingLabs
08e25c9856921be4047a4ed1ebe17d4aa75d0cd4
292a01103dfdcab7c97066cb2efd359e8b057638
refs/heads/master
2020-03-16T11:05:13.756348
2018-05-24T22:22:54
2018-05-24T22:22:54
132,642,739
0
0
null
null
null
null
UTF-8
C++
false
false
2,070
h
Ball.h
/// <summary> /// @Author Eoin Abbey-Maher /// </summary> #ifndef BALL #define BALL #include "Block.h" #include "ScreenSize.h" #include "Enemy.h" #include "Paddle.h" #include "KeyHandler.h" #include <iostream> #include <SFML\Graphics.hpp> class Ball { public: /// <summary> /// Default Constructor /// </summary> /// <param name="t_keyHandler"> Passed the Keyhandler from the Game Class</param> Ball(KeyHandler & t_keyHandler); /// <summary> /// Default Destructor /// </summary> ~Ball(); void update(); void render(sf::RenderWindow & t_window); /// <summary> /// function to reset the ball object after it goes /// out of the play area /// </summary> void reset(); /// <summary> /// Functions to test for colisiions between the ball and /// other on screen objects /// /// Passed references to the Paddle, Blocks and Enemies from the Game Class /// </summary> void m_collisionBlock(Block & t_block); void m_collisionEnemy(Enemy& t_enemy); void m_collisionPaddle(Paddle & t_paddle); void m_collisionWall(); /// <summary> /// Setups for when the Game is started /// </summary> sf::Vector2f m_startingVector{ 2,2 }; sf::Vector2f m_startPosition; sf::Vector2f m_DirectionVector{ 2,2 }; sf::Vector2f m_position; sf::Vector2f m_lastPosition; sf::CircleShape m_body; int m_boostUsages{ 3 }; int m_score{ 0 }; int m_timer{ 120 }; int m_subtimer{ 0 }; float m_speed{ 3 }; /// <summary> /// Booleans for if the Ball is to be drawn /// & for if the ball is dead or not /// </summary> bool m_isShown; bool m_dead{ false }; private: /// <summary> /// Variables for the Collision /// </summary> float m_hitDistance{ 0.0f }; float m_deflection{ 0.0f }; float m_angle{ 0.0f }; /// <summary> /// Timer activated when the power up is used /// </summary> int m_boostTimer{ 0 }; void boost(); void move(); /// <summary> /// Booleans for if the ball is moving and if it is powered up /// </summary> bool m_moving{ false }; bool m_boosted{ false }; KeyHandler & m_keyHandler; }; #endif // !BALL
0acc74131306806e24d87470aba048a1a6d89463
60619a8daa4603fb65f4f86f383a6ddde841e326
/2014-03-20/j.cpp
71e42bb4fdd9476c121a7e01a1fb29a109739296
[]
no_license
MYREarth/secret-weapon
f4b1d4b995951546b2fb1e40190707a805fb88b5
77f3ff1111aafaaae8f56893b78e3be9134437a9
refs/heads/master
2020-05-22T02:29:43.024017
2015-10-03T08:17:46
2015-10-03T08:17:46
186,199,326
3
0
null
2019-05-12T01:46:13
2019-05-12T01:46:13
null
UTF-8
C++
false
false
1,572
cpp
j.cpp
#include <cstdio> #include <queue> #include <map> using namespace std; struct state { int u,v,end; state(int u,int v,int end):u(u),v(v),end(end){} }; inline bool operator <(const state &a,const state &b) { return(a.u<b.u || a.u==b.u && (a.v<b.v || a.v==b.v && a.end<b.end)); } int end[110],a[110][10],ans[110][110][2][10]; int main() { int K,n; scanf("%d%d",&K,&n); for (int i=1;i<=n;i++) scanf("%d",&end[i]); for (int i=1;i<=n;i++) for (int j=0;j<10;j++) scanf("%d",&a[i][j]); queue <state> Q; map <state,int> M; state init(1,0,end[1]); int tot=1; M[init]=0; Q.push(init); while (!Q.empty()) { int u=Q.front().u,v=Q.front().v,w=Q.front().end; Q.pop(); for (int i=0;i<10;i++) { int x=a[u][i],y=i==0?a[v][9]:a[u][i-1],z=i>=K?end[a[u][i-K]]:end[a[v][i+10-K]]; state now(x,y,z); if (!M.count(now)) { M[now]=tot++; Q.push(now); } ans[u][v][w][i]=M[now]+1; } } vector <state> tmp(M.size(),state(0,0,0)); for (map <state,int>::iterator k=M.begin();k!=M.end();k++) tmp[k->second]=k->first; printf("Success\n%d\n",tmp.size()); for (int i=0;i<tmp.size();i++) printf("%d%c",tmp[i].end,i+1==tmp.size()?'\n':' '); for (int i=0;i<tmp.size();i++) { int x=tmp[i].u,y=tmp[i].v,z=tmp[i].end; for (int j=0;j<10;j++) printf("%d%c",ans[x][y][z][j],j==9?'\n':' '); } return(0); }
4306a054b3099b5f8c0bd587f63014e1600fe715
2d1f82fe5c4818ef1da82d911d0ed81a0b41ec85
/codeforces/R528/CF1086D.cpp
53770e7a7eea2139091f6392981429471d53a068
[]
no_license
OrigenesZhang/-1s
d12bad12dee37d4bb168647d7b888e2e198e8e56
08a88e4bb84b67a44eead1b034a42f5338aad592
refs/heads/master
2020-12-31T00:43:17.972520
2020-12-23T14:56:38
2020-12-23T14:56:38
80,637,191
4
1
null
null
null
null
UTF-8
C++
false
false
2,494
cpp
CF1086D.cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++) #define ROF(i, a, b) for (int (i) = (a); (i) >= (b); (i)--) #define REP(i, n) FOR(i, 0, (n)-1) #define sqr(x) ((x) * (x)) #define all(x) (x).begin(), (x).end() #define reset(x, y) memset(x, y, sizeof(x)) #define uni(x) (x).erase(unique(all(x)), (x).end()); #define BUG(x) cerr << #x << " = " << (x) << endl #define pb push_back #define eb emplace_back #define mp make_pair #define _1 first #define _2 second const int maxn = 212345; int n, C[3][maxn], q; set<int> s[3]; char ini[maxn], op[5]; inline int lowbit(int x) { return x & -x; } int sum(const int *C, int x) { int ret = 0; while (x > 0) { ret += C[x]; x -= lowbit(x); } return ret; } void add(int *C, int x, int d) { while (x <= n) { C[x] += d; x += lowbit(x); } } int query() { int cnt = 0; REP(i, 3) cnt += s[i].empty(); if (cnt == 2) return n; if (cnt == 1) REP(i, 3) if (s[i].size() && s[(i + 2) % 3].size()) return s[i].size(); int ans = n; REP(i, 3) { int l = *(s[(i + 1) % 3].begin()), r = *(s[(i + 2) % 3].begin()); if (r > l) ans -= sum(C[i], r) - sum(C[i], l); l = *(s[(i + 2) % 3].rbegin()), r = *(s[(i + 1) % 3].rbegin()); if (r > l) ans -= sum(C[i], r) - sum(C[i], l); } return ans; } int main() { scanf("%d%d", &n, &q); scanf("%s", ini + 1); FOR(i, 1, n) { if (ini[i] == 'R') { add(C[0], i, 1); s[0].insert(i); } else if (ini[i] == 'P') { add(C[1], i, 1); s[1].insert(i); } else { add(C[2], i, 1); s[2].insert(i); } } printf("%d\n", query()); while (q--) { int i; scanf("%d%s", &i, op); if (ini[i] == 'R') { add(C[0], i, -1); s[0].erase(i); } else if (ini[i] == 'P') { add(C[1], i, -1); s[1].erase(i); } else { add(C[2], i, -1); s[2].erase(i); } ini[i] = op[0]; if (ini[i] == 'R') { add(C[0], i, 1); s[0].insert(i); } else if (ini[i] == 'P') { add(C[1], i, 1); s[1].insert(i); } else { add(C[2], i, 1); s[2].insert(i); } printf("%d\n", query()); } }
3a0300671f32e3da85cf42c9491b3a6fdf07a206
edfe03159a3e622e7407c9b842877fe4c8c1c049
/include/TSiLiHit.h
b6082800497bd1f4aa6103a3ca3418028ad3d9aa
[]
no_license
jhenderson88/GRSISort
66c9ad2e28d5c506c4aa884ee41524ed1d528d54
e8fe2ad82bb54022f2f2ac1f8e68bda73a3f601c
refs/heads/master
2021-01-17T05:18:36.108816
2016-10-20T15:45:23
2016-10-20T15:45:23
34,932,903
0
0
null
2015-05-02T02:28:13
2015-05-02T02:28:12
null
UTF-8
C++
false
false
1,127
h
TSiLiHit.h
#ifndef TSILIHIT_H #define TSILIHIT_H /** \addtogroup Detectors * @{ */ #include <cstdio> #include <utility> #include "TFragment.h" #include "TChannel.h" #include "TGRSIDetectorHit.h" #include "TPulseAnalyzer.h" class TSiLiHit : public TGRSIDetectorHit { public: TSiLiHit(); TSiLiHit(TFragment &); virtual ~TSiLiHit(); TSiLiHit(const TSiLiHit&); void Copy(TObject&) const; //! void Clear(Option_t *opt=""); void Print(Option_t *opt="") const; Double_t GetSig2Noise()const { return fSig2Noise;} Int_t GetRing() const { return 9-(GetSegment()/12); } Int_t GetSector() const { return GetSegment()%12; } Int_t GetPreamp() const { return ((GetSector()/3)*2)+(((GetSector()%3)+GetRing())%2); } Double_t GetTimeFit() { return fTimeFit; } void SetWavefit(TFragment&); TVector3 GetPosition(Double_t dist) const; //! TVector3 GetPosition() const; //! private: Double_t GetDefaultDistance() const { return 0.0; } Double_t fTimeFit; Double_t fSig2Noise; /// \cond CLASSIMP ClassDef(TSiLiHit,7); /// \endcond }; /*! @} */ #endif
3be754294cd5931b2a40816ce5afb4d9d7a600df
933f154b469178fb9c3dd648bc985960c19290db
/second/482_LicenseKeyFormat/solution.cpp
4184da7d5c7bb690bf7e5f892c2d20eda5f12fea
[]
no_license
zywangzy/LeetCode
c5468ea8b108e9c1dec125fb07a5841348693f96
df2cba28ed47938073ab1ffc984af158e3de7611
refs/heads/master
2021-09-29T13:39:58.151078
2018-11-24T22:35:04
2018-11-24T22:35:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
solution.cpp
#include "../../IOLib.hpp" class Solution { public: string licenseKeyFormatting(string S, int K) { vector<char> str; for(auto c: S){ if(c != '-') str.push_back(toupper(c)); } int num = str.size() % K; string res; auto it = str.begin(); if(num){ res += string(it, it + num) + "-"; } for(int start = num; start < str.size(); start += K){ res += string(it + start, it + start + K) + "-"; } return res.substr(0, res.size() - 1); } };
9fd9c6bb98fe140e9a3f11c5c60a1c07d9364305
6bdff07dcdbddb26fdee09f8e9899d45fbdeb77d
/flatlandspacestations.cpp
039166f281bfc5c6aa25f644b195cfd752ff76f1
[]
no_license
GauravSingh9356/Hackerrank-Solution
3de152bba73b5f96eab526bc4f0240fd43e2e1ef
7ba675e93da4682790830b0a80705433c0321d63
refs/heads/master
2022-12-22T01:25:26.336411
2020-10-04T07:50:38
2020-10-04T07:50:38
288,470,380
1
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
flatlandspacestations.cpp
#include<bits/stdc++.h> using namespace std; int main(int argc, char const *argv[]) { int n,m,value; vector<int>ans; scanf("%d%d",&n,&m); int arr[m]; for(int i=0;i<m;i++) scanf("%d",&arr[i]); sort(arr, arr+m); for(int i=0;i<n;i++){ value=INT_MAX; for(int j=0;j<m;j++){ value = min(value,abs(i-arr[j])); if(value==0){ ans.push_back(0); break; } } ans.push_back(value); } cout<<*max_element(ans.begin(), ans.end()); return 0; }
17ac5c288f2ccba378c3e63bd11b8d0f32b5a9fb
e842372699fbba5e42708fc18de4cc775377e5d0
/fs_mgr/liblp/partition_opener.cpp
4696ff173b0ad0b3d8950931494878316c67b8d4
[ "MIT" ]
permissive
aosp-mirror/platform_system_core
cd1921c7e87396ef99ff46332aa34512977c58a4
18560efc308f9c345915dd4d5fa1a2939fcf5ebc
refs/heads/master
2023-08-28T05:09:18.711274
2023-08-25T17:07:42
2023-08-25T17:07:42
65,923
610
877
NOASSERTION
2023-05-13T20:56:01
2008-10-21T18:21:04
C++
UTF-8
C++
false
false
3,966
cpp
partition_opener.cpp
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "liblp/partition_opener.h" #if defined(__linux__) #include <linux/fs.h> #endif #if !defined(_WIN32) #include <sys/ioctl.h> #endif #include <sys/types.h> #include <unistd.h> #include <android-base/file.h> #include <android-base/strings.h> #include "utility.h" namespace android { namespace fs_mgr { using android::base::unique_fd; namespace { std::string GetPartitionAbsolutePath(const std::string& path) { #if !defined(__ANDROID__) return path; #else if (android::base::StartsWith(path, "/")) { return path; } auto by_name = "/dev/block/by-name/" + path; if (access(by_name.c_str(), F_OK) != 0) { // If the by-name symlink doesn't exist, as a special case we allow // certain devices to be used as partition names. This can happen if a // Dynamic System Update is installed to an sdcard, which won't be in // the boot device list. // // mmcblk* is allowed because most devices in /dev/block are not valid for // storing fiemaps. if (android::base::StartsWith(path, "mmcblk")) { return "/dev/block/" + path; } } return by_name; #endif } bool GetBlockDeviceInfo(const std::string& block_device, BlockDeviceInfo* device_info) { #if defined(__linux__) unique_fd fd = GetControlFileOrOpen(block_device.c_str(), O_RDONLY); if (fd < 0) { PERROR << __PRETTY_FUNCTION__ << "open '" << block_device << "' failed"; return false; } if (!GetDescriptorSize(fd, &device_info->size)) { return false; } if (ioctl(fd, BLKIOMIN, &device_info->alignment) < 0) { PERROR << __PRETTY_FUNCTION__ << "BLKIOMIN failed on " << block_device; return false; } int alignment_offset; if (ioctl(fd, BLKALIGNOFF, &alignment_offset) < 0) { PERROR << __PRETTY_FUNCTION__ << "BLKALIGNOFF failed on " << block_device; return false; } // The kernel can return -1 here when misaligned devices are stacked (i.e. // device-mapper). if (alignment_offset == -1) { alignment_offset = 0; } int logical_block_size; if (ioctl(fd, BLKSSZGET, &logical_block_size) < 0) { PERROR << __PRETTY_FUNCTION__ << "BLKSSZGET failed on " << block_device; return false; } device_info->alignment_offset = static_cast<uint32_t>(alignment_offset); device_info->logical_block_size = static_cast<uint32_t>(logical_block_size); device_info->partition_name = android::base::Basename(block_device); return true; #else (void)block_device; (void)device_info; LERROR << __PRETTY_FUNCTION__ << ": Not supported on this operating system."; return false; #endif } } // namespace unique_fd PartitionOpener::Open(const std::string& partition_name, int flags) const { std::string path = GetPartitionAbsolutePath(partition_name); return GetControlFileOrOpen(path.c_str(), flags | O_CLOEXEC); } bool PartitionOpener::GetInfo(const std::string& partition_name, BlockDeviceInfo* info) const { std::string path = GetPartitionAbsolutePath(partition_name); return GetBlockDeviceInfo(path, info); } std::string PartitionOpener::GetDeviceString(const std::string& partition_name) const { return GetPartitionAbsolutePath(partition_name); } } // namespace fs_mgr } // namespace android
ea0834c0dc86325f31816adb6a0324c2db75ed35
8ca39fc7c4179449d99b38ccebe00146c22b6925
/Learning_Cpp/quickCal.cpp
7c9f3573233f5efe3cfcda3f5bfaa4dd00e4477a
[]
no_license
goluckyryan/programmings
8cc03ac6c0158560a7149eca2ef923dca4f00e81
c4e2a5084dd957cfa4dd5f33f5f42a6339a5ff59
refs/heads/master
2021-07-17T14:04:13.348287
2021-02-18T04:40:58
2021-02-18T04:40:58
48,151,691
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
quickCal.cpp
#include <iostream> #include <cmath> #include "../CppLibrary/constant.h" #include "../CppLibrary/nuclei_mass.h" using namespace std; int main(){ int choice; double Brho, mass, A, Z; cout << " choose floowing calculation: \n"; cout << "--------------------------------------------------\n"; cout << " 1) KE per A -> Brho \n"; cout << " 2) Brho -> KE per A \n"; c cout << " (Brho, A, Z) = "; cin >> Brho >> A >> Z; mass = Nucleus_Mass(A,Z); if ( mass > 0 ) { cout << Brho2T(mass, Z, A, Brho) << "MeV/A" << endl; }else{ cout << "no such nuleus.\n"; } return 0; }
0b578e33429bad438c46961406dce377cda52bbb
165c448a5e9c982b5f8607f79783921aa001f403
/main.cxx
ab79c0507a74a31e6621cac949489067d8565abd
[]
no_license
xiwang1289/BoostLog
01effb643a55e88cdd21b1a29e7f7c98277c8059
5834d0f316c4c25fa460c614cfc3d2f6a810a088
refs/heads/master
2023-03-17T21:05:57.878806
2016-02-26T22:20:12
2016-02-26T22:20:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
539
cxx
main.cxx
#include "logger.hxx" #include <iostream> #include <exception> int main(int argc, char* argv[]) { try { if (argc > 1) { Logger::initFromConfig(argv[1]); Logger::addDataFileLog("test.log"); } else { Logger::init(); } LOG_DEBUG("Start of loop"); LOG_TRACE("before for loop"); for (int i = 0; i < 10; ++i) { LOG_DATA_INFO("i: " << i); } LOG_TRACE("after for loop"); } catch (std::exception& e) { LOG_ERROR("Exception in main: " << e.what()); return 1; } return 0; }
74ea4dbeae356cd301d4b35ce2209a685df96632
76957b84c5c97ac08dd2baea6cd3d5db96d26012
/common_project/tool_kits/qcef_view/src/handler/QCefViewBrowserAppHelper.cpp
872eceadcf209247e62a7316b7549461fa253562
[]
no_license
luchengbiao/base
4e14e71b9c17ff4d2f2c064ec4f5eb7e9ce09ac8
f8af675e01b0fee31a2b648eb0b95d0c115d68ff
refs/heads/master
2021-06-27T12:04:29.620264
2019-04-29T02:39:32
2019-04-29T02:39:32
136,405,188
0
1
null
null
null
null
UTF-8
C++
false
false
864
cpp
QCefViewBrowserAppHelper.cpp
#pragma region stl_headers #include <string> #pragma endregion stl_headers #pragma region cef_headers #include <include/cef_browser.h> #include <include/cef_command_line.h> #pragma endregion cef_headers #include "QCefViewBrowserApp.h" #include "QCefViewBrowserHandler.h" #include "BrowserDelegates/QCefViewDefaultBrowserDelegate.h" #include "SchemeHandlers/QCefViewDefaultSchemeHandler.h" void QCefViewBrowserApp::CreateBrowserDelegates(BrowserDelegateSet& delegates) { QCefViewDefaultBrowserDelegate::CreateBrowserDelegate(delegates); // add more browser delegates here } void QCefViewBrowserApp::RegisterCustomSchemesHandlerFactories() { QCefViewDefaultSchemeHandler::RegisterSchemeHandlerFactory(); } void QCefViewBrowserApp::RegisterCustomSchemes(CefRefPtr<CefSchemeRegistrar> registrar) { QCefViewDefaultSchemeHandler::RegisterScheme(registrar); }
88e5f0495a0f50780f8929ba2baf49620ac61289
988bd08eb7c953e44b4603da673ae0e5edfb89c9
/window_object/widgetobject.h
f0c73a8daf8090e994722caa80f17a3a2e217a6b
[]
no_license
adcpk/MadMan
8f882c7abb787742d663ff2067c38e4b211cae9f
44bdb80fc9c92a32b8add371216ae7c6962ea3a6
refs/heads/master
2020-05-01T09:14:36.770926
2019-03-24T10:36:35
2019-03-24T10:36:35
177,395,597
2
0
null
null
null
null
UTF-8
C++
false
false
1,156
h
widgetobject.h
#ifndef WIDGETOBJECT_H #define WIDGETOBJECT_H #include <QWidget> #include <QModelIndex> #include "container/data_object.h" namespace Ui { class WidgetObject; } class ModelObject; class KeyFilterProxyModel; class Data_Index; class WidgetObject : public QWidget { Q_OBJECT public: explicit WidgetObject(QWidget* parent = nullptr); ~WidgetObject(); protected: bool eventFilter(QObject* watched, QEvent* event) override; signals: void db_key(QStringList type,QString name,QModelIndex namei); void cdb_key(QStringList type,QString name,QModelIndex namei); void rc_key(QStringList type,QString name,QModelIndex namei); public: void loadData(QString t, Group tpl, QString rule,QString art, QString n, const QMap<QString,Data_Index> *ind); void saveDate(QString rule,QString art); void exportDate(); void setLoaction(QString l); private: Ui::WidgetObject* ui; QString rulepath; QString artpath; Data_Object dataobject; ModelObject* mdlobject; KeyFilterProxyModel* mdlproobject; const QMap<QString,Data_Index> *indexs = nullptr; }; #endif // WIDGETOBJECT_H
95de48ff6583ec7d79388702e9917fe4737319fd
a5a99f646e371b45974a6fb6ccc06b0a674818f2
/RecoBTag/ONNXRuntime/interface/tensor_fillers.h
bb1a25a2d0f0bf335afa48260358906f9e1caf1b
[ "Apache-2.0" ]
permissive
cms-sw/cmssw
4ecd2c1105d59c66d385551230542c6615b9ab58
19c178740257eb48367778593da55dcad08b7a4f
refs/heads/master
2023-08-23T21:57:42.491143
2023-08-22T20:22:40
2023-08-22T20:22:40
10,969,551
1,006
3,696
Apache-2.0
2023-09-14T19:14:28
2013-06-26T14:09:07
C++
UTF-8
C++
false
false
910
h
tensor_fillers.h
#ifndef RecoBTag_ONNXRuntime_tensor_fillers_h #define RecoBTag_ONNXRuntime_tensor_fillers_h #include "DataFormats/BTauReco/interface/DeepFlavourTagInfo.h" namespace btagbtvdeep { void jet_tensor_filler(float*& ptr, const btagbtvdeep::DeepFlavourFeatures& features); void cpf_tensor_filler(float*& ptr, const btagbtvdeep::ChargedCandidateFeatures& c_pf_features); void npf_tensor_filler(float*& ptr, const btagbtvdeep::NeutralCandidateFeatures& n_pf_features); void sv_tensor_filler(float*& ptr, const btagbtvdeep::SecondaryVertexFeatures& sv_features); void jet4vec_tensor_filler(float*& ptr, const btagbtvdeep::JetFeatures& jet_features); void seedTrack_tensor_filler(float*& ptr, const btagbtvdeep::SeedingTrackFeatures& seed_features); void neighbourTrack_tensor_filler(float*& ptr, const btagbtvdeep::TrackPairFeatures& neighbourTrack_features); } // namespace btagbtvdeep #endif
49c6cc1a55908cc249f59239a3911ee937357882
4724afa8472b0d961d40cc3be71f5abd1373143f
/spoj/hprof.cpp
94a3694022e2ba97cb7c4f33199cd1197e88de91
[]
no_license
banarun/my_competitive_codes
2f88334c563ad050c21c68ae449134a28fb2ba95
c5a5af3cf74341d02a328974e8e316d300a221b2
refs/heads/master
2021-01-18T22:46:47.419449
2016-06-25T14:14:15
2016-06-25T14:14:15
33,266,178
0
0
null
null
null
null
UTF-8
C++
false
false
1,248
cpp
hprof.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <ctime> #include <vector> #include <deque> #include <set> #include <map> #include <queue> #include <stack> #include <bitset> #include <string> #include <algorithm> #include <complex> #include <climits> #include <utility> using namespace std; #define ll long long #ifdef DEBUG #define dbg(args...) { cerr<<#args<<": "; dbgr,args; cerr<<endl;} #else #define dbg(args...) #endif struct debugger{template<typename T> debugger& operator , (const T& v){cerr<<v<<" "; return *this; }}dbgr; #define ll long long #define ull unsigned long long typedef pair<ll,ll> lpair; typedef pair<int,int> ipair; #define mp(A,B) make_pair(A,B) #define pb(X) push_back(X) #define ln length() #define inp(X) scanf("%d",&X) #define sl(n) scanf("%I64",&n) #define mod 1000000007 #define N 100002 int ans=0,n; string s; void foo(int p) { if(p>n) return; if(p==n){ ans++; return; } foo(p+1); if(p+1<n && s[p]>'0' && s[p]<'2') foo(p+2); else if(p+1<n && s[p]=='2' && s[p+1]=='0') foo(p+2); } int main() { cin>>s; n=s.ln; foo(0); cout<<ans<<endl; return 0; }
d640a8750aa5c284edb948590e74afa452b8369d
28d25f81c33fe772a6d5f740a1b36b8c8ba854b8
/FE-CU Training/FU-CU Team Formation Contest/4/A/main.cpp
e937863de99c06995f3d663c23d403f5f1a7d1d8
[]
no_license
ahmedibrahim404/CompetitiveProgramming
b59dcfef250818fb9f34797e432a75ef1507578e
7473064433f92ac8cf821b3b1d5cd2810f81c4ad
refs/heads/master
2021-12-26T01:18:35.882467
2021-11-11T20:43:08
2021-11-11T20:43:08
148,578,163
1
0
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
main.cpp
#include<bits/stdc++.h> using namespace std; int n, m; string str; int main(){ ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); cin >> n >> m; cin >> str; vector<int> odds(n); int mxodd=1, mxeven=0; for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r) ? 1 : min(odds[l + r - i], r - i + 1); while (k <= i && i + k < n && str[i - k] == str[i + k]) { k++; } odds[i] = k--; if (i + k > r) { l = i - k; r = i + k; } mxodd=max(mxodd, r-l+1); } vector<int> evens(n); for (int i = 0, l = 0, r = -1; i < n; i++) { int k = (i > r) ? 0 : min(evens[l + r - i + 1], r - i + 1); while (k <= i - 1 && i + k < n && str[i - k - 1] == str[i + k]) { k++; } evens[i] = k--; if (i + k > r) { l = i - k - 1; r = i + k ; } mxeven=max(mxeven, r-l+1); } if(m%2){ if(mxodd>=m) cout << "Accept\n"; else cout << "Reject\n"; } else { if(mxeven>=m) cout << "Accept\n"; else cout << "Reject\n"; } return 0; }
ee25a5bcf9d88b488796063a1079e75ba2167f9a
630c173c5ea37f58ea7de8636e449635a6af51fa
/Source/RandomLib/RandomPermutation.cpp
c75554dfb96b55393d4f837714c85241e82cee4b
[]
no_license
smfr/mactierra
021bf14ae175ff38cad7fb2ed2d39f2a65be6610
2c173694315868c3f03a7d7cb1e53e4a79719561
refs/heads/master
2021-01-19T15:00:10.961337
2014-07-23T06:31:24
2014-07-23T06:31:24
43,445
16
2
null
2014-07-22T06:14:14
2008-08-18T00:30:11
C++
UTF-8
C++
false
false
3,459
cpp
RandomPermutation.cpp
/** * \file RandomPermutation.cpp * \brief Prints a random permutation of integers * * Usage: RandomPermutation [-o] [-d] [-x] [-s seed] [-v] [-h] [num] * * Print a random permutation of numbers from 0 thru num-1 on standard output. * num is supplied on the command line as a decimal number (default is 100). * Optional arguments -o, -d, and -x selection octal, decimal, and hexadecimal * output base (default decimal). -s seed sets the seed. -v prints seed on * standard error. -h prints this help. * * seed is typically a list of comma-separated numbers, * e.g., -s ""; -s 1234; * -s 1,2,3,4; etc. You can repeat a permutatoin by * using the form of the seed, printed to standard error with -v, as the * argument to -s, e.g., -s "[671916,1201036551,9299,562196172,2008]". If the * seed is omitted, a "unique" seed is used. * * This is used by the "shuffle" script to shuffle the lines of a file. * * Written by <a href="http://charles.karney.info/">Charles Karney</a> * <charles@karney.com> and licensed under the GPL. For more information, see * http://charles.karney.info/random/ **********************************************************************/ #include "RandomLib/Random.hpp" #include <iostream> #include <iomanip> #include <sstream> #include <vector> #define RANDOMPERMUTATION_CPP "$Id: RandomPermutation.cpp 6424 2008-01-31 04:03:13Z ckarney $"; RCSID_DECL(RANDOMPERMUTATION_CPP); void usage(const std::string name, int retval) { ( retval == 0 ? std::cout : std::cerr ) << "Usage: " << name << " [-o] [-d] [-x] [-s seed] [-v] [-h] [num]\n\ \n\ Print a random permutation of numbers from 0 thru num-1\n\ on standard output. num is supplied on the command line\n\ as a decimal number (default is 100). Optional arguments\n\ -o, -d, and -x selection octal, decimal, and hexadecimal\n\ output base (default decimal). -s seed sets the seed.\n\ -v prints seed on standard error. -h prints this help.\n"; exit(retval); } int main(int argc, char* argv[]) { unsigned n = 100; unsigned base = 10; bool verbose = false; bool seedgiven = false; std::string seed; std::string arg; int m = 0; while (++m < argc) { arg = std::string(argv[m]); if (arg[0] != '-') break; // Exit loop if not option if (arg == "-o") base = 8; else if (arg == "-d") base = 10; else if (arg == "-x") base = 16; else if (arg == "-v") verbose = true; else if (arg == "-s") { seedgiven = true; if (++m == argc) usage(argv[0], 1); // Missing seed seed = std::string(argv[m]); } else if (arg == "-h") usage(argv[0], 0); else usage(argv[0], 1); // Unknown option } if (m == argc - 1) { std::istringstream str(arg); // First non-option argument str >> n; } else if (m != argc) usage(argv[0], 1); // Left over arguments unsigned k = 0; // Figure width of output for (unsigned i = n - 1; i; i /= base) k++; std::vector<unsigned> a(n); for (unsigned i = n; i--;) a[i] = i; RandomLib::Random r = seedgiven ? RandomLib::Random(seed) : RandomLib::Random(RandomLib::Random::SeedVector()); if (verbose) std::cerr << "Seed: " << r.SeedString() << "\n"; std::random_shuffle(a.begin(), a.end(), r); std::cout << std::setfill('0') << (base == 16 ? std::hex : (base == 8 ? std::oct : std::dec)); for (unsigned i = n; i--;) std::cout << std::setw(k) << a[i] << "\n"; return 0; }
c6a4945c4660ee0d8251f6a2c5893ab2a51eace1
c6d109a9bf019e29aa07c5cd5159eb5f3b407fe3
/fiber_bundles/section_spaces/sec_rep_descriptor.h
a427cf513939ff81f4013e8269f93587af1ad9ca
[ "Apache-2.0" ]
permissive
LimitPointSystems/SheafSystem
883effa60ec9533a085e2d1442c83df721e8d264
617faf00175b1422be648b85146e43d2fc54f662
refs/heads/master
2020-09-12T20:01:59.763743
2017-05-02T20:48:52
2017-05-02T20:48:52
16,596,740
2
3
null
2017-05-02T20:48:52
2014-02-06T22:44:58
C++
UTF-8
C++
false
false
12,847
h
sec_rep_descriptor.h
// // Copyright (c) 2014 Limit Point Systems, Inc. // // 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. // // Interface for class sec_rep_descriptor #ifndef SEC_REP_DESCRIPTOR_H #define SEC_REP_DESCRIPTOR_H #ifndef SHEAF_DLL_SPEC_H #include "SheafSystem/sheaf_dll_spec.h" #endif #ifdef STD_STRING_H #include "SheafSystem/std_string.h" #endif #ifndef TOTAL_POSET_MEMBER #include "SheafSystem/total_poset_member.h" #endif #ifndef ARRAY_POSET_DOF_MAP #include "SheafSystem/array_poset_dof_map.h" #endif namespace sheaf { class any; class namespace_poset; class poset; class poset_state_handle; } namespace fiber_bundle { using namespace sheaf; class eval_family; class fiber_bundles_namespace; class sec_rep_descriptor_poset; class sec_rep_space; /// /// A description for a section representation scheme. /// class SHEAF_DLL_SPEC sec_rep_descriptor: public total_poset_member { // =========================================================== /// @name HOST FACTORY FACET // =========================================================== //@{ public: /// /// The type of namespace for this type of member. /// typedef fiber_bundles_namespace namespace_type; /// /// The type of host poset. /// typedef sec_rep_descriptor_poset host_type; /// /// The path of the schema required by this class. /// static const poset_path& standard_schema_path(); /// /// Creates the standard schema for this class in namespace xns. /// static void make_standard_schema(namespace_poset& xns); /// /// The standard path for host spaces for this class. /// static const poset_path& standard_host_path(); /// /// Creates a new host table for members of this type. /// The poset is created in namespace xns with path xhost_path, schema specified by xschema_path, /// and table attribute prototypes_path specified by xprototypes_path. /// static host_type& new_host(namespace_type& xns, const poset_path& xhost_path, const poset_path& xschema_path, const poset_path& xprototypes_path, bool xauto_access); /// /// The host with path standard_host_path(). /// Returns the host if it already exists, otherwise, creates it in namespace xns /// with schema specified by standard_schema_path() and standard paths for prerequisites, /// which are also created if needed. /// static host_type& standard_host(namespace_type& xns, bool xauto_access); protected: private: //@} // =========================================================== /// @name SEC_REP_DESCRIPTOR FACET // =========================================================== //@{ public: /// /// Assignment operator /// virtual sec_rep_descriptor& operator=(const abstract_poset_member& xother); /// /// Assignment operator /// sec_rep_descriptor& operator=(const sec_rep_descriptor& xother); // CANONICAL MEMBERS /// /// Default constructor /// /// sec_rep_descriptor(); /// /// Copy constructor /// /// sec_rep_descriptor(const sec_rep_descriptor& xother, bool xnew_jem); /// /// Make a new handle, no state instance of current /// virtual sec_rep_descriptor* clone() const; /// /// Make a new handle instance of current. Attach the new instance to /// a new state if xnew_state is true. Otherwise, attach the new instance /// to the current state. /// inline sec_rep_descriptor* clone(bool xnew_state, bool xauto_access = true) const { return static_cast<sec_rep_descriptor*>(total_poset_member::clone(xnew_state, xauto_access)); } /// /// Destructor /// virtual ~sec_rep_descriptor(); /// /// Class invariant. /// virtual bool invariant() const; /// /// Conformance test; true if other conforms to this /// virtual bool is_ancestor_of(const any* other) const; // NEW HANDLE, NEW STATE CONSTRUCTORS /// /// Creates a new handle attached to a new jim state in xhost. /// sec_rep_descriptor(poset *xhost, const std::string& xdiscretization_subposet_name, const std::string& xmultivalued_subposet_name, const std::string& xevaluation_subposet_name, const std::string& xevaluation_method_name, const std::string& xurl, int xmultiplicity, bool xeval_is_above_disc, bool xauto_access); // NEW HANDLE, EXISTING STATE CONSTRUCTORS /// /// Creates a new handle attached to /// the member state with index xindex in xhost. /// sec_rep_descriptor(const poset *xhost, pod_index_type xindex); /// /// Creates a new handle attached to /// the member state with index xindex in xhost. /// sec_rep_descriptor(const poset *xhost, const scoped_index& xindex); /// /// Creates a new handle attached to /// the member state with name xname in xhost. /// sec_rep_descriptor(const poset *xhost, const std::string& xname); /// /// Creates a new sec_rep_descriptor handle attached to the member state /// specified by path xpath in namespace xns. /// sec_rep_descriptor(const namespace_poset* xns, const poset_path& xpath, bool xauto_access = true); /// /// Creates a new sec_rep_descriptor handle attached to the member state /// with index xmember_id in the poset with index xposet_id in the /// namespace xnamespace /// sec_rep_descriptor(const namespace_poset* xnamespace, pod_index_type xposet_id, pod_index_type xmember_id, bool xauto_access = true); /// /// Creates a new sec_rep_descriptor handle attached to the member state /// with index xmember_id in the poset with index xposet_id in the /// namespace xnamespace /// sec_rep_descriptor(const namespace_poset* xnamespace, const scoped_index& xposet_id, const scoped_index& xmember_id, bool xauto_access = true); // EXISTING HANDLE, NEW STATE "CONSTRUCTORS" using total_poset_member::new_jim_state; /// /// Creates a new jim (join-irreducible member) state in host() and attaches /// this to it. If xdof_map == 0 a new dof map is created. If xdof_map != 0 /// and xcopy_dof_map == false, xdof_map is used as the dof map. If /// xdof_map != 0 and xcopy_dof_map is true, a copy of xdof_map is used. /// virtual void new_jim_state(poset_dof_map* xdof_map = 0, bool xcopy_dof_map = false, bool xauto_access = true); /// /// Creates a new jim (join-irreducible member) state in xhost and attaches /// this to it. /// virtual void new_jim_state(poset_state_handle* xhost, poset_dof_map* xdof_map = 0, bool xcopy_dof_map = false, bool xauto_access = true); /// /// Creates a new jim state in xhost and attaches this to it. /// void new_jim_state(poset *xhost, const std::string& xdiscretization_subposet_name, const std::string& xmultivalued_subposet_name, const std::string& xevaluation_subposet_name, const std::string& xevaluation_method_name, const std::string& xurl, int xmultiplicity, bool xeval_is_above_disc, bool xauto_access); // DEGREE OF FREEDOM (DOF) TUPLE INTERFACE /// /// The map from client_ids to dof values for this poset member (mutable version) /// virtual array_poset_dof_map& dof_map(bool xrequire_write_access = false); /// /// The map from client_ids to dof values for this poset member (const version) /// virtual const array_poset_dof_map& dof_map(bool xrequire_write_access = false) const; /// /// True if xdof_map conforms to (i.e. is derived from) the type of /// dof map required by this member /// virtual bool dof_map_is_ancestor_of(const poset_dof_map* xdof_map) const; // SEC_REP_DESCRIPTOR FACET /// /// The name of the discretization subposet. /// std::string discretization_subposet_name() const; /// /// Sets the name of the discretization subposet to xname. /// void put_discretization_subposet_name(const std::string& xname); /// /// The name of the multivalued subposet. /// std::string multivalued_subposet_name() const; /// /// Sets the name of the multivalued subposet to xname. /// void put_multivalued_subposet_name(const std::string& xname); /// /// The name of the evaluation subposet. /// std::string evaluation_subposet_name() const; /// /// Sets the name of the evaluation subposet to xname. /// void put_evaluation_subposet_name(const std::string& xname); /// /// The name of the evaluator family. /// std::string evaluator_family_name() const; /// /// Sets the name of the evaluator family to xname. /// void put_evaluator_family_name(const std::string& xname); /// /// The url for a description of this representation /// std::string url() const; /// /// Sets the url for a description of this representation to xurl. /// void put_url(const std::string& xurl); /// /// The number of degrees of freedom associated with each /// (discretization member, fiber_schema member) pair. /// int multiplicity() const; /// /// Sets the number of degrees of freedom associated with each /// (discretization member, fiber_schema member) pair. /// void put_multiplicity(int xmultiplicity); /// /// True is the evaluation subposet is strictly above /// the discretization subposet. /// bool eval_is_above_disc() const; /// /// Sets eval_is_above_disc to xvalue. /// void put_eval_is_above_disc(bool xvalue); /// /// The family of evaluators for this rep. //// @hack return type any because can't return type eval_family //// until we've finished refactoring sheaves and fiber_bundles. //// Client should down cast to eval_family*. //// @todo convert to eval_family when refactoring complete. //// eval_family* evaluators() const; protected: /// /// Initializes handle data members when attaching /// to a different member of the same host. /// virtual void attach_handle_data_members(); private: /// /// Class represention of the row dofs /// class SHEAF_DLL_SPEC row_dof_tuple { public: /// /// The name of the discretization subposet /// char* discretization_subposet_name; /// /// The name of the multivalued subposet /// char* multivalued_subposet_name; /// /// The name of the evaluation subposet /// char* evaluation_subposet_name; /// /// The name of the evaluator family. /// char* evaluator_family_name; /// /// The url /// char* url; /// /// The multiplicity value /// int multiplicity; /// /// True if evaluation is above discretization. /// size_type eval_is_above_disc; /// /// Constructor /// row_dof_tuple(const std::string& xdiscretization_subposet_name, const std::string& xmultivalued_subposet_name, const std::string& xevaluation_subposet_name, const std::string& xevaluator_family_name, const std::string& xurl, int xmultiplicity, size_type xeval_is_above_disc); /// /// Duplicates xodf_value.str() and makes xdof point to the copy. /// static void copy_string_dof(char*& xdof, const std::string& xdof_value); }; /// /// Pointer to the storage for the row dofs (const version). /// inline const row_dof_tuple* row_dof_tuple_ptr() const { return reinterpret_cast<const row_dof_tuple*>(dof_map(false).dof_tuple()); }; /// /// Pointer to the storage for the row dofs (mutable version). /// inline row_dof_tuple* row_dof_tuple_ptr() { return reinterpret_cast<row_dof_tuple*>(dof_map(true).dof_tuple()); }; /// /// The family of evaluators for this rep. /// eval_family* _evaluators; //@} }; } // namespace fiber_bundle #endif // ifndef SEC_REP_DESCRIPTOR_H
6a4b7e3eb29b6653383c994066f5e671b014cd4b
8aab06394eb9b1d257df9ef6213a1e51423cdd2b
/common_defs.hpp
6a1670ee520205b2e8c5997e2c639763a6d17aec
[]
no_license
omer-g/comphw3
0117471a901aa4a013d62214b56652438712337a
ca697610821a7a74beab6ba1b19517bf6aea0b0d
refs/heads/master
2020-05-26T15:37:05.710004
2019-05-24T08:31:15
2019-05-24T08:31:15
188,289,500
0
0
null
null
null
null
UTF-8
C++
false
false
4,594
hpp
common_defs.hpp
#ifndef _COMMON_DEFS_H #define _COMMON_DEFS_H #include <string> //////////////////////////////////////////////////////////// ///////// Expression Types //////////// //////////////////////////////////////////////////////////// typedef enum { EXPRRESSION_TYPE_INT, EXPRRESSION_TYPE_BYTE, EXPRRESSION_TYPE_STRING, EXPRRESSION_TYPE_BOOL, EXPRRESSION_TYPE_INVALID // For error checks etc. } ExpressionType; //////////////////////////////////////////////////////////// ///////// Value type definitions //////////// //////////////////////////////////////////////////////////// #define YYSTYPE Node* #define YYLVAL_DEFAULT_VAL 0 #define YYLVAL_DEFAULT_TYPE int //////////////////////////////// /////// NON-TERMINALS ///// //////////////////////////////// typedef struct { std::string* id_string; } id_tt_st; typedef struct { int val; } num_tt_st; typedef struct { std::string* string; } string_tt_st; typedef struct { std::string* comment_string; } comments_tt_st; //////////////////////////// /////// TERMINALS ///// //////////////////////////// typedef struct { ExpressionType type; // Insert fields here } program_nt_st; typedef struct { ExpressionType type; // Insert fields here } funcs_nt_st; typedef struct { ExpressionType type; // Insert fields here } funcdecl_nt_st; typedef struct { ExpressionType type; // Insert fields here } rettype_nt_st; typedef struct { ExpressionType type; // Insert fields here } formals_nt_st; typedef struct { ExpressionType type; // Insert fields here } formalslist_nt_st; typedef struct { ExpressionType type; // Insert fields here } formalsdecl_nt_st; typedef struct { ExpressionType type; // Insert fields here } preconditions_nt_st; typedef struct { ExpressionType type; // Insert fields here } precondition_nt_st; typedef struct { ExpressionType type; // Insert fields here } statements_nt_st; typedef struct { ExpressionType type; // Insert fields here } statement_nt_st; typedef struct { ExpressionType type; // Insert fields here } nonifstatement_nt_st; typedef struct { ExpressionType type; // Insert fields here } binop_nt_st; typedef struct { ExpressionType type; // Insert fields here } relop_nt_st; typedef struct { ExpressionType type; // Insert fields here } ifstatement_nt_st; typedef struct { ExpressionType type; // Insert fields here } ifelsestatement_nt_st; typedef struct { ExpressionType type; // Insert fields here } call_nt_st; typedef struct { ExpressionType type; // Insert fields here } explist_nt_st; typedef struct { ExpressionType type; // Insert fields here } type_nt_st; typedef struct { ExpressionType type; // Insert fields here } exp_nt_st; typedef union { /* Default value */ YYLVAL_DEFAULT_TYPE default_value; /* NON-TERMINALS */ id_tt_st id_tt; num_tt_st num_tt; string_tt_st string_tt; comments_tt_st comments_tt; /* TERMINALS */ program_nt_st program_nt; funcs_nt_st funcs_nt; funcdecl_nt_st funcdecl_nt; rettype_nt_st rettype_nt; formals_nt_st formals_nt; formalslist_nt_st formalslist_nt; formalsdecl_nt_st formalsdecl_nt; preconditions_nt_st preconditions_nt; precondition_nt_st precondition_nt; statements_nt_st statements_nt; statement_nt_st statement_nt; nonifstatement_nt_st nonifstatement_nt; binop_nt_st binop_nt; relop_nt_st relop_nt; ifstatement_nt_st ifstatement_nt; ifelsestatement_nt_st ifelsestatement_nt; call_nt_st call_nt; explist_nt_st explist_nt; type_nt_st type_nt; exp_nt_st exp_nt; } STYPE; //////////////////////////////////////////////////////////// ///////// Debug macros //////////// //////////////////////////////////////////////////////////// /* Debug ENABLE/DISABLE */ #define DBUG_PRINT_FLEX 1 #define DBUG_PRINT_SEMANTIC 1 /* Debug prints macros */ #if (DBUG_PRINT_FLEX == 1) #define FLEX_DEBUG_PRINT(token_str) do {printf(token_str); printf("\n");} while(0); #else // DBUG_PRINT_FLEX #define FLEX_DEBUG_PRINT(token_str) #endif #if (DBUG_PRINT_SEMANTIC == 1) #define SEMANTIC_DEBUG_PRINT(token_str) do {printf(token_str); printf("\n");} while(0); #else // DBUG_PRINT_SEMANTIC #define SEMANTIC_DEBUG_PRINT(token_str) #endif #endif /* _COMMON_DEFS_H */
2ecc59eea9656cfedc7c3d5b227babaf342aac9b
5da872ee303e48da52fbf485723ac3a807a3a8fc
/milestone9_assembler/include/irtree/blocks/BlockTree.cpp
c72bcdfa8efe5f548fb031f7b862250aec219c04
[]
no_license
mikhailyumanov/compilers_course_4sem_2020
81ee4e5e6dd84bef2de7a124a19bbd7163ae36a9
465edad241b41aeb1fd400c915c3e97de78f5cd2
refs/heads/master
2023-04-22T11:02:05.148018
2021-05-05T20:29:41
2021-05-05T20:29:41
245,890,536
1
0
null
2021-05-05T20:30:47
2020-03-08T21:26:40
C++
UTF-8
C++
false
false
6,993
cpp
BlockTree.cpp
#include "irtree/blocks/BlockTree.hpp" #include <cassert> #include <stack> #include <unordered_map> #include <unordered_set> #include <queue> namespace IRT { BlockTree::BlockTree(std::shared_ptr<Statement> pre_root, bool is_main) : is_main_{is_main} { assert(pre_root != nullptr); CanonizeIrtree(pre_root); std::shared_ptr<SeqStatement> root; if (IRT::GetNodeType(pre_root) != NodeType::SeqStatement) { root = std::make_shared<SeqStatement>( std::make_shared<LabelStatement>(is_main ? GetMainLabel() : Label()), pre_root); } else { root = GetSeqStmt(pre_root); } //check if first stmt is Label if (NodeAdapter(root).GetType() != NodeType::LabelStatement) { root = std::make_shared<SeqStatement>( std::make_shared<LabelStatement>(is_main ? GetMainLabel() : Label()), root); } //close last block NodeAdapter it(root); for (; !it.IsFinal(); it = it.GetNext()); auto tmp = it.GetSeq()->rhs; it.GetSeq()->rhs = std::make_shared<SeqStatement>( tmp, std::make_shared<SeqStatement>( std::make_shared<JumpStatement>(GetDoneLabel()), std::make_shared<SeqStatement>( std::make_shared<LabelStatement>(GetDoneLabel()), std::make_shared<LabelStatement>(Label())))); //set jumps it = NodeAdapter(root); for (; !it.IsFinal(); it = it.GetNext()) { if (it.GetNext().IsLabelStmt() && !(it.IsJumpStmt() || it.IsCJumpStmt())) { SetJump(it.GetNextSeq(), it.GetNext().GetLabelStmt()->label); } } //irtree -> block tree // DEBUG root_ = std::make_shared<Block>(root, std::shared_ptr<SeqStatement>()); BuildBlocks(root); } std::vector<std::shared_ptr<Trace>> BlockTree::GetTraces() const { std::vector<std::shared_ptr<Trace>> traces; std::vector<std::shared_ptr<Block>> new_trace; DFS([&traces, &new_trace](std::shared_ptr<Block> it) { DEBUG_SINGLE(it->GetLabelName()) bool is_new_trace = true; if (!new_trace.empty()) { for (auto&& child : new_trace.back()->GetNext()) { if (child->GetLabelName() == it->GetLabelName()) { is_new_trace = false; } } } if (is_new_trace) { if (!new_trace.empty()) { traces.push_back(std::make_shared<Trace>(new_trace)); } new_trace = std::vector<std::shared_ptr<Block>>{it}; } else { new_trace.push_back(it); } }); traces.push_back(std::make_shared<Trace>(new_trace)); return traces; } void BlockTree::PrintTree(const std::string& filename) const { DEBUG_SINGLE("BlockTree::PrintTree") static auto print_visitor = std::make_shared<PrintVisitor>(filename); root_->GetLabelSeq()->Accept(print_visitor); Routine routine = [&filename](std::shared_ptr<Block> it) { static std::ofstream stream(filename + "_blocks"); // stream << "Current: " << it->GetLabelName() << std::endl; // stream << "Prev: " << std::endl << " > "; // for (auto&& prev : it->GetPrev()) { // stream << prev->GetLabelName() << ", "; // } // stream << std::endl << "Next: " << std::endl << " > "; for (auto&& next : it->GetNext()) { stream << it->GetLabelName() << " " << next->GetLabelName() << std::endl; } stream << std::endl << std::endl; }; BFS(routine); DEBUG_SINGLE("BFS finished") } void BlockTree::PrintJouette(const std::string& filename) const { DEBUG_SINGLE("BlockTree::PrintJouette") auto traces = GetTraces(); for (auto&& trace : GetTraces()) { for (auto&& block : trace->GetBlocks()) { block->PrintBlock(filename, is_main_); } } } std::shared_ptr<Jouette::PrintVisitor> BlockTree::GetPrinter( const std::string& filename) const { return Block().GetPrinter(filename); } void BlockTree::BFS(Routine routine) const { std::unordered_set<std::string> visited; std::queue<std::shared_ptr<Block>> nodes; nodes.push(root_); while (!nodes.empty()) { DEBUG_SINGLE("BFS") auto it = nodes.front(); visited.insert(it->GetLabelName()); routine(it); for (auto&& child : it->GetNext()) { if (visited.find(child->GetLabelName()) == visited.end()) { nodes.push(child); } } nodes.pop(); } } void BlockTree::DFS(Routine routine) const { std::unordered_set<std::string> visited; std::stack<std::vector<std::shared_ptr<Block>>> nodes; nodes.push({root_}); while (!nodes.empty()) { DEBUG_SINGLE("DFS") if (nodes.top().empty()) { nodes.pop(); continue; } auto it = nodes.top()[0]; nodes.top().erase(nodes.top().begin()); if (visited.find(it->GetLabelName()) != visited.end()) { continue; } visited.insert(it->GetLabelName()); nodes.push(it->GetNext()); routine(it); } } void BlockTree::CanonizeIrtree(std::shared_ptr<Statement>& root) const { root = std::make_shared<DoubleCallEliminationVisitor>()->Accept(root).stmt; root = std::make_shared<EseqEliminationVisitor>()->Accept(root).stmt; root = std::make_shared<LinearizeVisitor>()->Accept(root).stmt; } void BlockTree::BuildBlocks(std::shared_ptr<SeqStatement> root) { std::unordered_map<std::string, std::shared_ptr<Block>> block_mapping; // make blocks NodeAdapter it{root}; NodeAdapter current_label{root}; for (; !it.IsFinal(); it = it.GetNext()) { if (it.IsLabelStmt()) { current_label = it; } else if (it.IsJumpStmt() || it.IsCJumpStmt()) { block_mapping[current_label.GetLabelName()] = std::make_shared<Block>(current_label.GetSeq(), it.GetSeq()); } DEBUG_SINGLE(it.GetNext().IsFinal()) } // make 'done' block block_mapping[GetDoneLabel().ToString()] = std::make_shared<Block>( it.GetSeq(), // 'it' points to SeqStmt-parent of 'done' label now. std::make_shared<SeqStatement>( std::make_shared<JumpStatement>(Label()), std::make_shared<LabelStatement>(Label()))); // set root_ root_ = block_mapping[NodeAdapter(root).GetLabelName()]; // bind blocks together for (auto&& pair : block_mapping) { if (pair.first == GetDoneLabel().ToString()) { continue; } DEBUG_SINGLE("build blocks: " + pair.first) DEBUG_SINGLE("build blocks: " << (bool) pair.second) auto parent = pair.second; NodeAdapter jump{parent->GetJumpSeq()}; if (jump.IsJumpStmt()) { auto child = block_mapping[jump.GetJumpName()]; parent->AddNext(child); child->AddPrev(parent); } else if (jump.IsCJumpStmt()) { auto true_child = block_mapping[jump.GetCJumpTrueName()]; auto false_child = block_mapping[jump.GetCJumpFalseName()]; parent->AddNext(false_child); // false lable first parent->AddNext(true_child); true_child->AddPrev(parent); false_child->AddPrev(parent); } } } void BlockTree::SetJump(std::shared_ptr<SeqStatement> element, Label label) { auto tmp = element->lhs; element->lhs = std::make_shared<JumpStatement>(label); element->rhs = std::make_shared<SeqStatement>(tmp, element->rhs); } }
3c8b4db180a4ae3edd7c3821ed493e0b605b7487
670d387d3e8caff516a92d8749fc58a85b4eaf06
/nn.cpp
5ac9fde4840194aeda64ac5d3be1071c50a3676e
[ "CC0-1.0" ]
permissive
ervaibhavkumar/QtFeedForwardNN
2d398110d10ed21579b04401cb9f7379ca6f93dd
e4062b0023288cfa16208c45103feea160b51c25
refs/heads/master
2022-12-04T05:55:55.555878
2020-08-08T11:48:48
2020-08-08T11:48:48
284,751,439
0
0
null
null
null
null
UTF-8
C++
false
false
1,357
cpp
nn.cpp
#include "nn.h" #include <math.h> #include <QDebug> NN::NN(int units, double lr) : hiddenUnits(units), learningRate(lr) { weights.reserve(hiddenUnits); initWeights(); } void NN::initWeights() { for (auto i = 0;i < this->hiddenUnits; i++) weights.push_back(Utilities::getRandomNum(-1,1)); } int NN::activation(double input) { if (input > 0.0) return 1; else if(input < 0.0) return -1; else return 0; // return (1.0 / ( 1.0 + exp(-input))); } double NN::sigmoidDerivative(double output) { return (output * (1.0 - output)); } void NN::train(v_d input, double output) { int guess = feedForward(input); double error = (output - (double) guess); // error = error * error; // error *= sigmoidDerivative(error); backPropagation(error, input); } int NN::feedForward(v_d input) { Q_ASSERT(weights.size() == input.size()); double sum = 0.0; for (int i = 0; i < (int) weights.size(); i++) { sum += weights[i] * input[i]; } return activation(sum); } void NN::backPropagation(double error, v_d input) { Q_ASSERT(weights.size() == input.size()); for (int i = 0; i < (int) weights.size(); i++) { weights[i] += learningRate * error * input[i]; } } v_d NN::getWeights() { return weights; }
033cc4318a4cb30f28b3bbf6164cea01d5c3c667
a67abbe5a3b887013b92aa55061842020d4b2ebd
/最小的数.cpp
b1af263a0eb999b67455bb92b62350a55ff2301c
[]
no_license
chengyufan2020/chengyufan
0de54daf2f4f0c98820bb963bbb1230dec684666
e5a1bb72869d0d8a249e8bee4de98650969fffc1
refs/heads/main
2023-02-16T05:58:08.524663
2021-01-13T04:07:21
2021-01-13T04:07:21
307,612,129
0
0
null
null
null
null
UTF-8
C++
false
false
342
cpp
最小的数.cpp
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> int main(){ int i=0,a[11]={0}; for(i=0;i<10;i++){ scanf("%d",&a[i]); } for(i=1;i<10;i++){ if(a[i]!=0){ printf("%d",i); a[i]--; break; } } for(i=0;i<10;i++){ while(a[i]!=0){ printf("%d",i); a[i]--; } } printf("\n"); return 0; }
42f8274e6f8f5ef9f7d066344fc69465eae366a2
b8e100637666e8beca1fba49d2b0c5f15079b4fa
/C++11 Features/EnhancedFor/EnhancedFor.cpp
f00645cae59eac72a9f557229b3639ec32fafd6e
[]
no_license
tjwhalen16/udemy-cpp-course
c70184a4657fa283bcfb8efe729c10132038e460
20d3407ef8b49bcdeaa7dbf318594d7bb9be3e47
refs/heads/master
2021-01-12T10:46:42.269451
2016-11-19T04:25:56
2016-11-19T04:25:56
72,692,849
0
0
null
null
null
null
UTF-8
C++
false
false
325
cpp
EnhancedFor.cpp
// EnhancedFor.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <string> #include <iostream> int main() { auto texts = { "one", "two", "three" }; for (auto text : texts) { std::cout << text << '\n'; } for (auto c : "Hello") { std::cout << c << '\n'; } return 0; }
6811dfbf71f7a28f9d73f6fefa10044bd2d45ca8
bd0636c61421941ee9d44d3ded8941e94a1a9de8
/16.Robotarm/robotarm/robotarm.ino
145e3b4095f3eb379873e6b619efc5bbb0a95a6e
[]
no_license
BluBugTwob/BluBug
3a0305953747b73140b164996dc850ba92259c4e
9277fd3fa3087f0f76ea3303d8874285c981dd8c
refs/heads/master
2021-01-12T12:06:29.714143
2016-10-29T18:03:20
2016-10-29T18:03:20
72,300,848
0
0
null
null
null
null
UTF-8
C++
false
false
1,913
ino
robotarm.ino
/* Robotarm Control the robot using smart phone via bluetooth using android app BluBug have an on-board bluetooth you can control. check the documentation at http://www.twob.co.in Control four dc motor with this code. This example code is in the public domain. modified 25 August 2016 by Sathish kumar */ #include <robotarm.h> // blugbug library for robotarm Robotarm mybot; void setup() { Serial.begin(9600); // initilize the serial communication } void loop() { if(Serial.available()) // check for data is available from serial port { char botdata = (char) Serial.read(); // read the data from serial port and move data a character if(botdata=='a') { mybot.left(); // if received value 'a' move motor1 forward } else if(botdata=='b') { mybot.right(); // if received value 'e' move motor1 reverse } else if(botdata=='c') { mybot.forward(); // if received value 'l' move motor4 stop } else if(botdata=='d') { mybot.reverse(); // if received value 'l' move motor4 stop } else if(botdata=='g') { mybot.up(); // if received value 'l' move motor4 stop } else if(botdata=='h') { mybot.down(); // if received value 'l' move motor4 stop } else if(botdata=='e') { mybot.openarm(); // if received value 'l' move motor4 stop } else if(botdata=='f') { mybot.closearm(); // if received value 'l' move motor4 stop } else if(botdata=='s') { mybot.stopbot(); // if received value 'i' move motor1 stop } } }
3be9918058edb4b9c56a20fe6fe5c89daa223acc
6e131dda5d27f451f9a00e36c98155102f473725
/guiapplication.h
b1681ef19e08495512e544963f779834491cc013
[]
no_license
bobreg/asku-gui
ff200095dd21536aa03b8336974fdcfa632fd11c
31b68e8098b3f012520199cabbb9c0e15c76a890
refs/heads/master
2022-12-14T05:46:01.139220
2020-09-15T06:37:04
2020-09-15T06:37:04
295,638,345
0
0
null
null
null
null
UTF-8
C++
false
false
697
h
guiapplication.h
#ifndef __GUIAPPLICATION_H__ #define __GUIAPPLICATION_H__ #include "../common/application.h" #include "guimodule.h" //---------------------------------------------------------------------------------------------------------------- class AskuGuiApplication : public AskuApplication { Q_OBJECT AskuGuiModule *guiModule; qint32 m_gprOverride; private: virtual bool writeSettings(QSettings &m_settings); virtual bool readSettings (QSettings &m_settings); public: AskuGuiApplication(int & argc, char** argv); virtual ~AskuGuiApplication(); }; //---------------------------------------------------------------------------------------------------------------- #endif // __GUIAPPLICATION_H__
68820ca4de3fe06cada586be04b7e2787a3bcbed
a200380e9ffb8efa05d3d8bfdc26fd6ad5237396
/CPP/실습 예제/07. 복사 생성자.cpp
6b1ff73ac74f8fa220f98ebed57c9563855e7941
[]
no_license
tyrosine1153/Learn_in_school
acf81b84efc201c720b4b09f308e9b6bc4a940ac
9b4052b8543dd769c8835fcc7c96959c7f01db79
refs/heads/master
2023-08-14T00:11:05.462762
2021-09-27T11:48:51
2021-09-27T11:48:51
298,144,477
0
0
null
null
null
null
UHC
C++
false
false
1,242
cpp
07. 복사 생성자.cpp
#include<iostream> using namespace std; /* 객체의 복사본을 생성할때 호출되는 생성자. 클래스 작성 시 복사생성자를 생략하면 디폴트 생성자처럼 컴파일러가 알아서 만듬 클래스 내부에서 메모리를 동적할당 및 해제하고 멤버포인터변수로 관리하는 경우 복사생성자 적용하지 않으면 문제가 발생 복사생성자 형태 : 클래스이름(const 클래스이름 &rhs); */ class CMyData { public: CMyData() { cout << "CMyData()" << endl; } CMyData(const CMyData& rhs) // : m_nData(rhs.m_nData) { this->m_nData = rhs.m_nData; cout << "CMyData(const CMyData &)" << endl; } int GetData()const { return m_Data; } void SetData(int nParam) { m_nData = nParam; } private: int m_nData = 0; }; int main() { CMyData a; // 디폴트생성자 a.SetData(10); CMyData b(a); // 복사생성자 cout << b.GetData() << endl; return 0; } /* 복사생성자가 호출되는 경우 1. 명시적으로 객체의 복사본을 생성하는 방식으로 선언하는 경우 2. 함수형태로 호출되는 경우 함수형태로 호출할때(매개변수, 반환형식에서) 클래스가 사용되는 경우 */
63932fefe4cd4c4ab063f0602d2909d47284b40b
d3f7ddeed6e4c9dde3fe4ccaf84e1adb36bfa40e
/rng2.h
895279cac8354724560c119af86caf2c979fab07
[]
no_license
kjgilbert/ExpLoad
492ea234bd510846282ad34e9d3e21f09f17169b
242e5954e43fc2b3a3d5800673e05d0c83b5260e
refs/heads/master
2021-03-16T10:15:09.961166
2019-01-10T17:51:49
2019-01-10T17:51:49
88,489,302
2
0
null
null
null
null
UTF-8
C++
false
false
1,258
h
rng2.h
#ifndef __RNG2__ #define __RNG2__ #include <math.h> using namespace std; typedef double my_float; // A routine for generating good random numbers extern double ran3(long *idum); void initializeRan3(const long &lidum); extern double gammln(double xx); // A routine to generate poisson deviates with mean xm extern double poidev(double xm, long *idum); // randint(a, b) returns a uniformly distributed random integer on [a, b] extern int randint(const int & lower_bound, const int & upper_bound); // Returns a uniformly distributed random deviate. // randreal() is uniform on [0, 1[ extern double randreal(); // randreal(a, b) is uniform on [a, b[. extern double randreal(const double & lower_bound, const double & upper_bound); // Returns a random deviate from an exponential distribution with parameter lambda extern double randexp(const double & lambda); // Returns a random deviate from an exponential distribution with parameter lambda extern double randpois(const double & lambda); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #endif //__RNG2__
1a0e8d94d7180d23ea241ec9be9e808147410dcc
d83a1756e1a454d76ad4e33587c2727bea8a3a4e
/OpenGLCookBook/SimpleCamera/Camera.cpp
e09a917797ba49fc9da959344b6184ce47289e48
[]
no_license
ChenZS/Practice
ce6b1f2d4739ee9c30c1913b79ec6770731483d1
df27273fd496b3b33acd70f3bb8b47d9cbf58762
refs/heads/master
2021-04-22T13:40:11.384536
2015-05-11T06:52:03
2015-05-11T06:52:03
33,928,565
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
Camera.cpp
#include "Camera.h" #include <glm/gtx/euler_angles.hpp> glm::vec3 Camera::sUp = glm::vec3(0, 1, 0); Camera::Camera() : mLook(glm::vec3(0, 0, -1)), mUp(glm::vec3(0, 1, 0)), mRight(glm::vec3(1, 0, 0)) { } Camera::~Camera() { } void Camera::setupProjection(const float fovy, const float aspectRatio) { mP = glm::perspective(fovy, aspectRatio, 0.1f, 1000.0f); mFOV = fovy; mAspectRatio = aspectRatio; } glm::mat4 Camera::matrixRPY(const float yaw, const float pitch, const float roll) { return glm::yawPitchRoll(yaw, pitch, roll); }
14e5791bad4e73840c9dbfd34550572eba9e731e
d905bee59352351774443a8dcf07de42a8765808
/example/common/op_params.hpp
ad08fc5c0349b4c58f118eadc0f51b6132026611
[]
no_license
vsrad/libplugintercept
e3a6cc595bbbbf1944b4d2a7a833878d53066d4a
c9b44b38175a33b0d2bde8bdd6224bd72bf21bd0
refs/heads/master
2023-06-05T08:00:30.447405
2021-06-19T02:53:12
2021-06-19T02:53:12
226,483,331
3
0
null
2021-06-19T02:38:08
2019-12-07T09:02:29
C++
UTF-8
C++
false
false
3,060
hpp
op_params.hpp
#ifndef OP_PARAMS_HPP__ #define OP_PARAMS_HPP__ 1 #include <vector> #include <cstddef> #include <iostream> #include <iomanip> using std::cout; using std::istream; using std::ostream; using std::setw; using std::size_t; using std::string; using std::vector; string str2str(const char* s); float str2f(const char* s); bool str2b(const char* s); unsigned int str2u(const char* s); class CLIFlagBase { public: bool MatchArg(const char* name); const char* MatchMergedArg(const char* name); bool ProcessArg(const char* name, const char* val, bool* merged); virtual void SetVal(const char* val) = 0; virtual void PrintHelp() = 0; virtual ~CLIFlagBase(){}; protected: CLIFlagBase(const char* name1, const char* name2, const char* comment) : name1(name1), name2(name2), comment(comment), count(0) { } const char* name1; const char* name2; const char* comment; int count; }; template <class T> class CLIFlag : CLIFlagBase { public: CLIFlag(const char* name1, const char* name2, const char* comment, T* ptr, T default_val, const char* default_str, T (*str2val)(const char*)) : CLIFlagBase(name1, name2, comment), val_ptr(ptr), default_val(default_val), default_str(default_str), str2val(str2val) { *ptr = default_val; } virtual void PrintHelp() { cout << setw(5) << name1 << setw(12) << name2 << setw(10); default_str ? (cout << default_str) : (cout << default_val); cout << "\t" << comment << "\n"; } virtual void SetVal(const char* val) { *val_ptr = str2val(val); } virtual ~CLIFlag() {} private: T* val_ptr; T default_val; const char* default_str; T(*str2val) (const char*); // pointer to StringToValue converter }; class Options { public: Options(size_t estimated_sz); ~Options(); bool MatchArg(const char* name); bool ProcessArg(const char* name, const char* val, bool* merged); bool ParseHeader(const char* s); bool ProcessRow(const char* s); void ShowHelp(); template <class T> void Add(T* ptr, const char* name1, const char* name2, T default_val, const char* comment, T (*str2val)(const char*)) { auto p = new CLIFlag<T>(name1, name2, comment, ptr, default_val, nullptr, str2val); opts.push_back((CLIFlagBase*)p); } template <class T> void Add(T* ptr, const char* name1, const char* name2, const char* default_str, const char* comment, T (*str2val)(const char*)) { T default_val = default_str ? str2val(default_str) : T(); Add(ptr, name1, name2, default_val, comment, str2val); } private: CLIFlagBase* ArgPtr(const char* name); vector<CLIFlagBase*> opts; vector<CLIFlagBase*> idx; vector<char> str; }; #endif
184a28e5e502f55fb1d0c6d5f1cdb39f7b92dc67
f5c60aeb664b14ff0f9d279e123d658ae0678bcd
/src/common/net/NetCommon.h
7367f32db5af8f4fb7cd40ae4b63f918a5c7d124
[]
no_license
shen597996478/program
62037e52139cc8c376c0b55fa1005775dfd46720
5a8638e1d631d6889eed4ac81e92a75ca2cee62e
refs/heads/master
2020-03-28T19:52:01.754968
2018-09-19T15:18:44
2018-09-19T15:18:44
149,016,700
0
0
null
null
null
null
UTF-8
C++
false
false
647
h
NetCommon.h
#ifndef __NetCommon_H__ #define __NetCommon_H__ #include "./base/CCommon.h" #include "./base/CLog.h" #include "NetError.h" #include "NetDefine.h" class CLog; #define NET_LOGV(format, args...) CBase::CLog::V("net", format, args) #define NET_LOGD(format, args...) CBase::CLog::D("net", format, args) #define NET_LOGI(format, args...) CBase::CLog::I("net", format, args) #define NET_LOGW(format, args...) CBase::CLog::W("net", format, args) #define NET_LOGE(format, args...) CBase::CLog::E("net", format, args) #ifdef DEBUG #define __AUTO_NET_LOG__ NET_LOGD("%s:%s enter()",__FILE__, __func__); #else #define __AUTO_NET_LOG__ #endif #endif
d64a4d06f1dde72767a7f7320514c4fabeb01c45
a4a03d391f0c911e5b0aed27fe21e4eb36624609
/POJ/2778/19345764_WA_0ms_0kB.cpp
99a3d2f65b1e159bdc20ba05d208f097f8447532
[]
no_license
jiaaaaaaaqi/ACM_Code
5e689bed9261ba768cfbfa01b39bd8fb0992e560
66b222d15544f6477cd04190c0d7397f232ed15e
refs/heads/master
2020-05-21T21:38:57.727420
2019-12-11T14:30:52
2019-12-11T14:30:52
186,153,816
0
0
null
null
null
null
UTF-8
C++
false
false
3,883
cpp
19345764_WA_0ms_0kB.cpp
#include <map> #include <set> #include <list> #include <ctime> #include <cmath> #include <stack> #include <queue> #include <cfloat> #include <string> #include <vector> #include <cstdio> #include <bitset> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> #define lowbit(x) x & (-x) #define mes(a, b) memset(a, b, sizeof a) #define fi first #define se second #define pii pair<int, int> #define INOPEN freopen("in.txt", "r", stdin) #define OUTOPEN freopen("out.txt", "w", stdout) typedef unsigned long long int ull; typedef long long int ll; const int maxn = 1e5 + 10; const int maxm = 1e5 + 10; const ll mod = 100000; const ll INF = 1e18 + 100; const int inf = 0x3f3f3f3f; const double pi = acos(-1.0); const double eps = 1e-8; using namespace std; int n, m; int cas, tol, T; /*-------------------------------------------------------------*/ struct Mat { int sz; ll mat[110][110]; void init() { mes(mat, 0); } }; Mat mmul(Mat a, Mat b) { Mat ans; ans.init(); ans.sz = a.sz; for(int i=1; i<=a.sz; i++) { for(int j=1; j<=a.sz; j++) { for(int k=1; k<=a.sz; k++) { ans.mat[i][j] += a.mat[i][k]*b.mat[k][j]; } } } return ans; } Mat mpow(Mat a, ll b) { Mat ans; ans.init(); ans.sz = a.sz; for(int i=1; i<=ans.sz; i++) { ans.mat[i][i] = 1; } while(b) { if(b&1) ans = mmul(ans, a); a = mmul(a, a); b >>= 1; } return ans; } /*-------------------------------------------------------------*/ struct AC { struct Node { int next[5]; int fail, flag; void init() { mes(next, -1); fail = flag = 0; } } node[200]; int sz; void init() { sz = 0; node[0].init(); } int getid(char c) { if(c == 'A') return 1; if(c == 'T') return 2; if(c == 'C') return 3; if(c == 'G') return 4; } void insert(char *s) { int len = strlen(s+1); int rt = 0; for(int i=1; i<=len; i++) { int k = getid(s[i]); if(node[rt].next[k] == -1) { node[++sz].init(); node[rt].next[k] = sz; } rt = node[rt].next[k]; } node[rt].flag = true; } void build() { queue<int> q; while(!q.empty()) q.pop(); node[0].fail = -1; q.push(0); while(!q.empty()) { int u = q.front(); q.pop(); if(u && node[node[u].fail].flag) { node[u].flag = 1; } for(int i=1; i<=4; i++) { if(node[u].next[i] == -1) { if(u == 0) node[u].next[i] = 0; else node[u].next[i] = node[node[u].fail].next[i]; } else { int k = node[u].next[i]; if(u == 0) { node[k].fail = 0; } else { int v = node[u].fail; while(v != -1) { if(node[v].next[i] != -1) { node[k].fail = node[v].next[i]; break; } v = node[v].fail; } if(v == -1) { node[k].fail = 0; } } q.push(k); } } } } } ac; char s[15]; int main() { scanf("%d%d", &m, &n); ac.init(); for(int i=1; i<=m; i++) { scanf("%s", s+1); ac.insert(s); } ac.build(); Mat a; a.init(); a.sz = ac.sz+1; for(int i=0; i<=ac.sz; i++) { for(int j=1; j<=4; j++) { int k = ac.node[i].next[j]; if(!ac.node[k].flag) { a.mat[i+1][k+1]++; } } } a = mpow(a, n); ll ans = 0; for(int i=1; i<=a.sz; i++) { ans += a.mat[1][i]; ans %= mod; } printf("%lld\n", ans); return 0; }
d37f83f5946d06ed91e6e5e8f0fa010f3f2a037a
9a3f8c3d4afe784a34ada757b8c6cd939cac701d
/leetMyCalendarIII.cpp
9c34b1216354e84ba25a740ab2d749b97d18a197
[]
no_license
madhav-bits/Coding_Practice
62035a6828f47221b14b1d2a906feae35d3d81a8
f08d6403878ecafa83b3433dd7a917835b4f1e9e
refs/heads/master
2023-08-17T04:58:05.113256
2023-08-17T02:00:53
2023-08-17T02:00:53
106,217,648
1
1
null
null
null
null
UTF-8
C++
false
false
4,439
cpp
leetMyCalendarIII.cpp
/* * //**********************************************************732. My Calendar III.*************************************************** Implement a MyCalendarThree class to store your events. A new event can always be added. Your class will have one method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end. A K-booking happens when K events have some non-empty intersection (ie., there is some time that is common to all K events.) For each call to the method MyCalendar.book, return an integer K representing the largest integer such that there exists a K-booking in the calendar. Your class will be called like this: MyCalendarThree cal = new MyCalendarThree(); MyCalendarThree.book(start, end) Example 1: MyCalendarThree(); MyCalendarThree.book(10, 20); // returns 1 MyCalendarThree.book(50, 60); // returns 1 MyCalendarThree.book(10, 40); // returns 2 MyCalendarThree.book(5, 15); // returns 3 MyCalendarThree.book(5, 10); // returns 3 MyCalendarThree.book(25, 55); // returns 3 Explanation: The first two events can be booked and are disjoint, so the maximum K-booking is a 1-booking. The third event [10, 40) intersects the first event, and the maximum K-booking is a 2-booking. The remaining events cause the maximum K-booking to be only a 3-booking. Note that the last event locally causes a 2-booking, but the answer is still 3 because eg. [10, 20), [10, 40), and [5, 15) are still triple booked. Note: The number of calls to MyCalendarThree.book per test case will be at most 400. In calls to MyCalendarThree.book(start, end), start and end are integers in the range [0, 10^9]. *******************************************************************TEST CASES:************************************************************ //These are the examples I had created, tweaked and worked on. ["MyCalendarThree","book","book","book","book","book","book"] [[],[10,20],[50,60],[10,40],[5,15],[5,10],[25,55]] ["MyCalendarThree","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book","book"] [[],[47,50],[1,10],[27,36],[40,47],[20,27],[15,23],[10,18],[27,36],[17,25],[8,17],[24,33],[23,28],[21,27],[47,50],[14,21],[26,32],[16,21],[2,7],[24,33],[6,13],[44,50],[33,39],[30,36],[6,15],[21,27],[49,50],[38,45],[4,12],[46,50],[13,21]] // Time Complexity: O(n). // Space Complexity: O(n). //********************************************************THIS IS LEET ACCEPTED CODE.*************************************************** */ //************************************************************Solution 1:************************************************************ //*****************************************************THIS IS LEET ACCEPTED CODE.*********************************************** // Time Complexity: O(n). // Space Complexity: O(n). // This algorithm is Segment Tree based, but more easily done through HashMap. We store the edges of intervals in the map, where start of // the interval is indicated by inc. the value for that key by 1.End of interval by dec. the value for that key by 1. For every insert the // interval, we then count of number of active intervals for all the edges stored in map. We track the max #active intervals and return the // max. num. class MyCalendarThree { public: map<int,int>m; // Tracks the edges of the intervals. MyCalendarThree() { } int book(int start, int end) { int res=0; // Tracks the max #active intervals. m[start]++; // Inc. the #active intervals by one. m[end]--; //Dec. the #active intervals by one. int count=0; // Tracks #active intervals at any instant. for(auto it: m){ count+=it.second; // Sums the rep.(#active interval) of curr. edge of interval. res=max(res,count); // Extracting max. #active interval. // if(it.second==end) break; } return res; // Returning the max. #active intervals. } }; /** * Your MyCalendarThree object will be instantiated and called as such: * MyCalendarThree obj = new MyCalendarThree(); * int param_1 = obj.book(start,end); */
91c8a03a36aafdb54620f49d35c4aa670d387f64
8c205ce137dfe056ae78db81c07271503f57db80
/IaEnemigoCarlos/JefeFinal.cpp
62665fce568a8cee8e9ba8ac21c6b081d15e5efd
[]
no_license
ismap1993/BitCrushers
75bc043e5bd28ba07617a8ac7233a0b050e40ad8
4893f1a1fc6b25f529a02b83d93bb69c9ba9905c
refs/heads/master
2021-01-21T13:57:17.075625
2016-05-11T18:27:05
2016-05-11T18:27:05
51,336,398
0
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
JefeFinal.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: JefeFinal.cpp * Author: chiri * * Created on 20 de abril de 2016, 3:33 */ #include "JefeFinal.h" JefeFinal::JefeFinal() { } JefeFinal::JefeFinal(const JefeFinal& orig) { } JefeFinal::~JefeFinal() { }
945192a1f9a95c0355323d4422885decf2e10e54
0da1b49f788f5f3c3b1f75bccd8565360f9154a9
/uri/matematica/p1240.cpp
72dba5b5f6ba3e6f0c54278acffdba7f90d966b4
[ "MIT" ]
permissive
jvrmaia/coding4fun
ea5ff54dbda713dc0deaef158863a55850352882
3e4ab5c50e055d7c41436f87ffc8493de8bb2b15
refs/heads/main
2023-03-16T05:02:59.509191
2021-02-27T19:28:20
2021-02-27T19:28:20
45,149,618
3
2
null
null
null
null
UTF-8
C++
false
false
723
cpp
p1240.cpp
#include <cstdio> #include <cstring> #include <cstdlib> using namespace std; int pot10(int x) { int i = 1, ret = 1; for (int i = 0; i < x; i++) ret *= 10; return ret; } int main() { int n; long long int a, b; scanf ("%d ", &n); for (int i = 0; i < n; i++) { scanf ("%lld %lld ", &a, &b); if (b > a) printf ("nao encaixa\n"); else if (a == b) printf ("encaixa\n"); else { char n[100]; sprintf (n, "%lld", b); a = a % pot10(strlen(n)); if (a - b == 0) printf ("encaixa\n"); else printf ("nao encaixa\n"); } } return 0; }
99d980419bb73cb9a1426e85f29e9b6d0d8d4224
9c82584f3489d0402a8404765281cabb66834aa2
/MyFimora/myfimoraprivate.h
381de88715c416590579108bf2b0301b46761d8d
[]
no_license
LuckyKingSSS/LuckKing
c8ed189d376326fd5d86418d53af7d0621eb77d8
19495d50fac1fc44879d34ba5b4df779d47f2a4b
refs/heads/master
2021-01-25T09:26:56.121973
2017-06-08T08:51:15
2017-06-08T08:51:30
93,839,764
0
0
null
null
null
null
UTF-8
C++
false
false
863
h
myfimoraprivate.h
#ifndef MYFIMORAPRIVATE_H #define MYFIMORAPRIVATE_H #include <QWidget> class ResourceView; class MeidaPlayerView; class TimeLineView; class ToolBarView; class IMediaPlayerControl; class MyFimoraPrivate : public QWidget { Q_OBJECT public: MyFimoraPrivate(QWidget *parent); ~MyFimoraPrivate(); void initUI(); void resizeEvent(QResizeEvent *event); IMediaPlayerControl* GetPlayerControler(); void refreshUI(); public Q_SLOTS: void slotChangeLanguage(); protected: void initConnections(); void LoadTimeline(); public: ResourceView* resView; MeidaPlayerView* playerView; ToolBarView* toolbarView; TimeLineView* timelineView; Q_SIGNALS: void sign(); void sigalDurationChanged(int iNewValue); void signalChangeLanguge(); private: QHBoxLayout* hLayout; QVBoxLayout* vLayout; }; #endif // MYFIMORAPRIVATE_H
5b3e1015c06b0a032c43261724f66df078caa72b
9a879c0669bc70facf5dc2fadaca2eff54bb8a53
/alljoyn/services/controlpanel/cpp/src/BusObjects/NotificationActionBusObject.h
5c681a375dc72d979e2f3c8a854621123ff45706
[ "ISC" ]
permissive
octoblu/alljoyn
d86c4d2bb60f989f52f3a3f9a0ce8d11ef5cd3f9
a74003fa25af1d0790468bf781a4d49347ec05c4
refs/heads/master
2021-01-21T12:47:18.034834
2016-03-15T16:23:31
2016-03-15T16:23:31
21,958,119
37
29
null
2016-03-15T16:12:35
2014-07-17T21:24:28
C++
UTF-8
C++
false
false
4,807
h
NotificationActionBusObject.h
/****************************************************************************** * Copyright AllSeen Alliance. All rights reserved. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************************/ #ifndef NOTIFICATIONACTIONBUSOBJECT_H_ #define NOTIFICATIONACTIONBUSOBJECT_H_ #include <alljoyn/BusAttachment.h> #include <alljoyn/BusObject.h> #include <alljoyn/InterfaceDescription.h> #include <alljoyn/controlpanel/NotificationAction.h> #include <vector> #include "IntrospectionNode.h" namespace ajn { namespace services { /** * NotificationActionBusObject class. BusObject for a NotificationAction */ class NotificationActionBusObject : public BusObject { public: /** * Constructor for NotificationActionBusObject * @param bus - bus used to create the interface * @param objectPath - objectPath of BusObject * @param status - success/failure */ NotificationActionBusObject(BusAttachment* bus, qcc::String const& objectPath, QStatus& status, NotificationAction* notificationAction = 0); /** * Destructor of NotificationActionBusObject class */ virtual ~NotificationActionBusObject(); /** * Callback for Alljoyn when GetProperty is called on this BusObject * @param interfaceName - the name of the Interface * @param propName - the name of the Property * @param val - the MsgArg to fill * @return status - success/failure */ QStatus Get(const char* interfaceName, const char* propName, MsgArg& val); /** * Callback for Alljoyn when SetProperty is called on this BusObject * @param interfaceName - the name of the Interface * @param propName - the name of the Property * @param val - the MsgArg that contains the new Value * @return status - success/failure */ QStatus Set(const char* ifcName, const char* propName, MsgArg& val); /** * Send a Dismiss Signal for This Notification Action * @return */ QStatus SendDismissSignal(); /** * Callback for DismissSignal signal * @param member - signal received * @param srcPath - objectPath of signal * @param msg - Message received */ void DismissSignal(const InterfaceDescription::Member* member, const char* srcPath, Message& msg); /** * Set RemoteController * @param bus - busAttachment * @param deviceBusName * @param sessionId * @return */ QStatus setRemoteController(BusAttachment* bus, qcc::String const& deviceBusName, SessionId sessionId); /** * Check compatibility of the versions * @return status - success/failure */ QStatus checkVersions(); /** * Introspect to receive childNodes * @param childNodes - childNodes found during introspection * @return status - success/failure */ QStatus Introspect(std::vector<IntrospectionNode>& childNodes); /** * @internal Explicitly provide implementation for virtual method. */ void Introspect(const InterfaceDescription::Member* member, Message& msg) { BusObject::Introspect(member, msg); } /** * remove the SignalHandler of the BusObject * @param bus - busAttachment used to remove the signalHandlers * @return status - success/failure */ virtual QStatus UnregisterSignalHandler(BusAttachment* bus); private: /** * The pointer used to send signal/register Signal Handler */ const ajn::InterfaceDescription::Member* m_SignalDismiss; /** * The NotificationAction of this BusObject */ NotificationAction* m_NotificationAction; /** * Pointer to ProxybusObject for this widget */ ProxyBusObject* m_Proxy; /** * ObjectPath of the BusObject */ qcc::String m_ObjectPath; /** * InterfaceDescription of the BusObject */ InterfaceDescription* m_InterfaceDescription; }; } /* namespace services */ } /* namespace ajn */ #endif /* NOTIFICATIONACTIONBUSOBJECT_H_ */
ba83cc22a8e99d148934c236dfb9557804196e51
c81e86d864623bb17afa24bad086f8ab91d8b112
/src/editor/editor_icon.h
ec1f0579ef01cba3bcee655f1464b460991d47e5
[ "MIT" ]
permissive
galek/LumixEngine
6e92f67d0f8fefc8c1eba35f26af1c15be7df2c9
d7d1738f7fc2bc7f6cf08d1217330a591b370ed9
refs/heads/master
2020-04-07T08:21:55.985858
2015-08-24T19:07:59
2015-08-24T19:07:59
41,364,902
8
0
null
2015-08-25T13:28:53
2015-08-25T13:28:52
null
UTF-8
C++
false
false
822
h
editor_icon.h
#pragma once #include "core/matrix.h" #include "universe/universe.h" namespace Lumix { class Engine; class Model; class PipelineInstance; class RenderScene; class WorldEditor; class EditorIcon { public: enum Type { PHYSICAL_CONTROLLER, PHYSICAL_BOX, CAMERA, LIGHT, TERRAIN, ENTITY, COUNT }; public: EditorIcon(WorldEditor& editor, RenderScene& scene, Entity entity); ~EditorIcon(); void render(PipelineInstance& pipeline); void show(); void hide(); float hit(const Vec3& origin, const Vec3& dir) const; Entity getEntity() const { return m_entity; } static bool loadIcons(Engine& engine); static void unloadIcons(); private: RenderScene* m_scene; Entity m_entity; Model* m_model; Matrix m_matrix; float m_scale; bool m_is_visible; Type m_type; }; }
38af964cd1320b7e81a3cf780ca659e0190e2ee5
b55942768e2608516931cb56471fb5434f582941
/INFO450SaveMore/BankAccount.cpp
85a3b0889d026c0979fd5a4e4a83ca9ccd3f4d87
[]
no_license
hicksmk2/INFO450SaveMore
2bc6aad21542003601fb51bee68950f06c855aa4
ffcec4fc186784f72e7569e1e2faff47d5c7ed89
refs/heads/master
2020-03-15T08:56:43.316943
2018-05-07T02:18:18
2018-05-07T02:18:18
132,063,142
1
0
null
null
null
null
UTF-8
C++
false
false
1,160
cpp
BankAccount.cpp
#include "stdafx.h" #include "BankAccount.h" BankAccount::BankAccount(int acctNumber, double acctBalance) { //Declare variables accountNumber = acctNumber; accountBalance = acctBalance; } int BankAccount::withdrawFunds(double withdrawAmount) { //Checks for a negative balance, if negative then it returns false if ((accountBalance - withdrawAmount) < 0) { return -1; } else if ((accountBalance - withdrawAmount) > 0) { accountBalance -= withdrawAmount; return 0; } } int BankAccount::depositFunds(double depositAmount) //Function used to deposit funds for each class { if (depositAmount >= 0) { accountBalance += depositAmount; return 0; } else if (depositAmount < 0) { return -1; } } int BankAccount::orderChecks() //Only applies to the Checking Account { return 0; } void BankAccount::assessInterest() //Only applies to the Savings and CD Account { } void BankAccount::displayAccountInfo() //Serves as the basic display for each account { cout << "Account Number: " << accountNumber << endl; cout << "Account Balance: " << accountBalance << endl; cout << "Interest Rate: " << interestRate << endl; }
b0eb53fefd6e0a0bcf7f37c9d433600e421c4079
1a9bb62b32771102c0b32ffefe305ca702bea268
/tide/wall/qml/TextureNodeYUV.cpp
bd6b9cbbcff1d60615a935100873ceb3d4bbbe44
[ "BSD-2-Clause" ]
permissive
BlueBrain/Tide
9fa3a5b802026f204491eb625653d6e431c2bea8
e35a8952b3c8ea86db098602f2d95fb4ba542dae
refs/heads/master
2022-05-07T01:14:44.308665
2022-04-27T13:47:18
2022-04-27T13:47:18
54,562,203
52
21
BSD-2-Clause
2022-04-27T13:47:19
2016-03-23T13:33:25
C++
UTF-8
C++
false
false
12,152
cpp
TextureNodeYUV.cpp
/*********************************************************************/ /* Copyright (c) 2017, EPFL/Blue Brain Project */ /* Raphael Dumusc <raphael.dumusc@epfl.ch> */ /* 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 THE ECOLE POLYTECHNIQUE */ /* FEDERALE DE LAUSANNE ''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 ECOLE */ /* POLYTECHNIQUE FEDERALE DE LAUSANNE 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. */ /* */ /* The views and conclusions contained in the software and */ /* documentation are those of the authors and should not be */ /* interpreted as representing official policies, either expressed */ /* or implied, of Ecole polytechnique federale de Lausanne. */ /*********************************************************************/ #include "TextureNodeYUV.h" #include "data/Image.h" #include "textureUtils.h" #include "utils/yuv.h" #include <QOpenGLBuffer> #include <QOpenGLContext> #include <QOpenGLFunctions> #include <QQuickWindow> #include <QSGSimpleMaterialShader> #include <QSGTexture> namespace { const char* vertShader = R"( #version 120 uniform highp mat4 qt_Matrix; attribute highp vec4 aVertex; attribute highp vec2 aTexCoord; varying vec2 vTexCoord; void main() { gl_Position = qt_Matrix * aVertex; vTexCoord = aTexCoord; } )"; const char* fragShader = R"( #version 120 uniform lowp float qt_Opacity; uniform lowp sampler2D y_tex; uniform lowp sampler2D u_tex; uniform lowp sampler2D v_tex; uniform lowp int color_space; uniform float tex_offset_x; uniform float tex_offset_y; uniform float tex_scale_x; uniform float tex_scale_y; uniform lowp bool reverse_orientation; varying vec2 vTexCoord; // https://en.wikipedia.org/wiki/YCbCr JPEG conversion const vec3 R_cf_jpeg = vec3(1.0, 0.0, 1.402); const vec3 offset_jpeg = vec3(0.0, -0.5, -0.5); const vec3 G_cf_jpeg = vec3(1.0, -0.344136, -0.714136); const vec3 B_cf_jpeg = vec3(1.0, 1.772, 0.0); // https://en.wikipedia.org/wiki/YCbCr ITU-R BT.601 conversion const vec3 offset_video = vec3(-0.0625, -0.5, -0.5); const vec3 R_cf_video = vec3(1.164383, 0.000000, 1.596027); const vec3 G_cf_video = vec3(1.164383, -0.391762, -0.812968); const vec3 B_cf_video = vec3(1.164383, 2.017232, 0.000000); void main() { vec2 texCoord = vTexCoord; if(reverse_orientation) texCoord.y = 1.0 - texCoord.y; texCoord.x = (texCoord.x - tex_offset_x) * tex_scale_x; texCoord.y = (texCoord.y - tex_offset_y) * tex_scale_y; float y = texture2D(y_tex, texCoord).r; float u = texture2D(u_tex, texCoord).r; float v = texture2D(v_tex, texCoord).r; vec3 yuv = vec3(y, u, v); if (color_space == 1) { yuv += offset_jpeg; float r = dot(yuv, R_cf_jpeg); float g = dot(yuv, G_cf_jpeg); float b = dot(yuv, B_cf_jpeg); gl_FragColor = vec4(r, g, b, qt_Opacity); } else if (color_space == 2) { yuv += offset_video; float r = dot(yuv, R_cf_video); float g = dot(yuv, G_cf_video); float b = dot(yuv, B_cf_video); gl_FragColor = vec4(r, g, b, qt_Opacity); } else { gl_FragColor = vec4(0, 0.0, 1.0, qt_Opacity); } } )"; } // namespace /** * The state of the QSGSimpleMaterialShader. */ struct YUVState { std::unique_ptr<QSGTexture> textureY; std::unique_ptr<QSGTexture> textureU; std::unique_ptr<QSGTexture> textureV; TextureFormat textureFormat; bool reverseOrientation = false; ColorSpace colorSpace = ColorSpace::undefined; std::unique_ptr<QOpenGLBuffer> pboY; std::unique_ptr<QOpenGLBuffer> pboU; std::unique_ptr<QOpenGLBuffer> pboV; float texOffsetX = 0.f; float texOffsetY = 0.f; float texScaleX = 1.f; float texScaleY = 1.f; }; /** * Material to render a YUV texture with OpenGL in a QSGNode. */ class YUVShader : public QSGSimpleMaterialShader<YUVState> { QSG_DECLARE_SIMPLE_SHADER(YUVShader, YUVState) public: QList<QByteArray> attributes() const final { return QList<QByteArray>() << "aVertex" << "aTexCoord"; } const char* vertexShader() const final { return vertShader; } const char* fragmentShader() const final { return fragShader; } void updateState(const YUVState* newState, const YUVState*) final { auto gl = QOpenGLContext::currentContext()->functions(); // We bind the textures in inverse order so that we leave the // updateState function with GL_TEXTURE0 as the active texture unit. // This is maintain the "contract" that updateState should not mess up // the GL state beyond what is needed for this material. gl->glActiveTexture(GL_TEXTURE2); newState->textureV->bind(); gl->glActiveTexture(GL_TEXTURE1); newState->textureU->bind(); gl->glActiveTexture(GL_TEXTURE0); newState->textureY->bind(); program()->setUniformValue("tex_offset_x", newState->texOffsetX); program()->setUniformValue("tex_offset_y", newState->texOffsetY); program()->setUniformValue("tex_scale_x", newState->texScaleX); program()->setUniformValue("tex_scale_y", newState->texScaleY); program()->setUniformValue("color_space", (int)newState->colorSpace); program()->setUniformValue("reverse_orientation", (int)newState->reverseOrientation); } void resolveUniforms() final { program()->setUniformValue("y_tex", 0); // GL_TEXTURE0 program()->setUniformValue("u_tex", 1); // GL_TEXTURE1 program()->setUniformValue("v_tex", 2); // GL_TEXTURE2 } }; YUVState* _getMaterialState(QSGGeometryNode& node) { using YUVShaderMaterial = QSGSimpleMaterial<YUVState>; return static_cast<YUVShaderMaterial*>(node.material())->state(); } const YUVState* _getMaterialState(const QSGGeometryNode& node) { using YUVShaderMaterial = QSGSimpleMaterial<YUVState>; return static_cast<const YUVShaderMaterial*>(node.material())->state(); } TextureNodeYUV::TextureNodeYUV(QQuickWindow& window, const bool dynamic) : _window(window) , _dynamicTexture(dynamic) { // Set up geometry, actual vertices will be initialized in updatePaintNode const auto& attr = QSGGeometry::defaultAttributes_TexturedPoint2D(); _node.setGeometry(new QSGGeometry(attr, 4)); _node.setFlag(QSGNode::OwnsGeometry); _node.setMaterial(YUVShader::createMaterial()); _node.setFlag(QSGNode::OwnsMaterial); auto state = _getMaterialState(_node); state->textureY.reset(_window.createTextureFromId(0, QSize(1, 1))); state->textureU.reset(_window.createTextureFromId(0, QSize(1, 1))); state->textureV.reset(_window.createTextureFromId(0, QSize(1, 1))); appendChildNode(&_node); } QRectF TextureNodeYUV::getCoord() const { return _rect; } void TextureNodeYUV::setCoord(const QRectF& rect) { if (_rect == rect) return; _rect = rect; QSGGeometry::updateTexturedRectGeometry(_node.geometry(), _rect, UNIT_RECTF); _node.markDirty(QSGNode::DirtyGeometry); } void TextureNodeYUV::uploadTexture(const Image& image) { if (!image.getTextureSize().isValid()) throw std::runtime_error("image texture has invalid size"); if (image.getGLPixelFormat() != GL_RED) throw std::runtime_error("TextureNodeYUV image format must be GL_RED"); auto state = _getMaterialState(_node); if (!state->pboY) _createPbos(); _uploadToPbos(image); _nextTextureSize = image.getTextureSize(); _nextFormat = image.getFormat(); { // Calculate viewport clipping const auto viewPort = image.getViewPort(); const double imageWidth = image.getWidth(); const double imageHeight = image.getHeight(); state->texOffsetX = viewPort.x() / imageWidth; state->texOffsetY = viewPort.y() / imageHeight; state->texScaleX = viewPort.width() / imageWidth; state->texScaleY = viewPort.height() / imageHeight; } state->reverseOrientation = image.getRowOrder() == deflect::RowOrder::bottom_up; state->colorSpace = image.getColorSpace(); } void TextureNodeYUV::swap() { if (_needTextureChange()) _createTextures(_nextTextureSize, _nextFormat); _copyPbosToTextures(); markDirty(DirtyMaterial); if (!_dynamicTexture) _deletePbos(); } bool TextureNodeYUV::_needTextureChange() const { auto state = _getMaterialState(_node); return state->textureY->textureSize() != _nextTextureSize || state->textureFormat != _nextFormat; } void TextureNodeYUV::_createTextures(const QSize& size, const TextureFormat format) { auto state = _getMaterialState(_node); const auto uvSize = yuv::getUVSize(size, format); state->textureY = _createTexture(size); state->textureU = _createTexture(uvSize); state->textureV = _createTexture(uvSize); state->textureFormat = format; } std::unique_ptr<QSGTexture> TextureNodeYUV::_createTexture( const QSize& size) const { auto texture = textureUtils::createTexture(size, _window); texture->setFiltering(QSGTexture::Linear); texture->setMipmapFiltering(QSGTexture::Linear); return texture; } void TextureNodeYUV::_createPbos() { auto state = _getMaterialState(_node); state->pboY = textureUtils::createPbo(_dynamicTexture); state->pboU = textureUtils::createPbo(_dynamicTexture); state->pboV = textureUtils::createPbo(_dynamicTexture); } void TextureNodeYUV::_deletePbos() { auto state = _getMaterialState(_node); state->pboY.reset(); state->pboU.reset(); state->pboV.reset(); } void TextureNodeYUV::_uploadToPbos(const Image& image) { auto state = _getMaterialState(_node); textureUtils::upload(image, 0, *state->pboY); textureUtils::upload(image, 1, *state->pboU); textureUtils::upload(image, 2, *state->pboV); } void TextureNodeYUV::_copyPbosToTextures() { auto state = _getMaterialState(_node); textureUtils::copy(*state->pboY, *state->textureY, GL_RED); textureUtils::copy(*state->pboU, *state->textureU, GL_RED); textureUtils::copy(*state->pboV, *state->textureV, GL_RED); }
e609946ff59ba9c49c580a701392b2453cd0ab47
b932134deff2e82f984c267c26b47ce74c521ef5
/leetcode/1306. Jump Game III.cpp
214c121061e5dad5adbb524ed39b7ef154f58009
[ "MIT" ]
permissive
chamow97/Interview-Prep
db234e0df0bfa6b3358d73ac187d6a132fa14595
9ce13afef6090b1604f72bf5f80a6e1df65be24f
refs/heads/master
2022-11-06T07:06:54.705258
2020-06-21T07:29:14
2020-06-21T07:29:14
112,472,858
1
0
null
null
null
null
UTF-8
C++
false
false
834
cpp
1306. Jump Game III.cpp
class Solution { public: bool solve(int i, vector<int> &dp, vector<int> &arr, vector<bool> &visited) { if(i < 0 || i >= arr.size()) { return false; } if(visited[i]) { return false; } if(dp[i] != -1) { return dp[i]; } visited[i] = true; bool currVal = solve(i - arr[i], dp, arr, visited) || solve(i + arr[i], dp, arr, visited); visited[i] = false; dp[i] = currVal; return dp[i]; } bool canReach(vector<int>& arr, int start) { int n = arr.size(); vector<int> dp(n, -1); vector<bool> visited(n, false); for(int i = 0; i < n; i++) { if(arr[i] == 0) { dp[i] = 1; } } return solve(start, dp, arr, visited); } };
6f763ccc1f3a3897b224d4da3a2efb903177e475
9b62cb953b73a4488eb6d93dcf7a8296823ce29e
/main.cpp
2dd95d21381bb49949d30402699affb7a83b374f
[]
no_license
ivan-didyk/cpp-game
646a6e0e82c41d99a79c4112f216cdb2e589d136
457fc6fac5bfa3fc285dae96c5b0da0c9a65df32
refs/heads/master
2023-02-28T04:23:12.084213
2021-02-04T07:55:49
2021-02-04T07:55:49
328,356,980
0
0
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
main.cpp
#include "./lib/object.cpp" #include "scenes.hpp" #include <unistd.h> #include <clocale> #include <ncurses.h> int main() { try { setlocale(LC_ALL, "en_US.UTF-8"); initscr(); use_default_colors(); noecho(); keypad(stdscr, true); start_color(); init_pair(0, COLOR_BLACK, -1); init_pair(1, COLOR_RED, -1); init_pair(2, COLOR_GREEN, -1); init_pair(3, COLOR_YELLOW, -1); init_pair(4, COLOR_BLUE, -1); init_pair(5, COLOR_MAGENTA, -1); init_pair(6, COLOR_CYAN, -1); init_pair(7, COLOR_WHITE, -1); nodelay(stdscr, TRUE); MEVENT nullEvt; mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, NULL); //erase(); Game manager; int ch; MEVENT evt; curs_set(0); while (!manager.shouldExit) { manager.pressed.clear(); manager.mouseEvent.bstate = 0; manager.mouseEvent.x = -1; manager.mouseEvent.y = -1; while((ch = getch()) != ERR) if(ch == KEY_MOUSE) { if(getmouse(&evt) == OK) { manager.mouseEvent = evt; } } else manager.pressed.insert(ch); manager.update(); erase(); manager.draw(); refresh(); flushinp(); usleep(10000); } erase(); curs_set(1); endwin(); } catch(const char* e) { endwin(); printf("[ERR] %s\n", e); } catch(...) { endwin(); printf("[ERR] Unknown\n"); } return 0; }
90cf0c572ee9114573e5e1492824ade1752879da
9410768ce24e7b907ca7b537d50d7bbf6ea9d882
/Regicide/Scenes/IntroScene.cpp
cee79dfaf9049644ea6bee872c6c8aa89c301ab7
[]
no_license
zbomb/RegicideClient
659a93ef32800d4ba9e3978e86f95e40948aaaee
33f5f24b2bea5c704f033d2d727bf1d673f1d1f5
refs/heads/master
2021-11-22T21:40:50.766420
2018-12-21T17:56:50
2018-12-21T17:56:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,693
cpp
IntroScene.cpp
// // IntroScene.cpp // Regicide Mobile // // Created: 10/9/18 // Updated: 11/20/18 // // © 2018 Zachary Berry, All Rights Reserved // #include "IntroScene.hpp" #include "SimpleAudioEngine.h" using namespace cocos2d; using namespace cocos2d::ui; Scene* IntroScene::createScene() { auto ret = IntroScene::create(); ret->setName( "IntroScene" ); return ret; } bool IntroScene::init() { // Initialize parent class if( !Scene::init() ) { return false; } auto sceneOrigin = Director::getInstance()->getVisibleOrigin(); auto sceneSize = Director::getInstance()->getVisibleSize(); int HeaderFontSize = ( sceneSize.width / 1920.f ) * 100.f; cocos2d::Vector< Node* > Items; auto IntroImage = Sprite::create( "LaunchScreenBackground2.png" ); IntroImage->setPosition( Vec2( sceneOrigin.x + sceneSize.width / 2.f, sceneOrigin.y + sceneSize.height / 2.f ) ); IntroImage->setContentSize( sceneSize ); this->addChild( IntroImage ); /* // Create Intro Text auto IntroText = Label::createWithTTF( "Regicide", "fonts/Ringbearer Medium.ttf", HeaderFontSize ); if( IntroText ) { IntroText->setAnchorPoint( Vec2( 0.5f, 0.5f ) ); IntroText->setTextColor( Color4B( 240, 240, 240, 255 ) ); IntroText->setPosition( Vec2( sceneOrigin.x + sceneSize.width / 2.f, sceneOrigin.y + sceneSize .height / 2.f + HeaderFontSize * 0.75 ) ); Items.pushBack( IntroText ); } else { log( "[UI ERROR] Failed to create intro text!" ); }*/ auto VersionText = Label::createWithTTF( "v 0.0.1a", "fonts/arial.ttf", HeaderFontSize * 0.22f ); if( VersionText ) { VersionText->setAnchorPoint( Vec2( 1.f, 0.f ) ); VersionText->setTextColor( Color4B( 240, 240, 240, 255 ) ); VersionText->setPosition( Vec2( sceneOrigin.x + sceneSize.width, sceneOrigin.y ) ); Items.pushBack( VersionText ); } else { log( "[UI ERROR] Failed to create version text" ); } /* auto WebsiteText = Label::createWithTTF( "Visit www.RegicideMobile.com", "fonts/arial.ttf", HeaderFontSize * 0.3f ); if( WebsiteText ) { WebsiteText->setAnchorPoint( Vec2( 0.5f, 0.5f ) ); WebsiteText->setTextColor( Color4B( 240, 240, 240, 255 ) ); WebsiteText->setPosition( Vec2( sceneOrigin.x + sceneSize.width / 2.f, sceneOrigin.y + sceneSize.height / 2.f - HeaderFontSize * 0.25f ) ); Items.pushBack( WebsiteText ); } else { log( "[UI ERROR] Failed to create website text" ); } */ // Run the fade in animation auto IntroAnimation = FadeIn::create( 2.f ); for( Node* ValidNode : Items ) { if( ValidNode ) { ValidNode->runAction( IntroAnimation ); this->addChild( ValidNode, 3 ); } } return true; }
12713698363d913b27b52d695e9d9e5d9adc4c63
23148187fbcda3dc6ec4883cc960a1c3d00f5844
/pre_epi_seizures/Preprocessing/Filtering/UNSW_QRSD/minmaxfilter.cpp
1844801ce2a535f1c1e4039e91d0a6376dc4b9ea
[ "BSD-3-Clause" ]
permissive
yinxiaojing1/pre_epi_seizures
c1944dbd5bda82c820bccab874b67a0d4efcff31
e4e83e10256a4ef402061ca8bcbc3331fd8fc431
refs/heads/master
2020-03-17T17:31:19.224073
2018-05-16T16:47:13
2018-05-16T16:47:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,317
cpp
minmaxfilter.cpp
// // minmaxfilter.cpp // Sortfilt // // Created by Robert Weiss on 19/06/13. // Copyright (c) 2013 Robert Weiss. All rights reserved. // #include <algorithm> #include <deque> #include <float.h> #include <iostream> #include <vector> #include "minmaxfilter.h" #include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *inMatrix; int n, N; int rows, cols; bool max; inMatrix = mxGetPr(prhs[0]); n = mxGetScalar(prhs[1]); N = mxGetNumberOfElements(prhs[0]); max = mxGetScalar(prhs[2]) == 1; rows = (int) mxGetM(prhs[0]); cols = (int) mxGetN(prhs[0]); plhs[0] = mxCreateDoubleMatrix(rows, cols, mxREAL); minmaxfilter(mxGetPr(plhs[0]), inMatrix, n, N, max); } void minmaxfilter(double *result, double *x, int n, int N, bool max) { if (max) maxfilter(result, x, n, N); else minfilter(result, x, n, N); } void printDeque(std::deque<double> *D) { std::cout << "Deque: "; for (int i = 0; i < D->size(); i++) { std::cout << D->at(i) << " "; } std::cout << std::endl; } void minfilter(double *result, double* x, int n, int N) { int N1, N2, A, B, last_B, index; if (n % 2 == 0) { N1 = (n/2) - 1; N2 = (n/2); } else { N1 = (n-1) / 2; N2 = (n-1) / 2; } last_B = 0; index = -1; for (int i = 0; i < N; i++) { A = std::max(0, i-N1); B = std::min(N-1, i+N2); if (index < A) { double MIN = x[A]; for (int j = A; j <= B; j++) if (x[j] <= MIN) { MIN = x[j]; index = j; } } if (last_B != B) if (x[B] <= x[index]) index = B; result[i] = x[index]; last_B = B; } } void maxfilter(double *result, double* x, int n, int N) { int N1, N2, A, B, last_B, index; if (n % 2 == 0) { N1 = (n/2) - 1; N2 = (n/2); } else { N1 = (n-1) / 2; N2 = (n-1) / 2; } last_B = 0; index = -1; for (int i = 0; i < N; i++) { A = std::max(0, i-N1); B = std::min(N-1, i+N2); if (index < A) { double MAX = x[A]; for (int j = A; j <= B; j++) if (x[j] >= MAX) { MAX = x[j]; index = j; } } if (last_B != B) if (x[B] >= x[index]) index = B; result[i] = x[index]; last_B = B; } }
bc7cc8892355e85a1882349065af8c725f4eb3fa
6fcf29488b90e7d6887b8fcb115a1a372232ad8a
/Sort/main.cpp
309630c57e4ddac3ecefeb3085e769081a54d4ea
[]
no_license
renshengqiang/Algorithm
6a1e4f113db5f3c6a3be2b5be2d81597c13cdcb0
c6c62b7583aa55205b7e95937cc881657c7e3d2f
refs/heads/master
2021-01-01T06:26:44.569174
2013-08-05T04:41:07
2013-08-05T04:41:07
8,687,742
3
0
null
null
null
null
UTF-8
C++
false
false
644
cpp
main.cpp
#include "sort.h" #include <string> #include <iostream> using namespace std; int main() { string strVec[]={"File", "Edit", "View", "Project", "Build", "Debug", "Team", "SQL", "Tool"}; int intVec[]={45, 23, 98, 28, 198, 67, 128,187, 1}; QuickSort<string>(strVec, 0, 8); // TwoWayMergeSort<int>(intVec, 0, sizeof(intVec)/sizeof(int)-1); HeapSort<int>(intVec, sizeof(intVec)/sizeof(int)); for(int i=0; i<9; ++i) cout << strVec[i] << " "; cout << endl; for(int i=0;i<sizeof(intVec)/sizeof(int); ++i){ cout << intVec[i] << " "; } cout << endl; #ifdef WIN32 getchar(); getchar(); #endif return 0; }
476c3dba42df33c4fb3416fc338f5f9e8d739809
763c48e7a3f5fa2273d6c05104cf8c316fb52284
/Mapa1.h
3ff0a644365a909d56805e68ffb347a969feb567
[]
no_license
ziombelas/jaszczurki
400bca79ee9653780ee5b3a131fe68e7cce3f395
c3a4bf12aa6ba6e2eae3cdb2ea5971c29fdccb2a
refs/heads/master
2021-01-19T04:19:50.277566
2017-03-06T17:38:12
2017-03-09T10:37:12
84,430,321
0
0
null
null
null
null
UTF-8
C++
false
false
176
h
Mapa1.h
/* * Pierwotna, podstawowa mapka. */ #ifndef MAPA1_H_ #define MAPA1_H_ #include "Mapa.h" class Mapa1: public Mapa { public: Mapa1(); ~Mapa1(); }; #endif /* MAPA1_H_ */
a0095b017674b654c218fdadd3cc7ef884390798
3055574eab5cdbb52e5c0ff89c07bf539bf7bef5
/clam/CLAM/examples/TickExtractor/RD_AutoCorrelationTD.cxx
705e1429b883ed0e60d2ff281bba11e566c153d8
[]
no_license
royedwards/3rdPartyAudio
e2c46e97e49561d95dc726b0cb7433fcf7097c51
e24250bd2b7167b68d51dcc1e0b914217262b998
refs/heads/master
2020-03-23T16:56:06.816045
2018-08-25T03:11:13
2018-08-25T03:11:13
141,834,203
1
1
null
null
null
null
UTF-8
C++
false
false
3,714
cxx
RD_AutoCorrelationTD.cxx
/* * Author: fabien gouyon * http://www.iua.upf.es/~fgouyon * Description: * * Syntax: C++ * * Copyright (c) 2001-2004 MUSIC TECHNOLOGY GROUP (MTG) * UNIVERSITAT POMPEU FABRA * * * 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 * */ #include "RD_AutoCorrelationTD.hxx" #include <CLAM/CLAM_Math.hxx> #include <numeric> #include <iostream> namespace CLAM { namespace RhythmDescription { void AutoCorrelationTDConfig::DefaultInit() { AddAll(); // All Attributes are added UpdateData(); //default values SetUpperLimit(10); SetAutomaticIntegTime(true); SetIntegrationTime(10); } AutoCorrelationTD::AutoCorrelationTD() { } AutoCorrelationTD::~AutoCorrelationTD() { } const char* AutoCorrelationTD::GetClassName() const { return "AutoCorrelationTD"; } const ProcessingConfig& AutoCorrelationTD::GetConfig() const { return mConfig; } // Configure the Processing Object according to the Config object bool AutoCorrelationTD::ConcreteConfigure(const ProcessingConfig& c) { CopyAsConcreteConfig( mConfig, c ); return true; } bool AutoCorrelationTD::Do(void) { CLAM_ASSERT( false, "AutoCorrelationTD::Do(): Supervised mode not implemented" ); return false; } bool AutoCorrelationTD::Do(Array<TData>& sequence, Array<TData>& acf) { int ul = mConfig.GetUpperLimit(); int it = mConfig.GetIntegrationTime(); int maxIt = sequence.Size()-ul; if (it>=maxIt) it = maxIt; if (mConfig.GetAutomaticIntegTime()) { it = maxIt; } if(maxIt<=1) { // the sequence is too short, ACF upper limit and integration time are being changed it = 2; ul = sequence.Size()-it; // final estimate may be unreliable. } Array<TData> x, y; TData* ptr = sequence.GetPtr(); //build x x.SetPtr(ptr,it); /* TData normX=0.0; for(int i=0;i<x.Size();i++) normX += x[i]*x[i]; normX = sqrt(normX); */ TData normX = sqrt( std::inner_product( x.GetPtr(), x.GetPtr()+it, x.GetPtr(), 0.0 ) ); //acf computation TData tmpCoef; TData normY; for(int m=0;m<maxIt;m++) { tmpCoef = 0.0; //build y y.SetPtr(ptr,it); /* normY=0.0; for(int i=0;i<y.Size();i++) normY += y[i]*y[i]; normY = sqrt(normY); */ normY = sqrt( std::inner_product( y.GetPtr(), y.GetPtr()+it, y.GetPtr(), 0.0 ) ); /* for(int k=0;k<y.Size();k++) tmpCoef += x[k]*y[k]; */ tmpCoef = std::inner_product( x.GetPtr(), x.GetPtr()+it, y.GetPtr(), 0.0 ); tmpCoef /= normX*normY; acf.AddElem(tmpCoef); ptr++; } /* --MATLAB code-- for featInd=1:size(A,2) for m=1:upperLimit x = []; y = []; aux = []; x = A(1:integTime+1,featInd); y = A(m:m+integTime,featInd); aux = x'*y/(norm(x)*norm(y)); atc(featInd,m) = aux; end; end; */ return true; } } } // namespace CLAM
6390444f477dcabf5e070255999bceccce1820c5
97325828fc083c0cf8bd63b84945d1d1a3000baa
/Bus to Udayland.cpp
aef1cc69a7fe7d1362af063b36683ba7f6ed6962
[]
no_license
1804054Miraz/Codeforces-solutions
bca7454602ecaf075e81f48dce9c044af3c2ba07
465f6ad205bf24e8e80b2a65f5b26b500591c0c1
refs/heads/main
2023-07-16T20:59:58.145519
2021-08-20T12:05:29
2021-08-20T12:05:29
312,970,662
1
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
Bus to Udayland.cpp
#include<iostream> #include<cstdio> #include<vector> using namespace std; int main(){ int n; cin>>n; getchar(); string st; int found = 0; vector<string>vec; for(int i=0;i<n;i++){ getline(cin,st); for(int i=0;i<st.size();i++){ if(found == 0 ){ if(st[i]=='O' && st[i+1]=='O' && i<5){ cout<<"YES"<<endl;; st[i]='+'; st[i+1]='+'; found = 1; } } } vec.push_back(st); } if(found == 0){ cout<<"NO"<<endl; } else{ auto it = vec.begin(); while(!vec.empty()){ cout<<*it<<endl; vec.pop_back(); it++; } } }
b17ce4397f34009ecdd133eb417d1c474cd2bda1
68bad99f88ce5b5b0733dee1734b64aed0ba3c7b
/Builds/AndroidStudio/app/src/main/jni/JuceModules/juce_core/native/juce_android_SystemStats.cpp
077fe5418cf372b180a24365b4fde8d41fc515da
[]
no_license
umnum/TestProject5
f3839322765571ffb53f50de3d6a91720eb1d974
84fe90638e1f7f3bcb22bd5c824de02854b1ea52
refs/heads/master
2020-12-24T06:33:36.486843
2016-06-05T20:55:11
2016-06-05T20:55:11
60,480,826
0
0
null
null
null
null
UTF-8
C++
false
false
79
cpp
juce_android_SystemStats.cpp
/home/umnum/Programs/juce/modules/juce_core/native/juce_android_SystemStats.cpp
f4d7526e4160572c24d8f85b9059870e6106e41c
82d84fd8dabaa4dac70cee100189b2834e7390ee
/面试基础/关于动态规划/添加回文串/test.cpp
4e119479bbdba69e088f466b5a23bb6403cd673b
[]
no_license
XHXaiXXR/code
da061cd1873ef3371b501b5d55ef02b78b5f7e50
37d01b255cd45a731d7ff88eb0fdfc9e8df5d5ee
refs/heads/master
2020-04-12T03:55:33.634090
2017-09-11T06:40:26
2017-09-11T06:40:26
61,038,026
0
0
null
null
null
null
UTF-8
C++
false
false
652
cpp
test.cpp
class Palindrome { private: bool _Equal(string str){ string strtmp = str; reverse(str.begin(), str.end()); if(str == strtmp){ return true; } return false; } public: string addToPalindrome(string A, int n) { // write code here string addstr; reverse(A.begin(), A.end()); while(!A.empty()){ addstr.push_back(A.back()); A.pop_back(); if(_Equal(A)){ break; } } reverse(addstr.begin(), addstr.end()); return addstr; } };
2b3019945a7bd67fe02b85b5d17b708a328e7997
166c8ff2490832030936e216b48aa0074b308783
/zawodnik-terminarz.cpp
e45cb00c872010a764e351c2dfb99f88380f5824
[]
no_license
MBurzynski/badminton-league
a0042de932c6ef12920bd4eda2e9697086bffe8f
bbe7a9941fe4458d6869b37b65124b72f6df40a8
refs/heads/master
2021-01-25T09:04:30.069120
2017-06-08T18:23:41
2017-06-08T18:23:41
93,779,593
0
0
null
null
null
null
UTF-8
C++
false
false
3,848
cpp
zawodnik-terminarz.cpp
#include "zawodnik-terminarz.h" #include "ui_zawodnik-terminarz.h" #include "QtDebug" ZawodnikTerminarz::ZawodnikTerminarz(QWidget *parent) : QWidget(parent), ui(new Ui::ZawodnikTerminarz) { ui->setupUi(this); qmodel=new QSqlQueryModel(this); ui->tableView->setModel(qmodel); refreshModel(); } ZawodnikTerminarz::~ZawodnikTerminarz() { delete qmodel; delete ui; delete zawodnik; } void ZawodnikTerminarz::refreshModel(Zawodnik *zawodnik) { this->zawodnik = zawodnik; if(zawodnik!=NULL) { QSqlDatabase db = QSqlDatabase::database(); if(db.isOpen()) { zapytanie = "SELECT kolejka.Data_rozegrania AS 'Termin meczu',mecz.Godzina AS 'Godzina',kolejka.numer AS 'Numer kolejki', mecz.numer_kortu AS 'Numer kortu', Concat(uzytkownik.Imie,' ', uzytkownik.Nazwisko) AS 'Przeciwnik' FROM kolejka JOIN mecz USING(IDKolejka) JOIN uzytkownik ON (uzytkownik.IDUzytkownik = mecz.IDZawodnikA1 OR uzytkownik.IDUzytkownik = mecz.IDZawodnikA2) WHERE kolejka.status = 0 AND (mecz.IDZawodnikB1 = "+QString::number(zawodnik->getIDZawodnik())+ " OR mecz.IDZawodnikB2 = "+QString::number(zawodnik->getIDZawodnik())+")" + "UNION " + "SELECT kolejka.Data_rozegrania AS 'Termin meczu',mecz.Godzina AS 'Godzina',kolejka.numer AS 'Numer kolejki', mecz.numer_kortu AS 'Numer kortu', Concat(uzytkownik.Imie,' ', uzytkownik.Nazwisko) AS 'Przeciwnik' FROM kolejka JOIN mecz USING(IDKolejka) JOIN uzytkownik ON (uzytkownik.IDUzytkownik = mecz.IDZawodnikB1 OR uzytkownik.IDUzytkownik = mecz.IDZawodnikB2) WHERE kolejka.status = 0 AND (mecz.IDZawodnikA1 = " +QString::number(zawodnik->getIDZawodnik())+ " OR mecz.IDZawodnikA2 = "+QString::number(zawodnik->getIDZawodnik())+")"; qmodel->setQuery(zapytanie);// najbliższe mecze tego zawodnika, czy tak naprawde mecze z jego udziałem w najbliższej kolejce } else qDebug() <<"Nie udało się odświeżyć listy usług. Brak połączenia z bazą!"; } } //Wyszukiwanie void ZawodnikTerminarz::on_lineEdit_textChanged(const QString &arg1) { QString filter = ui->lineEdit->text(); zapytanie = "SELECT kolejka.Data_rozegrania AS 'Termin meczu',mecz.Godzina AS 'Godzina',kolejka.numer AS 'Numer kolejki', mecz.numer_kortu AS 'Numer kortu', Concat(uzytkownik.Imie,' ', uzytkownik.Nazwisko) AS 'Przeciwnik' FROM kolejka JOIN mecz USING(IDKolejka) JOIN uzytkownik ON (uzytkownik.IDUzytkownik = mecz.IDZawodnikA1 OR uzytkownik.IDUzytkownik = mecz.IDZawodnikA2) WHERE kolejka.status = 0 AND (mecz.IDZawodnikB1 = "+QString::number(zawodnik->getIDZawodnik())+ " OR mecz.IDZawodnikB2 = "+QString::number(zawodnik->getIDZawodnik())+") AND ((kolejka.Data_rozegrania LIKE '" + filter+"%') OR (mecz.Godzina LIKE '" + filter+"%') OR (kolejka.numer LIKE '" + filter+"%') OR (mecz.numer_kortu LIKE '" + filter+"%') OR (uzytkownik.Imie LIKE '" + filter+"%') OR (uzytkownik.Nazwisko LIKE '" + filter+"%') )" + " UNION " + " SELECT kolejka.Data_rozegrania AS 'Termin meczu',mecz.Godzina AS 'Godzina',kolejka.numer AS 'Numer kolejki', mecz.numer_kortu AS 'Numer kortu', Concat(uzytkownik.Imie,' ', uzytkownik.Nazwisko) AS 'Przeciwnik' FROM kolejka JOIN mecz USING(IDKolejka) JOIN uzytkownik ON (uzytkownik.IDUzytkownik = mecz.IDZawodnikB1 OR uzytkownik.IDUzytkownik = mecz.IDZawodnikB2) WHERE kolejka.status = 0 AND (mecz.IDZawodnikA1 = " +QString::number(zawodnik->getIDZawodnik())+ " OR mecz.IDZawodnikA2 = "+QString::number(zawodnik->getIDZawodnik())+")AND ((kolejka.Data_rozegrania LIKE '" + filter+"%') OR (mecz.Godzina LIKE '" + filter+"%') OR (kolejka.numer LIKE '" + filter+"%') OR (mecz.numer_kortu LIKE '" + filter+"%') OR (uzytkownik.Imie LIKE '" + filter+"%') OR (uzytkownik.Nazwisko LIKE '" + filter+"%') )"; qmodel->setQuery(zapytanie); }
23389e87f9193c196443bcb92ad2c06a87095967
776f5892f1395bb8d30731a60466e4c756a44c8c
/contests/abc294/abc294_a/main.cc
7f2bc2b6446dd1e4a07ac12ad333c6275819354c
[]
no_license
kkishi/atcoder
fae494af4b47a9f39f05e7536e93d5c4dd21555b
f21d22095699dbf064c0d084a5ce5a09a252dc6b
refs/heads/master
2023-08-31T18:37:13.293499
2023-08-27T21:33:43
2023-08-27T21:33:43
264,760,383
0
0
null
2023-03-10T05:24:07
2020-05-17T21:30:14
C++
UTF-8
C++
false
false
156
cc
main.cc
#include <bits/stdc++.h> #include "atcoder.h" void Main() { ints(n); V<int> ans; rep(n) { ints(a); if (even(a)) ans.eb(a); } wt(ans); }
910932b748acd4db8eba724ff28cafbdda6c3601
e37f0ef98552770d6d60f82c589911d85dcc19e9
/Codeforces/290349.C.cpp
45c4726cc3f3a0adb2b8ae11ee30fb46f44f28a3
[]
no_license
anand873/CP_Codes
00c9948810a84d8c9085684f31b75246b1f4ea2c
ec7cd07141512646d96cd247c190924ae9a7e263
refs/heads/master
2021-09-09T20:58:51.713079
2021-08-30T08:15:13
2021-08-30T08:15:13
204,478,713
3
1
null
null
null
null
UTF-8
C++
false
false
3,205
cpp
290349.C.cpp
//Author: AnandRaj doubleux #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> pii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<pii> vpii; typedef pair<ll,ll> pll; typedef vector<ll> vl; typedef vector<vl> vvl; typedef vector<pll> vpll; #define fastio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define test() int t;cin>>t;while(t--) #define all(v) v.begin(),v.end() #define prinp(p) cout<<p.first<<" "<<p.second<<endl #define prinv(V) for(auto v:V) cout<<v<<" ";cout<<endl #define take(V,f,n) for(int in=f;in<f+n;in++) cin>>V[in] #define what(x) cerr<<#x<<" = "<<x<<endl #define KStest() int t,t1;cin>>t;t1=t;while(t--) #define KScout cout<<"Case #"<<t1-t<<": " mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); const int MOD = 1e9+7,MAX = 1e6+5; const ll INF = 1e18+5; vector<int> sort_cyclic_shifts(string const& s) { int n = s.size(); const int alphabet = 256; vector<int> p(n), c(n), cnt(max(alphabet, n), 0); for (int i = 0; i < n; i++) cnt[s[i]]++; for (int i = 1; i < alphabet; i++) cnt[i] += cnt[i-1]; for (int i = 0; i < n; i++) p[--cnt[s[i]]] = i; c[p[0]] = 0; int classes = 1; for (int i = 1; i < n; i++) { if (s[p[i]] != s[p[i-1]]) classes++; c[p[i]] = classes - 1; } vector<int> pn(n), cn(n); for (int h = 0; (1ll << h) < n; ++h) { for (int i = 0; i < n; i++) { pn[i] = p[i] - (1 << h); if (pn[i] < 0) pn[i] += n; } fill(cnt.begin(), cnt.begin() + classes, 0); for (int i = 0; i < n; i++) cnt[c[pn[i]]]++; for (int i = 1; i < classes; i++) cnt[i] += cnt[i-1]; for (int i = n-1; i >= 0; i--) p[--cnt[c[pn[i]]]] = pn[i]; cn[p[0]] = 0; classes = 1; for (int i = 1; i < n; i++) { pair<int, int> cur = {c[p[i]], c[(p[i] + (1 << h)) % n]}; pair<int, int> prev = {c[p[i-1]], c[(p[i-1] + (1 << h)) % n]}; if (cur != prev) ++classes; cn[p[i]] = classes - 1; } c.swap(cn); } return p; } vector<int> lcp_construction(string const& s, vector<int> const& p) { int n = s.size(); vector<int> rank(n, 0); for (int i = 0; i < n; i++) rank[p[i]] = i; int k = 0; vector<int> lcp(n-1, 0); for (int i = 0; i < n; i++) { if (rank[i] == n - 1) { k = 0; continue; } int j = p[rank[i] + 1]; while (i + k < n && j + k < n && s[i+k] == s[j+k]) k++; lcp[rank[i]] = k; if (k) k--; } return lcp; } int main() { fastio string s; cin>>s; vi p = sort_cyclic_shifts(s); vi lcp = lcp_construction(s,p); ll ans = 0; ll n = s.size(); for(int i=0;i<n-1;i++) { ans += lcp[i]; } for(int i=0;i<n;i++) ans += p[i]; cout<< (ll)n*(n-1)/2 - ans <<endl; }
6f55cc5e38694cc65b4b9784a00c609c95425e17
076885ff2864b4443203f45e40cd58e3acfb0dde
/src/ofApp.cpp
ed643d455755a00ad8dd6e22df4cac39be3c2a80
[]
no_license
tam-ng0905/CV-OpenFramework
85657ad43200c90f71ccddd57f80cc0582e7651e
23800b592227d4dd3b7f9ccbde56d1efff93c442
refs/heads/master
2022-12-01T03:25:57.488454
2020-02-29T17:29:58
2020-02-29T17:29:58
288,385,245
0
0
null
null
null
null
UTF-8
C++
false
false
6,463
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetDataPathRoot(ofFile("model/")); grabber.setup(1280,768); light.setup(); // Setup tracker light.setup(); siri.setSpeaker("Samantha"); siri.setSinger("Bad News"); siri.setContent("You just smiled. You look pretty handsome "); // Setup gui gui.setup(); gui.add(dotSize.setup("Dot Size", 10, 0, 20)); gui.add(blackWhite.setup("Black and White", false)); //this makes sure that the back of the model doesn't show through the front model.setPosition(ofGetWidth()*.5, ofGetHeight() * 0.75, 0); // Setup face tracker tracker.setup(); // Initialize the color for the overplay circles color = ofColor(36,13,255,50); time = 0; } //-------------------------------------------------------------- void ofApp::update(){ grabber.update(); // Update tracker when there are new frames if(grabber.isFrameNew()){ tracker.update(grabber); } //gets landmarks from all the faces for(auto face : tracker.getInstances()){ ofxFaceTracker2Landmarks markers = face.getLandmarks(); int distFaceWide =(int) ofDist(markers.getImagePoint(42).x, markers.getImagePoint(42).y, markers.getImagePoint(47).x, markers.getImagePoint(47).y); //int dist =(int) ofDist(markers.getImagePoint(63).x, markers.getImagePoint(63).y, markers.getImagePoint(67).x, markers.getImagePoint(67).y); int distMouth =(int) ofDist(markers.getImagePoint(49).x, markers.getImagePoint(49).y, markers.getImagePoint(55).x, markers.getImagePoint(55).y); //Calculate the distance for the sides of the eyes //int distEye =(int) ofDist(markers.getImagePoint(38).x, markers.getImagePoint(38).y, markers.getImagePoint(42).x, markers.getImagePoint(42).y); if(distMouth >= (0.95 * distFaceWide) && (time % 240 == 0)){ cout <<"You are smiling"; cout << " "; siri.speak(); siri.sing(); //count += 1; smilePoint = ofPoint(markers.getImagePoint(67).x, markers.getImagePoint(67).y); smile = !smile; color = ofColor(232,12,147,10); } time ++; } //Detect if the screen is all black so that can reset it for (int i = 0; i < grabber.getWidth(); i+= 16) { for (int j = 0; j < grabber.getHeight(); j+= 16) { ofColor color1 = grabber.getPixels().getColor(i, j) + color; float bright = grabber.getPixels().getColor(i, j).getBrightness(); if(bright < 20){ brightnessCount ++; if(brightnessCount < (ofGetWidth()*ofGetHeight())){ smile = false; } } } } } //-------------------------------------------------------------- void ofApp::draw(){ //drawWithMesh(); tracker.drawDebug(); float myTime = ofGetSystemTimeMillis(); //draw the grids of colored circled that overlay the image for (int i = 0; i < grabber.getWidth(); i+= 16) { for (int j = 0; j < grabber.getHeight(); j+= 16) { ofColor color1 = grabber.getPixels().getColor(i, j) + color; if(blackWhite){ ofColor colorBW = ofColor(0,0,0,20); ofSetColor(colorBW); } else{ ofSetColor(color1); } float myNoise = 60.0 * ofSignedNoise(glm::vec2(i/400.0, myTime/8000.0)); float brightness = color.getBrightness(); float radius = ofMap(brightness, 0, 255, 0, 8); float light = grabber.getPixels().getColor(i, j).getLightness(); if(light > 200){ ofDrawSphere(i*myNoise, j*myNoise, 100*myNoise, radius + dotSize); } if(smile){ ofTranslate(smilePoint.x, smilePoint.y); ofDrawCircle(i, j, radius + dotSize); } else { ofDrawCircle(i, j, radius + dotSize); } } } tracker.drawDebug(); gui.draw(); } //-------------------------------------------------------------- //The code below is a test method used to apply the 3d object onto the screen /*void ofApp::drawWithMesh(){ //get the model attributes we need for(auto face : tracker.getInstances()){ ofxFaceTracker2Landmarks markers = face.getLandmarks(); glm::vec3 scale = model.getScale(); glm::vec3 position = model.getPosition(); float normalizedScale = model.getNormalizedScale(); ofVboMesh mesh = model.getMesh(0); ofTexture texture; ofxAssimpMeshHelper& meshHelper = model.getMeshHelper( 0 ); bool bHasTexture = meshHelper.hasTexture(); if( bHasTexture ) { texture = model.getTextureForMesh(0); } ofMaterial material = model.getMaterialForMesh(0); ofPushMatrix(); //translate and scale based on the positioning. ofTranslate(position); ofRotateDeg(-markers.getImagePoint(34).x, 0, 1, 0); ofRotateDeg(90,1,0,0); ofScale(normalizedScale, normalizedScale, normalizedScale); ofScale(scale.x,scale.y,scale.z); //modify mesh with some noise float liquidness = 5; float amplitude = -markers.getImagePoint(34).y/100.0; float speedDampen = 5; auto &verts = mesh.getVertices(); for(unsigned int i = 0; i < verts.size(); i++){ verts[i].x += ofSignedNoise(verts[i].x/liquidness, verts[i].y/liquidness,verts[i].z/liquidness, ofGetElapsedTimef()/speedDampen)*amplitude; verts[i].y += ofSignedNoise(verts[i].z/liquidness, verts[i].x/liquidness,verts[i].y/liquidness, ofGetElapsedTimef()/speedDampen)*amplitude; verts[i].z += ofSignedNoise(verts[i].y/liquidness, verts[i].z/liquidness,verts[i].x/liquidness, ofGetElapsedTimef()/speedDampen)*amplitude; } //draw the model manually if(bHasTexture) texture.bind(); material.begin(); mesh.drawWireframe(); //you can draw wireframe too mesh.drawFaces(); material.end(); if(bHasTexture) texture.unbind(); ofPopMatrix(); } }*/
dbf965fda91919a00626a0eb91317f46ba069b23
5b39937c88d98d8bf9aa3d242ade98d3ebdb3bd3
/Documents Personnels/Iris Hoel/soft pour controle robot/PC/affichage.hpp
7c450c8c1f3f2a228081963e5e3ccde94fdd3ad1
[]
no_license
robinmoussu/robotronik
2c542360ac5819a3cedab3b3786909df021e927f
5a21218001c79dbfd1c987b2041f9ba2647b0c96
refs/heads/master
2021-01-10T21:11:34.944493
2015-03-12T17:04:04
2015-03-12T17:04:04
32,186,393
0
0
null
null
null
null
UTF-8
C++
false
false
410
hpp
affichage.hpp
#ifndef _AFFICHAGE_ #define _AFFICHAGE_ /*------------------------------- include -----------------------------------*/ #include "main.hpp" /*------------------------------- declaration fonctions ---------------------*/ Robot * configuration_initiale_robot(Uint32 couleur, Coord position); float tourner_a_90(Robot* R); void oneStepSimu(); void afficher_robot(Robot* R); #endif
d334f9975076a482af928e6b166bb8949e29191d
1a2520b2c9176e7c5416db76ec5ce1209d8f92d5
/TecProg_DaniLuque/GameEngine.hh
55e7d52e13c799599e23a586cd3edc093cb304e1
[]
no_license
lemminghart/TecProg_DaniLuque
5f788cdd867e1b3bf023c8261d7fc7da4bb01ad2
71c4745f89f0e87436b457c7a88a848538c7b8f3
refs/heads/master
2021-01-13T15:37:00.028358
2017-01-09T18:05:30
2017-01-09T18:05:30
76,873,440
0
0
null
null
null
null
UTF-8
C++
false
false
3,025
hh
GameEngine.hh
/****************************************************************** * Copyright (C) 2016 Jordi Serrano Berbel <jsberbel95@gmail.com> * * This can not be copied, modified and/or distributed without * * express permission of the copyright owner. * ******************************************************************/ #pragma once #include "System.hh" #include <iostream> #pragma region GAME_SCENES #include "GameMenu.hh" #include "Scene_Playing.h" #include "Scene_Ranking.h" #pragma endregion TODO //! Initializes game needs and controls the game loop namespace GameEngine { //! Loads main resources such as game images and fonts void LoadMedia(void) { R.LoadFont<FontID::ARIAL>("fnt/arial.ttf", 40); R.LoadFont<FontID::CANDY>("fnt/candy.ttf", 50); R.LoadFont<FontID::FACTORY>("fnt/candsb.ttf", 80); R.LoadTexture<ObjectID::BG_00>("gfx/bg.png"); R.LoadTexture<ObjectID::SNAKE_HEAD>("gfx/Snake/Snake_head.png"); R.LoadTexture<ObjectID::SNAKE_BODY>("gfx/Snake/Snake_body.png"); R.LoadTexture<ObjectID::SNAKE_TAIL>("gfx/Snake/Snake_tail.png"); R.LoadTexture<ObjectID::FOOD_APPLE>("gfx/Snake/Food_apple.png"); R.LoadTexture<ObjectID::CELL_EMPTY>("gfx/empty.png"); R.LoadTexture<ObjectID::CELL_WALL>("gfx/wall.png"); } //! Adds the game scenes into the Scene Manager and decides which is the first screen void AddScenes(void) { SM.AddScene<GameMenu>(); SM.AddScene<GamePlaying>(); SM.AddScene<Ranking>(); SM.SetCurScene<GameMenu>(); } /** * Runs the game specifying the window's name and dimensions * @tparam screenWidth Determines the window's width * @tparam screenHeight Determines the window's height * @param name Determines the window's title */ template<int screenWidth, int screenHeight> void Run(std::string &&name) { Window::Instance(std::move(name), screenWidth, screenHeight); // Initialize window Singleton instance for the first time LoadMedia(); // Loads the resource assets AddScenes(); // Loads the scenes bool m_isRunning{ true }; // Decides if the game loop is running Scene *&m_curScene(SM.GetCurScene()); // Defines a reference to a pointer that points to the current scene pointer (mindblown) while (!IM.HasQuit() && m_isRunning) { // Checks while game's still playable #pragma region GAME_UPDATE TM.Update([&] { switch (m_curScene->GetState()) { // Check for the state of the screen case SceneState::RUNNING: IM.Update(); m_curScene->Update(); break; // Updates the InputManager and the current scene case SceneState::EXIT: m_isRunning = false; break; // Triggers an end of the game looping case SceneState::SLEEP: default:; }}); #pragma endregion #pragma region GAME_DRAW if (m_curScene->CheckState<SceneState::RUNNING>()) { // If screen object exists and its state is running R.Clear(); // Clear the screen buffer m_curScene->Draw(); // Call the draw method of the scene R.Render(); // Update the screen buffer with all sprites that were pushed } #pragma endregion } } }
3b0dcbb18b8bbe42a78c9626f227e1a811756dcf
04a7e0936e2823dfd0976b518ba5379cd5e5a841
/911/4.cpp
b7e88429a48ad58a520992585fd415675f44536e
[]
no_license
sanket0211/Codeforces-Contests
152d41a215ed68eb9a05047d2aab328d78d2e1eb
96d791ec8dd618381e24855e102cf4392c8414ff
refs/heads/master
2021-09-04T01:42:03.062971
2018-01-14T05:00:07
2018-01-14T05:00:07
114,529,290
0
0
null
null
null
null
UTF-8
C++
false
false
1,848
cpp
4.cpp
/* * USER: Raj Manvar * LANG: C++ * */ #include <bits/stdc++.h> #include <unistd.h> #define pb push_back #define mp make_pair #define f first #define s second #define DRT() int t; cin>>t; while(t--) #define TRACE #ifdef TRACE #define trace1(x) cerr << #x << ": " << x << endl; #define trace2(x, y) cerr << #x << ": " << x << " | " << #y << ": " << y << endl; #define trace3(x, y, z) cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl; #define trace4(a, b, c, d) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl; #define trace5(a, b, c, d, e) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl; #define trace6(a, b, c, d, e, f) cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl; #else #define trace1(x) #define trace2(x, y) #define trace3(x, y, z) #define trace4(a, b, c, d) #define trace5(a, b, c, d, e) #define trace6(a, b, c, d, e, f) #endif using namespace std; typedef long long int lli; int main() { int n; cin>>n; vector<int> a(n); for (int i=0;i<n;i++) cin>>a[i]; int c=0; for (int i=0;i<n;i++) { for (int j=i-1;j>=0;j--) { if (a[i]<a[j]) c++; } } string pre; if (c%2==0) pre="even"; else pre="odd"; int m; cin>>m; for (int i=0;i<m;i++) { int l,r; cin>>l>>r; int c=r-l+1; int c1 = ((c)*(c-1))/2; if (c1%2==1) { if (pre=="even") pre="odd"; else pre="even"; } cout<<pre<<endl; } }
a2f3f1bb2ce09fc372258a6e648a533fc4885e4c
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/enduser/speech/src/lexicon/lexapi/clookup.cpp
8c4e4f53e29472892263b381c8dc7fcc186ecd0f
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,805
cpp
clookup.cpp
/***************************************************************************** * Clookup.cpp * Implements the vendor lexicon object for SR and TTS lookup lexicons * * Owner: YunusM * * Copyright 1999 Microsoft Corporation All Rights Reserved. *****************************************************************************/ #include "PreCompiled.h" #include "MSGenLex.h" static const PCSTR pLkupMutexName = "8FA68BB0-EE1B-11d2-9C23-00C04F8EF87C"; static const PCSTR pLkupMapName = "992C78C4-D8D7-11d2-9C1F-00C04F8EF87C"; static const PCSTR pRefCntMapName = "82309534-F6C7-11d2-9C24-00C04F8EF87C"; /***************************************************************************** * _Constructor * *--------------* * * The real constructor. * Return: **********************************************************************YUNUSM*/ void CLookup::_Constructor(CVendorManager *pMgr) { m_fInit = false; *m_wszLkupFile = 0; m_pMgr = pMgr; m_fAuthenticated = true; m_pLkupLexInfo = NULL; m_hLkupFile = NULL; m_hLkupMap = NULL; m_hInitMutex = NULL; m_pLkup = NULL; m_pWordHash = NULL; m_pCmpBlock = NULL; m_pRefCount = NULL; m_hRefMapping = NULL; m_pWordsDecoder = NULL; m_pPronsDecoder = NULL; m_pPosDecoder = NULL; m_pLts = NULL; } // void CLookup::_Constructor (void) /***************************************************************************** * CLookup * *---------* * * Constructor * Return: **********************************************************************YUNUSM*/ CLookup::CLookup(CVendorManager *pMgr) { _Constructor(pMgr); } // CLookup::CLookup () /***************************************************************************** * _Destructor * *-------------* * * The real destructor. * Return: **********************************************************************YUNUSM*/ void CLookup::_Destructor (void) { delete m_pLts; delete m_pWordsDecoder; delete m_pPronsDecoder; delete m_pPosDecoder; m_pLts = NULL; m_pWordsDecoder = NULL; m_pPronsDecoder = NULL; m_pPosDecoder = NULL; UnmapViewOfFile (m_pLkup); CloseHandle (m_hLkupMap); CloseHandle (m_hLkupFile); m_pLkup = NULL; m_hLkupFile = NULL; m_hLkupMap = NULL; UnmapViewOfFile (m_pRefCount); CloseHandle (m_hRefMapping); m_pRefCount = NULL; m_hRefMapping = NULL; } // CLookup::_Destructor (void) /***************************************************************************** * ~CLookup * *----------* * * Destructor * Return: **********************************************************************YUNUSM*/ CLookup::~CLookup () { _Destructor (); CloseHandle (m_hInitMutex); m_hInitMutex = NULL; } // CLookup::~CLookup () /***************************************************************************** * _Init * *-------* * * Initializes the CLookup object with a lookup lexicon and a LTS lexicon. The * LTS lexicon is used to compress the lookup lexicon by storing the indexes * of the pronunciations in LTS lexion that also occur in the lookup lexicon. * * Return: S_OK E_FAIL, Win32 errors **********************************************************************YUNUSM*/ HRESULT CLookup::_Init(PCWSTR pwszLkupFile, // Lookup lexicon file PCWSTR pwszLtsFile // Lts lexicon file ) { HRESULT hRes = S_OK; char szLkupFile[MAX_PATH]; // We limit the fully qualified name length to a max of MAX_PATH if (!WideCharToMultiByte (CP_ACP, 0, pwszLkupFile, -1, szLkupFile, MAX_PATH, NULL, NULL)) { hRes = E_FAIL; goto ErrorInit; } wcscpy (m_wszLkupFile, pwszLkupFile); wcscpy (m_wszLtsFile, pwszLtsFile); // Map the lookup lexicon m_hLkupFile = CreateFile (szLkupFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL); if (m_hLkupFile == INVALID_HANDLE_VALUE) { hRes = HRESULT_FROM_WIN32 (GetLastError()); // bad input goto ErrorInit; } m_hLkupMap = CreateFileMapping (m_hLkupFile, NULL, PAGE_READONLY | SEC_COMMIT, 0 , 0, pLkupMapName); if (!m_hLkupMap) { hRes = HRESULT_FROM_WIN32 (GetLastError()); goto ErrorInit; } m_pLkup = (PBYTE) MapViewOfFile (m_hLkupMap, FILE_MAP_READ, 0, 0, 0); if (!m_pLkup) { hRes = HRESULT_FROM_WIN32 (GetLastError()); // We or the OS did something wrong - cant return GetLastError() goto ErrorInit; } PBYTE p; p = m_pLkup; // Header m_pLkupLexInfo = (PLKUPLEXINFO)p; p += sizeof (LKUPLEXINFO); // Words Codebook PBYTE pWordCB; pWordCB = p; p += m_pLkupLexInfo->nWordCBSize; // Prons Codebook PBYTE pPronCB; pPronCB = p; p += m_pLkupLexInfo->nPronCBSize; // Pos Codebook PBYTE pPosCB; pPosCB = p; p += m_pLkupLexInfo->nPosCBSize; // Word hash table holding offsets into the compressed block m_pWordHash = p; p += (((m_pLkupLexInfo->nBitsPerHashEntry * m_pLkupLexInfo->nLengthHashTable) + 0x7) & (~0x7)) / 8; m_pCmpBlock = (PDWORD)p; m_pLts = new CLTS (NULL); if (!m_pLts) { hRes = E_OUTOFMEMORY; goto ErrorInit; } if (FAILED (hRes = m_pLts->Init(pwszLtsFile, NULL))) { goto ErrorInit; } m_pWordsDecoder = new CHuffDecoder(pWordCB); if (!m_pWordsDecoder) { hRes = E_OUTOFMEMORY; goto ErrorInit; } m_pPronsDecoder = new CHuffDecoder(pPronCB); if (!m_pPronsDecoder) { hRes = E_OUTOFMEMORY; goto ErrorInit; } m_pPosDecoder = new CHuffDecoder(pPosCB); if (!m_pPosDecoder) { hRes = E_OUTOFMEMORY; goto ErrorInit; } // Init the Read-write lex hRes = m_RWLex.Init (m_pLkupLexInfo); if (FAILED (hRes)) { goto ErrorInit; } // Create the shared memory to store the number of clients to the lookup file m_hRefMapping = CreateFileMapping ((HANDLE)0xffffffff, // use the system paging file NULL, PAGE_READWRITE, 0, sizeof (DWORD), pRefCntMapName); if (!m_hRefMapping) { hRes = HRESULT_FROM_WIN32 (GetLastError ()); goto ErrorInit; } bool fMapCreated; (ERROR_ALREADY_EXISTS == GetLastError ()) ? fMapCreated = false : fMapCreated = true; m_pRefCount = (PINT) MapViewOfFile (m_hRefMapping, FILE_MAP_WRITE, 0, 0, 0); if (!m_pRefCount) { hRes = HRESULT_FROM_WIN32 (GetLastError ()); goto ErrorInit; } // Increment the ref count at the end of init when everything has succeeded if (fMapCreated) { *m_pRefCount = 1; } else { (*m_pRefCount)++; } goto ReturnInit; ErrorInit: _Destructor (); ReturnInit: return hRes; } // HRESULT CLookup::_Init (PWSTR pwszLkupFile) /***************************************************************************** * Init * *------* * * Initializes the CLookup object with a lookup lexicon and a LTS lexicon. The * LTS lexicon is used to compress the lookup lexicon by storing the indexes * of the pronunciations in LTS lexion that also occur in the lookup lexicon. * * Return: S_OK E_FAIL, Win32 errors **********************************************************************YUNUSM*/ HRESULT CLookup::Init(PCWSTR pwszLkupFile, // Lookup lexicon file PCWSTR pwszLtsFile) // Lts lexicon file { if (LexIsBadStringPtr(pwszLkupFile) || LexIsBadStringPtr(pwszLtsFile)) return E_INVALIDARG; // Do not allow multiple inits if (true == m_fInit) { return HRESULT_FROM_WIN32 (ERROR_ALREADY_INITIALIZED); } HRESULT hRes = S_OK; // We don't ask for ownership of the mutex because more than // one thread could be executing here m_hInitMutex = CreateMutex (NULL, FALSE, pLkupMutexName); if (!m_hInitMutex) { return HRESULT_FROM_WIN32 (GetLastError()); } WaitForSingleObject (m_hInitMutex, INFINITE); hRes = _Init (pwszLkupFile, pwszLtsFile); m_fInit = true; ReleaseMutex (m_hInitMutex); return hRes; } // HRESULT CLookup::Init (PWSTR pwzLkupPath) /********************************************************** Hash function for the Word hash tables **********************************************************/ __inline DWORD GetWordHashValue (PCWSTR pwszWord, DWORD nLengthHash) { DWORD dHash = *pwszWord++; WCHAR c; WCHAR cPrev = (WCHAR)dHash; for (; *pwszWord; pwszWord++) { c = *pwszWord; //dHash += ((*pszWord + *(pszWord - 1)) << (char)(*pszWord)); // 79k //dHash += (((*pszWord) << (char)(*pszWord)) + ((*(pszWord - 1)) << (char)(*(pszWord - 1)))); // 73k //dHash += (((*pszWord) << (char)(*(pszWord+1))) + ((*(pszWord - 1)) << (char)(*(pszWord)))); // 71k //dHash += ((*pszWord) << (char)(*(pszWord+1))); // 72k //dHash += (((*pszWord) << (char)(*(pszWord+1))) + ((*(pszWord)) << (char)(*(pszWord-1)))); // 71k //dHash += (((*pszWord) << (char)(*(pszWord))) + ((*(pszWord-1)) << (char)(*(pszWord+1)))); // 73k //dHash += (((*pszWord) << (char)(*(pszWord-1))) + ((*(pszWord-1)) << (char)(*(pszWord+1)))); // 70.5k dHash += ((c << cPrev) + (cPrev << c)); // 70.3k cPrev = c; } return (((dHash << 16) - dHash) % nLengthHash); } // __inline DWORD GetWordHashValue (PCWSTR pwszWord, DWORD nLengthHash) /********************************************************** Stub hash function for the Word hash tables Called by the tools (outside the lib) since the GetWordHashValue is inlined in 'release' build and cannot be called **********************************************************/ DWORD GetWordHashValueStub (PWSTR pwszWord, DWORD nLengthHash) { return GetWordHashValue (pwszWord, nLengthHash); } /********************************************************** Get the entry in hash table at index dHash **********************************************************/ __inline DWORD CLookup::GetCmpHashEntry (DWORD dHash) { DWORD d = 0; DWORD dBitStart = dHash * m_pLkupLexInfo->nBitsPerHashEntry; _ASSERTE (m_pLkupLexInfo->nBitsPerHashEntry < 8 * sizeof (d)); for (DWORD i = 0; i < m_pLkupLexInfo->nBitsPerHashEntry; i++) { d <<= 1; // No change the first time since d is 0 d |= ((m_pWordHash[dBitStart >> 3] >> (7 ^ (dBitStart & 7))) & 1); dBitStart++; } return d; } // DWORD CLookup::GetCmpHashEntry (DWORD dhash) /********************************************************** Do a compare over the valid bit range **********************************************************/ __inline bool CLookup::CompareHashValue (DWORD dHash, DWORD d) { return (dHash == (d & ~(-1 << m_pLkupLexInfo->nBitsPerHashEntry))); } // bool CLookup::CompareHashValue (DWORD dhash, DWORD d) /********************************************************** Copy nBits from pSource at dSourceOffset bit to pDest **********************************************************/ __inline void CLookup::CopyBitsAsDWORDs (PDWORD pDest, PDWORD pSource, DWORD dSourceOffset, DWORD nBits) { DWORD sDWORDs = dSourceOffset >> 5; DWORD sBit = dSourceOffset & 0x1f; // Figure out how many DWORDs dSourceOffset - dSourceOffset + nBits straddles DWORD nDWORDs = nBits ? 1 : 0; DWORD nNextDWORDBoundary = ((dSourceOffset + 0x1f) & ~0x1f); if (!nNextDWORDBoundary) nNextDWORDBoundary = 32; while (nNextDWORDBoundary < (dSourceOffset + nBits)) { nDWORDs++; nNextDWORDBoundary += 32; } CopyMemory (pDest, pSource + sDWORDs, nDWORDs * sizeof (DWORD)); if (sBit) { for (DWORD i = 0; i < nDWORDs; i++) { pDest[i] >>= sBit; if (i < nDWORDs - 1) pDest[i] |= (pDest[i+1] << (32 - sBit)); else pDest[i] &= ~(-1 << (32 - sBit)); } } } // void CLookup::CopyBitsAsDWORDs (PDWORD pDest, PDWORD pSource, /********************************************************** Read the (compressed) word at the dOffset bit and return the word and the new offset **********************************************************/ __inline HRESULT CLookup::ReadWord (DWORD *dOffset, PWSTR pwWord) { // Get the length of the entire compressed block in bytes DWORD nCmpBlockLen; if (m_pLkupLexInfo->nLengthCmpBlockBits % 8) nCmpBlockLen = (m_pLkupLexInfo->nLengthCmpBlockBits / 8) + 1; else nCmpBlockLen = m_pLkupLexInfo->nLengthCmpBlockBits / 8; // Get the amount of compressed block after *dOffset in bytes // We include the byte in which *dOffset bit occurs if *dOffset // is not a byte boundary DWORD nLenDecode = nCmpBlockLen - ((*dOffset) / 8); if (nLenDecode > 2*MAX_STRING_LEN) nLenDecode = 2*MAX_STRING_LEN; // We dont know the length of the word. Just keep decoding and // stop when you encounter a NULL. Since we allow words of maximum // length MAX_STRING_LEN chars and the compressed word *can* theoretically be // longer than the word itself, a buffer of length 2*MAX_STRING_LEN is used. BYTE BufToDecode[2*MAX_STRING_LEN]; CopyBitsAsDWORDs ((DWORD*)BufToDecode, m_pCmpBlock, *dOffset, nLenDecode * 8); PWSTR pw = pwWord; /* ZeroMemory (BufToDecode,sizeof (BufToDecode)); BufToDecode [0] = 0xff; BufToDecode [1] = 0x5d; BufToDecode [2] = 0x1f; BufToDecode [3] = 0xeb; BufToDecode [4] = 0xed; BufToDecode [5] = 0x10; BufToDecode [6] = 0x71; BufToDecode [7] = 0x8a; BufToDecode [8] = 0x02; //BufToDecode [9] = 0x10; BufToDecode [9] = 0x02; */ //m_pWordsDecoder->SetBase (BufToDecode); int iBit = (int)*dOffset; HUFFKEY k = 0; while (SUCCEEDED(m_pWordsDecoder->Next (m_pCmpBlock, &iBit, &k))) { *pw++ = k; if (!k) break; } _ASSERTE (!k && iBit); *dOffset = iBit; if (pw == pwWord) { _ASSERTE (0); return E_FAIL; } return NOERROR; } // __inline HRESULT CLookup::ReadWord (DWORD *dOffset, PWSTR pwWord) /********************************************************** Reads word information of type 'Type' at offset *dOffset and returns the info in *ppInfo and also updates *dOffset **********************************************************/ STDMETHODIMP CLookup::GetWordInformation(const WCHAR *pwWord, LCID lcid, DWORD dwInfoTypeFlags, DWORD dwLex, PWORD_INFO_BUFFER pInfo, PINDEXES_BUFFER pIndexes, DWORD *pdwLexTypeFound, GUID *pGuidLexFound) { // Not validating args since this is an internal call HRESULT hr = S_OK; WCHAR wlWord [MAX_STRING_LEN]; wcscpy (wlWord, pwWord); towcslower (wlWord); PWSTR pwlWord = wlWord; if (dwLex == LEXTYPE_GUESS) { hr = m_pLts->GetWordInformation (pwWord, lcid, dwInfoTypeFlags, dwLex, pInfo, pIndexes, pdwLexTypeFound, pGuidLexFound); goto ReturnLkupGetPronunciations; } if (!(dwLex & LEXTYPE_VENDOR)) { hr = LEXERR_NOTINLEX; goto ReturnLkupGetPronunciations; } DWORD dHash; dHash = GetWordHashValue (pwlWord, m_pLkupLexInfo->nLengthHashTable); // Cannot just index into hash table since each element in hash table is // m_pLkupLexInfo->nBitsPerHashEntry long WCHAR wszWord[MAX_STRING_LEN]; DWORD dOffset; dOffset = 0; for (;;) { dOffset = GetCmpHashEntry (dHash); if (CompareHashValue (dOffset, (DWORD)-1)) { // BUGBUG: Activate this check when appropriate //if (dwLex & LEXTYPE_GUESS) //{ hr = m_pLts->GetWordInformation (pwWord, lcid, dwInfoTypeFlags, dwLex, pInfo, pIndexes, pdwLexTypeFound, pGuidLexFound); goto ReturnLkupGetPronunciations; //} //else //{ // hRes = LEXERR_NOTINLEX; // goto ReturnLkupGetPronunciations; //} } hr = ReadWord (&dOffset, wszWord); if (FAILED(hr)) goto ReturnLkupGetPronunciations; if (wcsicmp (pwlWord, wszWord)) { dHash++; if (dHash == m_pLkupLexInfo->nLengthHashTable) dHash = 0; continue; } else break; } // for (;;) DWORD dwInfoBytesNeeded; DWORD dwNumInfoBlocks; dwInfoBytesNeeded = 0; dwNumInfoBlocks = 0; // we figure we won't need a return buffer bigger than this BYTE InfoReturned[MAXINFOBUFLEN]; PLEX_WORD_INFO pWordInfoReturned; pWordInfoReturned = (PLEX_WORD_INFO)InfoReturned; //char sz[256]; //sprintf (sz, "*dOffset = %d\n", *dOffset); //OutputDebugString (sz); bool fLast; fLast = false; WCHAR LTSProns [MAX_PRON_LEN * MAX_OUTPUT_STRINGS]; *LTSProns = 0; //OutputDebugString ("In ReadWordInfo\n"); while (false == fLast) { // Read the control block (CBSIZE bits) // Length is 2 because of the way CopyBitsAsDWORDs works when the bits // to be copied straddle across DWORDs DWORD cb[4]; cb[0] = 0; _ASSERTE (CBSIZE <= 8); CopyBitsAsDWORDs (cb, m_pCmpBlock, dOffset, CBSIZE); dOffset += CBSIZE; if (cb[0] & (1 << (CBSIZE - 1))) { fLast = true; } int CBType = cb[0] & ~(-1 << (CBSIZE -1)); switch (CBType) { case I_LKUPLTSPRON: { // Read the index of LTS pron which takes LTSINDEXSIZE bits _ASSERTE (LTSINDEXSIZE <= 8); // Length is 2 because of the way CopyBitsAsDWORDs works when the bits // to be copied straddle across DWORDs DWORD iLTS[4]; iLTS[0] = 0; CopyBitsAsDWORDs (iLTS, m_pCmpBlock, dOffset, LTSINDEXSIZE); iLTS[0] &= ~(-1 << (LTSINDEXSIZE -1)); dOffset += LTSINDEXSIZE; if (!(dwInfoTypeFlags & PRON)) { continue; } pWordInfoReturned->Type = PRON; WORD_INFO_BUFFER WI; INDEXES_BUFFER IB; ZeroMemory(&WI, sizeof(WI)); ZeroMemory(&IB, sizeof(IB)); // Get the iLTSth LTS pronunciation if (!*LTSProns) { hr = m_pLts->GetWordInformation(pwWord, lcid, PRON, LEXTYPE_GUESS, &WI, &IB, pdwLexTypeFound, pGuidLexFound); if (FAILED(hr)) { goto ReturnLkupGetPronunciations; } } wcscpy (pWordInfoReturned->wPronunciation, (((LEX_WORD_INFO*)(WI.pInfo))[IB.pwIndex[iLTS[0]]]).wPronunciation); CoTaskMemFree(WI.pInfo); CoTaskMemFree(IB.pwIndex); DWORD d = (wcslen (pWordInfoReturned->wPronunciation) + 1) * sizeof (WCHAR); if (d > sizeof (LEX_WORD_INFO_UNION)) d -= sizeof (LEX_WORD_INFO_UNION); else d = 0; d += sizeof (LEX_WORD_INFO); dwNumInfoBlocks++; dwInfoBytesNeeded += d; pWordInfoReturned = (PLEX_WORD_INFO)((PBYTE)pWordInfoReturned + d); break; } // case LTSPRON: case I_LKUPLKUPPRON: { //OutputDebugString ("lkup pron\n"); /* // Read the length of Lookup pron which takes LKUPLENSIZE bits _ASSERTE (LKUPLENSIZE <= 8); // Length is 2 because of the way CopyBitsAsDWORDs works when the bits // to be copied straddle across DWORDs DWORD nLkupLen[2]; nLkupLen[0] = 0; CopyBitsAsDWORDs (nLkupLen, m_pCmpBlock, *dOffset, LKUPLENSIZE); nLkupLen[0] &= ~(-1 << (LKUPLENSIZE -1)); *dOffset += LKUPLENSIZE; _ASSERTE (nLkupLen[0]); */ DWORD dOffsetSave = dOffset; DWORD CmpLkupPron[MAX_PRON_LEN]; DWORD nCmpBlockLen; if (m_pLkupLexInfo->nLengthCmpBlockBits & 0x7) { nCmpBlockLen = (m_pLkupLexInfo->nLengthCmpBlockBits >> 3) + 1; } else { nCmpBlockLen = m_pLkupLexInfo->nLengthCmpBlockBits >> 3; } // Get the amount of compressed block after *dOffset in bytes // We include the byte in which *dOffset bit occurs if *dOffset // is not a byte boundary DWORD nLenDecode = nCmpBlockLen - (dOffsetSave >> 3); if (nLenDecode > MAX_STRING_LEN) { nLenDecode = MAX_STRING_LEN; } CopyBitsAsDWORDs (CmpLkupPron, m_pCmpBlock, dOffsetSave, (nLenDecode << 3)); // Decode the pronunciation //m_pPronsDecoder->SetBase ((PBYTE)CmpLkupPron); int iBit = (int)dOffset; WCHAR LkupPron[MAX_PRON_LEN]; PWSTR p = LkupPron; /* for (DWORD i = 0; i < nLkupLen[0]; i++) { *p++ = m_pPronsDecoder->Next (&iBit); } */ HUFFKEY k = 0; while (SUCCEEDED(m_pPronsDecoder->Next (m_pCmpBlock, &iBit, &k))) { //if (k) // sprintf (sz, "k = %x\n", k); //else // sprintf (sz, "NULL k\n"); //OutputDebugString (sz); *p++ = k; if (!k) { break; } } _ASSERTE (!k && iBit); // Increase the offset past the encoded pronunciation dOffset = iBit; if (! (dwInfoTypeFlags & PRON)) { continue; } // Increase the *pdwInfoBytesNeeded so that it is a multiple of sizeof (LEX_WORD_INFO); // Note: WordInfos are made to be start LEX_WORD_INFO multiple boundaries only in // the buffer that is returned. pWordInfoReturned->Type = PRON; *p = NULL; wcscpy (pWordInfoReturned->wPronunciation, LkupPron); DWORD d = (wcslen (pWordInfoReturned->wPronunciation) + 1) * sizeof (WCHAR); if (d > sizeof (LEX_WORD_INFO_UNION)) d -= sizeof (LEX_WORD_INFO_UNION); else d = 0; d += sizeof (LEX_WORD_INFO); dwNumInfoBlocks++; dwInfoBytesNeeded += d; pWordInfoReturned = (PLEX_WORD_INFO)((PBYTE)pWordInfoReturned + d); break; } // case LKUPPRON: case I_POS: { DWORD CmpPos[4]; CopyBitsAsDWORDs (CmpPos, m_pCmpBlock, dOffset, POSSIZE); int iBit = (int)dOffset; HUFFKEY k = 0; if (FAILED(m_pPosDecoder->Next (m_pCmpBlock, &iBit, &k))) { goto ReturnLkupGetPronunciations; } // Increase the offset past the encoded pronunciation dOffset = iBit; if (! (dwInfoTypeFlags & POS)) { continue; } pWordInfoReturned->Type = POS; pWordInfoReturned->POS = (unsigned short)k; dwNumInfoBlocks++; DWORD d = sizeof (LEX_WORD_INFO); dwInfoBytesNeeded += d; pWordInfoReturned = (PLEX_WORD_INFO)((PBYTE)pWordInfoReturned + d); break; } // case I_POS: default: { // Not supported yet _ASSERTE (0); } } // switch (CBType) } // while (false == fLast) //sprintf (sz, "nInfoUse = %d\n", nInfoUse); //OutputDebugString (sz); hr = _ReallocWordInfoBuffer(pInfo, dwInfoBytesNeeded + sizeof(LEX_WORD_INFO) * dwNumInfoBlocks); if (FAILED(hr)) goto ReturnLkupGetPronunciations; hr = _ReallocIndexesBuffer(pIndexes, dwNumInfoBlocks); if (FAILED(hr)) goto ReturnLkupGetPronunciations; _AlignWordInfo((LEX_WORD_INFO*)InfoReturned, dwNumInfoBlocks, dwInfoTypeFlags, pInfo, pIndexes); //sprintf (sz, "hRes returned from ReadWordInfo = %x\n", hRes); //OutputDebugString (sz); if (pdwLexTypeFound) *pdwLexTypeFound = LEXTYPE_VENDOR; if (pGuidLexFound) *pGuidLexFound = m_pLkupLexInfo->gLexiconID; ReturnLkupGetPronunciations: return hr; } // STDMETHODIMP CLookup::GetWordInformation() HRESULT CLookup::Shutdown (bool fSerialize) { WaitForSingleObject (m_hInitMutex, INFINITE); m_RWLex.Lock (true); // lock the r/w lex in read-only mode HRESULT hRes = NOERROR; FILE * fp = NULL; FILE *fprw = NULL; // BUGBUG: The intermediate file should be hidden // temp text file to dump the r/w lex char szTempRWFile[MAX_PATH * 2]; WCHAR wszTempRWFile[MAX_PATH * 2]; wcscpy (wszTempRWFile, m_wszLkupFile); wcscat (wszTempRWFile, L".rw.txt"); (*m_pRefCount)--; _ASSERTE ((*m_pRefCount) >= 0); if ((fSerialize == false) || (*m_pRefCount > 0) || (true == m_RWLex.IsEmpty ())) { // nothing to do goto ReturnSerialize; } WideCharToMultiByte (CP_ACP, 0, wszTempRWFile, -1, szTempRWFile, MAX_PATH, NULL, NULL); hRes = m_RWLex.FlushAscii (m_pLkupLexInfo->Lcid, wszTempRWFile); if (FAILED (hRes)) { goto ReturnSerialize; } fprw = fopen (szTempRWFile, "r"); if (!fprw) { hRes = E_FAIL; goto ReturnSerialize; } // temp text file to dump the word and word-info to char szTempLkupFile [MAX_PATH * 2]; WideCharToMultiByte (CP_ACP, 0, m_wszLkupFile, -1, szTempLkupFile, MAX_PATH, NULL, NULL); strcat (szTempLkupFile, ".interm.txt"); fp = fopen (szTempLkupFile, "w"); if (!fp) { hRes = E_FAIL; goto ReturnSerialize; } WORD_INFO_BUFFER WI; INDEXES_BUFFER IB; ZeroMemory(&WI, sizeof(WI)); ZeroMemory(&IB, sizeof(IB)); // walk the words in the lookup file and check if they occur in dict file DWORD dHash; for (dHash = 0; dHash < m_pLkupLexInfo->nLengthHashTable; dHash++) { DWORD dOffset = GetCmpHashEntry (dHash); if (CompareHashValue (dOffset, (DWORD)-1)) { continue; } WCHAR wszWord[MAX_STRING_LEN]; hRes = ReadWord (&dOffset, wszWord); if (FAILED(hRes)) { goto ReturnSerialize; } // query the dict file for this word hRes = m_RWLex.GetWordInformation(wszWord, m_pLkupLexInfo->Lcid, PRON|POS, &WI, &IB, NULL, NULL); if (FAILED (hRes)) { if (hRes != LEXERR_NOTINLEX) { goto ReturnSerialize; } DWORD dwLexTypeFound; hRes = GetWordInformation (wszWord, m_pLkupLexInfo->Lcid, PRON|POS, LEXTYPE_VENDOR, &WI, &IB, &dwLexTypeFound, NULL); if (LEXTYPE_VENDOR != dwLexTypeFound) { goto ReturnSerialize; } } else { continue; // ignore the entry in lookup lexicon } char sz[MAX_PRON_LEN * 10]; // Write the word strcpy (sz, "Word "); WideCharToMultiByte (CP_ACP, 0, wszWord, -1, sz + strlen (sz), MAX_STRING_LEN, NULL, NULL); fprintf (fp, "%s\n", sz); // Write the word-information DWORD iPron; DWORD iPOS; iPron = 0; iPOS = 0; PLEX_WORD_INFO pInfo; pInfo = (PLEX_WORD_INFO)(WI.pInfo); DWORD i; for (i = 0; i < WI.cInfoBlocks; i++) { WORD Type = pInfo[IB.pwIndex[i]].Type; switch (Type) { case PRON: strcpy (sz, "Pronunciation"); itoa (iPron, sz + strlen (sz), 10); strcat (sz, " "); itoah (pInfo[IB.pwIndex[i]].wPronunciation, sz + strlen (sz)); fprintf (fp, "%s\n", sz); iPron++; break; case POS: strcpy (sz, "POS"); itoa (iPOS, sz + strlen (sz), 10); strcat (sz, " "); itoa (pInfo[IB.pwIndex[i]].POS, sz + strlen (sz), 10); fprintf (fp, "%s\n", sz); iPOS++; break; default: _ASSERTE (0); goto ReturnSerialize; } // switch (Type) } // for (i = 0; i < dwNumInfoBlocks; i++) } // for (DWORD dHash = 0; dHash < m_pLkupLexInfo->nLengthHashTable; dHash++) CoTaskMemFree(WI.pInfo); CoTaskMemFree(IB.pwIndex); // append the entries of the rw lex to the llokup text file char sz[MAX_PRON_LEN * 10]; while (fgets (sz, MAX_PRON_LEN * 10, fprw)) { fprintf (fp, sz); } fclose (fp); fclose (fprw); fp = NULL; fprw = NULL; // Build a lookup lex file out of szTempLkupFile // temp lex file char szTempLexFile [MAX_PATH * 2]; WCHAR wszTempLexFile [MAX_PATH * 2]; WCHAR wszTempLkupFile [MAX_PATH * 2]; char szLkupFile [MAX_PATH * 2]; wcscpy (wszTempLexFile, m_wszLkupFile); wcscat (wszTempLexFile, L".interm.lex"); MultiByteToWideChar(CP_ACP, MB_COMPOSITE, szTempLkupFile, -1, wszTempLkupFile, MAX_PATH); hRes = BuildLookup(m_pLkupLexInfo->Lcid, m_pLkupLexInfo->gLexiconID, wszTempLkupFile, wszTempLexFile, m_wszLtsFile, true, false); if (FAILED (hRes)) { goto ReturnSerialize; } WideCharToMultiByte (CP_ACP, 0, m_wszLkupFile, -1, szLkupFile, MAX_PATH, NULL, NULL); // release the current object and reinit it _Destructor (); // delete the existing lookup file if (!DeleteFile (szLkupFile)) { hRes = HRESULT_FROM_WIN32 (GetLastError ()); goto ReturnSerialize; } WideCharToMultiByte (CP_ACP, 0, wszTempLexFile, -1, szTempLexFile, MAX_PATH, NULL, NULL); // would like to use MoveFileEx with MOVEFILE_WRITE_THROUGH flag // but it is not supported in Win95 if (!MoveFile(szTempLexFile, szLkupFile)) { hRes = HRESULT_FROM_WIN32 (GetLastError ()); goto ReturnSerialize; } WCHAR wszLkupFile [MAX_PATH], wszLtsFile[MAX_PATH]; wcscpy (wszLkupFile, m_wszLkupFile); wcscpy (wszLtsFile, m_wszLtsFile); hRes = _Init (wszLkupFile, wszLtsFile); if (FAILED (hRes)) { goto ReturnSerialize; } ReturnSerialize: DeleteFile (szTempLkupFile); DeleteFile (szTempRWFile); if (fp) { fclose (fp); } if (fprw) { fclose (fprw); } m_RWLex.UnLock (true); ReleaseMutex (m_hInitMutex); return hRes; } // HRESULT CLookup::Shutdown (bool fSerialize) STDMETHODIMP_ (ULONG) CLookup::AddRef() { m_pMgr->AddRef(); return ++m_cRef; } STDMETHODIMP_ (ULONG) CLookup::Release() { ULONG i = --m_cRef; m_pMgr->Release(); return i; } STDMETHODIMP CLookup::QueryInterface(REFIID riid, LPVOID *ppv) { return m_pMgr->QueryInterface(riid, ppv); } STDMETHODIMP CLookup::GetHeader(LEX_HDR *pLexHdr) { if (!pLexHdr) { return E_POINTER; } if (IsBadWritePtr(pLexHdr, sizeof(LEX_HDR))) { return E_INVALIDARG; } return E_NOTIMPL; } STDMETHODIMP CLookup::Authenticate(GUID, GUID *pLexId) { if (!pLexId) return E_POINTER; if (IsBadWritePtr(pLexId, sizeof(GUID))) return E_INVALIDARG; *pLexId = m_pLkupLexInfo->gLexiconID; return S_OK; } STDMETHODIMP CLookup::IsAuthenticated(BOOL *pfAuthenticated) { if (!pfAuthenticated) { return E_POINTER; } if (IsBadWritePtr(pfAuthenticated, sizeof(BOOL))) { return E_INVALIDARG; } *pfAuthenticated = m_fAuthenticated; return S_OK; }
52645a4d79e3a7c70cfe2ef58822017b4b4c9306
b16d370b74422644e2cc92cb1573f2495bb6c637
/c/cf/cf1015b.cc
d7fa4dfd0313acc273eef8f8e8b6f26337d91afd
[]
no_license
deniskokarev/practice
8646a3a29b9e4f9deca554d1a277308bf31be188
7e6742b6c24b927f461857a5509c448ab634925c
refs/heads/master
2023-09-01T03:37:22.286458
2023-08-22T13:01:46
2023-08-22T13:01:46
76,293,257
0
0
null
null
null
null
UTF-8
C++
false
false
541
cc
cf1015b.cc
#include <iostream> #include <vector> /* CodeForces CF1015B problem */ using namespace std; int main(int argc, char **argv) { int n; string s, t; cin >> n >> s >> t; vector<int> ans; for (int i=0; i<n; i++) { int j; for (j=i; j<n; j++) { if (t[i] == s[j]) { for (int k=j; k>i; k--) { ans.push_back(k); swap(s[k-1],s[k]); } break; } } if (j==n) goto no_ans; } cout << ans.size() << endl; for (auto a:ans) cout << a << ' '; cout << endl; return 0; no_ans: cout << -1 << endl; return 0; }
693c5e5560179858738852ddf570ed9af747ab20
ba2b37e3be216c87877e212b13639f839cc857f5
/src/disc/stk/Albany_OrdinarySTKFieldContainer_Def.hpp
9f87e6ffa2730d5a866e068feea4808d5ed8eb97
[ "BSD-2-Clause" ]
permissive
stvsun/Albany
ac1e8dbb27823f9a5b357aa041a37b1eca494548
7971bb6951b868f7029fe11cbb0898d351ae4a1d
refs/heads/master
2022-04-29T20:51:55.453554
2022-03-26T21:22:21
2022-03-26T21:22:21
19,159,626
1
0
null
null
null
null
UTF-8
C++
false
false
10,648
hpp
Albany_OrdinarySTKFieldContainer_Def.hpp
//*****************************************************************// // Albany 2.0: Copyright 2012 Sandia Corporation // // This Software is released under the BSD license detailed // // in the file "license.txt" in the top-level Albany directory // //*****************************************************************// #include <iostream> #include "Albany_OrdinarySTKFieldContainer.hpp" #include "Albany_Utils.hpp" #include <stk_mesh/base/GetBuckets.hpp> #ifdef ALBANY_SEACAS #include <stk_io/IossBridge.hpp> #endif template<bool Interleaved> Albany::OrdinarySTKFieldContainer<Interleaved>::OrdinarySTKFieldContainer( const Teuchos::RCP<Teuchos::ParameterList>& params_, stk::mesh::fem::FEMMetaData* metaData_, stk::mesh::BulkData* bulkData_, const int neq_, const AbstractFieldContainer::FieldContainerRequirements& req, const int numDim_, const Teuchos::RCP<Albany::StateInfoStruct>& sis) : GenericSTKFieldContainer<Interleaved>(params_, metaData_, bulkData_, neq_, numDim_), buildSurfaceHeight(false), buildTemperature(false), buildBasalFriction(false), buildThickness(false), buildFlowFactor(false), buildSurfaceVelocity(false), buildVelocityRMS(false) { typedef typename AbstractSTKFieldContainer::VectorFieldType VFT; typedef typename AbstractSTKFieldContainer::ScalarFieldType SFT; #ifdef ALBANY_FELIX buildSurfaceHeight = (std::find(req.begin(), req.end(), "Surface Height") != req.end()); buildTemperature = (std::find(req.begin(), req.end(), "Temperature") != req.end()); buildBasalFriction = (std::find(req.begin(), req.end(), "Basal Friction") != req.end()); buildThickness = (std::find(req.begin(), req.end(), "Thickness") != req.end()); buildFlowFactor = (std::find(req.begin(), req.end(), "Flow Factor") != req.end()); buildSurfaceVelocity = (std::find(req.begin(), req.end(), "Surface Velocity") != req.end()); buildVelocityRMS = (std::find(req.begin(), req.end(), "Velocity RMS") != req.end()); #endif //Start STK stuff this->coordinates_field = & metaData_->declare_field< VFT >("coordinates"); solution_field = & metaData_->declare_field< VFT >( params_->get<std::string>("Exodus Solution Name", "solution")); #ifdef ALBANY_LCM residual_field = & metaData_->declare_field< VFT >( params_->get<std::string>("Exodus Residual Name", "residual")); #endif #ifdef ALBANY_FELIX if(buildSurfaceHeight) this->surfaceHeight_field = & metaData_->declare_field< SFT >("surface_height"); if(buildTemperature) this->temperature_field = & metaData_->declare_field< SFT >("temperature"); if(buildBasalFriction) this->basalFriction_field = & metaData_->declare_field< SFT >("basal_friction"); if(buildThickness) this->thickness_field = & metaData_->declare_field< SFT >("thickness"); if(buildFlowFactor) this->flowFactor_field = & metaData_->declare_field< SFT >("flow_factor"); if(buildSurfaceVelocity) this->surfaceVelocity_field = & metaData_->declare_field< VFT >("surface_velocity"); if(buildVelocityRMS) this->velocityRMS_field = & metaData_->declare_field< VFT >("velocity_RMS"); #endif stk::mesh::put_field(*this->coordinates_field , metaData_->node_rank() , metaData_->universal_part(), numDim_); stk::mesh::put_field(*solution_field , metaData_->node_rank() , metaData_->universal_part(), neq_); #ifdef ALBANY_LCM stk::mesh::put_field(*residual_field , metaData_->node_rank() , metaData_->universal_part() , neq_); #endif #ifdef ALBANY_FELIX if(buildSurfaceHeight) stk::mesh::put_field( *this->surfaceHeight_field , metaData_->node_rank() , metaData_->universal_part()); if(buildTemperature) stk::mesh::put_field( *this->temperature_field , metaData_->element_rank() , metaData_->universal_part()); if(buildBasalFriction) stk::mesh::put_field( *this->basalFriction_field , metaData_->node_rank() , metaData_->universal_part());//*metaData_->get_part("basalside","Mpas Interface")); if(buildThickness) stk::mesh::put_field( *this->thickness_field , metaData_->node_rank() , metaData_->universal_part()); if(buildFlowFactor) stk::mesh::put_field( *this->flowFactor_field , metaData_->element_rank() , metaData_->universal_part()); if(buildSurfaceVelocity) stk::mesh::put_field( *this->surfaceVelocity_field , metaData_->node_rank() , metaData_->universal_part(), neq_); if(buildVelocityRMS) stk::mesh::put_field( *this->velocityRMS_field , metaData_->node_rank() , metaData_->universal_part(), neq_); #endif #ifdef ALBANY_SEACAS stk::io::set_field_role(*this->coordinates_field, Ioss::Field::MESH); stk::io::set_field_role(*solution_field, Ioss::Field::TRANSIENT); #ifdef ALBANY_LCM stk::io::set_field_role(*residual_field, Ioss::Field::TRANSIENT); #endif #ifdef ALBANY_FELIX // ATTRIBUTE writes only once per file, but somehow did not work on restart. //stk::io::set_field_role(*surfaceHeight_field, Ioss::Field::ATTRIBUTE); if(buildSurfaceHeight) stk::io::set_field_role(*this->surfaceHeight_field, Ioss::Field::TRANSIENT); if(buildTemperature) stk::io::set_field_role(*this->temperature_field, Ioss::Field::TRANSIENT); if(buildBasalFriction) stk::io::set_field_role(*this->basalFriction_field, Ioss::Field::TRANSIENT); if(buildThickness) stk::io::set_field_role(*this->thickness_field, Ioss::Field::TRANSIENT); if(buildFlowFactor) stk::io::set_field_role(*this->flowFactor_field, Ioss::Field::TRANSIENT); if(buildSurfaceVelocity) stk::io::set_field_role(*this->surfaceVelocity_field, Ioss::Field::TRANSIENT); if(buildVelocityRMS) stk::io::set_field_role(*this->velocityRMS_field, Ioss::Field::TRANSIENT); #endif #endif // If the problem requests that the initial guess at the solution equals the input node coordinates, // set that here /* if(std::find(req.begin(), req.end(), "Initial Guess Coords") != req.end()){ this->copySTKField(this->coordinates_field, solution_field); } */ this->buildStateStructs(sis); initializeSTKAdaptation(); } template<bool Interleaved> Albany::OrdinarySTKFieldContainer<Interleaved>::~OrdinarySTKFieldContainer() { } template<bool Interleaved> void Albany::OrdinarySTKFieldContainer<Interleaved>::initializeSTKAdaptation() { typedef typename AbstractSTKFieldContainer::IntScalarFieldType ISFT; this->proc_rank_field = & this->metaData->template declare_field< ISFT >("proc_rank"); this->refine_field = & this->metaData->template declare_field< ISFT >("refine_field"); // Processor rank field, a scalar stk::mesh::put_field( *this->proc_rank_field, this->metaData->element_rank(), this->metaData->universal_part()); stk::mesh::put_field( *this->refine_field, this->metaData->element_rank(), this->metaData->universal_part()); #ifdef ALBANY_LCM // Fracture state used for adaptive insertion. // It exists for all entities except cells (elements). this->fracture_state = & this->metaData->template declare_field< ISFT >("fracture_state"); stk::mesh::EntityRank const cell_rank = this->metaData->element_rank(); for (stk::mesh::EntityRank rank = 0; rank < cell_rank; ++rank) { stk::mesh::put_field( *this->fracture_state, rank, this->metaData->universal_part()); } #endif // ALBANY_LCM #ifdef ALBANY_SEACAS stk::io::set_field_role(*this->proc_rank_field, Ioss::Field::MESH); stk::io::set_field_role(*this->refine_field, Ioss::Field::MESH); #ifdef ALBANY_LCM stk::io::set_field_role(*this->fracture_state, Ioss::Field::MESH); #endif // ALBANY_LCM #endif } template<bool Interleaved> void Albany::OrdinarySTKFieldContainer<Interleaved>::fillSolnVector(Epetra_Vector& soln, stk::mesh::Selector& sel, const Teuchos::RCP<Epetra_Map>& node_map) { typedef typename AbstractSTKFieldContainer::VectorFieldType VFT; // Iterate over the on-processor nodes by getting node buckets and iterating over each bucket. stk::mesh::BucketVector all_elements; stk::mesh::get_buckets(sel, this->bulkData->buckets(this->metaData->node_rank()), all_elements); this->numNodes = node_map->NumMyElements(); // Needed for the getDOF function to work correctly // This is either numOwnedNodes or numOverlapNodes, depending on // which map is passed in for(stk::mesh::BucketVector::const_iterator it = all_elements.begin() ; it != all_elements.end() ; ++it) { const stk::mesh::Bucket& bucket = **it; this->fillVectorHelper(soln, solution_field, node_map, bucket, 0); } } template<bool Interleaved> void Albany::OrdinarySTKFieldContainer<Interleaved>::saveSolnVector(const Epetra_Vector& soln, stk::mesh::Selector& sel, const Teuchos::RCP<Epetra_Map>& node_map) { typedef typename AbstractSTKFieldContainer::VectorFieldType VFT; // Iterate over the on-processor nodes by getting node buckets and iterating over each bucket. stk::mesh::BucketVector all_elements; stk::mesh::get_buckets(sel, this->bulkData->buckets(this->metaData->node_rank()), all_elements); this->numNodes = node_map->NumMyElements(); // Needed for the getDOF function to work correctly // This is either numOwnedNodes or numOverlapNodes, depending on // which map is passed in for(stk::mesh::BucketVector::const_iterator it = all_elements.begin() ; it != all_elements.end() ; ++it) { const stk::mesh::Bucket& bucket = **it; this->saveVectorHelper(soln, solution_field, node_map, bucket, 0); } } template<bool Interleaved> void Albany::OrdinarySTKFieldContainer<Interleaved>::saveResVector(const Epetra_Vector& res, stk::mesh::Selector& sel, const Teuchos::RCP<Epetra_Map>& node_map) { typedef typename AbstractSTKFieldContainer::VectorFieldType VFT; // Iterate over the on-processor nodes by getting node buckets and iterating over each bucket. stk::mesh::BucketVector all_elements; stk::mesh::get_buckets(sel, this->bulkData->buckets(this->metaData->node_rank()), all_elements); this->numNodes = node_map->NumMyElements(); // Needed for the getDOF function to work correctly // This is either numOwnedNodes or numOverlapNodes, depending on // which map is passed in for(stk::mesh::BucketVector::const_iterator it = all_elements.begin() ; it != all_elements.end() ; ++it) { const stk::mesh::Bucket& bucket = **it; this->saveVectorHelper(res, residual_field, node_map, bucket, 0); } } template<bool Interleaved> void Albany::OrdinarySTKFieldContainer<Interleaved>::transferSolutionToCoords() { this->copySTKField(solution_field, this->coordinates_field); }
d45e87046624c6eccf306a0824131352d1d0c8fe
435633d9a1bd03ad1c3ce537c654494f1820d084
/core/pmml/BuiltInMath.cpp
259b41e839fc4b504790448d88e06be11c360570
[]
no_license
gsm1011/cppweka
518e6086cf352b24b4b74ec12960b20c5fc2b5a6
ad26add3ef96ec266e4b0982de1987a15c16f7f2
refs/heads/master
2020-05-29T19:05:25.823897
2014-06-26T00:42:40
2014-06-26T00:42:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,397
cpp
BuiltInMath.cpp
/* * 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. */ /* * Arithmetic.java * Copyright (C) 2008 University of Waikato, Hamilton, New Zealand * */ // package weka.core.pmml; // import java.util.ArrayList; // import weka.core.Attribute; // import weka.core.Utils; /** * Built-in function for min, max, sum, avg, log10, * ln, sqrt, abs, exp, pow, threshold, floor, ceil and round. * * @author Mark Hall (mhall{[at]}pentaho{[dot]}com) * @version $Revision 1.0 $ */ class BuiltInMath : public Function { /** * For serialization */ // private static final long serialVersionUID = -8092338695602573652L; /** * Enum for the math functions. */ enum MathFunc { public: MIN ("min") { double eval(double[] args) { return args[Utils.minIndex(args)]; } bool legalNumParams(int num) { return (num > 0); } String[] getParameterNames() { return null; // unbounded number of parameters } }, MAX ("max") { double eval(double[] args) { return args[Utils.maxIndex(args)]; } bool legalNumParams(int num) { return (num > 0); } String[] getParameterNames() { return null; // unbounded number of parameters } }, SUM ("sum") { double eval(double[] args) { return Utils.sum(args); } bool legalNumParams(int num) { return (num > 0); } String[] getParameterNames() { return null; // unbounded number of parameters } }, AVG ("avg") { double eval(double[] args) { return Utils.mean(args); } bool legalNumParams(int num) { return (num > 0); } String[] getParameterNames() { return null; // unbounded number of parameters } }, LOG10 ("log10") { double eval(double[] args) { return Math.log10(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, LN ("ln") { double eval(double[] args) { return Math.log(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, SQRT ("sqrt") { double eval(double[] args) { return Math.sqrt(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, ABS ("abs") { double eval(double[] args) { return Math.abs(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, EXP ("exp") { double eval(double[] args) { return Math.exp(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, POW ("pow") { double eval(double[] args) { return Math.pow(args[0], args[1]); } bool legalNumParams(int num) { return (num == 2); } String[] getParameterNames() { return new String[] {"A", "B"}; } }, THRESHOLD ("threshold") { double eval(double[] args) { if (args[0] > args[1]) { return 1.0; } else { return 0.0; } } bool legalNumParams(int num) { return (num == 2); } String[] getParameterNames() { return new String[] {"A", "B"}; } }, FLOOR ("floor") { double eval(double[] args) { return Math.floor(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, CEIL ("ceil") { double eval(double[] args) { return Math.ceil(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }, ROUND ("round") { double eval(double[] args) { return Math.round(args[0]); } bool legalNumParams(int num) { return (num == 1); } String[] getParameterNames() { return new String[] {"A"}; } }; virtual double eval(double[] args); virtual bool legalNumParams(int num); virtual String[] getParameterNames(); MathFunc(string funcName) { m_stringVal = funcName; } private: final string m_stringVal; public: string toString() { return m_stringVal; } }; /** The function to apply */ protected: MathFunc m_func = MathFunc.ABS; public: /** * Construct a new built-in pmml Math function. * @param func the math function to use */ BuiltInMath(MathFunc func) { m_func = func; m_functionName = m_func.toString(); } /** * Set the structure of the parameters that are expected as input by * this function. This must be called before getOutputDef() is called. * * @param paramDefs the structure of the input parameters * @throws Exception if the number or types of parameters are not acceptable by * this function */ void setParameterDefs(ArrayList<Attribute> paramDefs) throws Exception { m_parameterDefs = paramDefs; if (!m_func.legalNumParams(m_parameterDefs.size())) { throw new Exception("[BuiltInMath] illegal number of parameters for function: " + m_functionName); } } /** * Get the structure of the result produced by this function. * Subclasses must implement. * * @return the structure of the result produced by this function. */ Attribute getOutputDef() { return new Attribute("BuiltInMathResult:" + m_func.toString()); } /** * Returns an array of the names of the parameters expected * as input by this function. May return null if the function * can accept an unbounded number of arguments. * * @return an array of the parameter names (or null if the function * can accept any number of arguments). */ String[] getParameterNames() { return m_func.getParameterNames(); } /** * Get the result of applying this function. * * @param incoming the arguments to this function (supplied in order to match that * of the parameter definitions * @return the result of applying this function. When the optype is * categorical or ordinal, an index into the values of the output definition * is returned. * @throws Exception if there is a problem computing the result of this function */ double getResult(double[] incoming) throws Exception { if (m_parameterDefs == null) { throw new Exception("[BuiltInMath] incoming parameter structure has not been set"); } if (!m_func.legalNumParams(incoming.length)) { throw new Exception("[BuiltInMath] wrong number of parameters!"); } double result = m_func.eval(incoming); return result; } string toString() { string result = m_func.toString() + "("; for (int i = 0; i < m_parameterDefs.size(); i++) { result += m_parameterDefs.get(i).name(); if (i != m_parameterDefs.size() - 1) { result += ", "; } else { result += ")"; } } return result; } };
172ad149bb3b60dd964cee66b5ad7be9e245e329
47947503e858244f47c6b90ba365a959fbce0d9e
/C++ all code/simple inheritance.cpp
de478300734ca22feecca990877f8ef3b81af1ab
[]
no_license
AnowarKabir/C-All-Codes
d4fa293347ee8241bf329f8270f44c29a5dd0e33
58ebc7d01d5b02f588138fe175bad3df6141f700
refs/heads/master
2022-12-24T13:10:14.285725
2020-09-20T17:03:18
2020-09-20T17:03:18
297,123,043
0
0
null
null
null
null
UTF-8
C++
false
false
423
cpp
simple inheritance.cpp
#include<iostream> using namespace std; class info{ int id; public: void getid(){cout<<"press id:-";//cin>>id;cout<<"ID:-"<<id<<endl; } void setid(int a){id=a;} }; class abc{ public: void set(){ cin>>id;} }; class student : public info{ public: void print(){getid();} }; main() { student obj; abc ob; obj.getid(); obj.print(); }
238703870e1bf65a61a97140d1b4de793ad85c18
8a87f5b889a9ce7d81421515f06d9c9cbf6ce64a
/3rdParty/boost/1.78.0/boost/asio/ip/icmp.hpp
d2ea36733166b19642db337107990958f4581c44
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode-public-domain", "JSON", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSD-4-Clause", "Python-2.0", "LGPL-2.1-or-later" ]
permissive
arangodb/arangodb
0980625e76c56a2449d90dcb8d8f2c485e28a83b
43c40535cee37fc7349a21793dc33b1833735af5
refs/heads/devel
2023-08-31T09:34:47.451950
2023-08-31T07:25:02
2023-08-31T07:25:02
2,649,214
13,385
982
Apache-2.0
2023-09-14T17:02:16
2011-10-26T06:42:00
C++
UTF-8
C++
false
false
2,865
hpp
icmp.hpp
// // ip/icmp.hpp // ~~~~~~~~~~~ // // Copyright (c) 2003-2021 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // #ifndef BOOST_ASIO_IP_ICMP_HPP #define BOOST_ASIO_IP_ICMP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/detail/socket_types.hpp> #include <boost/asio/basic_raw_socket.hpp> #include <boost/asio/ip/basic_endpoint.hpp> #include <boost/asio/ip/basic_resolver.hpp> #include <boost/asio/ip/basic_resolver_iterator.hpp> #include <boost/asio/ip/basic_resolver_query.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { namespace ip { /// Encapsulates the flags needed for ICMP. /** * The boost::asio::ip::icmp class contains flags necessary for ICMP sockets. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Safe. * * @par Concepts: * Protocol, InternetProtocol. */ class icmp { public: /// The type of a ICMP endpoint. typedef basic_endpoint<icmp> endpoint; /// Construct to represent the IPv4 ICMP protocol. static icmp v4() BOOST_ASIO_NOEXCEPT { return icmp(BOOST_ASIO_OS_DEF(IPPROTO_ICMP), BOOST_ASIO_OS_DEF(AF_INET)); } /// Construct to represent the IPv6 ICMP protocol. static icmp v6() BOOST_ASIO_NOEXCEPT { return icmp(BOOST_ASIO_OS_DEF(IPPROTO_ICMPV6), BOOST_ASIO_OS_DEF(AF_INET6)); } /// Obtain an identifier for the type of the protocol. int type() const BOOST_ASIO_NOEXCEPT { return BOOST_ASIO_OS_DEF(SOCK_RAW); } /// Obtain an identifier for the protocol. int protocol() const BOOST_ASIO_NOEXCEPT { return protocol_; } /// Obtain an identifier for the protocol family. int family() const BOOST_ASIO_NOEXCEPT { return family_; } /// The ICMP socket type. typedef basic_raw_socket<icmp> socket; /// The ICMP resolver type. typedef basic_resolver<icmp> resolver; /// Compare two protocols for equality. friend bool operator==(const icmp& p1, const icmp& p2) { return p1.protocol_ == p2.protocol_ && p1.family_ == p2.family_; } /// Compare two protocols for inequality. friend bool operator!=(const icmp& p1, const icmp& p2) { return p1.protocol_ != p2.protocol_ || p1.family_ != p2.family_; } private: // Construct with a specific family. explicit icmp(int protocol_id, int protocol_family) BOOST_ASIO_NOEXCEPT : protocol_(protocol_id), family_(protocol_family) { } int protocol_; int family_; }; } // namespace ip } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_IP_ICMP_HPP
d51957235983578068ead4f8b94af39f5e5b94d5
2669aba67d6e6428eaec0aa7e557e0322d648761
/Cpp_beginner_tutorial/12_Nested_arrays_forloops.cpp
eb22bcefd9ff98e148ca25b3588e243666c2acf4
[]
no_license
packetsss/Cpp
e3a17d85f116707a7e3f6836d29e846fb90a05aa
0e958a4db0049a0aace798e3f5385f62dc33dc19
refs/heads/main
2023-04-11T00:15:55.974411
2021-04-13T06:02:59
2021-04-13T06:02:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
12_Nested_arrays_forloops.cpp
# include <iostream> # include <cmath> using namespace std; /* comment block lol lll */ int main() { int grid[3][2] = {{1, 2}, {3, 4}, {5, 6}}; cout << grid[2][0] << endl; // access array for(int i = 0; i < 3; i++) { for(int j = 0; j < 2; j++){ cout << grid[i][j]; } cout << endl; } }
320fe29d8fba7f15e719a3f6847bf228080513e4
6b7bbd247b6468129ccd1277bd95ca3e790a8486
/DotGame/src/applicationModes/applicationmodeintro.cpp
b7f6faecea91512bf613efaf0c3e140c6711ae54
[]
no_license
carloshd86/DotGame
01d5d940a9ec5736d9f77198ad0067d89b63927c
31e9f3228a7d24ac4da52548a0a5c8ff414e455f
refs/heads/master
2020-04-26T03:54:44.605670
2019-04-28T14:46:14
2019-04-28T14:46:14
173,283,123
0
0
null
null
null
null
UTF-8
C++
false
false
3,742
cpp
applicationmodeintro.cpp
#include "globals.h" #include "applicationmodeintro.h" #include "applicationmanager.h" #include "core.h" #include "events.h" #include "fontmanager.h" #include "asserts.h" #include "memorycontrol.h" const float ApplicationModeIntro::TIME_TO_START_GAME = 5.f; // ************************************************* ApplicationModeIntro::ApplicationModeIntro() : mTimeElapsed (0.f), mRestingTime (static_cast<int>(TIME_TO_START_GAME)) { mMusicId.pId = nullptr; } // ************************************************* ApplicationModeIntro::~ApplicationModeIntro() { } // ************************************************* IdMode ApplicationModeIntro::GetId() { return AM_Menu; } // ************************************************* void ApplicationModeIntro::Activate() { GAME_ASSERT(g_pEventManager); GAME_ASSERT(g_pFontManager); m_pProperties = Properties::Instance("messages", g_pApplicationManager->GetLang()); GAME_ASSERT(m_pProperties); g_pEventManager->Register(this, IEventManager::EM_Event::MouseClick); g_pEventManager->Register(this, IEventManager::EM_Event::Quit); g_pWindowManager->InitWindow(); g_pWindowManager->SetBackgroundColor(0.f, 0.f, 0.f); mTimeElapsed = 0.f; mRestingTime = static_cast<int>(TIME_TO_START_GAME); mTitleText = m_pProperties->GetProperty("intro.title.text"); mStartText = m_pProperties->GetProperty("intro.click_start.text"); mAutomaticStartText = m_pProperties->GetProperty("intro.time_start.text"); } // ************************************************* void ApplicationModeIntro::Deactivate() { GAME_ASSERT(g_pEventManager); Properties::RemoveInstance(); m_pProperties = nullptr; g_pEventManager->Unregister(this); if (g_pSoundManager) { g_pSoundManager->UnloadMusic(); } g_pWindowManager->EndWindow(); } // ************************************************* void ApplicationModeIntro::ProcessInput() { GAME_ASSERT(g_pEventManager); g_pEventManager->UpdateEvents(); } // ************************************************* void ApplicationModeIntro::Run(float deltaTime) { mTimeElapsed += deltaTime; if (mTimeElapsed >= TIME_TO_START_GAME) StartLevel(Game::GameLevel::Level1); else if (static_cast<int>(TIME_TO_START_GAME - mTimeElapsed) < mRestingTime - 1) { mRestingTime = static_cast<int>(TIME_TO_START_GAME - mTimeElapsed) + 1; } } // ************************************************* void ApplicationModeIntro::Render() { g_pWindowManager->ClearColorBuffer(0.f, 0.f, 0.f); g_pWindowManager->Render(); g_pFontManager->DrawText(Vec2(100, 100), mTitleText.c_str()); g_pFontManager->DrawText(Vec2(100, 200), mStartText.c_str()); std::string timeMessage = mAutomaticStartText; timeMessage.append(std::to_string(mRestingTime)); g_pFontManager->DrawText(Vec2(100, 300), timeMessage.c_str()); g_pWindowManager->RefreshRendering(); } // ************************************************* bool ApplicationModeIntro::ProcessEvent(const Event& event) { switch (event.GetType()) { case IEventManager::EM_Event::MouseClick: { const EventMouseClick* eMouseClick = dynamic_cast<const EventMouseClick*>(&event); if (EventMouseClick::EMouseButton::Left == eMouseClick->GetMouseButton()) { StartLevel(Game::GameLevel::Level1); } break; } case IEventManager::EM_Event::Quit: { QuitGame(); break; } } return true; } // ************************************************* void ApplicationModeIntro::StartLevel(Game::GameLevel level) { if (g_pSoundManager) { g_pSoundManager->PlaySound(gStartSoundId); } g_gameLevel = level; g_pApplicationManager->SwitchMode(AM_Game); } // ************************************************* void ApplicationModeIntro::QuitGame() { gQuit = true; }
e0a21eadd46ee253ff2a77f1a6754a96a69f11ba
5f42387a94da27090557a73458bd3d1fac20074c
/cpp/study/prototype/ImageType.h
ec10251becb297b3878f34e02bc65bda136be4da
[]
no_license
NicePigg/test_repository_cpp
ad5cf7d94c1c957ece63e0dcc797a140661f2f21
da3f2fa5e662d99d1673e77f791d3a461ea58079
refs/heads/main
2023-07-06T21:49:55.013188
2021-08-11T14:06:45
2021-08-11T14:06:45
328,578,533
0
0
null
null
null
null
UTF-8
C++
false
false
2,970
h
ImageType.h
/*prototype 原型模式 创建未来的class 1.使用场景:由于需求的变化,对象经常剧烈的变化,但他们拥有比较稳定一致的接口clone 2.理论依据:虚函数 3.定义:使用原型实例指定创建对象的种类,然后通过拷贝这些原型来创建新的对象 4.步骤:如何创建易变类的实体对象,(采用原型克隆的方法来做,它使得我们可以非常灵活的动态创建“拥有某些稳定接口”的新对象)所需工作仅仅是注册一个新类的对象(即原型),然后在任何需要的地方Clone(深拷贝)。 5.技法:早绑定->晚绑定 6.变化:需创建新的对象 不变:接口 静态数据成员: 1.初始化在类体外进行,而前面不加static,以免与一般静态变量或对象相混淆。 2.初始化时不加该成员的访问权限控制符private,public等。 3.初始化未赋值。默认为NULL; 多态: 多态可以通过基类的指针或引用访问派生类的对象, 执行派生类中实现的操作(虚函数) */ #ifndef __IMAGETYPE__ #define __IMAGETYPE__ #include <iostream> using namespace std; enum imageType { LSAT,SOPT }; class Image { public: virtual void draw() = 0; static Image* findAndClone(imageType); protected: virtual imageType returnType() = 0; virtual Image* clone() = 0; static void addPrototype(Image* image) { __prototypes[__nextSlot++] = image; } private: static Image* __prototypes[10]; // 静态变量的声明 static int __nextSlot; }; Image* Image::__prototypes[]; // 静态变量类外定义 int Image::__nextSlot; Image* Image::findAndClone(imageType type) { for (int i = 0; i < __nextSlot; i++) { if (__prototypes[i]->returnType() == type) //找到原型,就返回克隆副本 return __prototypes[i]->clone(); } } class LandSatImage :public Image { public: imageType returnType() { return LSAT; } void draw() { cout << "LandSatImage::draw" << __id << endl; } Image *clone() { return new LandSatImage(1); } protected: LandSatImage(int dummy) { // 新增的构造函数 这个dummy没有用到,只是为了区别私有构造函数 __id = __count++; } private: static LandSatImage __LandSatImage; //一个静态的自己 LandSatImage() // 私有的构造函数 { addPrototype(this); } int __id; static int __count; }; LandSatImage LandSatImage::__LandSatImage; int LandSatImage::__count = 1; class SpotImage :public Image { public: imageType returnType() { return SOPT; } void draw() { cout << "SpotImage::draw " << _id << endl; } Image* clone() { return new SpotImage(1); } protected: SpotImage(int dummy) { _id = _count++; } private: SpotImage() { addPrototype(this); } static SpotImage _spotImage; int _id; static int _count; }; SpotImage SpotImage::_spotImage; int SpotImage::_count = 1; #endif
5fed3c72b2a27c1bf3d38ec451c0824cbfdc48cc
7d3be46a494202ef13ea4736f6f57fd553c512ca
/Board.h
712d3caa791789529f18369a51d194d428cb6adf
[]
no_license
marykkwon/Kalah-Game
fe319b197b05f49eea749e1f60b1b3f42dfef65f
0710c7d84fc6caaf26ecd8ff9e6c87bb519227f8
refs/heads/master
2023-08-16T06:55:19.358658
2021-10-02T04:32:52
2021-10-02T04:32:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,465
h
Board.h
#ifndef BOARD_H #define BOARD_H #include "Side.h" class Board { public: Board(int nHoles, int nInitialBeansPerHole); //Construct a Board with the indicated number of holes per side(not counting the pot) and initial number of beans per hole.If nHoles is not positive, act as if it were 1; if nInitialBeansPerHole is negative, act as if it were 0. Board(const Board& other); int holes() const; //Return the number of holes on a side(not counting the pot). int beans(Side s, int hole) const; //Return the number of beans in the indicated hole or pot, or −1 if the hole number is invalid. int beansInPlay(Side s) const; //Return the total number of beans in all the holes on the indicated side, not counting the beans in the pot. int totalBeans() const; //Return the total number of beans in the game, including any in the pots. bool sow(Side s, int hole, Side& endSide, int& endHole); //If the hole indicated by(s, hole) is empty or invalid or a pot, this function returns false without changing anything.Otherwise, it will return true after sowing the beans : the beans are removed from hole(s, hole) and sown counterclockwise, including s's pot if encountered, but skipping s's opponent's pot. The parameters endSide and endHole are set to the side and hole where the last bean was placed. (This function does not make captures or multiple turns; different Kalah variants have different rules about these issues, so dealing with them should not be the responsibility of the Board class.) bool moveToPot(Side s, int hole, Side potOwner); //If the indicated hole is invalid or a pot, return false without changing anything. //Otherwise, move all the beans in hole(s, hole) into the pot belonging to potOwnerand return true. bool setBeans(Side s, int hole, int beans); //If the indicated hole is invalid or beans is negative, //this function returns false without changing anything. //Otherwise, it will return true after setting the number of beans in the indicated hole or pot to the value of the third parameter. //(This may change what beansInPlayand totalBeans return if they are called later.) //This function exists solely so that weand you can more easily test your program : //None of your code that implements the member functions of any class is allowed to call this function directly or indirectly. //(We'll show an example of its use below.) private: int m_nholes; int m_nbeans; int* m_north; int* m_south; }; #endif
c3ece90e7a6882dc2cd597f5ef5ea86a90ede599
3e4fd5153015d03f147e0f105db08e4cf6589d36
/Cpp/SDK/SkillSlotPicker_functions.cpp
af5847349abecf44f1a1ca1426884b69002d3553
[]
no_license
zH4x-SDK/zTorchlight3-SDK
a96f50b84e6b59ccc351634c5cea48caa0d74075
24135ee60874de5fd3f412e60ddc9018de32a95c
refs/heads/main
2023-07-20T12:17:14.732705
2021-08-27T13:59:21
2021-08-27T13:59:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,859
cpp
SkillSlotPicker_functions.cpp
// Name: Torchlight3, Version: 4.26.1 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function SkillSlotPicker.SkillSlotPicker_C.GetIconImage // (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const) // Parameters: // class UAsyncImage* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) class UAsyncImage* USkillSlotPicker_C::GetIconImage() { static auto fn = UObject::FindObject<UFunction>("Function SkillSlotPicker.SkillSlotPicker_C.GetIconImage"); USkillSlotPicker_C_GetIconImage_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SkillSlotPicker.SkillSlotPicker_C.Get_LockNumber_Text_1 // (Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // struct FText ReturnValue (Parm, OutParm, ReturnParm) struct FText USkillSlotPicker_C::Get_LockNumber_Text_1() { static auto fn = UObject::FindObject<UFunction>("Function SkillSlotPicker.SkillSlotPicker_C.Get_LockNumber_Text_1"); USkillSlotPicker_C_Get_LockNumber_Text_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SkillSlotPicker.SkillSlotPicker_C.Get_Lock_Visibility_1 // (Public, HasOutParms, BlueprintCallable, BlueprintEvent, BlueprintPure) // Parameters: // UMG_ESlateVisibility ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash) UMG_ESlateVisibility USkillSlotPicker_C::Get_Lock_Visibility_1() { static auto fn = UObject::FindObject<UFunction>("Function SkillSlotPicker.SkillSlotPicker_C.Get_Lock_Visibility_1"); USkillSlotPicker_C_Get_Lock_Visibility_1_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SkillSlotPicker.SkillSlotPicker_C.GetDescriptionAnchor // (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // class UMenuAnchor* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) class UMenuAnchor* USkillSlotPicker_C::GetDescriptionAnchor() { static auto fn = UObject::FindObject<UFunction>("Function SkillSlotPicker.SkillSlotPicker_C.GetDescriptionAnchor"); USkillSlotPicker_C_GetDescriptionAnchor_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SkillSlotPicker.SkillSlotPicker_C.OnMouseButtonDown // (BlueprintCosmetic, Event, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FGeometry MyGeometry (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData, NoDestructor) // struct FPointerEvent MouseEvent (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm) // struct FEventReply ReturnValue (Parm, OutParm, ReturnParm) struct FEventReply USkillSlotPicker_C::OnMouseButtonDown(const struct FGeometry& MyGeometry, const struct FPointerEvent& MouseEvent) { static auto fn = UObject::FindObject<UFunction>("Function SkillSlotPicker.SkillSlotPicker_C.OnMouseButtonDown"); USkillSlotPicker_C_OnMouseButtonDown_Params params; params.MyGeometry = MyGeometry; params.MouseEvent = MouseEvent; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function SkillSlotPicker.SkillSlotPicker_C.GetSkillHotkey // (Event, Protected, HasOutParms, BlueprintCallable, BlueprintEvent, Const) // Parameters: // class USkillHotkey* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) class USkillHotkey* USkillSlotPicker_C::GetSkillHotkey() { static auto fn = UObject::FindObject<UFunction>("Function SkillSlotPicker.SkillSlotPicker_C.GetSkillHotkey"); USkillSlotPicker_C_GetSkillHotkey_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } } #ifdef _MSC_VER #pragma pack(pop) #endif
de766b3cd2b20d78d32d60e7dd6024e458bb9ff6
0a6cce6391b2a830aa75f417f8f8d65b240ca4c4
/veeamQA/Source.cpp
86d2aec47faf03266e4ab38f1ba92d9e8c6bf389
[]
no_license
Dies1rae/VeeamQA_1
1852402575c160b21f791805f0cb2bb8f950decc
9a5a032a8d664eb0449aae65bdca8a613bab4535
refs/heads/master
2023-07-10T03:09:05.440988
2021-08-16T14:43:21
2021-08-16T14:43:21
395,696,683
0
0
null
null
null
null
UTF-8
C++
false
false
345
cpp
Source.cpp
#include "FileCopier.h" #include <string> #include <iostream> using namespace std; int main(int argc, char* argv[]) { if (argc > 1) { FileCopier main{argv[1]}; try { main.copierGoBrrrr(); } catch (...) { cerr << "Something goes wrong" << endl; } } else { cerr << "Write path to xml file" << endl; return 1; } return 0; }
ad75c53a106b3e8592e6b8d90b4f279372161e49
9fa212528b2427c8a6ad99fb5e8322c2e4995d2c
/tests/ut/tests/base_dictionary_warehouse.cpp
0b7f3f01db0360589acbb158a246581423ccbc92
[]
no_license
T4ng10r/phonetic_number_system
d7b61daa302bd485275da8d7bea88225c43880f3
bea1c0eb501684f28d8b2b4282056f38a2893f6e
refs/heads/master
2020-04-10T03:11:48.414844
2018-02-12T22:05:11
2018-02-12T22:05:11
10,117,675
0
1
null
null
null
null
UTF-8
C++
false
false
4,031
cpp
base_dictionary_warehouse.cpp
#include <boost/test/unit_test.hpp> #include <data/dictionaries/base_dictionary_warehouse.cpp> namespace constants { const std::string test_filepath_1("testdir/testfile"); const std::string test_filepath_2("testdir/testfile.aff"); const std::string test_filepath_3("testdir/testfile.dic"); const std::string codepage_iso("ISO8859-2"); } using namespace boost::filesystem; class base_dictonary_warehouse_tmp : public base_dictionary_warehouse { public: bool openFile(const std::string & filePath) { return true; } void loadFileContent(const std::string &){} void removeDictionary(){} void close_file(){}; std::string get_word_by_index(unsigned int index){return std::string(); } }; class ut_base_dictionary_warehouse_test //: public ::testing::Test { public: ut_base_dictionary_warehouse_test() { } void create_file(const std::string & filepath) { path dir(filepath); create_directory(dir.parent_path().string()); std::ofstream ofs(filepath.c_str(), std::ofstream::out); ofs.close(); } void delete_file(const std::string & filepath) { remove(filepath); } void create_aff_file(const std::string & filepath) { create_file(filepath); std::ofstream ofs(filepath.c_str(), std::ofstream::out); ofs<<constants::file_codepage_keyword<<" "<<constants::codepage_iso<<std::endl; ofs.close(); } public: base_dictonary_warehouse_tmp uut; }; BOOST_FIXTURE_TEST_SUITE(dictionaries, ut_base_dictionary_warehouse_test) BOOST_AUTO_TEST_CASE(prepare_aff_file_empty) //TEST_F(ut_base_dictionary_warehouse_test, prepare_aff_file_empty) { //Given std::string filepath; BOOST_CHECK(filepath.empty()); //When prepare_aff_file_path(filepath); //Then BOOST_CHECK(filepath.empty()); } //TEST_F(ut_base_dictionary_warehouse_test, BOOST_AUTO_TEST_CASE(prepare_aff_file_fake_path) { //Given create_file(constants::test_filepath_1); std::string filepath(constants::test_filepath_1); //When prepare_aff_file_path(filepath); //Then BOOST_CHECK(filepath.empty()); delete_file(constants::test_filepath_1); } //TEST_F(ut_base_dictionary_warehouse_test, BOOST_AUTO_TEST_CASE(prepare_aff_file_aff_path) { //Given create_file(constants::test_filepath_2); std::string filepath(constants::test_filepath_2); //When prepare_aff_file_path(filepath); //Then BOOST_CHECK_EQUAL(filepath, constants::test_filepath_2); delete_file(constants::test_filepath_2); } //TEST_F(ut_base_dictionary_warehouse_test, BOOST_AUTO_TEST_CASE(prepare_aff_file_without_ext) { //Given create_file(constants::test_filepath_1); create_file(constants::test_filepath_2); std::string filepath(constants::test_filepath_1); //When prepare_aff_file_path(filepath); //Then BOOST_CHECK_EQUAL(filepath, constants::test_filepath_2); delete_file(constants::test_filepath_2); delete_file(constants::test_filepath_1); } //TEST_F(ut_base_dictionary_warehouse_test, BOOST_AUTO_TEST_CASE(prepare_aff_file_dic_ext) { //Given create_file(constants::test_filepath_2); create_file(constants::test_filepath_3); std::string filepath(constants::test_filepath_3); //When prepare_aff_file_path(filepath); //Then BOOST_CHECK_EQUAL(filepath, constants::test_filepath_2); delete_file(constants::test_filepath_2); delete_file(constants::test_filepath_3); } //TEST_F(ut_base_dictionary_warehouse_test, BOOST_AUTO_TEST_CASE(get_file_codepage_empty_path) { //Given std::string filepath; //When std::string file_codepage = uut.get_file_codepage(filepath); //Then BOOST_CHECK(file_codepage.empty()); } //TEST_F(ut_base_dictionary_warehouse_test, BOOST_AUTO_TEST_CASE(get_file_codepage_proper_file) { //Given std::string filepath(constants::test_filepath_2); create_file(constants::test_filepath_1); create_aff_file(filepath); //When std::string file_codepage = uut.get_file_codepage(filepath); //Then BOOST_CHECK(!file_codepage.empty()); BOOST_CHECK_EQUAL(file_codepage, constants::codepage_iso); delete_file(constants::test_filepath_1); delete_file(constants::test_filepath_2); } BOOST_AUTO_TEST_SUITE_END()
6bc6e8e02d7831d27ae93adbcbf8b9c3da73b33b
05892598bd81445db6c290a073fcbade49c517f6
/new.ino
a8daddbe7a389d26e79759b93c29db5c46dbb553
[]
no_license
imaicom/AutoFeeder
8eaec5552c5a5dabe56f103428e2ae11b595c7fd
73cd1885bea2140dcede7bc576ef3f3be00a1c63
refs/heads/master
2020-03-28T21:44:17.863315
2018-10-02T07:49:26
2018-10-02T07:49:26
149,178,114
0
0
null
null
null
null
UTF-8
C++
false
false
7,160
ino
new.ino
#include <math.h> #include <LiquidCrystal.h> LiquidCrystal lcd = LiquidCrystal(12, 11, 10, 5, 4, 3, 1); int m = 0; // Menu transition int k = 4; // Item selection( Feed ) int before_k = 2; int i = 0; // Encoder count int before_i = 0; int j = 0; // Acceleration encoder count int p1 = 0; // Decimal 1 digit setting int before_p1 = 0; int skip_p1 = 0; // Return 1 decimal place setting int erase_setting = 0; void setup() { pinMode( A2, INPUT_PULLUP ); // Menu button pinMode( A3, INPUT_PULLUP ); // Encoder button pinMode( 2, INPUT_PULLUP ); // Encoder count pinMode( A5, INPUT_PULLUP ); // Rotational direction of encoder pinMode( 8, OUTPUT ); // Motor rotation direction pinMode( 9, OUTPUT ); // Motor rotation pulse digitalWrite( 8, 0 ); digitalWrite( 9, 0); attachInterrupt(0, counta, FALLING); //INT0 - D2 pin } void loop() { char buf[30]; int z, zz; if (m != 1) { if (!digitalRead(A2)) { delay(10); while (!digitalRead(A2)); m = 0; k = 4; }; }; // if (m != 1) if (m == 0) { lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(" Feed "); sprintf(buf,"%+1d",p1); lcd.print(buf); lcd.print(" cnt"); lcd.setCursor(0, 1); lcd.print(" Fwd Back"); lcd.blink(); m = 1; }; // if (m == 0) if (m == 1) { if (k == 2)lcd.setCursor(1, 1); if (k == 3)lcd.setCursor(8, 1); if (k == 4)lcd.setCursor(1, 0); if (k == 5)lcd.setCursor(8, 0); if (!digitalRead(A3)) { delay(10); while (!digitalRead(A3)); m = k; } if (before_k != k) beep(); before_k = k; if (!digitalRead(A2)) { erase_setting++; delay(1); if (erase_setting > 1000) { // Press and hold for 1 second or longer lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(" Erase "); lcd.setCursor(0, 1); lcd.print(" all settings"); hi_beep(); delay(100); hi_beep(); delay(100); hi_beep(); delay(100); m = 0; k = 4; p1 = 0; i = 0; }; } else erase_setting = 0; }; // if (m == 1) if (m == 2) { hi_beep(); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(" Fwd "); lcd.setCursor(0, 1); lcd.print(" "); m = 22; }; // if (m == 2) if (m == 22) { delay(10); do { if (!digitalRead(A3)) { digitalWrite( 8, 1); digitalWrite( 9, 0); delay(2); digitalWrite( 8, 1); digitalWrite( 9, 1); delay(2); } } while (digitalRead(A2)); // menu m = 0; }; // if (m == 22) if (m == 3) { hi_beep(); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(" "); lcd.setCursor(0, 1); lcd.print(" Back "); m = 33; }; // if (m == 3) if (m == 33) { delay(10); do { if (!digitalRead(A3)) { digitalWrite( 8, 0); digitalWrite( 9, 0); delay(2); digitalWrite( 8, 0); digitalWrite( 9, 1); delay(2); } } while (digitalRead(A2)); // menu m = 0; }; // if (m == 33) if (m == 4) { hi_beep(); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(" Feed "); lcd.setCursor(0, 1); lcd.print(" "); m = 44; }; // if (m == 4) if (m == 44) { delay(10); do { if (!digitalRead(A3)) { delay(10); while (!digitalRead(A3)); hi_beep(); delay(500); hi_beep(); delay(500); if (i > 0) { // Feed forward + Consider the blade thickness if (i >= 2) z = int((float)i/(98.63/100.0*11.0 * M_PI / 360.0 * 1.8)); else z = int((float)i/(98.63/100.0*11.0 * M_PI / 360.0 * 1.8)); z=z+p1; lcd.setCursor(12, 0); sprintf(buf, "%4d", z); lcd.print(buf); digitalWrite( 8, 1); for (zz = 1; zz <= z; zz++) { digitalWrite( 9, 0); delay(3); digitalWrite( 9, 1); delay(3); if (!digitalRead(A2)) break; // Emergency stop if (!digitalRead(A3)) break; // Emergency stop }; } else if(i < 0){ // Negative feed z = int((float)(-i) / (98.63/100.0*11.0 * M_PI / 360.0 * 1.8))+p1; z=z+p1; lcd.setCursor(12, 0); sprintf(buf, "%4d", z); lcd.print(buf); digitalWrite( 8, 0); for (zz = -1; zz <= z; zz++) { digitalWrite( 9, 0); delay(3); digitalWrite( 9, 1); delay(3); if (!digitalRead(A2)) break; // Emergency stop if (!digitalRead(A3)) break; // Emergency stop }; if (!digitalRead(A2)) break; }; while (!digitalRead(A3)); }; lcd.setCursor(0, 1); if (i >= 2) sprintf(buf, "%4d+1.5mm %+1dcnt ", i, p1); else sprintf(buf, "%4dmm %+1dcnt ", i, p1); lcd.print(buf); j++; if (j > 29) j = 29; // Acceleration processing of encoder if (before_i != i) beep(); before_i = i; } while (digitalRead(A2)); // menu m = 0; before_k = 0; }; // if (m == 44) if (m == 5) { hi_beep(); lcd.begin(16, 2); lcd.setCursor(0, 0); lcd.print(" "); skip_p1 = p1; m = 55; }; // if (m == 5) if (m == 55) { delay(10); do { lcd.setCursor(8, 0); sprintf(buf,"%+1d cnt",p1); lcd.print(buf); if (!digitalRead(A3)) { delay(10); while (!digitalRead(A3)); hi_beep(); k = 4; break; } } while (digitalRead(A2)); // menu if (!digitalRead(A2)) p1 = skip_p1; m = 0; }; // if (m == 55) } // void loop() void counta() { if (m == 1) { delay(1); if (!digitalRead(A5)) { k++; } else { k--; }; if (k < 2) k = 5; if (k > 5) k = 2; }; if (m == 44) { delay(1); if (!digitalRead(A5)) { if (j < 27) i = ((i + (30 - j)) / 10 * 10); else if (j >= 27) i++; } else { if (j < 27) i = ((i - (30 - j)) / 10 * 10); else if (j >= 27) i--; }; if (i < -1400) i = -1400; if (i > 1400) i = 1400; j = 0; }; if (m == 55) { delay(1); if (!digitalRead(A5)) { p1++; } else { p1--; }; if (p1 < -4) p1 = -4; if (p1 > +4) p1 = +4; if (before_p1 != p1) beep(); before_p1 = p1; }; } // counta() void beep() { int i; for (i = 1; i <= 200; i++) { // digitalWrite( 8, 1); // digitalWrite( 9, 0); delayMicroseconds(100); // digitalWrite( 8, 1); // digitalWrite( 9, 1); delayMicroseconds(100); }; } void hi_beep() { int i; for (i = 1; i <= 100; i++) { // digitalWrite( 8, 1); // digitalWrite( 9, 0); delayMicroseconds(200); // digitalWrite( 8, 1); // digitalWrite( 9, 1); delayMicroseconds(200); }; }