blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
18f7257bd82f5385e532a1d33219fdca8129e513
e7533029e6b737623c11517f77b2f143b2c508a6
/Android/PFCVersion2/proj.winrt/MainPage.xaml.h
e816a125e04c48ef6995906a7262774ad41a0a41
[]
no_license
juaniiton1/PFC
e1593dce6b0d6cb3bec8e18d2c99ee42798c3ebb
1f1cb61d5c806244e48da07a0a0fa99a4b35d5be
refs/heads/master
2021-01-19T03:13:01.328958
2014-03-17T18:07:24
2014-03-17T18:07:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,080
h
/**************************************************************************** Copyright (c) 2010-2013 cocos2d-x.org Copyright (c) Microsoft Open Technologies, Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ // // BlankPage.xaml.h // Declaration of the BlankPage.xaml class. // #pragma once #include "MainPage.g.h" #include "../Classes/AppDelegate.h" namespace PFCVersion2 { /// <summary> /// A DirectX page that can be used on its own. Note that it may not be used within a Frame. /// </summary> [Windows::Foundation::Metadata::WebHostHidden] public ref class MainPage sealed { public: MainPage(); void OnPreviousPressed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); void OnNextPressed(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e); void SaveInternalState(Windows::Foundation::Collections::IPropertySet^ state); void LoadInternalState(Windows::Foundation::Collections::IPropertySet^ state); private: AppDelegate app; }; }
[ "montagut.joan@gmail.com" ]
montagut.joan@gmail.com
408cb323264835f02a0e54ce98e15a7079d6eba8
98932def41d8b42c022be87905733a419c54a169
/details/callbacks.h
0b8d91a0465551714e7373e0e34367f5e477cfd8
[ "LicenseRef-scancode-boost-original" ]
permissive
hwgyy/cpptcl
10e8342cfae3672cbe5538d942483f231bbc4845
c5917b75de5f6fdace6dc2adee24e929961a8570
refs/heads/master
2021-09-13T06:53:51.257193
2018-04-26T07:09:51
2018-04-26T07:09:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,001
h
// Copyright (c) 2011-2012, Wei Song // Copyright (C) 2004-2006, Maciej Sobczak // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // // Note: this file is not supposed to be a stand-alone header template <typename R> class callback0 : public callback_base { typedef R (*functor_type)(); public: callback0(functor_type f) : f_(f) {} virtual void invoke(Tcl_Interp *interp, int, Tcl_Obj * CONST [], policies const &, ClientData) { dispatch<R>::do_dispatch(interp, f_); } private: functor_type f_; }; #define BOOST_PP_ITERATION_LIMITS (1, 9) #define BOOST_PP_FILENAME_1 "preproc/callbacks.hpp" #include BOOST_PP_ITERATE() #undef BOOST_PP_ITERATION_LIMITS #undef BOOST_PP_FILENAME_1
[ "wsong83@gmail.com" ]
wsong83@gmail.com
d2bb78410d8b1596d986d4a01b142ecb820a2df3
5b49e47ace71e6715a6d59e8f7470b30134eca65
/programs/android/project_template/jni/main.cpp
db6febb9618933435c7751ce5cbf09ec123a9c4f
[]
no_license
menezesd/qb64
1515971192955f15f37dd3887bbf82eb130092cc
d7aad9cc49d0f6df3872e01fc72d29e5f682a4f8
refs/heads/master
2020-05-19T22:15:23.413835
2015-07-16T16:39:29
2015-07-16T16:39:29
39,279,462
1
0
null
null
null
null
UTF-8
C++
false
false
231
cpp
#include <jni.h> #include <android/log.h> #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "FreeGLUT", __VA_ARGS__)) #include <EGL/egl.h> #include <GLES/gl.h> #include <GLES/glext.h> #include "c/libqb.cpp"
[ "galleondragon@gmail.com" ]
galleondragon@gmail.com
8c9c7e89967e3d7c6ac855333856a62ac8e77650
b06e32854c1e028a99be9ca70b614a5a8a733067
/archive/kxkm_esp32_sac_v2_002_h_s/do_effet_2.ino
ff9f65a5afe077d9217af2fe15a7da56b0c8c949
[]
no_license
ririfonfon/KXKM_ESP32_SAC_V2
8cd4361337ce20878ace4a7738a8f02a081ea611
503f51c815ab5b5f0e0c992bb5fac924d56bb9d5
refs/heads/master
2021-06-13T06:51:04.525298
2021-03-09T10:04:24
2021-03-09T10:04:24
155,556,347
0
1
null
null
null
null
UTF-8
C++
false
false
5,399
ino
void do_effet_2() { if (pix_mod >= 0 && pix_mod <= 10) { for (int i = 0 ; i < NUM_LEDS_PER_STRIP ; i++) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); }//for i }//pix_mod 0 if (pix_mod >= 11 && pix_mod <= 20) { for (int i = 0 ; i < NUM_LEDS_PER_STRIP ; i++) { if (i >= (pix_pos) && i <= pix_start + (pix_pos)) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } else { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } }//for i }//pix_mod 10 if (pix_mod >= 21 && pix_mod <= 30) { for (int i = 0 ; i < numberOfLed ; i++) { if (i <= NUM_LEDS_PER_STRIP) { if (i >= (pix_pos) && i <= pix_start + (pix_pos)) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } else { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } }//for i }//pix_mod 20 if (pix_mod >= 31 && pix_mod <= 40) { for (int i = 0 ; i < NUM_LEDS_PER_STRIP ; i++) { if (i >= (pix_pos) && i <= pix_start + (pix_pos)) { if (pix_start <= 1) { pix_start_v = 1; } else { pix_start_v = pix_start; } pix_coefi = (((i - pix_pos) * 100) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } else { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } }//for i }//pix_mod 30 if (pix_mod >= 41 && pix_mod <= 50) { ref_pix_pos = (pix_start + pix_pos); for (int i = 0 ; i < NUM_LEDS_PER_STRIP ; i++) { if (i >= (pix_pos) && i <= (pix_start + pix_pos)) { if (pix_start <= 1) { pix_start_v = 1; } else { pix_start_v = pix_start; } pix_coefi = (((pix_pos - ref_pix_pos) * 100) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); ref_pix_pos--; } else { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } }//for i }//pix_mod 40 if (pix_mod >= 51 && pix_mod <= 60) { ref_pix_pos = (pix_start + pix_pos); for (int i = 0 ; i < NUM_LEDS_PER_STRIP ; i++) { if (i >= (pix_pos) && i <= (pix_start + pix_pos)) { if (pix_start <= 1) { pix_start_v = 1; } else { pix_start_v = pix_start; } if (i <= pix_center) { pix_coefi = ((((i - pix_pos + 1)) * 200) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; } else if (i >= pix_center) { pix_coefi = ((((pix_pos - ref_pix_pos)) * 100) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; ref_pix_pos = ref_pix_pos - 2; } if (pix_coef > 1) pix_coef = 1; strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } else { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } }//for i }//pix_mod 50 if (pix_mod >= 61 && pix_mod <= 70) { for (int i = 0 ; i < numberOfLed ; i++) { if (i >= (pix_pos) && i <= pix_start + (pix_pos)) { if (pix_start <= 1) { pix_start_v = 1; } else { pix_start_v = pix_start; } pix_coefi = (((i - pix_pos) * 100) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; if (i <= NUM_LEDS_PER_STRIP) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } else { if (i <= NUM_LEDS_PER_STRIP) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } }//for i }//pix_mod 60 if (pix_mod >= 71 && pix_mod <= 80) { ref_pix_pos = (pix_start + pix_pos); for (int i = 0 ; i < numberOfLed ; i++) { if (i >= (pix_pos) && i <= (pix_start + pix_pos)) { if (pix_start <= 1) { pix_start_v = 1; } else { pix_start_v = pix_start; } pix_coefi = (((pix_pos - ref_pix_pos) * 100) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; ref_pix_pos--; if (i <= NUM_LEDS_PER_STRIP) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } else { if (i <= NUM_LEDS_PER_STRIP) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } }//for i }//pix_mod 70 if (pix_mod >= 81 && pix_mod <= 90) { ref_pix_pos = (pix_start + pix_pos); for (int i = 0 ; i < numberOfLed ; i++) { if (i >= (pix_pos) && i <= (pix_start + pix_pos)) { if (pix_start <= 1) { pix_start_v = 1; } else { pix_start_v = pix_start; } if (i <= pix_center) { pix_coefi = ((((i - pix_pos + 1)) * 200) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; } else if (i >= pix_center) { pix_coefi = ((((pix_pos - ref_pix_pos)) * 100) / pix_start_v) * 0.01; pix_coef = pix_coefi * pix_coefi; ref_pix_pos = ref_pix_pos - 2; } if (pix_coef > 1) pix_coef = 1; if (i <= NUM_LEDS_PER_STRIP) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } else { if (i <= NUM_LEDS_PER_STRIP) { strands[0]->pixels[i] = pixelFromRGBW(sr, sg, sb, sw); } } }//for i }//pix_mod 80 }//do_effet_2 ruban 2
[ "ririfonfon10@gmail.com" ]
ririfonfon10@gmail.com
22cb22ece094066c65b78444008252bc0373487a
d0fb746f1be49b7c0de6b9b6c15d034329cd23dc
/Game Engine Esqueleto/PhysicsDynamicsMng.cpp
25061e1258207dc1ec1f71e0d77994913b36131b
[]
no_license
EdgarSAE/Game-Engine-Esqueleto
23b471eacef9fd217af743c8acf1038c7dcb3e1f
501a8c1de748159b6630c5d13f57ac8b4c6a8be0
refs/heads/master
2021-01-11T03:35:28.088813
2016-09-23T06:24:28
2016-09-23T06:24:28
68,940,999
0
0
null
2016-09-23T06:24:29
2016-09-22T16:33:35
C++
UTF-8
C++
false
false
578
cpp
#include "PhysicsDynamicsMng.h" PhysicsDynamicsMng& PhysicsDynamicsMng::instance() { static PhysicsDynamicsMng *instance = new PhysicsDynamicsMng(); return *instance; } PhysicsDynamicsMng::PhysicsDynamicsMng() {} void PhysicsDynamicsMng::Start() { std::cout << "Start Physics Dynamics Manager\n"; } void PhysicsDynamicsMng::Run() { //std::cout << "Running Physics Dynamics Manager\n"; std::call_once(flag1, []() { std::cout << "Running Physics Dynamics Manager\n"; }); } void PhysicsDynamicsMng::Shutdown() { std::cout << "Shutting down Physics Dynamics Manager\n"; }
[ "edgar.alonso@saei.mx" ]
edgar.alonso@saei.mx
0df33e9dfc0e67867a735470c56e57e6e242e168
6e23eb6f1ced65abe6178d5379f78af7ffc53f1f
/gorodlangtokens.cpp
c2b5e8dee4930e484246d733e05d163f2b0cd821
[]
no_license
Childcity/SimpleLanguageParser
0cba111d7bc1fa3e2254a5e391885b456f2f14a4
5ced5e40163baaec4c1d13b44a412c19688b89b0
refs/heads/master
2020-04-21T12:28:27.261508
2019-09-26T21:45:10
2019-09-26T21:45:10
169,563,282
0
0
null
null
null
null
UTF-8
C++
false
false
29
cpp
#include "gorodlangtokens.h"
[ "skulazkiy@gmail.com" ]
skulazkiy@gmail.com
39ddc96c4f6de5c03def288a20843b6e9723f8d0
1ffd95f3829428bbd0b79292c93c08c3d7ff7498
/expression.h
db002730255b90afa22d2066c915b3e634275619
[]
no_license
adamwojs/tautology
dde040423d1386684ac6db1b7b3626bd83ba8039
d3ea0fbac05a8a08dbaaeacdcf4afb72b0563b6f
refs/heads/master
2021-01-15T19:44:57.070512
2014-09-03T12:14:49
2014-09-03T12:14:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,156
h
#ifndef EXPRESSION_H #define EXPRESSION_H #include <map> #include <istream> #include <vector> #include "scanner.h" class Expression { public: // Symbols table std::map<char, bool> symbols; Expression(std::istream& input); // Return expression value bool calculate(); // Print expression converted to RPN void printf_rpn(); protected: Scanner scanner; // Expression in RPN std::vector<int> output; private: // Parse expression void parse(); /** * EXPR -> LOW_EXPR LOW_EXPR_PRIM * LOW_EXPR -> HIGH_EXPR HIGH_EXPR_PRIM * LOW_EXPR_PRIM -> '&' LOW_EXPR LOW_EXPR_PRIM * -> '|' LOW_EXPR LOW_EXPR_PRIM * -> Epsilon * HIGH_EXPR -> VALUE HIGH_EXPR_PRIM * HIGH_EXPR_PRIM -> '=>' HIGH_EXPR HIGH_EXPR_PRIM * -> '<=>' HIGH_EXPR HIGH_EXPR_PRIM * -> Epsilon */ // Low Priority Expression void parse_low_expr(); // High Priority Expression: IMP and IFF void parse_high_expr(); // Value void parse_value(); }; #endif // EXPRESSION_H
[ "adam@wojs.pl" ]
adam@wojs.pl
4bcb7760952937c4da4dd23751ed8faf125bd003
96ca579d05d4ba34c43f60a9fbd8e54f50729902
/Gyver_Ambilight/Gyver_Ambilight.ino
aa3c7252e2a703ce0adfe19828fdd28aad2b84d7
[]
no_license
AlexGyver/Arduino_Ambilight
19b1a0a222d8755e9e0590a5742031d904aefaf3
68f135c45c15a11777786dd6da18ab0aafd584d2
refs/heads/master
2023-08-31T11:14:24.383330
2022-03-26T05:30:22
2022-03-26T05:30:22
101,448,788
150
86
null
2023-08-27T15:30:24
2017-08-25T23:11:55
C++
UTF-8
C++
false
false
3,860
ino
/* Управление лентой на WS2812 с компьютера + динамическая яркость Создано не знаю кем, допилил и перевёл AlexGyver http://alexgyver.ru/ 2017 */ //----------------------НАСТРОЙКИ----------------------- #define NUM_LEDS 98 // число светодиодов в ленте #define DI_PIN 13 // пин, к которому подключена лента #define start_flashes 0 // проверка цветов при запуске (1 - включить, 0 - выключить) #define auto_bright 1 // автоматическая подстройка яркости от уровня внешнего освещения (1 - включить, 0 - выключить) #define max_bright 255 // максимальная яркость (0 - 255) #define min_bright 50 // минимальная яркость (0 - 255) #define bright_constant 500 // константа усиления от внешнего света (0 - 1023) // чем МЕНЬШЕ константа, тем "резче" будет прибавляться яркость #define coef 0.9 // коэффициент фильтра (0.0 - 1.0), чем больше - тем медленнее меняется яркость //----------------------НАСТРОЙКИ----------------------- int new_bright, new_bright_f; unsigned long bright_timer; #define serialRate 115200 // скорость связи с ПК uint8_t prefix[] = {'A', 'd', 'a'}, hi, lo, chk, i; // кодовое слово Ada для связи #include <FastLED.h> CRGB leds[NUM_LEDS]; // создаём ленту void setup() { FastLED.addLeds<WS2812, DI_PIN, GRB>(leds, NUM_LEDS); // инициализация светодиодов // вспышки красным синим и зелёным при запуске (можно отключить) if (start_flashes) { LEDS.showColor(CRGB(255, 0, 0)); delay(500); LEDS.showColor(CRGB(0, 255, 0)); delay(500); LEDS.showColor(CRGB(0, 0, 255)); delay(500); LEDS.showColor(CRGB(0, 0, 0)); } Serial.begin(serialRate); Serial.print("Ada\n"); // Связаться с компом } void loop() { if (auto_bright) { // если включена адаптивная яркость if (millis() - bright_timer > 100) { // каждые 100 мс bright_timer = millis(); // сброить таймер new_bright = map(analogRead(6), 0, bright_constant, min_bright, max_bright); // считать показания с фоторезистора, перевести диапазон new_bright = constrain(new_bright, min_bright, max_bright); new_bright_f = new_bright_f * coef + new_bright * (1 - coef); LEDS.setBrightness(new_bright_f); // установить новую яркость } } for (i = 0; i < sizeof prefix; ++i) { waitLoop: while (!Serial.available()) ;; if (prefix[i] == Serial.read()) continue; i = 0; goto waitLoop; } while (!Serial.available()) ;; hi = Serial.read(); while (!Serial.available()) ;; lo = Serial.read(); while (!Serial.available()) ;; chk = Serial.read(); if (chk != (hi ^ lo ^ 0x55)) { i = 0; goto waitLoop; } memset(leds, 0, NUM_LEDS * sizeof(struct CRGB)); for (uint8_t i = 0; i < NUM_LEDS; i++) { byte r, g, b; // читаем данные для каждого цвета while (!Serial.available()); r = Serial.read(); while (!Serial.available()); g = Serial.read(); while (!Serial.available()); b = Serial.read(); leds[i].r = r; leds[i].g = g; leds[i].b = b; } FastLED.show(); // записываем цвета в ленту }
[ "beragumbo@ya.ru" ]
beragumbo@ya.ru
2935632a9aed550c0324f48eaa9e471b4ac3d2c8
77f0a8e61cc3e6d9ad0039505fb09337e6d1a670
/NetworkSession/NetworkSessionRecvDataThread.cpp
98151f6eb536bc599b6db525c963c42f37f9a0ca
[]
no_license
SilentLee/Classes
b0c012db38940516c512d8c5185d38093e24529c
6470fe45e73f672c932aec8bd4b2ea27d0cce16b
refs/heads/master
2021-09-04T13:25:06.614107
2018-01-19T05:48:18
2018-01-19T05:48:18
110,434,008
0
0
null
null
null
null
UTF-8
C++
false
false
13,499
cpp
#include "NetworkSession.h" #include "OutputProc.h" VOID CNetworkSession::RecvData() { DWORD protocol = 0; BYTE packet[MAX_BUFFER_LENGTH] = {0, }; DWORD packetLength = 0; while (true) { memset(packet, 0, sizeof(packet)); int result = Recv((char*)mPacketBuffer, sizeof(mPacketBuffer), 0); if (result <= 0) { printf("Server Disconnect\n"); break; } mRemainLength = mRemainLength + result; //printf("\nSize of data received from Server is %d", result); if(GetPacket(protocol, packet, packetLength)) { printf("GetPacket success\n"); } log("##Analize Result:\n"); switch(protocol) { // 对战协议处理 case PT_BATTLE_SEARCH_ROOM_SUCC_U: onPT_BATTLE_SEARCH_ROOM_SUCC_U(packet); break; case PT_BATTLE_START_GAME_M: onPT_BATTLE_START_GAME_M(packet); break; case PT_BATTLE_ARRANGE_WEAPON_SUCC_M: onPT_ARRANGE_WEAPON_SUCC_M(packet); break; case PT_BATTLE_UPDATE_SITUATION_M: onPT_BATTLE_UPDATE_SITUATION_M(packet); break; // // 用户登录或注册消息 // // 1. PT_VISITOR_REGIST_SUCC_U // case PT_VISITOR_REGIST_SUCC_U: // onPT_VISITOR_REGIST_SUCC_U(packet); // break; // // // 2. PT_USER_NAME_REGIST_SUCC_U // case PT_USER_NAME_REGIST_SUCC_U: // onPT_USER_NAME_REGIST_SUCC_U(packet); // break; // // // 3. PT_BIND_ACCOUNT_REGIST_SUCC_U // case PT_BIND_ACCOUNT_REGIST_SUCC_U: // onPT_BIND_ACCOUNT_REGIST_SUCC_U(packet); // break; // // // 4. PT_CELLPHONE_NO_REGIST_SUCC_U // case PT_CELLPHONE_NO_REGIST_SUCC_U: // onPT_CELLPHONE_NO_REGIST_SUCC_U(packet); // break; // // // 5. PT_USER_NAME_LOGIN_SUCC_U // case PT_USER_NAME_LOGIN_SUCC_U: // onPT_USER_NAME_LOGIN_SUCC_U(packet); // break; // // // 6. PT_BIND_ACCOUNT_LOGIN_SUCC_U // case PT_BIND_ACCOUNT_LOGIN_SUCC_U: // onPT_BIND_ACCOUNT_LOGIN_SUCC_U(packet); // break; // // // 7. PT_CELLPHONE_NO_LOGIN_SUCC_U // case PT_CELLPHONE_NO_LOGIN_SUCC_U: // onPT_CELLPHONE_NO_LOGIN_SUCC_U(packet); // break; // // // 8. PT_VISITOR_DEFAULT_LOGIN_SUCC_U // case PT_VISITOR_DEFAULT_LOGIN_SUCC_U: // onPT_VISITOR_DEFAULT_LOGIN_SUCC_U(packet); // break; // // // 用户信息更改 // // 12. PT_ADD_NICKNAME_SUCC_U // case PT_ADD_NICKNAME_SUCC_U: // onPT_ADD_NICKNAME_SUCC_U(packet); // break; // // // 13. PT_ADD_BIND_ACCOUNT_SUCC_U // case PT_ADD_BIND_ACCOUNT_SUCC_U: // onPT_ADD_BIND_ACCOUNT_SUCC_U(packet); // break; // // // 14. PT_ADD_CELLPHONE_NO_SUCC_U // case PT_ADD_CELLPHONE_NO_SUCC_U: // onPT_ADD_CELLPHONE_NO_SUCC_U(packet); // break; // // // 15. PT_UPDATE_PASSWORD_SUCC_U // case PT_UPDATE_PASSWORD_SUCC_U: // onPT_UPDATE_PASSWORD_SUCC_U(packet); // break; // // // 16. PT_UPDATE_NICKNAME_SUCC_U // case PT_UPDATE_NICKNAME_SUCC_U: // onPT_UPDATE_NICKNAME_SUCC_U(packet); // break; // // // 17. PT_UPDATE_CELLPHONE_NO_SUCC_U // case PT_UPDATE_CELLPHONE_NO_SUCC_U: // onPT_UPDATE_CELLPHONE_NO_SUCC_U(packet); // break; // // // 18. PT_UPDATE_RECORD_SUCC_U // case PT_UPDATE_RECORD_SUCC_U: // onPT_UPDATE_RECORD_SUCC_U(packet); // break; // // // 用户交易信息 // case PT_BUY_COINS_SUCC_U: // onPT_BUY_COINS_SUCC_U(packet); // break; // // case PT_BUY_DIAMONDS_SUCC_U: // onPT_BUY_DIAMONDS_SUCC_U(packet); // break; // // case PT_BUY_CARDS_SUCC_U: // onPT_BUY_CARDS_SUCC_U(packet); // break; // // case PT_OPEN_SUPPLY_CHEST_SUCC_U: // onPT_OPEN_SUPPLY_CHEST_SUCC_U(packet); // break; // // case PT_LOAD_CARDS_ON_SALE_SUCC_U: // onPT_LOAD_CARDS_ON_SALE_SUCC_U(packet); // break; // // case PT_UPGRADE_CARD_SUCC_U: // onPT_UPGRADE_CARD_SUCC_U(packet); // break; // // case PT_ACQUIRE_CHEST_SUCC_U: // onPT_ACQUIRE_CHEST_SUCC_U(packet); // break; // // // 二人死斗 游戏房间搜索信息 // case PT_DOUBLE_BATTLE_SEARCH_ROOM_SUCC_U: // onPT_DOUBLE_BATTLE_SEARCH_ROOM_SUCC_U(packet); // break; // // // 二人死斗 更新玩家列表 // case PT_DOUBLE_BATTLE_UPDATE_USER_LIST_M: // onPT_DOUBLE_BATTLE_UPDATE_USER_LIST_M(packet); // break; // // // 二人死斗 游戏开始 // case PT_DOUBLE_BATTLE_START_GAME_M: // onPT_DOUBLE_BATTLE_START_GAME_M(packet); // break; // // // 二人死斗 游戏结束消息 // case PT_DOUBLE_BATTLE_END_M: // onPT_DOUBLE_BATTLE_END_M(packet); // break; // // // 二人死斗 插入飞机 成功 // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_PLANE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_PLANE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_PLANE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_PLANE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_PLANE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_PLANE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_STEALTH_PLANE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_STEALTH_PLANE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_STEALTH_PLANE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_STEALTH_PLANE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_STEALTH_PLANE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_STEALTH_PLANE_SUCC_M(packet); // break; // // // 二人死斗 插入飞机 成功 // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_PLANE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_PLANE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_PLANE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_PLANE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_PLANE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_PLANE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_STEALTH_PLANE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_STEALTH_PLANE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_STEALTH_PLANE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_STEALTH_PLANE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_STEALTH_PLANE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_STEALTH_PLANE_FAIL_U(packet); // break; // // // 处理从服务器传来的武器布设消息 // case PT_DOUBLE_BATTLE_INSERT_SENIOR_ANTI_STEALTH_RADAR_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_ANTI_STEALTH_RADAR_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_ANTI_STEALTH_RADAR_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_ANTI_STEALTH_RADAR_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_ANTI_STEALTH_RADAR_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_ANTI_STEALTH_RADAR_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_MISSILE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_MISSILE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_MISSILE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_MISSILE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_MISSILE_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_MISSILE_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_RADAR_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_RADAR_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_RADAR_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_RADAR_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_RADAR_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_RADAR_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_CANNONBALL_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_CANNONBALL_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_CANNONBALL_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_CANNONBALL_SUCC_M(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_CANNONBALL_SUCC_M: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_CANNONBALL_SUCC_M(packet); // break; // // // 插入武器失败消息 // case PT_DOUBLE_BATTLE_INSERT_SENIOR_ANTI_STEALTH_RADAR_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_ANTI_STEALTH_RADAR_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_ANTI_STEALTH_RADAR_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_ANTI_STEALTH_RADAR_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_ANTI_STEALTH_RADAR_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_ANTI_STEALTH_RADAR_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_MISSILE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_MISSILE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_MISSILE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_MISSILE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_MISSILE_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_MISSILE_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_RADAR_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_RADAR_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_RADAR_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_RADAR_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_RADAR_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_RADAR_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_SENIOR_CANNONBALL_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_SENIOR_CANNONBALL_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_MIDDLE_CANNONBALL_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_MIDDLE_CANNONBALL_FAIL_U(packet); // break; // // case PT_DOUBLE_BATTLE_INSERT_JUNIOR_CANNONBALL_FAIL_U: // onPT_DOUBLE_BATTLE_INSERT_JUNIOR_CANNONBALL_FAIL_U(packet); // break; // // // // 二人死斗 游戏时间等 定时更新信息 // case PT_DOUBLE_BATTLE_UPDATE_U: // onPT_DOUBLE_BATTLE_UPDATE_U(packet); // break; // //// // 从服务器端接收飞机被击毁的消息 //// case PT_DOUBLE_BATTLE_PLANE_DOWN_M: //// onPT_DOUBLE_BATTLE_PLANE_DOWN_M(packet); //// break; } } Close(); }
[ "1378180704@qq.com" ]
1378180704@qq.com
9a680cbb01c0e40ff39d326c43ec995a3f219e90
d9c1c4ae9e03d9e2782d8a898e518a3b8bf6ff58
/NewGDTS/GDTS_MICROVIDEO/Microvideo/Microvideo/comm/src/VNMP_datawork_app.cpp
1b2b6bb09d5ef0ebb3dceb3904526c94916fdae2
[]
no_license
zhaohongqiang/Codes
753166b168a081d679e474ad0b0062d463a06096
f28c860a65afc81ba19d1f49e1edbda719f44f03
refs/heads/master
2021-03-04T16:11:47.299084
2019-11-02T06:12:39
2019-11-02T06:12:39
null
0
0
null
null
null
null
GB18030
C++
false
false
28,278
cpp
#include "stdafx.h" #include "C2Htype.h" #if 1 #include "../../include/dev_init.h" #include "../include/commapp.h" //#include "../include/command.h" //#include "../include/frame.h" #include "../include/VNMP_datawork_app.h" //#include "../include/data_srv.h" //#include "../include/queuesappl.h" #include "../include/thread.h" //#include "../../led/include/ledlib.h" #include "../../comm/include/commbase.h" #define REQUEST_PERIOD 500 //extern MS_CHAR *g_RecvBuf; //extern MS_CHAR *g_SendBuf; //extern MS_INT32 g_stateInfo; extern CVNMPDlg* Main; /* MS_INT32 GetParamFrmHost(MS_INT32 comid) {//首次主动向HOST发送信息,请求参数 MS_INT32 len,i; MICP_HDR *pmicp_hdr; MS_CHAR msg[DEF_MAX_CHARSTR_LENGHT4]; memset(g_SendBuf,0,sizeof(MICP_HDR)); pmicp_hdr = (MICP_HDR*)(g_SendBuf); pmicp_hdr->size = sizeof(MICP_HDR); pmicp_hdr->dev = DEF_MICP_DEV_BRD; pmicp_hdr->direct = DEF_MICP_DIRECT_BRD_TO_HOST; pmicp_hdr->type = DEF_MICP_TYPE_BRD_GET; pmicp_hdr->devid = g_boardBaseInfo.card_no; pmicp_hdr->body_len = 0x00; pmicp_hdr->seq = g_boardBaseInfo.sequence_id; pmicp_hdr->ext_info = 0x00; pmicp_hdr->ident = DEF_MICP_IDENT_BRD_DM642; sprintf(msg,"发请求参数包 \n"); //LogPrintf(msg,DEF_MSG_PRINT ,0); len = sendComToHostW(comid,(MS_CHAR *)pmicp_hdr,sizeof(MICP_HDR),NULL,0); if(len < 0) return MD_FAILED; //sleep(10); for(i = 0;i<REQUEST_PERIOD;i++) { ms_sleep(10); kick_dog(); len = recvComFrHost(comid,g_RecvBuf,DEF_RECV_BUFFER_LEN); if(len < 0) return MD_FAILED; if(len == 0) continue; sprintf(msg,"获得参数包 \n"); //LogPrintf(msg,DEF_MSG_PRINT ,0); g_RecvBuf[len] = 0; return NetProcessCMD( g_RecvBuf,comid ); } return MD_FAILED; } MS_INT32 SendUpdateToHost(MS_INT32 comid) { MICP_HDR *pmicp_hdr; memset(g_SendBuf,0,sizeof(MICP_HDR)); pmicp_hdr = (MICP_HDR*)(g_SendBuf); pmicp_hdr->dev = DEF_MICP_DEV_BRD; pmicp_hdr->direct = DEF_MICP_DIRECT_BRD_TO_HOST; pmicp_hdr->type = DEF_MICP_TYPE_BRD_UPDATE; pmicp_hdr->devid = g_boardBaseInfo.card_no; pmicp_hdr->seq = g_boardBaseInfo.sequence_id; pmicp_hdr->ext_info = 0x00; pmicp_hdr->ident = DEF_MICP_IDENT_BRD_DM642; pmicp_hdr->none1 = g_boardBaseInfo.none[0];//VERSION_TYPE <<16 | VERSION_EXTENSION ; pmicp_hdr->none2 = VERSION_NUMBER;//VERSION_EXTENSION; //pmicp_hdr->none3 = 0; pmicp_hdr->size = sizeof(MICP_HDR); return sendComToHostW(comid,g_SendBuf,sizeof(MICP_HDR),NULL,0); } MS_INT32 SendRespToHost(MS_INT32 comid) { Audio_Info my_content1; MU_INT8 extradata1[32]; Video_Info my_content2; MU_INT8 extradata2[32]; MICP_BODY_BRD_PARAMS tbrd_param; MICP_HDR *pmicp_hdr; MS_INT32 ndx,nOffset=0; memset(g_SendBuf,0,sizeof(MICP_HDR)); pmicp_hdr = (MICP_HDR*)(g_SendBuf); pmicp_hdr->dev = DEF_MICP_DEV_BRD; pmicp_hdr->direct = DEF_MICP_DIRECT_BRD_TO_HOST; pmicp_hdr->type = DEF_MICP_TYPE_RESP | DEF_MICP_TYPE_BRD_SET; pmicp_hdr->devid = g_boardBaseInfo.card_no; pmicp_hdr->seq = g_boardBaseInfo.sequence_id; pmicp_hdr->ext_info = 0x00; pmicp_hdr->ident = DEF_MICP_IDENT_BRD_DM642; pmicp_hdr->none1 = g_boardBaseInfo.chaoping; pmicp_hdr->size = sizeof(MICP_HDR); nOffset += sizeof(MICP_HDR); for(ndx=0;ndx<DEF_BOARD_MAX_CHANNELS;ndx++) { if(g_vInfo[ndx].channel_id == 0) break; get_video_content(&my_content2,g_vInfo[ndx].params,extradata2); memset(&tbrd_param,0,sizeof(tbrd_param)); strcpy(tbrd_param.flags,"MICROVIDEO"); tbrd_param.size = sizeof(tbrd_param)-sizeof(MU_INT8*)+sizeof(Video_Info)+my_content2.ExtraDataSize-sizeof(MU_INT8*);//?hao tbrd_param.type = DEF_MICP_BODY_MEDIA_VIDEO; tbrd_param.channel = ndx+1;//g_vInfo[ndx].channel_id;//hao memcpy(g_SendBuf+nOffset,&tbrd_param,sizeof(MICP_BODY_BRD_PARAMS)-sizeof(MU_INT8*)); nOffset += sizeof(MICP_BODY_BRD_PARAMS)-sizeof(MU_INT8*); memcpy(g_SendBuf+nOffset,&my_content2,sizeof(Video_Info)-sizeof(MU_INT8*)); nOffset += sizeof(Video_Info)-sizeof(MU_INT8*); memcpy(g_SendBuf+nOffset,&extradata2,my_content2.ExtraDataSize); nOffset += my_content2.ExtraDataSize; //printf("video param size = %x\n",tbrd_param.size); } for(ndx=0;ndx<DEF_BOARD_MAX_CHANNELS;ndx++) { if(g_aInfo[ndx].channel_id == 0) break; get_audio_content(&my_content1,ndx,extradata1); memset(&tbrd_param,0,sizeof(tbrd_param)); strcpy(tbrd_param.flags,"MICROVIDEO"); tbrd_param.size = sizeof(tbrd_param)-sizeof(MU_INT8*)+sizeof(Audio_Info)+my_content1.ExtraDataSize-sizeof(MU_INT8*);//?hao tbrd_param.type = DEF_MICP_BODY_MEDIA_AUDIO; tbrd_param.channel = ndx+1;//g_aInfo[ndx].channel_id;//hao memcpy(g_SendBuf+nOffset,&tbrd_param,sizeof(MICP_BODY_BRD_PARAMS)-sizeof(MU_INT8*)); nOffset += sizeof(MICP_BODY_BRD_PARAMS)-sizeof(MU_INT8*); memcpy(g_SendBuf+nOffset,&my_content1,sizeof(Audio_Info)-sizeof(MU_INT8*)); nOffset += sizeof(Audio_Info)-sizeof(MU_INT8*); memcpy(g_SendBuf+nOffset,&extradata1,my_content1.ExtraDataSize); nOffset += my_content1.ExtraDataSize; //printf("audio param size = %x\n",tbrd_param.size); } pmicp_hdr->body_len = nOffset-sizeof(*pmicp_hdr); pmicp_hdr->size = nOffset; { MS_CHAR msg[64]; sprintf(msg,"send (SendRespToHost) packet size = %d\n",nOffset) ; //LogPrintf(msg,DEF_MSG_PRINT,0); } return sendComToHostW(comid,g_SendBuf,nOffset,NULL,0); } */ /* MU_INT32 sendDataFrmBufW(MS_INT32 comid,MU_INT32 channel,MU_INT8 *send_buf) { FrameOut tframeOut; MU_INT32 nlenght,len; MICP_HDR *pMicp_hdr = (MICP_HDR*)send_buf; MICP_BODY_BRD_VIDEO *pmicp_body_head = (MICP_BODY_BRD_VIDEO*)(send_buf+sizeof(MICP_HDR)); if(MD_OK != readDataFrmBuf(channel,&tframeOut)) return MD_OK; memset(pMicp_hdr,0,sizeof(*pMicp_hdr)); memset(pmicp_body_head,0,sizeof(*pmicp_body_head)); pmicp_body_head->channel = tframeOut.rtmpPackets.m_nChannel; pmicp_body_head->timstamp = tframeOut.timeStamp; pmicp_body_head->keyframe = tframeOut.keyframe; pmicp_body_head->none[0] = tframeOut.rtmpPackets.m_nInfoField[0]; pmicp_body_head->none[1] = tframeOut.rtmpPackets.m_nInfoField[1]; pmicp_body_head->none[2] = tframeOut.rtmpPackets.m_nInfoField[2]; pmicp_body_head->none[3] = tframeOut.rtmpPackets.m_nInfoField[3]; pMicp_hdr->dev = DEF_MICP_DEV_BRD; pMicp_hdr->direct = DEF_MICP_DIRECT_BRD_TO_HOST; pMicp_hdr->type = tframeOut.rtmpPackets.m_packetType; pMicp_hdr->body_len = tframeOut.Outlen + sizeof(MICP_BODY_BRD_VIDEO)-sizeof(MS_CHAR *); pMicp_hdr->seq = g_boardBaseInfo.sequence_id; pMicp_hdr->ext_info = 0x00;//? pMicp_hdr->devid = g_boardBaseInfo.card_no; pMicp_hdr->ident = DEF_MICP_IDENT_BRD_DM642;//DM642(作为子卡) pMicp_hdr->none1 = g_boardBaseInfo.chaoping; pMicp_hdr->size = pMicp_hdr->body_len + sizeof(*pMicp_hdr); nlenght = sizeof(MICP_HDR)+sizeof(MICP_BODY_BRD_VIDEO)-sizeof(MS_CHAR *); //if (tframeOut.Outlen<=0 || tframeOut.Outlen>0x4000) // printf("-------------index:%d---buffsize:%08x---frameType:%d------\n",channel ,tframe.outputSize,tframe.frameType); if (tframeOut.Outlen>DEF_SEND_BUGGER_LEN-nlenght) { //LogPrintf("Frame is too larger than send buffer\n",DEF_MSG_PRINT,0); return MD_FAILED; } len = sendComToHostW(comid,(MS_CHAR*)send_buf,nlenght,tframeOut.pOut,tframeOut.Outlen); //if (channel == 0 && 0x1000<(MU_INT32)tframeOut.Outlen) // printf("index:%d,Send Size =%08x,frameSize = %08x,result =%08x\n",channel,nlenght+tframeOut.Outlen,tframeOut.Outlen,len ); if(len == (nlenght+tframeOut.Outlen)) { releaseReadBuf(channel); //#define DEBUG_TEST #ifdef DEBUG_TEST { static MU_INT32 num = 0; MS_CHAR msg[64]; sprintf(msg,"send %d packet size = %d\n",num++,len) ; //LogPrintf(msg,DEF_MSG_PRINT,0); } #endif } return len; } */ MU_INT32 sendFrmBufToServer(MU_INT32 nChannel,MU_INT8 *send_buf) { // FrameOut tframeOut; MU_INT32 len; MS_CHAR msg[DEF_MAX_CHARSTR_LENGHT2]; MU_INT32 comid = MD_INVALID; MS_CHAR tempaddr[20]; //if(MD_OK != readDataFrmBuf(nChannel,&tframeOut)) // return MD_OK; //if (tframeOut.Outlen>DEF_SEND_BUGGER_LEN-nlenght) //{ // printf("Frame is too larger than send buffer\n"); // return MD_FAILED; //} //sprintf(tempaddr,"%d.%d.%d.%d",tframeOut.ipAddr & 0xFF,tframeOut.ipAddr>>8 & 0xFF,tframeOut.ipAddr>>16 & 0xFF,tframeOut.ipAddr>>24); int nPort=10000; sprintf(tempaddr,"192.168.0.58"); char pOut[1024]="11"; int Outlen=1024; if(MD_OK != openNewSession((MS_INT32*)&comid,tempaddr,nPort)) { //sprintf(msg,"ERROR:connect %s:%d error\n",tempaddr,tframeOut.nPort); ////LogPrintf(msg,DEF_MSG_PRINT|DEF_MSG_SAVE,0); return MD_FAILED; } if(comid == MD_INVALID) return MD_FAILED; len = sendComToHostIm(comid,NULL,0,(MS_CHAR*)pOut,Outlen); if(len == (Outlen)) { MS_INT32 rtn = MD_OK; rtn = checkHumanResponse(comid); //if(rtn != MD_OK) // return MD_FAILED; //releaseReadBuf(nChannel); //yellow_light(0x01); //#define DEBUG_TEST #ifdef DEBUG_TEST { //MS_CHAR msg[64]; static MU_INT32 nTimes = 0; sprintf(msg,"SEND %d packet size = %d of %d\n",nTimes++,len,nChannel); //LogPrintf(msg,DEF_MSG_PRINT,0); } #endif } if( comid != MD_INVALID ) { closeSession(&comid); comid = MD_INVALID; return MD_OK; } return MD_OK; } #define DEF_STR_CONTEN_LENGTH "Content-Length:" #if 1 MS_INT32 parseHttpHead(MS_CHAR *const buf,MS_INT32 *pLen) { MICP_HDR *pTmp = (MICP_HDR *)buf; if(pTmp->dev != 0x03)//"转码服务器" 和 "拉流程序" 通讯 { TRACE("parseHttpHead:pTmp->dev != 0x03\n"); goto leave; } if(pTmp->direct != 0x01)// "转码服务器" ==>"拉流程序" { TRACE("parseHttpHead:pTmp->direct != 0x01\n"); goto leave; } if(pTmp->type != 0x01)//请求参数 { TRACE("parseHttpHead:pTmp->type != 0x01\n"); goto leave; } if(pTmp->size - pTmp->body_len !=sizeof(MICP_HDR)) { TRACE("parseHttpHead:ppTmp->size - pTmp->body_len !=sizeof-MICP_HDR\n"); goto leave; } *pLen=pTmp->body_len; return MD_OK; leave: return MD_FAILED; } #else MS_INT32 parseHttpHead(MS_CHAR *const buf,MS_INT32 *pLen) { MS_INT32 rtn = MD_OK; MS_CHAR *pkey; pkey = strstr(buf,DEF_STR_CONTEN_LENGTH); if(pkey != NULL) { *pLen = atoi(pkey+strlen(DEF_STR_CONTEN_LENGTH)); } else { *pLen = 0; return MD_FAILED; } return rtn; } #endif MS_INT32 recvHttpHead(MS_INT32 s,MS_CHAR *pBuf,MS_INT32 maxLen) { MS_INT32 tmpLen = 0; MS_INT32 rtn = MD_OK; MS_CHAR *pKeyBuf; MS_CHAR msg[DEF_MAX_CHARSTR_LENGHT2]; #if 1 while(tmpLen < maxLen) { rtn = readDataFrmCommW(s,(MU_CHAR*)(pBuf+tmpLen),maxLen-tmpLen,SOCKET_TCP_MODE,DEF_COMM_READ_WAITTIME_W,1); if(rtn < 0) { m_Log.Add("recvHttpHead:readDataFrmCommW fail tmpLen[%d],maxLen[%d]\n",tmpLen,maxLen); TRACE("recvHttpHead:readDataFrmCommW fail tmpLen[%d],maxLen[%d]\n",tmpLen,maxLen); return MD_FAILED; } tmpLen += rtn; } return MD_OK; #else while(1) { rtn = readDataFrmCommW(s,(MU_CHAR*)(pBuf+tmpLen),1,SOCKET_TCP_MODE,DEF_COMM_READ_WAITTIME_W,1); if(rtn < 0) { sprintf(msg,"recvHttpHead:readDataFrmCommW fail \n"); m_Log.Add(msg); return MD_FAILED; } tmpLen += rtn; if(tmpLen >= (maxLen)) { sprintf(msg,"recvHttpHead:tmpLen[%d] >= maxLen[%d] \n",tmpLen,maxLen); m_Log.Add(msg); return MD_FAILED; } // pKeyBuf = strstr(pBuf, "\r\n\r\n"); // if(pKeyBuf != NULL) // { // sprintf(msg,"recvHttpHead:strstr fail \n"); // m_Log.Add(msg); // return MD_OK; // } } #endif return rtn; } MS_INT32 checkHumanResponse(MS_INT32 s) { MS_INT32 rtn = MD_OK; MS_CHAR buf[DEF_BUFFER_LENGTH_1K],*dataBuf=NULL; MS_INT32 nLen = 0; memset(buf,0,DEF_BUFFER_LENGTH_1K); rtn = recvHttpHead(s,buf,DEF_BUFFER_LENGTH_1K); if(rtn != MD_OK) { printf("ERROR: checkHumanResponse -> recvHttpHead \n"); return rtn; } rtn = parseHttpHead(buf,&nLen); if(rtn != MD_OK || nLen == 0) { printf("ERROR: checkHumanResponse -> parseHttpHead \n"); return rtn; } dataBuf = (MS_CHAR*)malloc(nLen*sizeof(MS_CHAR)); memset(dataBuf,0,nLen); rtn = readDataFrmCommW(s,(MU_CHAR*)dataBuf,nLen,SOCKET_TCP_MODE,DEF_COMM_READ_WAITTIME_W,1); if(rtn < 0) { printf("\nERROR: checkHumanResponse->readDataFrmCommW error\n"); return rtn; } //rtn = parseHumanCountContent(dataBuf,nLen); //if(rtn != MD_OK) //{ // printf("ERROR: checkHumanResponse is lawless \n"); // return rtn; //} return rtn; } MS_INT32 checkMetricsResponse(MS_INT32 s) { MS_INT32 rtn = MD_OK; MS_CHAR *pkey; MS_CHAR buf[DEF_BUFFER_LENGTH_1K],*dataBuf=NULL; MS_INT32 nLen = 0; memset(buf,0,DEF_BUFFER_LENGTH_1K); rtn = recvHttpHead(s,buf,DEF_BUFFER_LENGTH_1K); if(rtn != MD_OK) { printf("ERROR: checkMetricsResponse -> recvHttpHead \n"); return rtn; } pkey = strstr(buf,"HTTP/1.0 200 OK"); if(pkey == NULL) rtn = MD_FAILED; return rtn; } MU_INT32 sendStateToServer(MU_INT8 *pBuf1,MS_INT32 len1,MU_INT32 *pBuf2,MS_INT32 len2,MS_CHAR *pIp,MS_INT32 port) { MS_INT32 len; MU_INT32 s = MD_INVALID; MS_CHAR msg[DEF_MAX_CHARSTR_LENGHT2]; if(MD_OK != openNewSession((MS_INT32*)&s,pIp,port)) { sprintf(msg,"ERROR:connect %s:%d error\n",pIp,port); //LogPrintf(msg,DEF_MSG_PRINT|DEF_MSG_SAVE,0); return MD_FAILED; } len = sendComToHostIm(s,(MS_CHAR*)pBuf1,len1,(MS_CHAR*)pBuf2,len2); if(len == (len1+len2)) { MS_INT32 rtn = MD_OK; rtn = checkMetricsResponse(s); }else { } if( s != MD_INVALID ) { closeSession(&s); s = MD_INVALID; } return MD_OK; } #include "./xml/include/xmlnode.h" #include "./xml/include/xmlparse.h" #define MAX_LEN 256 #define MAX_LEN_MIN 4*1024 #define MAX_ITEM_SIZE 20 MS_INT32 parseGDContent(MS_CHAR*pXmlBuf) { #if 0 if(NULL != strstr(pXmlBuf,"ok")) { // Main->m_MicrovideoParams.nPort=10000; // Main->m_MicrovideoParams.PubName="TEST_JC"; // Main->m_MicrovideoParams.ServerIP="192.168.100.113"; Main->m_MicrovideoParams.SrcUrl="http://10.20.90.90:8080/CD2"; Main->m_MicrovideoParams.StreamNumber=0; return MD_OK; } #endif int rt; CString resultStr="",tmpStr,serverStr; DEV_VNMP_PARAMS tmpVNMP; XMLNODE *root = NULL; XMLNODE *subroot = NULL; XMLNODE *node = NULL,*chNode=NULL; XML xml; CString CH; rt = f_xmlparse_init(&xml, (const char*)pXmlBuf); if (rt != 0) { m_Log.Add("xml解析错误,xml结构体初始化失败!"); rt = 400; goto leaveOut; } if(NULL == xml.root) { m_Log.Add("xml解析错误,无效的XML文件!"); rt = 400; goto leaveOut; } if (strcmp(xml.root->name, "Command") != 0) { m_Log.Add("xml解析错误,未能找到Command节点!"); rt = 400; goto leave; } root = xml.root; node = f_xmlnode_sch_elem_ext(root, "serverip", MAX_LEN); if(node == NULL) { m_Log.Add("xml解析错误,未能找到serverip节点!\n"); rt = 400; goto leave; } else { //m_MicrovideoParams.ServerIP = node->data; strcpy(tmpVNMP.m_devInfo.m_dstIp,node->data); //m_Log.Add("解析到的serverip: %s",pubserverip); } #if 0 node = f_xmlnode_sch_elem_ext(root, "company", MAX_LEN); if(node == NULL || atoi(node->data)!=3) { m_Log.Add("xml解析错误,未能找到company节点,或者company节点内容不是hk == 4!\n"); rt = 400; goto leave; } #endif subroot = f_xmlnode_sch_elem(root, "vnmp"); // subroot = f_xmlnode_sch_elem(root, "microvideo"); if(subroot==NULL) { m_Log.Add("xml解析错误,未能找到vnmp节点!"); rt = 400; goto leave; } else { m_Log.Add("开始解析VNMP的XML!"); node = f_xmlnode_sch_elem_ext(subroot, "ip", MAX_LEN); if (node != NULL) { //tmpVNMP.ServerIP=node->data; strcpy(tmpVNMP.m_proxyIp,node->data); //m_Log.Add("解析到的ip:%s",tmpIp); } else { m_Log.Add("xml解析错误,未能找到ip节点!"); rt = 400; goto leave; } node = f_xmlnode_sch_elem_ext(subroot, "port", MAX_LEN); if (node != NULL) { //tmpVNMP.nPort=atoi(node->data); tmpVNMP.m_proxyPort = atoi(node->data); //m_Log.Add("解析到的port:%s",tmpPort); } else { m_Log.Add("xml解析错误,未能找到port节点!"); rt = 400; goto leave; } node = f_xmlnode_sch_elem_ext(subroot, "user", MAX_LEN); if (node != NULL) { //tmpVNMP.SrcUrl = node->data; strcpy(tmpVNMP.m_userName,node->data); //m_Log.Add("解析到的url:%s",tmpSource); } else { m_Log.Add("xml解析错误,未能找到user节点!"); rt = 400; goto leave; } node = f_xmlnode_sch_elem_ext(subroot, "passwd", MAX_LEN); if (node != NULL) { //tmpVNMP.SrcUrl = node->data; strcpy(tmpVNMP.m_passWord,node->data); //m_Log.Add("解析到的url:%s",tmpSource); } else { m_Log.Add("xml解析错误,未能找到passwd节点!"); rt = 400; goto leave; } node = f_xmlnode_sch_elem_ext(subroot, "channel", MAX_LEN); if (node != NULL) { //tmpVNMP.nPort=atoi(node->data); //tmpVNMP.m_playChn = atoi(node->data); strcpy(tmpVNMP.m_cameraId,node->data); //m_Log.Add("解析到的port:%s",tmpPort); } else { m_Log.Add("xml解析错误,未能找到channel节点!"); rt = 400; goto leave; } } chNode = f_xmlnode_sch_elem_ext(root, "ch", MAX_LEN);// if (chNode != NULL) { CH = chNode->data; if(atoi(CH)>=g_maxLiveNum) { int ntmp = atoi(CH); ntmp = ntmp%g_maxLiveNum; CH.Format("%d",ntmp); } // Main->m_MicrovideoParams.StreamNumber=atoi(CH); rt=MD_OK; m_Log.Add("解析到的ch: %s",CH); } else { m_Log.Add("xml解析错误,ch节点的值为空!"); rt = 400; goto leave; } strcpy(Main->m_devParams.m_proxyIp,tmpVNMP.m_proxyIp); Main->m_devParams.m_proxyPort = tmpVNMP.m_proxyPort; strcpy(Main->m_devParams.m_userName,tmpVNMP.m_userName); strcpy(Main->m_devParams.m_passWord,tmpVNMP.m_passWord); strcpy(Main->m_devParams.m_cameraId,tmpVNMP.m_cameraId); leave: f_xmlnode_del(&xml); leaveOut: return rt; } MS_INT32 checkGDServerResponse(MS_INT32 s) { MS_INT32 rtn = MD_OK; MS_CHAR buf[DEF_BUFFER_LENGTH_1K],*dataBuf=NULL; MS_INT32 nLen = 0; memset(buf,0,DEF_BUFFER_LENGTH_1K); rtn = recvHttpHead(s,buf,sizeof(MICP_HDR)); if(rtn != MD_OK) { TRACE("checkGDServerResponse:recvHttpHead fail buf[%s]\n",buf); m_Log.Add("checkGDServerResponse:recvHttpHead fail buf[%s]\n",buf); return MD_FAILED; } // m_Log.Add("checkGDServerResponse:buf[%s]",buf); rtn = parseHttpHead(buf,&nLen); if(rtn != MD_OK || nLen == 0) { TRACE("checkGDServerResponse:parseHttpHead fail buf[%s]\n",buf); return MD_FAILED; } TRACE("checkGDServerResponse:parseHttpHead nLen[%d]\n",nLen); dataBuf = (MS_CHAR*)malloc(nLen*sizeof(MS_CHAR)+1); memset(dataBuf,0,nLen*sizeof(MS_CHAR)+1); rtn = readDataFrmCommW(s,(MU_CHAR*)dataBuf,nLen,SOCKET_TCP_MODE,DEF_COMM_READ_WAITTIME_W,1); if(rtn < 0) { TRACE("checkGDServerResponse:readDataFrmCommW fail \n"); goto leave; } rtn = parseGDContent(dataBuf); if(rtn != MD_OK) { TRACE("checkGDServerResponse:parseGDContent fail \n"); goto leave; }else{ goto done; } leave: if(dataBuf) { free(dataBuf); } return MD_FAILED; done: if(dataBuf) { free(dataBuf); } return MD_OK; } MU_INT32 sendRequireToServer(MU_INT8 nDevId) { MS_INT32 len; MU_INT32 s = MD_INVALID; MS_INT32 len1=sizeof(MICP_HDR); MU_INT32 *pBuf2=NULL; MS_INT32 len2=0; // MS_CHAR *pIp="192.168.0.58"; MS_CHAR *pIp=g_ip; MS_INT32 port=g_port; if(MD_OK != openNewSession((MS_INT32*)&s,pIp,port)) { m_Log.Add("sendRequireToServer:openNewSession connect %s:%d error\n",pIp,port); TRACE("sendRequireToServer:openNewSession connect %s:%d error\n",pIp,port); return MD_FAILED; } // TRACE("sendRequireToServer:openNewSession connect %s:%d suc\n",pIp,port); MICP_HDR sMicpHdr; memset(&sMicpHdr,0,sizeof(MICP_HDR)); //pmicp_hdr = (MICP_HDR*)(&SendBufHead); len = 0; sMicpHdr.size = sizeof(MICP_HDR)+len; sMicpHdr.dev = 0x03;//"转码服务器" 和 "拉流程序" 通讯 sMicpHdr.direct = DEF_MICP_DIRECT_BRD_TO_HOST;//"拉流程序" ==> "转码服务器" sMicpHdr.type = 0x01;//请求参数 sMicpHdr.devid = nDevId;//reversed sMicpHdr.body_len = len; sMicpHdr.seq = 0;//reversed sMicpHdr.ext_info = 0x00;//reversed sMicpHdr.ident = 0x00003001;//拉流子程序 sMicpHdr.none1 =0;//reversed sMicpHdr.none2 =0;//reversed len = sendComToHostW(s,(MS_CHAR*)&sMicpHdr,sizeof(MICP_HDR),(MS_CHAR*)pBuf2,len2); if(len == (len1+len2)) { MS_INT32 rtn = MD_OK; rtn = checkGDServerResponse(s); if(rtn == MD_OK) { if( s != MD_INVALID ) { closeSession(&s); s = MD_INVALID; } return MD_OK; }else{ TRACE("sendRequireToServer:checkGDServerResponse fail socket[%d]\n",s); m_Log.Add("sendRequireToServer:checkGDServerResponse fail socket[%d]",s); goto leave; } }else { TRACE("sendRequireToServer:sendComToHostW fail len[%d]\n",len); m_Log.Add("sendRequireToServer:sendComToHostW fail len[%d]\n",len); goto leave; } leave: if( s != MD_INVALID ) { closeSession(&s); s = MD_INVALID; } return MD_FAILED; } MS_INT32 FormatFrameHead(MS_CHAR* dst,MU_INT8 devid,MU_INT32 bodyLen) {//首次主动向HOST发送信息,请求参数 MS_INT32 len; MICP_HDR *pmicp_hdr; MS_CHAR msg[DEF_MAX_CHARSTR_LENGHT4]; MICP_HDR SendBufHead; memset(&SendBufHead,0,sizeof(MICP_HDR)); pmicp_hdr = (MICP_HDR*)(&SendBufHead); pmicp_hdr->size = sizeof(MICP_HDR); pmicp_hdr->dev = DEF_MICP_DEV_BRD; pmicp_hdr->direct = DEF_MICP_DIRECT_BRD_TO_HOST; pmicp_hdr->type = DEF_MICP_TYPE_BRD_ADJUST; pmicp_hdr->devid = devid; pmicp_hdr->body_len = bodyLen; pmicp_hdr->seq = 0x00; pmicp_hdr->ext_info = 0x00; pmicp_hdr->ident = DEF_MICP_IDENT_BRD_DM642; memcpy(dst,(MS_CHAR*)pmicp_hdr,sizeof(MICP_HDR)); return MD_OK; } static int nTimess=0; static MU_INT32 fdClient=MD_INVALID; MU_INT32 sendDataToServer(MU_INT8 devId)//MU_INT8 *pBuf1,MS_INT32 len1,MU_INT32 *pBuf2,MS_INT32 len2,MS_CHAR *pIp,MS_INT32 port) { MS_INT32 len; // MU_INT32 s = MD_INVALID; MS_CHAR tempaddr[20]; MyAvFrame *m_Frame=NULL; //MS_CHAR *pIp="192.168.100.114"; //MS_CHAR *pIp="192.168.0.58"; MS_CHAR *pIp=g_ip; MS_INT32 port=g_port; //MU_INT32 dd; //sprintf(tempaddr,"%d.%d.%d.%d",pIp & 0xFF,pIp>>8 & 0xFF,pIp>>16 & 0xFF,pIp>>24); if(fdClient==MD_INVALID) { if(MD_OK != openNewSession((MS_INT32*)&fdClient,pIp,port)) //if(MD_OK != openNewSession((MS_INT32*)&s,"192.168.0.15",8888)) { m_Log.Add("sendDataToServer:openNewSession %s:%d error\n",pIp,port); return MD_FAILED; } } // m_Frame=NULL; Main->m_streamlock.Lock(); if (Main->p_YuvArray.GetSize()>0) { m_Frame=Main->p_YuvArray.ElementAt(0); Main->p_YuvArray.RemoveAt(0); } Main->m_streamlock.Unlock(); if (NULL!=m_Frame)//从模板CArray获取到了视频数据 { MICP_HDR sMicpHdr; memset(&sMicpHdr,0,sizeof(MICP_HDR)); //pmicp_hdr = (MICP_HDR*)(&SendBufHead); len = (m_Frame->i_height*m_Frame->i_width)*3/2; sMicpHdr.size = sizeof(MICP_HDR)+len; sMicpHdr.dev = 0x03; sMicpHdr.direct = DEF_MICP_DIRECT_BRD_TO_HOST; sMicpHdr.type = DEF_MICP_TYPE_BRD_SET; sMicpHdr.devid = devId; sMicpHdr.body_len = len; sMicpHdr.seq = nTimess++; sMicpHdr.ext_info = 0x00; sMicpHdr.ident = 0x00003001; sMicpHdr.none1 =m_Frame->i_width; sMicpHdr.none2 =m_Frame->i_height; // len = sendComToHostW(fdClient,(MS_CHAR*)&sMicpHdr,sizeof(MICP_HDR), (MS_CHAR*)m_Frame->p_data,(m_Frame->i_height*m_Frame->i_width)*3/2); if(len == (m_Frame->i_height*m_Frame->i_width)*3/2 + sizeof(MICP_HDR)) { //TRACE("sendDataToServer:len suc\n"); if(m_Frame) delete m_Frame; }else { TRACE("sendDataToServer:sendComToHostW fail,len[%d]\n",len); m_Log.Add("sendDataToServer:sendComToHostW fail,len[%d]\n",len); if( fdClient != MD_INVALID ) { closeSession(&fdClient); fdClient = MD_INVALID; } if(m_Frame) delete m_Frame; return MD_FAILED; } }else{ return MD_NODATA; } //if( fdClient != MD_INVALID ) //{ // closeSession(&fdClient); // fdClient = MD_INVALID; //} return MD_OK; } /* MU_INT32 sendStateInfo(MS_INT32 Comid)//,DSP_STAT *pdsp_stat { MICP_HDR tMicp_hdr; MS_INT32 bFlag; BOARDINFO bi ; memset(&tMicp_hdr,0,sizeof(tMicp_hdr)); memset(&bi,0,sizeof(bi)); bi.code = MAKE_SX_XR_EXT(XR_GINF,(XR_DEV>>16)| (g_boardBaseInfo.card_no & 0xFF) , 3, g_stateInfo & 0x1FFF); bi.gtime = GetBoardTimeSec(); //dequeue_sq( &bi); //if(bi.code == 0) // return MD_OK; tMicp_hdr.dev = DEF_MICP_DEV_BRD; tMicp_hdr.direct = DEF_MICP_DIRECT_BRD_TO_HOST; tMicp_hdr.type = DEF_MICP_TYPE_BRD_WARN;//DEF_MICP_TYPE_BRD_PING; tMicp_hdr.body_len = 0;//sizeof(DSP_STAT); tMicp_hdr.seq = g_boardBaseInfo.sequence_id; tMicp_hdr.ext_info = bi.code;//? tMicp_hdr.devid = g_boardBaseInfo.card_no; tMicp_hdr.ident = DEF_MICP_IDENT_BRD_DM642;//DM642(作为子卡) tMicp_hdr.none1 = bi.gtime; tMicp_hdr.size = sizeof(tMicp_hdr) + tMicp_hdr.body_len; //bFlag = SendData( &tMicp_hdr,pdsp_stat,sizeof(MICP_HDR),sizeof(DSP_STAT) ,1 ); bFlag = sendComToHostIm(Comid,(MS_CHAR *)&tMicp_hdr,sizeof(MICP_HDR),NULL,0);//pdsp_stat,sizeof(DSP_STAT) //g_stateInfo = 0 ; if(bFlag == (sizeof(MICP_HDR)))//+sizeof(DSP_STAT) { //#define DEBUG_TEST #ifdef DEBUG_TEST { static MU_INT32 num = 0; MS_CHAR msg[64]; sprintf(msg,"send %d state info time = %u\n",num++,bi.gtime) ; //LogPrintf(msg,DEF_MSG_PRINT,0); } #endif //printf("send status is 0x%x\n",bi.code); } return MD_OK; } */ /* MU_INT32 sendWarnFrmBuf(MS_INT32 Comid) { MICP_HDR tMicp_hdr; MS_INT32 bFlag; BOARDINFO bi ;//必须有初始值,否则会是随机数 memset(&tMicp_hdr,0,sizeof(tMicp_hdr)); memset(&bi,0,sizeof(bi)); dequeue_sq( &bi); if((bi.code&0x1FFF) == 0) return MD_OK; tMicp_hdr.dev = DEF_MICP_DEV_BRD; tMicp_hdr.direct = DEF_MICP_DIRECT_BRD_TO_HOST; tMicp_hdr.type = DEF_MICP_TYPE_BRD_WARN; tMicp_hdr.body_len = 0; tMicp_hdr.seq = g_boardBaseInfo.sequence_id; tMicp_hdr.ext_info = bi.code; tMicp_hdr.devid = g_boardBaseInfo.card_no; tMicp_hdr.ident = DEF_MICP_IDENT_BRD_DM642;//DM642(作为子卡) tMicp_hdr.none1 = bi.gtime; tMicp_hdr.size = sizeof(tMicp_hdr) + tMicp_hdr.body_len; //bFlag = SendData( &tMicp_hdr,pdsp_stat,sizeof(MICP_HDR),sizeof(DSP_STAT) ,1 ); bFlag = sendComToHostIm(Comid,(MS_CHAR *)&tMicp_hdr,sizeof(MICP_HDR),NULL,0);//pdsp_stat,sizeof(DSP_STAT) if(bFlag == (sizeof(MICP_HDR)))//+sizeof(DSP_STAT) { //#define DEBUG_TEST #ifdef DEBUG_TEST { static MU_INT32 num = 0; MS_CHAR msg[64]; sprintf(msg,"send %d state info time = %u\n",num++,bi.gtime) ; //LogPrintf(msg,DEF_MSG_PRINT,0); } #endif } return MD_OK; } */ /* MS_INT32 SendTimeRequest(MS_INT32 comid) {//首次主动向HOST发送信息,请求参数 MS_INT32 len; MICP_HDR *pmicp_hdr; MS_CHAR msg[DEF_MAX_CHARSTR_LENGHT4]; memset(g_SendBuf,0,sizeof(MICP_HDR)); pmicp_hdr = (MICP_HDR*)(g_SendBuf); pmicp_hdr->size = sizeof(MICP_HDR); pmicp_hdr->dev = DEF_MICP_DEV_BRD; pmicp_hdr->direct = DEF_MICP_DIRECT_BRD_TO_HOST; pmicp_hdr->type = DEF_MICP_TYPE_BRD_ADJUST; pmicp_hdr->devid = g_boardBaseInfo.card_no; pmicp_hdr->body_len = 0x00; pmicp_hdr->seq = g_boardBaseInfo.sequence_id; pmicp_hdr->ext_info = 0x00; pmicp_hdr->ident = DEF_MICP_IDENT_BRD_DM642; sprintf(msg,"发送时间校时请求...\n"); //LogPrintf(msg,DEF_MSG_PRINT ,0); len = sendComToHostW(comid,(MS_CHAR *)pmicp_hdr,sizeof(MICP_HDR),NULL,0); if(len < 0) return MD_FAILED; return MD_OK; } */ #endif
[ "jc1402080216@163.com" ]
jc1402080216@163.com
793391dfd36b8bdc69224e8346cc002fb7b4b541
0269cefece8a89f11b313161556cc2cac55e797c
/1/src/ScissorPanelUI.cpp
fa310a86bf48fa250b97cb50084eb332b9351643
[]
no_license
itsachen/CS-4670
aa206bc9597a1460672b6cac50491dca201d6a6e
9c35fae183b3ece0e2a3ad3d52cf9928b1a78f26
refs/heads/master
2020-06-08T08:49:30.301376
2013-04-12T01:48:37
2013-04-12T01:48:37
9,384,269
1
0
null
null
null
null
UTF-8
C++
false
false
5,597
cpp
// generated by Fast Light User Interface Designer (fluid) version 1.0011 #include "ScissorPanelUI.h" inline void ScissorPanelUI::cb_Image_i(Fl_Round_Button*, void*) { imgView->OrigImage(); } void ScissorPanelUI::cb_Image(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_Image_i(o,v); } inline void ScissorPanelUI::cb_contour_i(Fl_Round_Button*, void*) { imgView->Contour(); } void ScissorPanelUI::cb_contour(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_contour_i(o,v); } inline void ScissorPanelUI::cb_Pixel_i(Fl_Round_Button*, void*) { imgView->PixelColor(); } void ScissorPanelUI::cb_Pixel(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_Pixel_i(o,v); } inline void ScissorPanelUI::cb_Cost_i(Fl_Round_Button*, void*) { imgView->CostGraph(); } void ScissorPanelUI::cb_Cost(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_Cost_i(o,v); } inline void ScissorPanelUI::cb_Path_i(Fl_Round_Button*, void*) { imgView->PathTree(); } void ScissorPanelUI::cb_Path(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_Path_i(o,v); } inline void ScissorPanelUI::cb_Minimum_i(Fl_Round_Button*, void*) { imgView->MinPath(); } void ScissorPanelUI::cb_Minimum(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_Minimum_i(o,v); } inline void ScissorPanelUI::cb_expanded_i(Fl_Counter*, void*) { imgView->PartialExpanding(); } void ScissorPanelUI::cb_expanded(Fl_Counter* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_expanded_i(o,v); } inline void ScissorPanelUI::cb_whole_i(Fl_Round_Button*, void*) { imgView->BrushSelection(0); } void ScissorPanelUI::cb_whole(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_whole_i(o,v); } inline void ScissorPanelUI::cb_Brush_i(Fl_Round_Button*, void*) { imgView->BrushSelection(1); } void ScissorPanelUI::cb_Brush(Fl_Round_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->parent()->user_data()))->cb_Brush_i(o,v); } inline void ScissorPanelUI::cb_Close_i(Fl_Button*, void*) { hide(); } void ScissorPanelUI::cb_Close(Fl_Button* o, void* v) { ((ScissorPanelUI*)(o->parent()->user_data()))->cb_Close_i(o,v); } ScissorPanelUI::ScissorPanelUI() { Fl_Window* w; { Fl_Window* o = mainWindow = new Fl_Window(522, 191, "Scissor Panel UI"); w = o; o->user_data((void*)(this)); { Fl_Group* o = new Fl_Group(0, 0, 520, 156); o->align(FL_ALIGN_TOP_LEFT); { Fl_Box* o = new Fl_Box(1, 3, 95, 21, "Work Mode:"); o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE); } { Fl_Box* o = new Fl_Box(0, 24, 264, 32); o->box(FL_ENGRAVED_FRAME); } { Fl_Round_Button* o = new Fl_Round_Button(1, 26, 103, 28, "Image Only"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->callback((Fl_Callback*)cb_Image); } { Fl_Round_Button* o = contour = new Fl_Round_Button(109, 26, 148, 28, "Image with Contour"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->callback((Fl_Callback*)cb_contour); } { Fl_Box* o = new Fl_Box(1, 59, 95, 22, "Debug Mode:"); o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE); } { Fl_Box* o = new Fl_Box(0, 81, 520, 75); o->box(FL_ENGRAVED_FRAME); } { Fl_Round_Button* o = new Fl_Round_Button(1, 83, 107, 28, "Pixel Nodes"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->callback((Fl_Callback*)cb_Pixel); } { Fl_Round_Button* o = new Fl_Round_Button(110, 83, 147, 28, "Cost Graph"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->callback((Fl_Callback*)cb_Cost); } { Fl_Round_Button* o = new Fl_Round_Button(273, 83, 115, 28, "Path Tree"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->callback((Fl_Callback*)cb_Path); } { Fl_Round_Button* o = new Fl_Round_Button(390, 83, 130, 28, "Minimum Path"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->callback((Fl_Callback*)cb_Minimum); } { Fl_Counter* o = expanded = new Fl_Counter(112, 113, 304, 20, "Number of Expanded Nodes"); o->minimum(0); o->maximum(0); o->step(1); o->callback((Fl_Callback*)cb_expanded); o->when(FL_WHEN_RELEASE); } o->end(); } { Fl_Group* o = new Fl_Group(268, 0, 256, 56); o->align(FL_ALIGN_TOP_LEFT); { Fl_Box* o = new Fl_Box(268, 24, 252, 32); o->box(FL_ENGRAVED_FRAME); } { Fl_Round_Button* o = whole = new Fl_Round_Button(272, 26, 116, 28, "Whole Image"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->selection_color(2); o->callback((Fl_Callback*)cb_whole); } { Fl_Round_Button* o = new Fl_Round_Button(389, 26, 127, 28, "Brush Selection"); o->type(102); o->down_box(FL_ROUND_DOWN_BOX); o->selection_color(2); o->callback((Fl_Callback*)cb_Brush); } { Fl_Box* o = new Fl_Box(268, 2, 132, 22, "Scissor Range:"); o->align(FL_ALIGN_LEFT|FL_ALIGN_INSIDE); } o->end(); } { Fl_Button* o = new Fl_Button(189, 159, 152, 28, "Close"); o->callback((Fl_Callback*)cb_Close); } o->end(); } } void ScissorPanelUI::show() { mainWindow->show(); } void ScissorPanelUI::hide() { mainWindow->hide(); }
[ "pandaman0529@gmail.com" ]
pandaman0529@gmail.com
3359bd7e89e4e86a97a6da284d25169e047ecc7c
d9162d21f86a94af89533636b228d45efb6fe87d
/benchmark/benchmark.cc
35b80a9b18c08a5f6a5351ba2e252954d4d46a3f
[ "MIT" ]
permissive
jonasohland/shgen
092af99903792509c9f268d00c5d5decb354f18f
d8ccbc966ef634fec7d0935606f6716e32c82956
refs/heads/master
2022-10-01T21:42:07.721045
2020-06-06T14:35:41
2020-06-06T14:35:41
268,918,432
0
0
null
2020-06-04T14:44:16
2020-06-02T22:06:27
C++
UTF-8
C++
false
false
467
cc
#include <benchmark/benchmark.h> #include <iostream> int main() { float iemdata[32]; float shgendata[32]; float xmm[8] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}; float ymm[8] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}; float zmm[8] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f}; // shgen::detail::shgen_eval_l1(xmm, ymm, zmm, iemdata); for(int i = 0; i < 16; ++i) std::cout << iemdata[i] << " "; return 0; }
[ "jonas.ohland@gmail.com" ]
jonas.ohland@gmail.com
d94a101cfe6690d14ba4075f742e3aa500cadd19
cdc372d374aa3017356ecf414806e89d3cad4961
/Development/nmos/system_api.cpp
aed7fdcd408a33a10ff21f028ebc218ba6558973
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
wsneijers/nmos-cpp
0837b36b17af7ffbcb819ddefbacf445895ecb8e
3221155f4da6b8600f8a5e79626638a515dd5ec6
refs/heads/master
2020-12-26T07:45:31.809298
2020-01-30T22:04:11
2020-01-30T22:04:11
237,437,301
0
0
Apache-2.0
2020-01-31T13:37:36
2020-01-31T13:37:35
null
UTF-8
C++
false
false
8,233
cpp
#include "nmos/system_api.h" #include "cpprest/json_validator.h" #include "nmos/api_utils.h" #include "nmos/json_schema.h" #include "nmos/log_manip.h" #include "nmos/model.h" namespace nmos { inline web::http::experimental::listener::api_router make_unmounted_system_api(nmos::registry_model& model, slog::base_gate& gate); web::http::experimental::listener::api_router make_system_api(nmos::registry_model& model, slog::base_gate& gate) { using namespace web::http::experimental::listener::api_router_using_declarations; api_router system_api; system_api.support(U("/?"), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U("x-nmos/") }, req, res)); return pplx::task_from_result(true); }); system_api.support(U("/x-nmos/?"), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U("system/") }, req, res)); return pplx::task_from_result(true); }); const std::set<api_version> versions{ { 1, 0 } }; system_api.support(U("/x-nmos/") + nmos::patterns::system_api.pattern + U("/?"), methods::GET, [versions](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body(nmos::make_api_version_sub_routes(versions), req, res)); return pplx::task_from_result(true); }); system_api.mount(U("/x-nmos/") + nmos::patterns::system_api.pattern + U("/") + nmos::patterns::version.pattern, make_unmounted_system_api(model, gate)); return system_api; } inline web::http::experimental::listener::api_router make_unmounted_system_api(nmos::registry_model& model, slog::base_gate& gate_) { using namespace web::http::experimental::listener::api_router_using_declarations; api_router system_api; // check for supported API version const std::set<api_version> versions{ { 1, 0 } }; system_api.support(U(".*"), details::make_api_version_handler(versions, gate_)); system_api.support(U("/?"), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U("global/") }, req, res)); return pplx::task_from_result(true); }); system_api.support(U("/global/?"), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); auto lock = model.read_lock(); if (model.system_global_resource.has_data()) { set_reply(res, status_codes::OK, model.system_global_resource.data); } else { slog::log<slog::severities::error>(gate, SLOG_FLF) << "System global resource not configured!"; set_reply(res, status_codes::InternalError); // rather than Not Found, since the System API doesn't allow a 404 response } return pplx::task_from_result(true); }); const web::json::experimental::json_validator validator { nmos::experimental::load_json_schema, { experimental::make_systemapi_global_schema_uri({ 1, 0 }) } }; // experimental extension, to allow the global configuration resource to be replaced system_api.support(U("/global/?"), methods::PUT, [&model, validator, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); return details::extract_json(req, gate).then([&model, &validator, req, res, parameters, gate](value body) mutable { auto lock = model.write_lock(); const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); // Validate JSON syntax according to the schema const bool allow_invalid_resources = nmos::experimental::fields::allow_invalid_resources(model.settings); if (!allow_invalid_resources) { validator.validate(body, experimental::make_systemapi_global_schema_uri(version)); } else { try { validator.validate(body, experimental::make_systemapi_global_schema_uri(version)); } catch (const web::json::json_exception& e) { slog::log<slog::severities::warning>(gate, SLOG_FLF) << "JSON error: " << e.what(); } } const auto& data = body; model.system_global_resource = { version, types::global, data, true }; // notify anyone who cares... model.notify(); set_reply(res, status_codes::Created, data); return true; }); }); // experimental extension, to allow the global configuration resource to be modified system_api.support(U("/global/?"), methods::PATCH, [&model, validator, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); return details::extract_json(req, gate).then([&model, &validator, req, res, parameters, gate](value body) mutable { auto lock = model.write_lock(); const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); if (model.system_global_resource.has_data()) // and version is the same? { // Merge the updates auto patched = model.system_global_resource.data; web::json::merge_patch(patched, body, true); // Validate JSON syntax according to the schema const bool allow_invalid_resources = nmos::experimental::fields::allow_invalid_resources(model.settings); if (!allow_invalid_resources) { validator.validate(patched, experimental::make_systemapi_global_schema_uri(version)); } else { try { validator.validate(patched, experimental::make_systemapi_global_schema_uri(version)); } catch (const web::json::json_exception& e) { slog::log<slog::severities::warning>(gate, SLOG_FLF) << "JSON error: " << e.what(); } } if (model.system_global_resource.id == nmos::fields::id(patched)) { model.system_global_resource.data = patched; // notify anyone who cares... model.notify(); set_reply(res, status_codes::OK, patched); } else { set_error_reply(res, status_codes::BadRequest, U("Bad Request; cannot modify resource id with a PATCH request")); } } else { slog::log<slog::severities::error>(gate, SLOG_FLF) << "System global resource not configured!"; set_reply(res, status_codes::InternalError); // rather than Not Found, since the System API doesn't allow a 404 response } return true; }); }); return system_api; } }
[ "gareth.sylvester-bradley@sony.com" ]
gareth.sylvester-bradley@sony.com
7ee12c8bca85035c272348809f93416ac3a2f938
bd9f9d3937f7ea8a825e1d9b61fb5493f88b4653
/src-plugins/vanilla-sdl2/test/TestInput.cpp
58ada1238785099eb3219193f4cee703c1bb6bec
[]
no_license
tea2code/fantasy-rts
ba3b0b73975d4c6d4c986a36f11002073b40995f
c38b43edb7ec54f18768564c42859195bc2477e4
refs/heads/master
2021-01-20T02:48:03.999913
2015-02-07T10:12:10
2015-02-07T10:12:10
15,477,479
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
cpp
#include <catch.hpp> #include <input/KeyToSdl2Key.h> #include <input/MouseButtonToSdl2MouseButton.h> #include <input/StringToSdl2Key.h> #include <input/StringToSdl2MouseButton.h> #include <input/impl/SelectionDataImpl.h> #include <shared/impl/IdImpl.h> TEST_CASE("KeyToSdl2Key.", "[input]") { REQUIRE(frts::keyToSdl2Key(frts::Key::Number0) == SDLK_0); } TEST_CASE("StringToSdl2Key.", "[input]") { REQUIRE(frts::stringToSdl2Key("Number0") == SDLK_0); REQUIRE(frts::stringToSdl2Key("number0") == SDLK_0); REQUIRE(frts::stringToSdl2Key("0") == SDLK_0); REQUIRE(frts::stringToSdl2Key(",") == SDLK_COMMA); REQUIRE(frts::stringToSdl2Key("\\") == SDLK_BACKSLASH); } TEST_CASE("MouseButtonToSdl2MouseButton.", "[input]") { REQUIRE(frts::mouseButtonToSdl2MouseButton(frts::MouseButton::Middle) == SDL_BUTTON_MIDDLE); } TEST_CASE("StringToSdl2MouseButton.", "[input]") { REQUIRE(frts::stringToSdl2MouseButton(frts::mouseButtonStringPrefix() + "Left") == SDL_BUTTON_LEFT); REQUIRE(frts::stringToSdl2MouseButton(frts::mouseButtonStringPrefix() + "left") == SDL_BUTTON_LEFT); } TEST_CASE("SelectionData.", "[input]") { auto sd = frts::makeSelectionData(); auto id = frts::makeId("test"); sd->setIsSelecting(true); sd->setSelectionEntityId(id); REQUIRE(sd->isSelecting()); REQUIRE(sd->getSelectionEntityId() == id); sd->resetSelection(); REQUIRE_FALSE(sd->isSelecting()); REQUIRE(sd->getSelectionEntityId() == id); }
[ "stefan4875@gmail.com" ]
stefan4875@gmail.com
97f1dba50e1128a36ff787f5f5e97f5d112be011
cecfda84e25466259d3ef091953c3ac7b44dc1fc
/UVa Online Judge/volume106/10603 Fill/program1.cpp
4d726d6364254c4cb9dcf502c714401c4c790b59
[]
no_license
metaphysis/Code
8e3c3610484a8b5ca0bb116bc499a064dda55966
d144f4026872aae45b38562457464497728ae0d6
refs/heads/master
2023-07-26T12:44:21.932839
2023-07-12T13:39:41
2023-07-12T13:39:41
53,327,611
231
57
null
null
null
null
UTF-8
C++
false
false
3,101
cpp
// Fill // UVa ID: 10603 // Verdict: Accepted // Submission Date: 2018-02-09 // UVa Run Time: 0.000s // // 版权所有(C)2018,邱秋。metaphysis # yeah dot net #include <bits/stdc++.h> using namespace std; struct edge { int a, b, c, d; edge (int a = 0, int b = 0, int c = 0, int d = 0): a(a), b(b), c(c), d(d) {} }; int dist[201][201]; int main(int argc, char *argv[]) { cin.tie(0), cout.tie(0), ios::sync_with_stdio(false); int cases; int a, b, c, d, dist[201][201], amount[201], INF = 0x7f7f7f7f; int aa, bb, cc; cin >> cases; for (int cs = 1; cs <= cases; cs++) { cin >> a >> b >> c >> d; memset(dist, 0x7f, sizeof(dist)); memset(amount, 0x7f, sizeof(amount)); queue<edge> q; q.push(edge(0, 0, c, 0)); dist[0][0] = 0; amount[0] = amount[c] = 0; edge edges[6]; while (!q.empty()) { edge u = q.front(); q.pop(); int cnt = 0; if (u.a) { if (u.a > (b - u.b)) edges[cnt++] = edge(u.a + u.b - b, b, u.c, b - u.b); else edges[cnt++] = edge(0, u.b + u.a, u.c, u.a); if (u.a > (c - u.c)) edges[cnt++] = edge(u.a + u.c - c, u.b, c, c - u.c); else edges[cnt++] = edge(0, u.b, u.c + u.a, u.a); } if (u.b) { if (u.b > (a - u.a)) edges[cnt++] = edge(a, u.b + u.a - a, u.c, a - u.a); else edges[cnt++] = edge(u.a + u.b, 0, u.c, u.b); if (u.b > (c - u.c)) edges[cnt++] = edge(u.a, u.b + u.c - c, c, c - u.c); else edges[cnt++] = edge(u.a, 0, u.c + u.b, u.b); } if (u.c) { if (u.c > (a - u.a)) edges[cnt++] = edge(a, u.b, u.c + u.a - a, a - u.a); else edges[cnt++] = edge(u.a + u.c, u.b, 0, u.c); if (u.c > (b - u.b)) edges[cnt++] = edge(u.a, b, u.c + u.b - b, b - u.b); else edges[cnt++] = edge(u.a, u.b + u.c, 0, u.c); } for (int k = 0; k < cnt; k++) { aa = edges[k].a, bb = edges[k].b, cc = edges[k].c; if (dist[aa][bb] > dist[u.a][u.b] + edges[k].d) { dist[aa][bb] = dist[u.a][u.b] + edges[k].d; amount[aa] = min(amount[aa], dist[aa][bb]); amount[bb] = min(amount[bb], dist[aa][bb]); amount[cc] = min(amount[cc], dist[aa][bb]); q.push(edge(aa, bb, cc, dist[aa][bb])); } } } for (int i = min(d, c); i >= 0; i--) if (amount[i] != INF) { cout << amount[i] << ' ' << i << '\n'; break; } } return 0; }
[ "metaphysis@yeah.net" ]
metaphysis@yeah.net
21f51a8076b79e7fd7fee5d67c3dfe6ebee763c5
81c66c9c0b78f8e9c698dcbb8507ec2922efc8b7
/src/domains/bdf/kernel/BDFStar.cc
fed382d5c91f5576dac44ec9c67bb47b1e3a6dc1
[ "MIT-Modern-Variant" ]
permissive
Argonnite/ptolemy
3394f95d3f58e0170995f926bd69052e6e8909f2
581de3a48a9b4229ee8c1948afbf66640568e1e6
refs/heads/master
2021-01-13T00:53:43.646959
2015-10-21T20:49:36
2015-10-21T20:49:36
44,703,423
0
0
null
null
null
null
UTF-8
C++
false
false
6,563
cc
static const char file_id[] = "BDFStar.cc"; /****************************************************************** Version identification: @(#)BDFStar.cc 2.14 3/2/95 Copyright (c) 1990-1995 The Regents of the University of California. All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. PT_COPYRIGHT_VERSION_2 COPYRIGHTENDKEY Programmer: J. T. Buck Date of creation: 1/8/91 *******************************************************************/ #ifdef __GNUG__ #pragma implementation #endif #include "BDFStar.h" #include "BDFPortHole.h" #include "SimControl.h" // an aid for debugging: make animation behavior look like DDF stars // in which partial evaluation occurs. Problem: this file now "knows" // the format of the animation info. #include "textAnimate.h" #include <iostream.h> /******************************************************************* class BDFStar methods ********************************************************************/ BDFStar :: BDFStar() : sdfCtx(0), dynExec(0) {} int BDFStar :: isSDFinContext() const { return sdfCtx;} // enable dynamic execution int BDFStar :: setDynamicExecution(int val) { dynExec = val ? TRUE : FALSE; return TRUE; } // in addition to baseclass initialize, set waitPort if we have a // dynamic input. void BDFStar :: initialize() { DynDFStar::initialize(); if (!isSDF() && !isSink() && dynamicExec()) { // find waitPort BDFStarPortIter nextp(*this); BDFPortHole *p; while ((p = nextp++) != 0) { p->clearReadFlag(); if (p->isDynamic() && p->isItInput()) { waitFor(*p->assoc()); } } } sdfCtx = isSDF() ? TRUE : dataIndependent(); } // the baseclass has no additional smarts for determining data-independence. int BDFStar::dataIndependent() { return isSDF();} // The following is defined in BDFDomain.cc -- this forces that module // to be included if any BDF stars are linked in. extern const char BDFdomainName[]; const char* BDFStar :: domain () const { return BDFdomainName;} ISA_FUNC(BDFStar,DynDFStar); // method called when an input port does not have enough data. // If we are being executed dynamically, we must make sure that there // is enough data (since the DDF scheduler will execute us based on // the waitPort). Otherwise it is an error if there is not enough data. int BDFStar :: handleWait(BDFPortHole& p) { if (dynamicExec()) { if (textAnimationState()) { cout << "PARTIAL: " << fullName() << ": wait on " << p.name() << "\n"; } waitFor(p,p.numXfer()); return TRUE; } else { Error::abortRun(p, "BDF scheduler error: too few tokens"); return FALSE; } } // run function: This does any required receiveData or sendData calls. // if SDF, we can use the simpler routine in DataFlowStar::run. int BDFStar :: run () { if (isSDF()) return DataFlowStar::run(); // not SDF. if (SimControl::haltRequested()) return FALSE; BDFStarPortIter nextPort(*this); BDFPortHole *p; // step 1: process unconditional inputs that haven't already // been read. while ((p = nextPort++) != 0) { if (p->isItOutput() || p->isDynamic() || p->alreadyRead()) continue; if (p->far() && p->numTokens() < p->numXfer()) return handleWait(*p); else p->receiveData(); } // step 2: process conditional inputs. Assumption: control // ports always move one integer, and previous processing // in step 1 has fetched the control token. // again, we skip ports that have already been read. DFPortHole* ctlp = 0; nextPort.reset(); while ((p = nextPort++) != 0) { if (p->isItOutput() || !p->isDynamic() || p->alreadyRead()) continue; ctlp = p->assoc(); int ctl_is_t = (*ctlp)%0; int read_on_t = (p->assocRelation() == BDF_TRUE); // data are moved if control token matches the // assocRelation. if (ctl_is_t == read_on_t) { if (p->far() && p->numTokens() < p->numXfer()) return handleWait(*p); else p->receiveData(); } } // leave a waitPort for next time if there was a control port. if (ctlp) waitFor(*ctlp); // step 3: execute the star if (!Star::run()) return FALSE; // step 4: do sendData calls for conditional outputs. // we do conditionals first so that we can still access any // output control booleans. // while we are at it, the read flags of input ph's are cleared. nextPort.reset(); while ((p = nextPort++) != 0) { if (p->isItInput() || !p->isDynamic()) { p->clearReadFlag(); continue; } ctlp = p->assoc(); int ctl_is_t = (*ctlp)%0; int write_on_t = (p->assocRelation() == BDF_TRUE); if (ctl_is_t == write_on_t) p->sendData(); } // step 5: do sendData calls for unconditional outputs. nextPort.reset(); while ((p = nextPort++) != 0) { if (p->isItOutput() && !p->isDynamic()) p->sendData(); } return TRUE; } int BDFStar :: notRunnable () { if (isSDFinContext()) { return DataFlowStar::notRunnable(); } else { Error::abortRun(*this, "fn notRunnable, not SDFinContext"); return 0; } } int BDFStar :: simRunStar (int deferFiring) { if (isSDFinContext()) { return DataFlowStar::simRunStar(deferFiring); } else { Error::abortRun(*this, "fn simRunStar, not SDFinContext"); return 0; } } /////////////////////////// // deferrable /////////////////////////// // return TRUE if we can defer the star, FALSE if we cannot. // Postpone any execution of a star feeding data to another // star that is runnable. Also postpone if each output port // has enough data on it to satisfy destination stars. int BDFStar :: deferrable () { if (isSDFinContext()) { return DataFlowStar::deferrable(); } else { Error::abortRun(*this, "fn deferrable: not SDFinContext"); return 0; } }
[ "dermalin3k@hotmail.com" ]
dermalin3k@hotmail.com
41f186a341645381ac37da84623b74f0326c6af0
b9d14b7c06dec68b93ca8914dec92861745b98eb
/大质数/大质数Dlg.h
e77b196340d8260daf7095fd42a2be4db4f4b4f8
[]
no_license
huangk4/prime_num
544c95d327e4f9d8224dc7db7c844367b74dfd37
463e9acfd92f0fb16b334c72cd95a2e98583b6f4
refs/heads/master
2020-04-24T18:34:27.740072
2019-02-23T07:18:49
2019-02-23T07:18:49
172,183,996
0
0
null
null
null
null
GB18030
C++
false
false
668
h
// 大质数Dlg.h : 头文件 // #pragma once // C大质数Dlg 对话框 class C大质数Dlg : public CDialogEx { // 构造 public: C大质数Dlg(CWnd* pParent = NULL); // 标准构造函数 // 对话框数据 enum { IDD = IDD_MY_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: CString m_num; // 生成质数的位数 int m_bit; afx_msg void OnBnClickedButton1(); };
[ "847209149@qq.com" ]
847209149@qq.com
368d665e1d57d9d95552ff7b3fcfe5511b8b90dd
c398c1e29b2ef21408f6c5a26cd8b150a0a3d054
/SFMLGit/SFML_Test2/SFML_Test2/obstacle.h
e5e02057d4db90e83931fecc8edc9d6f882c5f21
[]
no_license
IAmArcanine/CptS122_Final_Project
4d5ff898a8ddee6f5d5e3fb9f016378b58b04068
8e18dc0761f1e7b644b5b0e226058ceccbcaa59c
refs/heads/master
2020-04-10T02:56:03.872718
2018-12-07T01:56:39
2018-12-07T01:56:39
160,756,224
0
0
null
null
null
null
UTF-8
C++
false
false
530
h
#ifndef OBSTACLE_H #define OBSTACLE_H #include "character.h" class obstacle { friend class character; public: // default constructor obstacle (); // normal constructor obstacle (int theOriginX, int theOriginY, int theDimX, int theDimY); // copy constructor obstacle (obstacle &copyObject); // destructor ~obstacle (); // getters int getOriginX (); int getOriginY (); int getSizeX (); int getSizeY (); private: int originX; int originY; int sizeX; int sizeY; }; #endif
[ "mferran@eecs.wsu.edu" ]
mferran@eecs.wsu.edu
218462506bdfb0e5b99bcd84622249de2ed8ddef
71f6510d68a33d828c9a7ee669e646211d34d2aa
/simplepongSIGIL/src/main.cpp
3c6ab50a4b6e6d69c75f50fc3bab567de762bd0a
[]
no_license
frankvega2010/simple-pong-SIGIL
ea742503ce7c5fedb30c1fdb4b32c3fc3137fffa
0dc81f346c2c19313050194bc3d81b30692a1626
refs/heads/master
2020-04-01T02:01:36.024457
2018-10-18T22:09:01
2018-10-18T22:09:01
152,762,799
0
0
null
null
null
null
UTF-8
C++
false
false
94
cpp
#include "Setup/Game.h" using namespace Juego; int main() { Execute(); return 0; }
[ "franco_vega@msn.com" ]
franco_vega@msn.com
ebd606ed5ef35c33748a267f323c07d0cffaf7dc
f6e49907d7331f1472ebc8149fc1338cb2bda8a7
/Chapter06/2/MyFriendClass.cpp
18195daaa6beab3b1f22ea5380263eff6a3b4b88
[]
no_license
Junhyung-Choi/CPP_TRAINING
8f77c6df49b7d62c0af1cb4eb75e69498fc16298
e7db36ede66a30fb7a2f79b240311647d51c2b26
refs/heads/master
2023-07-20T07:40:11.563364
2021-08-31T12:36:55
2021-08-31T12:36:55
364,784,531
0
0
null
null
null
null
UTF-8
C++
false
false
771
cpp
#include <iostream> #include <cstring> using namespace std; class Girl; class Boy { private: int height; friend class Girl; public: Boy(int len) : height(len) { //empty } void ShowYourFriendInfo(Girl &frn); }; class Girl { private: char phNum[20]; public: Girl(const char * num) { strcpy(phNum,num); } void ShowYourFriendInfo(Boy &frn); friend class Boy; }; void Boy::ShowYourFriendInfo(Girl &frn) { cout << "Her phone number: " << frn.phNum << endl; } void Girl::ShowYourFriendInfo(Boy &frn) { cout << "His height: " << frn.height << endl; } int main(void) { Boy boy(170); Girl girl("010-1234-5678"); boy.ShowYourFriendInfo(girl); girl.ShowYourFriendInfo(boy); return 0; }
[ "junhyung9571@naver.com" ]
junhyung9571@naver.com
311140903b448acfbac3e5a3b26458c1e44ea817
2ab6eb4baffcf01b4e1e872679aaa90f935bd221
/cpp/practise/array_partition_min_diff.cpp
aed9907caac25db5a538d39b017bc954f6e594ea
[]
no_license
3l-d1abl0/DS-Algo
771395ac1caff0d51e7d0e4ddc0ce69a0d568863
09d1abf747590b4b7b64906c19d23874e880b8c4
refs/heads/master
2022-06-26T05:01:25.435541
2022-06-17T04:50:14
2022-06-17T04:50:14
237,816,236
0
0
null
null
null
null
UTF-8
C++
false
false
686
cpp
#include<bits/stdc++.h> using namespace std; bool partition(int arr[], int sz, int currentSum, int sum){ if(sz==0) return abs( (sum-currentSum)- currentSum); return min( partition(arr, sz-1, currentSum, sum), partition(arr, sz-1, currentSum+arr[sz-1], sum)); } bool findMin(int arr[], int sz){ int sum =0; for(int i=0; i<sz;i++) sum+=arr[i]; return partition(arr, sz, 0, sum); } int main(){ //int arr[] = {3, 1, 4, 2, 2, 1}; int arr[] = {3, 1, 17, 7, 16}; int n = sizeof(arr)/sizeof(arr[0]); cout << "The minimum difference between two sets is " << findMin(arr, n); return 0; }
[ "sameer.barha12@gmail.com" ]
sameer.barha12@gmail.com
915c495a6966743a29a77be58b5cc958287c8c21
777713d22368076710db7a008b791625b79bddae
/CCPC&ICPC/2018icpc-qingdao-M.cpp
bf07c4a70451f421e5380dab4f2600a87e717e48
[]
no_license
jelech/To_Be_ACMer
bcf468a5245b67f0d3d3604d2e867388fb21a5ee
626d289ff76b013f2cb84bc2d5290c8d76182214
refs/heads/master
2021-04-06T00:28:24.653734
2019-10-14T12:00:52
2019-10-14T12:00:52
124,747,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,022
cpp
#include <bits/stdc++.h> using namespace std; int solve(int x,int k) { // printf("std %d %d\n",x,k); if(k==0)return x; if(x<10){ if(k==1){ if(x==8)return 2; if(x==0||x==4||x==6||x==9)return 1; return 0; } if(k&1){ if(x==8)return 1; if(x==0||x==4||x==6||x==9)return 1; return 0; } else { if(x==8)return 0; if(x==0||x==4||x==6||x==9)return 0; return 1; } } int res=0; while(x){ int as=x%10; if(as==8)res+=2; if(as==0||as==4||as==6||as==9)res++; x/=10; } // printf("test %d %d\n",res,k); return solve(res,k-1); } int main() { int T; scanf("%d",&T); while(T--){ int a,k; scanf("%d%d",&a,&k); int ans=solve(a,k); printf("%d\n",ans); } return 0; } /* 6 123456789 1 888888888 1 888888888 2 888888888 999999999 98640 12345 1000000000 0 1 888888888 2 */
[ "Milking2k@qq.com" ]
Milking2k@qq.com
c1950480d356b3800395d8ba342a3ba2e796f60a
d2b8fe1806ed60301f32f7f4ce3d444d068ff93b
/ssf_core/SMManager.h
022f3871b59f4e5db911e699def2db58a4d35760
[]
no_license
acnazarejr/ssf
142abf74003affe0ff97cc349b4a687a048aa1a8
27d18e4ea44e61739cec02ee4e00ced1c2d18c58
refs/heads/master
2022-11-20T00:54:04.425397
2020-07-29T01:13:10
2020-07-29T01:13:10
283,364,245
1
1
null
null
null
null
UTF-8
C++
false
false
1,480
h
#ifndef _SM_MANAGER_H_ #define _SM_MANAGER_H_ class SMManager : public SSFStructure { friend class SMDataStream; friend class SharedMemory; SSFMutex mutex; size_t nAllocatedBytes; // number of currenty allocated bytes in RAM vector<SSFData *> dataEntries; // actual data storage (if NULL, the data is in the disk) vector<int> nlinks; // number of links to each data entry // input parameters int maxMemory; // maximum number of bytes in the memory string directory; // directory to store the memory // recover data from disk void RecoverData(SMIndexType idx); // save data to the disk void SaveData(); protected: // set a new data entry - returns its unique ID SMIndexType SetData(SSFData *data); // retrieve a data entry with identifier id SSFData *GetData(SMIndexType id); // decrease a link for a data item (to control is a item can be write in disk, when it is 0, can be released) void UnlinkData(SMIndexType id); // decrease links for a set of data entries void UnlinkData(unordered_map<SMIndexType, int> &entriesID); public: SMManager(); ~SMManager(); // retrieve the name of the method string GetName() { return SSF_STRUCTURE_SMManager; } // retrieve the type of the method string GetType() { return SSF_METHOD_TYPE_STRUCTURE; } // retrieve structure version string GetVersion() { return "0.0.1"; } // structure setup - function written by the user and called after parameters have been set void Setup(); }; #endif
[ "acnazarejr@gmail.com" ]
acnazarejr@gmail.com
662749c0abc5e4f246112cb5c1a2c189b2570afe
f22013843b426169488476296211d0f0183ee60e
/chapter3-2/subsequence/kanpe/answer.cc
5ecb7c7fb341d265afd00659710859c3f851180b
[]
no_license
ie-ProCon/ant_book
2c275914290c60c545cebd84c062ae2faab38f01
3821a5504df08a70f150efe2b25c7e7fde804546
refs/heads/master
2021-01-15T13:48:34.489883
2014-02-18T03:09:41
2014-02-18T03:09:41
13,138,340
1
0
null
2014-02-18T03:09:41
2013-09-27T01:12:00
C++
UTF-8
C++
false
false
1,359
cc
#include <iostream> #include <algorithm> #include <vector> void input(void); int get_ans1(void); int get_ans2(void); int N, S; std::vector<int> array; int main(void) { int case_num; std::cin >> case_num; for (int i = 0; i < case_num; i++) { input(); //int ans = get_ans1(); int ans = get_ans2(); std::cout << ans << std::endl; } return 0; } // O(N*log(N)) int get_ans1(void) { std::vector<int> sum = std::vector<int>(N+1, 0); for (int i = 0; i < N; i++) { sum[i+1] = sum[i] + array[i]; } if (sum[N] < S) { return 0; } int result = N; for (int s = 0; sum[s]+S <= sum[N]; s++) { int t = std::lower_bound(sum.begin()+s, sum.begin()+N, sum[s]+S) - sum.begin(); result = std::min(result, t-s); } return result; } // O(N) int get_ans2(void) { int result = N + 1; int s = 0, t = 0, sum = 0; while (true) { while (t<N && sum<S) { sum += array[t++]; } if (sum < S) { break; } result = std::min(result, t-s); sum -= array[s++]; } if (N < result) { return 0; } return result; } void input(void) { std::cin >> N >> S; array = std::vector<int>(N); for (int i = 0; i < N; i++) { std::cin >> array[i]; } }
[ "kanpe777@gmail.com" ]
kanpe777@gmail.com
29f540e4d4b1a3556f8700d5ad7c36d2106dd637
92db9439189aaa1266c3d2ec99562f813a76dc00
/1102.path-with-maximum-minimum-value.cpp
3cf660ea43c739bd1d880f18cd86709335f0de52
[]
no_license
Raees678/leetcode-solutions
0d39b0ac19568df1746c83141f119c9080859f57
0f7b41f3bde6e926f57c5b994c02cd8d83d470c3
refs/heads/master
2022-11-26T22:13:14.397227
2020-07-28T14:30:55
2020-07-28T14:30:55
283,237,597
0
0
null
null
null
null
UTF-8
C++
false
false
3,925
cpp
// Given a matrix of integers A with R rows and C columns, find the maximum // score of a path starting at [0,0] and ending at [R-1,C-1]. // // The score of a path is the minimum value in that path. For example, the // value of the path 8 &rarr; 4 &rarr; 5 &rarr; 9 is 4. // // A path moves some number of times from one visited cell to any neighbouring // unvisited cell in one of the 4 cardinal directions (north, east, west, // south). // // // // -------------------------------------------------- // // Example 1: // // // // // Input: [[5,4,5],[1,2,6],[7,4,6]] // Output: 4 // Explanation: // The path with the maximum score is highlighted in yellow. // // // -------------------------------------------------- // // Example 2: // // // // // Input: [[2,2,1,2,2,2],[1,2,2,2,1,2]] // Output: 2 // // -------------------------------------------------- // // Example 3: // // // // // Input: // [[3,4,6,3,4],[0,2,1,1,7],[8,8,3,2,7],[3,2,4,9,8],[4,1,2,0,0],[4,6,5,4,3]] // Output: 3 // // // // * * * * * * * * * * * * * * * * * * * * * * * * * // // Note: // // // 1 <= R, C <= 100 // 0 <= A[i][j] <= 10^9 // // class Solution { public: std::vector<std::vector<int>> neighbour_basis{ {0, 1}, {1, 0}, {-1, 0}, {0, -1}}; enum state { UNVISITED, VISITED }; inline std::vector<std::vector<int>> findNeighbours( int row, int col, std::vector<std::vector<int>>& A, std::vector<std::vector<state>>& states) { std::vector<std::vector<int>> neighbours; for (int i = 0; i < 4; ++i) { int new_row = row + neighbour_basis[i][0]; int new_col = col + neighbour_basis[i][1]; if (new_row >= 0 && new_row < A.size() && new_col >= 0 && new_col < A[new_row].size() && states[new_row][new_col] == UNVISITED) { neighbours.push_back(std::vector<int>{new_row, new_col}); } } return neighbours; } struct CompareScore { bool operator()(const std::vector<int>& a, const std::vector<int>& b) { return a[2] < b[2]; } }; int maximumMinimumPath(std::vector<std::vector<int>>& A) { // we use djikstras algorithm. to find the single source shortest path std::vector<std::vector<int>> scores(A.size(), std::vector<int>(A[0].size(), -1)); std::priority_queue<std::vector<int>> queue; std::vector<std::vector<state>> states( A.size(), std::vector<state>(A[0].size(), UNVISITED)); queue.push(std::vector<int>{0, 0, A[0][0]}); while (!queue.empty()) { std::vector<int> current_node = queue.top(); queue.pop(); int row = current_node[0]; int col = current_node[1]; int score = current_node[2]; // if the node obtained shows that the score is lesser than the recorded // score dont try to compute its neighbours scores, because we have // already done it with a better recorded score, since better scores are // popped from the priority queue first if (score <= scores[row][col]) { continue; } scores[row][col] = score; if (row == A.size() - 1 && col == A[0].size() - 1) { break; } std::vector<std::vector<int>> neighbours = findNeighbours(row, col, A, states); for (int i = 0; i < neighbours.size(); ++i) { // for all neighbours calculate the score of getting to them and update // the score table int neighbour_row = neighbours[i][0]; int neighbour_col = neighbours[i][1]; int neighbour_score = std::min(score, A[neighbour_row][neighbour_col]); states[neighbour_row][neighbour_col] = VISITED; queue.push( std::vector<int>{neighbour_row, neighbour_col, neighbour_score}); } } return scores[A.size() - 1][A[0].size() - 1]; } };
[ "raeesrajwani95@gmail.com" ]
raeesrajwani95@gmail.com
ed62bd197f0eb77887cede2ecb2dcc6c1067a514
67c6408ea53378a43e10f01434fc76254c8f2b73
/library/getopt/small/modchooser.h
c2d658c14627fc89227c39ecf25e96b141e2160f
[ "Apache-2.0" ]
permissive
yandex/CMICOT
bd18268d5f61edafc8a2e4a1c08119c213399699
480ed30e36fe89535f52c08d70f80f83e098f01b
refs/heads/master
2023-01-24T08:12:00.446425
2023-01-11T17:06:04
2023-01-11T17:06:04
76,370,586
39
15
NOASSERTION
2022-11-08T19:24:36
2016-12-13T15:19:15
C++
UTF-8
C++
false
false
4,306
h
#pragma once #include <util/generic/map.h> #include <util/generic/string.h> #include <util/generic/vector.h> #include <functional> //! Mode function with vector of cli arguments. typedef std::function<int(const yvector<TString>&)> TMainFunctionPtrV; typedef int (*TMainFunctionRawPtrV)(const yvector<TString> &argv); //! Mode function with classic argc and argv arguments. typedef std::function<int(const int, const char **)> TMainFunctionPtr; typedef int (*TMainFunctionRawPtr)(const int argc, const char **argv); //! Mode class with vector of cli arguments. class TMainClassV { public: virtual int operator()(const yvector<TString> &argv) = 0; virtual ~TMainClassV() = default; }; //! Mode class with classic argc and argv arguments. class TMainClass { public: virtual int operator()(const int argc, const char **argv) = 0; virtual ~TMainClass() = default; }; //! Function to handle '--version' parameter typedef void (*TVersionHandlerPtr)(); /*! Main class for handling different modes in single tool. * * You can add modes for this class, use autogenerated help with * list of modes and automaticly call necessary mode in run(). * * In first argv element mode get joined by space tool name and * current mode name. */ class TModChooser { public: TModChooser(); ~TModChooser(); public: void AddMode(const TString& mode, const TMainFunctionRawPtr func, const TString& description); void AddMode(const TString& mode, const TMainFunctionRawPtrV func, const TString& description); void AddMode(const TString& mode, const TMainFunctionPtr func, const TString& description); void AddMode(const TString& mode, const TMainFunctionPtrV func, const TString& description); void AddMode(const TString& mode, TMainClass *func, const TString& description); void AddMode(const TString& mode, TMainClassV *func, const TString& description); void AddGroupModeDescription(const TString& description); //! Set main program description. void SetDescription(const TString& descr); //! Set modes help option name (-h is by default) void SetModesHelpOption(const TString& helpOption); //! Specify handler for '--version' parameter void SetVersionHandler(TVersionHandlerPtr handler); //! Set description show mode void SetSeparatedMode(bool separated = true); //! Set separation string void SetSeparationString(const TString& str); void DisableSvnRevisionOption(); /*! Run appropriate mode. * * In this method following things happen: * 1) If first argument is -h/--help/-? then print short description of * all modes and exit with zero code. * 2) If first argument is -v/--version and version handler is specified, * then call it and exit with zero code. * 3) Find mode with the same name as first argument. If it's found then * call it and return its return code. * 4) If appropriate mode is not found - return non-zero code. */ int Run(const int argc, const char** argv) const; //! Run appropriate mode. Same as Run(const int, const char**) int Run(const yvector<TString> &argv) const; void PrintHelp(const TString& progName) const; private: struct TMode { TString Name; TMainClassV *Main; TString Description; bool Separator; TMode() : Main(nullptr) , Separator(false) { } TMode(const TString& name, TMainClassV* main, const TString& descr); }; typedef ymap<TString, TMode> TModes; private: //! Main program description. TString Description; //! Help option for modes. TString ModesHelpOption; //! Wrappers around all modes. yvector<TAutoPtr<TMainClassV>> Wrappers; //! Modes TModes Modes; //! Handler for '--version' parameter TVersionHandlerPtr VersionHandler; //! When set to true, show descriptions unsorted and display separators bool ShowSeparated; //! When set to true, disables --svnrevision option, useful for opensource (git hosted) projects bool SvnRevisionOptionDisabled; //! Text string used when displaying each separator TString SeparationString; //! Unsorted list of options yvector<TMode> UnsortedModes; };
[ "sisoid@yandex-team.ru" ]
sisoid@yandex-team.ru
cbf2bed40083f55b101d48c21d3ec73615e459a0
dd16b0a35400676b7734439608df84e4854f9ed3
/Lab4/PrintToFile.cpp
25a536bad2eda65891a1937b962d333b925653c4
[]
no_license
kukichek/NumericalAnalysis
3ed0aa4d8724bc720d5b55dc5749f0d13033a823
15075fcce1e1efc9c0f8421f22735c4512a90d2f
refs/heads/master
2020-08-02T18:48:52.665932
2020-03-11T20:30:03
2020-03-11T20:30:03
211,470,241
0
0
null
null
null
null
UTF-8
C++
false
false
953
cpp
#include "LES.h" #include "PrintToFile.h" void PrintToFile::operator()(LES& les, int iteration) { int pr, w; std::string nameOfFile; nameOfFile = les.state + ".txt"; std::ofstream out(nameOfFile); if (les.state.find("JakobianMethod") != std::string::npos || les.state.find("RelaxationMethod") != std::string::npos) { pr = 6; w = 11; if (les.state.find("ExceededKMax") != std::string::npos) { out << "ExceededKMax\n"; } else { out << "Iteration: " << iteration << "\n"; }; for (int i = 0; i < les.mSize_; ++i) { out << std::fixed << std::setprecision(pr) << std::setw(w) << les.curSol_[i] << " \\\\\n"; } out.flush(); return; } w = 4; for (int i = 0; i < les.mSize_; ++i) { for (int j = 0; j < les.mSize_; ++j) { out << std::setw(w) << les[i][j] << " &"; } out << "\t" << std::setw(w) << les[i][les.mSize_] << " \\\\\n"; } out.flush(); }
[ "tavi4ham@gmail.com" ]
tavi4ham@gmail.com
c87d60f694ecab9de4364977af302ec903c6d414
b8723a2862a0bc34e02a44628a2f9434693ea7d1
/kattis/variablearithmetic.cpp
77a9aaa2fec1c63955032267c99ae26e3a14b785
[]
no_license
mario7lorenzo/cp
ea6d20bbde7ec7217b7bab45f635dda40d2e078b
253c16599a06cb676a3c94b4892279905486cf5d
refs/heads/master
2022-05-03T22:27:07.710681
2022-04-10T08:37:53
2022-04-10T08:37:53
158,787,709
0
0
null
null
null
null
UTF-8
C++
false
false
1,434
cpp
#include <bits/stdc++.h> using namespace std; int main() { string p; unordered_map<string, int> definition; while (getline(cin, p), p != "0") { int counter = 0; vector<string> saver; string defi; string temp = ""; bool definisi = false; for (int i = 0; i < p.length(); i++) { if (p[i] == ' ') { if (temp != "") { saver.push_back(temp); temp = ""; } } else if (p[i] == '=') { definisi = true; defi = saver[0]; temp = ""; } else if (p[i] == '+') { continue; } else { temp += p[i]; } } if (definisi) { definition[defi] = stoi(temp); } else { saver.push_back(temp); vector<string> nondef; int counter = 0; for (int i = 0; i < saver.size(); i++) { if (isdigit(saver[i][0])) { counter += stoi(saver[i]); } else { if (definition.find(saver[i]) != definition.end()) { counter += definition[saver[i]]; } else { nondef.push_back(saver[i]); } } } if (counter == 0 && nondef.size() == 0) { cout << 0 << endl; } else if (counter == 0 && nondef.size() != 0) { bool isfirst = true; for (auto i : nondef) { if (isfirst) { cout << i; isfirst = false; } else { cout << " + " << i; } } cout << endl; } else { cout << counter; for (auto i : nondef) { cout << " + " << i; } cout << endl; } } } }
[ "mariolorenzo213@gmail.com" ]
mariolorenzo213@gmail.com
9b546eda8b1e5becde8bbbdd6dd7c95530aab108
93db044eb00abbd18b75eeb0617dd1e054f2b199
/Engine/Source/ThirdParty/PhysX/APEX-1.3/framework/public/NxUserRenderResource.h
fbc86616108725a3f85d0037d916639c3331c6ee
[]
no_license
cadviz/AHRUnrealEngine
9c003bf9988d58ece42be4af030ec6ec092cd12e
e0c1a65098f4a86b4d0538535b5a85dd1544fd30
refs/heads/release
2021-01-01T15:59:31.497876
2015-04-13T22:03:55
2015-04-13T22:03:55
34,035,641
9
19
null
2015-04-16T05:12:05
2015-04-16T05:12:05
null
UTF-8
C++
false
false
3,628
h
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved. #ifndef NX_USER_RENDER_RESOURCE_H #define NX_USER_RENDER_RESOURCE_H /*! \file \brief class NxUserRenderResource */ #include "NxApexUsingNamespace.h" namespace physx { namespace apex { class NxUserRenderVertexBuffer; class NxUserRenderIndexBuffer; class NxUserRenderBoneBuffer; class NxUserRenderInstanceBuffer; class NxUserRenderSpriteBuffer; PX_PUSH_PACK_DEFAULT /** \brief An abstract interface to a renderable resource */ class NxUserRenderResource { public: virtual ~NxUserRenderResource() {} /** \brief Set vertex buffer range */ virtual void setVertexBufferRange(physx::PxU32 firstVertex, physx::PxU32 numVerts) = 0; /** \brief Set index buffer range */ virtual void setIndexBufferRange(physx::PxU32 firstIndex, physx::PxU32 numIndices) = 0; /** \brief Set bone buffer range */ virtual void setBoneBufferRange(physx::PxU32 firstBone, physx::PxU32 numBones) = 0; /** \brief Set instance buffer range */ virtual void setInstanceBufferRange(physx::PxU32 firstInstance, physx::PxU32 numInstances) = 0; /** \brief Set sprite buffer range */ virtual void setSpriteBufferRange(physx::PxU32 firstSprite, physx::PxU32 numSprites) = 0; /** \brief Set sprite visible count */ virtual void setSpriteVisibleCount(physx::PxU32 visibleCount) { PX_UNUSED(visibleCount); } /** \brief Set material */ virtual void setMaterial(void* material) = 0; /** \brief Get number of vertex buffers */ virtual physx::PxU32 getNbVertexBuffers() const = 0; /** \brief Get vertex buffer */ virtual NxUserRenderVertexBuffer* getVertexBuffer(physx::PxU32 index) const = 0; /** \brief Get index buffer */ virtual NxUserRenderIndexBuffer* getIndexBuffer() const = 0; /** \brief Get bone buffer */ virtual NxUserRenderBoneBuffer* getBoneBuffer() const = 0; /** \brief Get instance buffer */ virtual NxUserRenderInstanceBuffer* getInstanceBuffer() const = 0; /** \brief Get sprite buffer */ virtual NxUserRenderSpriteBuffer* getSpriteBuffer() const = 0; }; PX_POP_PACK } } // end namespace physx::apex #endif
[ "unrealbot@users.noreply.github.com" ]
unrealbot@users.noreply.github.com
152244423c93e7f7aef9dfc8c1fb64a8376b1f7d
85e098156370fdb3d513f20edfa8a514fe55175f
/higan/sfc/coprocessor/icd2/icd2.hpp
d80e5bbbb470f38f1361e8b54da395ba4b5919d2
[]
no_license
jeapostrophe/higan
65efcbf70bd43ccb48cd3f8dddb7264bbef1b132
c6fc15f8d26080b9d08e7bc029532c2f59a902ba
refs/heads/master
2021-01-09T20:42:11.304359
2016-09-14T11:55:53
2016-09-14T11:55:53
62,882,832
2
0
null
null
null
null
UTF-8
C++
false
false
2,245
hpp
#if defined(SFC_SUPERGAMEBOY) struct ICD2 : Emulator::Interface::Bind, GameBoy::Interface::Hook, Thread { shared_pointer<Emulator::Stream> stream; static auto Enter() -> void; auto main() -> void; auto init() -> void; auto load() -> bool; auto unload() -> void; auto power() -> void; auto reset(bool soft = false) -> void; //interface.cpp auto lcdScanline() -> void override; auto lcdOutput(uint2 color) -> void override; auto joypWrite(bool p15, bool p14) -> void override; auto open(uint id, string name, vfs::file::mode mode, bool required) -> vfs::shared::file override; auto load(uint id, string name, string type) -> maybe<uint> override; auto videoRefresh(const uint32* data, uint pitch, uint width, uint height) -> void override; auto audioSample(const double* samples, uint channels) -> void override; auto inputPoll(uint port, uint device, uint id) -> int16 override; //io.cpp auto readIO(uint24 addr, uint8 data) -> uint8; auto writeIO(uint24 addr, uint8 data) -> void; //serialization.cpp auto serialize(serializer&) -> void; uint revision; private: Emulator::Interface::Bind* bind = nullptr; GameBoy::Interface::Hook* hook = nullptr; struct Packet { auto operator[](uint addr) -> uint8& { return data[addr & 15]; } uint8 data[16]; }; Packet packet[64]; uint packetSize; uint joypID; bool joyp15Lock; bool joyp14Lock; bool pulseLock; bool strobeLock; bool packetLock; Packet joypPacket; uint8 packetOffset; uint8 bitData, bitOffset; uint8 r6003; //control port uint8 r6004; //joypad 1 uint8 r6005; //joypad 2 uint8 r6006; //joypad 3 uint8 r6007; //joypad 4 uint8 r7000[16]; //JOYP packet data uint8 mltReq; //number of active joypads uint8 output[4 * 512]; uint readBank; uint readAddress; uint writeBank; uint writeAddress; }; #else struct ICD2 : Thread { auto init() -> void {} auto load() -> void {} auto unload() -> void {} auto power() -> void {} auto reset() -> void {} auto readIO(uint24, uint8) -> uint8 { return 0; } auto writeIO(uint24, uint8) -> void { return; } auto serialize(serializer&) -> void {} uint revision; }; #endif extern ICD2 icd2;
[ "screwtape@froup.com" ]
screwtape@froup.com
3188c1945f3098789862fbfd3066a14e609dc7c3
ea4e3ac0966fe7b69f42eaa5a32980caa2248957
/download/unzip/WebKit2/WebKit2-7600.1.4.9/UIProcess/efl/WebContextEfl.cpp
003f10ecdc54f00b7367dbbc62b6d85ac7d06dfa
[]
no_license
hyl946/opensource_apple
36b49deda8b2f241437ed45113d624ad45aa6d5f
e0f41fa0d9d535d57bfe56a264b4b27b8f93d86a
refs/heads/master
2023-02-26T16:27:25.343636
2020-03-29T08:50:45
2020-03-29T08:50:45
249,169,732
0
0
null
null
null
null
UTF-8
C++
false
false
5,200
cpp
/* * Copyright (C) 2011 Samsung Electronics * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WebCookieManagerProxy.h" #include "WebContext.h" #include "Logging.h" #include "WebInspectorServer.h" #include "WebProcessCreationParameters.h" #include "WebProcessMessages.h" #include "WebSoupRequestManagerProxy.h" #include <Efreet.h> #include <WebCore/ApplicationCacheStorage.h> #include <WebCore/IconDatabase.h> #include <WebCore/NotImplemented.h> namespace WebKit { static void initializeInspectorServer() { #if ENABLE(INSPECTOR_SERVER) static bool initialized = false; if (initialized) return; // It should be set to true always. // Because it is to ensure initializeInspectorServer() is executed only once, // even if the server fails to run. initialized = true; String serverAddress(getenv("WEBKIT_INSPECTOR_SERVER")); if (!serverAddress.isNull()) { String bindAddress = ASCIILiteral("127.0.0.1"); unsigned short port = 2999; Vector<String> result; serverAddress.split(':', result); if (result.size() == 2) { bindAddress = result[0]; bool ok = false; port = result[1].toUInt(&ok); if (!ok) { port = 2999; LOG_ERROR("Couldn't parse the port. Using 2999 instead."); } } else LOG_ERROR("Couldn't parse %s, wrong format? Using 127.0.0.1:2999 instead.", serverAddress.utf8().data()); if (!WebInspectorServer::shared().listen(bindAddress, port)) LOG_ERROR("Couldn't start listening on: IP address=%s, port=%d.", bindAddress.utf8().data(), port); return; } LOG(InspectorServer, "To start inspector server set WEBKIT_INSPECTOR_SERVER to 127.0.0.1:2999 for example."); #endif } String WebContext::platformDefaultApplicationCacheDirectory() const { return String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl/Applications"; } void WebContext::platformInitializeWebProcess(WebProcessCreationParameters& parameters) { initializeInspectorServer(); parameters.urlSchemesRegistered = supplement<WebSoupRequestManagerProxy>()->registeredURISchemes(); supplement<WebCookieManagerProxy>()->getCookiePersistentStorage(parameters.cookiePersistentStoragePath, parameters.cookiePersistentStorageType); parameters.cookieAcceptPolicy = m_initialHTTPCookieAcceptPolicy; parameters.ignoreTLSErrors = m_ignoreTLSErrors; } void WebContext::platformInvalidateContext() { notImplemented(); } String WebContext::platformDefaultWebSQLDatabaseDirectory() { return String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/Databases"; } String WebContext::platformDefaultIndexedDBDatabaseDirectory() { notImplemented(); return String(); } String WebContext::platformDefaultIconDatabasePath() const { return String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/IconDatabase/" + WebCore::IconDatabase::defaultDatabaseFilename(); } String WebContext::platformDefaultLocalStorageDirectory() { return String::fromUTF8(efreet_data_home_get()) + "/WebKitEfl/LocalStorage"; } String WebContext::platformDefaultDiskCacheDirectory() const { return String::fromUTF8(efreet_cache_home_get()) + "/WebKitEfl"; } String WebContext::platformDefaultCookieStorageDirectory() const { notImplemented(); return String(); } String WebContext::platformDefaultOpenGLCacheDirectory() const { notImplemented(); return String(); } String WebContext::containerTemporaryDirectory() const { notImplemented(); return String(); } String WebContext::platformDefaultNetworkingHSTSDatabasePath() const { notImplemented(); return String(); } void WebContext::setIgnoreTLSErrors(bool ignoreTLSErrors) { m_ignoreTLSErrors = ignoreTLSErrors; sendToAllProcesses(Messages::WebProcess::SetIgnoreTLSErrors(m_ignoreTLSErrors)); } } // namespace WebKit
[ "hyl946@163.com" ]
hyl946@163.com
fe3eb1f49c89aa878cca6e52f68b71443b56bb45
f5f053975aadd70cadbf3831cb27d2873e51c808
/ceGame/stdafx.cpp
e78adafde8736ff597a94db3afd8f5dc9c210914
[]
no_license
YoelShoshan/Dooake
fd5ded20b21075276c27899215392f6078d8713e
254b74bc8fa30d38511d5bda992a59253cc8c37d
refs/heads/master
2021-01-20T11:11:23.048481
2016-09-15T20:03:32
2016-09-15T20:03:32
68,323,638
1
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
// stdafx.cpp : source file that includes just the standard includes // ceGame.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "yoelshoshan@gmail.com" ]
yoelshoshan@gmail.com
7f7fec9e141fb71a1d88b3694a2cba4dcaabc4ee
b72890d0e6503b4528bef2b09743f6df72cb01d2
/Captions/Implementation/include/Captions/CaptionTimingAdapterInterface.h
0b6e1a3d7983bed2c907e2503b1a2a2176d31f13
[ "Apache-2.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-pml-2020", "LicenseRef-.amazon.com.-AmznSL-1.0" ]
permissive
shivasiddharth/avs-device-sdk
b1375db55f204f1baaa9a4825e31f944a6e6d13c
c7ca5a12f65ce95f99d56fc7a1ab79cc96147ed8
refs/heads/master
2021-12-01T17:21:42.067397
2021-11-28T09:34:42
2021-11-28T09:34:42
152,394,898
0
2
Apache-2.0
2021-11-26T09:17:25
2018-10-10T09:09:11
C++
UTF-8
C++
false
false
2,707
h
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef ALEXA_CLIENT_SDK_CAPTIONS_IMPLEMENTATION_INCLUDE_CAPTIONS_CAPTIONTIMINGADAPTERINTERFACE_H_ #define ALEXA_CLIENT_SDK_CAPTIONS_IMPLEMENTATION_INCLUDE_CAPTIONS_CAPTIONTIMINGADAPTERINTERFACE_H_ #include "DelayInterface.h" #include <Captions/CaptionFrame.h> namespace alexaClientSDK { namespace captions { /** * An abstract class that is responsible for handling the timed display of @c CaptionFrame objects. Each @c * CaptionFrame's delay and duration values should be used with the @c DelayInterface to maintain this timing. * * Implementations of this class must be thread-safe and allow for asynchronous calls to any of the provided methods. */ class CaptionTimingAdapterInterface { public: /** * Destructor. */ virtual ~CaptionTimingAdapterInterface() = default; /** * Enqueues a @c CaptionFrame object for display. This method must begin the serial presentation of the enqueued * caption frames if such presentation is not already taking place and @c autostart is true. The order of the * caption frames must be maintained as first-in-first-out. * * @param captionFrame The @c CaptionFrame object to be enqueued for display. * @param autostart Determines if presentation should begin immediately if it has not already; defaults to true. */ virtual void queueForDisplay(const CaptionFrame& captionFrame, bool autostart = true) = 0; /** * Resets the state of this adapter, in preparation for new captions content. */ virtual void reset() = 0; /** * Resumes the playback of captions content, starting from the caption frame following the last one shown. */ virtual void start() = 0; /** * Stops the playback of captions, forgetting which caption frame was last shown. */ virtual void stop() = 0; /** * Pauses the playback of captions, keeping track of the last caption frame shown. */ virtual void pause() = 0; }; } // namespace captions } // namespace alexaClientSDK #endif // ALEXA_CLIENT_SDK_CAPTIONS_IMPLEMENTATION_INCLUDE_CAPTIONS_CAPTIONTIMINGADAPTERINTERFACE_H_
[ "ushivasiddharth@gmail.com" ]
ushivasiddharth@gmail.com
116859c465511b625ee69e08d672560283d57207
5781992b8eb5f8e8f6ce7ccf8069b60138b6f4d7
/old_src/GetDataDlg.cpp
8863f1716e40a52d5611f733dc0c30de6db56c7f
[]
no_license
liyonghelpme/dota-replay-manager
fd7c041cc48bac9fd726af4771a03fe8ec1a4ae6
21b965a8a63e077df275379d1f5055d77d98e580
refs/heads/master
2021-01-10T08:11:31.169556
2014-12-24T21:35:29
2014-12-24T21:35:29
36,912,875
1
1
null
null
null
null
UTF-8
C++
false
false
5,016
cpp
// GetDataDlg.cpp : implementation file // #include "stdafx.h" #include "DotAReplay.h" #include "GetDataDlg.h" #include "utils.h" #include "dota.h" #include ".\getdatadlg.h" // CGetDataDlg dialog IMPLEMENT_DYNAMIC(CGetDataDlg, CDialog) CGetDataDlg::CGetDataDlg(bool fixed, int version, char const* path, CWnd* pParent /*=NULL*/) : CDialog(CGetDataDlg::IDD, pParent) { ver = version; fix = fixed; pth = path; } CGetDataDlg::~CGetDataDlg() { } void CGetDataDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CGetDataDlg, CDialog) ON_BN_CLICKED(IDC_MAPBROWSE, OnBnClickedMapbrowse) ON_BN_CLICKED(IDC_CLOSEST, OnBnClickedClosest) ON_BN_CLICKED(IDC_COPYVERSION, OnBnClickedCopyversion) ON_BN_CLICKED(IDC_LOADMAP, OnBnClickedLoadmap) ON_BN_CLICKED(IDC_LOADTHISMAP, OnBnClickedLoadthismap) ON_EN_CHANGE(IDC_VERSION, OnEnChangeVersion) ON_BN_CLICKED(IDOK, OnBnClickedOk) END_MESSAGE_MAP() // CGetDataDlg message handlers BOOL CGetDataDlg::OnInitDialog () { CDialog::OnInitDialog (); if (fix) GetDlgItem (IDC_VERSION)->EnableWindow (FALSE); else { SetDlgItemText (IDC_VERSION_TIP, "Create data for"); CheckDlgButton (IDC_SAVEDATA, BST_CHECKED); GetDlgItem (IDC_SAVEDATA)->EnableWindow (FALSE); } if (ver) SetDlgItemText (IDC_VERSION, formatVersion (ver)); if (pth) SetDlgItemText (IDC_MAPTOLOAD, pth); else GetDlgItem (IDC_LOADMAP)->EnableWindow (FALSE); if (getNumVersions () == 0) { GetDlgItem (IDC_CLOSEST)->EnableWindow (FALSE); GetDlgItem (IDC_COPYVER)->EnableWindow (FALSE); GetDlgItem (IDC_COPYVERSION)->EnableWindow (FALSE); } else { CComboBox* vlist = (CComboBox*) GetDlgItem (IDC_COPYVER); int index = 0; int best = getClosestVersion (ver); sortVersions (); for (int i = 0; i < getNumVersions (); i++) { if (best == getVersion (i)) index = i; vlist->AddString (formatVersion (getVersion (i))); } vlist->SetCurSel (index); SetDlgItemText (IDC_CLOSEST, mprintf ("Copy data from closest version (%s)", formatVersion (best))); } return TRUE; } void CGetDataDlg::OnBnClickedMapbrowse() { char buf[1024]; GetDlgItemText (IDC_MAPTOLOAD, buf, sizeof buf); CFileDialog dlg (TRUE, ".w3x", buf, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, "DotA Maps|DotA?Allstars?v6.*.w3x;DotA?v6.*.w3x|All Warcraft Maps|*.w3m;*.w3x|All Files|*.*||", this, sizeof (OPENFILENAME)); if (dlg.DoModal () == IDOK) SetDlgItemText (IDC_MAPTOLOAD, dlg.GetPathName ()); } void CGetDataDlg::OnBnClickedClosest() { if (fix) GetDlgItem (IDC_SAVECHOICE)->EnableWindow (TRUE); char txt[256]; GetDlgItemText (IDC_VERSION, txt, sizeof txt); if (parseVersion (txt)) GetDlgItem (IDOK)->EnableWindow (TRUE); } void CGetDataDlg::OnBnClickedCopyversion() { if (fix) GetDlgItem (IDC_SAVECHOICE)->EnableWindow (FALSE); char txt[256]; GetDlgItemText (IDC_VERSION, txt, sizeof txt); if (parseVersion (txt)) GetDlgItem (IDOK)->EnableWindow (TRUE); } void CGetDataDlg::OnBnClickedLoadmap() { if (fix) GetDlgItem (IDC_SAVECHOICE)->EnableWindow (TRUE); char txt[256]; GetDlgItemText (IDC_VERSION, txt, sizeof txt); if (parseVersion (txt)) GetDlgItem (IDOK)->EnableWindow (TRUE); } void CGetDataDlg::OnBnClickedLoadthismap() { if (fix) GetDlgItem (IDC_SAVECHOICE)->EnableWindow (FALSE); char txt[256]; GetDlgItemText (IDC_VERSION, txt, sizeof txt); if (parseVersion (txt)) GetDlgItem (IDOK)->EnableWindow (TRUE); } void CGetDataDlg::OnEnChangeVersion() { char txt[256]; GetDlgItemText (IDC_VERSION, txt, sizeof txt); int ver = parseVersion (txt); if (ver == 0) GetDlgItem (IDOK)->EnableWindow (FALSE); else { if (IsDlgButtonChecked (IDC_CLOSEST) || IsDlgButtonChecked (IDC_COPYVERSION) || IsDlgButtonChecked (IDC_LOADMAP) || IsDlgButtonChecked (IDC_LOADTHISMAP)) GetDlgItem (IDOK)->EnableWindow (TRUE); int best = getClosestVersion (ver); if (best) SetDlgItemText (IDC_CLOSEST, mprintf ("Copy data from closest version (%s)", formatVersion (best))); } } void CGetDataDlg::OnBnClickedOk() { saved = IsDlgButtonChecked (IDC_SAVEDATA) != 0; alwaysdo = IsDlgButtonChecked (IDC_SAVECHOICE) != 0; GetDlgItemText (IDC_VERSION, path, sizeof path); ver = parseVersion (path); if (IsDlgButtonChecked (IDC_CLOSEST)) { mode = Closest; copyfrom = getClosestVersion (ver); } else if (IsDlgButtonChecked (IDC_COPYVERSION)) { mode = Version; GetDlgItemText (IDC_COPYVER, path, sizeof path); copyfrom = parseVersion (path); } else if (IsDlgButtonChecked (IDC_LOADMAP)) mode = Used; else //if (IsDlgButtonChecked (IDC_LOADTHISMAP)) { mode = Path; GetDlgItemText (IDC_MAPTOLOAD, path, sizeof path); } OnOK(); }
[ "d07.RiV@gmail.com" ]
d07.RiV@gmail.com
ecb6f4a6c5111c07eb32abc5e7961c926d5f9fc5
b428282a4c5923b3090a5c6306dc275bbe5cdb56
/Interface.h
eb11e347ed6b60f71a88441ac6799bb8891ac94c
[]
no_license
Mohamed-Omran/Chaos-Visualizer
bb5e91f97e153311b3c8966830545774b67d98ae
12b2fbc58f0f4b7fa4c504e2d9d128aa7dc4c101
refs/heads/master
2022-05-29T08:47:44.931664
2020-04-24T00:17:55
2020-04-24T00:17:55
255,491,543
0
0
null
null
null
null
UTF-8
C++
false
false
577
h
#pragma once #include<iostream> #include <cmath> #include"SFML\Graphics.hpp" #include"SFML\Window.hpp" #include"SFML\System.hpp" using namespace std; class Interface { private: sf::RenderWindow window; public: // setting up the program window Interface(); // Clears the frame (first step in rendering a new frame) void clear(); void control(); // Displays the frame (last step in rendering a new frame) void display(); // draws a double Pendulum void drawDP(double m1, double m2, double l1, double l2, double theta1, double theta2, sf::Vector2f pos); };
[ "kamelomran3@gmail.com" ]
kamelomran3@gmail.com
af2448d60acf315caeacc5e7a26b055b728d952c
ec5e5ad6c7ee721a8c623cb5101be4272c26a375
/compare_test.cpp
9489d513c86fcb57dd6df573bb842c65124cc6be
[]
no_license
1768012206/batch_verify
bf052bf8c60537fdc71cd71c9819607f74f1b74b
888fbba261a9c124c78752e01c99b733ef5c3fec
refs/heads/master
2020-04-11T07:14:59.210846
2017-12-12T11:11:36
2017-12-12T11:11:36
161,605,221
1
0
null
2018-12-13T08:08:50
2018-12-13T08:08:50
null
UTF-8
C++
false
false
1,807
cpp
#include <iostream> #include <ctime> #define MR_PAIRING_SSP #define AES_SECURITY 80 //#define AES_SECURITY 128 //************* //compare calculate time //(g1^r1)*...*(g100^r100) //(g1^w1)*...*(g100^w100) //************* #define NUM 40 #define W 4 #include "pairing_1.h" using namespace std; char* gen_exp(char* str) { int i,j; for(i=0;i<NUM*W;i=i+W) { str[i]='0'+rand()%2; for(j=1;j<=W;j++) { str[i+j]='0'; } } for(i=0;i<NUM*W-W+1;i++) { str[i]=str[i+W-1]; } return str; } int main() { srand((unsigned int)time(NULL)); PFC pfc(AES_SECURITY); miracl *mip=get_mip(); //mip->IOBASE=2; G1 g[100]; Big r[100],w[100]; char* str[100]; char str2[100][200]={'\0'}; int i; time_t seed; time(&seed); irand((long)seed); for(i=0;i<100;++i) { pfc.random(g[i]); pfc.random(r[i]); str[i]=gen_exp(str2[i]); } mip->IOBASE=2; for(i=0;i<100;++i) { w[i]=str[i]; } mip->IOBASE=16; clock_t s,d; double time; s=clock(); G1 t1=pfc.mult(g[0],r[0]); int x=bits(r[0]); cout<<x<<endl; cout<<r[0]<<endl; for(i=1;i<100;++i) { t1=t1+pfc.mult(g[i],r[i]); } d=clock(); time=(double)(d-s)*1000/CLOCKS_PER_SEC; cout<<"time:"<<time<<endl; clock_t ss,dd; ss=clock(); G1 t2=pfc.mult(g[0],w[0]); cout<<bits(w[0])<<endl; /*for(i=0;i<100;++i) { cout<<bits(w[i])<<endl; cout<<bits(r[i])<<endl; }*/ cout<<w[0]<<endl; for(i=1;i<100;++i) { t2=t2+pfc.mult(g[i],w[i]); } dd=clock(); time=(double)(dd-ss)*1000/CLOCKS_PER_SEC; cout<<"time:"<<time<<endl; char str3[100]={'\0'}; cout<<str3<<endl; return 0; }
[ "zyfwol@hotmail.com" ]
zyfwol@hotmail.com
7c68a08d914041cab171811f29a506fe7dc9b7e8
10111ad3c88c66260bbaa82ba60d776f8a070152
/T100/T100.ino
541cf2057e5c3d27afd3415773f2f05c298deb71
[]
no_license
techi602/arduino
1ed5c53f368c1c440274b53bb5c60cc94c63656e
bb0330ca669d1e0b01912cc5d0e55fcd4114d143
refs/heads/master
2021-01-11T20:41:30.519765
2019-05-08T16:04:19
2019-05-08T16:04:19
79,167,019
0
0
null
null
null
null
UTF-8
C++
false
false
9,043
ino
/* * T100 robot control * * Wemos D1 R2 + DOIT.AM shield https://github.com/SmartArduino/SZDOITWiKi/wiki/Arduino---2-way%26amp%3B16-way-motor%26amp%3Bservo-shield * SSD1306 oled siplay https://github.com/acrobotic/Ai_Ardulib_SSD1306 * * joystick coordinates math http://home.kendra.com/mauser/Joystick.html * * browser gamepad demo: * http://luser.github.io/gamepadtest/ * http://internetexplorer.github.io/Gamepad-Sample/ */ #ifdef ESP32 #define PWMRANGE 1023 #include <WiFi.h> #include <WiFiClient.h> #include <WiFiMulti.h> #include <WebServer.h> #include <ESPmDNS.h> #else #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #endif #include <Arduino.h> #include <WebSocketsServer.h> #include <string.h> #include <Wire.h> #include <ACROBOTIC_SSD1306.h> #include "joystick.js.h" #include "control.html.h" #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 64 // OLED display height, in pixels // WiFi parameters #include "secrets.h" #ifndef WIFI_SSID #define WIFI_SSID "wifi" #endif #ifndef WIFI_PASSWORD #define WIFI_PASSWORD "" #endif const char* ssid = WIFI_SSID; const char* password = WIFI_PASSWORD; char buffer[40]; #ifdef ESP32 //MDNSResponder mdns; WiFiMulti WiFiMulti; WebServer server(80); WebSocketsServer webSocket = WebSocketsServer(81); #else MDNSResponder mdns; ESP8266WiFiMulti WiFiMulti; ESP8266WebServer server(80); WebSocketsServer webSocket = WebSocketsServer(81); #endif #define PWMA D6 #define PWMB D4 #define DIRA D7 #define DIRB D5 #define POWER_PIN D8 // speed range from -100 to +100 int motor_speed_left = 0; int motor_speed_right = 0; void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) { Serial.printf("webSocketEvent(%d, %d, ...)\r\n", num, type); switch (type) { case WStype_DISCONNECTED: { Serial.printf("[%u] Disconnected!\r\n", num); oled.clearDisplay(); oled.putString("Client disconnected"); break; } case WStype_CONNECTED: { IPAddress ip = webSocket.remoteIP(num); sprintf(buffer, "[%u] Connected from %d.%d.%d.%d url: %s\r\n", num, ip[0], ip[1], ip[2], ip[3], payload); Serial.printf(buffer); // Send the current LED status webSocket.sendTXT(0, "HELLO", 5); oled.clearDisplay(); oled.setTextXY(0,0); oled.putString("Client connected"); oled.setTextXY(1,0); oled.putString(buffer); break; } case WStype_TEXT: { Serial.printf("[%u] get Text: %s\r\n", num, payload); // motor:<leftspeed>:<rightspeed> if (strncmp("motor", (const char *)payload, 5) == 0) { const char delim[2] = ":"; char *token; // expect "motor" token = strtok((char *)payload, delim); // expect left speed as string token = strtok(NULL, delim); motor_speed_left = atoi(token); // expect right speed as string token = strtok(NULL, delim); motor_speed_right = atoi(token); setMotorSpeed(motor_speed_left, motor_speed_right); Serial.print("Setting motor speed "); Serial.print(motor_speed_left); Serial.print(' '); Serial.println(motor_speed_right); // display delay too slow blocking socket IO /* oled.setTextXY(0,0); oled.putString("Motor speed"); oled.setTextXY(1,0); oled.putString(" "); oled.putNumber(motor_speed_left); oled.setTextXY(2,0); oled.putString(" "); oled.putNumber(motor_speed_right); */ } else if (strcmp("on", (const char *)payload) == 0) { robot_on(); oled.setTextXY(0,0); oled.putString("FIRE! "); } else if (strcmp("off", (const char *)payload) == 0) { robot_off(); } else if (strcmp("stop", (const char *)payload) == 0) { robot_stop(); } else { Serial.print("Unknown command: "); Serial.println((const char *)payload); } // send data to all connected clients // too slow - blocking IO //webSocket.broadcastTXT(payload, length); break; } case WStype_BIN: { Serial.printf("[%u] get binary length: %u\r\n", num, length); //hexdump(payload, length); // echo data back to browser //webSocket.sendBIN(num, payload, length); break; } default: { Serial.printf("Invalid WStype [%d]\r\n", type); break; } } } void handleRoot() { server.send_P(200, "text/html", INDEX_HTML); } void handleJoystickJs() { server.send_P(200, "text/javascript", JOYSTICK_JS); } void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } String IPAddress2String(IPAddress address) { return String(address[0]) + "." + String(address[1]) + "." + String(address[2]) + "." + String(address[3]); } void setup(void) { pinMode(DIRA, OUTPUT); pinMode(DIRB, OUTPUT); pinMode(PWMA, OUTPUT); pinMode(PWMB, OUTPUT); pinMode(POWER_PIN, OUTPUT); analogWrite(PWMA, 0); analogWrite(PWMB, 0); digitalWrite(DIRA, LOW); digitalWrite(DIRB, LOW); digitalWrite(POWER_PIN, LOW); Serial.begin(115200); Serial.println(); Serial.println(); Serial.println(); Serial.println("T100 booting"); Wire.begin(); // Initialze SSD1306 OLED display oled.init(); oled.clearDisplay(); oled.setTextXY(0,0); oled.putString("Connecting to Wi-Fi..."); // my mobile hotspot WiFiMulti.addAP("AndroidAP", "uche7888"); WiFiMulti.addAP(ssid, password); while (WiFiMulti.run() != WL_CONNECTED) { //oled.write('.'); Serial.print("."); delay(100); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.println(WiFi.localIP()); oled.clearDisplay(); oled.setTextXY(0, 0); oled.putString("Connected"); oled.setTextXY(1, 0); oled.putString(ssid); oled.setTextXY(2, 0); oled.putString(IPAddress2String(WiFi.localIP())); if (mdns.begin("t100", WiFi.localIP())) { Serial.println("MDNS responder started"); mdns.addService("http", "tcp", 80); mdns.addService("ws", "tcp", 81); } else { Serial.println("MDNS.begin failed"); } Serial.print("Connect to http://t100.local"); Serial.println(""); Serial.println(WiFi.localIP()); server.on("/", handleRoot); server.on("/virtualjoystick.js", handleJoystickJs); server.onNotFound(handleNotFound); server.begin(); webSocket.begin(); webSocket.onEvent(webSocketEvent); } void loop() { webSocket.loop(); server.handleClient(); } /** * Speed will be * * @param leftSpeed left motor speed -100 to +100 * @param rightSpeed right motor speed -100 to +100 */ void setMotorSpeed(int leftSpeed, int rightSpeed) { const int minSpeedTreshhold = 10; const int maxSpeedTreshhold = 100; const int minPwmSpeed = PWMRANGE / 4; const int maxPwmSpeed = PWMRANGE; if (abs(leftSpeed) < minSpeedTreshhold) { leftSpeed = 0; } if (abs(rightSpeed) < minSpeedTreshhold) { rightSpeed = 0; } digitalWrite(DIRA, leftSpeed < 0 ? HIGH : LOW); digitalWrite(DIRB, rightSpeed > 0 ? HIGH : LOW); if (leftSpeed) { analogWrite(PWMA, map(abs(leftSpeed), 0, maxSpeedTreshhold, minPwmSpeed, maxPwmSpeed)); } else { analogWrite(PWMA, 0); } if (rightSpeed) { analogWrite(PWMB, map(abs(rightSpeed), 0, maxSpeedTreshhold, minPwmSpeed, maxPwmSpeed)); } else { analogWrite(PWMB, 0); } } void robot_stop() { setMotorSpeed(0, 0); } void robot_on() { digitalWrite(POWER_PIN, HIGH); } void robot_off() { digitalWrite(POWER_PIN, LOW); }
[ "michal.vrchota@gmail.com" ]
michal.vrchota@gmail.com
73d483a7d12242d7dce43c3da5e539b635e1e2eb
86b55c5bfd3cbce99db30907ecc63c0038b0f1e2
/chrome/browser/chromeos/login/screens/update_required_screen.cc
2c7ac3bdbb9995f4f9da4c9df69d4469ee3c8d95
[ "BSD-3-Clause" ]
permissive
Claw-Lang/chromium
3ed8160ea3f2b5d51fdc2a7d764aadd5b443eb3f
651cebac57fcd0ce2c7c974494602cc098fe7348
refs/heads/master
2022-11-19T07:46:03.573023
2020-07-28T06:45:27
2020-07-28T06:45:27
283,134,740
1
0
BSD-3-Clause
2020-07-28T07:26:49
2020-07-28T07:26:48
null
UTF-8
C++
false
false
15,325
cc
// Copyright (c) 2017 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 "chrome/browser/chromeos/login/screens/update_required_screen.h" #include <algorithm> #include <utility> #include "ash/public/cpp/login_screen.h" #include "ash/public/cpp/system_tray.h" #include "base/bind.h" #include "base/logging.h" #include "base/time/default_clock.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chromeos/login/error_screens_histogram_helper.h" #include "chrome/browser/chromeos/login/helper.h" #include "chrome/browser/chromeos/login/screen_manager.h" #include "chrome/browser/chromeos/login/ui/login_display.h" #include "chrome/browser/chromeos/login/ui/login_display_host.h" #include "chrome/browser/chromeos/login/wizard_controller.h" #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h" #include "chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/network/network_handler.h" #include "chromeos/network/network_state_handler.h" #include "chromeos/settings/cros_settings_names.h" #include "ui/chromeos/devicetype_utils.h" namespace { constexpr char kUserActionSelectNetworkButtonClicked[] = "select-network"; constexpr char kUserActionUpdateButtonClicked[] = "update"; constexpr char kUserActionAcceptUpdateOverCellular[] = "update-accept-cellular"; constexpr char kUserActionRejectUpdateOverCellular[] = "update-reject-cellular"; // Delay before showing error message if captive portal is detected. // We wait for this delay to let captive portal to perform redirect and show // its login page before error message appears. constexpr const base::TimeDelta kDelayErrorMessage = base::TimeDelta::FromSeconds(10); } // namespace namespace chromeos { // static UpdateRequiredScreen* UpdateRequiredScreen::Get(ScreenManager* manager) { return static_cast<UpdateRequiredScreen*>( manager->GetScreen(UpdateRequiredView::kScreenId)); } UpdateRequiredScreen::UpdateRequiredScreen(UpdateRequiredView* view, ErrorScreen* error_screen) : BaseScreen(UpdateRequiredView::kScreenId, OobeScreenPriority::SCREEN_UPDATE_REQUIRED), view_(view), error_screen_(error_screen), histogram_helper_( std::make_unique<ErrorScreensHistogramHelper>("UpdateRequired")), version_updater_(std::make_unique<VersionUpdater>(this)), clock_(base::DefaultClock::GetInstance()) { error_message_delay_ = kDelayErrorMessage; eol_message_subscription_ = CrosSettings::Get()->AddSettingsObserver( chromeos::kDeviceMinimumVersionAueMessage, base::Bind(&UpdateRequiredScreen::OnEolMessageChanged, weak_factory_.GetWeakPtr())); if (view_) view_->Bind(this); } UpdateRequiredScreen::~UpdateRequiredScreen() { StopObservingNetworkState(); if (view_) view_->Unbind(); } void UpdateRequiredScreen::OnViewDestroyed(UpdateRequiredView* view) { if (view_ == view) view_ = nullptr; } void UpdateRequiredScreen::ShowImpl() { ash::LoginScreen::Get()->SetAllowLoginAsGuest(false); policy::BrowserPolicyConnectorChromeOS* connector = g_browser_process->platform_part()->browser_policy_connector_chromeos(); view_->SetEnterpriseAndDeviceName(connector->GetEnterpriseDisplayDomain(), ui::GetChromeOSDeviceName()); is_shown_ = true; if (first_time_shown_) { first_time_shown_ = false; if (view_) { view_->SetUIState(UpdateRequiredView::UPDATE_REQUIRED_MESSAGE); view_->Show(); } } // Check network state to set initial screen UI. RefreshNetworkState(); // Fire it once so we're sure we get an invocation on startup. OnEolMessageChanged(); version_updater_->GetEolInfo(base::BindOnce( &UpdateRequiredScreen::OnGetEolInfo, weak_factory_.GetWeakPtr())); } void UpdateRequiredScreen::OnGetEolInfo( const chromeos::UpdateEngineClient::EolInfo& info) { // TODO(crbug.com/1020616) : Handle if the device is left on this screen // for long enough to reach Eol. if (chromeos::switches::IsAueReachedForUpdateRequiredForTest() || (!info.eol_date.is_null() && info.eol_date <= clock_->Now())) { EnsureScreenIsShown(); if (view_) view_->SetUIState(UpdateRequiredView::EOL_REACHED); } else { // UI state does not change for EOL devices. // Subscribe to network state change notifications to adapt the UI as // network changes till update is started. ObserveNetworkState(); } } void UpdateRequiredScreen::OnEolMessageChanged() { chromeos::CrosSettingsProvider::TrustedStatus status = CrosSettings::Get()->PrepareTrustedValues( base::BindOnce(&UpdateRequiredScreen::OnEolMessageChanged, weak_factory_.GetWeakPtr())); if (status != chromeos::CrosSettingsProvider::TRUSTED) return; std::string eol_message; if (view_ && CrosSettings::Get()->GetString( chromeos::kDeviceMinimumVersionAueMessage, &eol_message)) { view_->SetEolMessage(eol_message); } } void UpdateRequiredScreen::HideImpl() { if (view_) view_->Hide(); is_shown_ = false; StopObservingNetworkState(); } void UpdateRequiredScreen::OnUserAction(const std::string& action_id) { if (action_id == kUserActionSelectNetworkButtonClicked) { OnSelectNetworkButtonClicked(); } else if (action_id == kUserActionUpdateButtonClicked) { OnUpdateButtonClicked(); } else if (action_id == kUserActionAcceptUpdateOverCellular) { if (version_updater_->update_info().status.current_operation() == update_engine::Operation::NEED_PERMISSION_TO_UPDATE) { version_updater_->SetUpdateOverCellularOneTimePermission(); } else { // This is to handle the case when metered network screen is shown at the // start and user accepts update over it. metered_network_update_permission = true; StopObservingNetworkState(); version_updater_->StartNetworkCheck(); } } else if (action_id == kUserActionRejectUpdateOverCellular) { version_updater_->RejectUpdateOverCellular(); version_updater_->StartExitUpdate(VersionUpdater::Result::UPDATE_ERROR); } else { BaseScreen::OnUserAction(action_id); } } void UpdateRequiredScreen::DefaultNetworkChanged(const NetworkState* network) { // Refresh the screen UI to reflect network state. RefreshNetworkState(); } void UpdateRequiredScreen::RefreshNetworkState() { // Do not refresh the UI if the update process has started. This can be // encountered if error screen is shown and later hidden due to captive portal // after starting the update process. if (!view_ || is_updating_now_) return; NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler(); const NetworkState* network = handler->DefaultNetwork(); // Set the UI state as per the current network state. // If device was connected to a good network at the start, we are already // showing (by default) the update required screen. If network switches from // one good network to another, it has no change in the UI state. This is only // till the update process is triggered. Post that, update engine status // drives the UI state. if (!network || !network->IsConnectedState()) { // No network is available for the update process to start. view_->SetUIState(UpdateRequiredView::UPDATE_NO_NETWORK); waiting_for_connection_ = false; } else if (handler->default_network_is_metered()) { // The device is either connected to a metered network at the start or has // switched to one. view_->SetUIState(UpdateRequiredView::UPDATE_NEED_PERMISSION); waiting_for_connection_ = true; } else if (waiting_for_connection_) { // The device has switched from a metered network to a good network. Start // the update process automatically and unsubscribe from the network change // notifications as any change in network state is reflected in the update // engine result. waiting_for_connection_ = false; is_updating_now_ = true; view_->SetUIState(UpdateRequiredView::UPDATE_PROCESS); StopObservingNetworkState(); version_updater_->StartNetworkCheck(); } else { // The device is either connected to a good network at the start or has // switched from no network to good network. view_->SetUIState(UpdateRequiredView::UPDATE_REQUIRED_MESSAGE); } } void UpdateRequiredScreen::RefreshView( const VersionUpdater::UpdateInfo& update_info) { if (!view_) return; if (update_info.requires_permission_for_cellular) { view_->SetUIState(UpdateRequiredView::UPDATE_NEED_PERMISSION); waiting_for_connection_ = true; } else if (waiting_for_connection_) { // Return UI state after getting permission. view_->SetUIState(UpdateRequiredView::UPDATE_PROCESS); waiting_for_connection_ = false; } view_->SetUpdateProgressUnavailable(update_info.progress_unavailable); view_->SetUpdateProgressValue(update_info.progress); view_->SetUpdateProgressMessage(update_info.progress_message); view_->SetEstimatedTimeLeftVisible(update_info.show_estimated_time_left); view_->SetEstimatedTimeLeft(update_info.estimated_time_left_in_secs); } void UpdateRequiredScreen::ObserveNetworkState() { if (!is_network_subscribed_) { is_network_subscribed_ = true; NetworkHandler::Get()->network_state_handler()->AddObserver(this, FROM_HERE); } } void UpdateRequiredScreen::StopObservingNetworkState() { if (is_network_subscribed_) { is_network_subscribed_ = false; NetworkHandler::Get()->network_state_handler()->RemoveObserver(this, FROM_HERE); } } void UpdateRequiredScreen::OnSelectNetworkButtonClicked() { ash::SystemTray::Get()->ShowNetworkDetailedViewBubble( true /* show_by_click */); } void UpdateRequiredScreen::OnUpdateButtonClicked() { if (is_updating_now_) return; is_updating_now_ = true; if (view_) view_->SetUIState(UpdateRequiredView::UPDATE_PROCESS); // Do not need network notification now as UI state depends on the result // received from the update engine. StopObservingNetworkState(); version_updater_->StartNetworkCheck(); } void UpdateRequiredScreen::OnWaitForRebootTimeElapsed() { LOG(ERROR) << "Unable to reboot - asking for a manual reboot."; EnsureScreenIsShown(); if (view_) view_->SetUIState(UpdateRequiredView::UPDATE_COMPLETED_NEED_REBOOT); } void UpdateRequiredScreen::PrepareForUpdateCheck() { VLOG(1) << "Update check started."; error_message_timer_.Stop(); error_screen_->HideCaptivePortal(); connect_request_subscription_.reset(); if (version_updater_->update_info().state == VersionUpdater::State::STATE_ERROR) HideErrorMessage(); } void UpdateRequiredScreen::ShowErrorMessage() { error_message_timer_.Stop(); is_shown_ = false; connect_request_subscription_ = error_screen_->RegisterConnectRequestCallback( base::BindRepeating(&UpdateRequiredScreen::OnConnectRequested, weak_factory_.GetWeakPtr())); error_screen_->SetUIState(NetworkError::UI_STATE_UPDATE); error_screen_->SetParentScreen(UpdateRequiredView::kScreenId); error_screen_->SetHideCallback(base::BindOnce( &UpdateRequiredScreen::OnErrorScreenHidden, weak_factory_.GetWeakPtr())); error_screen_->SetIsPersistentError(true /* is_persistent */); error_screen_->Show(nullptr); histogram_helper_->OnErrorShow(error_screen_->GetErrorState()); } void UpdateRequiredScreen::UpdateErrorMessage( const NetworkPortalDetector::CaptivePortalStatus status, const NetworkError::ErrorState& error_state, const std::string& network_name) { error_screen_->SetErrorState(error_state, network_name); if (status == NetworkPortalDetector::CAPTIVE_PORTAL_STATUS_PORTAL) { if (is_first_portal_notification_) { is_first_portal_notification_ = false; error_screen_->FixCaptivePortal(); } } } void UpdateRequiredScreen::DelayErrorMessage() { if (error_message_timer_.IsRunning()) return; error_message_timer_.Start(FROM_HERE, error_message_delay_, this, &UpdateRequiredScreen::ShowErrorMessage); } void UpdateRequiredScreen::SetErrorMessageDelayForTesting( const base::TimeDelta& delay) { error_message_delay_ = delay; } void UpdateRequiredScreen::UpdateInfoChanged( const VersionUpdater::UpdateInfo& update_info) { switch (update_info.status.current_operation()) { case update_engine::Operation::CHECKING_FOR_UPDATE: case update_engine::Operation::ATTEMPTING_ROLLBACK: case update_engine::Operation::DISABLED: case update_engine::Operation::IDLE: break; case update_engine::Operation::UPDATE_AVAILABLE: case update_engine::Operation::DOWNLOADING: case update_engine::Operation::VERIFYING: case update_engine::Operation::FINALIZING: EnsureScreenIsShown(); break; case update_engine::Operation::NEED_PERMISSION_TO_UPDATE: VLOG(1) << "Need permission to update."; EnsureScreenIsShown(); if (metered_network_update_permission) { version_updater_->SetUpdateOverCellularOneTimePermission(); return; } break; case update_engine::Operation::UPDATED_NEED_REBOOT: VLOG(1) << "Update completed successfully."; EnsureScreenIsShown(); waiting_for_reboot_ = true; version_updater_->RebootAfterUpdate(); break; case update_engine::Operation::ERROR: case update_engine::Operation::REPORTING_ERROR_EVENT: LOG(ERROR) << "Exiting update due to error."; version_updater_->StartExitUpdate(VersionUpdater::Result::UPDATE_ERROR); break; default: NOTREACHED(); } RefreshView(update_info); } void UpdateRequiredScreen::FinishExitUpdate(VersionUpdater::Result result) { if (waiting_for_reboot_) return; is_updating_now_ = false; if (view_) view_->SetUIState(UpdateRequiredView::UPDATE_ERROR); } VersionUpdater* UpdateRequiredScreen::GetVersionUpdaterForTesting() { return version_updater_.get(); } void UpdateRequiredScreen::SetClockForTesting(base::Clock* clock) { clock_ = clock; } void UpdateRequiredScreen::EnsureScreenIsShown() { if (is_shown_ || !view_) return; is_shown_ = true; histogram_helper_->OnScreenShow(); view_->Show(); } void UpdateRequiredScreen::HideErrorMessage() { error_screen_->Hide(); if (view_) view_->Show(); histogram_helper_->OnErrorHide(); } void UpdateRequiredScreen::OnConnectRequested() { if (version_updater_->update_info().state == VersionUpdater::State::STATE_ERROR) { LOG(WARNING) << "Hiding error message since AP was reselected"; version_updater_->StartUpdateCheck(); } } void UpdateRequiredScreen::OnErrorScreenHidden() { error_screen_->SetParentScreen(OobeScreen::SCREEN_UNKNOWN); // Return to the default state. error_screen_->SetIsPersistentError(false /* is_persistent */); Show(context()); } } // namespace chromeos
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
0271d29b0d2a1706e464afd33e2f649114a116b5
d14620edb869dd735f481b7d4c0502f4afa5de89
/ERAnalysis/ERAnaLowEnergyExcess.h
d2dc528f437c1229c979b75af74d39e784fce5f5
[]
no_license
soleti/LowEnergyExcess
7cfa7c6bfe337125e951c3ee07c1ceb4f6d7e64d
fc7052fe2a0f9633c3ebe75a78e6e2b74dead9ef
refs/heads/master
2021-01-18T17:32:46.634898
2016-02-08T20:21:26
2016-02-08T20:21:26
51,940,077
0
0
null
2016-02-17T17:10:42
2016-02-17T17:10:42
null
UTF-8
C++
false
false
5,659
h
/** * \file ERAnaLowEnergyExcess.h * * \ingroup LowEPlots * * \brief Class def header for a class ERAnaLowEnergyExcess * * @author jzennamo */ /** \addtogroup LowEPlots @{*/ #ifndef ERTOOL_ERAnaLowEnergyExcess_H #define ERTOOL_ERAnaLowEnergyExcess_H #include "ERTool/Base/AnaBase.h" #include "TTree.h" #include "TH1D.h" #include "TH2F.h" #include <string> #include "DataFormat/mctruth.h" // #include "ERToolBackend/ParticleID.h" #include "../../LArLiteApp/fluxRW/fluxRW.h" #include "GeoAlgo/GeoAABox.h" #include "LArUtil/Geometry.h" #include "LEERW.h" #include <cmath> #include "GeoAlgo/GeoAlgo.h" #include "ECCQECalculator.h" namespace ertool { /** \class ERAnaLowEnergyExcess User custom Analysis class made by kazuhiro */ class ERAnaLowEnergyExcess : public AnaBase { public: /// Default constructor ERAnaLowEnergyExcess(const std::string& name = "ERAnaLowEnergyExcess"); /// Default destructor virtual ~ERAnaLowEnergyExcess() {} /// Reset function virtual void Reset() {} /// Function to accept fclite::PSet void AcceptPSet(const ::fcllite::PSet& cfg) {} /// Called @ before processing the first event sample void ProcessBegin(); /// Function to evaluate input showers and determine a score bool Analyze(const EventData &data, const ParticleGraph &ps); /// Called after processing the last event sample void ProcessEnd(TFile* fout); /// setting result tree name for running the LowEExcess plotting code void SetTreeName(const std::string& name) { _treename = name; } //Set this to true if you're running over LEE sample (so it uses LEE reweighting package) void SetLEESampleMode(bool flag) { _LEESample_mode = flag; } private: // Calc new E_nu^calo, with missing pT cut double EnuCaloMissingPt(const std::vector< ::ertool::NodeID_t >& Children, const ParticleGraph &graph); // Determine if the event is "simple" (1e, np, 0else) bool isInteractionSimple(const Particle &singleE, const ParticleGraph &ps); /// Function to compute BITE relevant variables (in ttree) and fill them void FillBITEVariables(const Shower &singleE_shower, const Particle &p); /// Function to compute BNB flux RW weight, or LEE weight (if in LEE mode) double GetWeight(const ParticleGraph mc_graph); /// Function to compute various neutrino energy definitions and fill them void FillRecoNuEnergies(const Particle &nue, const ParticleGraph &ps, const EventData &data); // Result tree comparison for reconstructed events TTree* _result_tree; std::string _treename; double _e_nuReco; /// Neutrino energy double _e_dep; /// Neutrino energy double _weight; int _parentPDG; /// true PDG of parent of the electron (only for running on MC) int _ptype; /// neutrino ptype to further break down nue slice in stacked histo int _mcPDG; /// true PDG of "single electron" (probably 11 or 22) int _mcGeneration; /// True generation of single electron (to characterize cosmics and other backgrounds) double _longestTrackLen; /// longest track associated with the reconstructed neutrino double _x_vtx; /// Neutrino vertex points (x,y,z separated) double _y_vtx; double _z_vtx; double _e_theta; /// Electron's angle w.r.t/ z- axis double _e_phi; /// Electron's phi angle double _e_Edep; /// Electron's truth energy double _e_CCQE; /// Electron's CCQE energy double _nu_p; /// Neutrino reconstructed momentum magnitude double _nu_pt; /// Component of nu momentum that is transverse (_nu_p*sin(_nu_theta)) double _nu_theta; /// Neutrino's reconstructed angle w.r.t. z- axis int _n_children; /// Number of children associated with the neutrino interaction bool _is_simple; /// Whether the interaction is 1e+np+0else (reconstructed) double _dedx; /// dedx of "single electron" shower double _flash_time; /// opflash associated with electron... flash time double _summed_flash_PE; /// total reconstructed PE of the flash bool _maybe_pi0_MID; /// whether the neutrino has a gamma tagged as one of its children int _n_ertool_showers; /// total number of ertool::Showers in the event int _n_nues_in_evt; /// # of nues reconstructed in the entire event (pi0 evts sometimes have two ) bool _has_muon_child; /// If there is a muon associated with the reconstructed nue double _e_nuReco_better; /// trying a better definition of energy // prepare TTree with variables void PrepareTreeVariables(); /// Function to re-set TTree variables void ResetTreeVariables(); ::fluxRW _fluxRW; // ertool_helper::ParticleID singleE_particleID; ertool::Shower singleE_shower; bool _LEESample_mode = false; // Variables for B.I.T.E analysis double _dist_2wall ; /// Electron backwards distance 2 wall double _dist_2wall_vtx; /// Vertex backwards distance 2 wall ::geoalgo::AABox _vactive; protected: ::lee::LEERW _rw; ::geoalgo::GeoAlgo _geoalg; ::lee::util::ECCQECalculator _eccqecalc; }; } #endif /** @} */ // end of doxygen group
[ "kaleko@nevis.columbia.edu" ]
kaleko@nevis.columbia.edu
b2b10818f170c7cf148561b19bc6ea998949cb29
20b49a6ef1fa417d67abef2d29a598c9e41c478e
/CodeForces/Contests/CF Raif Round 1/E.cpp
cf6e1f534a271171a454fc2d2b117640665e9f4c
[]
no_license
switchpiggy/Competitive_Programming
956dac4a71fdf65de2959dd142a2032e2f0710e1
beaaae4ece70889b0af1494d68c630a6e053558a
refs/heads/master
2023-04-15T19:13:12.348433
2021-04-04T06:12:29
2021-04-04T06:12:29
290,905,106
1
3
null
2020-10-05T20:16:53
2020-08-27T23:38:48
C++
UTF-8
C++
false
false
228
cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; ll n, k, a[100007]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> k; for(ll i = 0; i < n; ++i) cin >> a[i]; }
[ "switchpiggy@users.noreply.github.com" ]
switchpiggy@users.noreply.github.com
a531c6469ac83b521ea4292ffd9a07a2f6db70a7
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE762_Mismatched_Memory_Management_Routines/s03/CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_67a.cpp
f2f5563d0d85d90e2338403a7962c7c668541af7
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
3,034
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_67a.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-67a.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_67 { typedef struct _structType { char * structFirst; } structType; #ifndef OMITBAD /* bad function declaration */ void badSink(structType myStruct); void bad() { char * data; structType myStruct; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (char *)realloc(data, 100*sizeof(char)); myStruct.structFirst = data; badSink(myStruct); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(structType myStruct); static void goodG2B() { char * data; structType myStruct; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using new */ data = new char; myStruct.structFirst = data; goodG2BSink(myStruct); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(structType myStruct); static void goodB2G() { char * data; structType myStruct; /* Initialize data*/ data = NULL; data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (char *)realloc(data, 100*sizeof(char)); myStruct.structFirst = data; goodB2GSink(myStruct); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_char_realloc_67; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
f3ceb9f2b47b342f8d43847abac7e20c0647278a
2d1f82fe5c4818ef1da82d911d0ed81a0b41ec85
/codeforces/gym/2018-2019 XIX Open Cup, Grand Prix of Korea/CF102059K.cpp
dc69bb2c3134f4a14f46d00095a69bbb50bb6148
[]
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
1,009
cpp
#include <bits/stdc++.h> using namespace std; const int maxn = 312345; long long fen[maxn]; int c[maxn], d[maxn]; int n; vector<int> G[maxn]; inline int lowbit(int x) { return x & -x; } void upd(int x, long long val) { while (x > 0) { fen[x] = max(fen[x], val); x -= lowbit(x); } } long long query(int x) { long long ret = 0; while (x <= n) { ret = max(fen[x], ret); x += lowbit(x); } return ret; } int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", c + i); if (i >= c[i] && c[i] != 1) G[i - c[i] + 1].emplace_back(i); } for (int i = 1; i <= n; i++) scanf("%d", d + i); for (int i = 1; i <= n; i++) { for (int j = int(G[i].size()) - 1; j >= 0; j--) { int u = G[i][j]; upd(u - 1, query(u) + d[u]); } printf("%lld ", query(i) + (c[i] == 1 ? d[i] : 0)); if (i + c[i] - 1 <= n) upd(i + c[i] - 1, query(i + c[i] - 1) + d[i]); } }
[ "zhangbin199807@gmail.com" ]
zhangbin199807@gmail.com
00d2c641daed2358b91070f40a04a0e8b04ac94e
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/ds/security/cryptoapi/secstor/prov/provui.cpp
850366d88f3aa29a48da731798f9cc203c57e6f7
[]
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
81,501
cpp
/* File: ProvUI.cpp Title: Base provider user interface Author: Matt Thomlinson Date: 12/13/96 ProvUI houses all user interface for the provider. During startup, InitUI() fetches all user strings from the resource string table. During shutdown, ReleaseUI() frees them. The other miscellaneous functions gather passwords, define new password groups and retrieve the windows password if it has changed. */ #include <pch.cpp> #pragma hdrstop #include <commctrl.h> #include "provui.h" #include "storage.h" #include "passwd.h" #include "filemisc.h" extern DISPIF_CALLBACKS g_sCallbacks; extern PRIVATE_CALLBACKS g_sPrivateCallbacks; extern HINSTANCE g_hInst; extern BOOL g_fAllowCachePW; // cached authentication list extern CUAList* g_pCUAList; HICON g_DefaultIcon = NULL; BOOL g_fUIInitialized = FALSE; CRITICAL_SECTION g_csUIInitialized; // string resources LPWSTR g_StringBlock = NULL; // single allocated block containing all sz strings LPWSTR g_ItemDetailsBannerMessage; LPWSTR g_PasswordDuplicate; LPWSTR g_PasswordAddError; LPWSTR g_PasswordChangeError; LPWSTR g_PasswordCreate; LPWSTR g_PasswordNoMatch; LPWSTR g_PasswordMustName; LPWSTR g_PasswordChange; LPWSTR g_PasswordSolicitOld; LPWSTR g_PasswordErrorDlgTitle; LPWSTR g_PasswordWin95Garbage; LPWSTR g_PasswordNoVerify; LPWSTR g_PasswordWinNoVerify; LPWSTR g_PWPromptPrefix; LPWSTR g_PWPromptSuffix; LPWSTR g_SimplifiedDlgMessageFormat; LPWSTR g_PromptReadItem; LPWSTR g_PromptOpenItem; LPWSTR g_PromptWriteItem; LPWSTR g_PromptDeleteItem; LPWSTR g_PromptHighSecurity; LPWSTR g_PromptMedSecurity; LPWSTR g_PromptLowSecurity; LPWSTR g_TitleContainerMapping; #define MAX_PW_LEN 160 #define MAX_STRING_RSC_SIZE 512 // define something not likely to be entered by a user #define WSZ_PASSWORD_CHANGE_DETECT_TOKEN L"[]{}9d1Dq" // // this one comes and goes only when needed // typedef DWORD (WINAPI *WNETVERIFYPASSWORD)( LPCSTR lpszPassword, BOOL *pfMatch ); /////////////////////////////////////////////////////////////////////////// // Forwards INT_PTR CALLBACK DialogAdvancedConfirmH( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); INT_PTR CALLBACK DialogAccessDetails( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); INT_PTR CALLBACK DialogOldNewPassword( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); INT_PTR CALLBACK DialogSolicitOldPassword( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); INT_PTR CALLBACK DialogSetSecurityLevel( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); INT_PTR CALLBACK DialogSimplifiedPasswordConfirm( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); INT_PTR CALLBACK DialogWaitForOKCancel( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ); int ServicesDialogBoxParam( HINSTANCE hInstance, // handle to application instance LPCTSTR lpTemplateName, // identifies dialog box template HWND hWndParent, // handle to owner window DLGPROC lpDialogFunc, // pointer to dialog box procedure LPARAM dwInitParam // initialization value ); BOOL FetchString( HMODULE hModule, // module to get string from UINT ResourceId, // resource identifier LPWSTR *String, // target buffer for string LPWSTR *StringBlock, // string buffer block DWORD *dwBufferSize, // size of string buffer block DWORD *dwRemainingBufferSize // remaining size of string buffer block ); BOOL CALLBACK FMyLoadIcon( HINSTANCE hModule, // resource-module handle LPCTSTR lpszType, // pointer to resource type LPWSTR lpszName, // pointer to resource name LONG_PTR lParam // application-defined parameter ); /////////////////////////////////////////////////////////////////////////// // Exposed functions #define GLOBAL_STRING_BUFFERSIZE 3800 BOOL InitUI() { DWORD dwBufferSize; DWORD dwRemainingBufferSize; BOOL bSuccess = FALSE; if( g_fUIInitialized ) return TRUE; // // take crit sec // EnterCriticalSection( &g_csUIInitialized ); // // check the global to prevent a race condition that would cause // re-init to occur. // if( g_fUIInitialized ) { bSuccess = TRUE; goto cleanup; } g_DefaultIcon = LoadIcon(g_hInst, MAKEINTRESOURCE(IDI_ICON1)); if(g_DefaultIcon == NULL) goto cleanup; // // get size of all string resources, and then allocate a single block // of memory to contain all the strings. This way, we only have to // free one block and we benefit memory wise due to locality of reference. // dwBufferSize = dwRemainingBufferSize = GLOBAL_STRING_BUFFERSIZE; g_StringBlock = (LPWSTR)SSAlloc(dwBufferSize); if(g_StringBlock == NULL) goto cleanup; if(!FetchString(g_hInst, IDS_ITEM_DETAILS_BANNER, &g_ItemDetailsBannerMessage, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_CREATE_MESSAGE, &g_PasswordCreate, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_NOMATCH, &g_PasswordNoMatch, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_CHANGE_MESSAGE, &g_PasswordChange, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_MUSTNAME, &g_PasswordMustName, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_SOLICIT_OLD_MESSAGE, &g_PasswordSolicitOld, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_DUPLICATE, &g_PasswordDuplicate, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_ADD_ERROR, &g_PasswordAddError, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_CHANGE_ERROR, &g_PasswordChangeError, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_ERROR_DLGTITLE, &g_PasswordErrorDlgTitle, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_WIN95_PASSWORDS_AREGARBAGE, &g_PasswordWin95Garbage, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_NOVERIFY, &g_PasswordNoVerify, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_WIN_NOVERIFY, &g_PasswordWinNoVerify, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_PROMPT_PREFIX, &g_PWPromptPrefix, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PASSWORD_PROMPT_SUFFIX, &g_PWPromptSuffix, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_SIMPLIFIED_DLG_MSG, &g_SimplifiedDlgMessageFormat, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_READITEM, &g_PromptReadItem, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_OPENITEM, &g_PromptOpenItem, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_WRITEITEM, &g_PromptWriteItem, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_DELETEITEM, &g_PromptDeleteItem, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_HIGH_SECURITY, &g_PromptHighSecurity, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_MED_SECURITY, &g_PromptMedSecurity, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_PROMPT_LOW_SECURITY, &g_PromptLowSecurity, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; if(!FetchString(g_hInst, IDS_TITLE_CONTAINER_MAPPING, &g_TitleContainerMapping, &g_StringBlock, &dwBufferSize, &dwRemainingBufferSize)) goto cleanup; // // if the block was realloc'ed to a different location, re-fetch strings // very unlikely to ever happen // #if DBG if(GLOBAL_STRING_BUFFERSIZE != dwBufferSize) OutputDebugString(TEXT("Forced to realloc global string area in provui.cpp:InitUI()\n")); #endif bSuccess = TRUE; cleanup: if(!bSuccess) { if(g_StringBlock) { SSFree(g_StringBlock); g_StringBlock = NULL; } } else { g_fUIInitialized = TRUE; } LeaveCriticalSection( &g_csUIInitialized ); return bSuccess; } BOOL ReleaseUI() { g_DefaultIcon = NULL; if(g_StringBlock) { SSFree(g_StringBlock); g_StringBlock = NULL; } #if 0 g_PasswordDuplicate = g_PasswordAddError = g_PasswordChangeError = g_PasswordCreate = g_PasswordNoMatch = g_PasswordMustName = g_PasswordChange = g_PasswordSolicitOld = g_PasswordErrorDlgTitle = g_PasswordWin95Garbage = g_PasswordNoVerify = g_PasswordWinNoVerify = g_PWPromptPrefix = g_PWPromptSuffix = g_SimplifiedDlgMessageFormat = g_PromptReadItem = g_PromptOpenItem = g_PromptWriteItem = g_PromptDeleteItem = g_PromptHighSecurity = g_PromptMedSecurity = g_PromptLowSecurity = NULL; #endif return TRUE; } BOOL FIsProviderUIAllowed( LPCWSTR szUser ) { // // UI always allowed under Win95. // if(!FIsWinNT()) return TRUE; // // UI is not allowed on NT when running as local system. // if(lstrcmpiW(szUser, TEXTUAL_SID_LOCAL_SYSTEM) == 0) return FALSE; return TRUE; } LPWSTR SZMakeDisplayableType(LPCWSTR szType,LPCWSTR szSubtype) { // create a nice UI string LPWSTR szUIType = (LPWSTR)SSAlloc(( wcslen(szType)+ 3 + // L" ()" wcslen(szSubtype) + 1 // L"\0" ) * sizeof(WCHAR)); if(szUIType == NULL) return FALSE; // sprintf: Subtype(Type) wcscpy(szUIType, szSubtype); wcscat(szUIType, L" ("); wcscat(szUIType, szType); wcscat(szUIType, L")"); return szUIType; } BOOL MyGetPwdHashEx( LPWSTR szPW, BYTE rgbPasswordDerivedBytes[A_SHA_DIGEST_LEN], BOOL fLowerCase ) { A_SHA_CTX sSHAHash; DWORD cbPassword; LPWSTR TemporaryPassword = NULL; LPWSTR PasswordToHash; // don't include NULL termination cbPassword = WSZ_BYTECOUNT(szPW) - sizeof(WCHAR); if ( fLowerCase ) { TemporaryPassword = (LPWSTR) SSAlloc( cbPassword + sizeof(WCHAR) ); if( TemporaryPassword == NULL ) return FALSE; CopyMemory(TemporaryPassword, szPW, cbPassword + sizeof(WCHAR) ); // // Win95: inconsistent handling of pwds // forces inplace convert to uppercase // MyToUpper(TemporaryPassword); PasswordToHash = TemporaryPassword; } else { PasswordToHash = szPW; } // hash pwd, copy out A_SHAInit(&sSHAHash); // Hash password A_SHAUpdate(&sSHAHash, (BYTE *) PasswordToHash, cbPassword); A_SHAFinal(&sSHAHash, rgbPasswordDerivedBytes); if( TemporaryPassword ) SSFree( TemporaryPassword ); return TRUE; } BOOL MyGetPwdHash( LPWSTR szPW, BYTE rgbPasswordDerivedBytes[A_SHA_DIGEST_LEN] ) { if (!FIsWinNT()) { // Win95: inconsistent handling of pwds // forces inplace convert to uppercase MyGetPwdHashEx( szPW, rgbPasswordDerivedBytes, TRUE ); } else { MyGetPwdHashEx( szPW, rgbPasswordDerivedBytes, FALSE ); } return TRUE; } BOOL FetchString( HMODULE hModule, // module to get string from UINT ResourceId, // resource identifier LPWSTR *String, // target buffer for string LPWSTR *StringBlock, // string buffer block DWORD *dwBufferSize, // size of string buffer block DWORD *dwRemainingBufferSize // remaining size of string buffer block ) { WCHAR szMessage[MAX_STRING_RSC_SIZE]; DWORD cchMessage; if(StringBlock == NULL || *StringBlock == NULL || String == NULL) return FALSE; cchMessage = LoadStringU( hModule, ResourceId, szMessage, MAX_STRING_RSC_SIZE); if(cchMessage == 0) return FALSE; if(*dwRemainingBufferSize < (cchMessage+1) * sizeof(WCHAR)) { // // realloc buffer and update size // DWORD dwOldSize = *dwBufferSize; DWORD dwNewSize = dwOldSize + ((cchMessage + 1) * sizeof(WCHAR)) ; *StringBlock = (LPWSTR)SSReAlloc( *StringBlock, dwNewSize ); if(*StringBlock == NULL) return FALSE; *dwBufferSize = dwNewSize; *dwRemainingBufferSize += dwNewSize - dwOldSize; } *String = (LPWSTR)((LPBYTE)*StringBlock + *dwBufferSize - *dwRemainingBufferSize); wcscpy(*String, szMessage); *dwRemainingBufferSize -= (cchMessage + 1) * sizeof(WCHAR); return TRUE; } int ServicesDialogBoxParam( HINSTANCE hInstance, // handle to application instance LPCTSTR lpTemplateName, // identifies dialog box template HWND hWndParent, // handle to owner window DLGPROC lpDialogFunc, // pointer to dialog box procedure LPARAM dwInitParam // initialization value ) /*++ This function is implemented to allow UI to originate from the Protected Storage service on Windows NT 5.0 installations. This UI will go to the user desktop, rather than an invisible desktop which would otherwise cause DialogBoxParam() calls to fail. --*/ { HWINSTA hOldWinsta = NULL; HWINSTA hNewWinsta = NULL; HDESK hOldDesk = NULL; HDESK hNewDesk = NULL; int iRet = -1; if( FIsWinNT5() ) { hOldWinsta = GetProcessWindowStation(); if(hOldWinsta == NULL) goto cleanup; hOldDesk = GetThreadDesktop( GetCurrentThreadId() ); if(hOldDesk == NULL) goto cleanup; hNewWinsta = OpenWindowStationW( L"WinSta0", FALSE, MAXIMUM_ALLOWED ); if(hNewWinsta == NULL) goto cleanup; if(!SetProcessWindowStation( hNewWinsta )) goto cleanup; hNewDesk = OpenDesktopW( L"default", 0, FALSE, MAXIMUM_ALLOWED ); if(hNewDesk == NULL) goto cleanup; if(!SetThreadDesktop( hNewDesk )) { if( GetLastError() != ERROR_BUSY ) goto cleanup; // // the desktop object is locked/in-use. Most likely explanation // is nested dialog box calls. Just put the process windowstation // back and continue.. // SetProcessWindowStation( hOldWinsta ); } } INITCOMMONCONTROLSEX initcomm; initcomm.dwSize = sizeof(initcomm); initcomm.dwICC = ICC_STANDARD_CLASSES | ICC_WIN95_CLASSES; InitCommonControlsEx(&initcomm); iRet = (int)DialogBoxParam( hInstance, // handle to application instance lpTemplateName, // identifies dialog box template hWndParent, // handle to owner window lpDialogFunc, // pointer to dialog box procedure dwInitParam // initialization value ); cleanup: if( hOldWinsta ) { SetProcessWindowStation( hOldWinsta ); } if( hOldDesk ) { SetThreadDesktop( hOldDesk ); } if( hNewWinsta ) { CloseWindowStation( hNewWinsta ); } if( hNewDesk ) { CloseDesktop( hNewDesk ); } return iRet; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // exposed Dialog setup functions BOOL FSimplifiedPasswordConfirm( PST_PROVIDER_HANDLE* phPSTProv, LPCWSTR szUserName, LPCWSTR szCallerName, LPCWSTR szType, LPCWSTR szSubtype, LPCWSTR szItemName, PPST_PROMPTINFO psPrompt, LPCWSTR szAccessType, LPWSTR* ppszPWName, DWORD* pdwPasswordOptions, BOOL fAllowUserFreedom, BYTE rgbPasswordDerivedBytes[], DWORD cbPasswordDerivedBytes, BYTE rgbPasswordDerivedBytesLowerCase[], DWORD cbPasswordDerivedBytesLowerCase, DWORD dwFlags ) { if ((rgbPasswordDerivedBytes == NULL) || (cbPasswordDerivedBytes < A_SHA_DIGEST_LEN)) return FALSE; if ((rgbPasswordDerivedBytesLowerCase == NULL) || (cbPasswordDerivedBytesLowerCase < A_SHA_DIGEST_LEN)) return FALSE; BOOL fRet = FALSE; LPWSTR pszUIPassword = NULL; // actual pwd LPWSTR szUIType = NULL; BOOL fCacheThisPasswd; // unDONE UNDONE going away DWORD cchItemName; LPCWSTR szTitle = szItemName; // default titlebar to itemname. // // check if szItemName is a GUID, if so, map the title to something legible. // cchItemName = lstrlenW( szItemName ); if( cchItemName == 36 ) { if( szItemName[ 8 ] == L'-' && szItemName[ 13 ] == L'-' && szItemName[ 18 ] == L'-' && szItemName[ 23 ] == L'-' ) { szTitle = g_TitleContainerMapping; } } else if( cchItemName == 38 ) { if( szItemName[ 0 ] == L'{' && szItemName[ 9 ] == L'-' && szItemName[ 14 ] == L'-' && szItemName[ 19 ] == L'-' && szItemName[ 24 ] == L'-' && szItemName[ 37 ] == L'}' ) { szTitle = g_TitleContainerMapping; } } if (NULL == (szUIType = SZMakeDisplayableType( szType, szSubtype)) ) return FALSE; int iRet; // PST_ flags go in.. // okay, take the hit PW_DIALOG_ARGS DialogArgs = { phPSTProv, szCallerName, szAccessType, psPrompt->szPrompt, szUIType, szTitle, szUserName, ppszPWName, &pszUIPassword, pdwPasswordOptions, fAllowUserFreedom, // allow user to change protection? &fCacheThisPasswd, rgbPasswordDerivedBytes, rgbPasswordDerivedBytesLowerCase }; if(FIsWinNT()) { BOOL fAuthID; if (!g_sCallbacks.pfnFImpersonateClient( phPSTProv )) { goto Ret; } fAuthID = GetThreadAuthenticationId(GetCurrentThread(), &(DialogArgs.luidAuthID)); g_sCallbacks.pfnFRevertToSelf( phPSTProv ); if( !fAuthID ) { goto Ret; } } DialogArgs.dwFlags = dwFlags; iRet = ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_SIMPLIFIED_PASSWD), (HWND)psPrompt->hwndApp, DialogSimplifiedPasswordConfirm, (LPARAM)&DialogArgs); if(iRet != IDOK) goto Ret; // BP_ flags, derived bytes come out fRet = TRUE; Ret: if (pszUIPassword) SSFree(pszUIPassword); if (szUIType) SSFree(szUIType); return fRet; } BOOL FChangePassword( HWND hParentWnd, LPCWSTR szUserName) { BOOL fRet = FALSE; LPWSTR pszOldPW = NULL, pszNewPW = NULL, pszSelectedPW = NULL; BYTE rgbOldPasswordDerivedBytes[A_SHA_DIGEST_LEN]; BYTE rgbNewPasswordDerivedBytes[A_SHA_DIGEST_LEN]; int iRet; OLDNEWPW_DIALOGARGS DialogArgs = {szUserName, &pszSelectedPW, &pszOldPW, &pszNewPW}; iRet = ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_PASSWORD_CHANGE), hParentWnd, DialogOldNewPassword, (LPARAM)&DialogArgs); if(iRet != IDOK) goto Ret; // and check response if ((pszOldPW == NULL) || (pszNewPW == NULL) || (pszSelectedPW == NULL)) goto Ret; if (!MyGetPwdHash(pszNewPW, rgbNewPasswordDerivedBytes)) goto Ret; ZeroMemory(pszNewPW, WSZ_BYTECOUNT(pszNewPW)); // sfield: zero the password if (!MyGetPwdHash(pszOldPW, rgbOldPasswordDerivedBytes)) goto Ret; // and now commit change if (!FPasswordChangeNotify( szUserName, pszSelectedPW, rgbOldPasswordDerivedBytes, sizeof(rgbOldPasswordDerivedBytes), rgbNewPasswordDerivedBytes, sizeof(rgbNewPasswordDerivedBytes) )) { // this W implemented in both Win95 & NT! MessageBoxW( NULL, // hParentWnd, g_PasswordChangeError, g_PasswordErrorDlgTitle, MB_OK | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION); goto Ret; } ZeroMemory(pszOldPW, WSZ_BYTECOUNT(pszOldPW)); // sfield: zero the password fRet = TRUE; Ret: if (pszOldPW) SSFree(pszOldPW); if (pszNewPW) SSFree(pszNewPW); if (pszSelectedPW) SSFree(pszSelectedPW); return fRet; } // In the case I detected a pwd change, but need the old password to migrate // (NOTE: assume I already have had the new password typed in once) BOOL FGetChangedPassword( PST_PROVIDER_HANDLE* phPSTProv, HWND hParentWnd, LPCWSTR szUserName, LPCWSTR szPasswordName, BYTE rgbNewPasswordDerivedBytes[]) { BOOL fRet = FALSE; LPWSTR pszOldPW = NULL; LPWSTR pszNewPW = NULL; BYTE rgbOldPasswordDerivedBytes[A_SHA_DIGEST_LEN]; if(wcscmp(szPasswordName, WSZ_PASSWORD_WINDOWS) == 0) { // // migrate old style windows password to new style. // if(!g_sPrivateCallbacks.pfnFGetWindowsPassword( phPSTProv, rgbOldPasswordDerivedBytes, A_SHA_DIGEST_LEN )) goto Ret; } else { int iRet; SOLICITOLDPW_DIALOGARGS DialogArgs = {szPasswordName, &pszOldPW, (FIsWinNT() ? NULL : &pszNewPW)}; while(TRUE) { iRet = ServicesDialogBoxParam( g_hInst, FIsWinNT() ? MAKEINTRESOURCE(IDD_SecPass_WinNT) : MAKEINTRESOURCE(IDD_SecPass_Win95), NULL, DialogSolicitOldPassword, (LPARAM)&DialogArgs); if(iRet != IDOK) goto Ret; // if win95, verify 'new' win pwd if ((!FIsWinNT()) && (0 == wcscmp(szPasswordName, WSZ_PASSWORD_WINDOWS)) ) { BOOL bSuccess = FALSE; CHAR PasswordANSI[MAX_PW_LEN]; HMODULE hMprModule; WNETVERIFYPASSWORD _WNetVerifyPassword; // on fail, uh... continue? if (NULL == (hMprModule = LoadLibraryA("mpr.dll")) ) goto FailGracefully; if (NULL == (_WNetVerifyPassword = (WNETVERIFYPASSWORD)GetProcAddress(hMprModule, "WNetVerifyPasswordA")) ) goto FailGracefully; if (0 == (WideCharToMultiByte( CP_ACP, 0, *DialogArgs.ppszNewPW, -1, PasswordANSI, MAX_PW_LEN, NULL, NULL)) ) goto FailGracefully; if(_WNetVerifyPassword(PasswordANSI, &bSuccess) != WN_SUCCESS) goto FailGracefully; if (!bSuccess) { MessageBoxW( NULL, // hParentWnd, g_PasswordWin95Garbage, g_PasswordErrorDlgTitle, MB_OK|MB_SERVICE_NOTIFICATION); continue; // loop } // slam over the top of NewPasswordDerivedBytes -- this pwd is always correct if (!MyGetPwdHash(*DialogArgs.ppszNewPW, rgbNewPasswordDerivedBytes)) goto Ret; FailGracefully: // cleanup ZeroMemory(*DialogArgs.ppszNewPW, WSZ_BYTECOUNT(*DialogArgs.ppszNewPW)); SSFree(*DialogArgs.ppszNewPW); ZeroMemory(PasswordANSI, sizeof(PasswordANSI)); FreeLibrary(hMprModule); } break; } // and check response if (pszOldPW == NULL) goto Ret; if (!MyGetPwdHash(pszOldPW, rgbOldPasswordDerivedBytes)) goto Ret; } // and now commit change if (!FPasswordChangeNotify( szUserName, szPasswordName, rgbOldPasswordDerivedBytes, sizeof(rgbOldPasswordDerivedBytes), rgbNewPasswordDerivedBytes, A_SHA_DIGEST_LEN)) { // this W implemented in both Win95 & NT! MessageBoxW( NULL, // hParentWnd, g_PasswordChangeError, g_PasswordErrorDlgTitle, MB_OK | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION); goto Ret; } fRet = TRUE; Ret: if (pszOldPW) { ZeroMemory(pszOldPW, WSZ_BYTECOUNT(pszOldPW)); // sfield: zero the password SSFree(pszOldPW); } if(!fRet && wcscmp(szPasswordName, WSZ_PASSWORD_WINDOWS) == 0) { // // TODO: migration of existing Windows key failed! // Nuke existing data. // } return fRet; } BOOL FInternal_CreateNewPasswordEntry( HWND hParentWnd, LPCWSTR szUserName, LPWSTR szPWName, LPWSTR szPW) { BOOL fRet = FALSE; BYTE rgbPasswordDerivedBytes[A_SHA_DIGEST_LEN]; // and check response if ((szPW == NULL) || (szPWName == NULL)) goto Ret; // everything went fine, now derive the password bits! if (!MyGetPwdHash(szPW, rgbPasswordDerivedBytes)) goto Ret; // and now commit change if (!FPasswordChangeNotify( szUserName, szPWName, NULL, 0, rgbPasswordDerivedBytes, A_SHA_DIGEST_LEN )) { LPWSTR szMessage; if (PST_E_ITEM_EXISTS == GetLastError()) { szMessage = g_PasswordDuplicate; } else { szMessage = g_PasswordAddError; } // this W implemented in both Win95 & NT! MessageBoxW( NULL, //hParentWnd, szMessage, g_PasswordErrorDlgTitle, MB_OK | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION); goto Ret; } fRet = TRUE; Ret: return fRet; } BOOL ChooseSecurityWizard(HWND hDlg, ADVANCEDCONFIRM_DIALOGARGS* pDialogArgs) { // make copy of pDialogArgs so we don't change original // unless everything goes ok LPWSTR szPWName_Stack = NULL; LPWSTR szPW_Stack = NULL; // no need to pull original password out DWORD dwPasswordOptions_Stack; DWORD dwReturnStatus; ADVANCEDCONFIRM_DIALOGARGS DlgArgs_Stack = { pDialogArgs->szUserName, &szPWName_Stack, &szPW_Stack, &dwPasswordOptions_Stack, pDialogArgs->szItemName}; if(*(pDialogArgs->ppszPWName) != NULL) { szPWName_Stack = (LPWSTR)SSAlloc(WSZ_BYTECOUNT(*(pDialogArgs->ppszPWName))); if(szPWName_Stack == NULL) { goto Ret; } wcscpy(szPWName_Stack, *(pDialogArgs->ppszPWName)); } dwPasswordOptions_Stack = *(pDialogArgs->pdwPasswordOptions); Choose_Step1: dwReturnStatus = ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_ADVANCED_CONFIRM), (HWND)hDlg, DialogSetSecurityLevel, (LPARAM)&DlgArgs_Stack); // if user decides not to choose, bail if (IDOK != dwReturnStatus) goto Ret; // else, switch on his decision switch (*(DlgArgs_Stack.pdwPasswordOptions)) { case (BP_CONFIRM_PASSWORDUI): { dwReturnStatus = ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_ADVANCED_CONFIRM_H), (HWND)hDlg, DialogAdvancedConfirmH, (LPARAM)&DlgArgs_Stack); // if user hits okay, execute if (IDOK == dwReturnStatus) goto ExecuteChange; // if user wants back, go back if (IDC_BACK == dwReturnStatus) goto Choose_Step1; // else, bail break; } case (BP_CONFIRM_OKCANCEL): { dwReturnStatus = ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_ADVANCED_CONFIRM_M), (HWND)hDlg, DialogWaitForOKCancel, (LPARAM)pDialogArgs); // if user hits okay, execute if (IDOK == dwReturnStatus) goto ExecuteChange; // if user wants back, go back if (IDC_BACK == dwReturnStatus) goto Choose_Step1; // else, bail break; } case (BP_CONFIRM_NONE): { dwReturnStatus = ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_ADVANCED_CONFIRM_L), (HWND)hDlg, DialogWaitForOKCancel, (LPARAM)pDialogArgs); // if user hits okay, execute if (IDOK == dwReturnStatus) goto ExecuteChange; // if user wants back, go back if (IDC_BACK == dwReturnStatus) goto Choose_Step1; // else, bail break; } default: break; } Ret: // free dyn alloced DialogArgs we aren't returning if (*(DlgArgs_Stack.ppszPWName)) SSFree(*(DlgArgs_Stack.ppszPWName)); if (*(DlgArgs_Stack.ppszPW)) SSFree(*(DlgArgs_Stack.ppszPW)); return FALSE; ExecuteChange: // free what we already know, point to newly alloc'ed pointers if (*(pDialogArgs->ppszPWName)) SSFree(*(pDialogArgs->ppszPWName)); *(pDialogArgs->ppszPWName) = szPWName_Stack; if (*(pDialogArgs->ppszPW)) SSFree(*(pDialogArgs->ppszPW)); *(pDialogArgs->ppszPW) = szPW_Stack; *(pDialogArgs->pdwPasswordOptions) = dwPasswordOptions_Stack; return TRUE; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Actual Dialog Callbacks INT_PTR CALLBACK DialogAdvancedConfirmH( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { BOOL bSuccess = FALSE; // assume error PADVANCEDCONFIRM_DIALOGARGS pDialogArgs; BYTE rgb1[_MAX_PATH]; LPWSTR pszMasterKey=NULL; char * szBuffer = NULL; DWORD dwCount; DWORD dwStatus; switch (message) { case WM_INITDIALOG: SetLastError( 0 ); // as per win32 documentation if(SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam) == 0) { if(GetLastError() != ERROR_SUCCESS) { EndDialog(hDlg, IDCANCEL); return FALSE; } } // lParam is struct pDialogArgs = (PADVANCEDCONFIRM_DIALOGARGS)lParam; // set dialog title SetWindowTextU(hDlg, pDialogArgs->szItemName); SetWindowTextU(GetDlgItem(hDlg, IDC_MESSAGE), g_PasswordCreate); // clear pwds SendDlgItemMessage(hDlg, IDC_PW_NAME, CB_RESETCONTENT, 0, 0); // Add known pwds for (dwCount=0; ;dwCount++) { if (PST_E_OK != BPEnumMasterKeys( pDialogArgs->szUserName, dwCount, &pszMasterKey)) break; // don't add non-editable passwords if (!FIsUserMasterKey(pszMasterKey)) continue; // add this to the list and continue if (FIsWinNT()) { SendDlgItemMessageW(hDlg, IDC_PW_NAME, CB_ADDSTRING, 0, (LPARAM) pszMasterKey); } #ifdef _M_IX86 else { // only add if (! (NULL username && Windows password)) if ( (0 != wcscmp(pDialogArgs->szUserName, L"")) || (0 != wcscmp(pszMasterKey, WSZ_PASSWORD_WINDOWS)) ) { MkMBStr(rgb1, _MAX_PATH, pszMasterKey, &szBuffer); SendDlgItemMessageA(hDlg, IDC_PW_NAME, CB_ADDSTRING, 0, (LPARAM) szBuffer); FreeMBStr(rgb1, szBuffer); } } #endif // _M_IX86 SSFree(pszMasterKey); } // check to see if there are any items in listbox dwStatus = (DWORD) SendDlgItemMessageW(hDlg, IDC_PW_NAME, CB_GETCOUNT, 0, 0); if ((dwStatus == CB_ERR) || (dwStatus == 0)) { // Listbox empty! // set default dialog selection to be "new password" EnableWindow(GetDlgItem(hDlg, IDC_RADIO_SELEXISTING), FALSE); SendMessage(hDlg, WM_COMMAND, IDC_RADIO_DEFINENEW, 0); // as if user clicked NEW SendDlgItemMessage(hDlg, IDC_RADIO_DEFINENEW, BM_SETCHECK, (WPARAM)BST_CHECKED, 0); } else { // Items do exist! // set default in dropdown if (FIsWinNT()) dwStatus = (DWORD) SendDlgItemMessageW(hDlg, IDC_PW_NAME, CB_SELECTSTRING, (WORD)-1, (LPARAM) *(pDialogArgs->ppszPWName)); #ifdef _M_IX86 else { MkMBStr(rgb1, _MAX_PATH, (*pDialogArgs->ppszPWName), &szBuffer); dwStatus = SendDlgItemMessageA(hDlg, IDC_PW_NAME, CB_SELECTSTRING, (WORD)-1, (LONG) szBuffer); FreeMBStr(rgb1, szBuffer); } #endif // _M_IX86 // if search failed, select first item in listbox if (dwStatus == CB_ERR) SendDlgItemMessage(hDlg, IDC_PW_NAME, CB_SETCURSEL, 0, 0); // set default dialog selection to be "existing pw" EnableWindow(GetDlgItem(hDlg, IDC_RADIO_SELEXISTING), TRUE); SendMessage(hDlg, WM_COMMAND, IDC_RADIO_SELEXISTING, 0); // as if user clicked EXISTING SendDlgItemMessage(hDlg, IDC_RADIO_SELEXISTING, BM_SETCHECK, (WPARAM)BST_CHECKED, 0); } return TRUE; case WM_COMMAND: { pDialogArgs = (PADVANCEDCONFIRM_DIALOGARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out switch (LOWORD(wParam)) { case (IDOK): { if( *(pDialogArgs->ppszPWName) ) { SSFree(*(pDialogArgs->ppszPWName)); *(pDialogArgs->ppszPWName) = NULL; } if(BST_CHECKED == SendDlgItemMessage(hDlg, IDC_RADIO_SELEXISTING, BM_GETCHECK, 0, 0)) { WCHAR sz1[MAX_PW_LEN]; DWORD cch1; // and get password name cch1 = GetDlgItemTextU( hDlg, IDC_PW_NAME, sz1, MAX_PW_LEN); *(pDialogArgs->ppszPWName) = (LPWSTR)SSAlloc((cch1+1)*sizeof(WCHAR)); if(NULL != *(pDialogArgs->ppszPWName)) { wcscpy(*(pDialogArgs->ppszPWName), sz1); } } else { LPWSTR* ppszPW; LPWSTR* ppszPWName; WCHAR sz1[MAX_PW_LEN]; WCHAR sz2[MAX_PW_LEN]; WCHAR szPWName[MAX_PW_LEN]; DWORD cch1 = 0, cch2 = 0, cchPWName = 0; ppszPW = pDialogArgs->ppszPW; ppszPWName = pDialogArgs->ppszPWName; // don't stomp existing ppszPW/ppszPWName until we know we're okay cch1 = GetDlgItemTextU( hDlg, IDC_EDIT1, sz1, MAX_PW_LEN); cch2 = GetDlgItemTextU( hDlg, IDC_EDIT2, sz2, MAX_PW_LEN); if ( (cch1 != cch2) || (0 != wcscmp(sz1, sz2)) ) { // this W implemented in both Win95 & NT! MessageBoxW( NULL, // hDlg, g_PasswordNoMatch, g_PasswordErrorDlgTitle, MB_OK | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION); SetWindowTextU(GetDlgItem(hDlg, IDC_EDIT1), WSZ_NULLSTRING); SetWindowTextU(GetDlgItem(hDlg, IDC_EDIT2), WSZ_NULLSTRING); goto cleanup; } cchPWName = GetDlgItemTextU( hDlg, IDC_PW_NEWNAME, szPWName, MAX_PW_LEN); if (cchPWName == 0) { // this W implemented in both Win95 & NT! MessageBoxW( NULL, // hDlg, g_PasswordMustName, g_PasswordErrorDlgTitle, MB_OK | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION); goto cleanup; } // trim spaces off rhs while(0 == memcmp(&szPWName[cchPWName-1], L" ", sizeof(WCHAR))) cchPWName--; szPWName[cchPWName] = L'\0'; // try and create the pw entry if (!FInternal_CreateNewPasswordEntry( hDlg, pDialogArgs->szUserName, szPWName, sz1) ) goto cleanup; // now bite it: save both SS_ASSERT(ppszPW != NULL); *ppszPW = (LPWSTR)SSAlloc( (cch1+1) * sizeof(WCHAR) ); if(*ppszPW == NULL) goto cleanup; SS_ASSERT(ppszPWName != NULL); *ppszPWName = (LPWSTR)SSAlloc( (cchPWName + 1) * sizeof(WCHAR)); if(*ppszPWName == NULL) goto cleanup; // // sfield: defer copying strings until we know everything succeeded. // this way, we don't have to zero these buffers if some // allocs + copies succeed, and others fail. // wcscpy(*ppszPW, sz1); wcscpy(*ppszPWName, szPWName); bSuccess = TRUE; cleanup: if(cch1) ZeroMemory(sz1, cch1 * sizeof(WCHAR)); if(cch2) ZeroMemory(sz2, cch2 * sizeof(WCHAR)); if(cchPWName) ZeroMemory(szPWName, cchPWName * sizeof(WCHAR)); if(!bSuccess) { // UNDONE: investigate freeing ppsz's on error here return FALSE; } break; // things went OK, just bail to EndDialog } } // IDOK // gray out options case IDC_RADIO_SELEXISTING: // set default selection to be "existing pw" EnableWindow(GetDlgItem(hDlg, IDC_PW_NAME), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_PW_NEWNAME), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_EDIT1), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_EDIT2), FALSE); // set focus to first box under button SetFocus(GetDlgItem(hDlg, IDC_PW_NAME)); break; case IDC_RADIO_DEFINENEW: // set default selection to be "existing pw" EnableWindow(GetDlgItem(hDlg, IDC_PW_NAME), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_PW_NEWNAME), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_EDIT1), TRUE); EnableWindow(GetDlgItem(hDlg, IDC_EDIT2), TRUE); // set focus to first box under button SetFocus(GetDlgItem(hDlg, IDC_PW_NEWNAME)); break; default: break; } if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) || (LOWORD(wParam) == IDC_BACK) ) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } } return FALSE; } INT_PTR CALLBACK DialogWaitForOKCancel( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { PADVANCEDCONFIRM_DIALOGARGS pDialogArgs; switch (message) { case WM_INITDIALOG: { pDialogArgs = (PADVANCEDCONFIRM_DIALOGARGS)lParam; // set dialog title SetWindowTextU(hDlg, pDialogArgs->szItemName); } return TRUE; case WM_COMMAND: { if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) || (LOWORD(wParam) == IDC_BACK) ) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } default: break; } return FALSE; } // // make string LPTSTR types due to the way that the call back is prototyped // when file is not compiled with #define UNICODE // we should look at compiling everything with #define UNICODE later // BOOL CALLBACK FMyLoadIcon( HINSTANCE hModule, // resource-module handle LPCWSTR lpszType, // pointer to resource type LPWSTR lpszName, // pointer to resource name LONG_PTR lParam // application-defined parameter ) { if ((LPCWSTR)RT_GROUP_ICON != lpszType) return TRUE; // keep looking, you fool! // // LoadIcon _may_ not work on Win95 if LOAD_LIBRARY_AS_DATAFILE was // specified to LoadLibraryEx. // We want to avoid calling DLL_PROCESS_ATTACH code for anything // because that's a way to get arbitrary code to run in our address space // if(FIsWinNT()) { // // load the image via LoadImage, instead of LoadIcon, because // LoadIcon does erroneous caching in some scenarios. // *(HICON*)lParam = (HICON)LoadImageW( hModule, lpszName, IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR | LR_DEFAULTSIZE ); return FALSE; // we've got at least one icon; stop! } else { // // this more convoluted approach doesn't seem to work on NT, due // to a limitation in CreateIconFromResource() // This approach is good for Win95 because it allows us to use all // Unicode API calls. // HRSRC hRsrc = NULL; HGLOBAL hGlobal = NULL; LPVOID lpRes = NULL; int nID; *(HICON*)lParam = NULL; hRsrc = FindResourceW(hModule, lpszName, lpszType); if(hRsrc == NULL) return FALSE; hGlobal = LoadResource(hModule, hRsrc); if(hGlobal == NULL) return FALSE; lpRes = LockResource(hGlobal); if(lpRes == NULL) return FALSE; nID = LookupIconIdFromDirectory( (PBYTE)lpRes, TRUE ); hRsrc = FindResourceW( hModule, MAKEINTRESOURCEW(nID), (LPCWSTR)RT_ICON ); if(hRsrc == NULL) return FALSE; hGlobal = LoadResource( hModule, hRsrc ); if(hGlobal == NULL) return FALSE; lpRes = LockResource(hGlobal); if(lpRes == NULL) return FALSE; // Let the OS make us an icon *(HICON*)lParam = CreateIconFromResource( (PBYTE)lpRes, SizeofResource(hModule, hRsrc), TRUE, 0x00030000 ); return FALSE; } } INT_PTR CALLBACK DialogAccessDetails( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) /*++ NOTENOTE Anybody calling this dialog box routine should be imperonsating the client associated with the call. This allows access to icon and any on-disk resources to occur in the security context of the client. --*/ { LPCWSTR ApplicationName; LPWSTR FileDescription = NULL; BOOL fDlgEnterPassword; PPW_DIALOG_ARGS pDialogArgs; // TODO this function needs more cleanup switch (message) { case WM_INITDIALOG: { BOOL fImpersonated; SetLastError( 0 ); // as per win32 documentation if(SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam) == 0) { if(GetLastError() != ERROR_SUCCESS) { EndDialog(hDlg, IDCANCEL); return FALSE; } } // lParam is struct pDialogArgs = (PPW_DIALOG_ARGS)lParam; // init static vars pDialogArgs->hMyDC = GetDC(hDlg); // set dialog title SetWindowTextU(hDlg, pDialogArgs->szItemName); // // set application name, path // fImpersonated = g_sCallbacks.pfnFImpersonateClient(pDialogArgs->phPSTProv); SetWindowTextU(GetDlgItem(hDlg,IDC_APP_PATH), pDialogArgs->szAppName); if(GetFileDescription(pDialogArgs->szAppName, &FileDescription)) ApplicationName = FileDescription; else GetFileNameFromPath(pDialogArgs->szAppName, &ApplicationName); if(fImpersonated) g_sCallbacks.pfnFRevertToSelf(pDialogArgs->phPSTProv); SetWindowTextU(GetDlgItem(hDlg, IDC_APP_NAME), ApplicationName); if(FileDescription) { SSFree(FileDescription); FileDescription = NULL; } // set item name, type SetWindowTextU(GetDlgItem(hDlg, IDC_ITEM_NAME), pDialogArgs->szItemName); SetWindowTextU(GetDlgItem(hDlg, IDC_ITEM_TYPE), pDialogArgs->szItemType); // set messages SetWindowTextU(GetDlgItem(hDlg, IDC_MESSAGE), g_ItemDetailsBannerMessage); // set access description SetWindowTextU(GetDlgItem(hDlg, IDC_ACCESS_TYPE), pDialogArgs->szAccess); // // set app icon // fImpersonated = g_sCallbacks.pfnFImpersonateClient(pDialogArgs->phPSTProv); HINSTANCE hCallerInst; hCallerInst = LoadLibraryExU(pDialogArgs->szAppName, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hCallerInst) { EnumResourceNamesW(hCallerInst, (LPCWSTR)RT_GROUP_ICON, FMyLoadIcon, (LPARAM)&pDialogArgs->hIcon); // never fails, unfortunately FreeLibrary(hCallerInst); } if(fImpersonated) g_sCallbacks.pfnFRevertToSelf(pDialogArgs->phPSTProv); HWND hIconBox; RECT rect; POINT point; hIconBox = GetDlgItem(hDlg, IDC_ICONBOX); if ((NULL != pDialogArgs) && GetWindowRect(hIconBox, &rect) && (pDialogArgs->hMyDC != NULL) && GetDCOrgEx(pDialogArgs->hMyDC, &point) ) // rect on window, window on screen { // need pos of icon on DC: subtract GetWindowRect()-GetDCOrgEx() pDialogArgs->xIconPos = rect.left - point.x; pDialogArgs->yIconPos = rect.top - point.y; } // update the changable data view SendMessage(hDlg, WM_COMMAND, (WORD)DLG_UPDATE_DATA, 0); return (TRUE); } // WM_INITDIALOG case WM_PAINT: { HDC hMyDC; HICON hIcon; int xIconPos, yIconPos; pDialogArgs = (PPW_DIALOG_ARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out hMyDC = pDialogArgs->hMyDC; hIcon = pDialogArgs->hIcon; xIconPos = pDialogArgs->xIconPos; yIconPos = pDialogArgs->yIconPos; if ((hMyDC != NULL) && (hIcon != NULL) && (xIconPos != 0) && (yIconPos != 0)) DrawIcon(hMyDC, xIconPos, yIconPos, hIcon); return (0); } // WM_PAINT case WM_COMMAND: pDialogArgs = (PPW_DIALOG_ARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out switch (LOWORD(wParam)) { case IDOK: break; default: break; } // switch if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) ) { ReleaseDC(hDlg, pDialogArgs->hMyDC); EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } // switch (message) return FALSE; } INT_PTR CALLBACK DialogSimplifiedPasswordConfirm( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) /*++ NOTENOTE Anybody calling this dialog box routine should be imperonsating the client associated with the call. This allows access to icon and any on-disk resources to occur in the security context of the client. --*/ { LPCWSTR ApplicationName; LPWSTR FileDescription = NULL; BOOL fDlgEnterPassword; PPW_DIALOG_ARGS pDialogArgs; // TODO this function needs more cleanup switch (message) { case WM_INITDIALOG: { BOOL fImpersonated; SetLastError( 0 ); // as per win32 documentation if(SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam) == 0) { if(GetLastError() != ERROR_SUCCESS) { EndDialog(hDlg, IDCANCEL); return FALSE; } } // lParam is struct pDialogArgs = (PPW_DIALOG_ARGS)lParam; // init static vars pDialogArgs->hMyDC = GetDC(hDlg); // Messages to User // Dialog Bar = item name SetWindowTextU(hDlg, pDialogArgs->szItemName); // application friendly name { // get application friendly name fImpersonated = g_sCallbacks.pfnFImpersonateClient(pDialogArgs->phPSTProv); if(GetFileDescription(pDialogArgs->szAppName, &FileDescription)) ApplicationName = FileDescription; else GetFileNameFromPath(pDialogArgs->szAppName, &ApplicationName); if(fImpersonated) g_sCallbacks.pfnFRevertToSelf(pDialogArgs->phPSTProv); if(ApplicationName) { SetWindowTextU(GetDlgItem(hDlg, IDC_MESSAGE), ApplicationName); } if(FileDescription) { SSFree(FileDescription); FileDescription = NULL; } } // app msg SetWindowTextU(GetDlgItem(hDlg, IDC_APP_MSG), pDialogArgs->szPrompt); #ifdef SHOW_APP_IDENTITY // // set app icon // fImpersonated = g_sCallbacks.pfnFImpersonateClient(pDialogArgs->phPSTProv); HINSTANCE hCallerInst; hCallerInst = LoadLibraryExU(pDialogArgs->szAppName, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hCallerInst) { HWND hIconBox; RECT rect; POINT point; EnumResourceNamesW(hCallerInst, (LPCWSTR)RT_GROUP_ICON, FMyLoadIcon, (LPARAM)&pDialogArgs->hIcon); // never fails, unfortunately hIconBox = GetDlgItem(hDlg, IDC_ICONBOX); if (GetWindowRect(hIconBox, &rect) && GetDCOrgEx(pDialogArgs->hMyDC, &point) ) // rect on window, window on screen { // need pos of icon on DC: subtract GetWindowRect()-GetDCOrgEx() pDialogArgs->xIconPos = rect.left - point.x; pDialogArgs->yIconPos = rect.top - point.y; } SendMessage(hDlg, WM_PAINT, 0,0); FreeLibrary(hCallerInst); } if(fImpersonated) g_sCallbacks.pfnFRevertToSelf(pDialogArgs->phPSTProv); #endif // SHOW_APP_IDENTITY // update the changable data view SendMessage(hDlg, WM_COMMAND, (WORD)DLG_UPDATE_DATA, 0); // // if migration disposition, bail out of UI now for OK-Cancel style. // if( (pDialogArgs->dwFlags & PST_NO_UI_MIGRATION) && ((*pDialogArgs->pdwPasswordOptions) & BP_CONFIRM_OKCANCEL) ) { SendMessage(hDlg, WM_COMMAND, IDOK, 0); } return (TRUE); } // WM_INITDIALOG case WM_PAINT: { HDC hMyDC; HICON hIcon; int xIconPos, yIconPos; pDialogArgs = (PPW_DIALOG_ARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out hMyDC = pDialogArgs->hMyDC; hIcon = pDialogArgs->hIcon; xIconPos = pDialogArgs->xIconPos; yIconPos = pDialogArgs->yIconPos; if ((hMyDC != NULL) && (hIcon != NULL) && (xIconPos != 0) && (yIconPos != 0)) DrawIcon(hMyDC, xIconPos, yIconPos, hIcon); return (0); } // WM_PAINT case WM_COMMAND: PLUID pluidAuthID; pDialogArgs = (PPW_DIALOG_ARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out pluidAuthID = &(pDialogArgs->luidAuthID); switch (LOWORD(wParam)) { case IDOK: if(NULL == g_pCUAList) { return FALSE; } if (*(pDialogArgs->pdwPasswordOptions) == BP_CONFIRM_PASSWORDUI) { WCHAR sz1[MAX_PW_LEN]; DWORD cch1; BOOL fUserSaysCache; if( g_fAllowCachePW ) { fUserSaysCache = (BST_CHECKED == SendMessage(GetDlgItem(hDlg, IDC_CACHEPW), BM_GETCHECK, 0, 0)); } else { fUserSaysCache = FALSE; } // get password cch1 = GetDlgItemTextU( hDlg, IDC_EDIT1, sz1, MAX_PW_LEN); // // compute hashs from scratch // if (!MyGetPwdHash(sz1, pDialogArgs->rgbPwd)) break; if (!MyGetPwdHashEx(sz1, pDialogArgs->rgbPwdLowerCase, TRUE)) break; // query cache for password if (FIsCachedPassword(pDialogArgs->szUserName, *pDialogArgs->ppszPWName, pluidAuthID)) { // find cached pwd UACACHE_LIST_ITEM li, *pli; CreateUACacheListItem( &li, pDialogArgs->szUserName, *pDialogArgs->ppszPWName, pluidAuthID); g_pCUAList->LockList(); // find in list if (NULL == (pli = g_pCUAList->SearchList(&li))) { g_pCUAList->UnlockList(); break; } // change behavior based on if user tampered with pwd if (0 == wcscmp(WSZ_PASSWORD_CHANGE_DETECT_TOKEN, sz1)) { // no; copy cached password to outbuf CopyMemory(pDialogArgs->rgbPwd, pli->rgbPwd, A_SHA_DIGEST_LEN); // no; copy cached password to outbuf CopyMemory(pDialogArgs->rgbPwdLowerCase, pli->rgbPwdLowerCase, A_SHA_DIGEST_LEN); } else { // yes: overwrite cached entry with user-entered CopyMemory(pli->rgbPwd, pDialogArgs->rgbPwd, A_SHA_DIGEST_LEN); // yes: overwrite cached entry with user-entered CopyMemory(pli->rgbPwdLowerCase, pDialogArgs->rgbPwdLowerCase, A_SHA_DIGEST_LEN); } g_pCUAList->UnlockList(); if (!fUserSaysCache) { // is already cached, and don't want it to be used // remove from cache g_pCUAList->DelFromList(&li); } } else { if (fUserSaysCache) { // isn't already cached, and want it to be used // create element UACACHE_LIST_ITEM* pli = (UACACHE_LIST_ITEM*) SSAlloc(sizeof(UACACHE_LIST_ITEM)); CreateUACacheListItem( pli, NULL, NULL, pluidAuthID); pli->szUserName = (LPWSTR)SSAlloc(WSZ_BYTECOUNT(pDialogArgs->szUserName)); wcscpy(pli->szUserName, pDialogArgs->szUserName); pli->szMKName = (LPWSTR)SSAlloc(WSZ_BYTECOUNT(*pDialogArgs->ppszPWName)); wcscpy(pli->szMKName, *pDialogArgs->ppszPWName); CopyMemory(pli->rgbPwd, pDialogArgs->rgbPwd, A_SHA_DIGEST_LEN); CopyMemory(pli->rgbPwdLowerCase, pDialogArgs->rgbPwdLowerCase, A_SHA_DIGEST_LEN); // add to list g_pCUAList->AddToList(pli); } else { // isn't already cached, and don't want it to be used } } ZeroMemory(sz1, WSZ_BYTECOUNT(sz1)); } // else break; case IDC_ADVANCED: { // make copy so static members (x, y, hIcon) don't get stomped PW_DIALOG_ARGS DetailDlgParms; CopyMemory(&DetailDlgParms, pDialogArgs, sizeof(PW_DIALOG_ARGS)); ServicesDialogBoxParam( g_hInst, MAKEINTRESOURCE(IDD_ITEM_DETAILS), (HWND)hDlg, DialogAccessDetails, (LPARAM)&DetailDlgParms); // update the changable data view SendMessage(hDlg, WM_COMMAND, (WORD)DLG_UPDATE_DATA, 0); } break; case IDC_CHANGE_SECURITY: { ADVANCEDCONFIRM_DIALOGARGS DialogArgs = {pDialogArgs->szUserName, pDialogArgs->ppszPWName, pDialogArgs->ppszPW, pDialogArgs->pdwPasswordOptions, pDialogArgs->szItemName}; ChooseSecurityWizard(hDlg, &DialogArgs); // commit changes SendMessage(hDlg, WM_COMMAND, (WORD)DLG_UPDATE_DATA, 0); break; } case DLG_UPDATE_DATA: { WCHAR szDialogMessage[MAX_STRING_RSC_SIZE] = L"\0"; // show or hide pwd entry box? fDlgEnterPassword = (*(pDialogArgs->pdwPasswordOptions) == BP_CONFIRM_PASSWORDUI); if (fDlgEnterPassword) { // // comment out the following because we don't use %ls format string at the moment. // wcscpy(szDialogMessage, g_PWPromptPrefix); wcscat(szDialogMessage, *(pDialogArgs->ppszPWName)); wcscat(szDialogMessage, g_PWPromptSuffix); SetWindowTextU(GetDlgItem(hDlg, IDC_LABEL_EDIT1), szDialogMessage); // we should not hide these windows ShowWindow(GetDlgItem(hDlg, IDC_EDIT1), SW_SHOW); EnableWindow(GetDlgItem(hDlg, IDC_EDIT1), TRUE); ShowWindow(GetDlgItem(hDlg, IDC_LABEL_EDIT1), SW_SHOW); EnableWindow(GetDlgItem(hDlg, IDC_LABEL_EDIT1), TRUE); if( pDialogArgs->fAllowConfirmChange && g_fAllowCachePW ) { // show or hide "cache this password" button ShowWindow(GetDlgItem(hDlg, IDC_CACHEPW), SW_SHOW ); EnableWindow(GetDlgItem(hDlg, IDC_CACHEPW), TRUE ); } else { ShowWindow(GetDlgItem(hDlg, IDC_CACHEPW), SW_HIDE ); EnableWindow(GetDlgItem(hDlg, IDC_CACHEPW), FALSE ); } // put untypable token into pwd field if (FIsCachedPassword(pDialogArgs->szUserName, *pDialogArgs->ppszPWName, pluidAuthID)) SetWindowTextU(GetDlgItem(hDlg, IDC_EDIT1), WSZ_PASSWORD_CHANGE_DETECT_TOKEN); // show if this password is cached SendMessage(GetDlgItem(hDlg, IDC_CACHEPW), BM_SETCHECK, (WPARAM)(FIsCachedPassword(pDialogArgs->szUserName, *pDialogArgs->ppszPWName, pluidAuthID)), 0); SetFocus(GetDlgItem(hDlg, IDC_EDIT1)); } else { // hide pw ShowWindow(GetDlgItem(hDlg, IDC_EDIT1), SW_HIDE); ShowWindow(GetDlgItem(hDlg, IDC_LABEL_EDIT1), SW_HIDE); EnableWindow(GetDlgItem(hDlg, IDC_EDIT1), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_LABEL_EDIT1), FALSE); ShowWindow(GetDlgItem(hDlg, IDC_CACHEPW), SW_HIDE); EnableWindow(GetDlgItem(hDlg, IDC_CACHEPW), FALSE); } // show or hide "change security" button ShowWindow(GetDlgItem(hDlg, IDC_CHANGE_SECURITY), ((pDialogArgs->fAllowConfirmChange) ? SW_SHOW : SW_HIDE)); EnableWindow(GetDlgItem(hDlg, IDC_CHANGE_SECURITY), ((pDialogArgs->fAllowConfirmChange) ? TRUE : FALSE)); // show or hide "details" button ShowWindow(GetDlgItem(hDlg, IDC_ADVANCED), ((pDialogArgs->fAllowConfirmChange) ? SW_SHOW : SW_HIDE)); EnableWindow(GetDlgItem(hDlg, IDC_ADVANCED), ((pDialogArgs->fAllowConfirmChange) ? TRUE : FALSE)); // show or hide "level currently set to *" ShowWindow(GetDlgItem(hDlg, IDC_SEC_PREFIX), ((pDialogArgs->fAllowConfirmChange) ? SW_SHOW : SW_HIDE)); ShowWindow(GetDlgItem(hDlg, IDC_SEC_LEVEL), ((pDialogArgs->fAllowConfirmChange) ? SW_SHOW : SW_HIDE)); // jam the current security setting switch(*pDialogArgs->pdwPasswordOptions) { case BP_CONFIRM_PASSWORDUI: SetWindowTextU(GetDlgItem(hDlg, IDC_SEC_LEVEL), g_PromptHighSecurity); break; case BP_CONFIRM_OKCANCEL: SetWindowTextU(GetDlgItem(hDlg, IDC_SEC_LEVEL), g_PromptMedSecurity); break; case BP_CONFIRM_NONE: SetWindowTextU(GetDlgItem(hDlg, IDC_SEC_LEVEL), g_PromptLowSecurity); break; } } break; default: break; } // switch if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) ) { ReleaseDC(hDlg, pDialogArgs->hMyDC); EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } // switch (message) return FALSE; } INT_PTR CALLBACK DialogOldNewPassword( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { LPCWSTR szUserName; LPWSTR* ppszPWName; LPWSTR* ppszPW; LPWSTR* ppszPWNew; POLDNEWPW_DIALOGARGS pDialogArgs; DWORD dwCount; BYTE rgb1[_MAX_PATH]; LPWSTR pszMasterKey=NULL; char * szBuffer = NULL; // TODO this function needs more cleanup switch (message) { case WM_INITDIALOG: { SetLastError( 0 ); // as per win32 documentation if(SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam) == 0) { if(GetLastError() != ERROR_SUCCESS) { EndDialog(hDlg, IDCANCEL); return FALSE; } } // lParam is POLDNEWPW_DIALOGARGS pDialogArgs = (POLDNEWPW_DIALOGARGS)lParam; szUserName = pDialogArgs->szUserName; ppszPWName = pDialogArgs->ppszPWName; ppszPW = pDialogArgs->ppszOldPW; ppszPWNew = pDialogArgs->ppszNewPW; // Add known pwds for (dwCount=0; ;dwCount++) { if (PST_E_OK != BPEnumMasterKeys( szUserName, dwCount, &pszMasterKey)) break; // don't add non-editable passwords if (!FIsUserMasterKey(pszMasterKey)) continue; // else, add this to the list and continue if (FIsWinNT()) { SendDlgItemMessageW(hDlg, IDC_PW_NAME, CB_ADDSTRING, 0, (LPARAM) pszMasterKey); } #ifdef _M_IX86 else { MkMBStr(rgb1, _MAX_PATH, pszMasterKey, &szBuffer); SendDlgItemMessageA(hDlg, IDC_PW_NAME, CB_ADDSTRING, 0, (LPARAM) szBuffer); FreeMBStr(rgb1, szBuffer); } #endif SSFree(pszMasterKey); } SendDlgItemMessage(hDlg, IDC_PW_NAME, CB_SETCURSEL, 0, 0); SetWindowTextU(GetDlgItem(hDlg, IDC_MESSAGE), g_PasswordChange); return (TRUE); } // WM_INITDIALOG case WM_COMMAND: if (LOWORD(wParam) == IDOK) { WCHAR sz1[MAX_PW_LEN]; WCHAR sz2[MAX_PW_LEN]; DWORD cch1, cch2; pDialogArgs = (POLDNEWPW_DIALOGARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out szUserName = pDialogArgs->szUserName; ppszPWName = pDialogArgs->ppszPWName; ppszPW = pDialogArgs->ppszOldPW; ppszPWNew = pDialogArgs->ppszNewPW; cch1 = GetDlgItemTextU( hDlg, IDC_EDIT1, sz1, MAX_PW_LEN); cch2 = GetDlgItemTextU( hDlg, IDC_EDIT2, sz2, MAX_PW_LEN); if ( (cch1 != cch2) || (0 != wcscmp(sz1, sz2)) ) { // this W implemented in both Win95 & NT! MessageBoxW( NULL, //hDlg, g_PasswordNoMatch, g_PasswordErrorDlgTitle, MB_OK | MB_ICONEXCLAMATION | MB_SERVICE_NOTIFICATION); SetWindowTextU(GetDlgItem(hDlg, IDC_EDIT1), WSZ_NULLSTRING); SetWindowTextU(GetDlgItem(hDlg, IDC_EDIT2), WSZ_NULLSTRING); break; } // and sock NEW PW away SS_ASSERT(ppszPWNew != NULL); *ppszPWNew = (LPWSTR)SSAlloc((cch1+1)*sizeof(WCHAR)); if(NULL != (*ppszPWNew)) { wcscpy(*ppszPWNew, sz1); } ZeroMemory(sz1, cch1 * sizeof(WCHAR)); // and sock OLD PW away cch1 = GetDlgItemTextU( hDlg, IDC_EDIT0, sz1, MAX_PW_LEN); SS_ASSERT(ppszPW != NULL); *ppszPW = (LPWSTR)SSAlloc((cch1+1)*sizeof(WCHAR)); // TODO check allocation failure wcscpy(*ppszPW, sz1); ZeroMemory(sz1, cch1 * sizeof(WCHAR)); // and get password name cch1 = GetDlgItemTextU( hDlg, IDC_PW_NAME, sz1, MAX_PW_LEN); SS_ASSERT(ppszPWName != NULL); *ppszPWName = (LPWSTR)SSAlloc((cch1+1)*sizeof(WCHAR)); // TODO check allocation failure wcscpy(*ppszPWName, sz1); ZeroMemory(sz1, cch1 * sizeof(WCHAR)); } if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) ) { EndDialog(hDlg, LOWORD(wParam)); return TRUE; } break; } return FALSE; } INT_PTR CALLBACK DialogSolicitOldPassword( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { PSOLICITOLDPW_DIALOGARGS pDialogArgs; switch (message) { case WM_INITDIALOG: { SetLastError( 0 ); // as per win32 documentation if(SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam) == 0) { if(GetLastError() != ERROR_SUCCESS) { EndDialog(hDlg, IDCANCEL); return FALSE; } } // lParam is PSOLICITOLDPW_DIALOGARGS pDialogArgs = (PSOLICITOLDPW_DIALOGARGS)lParam; SetWindowTextU(GetDlgItem(hDlg, IDC_PW_NAME), pDialogArgs->szPWName); SetWindowTextU(GetDlgItem(hDlg, IDC_MESSAGE), g_PasswordSolicitOld); if (pDialogArgs->ppszNewPW == NULL) { // if NT, we don't need extra user confirmation of new passwd ShowWindow(GetDlgItem(hDlg, IDC_ST_NEWPW), FALSE); ShowWindow(GetDlgItem(hDlg, IDC_EDIT1), FALSE); EnableWindow(GetDlgItem(hDlg, IDC_EDIT1), FALSE); } return TRUE; } // WM_INITDIALOG case WM_COMMAND: { LPWSTR* ppszPW; BOOL bSuccess = FALSE; if (LOWORD(wParam) == IDOK) { WCHAR sz1[MAX_PW_LEN]; DWORD cch1; pDialogArgs = (PSOLICITOLDPW_DIALOGARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out ppszPW = pDialogArgs->ppszOldPW; // if asked for, sock NEW PW away if (pDialogArgs->ppszNewPW != NULL) { LPWSTR* ppszNewPW = pDialogArgs->ppszNewPW; // copy out "new" pwd cch1 = GetDlgItemTextU( hDlg, IDC_EDIT1, sz1, MAX_PW_LEN); SS_ASSERT(ppszNewPW != NULL); *ppszNewPW = (LPWSTR)SSAlloc((cch1+1)*sizeof(WCHAR)); if(NULL != *ppszNewPW) { wcscpy(*ppszNewPW, sz1); } } // and sock OLD PW away cch1 = GetDlgItemTextU( hDlg, IDC_EDIT0, sz1, MAX_PW_LEN); SS_ASSERT(ppszPW != NULL); *ppszPW = (LPWSTR)SSAlloc((cch1+1)*sizeof(WCHAR)); if(*ppszPW != NULL) { wcscpy(*ppszPW, sz1); bSuccess = TRUE; } ZeroMemory(sz1, cch1 * sizeof(WCHAR)); } if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) ) { EndDialog(hDlg, LOWORD(wParam)); return bSuccess; } } // WM_COMMAND default: return FALSE; } return FALSE; } INT_PTR CALLBACK DialogSetSecurityLevel( HWND hDlg, // handle to dialog box UINT message, // message WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { PADVANCEDCONFIRM_DIALOGARGS pDialogArgs; BYTE rgb1[_MAX_PATH]; LPWSTR pszMasterKey=NULL; char * szBuffer = NULL; switch (message) { case WM_INITDIALOG: { SetLastError( 0 ); // as per win32 documentation if(SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam) == 0) { if(GetLastError() != ERROR_SUCCESS) { EndDialog(hDlg, IDCANCEL); return FALSE; } } // lParam is PADVANCEDCONFIRM_DIALOGARGS pDialogArgs = (PADVANCEDCONFIRM_DIALOGARGS)lParam; // set the dialog title SetWindowTextU(hDlg, pDialogArgs->szItemName); switch(*(pDialogArgs->pdwPasswordOptions)) { case BP_CONFIRM_NONE: SendDlgItemMessage(hDlg, IDC_RADIO_NOCONFIRM, BM_SETCHECK, BST_CHECKED, 0); SendMessage(hDlg, WM_COMMAND, (WORD)IDC_RADIO_NOCONFIRM, 0); break; case BP_CONFIRM_OKCANCEL: SendDlgItemMessage(hDlg, IDC_RADIO_OKCANCEL, BM_SETCHECK, BST_CHECKED, 0); SendMessage(hDlg, WM_COMMAND, (WORD)IDC_RADIO_OKCANCEL, 0); break; case BP_CONFIRM_PASSWORDUI: default: SendDlgItemMessage(hDlg, IDC_RADIO_ASSIGNPW, BM_SETCHECK, BST_CHECKED, 0); SendMessage(hDlg, WM_COMMAND, (WORD)IDC_RADIO_ASSIGNPW, 0); break; } return TRUE; } // WM_INITDIALOG case WM_COMMAND: { LPWSTR* ppszPW; BOOL bSuccess = FALSE; switch (LOWORD(wParam)) { case IDC_NEXT: case IDOK: { pDialogArgs = (PADVANCEDCONFIRM_DIALOGARGS)GetWindowLongPtr(hDlg, GWLP_USERDATA); if(pDialogArgs == 0) break; // TODO: bail out // modify *(pDialogArgs->pdwPasswordOptions); if (BST_CHECKED == SendDlgItemMessage(hDlg, IDC_RADIO_ASSIGNPW, BM_GETCHECK, 0, 0)) { *(pDialogArgs->pdwPasswordOptions) = BP_CONFIRM_PASSWORDUI; } else if (BST_CHECKED == SendDlgItemMessage(hDlg, IDC_RADIO_NOCONFIRM, BM_GETCHECK, 0, 0)) *(pDialogArgs->pdwPasswordOptions) = BP_CONFIRM_NONE; else *(pDialogArgs->pdwPasswordOptions) = BP_CONFIRM_OKCANCEL; if (BP_CONFIRM_PASSWORDUI != *(pDialogArgs->pdwPasswordOptions)) { *(pDialogArgs->ppszPWName) = (LPWSTR)SSAlloc(sizeof(WSZ_PASSWORD_WINDOWS)); if(*(pDialogArgs->ppszPWName) != NULL) { wcscpy(*(pDialogArgs->ppszPWName), WSZ_PASSWORD_WINDOWS); } } break; } default: break; } if ( (LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL) || (LOWORD(wParam) == IDC_NEXT) ) { EndDialog(hDlg, LOWORD(wParam)); return bSuccess; } } // WM_COMMAND default: return FALSE; } }
[ "support@cryptoalgo.cf" ]
support@cryptoalgo.cf
d2fa7c2e0c59a756608c773c26403013f10400aa
184bea6977339a78cff9f9d01dd634a6793058b0
/include/H3DUbitrack/Vec2Sender.h
bcf3a806c31b9febbe7e70a43114665a4e7de0c2
[]
no_license
Ubitrack/integration_h3dapi
f16298ec2a19ddc45cc57c0aa04db933d7da743a
63c9d1bb1e5a4995ba77648f239f1e8201b9cdc8
refs/heads/master
2020-12-24T06:45:50.734670
2017-04-19T13:03:00
2017-04-19T13:03:00
73,459,968
0
0
null
null
null
null
UTF-8
C++
false
false
1,067
h
/* * UbitrackContext.h * * Created on: 03/08/2010 * Author: mvl */ #ifndef VEC2SENDER_H_ #define VEC2SENDER_H_ #include <H3D/X3DNode.h> #include <H3D/SFString.h> #include <H3D/SFVec2d.h> #include <H3DUbitrack/H3DUbitrack.h> #include <H3DUbitrack/MeasurementSender.h> #include <vector> using namespace Ubitrack::Facade; namespace H3DUbitrack { typedef MeasurementSender<Ubitrack::Measurement::Position2D , Ubitrack::Components::ApplicationPushSourcePosition2D > Vec2SenderBase; class H3DUBITRACK_API Vec2Sender : public Vec2SenderBase { public: Vec2Sender( H3D::Inst< H3D::SFNode > _metadata = 0, H3D::Inst< H3D::SFString > _pattern = 0, H3D::Inst< H3D::SFVec2d > _value = 0 ); std::auto_ptr< H3D::SFVec2d > value; /// Add this node to the H3DNodeDatabase system. static H3D::H3DNodeDatabase database; Ubitrack::Measurement::Position2D getMeasurement(H3D::TraverseInfo &ti, unsigned long long ts); }; } // namespace H3DUbitrack #endif //VEC2SENDER_H_
[ "someone@naist.jp" ]
someone@naist.jp
41092691b6469d4a163d497d80d2fa4732bdf13c
211dc21c56188036f3c0b5c1a9191a92f53c77e9
/include/Grass.h
c34b01c31af98a2f162d9212a40371165a8c1bee
[]
no_license
FrapoDeveloper/ciudadOpenGL
d3d1188a464a95a9004cff38f8aa0c84d24cca96
576fdfa6fb72956ab24b6beb82a6416bb1b24111
refs/heads/master
2020-09-30T21:28:27.767558
2019-12-11T13:56:47
2019-12-11T13:56:47
227,377,866
3
0
null
null
null
null
UTF-8
C++
false
false
2,101
h
#ifndef GRASS_H #define GRASS_H #include <gl/glut.h> class Grass { public: Grass(); public: void graficarGrass(); }; void Grass::graficarGrass() { for(int i=0;i<185;i++){ for(int j=0;j<150;j++){ glPushMatrix(); glTranslatef(-i*0.16,0,-j*0.16); glTranslatef(14.8,0.3,15); glScaled(0.01,0.01,0.01); glColor3f(0,0.6,0); glBegin(GL_TRIANGLES);//derecha glVertex3f(12,13,0); glVertex3f(-4,-8,0); glVertex3f(4,-8,0); glEnd(); glBegin(GL_TRIANGLES);//izquierda glVertex3f(-12,13,0); glVertex3f(-4,-8,0); glVertex3f(4,-8,0); glEnd(); glBegin(GL_TRIANGLES);//enmedio glVertex3f(0,16,0); glVertex3f(-4,-8,0); glVertex3f(4,-8,0); glEnd(); glPopMatrix(); } } for(int i=0;i<185;i++){ for(int j=0;j<150;j++){ glPushMatrix(); glTranslatef(-i*0.16,0,-j*0.16); glTranslatef(14.8,0.3,15); glRotatef(90,0,1,0); glScaled(0.01,0.01,0.01); glColor3f(0,0.6,0); glBegin(GL_TRIANGLES);//derecha glVertex3f(12,13,0); glVertex3f(-4,-8,0); glVertex3f(4,-8,0); glEnd(); glBegin(GL_TRIANGLES);//izquierda glVertex3f(-12,13,0); glVertex3f(-4,-8,0); glVertex3f(4,-8,0); glEnd(); glBegin(GL_TRIANGLES);//enmedio glVertex3f(0,16,0); glVertex3f(-4,-8,0); glVertex3f(4,-8,0); glEnd(); glPopMatrix(); } } } #endif // GRASS_H
[ "fran_espino189@outlook.com" ]
fran_espino189@outlook.com
e4b95839673c2d1cd22afdc99fd2181310631e58
9fa363c042e4f7ba31d75f9535acb6dca69e79cb
/LCBCAdminSystem/stdafx.cpp
40f3ad8290e787df0c5f0003ef0d1f7d4c1e159b
[]
no_license
andreboyce/lcbcadminsystem
f30914132fdd100fa1e879b6f2648879a4f02b9f
425af46bc3324289d23135f28f6ef6d8c702ba04
refs/heads/main
2023-03-14T15:34:08.496230
2021-03-11T11:10:49
2021-03-11T11:10:49
346,674,135
0
0
null
null
null
null
UTF-8
C++
false
false
208
cpp
// stdafx.cpp : source file that includes just the standard includes // LCBCAdminSystem.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
[ "mobile@andreboyce.com" ]
mobile@andreboyce.com
82a84439f0826a88e3d302d2c3e98d6b227e7667
bdcedb3e8cbb8cd1a748423050f56b0d71dff125
/Server/WebGameManager/PlayerSession.cpp
b735949ebfd3d77e0051396c8d7c5db5274021d6
[ "MIT" ]
permissive
lxlyh/FxLib
f3858c21f8da76a5f7eab301de3a2539d483e82c
49e3fb12b4fe324c0b5b1503b37492dc742100de
refs/heads/master
2020-09-12T12:19:48.723598
2019-09-20T07:36:52
2019-09-20T07:36:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,125
cpp
#include "PlayerSession.h" #include "netstream.h" #include "gamedefine.h" #include "GameServer.h" #ifdef WIN32 #include <Windows.h> #include <ShellAPI.h> #else #include<unistd.h> #endif // WIN32 const static unsigned int g_dwPlayerSessionBuffLen = 64 * 1024; static char g_pPlayerSessionBuf[g_dwPlayerSessionBuffLen]; CPlayerSession::CPlayerSession() { } CPlayerSession::~CPlayerSession() { } void CPlayerSession::OnConnect(void) { } void CPlayerSession::OnClose(void) { } void CPlayerSession::OnError(unsigned int dwErrorNo) { LogExe(LogLv_Debug, "ip : %s, port : %d, connect addr : %p, error no : %d", GetRemoteIPStr(), GetRemotePort(), (GetConnection()), dwErrorNo); } void CPlayerSession::OnRecv(const char* pBuf, unsigned int dwLen) { //CNetStream oStream(pBuf, dwLen); //Protocol::EGameProtocol eProrocol; //oStream.ReadInt((int&)eProrocol); //const char* pData = pBuf + sizeof(UINT32); //dwLen -= sizeof(UINT32); //switch (eProrocol) //{ //case Protocol::PLAYER_REQUEST_GAME_MANAGER_INFO: OnRequestGameManagerInfo(pData, dwLen); break; //default: Assert(0); break; //} } void CPlayerSession::Release(void) { LogExe(LogLv_Debug, "ip : %s, port : %d, connect addr : %p", GetRemoteIPStr(), GetRemotePort(), GetConnection()); OnDestroy(); Init(NULL); } void CPlayerSession::OnRequestGameManagerInfo(const char* pBuf, unsigned int dwLen) { //CNetStream oStream(pBuf, dwLen); //stPLAYER_REQUEST_GAME_MANAGER_INFO oPLAYER_REQUEST_GAME_MANAGER_INFO; //oPLAYER_REQUEST_GAME_MANAGER_INFO.Read(oStream); //if (StartProccess((unsigned long long)this)) //{ // GameServer::Instance()->AddRequestPlayer(this); //} } void CPlayerSession::OnGameInfo(GameProto::GameNotifyGameManagerInfo& refInfo) { //CNetStream oStream(ENetStreamType_Write, g_pPlayerSessionBuf, g_dwPlayerSessionBuffLen); //oStream.WriteInt(Protocol::GAME_MANAGER_ACK_PLAYER_INFO_RESULT); //stGAME_MANAGER_ACK_PLAYER_INFO_RESULT oGAME_MANAGER_ACK_PLAYER_INFO_RESULT; //oGAME_MANAGER_ACK_PLAYER_INFO_RESULT.wPlayerPort = refInfo.dw_player_port(); //oGAME_MANAGER_ACK_PLAYER_INFO_RESULT.wServerPort = refInfo.dw_server_port(); //oGAME_MANAGER_ACK_PLAYER_INFO_RESULT.wSlaveServerPort = refInfo.dw_slave_server_port(); //oGAME_MANAGER_ACK_PLAYER_INFO_RESULT.Write(oStream); //Send(g_pPlayerSessionBuf, g_dwPlayerSessionBuffLen - oStream.GetDataLength()); } ////////////////////////////////////////////////////////////////////////// void CWebSocketPlayerSession::Release(void) { LogExe(LogLv_Debug, "ip : %s, port : %d, connect addr : %p", GetRemoteIPStr(), GetRemotePort(), GetConnection()); OnDestroy(); Init(NULL); } ////////////////////////////////////////////////////////////////////////// FxSession * WebSocketPlayerSessionManager::CreateSession() { FxSession* pSession = m_poolSessions.FetchObj(); return pSession; } bool WebSocketPlayerSessionManager::Init() { return m_poolSessions.Init(64, 64); } void WebSocketPlayerSessionManager::Release(FxSession * pSession) { Assert(0); } void WebSocketPlayerSessionManager::Release(CWebSocketPlayerSession* pSession) { m_poolSessions.ReleaseObj(pSession); }
[ "724789975@qq.com" ]
724789975@qq.com
c538ac8d4d2cb310bddaed938b66eb811bd4b2e9
4f52a4da323feb3bfaa3c67d141999f46cfd3d9e
/BOJ_5397/BOJ_5397/BOJ_5397.cpp
bbbeab5682c9a5bd377b7f013cacdcb6a8229a04
[]
no_license
LHI0915/StudyBackjoon
407b4c7c3fbbec60e6cc719714303570ddf34a1f
e649de567abea81e49ea8d95249ad735a2bc0a37
refs/heads/master
2021-07-22T22:12:26.399750
2021-07-13T17:35:53
2021-07-13T17:35:53
141,692,612
0
0
null
null
null
null
UTF-8
C++
false
false
842
cpp
#include <stdio.h> #include <stack> #include <iostream> #include <string> using namespace std; int main(void){ int testcase,st1size,st2size; string s; stack<char> st1,st2; scanf("%d",&testcase); for(int i=0;i<testcase;i++){ cin >> s; for(int j=0;j<s.size();j++){ if(s[j]=='<'){ if(!st1.empty()){ st2.push(st1.top()); st1.pop(); } } else if(s[j]=='>'){ if(!st2.empty()){ st1.push(st2.top()); st2.pop(); } } else if(s[j]=='-'){ if(!st1.empty()){ st1.pop(); } } else{ st1.push(s[j]); } } st1size=st1.size(); for(int j=0;j<st1size;j++){ if(!st1.empty()){ st2.push(st1.top()); st1.pop(); } } st2size=st2.size(); for(int j=0;j<st2size;j++){ if(!st2.empty()){ printf("%c",st2.top()); st2.pop(); } } printf("\n"); } }
[ "gowns1998@gmail.com" ]
gowns1998@gmail.com
227e3c636c917e72bd597dc040e014286ac2f7fd
d47c341d59ed8ba577463ccf100a51efb669599c
/boost/intrusive/hashtable.hpp
af73f70629fe70372ab04b5a740d621565ac83eb
[ "BSL-1.0" ]
permissive
cms-externals/boost
5980d39d50b7441536eb3b10822f56495fdf3635
9615b17aa7196c42a741e99b4003a0c26f092f4c
refs/heads/master
2023-08-29T09:15:33.137896
2020-08-04T16:50:18
2020-08-04T16:50:18
30,637,301
0
4
BSL-1.0
2023-08-09T23:00:37
2015-02-11T08:07:04
C++
UTF-8
C++
false
false
137,318
hpp
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2006-2013 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_HASHTABLE_HPP #define BOOST_INTRUSIVE_HASHTABLE_HPP #if defined(_MSC_VER) # pragma once #endif #include <boost/intrusive/detail/config_begin.hpp> #include <boost/intrusive/intrusive_fwd.hpp> //std C++ #include <functional> //std::equal_to #include <utility> //std::pair #include <algorithm> //std::swap, std::lower_bound, std::upper_bound #include <cstddef> //std::size_t //boost #include <boost/intrusive/detail/assert.hpp> #include <boost/static_assert.hpp> #include <boost/functional/hash.hpp> //General intrusive utilities #include <boost/intrusive/detail/hashtable_node.hpp> #include <boost/intrusive/detail/transform_iterator.hpp> #include <boost/intrusive/link_mode.hpp> #include <boost/intrusive/detail/ebo_functor_holder.hpp> #include <boost/intrusive/detail/is_stateful_value_traits.hpp> #include <boost/intrusive/detail/node_to_value.hpp> #include <boost/intrusive/detail/exception_disposer.hpp> #include <boost/intrusive/detail/node_cloner_disposer.hpp> #include <boost/intrusive/detail/simple_disposers.hpp> #include <boost/intrusive/detail/size_holder.hpp> //Implementation utilities #include <boost/intrusive/unordered_set_hook.hpp> #include <boost/intrusive/slist.hpp> #include <boost/intrusive/pointer_traits.hpp> #include <boost/intrusive/detail/mpl.hpp> #include <boost/move/utility_core.hpp> namespace boost { namespace intrusive { /// @cond template<int Dummy = 0> struct prime_list_holder { static const std::size_t prime_list[]; static const std::size_t prime_list_size; }; //We only support LLP64(Win64) or LP64(most Unix) data models #ifdef _WIN64 //In 64 bit windows sizeof(size_t) == sizeof(unsigned long long) #define BOOST_INTRUSIVE_PRIME_C(NUMBER) NUMBER##ULL #define BOOST_INTRUSIVE_64_BIT_SIZE_T 1 #else //In 32 bit windows and 32/64 bit unixes sizeof(size_t) == sizeof(unsigned long) #define BOOST_INTRUSIVE_PRIME_C(NUMBER) NUMBER##UL #define BOOST_INTRUSIVE_64_BIT_SIZE_T (((((ULONG_MAX>>16)>>16)>>16)>>15) != 0) #endif template<int Dummy> const std::size_t prime_list_holder<Dummy>::prime_list[] = { BOOST_INTRUSIVE_PRIME_C(3), BOOST_INTRUSIVE_PRIME_C(7), BOOST_INTRUSIVE_PRIME_C(11), BOOST_INTRUSIVE_PRIME_C(17), BOOST_INTRUSIVE_PRIME_C(29), BOOST_INTRUSIVE_PRIME_C(53), BOOST_INTRUSIVE_PRIME_C(97), BOOST_INTRUSIVE_PRIME_C(193), BOOST_INTRUSIVE_PRIME_C(389), BOOST_INTRUSIVE_PRIME_C(769), BOOST_INTRUSIVE_PRIME_C(1543), BOOST_INTRUSIVE_PRIME_C(3079), BOOST_INTRUSIVE_PRIME_C(6151), BOOST_INTRUSIVE_PRIME_C(12289), BOOST_INTRUSIVE_PRIME_C(24593), BOOST_INTRUSIVE_PRIME_C(49157), BOOST_INTRUSIVE_PRIME_C(98317), BOOST_INTRUSIVE_PRIME_C(196613), BOOST_INTRUSIVE_PRIME_C(393241), BOOST_INTRUSIVE_PRIME_C(786433), BOOST_INTRUSIVE_PRIME_C(1572869), BOOST_INTRUSIVE_PRIME_C(3145739), BOOST_INTRUSIVE_PRIME_C(6291469), BOOST_INTRUSIVE_PRIME_C(12582917), BOOST_INTRUSIVE_PRIME_C(25165843), BOOST_INTRUSIVE_PRIME_C(50331653), BOOST_INTRUSIVE_PRIME_C(100663319), BOOST_INTRUSIVE_PRIME_C(201326611), BOOST_INTRUSIVE_PRIME_C(402653189), BOOST_INTRUSIVE_PRIME_C(805306457), BOOST_INTRUSIVE_PRIME_C(1610612741), BOOST_INTRUSIVE_PRIME_C(3221225473), #if BOOST_INTRUSIVE_64_BIT_SIZE_T //Taken from Boost.MultiIndex code, thanks to Joaquin M Lopez Munoz. BOOST_INTRUSIVE_PRIME_C(6442450939), BOOST_INTRUSIVE_PRIME_C(12884901893), BOOST_INTRUSIVE_PRIME_C(25769803751), BOOST_INTRUSIVE_PRIME_C(51539607551), BOOST_INTRUSIVE_PRIME_C(103079215111), BOOST_INTRUSIVE_PRIME_C(206158430209), BOOST_INTRUSIVE_PRIME_C(412316860441), BOOST_INTRUSIVE_PRIME_C(824633720831), BOOST_INTRUSIVE_PRIME_C(1649267441651), BOOST_INTRUSIVE_PRIME_C(3298534883309), BOOST_INTRUSIVE_PRIME_C(6597069766657), BOOST_INTRUSIVE_PRIME_C(13194139533299), BOOST_INTRUSIVE_PRIME_C(26388279066623), BOOST_INTRUSIVE_PRIME_C(52776558133303), BOOST_INTRUSIVE_PRIME_C(105553116266489), BOOST_INTRUSIVE_PRIME_C(211106232532969), BOOST_INTRUSIVE_PRIME_C(422212465066001), BOOST_INTRUSIVE_PRIME_C(844424930131963), BOOST_INTRUSIVE_PRIME_C(1688849860263953), BOOST_INTRUSIVE_PRIME_C(3377699720527861), BOOST_INTRUSIVE_PRIME_C(6755399441055731), BOOST_INTRUSIVE_PRIME_C(13510798882111483), BOOST_INTRUSIVE_PRIME_C(27021597764222939), BOOST_INTRUSIVE_PRIME_C(54043195528445957), BOOST_INTRUSIVE_PRIME_C(108086391056891903), BOOST_INTRUSIVE_PRIME_C(216172782113783843), BOOST_INTRUSIVE_PRIME_C(432345564227567621), BOOST_INTRUSIVE_PRIME_C(864691128455135207), BOOST_INTRUSIVE_PRIME_C(1729382256910270481), BOOST_INTRUSIVE_PRIME_C(3458764513820540933), BOOST_INTRUSIVE_PRIME_C(6917529027641081903), BOOST_INTRUSIVE_PRIME_C(13835058055282163729), BOOST_INTRUSIVE_PRIME_C(18446744073709551557) #else BOOST_INTRUSIVE_PRIME_C(4294967291) #endif }; #undef BOOST_INTRUSIVE_PRIME_C #undef BOOST_INTRUSIVE_64_BIT_SIZE_T template<int Dummy> const std::size_t prime_list_holder<Dummy>::prime_list_size = sizeof(prime_list)/sizeof(std::size_t); struct hash_bool_flags { static const std::size_t unique_keys_pos = 1u; static const std::size_t constant_time_size_pos = 2u; static const std::size_t power_2_buckets_pos = 4u; static const std::size_t cache_begin_pos = 8u; static const std::size_t compare_hash_pos = 16u; static const std::size_t incremental_pos = 32u; }; namespace detail { template<class SupposedValueTraits> struct get_slist_impl_from_supposed_value_traits { typedef SupposedValueTraits value_traits; typedef typename detail::get_node_traits <value_traits>::type node_traits; typedef typename get_slist_impl <typename reduced_slist_node_traits <node_traits>::type >::type type; }; template<class SupposedValueTraits> struct unordered_bucket_impl { typedef typename get_slist_impl_from_supposed_value_traits <SupposedValueTraits>::type slist_impl; typedef detail::bucket_impl<slist_impl> implementation_defined; typedef implementation_defined type; }; template<class SupposedValueTraits> struct unordered_bucket_ptr_impl { typedef typename detail::get_node_traits <SupposedValueTraits>::type::node_ptr node_ptr; typedef typename unordered_bucket_impl <SupposedValueTraits>::type bucket_type; typedef typename pointer_traits <node_ptr>::template rebind_pointer < bucket_type >::type implementation_defined; typedef implementation_defined type; }; template <class T> struct store_hash_bool { template<bool Add> struct two_or_three {one _[2 + Add];}; template <class U> static one test(...); template <class U> static two_or_three<U::store_hash> test (int); static const std::size_t value = sizeof(test<T>(0)); }; template <class T> struct store_hash_is_true { static const bool value = store_hash_bool<T>::value > sizeof(one)*2; }; template <class T> struct optimize_multikey_bool { template<bool Add> struct two_or_three {one _[2 + Add];}; template <class U> static one test(...); template <class U> static two_or_three<U::optimize_multikey> test (int); static const std::size_t value = sizeof(test<T>(0)); }; template <class T> struct optimize_multikey_is_true { static const bool value = optimize_multikey_bool<T>::value > sizeof(one)*2; }; struct insert_commit_data_impl { std::size_t hash; }; template<class Node, class SlistNodePtr> inline typename pointer_traits<SlistNodePtr>::template rebind_pointer<Node>::type dcast_bucket_ptr(const SlistNodePtr &p) { typedef typename pointer_traits<SlistNodePtr>::template rebind_pointer<Node>::type node_ptr; return pointer_traits<node_ptr>::pointer_to(static_cast<Node&>(*p)); } template<class NodeTraits> struct group_functions { typedef NodeTraits node_traits; typedef unordered_group_adapter<node_traits> group_traits; typedef typename node_traits::node_ptr node_ptr; typedef typename node_traits::node node; typedef typename reduced_slist_node_traits <node_traits>::type reduced_node_traits; typedef typename reduced_node_traits::node_ptr slist_node_ptr; typedef typename reduced_node_traits::node slist_node; typedef circular_slist_algorithms<group_traits> group_algorithms; static slist_node_ptr get_bucket_before_begin (const slist_node_ptr &bucket_beg, const slist_node_ptr &bucket_end, const node_ptr &p) { //First find the last node of p's group. //This requires checking the first node of the next group or //the bucket node. node_ptr prev_node = p; node_ptr nxt(node_traits::get_next(p)); while(!(bucket_beg <= nxt && nxt <= bucket_end) && (group_traits::get_next(nxt) == prev_node)){ prev_node = nxt; nxt = node_traits::get_next(nxt); } //If we've reached the bucket node just return it. if(bucket_beg <= nxt && nxt <= bucket_end){ return nxt; } //Otherwise, iterate using group links until the bucket node node_ptr first_node_of_group = nxt; node_ptr last_node_group = group_traits::get_next(first_node_of_group); slist_node_ptr possible_end = node_traits::get_next(last_node_group); while(!(bucket_beg <= possible_end && possible_end <= bucket_end)){ first_node_of_group = detail::dcast_bucket_ptr<node>(possible_end); last_node_group = group_traits::get_next(first_node_of_group); possible_end = node_traits::get_next(last_node_group); } return possible_end; } static node_ptr get_prev_to_first_in_group(const slist_node_ptr &bucket_node, const node_ptr &first_in_group) { //Just iterate using group links and obtain the node //before "first_in_group)" node_ptr prev_node = detail::dcast_bucket_ptr<node>(bucket_node); node_ptr nxt(node_traits::get_next(prev_node)); while(nxt != first_in_group){ prev_node = group_traits::get_next(nxt); nxt = node_traits::get_next(prev_node); } return prev_node; } static node_ptr get_first_in_group_of_last_in_group(const node_ptr &last_in_group) { //Just iterate using group links and obtain the node //before "last_in_group" node_ptr possible_first = group_traits::get_next(last_in_group); node_ptr possible_first_prev = group_traits::get_next(possible_first); // The deleted node is at the end of the group, so the // node in the group pointing to it is at the beginning // of the group. Find that to change its pointer. while(possible_first_prev != last_in_group){ possible_first = possible_first_prev; possible_first_prev = group_traits::get_next(possible_first); } return possible_first; } static void erase_from_group(const slist_node_ptr &end_ptr, const node_ptr &to_erase_ptr, detail::true_) { node_ptr nxt_ptr(node_traits::get_next(to_erase_ptr)); node_ptr prev_in_group_ptr(group_traits::get_next(to_erase_ptr)); bool last_in_group = (end_ptr == nxt_ptr) || (group_traits::get_next(nxt_ptr) != to_erase_ptr); bool is_first_in_group = node_traits::get_next(prev_in_group_ptr) != to_erase_ptr; if(is_first_in_group && last_in_group){ group_algorithms::init(to_erase_ptr); } else if(is_first_in_group){ group_algorithms::unlink_after(nxt_ptr); } else if(last_in_group){ node_ptr first_in_group = get_first_in_group_of_last_in_group(to_erase_ptr); group_algorithms::unlink_after(first_in_group); } else{ group_algorithms::unlink_after(nxt_ptr); } } static void erase_from_group(const slist_node_ptr&, const node_ptr&, detail::false_) {} static node_ptr get_last_in_group(const node_ptr &first_in_group, detail::true_) { return group_traits::get_next(first_in_group); } static node_ptr get_last_in_group(const node_ptr &n, detail::false_) { return n; } static void init_group(const node_ptr &n, true_) { group_algorithms::init(n); } static void init_group(const node_ptr &, false_) {} static void insert_in_group(const node_ptr &first_in_group, const node_ptr &n, true_) { if(first_in_group){ if(group_algorithms::unique(first_in_group)) group_algorithms::link_after(first_in_group, n); else{ group_algorithms::link_after(node_traits::get_next(first_in_group), n); } } else{ group_algorithms::init_header(n); } } static slist_node_ptr get_previous_and_next_in_group ( const slist_node_ptr &i, node_ptr &nxt_in_group //If first_end_ptr == last_end_ptr, then first_end_ptr is the bucket of i //Otherwise first_end_ptr is the first bucket and last_end_ptr the last one. , const slist_node_ptr &first_end_ptr, const slist_node_ptr &last_end_ptr) { slist_node_ptr prev; node_ptr elem(detail::dcast_bucket_ptr<node>(i)); //It's the last in group if the next_node is a bucket slist_node_ptr nxt(node_traits::get_next(elem)); bool last_in_group = (first_end_ptr <= nxt && nxt <= last_end_ptr) || (group_traits::get_next(detail::dcast_bucket_ptr<node>(nxt)) != elem); //It's the first in group if group_previous's next_node is not //itself, as group list does not link bucket node_ptr prev_in_group(group_traits::get_next(elem)); bool first_in_group = node_traits::get_next(prev_in_group) != elem; if(first_in_group){ node_ptr start_pos; if(last_in_group){ start_pos = elem; nxt_in_group = node_ptr(); } else{ start_pos = prev_in_group; nxt_in_group = node_traits::get_next(elem); } slist_node_ptr bucket_node; if(first_end_ptr != last_end_ptr){ bucket_node = group_functions::get_bucket_before_begin (first_end_ptr, last_end_ptr, start_pos); } else{ bucket_node = first_end_ptr; } prev = group_functions::get_prev_to_first_in_group(bucket_node, elem); } else{ if(last_in_group){ nxt_in_group = group_functions::get_first_in_group_of_last_in_group(elem); } else{ nxt_in_group = node_traits::get_next(elem); } prev = group_traits::get_next(elem); } return prev; } static void insert_in_group(const node_ptr&, const node_ptr&, false_) {} }; template<class BucketType, class SplitTraits> class incremental_rehash_rollback { private: typedef BucketType bucket_type; typedef SplitTraits split_traits; incremental_rehash_rollback(); incremental_rehash_rollback & operator=(const incremental_rehash_rollback &); incremental_rehash_rollback (const incremental_rehash_rollback &); public: incremental_rehash_rollback (bucket_type &source_bucket, bucket_type &destiny_bucket, split_traits &split_traits) : source_bucket_(source_bucket), destiny_bucket_(destiny_bucket) , split_traits_(split_traits), released_(false) {} void release() { released_ = true; } ~incremental_rehash_rollback() { if(!released_){ //If an exception is thrown, just put all moved nodes back in the old bucket //and move back the split mark. destiny_bucket_.splice_after(destiny_bucket_.before_begin(), source_bucket_); split_traits_.decrement(); } } private: bucket_type &source_bucket_; bucket_type &destiny_bucket_; split_traits &split_traits_; bool released_; }; template<class NodeTraits> struct node_functions { static void store_hash(typename NodeTraits::node_ptr p, std::size_t h, true_) { return NodeTraits::set_hash(p, h); } static void store_hash(typename NodeTraits::node_ptr, std::size_t, false_) {} }; inline std::size_t hash_to_bucket(std::size_t hash_value, std::size_t bucket_cnt, detail::false_) { return hash_value % bucket_cnt; } inline std::size_t hash_to_bucket(std::size_t hash_value, std::size_t bucket_cnt, detail::true_) { return hash_value & (bucket_cnt - 1); } template<bool Power2Buckets, bool Incremental> inline std::size_t hash_to_bucket_split(std::size_t hash_value, std::size_t bucket_cnt, std::size_t split) { std::size_t bucket_number = detail::hash_to_bucket(hash_value, bucket_cnt, detail::bool_<Power2Buckets>()); if(Incremental) if(bucket_number >= split) bucket_number -= bucket_cnt/2; return bucket_number; } } //namespace detail { //!This metafunction will obtain the type of a bucket //!from the value_traits or hook option to be used with //!a hash container. template<class ValueTraitsOrHookOption> struct unordered_bucket : public detail::unordered_bucket_impl <typename ValueTraitsOrHookOption:: template pack<empty>::proto_value_traits > {}; //!This metafunction will obtain the type of a bucket pointer //!from the value_traits or hook option to be used with //!a hash container. template<class ValueTraitsOrHookOption> struct unordered_bucket_ptr : public detail::unordered_bucket_ptr_impl <typename ValueTraitsOrHookOption:: template pack<empty>::proto_value_traits > {}; //!This metafunction will obtain the type of the default bucket traits //!(when the user does not specify the bucket_traits<> option) from the //!value_traits or hook option to be used with //!a hash container. template<class ValueTraitsOrHookOption> struct unordered_default_bucket_traits { typedef typename ValueTraitsOrHookOption:: template pack<empty>::proto_value_traits supposed_value_traits; typedef typename detail:: get_slist_impl_from_supposed_value_traits <supposed_value_traits>::type slist_impl; typedef detail::bucket_traits_impl <slist_impl> implementation_defined; typedef implementation_defined type; }; struct default_bucket_traits; //hashtable default hook traits struct default_hashtable_hook_applier { template <class T> struct apply{ typedef typename T::default_hashtable_hook type; }; }; template<> struct is_default_hook_tag<default_hashtable_hook_applier> { static const bool value = true; }; struct hashtable_defaults { typedef default_hashtable_hook_applier proto_value_traits; typedef std::size_t size_type; typedef void equal; typedef void hash; typedef default_bucket_traits bucket_traits; static const bool constant_time_size = true; static const bool power_2_buckets = false; static const bool cache_begin = false; static const bool compare_hash = false; static const bool incremental = false; }; template<class ValueTraits, bool IsConst> struct downcast_node_to_value_t : public detail::node_to_value<ValueTraits, IsConst> { typedef detail::node_to_value<ValueTraits, IsConst> base_t; typedef typename base_t::result_type result_type; typedef ValueTraits value_traits; typedef typename detail::get_slist_impl <typename detail::reduced_slist_node_traits <typename value_traits::node_traits>::type >::type slist_impl; typedef typename detail::add_const_if_c <typename slist_impl::node, IsConst>::type & first_argument_type; typedef typename detail::add_const_if_c < typename ValueTraits::node_traits::node , IsConst>::type & intermediate_argument_type; typedef typename pointer_traits <typename ValueTraits::pointer>:: template rebind_pointer <const ValueTraits>::type const_value_traits_ptr; downcast_node_to_value_t(const const_value_traits_ptr &ptr) : base_t(ptr) {} result_type operator()(first_argument_type arg) const { return this->base_t::operator()(static_cast<intermediate_argument_type>(arg)); } }; template<class F, class SlistNodePtr, class NodePtr> struct node_cast_adaptor : private detail::ebo_functor_holder<F> { typedef detail::ebo_functor_holder<F> base_t; typedef typename pointer_traits<SlistNodePtr>::element_type slist_node; typedef typename pointer_traits<NodePtr>::element_type node; template<class ConvertibleToF, class RealValuTraits> node_cast_adaptor(const ConvertibleToF &c2f, const RealValuTraits *traits) : base_t(base_t(c2f, traits)) {} typename base_t::node_ptr operator()(const slist_node &to_clone) { return base_t::operator()(static_cast<const node &>(to_clone)); } void operator()(SlistNodePtr to_clone) { base_t::operator()(pointer_traits<NodePtr>::pointer_to(static_cast<node &>(*to_clone))); } }; static const std::size_t hashtable_data_bool_flags_mask = ( hash_bool_flags::cache_begin_pos | hash_bool_flags::constant_time_size_pos | hash_bool_flags::incremental_pos ); //bucket_plus_vtraits stores ValueTraits + BucketTraits //this data is needed by iterators to obtain the //value from the iterator and detect the bucket template<class ValueTraits, class BucketTraits> struct bucket_plus_vtraits : public ValueTraits { typedef BucketTraits bucket_traits; typedef ValueTraits value_traits; static const bool safemode_or_autounlink = is_safe_autounlink<value_traits::link_mode>::value; typedef typename detail::get_slist_impl_from_supposed_value_traits <value_traits>::type slist_impl; typedef typename value_traits::node_traits node_traits; typedef unordered_group_adapter<node_traits> group_traits; typedef typename slist_impl::iterator siterator; typedef typename slist_impl::size_type size_type; typedef detail::bucket_impl<slist_impl> bucket_type; typedef detail::group_functions<node_traits> group_functions_t; typedef typename slist_impl::node_algorithms node_algorithms; typedef typename slist_impl::node_ptr slist_node_ptr; typedef typename node_traits::node_ptr node_ptr; typedef typename node_traits::node node; typedef typename value_traits::value_type value_type; typedef circular_slist_algorithms<group_traits> group_algorithms; typedef typename pointer_traits <typename value_traits::pointer>:: template rebind_pointer <const value_traits>::type const_value_traits_ptr; typedef typename pointer_traits <typename value_traits::pointer>:: template rebind_pointer <const bucket_plus_vtraits>::type const_bucket_value_traits_ptr; typedef typename detail::unordered_bucket_ptr_impl <value_traits>::type bucket_ptr; typedef detail::bool_<detail::optimize_multikey_is_true <node_traits>::value> optimize_multikey_t; template<class BucketTraitsType> bucket_plus_vtraits(const ValueTraits &val_traits, BOOST_FWD_REF(BucketTraitsType) b_traits) : ValueTraits(val_traits), bucket_traits_(::boost::forward<BucketTraitsType>(b_traits)) {} bucket_plus_vtraits & operator =(const bucket_plus_vtraits &x) { bucket_traits_ = x.bucket_traits_; return *this; } const_value_traits_ptr priv_value_traits_ptr() const { return pointer_traits<const_value_traits_ptr>::pointer_to(this->priv_value_traits()); } //bucket_value_traits // const bucket_plus_vtraits &get_bucket_value_traits() const { return *this; } bucket_plus_vtraits &get_bucket_value_traits() { return *this; } const_bucket_value_traits_ptr bucket_value_traits_ptr() const { return pointer_traits<const_bucket_value_traits_ptr>::pointer_to(this->get_bucket_value_traits()); } //value traits // const value_traits &priv_value_traits() const { return *this; } value_traits &priv_value_traits() { return *this; } //bucket_traits // const bucket_traits &priv_bucket_traits() const { return this->bucket_traits_; } bucket_traits &priv_bucket_traits() { return this->bucket_traits_; } //bucket operations bucket_ptr priv_bucket_pointer() const { return this->priv_bucket_traits().bucket_begin(); } typename slist_impl::size_type priv_bucket_count() const { return this->priv_bucket_traits().bucket_count(); } bucket_ptr priv_invalid_bucket() const { const bucket_traits &rbt = this->priv_bucket_traits(); return rbt.bucket_begin() + rbt.bucket_count(); } siterator priv_invalid_local_it() const { return this->priv_bucket_traits().bucket_begin()->before_begin(); } static siterator priv_get_last(bucket_type &b, detail::true_) //optimize multikey { //First find the last node of p's group. //This requires checking the first node of the next group or //the bucket node. slist_node_ptr end_ptr(b.end().pointed_node()); node_ptr possible_end(node_traits::get_next( detail::dcast_bucket_ptr<node>(end_ptr))); node_ptr last_node_group(possible_end); while(end_ptr != possible_end){ last_node_group = group_traits::get_next(detail::dcast_bucket_ptr<node>(possible_end)); possible_end = node_traits::get_next(last_node_group); } return bucket_type::s_iterator_to(*last_node_group); } static siterator priv_get_last(bucket_type &b, detail::false_) //NOT optimize multikey { return b.previous(b.end()); } static siterator priv_get_previous(bucket_type &b, siterator i, detail::true_) //optimize multikey { node_ptr elem(detail::dcast_bucket_ptr<node>(i.pointed_node())); node_ptr prev_in_group(group_traits::get_next(elem)); bool first_in_group = node_traits::get_next(prev_in_group) != elem; typename bucket_type::node &n = first_in_group ? *group_functions_t::get_prev_to_first_in_group(b.end().pointed_node(), elem) : *group_traits::get_next(elem) ; return bucket_type::s_iterator_to(n); } static siterator priv_get_previous(bucket_type &b, siterator i, detail::false_) //NOT optimize multikey { return b.previous(i); } static void priv_clear_group_nodes(bucket_type &b, detail::true_) //optimize multikey { siterator it(b.begin()), itend(b.end()); while(it != itend){ node_ptr to_erase(detail::dcast_bucket_ptr<node>(it.pointed_node())); ++it; group_algorithms::init(to_erase); } } static void priv_clear_group_nodes(bucket_type &, detail::false_) //NOT optimize multikey {} std::size_t priv_get_bucket_num_no_hash_store(siterator it, detail::true_) //optimize multikey { const bucket_ptr f(this->priv_bucket_pointer()), l(f + this->priv_bucket_count() - 1); slist_node_ptr bb = group_functions_t::get_bucket_before_begin ( f->end().pointed_node() , l->end().pointed_node() , detail::dcast_bucket_ptr<node>(it.pointed_node())); //Now get the bucket_impl from the iterator const bucket_type &b = static_cast<const bucket_type&> (bucket_type::slist_type::container_from_end_iterator(bucket_type::s_iterator_to(*bb))); //Now just calculate the index b has in the bucket array return static_cast<size_type>(&b - &*f); } std::size_t priv_get_bucket_num_no_hash_store(siterator it, detail::false_) //NO optimize multikey { bucket_ptr f(this->priv_bucket_pointer()), l(f + this->priv_bucket_count() - 1); slist_node_ptr first_ptr(f->cend().pointed_node()) , last_ptr(l->cend().pointed_node()); //The end node is embedded in the singly linked list: //iterate until we reach it. while(!(first_ptr <= it.pointed_node() && it.pointed_node() <= last_ptr)){ ++it; } //Now get the bucket_impl from the iterator const bucket_type &b = static_cast<const bucket_type&> (bucket_type::container_from_end_iterator(it)); //Now just calculate the index b has in the bucket array return static_cast<std::size_t>(&b - &*f); } static std::size_t priv_stored_hash(slist_node_ptr n, detail::true_) //store_hash { return node_traits::get_hash(detail::dcast_bucket_ptr<node>(n)); } static std::size_t priv_stored_hash(slist_node_ptr, detail::false_) //NO store_hash (This should never be called) { BOOST_INTRUSIVE_INVARIANT_ASSERT(0); return 0; } node &priv_value_to_node(value_type &v) { return *this->priv_value_traits().to_node_ptr(v); } const node &priv_value_to_node(const value_type &v) const { return *this->priv_value_traits().to_node_ptr(v); } value_type &priv_value_from_slist_node(slist_node_ptr n) { return *this->priv_value_traits().to_value_ptr(detail::dcast_bucket_ptr<node>(n)); } const value_type &priv_value_from_slist_node(slist_node_ptr n) const { return *this->priv_value_traits().to_value_ptr(detail::dcast_bucket_ptr<node>(n)); } void priv_clear_buckets(const bucket_ptr buckets_ptr, const size_type bucket_cnt) { bucket_ptr buckets_it = buckets_ptr; for(size_type bucket_i = 0; bucket_i != bucket_cnt; ++buckets_it, ++bucket_i){ if(safemode_or_autounlink){ bucket_plus_vtraits::priv_clear_group_nodes(*buckets_it, optimize_multikey_t()); buckets_it->clear_and_dispose(detail::init_disposer<node_algorithms>()); } else{ buckets_it->clear(); } } } bucket_traits bucket_traits_; }; template<class Hash, class T> struct get_hash { typedef Hash type; }; template<class T> struct get_hash<void, T> { typedef ::boost::hash<T> type; }; //bucket_hash_t //Stores bucket_plus_vtraits plust the hash function template<class VoidOrKeyHash, class ValueTraits, class BucketTraits> struct bucket_hash_t : public detail::ebo_functor_holder <typename get_hash< VoidOrKeyHash , typename bucket_plus_vtraits<ValueTraits,BucketTraits>::value_traits::value_type >::type > { typedef typename bucket_plus_vtraits<ValueTraits,BucketTraits>::value_traits value_traits; typedef typename value_traits::value_type value_type; typedef typename value_traits::node_traits node_traits; typedef typename get_hash< VoidOrKeyHash, value_type>::type hasher; typedef BucketTraits bucket_traits; typedef bucket_plus_vtraits<ValueTraits, BucketTraits> bucket_plus_vtraits_t; template<class BucketTraitsType> bucket_hash_t(const ValueTraits &val_traits, BOOST_FWD_REF(BucketTraitsType) b_traits, const hasher & h) : detail::ebo_functor_holder<hasher>(h), internal(val_traits, ::boost::forward<BucketTraitsType>(b_traits)) {} const hasher &priv_hasher() const { return this->detail::ebo_functor_holder<hasher>::get(); } hasher &priv_hasher() { return this->detail::ebo_functor_holder<hasher>::get(); } std::size_t priv_stored_or_compute_hash(const value_type &v, detail::true_) const //For store_hash == true { return node_traits::get_hash(this->internal.priv_value_traits().to_node_ptr(v)); } std::size_t priv_stored_or_compute_hash(const value_type &v, detail::false_) const //For store_hash == false { return this->priv_hasher()(v); } bucket_plus_vtraits_t internal; //4 }; template<class EqualTo, class T> struct get_equal_to { typedef EqualTo type; }; template<class T> struct get_equal_to<void, T> { typedef ::std::equal_to<T> type; }; //bucket_hash_equal_t //Stores bucket_hash_t and the equality function when the first //non-empty bucket shall not be cached. template<class VoidOrKeyHash, class VoidOrKeyEqual, class ValueTraits, class BucketTraits, bool> struct bucket_hash_equal_t : public detail::ebo_functor_holder //equal <typename get_equal_to< VoidOrKeyEqual , typename bucket_plus_vtraits<ValueTraits,BucketTraits>::value_traits::value_type >::type > { typedef bucket_hash_t<VoidOrKeyHash, ValueTraits, BucketTraits> bucket_hash_type; typedef bucket_plus_vtraits<ValueTraits,BucketTraits> bucket_plus_vtraits_t; typedef typename bucket_plus_vtraits_t::value_traits value_traits; typedef typename get_equal_to< VoidOrKeyEqual , typename value_traits::value_type >::type value_equal; typedef typename bucket_hash_type::hasher hasher; typedef BucketTraits bucket_traits; typedef typename bucket_plus_vtraits_t::slist_impl slist_impl; typedef typename slist_impl::size_type size_type; typedef typename slist_impl::iterator siterator; typedef detail::bucket_impl<slist_impl> bucket_type; typedef typename detail::unordered_bucket_ptr_impl<value_traits>::type bucket_ptr; template<class BucketTraitsType> bucket_hash_equal_t(const ValueTraits &val_traits, BOOST_FWD_REF(BucketTraitsType) b_traits, const hasher & h, const value_equal &e) : detail::ebo_functor_holder<value_equal>(e) , internal(val_traits, ::boost::forward<BucketTraitsType>(b_traits), h) {} bucket_ptr priv_get_cache() { return this->internal.internal.priv_bucket_pointer(); } void priv_set_cache(const bucket_ptr &) {} size_type priv_get_cache_bucket_num() { return 0u; } void priv_initialize_cache() {} void priv_swap_cache(bucket_hash_equal_t &) {} siterator priv_begin() const { size_type n = 0; size_type bucket_cnt = this->internal.internal.priv_bucket_count(); for (n = 0; n < bucket_cnt; ++n){ bucket_type &b = this->internal.internal.priv_bucket_pointer()[n]; if(!b.empty()){ return b.begin(); } } return this->internal.internal.priv_invalid_local_it(); } void priv_insertion_update_cache(size_type) {} void priv_erasure_update_cache_range(size_type, size_type) {} void priv_erasure_update_cache() {} const value_equal &priv_equal() const { return this->detail::ebo_functor_holder<value_equal>::get(); } value_equal &priv_equal() { return this->detail::ebo_functor_holder<value_equal>::get(); } bucket_hash_t<VoidOrKeyHash, ValueTraits, BucketTraits> internal; //3 }; //bucket_hash_equal_t //Stores bucket_hash_t and the equality function when the first //non-empty bucket shall be cached. template<class VoidOrKeyHash, class VoidOrKeyEqual, class ValueTraits, class BucketTraits> //cache_begin == true version struct bucket_hash_equal_t<VoidOrKeyHash, VoidOrKeyEqual, ValueTraits, BucketTraits, true> : public detail::ebo_functor_holder //equal <typename get_equal_to< VoidOrKeyEqual , typename bucket_plus_vtraits<ValueTraits,BucketTraits>::value_traits::value_type >::type > { typedef bucket_plus_vtraits<ValueTraits, BucketTraits> bucket_plus_vtraits_t; typedef bucket_hash_t<VoidOrKeyHash, ValueTraits, BucketTraits> bucket_hash_type; typedef typename bucket_plus_vtraits <ValueTraits,BucketTraits>::value_traits value_traits; typedef typename get_equal_to < VoidOrKeyEqual , typename value_traits::value_type>::type value_equal; typedef typename bucket_hash_type::hasher hasher; typedef BucketTraits bucket_traits; typedef typename bucket_plus_vtraits_t::slist_impl::size_type size_type; typedef typename bucket_plus_vtraits_t::slist_impl::iterator siterator; template<class BucketTraitsType> bucket_hash_equal_t(const ValueTraits &val_traits, BOOST_FWD_REF(BucketTraitsType) b_traits, const hasher & h, const value_equal &e) : detail::ebo_functor_holder<value_equal>(e) , internal(val_traits, ::boost::forward<BucketTraitsType>(b_traits), h) {} typedef typename detail::unordered_bucket_ptr_impl <typename bucket_hash_type::value_traits>::type bucket_ptr; bucket_ptr &priv_get_cache() { return cached_begin_; } const bucket_ptr &priv_get_cache() const { return cached_begin_; } void priv_set_cache(const bucket_ptr &p) { cached_begin_ = p; } std::size_t priv_get_cache_bucket_num() { return this->cached_begin_ - this->internal.internal.priv_bucket_pointer(); } void priv_initialize_cache() { this->cached_begin_ = this->internal.internal.priv_invalid_bucket(); } void priv_swap_cache(bucket_hash_equal_t &other) { std::swap(this->cached_begin_, other.cached_begin_); } siterator priv_begin() const { if(this->cached_begin_ == this->internal.internal.priv_invalid_bucket()){ return this->internal.internal.priv_invalid_local_it(); } else{ return this->cached_begin_->begin(); } } void priv_insertion_update_cache(size_type insertion_bucket) { bucket_ptr p = this->internal.internal.priv_bucket_pointer() + insertion_bucket; if(p < this->cached_begin_){ this->cached_begin_ = p; } } const value_equal &priv_equal() const { return this->detail::ebo_functor_holder<value_equal>::get(); } value_equal &priv_equal() { return this->detail::ebo_functor_holder<value_equal>::get(); } void priv_erasure_update_cache_range(size_type first_bucket_num, size_type last_bucket_num) { //If the last bucket is the end, the cache must be updated //to the last position if all if(this->priv_get_cache_bucket_num() == first_bucket_num && this->internal.internal.priv_bucket_pointer()[first_bucket_num].empty() ){ this->priv_set_cache(this->internal.internal.priv_bucket_pointer() + last_bucket_num); this->priv_erasure_update_cache(); } } void priv_erasure_update_cache() { if(this->cached_begin_ != this->internal.internal.priv_invalid_bucket()){ size_type current_n = this->priv_get_cache() - this->internal.internal.priv_bucket_pointer(); for( const size_type num_buckets = this->internal.internal.priv_bucket_count() ; current_n < num_buckets ; ++current_n, ++this->priv_get_cache()){ if(!this->priv_get_cache()->empty()){ return; } } this->priv_initialize_cache(); } } bucket_ptr cached_begin_; bucket_hash_t<VoidOrKeyHash, ValueTraits, BucketTraits> internal; //2 }; //hashdata_internal //Stores bucket_hash_equal_t and split_traits template<class SizeType, std::size_t BoolFlags, class VoidOrKeyHash, class VoidOrKeyEqual, class ValueTraits, class BucketTraits> struct hashdata_internal : public detail::size_holder< 0 != (BoolFlags & hash_bool_flags::incremental_pos), SizeType, int> //split_traits { typedef bucket_hash_equal_t < VoidOrKeyHash, VoidOrKeyEqual , ValueTraits, BucketTraits , 0 != (BoolFlags & hash_bool_flags::cache_begin_pos) > internal_type; typedef typename internal_type::value_equal value_equal; typedef typename internal_type::hasher hasher; typedef bucket_plus_vtraits<ValueTraits,BucketTraits> bucket_plus_vtraits_t; typedef typename bucket_plus_vtraits_t::size_type size_type; typedef typename bucket_plus_vtraits_t::bucket_ptr bucket_ptr; typedef detail::size_holder <0 != (BoolFlags & hash_bool_flags::incremental_pos) , SizeType, int> split_traits; typedef typename bucket_plus_vtraits_t:: value_traits::node_traits node_traits; typedef detail::bool_<detail::optimize_multikey_is_true <node_traits>::value> optimize_multikey_t; template<class BucketTraitsType> hashdata_internal( const ValueTraits &val_traits, BOOST_FWD_REF(BucketTraitsType) b_traits , const hasher & h, const value_equal &e) : internal(val_traits, ::boost::forward<BucketTraitsType>(b_traits), h, e) {} split_traits &priv_split_traits() { return *this; } const split_traits &priv_split_traits() const { return *this; } ~hashdata_internal() { this->priv_clear_buckets(); } void priv_clear_buckets() { this->internal.internal.internal.priv_clear_buckets ( this->internal.priv_get_cache() , this->internal.internal.internal.priv_bucket_count() - (this->internal.priv_get_cache() - this->internal.internal.internal.priv_bucket_pointer())); } void priv_clear_buckets_and_cache() { this->priv_clear_buckets(); this->internal.priv_initialize_cache(); } void priv_initialize_buckets_and_cache() { this->internal.internal.internal.priv_clear_buckets ( this->internal.internal.internal.priv_bucket_pointer() , this->internal.internal.internal.priv_bucket_count()); this->internal.priv_initialize_cache(); } internal_type internal; //2 }; //hashtable_data_t //Stores hashdata_internal and size_traits template<class SizeType, std::size_t BoolFlags, class VoidOrKeyHash, class VoidOrKeyEqual, class ValueTraits, class BucketTraits> struct hashtable_data_t : public detail::size_holder < 0 != (BoolFlags & hash_bool_flags::constant_time_size_pos), SizeType> //size_traits { typedef detail::size_holder < 0 != (BoolFlags & hash_bool_flags::constant_time_size_pos) , SizeType> size_traits; typedef hashdata_internal < SizeType , BoolFlags & (hash_bool_flags::incremental_pos | hash_bool_flags::cache_begin_pos) , VoidOrKeyHash, VoidOrKeyEqual , ValueTraits, BucketTraits> internal_type; typedef ValueTraits value_traits; typedef typename internal_type::value_equal value_equal; typedef typename internal_type::hasher hasher; typedef BucketTraits bucket_traits; typedef bucket_plus_vtraits <ValueTraits,BucketTraits> bucket_plus_vtraits_t; template<class BucketTraitsType> hashtable_data_t( BOOST_FWD_REF(BucketTraitsType) b_traits, const hasher & h , const value_equal &e, const value_traits &val_traits) : internal(val_traits, ::boost::forward<BucketTraitsType>(b_traits), h, e) {} internal_type internal; //1 }; /// @endcond //! The class template hashtable is an intrusive hash table container, that //! is used to construct intrusive unordered_set and unordered_multiset containers. The //! no-throw guarantee holds only, if the VoidOrKeyEqual object and Hasher don't throw. //! //! hashtable is a semi-intrusive container: each object to be stored in the //! container must contain a proper hook, but the container also needs //! additional auxiliary memory to work: hashtable needs a pointer to an array //! of type `bucket_type` to be passed in the constructor. This bucket array must //! have at least the same lifetime as the container. This makes the use of //! hashtable more complicated than purely intrusive containers. //! `bucket_type` is default-constructible, copyable and assignable //! //! The template parameter \c T is the type to be managed by the container. //! The user can specify additional options and if no options are provided //! default options are used. //! //! The container supports the following options: //! \c base_hook<>/member_hook<>/value_traits<>, //! \c constant_time_size<>, \c size_type<>, \c hash<> and \c equal<> //! \c bucket_traits<>, power_2_buckets<>, cache_begin<> and incremental<>. //! //! hashtable only provides forward iterators but it provides 4 iterator types: //! iterator and const_iterator to navigate through the whole container and //! local_iterator and const_local_iterator to navigate through the values //! stored in a single bucket. Local iterators are faster and smaller. //! //! It's not recommended to use non constant-time size hashtables because several //! key functions, like "empty()", become non-constant time functions. Non //! constant_time size hashtables are mainly provided to support auto-unlink hooks. //! //! hashtables, does not make automatic rehashings nor //! offers functions related to a load factor. Rehashing can be explicitly requested //! and the user must provide a new bucket array that will be used from that moment. //! //! Since no automatic rehashing is done, iterators are never invalidated when //! inserting or erasing elements. Iterators are only invalidated when rehashing. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) template<class T, class ...Options> #else template<class ValueTraits, class VoidOrKeyHash, class VoidOrKeyEqual, class SizeType, class BucketTraits, std::size_t BoolFlags> #endif class hashtable_impl : private hashtable_data_t < SizeType , BoolFlags & hashtable_data_bool_flags_mask , VoidOrKeyHash, VoidOrKeyEqual, ValueTraits, BucketTraits> { typedef hashtable_data_t < SizeType , BoolFlags & hashtable_data_bool_flags_mask , VoidOrKeyHash, VoidOrKeyEqual, ValueTraits, BucketTraits> data_type; public: typedef ValueTraits value_traits; /// @cond typedef BucketTraits bucket_traits; typedef typename detail::get_slist_impl <typename detail::reduced_slist_node_traits <typename value_traits::node_traits>::type >::type slist_impl; typedef bucket_plus_vtraits<ValueTraits, BucketTraits> bucket_plus_vtraits_t; typedef typename bucket_plus_vtraits_t::const_value_traits_ptr const_value_traits_ptr; /// @endcond typedef typename value_traits::pointer pointer; typedef typename value_traits::const_pointer const_pointer; typedef typename value_traits::value_type value_type; typedef typename pointer_traits<pointer>::reference reference; typedef typename pointer_traits<const_pointer>::reference const_reference; typedef typename pointer_traits<pointer>::difference_type difference_type; typedef SizeType size_type; typedef value_type key_type; typedef typename data_type::value_equal key_equal; typedef typename data_type::value_equal value_equal; typedef typename data_type::hasher hasher; typedef detail::bucket_impl<slist_impl> bucket_type; typedef typename pointer_traits <pointer>::template rebind_pointer < bucket_type >::type bucket_ptr; typedef typename pointer_traits <pointer>::template rebind_pointer < const bucket_type >::type const_bucket_ptr; typedef typename pointer_traits <bucket_ptr>::reference bucket_reference; typedef typename pointer_traits <bucket_ptr>::reference const_bucket_reference; typedef typename slist_impl::iterator siterator; typedef typename slist_impl::const_iterator const_siterator; typedef hashtable_iterator<bucket_plus_vtraits_t, false> iterator; typedef hashtable_iterator<bucket_plus_vtraits_t, true> const_iterator; typedef typename value_traits::node_traits node_traits; typedef typename node_traits::node node; typedef typename pointer_traits <pointer>::template rebind_pointer < node >::type node_ptr; typedef typename pointer_traits <pointer>::template rebind_pointer < const node >::type const_node_ptr; typedef typename pointer_traits <node_ptr>::reference node_reference; typedef typename pointer_traits <const_node_ptr>::reference const_node_reference; typedef typename slist_impl::node_algorithms node_algorithms; static const bool stateful_value_traits = detail::is_stateful_value_traits<value_traits>::value; static const bool store_hash = detail::store_hash_is_true<node_traits>::value; static const bool unique_keys = 0 != (BoolFlags & hash_bool_flags::unique_keys_pos); static const bool constant_time_size = 0 != (BoolFlags & hash_bool_flags::constant_time_size_pos); static const bool cache_begin = 0 != (BoolFlags & hash_bool_flags::cache_begin_pos); static const bool compare_hash = 0 != (BoolFlags & hash_bool_flags::compare_hash_pos); static const bool incremental = 0 != (BoolFlags & hash_bool_flags::incremental_pos); static const bool power_2_buckets = incremental || (0 != (BoolFlags & hash_bool_flags::power_2_buckets_pos)); static const bool optimize_multikey = detail::optimize_multikey_is_true<node_traits>::value && !unique_keys; /// @cond private: //Configuration error: compare_hash<> can't be specified without store_hash<> //See documentation for more explanations BOOST_STATIC_ASSERT((!compare_hash || store_hash)); typedef typename slist_impl::node_ptr slist_node_ptr; typedef typename pointer_traits <slist_node_ptr>::template rebind_pointer < void >::type void_pointer; //We'll define group traits, but these won't be instantiated if //optimize_multikey is not true typedef unordered_group_adapter<node_traits> group_traits; typedef circular_slist_algorithms<group_traits> group_algorithms; typedef detail::bool_<store_hash> store_hash_t; typedef detail::bool_<optimize_multikey> optimize_multikey_t; typedef detail::bool_<cache_begin> cache_begin_t; typedef detail::bool_<power_2_buckets> power_2_buckets_t; typedef detail::size_holder<constant_time_size, size_type> size_traits; typedef detail::size_holder<incremental, size_type, int> split_traits; typedef detail::group_functions<node_traits> group_functions_t; typedef detail::node_functions<node_traits> node_functions_t; private: //noncopyable, movable BOOST_MOVABLE_BUT_NOT_COPYABLE(hashtable_impl) static const bool safemode_or_autounlink = is_safe_autounlink<value_traits::link_mode>::value; //Constant-time size is incompatible with auto-unlink hooks! BOOST_STATIC_ASSERT(!(constant_time_size && ((int)value_traits::link_mode == (int)auto_unlink))); //Cache begin is incompatible with auto-unlink hooks! BOOST_STATIC_ASSERT(!(cache_begin && ((int)value_traits::link_mode == (int)auto_unlink))); template<class Disposer> node_cast_adaptor< detail::node_disposer<Disposer, value_traits, CircularSListAlgorithms> , slist_node_ptr, node_ptr > make_node_disposer(const Disposer &disposer) const { return node_cast_adaptor < detail::node_disposer<Disposer, value_traits, CircularSListAlgorithms> , slist_node_ptr, node_ptr > (disposer, &this->priv_value_traits()); } /// @endcond public: typedef detail::insert_commit_data_impl insert_commit_data; typedef detail::transform_iterator < typename slist_impl::iterator , downcast_node_to_value_t < value_traits , false> > local_iterator; typedef detail::transform_iterator < typename slist_impl::iterator , downcast_node_to_value_t < value_traits , true> > const_local_iterator; public: //! <b>Requires</b>: buckets must not be being used by any other resource. //! //! <b>Effects</b>: Constructs an empty unordered_set, storing a reference //! to the bucket array and copies of the key_hasher and equal_func functors. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If value_traits::node_traits::node //! constructor throws (this does not happen with predefined Boost.Intrusive hooks) //! or the copy constructor or invocation of hash_func or equal_func throws. //! //! <b>Notes</b>: buckets array must be disposed only after //! *this is disposed. explicit hashtable_impl ( const bucket_traits &b_traits , const hasher & hash_func = hasher() , const key_equal &equal_func = key_equal() , const value_traits &v_traits = value_traits()) : data_type(b_traits, hash_func, equal_func, v_traits) { this->data_type::internal.priv_initialize_buckets_and_cache(); this->priv_size_traits().set_size(size_type(0)); size_type bucket_sz = this->priv_bucket_count(); BOOST_INTRUSIVE_INVARIANT_ASSERT(bucket_sz != 0); //Check power of two bucket array if the option is activated BOOST_INTRUSIVE_INVARIANT_ASSERT (!power_2_buckets || (0 == (bucket_sz & (bucket_sz-1)))); this->priv_split_traits().set_size(bucket_sz>>1); } //! <b>Effects</b>: to-do //! hashtable_impl(BOOST_RV_REF(hashtable_impl) x) : data_type( ::boost::move(x.priv_bucket_traits()) , ::boost::move(x.priv_hasher()) , ::boost::move(x.priv_equal()) , ::boost::move(x.priv_value_traits()) ) { this->priv_swap_cache(x); x.priv_initialize_cache(); if(constant_time_size){ this->priv_size_traits().set_size(size_type(0)); this->priv_size_traits().set_size(x.priv_size_traits().get_size()); x.priv_size_traits().set_size(size_type(0)); } if(incremental){ this->priv_split_traits().set_size(x.priv_split_traits().get_size()); x.priv_split_traits().set_size(size_type(0)); } } //! <b>Effects</b>: to-do //! hashtable_impl& operator=(BOOST_RV_REF(hashtable_impl) x) { this->swap(x); return *this; } #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) //! <b>Effects</b>: Detaches all elements from this. The objects in the unordered_set //! are not deleted (i.e. no destructors are called). //! //! <b>Complexity</b>: Linear to the number of elements in the unordered_set, if //! it's a safe-mode or auto-unlink value. Otherwise constant. //! //! <b>Throws</b>: Nothing. ~hashtable_impl(); #endif //! <b>Effects</b>: Returns an iterator pointing to the beginning of the unordered_set. //! //! <b>Complexity</b>: Amortized constant time. //! Worst case (empty unordered_set): O(this->bucket_count()) //! //! <b>Throws</b>: Nothing. iterator begin() { return iterator(this->priv_begin(), &this->get_bucket_value_traits()); } //! <b>Effects</b>: Returns a const_iterator pointing to the beginning //! of the unordered_set. //! //! <b>Complexity</b>: Amortized constant time. //! Worst case (empty unordered_set): O(this->bucket_count()) //! //! <b>Throws</b>: Nothing. const_iterator begin() const { return this->cbegin(); } //! <b>Effects</b>: Returns a const_iterator pointing to the beginning //! of the unordered_set. //! //! <b>Complexity</b>: Amortized constant time. //! Worst case (empty unordered_set): O(this->bucket_count()) //! //! <b>Throws</b>: Nothing. const_iterator cbegin() const { return const_iterator(this->priv_begin(), &this->get_bucket_value_traits()); } //! <b>Effects</b>: Returns an iterator pointing to the end of the unordered_set. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. iterator end() { return iterator(this->priv_invalid_local_it(), 0); } //! <b>Effects</b>: Returns a const_iterator pointing to the end of the unordered_set. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator end() const { return this->cend(); } //! <b>Effects</b>: Returns a const_iterator pointing to the end of the unordered_set. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_iterator cend() const { return const_iterator(this->priv_invalid_local_it(), 0); } //! <b>Effects</b>: Returns the hasher object used by the unordered_set. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If hasher copy-constructor throws. hasher hash_function() const { return this->priv_hasher(); } //! <b>Effects</b>: Returns the key_equal object used by the unordered_set. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If key_equal copy-constructor throws. key_equal key_eq() const { return this->priv_equal(); } //! <b>Effects</b>: Returns true if the container is empty. //! //! <b>Complexity</b>: if constant-time size and cache_begin options are disabled, //! average constant time (worst case, with empty() == true: O(this->bucket_count()). //! Otherwise constant. //! //! <b>Throws</b>: Nothing. bool empty() const { if(constant_time_size){ return !this->size(); } else if(cache_begin){ return this->begin() == this->end(); } else{ size_type bucket_cnt = this->priv_bucket_count(); const bucket_type *b = boost::intrusive::detail::to_raw_pointer(this->priv_bucket_pointer()); for (size_type n = 0; n < bucket_cnt; ++n, ++b){ if(!b->empty()){ return false; } } return true; } } //! <b>Effects</b>: Returns the number of elements stored in the unordered_set. //! //! <b>Complexity</b>: Linear to elements contained in *this if //! constant_time_size is false. Constant-time otherwise. //! //! <b>Throws</b>: Nothing. size_type size() const { if(constant_time_size) return this->priv_size_traits().get_size(); else{ size_type len = 0; size_type bucket_cnt = this->priv_bucket_count(); const bucket_type *b = boost::intrusive::detail::to_raw_pointer(this->priv_bucket_pointer()); for (size_type n = 0; n < bucket_cnt; ++n, ++b){ len += b->size(); } return len; } } //! <b>Requires</b>: the hasher and the equality function unqualified swap //! call should not throw. //! //! <b>Effects</b>: Swaps the contents of two unordered_sets. //! Swaps also the contained bucket array and equality and hasher functors. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If the swap() call for the comparison or hash functors //! found using ADL throw. Basic guarantee. void swap(hashtable_impl& other) { using std::swap; //These can throw swap(this->priv_equal(), other.priv_equal()); swap(this->priv_hasher(), other.priv_hasher()); //These can't throw swap(this->priv_bucket_traits(), other.priv_bucket_traits()); swap(this->priv_value_traits(), other.priv_value_traits()); this->priv_swap_cache(other); if(constant_time_size){ size_type backup = this->priv_size_traits().get_size(); this->priv_size_traits().set_size(other.priv_size_traits().get_size()); other.priv_size_traits().set_size(backup); } if(incremental){ size_type backup = this->priv_split_traits().get_size(); this->priv_split_traits().set_size(other.priv_split_traits().get_size()); other.priv_split_traits().set_size(backup); } } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw //! Cloner should yield to nodes that compare equal and produce the same //! hash than the original node. //! //! <b>Effects</b>: Erases all the elements from *this //! calling Disposer::operator()(pointer), clones all the //! elements from src calling Cloner::operator()(const_reference ) //! and inserts them on *this. The hash function and the equality //! predicate are copied from the source. //! //! If store_hash option is true, this method does not use the hash function. //! //! If any operation throws, all cloned elements are unlinked and disposed //! calling Disposer::operator()(pointer). //! //! <b>Complexity</b>: Linear to erased plus inserted elements. //! //! <b>Throws</b>: If cloner or hasher throw or hash or equality predicate copying //! throws. Basic guarantee. template <class Cloner, class Disposer> void clone_from(const hashtable_impl &src, Cloner cloner, Disposer disposer) { this->clear_and_dispose(disposer); if(!constant_time_size || !src.empty()){ const size_type src_bucket_count = src.bucket_count(); const size_type dst_bucket_count = this->bucket_count(); //Check power of two bucket array if the option is activated BOOST_INTRUSIVE_INVARIANT_ASSERT (!power_2_buckets || (0 == (src_bucket_count & (src_bucket_count-1)))); BOOST_INTRUSIVE_INVARIANT_ASSERT (!power_2_buckets || (0 == (dst_bucket_count & (dst_bucket_count-1)))); //If src bucket count is bigger or equal, structural copy is possible if(!incremental && (src_bucket_count >= dst_bucket_count)){ //First clone the first ones const bucket_ptr src_buckets = src.priv_bucket_pointer(); const bucket_ptr dst_buckets = this->priv_bucket_pointer(); size_type constructed; typedef node_cast_adaptor< detail::node_disposer<Disposer, value_traits, CircularSListAlgorithms> , slist_node_ptr, node_ptr > NodeDisposer; typedef node_cast_adaptor< detail::node_cloner <Cloner, value_traits, CircularSListAlgorithms> , slist_node_ptr, node_ptr > NodeCloner; NodeDisposer node_disp(disposer, &this->priv_value_traits()); detail::exception_array_disposer<bucket_type, NodeDisposer, size_type> rollback(dst_buckets[0], node_disp, constructed); for( constructed = 0 ; constructed < dst_bucket_count ; ++constructed){ dst_buckets[constructed].clone_from ( src_buckets[constructed] , NodeCloner(cloner, &this->priv_value_traits()), node_disp); } if(src_bucket_count != dst_bucket_count){ //Now insert the remaining ones using the modulo trick for(//"constructed" comes from the previous loop ; constructed < src_bucket_count ; ++constructed){ bucket_type &dst_b = dst_buckets[detail::hash_to_bucket_split<power_2_buckets, incremental>(constructed, dst_bucket_count, dst_bucket_count)]; bucket_type &src_b = src_buckets[constructed]; for( siterator b(src_b.begin()), e(src_b.end()) ; b != e ; ++b){ dst_b.push_front(*(NodeCloner(cloner, &this->priv_value_traits())(*b.pointed_node()))); } } } this->priv_hasher() = src.priv_hasher(); this->priv_equal() = src.priv_equal(); rollback.release(); this->priv_size_traits().set_size(src.priv_size_traits().get_size()); this->priv_split_traits().set_size(dst_bucket_count); this->priv_insertion_update_cache(0u); this->priv_erasure_update_cache(); } else if(store_hash){ //Unlike previous cloning algorithm, this can throw //if cloner, hasher or comparison functor throw const_iterator b(src.cbegin()), e(src.cend()); detail::exception_disposer<hashtable_impl, Disposer> rollback(*this, disposer); for(; b != e; ++b){ std::size_t hash_value = this->priv_stored_or_compute_hash(*b, store_hash_t());; this->priv_insert_equal_with_hash(*cloner(*b), hash_value); } rollback.release(); } else{ //Unlike previous cloning algorithm, this can throw //if cloner, hasher or comparison functor throw const_iterator b(src.cbegin()), e(src.cend()); detail::exception_disposer<hashtable_impl, Disposer> rollback(*this, disposer); for(; b != e; ++b){ this->insert_equal(*cloner(*b)); } rollback.release(); } } } //! <b>Requires</b>: value must be an lvalue //! //! <b>Effects</b>: Inserts the value into the unordered_set. //! //! <b>Returns</b>: An iterator to the inserted value. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. Strong guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. iterator insert_equal(reference value) { size_type bucket_num; std::size_t hash_value; siterator prev; siterator it = this->priv_find (value, this->priv_hasher(), this->priv_equal(), bucket_num, hash_value, prev); return this->priv_insert_equal_find(value, bucket_num, hash_value, it); } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! <b>Effects</b>: Equivalent to this->insert_equal(t) for each element in [b, e). //! //! <b>Complexity</b>: Average case O(N), where N is std::distance(b, e). //! Worst case O(N*this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. Basic guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. template<class Iterator> void insert_equal(Iterator b, Iterator e) { for (; b != e; ++b) this->insert_equal(*b); } //! <b>Requires</b>: value must be an lvalue //! //! <b>Effects</b>: Tries to inserts value into the unordered_set. //! //! <b>Returns</b>: If the value //! is not already present inserts it and returns a pair containing the //! iterator to the new value and true. If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. Strong guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. std::pair<iterator, bool> insert_unique(reference value) { insert_commit_data commit_data; std::pair<iterator, bool> ret = this->insert_unique_check (value, this->priv_hasher(), this->priv_equal(), commit_data); if(!ret.second) return ret; return std::pair<iterator, bool> (this->insert_unique_commit(value, commit_data), true); } //! <b>Requires</b>: Dereferencing iterator must yield an lvalue //! of type value_type. //! //! <b>Effects</b>: Equivalent to this->insert_unique(t) for each element in [b, e). //! //! <b>Complexity</b>: Average case O(N), where N is std::distance(b, e). //! Worst case O(N*this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. Basic guarantee. //! //! <b>Note</b>: Does not affect the validity of iterators and references. //! No copy-constructors are called. template<class Iterator> void insert_unique(Iterator b, Iterator e) { for (; b != e; ++b) this->insert_unique(*b); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Checks if a value can be inserted in the unordered_set, using //! a user provided key instead of the value itself. //! //! <b>Returns</b>: If there is an equivalent value //! returns a pair containing an iterator to the already present value //! and false. If the value can be inserted returns true in the returned //! pair boolean and fills "commit_data" that is meant to be used with //! the "insert_commit" function. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or equal_func throw. Strong guarantee. //! //! <b>Notes</b>: This function is used to improve performance when constructing //! a value_type is expensive: if there is an equivalent value //! the constructed object must be discarded. Many times, the part of the //! node that is used to impose the hash or the equality is much cheaper to //! construct than the value_type and this function offers the possibility to //! use that the part to check if the insertion will be successful. //! //! If the check is successful, the user can construct the value_type and use //! "insert_commit" to insert the object in constant-time. //! //! "commit_data" remains valid for a subsequent "insert_commit" only if no more //! objects are inserted or erased from the unordered_set. //! //! After a successful rehashing insert_commit_data remains valid. template<class KeyType, class KeyHasher, class KeyValueEqual> std::pair<iterator, bool> insert_unique_check ( const KeyType &key , KeyHasher hash_func , KeyValueEqual equal_func , insert_commit_data &commit_data) { size_type bucket_num; siterator prev; siterator prev_pos = this->priv_find(key, hash_func, equal_func, bucket_num, commit_data.hash, prev); bool success = prev_pos == this->priv_invalid_local_it(); if(success){ prev_pos = prev; } return std::pair<iterator, bool>(iterator(prev_pos, &this->get_bucket_value_traits()),success); } //! <b>Requires</b>: value must be an lvalue of type value_type. commit_data //! must have been obtained from a previous call to "insert_check". //! No objects should have been inserted or erased from the unordered_set between //! the "insert_check" that filled "commit_data" and the call to "insert_commit". //! //! <b>Effects</b>: Inserts the value in the unordered_set using the information obtained //! from the "commit_data" that a previous "insert_check" filled. //! //! <b>Returns</b>: An iterator to the newly inserted object. //! //! <b>Complexity</b>: Constant time. //! //! <b>Throws</b>: Nothing. //! //! <b>Notes</b>: This function has only sense if a "insert_check" has been //! previously executed to fill "commit_data". No value should be inserted or //! erased between the "insert_check" and "insert_commit" calls. //! //! After a successful rehashing insert_commit_data remains valid. iterator insert_unique_commit(reference value, const insert_commit_data &commit_data) { size_type bucket_num = this->priv_hash_to_bucket(commit_data.hash); bucket_type &b = this->priv_bucket_pointer()[bucket_num]; this->priv_size_traits().increment(); node_ptr n = pointer_traits<node_ptr>::pointer_to(this->priv_value_to_node(value)); node_functions_t::store_hash(n, commit_data.hash, store_hash_t()); if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(n)); this->priv_insertion_update_cache(bucket_num); group_functions_t::insert_in_group(node_ptr(), n, optimize_multikey_t()); return iterator(b.insert_after(b.before_begin(), *n), &this->get_bucket_value_traits()); } //! <b>Effects</b>: Erases the element pointed to by i. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased element. No destructors are called. void erase(const_iterator i) { this->erase_and_dispose(i, detail::null_disposer()); } //! <b>Effects</b>: Erases the range pointed to by b end e. //! //! <b>Complexity</b>: Average case O(std::distance(b, e)), //! worst case O(this->size()). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. void erase(const_iterator b, const_iterator e) { this->erase_and_dispose(b, e, detail::null_disposer()); } //! <b>Effects</b>: Erases all the elements with the given value. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: Average case O(this->count(value)). //! Worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. //! Basic guarantee. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. size_type erase(const_reference value) { return this->erase(value, this->priv_hasher(), this->priv_equal()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Erases all the elements that have the same hash and //! compare equal with the given key. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: Average case O(this->count(value)). //! Worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or equal_func throw. Basic guarantee. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class KeyType, class KeyHasher, class KeyValueEqual> size_type erase(const KeyType& key, KeyHasher hash_func, KeyValueEqual equal_func) { return this->erase_and_dispose(key, hash_func, equal_func, detail::null_disposer()); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases the element pointed to by i. //! Disposer::operator()(pointer) is called for the removed element. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class Disposer> void erase_and_dispose(const_iterator i, Disposer disposer /// @cond , typename detail::enable_if_c<!detail::is_convertible<Disposer, const_iterator>::value >::type * = 0 /// @endcond ) { this->priv_erase(i, disposer, optimize_multikey_t()); this->priv_size_traits().decrement(); this->priv_erasure_update_cache(); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases the range pointed to by b end e. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Complexity</b>: Average case O(std::distance(b, e)), //! worst case O(this->size()). //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class Disposer> void erase_and_dispose(const_iterator b, const_iterator e, Disposer disposer) { if(b != e){ //Get the bucket number and local iterator for both iterators siterator first_local_it(b.slist_it()); size_type first_bucket_num = this->priv_get_bucket_num(first_local_it); const bucket_ptr buck_ptr = this->priv_bucket_pointer(); siterator before_first_local_it = this->priv_get_previous(buck_ptr[first_bucket_num], first_local_it); size_type last_bucket_num; siterator last_local_it; //For the end iterator, we will assign the end iterator //of the last bucket if(e == this->end()){ last_bucket_num = this->bucket_count() - 1; last_local_it = buck_ptr[last_bucket_num].end(); } else{ last_local_it = e.slist_it(); last_bucket_num = this->priv_get_bucket_num(last_local_it); } this->priv_erase_range(before_first_local_it, first_bucket_num, last_local_it, last_bucket_num, disposer); this->priv_erasure_update_cache_range(first_bucket_num, last_bucket_num); } } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all the elements with the given value. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: Average case O(this->count(value)). //! Worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. //! Basic guarantee. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class Disposer> size_type erase_and_dispose(const_reference value, Disposer disposer) { return this->erase_and_dispose(value, this->priv_hasher(), this->priv_equal(), disposer); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all the elements with the given key. //! according to the comparison functor "equal_func". //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Returns</b>: The number of erased elements. //! //! <b>Complexity</b>: Average case O(this->count(value)). //! Worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or equal_func throw. Basic guarantee. //! //! <b>Note</b>: Invalidates the iterators //! to the erased elements. template<class KeyType, class KeyHasher, class KeyValueEqual, class Disposer> size_type erase_and_dispose(const KeyType& key, KeyHasher hash_func ,KeyValueEqual equal_func, Disposer disposer) { size_type bucket_num; std::size_t h; siterator prev; siterator it = this->priv_find(key, hash_func, equal_func, bucket_num, h, prev); bool success = it != this->priv_invalid_local_it(); size_type cnt(0); if(!success){ return 0; } else if(optimize_multikey){ siterator last = bucket_type::s_iterator_to (*node_traits::get_next(group_functions_t::get_last_in_group (detail::dcast_bucket_ptr<node>(it.pointed_node()), optimize_multikey_t()))); this->priv_erase_range_impl(bucket_num, prev, last, disposer, cnt); } else{ //If found erase all equal values bucket_type &b = this->priv_bucket_pointer()[bucket_num]; for(siterator end_sit = b.end(); it != end_sit; ++cnt, ++it){ slist_node_ptr n(it.pointed_node()); const value_type &v = this->priv_value_from_slist_node(n); if(compare_hash){ std::size_t vh = this->priv_stored_or_compute_hash(v, store_hash_t()); if(h != vh || !equal_func(key, v)){ break; } } else if(!equal_func(key, v)){ break; } this->priv_size_traits().decrement(); } b.erase_after_and_dispose(prev, it, make_node_disposer(disposer)); } this->priv_erasure_update_cache(); return cnt; } //! <b>Effects</b>: Erases all of the elements. //! //! <b>Complexity</b>: Linear to the number of elements on the container. //! if it's a safe-mode or auto-unlink value_type. Constant time otherwise. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. void clear() { this->data_type::internal.priv_clear_buckets_and_cache(); this->priv_size_traits().set_size(size_type(0)); } //! <b>Requires</b>: Disposer::operator()(pointer) shouldn't throw. //! //! <b>Effects</b>: Erases all of the elements. //! //! <b>Complexity</b>: Linear to the number of elements on the container. //! Disposer::operator()(pointer) is called for the removed elements. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: Invalidates the iterators (but not the references) //! to the erased elements. No destructors are called. template<class Disposer> void clear_and_dispose(Disposer disposer) { if(!constant_time_size || !this->empty()){ size_type num_buckets = this->bucket_count(); bucket_ptr b = this->priv_bucket_pointer(); for(; num_buckets--; ++b){ b->clear_and_dispose(make_node_disposer(disposer)); } this->priv_size_traits().set_size(size_type(0)); } this->priv_initialize_cache(); } //! <b>Effects</b>: Returns the number of contained elements with the given value //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. size_type count(const_reference value) const { return this->count(value, this->priv_hasher(), this->priv_equal()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Returns the number of contained elements with the given key //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or equal throw. template<class KeyType, class KeyHasher, class KeyValueEqual> size_type count(const KeyType &key, const KeyHasher &hash_func, const KeyValueEqual &equal_func) const { size_type bucket_n1, bucket_n2, cnt; this->priv_equal_range(key, hash_func, equal_func, bucket_n1, bucket_n2, cnt); return cnt; } //! <b>Effects</b>: Finds an iterator to the first element is equal to //! "value" or end() if that element does not exist. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. iterator find(const_reference value) { return this->find(value, this->priv_hasher(), this->priv_equal()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Finds an iterator to the first element whose key is //! "key" according to the given hash and equality functor or end() if //! that element does not exist. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or equal_func throw. //! //! <b>Note</b>: This function is used when constructing a value_type //! is expensive and the value_type can be compared with a cheaper //! key type. Usually this key is part of the value_type. template<class KeyType, class KeyHasher, class KeyValueEqual> iterator find(const KeyType &key, KeyHasher hash_func, KeyValueEqual equal_func) { size_type bucket_n; std::size_t hash; siterator prev; siterator local_it = this->priv_find(key, hash_func, equal_func, bucket_n, hash, prev); return iterator(local_it, &this->get_bucket_value_traits()); } //! <b>Effects</b>: Finds a const_iterator to the first element whose key is //! "key" or end() if that element does not exist. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. const_iterator find(const_reference value) const { return this->find(value, this->priv_hasher(), this->priv_equal()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Finds an iterator to the first element whose key is //! "key" according to the given hasher and equality functor or end() if //! that element does not exist. //! //! <b>Complexity</b>: Average case O(1), worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or equal_func throw. //! //! <b>Note</b>: This function is used when constructing a value_type //! is expensive and the value_type can be compared with a cheaper //! key type. Usually this key is part of the value_type. template<class KeyType, class KeyHasher, class KeyValueEqual> const_iterator find (const KeyType &key, KeyHasher hash_func, KeyValueEqual equal_func) const { size_type bucket_n; std::size_t hash_value; siterator prev; siterator sit = this->priv_find(key, hash_func, equal_func, bucket_n, hash_value, prev); return const_iterator(sit, &this->get_bucket_value_traits()); } //! <b>Effects</b>: Returns a range containing all elements with values equivalent //! to value. Returns std::make_pair(this->end(), this->end()) if no such //! elements exist. //! //! <b>Complexity</b>: Average case O(this->count(value)). Worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. std::pair<iterator,iterator> equal_range(const_reference value) { return this->equal_range(value, this->priv_hasher(), this->priv_equal()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Returns a range containing all elements with equivalent //! keys. Returns std::make_pair(this->end(), this->end()) if no such //! elements exist. //! //! <b>Complexity</b>: Average case O(this->count(key, hash_func, equal_func)). //! Worst case O(this->size()). //! //! <b>Throws</b>: If hash_func or the equal_func throw. //! //! <b>Note</b>: This function is used when constructing a value_type //! is expensive and the value_type can be compared with a cheaper //! key type. Usually this key is part of the value_type. template<class KeyType, class KeyHasher, class KeyValueEqual> std::pair<iterator,iterator> equal_range (const KeyType &key, KeyHasher hash_func, KeyValueEqual equal_func) { size_type bucket_n1, bucket_n2, cnt; std::pair<siterator, siterator> ret = this->priv_equal_range (key, hash_func, equal_func, bucket_n1, bucket_n2, cnt); return std::pair<iterator, iterator> (iterator(ret.first, &this->get_bucket_value_traits()), iterator(ret.second, &this->get_bucket_value_traits())); } //! <b>Effects</b>: Returns a range containing all elements with values equivalent //! to value. Returns std::make_pair(this->end(), this->end()) if no such //! elements exist. //! //! <b>Complexity</b>: Average case O(this->count(value)). Worst case O(this->size()). //! //! <b>Throws</b>: If the internal hasher or the equality functor throws. std::pair<const_iterator, const_iterator> equal_range(const_reference value) const { return this->equal_range(value, this->priv_hasher(), this->priv_equal()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! "equal_func" must be a equality function that induces //! the same equality as key_equal. The difference is that //! "equal_func" compares an arbitrary key with the contained values. //! //! <b>Effects</b>: Returns a range containing all elements with equivalent //! keys. Returns std::make_pair(this->end(), this->end()) if no such //! elements exist. //! //! <b>Complexity</b>: Average case O(this->count(key, hash_func, equal_func)). //! Worst case O(this->size()). //! //! <b>Throws</b>: If the hasher or equal_func throw. //! //! <b>Note</b>: This function is used when constructing a value_type //! is expensive and the value_type can be compared with a cheaper //! key type. Usually this key is part of the value_type. template<class KeyType, class KeyHasher, class KeyValueEqual> std::pair<const_iterator,const_iterator> equal_range (const KeyType &key, KeyHasher hash_func, KeyValueEqual equal_func) const { size_type bucket_n1, bucket_n2, cnt; std::pair<siterator, siterator> ret = this->priv_equal_range(key, hash_func, equal_func, bucket_n1, bucket_n2, cnt); return std::pair<const_iterator, const_iterator> ( const_iterator(ret.first, &this->get_bucket_value_traits()) , const_iterator(ret.second, &this->get_bucket_value_traits())); } //! <b>Requires</b>: value must be an lvalue and shall be in a unordered_set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid iterator belonging to the unordered_set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If the internal hash function throws. iterator iterator_to(reference value) { return iterator(bucket_type::s_iterator_to (this->priv_value_to_node(value)), &this->get_bucket_value_traits()); } //! <b>Requires</b>: value must be an lvalue and shall be in a unordered_set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_iterator belonging to the //! unordered_set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If the internal hash function throws. const_iterator iterator_to(const_reference value) const { node_reference r = *pointer_traits<node_ptr>::const_cast_from (pointer_traits<const_node_ptr>::pointer_to(this->priv_value_to_node(value))); siterator sit = bucket_type::s_iterator_to(r); return const_iterator(sit, &this->get_bucket_value_traits()); } //! <b>Requires</b>: value must be an lvalue and shall be in a unordered_set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid local_iterator belonging to the unordered_set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This static function is available only if the <i>value traits</i> //! is stateless. static local_iterator s_local_iterator_to(reference value) { BOOST_STATIC_ASSERT((!stateful_value_traits)); siterator sit = bucket_type::s_iterator_to(*value_traits::to_node_ptr(value)); return local_iterator(sit, const_value_traits_ptr()); } //! <b>Requires</b>: value must be an lvalue and shall be in a unordered_set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_local_iterator belonging to //! the unordered_set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: This static function is available only if the <i>value traits</i> //! is stateless. static const_local_iterator s_local_iterator_to(const_reference value) { BOOST_STATIC_ASSERT((!stateful_value_traits)); node_reference r = *pointer_traits<node_ptr>::const_cast_from (value_traits::to_node_ptr(value)); siterator sit = bucket_type::s_iterator_to(r); return const_local_iterator(sit, const_value_traits_ptr()); } //! <b>Requires</b>: value must be an lvalue and shall be in a unordered_set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid local_iterator belonging to the unordered_set //! that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. local_iterator local_iterator_to(reference value) { siterator sit = bucket_type::s_iterator_to(this->priv_value_to_node(value)); return local_iterator(sit, this->priv_value_traits_ptr()); } //! <b>Requires</b>: value must be an lvalue and shall be in a unordered_set of //! appropriate type. Otherwise the behavior is undefined. //! //! <b>Effects</b>: Returns: a valid const_local_iterator belonging to //! the unordered_set that points to the value //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. const_local_iterator local_iterator_to(const_reference value) const { node_reference r = *pointer_traits<node_ptr>::const_cast_from (pointer_traits<const_node_ptr>::pointer_to(this->priv_value_to_node(value))); siterator sit = bucket_type::s_iterator_to(r); return const_local_iterator(sit, this->priv_value_traits_ptr()); } //! <b>Effects</b>: Returns the number of buckets passed in the constructor //! or the last rehash function. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. size_type bucket_count() const { return this->priv_bucket_count(); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns the number of elements in the nth bucket. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. size_type bucket_size(size_type n) const { return this->priv_bucket_pointer()[n].size(); } //! <b>Effects</b>: Returns the index of the bucket in which elements //! with keys equivalent to k would be found, if any such element existed. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If the hash functor throws. //! //! <b>Note</b>: the return value is in the range [0, this->bucket_count()). size_type bucket(const key_type& k) const { return this->bucket(k, this->priv_hasher()); } //! <b>Requires</b>: "hash_func" must be a hash function that induces //! the same hash values as the stored hasher. The difference is that //! "hash_func" hashes the given key instead of the value_type. //! //! <b>Effects</b>: Returns the index of the bucket in which elements //! with keys equivalent to k would be found, if any such element existed. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: If hash_func throws. //! //! <b>Note</b>: the return value is in the range [0, this->bucket_count()). template<class KeyType, class KeyHasher> size_type bucket(const KeyType& k, const KeyHasher &hash_func) const { return this->priv_hash_to_bucket(hash_func(k)); } //! <b>Effects</b>: Returns the bucket array pointer passed in the constructor //! or the last rehash function. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. bucket_ptr bucket_pointer() const { return this->priv_bucket_pointer(); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns a local_iterator pointing to the beginning //! of the sequence stored in the bucket n. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: [this->begin(n), this->end(n)) is a valid range //! containing all of the elements in the nth bucket. local_iterator begin(size_type n) { return local_iterator(this->priv_bucket_pointer()[n].begin(), this->priv_value_traits_ptr()); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns a const_local_iterator pointing to the beginning //! of the sequence stored in the bucket n. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: [this->begin(n), this->end(n)) is a valid range //! containing all of the elements in the nth bucket. const_local_iterator begin(size_type n) const { return this->cbegin(n); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns a const_local_iterator pointing to the beginning //! of the sequence stored in the bucket n. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: [this->begin(n), this->end(n)) is a valid range //! containing all of the elements in the nth bucket. const_local_iterator cbegin(size_type n) const { bucket_reference br = pointer_traits<bucket_ptr>::const_cast_from(this->priv_bucket_pointer())[n]; return const_local_iterator(br.begin(), this->priv_value_traits_ptr()); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns a local_iterator pointing to the end //! of the sequence stored in the bucket n. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: [this->begin(n), this->end(n)) is a valid range //! containing all of the elements in the nth bucket. local_iterator end(size_type n) { return local_iterator(this->priv_bucket_pointer()[n].end(), this->priv_value_traits_ptr()); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns a const_local_iterator pointing to the end //! of the sequence stored in the bucket n. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: [this->begin(n), this->end(n)) is a valid range //! containing all of the elements in the nth bucket. const_local_iterator end(size_type n) const { return this->cend(n); } //! <b>Requires</b>: n is in the range [0, this->bucket_count()). //! //! <b>Effects</b>: Returns a const_local_iterator pointing to the end //! of the sequence stored in the bucket n. //! //! <b>Complexity</b>: Constant. //! //! <b>Throws</b>: Nothing. //! //! <b>Note</b>: [this->begin(n), this->end(n)) is a valid range //! containing all of the elements in the nth bucket. const_local_iterator cend(size_type n) const { bucket_reference br = pointer_traits<bucket_ptr>::const_cast_from(this->priv_bucket_pointer())[n]; return const_local_iterator ( br.end(), this->priv_value_traits_ptr()); } //! <b>Requires</b>: new_bucket_traits can hold a pointer to a new bucket array //! or the same as the old bucket array with a different length. new_size is the length of the //! the array pointed by new_buckets. If new_bucket_traits.bucket_begin() == this->bucket_pointer() //! new_bucket_traits.bucket_count() can be bigger or smaller than this->bucket_count(). //! 'new_bucket_traits' copy constructor should not throw. //! //! <b>Effects</b>: Updates the internal reference with the new bucket, erases //! the values from the old bucket and inserts then in the new one. //! Bucket traits hold by *this is assigned from new_bucket_traits. //! If the container is configured as incremental<>, the split bucket is set //! to the new bucket_count(). //! //! If store_hash option is true, this method does not use the hash function. //! //! <b>Complexity</b>: Average case linear in this->size(), worst case quadratic. //! //! <b>Throws</b>: If the hasher functor throws. Basic guarantee. void rehash(const bucket_traits &new_bucket_traits) { const bucket_ptr new_buckets = new_bucket_traits.bucket_begin(); size_type new_bucket_count = new_bucket_traits.bucket_count(); const bucket_ptr old_buckets = this->priv_bucket_pointer(); size_type old_bucket_count = this->priv_bucket_count(); //Check power of two bucket array if the option is activated BOOST_INTRUSIVE_INVARIANT_ASSERT (!power_2_buckets || (0 == (new_bucket_count & (new_bucket_count-1u)))); size_type n = this->priv_get_cache_bucket_num(); const bool same_buffer = old_buckets == new_buckets; //If the new bucket length is a common factor //of the old one we can avoid hash calculations. const bool fast_shrink = (!incremental) && (old_bucket_count > new_bucket_count) && (power_2_buckets ||(old_bucket_count % new_bucket_count) == 0); //If we are shrinking the same bucket array and it's //is a fast shrink, just rehash the last nodes size_type new_first_bucket_num = new_bucket_count; if(same_buffer && fast_shrink && (n < new_bucket_count)){ n = new_bucket_count; new_first_bucket_num = this->priv_get_cache_bucket_num(); } //Anti-exception stuff: they destroy the elements if something goes wrong. //If the source and destination buckets are the same, the second rollback function //is harmless, because all elements have been already unlinked and destroyed typedef detail::init_disposer<node_algorithms> NodeDisposer; NodeDisposer node_disp; bucket_type & newbuck = new_buckets[0]; bucket_type & oldbuck = old_buckets[0]; detail::exception_array_disposer<bucket_type, NodeDisposer, size_type> rollback1(newbuck, node_disp, new_bucket_count); detail::exception_array_disposer<bucket_type, NodeDisposer, size_type> rollback2(oldbuck, node_disp, old_bucket_count); //Put size in a safe value for rollback exception size_type size_backup = this->priv_size_traits().get_size(); this->priv_size_traits().set_size(0); //Put cache to safe position this->priv_initialize_cache(); this->priv_insertion_update_cache(size_type(0u)); //Iterate through nodes for(; n < old_bucket_count; ++n){ bucket_type &old_bucket = old_buckets[n]; if(!fast_shrink){ siterator before_i(old_bucket.before_begin()); siterator end_sit(old_bucket.end()); siterator i(old_bucket.begin()); for(;i != end_sit; ++i){ const value_type &v = this->priv_value_from_slist_node(i.pointed_node()); const std::size_t hash_value = this->priv_stored_or_compute_hash(v, store_hash_t()); const size_type new_n = detail::hash_to_bucket_split<power_2_buckets, incremental>(hash_value, new_bucket_count, new_bucket_count); if(cache_begin && new_n < new_first_bucket_num) new_first_bucket_num = new_n; siterator last = bucket_type::s_iterator_to (*group_functions_t::get_last_in_group (detail::dcast_bucket_ptr<node>(i.pointed_node()), optimize_multikey_t())); if(same_buffer && new_n == n){ before_i = last; } else{ bucket_type &new_b = new_buckets[new_n]; new_b.splice_after(new_b.before_begin(), old_bucket, before_i, last); } i = before_i; } } else{ const size_type new_n = detail::hash_to_bucket_split<power_2_buckets, incremental>(n, new_bucket_count, new_bucket_count); if(cache_begin && new_n < new_first_bucket_num) new_first_bucket_num = new_n; bucket_type &new_b = new_buckets[new_n]; if(!old_bucket.empty()){ new_b.splice_after( new_b.before_begin() , old_bucket , old_bucket.before_begin() , hashtable_impl::priv_get_last(old_bucket)); } } } this->priv_size_traits().set_size(size_backup); this->priv_split_traits().set_size(new_bucket_count); this->priv_bucket_traits() = new_bucket_traits; this->priv_initialize_cache(); this->priv_insertion_update_cache(new_first_bucket_num); rollback1.release(); rollback2.release(); } //! <b>Requires</b>: //! //! <b>Effects</b>: //! //! <b>Complexity</b>: //! //! <b>Throws</b>: //! //! <b>Note</b>: this method is only available if incremental<true> option is activated. bool incremental_rehash(bool grow = true) { //This function is only available for containers with incremental hashing BOOST_STATIC_ASSERT(( incremental && power_2_buckets )); const size_type split_idx = this->priv_split_traits().get_size(); const size_type bucket_cnt = this->priv_bucket_count(); const bucket_ptr buck_ptr = this->priv_bucket_pointer(); if(grow){ //Test if the split variable can be changed if(split_idx >= bucket_cnt) return false; const size_type bucket_to_rehash = split_idx - bucket_cnt/2; bucket_type &old_bucket = buck_ptr[bucket_to_rehash]; siterator before_i(old_bucket.before_begin()); const siterator end_sit(old_bucket.end()); siterator i(old_bucket.begin()); this->priv_split_traits().increment(); //Anti-exception stuff: if an exception is thrown while //moving elements from old_bucket to the target bucket, all moved //elements are moved back to the original one. detail::incremental_rehash_rollback<bucket_type, split_traits> rollback ( buck_ptr[split_idx], old_bucket, this->priv_split_traits()); for(;i != end_sit; ++i){ const value_type &v = this->priv_value_from_slist_node(i.pointed_node()); const std::size_t hash_value = this->priv_stored_or_compute_hash(v, store_hash_t()); const size_type new_n = this->priv_hash_to_bucket(hash_value); siterator last = bucket_type::s_iterator_to (*group_functions_t::get_last_in_group (detail::dcast_bucket_ptr<node>(i.pointed_node()), optimize_multikey_t())); if(new_n == bucket_to_rehash){ before_i = last; } else{ bucket_type &new_b = buck_ptr[new_n]; new_b.splice_after(new_b.before_begin(), old_bucket, before_i, last); } i = before_i; } rollback.release(); this->priv_erasure_update_cache(); return true; } else{ //Test if the split variable can be changed if(split_idx <= bucket_cnt/2) return false; const size_type target_bucket_num = split_idx - 1 - bucket_cnt/2; bucket_type &target_bucket = buck_ptr[target_bucket_num]; bucket_type &source_bucket = buck_ptr[split_idx-1]; target_bucket.splice_after(target_bucket.cbefore_begin(), source_bucket); this->priv_split_traits().decrement(); this->priv_insertion_update_cache(target_bucket_num); return true; } } //! <b>Effects</b>: If new_bucket_traits.bucket_count() is not //! this->bucket_count()/2 or this->bucket_count()*2, or //! this->split_bucket() != new_bucket_traits.bucket_count() returns false //! and does nothing. //! //! Otherwise, copy assigns new_bucket_traits to the internal bucket_traits //! and transfers all the objects from old buckets to the new ones. //! //! <b>Complexity</b>: Linear to size(). //! //! <b>Throws</b>: Nothing //! //! <b>Note</b>: this method is only available if incremental<true> option is activated. bool incremental_rehash(const bucket_traits &new_bucket_traits) { //This function is only available for containers with incremental hashing BOOST_STATIC_ASSERT(( incremental && power_2_buckets )); size_type new_bucket_traits_size = new_bucket_traits.bucket_count(); size_type cur_bucket_traits = this->priv_bucket_count(); if(new_bucket_traits_size/2 != cur_bucket_traits && new_bucket_traits_size != cur_bucket_traits/2){ return false; } const size_type split_idx = this->split_count(); if(new_bucket_traits_size/2 == cur_bucket_traits){ //Test if the split variable can be changed if(!(split_idx >= cur_bucket_traits)) return false; } else{ //Test if the split variable can be changed if(!(split_idx <= cur_bucket_traits/2)) return false; } const size_type ini_n = this->priv_get_cache_bucket_num(); const bucket_ptr old_buckets = this->priv_bucket_pointer(); this->priv_bucket_traits() = new_bucket_traits; if(new_bucket_traits.bucket_begin() != old_buckets){ for(size_type n = ini_n; n < split_idx; ++n){ bucket_type &new_bucket = new_bucket_traits.bucket_begin()[n]; bucket_type &old_bucket = old_buckets[n]; new_bucket.splice_after(new_bucket.cbefore_begin(), old_bucket); } //Put cache to safe position this->priv_initialize_cache(); this->priv_insertion_update_cache(ini_n); } return true; } //! <b>Requires</b>: //! //! <b>Effects</b>: //! //! <b>Complexity</b>: //! //! <b>Throws</b>: size_type split_count() const { //This function is only available if incremental hashing is activated BOOST_STATIC_ASSERT(( incremental && power_2_buckets )); return this->priv_split_traits().get_size(); } //! <b>Effects</b>: Returns the nearest new bucket count optimized for //! the container that is bigger or equal than n. This suggestion can be //! used to create bucket arrays with a size that will usually improve //! container's performance. If such value does not exist, the //! higher possible value is returned. //! //! <b>Complexity</b>: Amortized constant time. //! //! <b>Throws</b>: Nothing. static size_type suggested_upper_bucket_count(size_type n) { const std::size_t *primes = &prime_list_holder<0>::prime_list[0]; const std::size_t *primes_end = primes + prime_list_holder<0>::prime_list_size; std::size_t const* bound = std::lower_bound(primes, primes_end, n); bound -= (bound == primes_end); return size_type(*bound); } //! <b>Effects</b>: Returns the nearest new bucket count optimized for //! the container that is smaller or equal than n. This suggestion can be //! used to create bucket arrays with a size that will usually improve //! container's performance. If such value does not exist, the //! lowest possible value is returned. //! //! <b>Complexity</b>: Amortized constant time. //! //! <b>Throws</b>: Nothing. static size_type suggested_lower_bucket_count(size_type n) { const std::size_t *primes = &prime_list_holder<0>::prime_list[0]; const std::size_t *primes_end = primes + prime_list_holder<0>::prime_list_size; size_type const* bound = std::upper_bound(primes, primes_end, n); bound -= (bound != primes); return size_type(*bound); } /// @cond void check() const {} private: size_traits &priv_size_traits() { return static_cast<size_traits&>(static_cast<data_type&>(*this)); } const size_traits &priv_size_traits() const { return static_cast<const size_traits&>(static_cast<const data_type&>(*this)); } bucket_ptr priv_bucket_pointer() const { return this->data_type::internal.internal.internal.internal.priv_bucket_pointer(); } SizeType priv_bucket_count() const { return this->data_type::internal.internal.internal.internal.priv_bucket_count(); } const bucket_plus_vtraits<ValueTraits, BucketTraits> &get_bucket_value_traits() const { return this->data_type::internal.internal.internal.internal.get_bucket_value_traits(); } bucket_plus_vtraits<ValueTraits, BucketTraits> &get_bucket_value_traits() { return this->data_type::internal.internal.internal.internal.get_bucket_value_traits(); } bucket_traits &priv_bucket_traits() { return this->data_type::internal.internal.internal.internal.priv_bucket_traits(); } const bucket_traits &priv_bucket_traits() const { return this->data_type::internal.internal.internal.internal.priv_bucket_traits(); } value_traits &priv_value_traits() { return this->data_type::internal.internal.internal.internal.priv_value_traits(); } const value_traits &priv_value_traits() const { return this->data_type::internal.internal.internal.internal.priv_value_traits(); } const_value_traits_ptr priv_value_traits_ptr() const { return this->data_type::internal.internal.internal.internal.priv_value_traits_ptr(); } siterator priv_invalid_local_it() const { return this->data_type::internal.internal.internal.internal.priv_invalid_local_it(); } split_traits &priv_split_traits() { return this->data_type::internal.priv_split_traits(); } const split_traits &priv_split_traits() const { return this->data_type::internal.priv_split_traits(); } bucket_ptr priv_get_cache() { return this->data_type::internal.internal.priv_get_cache(); } void priv_initialize_cache() { return this->data_type::internal.internal.priv_initialize_cache(); } siterator priv_begin() const { return this->data_type::internal.internal.priv_begin(); } const value_equal &priv_equal() const { return this->data_type::internal.internal.priv_equal(); } value_equal &priv_equal() { return this->data_type::internal.internal.priv_equal(); } const hasher &priv_hasher() const { return this->data_type::internal.internal.internal.priv_hasher(); } hasher &priv_hasher() { return this->data_type::internal.internal.internal.priv_hasher(); } void priv_swap_cache(hashtable_impl &h) { this->data_type::internal.internal.priv_swap_cache(h.data_type::internal.internal); } node &priv_value_to_node(value_type &v) { return this->data_type::internal.internal.internal.internal.priv_value_to_node(v); } const node &priv_value_to_node(const value_type &v) const { return this->data_type::internal.internal.internal.internal.priv_value_to_node(v); } SizeType priv_get_cache_bucket_num() { return this->data_type::internal.internal.priv_get_cache_bucket_num(); } void priv_insertion_update_cache(SizeType n) { return this->data_type::internal.internal.priv_insertion_update_cache(n); } template<bool Boolean> std::size_t priv_stored_or_compute_hash(const value_type &v, detail::bool_<Boolean> b) const { return this->data_type::internal.internal.internal.priv_stored_or_compute_hash(v, b); } value_type &priv_value_from_slist_node(slist_node_ptr n) { return this->data_type::internal.internal.internal.internal.priv_value_from_slist_node(n); } const value_type &priv_value_from_slist_node(slist_node_ptr n) const { return this->data_type::internal.internal.internal.internal.priv_value_from_slist_node(n); } void priv_erasure_update_cache_range(SizeType first_bucket_num, SizeType last_bucket_num) { return this->data_type::internal.internal.priv_erasure_update_cache_range(first_bucket_num, last_bucket_num); } void priv_erasure_update_cache() { return this->data_type::internal.internal.priv_erasure_update_cache(); } static std::size_t priv_stored_hash(slist_node_ptr n, detail::true_ true_value) { return bucket_plus_vtraits<ValueTraits, BucketTraits>::priv_stored_hash(n, true_value); } static std::size_t priv_stored_hash(slist_node_ptr n, detail::false_ false_value) { return bucket_plus_vtraits<ValueTraits, BucketTraits>::priv_stored_hash(n, false_value); } std::size_t priv_hash_to_bucket(std::size_t hash_value) const { return detail::hash_to_bucket_split<power_2_buckets, incremental> (hash_value, this->priv_bucket_traits().bucket_count(), this->priv_split_traits().get_size()); } template<class Disposer> void priv_erase_range_impl (size_type bucket_num, siterator before_first_it, siterator end_sit, Disposer disposer, size_type &num_erased) { const bucket_ptr buckets = this->priv_bucket_pointer(); bucket_type &b = buckets[bucket_num]; if(before_first_it == b.before_begin() && end_sit == b.end()){ this->priv_erase_range_impl(bucket_num, 1, disposer, num_erased); } else{ num_erased = 0; siterator to_erase(before_first_it); ++to_erase; slist_node_ptr end_ptr = end_sit.pointed_node(); while(to_erase != end_sit){ group_functions_t::erase_from_group(end_ptr, detail::dcast_bucket_ptr<node>(to_erase.pointed_node()), optimize_multikey_t()); to_erase = b.erase_after_and_dispose(before_first_it, make_node_disposer(disposer)); ++num_erased; } this->priv_size_traits().set_size(this->priv_size_traits().get_size()-num_erased); } } template<class Disposer> void priv_erase_range_impl (size_type first_bucket_num, size_type num_buckets, Disposer disposer, size_type &num_erased) { //Now fully clear the intermediate buckets const bucket_ptr buckets = this->priv_bucket_pointer(); num_erased = 0; for(size_type i = first_bucket_num; i < (num_buckets + first_bucket_num); ++i){ bucket_type &b = buckets[i]; siterator b_begin(b.before_begin()); siterator nxt(b_begin); ++nxt; siterator end_sit(b.end()); while(nxt != end_sit){ group_functions_t::init_group(detail::dcast_bucket_ptr<node>(nxt.pointed_node()), optimize_multikey_t()); nxt = b.erase_after_and_dispose (b_begin, make_node_disposer(disposer)); this->priv_size_traits().decrement(); ++num_erased; } } } template<class Disposer> void priv_erase_range( siterator before_first_it, size_type first_bucket , siterator last_it, size_type last_bucket , Disposer disposer) { size_type num_erased; if (first_bucket == last_bucket){ this->priv_erase_range_impl(first_bucket, before_first_it, last_it, disposer, num_erased); } else { bucket_type *b = (&this->priv_bucket_pointer()[0]); this->priv_erase_range_impl(first_bucket, before_first_it, b[first_bucket].end(), disposer, num_erased); if(size_type n = (last_bucket - first_bucket - 1)) this->priv_erase_range_impl(first_bucket + 1, n, disposer, num_erased); this->priv_erase_range_impl(last_bucket, b[last_bucket].before_begin(), last_it, disposer, num_erased); } } std::size_t priv_get_bucket_num(siterator it) { return this->priv_get_bucket_num_hash_dispatch(it, store_hash_t()); } std::size_t priv_get_bucket_num_hash_dispatch(siterator it, detail::true_) //store_hash { return this->priv_hash_to_bucket (this->priv_stored_hash(it.pointed_node(), store_hash_t())); } std::size_t priv_get_bucket_num_hash_dispatch(siterator it, detail::false_) //NO store_hash { return this->data_type::internal.internal.internal.internal.priv_get_bucket_num_no_hash_store(it, optimize_multikey_t()); } static siterator priv_get_previous(bucket_type &b, siterator i) { return bucket_plus_vtraits_t::priv_get_previous(b, i, optimize_multikey_t()); } static siterator priv_get_last(bucket_type &b) { return bucket_plus_vtraits_t::priv_get_last(b, optimize_multikey_t()); } template<class Disposer> void priv_erase(const_iterator i, Disposer disposer, detail::true_) { slist_node_ptr elem(i.slist_it().pointed_node()); slist_node_ptr f_bucket_end, l_bucket_end; if(store_hash){ f_bucket_end = l_bucket_end = (this->priv_bucket_pointer() [this->priv_hash_to_bucket (this->priv_stored_hash(elem, store_hash_t())) ]).before_begin().pointed_node(); } else{ f_bucket_end = this->priv_bucket_pointer()->cend().pointed_node(); l_bucket_end = f_bucket_end + this->priv_bucket_count() - 1; } node_ptr nxt_in_group; siterator prev = bucket_type::s_iterator_to (*group_functions_t::get_previous_and_next_in_group ( elem, nxt_in_group, f_bucket_end, l_bucket_end) ); bucket_type::s_erase_after_and_dispose(prev, make_node_disposer(disposer)); if(nxt_in_group) group_algorithms::unlink_after(nxt_in_group); if(safemode_or_autounlink) group_algorithms::init(detail::dcast_bucket_ptr<node>(elem)); } template <class Disposer> void priv_erase(const_iterator i, Disposer disposer, detail::false_) { siterator to_erase(i.slist_it()); bucket_type &b = this->priv_bucket_pointer()[this->priv_get_bucket_num(to_erase)]; siterator prev(this->priv_get_previous(b, to_erase)); b.erase_after_and_dispose(prev, make_node_disposer(disposer)); } template<class KeyType, class KeyHasher, class KeyValueEqual> siterator priv_find ( const KeyType &key, KeyHasher hash_func , KeyValueEqual equal_func, size_type &bucket_number, std::size_t &h, siterator &previt) const { h = hash_func(key); return this->priv_find_with_hash(key, equal_func, bucket_number, h, previt); } template<class KeyType, class KeyValueEqual> siterator priv_find_with_hash ( const KeyType &key, KeyValueEqual equal_func, size_type &bucket_number, const std::size_t h, siterator &previt) const { bucket_number = this->priv_hash_to_bucket(h); bucket_type &b = this->priv_bucket_pointer()[bucket_number]; previt = b.before_begin(); if(constant_time_size && this->empty()){ return this->priv_invalid_local_it(); } siterator it = previt; ++it; while(it != b.end()){ const value_type &v = this->priv_value_from_slist_node(it.pointed_node()); if(compare_hash){ std::size_t vh = this->priv_stored_or_compute_hash(v, store_hash_t()); if(h == vh && equal_func(key, v)){ return it; } } else if(equal_func(key, v)){ return it; } if(optimize_multikey){ previt = bucket_type::s_iterator_to (*group_functions_t::get_last_in_group (detail::dcast_bucket_ptr<node>(it.pointed_node()), optimize_multikey_t())); it = previt; } else{ previt = it; } ++it; } previt = b.before_begin(); return this->priv_invalid_local_it(); } iterator priv_insert_equal_with_hash(reference value, std::size_t hash_value) { size_type bucket_num; siterator prev; siterator it = this->priv_find_with_hash (value, this->priv_equal(), bucket_num, hash_value, prev); return this->priv_insert_equal_find(value, bucket_num, hash_value, it); } iterator priv_insert_equal_find(reference value, size_type bucket_num, std::size_t hash_value, siterator it) { bucket_type &b = this->priv_bucket_pointer()[bucket_num]; bool found_equal = it != this->priv_invalid_local_it(); if(!found_equal){ it = b.before_begin(); } //Now store hash if needed node_ptr n = pointer_traits<node_ptr>::pointer_to(this->priv_value_to_node(value)); node_functions_t::store_hash(n, hash_value, store_hash_t()); //Checks for some modes if(safemode_or_autounlink) BOOST_INTRUSIVE_SAFE_HOOK_DEFAULT_ASSERT(node_algorithms::unique(n)); //Shortcut for optimize_multikey cases if(optimize_multikey){ node_ptr first_in_group = found_equal ? detail::dcast_bucket_ptr<node>(it.pointed_node()) : node_ptr(); group_functions_t::insert_in_group(first_in_group, n, optimize_multikey_t()); } //Update cache and increment size if needed this->priv_insertion_update_cache(bucket_num); this->priv_size_traits().increment(); //Insert the element in the bucket after it return iterator(b.insert_after(it, *n), &this->get_bucket_value_traits()); } template<class KeyType, class KeyHasher, class KeyValueEqual> std::pair<siterator, siterator> priv_equal_range ( const KeyType &key , KeyHasher hash_func , KeyValueEqual equal_func , size_type &bucket_number_first , size_type &bucket_number_second , size_type &cnt) const { std::size_t h; cnt = 0; siterator prev; //Let's see if the element is present std::pair<siterator, siterator> to_return ( this->priv_find(key, hash_func, equal_func, bucket_number_first, h, prev) , this->priv_invalid_local_it()); if(to_return.first == to_return.second){ bucket_number_second = bucket_number_first; return to_return; } { //If it's present, find the first that it's not equal in //the same bucket bucket_type &b = this->priv_bucket_pointer()[bucket_number_first]; siterator it = to_return.first; if(optimize_multikey){ to_return.second = bucket_type::s_iterator_to (*node_traits::get_next(group_functions_t::get_last_in_group (detail::dcast_bucket_ptr<node>(it.pointed_node()), optimize_multikey_t()))); cnt = 0; for(; it != to_return.second; ++it){ ++cnt; } if(to_return.second != b.end()){ bucket_number_second = bucket_number_first; return to_return; } } else{ ++cnt; ++it; while(it != b.end()){ const value_type &v = this->priv_value_from_slist_node(it.pointed_node()); if(compare_hash){ std::size_t hv = this->priv_stored_or_compute_hash(v, store_hash_t()); if(hv != h || !equal_func(key, v)){ to_return.second = it; bucket_number_second = bucket_number_first; return to_return; } } else if(!equal_func(key, v)){ to_return.second = it; bucket_number_second = bucket_number_first; return to_return; } ++it; ++cnt; } } } //If we reached the end, find the first, non-empty bucket for(bucket_number_second = bucket_number_first+1 ; bucket_number_second != this->priv_bucket_count() ; ++bucket_number_second){ bucket_type &b = this->priv_bucket_pointer()[bucket_number_second]; if(!b.empty()){ to_return.second = b.begin(); return to_return; } } //Otherwise, return the end node to_return.second = this->priv_invalid_local_it(); return to_return; } /// @endcond }; /// @cond #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template < class T , bool UniqueKeys , class PackedOptions > #else template <class T, bool UniqueKeys, class ...Options> #endif struct make_bucket_traits { //Real value traits must be calculated from options typedef typename detail::get_value_traits <T, typename PackedOptions::proto_value_traits>::type value_traits; typedef typename PackedOptions::bucket_traits specified_bucket_traits; //Real bucket traits must be calculated from options and calculated value_traits typedef typename detail::get_slist_impl <typename detail::reduced_slist_node_traits <typename value_traits::node_traits>::type >::type slist_impl; typedef typename detail::if_c< detail::is_same < specified_bucket_traits , default_bucket_traits >::value , detail::bucket_traits_impl<slist_impl> , specified_bucket_traits >::type type; }; /// @endcond //! Helper metafunction to define a \c hashtable that yields to the same type when the //! same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1 = void, class O2 = void , class O3 = void, class O4 = void , class O5 = void, class O6 = void , class O7 = void, class O8 = void , class O9 = void, class O10= void > #endif struct make_hashtable { /// @cond typedef typename pack_options < hashtable_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6, O7, O8, O9, O10 #else Options... #endif >::type packed_options; typedef typename detail::get_value_traits <T, typename packed_options::proto_value_traits>::type value_traits; typedef typename make_bucket_traits <T, false, packed_options>::type bucket_traits; typedef hashtable_impl < value_traits , typename packed_options::hash , typename packed_options::equal , typename packed_options::size_type , bucket_traits , (std::size_t(false)*hash_bool_flags::unique_keys_pos) | (std::size_t(packed_options::constant_time_size)*hash_bool_flags::constant_time_size_pos) | (std::size_t(packed_options::power_2_buckets)*hash_bool_flags::power_2_buckets_pos) | (std::size_t(packed_options::cache_begin)*hash_bool_flags::cache_begin_pos) | (std::size_t(packed_options::compare_hash)*hash_bool_flags::compare_hash_pos) | (std::size_t(packed_options::incremental)*hash_bool_flags::incremental_pos) > implementation_defined; /// @endcond typedef implementation_defined type; }; #if !defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) #if defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class ...Options> #else template<class T, class O1, class O2, class O3, class O4, class O5, class O6, class O7, class O8, class O9, class O10> #endif class hashtable : public make_hashtable<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6, O7, O8, O9, O10 #else Options... #endif >::type { typedef typename make_hashtable<T, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6, O7, O8, O9, O10 #else Options... #endif >::type Base; BOOST_MOVABLE_BUT_NOT_COPYABLE(hashtable) public: typedef typename Base::value_traits value_traits; typedef typename Base::iterator iterator; typedef typename Base::const_iterator const_iterator; typedef typename Base::bucket_ptr bucket_ptr; typedef typename Base::size_type size_type; typedef typename Base::hasher hasher; typedef typename Base::bucket_traits bucket_traits; typedef typename Base::key_equal key_equal; //Assert if passed value traits are compatible with the type BOOST_STATIC_ASSERT((detail::is_same<typename value_traits::value_type, T>::value)); explicit hashtable ( const bucket_traits &b_traits , const hasher & hash_func = hasher() , const key_equal &equal_func = key_equal() , const value_traits &v_traits = value_traits()) : Base(b_traits, hash_func, equal_func, v_traits) {} hashtable(BOOST_RV_REF(hashtable) x) : Base(::boost::move(static_cast<Base&>(x))) {} hashtable& operator=(BOOST_RV_REF(hashtable) x) { return static_cast<hashtable&>(this->Base::operator=(::boost::move(static_cast<Base&>(x)))); } }; #endif } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_HASHTABLE_HPP
[ "giulio.eulisse@cern.ch" ]
giulio.eulisse@cern.ch
01cd70e44b6741df2e1855a0b8b148ad980c068c
2ad8e7ca390ac0851f49c04331e634ee1527c314
/JiuDu/minStack.cpp
dd0bcb345e45b7aac9e7041c303a63ea409d210f
[]
no_license
xuqing-ict/BackupCode
1659e6e367a7c5f2c5509f66a6c7d79f2d70e738
73d29e572c01b2ff8e3e42d8b9ea9be7bd57e1cc
refs/heads/master
2021-03-12T22:41:06.629381
2015-03-09T11:41:42
2015-03-09T11:41:42
24,397,766
0
0
null
null
null
null
UTF-8
C++
false
false
1,023
cpp
#include <bits/stdc++.h> using namespace std; template<class T> class minStack { public: minStack(){} void push(const T &); void pop(); T min_e() const; T top() const; private: stack<T> s; stack<T> min_s; }; template<class T>6 void minStack<T>::push(const T & val) { s.push(val); if(min_s.empty() || val < min_s.top()) { min_s.push(val); } } template<class T> void minStack<T>::pop() { assert(!s.empty() && !min_s.empty()); if(min_s.top() == s.top()) { min_s.pop(); } s.pop(); } template<class T> T minStack<T>::min_e() const { assert(!s.empty() && !min_s.empty()); return min_s.top(); } template<class T> T minStack<T>::top() const { assert(!s.empty()); return s.top(); } int main() { minStack<int> ms; ms.push(1); ms.push(2); cout << ms.top() << endl; cout << ms.min_e() << endl; ms.pop(); cout << ms.min_e() << endl; return 0; }
[ "xuqinguestc@gmail.com" ]
xuqinguestc@gmail.com
d9933c30d7af70667b3008bb6a3c4f2602f09d0b
cdc283b08383b8c4dc5239ad58c756c25d9c3947
/third_party/seasocks/src/main/c/util/PathHandler.cpp
4f9b60fa4ccd3c2b5a3536212319a1764f9158ab
[ "MIT", "BSD-2-Clause" ]
permissive
amartin11/robot-code-public
4058386817fd8bcdd8b6ab9d176b4b2b96fb943a
9671deebff32336fea9865daf0f54d7925c36dd8
refs/heads/master
2020-03-19T02:49:19.175606
2018-05-27T16:02:41
2018-05-27T16:02:41
135,664,264
0
1
MIT
2019-10-03T20:44:48
2018-06-01T03:42:31
C++
UTF-8
C++
false
false
2,129
cpp
// Copyright (c) 2013, Matt Godbolt // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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. #include "seasocks/util/PathHandler.h" #include "seasocks/Request.h" #include "seasocks/Response.h" #include "seasocks/util/CrackedUri.h" using namespace seasocks; CrackedUriPageHandler::Ptr PathHandler::add(const CrackedUriPageHandler::Ptr& handler) { _handlers.emplace_back(handler); return _handlers.back(); } std::shared_ptr<Response> PathHandler::handle( const CrackedUri& uri, const Request& request) { const auto &path = uri.path(); if (path.empty() || path[0] != _path) return Response::unhandled(); auto shiftedUri = uri.shift(); for (const auto &it : _handlers) { auto response = it->handle(shiftedUri, request); if (response != Response::unhandled()) return response; } return Response::unhandled(); }
[ "tahoekeo@gmail.com" ]
tahoekeo@gmail.com
d55ebb4ce9ef726834c06ca35343bf1c7242047c
22c4f75689be2dc8c83bbd5feba57e716420d8c0
/src/Triangulation.cpp
6190381dc0798da70294cd0554cfb3b305ca3460
[ "Zlib" ]
permissive
Spessi/Thor
9fded122a6a0fc168e7ebd6c66fb1ef0e1c6d5c0
d204afb40b9d4de45239be74a0c3c1f463be0862
refs/heads/master
2021-07-19T13:53:25.140717
2021-06-23T10:09:34
2021-06-23T10:09:34
223,505,972
0
0
NOASSERTION
2019-11-23T00:01:54
2019-11-23T00:01:53
null
UTF-8
C++
false
false
39,000
cpp
///////////////////////////////////////////////////////////////////////////////// // // Thor C++ Library // Copyright (c) 2011-2021 Jan Haller // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // ///////////////////////////////////////////////////////////////////////////////// #include <Thor/Math/Triangulation.hpp> #include <Thor/Vectors/VectorAlgebra2D.hpp> #include <Thor/Config.hpp> #include <functional> #include <numeric> #include <limits> #include <stack> namespace thor { namespace { const float InfiniteRadius = std::numeric_limits<float>::max(); } namespace detail { // Struct instead of typedef, since the latter cannot be forward-declared struct OptTriangleItrArray { std::array<OptTriangleIterator, 3> iterators; }; // Type definitions typedef std::array<TriangleIterator, 3> TriangleItrArray; typedef std::pair<TriangleIterator, TriangleIterator> TriangleItrPair; typedef std::pair<std::size_t, std::size_t> IndexPair; // --------------------------------------------------------------------------------------------------------------------------- // Functor operator() definitions bool CompareVertexPtrs::operator() (const AdvancedVertex* lhs, const AdvancedVertex* rhs) const { return std::make_pair(lhs->getPosition().x, lhs->getPosition().y) < std::make_pair(rhs->getPosition().x, rhs->getPosition().y); } bool CompareEdges::operator() (const AdvancedEdge& lhs, const AdvancedEdge& rhs) const { // Automatically compare each coordinate, delegate work to std::pair return std::make_pair( std::make_pair(lhs[0].getPosition().x, lhs[0].getPosition().y), std::make_pair(lhs[1].getPosition().x, lhs[1].getPosition().y)) < std::make_pair( std::make_pair(rhs[0].getPosition().x, rhs[0].getPosition().y), std::make_pair(rhs[1].getPosition().x, rhs[1].getPosition().y)); } // --------------------------------------------------------------------------------------------------------------------------- OptTriangleIterator::OptTriangleIterator() : valid(false) , target() { } OptTriangleIterator::OptTriangleIterator(TriangleIterator target) : valid(true) , target(target) { } OptTriangleIterator::OptTriangleIterator(const OptTriangleIterator& origin) : valid(origin.valid) , target() { // Don't copy target if invalid, since the iterator is singular (default-constructed) // and almost all operations on singular iterators evoke undefined behavior. if (valid) target = origin.target; } OptTriangleIterator& OptTriangleIterator::operator= (const OptTriangleIterator& origin) { // Don't assign target if invalid, since the iterator is singular (default-constructed) // and almost all operations on singular iterators evoke undefined behavior. valid = origin.valid; if (valid) target = origin.target; return *this; } // --------------------------------------------------------------------------------------------------------------------------- Circle::Circle(sf::Vector2f midPoint, float squaredRadius) : midPoint(midPoint) , squaredRadius(squaredRadius) { } // --------------------------------------------------------------------------------------------------------------------------- AdvancedVertex::AdvancedVertex(float x, float y) : mUserVertex(nullptr) , mPosition(x, y) , mSurroundingTriangle(aurora::makeCopied<OptTriangleIterator>()) #ifndef NDEBUG , mUserType(&typeid(void)) #endif { // mSurroundingTriangle is a singular iterator. setSurroundingTriangle() must called before other operations, // especially before assignments and copies of AdvancedVertex objects. // Can't initialize surroundingTriangle here: In case of boundary vertices, the vertices themselves form the triangle. } sf::Vector2f AdvancedVertex::getPosition() const { return mPosition; } void AdvancedVertex::setSurroundingTriangle(OptTriangleIterator target) { assert(target.valid); *mSurroundingTriangle = target; } OptTriangleIterator AdvancedVertex::getSurroundingTriangle() const { assert(mSurroundingTriangle->valid); return *mSurroundingTriangle; } // --------------------------------------------------------------------------------------------------------------------------- AdvancedEdge::AdvancedEdge(AdvancedVertex& startPoint, AdvancedVertex& endPoint) : Edge<AdvancedVertex>(startPoint, endPoint) { orderCorners(); } void AdvancedEdge::orderCorners() { if (CompareVertexPtrs()(mCorners[1], mCorners[0])) { std::swap(mCorners[0], mCorners[1]); } } // --------------------------------------------------------------------------------------------------------------------------- AdvancedTriangle::AdvancedTriangle(AdvancedVertex& corner0, AdvancedVertex& corner1, AdvancedVertex& corner2) : Triangle<AdvancedVertex>(corner0, corner1, corner2) , mRemainingVertices() , mAdjacentTriangles(aurora::makeCopied<OptTriangleItrArray>()) , mFlagged(false) { } void AdvancedTriangle::addVertex(AdvancedVertex& vertexRef) { mRemainingVertices.insert(&vertexRef); } void AdvancedTriangle::removeVertex(AdvancedVertex& vertexRef) { std::size_t erased = mRemainingVertices.erase(&vertexRef); assert(erased == 1); } void AdvancedTriangle::removeVertex(VertexPtrIterator vertexItr) { std::size_t size = mRemainingVertices.size(); mRemainingVertices.erase(vertexItr); assert(size == mRemainingVertices.size() + 1); } VertexPtrIterator AdvancedTriangle::begin() { return mRemainingVertices.begin(); } VertexPtrIterator AdvancedTriangle::end() { return mRemainingVertices.end(); } void AdvancedTriangle::setAdjacentTriangle(std::size_t index, const OptTriangleIterator& adjacentTriangle) { mAdjacentTriangles->iterators[index] = adjacentTriangle; } OptTriangleIterator AdvancedTriangle::getAdjacentTriangle(std::size_t index) const { return mAdjacentTriangles->iterators[index]; } void AdvancedTriangle::setFlagged(bool flagged) { mFlagged = flagged; } bool AdvancedTriangle::isFlagged() const { return mFlagged; } // --------------------------------------------------------------------------------------------------------------------------- // Returns the position of the triangle's vertex identified by index. sf::Vector2f at(const AdvancedTriangle& triangle, std::size_t index) { return triangle[index].getPosition(); } bool isClockwiseOriented(sf::Vector2f v0, sf::Vector2f v1, sf::Vector2f v2) { return crossProduct(v1 - v0, v2 - v0) <= 0; } Circle computeCircumcircle(const AdvancedTriangle& triangle) { assert(at(triangle, 0) != at(triangle, 1) && at(triangle, 0) != at(triangle, 2)); // Compute midpoint of two sides sf::Vector2f p = 0.5f * (at(triangle, 0) + at(triangle, 1)); sf::Vector2f q = 0.5f * (at(triangle, 0) + at(triangle, 2)); // Compute perpendicular bisectors of the sides sf::Vector2f v = perpendicularVector(p - at(triangle, 0)); sf::Vector2f w = perpendicularVector(q - at(triangle, 0)); // Cross product's Z component float cross = v.x * w.y - v.y * w.x; // Special case of a flat triangle (this can occur if 3 vertices are collinear, which is not broken per se) // We don't need an epsilon here, almost-flat triangles will automatically have huge circumcircle if (cross == 0.f) { // We define the circumcircle as extremely large, so that it will always breach the Delaunay condition // The midpoint is not relevant, we simply choose the gravity center of the triangle return Circle((at(triangle, 0) + at(triangle, 1) + at(triangle, 2)) / 3.f, InfiniteRadius); } // Now we have the lines p + s*v and q + t*w with s and t being real numbers. The intersection is: sf::Vector2f intersection( v.x * (p.y * w.x + q.x * w.y - q.y * w.x) - p.x * v.y * w.x, w.y * (p.y * v.x + q.x * v.y - p.x * v.y) - q.y * v.y * w.x); intersection /= cross; // Alternative to calculating intersection (slower): // sf::Vector3f cross = crossProduct(v,w); // sf::Vector2f intersection = p + v * dotProduct(crossProduct(q-p, w), cross) / squaredLength(cross); return Circle(intersection, squaredLength(intersection - at(triangle, 0))); } // Checks two edges for intersection (if one of the endpoints is equal, this doesn't count as intersection). // Returns true, if the edges intersect anywhere except at the endpoints. bool intersection(const AdvancedEdge& lhs, const AdvancedEdge& rhs) { sf::Vector2f a = lhs[0].getPosition(); // c sf::Vector2f b = lhs[1].getPosition(); // a--+------b sf::Vector2f c = rhs[0].getPosition(); // | sf::Vector2f d = rhs[1].getPosition(); // d if (a == c || a == d || b == c || b == d) return false; return detail::isClockwiseOriented(a, c, d) != detail::isClockwiseOriented(b, c, d) && detail::isClockwiseOriented(a, b, c) != detail::isClockwiseOriented(a, b, d); } // Checks if edge intersects any constrained edge in constrainedEdges. bool intersectsEdge(const AdvancedEdge& edge, const EdgeSet& constrainedEdges) { AURORA_FOREACH(const AdvancedEdge& constrainedEdge, constrainedEdges) { if (intersection(edge, constrainedEdge)) return true; } return false; } // Inserts a new triangle built of the 3 corners and returns an iterator to it. TriangleIterator insertTriangle(TriangleList& triangles, AdvancedVertex& corner0, AdvancedVertex& corner1, AdvancedVertex& corner2) { triangles.push_back(AdvancedTriangle(corner0, corner1, corner2)); return --triangles.end(); } // Checks whether vertex is inside the triangle (center,corner1,corner2). c2 // To be exact, this function only checks if vertex is beyond the two vectors / // corner1-center, corner2-center, but since the original triangle is split v / // up into three new triangles, this doesn't matter. The example returns true. c1-----ce bool isVertexInSection(const AdvancedVertex& vertex, sf::Vector2f center, sf::Vector2f corner1, sf::Vector2f corner2) { assert(isClockwiseOriented(corner1, corner2, center)); return crossProduct(corner1 - center, vertex.getPosition() - center) < 0.f && crossProduct(corner2 - center, vertex.getPosition() - center) >= 0.f; } // The same as above, but with only 2 sections. Returns true when the vertex // is located on the "left" of the vector corner2-corner1 v // The example on the right would return true. c1------c2 bool isVertexInSection(const AdvancedVertex& vertex, sf::Vector2f corner1, sf::Vector2f corner2) { return crossProduct(corner2 - corner1, vertex.getPosition() - corner1) >= 0.f; } // Moves the vertex pointed by sourceItr in sourceTriangle void transferVertex(TriangleIterator sourceTriangle, VertexPtrIterator sourceItr, TriangleIterator destTriangle) { // Let the vertex point to the new triangle (*sourceItr)->setSurroundingTriangle(destTriangle); // Move vertex from source to dest destTriangle->addVertex(**sourceItr); sourceTriangle->removeVertex(sourceItr); } // Updates the adjacent triangle's references back to oldTriangle. They are replaced by references to newTriangle (which can be invalid). // @param other: The adjacent triangle of which the back-references are updated. May be invalid. void updateAdjacentBackReferences(TriangleIterator oldTriangle, OptTriangleIterator newTriangle, OptTriangleIterator other) { if (other.valid) { // Find out the index of other's adjacent that points to this triangle. for (std::size_t i = 0; i < 3; ++i) { OptTriangleIterator thisOne = other.target->getAdjacentTriangle(i); if (thisOne.valid && thisOne.target == oldTriangle) { other.target->setAdjacentTriangle(i, newTriangle); return; } } assert(false); } } // Sets up the adjacent triangles of each element in newTriangles according to the old triangle // (before the split into three new ones). Updates also the adjacents' back-references. void initializeAdjacents(TriangleItrArray& newTriangles, std::size_t index, TriangleIterator oldTriangle) { std::size_t index1 = (index+1) % 3; std::size_t index2 = (index+2) % 3; OptTriangleIterator other = oldTriangle->getAdjacentTriangle(index2); newTriangles[index]->setAdjacentTriangle(0, newTriangles[index1]); newTriangles[index]->setAdjacentTriangle(1, newTriangles[index2]); newTriangles[index]->setAdjacentTriangle(2, other); updateAdjacentBackReferences(oldTriangle, newTriangles[index], other); } // Move all vertices in oldTriangle into the 3 new ones in newTriangles, according to their position. void transferVertices3(TriangleIterator oldTriangleItr, TriangleItrArray& newTriangles, sf::Vector2f& newCornerPosition) { AdvancedTriangle& oldTriangle = *oldTriangleItr; // Determine in which sub-triangle all the remaining vertices of currentTriangle are transferred. // The transfer invalidates the current iterator itr, that's why it is incremented before the call. for (VertexPtrIterator itr = oldTriangle.begin(); itr != oldTriangle.end(); ) { if (isVertexInSection(**itr, newCornerPosition, at(oldTriangle, 0), at(oldTriangle, 1))) { transferVertex(oldTriangleItr, itr++, newTriangles[0]); } else if (isVertexInSection(**itr, newCornerPosition, at(oldTriangle, 1), at(oldTriangle, 2))) { transferVertex(oldTriangleItr, itr++, newTriangles[1]); } else { assert(isVertexInSection(**itr, newCornerPosition, at(oldTriangle, 2), at(oldTriangle, 0))); transferVertex(oldTriangleItr, itr++, newTriangles[2]); } } } // Of two given adjacent triangles, this function finds out which two corners are shared by both triangles, and which two are // contained by only one triangle. // // The output parameter sharedCornerIndices1 contains the subscripts (referring to the triangles) of the first shared corner, // sharedCornerIndices2 to the second shared corner, disjointCornerIndices to the corners that aren't part of the common edge. // The member first refers for each pair to the first triangle, second to the second one. void arrangeCorners(const AdvancedTriangle& first, const AdvancedTriangle& second, IndexPair& sharedCornerIndices1, IndexPair& sharedCornerIndices2, IndexPair& disjointCornerIndices) { // The triangle's corners are numbered in clockwise order. For example, to compare ABC and BAD, A // we need to reverse BAD to DAB. Here, the AB subsequences are equal in ABC and DAB. C | D // The variable j determines by how many elements the first sequence is rotated. B for (std::size_t j = 0; j < 3; ++j) { std::array<bool, 3> match; // Rotate vertex sequence in first until two of them are equal to second for (std::size_t i = 0; i < 3; ++i) { // j determines rotation, 2-i is the reversed second sequence match[i] = (at(first, (j+i) % 3) == at(second, 2-i)); } // If 2 of 3 corners are equal, then we know the corner arrangement. if (std::accumulate(match.begin(), match.end(), 0) == 2) { std::size_t nbSharedCorners = 0; // Fill output parameters with the correct vertices (according to the function's interface description) for (std::size_t i = 0; i < 3; ++i) { std::size_t firstIndex = (j+i) % 3; std::size_t secondIndex = 2-i; // A corner that both adjacent triangles (first and second) have in common if (match[i]) { assert(&first[firstIndex] == &second[secondIndex]); if (nbSharedCorners++ == 0) { sharedCornerIndices1.first = firstIndex; sharedCornerIndices1.second = secondIndex; } else { sharedCornerIndices2.first = firstIndex; sharedCornerIndices2.second = secondIndex; } } // A disjoint corner (contained in either first or second) else { assert(&first[firstIndex] != &second[secondIndex]); disjointCornerIndices.first = firstIndex; disjointCornerIndices.second = secondIndex; } } // Ensure that the indices are clockwise oriented for both triangles. (sc1.f)|(sc1.s) // first: sc1 -> sc2 -> dc first -> (dc.f) | (dc.s) <- second // second: sc2 -> sc1 -> dc (sc2.f)|(sc2.s) // Two checks required because one of the old triangles may have been flat if (!isClockwiseOriented( at(first, sharedCornerIndices1.first), at(first, sharedCornerIndices2.first), at(first, disjointCornerIndices.first)) || !isClockwiseOriented( at(second, sharedCornerIndices2.second), at(second, sharedCornerIndices1.second), at(second, disjointCornerIndices.second))) { std::swap(sharedCornerIndices1, sharedCornerIndices2); } return; } } // We get here when the triangles are not adjacent (and thus don't share two corners); this should not happen. assert(false); } // Helper function for transferVertices2() void transferVertices2Impl(TriangleIterator oldFirst, TriangleIterator oldSecond, TriangleIterator newFirst, TriangleIterator newSecond, const IndexPair& disjointCornerIndices, TriangleIterator oldTriangle) { // Find out on which side of the new edge each vertex is located and push it into the appropriate new triangle. for (VertexPtrIterator itr = oldTriangle->begin(); itr != oldTriangle->end(); ) { if (isVertexInSection(**itr, at(*oldFirst, disjointCornerIndices.first), at(*oldSecond, disjointCornerIndices.second))) { transferVertex(oldTriangle, itr++, newFirst); } else { assert(isVertexInSection(**itr, at(*oldSecond, disjointCornerIndices.second), at(*oldFirst, disjointCornerIndices.first))); transferVertex(oldTriangle, itr++, newSecond); } } } // Moves all vertices in oldTriangle to either newFirst or newSecond, depending on which side of the new // edge they are situated. void transferVertices2(TriangleIterator oldFirst, TriangleIterator oldSecond, TriangleIterator newFirst, TriangleIterator newSecond, const IndexPair& disjointCornerIndices) { transferVertices2Impl(oldFirst, oldSecond, newFirst, newSecond, disjointCornerIndices, oldFirst); transferVertices2Impl(oldFirst, oldSecond, newFirst, newSecond, disjointCornerIndices, oldSecond); } // Copies the adjacent triangle from oldTriangle at oldIndex to newTriangle at newIndex (only one reference). // Additionally, the referencee is updated so that it points to newTriangle instead of oldTriangle. void updateAdjacentRelation(TriangleIterator oldTriangle, std::size_t oldIndex, TriangleIterator newTriangle, std::size_t newIndex) { OptTriangleIterator other = oldTriangle->getAdjacentTriangle(oldIndex); // Update this triangle's references to adjacent triangles. newTriangle->setAdjacentTriangle(newIndex, other); // Update adjacent triangles's references to this triangle. updateAdjacentBackReferences(oldTriangle, newTriangle, other); } // Performs an edge flip, i.e. both triangles are merged and the resulting quadrilateral is split again, but into two different // triangles (choose the other diagonal as cutting edge). // @param oldFirst Iterator to the old first triangle. This iterator is invalidated during the operation. // @param oldSecond Like oldFirst, but iterator to the second triangle. // @param sharedCornerIndices1 Indices of the corners in oldFirst and oldSecond that refer to the shared corners. // @param sharedCornerIndices2 Like 1, but the other shared corner. // @param disjointCornerIndices Indices of the non-shared, disjoint corners. // @return Pair of the newly created triangles TriangleItrPair flipEdges(TriangleList& triangles, TriangleIterator oldFirst, TriangleIterator oldSecond, const IndexPair& sharedCornerIndices1, const IndexPair& sharedCornerIndices2, const IndexPair& disjointCornerIndices) { // Create the new triangles which are going to outlive this function TriangleIterator newFirst = insertTriangle(triangles, (*oldFirst)[sharedCornerIndices1.first], // (sc1) (*oldSecond)[disjointCornerIndices.second], // (dc.s) (*oldFirst)[disjointCornerIndices.first]); // (dc.f) TriangleIterator newSecond = insertTriangle(triangles, (*oldSecond)[sharedCornerIndices2.second], // (sc2) (*oldFirst)[disjointCornerIndices.first], // (dc.f) (*oldSecond)[disjointCornerIndices.second]); // (dc.s) // Move each vertex to the new corresponding triangle transferVertices2(oldFirst, oldSecond, newFirst, newSecond, disjointCornerIndices); // Adapt referenced adjacents - note that the old indices // (dc.f) edge // (non-shared corners) now form the end points of the new edge. // oldFirst (sc2.f) (sc1.f) flip (1)|(2) updateAdjacentRelation(oldFirst, sharedCornerIndices1.first, newSecond, 2); // ------------------------ -> (0) | (0) updateAdjacentRelation(oldFirst, sharedCornerIndices2.first, newFirst, 1); // oldSecond (sc2.s) (sc1.s) (2)|(1) updateAdjacentRelation(oldSecond, sharedCornerIndices1.second, newSecond, 1); // (dc.s) updateAdjacentRelation(oldSecond, sharedCornerIndices2.second, newFirst, 2); // newSecond|newFirst // Of course, the new triangles are adjacent to each other. newFirst->setAdjacentTriangle(0, newSecond); newSecond->setAdjacentTriangle(0, newFirst); // Mark old triangles for removal; they're not needed anymore. oldFirst->setFlagged(true); oldSecond->setFlagged(true); return TriangleItrPair(newFirst, newSecond); } // Returns true if the triangle contains the passed vertex as a corner. bool hasCorner(const AdvancedTriangle& triangle, const AdvancedVertex& corner) { // Note: Comparing addresses requires that vertices be stored only once and in a non-invalidating container. return &triangle[0] == &corner || &triangle[1] == &corner || &triangle[2] == &corner; } // Returns true if triangle contains at least one of three corners in the corners triangle bool has1Of3Corners(const AdvancedTriangle& triangle, const AdvancedTriangle& corners) { return hasCorner(triangle, corners[0]) || hasCorner(triangle, corners[1]) || hasCorner(triangle, corners[2]); } // Returns true if any of the boundary (dummy) vertices is part of first/second's shared edge. bool isSharedBoundary(const AdvancedTriangle& boundaryTriangle, const AdvancedTriangle& first, const IndexPair& sharedCornerIndices1, const IndexPair& sharedCornerIndices2) { return hasCorner(boundaryTriangle, first[sharedCornerIndices1.first]) || hasCorner(boundaryTriangle, first[sharedCornerIndices2.first]); } // Returns true if any of the boundary (dummy) vertices is either first's or second's disjoint corner. bool isDisjointBoundary(const AdvancedTriangle& boundaryTriangle, const AdvancedTriangle& first, const AdvancedTriangle& second, const IndexPair& disjointCornerIndices) { return hasCorner(boundaryTriangle, first[disjointCornerIndices.first]) || hasCorner(boundaryTriangle, second[disjointCornerIndices.second]); } bool ensureLocalDelaunay(TriangleList& triangles, TriangleIterator first, TriangleIterator second, const AdvancedTriangle& boundaryTriangle, const EdgeSet& constrainedEdges); // Applies the check for the Delaunay condition recursively to the triangles neighbors. // @return true if an edge flip is performed, false otherwise. bool ensureLocalDelaunayAdjacent(TriangleList& triangles, TriangleIterator triangleItr, std::size_t adjacentIndex, const AdvancedTriangle& boundaryTriangle, const EdgeSet& constrainedEdges) { OptTriangleIterator itr = triangleItr->getAdjacentTriangle(adjacentIndex); return itr.valid && ensureLocalDelaunay(triangles, triangleItr, itr.target, boundaryTriangle, constrainedEdges); } // Flips edges and enforces the Delaunay condition at adjacent triangles void changeEdgeSituation(TriangleList& triangles, TriangleIterator first, TriangleIterator second, const AdvancedTriangle& boundaryTriangle, const EdgeSet& constrainedEdges, const IndexPair& sharedCornerIndices1, const IndexPair& sharedCornerIndices2, const IndexPair& disjointCornerIndices) { TriangleItrPair newTriangles = flipEdges(triangles, first, second, sharedCornerIndices1, sharedCornerIndices2, disjointCornerIndices); // Ensure that the adjacent triangles locally conform to Delaunay, as well. // If one function call returns true, don't execute the others because iterators are invalidated. // On average, the recursion stops on O(1) time, the adjacent triangles are already Delaunay-conforming. ensureLocalDelaunayAdjacent(triangles, newTriangles.first, 1, boundaryTriangle, constrainedEdges); ensureLocalDelaunayAdjacent(triangles, newTriangles.first, 2, boundaryTriangle, constrainedEdges); ensureLocalDelaunayAdjacent(triangles, newTriangles.second, 1, boundaryTriangle, constrainedEdges); ensureLocalDelaunayAdjacent(triangles, newTriangles.second, 2, boundaryTriangle, constrainedEdges); } // Checks whether the shared edge of two triangles must be moved (to the other diagonal of the quadrilateral) // and performs the necessary actions in this case, so that the triangulation locally conforms Delaunay. // Also, the adjacent triangles are checked and edge-flipped, if necessary. On average, this requires constant // time because the surrounding triangles already satisfy Delaunay before the flip of this triangle. // If an edge flip is performed, true is returned and the new triangles are stored in the input/output parameters first, second. // @return true if an edge flip is performed, false otherwise. bool ensureLocalDelaunay(TriangleList& triangles, TriangleIterator first, TriangleIterator second, const AdvancedTriangle& boundaryTriangle, const EdgeSet& constrainedEdges) { // Note: If the merged quadrilateral is concave, the Delaunay condition will locally already be satisfied. // Flagged triangles are going to be removed, don't take them into account if (first->isFlagged() || second->isFlagged()) return false; // Find out which triangle indices refer to the corners that are shared by both triangles, and which to the disjoint ones. IndexPair sharedCornerIndices1; IndexPair sharedCornerIndices2; IndexPair disjointCornerIndices; arrangeCorners(*first, *second, sharedCornerIndices1, sharedCornerIndices2, disjointCornerIndices); // Check if we must flip edges because of the boundaries (the triangles there don't have to conform Delaunay, but the triangles inside do) bool disjointBoundary = isDisjointBoundary(boundaryTriangle, *first, *second, disjointCornerIndices); bool sharedBoundary = isSharedBoundary(boundaryTriangle, *first, sharedCornerIndices1, sharedCornerIndices2); // The following additional checks are not required if constrained edges are always part of a merged quadrilateral (=two adjacent triangles). // But in general, we may have constrained edges that span many triangles, and the local Delaunay condition doesn't capture them. bool sharedBlocking = intersectsEdge(AdvancedEdge((*first)[sharedCornerIndices1.first], (*first)[sharedCornerIndices2.first]), constrainedEdges); bool disjointBlocking = intersectsEdge(AdvancedEdge((*first)[disjointCornerIndices.first], (*second)[disjointCornerIndices.second]), constrainedEdges); // These two bools express whether the disjoint edge respectively the shared edge MUST be flipped. bool disjointEdgeEnforced = disjointBoundary || disjointBlocking; bool sharedEdgeEnforced = sharedBoundary || sharedBlocking; // If the Delaunay test concerns one of the initial vertices, we pretend that those vertices are never inside the circumcircle. // This is required because we don't want to perform edge flips at the boundary of the very big outer triangle. // The same applies to constrained edges as input of the Constrained Delaunay Triangulation. if (disjointEdgeEnforced && !sharedEdgeEnforced) return false; if (sharedEdgeEnforced && !disjointEdgeEnforced) { // If the merged quadrilateral isn't convex, we may of course not flip edges (since the new edge would be located outside both triangles). if (isClockwiseOriented(at(*first, disjointCornerIndices.first), at(*second, disjointCornerIndices.second), at(*first, sharedCornerIndices1.first)) || isClockwiseOriented(at(*second, disjointCornerIndices.second), at(*first, disjointCornerIndices.first), at(*first, sharedCornerIndices2.first))) return false; changeEdgeSituation(triangles, first, second, boundaryTriangle, constrainedEdges, sharedCornerIndices1, sharedCornerIndices2, disjointCornerIndices); return true; } // If the vertex of the other triangle is inside this triangle's circumcircle, the Delaunay condition is locally breached and we need to flip edges. // Independently, there can be an enforced edge flip (at the boundary, or because of the constraints). // Condition (2) is actually not necessary, since the Delaunay condition is symmetric to both triangles. However, rounding errors may occur // at close points. Condition (0) makes sure that we don't perform a pointless edge flip if both triangles are degenerate (flat). Circle circle = computeCircumcircle(*first); Circle circle2 = computeCircumcircle(*second); if (!(circle.squaredRadius == InfiniteRadius && circle2.squaredRadius == InfiniteRadius) // (0) && squaredLength(at(*second, disjointCornerIndices.second) - circle.midPoint) < circle.squaredRadius // (1) && squaredLength(at(*first, disjointCornerIndices.first) - circle2.midPoint) < circle2.squaredRadius) // (2) { changeEdgeSituation(triangles, first, second, boundaryTriangle, constrainedEdges, sharedCornerIndices1, sharedCornerIndices2, disjointCornerIndices); return true; } // Otherwise, the triangles are Delaunay at the moment and no edge flip is required. return false; } // Inserts the specified vertex into the list of triangles. void insertPoint(TriangleList& triangles, AdvancedVertex& vertex, const AdvancedTriangle& boundaryTriangle, const EdgeSet& constrainedEdges) { TriangleIterator oldTriangleItr = vertex.getSurroundingTriangle().target; AdvancedTriangle& oldTriangle = *oldTriangleItr; assert(isClockwiseOriented(at(oldTriangle, 0), at(oldTriangle, 1), at(oldTriangle, 2))); // Split triangle up into three new sub-triangles, each consisting of two old corners and the new vertex TriangleItrArray newTriangles = { insertTriangle(triangles, oldTriangle[0], oldTriangle[1], vertex), insertTriangle(triangles, oldTriangle[1], oldTriangle[2], vertex), insertTriangle(triangles, oldTriangle[2], oldTriangle[0], vertex)}; // Assign the adjacent triangles to the new triangles for (std::size_t i = 0; i < 3; ++i) initializeAdjacents(newTriangles, i, oldTriangleItr); // Remove current vertex - as soon as it forms a triangle corner, it counts no longer as remaining vertex sf::Vector2f newCornerPosition = vertex.getPosition(); oldTriangle.removeVertex(vertex); // Move each vertex to its corresponding new surrounding triangle transferVertices3(oldTriangleItr, newTriangles, newCornerPosition); // Remove the old big triangle, we have three new ones triangles.erase(oldTriangleItr); // For each newly created triangle, we must ensure that the Delaunay condition with its adjacent is kept up. // The variable adjacent (third argument of ensureLocalDelaunay()) is the adjacent of the old triangle. // Corner number 2 is always the vertex inserted in this function, so the triangle on the opposite is the sought one. for (std::size_t i = 0; i < 3; ++i) { OptTriangleIterator adjacent = newTriangles[i]->getAdjacentTriangle(2); if (adjacent.valid) ensureLocalDelaunay(triangles, newTriangles[i], adjacent.target, boundaryTriangle, constrainedEdges); } // Remove currently flagged triangles. Don't do this earlier because of iterator invalidations. triangles.remove_if(std::mem_fn(&AdvancedTriangle::isFlagged)); } // Creates 3 "dummy" vertices that form a huge triangle which later includes all other vertices // (every element of allVertices). void createBoundaryPoints(VertexCtr& allVertices, TriangleList& triangles) { assert(allVertices.empty()); assert(triangles.empty()); // Add boundary vertices (choose arbitrary, clockwise oriented positions) allVertices.push_back(AdvancedVertex(-1, 0)); allVertices.push_back(AdvancedVertex( 0,+1)); allVertices.push_back(AdvancedVertex(+1, 0)); // First triangle in list is the one containing the three boundary vertices triangles.push_back(AdvancedTriangle(allVertices[0], allVertices[1], allVertices[2])); for (std::size_t i = 0; i < 3; ++i) allVertices[i].setSurroundingTriangle(triangles.begin()); } // Sets the initial point positions so that the triangle of dummy vertices includes all other vertices. // Like this, we can start the algorithm seamlessly. void setBoundaryPositions(const VertexCtr& allVertices, AdvancedTriangle& boundaryTriangle) { // Find maximal coordinate in any direction float maxCoord = 0.f; AURORA_FOREACH(const AdvancedVertex& vertex, allVertices) { sf::Vector2f position = vertex.getPosition(); maxCoord = std::max(maxCoord, std::abs(position.x)); maxCoord = std::max(maxCoord, std::abs(position.y)); } // Reduce probability to have a 3 collinear points (which can't be triangulated) by slightly moving boundary points. Take arbitrary value... const float epsilon = 0.000372f; // Overwrite 3 dummy vertices so that the resulting triangle certainly surrounds all other vertices. maxCoord *= 4.f; boundaryTriangle[0] = AdvancedVertex(epsilon, maxCoord-epsilon); boundaryTriangle[1] = AdvancedVertex(maxCoord+epsilon, -epsilon); boundaryTriangle[2] = AdvancedVertex(-maxCoord-epsilon, -maxCoord+epsilon); } // Checks whether the edge formed of the two specified points is contained in constrainedEdges. // Copies vertex parameters, but they're not further used. bool isEdgeConstrained(const EdgeSet& constrainedEdges, AdvancedVertex startPoint, AdvancedVertex endPoint) { AdvancedEdge adv(startPoint, endPoint); EdgeSet::const_iterator candidate = constrainedEdges.find(adv); // Just to make sure the set predicate really works. Otherwise: return candidate != ..end() && .. && ..; assert(candidate == constrainedEdges.end() || adv[0].getPosition() == (*candidate)[0].getPosition() && adv[1].getPosition() == (*candidate)[1].getPosition()); return candidate != constrainedEdges.end(); } // Checks if the adjacent triangle is in use (i.e. inside the polygon) and returns a valid OptTriangleIterator in this case. // Otherwise, the latter is invalid. OptTriangleIterator hasUnusedAdjacent(const AdvancedTriangle& triangle, std::size_t index, const EdgeSet& constrainedEdges) { if (isEdgeConstrained(constrainedEdges, triangle[(index+1) % 3], triangle[(index+2) % 3])) return OptTriangleIterator(); else return triangle.getAdjacentTriangle(index); } // Iterative implementation of RemoveUnusedTriangles void removeOuterPolygonTrianglesImpl(TriangleIterator current, std::stack<TriangleIterator>& stack, const EdgeSet& constrainedEdges) { // Flagged triangles have already been passed, skip them if (current->isFlagged()) return; current->setFlagged(true); OptTriangleIterator adjacent; for (std::size_t i = 0; i < 3; ++i) { if ((adjacent = hasUnusedAdjacent(*current, i, constrainedEdges)).valid) stack.push(adjacent.target); } } // Removes the triangles that are "unused" (i.e. outside the polygon). // The parameter current refers to any triangle touching at least one boundary point. Starting at this triangle, adjacent triangles // are walked through recursively. When we reach an edge of the polygon (which is always a constrained edge, and vice versa), // we stop here and complete the remaining directions. Finally, all triangles that are outside of the polygon bounds are removed. void removeOuterPolygonTriangles(TriangleList& triangles, TriangleIterator current, const EdgeSet& constrainedEdges) { std::stack<TriangleIterator> stack; stack.push(current); while (!stack.empty()) { // get the top element of the stack (next triangle to traverse) and pop it current = stack.top(); stack.pop(); // Call function that may push new triangles onto the stack removeOuterPolygonTrianglesImpl(current, stack, constrainedEdges); } // Remove all triangles marked as unused. // We can't erase() during the stack iteration, because triangles' flags are still polled, so the iterators must be valid. triangles.remove_if(std::mem_fn(&AdvancedTriangle::isFlagged)); } // Removes all triangles that are not directly required for the resulting triangulation (algorithm-supporting data). // In case that a polygon is triangulated, all triangles at the outside of the polygon are removed. void removeUnusedTriangles(TriangleList& triangles, const AdvancedTriangle& boundaryTriangle, const EdgeSet& constrainedEdges, bool limitToPolygon) { for (TriangleList::iterator itr = triangles.begin(); itr != triangles.end(); ) { // If the current triangle is located at the boundary (touches one of the boundary corners) if (has1Of3Corners(*itr, boundaryTriangle)) { // When we just want to triangulate the inside of a polygon, we must cut off all outer triangles, beginning // at any boundary-touching triangle. if (limitToPolygon) return removeOuterPolygonTriangles(triangles, itr, constrainedEdges); // Otherwise, only the very outer triangles (those touching the boundary vertices) must be removed else itr = triangles.erase(itr); } // Triangle is retained, continue else { ++itr; } } } } // namespace detail } // namespace thor
[ "bromeon@gmail.com" ]
bromeon@gmail.com
2f4410e1d807a9a3652287f17b2da8490627e656
1c680f13c7c33bb44a1bbb9082b410bb6d7fa3a4
/LeetCode/0029/0029_1.cpp
0e891c50926eb2020d199a7ff2ec38aa9e14ce27
[ "MIT" ]
permissive
samsonwang/ToyCpp
a59b89529445333c0cf4e31e1d23f59e5323087d
399d45feda210028d798a4b3b25b1af707b23a73
refs/heads/master
2023-04-04T02:53:57.990277
2023-03-30T01:08:44
2023-03-30T01:08:44
133,638,289
0
0
null
null
null
null
UTF-8
C++
false
false
1,252
cpp
#include <cstdio> #include <cmath> #include <cstdint> #include <cinttypes> int divide(int dividend, int divisor) { printf("dividend = %d(0x%x) divisor = %d(0x%x)\n", dividend, dividend, divisor, divisor); std::int64_t d1 = dividend; std::int64_t d2 = divisor; // 符号转换 bool neg = false; if (d1 < 0) { neg = !neg; d1 = -d1; } if (d2 < 0) { neg = !neg; d2 = -d2; } std::printf("d1 = %" PRId64 "(0x%x) d2 = %" PRId64 "(0x%x)\n", d1, d1, d2, d2); fflush(stdout); // 这样两个数的符号都是正的了 int ans = 0; while (d1 >= d2) { d1 -= d2; ++ans; // overflow if (ans < 0) { return 0x7fffffff; } } if (neg) { return -ans; } return ans; } int main(int argc, char* argv[]) { int d1 = 2147483647; int d2 = 1; printf("dividend = %d(0x%x) divisor = %d(0x%x)\n", d1, d1, d2, d2); int ret = divide(d1, d2); printf("d1 = %d, d2 = %d, ret = %d\n", d1, d2, ret); int t1 = std::pow(2, 31) - 1; printf("t1 = 0x%x , %lld\n", t1, t1); // printf("0x%x\n", -2147483648); return 0; }
[ "wangzhilv@gmail.com" ]
wangzhilv@gmail.com
c3eb4883314072aae1230943c53a36fe575eb7a5
3418dcc860d6b58b66e7fd2d1893daf63aeea046
/数论/大整数/Untitled-1.cpp
82118eda4a3e4e242802e733952a3b1d4baf9148
[]
no_license
HexQwQ/BanZi
2a175aa88ddb67b8fe1b6553d0319338da4805b8
9ebe322303cdcaaf2ba912e1af1317c643e6ed3e
refs/heads/master
2020-08-09T19:07:03.565869
2019-10-10T10:11:10
2019-10-10T10:11:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,746
cpp
#include <iostream> #include <string> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #define range(i, a, b) for (int i = a; i <= b; ++i) #define rerange(i, a, b) for (int i = a; i >= b; --i) #define LL long long #define fill(arr, tmp) memset(arr, tmp, sizeof(arr)) using namespace std; const int S = 20; LL mult_mod(LL a, LL b, LL c) { a %= c; b %= c; long long ret = 0; while (b) { if (b & 1) { ret += a; ret %= c; } a <<= 1; if (a >= c) a %= c; b >>= 1; } return ret; } LL pow_mod(LL x, LL n, LL mod) { if (n == 1) return x % mod; x %= mod; LL tmp = x; LL ret = 1; while (n) { if (n & 1) ret = mult_mod(ret, tmp, mod); tmp = mult_mod(tmp, tmp, mod); n >>= 1; } return ret; } bool check(LL a, LL n, LL x, LL t) { LL ret = pow_mod(a, x, n); LL last = ret; range(i, 1, t) { ret = mult_mod(ret, ret, n); if (ret == 1 && last != 1 && last != n - 1) return true; last = ret; } if (ret != 1) return true; return false; } bool Miller_Rabin(LL n) { if (n < 2) return false; if (n == 2) return true; if ((n & 1) == 0) return false; LL x = n - 1; LL t = 0; while ((x & 1) == 0) { x >>= 1; t++; } range(i, 0, S - 1) { LL a = rand() % (n - 1) + 1; if (check(a, n, x, t)) return false; } return true; } LL factor[100]; int tol; LL gcd(LL a, LL b) { if (a == 0) return 1; if (a < 0) return gcd(-a, b); while (b) { long long t = a % b; a = b; b = t; } return a; } LL Pollard_rho(LL x, LL c) { LL i = 1, k = 2; LL x0 = rand() % x; LL y = x0; while (1) { i++; x0 = (mult_mod(x0, x0, x) + c) % x; LL d = gcd(y - x0, x); if (d != 1 && d != x) return d; if (y == x0) return x; if (i == k) { y = x0; k += k; } } } void findfac(LL n) { if (Miller_Rabin(n)) { factor[tol++] = n; return; } LL p = n; while (p >= n) p = Pollard_rho(p, rand() % (n - 1) + 1); findfac(p); findfac(n / p); } int main() { long long n; while (scanf("%lld", &n) != EOF) { tol = 0; /* findfac(n); for(int i=0;i<tol;++i)cout<<factor[i]<<" "; printf("\n"); */ if (Miller_Rabin(n)) printf("Yes\n"); else printf("No\n"); } return 0; }
[ "hexi0921" ]
hexi0921
231d66861b79ec634915477dddf5c51db663cc02
33961eca45e9ae43d3f11cd43760076d7f3c0337
/src/utils/vutils.cpp
7a190be48bc279d731c9d51eb940d9b605b88f86
[ "BSD-3-Clause", "ISC", "Apache-2.0", "GPL-3.0-only", "MIT" ]
permissive
luo-chuan/vnote
1fc04319c371083391b8a67bab4c6bd59ff24723
a72e2a316947dfb9e2ac27225f7b9ed702f8567d
refs/heads/master
2020-04-02T07:01:16.712716
2018-10-23T13:42:41
2018-10-23T13:42:41
154,178,003
0
0
MIT
2018-10-23T13:42:42
2018-10-22T16:32:26
C++
UTF-8
C++
false
false
55,612
cpp
#include "vutils.h" #include <QFile> #include <QDir> #include <QDebug> #include <QRegExp> #include <QClipboard> #include <QApplication> #include <QMimeData> #include <QJsonObject> #include <QJsonDocument> #include <QDateTime> #include <QFileInfo> #include <QImageReader> #include <QKeyEvent> #include <QScreen> #include <cmath> #include <QLocale> #include <QPushButton> #include <QElapsedTimer> #include <QValidator> #include <QRegExpValidator> #include <QRegExp> #include <QKeySequence> #include <QComboBox> #include <QStyledItemDelegate> #include <QWebEngineView> #include <QAction> #include <QTreeWidgetItem> #include <QFormLayout> #include <QInputDialog> #include <QFontDatabase> #include <QSvgRenderer> #include <QPainter> #include <QTemporaryFile> #include "vorphanfile.h" #include "vnote.h" #include "vnotebook.h" #include "vpreviewpage.h" #include "pegparser.h" extern VConfigManager *g_config; QVector<QPair<QString, QString>> VUtils::s_availableLanguages; const QString VUtils::c_imageLinkRegExp = QString("\\!\\[([^\\[\\]]*)\\]" "\\(\\s*" "([^\\)\"'\\s]+)" "(\\s*(\"[^\"\\)\\n\\r]*\")|('[^'\\)\\n\\r]*'))?" "(\\s*=(\\d*)x(\\d*))?" "\\s*\\)"); const QString VUtils::c_imageTitleRegExp = QString("[^\\[\\]]*"); const QString VUtils::c_linkRegExp = QString("\\[([^\\]]*)\\]" "\\(\\s*(\\S+)" "(?:\\s+((\"[^\"\\n\\r]*\")" "|('[^'\\n\\r]*')))?\\s*" "\\)"); const QString VUtils::c_fileNameRegExp = QString("(?:[^\\\\/:\\*\\?\"<>\\|\\s]| )*"); const QString VUtils::c_fencedCodeBlockStartRegExp = QString("^(\\s*)```([^`\\s]*)\\s*[^`]*$"); const QString VUtils::c_fencedCodeBlockEndRegExp = QString("^(\\s*)```$"); const QString VUtils::c_previewImageBlockRegExp = QString("[\\n|^][ |\\t]*\\xfffc[ |\\t]*(?=\\n)"); const QString VUtils::c_headerRegExp = QString("^(#{1,6})\\s+(((\\d+\\.)+(?=\\s))?\\s*(\\S.*)?)$"); const QString VUtils::c_headerPrefixRegExp = QString("^(#{1,6}\\s+((\\d+\\.)+(?=\\s))?\\s*)($|(\\S.*)?$)"); const QString VUtils::c_listRegExp = QString("^\\s*(-|\\*|\\d+\\.)\\s"); const QString VUtils::c_blockQuoteRegExp = QString("^\\s*(\\>\\s?)"); void VUtils::initAvailableLanguage() { if (!s_availableLanguages.isEmpty()) { return; } s_availableLanguages.append(QPair<QString, QString>("en_US", "English (US)")); s_availableLanguages.append(QPair<QString, QString>("zh_CN", "Chinese")); } QString VUtils::readFileFromDisk(const QString &filePath) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { qWarning() << "fail to open file" << filePath << "to read"; return QString(); } QString fileText(file.readAll()); file.close(); qDebug() << "read file content:" << filePath; return fileText; } bool VUtils::writeFileToDisk(const QString &p_filePath, const QString &p_text) { QFile file(p_filePath); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << "fail to open file" << p_filePath << "to write"; return false; } QTextStream stream(&file); stream << p_text; file.close(); qDebug() << "write file content:" << p_filePath; return true; } bool VUtils::writeFileToDisk(const QString &p_filePath, const QByteArray &p_data) { QFile file(p_filePath); if (!file.open(QIODevice::WriteOnly)) { qWarning() << "fail to open file" << p_filePath << "to write"; return false; } file.write(p_data); file.close(); qDebug() << "write file content:" << p_filePath; return true; } bool VUtils::writeJsonToDisk(const QString &p_filePath, const QJsonObject &p_json) { QFile file(p_filePath); // We use Unix LF for config file. if (!file.open(QIODevice::WriteOnly)) { qWarning() << "fail to open file" << p_filePath << "to write"; return false; } QJsonDocument doc(p_json); if (-1 == file.write(doc.toJson())) { return false; } return true; } QJsonObject VUtils::readJsonFromDisk(const QString &p_filePath) { QFile file(p_filePath); if (!file.open(QIODevice::ReadOnly)) { qWarning() << "fail to open file" << p_filePath << "to read"; return QJsonObject(); } return QJsonDocument::fromJson(file.readAll()).object(); } QString VUtils::generateImageFileName(const QString &path, const QString &title, const QString &format) { Q_UNUSED(title); const QChar sep('_'); QString baseName(g_config->getImageNamePrefix()); if (!baseName.isEmpty() && !(baseName.size() == 1 && baseName[0] == sep)) { baseName += sep; } // Add current time at fixed length. baseName += QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz"); // Add random number to make the name be most likely unique. baseName += (sep + QString::number(qrand())); QString suffix; if (!format.isEmpty()) { suffix = "." + format.toLower(); } QString imageName(baseName + suffix); int index = 1; QDir dir(path); while (fileExists(dir, imageName, true)) { imageName = QString("%1_%2%3").arg(baseName).arg(index++).arg(suffix); } return imageName; } QString VUtils::fileNameFromPath(const QString &p_path) { if (p_path.isEmpty()) { return p_path; } return QFileInfo(QDir::cleanPath(p_path)).fileName(); } QString VUtils::basePathFromPath(const QString &p_path) { if (p_path.isEmpty()) { return p_path; } return QFileInfo(QDir::cleanPath(p_path)).path(); } QVector<ImageLink> VUtils::fetchImagesFromMarkdownFile(VFile *p_file, ImageLink::ImageLinkType p_type) { Q_ASSERT(p_file->getDocType() == DocType::Markdown); QVector<ImageLink> images; bool isOpened = p_file->isOpened(); if (!isOpened && !p_file->open()) { return images; } const QString &text = p_file->getContent(); if (text.isEmpty()) { if (!isOpened) { p_file->close(); } return images; } // Used to de-duplicate the links. Url as the key. QSet<QString> fetchedLinks; QVector<VElementRegion> regions = fetchImageRegionsUsingParser(text); QRegExp regExp(c_imageLinkRegExp); QString basePath = p_file->fetchBasePath(); for (int i = 0; i < regions.size(); ++i) { const VElementRegion &reg = regions[i]; QString linkText = text.mid(reg.m_startPos, reg.m_endPos - reg.m_startPos); bool matched = regExp.exactMatch(linkText); if (!matched) { // Image links with reference format will not match. continue; } QString imageUrl = regExp.capturedTexts()[2].trimmed(); ImageLink link; link.m_url = imageUrl; QFileInfo info(basePath, purifyUrl(imageUrl)); if (info.exists()) { if (info.isNativePath()) { // Local file. link.m_path = QDir::cleanPath(info.absoluteFilePath()); if (QDir::isRelativePath(imageUrl)) { link.m_type = p_file->isInternalImageFolder(VUtils::basePathFromPath(link.m_path)) ? ImageLink::LocalRelativeInternal : ImageLink::LocalRelativeExternal; } else { link.m_type = ImageLink::LocalAbsolute; } } else { link.m_type = ImageLink::Resource; link.m_path = imageUrl; } } else { QUrl url(imageUrl); link.m_path = url.toString(); link.m_type = ImageLink::Remote; } if (link.m_type & p_type) { if (!fetchedLinks.contains(link.m_url)) { fetchedLinks.insert(link.m_url); images.push_back(link); qDebug() << "fetch one image:" << link.m_type << link.m_path << link.m_url; } } } if (!isOpened) { p_file->close(); } return images; } QString VUtils::linkUrlToPath(const QString &p_basePath, const QString &p_url) { QString fullPath; QFileInfo info(p_basePath, purifyUrl(p_url)); if (info.exists()) { if (info.isNativePath()) { // Local file. fullPath = QDir::cleanPath(info.absoluteFilePath()); } else { fullPath = p_url; } } else { QString decodedUrl(p_url); VUtils::decodeUrl(decodedUrl); QFileInfo dinfo(p_basePath, decodedUrl); if (dinfo.exists()) { if (dinfo.isNativePath()) { // Local file. fullPath = QDir::cleanPath(dinfo.absoluteFilePath()); } else { fullPath = p_url; } } else { QUrl url(p_url); if (url.isLocalFile()) { fullPath = url.toLocalFile(); } else { fullPath = url.toString(); } } } return fullPath; } bool VUtils::makePath(const QString &p_path) { if (p_path.isEmpty()) { return true; } bool ret = true; QDir dir; if (dir.mkpath(p_path)) { qDebug() << "make path" << p_path; } else { qWarning() << "fail to make path" << p_path; ret = false; } return ret; } QJsonObject VUtils::clipboardToJson() { QClipboard *clipboard = QApplication::clipboard(); const QMimeData *mimeData = clipboard->mimeData(); QJsonObject obj; if (mimeData->hasText()) { QString text = mimeData->text(); obj = QJsonDocument::fromJson(text.toUtf8()).object(); qDebug() << "Json object in clipboard" << obj; } return obj; } ClipboardOpType VUtils::operationInClipboard() { QJsonObject obj = clipboardToJson(); if (obj.contains(ClipboardConfig::c_type)) { return (ClipboardOpType)obj[ClipboardConfig::c_type].toInt(); } return ClipboardOpType::Invalid; } bool VUtils::copyFile(const QString &p_srcFilePath, const QString &p_destFilePath, bool p_isCut) { QString srcPath = QDir::cleanPath(p_srcFilePath); QString destPath = QDir::cleanPath(p_destFilePath); if (srcPath == destPath) { return true; } QDir dir; if (!dir.mkpath(basePathFromPath(p_destFilePath))) { qWarning() << "fail to create directory" << basePathFromPath(p_destFilePath); return false; } if (p_isCut) { QFile file(srcPath); if (!file.rename(destPath)) { qWarning() << "fail to copy file" << srcPath << destPath; return false; } } else { if (!QFile::copy(srcPath, destPath)) { qWarning() << "fail to copy file" << srcPath << destPath; return false; } } return true; } bool VUtils::copyDirectory(const QString &p_srcDirPath, const QString &p_destDirPath, bool p_isCut) { QString srcPath = QDir::cleanPath(p_srcDirPath); QString destPath = QDir::cleanPath(p_destDirPath); if (srcPath == destPath) { return true; } if (QFileInfo::exists(destPath)) { qWarning() << QString("target directory %1 already exists").arg(destPath); return false; } // QDir.rename() could not move directory across drives. // Make sure target directory exists. QDir destDir(destPath); if (!destDir.exists()) { if (!destDir.mkpath(destPath)) { qWarning() << QString("fail to create target directory %1").arg(destPath); return false; } } // Handle directory recursively. QDir srcDir(srcPath); Q_ASSERT(srcDir.exists() && destDir.exists()); QFileInfoList nodes = srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); for (int i = 0; i < nodes.size(); ++i) { const QFileInfo &fileInfo = nodes.at(i); QString name = fileInfo.fileName(); if (fileInfo.isDir()) { if (!copyDirectory(srcDir.filePath(name), destDir.filePath(name), p_isCut)) { return false; } } else { Q_ASSERT(fileInfo.isFile()); if (!copyFile(srcDir.filePath(name), destDir.filePath(name), p_isCut)) { return false; } } } if (p_isCut) { if (!destDir.rmdir(srcPath)) { qWarning() << QString("fail to delete source directory %1 after cut").arg(srcPath); return false; } } return true; } int VUtils::showMessage(QMessageBox::Icon p_icon, const QString &p_title, const QString &p_text, const QString &p_infoText, QMessageBox::StandardButtons p_buttons, QMessageBox::StandardButton p_defaultBtn, QWidget *p_parent, MessageBoxType p_type) { QMessageBox msgBox(p_icon, p_title, p_text, p_buttons, p_parent); msgBox.setInformativeText(p_infoText); msgBox.setDefaultButton(p_defaultBtn); if (p_type == MessageBoxType::Danger) { QPushButton *okBtn = dynamic_cast<QPushButton *>(msgBox.button(QMessageBox::Ok)); if (okBtn) { setDynamicProperty(okBtn, "DangerBtn"); } } QPushButton *defaultBtn = dynamic_cast<QPushButton *>(msgBox.button(p_defaultBtn)); if (defaultBtn) { setDynamicProperty(defaultBtn, "SpecialBtn"); } return msgBox.exec(); } void VUtils::promptForReopen(QWidget *p_parent) { VUtils::showMessage(QMessageBox::Information, QObject::tr("Information"), QObject::tr("Please re-open current opened tabs to make it work."), "", QMessageBox::Ok, QMessageBox::Ok, p_parent); } QString VUtils::generateCopiedFileName(const QString &p_dirPath, const QString &p_fileName, bool p_completeBaseName) { QDir dir(p_dirPath); if (!dir.exists() || !dir.exists(p_fileName)) { return p_fileName; } QFileInfo fi(p_fileName); QString baseName = p_completeBaseName ? fi.completeBaseName() : fi.baseName(); QString suffix = p_completeBaseName ? fi.suffix() : fi.completeSuffix(); int index = 0; QString fileName; do { QString seq; if (index > 0) { seq = QString("%1").arg(QString::number(index), 3, '0'); } index++; fileName = QString("%1_copy%2").arg(baseName).arg(seq); if (!suffix.isEmpty()) { fileName = fileName + "." + suffix; } } while (fileExists(dir, fileName, true)); return fileName; } QString VUtils::generateCopiedDirName(const QString &p_parentDirPath, const QString &p_dirName) { QDir dir(p_parentDirPath); QString name = p_dirName; QString dirPath = dir.filePath(name); int index = 0; while (QDir(dirPath).exists()) { QString seq; if (index > 0) { seq = QString::number(index); } index++; name = QString("%1_copy%2").arg(p_dirName).arg(seq); dirPath = dir.filePath(name); } return name; } const QVector<QPair<QString, QString>>& VUtils::getAvailableLanguages() { if (s_availableLanguages.isEmpty()) { initAvailableLanguage(); } return s_availableLanguages; } bool VUtils::isValidLanguage(const QString &p_lang) { for (auto const &lang : getAvailableLanguages()) { if (lang.first == p_lang) { return true; } } return false; } bool VUtils::isImageURL(const QUrl &p_url) { QString urlStr; if (p_url.isLocalFile()) { urlStr = p_url.toLocalFile(); } else { urlStr = p_url.toString(); } return isImageURLText(urlStr); } bool VUtils::isImageURLText(const QString &p_url) { QFileInfo info(purifyUrl(p_url)); return QImageReader::supportedImageFormats().contains(info.suffix().toLower().toLatin1()); } qreal VUtils::calculateScaleFactor() { static qreal factor = -1; if (factor < 0) { const qreal refDpi = 96; qreal dpi = QGuiApplication::primaryScreen()->logicalDotsPerInch(); factor = dpi / refDpi; if (factor < 1) { factor = 1; } else { // Keep only two digits after the dot. factor = (int)(factor * 100) / 100.0; } } return factor; } bool VUtils::realEqual(qreal p_a, qreal p_b) { return std::abs(p_a - p_b) < 1e-8; } QChar VUtils::keyToChar(int p_key, bool p_smallCase) { QString key = QKeySequence(p_key).toString(); if (key.size() == 1) { return p_smallCase ? key[0].toLower() : key[0]; } return QChar(); } QString VUtils::getLocale() { QString locale = g_config->getLanguage(); if (locale == "System" || !isValidLanguage(locale)) { locale = QLocale::system().name(); } return locale; } void VUtils::sleepWait(int p_milliseconds) { if (p_milliseconds <= 0) { return; } QElapsedTimer t; t.start(); while (t.elapsed() < p_milliseconds) { QCoreApplication::processEvents(); } } DocType VUtils::docTypeFromName(const QString &p_name) { if (p_name.isEmpty()) { return DocType::Unknown; } const QHash<int, QList<QString>> &suffixes = g_config->getDocSuffixes(); QString suf = QFileInfo(p_name).suffix().toLower(); for (auto it = suffixes.begin(); it != suffixes.end(); ++it) { if (it.value().contains(suf)) { return DocType(it.key()); } } return DocType::Unknown; } QString VUtils::generateSimpleHtmlTemplate(const QString &p_body) { QString html(VNote::s_simpleHtmlTemplate); return html.replace(HtmlHolder::c_bodyHolder, p_body); } QString VUtils::generateHtmlTemplate(MarkdownConverterType p_conType) { return generateHtmlTemplate(VNote::s_markdownTemplate, p_conType); } QString VUtils::generateHtmlTemplate(MarkdownConverterType p_conType, const QString &p_renderBg, const QString &p_renderStyle, const QString &p_renderCodeBlockStyle, bool p_isPDF, bool p_wkhtmltopdf, bool p_addToc) { Q_ASSERT((p_isPDF && p_wkhtmltopdf) || !p_wkhtmltopdf); QString templ = VNote::generateHtmlTemplate(g_config->getRenderBackgroundColor(p_renderBg), g_config->getCssStyleUrl(p_renderStyle), g_config->getCodeBlockCssStyleUrl(p_renderCodeBlockStyle), p_isPDF); return generateHtmlTemplate(templ, p_conType, p_isPDF, p_wkhtmltopdf, p_addToc); } QString VUtils::generateHtmlTemplate(const QString &p_template, MarkdownConverterType p_conType, bool p_isPDF, bool p_wkhtmltopdf, bool p_addToc) { bool mathjaxTypeSetOnLoad = true; QString jsFile, extraFile; switch (p_conType) { case MarkdownConverterType::Marked: jsFile = "qrc" + VNote::c_markedJsFile; extraFile = "<script src=\"qrc" + VNote::c_markedExtraFile + "\"></script>\n"; break; case MarkdownConverterType::Hoedown: jsFile = "qrc" + VNote::c_hoedownJsFile; // Use Marked to highlight code blocks. extraFile = "<script src=\"qrc" + VNote::c_markedExtraFile + "\"></script>\n"; break; case MarkdownConverterType::MarkdownIt: { jsFile = "qrc" + VNote::c_markdownitJsFile; extraFile = "<script src=\"qrc" + VNote::c_markdownitExtraFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_markdownitAnchorExtraFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_markdownitTaskListExtraFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_markdownitImsizeExtraFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_markdownitFootnoteExtraFile + "\"></script>\n"; if (g_config->getEnableMathjax()) { extraFile += "<script src=\"qrc" + VNote::c_markdownitTexMathExtraFile + "\"></script>\n"; } const MarkdownitOption &opt = g_config->getMarkdownitOption(); if (opt.m_sup) { extraFile += "<script src=\"qrc" + VNote::c_markdownitSupExtraFile + "\"></script>\n"; } if (opt.m_sub) { extraFile += "<script src=\"qrc" + VNote::c_markdownitSubExtraFile + "\"></script>\n"; } if (opt.m_metadata) { extraFile += "<script src=\"qrc" + VNote::c_markdownitFrontMatterExtraFile + "\"></script>\n"; } if (opt.m_emoji) { extraFile += "<script src=\"qrc" + VNote::c_markdownitEmojiExtraFile + "\"></script>\n"; } QString optJs = QString("<script>var VMarkdownitOption = {" "html: %1,\n" "breaks: %2,\n" "linkify: %3,\n" "sub: %4,\n" "sup: %5,\n" "metadata: %6,\n" "emoji: %7 };\n" "</script>\n") .arg(opt.m_html ? QStringLiteral("true") : QStringLiteral("false")) .arg(opt.m_breaks ? QStringLiteral("true") : QStringLiteral("false")) .arg(opt.m_linkify ? QStringLiteral("true") : QStringLiteral("false")) .arg(opt.m_sub ? QStringLiteral("true") : QStringLiteral("false")) .arg(opt.m_sup ? QStringLiteral("true") : QStringLiteral("false")) .arg(opt.m_metadata ? QStringLiteral("true") : QStringLiteral("false")) .arg(opt.m_emoji ? QStringLiteral("true") : QStringLiteral("false")); extraFile += optJs; mathjaxTypeSetOnLoad = false; break; } case MarkdownConverterType::Showdown: jsFile = "qrc" + VNote::c_showdownJsFile; extraFile = "<script src=\"qrc" + VNote::c_showdownExtraFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_showdownAnchorExtraFile + "\"></script>\n"; break; default: Q_ASSERT(false); } extraFile += "<script src=\"qrc" + VNote::c_turndownJsFile + "\"></script>\n"; extraFile += "<script src=\"qrc" + VNote::c_turndownGfmExtraFile + "\"></script>\n"; if (g_config->getEnableMermaid()) { extraFile += "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + g_config->getMermaidCssStyleUrl() + "\"/>\n" + "<script src=\"qrc" + VNote::c_mermaidApiJsFile + "\"></script>\n" + "<script>var VEnableMermaid = true;</script>\n"; } if (g_config->getEnableFlowchart()) { extraFile += "<script src=\"qrc" + VNote::c_raphaelJsFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_flowchartJsFile + "\"></script>\n" + "<script>var VEnableFlowchart = true;</script>\n"; } if (g_config->getEnableMathjax()) { QString mj = g_config->getMathjaxJavascript(); if (p_wkhtmltopdf) { // Chante MathJax to be rendered as SVG. // If rendered as HTML, it will make the font of <code> messy. QRegExp reg("(Mathjax\\.js\\?config=)\\S+", Qt::CaseInsensitive); mj.replace(reg, QString("\\1%1").arg("TeX-MML-AM_SVG")); } extraFile += "<script type=\"text/x-mathjax-config\">" "MathJax.Hub.Config({\n" " tex2jax: {inlineMath: [['$','$'], ['\\\\(','\\\\)']],\n" "processEscapes: true,\n" "processClass: \"tex2jax_process|language-mathjax|lang-mathjax\"},\n" " showProcessingMessages: false,\n" " skipStartupTypeset: " + QString("%1,\n").arg(mathjaxTypeSetOnLoad ? "false" : "true") + " TeX: {\n" " Macros: {\n" " bm: [\"\\\\boldsymbol{#1}\", 1]\n" " }\n" " },\n" " messageStyle: \"none\"});\n" "MathJax.Hub.Register.StartupHook(\"End\", function() { handleMathjaxReady(); });\n" "</script>\n" "<script type=\"text/javascript\" async src=\"" + mj + "\"></script>\n" + "<script>var VEnableMathjax = true;</script>\n"; if (p_wkhtmltopdf) { extraFile += "<script>var VRemoveMathjaxScript = true;</script>\n"; } } int plantUMLMode = g_config->getPlantUMLMode(); if (plantUMLMode != PlantUMLMode::DisablePlantUML) { if (plantUMLMode == PlantUMLMode::OnlinePlantUML) { extraFile += "<script type=\"text/javascript\" src=\"" + VNote::c_plantUMLJsFile + "\"></script>\n" + "<script type=\"text/javascript\" src=\"" + VNote::c_plantUMLZopfliJsFile + "\"></script>\n" + "<script>var VPlantUMLServer = '" + g_config->getPlantUMLServer() + "';</script>\n"; } extraFile += QString("<script>var VPlantUMLMode = %1;</script>\n").arg(plantUMLMode); QString format = p_isPDF ? "png" : "svg"; extraFile += QString("<script>var VPlantUMLFormat = '%1';</script>\n").arg(format); } if (g_config->getEnableGraphviz()) { extraFile += "<script>var VEnableGraphviz = true;</script>\n"; // If we use png, we need to specify proper font in the dot command to render // non-ASCII chars properly. // Hence we use svg format in both cases. QString format = p_isPDF ? "svg" : "svg"; extraFile += QString("<script>var VGraphvizFormat = '%1';</script>\n").arg(format); } if (g_config->getEnableImageCaption()) { extraFile += "<script>var VEnableImageCaption = true;</script>\n"; } if (g_config->getEnableCodeBlockLineNumber()) { extraFile += "<script src=\"qrc" + VNote::c_highlightjsLineNumberExtraFile + "\"></script>\n" + "<script>var VEnableHighlightLineNumber = true;</script>\n"; } if (g_config->getEnableFlashAnchor()) { extraFile += "<script>var VEnableFlashAnchor = true;</script>\n"; } if (p_addToc) { extraFile += "<script>var VAddTOC = true;</script>\n"; extraFile += "<style type=\"text/css\">\n" " @media print {\n" " .vnote-toc {\n" " page-break-after: always;\n" " }\n" " }\n" "</style>"; } extraFile += "<script>var VStylesToInline = '" + g_config->getStylesToInlineWhenCopied() + "';</script>\n"; #if defined(Q_OS_MACOS) || defined(Q_OS_MAC) extraFile += "<script>var VOS = 'mac';</script>\n"; #elif defined(Q_OS_WIN) extraFile += "<script>var VOS = 'win';</script>\n"; #else extraFile += "<script>var VOS = 'linux';</script>\n"; #endif QString htmlTemplate(p_template); htmlTemplate.replace(HtmlHolder::c_JSHolder, jsFile); if (!extraFile.isEmpty()) { htmlTemplate.replace(HtmlHolder::c_extraHolder, extraFile); } return htmlTemplate; } QString VUtils::generateExportHtmlTemplate(const QString &p_renderBg, bool p_includeMathJax, bool p_outlinePanel) { QString templ = VNote::generateExportHtmlTemplate(g_config->getRenderBackgroundColor(p_renderBg)); QString extra; if (p_includeMathJax) { extra += "<script type=\"text/x-mathjax-config\">\n" "MathJax.Hub.Config({\n" "showProcessingMessages: false,\n" "messageStyle: \"none\",\n" "SVG: {\n" "minScaleAdjust: 100,\n" "styles: {\n" /* FIXME: Using wkhtmltopdf, without 2em, the math formula will be very small. However, with 2em, if there are Chinese characters in it, the font will be a mess. */ #if defined(Q_OS_WIN) "\".MathJax_SVG\": {\n" "\"font-size\": \"2em !important\"\n" "}\n" #endif "}\n" "},\n" "TeX: {\n" " Macros: {\n" " bm: [\"\\\\boldsymbol{#1}\", 1]\n" " }\n" "}\n" "});\n" "</script>\n"; QString mj = g_config->getMathjaxJavascript(); // Chante MathJax to be rendered as SVG. QRegExp reg("(Mathjax\\.js\\?config=)\\S+", Qt::CaseInsensitive); mj.replace(reg, QString("\\1%1").arg("TeX-MML-AM_SVG")); extra += "<script type=\"text/javascript\" async src=\"" + mj + "\"></script>\n"; } if (p_outlinePanel) { const QString outlineCss(":/resources/export/outline.css"); QString css = VUtils::readFileFromDisk(outlineCss); if (!css.isEmpty()) { templ.replace(HtmlHolder::c_outlineStyleHolder, css); } const QString outlineJs(":/resources/export/outline.js"); QString js = VUtils::readFileFromDisk(outlineJs); extra += QString("<script type=\"text/javascript\">\n%1\n</script>\n").arg(js); } if (!extra.isEmpty()) { templ.replace(HtmlHolder::c_extraHolder, extra); } return templ; } QString VUtils::generateMathJaxPreviewTemplate() { QString mj = g_config->getMathjaxJavascript(); QString templ = VNote::generateMathJaxPreviewTemplate(); templ.replace(HtmlHolder::c_JSHolder, mj); QString extraFile; QString mathjaxScale = QString::number((int)(100 * VUtils::calculateScaleFactor())); /* // Mermaid. extraFile += "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + g_config->getMermaidCssStyleUrl() + "\"/>\n" + "<script src=\"qrc" + VNote::c_mermaidApiJsFile + "\"></script>\n"; */ // Flowchart. extraFile += "<script src=\"qrc" + VNote::c_raphaelJsFile + "\"></script>\n" + "<script src=\"qrc" + VNote::c_flowchartJsFile + "\"></script>\n"; // MathJax. extraFile += "<script type=\"text/x-mathjax-config\">" "MathJax.Hub.Config({\n" " tex2jax: {inlineMath: [['$','$'], ['\\\\(','\\\\)']],\n" "processEscapes: true,\n" "processClass: \"tex2jax_process|language-mathjax|lang-mathjax\"},\n" " \"HTML-CSS\": {\n" " scale: " + mathjaxScale + "\n" " },\n" " showProcessingMessages: false,\n" " TeX: {\n" " Macros: {\n" " bm: [\"\\\\boldsymbol{#1}\", 1]\n" " }\n" " },\n" " messageStyle: \"none\"});\n" "</script>\n"; // PlantUML. extraFile += "<script type=\"text/javascript\" src=\"" + VNote::c_plantUMLJsFile + "\"></script>\n" + "<script type=\"text/javascript\" src=\"" + VNote::c_plantUMLZopfliJsFile + "\"></script>\n" + "<script>var VPlantUMLServer = '" + g_config->getPlantUMLServer() + "';</script>\n"; templ.replace(HtmlHolder::c_extraHolder, extraFile); return templ; } QString VUtils::getFileNameWithSequence(const QString &p_directory, const QString &p_baseFileName, bool p_completeBaseName) { QDir dir(p_directory); if (!dir.exists() || !dir.exists(p_baseFileName)) { return p_baseFileName; } // Append a sequence. QFileInfo fi(p_baseFileName); QString baseName = p_completeBaseName ? fi.completeBaseName() : fi.baseName(); QString suffix = p_completeBaseName ? fi.suffix() : fi.completeSuffix(); int seq = 1; QString fileName; do { fileName = QString("%1_%2").arg(baseName).arg(QString::number(seq++), 3, '0'); if (!suffix.isEmpty()) { fileName = fileName + "." + suffix; } } while (fileExists(dir, fileName, true)); return fileName; } QString VUtils::getDirNameWithSequence(const QString &p_directory, const QString &p_baseDirName) { QDir dir(p_directory); if (!dir.exists() || !dir.exists(p_baseDirName)) { return p_baseDirName; } // Append a sequence. int seq = 1; QString fileName; do { fileName = QString("%1_%2").arg(p_baseDirName).arg(QString::number(seq++), 3, '0'); } while (fileExists(dir, fileName, true)); return fileName; } QString VUtils::getRandomFileName(const QString &p_directory) { Q_ASSERT(!p_directory.isEmpty()); QString baseName(QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz")); QDir dir(p_directory); QString name; do { name = baseName + '_' + QString::number(qrand()); } while (fileExists(dir, name, true)); return name; } bool VUtils::checkPathLegal(const QString &p_path) { // Ensure every part of the p_path is a valid file name until we come to // an existing parent directory. if (p_path.isEmpty()) { return false; } if (QFileInfo::exists(p_path)) { #if defined(Q_OS_WIN) // On Windows, "/" and ":" will also make exists() return true. if (p_path.startsWith('/') || p_path == ":") { return false; } #endif return true; } bool ret = false; int pos; QString basePath = basePathFromPath(p_path); QString fileName = fileNameFromPath(p_path); QValidator *validator = new QRegExpValidator(QRegExp(c_fileNameRegExp)); while (!fileName.isEmpty()) { QValidator::State validFile = validator->validate(fileName, pos); if (validFile != QValidator::Acceptable) { break; } if (QFileInfo::exists(basePath)) { ret = true; #if defined(Q_OS_WIN) // On Windows, "/" and ":" will also make exists() return true. if (basePath.startsWith('/') || basePath == ":") { ret = false; } #endif break; } fileName = fileNameFromPath(basePath); basePath = basePathFromPath(basePath); } delete validator; return ret; } bool VUtils::checkFileNameLegal(const QString &p_name) { if (p_name.isEmpty()) { return false; } QRegExp exp(c_fileNameRegExp); return exp.exactMatch(p_name); } bool VUtils::equalPath(const QString &p_patha, const QString &p_pathb) { QString a = QDir::cleanPath(p_patha); QString b = QDir::cleanPath(p_pathb); #if defined(Q_OS_WIN) a = a.toLower(); b = b.toLower(); #endif return a == b; } bool VUtils::splitPathInBasePath(const QString &p_base, const QString &p_path, QStringList &p_parts) { p_parts.clear(); QString a = QDir::cleanPath(p_base); QString b = QDir::cleanPath(p_path); #if defined(Q_OS_WIN) if (!b.toLower().startsWith(a.toLower())) { return false; } #else if (!b.startsWith(a)) { return false; } #endif if (a.size() == b.size()) { return true; } Q_ASSERT(a.size() < b.size()); if (b.at(a.size()) != '/') { return false; } p_parts = b.right(b.size() - a.size() - 1).split("/", QString::SkipEmptyParts); return true; } void VUtils::decodeUrl(QString &p_url) { QHash<QString, QString> maps; maps.insert("%20", " "); for (auto it = maps.begin(); it != maps.end(); ++it) { p_url.replace(it.key(), it.value()); } } QString VUtils::getShortcutText(const QString &p_keySeq) { return QKeySequence(p_keySeq).toString(QKeySequence::NativeText); } bool VUtils::deleteDirectory(const VNotebook *p_notebook, const QString &p_path, bool p_skipRecycleBin) { if (p_skipRecycleBin) { QDir dir(p_path); return dir.removeRecursively(); } else { // Move it to the recycle bin folder. return deleteFile(p_notebook->getRecycleBinFolderPath(), p_path); } } bool VUtils::deleteDirectory(const QString &p_path) { if (p_path.isEmpty()) { return true; } QDir dir(p_path); return dir.removeRecursively(); } bool VUtils::emptyDirectory(const VNotebook *p_notebook, const QString &p_path, bool p_skipRecycleBin) { QDir dir(p_path); if (!dir.exists()) { return true; } QFileInfoList nodes = dir.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); for (int i = 0; i < nodes.size(); ++i) { const QFileInfo &fileInfo = nodes.at(i); if (fileInfo.isDir()) { if (!deleteDirectory(p_notebook, fileInfo.absoluteFilePath(), p_skipRecycleBin)) { return false; } } else { Q_ASSERT(fileInfo.isFile()); if (!deleteFile(p_notebook, fileInfo.absoluteFilePath(), p_skipRecycleBin)) { return false; } } } return true; } bool VUtils::deleteFile(const VNotebook *p_notebook, const QString &p_path, bool p_skipRecycleBin) { if (p_skipRecycleBin) { QFile file(p_path); return file.remove(); } else { // Move it to the recycle bin folder. return deleteFile(p_notebook->getRecycleBinFolderPath(), p_path); } } bool VUtils::deleteFile(const QString &p_path) { QFile file(p_path); bool ret = file.remove(); if (ret) { qDebug() << "deleted file" << p_path; } else { qWarning() << "fail to delete file" << p_path; } return ret; } bool VUtils::deleteFile(const VOrphanFile *p_file, const QString &p_path, bool p_skipRecycleBin) { if (p_skipRecycleBin) { QFile file(p_path); return file.remove(); } else { // Move it to the recycle bin folder. return deleteFile(p_file->fetchRecycleBinFolderPath(), p_path); } } static QString getRecycleBinSubFolderToUse(const QString &p_folderPath) { QDir dir(p_folderPath); return QDir::cleanPath(dir.absoluteFilePath(QDateTime::currentDateTime().toString("yyyyMMdd"))); } bool VUtils::deleteFile(const QString &p_recycleBinFolderPath, const QString &p_path) { QString binPath = getRecycleBinSubFolderToUse(p_recycleBinFolderPath); QDir binDir(binPath); if (!binDir.exists()) { binDir.mkpath(binPath); if (!binDir.exists()) { return false; } } QString destName = getFileNameWithSequence(binPath, fileNameFromPath(p_path), true); qDebug() << "try to move" << p_path << "to" << binPath << "as" << destName; if (!binDir.rename(p_path, binDir.filePath(destName))) { qWarning() << "fail to move" << p_path << "to" << binDir.filePath(destName); return false; } return true; } QVector<VElementRegion> VUtils::fetchImageRegionsUsingParser(const QString &p_content) { Q_ASSERT(!p_content.isEmpty()); const QSharedPointer<PegParseConfig> parserConfig(new PegParseConfig()); parserConfig->m_data = p_content.toUtf8(); return PegParser::parseImageRegions(parserConfig); } QString VUtils::displayDateTime(const QDateTime &p_dateTime, bool p_uniformNum) { QString res = p_dateTime.date().toString(p_uniformNum ? Qt::ISODate : Qt::DefaultLocaleLongDate); res += " " + p_dateTime.time().toString(p_uniformNum ? Qt::ISODate : Qt::TextDate); return res; } bool VUtils::fileExists(const QDir &p_dir, const QString &p_name, bool p_forceCaseInsensitive) { if (!p_forceCaseInsensitive) { return p_dir.exists(p_name); } QString name = p_name.toLower(); QStringList names = p_dir.entryList(QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoSymLinks | QDir::NoDotAndDotDot); foreach (const QString &str, names) { if (str.toLower() == name) { return true; } } return false; } void VUtils::addErrMsg(QString *p_msg, const QString &p_str) { if (!p_msg) { return; } if (p_msg->isEmpty()) { *p_msg = p_str; } else { *p_msg = *p_msg + '\n' + p_str; } } QStringList VUtils::filterFilePathsToOpen(const QStringList &p_files) { QStringList paths; for (int i = 0; i < p_files.size(); ++i) { if (p_files[i].startsWith('-')) { continue; } QString path = validFilePathToOpen(p_files[i]); if (!path.isEmpty()) { paths.append(path); } } return paths; } QString VUtils::validFilePathToOpen(const QString &p_file) { if (QFileInfo::exists(p_file)) { QFileInfo fi(p_file); if (fi.isFile()) { // Need to use absolute path here since VNote may be launched // in different working directory. return QDir::cleanPath(fi.absoluteFilePath()); } } return QString(); } bool VUtils::isControlModifierForVim(int p_modifiers) { #if defined(Q_OS_MACOS) || defined(Q_OS_MAC) return p_modifiers == Qt::MetaModifier; #else return p_modifiers == Qt::ControlModifier; #endif } void VUtils::touchFile(const QString &p_file) { if (p_file.isEmpty()) { return; } QFile file(p_file); if (!file.open(QIODevice::WriteOnly)) { qWarning() << "fail to touch file" << p_file; return; } file.close(); } bool VUtils::isMetaKey(int p_key) { return p_key == Qt::Key_Control || p_key == Qt::Key_Shift || p_key == Qt::Key_Meta #if defined(Q_OS_LINUX) // For mapping Caps as Ctrl in KDE. || p_key == Qt::Key_CapsLock #endif || p_key == Qt::Key_Alt; } QComboBox *VUtils::getComboBox(QWidget *p_parent) { QComboBox *box = new QComboBox(p_parent); QStyledItemDelegate *itemDelegate = new QStyledItemDelegate(box); box->setItemDelegate(itemDelegate); return box; } void VUtils::setDynamicProperty(QWidget *p_widget, const char *p_prop, bool p_val) { p_widget->setProperty(p_prop, p_val); p_widget->style()->unpolish(p_widget); p_widget->style()->polish(p_widget); } QWebEngineView *VUtils::getWebEngineView(QWidget *p_parent) { QWebEngineView *viewer = new QWebEngineView(p_parent); VPreviewPage *page = new VPreviewPage(viewer); page->setBackgroundColor(Qt::transparent); viewer->setPage(page); viewer->setZoomFactor(g_config->getWebZoomFactor()); return viewer; } QString VUtils::getFileNameWithLocale(const QString &p_name, const QString &p_locale) { QString locale = p_locale.isEmpty() ? getLocale() : p_locale; locale = locale.split('_')[0]; QFileInfo fi(p_name); QString baseName = fi.completeBaseName(); QString suffix = fi.suffix(); if (suffix.isEmpty()) { return QString("%1_%2").arg(baseName).arg(locale); } else { return QString("%1_%2.%3").arg(baseName).arg(locale).arg(suffix); } } QString VUtils::getDocFile(const QString &p_name) { QDir dir(VNote::c_docFileFolder); QString name(getFileNameWithLocale(p_name)); if (!dir.exists(name)) { name = getFileNameWithLocale(p_name, "en_US"); } return dir.filePath(name); } QString VUtils::getCaptainShortcutSequenceText(const QString &p_operation) { QString capKey = g_config->getShortcutKeySequence("CaptainMode"); QString sec = g_config->getCaptainShortcutKeySequence(p_operation); QKeySequence seq(capKey + "," + sec); if (!seq.isEmpty()) { return seq.toString(QKeySequence::NativeText); } return QString(); } QString VUtils::getAvailableFontFamily(const QStringList &p_families) { QStringList availFamilies = QFontDatabase().families(); for (int i = 0; i < p_families.size(); ++i) { QString family = p_families[i].trimmed(); if (family.isEmpty()) { continue; } for (int j = 0; j < availFamilies.size(); ++j) { QString availFamily = availFamilies[j]; availFamily.remove(QRegExp("\\[.*\\]")); availFamily = availFamily.trimmed(); if (family == availFamily || family.toLower() == availFamily.toLower()) { qDebug() << "matched font family" << availFamilies[j]; return availFamilies[j]; } } } return QString(); } bool VUtils::fixTextWithShortcut(QAction *p_act, const QString &p_shortcut) { QString keySeq = g_config->getShortcutKeySequence(p_shortcut); if (!keySeq.isEmpty()) { p_act->setText(QString("%1\t%2").arg(p_act->text()).arg(VUtils::getShortcutText(keySeq))); return true; } return false; } bool VUtils::fixTextWithCaptainShortcut(QAction *p_act, const QString &p_shortcut) { QString keyText = VUtils::getCaptainShortcutSequenceText(p_shortcut); if (!keyText.isEmpty()) { p_act->setText(QString("%1\t%2").arg(p_act->text()).arg(keyText)); return true; } return false; } QStringList VUtils::parseCombinedArgString(const QString &p_program) { QStringList args; QString tmp; int quoteCount = 0; bool inQuote = false; // handle quoting. tokens can be surrounded by double quotes // "hello world". three consecutive double quotes represent // the quote character itself. for (int i = 0; i < p_program.size(); ++i) { if (p_program.at(i) == QLatin1Char('"')) { ++quoteCount; if (quoteCount == 3) { // third consecutive quote quoteCount = 0; tmp += p_program.at(i); } continue; } if (quoteCount) { if (quoteCount == 1) { inQuote = !inQuote; } quoteCount = 0; } if (!inQuote && p_program.at(i).isSpace()) { if (!tmp.isEmpty()) { args += tmp; tmp.clear(); } } else { tmp += p_program.at(i); } } if (!tmp.isEmpty()) { args += tmp; } return args; } QImage VUtils::imageFromFile(const QString &p_filePath) { QImage img; QFile file(p_filePath); if (!file.open(QIODevice::ReadOnly)) { qWarning() << "fail to open image file" << p_filePath; return img; } img.loadFromData(file.readAll()); qDebug() << "imageFromFile" << p_filePath << img.isNull() << img.format(); return img; } QPixmap VUtils::pixmapFromFile(const QString &p_filePath) { QPixmap pixmap; QFile file(p_filePath); if (!file.open(QIODevice::ReadOnly)) { qWarning() << "fail to open pixmap file" << p_filePath; return pixmap; } pixmap.loadFromData(file.readAll()); qDebug() << "pixmapFromFile" << p_filePath << pixmap.isNull(); return pixmap; } QFormLayout *VUtils::getFormLayout() { QFormLayout *layout = new QFormLayout(); #if defined(Q_OS_MACOS) || defined(Q_OS_MAC) layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); layout->setFormAlignment(Qt::AlignLeft | Qt::AlignTop); #endif return layout; } bool VUtils::inSameDrive(const QString &p_a, const QString &p_b) { #if defined(Q_OS_WIN) QChar sep(':'); int ai = p_a.indexOf(sep); int bi = p_b.indexOf(sep); if (ai == -1 || bi == -1) { return false; } return p_a.left(ai).toLower() == p_b.left(bi).toLower(); #else return true; #endif } QString VUtils::promptForFileName(const QString &p_title, const QString &p_label, const QString &p_default, const QString &p_dir, QWidget *p_parent) { QString name = p_default; QString text = p_label; QDir paDir(p_dir); while (true) { bool ok; name = QInputDialog::getText(p_parent, p_title, text, QLineEdit::Normal, name, &ok); if (!ok || name.isEmpty()) { return ""; } if (!VUtils::checkFileNameLegal(name)) { text = QObject::tr("Illegal name. Please try again:"); continue; } if (paDir.exists(name)) { text = QObject::tr("Name already exists. Please try again:"); continue; } break; } return name; } QString VUtils::promptForFileName(const QString &p_title, const QString &p_label, const QString &p_default, std::function<bool(const QString &p_name)> p_checkExistsFunc, QWidget *p_parent) { QString name = p_default; QString text = p_label; while (true) { bool ok; name = QInputDialog::getText(p_parent, p_title, text, QLineEdit::Normal, name, &ok); if (!ok || name.isEmpty()) { return ""; } if (!VUtils::checkFileNameLegal(name)) { text = QObject::tr("Illegal name. Please try again:"); continue; } if (p_checkExistsFunc(name)) { text = QObject::tr("Name already exists. Please try again:"); continue; } break; } return name; } bool VUtils::onlyHasImgInHtml(const QString &p_html) { // Tricky. QRegExp reg("<(?:p|span|div) "); return !p_html.contains(reg); } int VUtils::elapsedTime(bool p_reset) { static QTime tm; if (p_reset) { tm = QTime(); return 0; } if (tm.isNull()) { tm.start(); return 0; } return tm.restart(); } QPixmap VUtils::svgToPixmap(const QByteArray &p_content, const QString &p_background, qreal p_factor) { QSvgRenderer renderer(p_content); QSize deSz = renderer.defaultSize(); if (p_factor > 0) { deSz *= p_factor; } QPixmap pm(deSz); if (!p_background.isEmpty()) { pm.fill(p_background); } QPainter painter(&pm); renderer.render(&painter); return pm; } QString VUtils::fetchImageLinkUrlToPreview(const QString &p_text, int &p_width, int &p_height) { QRegExp regExp(VUtils::c_imageLinkRegExp); p_width = p_height = -1; int index = regExp.indexIn(p_text); if (index == -1) { return QString(); } int lastIndex = regExp.lastIndexIn(p_text); if (lastIndex != index) { return QString(); } QString tmp(regExp.cap(7)); if (!tmp.isEmpty()) { p_width = tmp.toInt(); if (p_width <= 0) { p_width = -1; } } tmp = regExp.cap(8); if (!tmp.isEmpty()) { p_height = tmp.toInt(); if (p_height <= 0) { p_height = -1; } } return regExp.cap(2).trimmed(); } QString VUtils::fetchImageLinkUrl(const QString &p_link) { QRegExp regExp(VUtils::c_imageLinkRegExp); int index = regExp.indexIn(p_link); if (index == -1) { return QString(); } return regExp.cap(2).trimmed(); } QString VUtils::fetchLinkUrl(const QString &p_link) { QRegExp regExp(VUtils::c_linkRegExp); int index = regExp.indexIn(p_link); if (index == -1) { return QString(); } return regExp.cap(2).trimmed(); } QUrl VUtils::pathToUrl(const QString &p_path) { QUrl url; if (QFileInfo::exists(p_path)) { url = QUrl::fromLocalFile(p_path); } else { url = QUrl(p_path); } return url; } QString VUtils::parentDirName(const QString &p_path) { if (p_path.isEmpty()) { return p_path; } return QFileInfo(p_path).dir().dirName(); } QString VUtils::purifyUrl(const QString &p_url) { int idx = p_url.indexOf('?'); if (idx > -1) { return p_url.left(idx); } return p_url; } // Suffix size for QTemporaryFile. #define MAX_SIZE_SUFFIX_FOR_TEMP_FILE 10 QTemporaryFile *VUtils::createTemporaryFile(QString p_suffix) { if (p_suffix.size() > MAX_SIZE_SUFFIX_FOR_TEMP_FILE) { p_suffix.clear(); } QString xx = p_suffix.isEmpty() ? "XXXXXX" : "XXXXXX."; return new QTemporaryFile(QDir::tempPath() + QDir::separator() + xx + p_suffix); } QString VUtils::purifyImageTitle(QString p_title) { return p_title.remove(QRegExp("[\\r\\n\\[\\]]")); } QString VUtils::escapeHtml(QString p_text) { p_text.replace(">", "&gt;").replace("<", "&lt;").replace("&", "&amp;"); return p_text; }
[ "tamlokveer@gmail.com" ]
tamlokveer@gmail.com
5238b176d173af0bcc857dafa1fcfa407a96431a
f0244768e887b137edf30451e77d48d7f1a4d781
/프로그래머스/Level_2/30.cpp
331afbedd6769a993decb39ab023feed6f2dbe7a
[]
no_license
firstep710/coding-test
269f090fc53cbaa52cc24109d7bfc87eb8757ecb
e8d5a7aadc559e7b06796d42829c7c449a292cdf
refs/heads/main
2023-06-28T10:59:44.897231
2021-08-03T20:45:22
2021-08-03T20:45:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
570
cpp
#include <string> #include <vector> using namespace std; int solution(int n) { int answer = 0; int countOfN = 0; int temp = n; while(temp > 0) { if (temp % 2 == 1) countOfN++; temp /= 2; } while(true) { int count = 0; temp = ++n; while(temp > 0) { if (temp % 2 == 1) count++; temp /= 2; } if (countOfN == count) break; } answer = n; return answer; }
[ "lobreamer@daum.net" ]
lobreamer@daum.net
d7d2471db1cd457999fab80f686a5d826184a603
f2e48c4bdec58b01693bae46635e9ce0065bb060
/Camera.cpp
5088a52ee720ebc40125ae8204e460f687aa9707
[]
no_license
alxklk/Bulleven
b048a754ac352b8c0b05d0d347f8dfff18a1b7c5
56745182e7db91e7ba247b6d249169917002cff7
refs/heads/master
2022-12-25T17:48:31.690517
2020-09-30T20:00:30
2020-09-30T20:00:30
298,680,656
0
0
null
null
null
null
UTF-8
C++
false
false
2,428
cpp
#include <cmath> #include "Camera.h" CCamera::CCamera(void) : m_FOV(1) , m_Pos(-0.01f, 0, 0.015f) , m_LookAt(0, 0, 0) , m_Near(.1) , m_Far(2000) , m_NeedUpdate(1) , crop0(-1, -1) , crop1(1, 1) , mode(CM_PROJ) , W(1024.0f) , H(768.0f) { } CCamera::~CCamera(void) { } void CCamera::Update() { if (!m_NeedUpdate) return; m_U = float3(0, 0, 1); m_F = m_LookAt - m_Pos; m_F = vnorm(m_F); m_R = vcross(m_F, m_U); m_R = vnorm(m_R); m_U = vcross(m_R, m_F); m_U = vnorm(m_U); m_NeedUpdate = 0; } void CCamera::CalcVPM(bool overkil) { Update(); float4x4 M; M.Identity(); M.m[0][0] = m_R.x; M.m[0][1] = m_U.x; M.m[0][2] = m_F.x; M.m[1][0] = m_R.y; M.m[1][1] = m_U.y; M.m[1][2] = m_F.y; M.m[2][0] = m_R.z; M.m[2][1] = m_U.z; M.m[2][2] = m_F.z; if (overkil) { M.m[0][1] = -M.m[0][1]; M.m[1][1] = -M.m[1][1]; M.m[2][1] = -M.m[2][1]; } M.m[3][0] = -vdot(m_R, m_Pos); M.m[3][1] = -vdot(m_U, m_Pos); M.m[3][2] = -vdot(m_F, m_Pos); float4x4 l_PM; if (mode == CM_PROJ) { l_PM.Projection((float)m_Near, (float)m_Far, (float)m_FOV, (float)(m_FOV * H / W)); } else { float3 dir = m_Pos; dir -= m_LookAt; float len = vlen(dir); } PM = l_PM; VM = M; VPM = M * l_PM; VPMT = VPM; VPMT.Transpose(); IVPM = VPM; IVPM.Inverse(); }; void CCamera::Forward(float i_Dist) { Update(); float3 F = m_F * i_Dist; m_LookAt += F; m_Pos += F; m_NeedUpdate = 1; } void CCamera::Zoom(float i_Prc) { Update(); float3 F = (m_LookAt - m_Pos) * (1 + i_Prc); m_Pos = m_LookAt - F; m_NeedUpdate = 1; } void CCamera::Right(float i_Dist) { Update(); float3 R = m_R * i_Dist; m_LookAt += R; m_Pos += R; m_NeedUpdate = 1; } void CCamera::Up(float i_Dist) { Update(); float3 R = m_U * i_Dist; m_LookAt += R; m_Pos += R; m_NeedUpdate = 1; } void CCamera::Translate(const float3& i_D) { Update(); m_Pos += i_D; m_LookAt += i_D; m_NeedUpdate = 1; } void CCamera::Rotate(float i_Yaw, float i_Pitch) { Update(); float3 l_Dir = m_LookAt - m_Pos; float ly = l_Dir.z; float lx = sqrt(l_Dir.x * l_Dir.x + l_Dir.y * l_Dir.y); float lx1 = lx; l_Dir.z = cos(i_Pitch) * ly + lx * sin(i_Pitch); lx = -sin(i_Pitch) * ly + lx * cos(i_Pitch); lx /= lx1; l_Dir.x *= lx; l_Dir.y *= lx; float4x4 l_TM; l_TM.Identity(); float4x4 l_RY; l_RY.RotationZ(sin(i_Yaw), cos(i_Yaw)); l_TM *= l_RY; float3 l_TV = l_Dir * l_TM; m_Pos = m_LookAt - float3(l_TV); m_NeedUpdate = 1; }
[ "klkspa@ukr.net" ]
klkspa@ukr.net
372c4320a5d6203065006c6b7ac26664b731dbce
6d66954fdc6777c0460e0e0269238215304cd6dd
/diger/Digger/src/Creature.cpp
edc5d27d8581235c31ceabc81613463500d5f9af
[]
no_license
eitanshalev/Digger
3ebbbcdd68a4c183596f80f4e0ac0d6640af3659
e3a9305c4d404aa1b4b18bfcb9f121271e82506d
refs/heads/main
2022-12-27T19:31:08.931472
2020-10-13T21:07:32
2020-10-13T21:07:32
301,988,974
2
0
null
null
null
null
UTF-8
C++
false
false
948
cpp
#include "Creature.h" Creature::Creature(sf::Vector2f& location, sf::Texture* texture, int width, int height) : Entity(location, texture, width, height) { m_sprite = getSprite(); animation(DOWN, m_sprite); m_sprite.scale(2.9, 2.9); setSprite(m_sprite); } void Creature::setLastLocation(sf::Vector2f lastLocation) { prevLocation = lastLocation; } void Creature::animation(enum Direction way,sf::Sprite & sprite) { m_source.y = way; animationCounter += clock.restart().asMilliseconds(); if (animationCounter >= animationFrameDuration) { animationCounter -= animationFrameDuration; m_source.x++; } if (m_source.x * SPRITE_SHEET_SIZE >= SPRITE_SHEET_SIZE * 3) m_source.x = 0; sprite.setTextureRect(sf::IntRect(m_source.x * SPRITE_SHEET_SIZE, m_source.y * SPRITE_SHEET_SIZE, SPRITE_SHEET_SIZE, SPRITE_SHEET_SIZE)); sprite.setOrigin(sprite.getLocalBounds().width / 2, sprite.getLocalBounds().height / 2); setSprite(sprite); }
[ "eitans1111@gmail.com" ]
eitans1111@gmail.com
f20c37a63487aeed057bc01d271ceab5f330fc7d
bd838116db143a926b5512a68b23237711076718
/chapter1/lesson1_13/1_13.cpp
a400fa95e62d4c7a49bec66aca0ce18c7b5377d3
[]
no_license
MUCb/The-C-Programming-Language
0343f975a43395069492298435ed6361d5988168
16fd18191365acb36d1a511934001802b173c72d
refs/heads/master
2021-01-11T03:20:18.769940
2016-10-16T11:54:01
2016-10-16T11:54:01
71,046,990
0
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
#include<stdio.h> #define IN 1 #define OUT 0 void main(){ int i, c, count, flag; flag=IN; count=0; while((c=getchar()) != EOF){ if(c == '\n' || c == '\t' || c == ' '){ flag = OUT; for (int i = 0; i < count; ++i) printf("#"); printf("\n"); count=0; } else if(flag == OUT){ flag = IN; ++count; } else { ++count; } } }
[ "vitalik560@yandex.ru" ]
vitalik560@yandex.ru
c1ef08056e9265285e5c827b9a97d239942106f7
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/test/protocols/jd3/StandardJobQueen.cxxtest.hh
73fe17062a981ad8108332ec723f8621deb61aa7
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
38,781
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file test/protocols/jd3/StandardJobQueen.cxxtest.hh /// @brief test suite for the StandardJobQueen /// @author Andrew Leaver-Fay (aleaverfay@gmail.com) /// @author Jared Adolf-Bryfogle (jadolfbr@gmail.com); Refactoring // Test headers #include <cxxtest/TestSuite.h> #include <test/core/init_util.hh> // Unit headers #include <protocols/jd3/standard/StandardJobQueen.hh> // Package headers #include <protocols/jd3/JobQueen.hh> #include <protocols/jd3/JobDigraph.hh> #include <protocols/jd3/LarvalJob.hh> #include <protocols/jd3/InnerLarvalJob.hh> #include <protocols/jd3/pose_inputters/PoseInputSource.hh> #include <protocols/jd3/deallocation/InputPoseDeallocationMessage.hh> #include <protocols/jd3/pose_inputters/PDBPoseInputter.hh> #include <protocols/jd3/pose_outputters/PDBPoseOutputter.hh> #include <protocols/jd3/standard/PreliminaryLarvalJobTracker.hh> #include <protocols/jd3/standard/PreliminaryLarvalJob.hh> #include <protocols/jd3/JobTracker.hh> // basic headers #include <basic/options/option.hh> // Utility headers #include <utility/string_util.hh> #include <utility/options/OptionCollection.hh> #include <utility/options/keys/OptionKey.hh> #include <utility/options/keys/BooleanOptionKey.hh> #include <utility/options/keys/StringOptionKey.hh> #include <utility/excn/Exceptions.hh> #include <utility/tag/Tag.hh> #include <utility/tag/XMLSchemaGeneration.hh> #include <utility/string_util.hh> // Boost headers #include <boost/bind.hpp> #include <boost/function.hpp> // C++ headers #include <sstream> using namespace utility::tag; using namespace protocols::jd3; using namespace protocols::jd3::standard; using namespace protocols::jd3::pose_inputters; //local options namespace basic { namespace options { namespace OptionKeys { basic::options::BooleanOptionKey const bool_arg1("bool_arg1"); basic::options::BooleanOptionKey const bool_arg2("bool_arg2"); basic::options::BooleanOptionKey const bool_arg3("bool_arg3"); basic::options::BooleanOptionKey const bool_arg_sjq_does_not_track("bool_arg_sjq_does_not_track"); basic::options::StringOptionKey const string_arg1("string_arg1"); basic::options::StringOptionKey const string_arg2("string_arg2"); basic::options::StringOptionKey const string_arg_w_default("string_arg_w_default"); basic::options::StringOptionKey const string_arg_sjq_does_not_track("string_arg_sjq_does_not_track"); namespace dummy_jq { basic::options::BooleanOptionKey const bool_arg4("dummy_jq:bool_arg4"); } utility::options::IntegerVectorOptionKey const intvect_arg1("intvect_arg1"); }}}//basic::options::OptionKeys class DummyJobQueen : public StandardJobQueen { public: typedef StandardJobQueen parent; using parent::note_job_completed; public: DummyJobQueen() { utility::options::OptionKeyList opts; add_options( opts ); add_option( basic::options::OptionKeys::bool_arg1 ); add_option( basic::options::OptionKeys::bool_arg2 ); add_option( basic::options::OptionKeys::bool_arg3 ); add_option( basic::options::OptionKeys::string_arg1 ); add_option( basic::options::OptionKeys::string_arg2 ); add_option( basic::options::OptionKeys::string_arg_w_default ); add_option( basic::options::OptionKeys::dummy_jq::bool_arg4 ); add_option( basic::options::OptionKeys::intvect_arg1 ); } ~DummyJobQueen() {} void append_job_tag_subelements( utility::tag::XMLSchemaDefinition & job_definition_xsd, utility::tag::XMLSchemaComplexTypeGenerator & job_ct_gen ) const override { if ( append_job_tag_subelements_ ) { append_job_tag_subelements_( job_definition_xsd, job_ct_gen ); } } void append_common_tag_subelements( utility::tag::XMLSchemaDefinition & job_definition_xsd, utility::tag::XMLSchemaComplexTypeGenerator & ct_gen ) const override { if ( append_common_tag_subelements_ ) { append_common_tag_subelements_( job_definition_xsd, ct_gen ); } } protocols::jd3::JobOP complete_larval_job_maturation( protocols::jd3::LarvalJobCOP larval_job, utility::options::OptionCollectionCOP job_options, utility::vector1< JobResultCOP > const & ) override { if ( complete_job_maturation_ ) { complete_job_maturation_( larval_job, job_options ); } return protocols::jd3::JobOP(); } //virtual bool has_job_completed( protocols::jd3::LarvalJobCOP job ) { return pose_outputter_for_job( *job->inner_job() )->job_has_already_completed( *job ); } void note_job_completed( protocols::jd3::LarvalJobCOP job, protocols::jd3::JobStatus status, core::Size nresults ) override { StandardJobQueen::note_job_completed( job, status, nresults ); } //void completed_job_result( protocols::jd3::LarvalJobCOP /*job*/, core::Size, protocols::jd3::JobResultOP /*result*/ ) override {}s //numeric::DiscreteIntervalEncodingTree< core::Size > const & completed_jobs() const { return parent::completed_jobs();} //numeric::DiscreteIntervalEncodingTree< core::Size > const & successful_jobs() const { return parent::successful_jobs();} //numeric::DiscreteIntervalEncodingTree< core::Size > const & failed_jobs() const { return parent::failed_jobs();} //numeric::DiscreteIntervalEncodingTree< core::Size > const & output_jobs() const { return parent::processed_jobs();} public: //Public wrappers for protected functions to aid in testing using parent::get_preliminary_larval_jobs_determined; using parent::get_prelim_larval_job_tracker; using parent::get_job_graph; using parent::get_preliminary_larval_jobs; using parent::get_job_tracker; public: // callbacks typedef boost::function< void ( protocols::jd3::LarvalJobCOP, utility::options::OptionCollectionCOP ) > CompleteJobMaturationCallback; CompleteJobMaturationCallback complete_job_maturation_; typedef boost::function< void ( utility::tag::XMLSchemaDefinition & xsd, utility::tag::XMLSchemaComplexTypeGenerator & ctgen ) > SubtagAppenderCallback; SubtagAppenderCallback append_job_tag_subelements_; SubtagAppenderCallback append_common_tag_subelements_; }; class StandardJobQueenTests : public CxxTest::TestSuite { public: StandardJobQueenTests() : local_options_added_( false ) {} void setUp() { if ( ! local_options_added_ ) { using namespace basic::options; option.add( OptionKeys::bool_arg1, "" ).def(false); option.add( OptionKeys::bool_arg2, "" ).def(false); option.add( OptionKeys::bool_arg3, "" ).def(true); option.add( OptionKeys::bool_arg_sjq_does_not_track, "" ).def(false); option.add( OptionKeys::string_arg1, "" ); option.add( OptionKeys::string_arg2, "" ); option.add( OptionKeys::string_arg_sjq_does_not_track, "" ); option.add( OptionKeys::string_arg_w_default, "" ).def("fiddlesticks"); option.add( OptionKeys::dummy_jq::bool_arg4, "" ).def(false); option.add( OptionKeys::intvect_arg1, "" ); local_options_added_ = true; } } void test_job_options_initialization() { core_init_with_additional_options( "-bool_arg1 -bool_arg_sjq_does_not_track -string_arg1 wakka_wakka_wakka -string_arg_sjq_does_not_track yippie -s 1ubq.pdb -intvect_arg1 1 2 3 4 5" ); DummyJobQueen djq; djq.create_and_set_initial_job_dag(); // no need to hold the DAG returned by this func, but it must be called //TS_ASSERT( ); LarvalJobs jobs = djq.determine_job_list( 1, 1000 ); TS_ASSERT( ! jobs.empty() ); TS_ASSERT( djq.get_preliminary_larval_jobs_determined()); if ( jobs.empty() ) return; djq.complete_job_maturation_ = boost::bind( StandardJobQueenTests::callback_complete_larval_job_maturation1, _1, _2 ); utility::vector1< JobResultOP > empty_vector; djq.mature_larval_job( jobs.front(), empty_vector ); // invokes callback_complete_larval_job_maturation1 } static void callback_complete_larval_job_maturation1( protocols::jd3::LarvalJobCOP larval_job, utility::options::OptionCollectionCOP job_options_ptr ) { using namespace basic::options::OptionKeys; TS_ASSERT_EQUALS( larval_job->inner_job()->n_input_sources(), 1 ); TS_ASSERT_EQUALS( larval_job->inner_job()->input_source().origin(), pose_inputters::PDBPoseInputter::keyname() ); TS_ASSERT_EQUALS( larval_job->inner_job()->input_source().input_tag(), "1ubq" ); TS_ASSERT_EQUALS( larval_job->inner_job()->job_tag(), "1ubq" ); TS_ASSERT( job_options_ptr ); utility::options::OptionCollection const & job_options( * job_options_ptr ); TS_ASSERT( job_options[ bool_arg1 ].user() ); TS_ASSERT( ! job_options[ bool_arg2 ].user() ); TS_ASSERT( ! job_options[ bool_arg3 ].user() ); TS_ASSERT( job_options[ bool_arg1 ].active() ); TS_ASSERT( job_options[ bool_arg2 ].active() ); TS_ASSERT( job_options[ bool_arg3 ].active() ); TS_ASSERT( job_options[ bool_arg1 ] ); TS_ASSERT( ! job_options[ bool_arg2 ] ); TS_ASSERT( job_options[ bool_arg3 ] ); TS_ASSERT( job_options[ string_arg1 ].user() ); TS_ASSERT( ! job_options[ string_arg2 ].user() ); TS_ASSERT( ! job_options[ string_arg_w_default ].user() ); TS_ASSERT( job_options[ string_arg1 ].active() ); TS_ASSERT( ! job_options[ string_arg2 ].active() ); TS_ASSERT( job_options[ string_arg_w_default ].active() ); TS_ASSERT( job_options[ string_arg1 ]() == "wakka_wakka_wakka" ); TS_ASSERT( ! job_options.has( bool_arg_sjq_does_not_track ) ); TS_ASSERT( ! job_options.has( string_arg_sjq_does_not_track ) ); TS_ASSERT( job_options[ intvect_arg1 ].user() ); TS_ASSERT( job_options[ intvect_arg1 ].active() ); utility::vector1< int > intvect_arg1_expected( 5 ); intvect_arg1_expected[ 1 ] = 1; intvect_arg1_expected[ 2 ] = 2; intvect_arg1_expected[ 3 ] = 3; intvect_arg1_expected[ 4 ] = 4; intvect_arg1_expected[ 5 ] = 5; } // Test that having two subelements of the SecondaryOutput tag in a Job definition // is ok. static void callback_complete_larval_job_maturation2( protocols::jd3::LarvalJobCOP larval_job, utility::options::OptionCollectionCOP ) { using namespace basic::options::OptionKeys; TS_ASSERT_EQUALS( larval_job->inner_job()->n_input_sources(), 1 ); TS_ASSERT_EQUALS( larval_job->inner_job()->input_source().origin(), pose_inputters::PDBPoseInputter::keyname() ); TS_ASSERT_EQUALS( larval_job->inner_job()->input_source().input_tag(), "1ubq" ); TS_ASSERT_EQUALS( larval_job->inner_job()->job_tag(), "1ubq" ); TS_ASSERT( larval_job->inner_job()->jobdef_tag() ); if ( ! larval_job->inner_job()->jobdef_tag() ) return; utility::tag::TagCOP job_tag = larval_job->inner_job()->jobdef_tag(); TS_ASSERT( job_tag->hasTag( "SecondaryOutput" ) ); if ( ! job_tag->hasTag( "SecondaryOutput" ) ) return; utility::tag::TagCOP secondary_output_tag = job_tag->getTag( "SecondaryOutput" ); TS_ASSERT_EQUALS( secondary_output_tag->getTags().size(), 2 ); if ( secondary_output_tag->getTags().size() != 2 ) return; for ( core::Size ii = 0; ii < 2; ++ii ) { TS_ASSERT_EQUALS( secondary_output_tag->getTags()[ii]->getName(), "ScoreFile" ); } } bool tag_has_subtag_w_name( TagCOP tag, std::string const & tag_name, std::string const & name_attribute ) { for ( auto const & subtag : tag->getTags() ) { if ( subtag->getName() != tag_name ) continue; if ( subtag->hasOption( "name" ) ) { if ( subtag->getOption< std::string >( "name" ) == name_attribute ) { return true; } } } return false; } TagCOP subtag_w_name( TagCOP tag, std::string const & tag_name, std::string const & name_attribute ) { for ( auto const & subtag : tag->getTags() ) { if ( subtag->getName() != tag_name ) continue; if ( subtag->hasOption( "name" ) ) { if ( subtag->getOption< std::string >( "name" ) == name_attribute ) { return subtag; } } } return TagCOP(); } void test_job_definition_file_xsd() { core_init(); DummyJobQueen djq; djq.append_job_tag_subelements_ = boost::bind( StandardJobQueenTests::job_tag_xsd1, _1, _2 ); std::string job_def_xsd = djq.job_definition_xsd(); // now lets turn this into a Tag object and then make sure the Job tag has the definition it ought to //std::cout << "job def xsd:\n" << job_def_xsd << std::endl; TagCOP job_def_xsd_tag = Tag::create( job_def_xsd ); TS_ASSERT_EQUALS( job_def_xsd_tag->getName(), std::string( "xs:schema" ) ); TS_ASSERT( tag_has_subtag_w_name( job_def_xsd_tag, "xs:complexType", "job_def_Job_type" )); TS_ASSERT( tag_has_subtag_w_name( job_def_xsd_tag, "xs:complexType", "job_def_Options_type" )); TagCOP options_type_tag = subtag_w_name( job_def_xsd_tag, "xs:complexType", "job_def_Options_type" ); if ( ! options_type_tag ) return; TS_ASSERT( options_type_tag->hasTag( "xs:all" )); TagCOP options_type_xs_all = options_type_tag->getTag( "xs:all" ); if ( ! options_type_xs_all ) return; TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "bool_arg1" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "bool_arg2" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "bool_arg3" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "string_arg1" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "string_arg2" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "string_arg_w_default" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "dummy_jq__bool_arg4" )); TS_ASSERT( tag_has_subtag_w_name( options_type_xs_all, "xs:element", "intvect_arg1" )); } static void job_tag_xsd1( utility::tag::XMLSchemaDefinition &, utility::tag::XMLSchemaComplexTypeGenerator & ctgen ) { using namespace utility::tag; AttributeList attributes; attributes + XMLSchemaAttribute( "foo", xs_string , "" ) + XMLSchemaAttribute( "bar", xs_integer , "" ); XMLSchemaSimpleSubelementList subelements; subelements.add_simple_subelement( "Hoo", attributes, "There once was a" ).add_simple_subelement( "Ville", attributes, "grinch" ); ctgen.add_ordered_subelement_set_as_pick_one( subelements ); } void test_read_jobs_from_xml_file() { std::string jobdef_file = "<JobDefinitionFile>\n" " <Job>\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " <Options>\n" " <bool_arg1/>\n" " <string_arg1 value=\"wakka_wakka_wakka\"/>\n" " <intvect_arg1 value=\"1 2 3 4 5\"/>\n" " </Options>\n" " </Job>\n" "</JobDefinitionFile>\n"; core_init(); // all options passed through job-definition file DummyJobQueen djq; try { djq.determine_preliminary_job_list_from_xml_file( jobdef_file ); } catch (utility::excn::Exception & e ) { std::cout << e.msg() << std::endl; TS_ASSERT( false ); } djq.create_and_set_initial_job_dag(); // no need to hold the DAG returned by this func, but it must be called LarvalJobs jobs = djq.determine_job_list( 1, 1000 ); utility::vector1< JobResultOP > empty_vector; djq.complete_job_maturation_ = boost::bind( StandardJobQueenTests::callback_complete_larval_job_maturation1, _1, _2 ); djq.mature_larval_job( jobs.front(), empty_vector ); // invokes callback_complete_larval_job_maturation1 } // Ensure that a job may use multiple SecondaryOutputters void test_read_jobs_from_xml_file2() { std::string jobdef_file = "<JobDefinitionFile>\n" " <Job>\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " <SecondaryOutput>\n" " <ScoreFile filename=\"score1.sc\"/>\n" " <ScoreFile filename=\"score2.sc\"/>\n" " </SecondaryOutput>\n" " </Job>\n" "</JobDefinitionFile>\n"; core_init(); // all options passed through job-definition file DummyJobQueen djq; try { djq.determine_preliminary_job_list_from_xml_file( jobdef_file ); } catch (utility::excn::Exception & e ) { std::cout << e.msg() << std::endl; TS_ASSERT( false ); } djq.create_and_set_initial_job_dag(); // no need to hold the DAG returned by this func, but it must be called JobDigraph const & job_graph = djq.get_job_graph(); TS_ASSERT_EQUALS( job_graph.num_nodes(), 1); LarvalJobs jobs = djq.determine_job_list( 1, 1000 ); utility::vector1< JobResultOP > empty_vector; djq.complete_job_maturation_ = boost::bind( StandardJobQueenTests::callback_complete_larval_job_maturation2, _1, _2 ); djq.mature_larval_job( jobs.front(), empty_vector ); // invokes callback_complete_larval_job_maturation2 } void test_preliminary_job_node_job_index_ranges() { std::string jobdef_file = "<JobDefinitionFile>\n" " <Job nstruct=\"5\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" " <Job nstruct=\"11\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" " <Job nstruct=\"3\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" "</JobDefinitionFile>\n"; core_init(); // all options passed through job-definition file DummyJobQueen djq; try { djq.determine_preliminary_job_list_from_xml_file( jobdef_file ); } catch (utility::excn::Exception & e ) { std::cout << e.msg() << std::endl; TS_ASSERT( false ); } JobDigraphOP dag = djq.create_and_set_initial_job_dag(); TS_ASSERT_EQUALS( dag->num_nodes(), 3 ); TS_ASSERT_EQUALS( dag->num_edges(), 0 ); std::string node_label ="T1"; for ( core::Size i = 1; i <= 3; ++i ) { dag->get_job_node(i)->set_node_label(node_label); } TS_ASSERT_EQUALS( dag->get_job_node(1)->get_node_label(), "T1"); TS_ASSERT_EQUALS( dag->get_job_node(2)->get_node_label(), "T1"); TS_ASSERT_EQUALS( dag->get_job_node(3)->get_node_label(), "T1"); JobDigraph const & job_graph = djq.get_job_graph(); TS_ASSERT_EQUALS( job_graph.num_nodes(), 3); TS_ASSERT_EQUALS( job_graph.num_edges(), 0); PreliminaryLarvalJobTracker & prelim_tracker = djq.get_prelim_larval_job_tracker(); utility::vector1< core::Size > prelim_nodes( 3 ); for ( core::Size ii = 1; ii <= 3; ++ii ) prelim_nodes[ ii ] = ii; TS_ASSERT_EQUALS( prelim_tracker.get_preliminary_job_node_indices(), prelim_nodes ); LarvalJobs jobs = djq.determine_job_list_and_track( 1, 4 ); prelim_tracker = djq.get_prelim_larval_job_tracker(); TS_ASSERT_EQUALS( jobs.size(), 4 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 1 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 2 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 3 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 1 ), 1 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 1 ), 4 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 2 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 2 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 3 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 3 ), 0 ); JobTracker & tracker = djq.get_job_tracker(); TS_ASSERT_EQUALS( tracker.last_job_for_input_source_id(1), 4); TS_ASSERT( tracker.started_jobs_for_node(1).member(1)); TS_ASSERT( tracker.started_jobs_for_node(1).member(2)); TS_ASSERT( tracker.started_jobs_for_node(1).member(3)); TS_ASSERT( tracker.started_jobs_for_node(1).member(4)); TS_ASSERT( tracker.started_jobs().member(1)); TS_ASSERT( tracker.started_jobs().member(2)); TS_ASSERT( tracker.started_jobs().member(3)); TS_ASSERT( tracker.started_jobs().member(4)); utility::vector1< LarvalJobOP > jobs_vector( jobs.size() ); std::copy( jobs.begin(), jobs.end(), jobs_vector.begin() ); djq.note_job_completed_and_track( jobs_vector[ 1 ], jd3_job_status_success, 1 ); djq.note_job_completed_and_track( jobs_vector[ 2 ], jd3_job_status_success, 1 ); djq.note_job_completed_and_track( jobs_vector[ 3 ], jd3_job_status_success, 1 ); djq.note_job_completed_and_track( jobs_vector[ 4 ], jd3_job_status_failed_max_retries, 0 ); tracker = djq.get_job_tracker(); TS_ASSERT( tracker.completed_jobs().member( 1 ) ); TS_ASSERT( tracker.completed_jobs().member( 2 ) ); TS_ASSERT( tracker.completed_jobs().member( 3 ) ); TS_ASSERT( tracker.completed_jobs().member( 4 ) ); TS_ASSERT( tracker.successful_jobs().member( 1 ) ); TS_ASSERT( tracker.successful_jobs().member( 2 ) ); TS_ASSERT( tracker.successful_jobs().member( 3 ) ); TS_ASSERT( ! tracker.successful_jobs().member( 4 ) ); TS_ASSERT( ! tracker.failed_jobs().member( 1 ) ); TS_ASSERT( ! tracker.failed_jobs().member( 2 ) ); TS_ASSERT( ! tracker.failed_jobs().member( 3 ) ); TS_ASSERT( tracker.failed_jobs().member( 4 ) ); TS_ASSERT( tracker.completed_jobs_for_node(1).member(1)); TS_ASSERT( tracker.completed_jobs_for_node(1).member(2)); TS_ASSERT( tracker.completed_jobs_for_node(1).member(3)); TS_ASSERT( tracker.completed_jobs_for_node(1).member(4)); jobs = djq.determine_job_list_and_track( 1, 4 ); prelim_tracker = djq.get_prelim_larval_job_tracker(); TS_ASSERT_EQUALS( jobs.size(), 1 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 1 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 2 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 3 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 1 ), 1 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node(1 ), 5 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 2 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 2 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 3 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 3 ), 0 ); TS_ASSERT_EQUALS( tracker.last_job_for_input_source_id(1), 5); TS_ASSERT( tracker.started_jobs_for_node(1).member(1)); TS_ASSERT( tracker.started_jobs_for_node(1).member(2)); TS_ASSERT( tracker.started_jobs_for_node(1).member(3)); TS_ASSERT( tracker.started_jobs_for_node(1).member(4)); TS_ASSERT( tracker.started_jobs_for_node(1).member(5)); TS_ASSERT( tracker.started_jobs().member(1)); TS_ASSERT( tracker.started_jobs().member(2)); TS_ASSERT( tracker.started_jobs().member(3)); TS_ASSERT( tracker.started_jobs().member(4)); TS_ASSERT( tracker.started_jobs().member(5)); TS_ASSERT( ! tracker.completed_jobs_for_node(1).member(5)); TS_ASSERT( ! tracker.completed_jobs_for_node(1).member(6)); TS_ASSERT( ! tracker.completed_jobs_for_node(1).member(7)); TS_ASSERT( ! tracker.completed_jobs_for_node(1).member(8)); jobs = djq.determine_job_list_and_track( 2, 6 ); prelim_tracker = djq.get_prelim_larval_job_tracker(); TS_ASSERT_EQUALS( jobs.size(), 6 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 1 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 2 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 3 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 1 ), 1 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 1 ), 5 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 2 ), 6 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 2 ), 11 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 3 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 3 ), 0 ); //Although they are the same input pose, since they are defined in Job, they are counted as separate poses. TS_ASSERT_EQUALS( tracker.last_job_for_input_source_id(2), 11); TS_ASSERT( tracker.started_jobs_for_node(2).member(6)); TS_ASSERT( tracker.started_jobs_for_node(2).member(7)); TS_ASSERT( tracker.started_jobs_for_node(2).member(8)); TS_ASSERT( tracker.started_jobs_for_node(2).member(9)); TS_ASSERT( tracker.started_jobs_for_node(2).member(10)); TS_ASSERT( tracker.started_jobs_for_node(2).member(11)); TS_ASSERT( tracker.started_jobs().member(6)); TS_ASSERT( tracker.started_jobs().member(7)); TS_ASSERT( tracker.started_jobs().member(8)); TS_ASSERT( tracker.started_jobs().member(9)); TS_ASSERT( tracker.started_jobs().member(10)); TS_ASSERT( tracker.started_jobs().member(11)); TS_ASSERT( tracker.started_jobs().member(6)); TS_ASSERT( tracker.started_jobs().member(7)); TS_ASSERT( tracker.started_jobs().member(8)); TS_ASSERT( tracker.started_jobs().member(9)); TS_ASSERT( tracker.started_jobs().member(10)); TS_ASSERT( tracker.started_jobs().member(11)); jobs = djq.determine_job_list_and_track( 2, 6 ); prelim_tracker = djq.get_prelim_larval_job_tracker(); TS_ASSERT_EQUALS( jobs.size(), 5 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 1 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 2 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 3 ), false ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 1 ), 1 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 1 ), 5 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 2 ), 6 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 2 ), 16 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 3 ), 0 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 3 ), 0 ); TS_ASSERT_EQUALS( tracker.last_job_for_input_source_id(2), 16); jobs = djq.determine_job_list_and_track( 3, 6 ); prelim_tracker = djq.get_prelim_larval_job_tracker(); TS_ASSERT_EQUALS( jobs.size(), 3 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 1 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 2 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_node_assigned( 3 ), true ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 1 ), 1 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 1 ), 5 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 2 ), 6 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 2 ), 16 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_starting_job_node( 3 ), 17 ); TS_ASSERT_EQUALS( prelim_tracker.get_job_index_ending_job_node( 3 ), 19 ); TS_ASSERT_EQUALS( tracker.last_job_for_input_source_id(3), 19); } void test_standard_job_queen_pose_deallocation_messages() { std::string jobdef_file = "<JobDefinitionFile>\n" " <Job nstruct=\"5\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" " <Job nstruct=\"11\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" " <Job nstruct=\"3\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" "</JobDefinitionFile>\n"; core_init(); // all options passed through job-definition file DummyJobQueen djq; try { djq.determine_preliminary_job_list_from_xml_file( jobdef_file ); } catch (utility::excn::Exception & e ) { std::cout << e.msg() << std::endl; TS_ASSERT( false ); } JobDigraphOP dag = djq.create_and_set_initial_job_dag(); TS_ASSERT_EQUALS( dag->num_nodes(), 3 ); TS_ASSERT_EQUALS( dag->num_edges(), 0 ); PreliminaryLarvalJobTracker const & prelim_tracker = djq.get_prelim_larval_job_tracker(); utility::vector1< core::Size > prelim_nodes( 3 ); for ( core::Size ii = 1; ii <= 3; ++ii ) prelim_nodes[ ii ] = ii; TS_ASSERT_EQUALS( prelim_tracker.get_preliminary_job_node_indices(), prelim_nodes ); LarvalJobs jobs = djq.determine_job_list( 1, 4 ); for ( LarvalJobOP node1_job : jobs ) { TS_ASSERT_EQUALS( node1_job->inner_job()->input_source().source_id(), 1 ); } std::list< deallocation::DeallocationMessageOP > msgs1 = djq.deallocation_messages(); TS_ASSERT( msgs1.empty() ); for ( LarvalJobOP node1_job : jobs ) { djq.note_job_completed_and_track( node1_job, jd3_job_status_success, 1 ); } LarvalJobs jobs2 = djq.determine_job_list( 1, 2 ); for ( LarvalJobOP node1_job : jobs2 ) { TS_ASSERT_EQUALS( node1_job->inner_job()->input_source().source_id(), 1 ); } std::list< deallocation::DeallocationMessageOP > msgs2 = djq.deallocation_messages(); TS_ASSERT( msgs2.empty() ); for ( LarvalJobOP node1_job : jobs2 ) { djq.note_job_completed_and_track( node1_job, jd3_job_status_success, 1 ); } LarvalJobs jobs3 = djq.determine_job_list( 2, 10 ); TS_ASSERT_EQUALS( jobs3.size(), 10 ); // After we tell the DJQ that all the jobs for node two have finished and // she has started assigning jobs for node2, then she will tell us that // it's ok to deallocate the input pose for node 1 std::list< deallocation::DeallocationMessageOP > msgs3 = djq.deallocation_messages(); TS_ASSERT_EQUALS( msgs3.size(), 1 ); typedef deallocation::InputPoseDeallocationMessage PoseDealloc; typedef deallocation::InputPoseDeallocationMessageOP PoseDeallocOP; PoseDeallocOP msg3 = utility::pointer::dynamic_pointer_cast< PoseDealloc > ( msgs3.front() ); TS_ASSERT( msg3 ); TS_ASSERT_EQUALS( msg3->pose_id(), 1 ); std::list< deallocation::DeallocationMessageOP > msgs4 = djq.deallocation_messages(); TS_ASSERT( msgs4.empty() ); for ( LarvalJobOP node2_job : jobs3 ) { djq.note_job_completed_and_track( node2_job, jd3_job_status_success, 1 ); } LarvalJobs jobs4 = djq.determine_job_list( 2, 10 ); TS_ASSERT_EQUALS( jobs4.size(), 1 ); std::list< deallocation::DeallocationMessageOP > msgs5 = djq.deallocation_messages(); TS_ASSERT( msgs5.empty() ); LarvalJobs jobs5 = djq.determine_job_list( 2, 10 ); TS_ASSERT( jobs5.empty() ); std::list< deallocation::DeallocationMessageOP > msgs6 = djq.deallocation_messages(); TS_ASSERT( msgs6.empty() ); // ok, let's mark all of the jobs from node 2 complete for ( LarvalJobOP node2_job : jobs4 ) { djq.note_job_completed_and_track( node2_job, jd3_job_status_success, 1 ); } LarvalJobs jobs6 = djq.determine_job_list( 3, 10 ); TS_ASSERT_EQUALS( jobs6.size(), 3 ); std::list< deallocation::DeallocationMessageOP > msgs7 = djq.deallocation_messages(); TS_ASSERT_EQUALS( msgs7.size(), 1 ); PoseDeallocOP msg7 = utility::pointer::dynamic_pointer_cast< PoseDealloc > ( msgs7.front() ); TS_ASSERT( msg7 ); TS_ASSERT_EQUALS( msg7->pose_id(), 2 ); } void test_standard_job_queen_pose_deallocation_messages_no_preserve_poses() { core_init_with_additional_options( "-in:file:s 1ubq.pdb" ); std::string jobdef_file = "<JobDefinitionFile>\n" " <Job nstruct=\"5\">\n" " </Job>\n" " <Job nstruct=\"11\">\n" " </Job>\n" " <Job nstruct=\"3\">\n" " </Job>\n" "</JobDefinitionFile>\n"; DummyJobQueen djq; try { djq.determine_preliminary_job_list_from_xml_file( jobdef_file ); } catch (utility::excn::Exception & e ) { std::cout << e.msg() << std::endl; TS_ASSERT( false ); } JobDigraphOP dag = djq.create_and_set_initial_job_dag(); TS_ASSERT_EQUALS( dag->num_nodes(), 3 ); TS_ASSERT_EQUALS( dag->num_edges(), 0 ); PreliminaryLarvalJobTracker const & prelim_tracker = djq.get_prelim_larval_job_tracker(); utility::vector1< core::Size > prelim_nodes( 3 ); for ( core::Size ii = 1; ii <= 3; ++ii ) prelim_nodes[ ii ] = ii; TS_ASSERT_EQUALS( prelim_tracker.get_preliminary_job_node_indices(), prelim_nodes ); LarvalJobs jobs = djq.determine_job_list( 1, 4 ); for ( LarvalJobOP node1_job : jobs ) { TS_ASSERT_EQUALS( node1_job->inner_job()->input_source().source_id(), 1 ); } std::list< deallocation::DeallocationMessageOP > msgs1 = djq.deallocation_messages(); TS_ASSERT( msgs1.empty() ); for ( LarvalJobOP node1_job : jobs ) { djq.note_job_completed_and_track( node1_job, jd3_job_status_success, 1 ); } LarvalJobs jobs2 = djq.determine_job_list( 1, 2 ); for ( LarvalJobOP node1_job : jobs2 ) { TS_ASSERT_EQUALS( node1_job->inner_job()->input_source().source_id(), 1 ); } std::list< deallocation::DeallocationMessageOP > msgs2 = djq.deallocation_messages(); TS_ASSERT( msgs2.empty() ); for ( LarvalJobOP node1_job : jobs2 ) { djq.note_job_completed_and_track( node1_job, jd3_job_status_success, 1 ); } LarvalJobs jobs3 = djq.determine_job_list( 2, 10 ); TS_ASSERT_EQUALS( jobs3.size(), 10 ); // After we tell the DJQ that all the jobs for node two have finished and // she has started assigning jobs for node2, then she will tell us that // it's ok to deallocate the input pose for node 1 std::list< deallocation::DeallocationMessageOP > msgs3 = djq.deallocation_messages(); TS_ASSERT_EQUALS( msgs3.size(), 1 ); typedef deallocation::InputPoseDeallocationMessage PoseDealloc; typedef deallocation::InputPoseDeallocationMessageOP PoseDeallocOP; PoseDeallocOP msg3 = utility::pointer::dynamic_pointer_cast< PoseDealloc > ( msgs3.front() ); TS_ASSERT( msg3 ); TS_ASSERT_EQUALS( msg3->pose_id(), 1 ); std::list< deallocation::DeallocationMessageOP > msgs4 = djq.deallocation_messages(); TS_ASSERT( msgs4.empty() ); for ( LarvalJobOP node2_job : jobs3 ) { djq.note_job_completed_and_track( node2_job, jd3_job_status_success, 1 ); } LarvalJobs jobs4 = djq.determine_job_list( 2, 10 ); TS_ASSERT_EQUALS( jobs4.size(), 1 ); std::list< deallocation::DeallocationMessageOP > msgs5 = djq.deallocation_messages(); TS_ASSERT( msgs5.empty() ); LarvalJobs jobs5 = djq.determine_job_list( 2, 10 ); TS_ASSERT( jobs5.empty() ); std::list< deallocation::DeallocationMessageOP > msgs6 = djq.deallocation_messages(); TS_ASSERT( msgs6.empty() ); // ok, let's mark all of the jobs from node 2 complete for ( LarvalJobOP node2_job : jobs4 ) { djq.note_job_completed_and_track( node2_job, jd3_job_status_success, 1 ); } LarvalJobs jobs6 = djq.determine_job_list( 3, 10 ); TS_ASSERT_EQUALS( jobs6.size(), 3 ); std::list< deallocation::DeallocationMessageOP > msgs7 = djq.deallocation_messages(); TS_ASSERT_EQUALS( msgs7.size(), 1 ); PoseDeallocOP msg7 = utility::pointer::dynamic_pointer_cast< PoseDealloc > ( msgs7.front() ); TS_ASSERT( msg7 ); TS_ASSERT_EQUALS( msg7->pose_id(), 2 ); } void test_standard_job_queen_pose_deallocation_messages_and_preserve_input_poses() { core_init_with_additional_options( "-in:file:s 1ubq.pdb -jd3:load_input_poses_only_once" ); // The first two Jobs will read from the command line, and the last one will read from // the Input tag; so the first two preliminary job nodes will both use the same // pose_id. After the jobs finish for node 2, then the DJQ should report that it's now time // to deallocate pose #1. std::string jobdef_file = "<JobDefinitionFile>\n" " <Job nstruct=\"5\">\n" " </Job>\n" " <Job nstruct=\"11\">\n" " </Job>\n" " <Job nstruct=\"3\">\n" " <Input>\n" " <PDB filename=\"1ubq.pdb\"/>\n" " </Input>\n" " </Job>\n" "</JobDefinitionFile>\n"; DummyJobQueen djq; try { djq.determine_preliminary_job_list_from_xml_file( jobdef_file ); } catch (utility::excn::Exception & e ) { std::cout << e.msg() << std::endl; TS_ASSERT( false ); } JobDigraphOP dag = djq.create_and_set_initial_job_dag(); TS_ASSERT_EQUALS( dag->num_nodes(), 3 ); TS_ASSERT_EQUALS( dag->num_edges(), 0 ); PreliminaryLarvalJobTracker const & prelim_tracker = djq.get_prelim_larval_job_tracker(); utility::vector1< core::Size > prelim_nodes( 3 ); for ( core::Size ii = 1; ii <= 3; ++ii ) prelim_nodes[ ii ] = ii; TS_ASSERT_EQUALS( prelim_tracker.get_preliminary_job_node_indices(), prelim_nodes ); LarvalJobs jobs = djq.determine_job_list( 1, 4 ); for ( LarvalJobOP node1_job : jobs ) { TS_ASSERT_EQUALS( node1_job->inner_job()->input_source().source_id(), 1 ); } std::list< deallocation::DeallocationMessageOP > msgs1 = djq.deallocation_messages(); TS_ASSERT( msgs1.empty() ); for ( LarvalJobOP node1_job : jobs ) { djq.note_job_completed_and_track( node1_job, jd3_job_status_success, 1 ); } LarvalJobs jobs2 = djq.determine_job_list( 1, 2 ); for ( LarvalJobOP node1_job : jobs2 ) { TS_ASSERT_EQUALS( node1_job->inner_job()->input_source().source_id(), 1 ); } std::list< deallocation::DeallocationMessageOP > msgs2 = djq.deallocation_messages(); TS_ASSERT( msgs2.empty() ); for ( LarvalJobOP node1_job : jobs2 ) { djq.note_job_completed_and_track( node1_job, jd3_job_status_success, 1 ); } LarvalJobs jobs3 = djq.determine_job_list( 2, 10 ); TS_ASSERT_EQUALS( jobs3.size(), 10 ); // After we tell the DJQ that all the jobs for node two have finished and // she has started assigning jobs for node2, then she would tell us that // it's ok to deallocate the input pose for node 1 IF the load_input_poses_only_once flag // weren't on the command line, but it is, so she'll not tell us to deallocate anything std::list< deallocation::DeallocationMessageOP > msgs3 = djq.deallocation_messages(); TS_ASSERT( msgs3.empty() ); for ( LarvalJobOP node2_job : jobs3 ) { djq.note_job_completed_and_track( node2_job, jd3_job_status_success, 1 ); } LarvalJobs jobs4 = djq.determine_job_list( 2, 10 ); TS_ASSERT_EQUALS( jobs4.size(), 1 ); std::list< deallocation::DeallocationMessageOP > msgs5 = djq.deallocation_messages(); TS_ASSERT( msgs5.empty() ); LarvalJobs jobs5 = djq.determine_job_list( 2, 10 ); TS_ASSERT( jobs5.empty() ); std::list< deallocation::DeallocationMessageOP > msgs6 = djq.deallocation_messages(); TS_ASSERT( msgs6.empty() ); // ok, let's mark all of the jobs from node 2 complete for ( LarvalJobOP node2_job : jobs4 ) { djq.note_job_completed_and_track( node2_job, jd3_job_status_success, 1 ); } LarvalJobs jobs6 = djq.determine_job_list( 3, 10 ); TS_ASSERT_EQUALS( jobs6.size(), 3 ); // OK! Now the DJQ should say to deallocate the first input pose. std::list< deallocation::DeallocationMessageOP > msgs7 = djq.deallocation_messages(); TS_ASSERT_EQUALS( msgs7.size(), 1 ); typedef deallocation::InputPoseDeallocationMessage PoseDealloc; typedef deallocation::InputPoseDeallocationMessageOP PoseDeallocOP; PoseDeallocOP msg7 = utility::pointer::dynamic_pointer_cast< PoseDealloc > ( msgs7.front() ); TS_ASSERT( msg7 ); TS_ASSERT_EQUALS( msg7->pose_id(), 1 ); } void test_sjq_remote_node_mature_larval_job() { TS_ASSERT( true ); // heh - looks like I never wrote this unit test? } private: bool local_options_added_; };
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
58dadc442ee9e1c14b2588a4718b46359845c396
e62f9576a618def368c0c5003676a3a6b1665683
/src/algorithms/kamenevs/WrapYakobi.cpp
7f0075cb5d0959b21366a3eceea10c8eaf3c1ee8
[ "MIT" ]
permissive
av-elier/fast-exponentiation-algs
934f77fc4a10148edacd6414b1f1e882bc48502a
1d6393021583686372564a7ca52b09dc7013fb38
refs/heads/master
2021-01-20T06:32:46.847635
2018-06-23T07:47:02
2018-06-23T07:47:02
13,882,073
4
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
/* * WrapYakobi.cpp * * Created on: 26 дек. 2013 г. * Author: Adelier */ #include "algorithms/kamenevs/WrapYakobi.h" #include "algorithms/kamenevs/Yakobi.h" WrapYakobi::WrapYakobi(Yakobi *yakobi){ this->yakobi = *yakobi; } WrapYakobi::~WrapYakobi() { // TODO Auto-generated destructor stub } void WrapYakobi::precalc(ZZ exponent){ yakobi.precalc(exponent); } ZZ_p WrapYakobi::exp(ZZ_p base){ return yakobi.exp(base); } ZZ_p WrapYakobi::exp(ZZ_p base, ZZ exponent){ precalc(exponent); return exp(base); }
[ "adelier@hotmail.com" ]
adelier@hotmail.com
c9fe52a7594b968b93bf009a717db58886d11e7e
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/python/return_by_value.hpp
22d18f7ebeaa6fc0d520a8acd5d96de2f1edfaa2
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
68
hpp
#include "thirdparty/boost_1_55_0/boost/python/return_by_value.hpp"
[ "liuhuahang@xiaomi.com" ]
liuhuahang@xiaomi.com
1c9caba0e285360e7169badacc83b4cbd235fb15
3943f4014015ae49a2c6c3c7018afd1d2119a7ed
/final_output/output_recur_large/hermite_formula_-10.000000_10.000000/13-14.cpp
854fb40cc6131880c92ee3e917b7766f5cc12e03
[]
no_license
Cathy272272272/practicum
9fa7bfcccc23d4e40af9b647d9d98f5ada37aecf
e13ab8aa5cf5c037245b677453e14b586b10736d
refs/heads/master
2020-05-23T10:10:15.111847
2019-06-08T00:23:57
2019-06-08T00:23:57
186,689,468
0
0
null
null
null
null
UTF-8
C++
false
false
1,807
cpp
#include <iostream> #include <stdio.h> #include <assert.h> #include <math.h> extern "C" { #include "quadmath.h" } #ifndef IFT #define IFT float #endif #ifndef OFT #define OFT __float128 #endif template <class _Real> _Real __libcpp_hermite_recurrence(unsigned __n, _Real __x) { if (__n == 0u) return _Real(1); _Real __t2(1); _Real __t1 = _Real(2) * __x; for (unsigned __i = 1; __i < __n; ++__i) { const _Real __t0 = _Real(2) * (__x * __t1 - _Real(__i) * __t2); __t2 = __t1; __t1 = __t0; } return __t1; } using namespace std; static const int k = 3; int main (int argc, char *argv[]) { assert(argc == 3); char *iname = argv[1]; char *oname = argv[2]; FILE *ifile = fopen(iname, "r"); FILE *ofile = fopen(oname, "w"); assert(ifile != NULL && ofile != NULL); fseek(ifile, 0, SEEK_END); unsigned long fsize = ftell(ifile); assert(fsize == (sizeof(IFT) * 1)); fseek(ifile, 0, SEEK_SET); IFT in_x; fread(&in_x, sizeof(IFT), 1, ifile); FT rel = 0; FT x = in_x; #ifdef ORIG rel = __libcpp_hermite_recurrence(14, x + 0.0); #else rel = ( ( ( ( ( ( x*x ) * ( x*x ) ) * ( ( ( x*x ) * ( x*x ) ) * ( ( x*x ) * ( x*x ) ) ) ) * ( ( x* ( x*16384.0 ) ) +-745472.0 ) ) + ( ( ( ( x*242161920.0 ) *x ) +-17297280.0 ) + ( ( ( x*x ) * ( x*x ) ) * ( -484323840.0+ ( x* ( 322882560.0*x ) ) ) ) ) ) + ( ( ( ( ( x*x ) * ( x*x ) ) * ( ( x*x ) * ( x*x ) ) ) * ( cbrt( ( ( 12300288.0* ( x*x ) ) +-92252160.0 ) )*cbrt( ( ( 12300288.0* ( x*x ) ) +-92252160.0 ) ) ) ) *cbrt( ( ( 12300288.0* ( x*x ) ) +-92252160.0 ) ) ) ) ; #endif OFT outv = rel; fwrite(&outv, sizeof(OFT), 1, ofile); fclose(ifile); fclose(ofile); return 0; }
[ "cathyxu@Cathys-MacBook-Pro.local" ]
cathyxu@Cathys-MacBook-Pro.local
7dc5e1ff5f4df7e80dec4d0cf78fa9c1042f1e6a
6fa0bee6a16bfea715d28e53b1017a2f8233d08c
/C++/humanPlayer.h
171af3897db8003fa6bee6bf1a9011f39154b074
[]
no_license
Megdatronica/JJChess
df04f8aed73d846510d4be2ece88260ea71f4b6a
79ae39bc16cc81035f5f371e843a5611c20417c3
refs/heads/master
2016-08-12T17:07:29.219447
2015-11-08T16:44:56
2015-11-08T16:44:56
36,559,317
1
1
null
null
null
null
UTF-8
C++
false
false
630
h
#include "gameState.h" #include "player.h" #include "constants.h" // Represents a human player. Functions make calls to GameInputOutput in order // to get the choices of the user. class HumanPlayer : public Player { public: // Purely a call to the superclass constructor - sets the player colour // equal to the passed bool. HumanPlayer(bool playerColour); // Displays the board and returns a legal move chosen by the user Move getMove(GameState *gameState); // Displays the board and returns the piece for pawn promotion chosen by the // user int choosePromotion(GameState *gameState); };
[ "johnrwoolley0@gmail.com" ]
johnrwoolley0@gmail.com
0cdb5b31d4f47a9230e6e932c7b66df790dde64a
bb09e3467d6b4da0210670f8a092199641543869
/Codes/336 - A Node Too Far.cpp
f61f6a2d5b1387fefdc35c043e716178ed2df87b
[]
no_license
olee12/uva_onlinejudge_solutions
55fdb26964bc0b47327feda77f087c558b78095a
028b9fe132b1cfebce69d0cb681eccf0eb0b58fb
refs/heads/master
2021-01-19T11:45:35.341641
2017-02-17T06:01:43
2017-02-17T06:01:43
82,262,173
0
0
null
null
null
null
UTF-8
C++
false
false
3,457
cpp
/*#include<iostream> #include<vector> #include<set> #include<queue> #include<stack> #include<iterator> #include<map> #include<algorithm> #include<cstdio> using namespace std; int bfsQ(int src,map<int ,vector<int> > graph,int x); int main() { map<int,vector<int> > graph; int node,a,b; int TTI; int ca=1; while(cin>>node && node){ for(int i = 0; i < node; i++){ cin>>a>>b; graph[a].push_back(b); graph[b].push_back(a); } puts("");*/ /*map<int ,vector<int> > :: iterator it; for(it=graph.begin();it!=graph.end();it++){ cout<<(*it).first<<" - > "; for(int j= 0;j<(*it).second.size();j++){ cout<<(*it).second[j]<<" "; } cout<<endl; }*/ /*while(cin>>a>>TTI && (TTI!=0 || a!=0)){ printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",ca++,bfsQ(a,graph,TTI),a,TTI); } graph.clear(); } return 0; } int bfsQ(int src,map<int ,vector<int> > graph,int x) { int count = 0; int taken[100]={0}; map<int, int> disten; taken[src]=1; disten[src]=0; queue<int > Q; Q.push(src); int u = Q.front(); while(!Q.empty()) { int u = Q.front(); map<int,vector<int> >:: iterator it; for(int i = 0;i<graph[u].size();i++){ int v = graph[u][i]; if(!taken[v]){ taken[v]=1; disten[v]=disten[u]+1; Q.push(v); } } Q.pop(); } map<int,vector<int> >:: iterator it; for(it=graph.begin();it!=graph.end();it++){ int u=(*it).first; // printf("%d to %d distance %d\n",src,(*it).first,disten[u]); if(disten[u]>x) count++; } return count; } //,distance[(*it).first] */ //accepted; #include<iostream> #include<vector> #include<set> #include<queue> #include<stack> #include<iterator> #include<map> #include<algorithm> #include<cstdio> using namespace std; int bfsQ(int src,map<int ,vector<int> > graph,int x); map<int,int>taken; int main() { int node,a,b; int TTI; int ca=1; while(cin>>node && node){ map<int,vector<int> > graph; for(int i = 0; i < node; i++){ cin>>a>>b; graph[a].push_back(b); graph[b].push_back(a); } // cout<<"graph size : "<<graph.size()<<" "; while(cin>>a>>TTI && (TTI != 0 || a != 0)){ taken.clear(); int result = bfsQ(a,graph,TTI); // cout<<"taken size : "<<taken.size()<<" "; result += graph.size()-taken.size(); printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",ca++,result,a,TTI); } } return 0; } int bfsQ(int src,map<int ,vector<int> > graph,int x) { int count = 0; map<int, int> disten; taken[src]=1; disten[src]=0; queue<int > Q; Q.push(src); int u = Q.front(); while(!Q.empty()) { int u = Q.front(); int sz=graph[u].size(); for(int i = 0;i<sz;i++){ int v = graph[u][i]; if(!taken[v]){ taken[v]=1; disten[v]=disten[u]+1; Q.push(v); } } Q.pop(); } map<int,vector<int> >:: iterator it; for(it=graph.begin();it!=graph.end();it++){ int u=(*it).first; if(disten[u]>x) count++; } return count; }
[ "th160887@gmail.com" ]
th160887@gmail.com
0d3745b5071a8f83834de82847c009574a27d176
4834c65c708b8284925ff7f67026f787ca0c032c
/src/netbase.h
3f8b66e86533a39b259f55e371c873426a2547de
[ "MIT" ]
permissive
sha-doh/domino
4a86e4adafd25dc9f8b45199bdcfcca155fcdc8c
68a97e6a47dd508970a3194ada7857c49c09f3d3
refs/heads/master
2020-03-20T10:51:42.958080
2018-05-06T07:36:57
2018-05-06T07:36:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,648
h
// Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NETBASE_H #define BITCOIN_NETBASE_H #if defined(HAVE_CONFIG_H) #include "config/domino-config.h" #endif #include "compat.h" #include "serialize.h" #include <stdint.h> #include <string> #include <vector> extern int nConnectTimeout; extern bool fNameLookup; /** -timeout default */ static const int DEFAULT_CONNECT_TIMEOUT = 5000; #ifdef WIN32 // In MSVC, this is defined as a macro, undefine it to prevent a compile and link error #undef SetPort #endif enum Network { NET_UNROUTABLE = 0, NET_IPV4, NET_IPV6, NET_TOR, NET_MAX, }; /** IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96)) */ class CNetAddr { protected: unsigned char ip[16]; // in network byte order public: CNetAddr(); CNetAddr(const struct in_addr& ipv4Addr); explicit CNetAddr(const char* pszIp, bool fAllowLookup = false); explicit CNetAddr(const std::string& strIp, bool fAllowLookup = false); void Init(); void SetIP(const CNetAddr& ip); /** * Set raw IPv4 or IPv6 address (in network byte order) * @note Only NET_IPV4 and NET_IPV6 are allowed for network. */ void SetRaw(Network network, const uint8_t* data); bool SetSpecial(const std::string& strName); // for Tor addresses bool IsIPv4() const; // IPv4 mapped address (::FFFF:0:0/96, 0.0.0.0/0) bool IsIPv6() const; // IPv6 address (not mapped IPv4, not Tor) bool IsRFC1918() const; // IPv4 private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) bool IsRFC2544() const; // IPv4 inter-network communcations (192.18.0.0/15) bool IsRFC6598() const; // IPv4 ISP-level NAT (100.64.0.0/10) bool IsRFC5737() const; // IPv4 documentation addresses (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24) bool IsRFC3849() const; // IPv6 documentation address (2001:0DB8::/32) bool IsRFC3927() const; // IPv4 autoconfig (169.254.0.0/16) bool IsRFC3964() const; // IPv6 6to4 tunnelling (2002::/16) bool IsRFC4193() const; // IPv6 unique local (FC00::/7) bool IsRFC4380() const; // IPv6 Teredo tunnelling (2001::/32) bool IsRFC4843() const; // IPv6 ORCHID (2001:10::/28) bool IsRFC4862() const; // IPv6 autoconfig (FE80::/64) bool IsRFC6052() const; // IPv6 well-known prefix (64:FF9B::/96) bool IsRFC6145() const; // IPv6 IPv4-translated address (::FFFF:0:0:0/96) bool IsTor() const; bool IsLocal() const; bool IsRoutable() const; bool IsValid() const; bool IsMulticast() const; enum Network GetNetwork() const; std::string ToString() const; std::string ToStringIP() const; unsigned int GetByte(int n) const; uint64_t GetHash() const; bool GetInAddr(struct in_addr* pipv4Addr) const; std::vector<unsigned char> GetGroup() const; int GetReachabilityFrom(const CNetAddr* paddrPartner = NULL) const; CNetAddr(const struct in6_addr& pipv6Addr); bool GetIn6Addr(struct in6_addr* pipv6Addr) const; friend bool operator==(const CNetAddr& a, const CNetAddr& b); friend bool operator!=(const CNetAddr& a, const CNetAddr& b); friend bool operator<(const CNetAddr& a, const CNetAddr& b); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(FLATDATA(ip)); } friend class CSubNet; }; class CSubNet { protected: /// Network (base) address CNetAddr network; /// Netmask, in network byte order uint8_t netmask[16]; /// Is this value valid? (only used to signal parse errors) bool valid; public: CSubNet(); explicit CSubNet(const std::string& strSubnet, bool fAllowLookup = false); bool Match(const CNetAddr& addr) const; std::string ToString() const; bool IsValid() const; friend bool operator==(const CSubNet& a, const CSubNet& b); friend bool operator!=(const CSubNet& a, const CSubNet& b); }; /** A combination of a network address (CNetAddr) and a (TCP) port */ class CService : public CNetAddr { protected: unsigned short port; // host order public: CService(); CService(const CNetAddr& ip, unsigned short port); CService(const struct in_addr& ipv4Addr, unsigned short port); CService(const struct sockaddr_in& addr); explicit CService(const char* pszIpPort, int portDefault, bool fAllowLookup = false); explicit CService(const char* pszIpPort, bool fAllowLookup = false); explicit CService(const std::string& strIpPort, int portDefault, bool fAllowLookup = false); explicit CService(const std::string& strIpPort, bool fAllowLookup = false); void Init(); void SetPort(unsigned short portIn); unsigned short GetPort() const; bool GetSockAddr(struct sockaddr* paddr, socklen_t* addrlen) const; bool SetSockAddr(const struct sockaddr* paddr); friend bool operator==(const CService& a, const CService& b); friend bool operator!=(const CService& a, const CService& b); friend bool operator<(const CService& a, const CService& b); std::vector<unsigned char> GetKey() const; std::string ToString() const; std::string ToStringPort() const; std::string ToStringIPPort() const; CService(const struct in6_addr& ipv6Addr, unsigned short port); CService(const struct sockaddr_in6& addr); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(FLATDATA(ip)); unsigned short portN = htons(port); READWRITE(portN); if (ser_action.ForRead()) port = ntohs(portN); } }; typedef CService proxyType; enum Network ParseNetwork(std::string net); std::string GetNetworkName(enum Network net); void SplitHostPort(std::string in, int& portOut, std::string& hostOut); bool SetProxy(enum Network net, CService addrProxy); bool GetProxy(enum Network net, proxyType& proxyInfoOut); bool IsProxy(const CNetAddr& addr); bool SetNameProxy(CService addrProxy); bool HaveNameProxy(); bool LookupHost(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions = 0, bool fAllowLookup = true); bool Lookup(const char* pszName, CService& addr, int portDefault = 0, bool fAllowLookup = true); bool Lookup(const char* pszName, std::vector<CService>& vAddr, int portDefault = 0, bool fAllowLookup = true, unsigned int nMaxSolutions = 0); bool LookupNumeric(const char* pszName, CService& addr, int portDefault = 0); bool ConnectSocket(const CService& addr, SOCKET& hSocketRet, int nTimeout, bool* outProxyConnectionFailed = 0); bool ConnectSocketByName(CService& addr, SOCKET& hSocketRet, const char* pszDest, int portDefault, int nTimeout, bool* outProxyConnectionFailed = 0); /** Return readable error string for a network error code */ std::string NetworkErrorString(int err); /** Close socket and set hSocket to INVALID_SOCKET */ bool CloseSocket(SOCKET& hSocket); /** Disable or enable blocking-mode for a socket */ bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking); #endif // BITCOIN_NETBASE_H
[ "dmocoin@usa.com" ]
dmocoin@usa.com
c7d3558d9703dd15ce76c3d11028efe9ba812422
c793cce4cff0c8cbdbbb46df3ffe1746e2ef7436
/Handmade Game Engine/Handmade/TextBox.h
bca089031baff1a25841eaf8b83b17d53b9e9ab5
[]
no_license
Silvertooth98/Space-Shooter
fdd8f19fe69106e55a783cc36bc94e251d3102f9
80ece7abe0f8510f8715c9b9bc5c1c81e6acafd7
refs/heads/master
2020-04-07T17:39:41.200960
2018-11-21T16:44:35
2018-11-21T16:44:35
158,578,150
0
0
null
null
null
null
UTF-8
C++
false
false
472
h
#ifndef TEXTBOX_H #define TEXTBOX_H #include "GameObject.h" #include "Text.h" class TextBox : public GameObject { public: TextBox(float x, float y, float z, float size, const std::string& ID); virtual ~TextBox() {}; void SetText(const std::string text); virtual bool Create() { return true; } virtual void Update() {} virtual void Draw(); virtual void Destroy() {} private: Text m_text; float m_size; glm::vec3 m_position; glm::mat4 m_transform; }; #endif
[ "silvertooth1998@gmail.com" ]
silvertooth1998@gmail.com
34a3d9e21c103f239a89ff26d7aed859420a201e
f2024e9881862ff64f9b1ae33334fa90c9447dbc
/BST/problem3.cpp
c193b5e4ece2298e7316732142f4b5a4ddc46f9a
[]
no_license
xiayan/data_structures
aa0a3b193c7b4aa230f7a7af2446dfb497f2ab13
a092fbd38561a25aef59962c4c629a3e1956ea67
refs/heads/master
2021-01-15T18:09:06.439756
2013-06-22T04:38:37
2013-06-22T04:38:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
583
cpp
#include <fstream> #include <stdlib.h> #include <time.h> #include "BinarySearchTree.h" #include "AsciiTree.h" void randomBST(BinarySearchTree &, int, int); int main(int argc, const char *argv[]) { //Build tree using insert BinarySearchTree tree; AsciiTree ascii; tree.insert(7); tree.insert(2); tree.insert(1); tree.insert(6); tree.insert(4); tree.insert(3); tree.insert(5); tree.insert(9); tree.insert(8); tree.insert(10); tree.remove(2); tree.remove(7); ascii.buildTree(tree); ascii.draw(); return 0; }
[ "drseanxy@mac.com" ]
drseanxy@mac.com
13c692eadb52ede1f53fc98c4e0c08a4af763fcb
7877b4bb5dfa3e27b1caa501990d6d1f0d427ef6
/Calc2/vars.h
939043628c7b3714d36d66f19005e9eff856d83e
[]
no_license
ts3334/OOP
c736714afe2d5710c2557b8d28e309740e777494
0c057536f2a2dd2cea22dbfc0d9e6d9700ed600e
refs/heads/master
2020-03-22T05:59:07.086781
2018-08-12T23:36:27
2018-08-12T23:36:27
139,603,652
0
0
null
null
null
null
UTF-8
C++
false
false
148
h
class Variable { public: string name; double value; }; double get_value(string s); void set_value(string s, double d); void print_vars();
[ "ts3334@nyu.edu" ]
ts3334@nyu.edu
f2cb890a4e9c413f6065d8ec639c6ef1d8f0e9d9
b75746d852236a867a72f717efcacb9a3e141250
/protocols/ace/INet/ClientRequestHandler.inl
8308c52ba23145b2319c486a312abd98b8e46177
[]
no_license
longfem/ACE-toolkit
e8c94cc1d75a2930ceba78dac13d1b84c0efecc8
c1fedd5f2033951eee9ecf898f6f2b75584aaefc
refs/heads/master
2021-06-01T06:54:56.916537
2016-08-17T14:36:01
2016-08-17T14:36:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
426
inl
// -*- C++ -*- ACE_BEGIN_VERSIONED_NAMESPACE_DECL namespace ACE { namespace INet { ACE_INLINE const ACE_CString& ClientINetRequestHandler::INetConnectionKey::host () const { return this->host_; } ACE_INLINE u_short ClientINetRequestHandler::INetConnectionKey::port () const { return this->port_; } } } ACE_END_VERSIONED_NAMESPACE_DECL
[ "yehonal.azeroth@gmail.com" ]
yehonal.azeroth@gmail.com
e8da2b3471bc6355d4ba90eb616cd9e448e16c21
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/hunk_3789.cpp
e55e8c7b15bb1fcff6dd8d2a24f47a95c87f5cf2
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
cpp
+commit 4659538844daa2849b1a9e7d6fadb96fcd26fc83 +Author: Thomas Rast <trast@student.ethz.ch> +Date: Thu Feb 28 10:48:43 2013 +0100 + + change back to complete line + +diff --git a/a.c b/a.c +--- a/a.c +@@ -18,5 +18,7 @@ + int main () + { + printf("%ld\n", f(15)); + return 0; +-} +\ No newline at end of file + +commit 100b61a6f2f720f812620a9d10afb3a960ccb73c +Author: Thomas Rast <trast@student.ethz.ch> +Date: Thu Feb 28 10:48:10 2013 +0100 + + change to an incomplete line at end + +diff --git a/a.c b/a.c +--- a/a.c +@@ -18,5 +18,5 @@ + int main () + { + printf("%ld\n", f(15)); + return 0; +-} +\ No newline at end of file + +commit a6eb82647d5d67f893da442f8f9375fd89a3b1e2 +Author: Thomas Rast <trast@student.ethz.ch> +Date: Thu Feb 28 10:45:16 2013 +0100 + + touch both functions + +diff --git a/a.c b/a.c +--- a/a.c +@@ -17,5 +17,5 @@ + int main () + { +- printf("%d\n", f(15)); + return 0; + } + +commit de4c48ae814792c02a49c4c3c0c757ae69c55f6a +Author: Thomas Rast <trast@student.ethz.ch> +Date: Thu Feb 28 10:44:48 2013 +0100 + + initial + +diff --git a/a.c b/a.c +--- /dev/null +@@ -0,0 +16,5 @@
[ "993273596@qq.com" ]
993273596@qq.com
c6cd27b97a6e78bbb3d2f222b5d8fdd1253e38f1
58f070c58fcc3da40cf57101c5e9e80eface0afb
/DynamicProgramming/Hard/123.BestTimeBuySellStock3_BU.cpp
63ab6950f8846bb172cc61c7fc4ca598b48da60b
[]
no_license
Imran4424/LeetCode-Solutions
ab32c829c8c916f0422f4899bc347accdfc50e0d
1f0f7a86e2ed74741a001e3ba2a6ea6c68c9b484
refs/heads/master
2023-04-08T13:01:46.322323
2023-03-25T19:17:14
2023-03-25T19:17:14
231,453,902
1
0
null
null
null
null
UTF-8
C++
false
false
1,012
cpp
class Solution { int maxValue(int x, int y) { if (x > y) { return x; } return y; } public: int maxProfit(vector<int>& prices) { int firstTransactionCost = prices[0]; int firstTransactionProfit = 0; int mostMoneyInPocket = -prices[0]; int profitFromTwoTransactions = 0; for (int i = 0; i < prices.size(); ++i) { firstTransactionCost = maxValue(firstTransactionCost, prices[i]); firstTransactionProfit = maxValue(firstTransactionProfit, prices[i] - firstTransactionCost); mostMoneyInPocket = maxValue(mostMoneyInPocket , firstTransactionProfit - prices[i]); profitFromTwoTransactions = maxValue(profitFromTwoTransactions, mostMoneyInPocket + prices[i]); } return profitFromTwoTransactions; } };
[ "akashganga.programming.534363@gmail.com" ]
akashganga.programming.534363@gmail.com
adf54275666a93d3d317d1373efa82fd46ba7e67
f5233ee52bbf2563a06b2159f96118061b9ae81a
/sgs2/src/packet_processor/packet_handler/lobby/handle_CS_MY_INFO.cpp
cae20ab8e6ce6f45dec1a78ba2811d0355c0f40d
[]
no_license
ddslot-pp2/sgs2-x
e785c6bdcdf9c0ab536d3952a58fd8e150f0aae8
2525b2b1c841271debf2c0d93bc965aa4f84bd4d
refs/heads/master
2020-12-02T19:50:37.650499
2017-09-17T10:20:31
2017-09-17T10:20:31
96,397,881
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
cpp
#include "../../packet_processor.h" #include <memory> #include "../../../server_session/server_session.h" #include "../../opcode.h" #include "../../send_helper.h" #include "../core/src/locale/string_helper.h" #include "../../../account/account_manager.h" #include <random> #include "../../../../../core/src/timer/timer_helper.hpp" #include "../../../mysql/mysql_connector.h" #include "../../../mysql/query_helper.h" void handle_CS_MY_INFO(std::shared_ptr<server_session> session, const LOBBY::CS_MY_INFO& read) { auto error_handler = [session] (std::string ec) { LOBBY::SC_MY_INFO send; send.set_result(false); send.set_ec(ec); send_packet(session, opcode::SC_MY_INFO, send); session->close(); }; auto acc = session->get_account(); if (!acc) { error_handler("invalid account"); return; } const auto medal_count = acc->get_medal_count(); const auto coin_count = acc->get_coin_count(); LOBBY::SC_MY_INFO send; send.set_result(true); send.set_ec(""); send.set_medal_count(medal_count); send.set_coin_count(coin_count); send_packet(session, opcode::SC_MY_INFO, send); }
[ "ddslot.pp2@gmail.com" ]
ddslot.pp2@gmail.com
10be4a826f1a27d0040a528a7a9b02fa79c5834b
6a33cb94d4af1d8a7329ddc6c9d42f870c35bb2f
/cpp/Euler020.cpp
875edcf62f4684f2650f3be86c5a43ae5dba3e45
[]
no_license
vochong/project-euler
836321cc8e7d2e7cdf22b3b136d44dcba74a8701
6a0c7103861ff825bf84800b6e2e62819a41e36d
refs/heads/master
2020-04-29T10:41:48.487159
2018-09-19T00:13:34
2018-09-19T00:13:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,680
cpp
#include <chrono> #include <cstdint> #include <iostream> #include <vector> uint64_t e020(){ uint64_t sum = 0; std::vector<uint8_t> digits; digits.push_back(1); for(uint32_t mult = 2; mult <= 100; ++mult){ std::vector<uint8_t> tmp; for(uint32_t i = 0; i < digits.size(); ++i){ uint32_t newDigits = digits[i] * mult; std::vector<uint8_t> meta; if(newDigits == 0){ meta.push_back(0); } else{ while(newDigits){ meta.push_back(newDigits % 10); newDigits /= 10; } } uint8_t carry = 0; for(uint32_t j = 0; j < meta.size(); ++j){ if(j + i < tmp.size()){ uint32_t newDigit = tmp[i+j] + meta[j] + carry; tmp[i+j] = newDigit % 10; carry = newDigit / 10; } else{ uint32_t newDigit = meta[j] + carry; tmp.push_back(newDigit % 10); carry = newDigit / 10; } } if(carry) tmp.push_back(carry); } digits = tmp; } for(uint32_t i = 0; i < digits.size(); ++i){ sum += digits[i]; } return sum; } int main(int argc, char * argv[]){ auto t1 = std::chrono::high_resolution_clock::now(); std::cout << e020() << std::endl; auto t2 = std::chrono::high_resolution_clock::now(); auto t = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count(); std::cout << "Time: " << t/1000.0 << "s" << std::endl; }
[ "kueltz.anton@gmail.com" ]
kueltz.anton@gmail.com
fb60ddeb448ed3e7997c37bda3836dca757f92a7
4170f21781956810b6d1db4fb99b91dd331ab9d8
/include/vertex.hpp
825e92cab01641046ce463f3bfb10a2cc92c6395
[ "MIT" ]
permissive
shakram02/opengl_shapes
5b50ec31e075437193713f4a05c4c161d60e3228
367619333ff4d009b6972c42410576bb0ccc6962
refs/heads/master
2021-07-09T19:10:45.657485
2017-10-06T09:31:18
2017-10-06T09:31:18
105,747,856
0
0
null
2017-10-06T09:31:19
2017-10-04T08:46:36
C++
UTF-8
C++
false
false
198
hpp
#ifndef VERTEX_H #define VERTEX_H #include <glm/glm.hpp> using namespace glm; class Vertex { public: Vertex(const vec3 &pos) { this->pos = pos; } protected: private: vec3 pos; }; #endif
[ "ahmedhamdyau@gmail.com" ]
ahmedhamdyau@gmail.com
7aecfa454135c6d5ac43203a2fb56c506baa818e
7eeff44dd78aa95e44c7522b19185e1a37bb24c1
/PhysicalObject.h
3039150b5d87645222b18b8f67c1a88824e6e3c5
[]
no_license
scottrick/dgame
cd8363bd09dfd73337938ffd982ebf8ac6391366
7ccb622c93f2c59fd73f2188e3427787e03fc99b
refs/heads/master
2016-09-06T17:29:12.573716
2011-07-16T17:09:21
2011-07-16T17:09:21
2,045,313
0
0
null
null
null
null
UTF-8
C++
false
false
5,036
h
#ifndef _PHYSICAL_OBJECT_ #define _PHYSICAL_OBJECT_ #include "def.h" #include "Object.h" #include "Weapon.h" #include <cassert> using namespace std; class Controller; class FiringPlugin; class FiringTask; class MovementPlugin; class MovementTask; class Shield; class Shockwave; //amount of decay per second if the ship is not accelerating in the direction the ship is moving #define VELOCITY_DECAY 3.0f #define REMOVAL_BOUNDS_DISTANCE_SQUARED 10000.0f //two hundred units away class PhysicalObject : public Object { public: enum PhysicalObjectType { eNO_TYPE, ePLAYER_SHIP, eCOMPUTER_SHIP, ePROJECTILE, ePOWER_UP, eOBSTACLE, eNUM_TYPES, }; PhysicalObject(); void AddKills(int dwNumKills); void ApplyDamage(Weapon::Damage damage, PhysicalObject *pCause); void ApplyOnePhysicalDamage(PhysicalObject *pCause); void Clone(PhysicalObject *pClone); virtual void Collide(PhysicalObject *pOtherObject) = 0; virtual void Destroy(); virtual PhysicalObject *Duplicate() = 0; void FireWeaponOne(); void FireWeaponTwo(); float GetMaxAcceleration() const { return m_fMaxAcceleration; } VECTOR3 GetAcceleration() const { return m_vAcceleration; } virtual const char *GetClassName() const = 0; bool GetCollidable() const { return m_bCollidable; } virtual VECTOR3 GetDebugColor() const = 0; virtual FiringPlugin *GetFiringPlugin() const { return m_pFiringPlugin; } virtual MovementPlugin *GetMovementPlugin() const { return m_pMovementPlugin; } int GetNumKills() const { return m_dwNumKills; } PhysicalObjectType GetPhysicalObjectType() const { return m_dwPhysicalObjectType; } virtual Shockwave *GetShockwave() = 0; Shield *GetShield() const { return m_pShield; } float GetShields() const { return m_fShields; } float GetShieldsMax() const { return m_fShieldsMax; } float GetStructure() const { return m_fStructure; } float GetStructureMax() const { return m_fStructureMax; } PhysicalObject *GetTarget() const { return m_pTarget; } VECTOR3 GetVelocity() const { return m_vVelocity; } Weapon *GetWeaponOne() const { return m_pWeaponOne; } Weapon *GetWeaponTwo() const { return m_pWeaponTwo; } bool IsAlive() const; virtual void Refresh(const float &fDeltaTime); void Regenerate(); void Reset(); void SetAccelerationDir(VECTOR3 vAccelerationDir); void SetDestroyer(PhysicalObject *pObject); virtual void SetFiringPlugin(FiringPlugin *pPlugin); void SetFiringTask(FiringTask *pTask); void SetMaxSpeed(float fMax) { m_fMaxSpeed = fMax; } virtual void SetMovementPlugin(MovementPlugin *pPlugin); void SetMovementTask(MovementTask *pTask); void SetShield(Shield *pNewShield); void SetTarget(PhysicalObject *pObject); void SetThrottle(float fThrottle); void SetVelocity(VECTOR3 vVelocity); void SetVelocityDecay(bool bDecay) { m_bVelocityDecay = bDecay; } void SetWeaponOne(Weapon *pWeapon); void SetWeaponTwo(Weapon *pWeapon); protected: virtual ~PhysicalObject(); virtual void OnDeath(); void SetPhysicalObjectType(PhysicalObjectType dwType); virtual void RefreshPosition(const float &fDeltaTime); void RefreshTilt(const float &fDeltaTime); bool m_bCollidable; float m_fShields; float m_fShieldsMax; float m_fStructure; float m_fStructureMax; float m_fShieldsRechargeRate; //shield pts per second PhysicalObject *m_pTarget; //the object this thing is targeting! PhysicalObject *m_pDestroyer; //the last object to deal damage to this thing Weapon *m_pWeaponOne; //objects first weapon Weapon *m_pWeaponTwo; //objects second weapon Shield *m_pShield; VECTOR3 m_vVelocity; //both stored as UNITS PER SECOND float m_fMaxAcceleration; //rate at which this object can accelerate float m_fThrottle; //percentage of max acceleration this is accelerating VECTOR3 m_vAccelerationDir; //direction this is currently accelerating VECTOR3 m_vAcceleration; //current acceleration! float m_fMaxSpeed; //max move speed float m_fTiltX; float m_fTiltY; bool m_bVelocityDecay; //whether or not this is affected by v decay FiringPlugin *m_pFiringPlugin; MovementPlugin *m_pMovementPlugin; FiringTask *m_pFiringTask; MovementTask *m_pMovementTask; int m_dwNumKills; //number of physical objects this thing has destroyed int m_dwBoundsCheck; //only check the bounds every now and then private: void Init(); PhysicalObjectType m_dwPhysicalObjectType; }; #endif
[ "scottrick49@gmail.com" ]
scottrick49@gmail.com
4f76d234b64f7f749f72dfad5350c942ae848c2a
c27fe4ee7378f9a645912a024ae0c56230eaa4d0
/informatique/sketches/test/test.ino
37f81c09846f6beb1c789afa64b9756ab6879f24
[ "Unlicense" ]
permissive
ideometre/BigMax
17608e959c9e77a75c3c4ab74cc66768a693b991
6d1d582927e07fca05ca06b12217a34cea3f07c3
refs/heads/master
2022-02-12T00:26:29.554104
2022-02-02T21:56:28
2022-02-02T21:56:28
128,891,009
2
1
null
null
null
null
UTF-8
C++
false
false
4,006
ino
#include <QTRSensors.h> // This example is designed for use with eight QTR-1RC sensors or the eight sensors of a // QTR-8RC module. These reflectance sensors should be connected to digital inputs 3 to 10. // The QTR-8RC's emitter control pin (LEDON) can optionally be connected to digital pin 2, // or you can leave it disconnected and change the EMITTER_PIN #define below from 2 to // QTR_NO_EMITTER_PIN. // The setup phase of this example calibrates the sensor for ten seconds and turns on // the LED built in to the Arduino on pin 13 while calibration is going on. // During this phase, you should expose each reflectance sensor to the lightest and // darkest readings they will encounter. // For example, if you are making a line follower, you should slide the sensors across the // line during the calibration phase so that each sensor can get a reading of how dark the // line is and how light the ground is. Improper calibration will result in poor readings. // If you want to skip the calibration phase, you can get the raw sensor readings // (pulse times from 0 to 2500 us) by calling qtrrc.read(sensorValues) instead of // qtrrc.readLine(sensorValues). // The main loop of the example reads the calibrated sensor values and uses them to // estimate the position of a line. You can test this by taping a piece of 3/4" black // electrical tape to a piece of white paper and sliding the sensor across it. It // prints the sensor values to the serial monitor as numbers from 0 (maximum reflectance) // to 1000 (minimum reflectance) followed by the estimated location of the line as a number // from 0 to 5000. 1000 means the line is directly under sensor 1, 2000 means directly // under sensor 2, etc. 0 means the line is directly under sensor 0 or was last seen by // sensor 0 before being lost. 5000 means the line is directly under sensor 5 or was // last seen by sensor 5 before being lost. #define NUM_SENSORS 2 // number of sensors used #define TIMEOUT 2500 // waits for 2500 microseconds for sensor outputs to go low #define EMITTER_PIN 2 // emitter is controlled by digital pin 2 // sensors 0 through 7 are connected to digital pins 3 through 10, respectively QTRSensorsRC qtrrc((unsigned char[]) {A6, A7}, NUM_SENSORS, TIMEOUT, QTR_NO_EMITTER_PIN); unsigned int sensorValues[NUM_SENSORS]; void setup() { delay(500); pinMode(13, OUTPUT); digitalWrite(13, HIGH); // turn on Arduino's LED to indicate we are in calibration mode for (int i = 0; i < 400; i++) // make the calibration take about 10 seconds { qtrrc.calibrate(); // reads all sensors 10 times at 2500 us per read (i.e. ~25 ms per call) } digitalWrite(13, LOW); // turn off Arduino's LED to indicate we are through with calibration // print the calibration minimum values measured when emitters were on Serial.begin(9600); for (int i = 0; i < NUM_SENSORS; i++) { Serial.print(qtrrc.calibratedMinimumOn[i]); Serial.print(' '); } Serial.println(); // print the calibration maximum values measured when emitters were on for (int i = 0; i < NUM_SENSORS; i++) { Serial.print(qtrrc.calibratedMaximumOn[i]); Serial.print(' '); } Serial.println(); Serial.println(); delay(1000); } void loop() { // read calibrated sensor values and obtain a measure of the line position from 0 to 5000 // To get raw sensor values, call: // qtrrc.read(sensorValues); instead of unsigned int position = qtrrc.readLine(sensorValues); unsigned int position = qtrrc.readLine(sensorValues); // print the sensor values as numbers from 0 to 1000, where 0 means maximum reflectance and // 1000 means minimum reflectance, followed by the line position for (unsigned char i = 0; i < NUM_SENSORS; i++) { Serial.print(sensorValues[i]); Serial.print('\t'); } //Serial.println(); // uncomment this line if you are using raw values Serial.println(position); // comment this line out if you are using raw values delay(250); }
[ "maxime.hanicotte@visian.fr" ]
maxime.hanicotte@visian.fr
c540338ca826a0be3fbd30ec41479ae8d844694e
d9e9aefeda75c9050c47b29ac3e6c4768255c5ee
/lab3/demo/src/main.cpp
6ca8b3fcfd58c19db82357bbcd4f2c4e82aaf985
[]
no_license
maPalacios/llpp
97c151238b8d9a6cd9b714138cc6a1657dd5370c
91f997c78b08ee26441816e45d1c715d73e9b7bb
refs/heads/master
2021-01-13T02:06:01.425843
2015-03-13T11:54:48
2015-03-13T11:54:48
30,023,377
0
0
null
null
null
null
UTF-8
C++
false
false
4,035
cpp
//#include "ped_agent.h" #include "ped_model.h" #include "MainWindow.h" #include "ParseScenario.h" #include "Parser/ParseNumOfAgents.h" #include "Parser/tinyxml.h" #include <string> #include <atomic> #include <QGraphicsView> #include <QGraphicsScene> #include <QApplication> #include <QTimer> #include <thread> #include <unistd.h> #include "Timer.h" #include <iostream> #include <chrono> #include <ctime> #include <cstring> #define SIMULATION_STEPS 1000000 enum IMPLEMENTATION {CUDA, VECTOR, OMP, PTHREAD, SEQ}; int main(int argc, char*argv[]) { Ped::Model model; bool timing_mode = 0; int i = 1; QString scenefile = "scenario.xml"; string scenefileString = "scenario.xml"; int par = SEQ; int np = 1; int collisionMode = PTHREAD; // 1.02 // Argument handling while(i < argc) { if(argv[i][0] == '-' && argv[i][1] == '-') { if(strcmp(&argv[i][2],"timing-mode") == 0){ cout << "Timing mode on\n"; timing_mode = true; } else if(strcmp(&argv[i][2],"openmp") == 0){ par = OMP; cout << "Using openmp parallelisation.\n"; } else if(strcmp(&argv[i][2],"pthreads") == 0){ par = PTHREAD; cout << "Using pthreads parallelisation.\n"; } else if(strcmp(&argv[i][2],"cuda") == 0){ par = CUDA; cout << "Using CUDA parallelisation.\n"; } else if(strcmp(&argv[i][2],"vector") == 0 || strcmp(&argv[i][2],"simd") == 0){ par = VECTOR; cout << "Using vector parallelisation.\n"; } else if(strcmp(&argv[i][2],"comp") == 0){ collisionMode = OMP; cout << "Using OMP collision detection.\n"; } else if(strcmp(&argv[i][2],"cseq") == 0 || strcmp(&argv[i][2],"simd") == 0){ collisionMode = SEQ; cout << "Using sequential collision detection.\n"; } else if(strcmp(&argv[i][2],"np") == 0){ i++; if (i < argc) np = atoi(argv[i]); else cerr << "Too few arguments, --np needs a number." << endl; } else { cerr << "Unrecognized command: \"" << argv[i] << "\". Ignoring ..." << endl; } } else // Assume it is a path to scenefile { scenefile = argv[i]; scenefileString = argv[i]; //(under scenefile = argv[i];) } i+=1; } ParseNumOfAgents numOfAgent(scenefileString.c_str()); int size = numOfAgent.getNumOfAgents(); CUDA_DATA data; data.ax = (double*)malloc(sizeof(double)*size); data.ay = (double*)malloc(sizeof(double)*size); data.wpx = (double*)malloc(sizeof(double)*size); data.wpy = (double*)malloc(sizeof(double)*size); data.wpr = (double*)malloc(sizeof(double)*size); ParseScenario parser(scenefile, &data); int WIDTH = 1000; int HEIGHT = 1000; atomic<bool> * rows[WIDTH]; for (int i=0;i<WIDTH;i++){ rows[i] = (atomic<bool>*)malloc(sizeof(atomic<bool>)*HEIGHT); } for (int i=0;i<WIDTH;i++) for (int j=0;j<HEIGHT;j++) rows[i][j] = false; model.grid = rows; model.setup(parser.getAgents()); model.setPar(par, np); model.setCollisionMode((IMPLEMENTATION)collisionMode); QApplication app(argc, argv); MainWindow mainwindow(model); const int delay_ms = 10; Timer *timer; #define TICK_LIMIT 10000 #define AS_FAST_AS_POSSIBLE 0 if(timing_mode) { timer = new Timer(model,mainwindow,AS_FAST_AS_POSSIBLE); timer->setTickLimit(TICK_LIMIT); } else { timer = new Timer(model,mainwindow,delay_ms); mainwindow.show(); } cout << "Demo setup complete, running ..." << endl; int retval = 0; std::chrono::time_point<std::chrono::system_clock> start,stop; start = std::chrono::system_clock::now(); // If timing mode, just go as fast as possible without delays or graphical updates if(timing_mode) { timer->busyTick(); } else { timer->qtTimerTick(); retval = app.exec(); } stop = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = stop-start; cout << "Time: " << elapsed_seconds.count() << " seconds." << endl; cout << "Done" << endl; delete (timer); return retval; }
[ "sharyari@gmail.com" ]
sharyari@gmail.com
5e3c138665f82ff1eeb579a4c0e7573543993f38
dccd1058e723b6617148824dc0243dbec4c9bd48
/aoj/vol13/1306.cpp
5b4d69750a746678347caf0280ef8e865720bdb8
[]
no_license
imulan/procon
488e49de3bcbab36c624290cf9e370abfc8735bf
2a86f47614fe0c34e403ffb35108705522785092
refs/heads/master
2021-05-22T09:24:19.691191
2021-01-02T14:27:13
2021-01-02T14:27:13
46,834,567
7
1
null
null
null
null
UTF-8
C++
false
false
3,014
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second const int INF=123456789; int dp[5][4][101]; int nx[5][4][101]; int b[50500]; inline void init() { memset(b,-1,sizeof(b)); rep(i,5)rep(j,4)rep(k,101) dp[i][j][k]=INF; } int main() { int n; while(cin >>n,n) { init(); map<int,int> num; vector<int> P(n), T(n); rep(i,n) { scanf(" %d %d", &P[i], &T[i]); b[T[i]]=P[i]; num[T[i]]=i; } int ans=-1; bool fail=false; dp[1][0][0]=0; for(int t=1; t<50500; ++t) { rep(w,4) { if(b[t]==-1) { bool ok=(t-(w+1)>=0); if(ok) { for(int i=t; i>t-(w+1); --i) if(b[i]!=-1) ok=false; } if(ok) dp[0][0][0]=min(dp[0][0][0],dp[w+1][w][1]+1); for(int pos=1; pos<=100; ++pos) { dp[0][w][pos]=min(dp[0][w][pos],dp[1][w][pos]); if(ok) { dp[0][w][pos]=min(dp[0][w][pos],dp[w+1][w][pos-1]+1); if(pos+1<=100) dp[0][w][pos]=min(dp[0][w][pos],dp[w+1][w][pos+1]+1); } } } else { int b_idx=num[t]; int pos=b[t]; if(w<3) { dp[0][w+1][pos]=min(dp[0][w+1][pos],dp[1][w][pos]); if( t-(w+1)>=0 && (b_idx==0 ||(b_idx>0 && t-(w+1)>=T[b_idx-1])) ) { if(pos-1>=0) dp[0][w+1][pos]=min(dp[0][w+1][pos],dp[w+1][w][pos-1]+1); if(pos+1<=100) dp[0][w+1][pos]=min(dp[0][w+1][pos],dp[w+1][w][pos+1]+1); } } } } if(b[t]!=-1) { // printf(" %d th balloon, (%d,%d)\n", num[t],P[num[t]],T[num[t]]); bool c=false; rep(j,4) { // printf(" %d, %d\n",j,dp[0][j][b[t]] ); if(dp[0][j][b[t]]<INF) c=true; } if(!c) { fail=true; ans=num[t]+1; break; } } for(int i=4; i>0; --i)rep(j,4)rep(k,101) dp[i][j][k]=dp[i-1][j][k]; rep(i,4)rep(j,101) dp[0][i][j]=INF; } if(fail) printf("NG %d\n", ans); else printf("OK %d\n", dp[1][0][0]); } return 0; }
[ "k0223.teru@gmail.com" ]
k0223.teru@gmail.com
bcb47c4479818500ee055c0649740bcd9591d64e
9735397c4f86a14694dece008024fceb81186d07
/ff/include/para/paracontainer.h
adb17c57c5664a9fa1ef915434f9b416cb773660
[ "MIT" ]
permissive
SkySlayer/functionflow
f36cfb33e63c327310ca33b1d943932ae20cd9a1
f15f78b30fa5dd2462ce76ce68cc63854eb165f4
refs/heads/master
2021-01-23T06:49:26.757259
2015-01-30T07:00:31
2015-01-30T07:00:31
30,061,023
1
1
null
null
null
null
UTF-8
C++
false
false
3,117
h
/*********************************************** The MIT License (MIT) Copyright (c) 2012 Athrun Arthur <athrunarthur@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *************************************************/ #ifndef FF_PARA_PARA_CONTAINER_H_ #define FF_PARA_PARA_CONTAINER_H_ #include "common/common.h" #include "para/para.h" #include "para/para_helper.h" #include "para/paras_with_lock.h" #include "common/log.h" #include "runtime/env.h" #include <cmath> namespace ff{ namespace internal { class wait_all; class wait_any; }//end namespace internal class paracontainer { public: typedef void ret_type; public: paracontainer() : m_pEntities(new internal::paras_with_lock()){} para<void> & operator [](int index) { std::lock_guard<ff::spinlock> _l(m_pEntities->lock); _DEBUG( if(index >= (*m_pEntities).entities.size()) { assert(false && "index out of range"); } ) return (*m_pEntities).entities[index]; } size_t size() const { std::lock_guard<ff::spinlock> _l(m_pEntities->lock); return m_pEntities->entities.size(); } ~paracontainer() { } void add(const para< void >& p) { std::lock_guard<ff::spinlock> _l(m_pEntities->lock); m_pEntities->entities.push_back(p); } void clear() { std::lock_guard<ff::spinlock> _l(m_pEntities->lock); m_pEntities->entities.clear(); } protected: typedef std::shared_ptr<internal::paras_with_lock > Entities_t; friend internal::wait_all all(paracontainer & pg); friend internal::wait_any any(paracontainer & pg); std::shared_ptr<internal::paras_with_lock> & all_entities() { return m_pEntities; }; std::shared_ptr<internal::paras_with_lock > m_pEntities; };//end class paracontainer }//end namespace ff #endif
[ "athrunarthur@gmail.com" ]
athrunarthur@gmail.com
3b34c189fd62b55d73e5bdf27dce3c8324e9aa3a
8903cb76cedac12995249e2e613af65365be7cf2
/hiro/qt/menu-bar.hpp
e1fed335f462c33487a21003d51aee0a10e2f3a2
[ "ISC" ]
permissive
kirwinia/ares-emu-v121
0c1e21e073f291741406cd1ed01acca43acd56d7
722aa227caf943a4a64f1678c1bdd07b38b15caa
refs/heads/main
2023-06-09T15:28:23.665934
2021-06-28T06:10:46
2021-06-28T06:10:46
380,923,321
0
0
ISC
2021-06-28T06:05:04
2021-06-28T06:05:04
null
UTF-8
C++
false
false
402
hpp
#if defined(Hiro_MenuBar) namespace hiro { struct pMenuBar : pObject { Declare(MenuBar, Object) auto append(sMenu menu) -> void; auto remove(sMenu menu) -> void; auto setEnabled(bool enabled) -> void override; auto setFont(const Font& font) -> void override; auto setVisible(bool visible) -> void override; auto _parent() -> maybe<pWindow&>; auto _setState() -> void; }; } #endif
[ "ecallaghan@protonmail.com" ]
ecallaghan@protonmail.com
357a9df8644cc7724affca7a9e27ed35e560ea5b
df21da8b317adf19fa96d0a15fddc5945a3ef28b
/include/IECore/MatrixInterpolator.inl
84886a9ae22d343747757afd179278d9d7e120c8
[]
no_license
turbosun/cortex
838d30ece6ce4946392703ba8add72c776faba7d
4bdc01a692652cd562f3bfa85f3dae99d07c0b15
refs/heads/master
2020-12-24T09:01:36.484303
2013-10-15T06:23:45
2013-10-15T06:23:45
11,165,381
1
0
null
null
null
null
UTF-8
C++
false
false
4,636
inl
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Image Engine Design nor the names of any // other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "OpenEXR/ImathVec.h" #include "OpenEXR/ImathMatrix.h" #include "OpenEXR/ImathMatrixAlgo.h" namespace IECore { // Partially specialize for Imath::Matrix44<T>. Interpolates through the shortest rotation path and linearly on the shear,translate and scale. // If one of the matrices cannot be decomposed it raises an exception. template<typename T> struct LinearInterpolator< Imath::Matrix44<T> > { void operator()(const Imath::Matrix44<T> &y0, const Imath::Matrix44<T> &y1, double x, Imath::Matrix44<T> &result) const { if ( x <= 0 ) { result = y0; return; } if ( x >= 1 ) { result = y1; return; } Imath::Vec3<T> s0, s1, sx; Imath::Vec3<T> h0, h1, hx; Imath::Vec3<T> r0, r1, rx; Imath::Vec3<T> t0, t1, tx; extractSHRT(y0, s0, h0, r0, t0); extractSHRT(y1, s1, h1, r1, t1); Imath::Quat<T> q0, q1, qx; q0 = Imath::Euler<T>(r0).toQuat(); q1 = Imath::Euler<T>(r1).toQuat(); LinearInterpolator< Imath::Vec3<T> >()( s0, s1, x, sx ); LinearInterpolator< Imath::Vec3<T> >()( h0, h1, x, hx ); LinearInterpolator< Imath::Quat<T> >()( q0, q1, x, qx ); LinearInterpolator< Imath::Vec3<T> >()( t0, t1, x, tx ); result.makeIdentity(); result.translate( tx ); result *= qx.toMatrix44(); result.shear( hx ); result.scale( sx ); } }; // Partially specialize for Imath::Matrix44<T>. Interpolates through the shortest rotation path and linearly on the shear,translate and scale. // If one of the matrices cannot be decomposed it raises an exception. template<typename T> struct CubicInterpolator< Imath::Matrix44< T > > { void operator()(const Imath::Matrix44< T > &y0, const Imath::Matrix44< T > &y1, const Imath::Matrix44< T > &y2, const Imath::Matrix44< T > &y3, double x, Imath::Matrix44< T > &result) const { if ( x <= 0 ) { result = y1; return; } if ( x >= 1 ) { result = y2; return; } Imath::Vec3<T> s0, s1, s2, s3, sx; Imath::Vec3<T> h0, h1, h2, h3, hx; Imath::Vec3<T> r0, r1, r2, r3, rx; Imath::Vec3<T> t0, t1, t2, t3, tx; extractSHRT(y0, s0, h0, r0, t0); extractSHRT(y1, s1, h1, r1, t1); extractSHRT(y2, s2, h2, r2, t2); extractSHRT(y3, s3, h3, r3, t3); Imath::Quat<T> q0, q1, q2, q3, qx; q0 = Imath::Euler<T>(r0).toQuat(); q1 = Imath::Euler<T>(r1).toQuat(); q2 = Imath::Euler<T>(r2).toQuat(); q3 = Imath::Euler<T>(r3).toQuat(); CubicInterpolator< Imath::Vec3<T> >()( s0, s1, s2, s3, x, sx ); CubicInterpolator< Imath::Vec3<T> >()( h0, h1, h2, h3, x, hx ); CubicInterpolator< Imath::Quat<T> >()( q0, q1, q2, q3, x, qx ); CubicInterpolator< Imath::Vec3<T> >()( t0, t1, t2, t3, x, tx ); result.makeIdentity(); result.translate( tx ); result *= qx.toMatrix44(); result.shear( hx ); result.scale( sx ); } }; } // namespace IECore
[ "lucio@image-engine.com" ]
lucio@image-engine.com
ecf6a10c3a201f05a80f4b3e5abfce663b778b87
674de04236af01eec7f2fa5f5b5b34461d140278
/Auburn school projects [archive]/X. Fa2012/2710 Sftwr Construction [C++, UML]/Project/_002/FO3/package/tool.h
259994b43961787602f08270ca62110a74b466f6
[]
no_license
aewallace/School-Archive
4e8cee69f9c096d6770ffec3676094610850871d
3c218342c319c833a72332f610fbeb0bf501cef4
refs/heads/master
2021-01-02T08:57:15.363033
2015-10-08T19:21:35
2015-10-08T19:21:35
27,462,309
0
0
null
null
null
null
UTF-8
C++
false
false
734
h
#ifndef TOOL_H #define TOOL_H #include <iostream> #include <map> #include <fstream> #include <string> #include <sstream> #include <stdlib.h> #include <cstring> #include "commandline.h" #include "configuration.h" #include "reportT.h" #ifndef ENUM_TYPES #define ENUM_TYPES enum OPER_TYPE_t {null_opr, help, run_t, set, print, save, exit_t}; enum FLAG_t {null_flag, report, count_t, interval, conf, blk_read, blk_read_s, blk_write, blk_write_s, kb_read, kb_write}; enum ARG3_PURPOSE_t {p0 = 0, p1 = 1, null_arg, filename, value}; #endif using namespace std; class tool{ public: tool(); ~tool(); void invalid_input(); void show_help(); bool run(commandline& cmdln, reportT& reporter, configuration& config); private: }; #endif
[ "aew0024@tigermail.auburn.edu" ]
aew0024@tigermail.auburn.edu
bbf32a414916b8a83b2b1e7ee007b3b09ba10f01
2cc63e61904c0b821b88687cbc7c20f4ffeb28cb
/2540 - Impeachment do Líder.cpp
aa96c6c116999f8deb71d9bf99c63b412f53402f
[]
no_license
lawrencesilva/URI
47557fbb007ccbfb00150d2cd503e8ab9bd0973a
1db51a14e7072099351e205abb691b191fb7d681
refs/heads/master
2020-03-24T02:08:58.630761
2018-07-26T11:12:00
2018-07-26T11:12:00
142,364,470
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
#include <iostream> #include <cmath> #include <iomanip> using namespace std; int main() { double doistercos, membrosd; int membros; int votaram = 0, voto; while(cin >> membros) { membrosd = membros; doistercos = (membrosd / 3) * 2; while(membros > 0) { cin >> voto; if(voto == 1) votaram++; membros--; } if(votaram >= doistercos) cout << "impeachment" << endl; else cout << "acusacao arquivada" << endl; votaram = 0; } return 0; }
[ "lawrencedowow@hotmail.com" ]
lawrencedowow@hotmail.com
546fbcad68bfb1f1b71af6e6755b315014149514
efa9be53cf1094300ed66fe09d19d3886de7e663
/tests/unit/plugins/dist_matrixops/dist_argmin_2_loc.cpp
7278a4b0473a3ac16e3c098a8189d79dfd935b79
[ "BSL-1.0" ]
permissive
STEllAR-GROUP/phylanx
25a6d1ecf8493fd77583d9b54ea4f6b7f2fcac63
443ba956e47c2c5ae1e3b6d0f51bb31930fa83e9
refs/heads/master
2022-04-30T13:57:26.767667
2022-04-06T13:57:01
2022-04-06T13:57:01
101,409,977
87
55
BSL-1.0
2022-04-06T13:57:02
2017-08-25T14:07:21
C++
UTF-8
C++
false
false
10,186
cpp
// Copyright (c) 2020 Bita Hasheminezhad // Copyright (c) 2020 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <phylanx/phylanx.hpp> #include <hpx/hpx_init.hpp> #include <hpx/iostream.hpp> #include <hpx/include/lcos.hpp> #include <hpx/modules/testing.hpp> #include <string> #include <utility> #include <vector> /////////////////////////////////////////////////////////////////////////////// phylanx::execution_tree::primitive_argument_type compile_and_run( std::string const& name, std::string const& codestr) { phylanx::execution_tree::compiler::function_list snippets; phylanx::execution_tree::compiler::environment env = phylanx::execution_tree::compiler::default_environment(); auto const& code = phylanx::execution_tree::compile(name, codestr, snippets, env); return code.run().arg_; } void test_argmin_d_operation(std::string const& name, std::string const& code, std::string const& expected_str) { phylanx::execution_tree::primitive_argument_type result = compile_and_run(name, code); phylanx::execution_tree::primitive_argument_type comparison = compile_and_run(name, expected_str); HPX_TEST_EQ(hpx::cout, result, comparison); } /////////////////////////////////////////////////////////////////////////////// void test_argmin_d_1d_0() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc1d_0", R"( argmin_d(annotate_d([42.0, 13.0], "array_0", list("args", list("locality", 0, 2), list("tile", list("columns", 0, 2))))) )", "2"); } else { test_argmin_d_operation("test_argmin_d_2loc1d_0", R"( argmin_d(annotate_d([1.0, 2.0, 33.0], "array_0", list("args", list("locality", 1, 2), list("tile", list("columns", 2, 5))))) )", "2"); } } void test_argmin_d_1d_1() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc1d_1", R"( argmin_d(annotate_d([42.0, -13.0, 1.0], "array_0", list("args", list("locality", 0, 2), list("tile", list("rows", 0, 3))))) )", "1"); } else { test_argmin_d_operation("test_argmin_d_2loc1d_1", R"( argmin_d(annotate_d([1.0, 2.0, 33.0], "array_0", list("args", list("locality", 1, 2), list("tile", list("rows", 3, 6))))) )", "1"); } } void test_argmin_d_1d_2() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc1d_2", R"( argmin_d(annotate_d([42.0, 13.0], "array_2", list("args", list("locality", 0, 2), list("tile", list("columns", 0, 2))))) )", "1"); } else { test_argmin_d_operation("test_argmin_d_2loc1d_2", R"( argmin_d(annotate_d([13.0, 22.0, 33.0], "array_2", list("args", list("locality", 1, 2), list("tile", list("columns", 2, 5))))) )", "1"); } } void test_argmin_d_1d_3() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc1d_3", R"( argmin_d(annotate_d([13.0, 22.0, 33.0], "array_3", list("tile", list("columns", 2, 5)))) )", "1"); } else { test_argmin_d_operation("test_argmin_d_2loc1d_3", R"( argmin_d(annotate_d([42.0, 13.0], "array_3", list("tile", list("columns", 0, 2)))) )", "1"); } } void test_argmin_d_1d_4() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc1d_4", R"( argmin_d(annotate_d(astype([], "int"), "array_4", list("tile", list("rows", 0, 0)))) )", "2"); } else { test_argmin_d_operation("test_argmin_d_2loc1d_4", R"( argmin_d(annotate_d([42, 13, -13], "array_4", list("tile", list("rows", 0, 3)))) )", "2"); } } void test_argmin_d_1d_5() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc1d_5", R"( argmin_d(annotate_d([42, 13, -13], "array_5", list("tile", list("rows", 0, 3)))) )", "2"); } else { test_argmin_d_operation("test_argmin_d_2loc1d_5", R"( argmin_d(annotate_d(astype([], "int"), "array_5", list("tile", list("rows", 0, 0)))) )", "2"); } } /////////////////////////////////////////////////////////////////////////////// void test_argmin_d_2d_0() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_0", R"( argmin_d(annotate_d([[4, 1, 2, 4], [1, 2, 3, 4]], "array2d_0", list("tile", list("columns", 0, 4), list("rows", 0, 2)))) )", "8"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_0", R"( argmin_d(annotate_d([[0, 3, 2, 0]], "array2d_0", list("tile", list("columns", 0, 4), list("rows", 2, 3)))) )", "8"); } } void test_argmin_d_2d_1() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_1", R"( argmin_d(annotate_d([[4, 1, 2, 4], [1, 2, 3, 4]], "array2d_1", list("tile", list("columns", 0, 4), list("rows", 0, 2))), -2) )", "[2, 0, 0, 2]"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_1", R"( argmin_d(annotate_d([[0, 3, 2, 0]], "array2d_1", list("tile", list("columns", 0, 4), list("rows", 2, 3))), -2) )", "[2, 0, 0, 2]"); } } void test_argmin_d_2d_2() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_2", R"( argmin_d(annotate_d([[4, 1, 2, 4], [1, 2, 3, 4]], "array2d_2", list("tile", list("columns", 0, 4), list("rows", 0, 2))), 1) )", R"( annotate_d([1, 0], "array2d_2/1", list("tile", list("columns", 0, 2))) )"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_2", R"( argmin_d(annotate_d([[0, 3, 2, 0]], "array2d_2", list("tile", list("columns", 0, 4), list("rows", 2, 3))), 1) )", R"( annotate_d([0], "array2d_2/1", list("tile", list("columns", 2, 3))) )"); } } void test_argmin_d_2d_3() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_3", R"( argmin_d(annotate_d([[2, 3, 4], [0, 0, 5], [5, 2, 3]], "array2d_3", list("tile", list("columns", 1, 4), list("rows", 0, 3)))) )", "5"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_3", R"( argmin_d(annotate_d([[1], [1], [0]], "array2d_3", list("tile", list("columns", 0, 1), list("rows", 0, 3)))) )", "5"); } } void test_argmin_d_2d_4() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_4", R"( argmin_d(annotate_d([[2, 3, 4], [0, 0, 5], [5, 2, 3]], "array2d_4", list("tile", list("columns", 1, 4), list("rows", 0, 3))), 0) )", R"( annotate_d([1, 1, 2], "array2d_4/1", list("tile", list("columns", 1, 4))) )"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_4", R"( argmin_d(annotate_d([[1], [1], [0]], "array2d_4", list("tile", list("columns", 0, 1), list("rows", 0, 3))), 0) )", R"( annotate_d([2], "array2d_4/1", list("tile", list("columns", 0, 1))) )"); } } void test_argmin_d_2d_5() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_5", R"( argmin_d(annotate_d([[2, 3, 4], [0, 0, 5], [5, 2, 3]], "array2d_5", list("tile", list("columns", 1, 4), list("rows", 0, 3))), -1) )", "[0, 1, 0]"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_5", R"( argmin_d(annotate_d([[1], [1], [0]], "array2d_5", list("tile", list("columns", 0, 1), list("rows", 0, 3))), -1) )", "[0, 1, 0]"); } } void test_argmin_d_2d_6() { if (hpx::get_locality_id() == 0) { test_argmin_d_operation("test_argmin_d_2loc2d_6", R"( argmin_d(annotate_d([[2, 3, 4], [0, 0, 5], [5, 2, 3]], "array2d_6", list("tile", list("columns", 0, 3), list("rows", 0, 3))), 0) )", R"( annotate_d([1, 1, 2], "array2d_6/1", list("tile", list("columns", 0, 3))) )"); } else { test_argmin_d_operation("test_argmin_d_2loc2d_6", R"( argmin_d(annotate_d(astype([[]], "int"), "array2d_6", list("tile", list("columns", 0, 0), list("rows", 0, 0))), 0) )", R"( annotate_d(astype([], "int"), "array2d_6/1", list("tile", list("columns", 0, 0))) )"); } } /////////////////////////////////////////////////////////////////////////////// int hpx_main(int argc, char* argv[]) { test_argmin_d_1d_0(); test_argmin_d_1d_1(); test_argmin_d_1d_2(); test_argmin_d_1d_3(); test_argmin_d_1d_4(); test_argmin_d_1d_5(); test_argmin_d_2d_0(); test_argmin_d_2d_1(); test_argmin_d_2d_2(); test_argmin_d_2d_3(); test_argmin_d_2d_4(); test_argmin_d_2d_5(); test_argmin_d_2d_6(); hpx::finalize(); return hpx::util::report_errors(); } int main(int argc, char* argv[]) { std::vector<std::string> cfg = { "hpx.run_hpx_main!=1" }; hpx::init_params params; params.cfg = std::move(cfg); return hpx::init(argc, argv, params); }
[ "hartmut.kaiser@gmail.com" ]
hartmut.kaiser@gmail.com
2654ba8306d37f166c6fc49167e356c7874626c6
15f92601d47d390ac454a717074d9661dae6a3ac
/example/im/src/entity/conversation.h
a0a0b3f4834434614b2a320270b8619d2d0d0a95
[ "MIT" ]
permissive
Zplutor/zaf
14ddf27bfb61a43fe9cfb5a38b519b25964ce1d7
312278af4f2f9cc99748ee8cc357532caafe62a0
refs/heads/master
2023-08-05T11:15:30.437396
2023-08-02T16:32:42
2023-08-02T16:32:42
45,374,274
15
8
null
null
null
null
UTF-8
C++
false
false
338
h
#pragma once #include <cstdint> #include <ctime> #include <string> #include <vector> #include "entity/id.h" #include "entity/user.h" class Conversation { public: Id id = InvalidId; std::wstring title; std::time_t last_updated_time = 0; std::vector<Id> members; bool is_sticked = false; bool is_silent = false; };
[ "zplutor@qq.com" ]
zplutor@qq.com
b99461a8d962c80d6f222ddcc59b7eaa0eaef942
a0d4416ed1cec0576086338201aae10f70ffbe47
/Kiselov_HW_Unicode/Convert.h
c4e665a30377ad8c6e254af28e4bc770c076b84a
[]
no_license
oKiselov/2016_08_27_WINAPI_Unicode
6924f77fa6727152609ebba5b0b5aa1cd4a02ce2
c4739dae50f18441de08aa9ddb116031a51a33b8
refs/heads/master
2020-12-08T17:52:20.106318
2016-09-04T15:14:00
2016-09-04T15:14:00
67,351,937
0
0
null
null
null
null
UTF-8
C++
false
false
864
h
#pragma once #include <iostream> #include <string> #include <Windows.h> class Convert { std::string mbString; std::wstring wcString; public: // Non-trivial member-functions and constructors Convert(); Convert(const std::string &, const std::wstring&); Convert(const Convert&); virtual ~Convert(); Convert&operator=(const Convert&); // Member-function of transformation from wide string into string static std::string WideCharToString(const std::wstring&); // Member-function of transformation from string into wide string static std::wstring StringToWideChar(const std::string&); // Member-functions of values settings int SetMultiByte(const std::string&); int SetWideChar(const std::wstring&); // Member-functions of values gettings const std::string&GetMultiByte(void)const; const std::wstring&GetWideChar(void)const; };
[ "dp.prk.kiselov@gmail.com" ]
dp.prk.kiselov@gmail.com
79d580b033d14575230a02b4386b0795efdd812d
0ee8dd745ef81204d09603700cdcc63acc96b814
/Cryptex/util.hpp
6632f2557aa0b43f38871375a31a607adec9120e
[]
no_license
sim642/Cryptex
1f3619eae21222c5e1c7dbd0b0d40bca216b2155
ac6d3ac671c969c1f86451c1f442bdca5ffb09c5
refs/heads/master
2020-04-13T21:07:20.894691
2016-12-04T20:38:31
2016-12-04T20:38:31
42,388,368
1
0
null
null
null
null
UTF-8
C++
false
false
245
hpp
#ifndef UTIL_H #define UTIL_H #include <type_traits> /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4380.html template<typename T> inline typename std::add_const<T>::type& as_const(T &t) noexcept { return t; } #endif // UTIL_H
[ "simmo.saan@gmail.com" ]
simmo.saan@gmail.com
0963a78c6ee5947c5ab04044f126eb89879f9d3a
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/third_party/WebKit/Source/core/css/properties/CSSPropertyAPIAnimationIterationCount.cpp
c86d6318a98d0404ec2e480fd4cb5eaaa4c86ffb
[ "BSD-3-Clause", "BSD-2-Clause", "LGPL-2.1-only", "LGPL-2.0-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
776
cpp
// Copyright 2017 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 "core/css/properties/CSSPropertyAPIAnimationIterationCount.h" #include "core/CSSValueKeywords.h" #include "core/css/parser/CSSPropertyParserHelpers.h" #include "core/css/properties/CSSPropertyAnimationIterationCountUtils.h" namespace blink { const CSSValue* CSSPropertyAPIAnimationIterationCount::ParseSingleValue( CSSParserTokenRange& range, const CSSParserContext&, const CSSParserLocalContext&) const { return CSSPropertyParserHelpers::ConsumeCommaSeparatedList( CSSPropertyAnimationIterationCountUtils::ConsumeAnimationIterationCount, range); } } // namespace blink
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
20ff076fe3078d28c98b53de8f63beeedabefb26
fad609ac22c6440bf392d3594314aaed627bff91
/meshes/shapes/Box.cpp
5168ecf1ac1b02a43f58f6e74abe4a3137ff2184
[]
no_license
WS002/GameEngine
9b1451cf2d52e2796ee2477927e9daba499adad4
2a6bdceaa7fdf0fb57853f083e4dde5c01bb5ee0
refs/heads/master
2021-01-13T01:36:09.256665
2015-05-19T18:54:11
2015-05-19T18:54:11
35,896,536
0
0
null
null
null
null
UTF-8
C++
false
false
6,039
cpp
#include "Box.hpp" Box::Box(glm::vec3 centerCoordinates, GLfloat width, GLfloat height, GLfloat depth): Mesh::Mesh(){ this->centerCoordinates = centerCoordinates; this->width = width; this->height = height; this->depth = depth; this->createBox(); } void Box::createBox() { //fill mesh parameters //Front Vertex v1; v1.Position = glm::vec3(centerCoordinates.x - width/2, centerCoordinates.y + height/2, centerCoordinates.z + depth/2); v1.TexCoords = glm::vec2(0, 1); v1.Normal = glm::vec3(0.0f, 0.0f, 1.0f); Vertex v2; v2.Position = glm::vec3(centerCoordinates.x - width/2, centerCoordinates.y - height/2, centerCoordinates.z + depth/2); v2.TexCoords = glm::vec2(0, 0); v2.Normal = v1.Normal; Vertex v3; v3.Position = glm::vec3(centerCoordinates.x + width/2, centerCoordinates.y - height/2, centerCoordinates.z + depth/2); v3.TexCoords = glm::vec2(1, 0); v3.Normal = v1.Normal; Vertex v4; v4.Position = glm::vec3(centerCoordinates.x + width/2, centerCoordinates.y + height/2, centerCoordinates.z + depth/2); v4.TexCoords = glm::vec2(1, 1); v4.Normal = v1.Normal; //Back Vertex v5; v5.Position = glm::vec3(centerCoordinates.x - width/2, centerCoordinates.y + height/2, centerCoordinates.z - depth/2); v5.TexCoords = glm::vec2(0, 1); v5.Normal = glm::vec3(0.0f, 0.0f, -1.0f); Vertex v6; v6.Position = glm::vec3(centerCoordinates.x - width/2, centerCoordinates.y - height/2, centerCoordinates.z - depth/2); v6.TexCoords = glm::vec2(0, 0); v6.Normal = v5.Normal; Vertex v7; v7.Position = glm::vec3(centerCoordinates.x + width/2, centerCoordinates.y - height/2, centerCoordinates.z - depth/2); v7.TexCoords = glm::vec2(1, 0); v7.Normal = v5.Normal; Vertex v8; v8.Position = glm::vec3(centerCoordinates.x + width/2, centerCoordinates.y + height/2, centerCoordinates.z - depth/2); v8.TexCoords = glm::vec2(1, 1); v8.Normal = v5.Normal; /* //Front this->calculatePerVertexNormal(&v1, &v2, &v4); this->calculatePerVertexNormal(&v4, &v2, &v3); //Left this->calculatePerVertexNormal(&v5, &v6, &v1); this->calculatePerVertexNormal(&v1, &v6, &v2); //Bottom this->calculatePerVertexNormal(&v6, &v2, &v7); this->calculatePerVertexNormal(&v7, &v2, &v3); //Right this->calculatePerVertexNormal(&v4, &v3, &v8); this->calculatePerVertexNormal(&v8, &v3, &v7); //Top this->calculatePerVertexNormal(&v5, &v1, &v8); this->calculatePerVertexNormal(&v8, &v1, &v4); //Back this->calculatePerVertexNormal(&v5, &v6, &v8); this->calculatePerVertexNormal(&v8, &v6, &v7); v1.Normal /= 5; v2.Normal /= 5; v3.Normal /= 4; v4.Normal /= 4; v5.Normal /= 3; v6.Normal /= 5; v7.Normal /= 4; v8.Normal /= 6; */ //Top Vertex v9; v9.Position = v5.Position; v9.TexCoords = glm::vec2(0, 1); v9.Normal = glm::vec3(0.0f, 1.0f, 0.0f); Vertex v10; v10.Position = v1.Position; v10.TexCoords = glm::vec2(0, 0); v10.Normal = v9.Normal; Vertex v11; v11.Position = v4.Position; v11.TexCoords = glm::vec2(1, 0); v11.Normal = v9.Normal; Vertex v12; v12.Position = v8.Position; v12.TexCoords = glm::vec2(1, 1); v12.Normal = v9.Normal; //Bottom Vertex v13; v13.Position = v6.Position; v13.TexCoords = glm::vec2(0, 1); v13.Normal = glm::vec3(0.0f, -1.0f, 0.0f); Vertex v14; v14.Position = v2.Position; v14.TexCoords = glm::vec2(0, 0); v14.Normal = v13.Normal; Vertex v15; v15.Position = v3.Position; v15.TexCoords = glm::vec2(1, 0); v15.Normal = v13.Normal; Vertex v16; v16.Position = v7.Position; v16.TexCoords = glm::vec2(1, 1); v16.Normal = v13.Normal; //Left Vertex v17; v17.Position = v5.Position; v17.TexCoords = glm::vec2(0, 1); v17.Normal = glm::vec3(-1.0f, 0.0f, 0.0f); Vertex v18; v18.Position = v6.Position; v18.TexCoords = glm::vec2(0, 0); v18.Normal = v17.Normal; Vertex v19; v19.Position = v2.Position; v19.TexCoords = glm::vec2(1, 0); v19.Normal = v17.Normal; Vertex v20; v20.Position = v1.Position; v20.TexCoords = glm::vec2(1, 1); v20.Normal = v17.Normal; //Right Vertex v21; v21.Position = v4.Position; v21.TexCoords = glm::vec2(0, 1); v21.Normal = glm::vec3(1.0f, 0.0f, 0.0f); Vertex v22; v22.Position = v3.Position; v22.TexCoords = glm::vec2(0, 0); v22.Normal = v21.Normal; Vertex v23; v23.Position = v7.Position; v23.TexCoords = glm::vec2(1, 0); v23.Normal = v21.Normal; Vertex v24; v24.Position = v8.Position; v24.TexCoords = glm::vec2(1, 1); v24.Normal = v21.Normal; this->vertices.push_back(v1); this->vertices.push_back(v2); this->vertices.push_back(v3); this->vertices.push_back(v4); this->vertices.push_back(v5); this->vertices.push_back(v6); this->vertices.push_back(v7); this->vertices.push_back(v8); this->vertices.push_back(v9); this->vertices.push_back(v10); this->vertices.push_back(v11); this->vertices.push_back(v12); this->vertices.push_back(v13); this->vertices.push_back(v14); this->vertices.push_back(v15); this->vertices.push_back(v16); this->vertices.push_back(v17); this->vertices.push_back(v18); this->vertices.push_back(v19); this->vertices.push_back(v20); this->vertices.push_back(v21); this->vertices.push_back(v22); this->vertices.push_back(v23); this->vertices.push_back(v24); const unsigned int arr[] = { 0, 1, 3, 1, 2, 3, 21, 20, 22, 20, 22, 23, 18, 17, 19, 19, 16, 17, 9, 10, 8, 10, 8, 11, 13, 12, 14, 14, 12, 15, 4, 5, 6, 4, 6, 7 }; std::vector<GLuint> indexVector(arr, arr + sizeof(arr) / sizeof(unsigned int)); this->indices = indexVector; this->setupMesh(); }
[ "ivanovnikolay25@yahoo.de" ]
ivanovnikolay25@yahoo.de
4557ee99828911b9063aa318d6418d551fe4d144
4b250da9813bd51979b7211778f720c0757eb82e
/tools/tests/gen_tree.cpp
697662cf23089b449589365337fb5f0389cd8421
[ "MIT" ]
permissive
mathemage/CompetitiveProgramming
07f7d4c269cca0b89955518131b01d037a5a1597
11a1a57c6ed144201b58eaeb34248f560f18d250
refs/heads/master
2023-04-16T17:55:24.948628
2023-04-14T19:16:54
2023-04-14T19:16:54
26,391,626
2
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
// generating a tree in a simple way #include <bits/stdc++.h> using namespace std; int rand(int a, int b) { return a + rand() % (b - a + 1); } int main(int argc, char* argv[]) { srand(atoi(argv[1])); int n = rand(2, 20); printf("%d\n", n); for(int i = 2; i <= n; ++i) { printf("%d %d\n", rand(1, i - 1), i); } }
[ "mathemage@gmail.com" ]
mathemage@gmail.com
be3820e8f4cd287c7a5680ba7c1067e121b956bc
7bf5c360d9e2ba3a3730c04266fcd88721824725
/game/g_world.cpp
da58adee6b8558cf6c4d47d1de2355fc7f23a579
[]
no_license
Qartar/quark
b773afd6a6882a6b25db5da4aa947fa9addf533a
8c516816367f11f72c9c1b4d45fd8cd75cd4e5cf
refs/heads/master
2022-06-14T10:56:39.564651
2020-07-31T17:21:10
2021-05-13T01:00:30
169,369,417
1
1
null
2019-10-18T06:16:27
2019-02-06T07:27:37
C++
UTF-8
C++
false
false
10,029
cpp
// g_world.cpp // #include "precompiled.h" #pragma hdrstop #include "g_aicontroller.h" #include "g_projectile.h" #include "g_ship.h" #include "g_player.h" #include "p_collide.h" #include "p_trace.h" #include <algorithm> #include <set> //////////////////////////////////////////////////////////////////////////////// namespace game { std::array<world*, world::max_worlds> world::_singletons{}; //------------------------------------------------------------------------------ world::world() : _sequence(0) , _physics( std::bind(&world::physics_filter_callback, this, std::placeholders::_1, std::placeholders::_2), std::bind(&world::physics_collide_callback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)) { for (_index = 0; _index < max_worlds; ++_index) { if (!_singletons[_index]) { _singletons[_index] = this; break; } } assert(_index < max_worlds); } //------------------------------------------------------------------------------ world::~world() { assert(_singletons[_index] == this); _singletons[_index] = nullptr; } //------------------------------------------------------------------------------ void world::init() { reset(); } //------------------------------------------------------------------------------ void world::shutdown() { clear(); } //------------------------------------------------------------------------------ void world::reset() { clear(); _sequence = 0; _framenum = 0; for (int ii = 0; ii < 3; ++ii) { float angle = float(ii) * (math::pi<float> * 2.f / 3.f); vec2 dir = vec2(std::cos(angle), std::sin(angle)); ship* sh = spawn<ship>(); sh->set_position(-dir * 192.f, true); sh->set_rotation(angle, true); // spawn ai controller to control the ship if (ii == 0) { spawn<player>(sh); } else { spawn<aicontroller>(sh); } } } //------------------------------------------------------------------------------ void world::clear() { _objects.clear(); // assign with empty queue because std::queue has no clear method _removed = std::queue<handle<game::object>>{}; _physics_objects.clear(); _particles.clear(); } //------------------------------------------------------------------------------ object_range<object const> world::objects() const { return object_range<object const>( _objects.data(), _objects.data() + _objects.size() ); } //------------------------------------------------------------------------------ object_range<object> world::objects() { return object_range<object>( _objects.data(), _objects.data() + _objects.size() ); } //------------------------------------------------------------------------------ void world::remove(handle<object> object) { _removed.push(object); } //------------------------------------------------------------------------------ void world::draw(render::system* renderer, time_value time) const { renderer->draw_starfield(); for (auto& obj : _objects) { // objects array is sparse if (!obj.get()) { continue; } obj->draw(renderer, time); } draw_particles(renderer, time); } //------------------------------------------------------------------------------ void world::run_frame() { _message.reset(); ++_framenum; while (_removed.size()) { if (_removed.front()) { _objects[_removed.front().get_index()] = nullptr; } _removed.pop(); } for (std::size_t ii = 0; ii < _objects.size(); ++ii) { // objects array is sparse if (!_objects[ii].get()) { continue; } // objects can spawn other objects, do not think this frame if (_objects[ii]->_spawn_time == frametime()) { continue; } _objects[ii]->think(); _objects[ii]->_old_position = _objects[ii]->get_position(); _objects[ii]->_old_rotation = _objects[ii]->get_rotation(); } _physics.step(FRAMETIME.to_seconds()); } //------------------------------------------------------------------------------ void world::read_snapshot(network::message& message) { while (_removed.size()) { if (_removed.front()) { _objects[_removed.front().get_index()] = nullptr; } _removed.pop(); } while (message.bytes_remaining()) { message_type type = static_cast<message_type>(message.read_byte()); if (type == message_type::none) { break; } switch (type) { case message_type::frame: read_frame(message); break; case message_type::sound: read_sound(message); break; case message_type::effect: read_effect(message); break; default: break; } } } //------------------------------------------------------------------------------ void world::read_frame(network::message const& /*message*/) { } //------------------------------------------------------------------------------ void world::read_sound(network::message const& message) { int asset = message.read_long(); vec2 position = message.read_vector(); float volume = message.read_float(); add_sound(static_cast<sound::asset>(asset), position, volume); } //------------------------------------------------------------------------------ void world::read_effect(network::message const& message) { float time = message.read_float(); int type = message.read_byte(); vec2 pos = message.read_vector(); vec2 vel = message.read_vector(); float strength = message.read_float(); add_effect(time_value::from_seconds(time), static_cast<game::effect_type>(type), pos, vel, strength); } //------------------------------------------------------------------------------ void world::write_snapshot(network::message& message) const { message.write_byte(svc_snapshot); // write frame message.write_byte(narrow_cast<uint8_t>(message_type::frame)); message.write_long(_framenum); // write active objects // ... // write sounds and effects message.write(_message); message.write_byte(narrow_cast<uint8_t>(message_type::none)); _message.rewind(); } //------------------------------------------------------------------------------ void world::write_sound(sound::asset sound_asset, vec2 position, float volume) { _message.write_byte(narrow_cast<uint8_t>(message_type::sound)); _message.write_long(narrow_cast<int>(sound_asset)); _message.write_vector(position); _message.write_float(volume); } //------------------------------------------------------------------------------ void world::write_effect(time_value time, effect_type type, vec2 position, vec2 direction, float strength) { _message.write_byte(narrow_cast<uint8_t>(message_type::effect)); _message.write_float(time.to_seconds()); _message.write_byte(narrow_cast<uint8_t>(type)); _message.write_vector(position); _message.write_vector(direction); _message.write_float(strength); } //------------------------------------------------------------------------------ game::object* world::trace(physics::contact& contact, vec2 start, vec2 end, game::object const* ignore) const { struct candidate { float fraction; physics::contact contact; game::object* object; bool operator<(candidate const& other) const { return fraction < other.fraction; } }; std::set<candidate> candidates; for (auto& other : _physics_objects) { if (other.second == ignore || other.second->_owner == ignore) { continue; } auto tr = physics::trace(other.first, start, end); if (tr.get_fraction() < 1.0f) { candidates.insert(candidate{ tr.get_fraction(), tr.get_contact(), other.second} ); } } if (candidates.size()) { contact = candidates.begin()->contact; return candidates.begin()->object; } return nullptr; } //------------------------------------------------------------------------------ void world::add_sound(sound::asset sound_asset, vec2 position, float volume) { write_sound(sound_asset, position, volume); pSound->play(sound_asset, vec3(position), volume, 1.0f); } //------------------------------------------------------------------------------ void world::add_body(game::object* owner, physics::rigid_body* body) { _physics.add_body(body); _physics_objects[body] = owner; } //------------------------------------------------------------------------------ void world::remove_body(physics::rigid_body* body) { _physics.remove_body(body); _physics_objects.erase(body); } //------------------------------------------------------------------------------ bool world::physics_filter_callback(physics::rigid_body const* body_a, physics::rigid_body const* body_b) { game::object* obj_a = _physics_objects[body_a]; game::object* obj_b = _physics_objects[body_b]; if (obj_b->is_type<projectile>()) { return false; } game::object const* owner_a = obj_a->_owner ? obj_a->_owner.get() : obj_a; game::object const* owner_b = obj_b->_owner ? obj_b->_owner.get() : obj_b; if (owner_a == owner_b) { return false; } return true; } //------------------------------------------------------------------------------ bool world::physics_collide_callback(physics::rigid_body const* body_a, physics::rigid_body const* body_b, physics::collision const& collision) { game::object* obj_a = _physics_objects[body_a]; game::object* obj_b = _physics_objects[body_b]; return obj_a->touch(obj_b, &collision); } } // namespace game
[ "qartar@live.com" ]
qartar@live.com
20c3351e4c53b81e813599d2e42f87aaa3822612
bf7173813f7f475e915df5fe16206de050f03050
/Engine/Engine.cpp
0d606998de449674bfba82d656d4d28a55311ca4
[ "MIT" ]
permissive
Archlisk/FrozenCore
0d67ef7b6899b594b7e352f659c9f4f281ed3f9e
2fad5e0ffbb74644cb63afaa29a93738342ab534
refs/heads/master
2022-12-02T07:10:39.186894
2020-08-20T05:34:00
2020-08-20T05:34:00
288,910,083
0
0
null
null
null
null
UTF-8
C++
false
false
3,184
cpp
#include <Engine.h> #include <Core/Config.h> #include <Core/RenderWindow.h> #include <Core/InputHandler.h> #include <Core/ResourceManager.h> #include <Core/Module.h> #include <Core/GameObject.h> #include <Core/GLM.h> #include <Render/RenderEngine.h> #include <Debug/FrameCounter.h> #include <Debug/Profiler.h> #include <GLFW/glfw3.h> #define CONFIG(str) \ (*m_config.get())[str] #define ENGINE_CONFIG_PATH "Data/Engine.conf" #undef Engine void Engine::Init() { Profiler::Create(); m_config = NewRef<Config>(ENGINE_CONFIG_PATH); if (!glfwInit()) throw std::runtime_error("Failed to initialize GLFW"); Vec2i window_resolution = Vec2i( CONFIG("Window")["Resolution"]["Width"].IntValue(), CONFIG("Window")["Resolution"]["Height"].IntValue() ); m_window = NewRef<RenderWindow>( window_resolution, CONFIG("Window")["Title"].StringValue(), CONFIG("Window")["Resizable"].IntValue(), CONFIG("Window")["Fullscreen"].IntValue() ); m_window->SetVSync(CONFIG("Window")["VSync"].IntValue()); m_resource_manager = NewRef<ResourceManager>(); m_render_engine = NewRef<RenderEngine>(m_window->GetResolution()); m_render_engine->Set2DShader(Shader::Load( CONFIG("Graphics")["GUIShader"]["Vertex"].StringValue(), CONFIG("Graphics")["GUIShader"]["Fragment"].StringValue() )); m_render_engine->SetTextShader(Shader::Load( CONFIG("Graphics")["TextShader"]["Vertex"].StringValue(), CONFIG("Graphics")["TextShader"]["Fragment"].StringValue() )); m_render_engine->SetClearColor(Vec3( CONFIG("Graphics")["ClearColor"]["r"].FloatValue(), CONFIG("Graphics")["ClearColor"]["g"].FloatValue(), CONFIG("Graphics")["ClearColor"]["b"].FloatValue() )); m_input_handler = NewRef<InputHandler>(*m_window.get()); m_track_performance = CONFIG("Debug")["Performance"]["Enabled"].IntValue(); if (m_track_performance) { m_performance_tracker = NewRef<FrameCounter>(); m_performance_tracker->SetInterval(CONFIG("Debug")["Performance"]["PrintInterval"].FloatValue()); } for (const Config::Value& val : CONFIG("Modules").Array()) m_modules.emplace_back(val.StringValue()); } Engine::~Engine() { for (auto& it : m_game_objects) delete it.second; Profiler::PrintSamples(); Profiler::Destroy(); glfwTerminate(); } void Engine::Inter_Run() { float last_time = glfwGetTime(); float current_time = glfwGetTime(); while (!m_exit) { last_time = current_time; current_time = glfwGetTime(); m_input_handler->Update(); glfwPollEvents(); if (m_window->ShouldClose()) Exit(); if (m_track_performance) m_performance_tracker->Sample(); // Update double delta = current_time - last_time; for (Module& mod : m_modules) mod.Update(delta); for (auto& it : m_game_objects) it.second->Update(delta); // Render 3D m_render_engine->Render3DBegin(); for (auto& it : m_game_objects) it.second->Render3D(); m_render_engine->Render3DEnd(); // Render 2D m_render_engine->Render2DBegin(); for (auto& it : m_game_objects) it.second->Render2D(); m_render_engine->Render2DEnd(); // Done m_window->SwapBuffers(); m_render_engine->Clear(); } }
[ "4rchlisk@gmail.com" ]
4rchlisk@gmail.com
f2e388901f7173fde8825518391166f10b8444b1
33b3f6d1094532a63c26d8151ba01af99761c3e7
/frameparam.h
f5f6da895a1f5a50d632aa15ba7b7c14e46ffc23
[]
no_license
Liberisi/foxconn
f6633292c4b823c232acb62fb309616378cda30e
ce9ac3e5a09383b641e9307172544a725d96aca9
refs/heads/master
2021-02-14T06:33:45.286351
2020-06-19T10:30:30
2020-06-19T10:30:30
244,780,720
0
3
null
null
null
null
UTF-8
C++
false
false
1,581
h
#ifndef FRAMEPARAM_H #define FRAMEPARAM_H #include <string> using namespace std; class FrameParam { public: FrameParam(); void read_param(const string& path); void write_param(const string& path); void set_x(int x); void set_y(int y); void set_w(int w); void set_h(int h); void set_magic_w(int magic_w); void set_magic_h(int magic_h); void set_lx(int x) { lx_ = x;} void set_ly(int y) { ly_ = y;} void set_lw(int w) { lw_ = w;} void set_lh(int h) { lh_ = h;} void set_rx(int x) { rx_ = x;} void set_ry(int y) { ry_ = y;} void set_rw(int w) { rw_ = w;} void set_rh(int h) { rh_ = h;} void set_side_hand_magic_h(int t) { side_hand_magic_h_ = t;} void set_side_hand_magic_w(int t) { side_hand_magic_w_ = t;} int x() {return x_;} int y() {return y_;} int w() {return w_;} int h() {return h_;} int magic_w() {return magic_w_;} int magic_h() {return magic_h_;} int lx() {return lx_;} int ly() {return ly_;} int lw() {return lw_;} int lh() {return lh_;} int rx() {return rx_;} int ry() {return ry_;} int rw() {return rw_;} int rh() {return rh_;} int side_hand_magic_h() {return side_hand_magic_h_;} int side_hand_magic_w() {return side_hand_magic_w_;} private: int x_; int y_; int w_; int h_; int magic_w_; int magic_h_; int lx_; int ly_; int lw_; int lh_; int side_hand_magic_w_; int rx_; int ry_; int rw_; int rh_; int side_hand_magic_h_; }; #endif // FRAMEPARAM_H
[ "wen-1431@qq.com" ]
wen-1431@qq.com
d6a6626ce6338df5ae951c56af1f5fdbd498f79c
3c36455a00bfc4484f41e251d66edead6cbb23f5
/src/demo_9/usestok0.cpp
8e12be74f0ceeb1afd6df8b27d98ef4ee333e3a6
[]
no_license
jerryxiee/linux-demo
f8b3034d75cae3125ba821a220c375dedd277a49
c1338e03f8ff82ae34ee49fd11a9f4690aed54be
refs/heads/master
2022-01-21T20:46:43.158451
2019-02-02T13:16:37
2019-02-02T13:16:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
// usestok0.cpp -- the client program // compile with stock.cpp #include <iostream> #include "demo_9/stock00.h" int use_stock00_test() { Stock fluffy_the_cat; fluffy_the_cat.acquire("NanoSmart", 20, 12.50); fluffy_the_cat.show(); fluffy_the_cat.buy(15, 18.125); fluffy_the_cat.show(); fluffy_the_cat.sell(400, 20.00); fluffy_the_cat.show(); fluffy_the_cat.buy(300000,40.125); fluffy_the_cat.show(); fluffy_the_cat.sell(300000,0.125); fluffy_the_cat.show(); // std::cin.get(); return 0; }
[ "wellok@139.com" ]
wellok@139.com
1d4acf9f3f2ea883f9f82c12c0073845b2f1dd02
24b33483a2c2a71885b21424ad42e653b14fa617
/src/qt/qrcodedialog.cpp
10d4b78a319fcd07c767cfce21ab961399b2d30b
[ "MIT" ]
permissive
Checoinbank/Checoin
23dceed267ea0eee64edab052237dbfa589f6063
436db740a68c1e6218cbaef9433bf7ea4cb433ee
refs/heads/main
2023-05-04T15:13:03.382402
2021-05-17T13:05:02
2021-05-17T13:05:02
368,186,636
2
0
null
null
null
null
UTF-8
C++
false
false
4,311
cpp
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("Chécoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
[ "kachhdiyajaydip@gmail.com" ]
kachhdiyajaydip@gmail.com
bf2ac61bf30fcbe7a77e75fdef114313bdd504c8
8ff6b90b1ce5312ebc1a2ed3579eed5cc102bec0
/target/platformio/test/test_oz_game/test_oz_game.cpp
969b7b17bff107ca5ea8ccebb11395453301884f
[]
no_license
dcowden/battlepoint
a208aef872c5eccff260254c599c6b67fdd0383a
ed13314fb6bb5a1c96301aa9dc4b7997df31a9c3
refs/heads/master
2022-01-20T01:36:01.150910
2021-12-24T22:54:49
2021-12-24T22:54:49
135,941,061
0
1
null
null
null
null
UTF-8
C++
false
false
3,423
cpp
#include <Arduino.h> #include <unity.h> #include <game.h> #include <ArduinoLog.h> #define DEFAULT_UPDATE_TIME 10000 GameState state; GameSettings settings; long current_time_ms = 0; void preTest(){ settings.gameType = GameType::GAME_TYPE_KOTH_FIRST_TO_OWN_TIME; settings.timed.max_duration_seconds=20; settings.timed.countdown_start_seconds=5; settings.timed.max_overtime_seconds=30; settings.capture.hits_to_capture=15; settings.timed.ownership_time_seconds = 10; startGame(&state,&settings,current_time_ms); } void assertEndedWithWinner ( Team t){ TEST_ASSERT_EQUAL(GameStatus::GAME_STATUS_ENDED, state.status); TEST_ASSERT_EQUAL(t, state.result.winner ); } void test_in_progress_pregame(){ preTest(); updateGame(&state,settings,2000); TEST_ASSERT_EQUAL(GameStatus::GAME_STATUS_PREGAME, state.status ); } void test_in_progress_ingame(){ preTest(); state.ownership.owner = Team::RED; updateGame(&state,settings,10000); TEST_ASSERT_EQUAL( GameStatus::GAME_STATUS_RUNNING,state.status); } void test_clear_victory(){ preTest(); state.ownership.owner = Team::RED; state.ownership.red_millis=10001; state.ownership.blu_millis=2220; updateGame(&state,settings,DEFAULT_UPDATE_TIME); assertEndedWithWinner( Team::RED); } void test_capture_overtime_time_is_not_up(){ preTest(); state.ownership.overtime_remaining_millis = 200; state.ownership.owner = Team::RED; state.ownership.red_millis=120001; state.ownership.blu_millis=32220; state.ownership.capturing=Team::BLU; state.ownership.capture_hits=4; updateGame(&state,settings,DEFAULT_UPDATE_TIME); TEST_ASSERT_EQUAL(GameStatus::GAME_STATUS_OVERTIME, state.status ); } void test_overtime_time_is_up(){ preTest(); state.ownership.overtime_remaining_millis = 200; state.ownership.owner = Team::RED; state.ownership.red_millis=120001; state.ownership.blu_millis=32220; state.ownership.capturing=Team::BLU; state.ownership.capture_hits=4; updateGame(&state,settings,DEFAULT_UPDATE_TIME); TEST_ASSERT_EQUAL( GameStatus::GAME_STATUS_OVERTIME,state.status ); } void test_time_is_up_nbody_capturing(){ preTest(); state.ownership.owner = Team::RED; state.ownership.red_millis=11000; state.ownership.blu_millis=8000; state.ownership.capturing=Team::NOBODY; state.ownership.capture_hits=0; updateGame(&state,settings,26000); //game ends at t=25 updateGame(&state,settings,27000); assertEndedWithWinner( Team::RED); } void test_time_is_up_overtime_is_up_too_capturing(){ preTest(); state.ownership.owner = Team::RED; state.ownership.red_millis=40000; state.ownership.blu_millis=30000; state.ownership.capturing=Team::BLU; updateGame(&state,settings,60000); updateGame(&state,settings,61000); assertEndedWithWinner( Team::RED); } void setup() { delay(1000); Serial.begin(115200); Log.begin(LOG_LEVEL_VERBOSE, &Serial, true); UNITY_BEGIN(); RUN_TEST(test_in_progress_pregame); RUN_TEST(test_in_progress_ingame); RUN_TEST(test_clear_victory); RUN_TEST(test_capture_overtime_time_is_not_up); RUN_TEST(test_overtime_time_is_up); RUN_TEST(test_time_is_up_nbody_capturing); RUN_TEST(test_time_is_up_overtime_is_up_too_capturing); UNITY_END(); } void loop() { delay(500); }
[ "dave.cowden@gmail.com" ]
dave.cowden@gmail.com
9a318da974bcb68335341a09fc8b17f9a7c4c20a
11cd65ab418283f31ded8a81304fa9abb70c9c74
/SDK/LibImath/src/src/ImathTest/testBitPatterns.cpp
d3418104543a0ff6cbf39229758d435917cc5eaf
[ "BSD-3-Clause" ]
permissive
sim9108/SDKS
16affd227b21ff40454e7fffd0fcde3ac7ad6844
358ff46d925de151c422ee008e1ddaea6be3d067
refs/heads/main
2023-03-15T22:47:10.973000
2022-05-16T12:50:00
2022-05-16T12:50:00
27,232,062
2
0
null
null
null
null
UTF-8
C++
false
false
15,678
cpp
// // SPDX-License-Identifier: BSD-3-Clause // Copyright Contributors to the OpenEXR Project. // #ifdef NDEBUG # undef NDEBUG #endif #include <half.h> #include <assert.h> #include <float.h> #include <iostream> #include <string.h> #include "testBitPatterns.h" using namespace std; namespace { bool equalBitPatterns (const char* b1, const char* b2) { // // Returns true if the characters in zero-terminated string b1 // are the same as the charaters in string b2, except for places // where b1 or b2 contains an 'X'. For example: // // equalBitPatterns ("100", "100") returns true // equalBitPatterns ("100", "101") returns false // equalBitPatterns ("10X", "101") returns true // equalBitPatterns ("10X", "100") returns true // while (*b1 && *b2) { if (*b1 != *b2 && *b1 != 'X' && *b2 != 'X') return false; ++b1; ++b2; } return !(*b1 || *b2); } void testBits (float f, const char bh[19], const char bg[35]) { half h (f); float g (h); cout.width (15); cout.precision (8); cout << f << " "; printBits (cout, f); cout << " "; printBits (cout, h); cout << '\n'; cout.width (15); cout << g << " "; printBits (cout, g); cout << "\n\n"; if (bh || bg) { char ch[19], cg[35]; printBits (ch, h); printBits (cg, g); if (!equalBitPatterns (ch, bh)) { cout << "error: expected " << bh << ", got " << ch << endl; assert (false); } if (!equalBitPatterns (cg, bg)) { cout << "error: expected " << bg << ", got " << cg << endl; assert (false); } } } float floatPosInfinity() { half::uif x; x.i = 0x7f800000; return x.f; } float floatNegInfinity() { half::uif x; x.i = 0xff800000; return x.f; } float floatPosQNan1() { half::uif x; x.i = 0x7fffffff; return x.f; } float floatNegQNan1() { half::uif x; x.i = 0xffffffff; return x.f; } float floatPosQNan2() { half::uif x; x.i = 0x7fd55555; return x.f; } float floatNegQNan2() { half::uif x; x.i = 0xffd55555; return x.f; } } // namespace void testBitPatterns() { cout << "specific bit patterns\n\n"; // // Numbers close to 1.0 // testBits (1.0f, "0 01111 0000000000", "0 01111111 00000000000000000000000"); testBits (1.0f + HALF_EPSILON, "0 01111 0000000001", "0 01111111 00000000010000000000000"); testBits (1.0f + HALF_EPSILON * 0.5f, "0 01111 0000000000", "0 01111111 00000000000000000000000"); testBits (1.0f + HALF_EPSILON * 0.4999f, "0 01111 0000000000", "0 01111111 00000000000000000000000"); testBits (1.0f + HALF_EPSILON * 0.5001f, "0 01111 0000000001", "0 01111111 00000000010000000000000"); testBits (1.0f + HALF_EPSILON + HALF_EPSILON, "0 01111 0000000010", "0 01111111 00000000100000000000000"); testBits (1.0f + HALF_EPSILON + HALF_EPSILON * 0.5f, "0 01111 0000000010", "0 01111111 00000000100000000000000"); testBits (1.0f + HALF_EPSILON + HALF_EPSILON * 0.4999f, "0 01111 0000000001", "0 01111111 00000000010000000000000"); testBits (1.0f + HALF_EPSILON + HALF_EPSILON * 0.5001f, "0 01111 0000000010", "0 01111111 00000000100000000000000"); testBits (1.0f - HALF_EPSILON * 0.5f, "0 01110 1111111111", "0 01111110 11111111110000000000000"); testBits (1.0f - HALF_EPSILON * 0.5f * 0.5f, "0 01111 0000000000", "0 01111111 00000000000000000000000"); testBits (1.0f - HALF_EPSILON * 0.5f * 0.4999f, "0 01111 0000000000", "0 01111111 00000000000000000000000"); testBits (1.0f - HALF_EPSILON * 0.5f * 0.5001f, "0 01110 1111111111", "0 01111110 11111111110000000000000"); // // Numbers close to HALF_DENORM_MIN // testBits (HALF_DENORM_MIN, "0 00000 0000000001", "0 01100111 00000000000000000000000"); testBits (HALF_DENORM_MIN + HALF_DENORM_MIN, "0 00000 0000000010", "0 01101000 00000000000000000000000"); testBits (HALF_DENORM_MIN + HALF_DENORM_MIN * 0.5f, "0 00000 0000000010", "0 01101000 00000000000000000000000"); testBits (HALF_DENORM_MIN + HALF_DENORM_MIN * 0.4999f, "0 00000 0000000001", "0 01100111 00000000000000000000000"); testBits (HALF_DENORM_MIN + HALF_DENORM_MIN * 0.5001f, "0 00000 0000000010", "0 01101000 00000000000000000000000"); testBits (HALF_DENORM_MIN - HALF_DENORM_MIN, // NOSONAR - suppress SonarCloud bug report. "0 00000 0000000000", "0 00000000 00000000000000000000000"); testBits (HALF_DENORM_MIN - HALF_DENORM_MIN * 0.5f, "0 00000 0000000000", "0 00000000 00000000000000000000000"); testBits (HALF_DENORM_MIN - HALF_DENORM_MIN * 0.4999f, "0 00000 0000000001", "0 01100111 00000000000000000000000"); testBits (HALF_DENORM_MIN - HALF_DENORM_MIN * 0.5001f, "0 00000 0000000000", "0 00000000 00000000000000000000000"); // // Numbers close to HALF_NRM_MIN // testBits (HALF_NRM_MIN, "0 00001 0000000000", "0 01110001 00000000000000000000000"); testBits (HALF_NRM_MIN + HALF_DENORM_MIN, "0 00001 0000000001", "0 01110001 00000000010000000000000"); testBits (HALF_NRM_MIN + HALF_DENORM_MIN * 0.5f, "0 00001 0000000000", "0 01110001 00000000000000000000000"); testBits (HALF_NRM_MIN + HALF_DENORM_MIN * 0.4999f, "0 00001 0000000000", "0 01110001 00000000000000000000000"); testBits (HALF_NRM_MIN + HALF_DENORM_MIN * 0.5001f, "0 00001 0000000001", "0 01110001 00000000010000000000000"); testBits (HALF_NRM_MIN - HALF_DENORM_MIN, "0 00000 1111111111", "0 01110000 11111111100000000000000"); testBits (HALF_NRM_MIN - HALF_DENORM_MIN * 0.5f, "0 00001 0000000000", "0 01110001 00000000000000000000000"); testBits (HALF_NRM_MIN - HALF_DENORM_MIN * 0.49995f, "0 00001 0000000000", "0 01110001 00000000000000000000000"); testBits (HALF_NRM_MIN - HALF_DENORM_MIN * 0.50005f, "0 00000 1111111111", "0 01110000 11111111100000000000000"); // // Small positive integers and simple decimal fractions // testBits (2, "0 10000 0000000000", "0 10000000 00000000000000000000000"); testBits (3, "0 10000 1000000000", "0 10000000 10000000000000000000000"); testBits (10, "0 10010 0100000000", "0 10000010 01000000000000000000000"); testBits (0.1f, "0 01011 1001100110", "0 01111011 10011001100000000000000"); testBits (0.2f, "0 01100 1001100110", "0 01111100 10011001100000000000000"); testBits (0.3f, "0 01101 0011001101", "0 01111101 00110011010000000000000"); // // Numbers close to HALF_MAX // testBits (HALF_MAX, "0 11110 1111111111", "0 10001110 11111111110000000000000"); testBits ((1 << HALF_MAX_EXP) * 1.0, "0 11111 0000000000", // +infinity "0 11111111 00000000000000000000000"); // +infinity testBits ((1 << HALF_MAX_EXP) * (1.0f - HALF_EPSILON * 0.25f), "0 11111 0000000000", // +infinity "0 11111111 00000000000000000000000"); // +infinity testBits ((1 << HALF_MAX_EXP) * (1.0f - HALF_EPSILON * 0.25005f), "0 11110 1111111111", "0 10001110 11111111110000000000000"); testBits ((1 << HALF_MAX_EXP) * (1.0f - HALF_EPSILON * 0.24995f), "0 11111 0000000000", // +infinity "0 11111111 00000000000000000000000"); // +infinity // // Large positive numbers, positive infinity and NANs // testBits (HALF_MAX * HALF_MAX, "0 11111 0000000000", // +infinity "0 11111111 00000000000000000000000"); // +infinity testBits (FLT_MAX, "0 11111 0000000000", // +infinity "0 11111111 00000000000000000000000"); // +infinity testBits (floatPosInfinity(), "0 11111 0000000000", // +infinity "0 11111111 00000000000000000000000"); // +infinity testBits (floatPosQNan1(), "0 11111 1111111111", // nan "0 11111111 11111111110000000000000"); // nan testBits (floatPosQNan2(), "0 11111 1010101010", // nan "0 11111111 10101010100000000000000"); // nan // // Numbers close to -1.0 // testBits (-1.0, "1 01111 0000000000", "1 01111111 00000000000000000000000"); testBits (-(1.0f + HALF_EPSILON), "1 01111 0000000001", "1 01111111 00000000010000000000000"); testBits (-(1.0f + HALF_EPSILON * 0.5f), "1 01111 0000000000", "1 01111111 00000000000000000000000"); testBits (-(1.0f + HALF_EPSILON * 0.4999f), "1 01111 0000000000", "1 01111111 00000000000000000000000"); testBits (-(1.0f + HALF_EPSILON * 0.5001f), "1 01111 0000000001", "1 01111111 00000000010000000000000"); testBits (-(1.0f + HALF_EPSILON + HALF_EPSILON), "1 01111 0000000010", "1 01111111 00000000100000000000000"); testBits (-(1.0f + HALF_EPSILON + HALF_EPSILON * 0.5f), "1 01111 0000000010", "1 01111111 00000000100000000000000"); testBits (-(1.0f + HALF_EPSILON + HALF_EPSILON * 0.4999f), "1 01111 0000000001", "1 01111111 00000000010000000000000"); testBits (-(1.0f + HALF_EPSILON + HALF_EPSILON * 0.5001f), "1 01111 0000000010", "1 01111111 00000000100000000000000"); testBits (-(1.0f - HALF_EPSILON * 0.5f), "1 01110 1111111111", "1 01111110 11111111110000000000000"); testBits (-(1.0f - HALF_EPSILON * 0.5f * 0.5f), "1 01111 0000000000", "1 01111111 00000000000000000000000"); testBits (-(1.0f - HALF_EPSILON * 0.5f * 0.4999f), "1 01111 0000000000", "1 01111111 00000000000000000000000"); testBits (-(1.0f - HALF_EPSILON * 0.5f * 0.5001f), "1 01110 1111111111", "1 01111110 11111111110000000000000"); // // Numbers close to -HALF_DENORM_MIN // testBits (-HALF_DENORM_MIN, "1 00000 0000000001", "1 01100111 00000000000000000000000"); testBits (-(HALF_DENORM_MIN + HALF_DENORM_MIN), "1 00000 0000000010", "1 01101000 00000000000000000000000"); testBits (-(HALF_DENORM_MIN + HALF_DENORM_MIN * 0.5f), "1 00000 0000000010", "1 01101000 00000000000000000000000"); testBits (-(HALF_DENORM_MIN + HALF_DENORM_MIN * 0.4999f), "1 00000 0000000001", "1 01100111 00000000000000000000000"); testBits (-(HALF_DENORM_MIN + HALF_DENORM_MIN * 0.5001f), "1 00000 0000000010", "1 01101000 00000000000000000000000"); testBits (-(HALF_DENORM_MIN - HALF_DENORM_MIN), // NOSONAR - suppress SonarCloud bug report. "X 00000 0000000000", "X 00000000 00000000000000000000000"); testBits (-(HALF_DENORM_MIN - HALF_DENORM_MIN * 0.5f), "1 00000 0000000000", "1 00000000 00000000000000000000000"); testBits (-(HALF_DENORM_MIN - HALF_DENORM_MIN * 0.4999f), "1 00000 0000000001", "1 01100111 00000000000000000000000"); testBits (-(HALF_DENORM_MIN - HALF_DENORM_MIN * 0.5001f), "1 00000 0000000000", "1 00000000 00000000000000000000000"); // // Numbers close to -HALF_NRM_MIN // testBits (-HALF_NRM_MIN, "1 00001 0000000000", "1 01110001 00000000000000000000000"); testBits (-(HALF_NRM_MIN + HALF_DENORM_MIN), "1 00001 0000000001", "1 01110001 00000000010000000000000"); testBits (-(HALF_NRM_MIN + HALF_DENORM_MIN * 0.5f), "1 00001 0000000000", "1 01110001 00000000000000000000000"); testBits (-(HALF_NRM_MIN + HALF_DENORM_MIN * 0.4999f), "1 00001 0000000000", "1 01110001 00000000000000000000000"); testBits (-(HALF_NRM_MIN + HALF_DENORM_MIN * 0.5001f), "1 00001 0000000001", "1 01110001 00000000010000000000000"); testBits (-(HALF_NRM_MIN - HALF_DENORM_MIN), "1 00000 1111111111", "1 01110000 11111111100000000000000"); testBits (-(HALF_NRM_MIN - HALF_DENORM_MIN * 0.5f), "1 00001 0000000000", "1 01110001 00000000000000000000000"); testBits (-(HALF_NRM_MIN - HALF_DENORM_MIN * 0.49995f), "1 00001 0000000000", "1 01110001 00000000000000000000000"); testBits (-(HALF_NRM_MIN - HALF_DENORM_MIN * 0.50005f), "1 00000 1111111111", "1 01110000 11111111100000000000000"); // // Small negative integers and simple decimal fractions // testBits (-2, "1 10000 0000000000", "1 10000000 00000000000000000000000"); testBits (-3, "1 10000 1000000000", "1 10000000 10000000000000000000000"); testBits (-10, "1 10010 0100000000", "1 10000010 01000000000000000000000"); testBits (-0.1f, "1 01011 1001100110", "1 01111011 10011001100000000000000"); testBits (-0.2f, "1 01100 1001100110", "1 01111100 10011001100000000000000"); testBits (-0.3f, "1 01101 0011001101", "1 01111101 00110011010000000000000"); // // Numbers close to -HALF_MAX // testBits (-HALF_MAX, "1 11110 1111111111", "1 10001110 11111111110000000000000"); testBits (-(1 << HALF_MAX_EXP) * 1.0f, "1 11111 0000000000", // +infinity "1 11111111 00000000000000000000000"); // +infinity testBits (-(1 << HALF_MAX_EXP) * (1.0f - HALF_EPSILON * 0.25f), "1 11111 0000000000", // +infinity "1 11111111 00000000000000000000000"); // +infinity testBits (-(1 << HALF_MAX_EXP) * (1.0f - HALF_EPSILON * 0.25005f), "1 11110 1111111111", "1 10001110 11111111110000000000000"); testBits (-(1 << HALF_MAX_EXP) * (1.0f - HALF_EPSILON * 0.24995f), "1 11111 0000000000", // +infinity "1 11111111 00000000000000000000000"); // +infinity // // Large negative numbers, negative infinity and NANs // testBits (-HALF_MAX * HALF_MAX, "1 11111 0000000000", // +infinity "1 11111111 00000000000000000000000"); // +infinity testBits (-FLT_MAX, "1 11111 0000000000", // +infinity "1 11111111 00000000000000000000000"); // +infinity testBits (floatNegInfinity(), "1 11111 0000000000", // +infinity "1 11111111 00000000000000000000000"); // +infinity testBits (floatNegQNan1(), "1 11111 1111111111", // nan "1 11111111 11111111110000000000000"); // nan testBits (floatNegQNan2(), "1 11111 1010101010", // nan "1 11111111 10101010100000000000000"); // nan cout << "ok\n\n" << flush; }
[ "sim910@naver.com" ]
sim910@naver.com
4e475a391fce2f4660d95a793c53d83a75e38569
2eb5c16df3bb1ba736a845f6bbc32bd7db29043a
/CodingInterviews/solution/04/replaceSpace.cc
eef13533f683b616ff4c4962048539464b02f445
[]
no_license
wowforestwow/TrainingCode
153ef46c437a8e1e0370b7153fb986a6af4a49f6
02912d6c331e7850ad7962c96075f7cc5ec66f84
refs/heads/master
2020-12-30T16:15:08.871765
2017-09-24T03:19:23
2017-09-24T03:19:23
90,969,202
0
0
null
null
null
null
UTF-8
C++
false
false
261
cc
#include<bits/stdc++.h> using namespace std; class Solution { public: void replaceSpace(char *str,int length) { int i = 4; cout << endl; } }; int main(){ Solution s; char str[] = "hel"; s.replaceSpace(str, 4); } /*int main(){*/ //Solution s; /*}*/
[ "httloveforest@163.com" ]
httloveforest@163.com
9c2692c739dd815188ffc75c1af1748bc86b3cf4
3391892861a1e1e71af6e414bcdb9fc0df66c62e
/src/client/places/action/action_view.cpp
d00e2584a8bedddddc15043aa103d777c61d2aea
[ "Apache-2.0" ]
permissive
jdmclark/gorc
a21208b1d03a85fc5a99fdd51fdad27446cc4767
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
refs/heads/develop
2021-01-21T05:01:26.609783
2020-12-21T00:26:22
2020-12-21T02:34:31
10,290,074
103
10
Apache-2.0
2020-12-21T02:34:33
2013-05-25T21:27:37
C++
UTF-8
C++
false
false
372
cpp
#include "action_view.hpp" #include "action_presenter.hpp" #include <iostream> gorc::client::action::action_view::action_view() { return; } gorc::maybe<gorc::input::input_adapter*> gorc::client::action::action_view::get_input_adapter() { return maybe_if(presenter, nothing, [](action_presenter *p) { return make_maybe(&p->get_input_adapter()); }); }
[ "jon@nullptr.ca" ]
jon@nullptr.ca