blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
158
a7e3ce26208009be0421e68088c088e2bd40aa0c
d1e4718197ba3bddd13d6f6958e1d5a492b51af5
/Object/Visitor.cpp
a1c2099a2e28813db295b6fc896ddc296182eac7
[]
no_license
reisoftware/ap2d
1f398664fdc4f8cab9479df18cd2a745f904cdff
e09732655ef66e13e98b8f3b008c91dac541e1f5
refs/heads/master
2022-01-22T05:36:56.295845
2022-01-04T05:31:57
2022-01-04T05:31:57
162,372,004
1
0
null
null
null
null
UTF-8
C++
false
false
352
cpp
// Visitor.cpp: implementation of the Visitor class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Visitor.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction //////////////////////////////////////////////////////////////////////
0d26f5287df086cfcd1d34071ac735b1f4e4794c
b14e9a12edb401b942ef2cc7224c7e95ba2e2ae6
/policy/common.h
4d3b5608dcf7182a46449a66722a8a795ffc5f4c
[]
no_license
donaldong/caching
f341f4c51e55f4f4800419f0df8fffeeecae47fc
69f3c40c772e6e28dc03f8c7b95bf78ffa54fbde
refs/heads/master
2021-03-27T13:33:48.207280
2018-05-12T15:58:35
2018-05-12T15:58:35
117,311,735
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
h
#include <algorithm> #include <climits> #include <cmath> #include <cstdio> #include <cstring> #include <deque> #include <iostream> #include <map> #include <queue> #include <regex> #include <set> #include <sstream> #include <stack> #include <unordered_map> #include <unordered_set> #include <vector> #include <fstream> #include <random> using namespace std; typedef long long int ll; typedef unsigned long long int ull; typedef long double ld; typedef unsigned int uint; #define hmap unordered_map #define hset unordered_set #define pq priority_queue #define pb push_back #define mp make_pair #define putchar putchar_unlocked inline int to_int(char *p) { int res = 0, i = 0; while (p[i] >= '0' && p[i] <= '9') { res = res * 10 + p[i++] - '0'; } return res; } string rstrip(const char *str, char c) { string s(str); int i = s.rfind(c); if (i < 0) return s; return s.substr(0, i); } ll get_file_size(ifstream &fs) { fs.seekg (0, fs.end); ll size = fs.tellg(); fs.seekg(0, fs.beg); return size; }
84243942e4d84e8ee9a68962a8c832569cf6b208
caf8c4d72e06fe214330e62bb3e3578da4380780
/src/particle.cpp
1c1cb2ec85a3ed6f5c7f29dbddff3145dd725998
[]
no_license
bricolete/openFrameworks
f345c683e9de175333d600becd1490f21b2be8d8
493a6b7ab56ffe0fd76a360915b21299f4a41405
refs/heads/master
2020-11-28T01:08:08.826991
2019-12-23T04:07:46
2019-12-23T04:07:46
229,665,477
0
0
null
null
null
null
UTF-8
C++
false
false
767
cpp
// // particle.cpp // VectorField3 // // Created by 堀内隆仁 on 2018/04/27. // #include "particle.hpp" void Particle::setP(ofVec2f _p){ p.set(_p); } void Particle::update(ofVec2f _v){ //ofApp内でaをsetしたのち、以下 //point[0] = p; //a -= v * 0.03;//friction //v = v + a; v = _v; p = p + v; //point[1] = p; } void Particle::draw(){ //ofSetLineWidth(3); //ofColor c; //float hue = ofMap(v.length(), 0, 3*PI, 0, 360); //c.setHueAngle(330); c1 = ofMap(v.x, 0, 3*PI, 100, 255); c2 = ofMap(v.y, 0, 3*PI, 100, 255); ofSetColor(125, c1, c2, 50); //c.setHsb(hue, 255, 255); //ofSetColor(c); ofDrawCircle(p, radius); //ofDrawLine(point[0], point[1]); }
f91b035fb1bc6bcdbc39f0edbbcd09d848a555f2
11e3826ed71675c942326edf727e2fe947afb48a
/C++版/12. 整数转罗马数字.cpp
68fd4b72042c1ec207cbf27750c25502505b3ced
[]
no_license
HYK13213036/LeetCode
4988a68390e055b340f8b7e1a3b10bcee7285856
41fa4367f684d27cd38d4944762d3014bd178e42
refs/heads/master
2020-04-13T14:28:11.273539
2018-11-26T13:56:08
2018-11-26T13:56:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
class Solution { public: string intToRoman(int num) { string res = ""; vector<int> key = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; vector<string> value={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; for(int i = 0;i < key.size(); i++){ int count = num / key[i]; for(int j = 0;j < count; j++){ res += value[i]; } num %= key[i]; } return res; } };
4074a356a2ea04dfa6e5e5f9af4f9f50ad97ac7e
c8b6676ac2e420e1ee79d682b2edf780685f103b
/antlr4-runtime-cpp/atn/ParseInfo.h
0c47e195a8a0fc0c35939bb7e560647a41b858e3
[]
no_license
eiselekd/vhdl2js
58d49d6a1fd391f196945fd131c70fe2fd850151
0bc45929aa53bca12adf9ba3e913533a8ff8d7c8
refs/heads/master
2021-01-23T08:56:42.933636
2016-11-20T10:26:24
2016-11-20T10:26:24
8,887,975
10
1
null
null
null
null
UTF-8
C++
false
false
4,960
h
/* * [The "BSD license"] * Copyright (c) 2016 Mike Lischke * Copyright (c) 2014 Terence Parr * Copyright (c) 2014 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "atn/DecisionInfo.h" namespace antlr4 { namespace atn { class ProfilingATNSimulator; /// This class provides access to specific and aggregate statistics gathered /// during profiling of a parser. class ANTLR4CPP_PUBLIC ParseInfo { public: ParseInfo(ProfilingATNSimulator *atnSimulator); virtual ~ParseInfo() {}; /// <summary> /// Gets an array of <seealso cref="DecisionInfo"/> instances containing the profiling /// information gathered for each decision in the ATN. /// </summary> /// <returns> An array of <seealso cref="DecisionInfo"/> instances, indexed by decision /// number. </returns> virtual std::vector<DecisionInfo> getDecisionInfo(); /// <summary> /// Gets the decision numbers for decisions that required one or more /// full-context predictions during parsing. These are decisions for which /// <seealso cref="DecisionInfo#LL_Fallback"/> is non-zero. /// </summary> /// <returns> A list of decision numbers which required one or more /// full-context predictions during parsing. </returns> virtual std::vector<size_t> getLLDecisions(); /// <summary> /// Gets the total time spent during prediction across all decisions made /// during parsing. This value is the sum of /// <seealso cref="DecisionInfo#timeInPrediction"/> for all decisions. /// </summary> virtual long long getTotalTimeInPrediction(); /// <summary> /// Gets the total number of SLL lookahead operations across all decisions /// made during parsing. This value is the sum of /// <seealso cref="DecisionInfo#SLL_TotalLook"/> for all decisions. /// </summary> virtual long long getTotalSLLLookaheadOps(); /// <summary> /// Gets the total number of LL lookahead operations across all decisions /// made during parsing. This value is the sum of /// <seealso cref="DecisionInfo#LL_TotalLook"/> for all decisions. /// </summary> virtual long long getTotalLLLookaheadOps(); /// <summary> /// Gets the total number of ATN lookahead operations for SLL prediction /// across all decisions made during parsing. /// </summary> virtual long long getTotalSLLATNLookaheadOps(); /// <summary> /// Gets the total number of ATN lookahead operations for LL prediction /// across all decisions made during parsing. /// </summary> virtual long long getTotalLLATNLookaheadOps(); /// <summary> /// Gets the total number of ATN lookahead operations for SLL and LL /// prediction across all decisions made during parsing. /// /// <para> /// This value is the sum of <seealso cref="#getTotalSLLATNLookaheadOps"/> and /// <seealso cref="#getTotalLLATNLookaheadOps"/>.</para> /// </summary> virtual long long getTotalATNLookaheadOps(); /// <summary> /// Gets the total number of DFA states stored in the DFA cache for all /// decisions in the ATN. /// </summary> virtual size_t getDFASize(); /// <summary> /// Gets the total number of DFA states stored in the DFA cache for a /// particular decision. /// </summary> virtual size_t getDFASize(size_t decision); protected: const ProfilingATNSimulator *_atnSimulator; // non-owning, we are created by this simulator. }; } // namespace atn } // namespace antlr4
c37026be3769427a35af533738605885b5854748
fc7d5b988d885bd3a5ca89296a04aa900e23c497
/Programming/mbed-os-example-sockets/mbed-os/connectivity/drivers/cellular/QUECTEL/M26/QUECTEL_M26_CellularInformation.cpp
bcdb0b32aa25c8c1552476fe34c13607be9ef163
[ "Apache-2.0" ]
permissive
AlbinMartinsson/master_thesis
52746f035bc24e302530aabde3cbd88ea6c95b77
495d0e53dd00c11adbe8114845264b65f14b8163
refs/heads/main
2023-06-04T09:31:45.174612
2021-06-29T16:35:44
2021-06-29T16:35:44
334,069,714
3
1
Apache-2.0
2021-03-16T16:32:16
2021-01-29T07:28:32
C++
UTF-8
C++
false
false
1,077
cpp
/* * Copyright (c) 2018, Arm Limited and affiliates. * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "QUECTEL_M26_CellularInformation.h" using namespace mbed; QUECTEL_M26_CellularInformation::QUECTEL_M26_CellularInformation(ATHandler &atHandler, AT_CellularDevice &device) : AT_CellularInformation(atHandler, device) { } // According to M26_AT_Commands_Manual_V1.9 nsapi_error_t QUECTEL_M26_CellularInformation::get_iccid(char *buf, size_t buf_size) { return _at.at_cmd_str("+CCID", "", buf, buf_size); }
3d13f07d88da797aae65e3b86432ae3587b9f6ed
a7adfa92772fe9900152c43f4ab0895b507c3da7
/slam_gmapping/gmapping/src/main.cpp
6c68ffd90e5b774c48103bd484a91545e92d3e71
[]
no_license
Nitrow/P9-SLAM-RL
8aa1a5bd2874b22a6dfa03d10f1ef591bfc13fac
fbfd2bf189d7dab8bbb48141053a5b1e6960e52d
refs/heads/main
2023-05-30T03:34:22.574058
2021-06-14T14:08:15
2021-06-14T14:08:15
302,137,573
3
1
null
2021-01-27T15:05:52
2020-10-07T19:18:11
C++
UTF-8
C++
false
false
1,358
cpp
/* * slam_gmapping * Copyright (c) 2008, Willow Garage, Inc. * * THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE * COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY * COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS * AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. * * BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO * BE BOUND BY THE TERMS OF THIS LICENSE. THE LICENSOR GRANTS YOU THE RIGHTS * CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND * CONDITIONS. * */ /* Author: Brian Gerkey */ #include <ros/ros.h> #include "std_msgs/String.h" #include "slam_gmapping.h" #include <iostream> bool shouldReset = false; void sysCmdCallback(const std_msgs::String& sys_cmd) { if (sys_cmd.data == "reset") { shouldReset = true; } } void main_loop() { while (ros::ok()) { SlamGMapping gn; gn.startLiveSlam(); while (!shouldReset) { ros::spinOnce(); ros::Duration(0.2).sleep(); } ROS_INFO("Resetting map..."); shouldReset = false; } } int main(int argc, char** argv) { ros::init(argc, argv, "slam_gmapping"); ros::NodeHandle n; ros::Subscriber sub = n.subscribe("syscommand", 10, sysCmdCallback); main_loop(); ros::spin(); return(0); }
d3e230cf31bf2a491d0ac1836718afe68062fab1
6f8bc7f3a387a9df141f8daa40cfa56645ad06cc
/DreamLayer/DreamLayer/src/Animation.cpp
472d2536a3080d4cdeb5905c5852d01236ed15f1
[]
no_license
trineroks/DreamLayer
3813d11d1e0437ec3bcd2dc77060eff84040fd4d
b2dfdcf402e94b101fc1209da4950317df061206
refs/heads/master
2021-09-13T06:18:25.991117
2018-04-25T20:12:49
2018-04-25T20:12:49
113,432,442
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
#include "Animation.h" Animation::Animation() { } void Animation::addFrame(TextureRegion _tex) { textures.push_back(_tex); } int Animation::getSize() const { return textures.size(); } TextureRegion& Animation::getFrame(int i) { return textures[i]; }
20433a85da6320682166a68ea46d97399b5e11ae
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_663_httpd-2.4.3.cpp
cf3b0ec0bae15ce0bd9381482dcf4a43d7dc0720
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,015
cpp
static void ssl_init_server_check(server_rec *s, apr_pool_t *p, apr_pool_t *ptemp, modssl_ctx_t *mctx) { /* * check for important parameters and the * possibility that the user forgot to set them. */ if (!mctx->pks->cert_files[0] && !mctx->pkcs7) { ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01891) "No SSL Certificate set [hint: SSLCertificateFile]"); ssl_die(s); } /* * Check for problematic re-initializations */ if (mctx->pks->certs[SSL_AIDX_RSA] || mctx->pks->certs[SSL_AIDX_DSA] #ifndef OPENSSL_NO_EC || mctx->pks->certs[SSL_AIDX_ECC] #endif ) { ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(01892) "Illegal attempt to re-initialise SSL for server " "(SSLEngine On should go in the VirtualHost, not in global scope.)"); ssl_die(s); } }
c49e2d8f5f656d403fdd01ba41164355f7c43dd4
9e19c5d659863918615e913b39b8a673fba1cf30
/OLOLO - Onotole needs your help.cpp
38e6ca20d0131b4c1755e7af7111a50eeb2c6c2d
[]
no_license
avichauhan6832/SPOJ-Solutions
10a76040139d08526e7e83db4f6277ead78bd014
c901b66b3216dc7dcd906978ca964fea4da7d4da
refs/heads/master
2020-12-13T04:24:56.257192
2020-02-10T16:18:47
2020-02-10T16:18:47
234,313,327
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
#include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const string normalChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "; const int N=1e6+5; int32_t main() { IOS; /*freopen("apache.in","r",stdin); freopen("apache.out","w",stdout); freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);*/ int n; cin >> n; int arr[n]; for(int i = 0; i < n; i++) { cin >> arr[i]; } int a, ans; a = arr[0]; for(int i = 1; i < n;i++) { ans = a^arr[i]; a = ans; } cout<<ans<<endl; return 0; }
cfa7eea8b6b87e4262580b260b393f4de1c7a242
f80b3e04480e575988c06b1f26a5f20d2279530f
/CS 172 Final All Documents/172 Final Most recent/172 Final/172 Final/MainHeader.h
5ca3ecc894a8b1aff11c78b69571a043d4b3936d
[]
no_license
SamuelW2018/CS2-Final-Project
c12740e82aa28193ba3ff535610961858aeb9e6b
3cdcb6046997c9d6759d5b68dc35fcd77d7c0efd
refs/heads/master
2021-01-19T10:35:46.694472
2017-02-16T18:52:17
2017-02-16T18:52:17
82,214,590
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
#include <iostream> #include <fstream> #include <vector> #include <iomanip> #include <conio.h> #include "Dungeon.h" #include "Room.h" #include "Door.h" #include "Character.h" #include "Windows.h" using namespace std; void printFrame(vector<vector<char>> map);
acad3581faf77f0484d7e8979ab75cf20fa6efed
bbeaadef08cccb872c9a1bb32ebac7335d196318
/BPR/Confiabilidade/Confiabilidade.cpp
2a27ff376bfd4cf93d065f1d6a7985fa091916d4
[]
no_license
danilodesouzapereira/plataformasinap_exportaopendss
d0e529b493f280aefe91b37e893359a373557ef8
c624e9e078dce4b9bcc8e5b03dd4d9ea71c29b3f
refs/heads/master
2023-03-20T20:37:21.948550
2021-03-12T17:53:12
2021-03-12T17:53:12
347,150,304
0
0
null
null
null
null
ISO-8859-2
C++
false
false
3,283
cpp
#include <vcl.h> #include <windows.h> #pragma hdrstop #include <Fontes\Confiabilidade\TFormConfiabilidade.h> #include <Fontes\Confiabilidade\TFormParam.h> #include <Fontes\Confiabilidade\VTConfiab.h> #include <DLL_Inc\Confiabilidade.h> #include <DLL_Inc\Funcao.h> #pragma argsused #pragma comment(lib, "Bloco.a") #pragma comment(lib, "Consulta.a") #pragma comment(lib, "Editor.a") #pragma comment(lib, "Funcao.a") #pragma comment(lib, "Progresso.a") #pragma comment(lib, "Rede.a") #pragma comment(lib, "Report.a") //----------------------------------------------------------------------------- int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved) { return 1; } //----------------------------------------------------------------------------- EXPORT bool __fastcall DLL_Confiabilidade_Enabled(void) { return(true); } //----------------------------------------------------------------------------- EXPORT int __fastcall DLL_Confiabilidade_LimiteBarras(void) { return(15000); } //----------------------------------------------------------------------------- EXPORT void __fastcall DLL_AtualizaFormConfiabilidade(TForm *form_owner) { } //----------------------------------------------------------------------------- EXPORT void __fastcall DLL_CloseFormConfiabilidade(TForm *form_owner) { //variáveis locais TForm *form; //destrói todos os TFormConfiabilidade abertos while ((form = ExisteForm("TFormConfiabilidade", form_owner)) != NULL) delete form; } //--------------------------------------------------------------------------- EXPORT bool __fastcall DLL_ModuloConfiabilidadePertencePlataformaSinap(void) { return(true); } //--------------------------------------------------------------------------- EXPORT TForm* __fastcall DLL_NewFormConfiabilidade(TForm *form_owner, VTApl *apl_owner, TWinControl *parent) { //variáveis locais TForm *form; try{//verifica se existe um TFormConfiabilidade aberto if ((form = ExisteForm("TFormConfiabilidade", form_owner)) == NULL) {//cria um novo TFormConfiabilidade e exibe como janela normal form = new TFormConfiabilidade(form_owner, apl_owner, parent); } //exibe TFormConfiabilidade if (form != NULL) form->Show(); }catch(Exception &e) { return(NULL); } return(form); } //--------------------------------------------------------------------------- EXPORT TFormParam* __fastcall DLL_NewFormParamConfiabilidade(TForm *form_owner, VTApl *apl_owner, TWinControl *parent) {//variáveis locais TForm *form; try{//verifica se existe um TFormConfiabilidade aberto if ((form = ExisteForm("TFormParam", form_owner)) == NULL) {//cria um novo TFormConfiabilidade e exibe como janela normal form = new TFormParam(form_owner, parent, apl_owner); } //exibe TFormParam //if (form != NULL) form->Show(); }catch(Exception &e) { return(NULL); } return((TFormParam*)form); } //----------------------------------------------------------------------------- EXPORT VTConfiab* __fastcall DLL_NewObjConfiab(VTApl *apl_owner) { return(NewObjConfiab(apl_owner)); } //--------------------------------------------------------------------------- //eof
ea466fbff8a65164552321fd905bcb2d3a372582
73bfad0687c4df96a7dbec54b8b90e35fe460069
/src/Math/Circle2D.h
cff66d09c22615bf3a4efb193341e8f52b994dc1
[]
no_license
brieucdnl/JV-IN
fb42d3cf7eab6a353714915a226a53d63465dd84
00381a6276e4eb04084bdbff44cf125f05412c4c
refs/heads/master
2016-08-11T19:43:59.254902
2016-03-09T22:06:57
2016-03-09T22:06:57
49,319,928
0
0
null
null
null
null
UTF-8
C++
false
false
8,423
h
#ifndef _Math_Circle_H #define _Math_Circle_H #include <assert.h> #include <Math/Vector2.h> #include <Math/Segment2D.h> #include <Math/Sphere.h> namespace Math { //////////////////////////////////////////////////////////////////////////////////////////////////// /// \class Circle2D /// /// \brief Circle in two dimensions. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 //////////////////////////////////////////////////////////////////////////////////////////////////// template <class Float> class Circle2D : public Sphere<Float, 2> { public: //////////////////////////////////////////////////////////////////////////////////////////////////// /// \struct Intersection : public Serialization::SerializableWithFactory, Serialization:: /// Factory<Intersection> /// /// \brief Result of a two circle intersection. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 //////////////////////////////////////////////////////////////////////////////////////////////////// struct Intersection { //! Number of intersections. unsigned int m_nbIntersections ; //! The intersections. Math::Vector2<Float> m_points[2] ; } ; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn Circle2D(Float radius, bool exp2=false) /// /// \brief Constructor. Creates a circle centered in (0,0) with a user supplied radius. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 /// /// \param radius The radius or radius^2 (if exp2 is true). /// \param exp2 true if radius is squared. //////////////////////////////////////////////////////////////////////////////////////////////////// Circle2D(Float radius, bool exp2=false) : Sphere<Float,2>(radius, exp2) {} //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn Circle2D(Math::Vector2<Float> const & center=Math::Vector2<Float>(), Float rayon=1.0, /// bool exp2=false) /// /// \brief Constructor. Creates a circle centered at a user supplied position. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 /// /// \param [in,out] center position of the center of the circle. /// \param radius The radius or radius^2 (if exp2 is true). /// \param exp2 true if radius is squared. //////////////////////////////////////////////////////////////////////////////////////////////////// Circle2D(Math::Vector2<Float> const & center=Math::Vector2<Float>(), Float radius=1.0, bool exp2=false) : Sphere<Float,2>(center, radius, exp2) {} //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool isInside(Math::Vector2<Float> const & point) const /// /// \brief Queries if 'point' is inside the circle. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 /// /// \param [in,out] point the point. /// /// \return true if the point is in the circle. //////////////////////////////////////////////////////////////////////////////////////////////////// bool isInside(Math::Vector<Float, 2> const & point) const { return Sphere<Float,2>::isInside(point) ; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool isInside(Segment2D<Float> const & segment) const /// /// \brief Query if 'segment' is partially of fully inside the circle. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 /// /// \param [in,out] segment the segment. /// /// \return true if inside, false if not. //////////////////////////////////////////////////////////////////////////////////////////////////// bool isInside(Segment2D<Float> const & segment) const { Float dist = segment.distance(m_center) ; return dist*dist<=m_radiusExp2 ; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn bool tangentPoints(Math::Vector2<Float> const & point, Math::Vector2<Float> & leftTangent, /// Math::Vector2<Float> & rightTangent) /// /// \brief Given a point point, computes two points leftTangent and rightTangent such as (point,rightTangent) /// and (point,leftTangent) are tangent to the circle. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 /// /// \param [in,out] point the source point. /// \param [in,out] leftTangent the left tangent point. /// \param [in,out] rightTangent the right tangent point. /// /// \return true if tangent points exist, false if not. //////////////////////////////////////////////////////////////////////////////////////////////////// bool tangentPoints(Math::Vector2<Float> const & point, Math::Vector<Float, 2> & leftTangent, Math::Vector<Float, 2> & rightTangent) ; //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void intersection(Circle2D const & circle, Intersection & circleIntersection) /// /// \brief Computes the intersection of two circles. /// /// \author Fabrice Lamarche, University Of Rennes 1 /// \date 04/12/2009 /// /// \param circle the second circle. /// \param [out] circleIntersection the circle intersection. //////////////////////////////////////////////////////////////////////////////////////////////////// void intersection(Circle2D const & circle, Intersection & circleIntersection) ; }; } namespace Math { template <class Float> bool Circle2D<Float>::tangentPoints(Math::Vector2<Float> const & point, Math::Vector<Float, 2> & leftTangent, Math::Vector<Float, 2> & rightTangent) { //assert(!in(v)) ; if(isInside(point)) { return false ; //std::cout<<"circle.tangentPoints :: in!!!!!"<<std::endl ; } Math::Vector2<Float> P = point-m_center ; Float normP = P.norm() ; //::norm(P) ; Float x = m_radiusExp2/normP ; Float y = sqrt(m_radiusExp2-x*x) ; Math::Vector2<Float> e1 = P*(Float(1.0)/normP) ; Math::Vector2<Float> e2 = e1.rotate90(); leftTangent = e1*x+e2*(-y) ; rightTangent = e1*x+e2*y ; // Modification pour les besoins de la cause... leftTangent = leftTangent + m_center ; rightTangent = rightTangent + m_center ; return true ; } template <class Float> void Circle2D<Float>::intersection(Circle2D const & circle, Intersection & circleIntersection) { Math::Vector2<Float> deltaCenter = circle.center() - this->center() ; Float deltaCenterNorm2 = deltaCenter.norm2(); Float radius0 = this->radius(), radius1 = circle.radius(); Float deltaRadius = radius0 - radius1; // Les deux cercles sont confondus if (deltaCenterNorm2 <= 0.0 && fabs(deltaRadius) <= 0.0) { circleIntersection.m_nbIntersections = 0; return ; } Float deltaRadius2 = deltaRadius*deltaRadius; // Les deux cercles ne s'intersectent pas if (deltaCenterNorm2 < deltaRadius2) { circleIntersection.m_nbIntersections = 0; return ; } Float radiusSum = radius0 + radius1; Float radiusSum2 = radiusSum*radiusSum; // Les deux cercles ne s'intersectent pas if (deltaCenterNorm2 > radiusSum2) { circleIntersection.m_nbIntersections = 0; return ; } // Les cercles s'intersectent if (deltaCenterNorm2 < radiusSum2) { if (deltaRadius2 < deltaCenterNorm2) // Intersection en deux points { Float invDeltaCenterNorm2 = ((Float)1.0)/deltaCenterNorm2; Float fS = ((Float)0.5)*((radius0*radius0-radius1*radius1)*invDeltaCenterNorm2+(Float)1.0); Math::Vector2<Float> kTmp = this->center() + deltaCenter*fS; Float fT = sqrt(radius0*radius0*invDeltaCenterNorm2 - fS*fS); Math::Vector2<Float> kV(deltaCenter[1],-deltaCenter[0]); circleIntersection.m_nbIntersections = 2; circleIntersection.m_points[0] = kTmp - kV*fT; circleIntersection.m_points[1] = kTmp + kV*fT; } else // Les deux cercles sont tangents { circleIntersection.m_nbIntersections = 1; circleIntersection.m_points[0] = this->center() + deltaCenter*(radius0/deltaRadius); } } else // Les deux cercles sont tangents { circleIntersection.m_nbIntersections = 1; circleIntersection.m_points[0] = this->center() + deltaCenter*(radius0/radiusSum); } } } #endif
9171b0c2ffb0cd2fcef8333e9586fb89f4bc683e
f588bd3b9a3f8233650c3ee6c253122af1a2d1ed
/psa/capitalize.cpp
05ec5a55679382035b094605dfaedddb16302fa1
[]
no_license
Omarabdul3ziz/lowlvl
e9b100fcacfcb798e1a2358d5879a61853cee2d3
3613ebc31ecc7159e5b3d41a126e663354746413
refs/heads/master
2022-12-26T14:56:32.387125
2020-10-02T00:44:18
2020-10-02T00:44:18
300,027,872
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
#include <iostream> #include <string> using namespace std; int main () { string word; cin >> word; word[0] = toupper(word[0]); cout << word; return 0;}
b823f25e76c1546a8797417097326eb87bfbd460
4ff617b6c2be2ffb08d9350be73f190ba2d7e659
/BigIntegerSingle/BigInteger.h
e6e2b30eeb600288e1a4678ac672c8ec294663df
[]
no_license
llgithubll/Cpp_toys
618e75109706443aa866178af427b1e4b09ec2a9
b6ba3bdf9e76143f234911e45e7f8eb65790175c
refs/heads/master
2020-12-24T12:04:49.738435
2019-01-10T09:24:51
2019-01-10T09:24:51
73,079,911
0
0
null
null
null
null
UTF-8
C++
false
false
19,388
h
#include <iostream> #include <string> #include <cctype> #include <cmath> #include <utility> #include <cassert> /////////////////////////////////////////////////////////////////////////////// //Declaration /////////////////////////////////////////////////////////////////////////////// //#define BIGINTEGER_EXCEPTION_ON #ifdef BIGINTEGER_EXCEPTION_ON #include <exception> class BigIntException : public std::exception { public: BigIntException(const std::string& _txt) throw(); ~BigIntException() throw(); const char* what() const throw(); private: std::string txt; }; #endif class BigInteger { friend std::ostream& operator<<(std::ostream &_os, const BigInteger &_num); friend std::istream& operator >> (std::istream &_is, BigInteger &_num); friend BigInteger gcd(const BigInteger &_lhs, const BigInteger &_rhs); // Other friend BigInteger lcm(const BigInteger &_lhs, const BigInteger &_rhs); // Other friend bool operator==(const BigInteger &_lhs, const BigInteger &_rhs); friend bool operator!=(const BigInteger &_lhs, const BigInteger &_rhs); friend bool operator< (const BigInteger &_lhs, const BigInteger &_rhs); friend bool operator<=(const BigInteger &_lhs, const BigInteger &_rhs); friend bool operator> (const BigInteger &_lhs, const BigInteger &_rhs); friend bool operator>=(const BigInteger &_lhs, const BigInteger &_rhs); friend BigInteger operator+(const BigInteger &_lhs, const BigInteger &_rhs); friend BigInteger operator-(const BigInteger &_lhs, const BigInteger &_rhs); friend BigInteger operator*(const BigInteger &_lhs, const BigInteger &_rhs); friend BigInteger operator/(const BigInteger &_lhs, const BigInteger &_rhs); // throw friend BigInteger operator%(const BigInteger &_lhs, const BigInteger &_rhs); // throw friend BigInteger operator^(const BigInteger &_lhs, const BigInteger &_rhs); // throw pow(m, n) n >= 0 private: std::string num = "0"; bool sign = false; // true: negative, false:positive public: // Constructor BigInteger() = default; BigInteger(const char *_c); BigInteger(const std::string& _s); BigInteger(const int _num); BigInteger(const long _num); BigInteger(const long long _num); BigInteger(const unsigned int _num); BigInteger(const unsigned long _num); BigInteger(const unsigned long long _num); BigInteger(const BigInteger& _num) = default; // Get, Set std::string getNum() const { return num; } void setNum(std::string &_num) { num = _num; } bool getSign() const { return sign; } void setSign(bool _sign) { sign = _sign; } bool isNeg() const { return sign == true; } // Primitive type int toInt() const; // throw long toLong() const; // throw long long toLongLong() const; // throw unsigned int toUnsignedInt() const; // throw unsigned long toUnsignedLong() const; // throw unsigned long long toUnsignedLongLong() const; // throw std::string toString() const; // Operations char operator [](size_t n) const; // throw(get nth digit, n begin from 0) BigInteger operator-() const; BigInteger add(const BigInteger &_rhs) const; BigInteger sub(const BigInteger &_rhs) const; BigInteger mul(const BigInteger &_rhs) const; BigInteger div(const BigInteger &_rhs) const; // throw BigInteger mod(const BigInteger &_rhs) const; // throw BigInteger pow(const BigInteger &_rhs) const; // throw pow(m, n) n >= 0 // Operational assignments const BigInteger& operator+=(const BigInteger& _rhs); const BigInteger& operator-=(const BigInteger& _rhs); const BigInteger& operator*=(const BigInteger& _rhs); const BigInteger& operator/=(const BigInteger& _rhs); // throw const BigInteger& operator%=(const BigInteger& _rhs); // throw const BigInteger& operator^=(const BigInteger& _rhs); // throw pow(m, n) n >= 0 // Increment/Decrement const BigInteger& operator++(); // prefix const BigInteger& operator--(); // prefix BigInteger operator++(int); // postfix BigInteger operator--(int); // postfix // Other size_t numberOfDigits() const; BigInteger absolute() const; BigInteger intSqrt() const; // throw private: bool equals(const BigInteger& _rhs) const; bool less(const BigInteger& _rhs) const; bool greater(const BigInteger& _rhs) const; std::string addNum(std::string num1, std::string num2) const; std::string subNum(std::string num1, std::string num2) const; std::string mulNum(std::string num1, std::string num2) const; std::pair<std::string, std::string> divNum(std::string num1, std::string num2) const; void removeLeadingZeros(std::string &num) const; }; std::ostream& operator<<(std::ostream &_os, const BigInteger &_num); std::istream& operator >> (std::istream &_is, BigInteger &_num); BigInteger gcd(const BigInteger &_lhs, const BigInteger &_rhs); // Other BigInteger lcm(const BigInteger &_lhs, const BigInteger &_rhs); // Other BigInteger operator+(const BigInteger &_lhs, const BigInteger &_rhs); BigInteger operator-(const BigInteger &_lhs, const BigInteger &_rhs); BigInteger operator*(const BigInteger &_lhs, const BigInteger &_rhs); BigInteger operator/(const BigInteger &_lhs, const BigInteger &_rhs); // throw BigInteger operator%(const BigInteger &_lhs, const BigInteger &_rhs); // throw BigInteger operator^(const BigInteger &_lhs, const BigInteger &_rhs); // throw pow(m, n) n >= 0 bool operator==(const BigInteger &_lhs, const BigInteger &_rhs); bool operator!=(const BigInteger &_lhs, const BigInteger &_rhs); bool operator< (const BigInteger &_lhs, const BigInteger &_rhs); bool operator<=(const BigInteger &_lhs, const BigInteger &_rhs); bool operator> (const BigInteger &_lhs, const BigInteger &_rhs); bool operator>=(const BigInteger &_lhs, const BigInteger &_rhs); /////////////////////////////////////////////////////////////////////////////// //Implemetation /////////////////////////////////////////////////////////////////////////////// #ifdef BIGINTEGER_EXCEPTION_ON BigIntException::BigIntException(const std::string & _txt) throw() :std::exception(), txt(_txt) { } BigIntException::~BigIntException() throw() { } const char * BigIntException::what() const throw() { return txt.c_str(); } #endif BigInteger::BigInteger(const char * _c) :BigInteger(std::string(_c)) { } BigInteger::BigInteger(const std::string & _s) { if (_s[0] == '-') { sign = true; num = _s.substr(1); } else { num = _s; } for (int i = 0; i < num.size(); i++) { if (!isdigit(num[i])) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Invalid integer"); #else std::cerr << "Invalid integer" << std::endl; #endif break; } } removeLeadingZeros(num); } BigInteger::BigInteger(const int _num) :BigInteger(std::to_string(_num)) { } BigInteger::BigInteger(const long _num) : BigInteger(std::to_string(_num)) { } BigInteger::BigInteger(const long long _num) : BigInteger(std::to_string(_num)) { } BigInteger::BigInteger(const unsigned int _num) : BigInteger(std::to_string(_num)) { } BigInteger::BigInteger(const unsigned long _num) : BigInteger(std::to_string(_num)) { } BigInteger::BigInteger(const unsigned long long _num) : BigInteger(std::to_string(_num)) { } int BigInteger::toInt() const { if (*this < INT_MIN || *this > INT_MAX) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Out of int bounds"); #else std::cerr << "Out of int bounds:" << *this << std::endl; #endif } else { return std::stoi((sign ? "-" : "") + num); } return 0; } long BigInteger::toLong() const { if (*this < LONG_MIN || *this > LONG_MAX) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Out of long bounds"); #else std::cerr << "Out of long bounds:" << *this << std::endl; #endif } else { return std::stol((sign ? "-" : "") + num); } return 0; } long long BigInteger::toLongLong() const { if (*this < LLONG_MIN || *this > LLONG_MAX) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Out of long long bounds"); #else std::cerr << "Out of long long bounds:" << *this << std::endl; #endif } else { return std::stoll((sign ? "-" : "") + num); } return 0; } unsigned int BigInteger::toUnsignedInt() const { if (sign || *this > UINT_MAX) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Out of unsigned int bounds"); #else std::cerr << "Out of unsigned int bounds:" << *this << std::endl; #endif } else { return stoul(num); // int auto cast to unsigned int ? } return 0; } unsigned long BigInteger::toUnsignedLong() const { if (sign || *this > ULONG_MAX) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Out of unsigned long bounds"); #else std::cerr << "Out of unsigned long bounds:" << *this << std::endl; #endif } else { return std::stoul(num); } return 0; } unsigned long long BigInteger::toUnsignedLongLong() const { if (sign || *this > ULLONG_MAX) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Out of unsigned long long bounds"); #else std::cerr << "Out of unsigned long long bounds:" << *this << std::endl; #endif } else { return std::stoull(num); } return 0; } std::string BigInteger::toString() const { return (sign ? "-" : "") + num; } bool BigInteger::equals(const BigInteger & _rhs) const { return (sign == _rhs.sign) && (num.size() == _rhs.num.size()) && num == _rhs.num; } bool BigInteger::less(const BigInteger & _rhs) const { if (sign && !_rhs.sign) return true; // - is less than + else if (!sign && _rhs.sign) return false; // + is not less than - else if (sign && _rhs.sign) { // -, - if (num.size() > _rhs.num.size()) return true; else if (num.size() < _rhs.num.size()) return false; else return num > _rhs.num; } else { // +, + if (num.size() < _rhs.num.size()) return true; else if (num.size() > _rhs.num.size()) return false; else return num < _rhs.num; } } bool BigInteger::greater(const BigInteger & _rhs) const { return !equals(_rhs) && !less(_rhs); } std::string BigInteger::addNum(std::string num1, std::string num2) const { std::string sum = (num1.size() > num2.size()) ? num1 : num2; char carry = '0'; int diffSize = (num1.size() > num2.size()) ? (num1.size() - num2.size()) : (num2.size() - num1.size()); if (num1.size() > num2.size()) num2.insert(0, diffSize, '0'); else num1.insert(0, diffSize, '0'); for (int i = num1.size() - 1; i >= 0; i--) { sum[i] = ((carry - '0') + (num1[i] - '0') + (num2[i] - '0')) + '0'; if (i != 0) { if (sum[i] > '9') { sum[i] -= 10; carry = '1'; } else { carry = '0'; } } } if (sum[0] > '9') { sum[0] -= 10; sum.insert(0, 1, '1'); } return sum; } std::string BigInteger::subNum(std::string num1, std::string num2) const { std::string diff = (num1.size() > num2.size()) ? num1 : num2; int diffSize = (num1.size() > num2.size()) ? num1.size() - num2.size() : num2.size() - num1.size(); if (num1.size() > num2.size()) num2.insert(0, diffSize, '0'); else num1.insert(0, diffSize, '0'); for (int i = num1.size() - 1; i >= 0; i--) { if (num1[i] < num2[i]) { num1[i] += 10; num1[i - 1]--; // because assume num1 >= num2, we will not access num1[0 - 1] } diff[i] = ((num1[i] - '0') - (num2[i] - '0')) + '0'; } removeLeadingZeros(diff); return diff; } std::string BigInteger::mulNum(std::string num1, std::string num2) const { if (num1.size() > num2.size()) num1.swap(num2); std::string res = "0"; for (int i = num1.size() - 1; i >= 0; i--) { std::string temp = num2; int curDigit = num1[i] - '0'; int carry = 0; for (int j = temp.size() - 1; j >= 0; j--) { int proDigit = ((temp[j] - '0') * curDigit) + carry; if (proDigit > 9) { carry = proDigit / 10; proDigit = proDigit % 10; } else { carry = 0; } temp[j] = proDigit + '0'; } if (carry > 0) { temp.insert(0, 1, carry + '0'); } temp.append(num1.size() - i - 1, '0'); res = addNum(res, temp); } removeLeadingZeros(res); return res; } std::pair<std::string, std::string> BigInteger::divNum(std::string num1, std::string num2) const { // algorithm: simulate traditional long division(https://en.wikipedia.org/wiki/Long_division) std::string quo, rem; std::string tmpNumer; for (int i = 0; i < num1.size(); i++) { tmpNumer.push_back(num1[i]); int digitQuo = 0; while (tmpNumer.size() > num2.size() || (tmpNumer.size() == num2.size() && tmpNumer >= num2)) { tmpNumer = subNum(tmpNumer, num2); if (tmpNumer == "0") tmpNumer = ""; digitQuo++; } quo.push_back(digitQuo + '0'); } rem = (tmpNumer == "") ? "0" : tmpNumer; removeLeadingZeros(quo); return std::pair<std::string, std::string>(quo, rem); } size_t BigInteger::numberOfDigits() const { return num.size(); } BigInteger BigInteger::absolute() const { return BigInteger(num); } BigInteger BigInteger::intSqrt() const { if (*this < 0) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Cannot compute negative square root"); #else std::cerr << "Cannot compute negative square root:" << *this << std::endl; #endif // BIGINTEGER_EXCEPTION_ON } if (*this == 0 || *this == 1) return *this; BigInteger start = 1, end = *this, mid, ans; while (start <= end) { mid = (start + end) / 2; if (mid * mid == *this) { return mid; } else if (mid * mid < *this) { start = mid + 1; ans = mid; } else { end = mid - 1; } } return ans; } void BigInteger::removeLeadingZeros(std::string &num) const { int i = 0; while (i < num.size()) { if (num[i] == '0') i++; else break; } if (i == num.size()) num = "0"; else num = num.substr(i); } std::ostream & operator<<(std::ostream & _os, const BigInteger & _num) { _os << _num.toString(); return _os; } std::istream & operator >> (std::istream & _is, BigInteger & _num) { std::string s; _is >> s; if (_is) { _num = BigInteger(s); } else { _num = BigInteger(); } return _is; } BigInteger gcd(const BigInteger & _lhs, const BigInteger & _rhs) { if (_lhs < 0 || _rhs < 0) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("parameters of gcd should not negative"); #else std::cerr << "parameters of gcd should not negative:(" << _lhs << "," << _rhs << ")" << std::endl; #endif // BIGINTEGER_EXCEPTION_ON } BigInteger r, m = _lhs, n = _rhs; while (n > 0) { r = m % n; m = n; n = r; } return m; } BigInteger lcm(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs * _rhs / gcd(_lhs, _rhs); } BigInteger operator+(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.add(_rhs); } BigInteger operator-(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.sub(_rhs); } BigInteger operator*(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.mul(_rhs); } BigInteger operator/(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.div(_rhs); } BigInteger operator%(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.mod(_rhs); } BigInteger operator^(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.pow(_rhs); } bool operator==(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.equals(_rhs); } bool operator!=(const BigInteger & _lhs, const BigInteger & _rhs) { return !_lhs.equals(_rhs); } bool operator<(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.less(_rhs); } bool operator<=(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.less(_rhs) || _lhs.equals(_rhs); } bool operator>(const BigInteger & _lhs, const BigInteger & _rhs) { return _lhs.greater(_rhs); } bool operator>=(const BigInteger & _lhs, const BigInteger & _rhs) { return !_lhs.less(_rhs); } char BigInteger::operator[](size_t n) const { if (n >= numberOfDigits()) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Invalid digit index"); #else std::cerr << "Invalid digit index:" << n << std::endl; return -1; #endif } return num[n]; } BigInteger BigInteger::operator-() const { BigInteger opposite = *this; opposite.setSign(!sign); return opposite; } BigInteger BigInteger::add(const BigInteger & _rhs) const { BigInteger addition; if (getSign() == _rhs.getSign()) { addition.setNum(addNum(getNum(), _rhs.getNum())); addition.setSign(getSign()); } else { if (absolute() > _rhs.absolute()) { addition.setNum(subNum(getNum(), _rhs.getNum())); addition.setSign(getSign()); } else { addition.setNum(subNum(_rhs.getNum(), getNum())); addition.setSign(_rhs.getSign()); } } if (addition.getNum() == "0") addition.setSign(false); // avoid -0 return addition; } BigInteger BigInteger::sub(const BigInteger & _rhs) const { BigInteger opposite = _rhs; opposite.setSign(!_rhs.sign); return (*this) + opposite; } BigInteger BigInteger::mul(const BigInteger & _rhs) const { BigInteger res; res.setNum(mulNum(num, _rhs.getNum())); if (sign ^ _rhs.getSign()) { // +,- or -,+ res.setSign(true); } else { // +,+ or -,- res.setSign(false); } return res; } BigInteger BigInteger::div(const BigInteger & _rhs) const { if (_rhs == 0) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Division by zeros"); #else std::cerr << "Division by zeros" << std::endl; return 0; #endif } // C++11 standard: // (-m) / n == -(m / n) // m / (-n) == -(m / n) auto ans = divNum(num, _rhs.getNum()); auto quo = BigInteger(ans.first); if (sign == _rhs.getSign()) { // + / + or - / - return quo; } else { // - / + or + / - quo.setSign(true); return quo; } } BigInteger BigInteger::mod(const BigInteger & _rhs) const { if (_rhs == 0) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Division by zeros"); #else std::cerr << "Division by zeros" << std::endl; return 0; #endif } // C++11 standard: // (-m) % n == -(m % n) // m % (-n) == m % n auto ans = divNum(num, _rhs.getNum()); auto rem = BigInteger(ans.second); if (sign) return -rem; else return rem; } BigInteger BigInteger::pow(const BigInteger & _rhs) const { // m ^ n is pow(m, n) if (_rhs < 0) { #ifdef BIGINTEGER_EXCEPTION_ON throw BigIntException("Not support negative exponent"); #else std::cerr << "Not support negative exponent:" << _rhs << std::endl; #endif } if (_rhs == 0) return BigInteger(1); BigInteger x = *this; BigInteger n = _rhs; BigInteger y(1); while (n > 1) { if ((n.getNum()[n.numberOfDigits() - 1] - '0') % 2 == 0) { // if n is even x = x * x; n = n / 2; } else { y = x * y; x = x * x; n = (n - 1) / 2; } } return x * y; } const BigInteger & BigInteger::operator+=(const BigInteger & _rhs) { *this = *this + _rhs; return *this; } const BigInteger & BigInteger::operator-=(const BigInteger & _rhs) { *this = *this - _rhs; return *this; } const BigInteger & BigInteger::operator*=(const BigInteger & _rhs) { *this = *this * _rhs; return *this; } const BigInteger & BigInteger::operator/=(const BigInteger & _rhs) { *this = *this / _rhs; return *this; } const BigInteger & BigInteger::operator%=(const BigInteger & _rhs) { *this = *this % _rhs; return *this; } const BigInteger & BigInteger::operator^=(const BigInteger & _rhs) { *this = *this ^ _rhs; return *this; } const BigInteger & BigInteger::operator++() { *this = *this + 1; return *this; } const BigInteger & BigInteger::operator--() { *this = *this - 1; return *this; } BigInteger BigInteger::operator++(int) { BigInteger before = *this; *this = *this + 1; return before; } BigInteger BigInteger::operator--(int) { BigInteger before = *this; *this = *this - 1; return before; }
676f78c68b8d6c64c3952c01b8faf2d79852728a
f728e25f48f315def7ae69fcaa0679786d2ed01c
/Thread_Mutex_C++11/UniqueLock和LazyInitialization/main.cpp
4d249cb2ede6da36a3a42578f423b08f997f7447
[]
no_license
Dujingwu/CppLearnProj
ec40fbe0dec038a00b8c7ce75b4812706aaada0d
964e5e21dfe7581624c1b530e7ad3a14eb48f45f
refs/heads/master
2021-06-23T14:03:45.435980
2017-09-07T09:26:44
2017-09-07T09:26:44
null
0
0
null
null
null
null
GB18030
C++
false
false
1,065
cpp
#include <iostream> #include <thread> #include <string> #include <mutex> #include <fstream> using namespace std; class LofFile { public: LofFile() { } void shared_print(string id, int value) { /*unique_lock<mutex> locker2(m_mutex_open, defer_lock); if (!of.is_open()) { of.open("log.txt"); }*/ call_once(m_flag, [&]() {of.open("log.txt"); });// //unique_lock<mutex> locker(m_mutex);等价下面两句 unique_lock<mutex> locker(m_mutex, defer_lock); locker.lock(); of << "from" << id << ": " << value << endl; locker.unlock(); //... locker.lock(); } protected: private: mutex m_mutex; mutex m_mutex_open; once_flag m_flag; ofstream of; }; void function_1(LofFile& log) { for (int i = 0; i > -100; i--) { log.shared_print("from function_1: ", i); } } int main() { LofFile log; std::thread t1(function_1, ref(log)); for (int i = 0; i < 100; i++) { log.shared_print("from main: ", i); } t1.join(); return 0; } //uniquelock defer_lock()让mutex暂时不被锁住,当要加锁再lock()\ //uniquelock 可以move
7ce031bb9e80fea8853118611139878325297aaa
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14489/function14489_schedule_24/function14489_schedule_24_wrapper.cpp
80dc69cc3a9c49fb401fe645d25bf9b6d9cc605b
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,352
cpp
#include "Halide.h" #include "function14489_schedule_24_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){ Halide::Buffer<int32_t> buf00(64, 128); Halide::Buffer<int32_t> buf01(128); Halide::Buffer<int32_t> buf02(64, 64, 128); Halide::Buffer<int32_t> buf03(128); Halide::Buffer<int32_t> buf04(64, 64, 128); Halide::Buffer<int32_t> buf05(64, 64, 128); Halide::Buffer<int32_t> buf06(64, 64); Halide::Buffer<int32_t> buf0(64, 64, 64, 128); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function14489_schedule_24(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf06.raw_buffer(), buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function14489/function14489_schedule_24/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
1eebee57d6475fefc65ab7ebc26b09a5a96452a7
24b8b7df9bd80c0f82dc7ea4f04cf83608b959c3
/src/Entities/Entity.cpp
8d7bbe451efa2e1def569891a5ec0c7c88217d4e
[]
no_license
AlexMainstone/new-continents
abc011aa3688b1d6e0aaa7237b2726180829b992
3a0a14b1b5a9e11709e9b591db82146b14ff92ba
refs/heads/master
2022-12-23T01:08:46.733338
2020-09-17T17:18:29
2020-09-17T17:18:29
294,742,636
0
0
null
null
null
null
UTF-8
C++
false
false
1,330
cpp
#include "Entities/Entity.hpp" Entity::Entity(sf::Vector2f pos, int tile, sf::Color color) { this->pos = pos; this->tile = tile; this->color = color; } bool Entity::isMoving() { return move_queue.size() != 0; } void Entity::update(float dt) { // skip if no move if(move_queue.size() == 0) { return; } sf::Vector2i move = move_queue.front(); if(move.x != 0) { move_progress.x += 2 * dt; } if(move.y != 0) { move_progress.y += 2 * dt; } if(move_progress.x >= 1 || move_progress.y >= 1) { move_progress.x = 0; move_progress.y = 0; pos.x += move.x; pos.y += move.y; move_queue.pop(); } } void Entity::moveTo(int x, int y, Map *map) { move_queue = Pathfinding::pathfind_astar(sf::Vector2i(x, y), sf::Vector2i(pos.x, pos.y), map); } void Entity::move(int x, int y) { move(sf::Vector2i(x, y)); } void Entity::move(sf::Vector2i movedir) { move_queue.push(movedir); } void Entity::draw(sf::RenderTarget &target, TileSet *tileset) { sf::Vector2f final_pos = sf::Vector2f(move_progress.x * move_queue.front().x, move_progress.y * move_queue.front().y) + pos; tileset->drawSprite(target, sf::Vector2f(final_pos.x * tileset->getTileSize(), final_pos.y * tileset->getTileSize()), 25, color); }
8e193f10ba3d6099423106a1b73e0626dd299d17
0dd9aaaf64ee65f2f8bec4484b1ca8f4517f54c4
/trunk/ViewController/Controller/SoundController.h
0197c681b7999382e1c79a4e64145ca2b56c3535
[]
no_license
dumppool/mazerts
53c186bcf8f85c5f618f25464a0067f0b23abeb4
7ff775fad18111de8c85552e7bd4c0435b0faba8
refs/heads/master
2020-09-14T16:57:56.936388
2012-07-08T16:36:08
2012-07-08T16:36:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
679
h
/** * * * $Revision$ * $Date$ * $Id$ */ #ifndef __SOUNDCONTROLLER_H__ #define __SOUNDCONTROLLER_H__ #include "IUIController.h" #include "../Camera/Camera.h" #include "../../Model/Common/Config.h" class SoundController : public IUIController { public: SoundController(); ~SoundController(); /** * @see IUIController */ virtual void updateControls(const float frameTime); /** * @see IUIController */ virtual void loadConfigurations(); private: int m_KeySoundToggle; int m_KeyMusicToggle; int m_KeyVolumeUp; int m_KeyVolumeDown; }; #endif // __SOUNDCONTROLLER_H__
e0bbcb59ff038b2d8b3eb9a42bf2e741f7482c1f
534cd3948c3bc665363e04826e1a42200e81cb1b
/code/twodNaive.cpp
43b4f9026672d28909c1a72669f6b07a9b8f373d
[]
no_license
yunpeng5/UpdateRandom
191a27e7e5619133e9c2d86da93dbc2855e212f7
d7a6f6260ab908bb4767617beebfc0e7e8eddcd0
refs/heads/master
2020-09-25T06:28:43.712826
2019-12-05T04:48:28
2019-12-05T04:48:28
225,938,093
0
0
null
null
null
null
UTF-8
C++
false
false
1,288
cpp
#include "twodNaive.h" #include <cmath> using namespace std; twodNaive::twodNaive(int num,double p[]) : gen(rd()) { n=num; sum=0; eps=1e-8; dstore=new double[n]; int i; sq=(int)(ceil(sqrt(n))+eps); sqn=(int)(ceil(1.0*n/sq)+eps); tdstore=new double[sqn]; int tei=0,ted=0; double te=0; for(i=0;i<n;i++) { dstore[i]=p[i]; sum+=p[i]; te+=p[i]; tei++; if(tei==sq) { tdstore[ted]=te; te=0; tei=0; ted++; } } if(tei!=0)tdstore[ted]=te; } twodNaive::~twodNaive() { delete [] dstore; delete [] tdstore; } const double* twodNaive::table1() { return dstore; } const double* twodNaive::table2() { return tdstore; } double twodNaive::resum() { return sum; } void twodNaive::change(int index,double weight) { int row=index/sq; tdstore[row]-=dstore[index]; tdstore[row]+=weight; sum-=dstore[index]; sum+=weight; dstore[index]=weight; } int twodNaive::ransample() { uniform_real_distribution<double> dr(0,sum); double dart=dr(gen); int row=0; while(tdstore[row]<dart)dart-=tdstore[row],row++; row*=sq; while(dstore[row]<dart)dart-=dstore[row],row++; return row; }
9227e1424724f87104c24250b09faa44a4201ab4
ba9322f7db02d797f6984298d892f74768193dcf
/snsuapi/include/alibabacloud/snsuapi/SnsuapiClient.h
7726d3e494403fd1d26824cf3e83117baa122465
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
8,387
h
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ALIBABACLOUD_SNSUAPI_SNSUAPICLIENT_H_ #define ALIBABACLOUD_SNSUAPI_SNSUAPICLIENT_H_ #include <future> #include <alibabacloud/core/AsyncCallerContext.h> #include <alibabacloud/core/EndpointProvider.h> #include <alibabacloud/core/RpcServiceClient.h> #include "SnsuapiExport.h" #include "model/MobileStartSpeedUpRequest.h" #include "model/MobileStartSpeedUpResult.h" #include "model/BandStopSpeedUpRequest.h" #include "model/BandStopSpeedUpResult.h" #include "model/BandStatusQueryRequest.h" #include "model/BandStatusQueryResult.h" #include "model/MobileStatusQueryRequest.h" #include "model/MobileStatusQueryResult.h" #include "model/BandOfferOrderRequest.h" #include "model/BandOfferOrderResult.h" #include "model/MobileStopSpeedUpRequest.h" #include "model/MobileStopSpeedUpResult.h" #include "model/BandPrecheckRequest.h" #include "model/BandPrecheckResult.h" #include "model/BandStartSpeedUpRequest.h" #include "model/BandStartSpeedUpResult.h" namespace AlibabaCloud { namespace Snsuapi { class ALIBABACLOUD_SNSUAPI_EXPORT SnsuapiClient : public RpcServiceClient { public: typedef Outcome<Error, Model::MobileStartSpeedUpResult> MobileStartSpeedUpOutcome; typedef std::future<MobileStartSpeedUpOutcome> MobileStartSpeedUpOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::MobileStartSpeedUpRequest&, const MobileStartSpeedUpOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MobileStartSpeedUpAsyncHandler; typedef Outcome<Error, Model::BandStopSpeedUpResult> BandStopSpeedUpOutcome; typedef std::future<BandStopSpeedUpOutcome> BandStopSpeedUpOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::BandStopSpeedUpRequest&, const BandStopSpeedUpOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> BandStopSpeedUpAsyncHandler; typedef Outcome<Error, Model::BandStatusQueryResult> BandStatusQueryOutcome; typedef std::future<BandStatusQueryOutcome> BandStatusQueryOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::BandStatusQueryRequest&, const BandStatusQueryOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> BandStatusQueryAsyncHandler; typedef Outcome<Error, Model::MobileStatusQueryResult> MobileStatusQueryOutcome; typedef std::future<MobileStatusQueryOutcome> MobileStatusQueryOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::MobileStatusQueryRequest&, const MobileStatusQueryOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MobileStatusQueryAsyncHandler; typedef Outcome<Error, Model::BandOfferOrderResult> BandOfferOrderOutcome; typedef std::future<BandOfferOrderOutcome> BandOfferOrderOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::BandOfferOrderRequest&, const BandOfferOrderOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> BandOfferOrderAsyncHandler; typedef Outcome<Error, Model::MobileStopSpeedUpResult> MobileStopSpeedUpOutcome; typedef std::future<MobileStopSpeedUpOutcome> MobileStopSpeedUpOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::MobileStopSpeedUpRequest&, const MobileStopSpeedUpOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MobileStopSpeedUpAsyncHandler; typedef Outcome<Error, Model::BandPrecheckResult> BandPrecheckOutcome; typedef std::future<BandPrecheckOutcome> BandPrecheckOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::BandPrecheckRequest&, const BandPrecheckOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> BandPrecheckAsyncHandler; typedef Outcome<Error, Model::BandStartSpeedUpResult> BandStartSpeedUpOutcome; typedef std::future<BandStartSpeedUpOutcome> BandStartSpeedUpOutcomeCallable; typedef std::function<void(const SnsuapiClient*, const Model::BandStartSpeedUpRequest&, const BandStartSpeedUpOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> BandStartSpeedUpAsyncHandler; SnsuapiClient(const Credentials &credentials, const ClientConfiguration &configuration); SnsuapiClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration); SnsuapiClient(const std::string &accessKeyId, const std::string &accessKeySecret, const ClientConfiguration &configuration); ~SnsuapiClient(); MobileStartSpeedUpOutcome mobileStartSpeedUp(const Model::MobileStartSpeedUpRequest &request)const; void mobileStartSpeedUpAsync(const Model::MobileStartSpeedUpRequest& request, const MobileStartSpeedUpAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; MobileStartSpeedUpOutcomeCallable mobileStartSpeedUpCallable(const Model::MobileStartSpeedUpRequest& request) const; BandStopSpeedUpOutcome bandStopSpeedUp(const Model::BandStopSpeedUpRequest &request)const; void bandStopSpeedUpAsync(const Model::BandStopSpeedUpRequest& request, const BandStopSpeedUpAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; BandStopSpeedUpOutcomeCallable bandStopSpeedUpCallable(const Model::BandStopSpeedUpRequest& request) const; BandStatusQueryOutcome bandStatusQuery(const Model::BandStatusQueryRequest &request)const; void bandStatusQueryAsync(const Model::BandStatusQueryRequest& request, const BandStatusQueryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; BandStatusQueryOutcomeCallable bandStatusQueryCallable(const Model::BandStatusQueryRequest& request) const; MobileStatusQueryOutcome mobileStatusQuery(const Model::MobileStatusQueryRequest &request)const; void mobileStatusQueryAsync(const Model::MobileStatusQueryRequest& request, const MobileStatusQueryAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; MobileStatusQueryOutcomeCallable mobileStatusQueryCallable(const Model::MobileStatusQueryRequest& request) const; BandOfferOrderOutcome bandOfferOrder(const Model::BandOfferOrderRequest &request)const; void bandOfferOrderAsync(const Model::BandOfferOrderRequest& request, const BandOfferOrderAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; BandOfferOrderOutcomeCallable bandOfferOrderCallable(const Model::BandOfferOrderRequest& request) const; MobileStopSpeedUpOutcome mobileStopSpeedUp(const Model::MobileStopSpeedUpRequest &request)const; void mobileStopSpeedUpAsync(const Model::MobileStopSpeedUpRequest& request, const MobileStopSpeedUpAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; MobileStopSpeedUpOutcomeCallable mobileStopSpeedUpCallable(const Model::MobileStopSpeedUpRequest& request) const; BandPrecheckOutcome bandPrecheck(const Model::BandPrecheckRequest &request)const; void bandPrecheckAsync(const Model::BandPrecheckRequest& request, const BandPrecheckAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; BandPrecheckOutcomeCallable bandPrecheckCallable(const Model::BandPrecheckRequest& request) const; BandStartSpeedUpOutcome bandStartSpeedUp(const Model::BandStartSpeedUpRequest &request)const; void bandStartSpeedUpAsync(const Model::BandStartSpeedUpRequest& request, const BandStartSpeedUpAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const; BandStartSpeedUpOutcomeCallable bandStartSpeedUpCallable(const Model::BandStartSpeedUpRequest& request) const; private: std::shared_ptr<EndpointProvider> endpointProvider_; }; } } #endif // !ALIBABACLOUD_SNSUAPI_SNSUAPICLIENT_H_
19e5ea90d0bf61c8c16c7176c831609c854d96dd
b2a8e29894f681a72ecf1d51a82a63bfa920e06f
/TinySTL/Vector.h
4ce9be6a9213685f4cdd60cde21d6c4541a10267
[]
no_license
SinnerA/TinySTL
3881aefc5349c15fc87eec11d96d9b6197ef8aa3
5b368accd62f208dc65df5721a56c4632d5f16b5
refs/heads/master
2021-01-10T20:38:31.969512
2015-10-12T07:17:30
2015-10-12T07:17:30
35,008,182
0
0
null
null
null
null
GB18030
C++
false
false
4,474
h
#ifndef _VECTOR_H_ #define _VECTOR_H_ #include <algorithm> #include <type_traits> #include "Allocator.h" #include "Algorithm.h" #include "Iterator.h" #include "ReverseIterator.h" #include "UninitializedFunctions.h" namespace TinySTL{ template <class T, class Alloc = allocator<T>> class vector{ private: T* start_; //vector首元素 T* finish_; //vector末元素后一个元素 T* endOfStorge_; //新分配内存中末元素后一个元素 typedef Alloc dataAllocator; public: typedef T value_type; typedef T* iterator; typedef const T* const_iterator; //typedef reverse_iterator_t<T*> reverse_iterator; //typedef reverse_iterator_t<const T*> const_reverse_iterator; typedef iterator pointer; typedef T& reference; typedef const T& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; public: //构造,复制,析构相关函数 vector() :start_(0), finish_(0), endOfStorge_(0){ } explicit vector(const size_type n); explicit vector(const size_type n, const value_type& value); vector(const vector& v); template <class InputIterator> vector(InputIterator begin, InputIterator end); vector& operator=(const vector&); ~vector(){ destoryAndDeallocateAll(); } //比较相关 bool operator==(const vector&); bool operator!=(const vector&); //迭代器相关 iterator begin(){ return start_; } const_iterator begin() const{ return start_; } const_iterator cbegin() const{ return start_; } iterator end() { return finish_; } const_iterator end() const{ return finish_; } const_iterator cend() const{ return finish_; } iterator rbegin(){ return reverse_iterator(finish_); } const_iterator crbegin(){ return const_reverse_iterator(finish_); } iterator rend(){ return reverse_iterator(start_); } const_iterator crend(){ return const_reverse_iterator(start_); } //容量相关 difference_type size() const{ return finish_ - start_; } difference_type capacity() const{ return endOfStorge_ - start_; } bool empty(){ return start_ == finish_; } void resize(size_type n, value_type val = value_type()); void reserve(size_type n); void shrink_to_fit(); //访问元素相关 reference operator[](const difference_type i){ return *(begin() + i); } const_reference operator[](const difference_type i) const{ return *(cbegin() + i); } reference front(){ return *(begin()); } reference back(){ return *(end() - 1); } pointer data(){ return start_; } //修改容器相关操作 void clear(); void push_back(const value_type& val); void pop_back(); void swap(vector& v); iterator insert(iterator position, const value_type& val); void insert(iterator position, const size_type& n, const value_type& val); template <class InputIterator> void insert(iterator position, InputIterator first, InputIterator last); iterator erase(iterator position); iterator erase(iterator first, iterator last); //容器的空间配置器相关 Alloc get_allocator(){ return dataAllocator; } private: //内存分配工具 void destoryAndDeallocateAll(); void allocateAndFillN(const size_type n, const value_type& value); template <class InputIterator> void allocateAndCopy(InputIterator first, InputIterator last); template <class InputIterator> void vector_aux(InputIterator first, InputIterator last, std::false_type); template <class Integer> void vector_aux(Integer n, const value_type& value, std::true_type); template <class InputIterator> void insert_aux(iterator position, InputIterator first, InputIterator last, std::false_type); template <class Integer> void insert_aux(iterator position, Integer n, const value_type& value, std::true_type); template <class InputIterator> void reallocateAndCopy(iterator position, InputIterator first, InputIterator last); void reallocateAndFillN(iterator position, const size_type& n, const value_type& value); size_type getNewCapacity(size_type len) const; public: template <class T, class Alloc> friend bool operator==(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2); template <class T, class Alloc> friend bool operator!=(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2); };//end of class vector } #include "Detail\Vector.impl.h" #endif
04ec13e86391c99a363ebaf8f36d39ab3d59315f
aab77b2a871638ca4ce0a162431206cb8e930e13
/data/input/boost_1_53_0 (1)/boost_1_53_0/libs/interprocess/test/offset_ptr_test.cpp
6b1189e2ded8ba1bbe3bfee4cd89cd9206f38202
[ "BSL-1.0" ]
permissive
tl66365561/Search_engine
0ddc51b3baa3eaddc4865d7411d75b08bf905ffb
7adcf988f0e25e3e1ed2f0bbf762ebd6d76bf810
refs/heads/master
2020-05-05T11:05:55.593848
2019-07-02T04:34:48
2019-07-02T04:34:48
179,975,031
3
0
null
null
null
null
UTF-8
C++
false
false
9,374
cpp
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2007-2012. 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/interprocess for documentation. // ////////////////////////////////////////////////////////////////////////////// #include <boost/interprocess/detail/config_begin.hpp> #include <boost/interprocess/offset_ptr.hpp> #include <boost/interprocess/detail/type_traits.hpp> #include <boost/intrusive/pointer_traits.hpp> #include <boost/static_assert.hpp> using namespace boost::interprocess; class Base {}; class Derived : public Base {}; class VirtualDerived : public virtual Base {}; bool test_types_and_conversions() { typedef offset_ptr<int> pint_t; typedef offset_ptr<const int> pcint_t; typedef offset_ptr<volatile int> pvint_t; typedef offset_ptr<const volatile int> pcvint_t; BOOST_STATIC_ASSERT((ipcdetail::is_same<pint_t::element_type, int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pcint_t::element_type, const int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pvint_t::element_type, volatile int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pcvint_t::element_type, const volatile int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pint_t::value_type, int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pcint_t::value_type, int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pvint_t::value_type, int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<pcvint_t::value_type, int>::value)); int dummy_int = 9; { pint_t pint(&dummy_int); pcint_t pcint(pint); if(pcint.get() != &dummy_int) return false; } { pint_t pint(&dummy_int); pvint_t pvint(pint); if(pvint.get() != &dummy_int) return false; } { pint_t pint(&dummy_int); pcvint_t pcvint(pint); if(pcvint.get() != &dummy_int) return false; } { pcint_t pcint(&dummy_int); pcvint_t pcvint(pcint); if(pcvint.get() != &dummy_int) return false; } { pvint_t pvint(&dummy_int); pcvint_t pcvint(pvint); if(pcvint.get() != &dummy_int) return false; } pint_t pint(0); pcint_t pcint(0); pvint_t pvint(0); pcvint_t pcvint(0); pint = &dummy_int; pcint = &dummy_int; pvint = &dummy_int; pcvint = &dummy_int; { pcint = pint; if(pcint.get() != &dummy_int) return false; } { pvint = pint; if(pvint.get() != &dummy_int) return false; } { pcvint = pint; if(pcvint.get() != &dummy_int) return false; } { pcvint = pcint; if(pcvint.get() != &dummy_int) return false; } { pcvint = pvint; if(pcvint.get() != &dummy_int) return false; } if(!pint) return false; pint = 0; if(pint) return false; if(pint != 0) return false; if(0 != pint) return false; pint = &dummy_int; if(0 == pint) return false; if(pint == 0) return false; pcint = &dummy_int; if( (pcint - pint) != 0) return false; if( (pint - pcint) != 0) return false; return true; } template<class BasePtr, class DerivedPtr> bool test_base_derived_impl() { typename DerivedPtr::element_type d; DerivedPtr pderi(&d); BasePtr pbase(pderi); pbase = pderi; if(pbase != pderi) return false; if(!(pbase == pderi)) return false; if((pbase - pderi) != 0) return false; if(pbase < pderi) return false; if(pbase > pderi) return false; if(!(pbase <= pderi)) return false; if(!(pbase >= pderi)) return false; return true; } bool test_base_derived() { typedef offset_ptr<Base> pbase_t; typedef offset_ptr<const Base> pcbas_t; typedef offset_ptr<Derived> pderi_t; typedef offset_ptr<VirtualDerived> pvder_t; if(!test_base_derived_impl<pbase_t, pderi_t>()) return false; if(!test_base_derived_impl<pbase_t, pvder_t>()) return false; if(!test_base_derived_impl<pcbas_t, pderi_t>()) return false; if(!test_base_derived_impl<pcbas_t, pvder_t>()) return false; return true; } bool test_arithmetic() { typedef offset_ptr<int> pint_t; const int NumValues = 5; int values[NumValues]; //Initialize p pint_t p = values; if(p.get() != values) return false; //Initialize p + NumValues pint_t pe = &values[NumValues]; if(pe == p) return false; if(pe.get() != &values[NumValues]) return false; //ptr - ptr if((pe - p) != NumValues) return false; //ptr - integer if((pe - NumValues) != p) return false; //ptr + integer if((p + NumValues) != pe) return false; //integer + ptr if((NumValues + p) != pe) return false; //indexing if(pint_t(&p[NumValues]) != pe) return false; if(pint_t(&pe[-NumValues]) != p) return false; //ptr -= integer pint_t p0 = pe; p0-= NumValues; if(p != p0) return false; //ptr += integer pint_t penew = p0; penew += NumValues; if(penew != pe) return false; //++ptr penew = p0; for(int j = 0; j != NumValues; ++j, ++penew); if(penew != pe) return false; //--ptr p0 = pe; for(int j = 0; j != NumValues; ++j, --p0); if(p != p0) return false; //ptr++ penew = p0; for(int j = 0; j != NumValues; ++j){ pint_t p_new_copy = penew; if(p_new_copy != penew++) return false; } //ptr-- p0 = pe; for(int j = 0; j != NumValues; ++j){ pint_t p0_copy = p0; if(p0_copy != p0--) return false; } return true; } bool test_comparison() { typedef offset_ptr<int> pint_t; const int NumValues = 5; int values[NumValues]; //Initialize p pint_t p = values; if(p.get() != values) return false; //Initialize p + NumValues pint_t pe = &values[NumValues]; if(pe == p) return false; if(pe.get() != &values[NumValues]) return false; //operators if(p == pe) return false; if(p != p) return false; if(!(p < pe)) return false; if(!(p <= pe)) return false; if(!(pe > p)) return false; if(!(pe >= p)) return false; return true; } bool test_pointer_traits() { typedef offset_ptr<int> OInt; typedef boost::intrusive::pointer_traits< OInt > PTOInt; BOOST_STATIC_ASSERT((ipcdetail::is_same<PTOInt::element_type, int>::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<PTOInt::pointer, OInt >::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<PTOInt::difference_type, OInt::difference_type >::value)); BOOST_STATIC_ASSERT((ipcdetail::is_same<PTOInt::rebind_pointer<double>::type, offset_ptr<double> >::value)); int dummy; OInt oi(&dummy); if(boost::intrusive::pointer_traits<OInt>::pointer_to(dummy) != oi){ return false; } return true; } int main() { if(!test_types_and_conversions()) return 1; if(!test_base_derived()) return 1; if(!test_arithmetic()) return 1; if(!test_comparison()) return 1; if(!test_pointer_traits()) return 1; return 0; } #include <boost/interprocess/detail/config_end.hpp> /* //Offset ptr benchmark #include <vector> #include <iostream> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/containers/vector.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <boost/timer.hpp> #include <cstddef> template<class InIt, class Ty> inline Ty accumulate2(InIt First, InIt Last, Ty Val) { // return sum of Val and all in [First, Last) for (; First != Last; ++First) //First = First + 1) Val = Val + *First; return (Val); } template <typename Vector> void time_test(const Vector& vec, std::size_t iterations, const char* label) { // assert(!vec.empty()) boost::timer t; typename Vector::const_iterator first = vec.begin(); typename Vector::value_type result(0); while (iterations != 0) { result = accumulate2(first, first + vec.size(), result); --iterations; } std::cout << label << t.elapsed() << " " << result << std::endl; } int main() { using namespace boost::interprocess; typedef allocator<double, managed_shared_memory::segment_manager> alloc_t; std::size_t n = 0x1 << 26; std::size_t file_size = n * sizeof(double) + 1000000; { shared_memory_object::remove("MyMappedFile"); managed_shared_memory segment(open_or_create, "MyMappedFile", file_size); shared_memory_object::remove("MyMappedFile"); alloc_t alloc_inst(segment.get_segment_manager()); vector<double, alloc_t> v0(n, double(42.42), alloc_inst); time_test(v0, 10, "iterator shared: "); } { std::vector<double> v1(n, double(42.42)); time_test(v1, 10, "iterator non-shared: "); } return 0; } */
8213ef62e0cc2fc930903347e054fcddecd0a2a5
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_block_2001.cpp
7f28ee7cda6269a2a8be549fce99e766882374ad
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
83
cpp
{ printf("Running command: %s with %d arguments\n", argv[0], argc); return 0; }
bbd18675f0b69ce3770bcbcb173e14ff0b034321
491c2662b78cd31356dc2234330bd7c11cce7276
/04-Collision/Stage.h
ea5e4ebc2548d258e6e5485e1171012301053172
[]
no_license
16520021/Game
71a92bf66847a7d0b588e866dd86ff2b898a4996
8685f43ea88fc9da7440457edf10b1cfb221f40d
refs/heads/master
2020-04-08T23:27:18.437496
2018-12-29T06:07:59
2018-12-29T06:07:59
157,554,653
0
0
null
null
null
null
UTF-8
C++
false
false
345
h
#pragma once #include <string.h> #include <sstream> #include <fstream> #include <vector> #include "debug.h" class CStage { public: CStage(); bool isRunning; void splitStr(const std::string& str, std::vector<int> &cont, char delim = ' '); void ReadArrayFromFile(std::string FileName, std::vector<int> &map, char delim = ' '); ~CStage(); };
[ "antran2361998" ]
antran2361998
58efc3a626d0e47424abc417801d9ec2e5e659f5
3dd49f1ebae3af35d6d24c58ade47880dbdfa11f
/src/chapter12/ex12_1.cpp
9650241cfa7e05c2c4fd7f184e27f352ee03be8d
[]
no_license
xiaoqiangkx/cpp_primer
dc6be8e602247f4bd0c6346ecefac8049b7f1207
37c51fcb1559b80dbe871fff22c8abb05396a608
refs/heads/master
2021-01-23T12:37:43.916372
2014-10-10T07:58:41
2014-10-10T07:58:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
917
cpp
#include <iostream> #include <string> #include "test1.cpp" using namespace std; class Person { public: typedef string str; Person(const string &_name, const string &_address): name(_name), address(_address) {} string get_name() const; string get_address() const; Person& plus(const string &add_str); private: str name; string address; }; string Person::get_name() const { return name; } string Person::get_address() const { return address; } Person& Person::plus(const string &add_str) { name += add_str; return *this; } int main() { const string &data = "hello"; string name("qingfeng"); string address("Beijing"); Person person(name, address); person.plus(address).plus(name).plus("hello"); Person::str _name = person.get_name(); cout << _name << endl << person.get_address() << endl; return 0; }
7ceaedeb1e13a9921c53aae0bb4925927c29d102
57ac85ca91d0f218be2a97e41ad7f8967728e7b9
/blazetest/src/mathtest/dmatdmatmin/MHaMDa.cpp
ef6eae40d1dd452724ecc40dc26285f6449bd5ad
[ "BSD-3-Clause" ]
permissive
AuroraDysis/blaze
b297baa6c96b77c3d32de789e0e3af27782ced77
d5cacf64e8059ca924eef4b4e2a74fc9446d71cb
refs/heads/master
2021-01-01T16:49:28.921446
2017-07-22T23:24:26
2017-07-22T23:24:26
97,930,727
1
0
null
null
null
null
UTF-8
C++
false
false
4,184
cpp
//================================================================================================= /*! // \file src/mathtest/dmatdmatmin/MHaMDa.cpp // \brief Source file for the MHaMDa dense matrix/dense matrix minimum math test // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT 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. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/HybridMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatmin/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MHaMDa'..." << std::endl; using blazetest::mathtest::TypeA; try { // Matrix type definitions typedef blaze::HybridMatrix<TypeA,128UL,128UL> MHa; typedef blaze::DynamicMatrix<TypeA> MDa; // Creator type definitions typedef blazetest::Creator<MHa> CMHa; typedef blazetest::Creator<MDa> CMDa; // Running tests with small matrices for( size_t i=0UL; i<=9UL; ++i ) { for( size_t j=0UL; j<=9UL; ++j ) { RUN_DMATDMATMIN_OPERATION_TEST( CMHa( i, j ), CMDa( i, j ) ); } } // Running tests with large matrices RUN_DMATDMATMIN_OPERATION_TEST( CMHa( 67UL, 67UL ), CMDa( 67UL, 67UL ) ); RUN_DMATDMATMIN_OPERATION_TEST( CMHa( 67UL, 127UL ), CMDa( 67UL, 127UL ) ); RUN_DMATDMATMIN_OPERATION_TEST( CMHa( 128UL, 64UL ), CMDa( 128UL, 64UL ) ); RUN_DMATDMATMIN_OPERATION_TEST( CMHa( 128UL, 128UL ), CMDa( 128UL, 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix minimum:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
5f29cadfb78935b2f6da0aa1322d5ed6590fe668
00019d89bab4f2d723aeb9e861a86965c5849023
/AI_Tribal/GameStateManager/KeyboardBehaviour.h
835cde85641f604941a9d7cc61afffa0b0b3cdf4
[]
no_license
Madcrafty/AI_Resource_Sim
d6a2c77aef014dead98ce4d3fce2785a57d6ae19
3f1f6ac831cf813fb28a749376be4a4280b18e2a
refs/heads/master
2022-12-10T02:12:25.837362
2020-09-04T07:11:05
2020-09-04T07:11:05
285,705,934
0
0
null
null
null
null
UTF-8
C++
false
false
251
h
#pragma once #include "Behaviour.h" class KeyboardBehaviour : public Behaviour { public: KeyboardBehaviour() {}; virtual ~KeyboardBehaviour() {}; virtual Vector2 Update(Agent* agent, float deltaTime); private: float m_speedIncrement = 50.0f; };
a493860c30e544fd31948d6178861564e7ceff9f
26c7705d5a1faa7f29d72ed8176f69be6965f4e8
/39SmoothTraffic1012.cpp
0551f4d23e40e08422b90ced5a89d2cac24fc5f8
[]
no_license
haiki/OJcode
adf9dcfdb66eb12faeed36745833c6103a90c243
1055071819d3417dbbac17b50abaeb1304078a89
refs/heads/master
2020-04-05T12:38:57.841769
2017-09-08T11:41:27
2017-09-08T11:41:27
95,211,438
0
0
null
null
null
null
GB18030
C++
false
false
1,264
cpp
#include<iostream> using namespace std; #define N 1000 int tree[N]; int FindRoot(int x) { if(tree[x]==-1) return x; else { int tmp=FindRoot(tree[x]); tree[x]=tmp; return tmp; } } //非递归实现 /*int FindRoot(int x) { if(tree[x]==-1) return x; else { int tmp=x; while(tree[x]!=-1) { x=tree[x]; } int ret=x; x=tmp; while(tree[x]!=-1) { tree[x]=ret; x=tree[x]; } return ret; } }*/ int main() { int n,m; while(cin>>n&&n!=0) { cin>>m; for(int i=1; i<=n; i++) //刚开始每个城镇都是孤立的节点,从1-n编号 tree[i]=-1; int a,b; for(int i=0; i<m; i++) { cin>>a>>b; a=FindRoot(a); b=FindRoot(b); if(a!=b) { tree[a]=b;//如果两个节点不在一个集合中 则把一个的根节点设置为另一个元素 即合并两个集合 } } int ans=0; for(int i=1; i<=n; i++) { if(tree[i]==-1) ans++; } cout<<ans-1<<endl; } return 0; }
29a927f113f09b907ed637e4f0aa39a3cd764132
7e2da146f889e44a6dd4c4470aa79737d69d7c55
/DSMCUService/GridTable.cpp
fb33dabab20ec513c875118cfa8fa0f809180935
[]
no_license
mbox54/DSMCU_UTB_rev0
e6a947acaf663b7ba691d59c9dc5c1bf43ca4808
18b97743db448ec33e784161bf2380408012a953
refs/heads/master
2021-01-23T20:07:14.536783
2017-09-08T11:31:26
2017-09-08T11:31:26
102,853,429
1
0
null
null
null
null
UTF-8
C++
false
false
18,270
cpp
// class CGridTable implementation file ///////////////////////////////////////////////////////////////////////////// // Includes ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "GridTable.h" // ################################################################### // CGridTable GridCtrl // ################################################################### CGridTable::CGridTable() { } CGridTable::~CGridTable() { } // Service // NOTE: // FORMAT of file: // --------------------------------------------------------------- // File consist set of Lines. // Lines has many Types: *starter descript*, *null*, *label*, *value*, *space delimeter* // /.../ - comment // /0 Line/ *starter descript* *value* - File Type /MSA Table Description File/ // .. *space delimeter* .. // *label* /[version]/ // /next Line/ *value* - version of File /ver 1.0/ // .. *space delimeter* .. // *label* /[info]/ // /next Line/ *value* 1: column count // /next Line/ *value* 2: fixed columns // /next Line/ *value* 3: column headers, column width // .. *(cols count) Times* // /next Line/ *value* 4: rows count // .. *space delimeter* .. // *label* /[data]/ // /next Line/ *value* : rows values(col1 \n col2 \n col3 \n col4 \n) // .. *(cols count) Times* // .. .. *(rows count) Times* // --------------------------------------------------------------- int CGridTable::TableConfig_LoadFromFile(char * file_name) { // > Read config from File FILE * fs; unsigned short uiRow; // Table Cell Row number unsigned char ucCol; // Table Cell Col number // > Open File / Try errno_t err; if ((err = fopen_s(&fs, file_name, "r")) != 0) { // "can't read file" return OP_FAILED; } // > Read File with Config and Data const unsigned short MAX_LINE_LENGTH = 256; char v_loadLine[MAX_LINE_LENGTH]; CString cellText; // Cell Value var // NOTE: MAX Line Length is MAX_LINE_LENGTH unsigned char ucColCount = 0; // Table Cell Col count unsigned short uiRowCount = 0; // Table Cell Row count // # Proceed Line routine unsigned short k; // line symbol var // > /Line 00/ *starter descript* *value* - File Type /MSA Table Description File/ fgets(v_loadLine, MAX_LINE_LENGTH, fs); // (proc) NOP // .. *space delimeter* .. fgets(v_loadLine, MAX_LINE_LENGTH, fs); // > /Line NN/ *label* /[version]/ fgets(v_loadLine, MAX_LINE_LENGTH, fs); // /next Line/ *value* - ver. NN fgets(v_loadLine, MAX_LINE_LENGTH, fs); // (proc) NOP // .. *space delimeter* .. fgets(v_loadLine, MAX_LINE_LENGTH, fs); // > /Line NN/ *label* / [info] / CString strLineInfo; fgets(v_loadLine, MAX_LINE_LENGTH, fs); // /next Line/ *comment* - 1: column count fgets(v_loadLine, MAX_LINE_LENGTH, fs); // /next Line/ *value* fgets(v_loadLine, MAX_LINE_LENGTH, fs); k = 0; strLineInfo.Truncate(0); while (v_loadLine[k] != '\n') { // SafeCheck if (v_loadLine[k] == '\0') { break; } strLineInfo.AppendChar(v_loadLine[k]); k++; } ucColCount = (WORD)_tcstoul(strLineInfo, NULL, 10); m_nFixRows = 1; m_nCols = ucColCount; // /next Line/ *comment* - 2: fixed columns fgets(v_loadLine, MAX_LINE_LENGTH, fs); // /next Line/ *value* fgets(v_loadLine, MAX_LINE_LENGTH, fs); k = 0; strLineInfo.Truncate(0); while (v_loadLine[k] != '\n') { // SafeCheck if (v_loadLine[k] == '\0') { break; } strLineInfo.AppendChar(v_loadLine[k]); k++; } m_nFixCols = (WORD)_tcstoul(strLineInfo, NULL, 10); m_nRows = 2; // 1 Fix + 1 vacant // Set Table Size TRY { this->SetRowCount(m_nRows); this->SetColumnCount(m_nCols); this->SetFixedRowCount(m_nFixRows); this->SetFixedColumnCount(m_nFixCols); } CATCH(CMemoryException, e) { e->ReportError(); return OP_FAILED; } END_CATCH // /next Line/ *comment* - 3: column headers, column width fgets(v_loadLine, MAX_LINE_LENGTH, fs); // /next Line/ *value* CString strLineColHead; unsigned short uiColHeadLength; uiRow = 0; // Set Header Row for (unsigned char k = 0; k < ucColCount; k++) { ucCol = k; // - column header if (fgets(v_loadLine, MAX_LINE_LENGTH, fs) == NULL) { fclose(fs); return OP_FILE_NODATA; } unsigned short kk = 0; // local line symbol number var // build value string strLineColHead.Truncate(0); while (v_loadLine[kk] != '\n') { // SafeCheck if (v_loadLine[kk] == '\0') { break; } strLineColHead.AppendChar(v_loadLine[kk]); kk++; } // adapt to set Value cellText.Truncate(0); cellText.Append(strLineColHead); // set in Table GV_ITEM Item; Item.mask = GVIF_TEXT; Item.row = uiRow; Item.col = ucCol; Item.strText = cellText; this->SetItem(&Item); //this->SetItemText(uiRow, ucCol, cellText); // - column length if (fgets(v_loadLine, MAX_LINE_LENGTH, fs) == NULL) { fclose(fs); return OP_FILE_NODATA; } // build value string kk = 0; strLineColHead.Truncate(0); while (v_loadLine[kk] != '\n') { // SafeCheck if (v_loadLine[kk] == '\0') { break; } strLineColHead.AppendChar(v_loadLine[kk]); kk++; } // adapt to set Value uiColHeadLength = (WORD)_tcstoul(strLineColHead, NULL, 10); // set in Table this->SetColumnWidth(k, uiColHeadLength); } // for: column parse // /next Line/ *comment* - 4: rows count fgets(v_loadLine, MAX_LINE_LENGTH, fs); // /next Line/ *value* fgets(v_loadLine, MAX_LINE_LENGTH, fs); k = 0; strLineInfo.Truncate(0); while (v_loadLine[k] != '\n') { // SafeCheck if (v_loadLine[k] == '\0') { break; } strLineInfo.AppendChar(v_loadLine[k]); k++; } uiRowCount = (WORD)_tcstoul(strLineInfo, NULL, 10); m_nRows = uiRowCount + 1; // Set Table Size TRY { this->SetRowCount(m_nRows); //this->SetColumnCount(m_nCols); //this->SetFixedRowCount(m_nFixRows); //this->SetFixedColumnCount(m_nFixCols); } CATCH(CMemoryException, e) { e->ReportError(); return OP_FAILED; } END_CATCH // .. *space delimeter* .. fgets(v_loadLine, MAX_LINE_LENGTH, fs); // search Pattern string // // get line str CString strPattern = _T("[data]"); unsigned char ucPatternLength = strPattern.GetLength(); unsigned char ACT = 1; while (ACT) // Read until key { // > /Line NN/ *label* / [data] if (fgets(v_loadLine, MAX_LINE_LENGTH, fs) == NULL) { // DECISION: alternative to "return" is var that keep error code at the last end. // ACT = 0; fclose(fs); return OP_FILE_NODATA; } // > compare to pattern CString strLine; for (unsigned char k = 0; k < ucPatternLength; k++) { strLine.AppendChar(v_loadLine[k]); } if (strPattern.Compare(strLine) == 0) { // pattern successed ACT = 0; } } // while [data] // /next Line/ *value* x(RowCount) : rows values(col1, col2, col3, col4) for (unsigned short k = 0; k < uiRowCount; k++) { uiRow = k + 1; // > Parse string set for (unsigned short kk = 0; kk < ucColCount; kk++) { ucCol = kk; if (fgets(v_loadLine, MAX_LINE_LENGTH, fs) == NULL) { fclose(fs); return OP_FILE_NODATA; } unsigned short k2 = 0; CString strLineCol; while (v_loadLine[k2] != '\n') { // SafeCheck if (v_loadLine[k2] == '\0') { break; } strLineCol.AppendChar(v_loadLine[k2]); k2++; } // adapt to set Value cellText.Truncate(0); cellText.Append(strLineCol); // set in Table GV_ITEM Item; Item.mask = GVIF_TEXT; Item.row = uiRow; Item.col = ucCol; Item.strText = cellText; this->SetItem(&Item); } // for Parse // Line \n ender if (fgets(v_loadLine, MAX_LINE_LENGTH, fs) == NULL) { fclose(fs); return OP_FILE_NODATA; } } // for rows values(col1 \n col2 \n col3 \n col4 \n) fclose(fs); return OP_SUCCESS; } void CGridTable::Init(char * fileName, unsigned char ucType) { if (ucType == 0) { // Define Grid table common parameters Config(); TableConfig_LoadFromFile(fileName); } } void CGridTable::Config() { m_OldSize = CSize(-1, -1); //{{AFX_DATA_INIT(CGridCtrlDemoDlg) m_bEditable = TRUE; m_bHorzLines = FALSE; m_bVertLines = FALSE; m_bListMode = TRUE; m_bHeaderSort = FALSE; m_bSingleSelMode = TRUE; m_bSingleColSelMode = TRUE; m_bSelectable = FALSE; m_bAllowColumnResize = FALSE; m_bAllowRowResize = FALSE; m_bItalics = FALSE; m_btitleTips = FALSE; m_bTrackFocus = FALSE; m_bFrameFocus = FALSE; m_bVirtualMode = FALSE; m_bCallback = TRUE; m_bVertical = TRUE; //m_bExpandUseFixed = FALSE; m_bExpandUseFixed = TRUE; m_bRejectEditAttempts = TRUE; m_bRejectEditChanges = FALSE; m_bRow2Col2Hidden = FALSE; // Set this->SetVirtualMode(m_bVirtualMode); this->SetEditable(m_bEditable); this->SetAutoSizeStyle(); } // Use: Update Grid[0xFF x 0xFF] Interface // FROM: startAddr TO: startAddr + count // with Memory Values[0xFF x 0xFF] // FROM: startAddr TO: startAddr + count void CGridTable::GridTable_Write_UpdateRange(BYTE * v_ByteData, BYTE startAddr, WORD count) { // Safe check if (startAddr + count > 256) { // out of range return; } else { // define table start cell unsigned char stRow = startAddr / 0x10; // start Row unsigned char stCol = startAddr - stRow * 0x10; // start Col // fill in table unsigned char uRow = stRow + 1; // +1 is for Fixed Cell unsigned char uCol = stCol + 1; // +1 is for Fixed Cell unsigned int k = 0; bool act = 1; do { // forming Cell Text CString cellText; cellText.Format(_T("%02X"), v_ByteData[startAddr + k]); this->SetItemText(uRow, uCol, cellText); // prepare next cell coord /NOTE: useless at last cycle uCol++; if (uCol > 0x0F + 1) // +1 is for Fixed Cell { uCol = 0 + 1; // +1 is for Fixed Cell uRow++; // can't exceed 0x0F val cause of #SafeCheck } k++; } while (k < count); this->Invalidate(); } //SafeCheck } void CGridTable::GridTable_Write(BYTE * v_ByteData, BYTE startAddr, WORD count) { // Safe check if (startAddr + count > 256) { // out of range return; } else { // define table start cell unsigned char stRow = startAddr / 0x10; // start Row unsigned char stCol = startAddr - stRow * 0x10; // start Col // fill in table unsigned char uRow = stRow + 1; // +1 is for Fixed Cell unsigned char uCol = stCol + 1; // +1 is for Fixed Cell unsigned int k = 0; bool act = 1; do { // forming Cell Text CString cellText; cellText.Format(_T("%02X"), v_ByteData[k]); this->SetItemText(uRow, uCol, cellText); // prepare next cell coord /NOTE: useless at last cycle uCol++; if (uCol > 0x0F + 1) // +1 is for Fixed Cell { uCol = 0 + 1; // +1 is for Fixed Cell uRow++; // can't exceed 0x0F val cause of #SafeCheck } k++; } while (k < count); this->Invalidate(); } //SafeCheck } void CGridTable::GridTable_Write_Byte(BYTE * v_ByteData, BYTE startAddr, WORD count) { // Safe check if (startAddr + count > 256) { // out of range return; } else { // define table start cell unsigned char stRow = startAddr / 0x10; // start Row unsigned char stCol = startAddr - stRow * 0x10; // start Col // fill in table unsigned char uRow = stRow + 1; // +1 is for Fixed Cell unsigned char uCol = stCol + 1; // +1 is for Fixed Cell unsigned int k = 0; bool act = 1; do { // forming Cell Text CString cellText; cellText.Format(_T("%c"), v_ByteData[startAddr + k]); this->SetItemText(uRow, uCol, cellText); // prepare next cell coord /NOTE: useless at last cycle uCol++; if (uCol > 0x0F + 1) // +1 is for Fixed Cell { uCol = 0 + 1; // +1 is for Fixed Cell uRow++; // can't exceed 0x0F val cause of #SafeCheck } k++; } while (k < count); this->Invalidate(); } //SafeCheck } // Use: Update Memory Values // FROM: startAddr TO: startAddr + count // with Grid Values // FROM: startAddr TO: startAddr + count void CGridTable::GridTable_Read_UpdateRange(BYTE * v_ByteData, BYTE startAddr, WORD count) { // Safe check if (startAddr + count > 256) { // out of range return; } else { // define table start cell unsigned char stRow = startAddr / 0x10; // start Row unsigned char stCol = startAddr - stRow * 0x10; // start Col // get from Table unsigned char uRow = stRow + 1; // +1 is for Fixed Cell unsigned char uCol = stCol + 1; // +1 is for Fixed Cell unsigned int k = 0; bool act = 1; do { // extract Cell Text CString cellText = this->GetItemText(uRow, uCol); v_ByteData[startAddr + k] = (BYTE)_tcstoul(cellText, NULL, 16); // prepare next cell coord /NOTE: useless at last cycle uCol++; if (uCol > 0x0F + 1) // +1 is for Fixed Cell { uCol = 0 + 1; // +1 is for Fixed Cell uRow++; // can't exceed 0x0F val cause of #SafeCheck } k++; } while (k < count); } } // Use: simple Read Grid OP // FROM: startAddr TO: startAddr + count // in Memory // FROM: 0 TO: count void CGridTable::GridTable_Read(BYTE * v_ByteData, BYTE startAddr, WORD count) { // Safe check if (startAddr + count > 256) { // out of range return; } else { // define table start cell unsigned char stRow = startAddr / 0x10; // start Row unsigned char stCol = startAddr - stRow * 0x10; // start Col // get from Table unsigned char uRow = stRow + 1; // +1 is for Fixed Cell unsigned char uCol = stCol + 1; // +1 is for Fixed Cell unsigned int k = 0; bool act = 1; do { // extract Cell Text CString cellText = this->GetItemText(uRow, uCol); v_ByteData[k] = (BYTE)_tcstoul(cellText, NULL, 16); // prepare next cell coord /NOTE: useless at last cycle uCol++; if (uCol > 0x0F + 1) // +1 is for Fixed Cell { uCol = 0 + 1; // +1 is for Fixed Cell uRow++; // can't exceed 0x0F val cause of #SafeCheck } k++; } while (k < count); } } // ------------------------------------------------------------------- // Supporting procedures // ------------------------------------------------------------------- // Check PROCs int CGridTable::CheckValidHex(int iRow, int iCol) { // error symbol at first bool act = 1; CString cellText = this->GetItemText(iRow, iCol); // check valid Length if (cellText.GetLength() == 2) { // check valid Symbols CString hexString = cellText.SpanIncluding(_T("0123456789abcdefABCDEF")); if (hexString.Compare(cellText) == 0) { act = 0; // Change to upper case this->SetItemText(iRow, iCol, cellText.MakeUpper()); } } return act; } int CGridTable::CheckValidHex2(int iRow, int iCol) { // error symbol at first bool act = 1; CString cellText = this->GetItemText(iRow, iCol); // check valid Length if (cellText.GetLength() == 4) { // check valid Symbols CString hexString = cellText.SpanIncluding(_T("0123456789abcdefABCDEF")); if (hexString.Compare(cellText) == 0) { act = 0; // Change to upper case this->SetItemText(iRow, iCol, cellText.MakeUpper()); } } return act; } int CGridTable::CheckValidASCII(int iRow, int iCol) { bool act = 0; CString cellText = this->GetItemText(iRow, iCol); // check valid Length if (cellText.GetLength() != 1) { // error symbol act = 1; } return act; } int CGridTable::ByteToBitStr(BYTE uByteValue, unsigned char * v_BitStrValue) { BYTE byte_var = 128; // 2^(8-1) for (int k = 0; k < 8; k++) { if (uByteValue >= byte_var) { v_BitStrValue[k] = '1'; uByteValue -= byte_var; } else { v_BitStrValue[k] = '0'; } byte_var /= 2; } return 0; } int CGridTable::BitStrToByte(BYTE * uByteValue, unsigned char * v_BitStrValue) { BYTE byte_var = 1; BYTE byteValue_loc = 0; for (int k = 0; k < 8; k++) { if (v_BitStrValue[7 - k] == '0') { // } else { if (v_BitStrValue[7 - k] == '1') { byteValue_loc += byte_var; } else { // bad parameter value return 2; } } byte_var *= 2; } *uByteValue = byteValue_loc; return 0; } int CGridTable::CheckValidChar(int iRow, int iCol) { // set error flag at first bool act = 1; CString cellText = this->GetItemText(iRow, iCol); // check valid Length if (cellText.GetLength() == 1) { act = 0; } return act; } int CGridTable::CheckValidBitStr8(int iRow, int iCol) { // set error flag at first bool act = 1; CString cellText = this->GetItemText(iRow, iCol); // check valid Length if (cellText.GetLength() == 8) { // valid Length // check valid Symbol act = 0; for (unsigned char k = 0; k < 8; k++) { if (!((cellText[k] == '0') || (cellText[k] == '1'))) { // invalid symbol act = 1; break; } } } return act; } int CGridTable::CheckValidBitStr16(int iRow, int iCol) { // set error flag at first bool act = 1; CString cellText = this->GetItemText(iRow, iCol); // check valid Length if (cellText.GetLength() == 16) { // valid Length // check valid Symbol act = 0; for (unsigned char k = 0; k < 16; k++) { if (!((cellText[k] == '0') || (cellText[k] == '1'))) { // invalid symbol act = 1; break; } } } return act; } /* // Get GPIO vals from ini int CPinConfigurationPage::GetGPIOini(BYTE *gpio_val) { FILE *fs; char* file_name = "cpiodirection.cfg"; errno_t err; if ((err = fopen_s(&fs, file_name, "r")) != 0) { // "can't read file" return 1; } else { char load_str[9] = "00000000"; fgets(load_str, 9, fs); fclose(fs); int file_val = 0; int k = 1; for (int i = 0; i < 8; i++) { if (load_str[7 - i] == '0') { // } else { if (load_str[7 - i] == '1') { file_val += k; } else { //bad file return 2; } } k = k * 2; } if (file_val < 256) { *gpio_val = (BYTE)file_val; } else { return 3; } } return 0; } */
[ "Korchagin@KORCHAGIN_PC" ]
Korchagin@KORCHAGIN_PC
d9ee2b90c7772d3ef76ec17f7859a2017c66c17c
888c421f1adf45b49474aeb46e508bb67f7f36f7
/CGameMap.h
25be192785555eeab297ef4f771bf9adaa50bbec
[]
no_license
lvzl20/OpencvTest
e3f00546f3ae6de56d9652407a84aa81332952a5
1a5650ad0e6c6b37acf4aead7dcdcaf3d8ac64d8
refs/heads/master
2023-04-28T11:04:05.978590
2021-05-20T15:22:28
2021-05-20T15:22:28
369,241,749
0
0
null
null
null
null
GB18030
C++
false
false
706
h
#pragma once #include<opencv2/opencv.hpp> //using namespace cv; #define MAP_SIZE 16 class CGameMap { public: CGameMap(); ~CGameMap(); void Init(); void ReadMaptext();//读取地图数据 void CreateMap();//创建地图 void Release(); void ClearMap(int x, int y);//清除该位置的物品 cv::Mat GetBackShowImg(); int level;//代表第几个地图 cv::Mat m_ObstacleImg[3];//定义三种障碍物 cv::Mat m_ObstacleImg2[6];//第二个地图的障碍物 cv::Mat m_Background;//背景图像 cv::Mat m_StaticBack;//静态背景图像 cv::Mat m_ShowImg;//显示的图像 bool Collision(int x, int y);//判断该点是否发生碰撞 int m_Map[MAP_SIZE][MAP_SIZE];//地图物品位置 };
75e8b54bf007d28965a20dba29628b5325b9360a
6e3b592de89cb3e7d594993c784e7059bdb2a9ae
/Source/AllProjects/Drivers/ElkM1V2/Client/ElkM1V2C_Window.cpp
56b320c1651efcbbc20f64afeab0cfd2ce50dd17
[ "MIT" ]
permissive
jjzhang166/CQC
9aae1b5ffeddde2c87fafc3bb4bd6e3c7a98a1c2
8933efb5d51b3c0cb43afe1220cdc86187389f93
refs/heads/master
2023-08-28T04:13:32.013199
2021-04-16T14:41:21
2021-04-16T14:41:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,587
cpp
// // FILE NAME: ElkM1V2C_Window.cpp // // AUTHOR: Dean Roddey // // CREATED: 02/26/2005 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the main window of the Elk M1 client driver // // // CAVEATS/GOTCHAS: // // LOG: // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "ElkM1V2C_.hpp" // --------------------------------------------------------------------------- // Magic macro // --------------------------------------------------------------------------- RTTIDecls(TElkM1V2CWnd,TCQCDriverClient) // --------------------------------------------------------------------------- // CLASS: TElkM1V2CWnd // PREFIX: wnd // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TElkM1V2CWnd: Public, static methods // --------------------------------------------------------------------------- // // This provides common checking for the id/name parts that apply to all of the // info classes. This way they don't all have to replicate this code. We display // an error to the user. We return the status so that the dialog can put the focus // on the offending item if an error. // tElkM1V2C::EBaseValRes TElkM1V2CWnd::eCheckBaseVals(const TWindow& wndOwner , tElkM1V2C::TItemList& colList , const TString& strName , const TString& strElkId , const tCIDLib::TCard4 c4ListInd , const tElkM1V2C::EItemTypes eType , tCIDLib::TCard4& c4ElkId) { if (strName.bIsEmpty()) { TErrBox msgbErr(facElkM1V2C().strMsg(kElkM1V2CErrs::errcCfg_NoName)); msgbErr.ShowIt(wndOwner); return tElkM1V2C::EBaseValRes::Name; } // Make sure the name is valid for a field if (!facCQCKit().bIsValidFldName(strName, kCIDLib::True)) { TErrBox msgbErr(facElkM1V2C().strMsg(kElkM1V2CErrs::errcEdit_BadFldName)); msgbErr.ShowIt(wndOwner); return tElkM1V2C::EBaseValRes::Name; } // We have to have an id if (strElkId.bIsEmpty() || !strElkId.bToCard4(c4ElkId)) { TErrBox msgbErr(facElkM1V2C().strMsg(kElkM1V2CErrs::errcEdit_NoId)); msgbErr.ShowIt(wndOwner); return tElkM1V2C::EBaseValRes::Id; } // Make sure it's legal for the type if (c4ElkId > kElkM1V2C::ac4MaxIds[eType]) { TErrBox msgbErr ( facElkM1V2C().strMsg ( kElkM1V2CErrs::errcEdit_IdRange , TString(kElkM1V2C::apszTypes[eType]) , TCardinal(kElkM1V2C::ac4MaxIds[eType]) ) ); msgbErr.ShowIt(wndOwner); return tElkM1V2C::EBaseValRes::Id; } // // Make sure it's not a dup name or id, (unless it's the original one). If // this is a new one, the incoming index is max card, so we will check them // all. // const tCIDLib::TCard4 c4Count = colList.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { // If not the same one as we are checking if (c4Index != c4ListInd) { if (colList.pobjAt(c4Index)->m_strName.bCompareI(strName)) { TErrBox msgbErr ( facElkM1V2C().strMsg(kElkM1V2CErrs::errcEdit_DupName, strName) ); msgbErr.ShowIt(wndOwner); return tElkM1V2C::EBaseValRes::Name; } if (colList.pobjAt(c4Index)->m_c4ElkId == c4ElkId) { TErrBox msgbErr ( facElkM1V2C().strMsg(kElkM1V2CErrs::errcEdit_DupId, TCardinal(c4ElkId)) ); msgbErr.ShowIt(wndOwner); return tElkM1V2C::EBaseValRes::Id; } } } return tElkM1V2C::EBaseValRes::OK; } // --------------------------------------------------------------------------- // TElkM1V2CWnd: Constructors and Destructor // --------------------------------------------------------------------------- TElkM1V2CWnd::TElkM1V2CWnd( const TCQCDriverObjCfg& cqcdcThis , const TCQCUserCtx& cuctxToUse) : TCQCDriverClient ( cqcdcThis , L"TElkM1V2CWnd" , tCQCKit::EActLevels::Low , cuctxToUse ) , m_colLists(tCIDLib::EAdoptOpts::Adopt, tElkM1V2C::EItemTypes::Count) , m_colModLists(tCIDLib::EAdoptOpts::Adopt, tElkM1V2C::EItemTypes::Count) , m_pwndAddButton(nullptr) , m_pwndClearButton(nullptr) , m_pwndEditButton(nullptr) , m_pwndItemList(nullptr) , m_pwndSettings(nullptr) , m_pwndTypeList(nullptr) , m_sfmtSettingsL(14, 0, tCIDLib::EHJustify::Right) , m_sfmtSettingsR(0, 2, tCIDLib::EHJustify::Left) { // // Go through the individual lists and allocate each list. THESE MUST be in the // same order as the EItemTypes enum! // m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxAreas)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxCounters)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxLoads)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxOutputs)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxThermos)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxThermoCpls)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxVolts)); m_colLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxZones)); // Do the same for the mod versions m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxAreas)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxCounters)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxLoads)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxOutputs)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxThermos)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxThermoCpls)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxVolts)); m_colModLists.Add(new tElkM1V2C::TItemList(tCIDLib::EAdoptOpts::Adopt, kElkM1V2C::c4MaxZones)); } TElkM1V2CWnd::~TElkM1V2CWnd() { } // --------------------------------------------------------------------------- // TElkM1V2CWnd: Public, inherited methods // --------------------------------------------------------------------------- // See if we have any changes tCIDLib::TBoolean TElkM1V2CWnd::bChanges() const { // // The first quick check is just if any of the lists are of different sizes. // If so, has to be changes. // tElkM1V2C::EItemTypes eType = tElkM1V2C::EItemTypes::Min; while (eType <= tElkM1V2C::EItemTypes::Max) { if (m_colModLists[eType]->c4ElemCount() != m_colLists[eType]->c4ElemCount()) return kCIDLib::True; eType++; } // // Let's compare the individual items them. The item classes provide a poly- // morphic comparison method, so we can do this completely generically. // eType = tElkM1V2C::EItemTypes::Min; while (eType <= tElkM1V2C::EItemTypes::Max) { const tElkM1V2C::TItemList& colOrg = *m_colLists[eType]; const tElkM1V2C::TItemList& colMod = *m_colModLists[eType]; const tCIDLib::TCard4 c4Count = colMod.c4ElemCount(); CIDAssert(c4Count == colOrg.c4ElemCount(), L"Lists should be the same size"); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { if (!colMod[c4Index]->bComp(*colOrg.pobjAt(c4Index))) return kCIDLib::True; } eType++; } return kCIDLib::False; } tCIDLib::TBoolean TElkM1V2CWnd::bSaveChanges(TString& strErrMsg) { try { // Format out the config in the exchange format TTextStringOutStream strmConfig(0x1000UL); TString strFmt; // Put out the version first strmConfig << L"Version=" << kElkM1V2C::c4ConfigVer << kCIDLib::NewLn; // Then all of the individual blocks tCIDLib::ForEachE<tElkM1V2C::EItemTypes> ( [this, &strmConfig](const tElkM1V2C::EItemTypes eType) { const tElkM1V2C::TItemList& colMod = *m_colModLists[eType]; // Output the block start strmConfig << kElkM1V2C::apszBlocks[eType] << kCIDLib::chEquals << kCIDLib::NewLn; const tCIDLib::TCard4 c4Count = colMod.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { colMod[c4Index]->FormatCfg(strmConfig); strmConfig << kCIDLib::NewLn; } // Output the end block line strmConfig << L"End" << kElkM1V2C::apszBlocks[eType] << kCIDLib::NewLn; } ); // Send the changes, flush the stream first to get it all out strmConfig.Flush(); orbcServer()->c4SendCmd(strMoniker(), L"TakeChanges", strmConfig.strData(), sectUser()); // Copy all of the mod lists to the regular lists to clear changes StoreMods(); } catch(TError& errToCatch) { if (facElkM1V2C().bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } strErrMsg = facElkM1V2C().strMsg(kElkM1V2CErrs::errcCfg_CantSendCfg); return kCIDLib::False; } return kCIDLib::True; } // --------------------------------------------------------------------------- // TElkM1V2CWnd: Protected, inherited methods // --------------------------------------------------------------------------- tCIDLib::TBoolean TElkM1V2CWnd::bCreated() { TParent::bCreated(); // Load the dialog resource that defines our content and create our content TDlgDesc dlgdChildren; facElkM1V2C().bCreateDlgDesc(kElkM1V2C::ridIntf_Main, dlgdChildren); tCIDCtrls::TWndId widInitFocus; CreateDlgItems(dlgdChildren, widInitFocus); // Do an initial auto-size to get them in sync with our initial size AutoAdjustChildren(dlgdChildren.areaPos(), areaClient()); // Get typed pointers to the widgets we want to interact with a lot CastChildWnd(*this, kElkM1V2C::ridIntf_Main_Add, m_pwndAddButton); CastChildWnd(*this, kElkM1V2C::ridIntf_Main_ClearChanges, m_pwndClearButton); CastChildWnd(*this, kElkM1V2C::ridIntf_Main_Delete, m_pwndDelButton); CastChildWnd(*this, kElkM1V2C::ridIntf_Main_Edit, m_pwndEditButton); CastChildWnd(*this, kElkM1V2C::ridIntf_Main_ItemList, m_pwndItemList); CastChildWnd(*this, kElkM1V2C::ridIntf_Main_Settings, m_pwndSettings); CastChildWnd(*this, kElkM1V2C::ridIntf_Main_TypeList, m_pwndTypeList); // Set up the settings window with a non-proportioal font m_pwndSettings->SetFont(TGUIFacility::gfontDefFixed()); // Register event handlers m_pwndAddButton->pnothRegisterHandler(this, &TElkM1V2CWnd::eClickHandler); m_pwndClearButton->pnothRegisterHandler(this, &TElkM1V2CWnd::eClickHandler); m_pwndDelButton->pnothRegisterHandler(this, &TElkM1V2CWnd::eClickHandler); m_pwndEditButton->pnothRegisterHandler(this, &TElkM1V2CWnd::eClickHandler); m_pwndItemList->pnothRegisterHandler(this, &TElkM1V2CWnd::eLBHandler); m_pwndTypeList->pnothRegisterHandler(this, &TElkM1V2CWnd::eLBHandler); // Set the column titles on the lists tCIDLib::TStrList colVals(2); // The type list has one column colVals.objAdd(facElkM1V2C().strMsg(kElkM1V2CMsgs::midIntf_Main_TypesPref)); m_pwndTypeList->SetColumns(colVals); // The item list has two columns colVals[0] = L"Elk Id"; colVals.objAdd(facElkM1V2C().strMsg(kElkM1V2CMsgs::midIntf_Main_TypesPref)); m_pwndItemList->SetColumns(colVals); // Auto-size the first column to fit the header. The other is auto-sized in the res file m_pwndItemList->AutoSizeCol(0, kCIDLib::True); // // Load up the list of item types, which will kick off the other loading. It only // has one column, so we have to remove the other value we added above. // colVals.RemoveAt(1); tElkM1V2C::EItemTypes eTypes = tElkM1V2C::EItemTypes::Min; while (eTypes <= tElkM1V2C::EItemTypes::Max) { colVals[0] = kElkM1V2C::apszTypes[eTypes]; m_pwndTypeList->c4AddItem(colVals, tCIDLib::c4EnumOrd(eTypes)); eTypes++; } return kCIDLib::True; } tCIDLib::TBoolean TElkM1V2CWnd::bGetConnectData(tCQCKit::TCQCSrvProxy& orbcTarget) { // Do any initial load of any config try { LoadConfig(orbcTarget); } catch(...) { return kCIDLib::False; } return kCIDLib::True; } tCIDLib::TBoolean TElkM1V2CWnd::bDoPoll(tCQCKit::TCQCSrvProxy& orbcTarget) { // We just display config data, so nothing to do here return kCIDLib::True; } tCIDLib::TVoid TElkM1V2CWnd::Connected() { // Get initial data displayed by forcing a reselect of the 0th item type m_pwndTypeList->SelectByIndex(0, kCIDLib::True); } tCIDLib::TVoid TElkM1V2CWnd::DoCleanup() { // Nothing for us to do currently } tCIDLib::TVoid TElkM1V2CWnd::LostConnection() { // Nothing for us to do currently } tCIDLib::TVoid TElkM1V2CWnd::UpdateDisplayData() { // We don't display any live data, just config } // --------------------------------------------------------------------------- // TElkM1V2CWnd: Private, non-virtual methods // --------------------------------------------------------------------------- // // Add a new item of the currently selected type // tCIDLib::TVoid TElkM1V2CWnd::AddNew() { // Get the type index and convert it to an item type tCIDLib::TCard4 c4TypeInd = m_pwndTypeList->c4CurItem(); if (c4TypeInd == kCIDLib::c4MaxCard) return; const tElkM1V2C::EItemTypes eCurType = tElkM1V2C::EItemTypes(c4TypeInd); // Get the selected item of that type and invoke the edit dialog tCIDLib::TBoolean bChanges = kCIDLib::False; tCIDLib::TCard4 c4ElkId = kCIDLib::c4MaxCard; tElkM1V2C::TItemList& colList = *m_colModLists[eCurType]; TItemInfo* piiNew = 0; switch(eCurType) { case tElkM1V2C::EItemTypes::Area : case tElkM1V2C::EItemTypes::Output : { // // These all use a generic dialog. But in this case we have to // allocate a temp to use. Put a janitor on it until we get it // stored away. // TItemInfo* piiEdit; if (eCurType == tElkM1V2C::EItemTypes::Area) piiEdit = new TAreaInfo; else piiEdit = new TOutputInfo; TJanitor<TItemInfo> janEdit(piiEdit); // Load the appropriate instruction text tCIDLib::TMsgId midInstruct; if (eCurType == tElkM1V2C::EItemTypes::Area) midInstruct = kElkM1V2CMsgs::midDlg_EdArea_Instruct; else midInstruct = kElkM1V2CMsgs::midDlg_EdOutput_Instruct; // The changes are stored by the dialog if committed TEdM1GenDlg dlgEd; bChanges = dlgEd.bRunDlg ( *this , kCIDLib::c4MaxCard , *m_colModLists[eCurType] , *piiEdit , facElkM1V2C().strMsg(midInstruct) , eCurType ); // If committed, give the pointer over to be handled below if (bChanges) piiNew = janEdit.pobjOrphan(); break; } case tElkM1V2C::EItemTypes::Counter : case tElkM1V2C::EItemTypes::Thermo : case tElkM1V2C::EItemTypes::ThermoCpl : { // // These all share the same dialog. They all are name, id, and low/high // limits. // TLimInfo* piiEdit; if (eCurType == tElkM1V2C::EItemTypes::Counter) piiEdit = new TCounterInfo; else if (eCurType == tElkM1V2C::EItemTypes::Thermo) piiEdit = new TThermoInfo; else piiEdit = new TThermoCplInfo; TJanitor<TItemInfo> janEdit(piiEdit); // Load the appropriate instruction text tCIDLib::TMsgId midInstruct; if (eCurType == tElkM1V2C::EItemTypes::Counter) midInstruct = kElkM1V2CMsgs::midDlg_EdCnt_Instruct; else if (eCurType == tElkM1V2C::EItemTypes::Thermo) midInstruct = kElkM1V2CMsgs::midDlg_EdThermo_Instruct; else midInstruct = kElkM1V2CMsgs::midDlg_EdThermoCpl_Instruct; // The changes are stored by the dialog if committed TEdM1GenLimDlg dlgEd; bChanges = dlgEd.bRunDlg ( *this , kCIDLib::c4MaxCard , *m_colModLists[eCurType] , *piiEdit , facElkM1V2C().strMsg(midInstruct) , eCurType ); // If committed, give the pointer over to be handled below if (bChanges) piiNew = janEdit.pobjOrphan(); break; } case tElkM1V2C::EItemTypes::Load : { TLoadInfo iiEdit; TEdM1LoadDlg dlgEd; bChanges = dlgEd.bRunDlg(*this, kCIDLib::c4MaxCard, colList, iiEdit); if (bChanges) piiNew = new TLoadInfo(iiEdit); break; } case tElkM1V2C::EItemTypes::Volt : { TVoltInfo iiEdit; TEdM1VoltDlg dlgEd; bChanges = dlgEd.bRunDlg(*this, kCIDLib::c4MaxCard, colList, iiEdit); if (bChanges) piiNew = new TVoltInfo(iiEdit); break; } case tElkM1V2C::EItemTypes::Zone : { TZoneInfo iiEdit; TEdM1ZoneDlg dlgEd; bChanges = dlgEd.bRunDlg(*this, kCIDLib::c4MaxCard, colList, iiEdit); if (bChanges) piiNew = new TZoneInfo(iiEdit); break; } default : return; }; // If changes, then add this item if (bChanges) { // // Find the insert point, in Elk id order. We need to insert it into the // mod list and the list box. // const tCIDLib::TCard4 c4Count = colList.c4ElemCount(); tCIDLib::TCard4 c4Index = 0; for (; c4Index < c4Count; c4Index++) { if (colList[c4Index]->m_c4ElkId > piiNew->m_c4ElkId) break; } if (c4Index == c4Count) colList.Add(piiNew); else colList.InsertAt(piiNew, c4Index); // Insert the list item at the same spot TString strFmt; strFmt.SetFormatted(piiNew->m_c4ElkId); tCIDLib::TStrList colCols(2); colCols.objAdd(strFmt); colCols.objAdd(piiNew->m_strName); m_pwndItemList->c4AddItem(colCols, piiNew->m_c4ElkId, c4Index); } } // // Checks the source config data stream for an xxx= type starting line for a block. // End of stream is never expected, so we just let it throw if it happens. // tCIDLib::TVoid TElkM1V2CWnd::CheckStart( TTextInStream& strmSrc , const TString& strExp) { GetNextLine(strmSrc, m_strTmp); // If not what we are expecting, then throw if (!m_strTmp.bCompareI(strExp)) { facElkM1V2C().ThrowErr ( CID_FILE , CID_LINE , kElkM1V2CErrs::errcCfg_ExpBlock , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , strExp , m_strTmp , TCardinal(m_c4LineNum) ); } } // We remove all of the items from all of the lists tCIDLib::TVoid TElkM1V2CWnd::ClearAllData() { tElkM1V2C::EItemTypes eType = tElkM1V2C::EItemTypes::Min; while (eType <= tElkM1V2C::EItemTypes::Max) { m_colLists[eType]->RemoveAll(); m_colModLists[eType]->RemoveAll(); eType++; } // Can't be any changes now m_pwndItemList->TakeFocus(); } // // Copy over the contents of the original lists back to the mod lists, which // undoes any changes since the last save (or initial load.) // tCIDLib::TVoid TElkM1V2CWnd::ClearMods() { tElkM1V2C::EItemTypes eType = tElkM1V2C::EItemTypes::Min; while (eType <= tElkM1V2C::EItemTypes::Max) { // Get the right lists for this type tElkM1V2C::TItemList& colTar = *m_colModLists[eType]; tElkM1V2C::TItemList& colSrc = *m_colLists[eType]; // Clear out the target list colTar.RemoveAll(); // And now dup the mod list const tCIDLib::TCard4 c4Count = colSrc.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { colTar.Add ( static_cast<TItemInfo*>(colSrc[c4Index]->pobjDuplicate()) ); } eType++; } // Force reload the data m_pwndTypeList->SelectByIndex(0, kCIDLib::True); } // // Called when the user selects the Delete button. IF there's a selected item, we // remove it. // tCIDLib::TVoid TElkM1V2CWnd::DeleteCurrent() { // Get the type index and convert it to an item type tCIDLib::TCard4 c4TypeInd = m_pwndTypeList->c4CurItem(); if (c4TypeInd == kCIDLib::c4MaxCard) return; // Something has to be selected in the item list tCIDLib::TCard4 c4ItemInd = m_pwndItemList->c4CurItem(); if (c4ItemInd == kCIDLib::c4MaxCard) return; const tElkM1V2C::EItemTypes eCurType = tElkM1V2C::EItemTypes(c4TypeInd); tElkM1V2C::TItemList& colList = *m_colModLists[eCurType]; colList.RemoveAt(c4ItemInd); m_pwndItemList->RemoveAt(c4ItemInd); } // // This is called on a button click. // tCIDCtrls::EEvResponses TElkM1V2CWnd::eClickHandler(TButtClickInfo& wnotEvent) { // If we are not connected, then do nothing if (eConnState() != tCQCGKit::EConnStates::Connected) return tCIDCtrls::EEvResponses::Handled; try { TWndPtrJanitor janPtr(tCIDCtrls::ESysPtrs::Wait); // According to the button id, we do the right thing const tCIDCtrls::TWndId widSrc = wnotEvent.widSource(); switch(widSrc) { case kElkM1V2C::ridIntf_Main_Add : { // Add a new item of the current type AddNew(); break; } case kElkM1V2C::ridIntf_Main_ClearChanges : { // Clear any local modifications and reload the lists ClearMods(); m_pwndTypeList->SelectByIndex(0, kCIDLib::True); break; } case kElkM1V2C::ridIntf_Main_Delete : { DeleteCurrent(); break; } case kElkM1V2C::ridIntf_Main_Edit : { // Edit the currently selected item, if any EditCurrent(); break; } }; } catch(TError& errToCatch) { if (facElkM1V2C().bShouldLog(errToCatch)) { errToCatch.AddStackLevel(CID_FILE, CID_LINE); TModule::LogEventObj(errToCatch); } TExceptDlg dlgbFail ( *this , strWndText() , facElkM1V2C().strMsg(kElkM1V2CMsgs::midStatus_RemOpFailed) , errToCatch ); } return tCIDCtrls::EEvResponses::Handled; } tCIDCtrls::EEvResponses TElkM1V2CWnd::eLBHandler(TListChangeInfo& wnotEvent) { const tCIDCtrls::TWndId widSrc = wnotEvent.widSource(); // On double clicks, we add/remove/change the item if (wnotEvent.eEvent() == tCIDCtrls::EListEvents::Cleared) { if (widSrc == kElkM1V2C::ridIntf_Main_ItemList) { m_pwndSettings->ClearText(); } else if (widSrc == kElkM1V2C::ridIntf_Main_TypeList) { // Clear out the item list since there's nothing now to display here m_pwndItemList->RemoveAll(); } } else if (wnotEvent.eEvent() == tCIDCtrls::EListEvents::SelChanged) { if (widSrc == kElkM1V2C::ridIntf_Main_ItemList) { // Get the currently selected type in the type list const tElkM1V2C::EItemTypes eType ( tElkM1V2C::EItemTypes(m_pwndTypeList->c4CurItem()) ); // Use that to get the item for the selected item within that type const TItemInfo& iiCur = *(*m_colModLists[eType])[wnotEvent.c4Index()]; // Update the settings window with the current item's settings TTextStringOutStream strmTar(8192UL); iiCur.FormatSettings(strmTar, m_sfmtSettingsL, m_sfmtSettingsR); strmTar.Flush(); m_pwndSettings->strWndText(strmTar.strData()); } else if (widSrc == kElkM1V2C::ridIntf_Main_TypeList) { // // Update the item list with the items for the newly selected // type. The indices of the types list box map directly to the // types enum. // const tElkM1V2C::EItemTypes eType(tElkM1V2C::EItemTypes(wnotEvent.c4Index())); LoadItemList(eType); // Update the title of the name column to indicate the new type m_pwndItemList->SetColTitle(1, kElkM1V2C::apszTypes[eType]); } } else if (wnotEvent.eEvent() == tCIDCtrls::EListEvents::Invoked) { } return tCIDCtrls::EEvResponses::Handled; } // // This will look at what tpe of thing is currently selected, and will invoke // the correct dialog box to let the user edit it. // tCIDLib::TVoid TElkM1V2CWnd::EditCurrent() { // Get the type index and convert it to an item type tCIDLib::TCard4 c4TypeInd = m_pwndTypeList->c4CurItem(); if (c4TypeInd == kCIDLib::c4MaxCard) return; const tElkM1V2C::EItemTypes eCurType = tElkM1V2C::EItemTypes(c4TypeInd); // If there's nothing selected in the item list, then do nothing tCIDLib::TCard4 c4ItemInd = m_pwndItemList->c4CurItem(); if (c4ItemInd == kCIDLib::c4MaxCard) return; // Get the selected item of that type and invoke the edit dialog tCIDLib::TBoolean bChanges = kCIDLib::False; switch(eCurType) { case tElkM1V2C::EItemTypes::Area : case tElkM1V2C::EItemTypes::Output : { // These all use a generic dialog TItemInfo* piiEdit = m_colModLists[eCurType]->pobjAt(c4ItemInd); // Load the appropriate instruction text tCIDLib::TMsgId midInstruct; if (eCurType == tElkM1V2C::EItemTypes::Area) midInstruct = kElkM1V2CMsgs::midDlg_EdArea_Instruct; else midInstruct = kElkM1V2CMsgs::midDlg_EdOutput_Instruct; // The changes are stored by the dialog if committed TEdM1GenDlg dlgEd; bChanges = dlgEd.bRunDlg ( *this , c4ItemInd , *m_colModLists[eCurType] , *piiEdit , facElkM1V2C().strMsg(midInstruct) , eCurType ); break; } case tElkM1V2C::EItemTypes::Counter : case tElkM1V2C::EItemTypes::Thermo : case tElkM1V2C::EItemTypes::ThermoCpl : { // These all use a generic dialog TLimInfo* piiEdit = static_cast<TLimInfo*> ( m_colModLists[eCurType]->pobjAt(c4ItemInd) ); // Load the appropriate instruction text tCIDLib::TMsgId midInstruct; if (eCurType == tElkM1V2C::EItemTypes::Counter) midInstruct = kElkM1V2CMsgs::midDlg_EdCnt_Instruct; else if (eCurType == tElkM1V2C::EItemTypes::Thermo) midInstruct = kElkM1V2CMsgs::midDlg_EdThermo_Instruct; else midInstruct = kElkM1V2CMsgs::midDlg_EdThermoCpl_Instruct; TEdM1GenLimDlg dlgEd; bChanges = dlgEd.bRunDlg ( *this , c4ItemInd , *m_colModLists[eCurType] , *piiEdit , facElkM1V2C().strMsg(midInstruct) , eCurType ); break; } case tElkM1V2C::EItemTypes::Load : { TLoadInfo iiEdit = *static_cast<TLoadInfo*> ( m_colModLists[eCurType]->pobjAt(c4ItemInd) ); TEdM1LoadDlg dlgEd; bChanges = dlgEd.bRunDlg(*this, c4ItemInd, *m_colModLists[eCurType], iiEdit); // Store the changes back if made if (bChanges) *static_cast<TLoadInfo*>(m_colModLists[eCurType]->pobjAt(c4ItemInd)) = iiEdit; break; } case tElkM1V2C::EItemTypes::Volt : { TVoltInfo iiEdit = *static_cast<TVoltInfo*> ( m_colModLists[eCurType]->pobjAt(c4ItemInd) ); TEdM1VoltDlg dlgEd; bChanges = dlgEd.bRunDlg(*this, c4ItemInd, *m_colModLists[eCurType], iiEdit); // Store the changes back if made if (bChanges) *static_cast<TVoltInfo*>(m_colModLists[eCurType]->pobjAt(c4ItemInd)) = iiEdit; break; } case tElkM1V2C::EItemTypes::Zone : { TZoneInfo iiEdit = *static_cast<TZoneInfo*> ( m_colModLists[eCurType]->pobjAt(c4ItemInd) ); TEdM1ZoneDlg dlgEd; bChanges = dlgEd.bRunDlg(*this, c4ItemInd, *m_colModLists[eCurType], iiEdit); // Store the changes back if made if (bChanges) *static_cast<TZoneInfo*>(m_colModLists[eCurType]->pobjAt(c4ItemInd)) = iiEdit; break; } default : return; }; // If changes, then update this item if (bChanges) { TItemInfo* piiCur = m_colModLists[eCurType]->pobjAt(c4ItemInd); // Update the item list entry tCIDLib::TStrList colVals(2); TString strFmt; strFmt.SetFormatted(piiCur->m_c4ElkId); colVals.objAdd(strFmt); colVals.objAdd(piiCur->m_strName); m_pwndItemList->UpdateRowAt(colVals, c4ItemInd, piiCur->m_c4ElkId); // And force a reselect so that the currently selected item's info is udpated m_pwndItemList->SelectByIndex(c4ItemInd, kCIDLib::True); } } // // Get the next non-empty, non-comment line from the source stream, from which // we are streaming in config data. // tCIDLib::TVoid TElkM1V2CWnd::GetNextLine( TTextInStream& strmSrc , TString& strToFill) { while (kCIDLib::True) { strmSrc >> strToFill; strToFill.StripWhitespace(); m_c4LineNum++; // If empty or a comment, try again if (strToFill.bIsEmpty() || (strToFill[0] == kCIDLib::chSemiColon)) continue; // Break out break; } } // // Asks the server side driver for it's current configuration. Our server // side driver is a CML driver, so we use the text value query to get it as // as formatted string. The more common config set/query methods use binary // flattened C++ data, and we want to avoid having to try to understand the // format of CML flattened data. // tCIDLib::TVoid TElkM1V2CWnd::LoadConfig(tCQCKit::TCQCSrvProxy& orbcSrv) { try { // // Ask the driver for the config data. It takes a 'command id' // but we only use this method for one thing, so we just pass // L"Driver". It's ignored on the other side. // TString strConfig(0x10000UL); orbcSrv->bQueryTextVal(strMoniker(), L"Driver", L"Config", strConfig); // Make an input stream over the data and parse it in TTextStringInStream strmIn(&strConfig); m_c4LineNum = 1; // Parse the version line GetNextLine(strmIn, m_strTmp); if (m_strTmp.bStartsWith(L"Version=")) { m_strTmp.Cut(0, 8); const tCIDLib::TCard4 c4Version = m_strTmp.c4Val(tCIDLib::ERadices::Dec); if (!c4Version || (c4Version > kElkM1V2C::c4ConfigVer)) { } } // // Now we have to read in all of the configured items // { TAreaInfo iiArea; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Area, L"Areas", iiArea); } { TCounterInfo iiCnt; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Counter, L"Counters", iiCnt); } { TLoadInfo iiLoad; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Load, L"Loads", iiLoad); } { TOutputInfo iiOutput; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Output, L"Outputs", iiOutput); } { TThermoInfo iiThermo; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Thermo, L"Thermos", iiThermo); } { TThermoCplInfo iiTCpl; ParseBlock(strmIn, tElkM1V2C::EItemTypes::ThermoCpl, L"ThermoCpls", iiTCpl); } { TVoltInfo iiVolt; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Volt, L"Volts", iiVolt); } { TZoneInfo iiZone; ParseBlock(strmIn, tElkM1V2C::EItemTypes::Zone, L"Zones", iiZone); } // Sort all the lists by elk number tElkM1V2C::EItemTypes eType = tElkM1V2C::EItemTypes::Min; while (eType <= tElkM1V2C::EItemTypes::Max) { m_colModLists[eType]->Sort(TItemInfo::eSortByNum); eType++; } // // OK, it worked, so let's copy the Mod versions tht we loaded into the // regular lists. // StoreMods(); } catch(const TError& errToCatch) { if (facElkM1V2C().bShouldLog(errToCatch)) TModule::LogEventObj(errToCatch); TExceptDlg dlgbFail ( *this , strWndText() , facElkM1V2C().strMsg(kElkM1V2CErrs::errcCfg_CantParseCfg) , errToCatch ); } } // // Load up the item list with all of the configured items of the indicated type. // we'll just put them in in the order that they are in the list. // // We store the elk ids in the row id storage of the list window item, in case we // need to get back to a list window item by id. // tCIDLib::TVoid TElkM1V2CWnd::LoadItemList(const tElkM1V2C::EItemTypes eType) { // Get the correct list tElkM1V2C::TItemList& colTar = *m_colModLists[eType]; // Stop painting while we update, then remove all and load up the new ones TWndPaintJanitor janPaint(this); m_pwndItemList->RemoveAll(); const tCIDLib::TCard4 c4Count = colTar.c4ElemCount(); if (c4Count) { tCIDLib::TStrList colVals(2); TString& strId = colVals.objAdd(TString::strEmpty()); colVals.objAdd(TString::strEmpty()); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TItemInfo& iiCur = *colTar[c4Index]; strId.SetFormatted(iiCur.m_c4ElkId); colVals[1] = iiCur.m_strName; m_pwndItemList->c4AddItem(colVals, iiCur.m_c4ElkId); } m_pwndItemList->SelectByIndex(0, kCIDLib::True); } } // // Generically parse one of the config file blocks and fill in the appropriate // Mod list with the parsed in items of the indicated type. // tCIDLib::TVoid TElkM1V2CWnd::ParseBlock( TTextInStream& strmSrc , const tElkM1V2C::EItemTypes eType , const TString& strType , TItemInfo& iiTmp) { // // Get the target list. We parse into the mod lists, and we'll later copy // these to the other lists. // tElkM1V2C::TItemList& colTar = *m_colModLists[eType]; // Check for the expected start line TString strCheck(strType); strCheck.Append(kCIDLib::chEquals); CheckStart(strmSrc, strCheck); // Build up the end line we'll watch for strCheck = L"End"; strCheck.Append(strType); // And now loop until we hit the end line, processing lines until we do while (kCIDLib::True) { GetNextLine(strmSrc, m_strTmp); // Watch for the end of block indicator if (m_strTmp.bCompareI(strCheck)) break; // Break out the id on the left, tokens on the right tCIDLib::TCard4 c4Id; if (!m_strTmp.bSplit(m_strTmp2, kCIDLib::chEquals) || !m_strTmp.bToCard4(c4Id)) { facElkM1V2C().ThrowErr ( CID_FILE , CID_LINE , kElkM1V2CErrs::errcCfg_LineId , tCIDLib::ESeverities::Failed , tCIDLib::EErrClasses::Format , TCardinal(m_c4LineNum) ); } // Tokenize the right side m_stokTmp.Reset(&m_strTmp2, L","); m_stokTmp.c4BreakApart(m_colTokens); iiTmp.ParseCfg(c4Id, m_colTokens); colTar.Add(static_cast<TItemInfo*>(iiTmp.pobjDuplicate())); } } // // Copy over the contents of the Mod lists to the regular lists. This is done // before saving any changes to the server or after downloading and parsing new // config. // tCIDLib::TVoid TElkM1V2CWnd::StoreMods() { tElkM1V2C::EItemTypes eType = tElkM1V2C::EItemTypes::Min; while (eType <= tElkM1V2C::EItemTypes::Max) { // Get the right lists for this type tElkM1V2C::TItemList& colSrc = *m_colModLists[eType]; tElkM1V2C::TItemList& colTar = *m_colLists[eType]; // Clear out the target list colTar.RemoveAll(); // And now dup the mod list const tCIDLib::TCard4 c4Count = colSrc.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { colTar.Add ( static_cast<TItemInfo*>(colSrc[c4Index]->pobjDuplicate()) ); } eType++; } }
fd2b0dfba5d96ae0cee2f6a0996013fab5fe5ba1
1ea9fb2026828ba5e8938644284ddaca1ce14310
/RTMFinalOptimized/RunRules/Simulation/maxfiles/CpuMain_VECTIS_DFE_SIM/scratch/software-sim/build/RTMKernel.h
2b7d09b2ae6435e8eb847a021e72c14d760095cc
[]
no_license
edeiana/MaxelerRTM
c5182826e37d1ecadd0c15e8c64688ce86cfad52
1cf5346e4e66fa671370bf08cc633d39c8526b7b
refs/heads/master
2021-10-12T21:36:51.411346
2013-06-23T21:56:14
2013-06-23T21:56:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,438
h
#ifndef RTMKERNEL_H_ #define RTMKERNEL_H_ // #include "KernelManagerBlockSync.h" namespace maxcompilersim { class RTMKernel : public KernelManagerBlockSync { public: RTMKernel(const std::string &instance_name); protected: virtual void runComputationCycle(); virtual void resetComputation(); virtual void resetComputationAfterFlush(); void updateState(); void preExecute(); virtual int getFlushLevelStart(); private: t_port_number m_controller; t_port_number m_p; t_port_number m_pp; t_port_number m_scale; t_port_number m_dvv; t_port_number m_py; t_port_number m_px; t_port_number m_source_container; t_port_number m_ppresult; HWOffsetFix<1,0,UNSIGNED> id0out_io_controller_force_disabled; HWOffsetFix<32,0,TWOSCOMPLEMENT> id2out_data; HWOffsetFix<1,0,UNSIGNED> id2st_read_next_cycle; HWOffsetFix<32,0,TWOSCOMPLEMENT> id2st_last_read_value; HWOffsetFix<1,0,UNSIGNED> id164out_output[159]; HWOffsetFix<1,0,UNSIGNED> id148out_io_ppresult_force_disabled; HWOffsetFix<1,0,UNSIGNED> id206out_output[89]; HWOffsetFix<1,0,UNSIGNED> id4out_io_p_force_disabled; HWFloat<8,24> id10out_data; HWOffsetFix<1,0,UNSIGNED> id10st_read_next_cycle; HWFloat<8,24> id10st_last_read_value; HWFloat<8,24> id174out_output[3]; HWFloat<8,24> id208out_output[10]; HWFloat<8,24> id209out_output[3]; HWFloat<8,24> id210out_output[3]; HWFloat<8,24> id211out_output[8]; HWFloat<8,24> id212out_output[7]; HWFloat<8,24> id213out_output[6]; HWFloat<8,24> id214out_output[9]; HWFloat<8,24> id215out_output[4]; HWFloat<8,24> id216out_output[11]; HWFloat<8,24> id163out_floatOut[2]; HWFloat<8,24> id170out_output[143]; HWOffsetFix<1,0,UNSIGNED> id166out_output[159]; HWRawBits<1> id167out_output[32]; HWOffsetFix<1,0,UNSIGNED> id12out_io_pp_force_disabled; HWFloat<8,24> id18out_data; HWOffsetFix<1,0,UNSIGNED> id18st_read_next_cycle; HWFloat<8,24> id18st_last_read_value; HWOffsetFix<1,0,UNSIGNED> id168out_output[159]; HWOffsetFix<1,0,UNSIGNED> id42out_io_scale_force_disabled; HWOffsetFix<1,0,UNSIGNED> id169out_output[32]; HWFloat<8,24> id48out_data; HWOffsetFix<1,0,UNSIGNED> id48st_read_next_cycle; HWFloat<8,24> id48st_last_read_value; HWFloat<8,24> id65out_result[9]; HWFloat<8,24> id68out_result[13]; HWOffsetFix<1,0,UNSIGNED> id171out_output[159]; HWOffsetFix<1,0,UNSIGNED> id20out_io_dvv_force_disabled; HWRawBits<1> id172out_output[44]; HWFloat<8,24> id26out_data; HWOffsetFix<1,0,UNSIGNED> id26st_read_next_cycle; HWFloat<8,24> id26st_last_read_value; HWFloat<8,24> id49out_c_0; HWFloat<8,24> id69out_result[9]; HWFloat<8,24> id50out_c_1_0; HWFloat<8,24> id72out_result[13]; HWFloat<8,24> id73out_result[9]; HWFloat<8,24> id74out_result[13]; HWFloat<8,24> id51out_c_1_1; HWFloat<8,24> id77out_result[13]; HWFloat<8,24> id78out_result[9]; HWFloat<8,24> id79out_result[13]; HWFloat<8,24> id52out_c_1_2; HWFloat<8,24> id82out_result[13]; HWFloat<8,24> id83out_result[9]; HWFloat<8,24> id84out_result[13]; HWFloat<8,24> id53out_c_1_3; HWFloat<8,24> id87out_result[13]; HWFloat<8,24> id88out_result[9]; HWFloat<8,24> id89out_result[13]; HWFloat<8,24> id54out_c_1_4; HWFloat<8,24> id92out_result[13]; HWFloat<8,24> id93out_result[9]; HWFloat<8,24> id94out_result[13]; HWFloat<8,24> id55out_c_2_0; HWOffsetFix<1,0,UNSIGNED> id38out_io_py_force_disabled; HWFloat<8,24> id40out_data; HWOffsetFix<1,0,UNSIGNED> id40st_read_next_cycle; HWFloat<8,24> id40st_last_read_value; HWFloat<8,24> id183out_output[3]; HWFloat<8,24> id97out_result[13]; HWFloat<8,24> id98out_result[9]; HWFloat<8,24> id99out_result[13]; HWFloat<8,24> id56out_c_2_1; HWFloat<8,24> id217out_output[10]; HWFloat<8,24> id218out_output[5]; HWFloat<8,24> id102out_result[13]; HWFloat<8,24> id103out_result[9]; HWFloat<8,24> id104out_result[13]; HWFloat<8,24> id57out_c_2_2; HWFloat<8,24> id219out_output[8]; HWFloat<8,24> id220out_output[7]; HWFloat<8,24> id107out_result[13]; HWFloat<8,24> id108out_result[9]; HWFloat<8,24> id109out_result[13]; HWFloat<8,24> id58out_c_2_3; HWFloat<8,24> id221out_output[4]; HWFloat<8,24> id222out_output[3]; HWFloat<8,24> id223out_output[9]; HWFloat<8,24> id112out_result[13]; HWFloat<8,24> id113out_result[9]; HWFloat<8,24> id114out_result[13]; HWFloat<8,24> id59out_c_2_4; HWFloat<8,24> id116out_result[13]; HWFloat<8,24> id117out_result[9]; HWFloat<8,24> id192out_output[14]; HWFloat<8,24> id118out_result[13]; HWFloat<8,24> id60out_c_3_0; HWOffsetFix<1,0,UNSIGNED> id35out_io_px_force_disabled; HWFloat<8,24> id37out_data; HWOffsetFix<1,0,UNSIGNED> id37st_read_next_cycle; HWFloat<8,24> id37st_last_read_value; HWFloat<8,24> id193out_output[3]; HWFloat<8,24> id121out_result[13]; HWFloat<8,24> id122out_result[9]; HWFloat<8,24> id123out_result[13]; HWFloat<8,24> id61out_c_3_1; HWFloat<8,24> id224out_output[10]; HWFloat<8,24> id225out_output[5]; HWFloat<8,24> id126out_result[13]; HWFloat<8,24> id127out_result[9]; HWFloat<8,24> id128out_result[13]; HWFloat<8,24> id62out_c_3_2; HWFloat<8,24> id226out_output[8]; HWFloat<8,24> id227out_output[7]; HWFloat<8,24> id131out_result[13]; HWFloat<8,24> id132out_result[9]; HWFloat<8,24> id133out_result[13]; HWFloat<8,24> id63out_c_3_3; HWFloat<8,24> id228out_output[4]; HWFloat<8,24> id229out_output[3]; HWFloat<8,24> id230out_output[9]; HWFloat<8,24> id136out_result[13]; HWFloat<8,24> id137out_result[9]; HWFloat<8,24> id138out_result[13]; HWFloat<8,24> id64out_c_3_4; HWFloat<8,24> id140out_result[13]; HWFloat<8,24> id141out_result[9]; HWFloat<8,24> id202out_output[14]; HWFloat<8,24> id142out_result[13]; HWFloat<8,24> id143out_result[9]; HWFloat<8,24> id144out_result[13]; HWOffsetFix<1,0,UNSIGNED> id203out_output[159]; HWOffsetFix<1,0,UNSIGNED> id28out_io_source_container_force_disabled; HWOffsetFix<1,0,UNSIGNED> id204out_output[64]; HWFloat<8,24> id34out_data; HWOffsetFix<1,0,UNSIGNED> id34st_read_next_cycle; HWFloat<8,24> id34st_last_read_value; HWFloat<8,24> id145out_result[13]; HWFloat<8,24> id205out_output[45]; HWFloat<8,24> id146out_result[9]; HWOffsetFix<1,0,UNSIGNED> id158out_value; HWOffsetFix<1,0,UNSIGNED> id231out_value; HWOffsetFix<49,0,UNSIGNED> id156out_value; HWOffsetFix<48,0,UNSIGNED> id157out_count; HWOffsetFix<1,0,UNSIGNED> id157out_wrap; HWOffsetFix<49,0,UNSIGNED> id157st_count; HWOffsetFix<48,0,UNSIGNED> id207out_output[5]; HWOffsetFix<48,0,UNSIGNED> id161out_run_cycle_count; HWOffsetFix<1,0,UNSIGNED> id162out_result[2]; const HWOffsetFix<1,0,UNSIGNED> c_hw_fix_1_0_uns_bits; const HWOffsetFix<32,0,TWOSCOMPLEMENT> c_hw_fix_32_0_sgn_undef; const HWOffsetFix<1,0,UNSIGNED> c_hw_fix_1_0_uns_undef; const HWFloat<8,24> c_hw_flt_8_24_undef; const HWFloat<8,24> c_hw_flt_8_24_2_0val; const HWRawBits<1> c_hw_bit_1_undef; const HWOffsetFix<1,0,UNSIGNED> c_hw_fix_1_0_uns_bits_1; const HWOffsetFix<49,0,UNSIGNED> c_hw_fix_49_0_uns_bits; const HWOffsetFix<49,0,UNSIGNED> c_hw_fix_49_0_uns_bits_1; const HWOffsetFix<49,0,UNSIGNED> c_hw_fix_49_0_uns_bits_2; const HWOffsetFix<48,0,UNSIGNED> c_hw_fix_48_0_uns_undef; void execute0(); }; } #endif /* RTMKERNEL_H_ */
085f0296599608c57cd4556c070c3b96d19d0103
393c305aceced1ded46709791838863027ccbd50
/src/rosap_exe/include/rosap_converter.h
1afca184fbdd0573a8fa8e3cb3423d6b42c92905
[]
no_license
korbu/turtlesim
c07943866c7f33126ae8bfdefe99d5666403c30c
22bba8d00ed7bd80134bf3f23c5afd0132fcb542
refs/heads/main
2023-04-21T20:37:54.389015
2021-05-09T11:05:32
2021-05-09T11:05:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
750
h
// // Created by root on 2021/3/23. // #ifndef TURTLESIM_ROSAP_CONVERTER_H #define TURTLESIM_ROSAP_CONVERTER_H #include "rosap_converter_swc.h" #include "ros/ros.h" #include "turtlesim/TeleportAbsolute.h" #include "turtlesim/Pose.h" class rosap_converter : public rosap_converter_swc, ros::NodeHandle { public: rosap_converter(); ~rosap_converter() override = default; bool run() override; bool stop() override; private: ros::Subscriber positionlistener; ros::ServiceServer elementListener; void topicConvertFunc(const turtlesim::PoseConstPtr &rossample); bool SetterConvertFunc(turtlesim::TeleportAbsolute::Request &req, turtlesim::TeleportAbsolute::Response &res); }; #endif //TURTLESIM_ROSAP_CONVERTER_H
02e44a65b65e3c51c7cb16620312f9fe1a8d44c9
33efb9eb97164e42a3556a219a121a604e8915d4
/排序子序列/排序子序列/排序子序列.cpp
a3eab83cb5ba29655c05ea200fe91bc603d07355
[]
no_license
JasmineHJM/leetcode
eb27151510136eb754a7e941ec81ffa7d13a849d
294272869657b8b9f0e9143dfa5f3962bbb17d66
refs/heads/master
2020-08-22T10:54:49.545543
2020-04-15T10:17:39
2020-04-15T10:17:39
216,378,130
0
0
null
null
null
null
GB18030
C++
false
false
987
cpp
//牛牛定义排序子序列为一个数组中一段连续的子序列, 并且这段子序列是非递增或者非递减排序的。 //牛牛有一个长度为n的整数数组A, 他现在有一个任务是把数组A分为若干段排序子序列, 牛牛想知道他最少可以把这个数组分为几段排序子序列 //如样例所示, 牛牛可以把数组A划分为[1, 2, 3]和[2, 2, 1]两个排序子序列, 至少需要划分为2个排序子序列, 所以输出2 #include<iostream> #include<vector> using namespace std; int main() { int n = 0; cin >> n; vector<int> arr; arr.resize(n + 1); arr[n] = 0; int count = 0; for (int i = 0; i < n; i++) { cin >> arr[i]; } for (int i = 0; i < n; i++) { if (arr[i] < arr[i + 1]) { while (arr[i] <= arr[i + 1]) { i++; } count++; } else if (arr[i] > arr[i + 1]) { while (arr[i] >= arr[i + 1]) { i++; if (i == n) break; } count++; } } cout << count << endl; return 0; }
e6f1321e88b5d3dfe8d64d77acfb978725009467
d3c1bf708bade0ed21c564aecb784c511dfa864d
/银行系统.cpp
3a880f22d88b7b33a5c287d27bca51cd6eff7963
[]
no_license
capwind11/project
d7a6d19655d84dc9cdba545cf375205f1e4f233a
1568c5cf8e7dadbc26813988c012b80a7df4ae0f
refs/heads/master
2020-04-01T09:44:58.298577
2018-10-15T09:37:35
2018-10-15T09:37:35
null
0
0
null
null
null
null
GB18030
C++
false
false
6,775
cpp
#include <iostream> #include <queue> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> using namespace std; int seed; //随机种子 enum Window_status{busy,available}; //窗口状态 double uniform() //平均分布 { double t; seed = (2045*(seed)+15)%1048576; t=(seed)/1048576.0; return(t); } int poisson(double lambda) //泊松分布 { int i,x; double a,b,u; a = exp(-lambda); i = 0; b = 1.0; do{ u=uniform(); b*=u; i++; }while(b>=a); x = i-1; return x; } class Customer //模拟顾客类 { private: int cus_num;//顾客编号 int arrive_time; //到达时间 int serving_time; //该顾客所需服务时间 public: Customer() { } Customer(int n,int current_time,int time) { cus_num = n; arrive_time = current_time; serving_time = time; } int getnum()//得到顾客编号 { return cus_num; } int get_servetime() { return serving_time; } int waiting_time(int current_time) { return current_time-arrive_time; } }; class Window { private: int serve_num; //服务顾客总数 int cus_num; //当前服务顾客编号 Window_status status; //窗口状态 int serving_time,start_time; //随机的服务时间 int Win_num;//窗口编号 public: Window() { serve_num = 0; cus_num = -1; serving_time = start_time = 0; status = available; } Window(int n) { serve_num = 0; serving_time = start_time = 0; Win_num = n; status = available; } int get_winnum() { return Win_num; } void set_winnum(int n) { Win_num = n; } void show()//显示当前窗口服务顾客编号 { if (cus_num==-1) cout << Win_num+1 << "号窗口空闲"<<endl; else cout << Win_num+1 << "号窗口正在服务"<<cus_num+1<<"号顾客"<<endl; } int get_serve_num() //得到服务总顾客数 { return serve_num; } void serve(Customer cus,int current_time)//服务队头顾客,并将顾客编号和所需服务时间等信息载入 { serving_time = cus.get_servetime(); start_time = current_time; status = busy; cus_num = cus.getnum(); serve_num++; } Window_status is_available(int current_time)//检测窗口状态 { if(current_time-start_time>=serving_time)//若前一顾客已经服务完毕 { status = available;//状态设置为空闲 cus_num=-1; } else status = busy; return status; } }; class System { private: queue<Customer> q;//一条队列 Window win[5];//五个窗口 int total_wait_time;//顾客总共等待时间 public: System() { total_wait_time = 0; for(int i=0;i<5;i++) { win[i].set_winnum(i); } } void line(Customer c)//将新来的顾客排入队尾 { q.push(c); } int size()//返回队列长度 { return q.size(); } void serve(int current_time)//更新窗口状态并分配顾客给窗口 { for(int i=0;i<5;i++){ if(win[i].is_available(current_time)==available&&!q.empty())//当出现窗口空闲时,安排顾客 { cout << q.front().getnum()+1<<"号顾客"<<"等待了"<<q.front().waiting_time(current_time)<<"分钟后得到了"<<i+1<<"号窗口的服务"<<endl; win[i].serve(q.front(),current_time); total_wait_time += q.front().waiting_time(current_time); q.pop();//顾客离开队列 } } cout << "此时有"<<q.size() << "位顾客在等待"<<endl; } void show()//显示每个窗口服务的顾客 { for(int i =0;i<5;i++) { win[i].show(); } } void close()//银行关闭,显示今天营业的各种信息 { int cus_num=0; for(int i=0;i<5;i++) { cout << i+1<<"号窗口总共服务了"<<win[i].get_serve_num()<<"位顾客"<<endl; cus_num+=win[i].get_serve_num(); } cout <<"人均等待时间为"<<((double)total_wait_time)/cus_num<<"分钟"<<endl; } bool empty() //判断队列是否为空 { return q.empty(); } }; void initialize(int &end_time,double &arrive_rate,double &solve_time_rate) { cout << "请输入银行工作时间长度(分钟)"<<endl; cin >> end_time; cout <<"请输入每分钟可能光临顾客的数目"<<endl; cin >> arrive_rate; cout << "请输入每位顾客办理业务可能所需时间(分钟)"<<endl; cin >> solve_time_rate; cout << endl; } int main() { int end_time; //营业总时长 int cus_num = 0; double arrive_rate,solve_time_rate; //每分钟到达顾客期望值和服务所需时间期望值 srand((unsigned)time(NULL)); seed = rand();//用时间常数设置随机种子 initialize(end_time,arrive_rate,solve_time_rate); System bank; for(int current_time = 0;current_time < end_time;current_time++){ cout <<"第"<<current_time+1<<"分钟:"<<endl; int number_arrivals = poisson(arrive_rate); //得到符合泊松分布的顾客数 cout << "有"<<number_arrivals << " 位新顾客到来"<<endl; for(int i = 0;i < number_arrivals;i++){ int time = poisson(solve_time_rate); Customer current_cus(cus_num++,current_time,time);//初始化顾客 bank.line(current_cus); } bank.serve(current_time); cout << "窗口服务状态:"<<endl; bank.show(); cout << endl; } int delay_time = end_time; cout << "正常营业时间已到"<< endl; cout << "---------------------------------------------" <<endl; bank.close(); cout << endl; if(bank.empty()) { cout << "已服务完所有顾客,银行关闭" <<endl; return 0; } cout << "此时队伍中还有"<< bank.size()<<"名顾客未得到服务"<<endl; cout <<"若要继续服务完队伍中顾客"<<endl; while(!bank.empty())//在正常营业时间外继续服务完已在队伍中的顾客 { cout << "第" <<delay_time+1<<"分钟:"<<endl; bank.serve(delay_time); bank.show(); delay_time++; } cout << endl; cout << "---------------------------------------------"<<endl; cout << "所有顾客服务完毕需要时间为" << delay_time << "分钟"<< endl; cout <<"比正常营业时间超出了" <<delay_time - end_time <<"分钟"<<endl; bank.close(); }
6ccde2f125698686bfeb02caffec28ee92123573
60db84d8cb6a58bdb3fb8df8db954d9d66024137
/android-cpp-sdk/platforms/android-7/java/util/GregorianCalendar.hpp
4a352fcb4f0216deec59c85b3c4b8e65a52730c5
[ "BSL-1.0" ]
permissive
tpurtell/android-cpp-sdk
ba853335b3a5bd7e2b5c56dcb5a5be848da6550c
8313bb88332c5476645d5850fe5fdee8998c2415
refs/heads/master
2021-01-10T20:46:37.322718
2012-07-17T22:06:16
2012-07-17T22:06:16
37,555,992
5
4
null
null
null
null
UTF-8
C++
false
false
15,444
hpp
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://[email protected] class: java.util.GregorianCalendar ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_GREGORIANCALENDAR_HPP_DECL #define J2CPP_JAVA_UTIL_GREGORIANCALENDAR_HPP_DECL namespace j2cpp { namespace java { namespace io { class Serializable; } } } namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class Comparable; } } } namespace j2cpp { namespace java { namespace lang { class Cloneable; } } } namespace j2cpp { namespace java { namespace util { class Locale; } } } namespace j2cpp { namespace java { namespace util { class Date; } } } namespace j2cpp { namespace java { namespace util { class Calendar; } } } namespace j2cpp { namespace java { namespace util { class TimeZone; } } } #include <java/io/Serializable.hpp> #include <java/lang/Cloneable.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/Object.hpp> #include <java/util/Calendar.hpp> #include <java/util/Date.hpp> #include <java/util/Locale.hpp> #include <java/util/TimeZone.hpp> namespace j2cpp { namespace java { namespace util { class GregorianCalendar; class GregorianCalendar : public object<GregorianCalendar> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) J2CPP_DECLARE_METHOD(19) J2CPP_DECLARE_METHOD(20) J2CPP_DECLARE_METHOD(21) J2CPP_DECLARE_METHOD(22) J2CPP_DECLARE_METHOD(23) J2CPP_DECLARE_METHOD(24) J2CPP_DECLARE_METHOD(25) J2CPP_DECLARE_FIELD(0) J2CPP_DECLARE_FIELD(1) explicit GregorianCalendar(jobject jobj) : object<GregorianCalendar>(jobj) { } operator local_ref<java::io::Serializable>() const; operator local_ref<java::lang::Object>() const; operator local_ref<java::lang::Comparable>() const; operator local_ref<java::lang::Cloneable>() const; operator local_ref<java::util::Calendar>() const; GregorianCalendar(); GregorianCalendar(jint, jint, jint); GregorianCalendar(jint, jint, jint, jint, jint); GregorianCalendar(jint, jint, jint, jint, jint, jint); GregorianCalendar(local_ref< java::util::Locale > const&); GregorianCalendar(local_ref< java::util::TimeZone > const&); GregorianCalendar(local_ref< java::util::TimeZone > const&, local_ref< java::util::Locale > const&); void add(jint, jint); local_ref< java::lang::Object > clone(); jboolean equals(local_ref< java::lang::Object > const&); jint getActualMaximum(jint); jint getActualMinimum(jint); jint getGreatestMinimum(jint); local_ref< java::util::Date > getGregorianChange(); jint getLeastMaximum(jint); jint getMaximum(jint); jint getMinimum(jint); jint hashCode(); jboolean isLeapYear(jint); void roll(jint, jint); void roll(jint, jboolean); void setGregorianChange(local_ref< java::util::Date > const&); void setFirstDayOfWeek(jint); void setMinimalDaysInFirstWeek(jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > BC; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > AD; }; //class GregorianCalendar } //namespace util } //namespace java } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_GREGORIANCALENDAR_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_JAVA_UTIL_GREGORIANCALENDAR_HPP_IMPL #define J2CPP_JAVA_UTIL_GREGORIANCALENDAR_HPP_IMPL namespace j2cpp { java::util::GregorianCalendar::operator local_ref<java::io::Serializable>() const { return local_ref<java::io::Serializable>(get_jobject()); } java::util::GregorianCalendar::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } java::util::GregorianCalendar::operator local_ref<java::lang::Comparable>() const { return local_ref<java::lang::Comparable>(get_jobject()); } java::util::GregorianCalendar::operator local_ref<java::lang::Cloneable>() const { return local_ref<java::lang::Cloneable>(get_jobject()); } java::util::GregorianCalendar::operator local_ref<java::util::Calendar>() const { return local_ref<java::util::Calendar>(get_jobject()); } java::util::GregorianCalendar::GregorianCalendar() : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(0), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(0) >() ) { } java::util::GregorianCalendar::GregorianCalendar(jint a0, jint a1, jint a2) : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(1), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(1) >(a0, a1, a2) ) { } java::util::GregorianCalendar::GregorianCalendar(jint a0, jint a1, jint a2, jint a3, jint a4) : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(2), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(2) >(a0, a1, a2, a3, a4) ) { } java::util::GregorianCalendar::GregorianCalendar(jint a0, jint a1, jint a2, jint a3, jint a4, jint a5) : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(3), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(3) >(a0, a1, a2, a3, a4, a5) ) { } java::util::GregorianCalendar::GregorianCalendar(local_ref< java::util::Locale > const &a0) : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(4), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(4) >(a0) ) { } java::util::GregorianCalendar::GregorianCalendar(local_ref< java::util::TimeZone > const &a0) : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(5), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(5) >(a0) ) { } java::util::GregorianCalendar::GregorianCalendar(local_ref< java::util::TimeZone > const &a0, local_ref< java::util::Locale > const &a1) : object<java::util::GregorianCalendar>( call_new_object< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(6), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(6) >(a0, a1) ) { } void java::util::GregorianCalendar::add(jint a0, jint a1) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(7), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject(), a0, a1); } local_ref< java::lang::Object > java::util::GregorianCalendar::clone() { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(8), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(8), local_ref< java::lang::Object > >(get_jobject()); } jboolean java::util::GregorianCalendar::equals(local_ref< java::lang::Object > const &a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(11), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(11), jboolean >(get_jobject(), a0); } jint java::util::GregorianCalendar::getActualMaximum(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(12), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(12), jint >(get_jobject(), a0); } jint java::util::GregorianCalendar::getActualMinimum(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(13), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(13), jint >(get_jobject(), a0); } jint java::util::GregorianCalendar::getGreatestMinimum(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(14), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(14), jint >(get_jobject(), a0); } local_ref< java::util::Date > java::util::GregorianCalendar::getGregorianChange() { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(15), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(15), local_ref< java::util::Date > >(get_jobject()); } jint java::util::GregorianCalendar::getLeastMaximum(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(16), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(16), jint >(get_jobject(), a0); } jint java::util::GregorianCalendar::getMaximum(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(17), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(17), jint >(get_jobject(), a0); } jint java::util::GregorianCalendar::getMinimum(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(18), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(18), jint >(get_jobject(), a0); } jint java::util::GregorianCalendar::hashCode() { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(19), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(19), jint >(get_jobject()); } jboolean java::util::GregorianCalendar::isLeapYear(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(20), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(20), jboolean >(get_jobject(), a0); } void java::util::GregorianCalendar::roll(jint a0, jint a1) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(21), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(21), void >(get_jobject(), a0, a1); } void java::util::GregorianCalendar::roll(jint a0, jboolean a1) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(22), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(22), void >(get_jobject(), a0, a1); } void java::util::GregorianCalendar::setGregorianChange(local_ref< java::util::Date > const &a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(23), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(23), void >(get_jobject(), a0); } void java::util::GregorianCalendar::setFirstDayOfWeek(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(24), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(24), void >(get_jobject(), a0); } void java::util::GregorianCalendar::setMinimalDaysInFirstWeek(jint a0) { return call_method< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_METHOD_NAME(25), java::util::GregorianCalendar::J2CPP_METHOD_SIGNATURE(25), void >(get_jobject(), a0); } static_field< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_FIELD_NAME(0), java::util::GregorianCalendar::J2CPP_FIELD_SIGNATURE(0), jint > java::util::GregorianCalendar::BC; static_field< java::util::GregorianCalendar::J2CPP_CLASS_NAME, java::util::GregorianCalendar::J2CPP_FIELD_NAME(1), java::util::GregorianCalendar::J2CPP_FIELD_SIGNATURE(1), jint > java::util::GregorianCalendar::AD; J2CPP_DEFINE_CLASS(java::util::GregorianCalendar,"java/util/GregorianCalendar") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,0,"<init>","()V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,1,"<init>","(III)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,2,"<init>","(IIIII)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,3,"<init>","(IIIIII)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,4,"<init>","(Ljava/util/Locale;)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,5,"<init>","(Ljava/util/TimeZone;)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,6,"<init>","(Ljava/util/TimeZone;Ljava/util/Locale;)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,7,"add","(II)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,8,"clone","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,9,"computeFields","()V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,10,"computeTime","()V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,11,"equals","(Ljava/lang/Object;)Z") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,12,"getActualMaximum","(I)I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,13,"getActualMinimum","(I)I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,14,"getGreatestMinimum","(I)I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,15,"getGregorianChange","()Ljava/util/Date;") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,16,"getLeastMaximum","(I)I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,17,"getMaximum","(I)I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,18,"getMinimum","(I)I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,19,"hashCode","()I") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,20,"isLeapYear","(I)Z") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,21,"roll","(II)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,22,"roll","(IZ)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,23,"setGregorianChange","(Ljava/util/Date;)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,24,"setFirstDayOfWeek","(I)V") J2CPP_DEFINE_METHOD(java::util::GregorianCalendar,25,"setMinimalDaysInFirstWeek","(I)V") J2CPP_DEFINE_FIELD(java::util::GregorianCalendar,0,"BC","I") J2CPP_DEFINE_FIELD(java::util::GregorianCalendar,1,"AD","I") } //namespace j2cpp #endif //J2CPP_JAVA_UTIL_GREGORIANCALENDAR_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
28f251cf10a293ab97e4b361790848e759073abc
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/A/B/A/A/B/AABAAB.cpp
1d71008396f12e7441c8d0ec3609fc17be6da611
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
108
cpp
#include "AABAAB.h" namespace AABAAB { std::string run() { std::string out("AABAAB"); return out; } }
b9568047a4ee6629fa167ae4a24fe46d2f5682a3
a60f2d47ad5d4630a60ca275b811f7349818717b
/Spoj_Solutions/LEARN_R_280_4.cpp
813aafeab982a856c9d03cfa69b96c31be8362b8
[]
no_license
kevin-212/KEVIN_SPOJ_SOLUTIONS
ef850ba6af140da5cdc76c83ce528b8abd2dd4b3
e48e5941bb33411f0daef7e3e2758f3f4861135f
refs/heads/master
2021-01-02T09:01:37.268731
2015-07-12T16:02:12
2015-07-12T16:02:12
37,242,944
0
0
null
null
null
null
UTF-8
C++
false
false
492
cpp
#include<iostream> #include<cstdio> #include<vector> #include<algorithm> #include<cstring> using namespace std; int main(){ long long i,n,m,dx,dy; cin>>n>>m>>dx>>dy; long long aux,res,x,y,a[n],c[n]; a[0]=0; for(i=1;i<n;i++){ a[(i*dx) % n] = (i*dy) % n; } memset(c,0,sizeof c); res=0; for(i=0;i<m;i++){ cin>>x>>y; aux = (n + y - a[x]) % n; c[aux]++; if(c[aux]>c[res]) res = aux; } cout<<0<<" "<<res<<endl; }
681a8b9f9b96b362c45c99ac3f8c4c6dd43cc8f6
a8bc4471c9ed6dd534193b58b560cc3d94536b09
/pathSumII.cpp
4c29a2e73c9fa85bd35e502018ee1df219198331
[]
no_license
JosephTseng1/leetcode-solutions
5f1c190345c7cced9b9d4ce2204a4b84ac884ca7
47e1f6a036e814e9c6d3afde035db3457ef432ce
refs/heads/master
2023-04-23T06:03:15.299971
2021-04-30T07:29:44
2021-04-30T07:29:44
361,069,157
0
0
null
null
null
null
UTF-8
C++
false
false
1,134
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void solve(TreeNode* root, vector<vector<int>> &results, vector<int> curr, int sum, int currSum) { if (root == NULL) { return; } currSum += root->val; curr.push_back(root->val); if (currSum == sum && root->left == NULL && root->right == NULL) { results.push_back(curr); return; } solve(root->left, results, curr, sum, currSum); solve(root->right, results, curr, sum, currSum); } vector<vector<int>> pathSum(TreeNode* root, int sum) { if (root == NULL) { return {}; } vector<vector<int>> results; vector<int> curr; solve(root, results, curr, sum, 0); return results; } };
7ab86c951ebf762ba320b3ee9a8f4f26ace74f68
427a32d9e3ba6436f7f1459e6c1f38c02baa7ffc
/IIR-O1Response/IIR-O1Response.cpp
6180b8b4f72b94def6338ca8e5d16c42f8c22908
[]
no_license
ryood/DigitalFilterTest
ac2ff26d684d109aa8cb26384a6b50411280d80a
75303b6b765d888f24f3f1aac15449e0fea9264b
refs/heads/master
2021-01-22T10:29:25.140079
2017-05-30T10:01:08
2017-05-30T10:01:08
92,646,676
0
0
null
null
null
null
UTF-8
C++
false
false
5,647
cpp
// IIR-O1Response.cpp : Defines the entry point for the console application. // #include "stdafx.h" /******************************* SOURCE LICENSE ********************************* Copyright (c) 2015 MicroModeler. A non-exclusive, nontransferable, perpetual, royalty-free license is granted to the Licensee to use the following Information for academic, non-profit, or government-sponsored research purposes. Use of the following Information under this License is restricted to NON-COMMERCIAL PURPOSES ONLY. Commercial use of the following Information requires a separately executed written license agreement. This Information is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ******************************* END OF LICENSE *********************************/ // A commercial license for MicroModeler DSP can be obtained at http://www.micromodeler.com/launch.jsp #include "filter1.h" #include <stdlib.h> // For malloc/free #include <string.h> // For memset float filter1_coefficients[5] = { // Scaled for floating point 0.1367287359973195, 0.1367287359973195, 0, 0.726542528005361, 0// b0, b1, b2, a1, a2 }; filter1Type *filter1_create(void) { filter1Type *result = (filter1Type *)malloc(sizeof(filter1Type)); // Allocate memory for the object filter1_init(result); // Initialize it return result; // Return the result } void filter1_destroy(filter1Type *pObject) { free(pObject); } void filter1_init(filter1Type * pThis) { filter1_reset(pThis); } void filter1_reset(filter1Type * pThis) { memset(&pThis->state, 0, sizeof(pThis->state)); // Reset state to 0 pThis->output = 0; // Reset output } int filter1_filterBlock(filter1Type * pThis, float * pInput, float * pOutput, unsigned int count) { filter1_executionState executionState; // The executionState structure holds call data, minimizing stack reads and writes if (!count) return 0; // If there are no input samples, return immediately executionState.pInput = pInput; // Pointers to the input and output buffers that each call to filterBiquad() will use executionState.pOutput = pOutput; // - pInput and pOutput can be equal, allowing reuse of the same memory. executionState.count = count; // The number of samples to be processed executionState.pState = pThis->state; // Pointer to the biquad's internal state and coefficients. executionState.pCoefficients = filter1_coefficients; // Each call to filterBiquad() will advance pState and pCoefficients to the next biquad // The 1st call to filter1_filterBiquad() reads from the caller supplied input buffer and writes to the output buffer. // The remaining calls to filterBiquad() recycle the same output buffer, so that multiple intermediate buffers are not required. filter1_filterBiquad(&executionState); // Run biquad #0 executionState.pInput = executionState.pOutput; // The remaining biquads will now re-use the same output buffer. // At this point, the caller-supplied output buffer will contain the filtered samples and the input buffer will contain the unmodified input samples. return count; // Return the number of samples processed, the same as the number of input samples } void filter1_filterBiquad(filter1_executionState * pExecState) { // Read state variables float x0; float x1 = pExecState->pState[0]; float x2 = pExecState->pState[1]; float y1 = pExecState->pState[2]; float y2 = pExecState->pState[3]; // Read coefficients into work registers float b0 = *(pExecState->pCoefficients++); float b1 = *(pExecState->pCoefficients++); float b2 = *(pExecState->pCoefficients++); float a1 = *(pExecState->pCoefficients++); float a2 = *(pExecState->pCoefficients++); // Read source and target pointers float *pInput = pExecState->pInput; float *pOutput = pExecState->pOutput; short count = pExecState->count; float accumulator; while (count--) { x0 = *(pInput++); accumulator = x2 * b2; accumulator += x1 * b1; accumulator += x0 * b0; x2 = x1; // Shuffle left history buffer x1 = x0; accumulator += y2 * a2; accumulator += y1 * a1; y2 = y1; // Shuffle right history buffer y1 = accumulator; *(pOutput++) = accumulator; } *(pExecState->pState++) = x1; *(pExecState->pState++) = x2; *(pExecState->pState++) = y1; *(pExecState->pState++) = y2; } #define LOOP (2) #define PERIOD (50) #define SQUARE (0) #define SAWUP (0) #define SAWDOWN (1) int _tmain(int argc, _TCHAR* argv[]) { filter1Type* filter = filter1_create(); printf("Sample\tInput\tOutput\n"); int count = 0; for (int i = 0; i < LOOP; i++) { #if (SQUARE) float in = 1.0f; for (int j = 0; j < PERIOD / 2; j++) { filter1_writeInput(filter, in); float out = filter1_readOutput(filter); printf("%d\t%f\t%f\n", count, in, out); count++; } in = 0.0f; for (int j = 0; j < PERIOD / 2; j++) { filter1_writeInput(filter, in); float out = filter1_readOutput(filter); printf("%d\t%f\t%f\n", count, in, out); count++; } #elif (SAWUP) float in = 0.0f; for (int j = 0; j < PERIOD; j++) { filter1_writeInput(filter, in); float out = filter1_readOutput(filter); printf("%d\t%f\t%f\n", count, in, out); in += 1.0f / PERIOD; count++; } #elif (SAWDOWN) float in = 1.0f; for (int j = 0; j < PERIOD; j++) { filter1_writeInput(filter, in); float out = filter1_readOutput(filter); printf("%d\t%f\t%f\n", count, in, out); in -= 1.0f / PERIOD; count++; } #endif } return 0; }
d629b448c02611060cf6e2a6989366e598aef3d8
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/Source/Includes/QtIncludes/src/3rdparty/webkit/WebCore/rendering/TextControlInnerElements.h
b2d2452e4d1c04c786f4c9f8e13f2194b266bfff
[ "Apache-2.0", "MIT", "curl", "LGPL-2.1-or-later", "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "Zlib", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference", "MS-LPL", "BSD-2-Clause", "LGPL-2.0-only" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
2,779
h
/* * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 COMPUTER, INC. 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. */ #ifndef TextControlInnerElements_h #define TextControlInnerElements_h #include "HTMLDivElement.h" namespace WebCore { class String; class TextControlInnerElement : public HTMLDivElement { public: TextControlInnerElement(Document*, Node* shadowParent = 0); virtual bool isMouseFocusable() const { return false; } virtual bool isShadowNode() const { return m_shadowParent; } virtual Node* shadowParentNode() { return m_shadowParent; } void setShadowParentNode(Node* node) { m_shadowParent = node; } void attachInnerElement(Node*, PassRefPtr<RenderStyle>, RenderArena*); private: Node* m_shadowParent; }; class TextControlInnerTextElement : public TextControlInnerElement { public: TextControlInnerTextElement(Document*, Node* shadowParent); virtual RenderObject* createRenderer(RenderArena*, RenderStyle*); virtual void defaultEventHandler(Event*); }; class SearchFieldResultsButtonElement : public TextControlInnerElement { public: SearchFieldResultsButtonElement(Document*); virtual void defaultEventHandler(Event*); }; class SearchFieldCancelButtonElement : public TextControlInnerElement { public: SearchFieldCancelButtonElement(Document*); virtual void defaultEventHandler(Event*); virtual void detach(); private: bool m_capturing; }; } //namespace #endif
df4a08f23f68a0ba910d4e3376ed4cbbb92a5446
b5fcbe33f68a415d35f202cb72430115b2312462
/catkin_ws/src/depth_camera/depthimage_to_laserscan/src/DepthImageToLaserScan.cpp
109fdf5d053b87f5da1d10831827bce8501622b9
[]
no_license
moneypi/moneypi_ros
93634c7f885d589c12e6e5f4c13272e2e6c19cc2
66c47456b0a89ec75ccf5d185c22b053ae351b08
refs/heads/master
2020-07-01T13:50:58.050091
2019-08-08T07:22:20
2019-08-08T07:22:20
201,187,767
2
0
null
null
null
null
UTF-8
C++
false
false
7,947
cpp
/* * Copyright (c) 2012, Willow Garage, 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 the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * Author: Chad Rockey */ #include <depthimage_to_laserscan/DepthImageToLaserScan.h> using namespace depthimage_to_laserscan; DepthImageToLaserScan::DepthImageToLaserScan(){ } DepthImageToLaserScan::~DepthImageToLaserScan(){ } double DepthImageToLaserScan::magnitude_of_ray(const cv::Point3d& ray) const{ return sqrt(pow(ray.x, 2.0) + pow(ray.y, 2.0) + pow(ray.z, 2.0)); } double DepthImageToLaserScan::angle_between_rays(const cv::Point3d& ray1, const cv::Point3d& ray2) const{ double dot_product = ray1.x*ray2.x + ray1.y*ray2.y + ray1.z*ray2.z; double magnitude1 = magnitude_of_ray(ray1); double magnitude2 = magnitude_of_ray(ray2);; return acos(dot_product / (magnitude1 * magnitude2)); } bool DepthImageToLaserScan::use_point(const float new_value, const float old_value, const float range_min, const float range_max) const{ // Check for NaNs and Infs, a real number within our limits is more desirable than these. bool new_finite = std::isfinite(new_value); bool old_finite = std::isfinite(old_value); // Infs are preferable over NaNs (more information) if(!new_finite && !old_finite){ // Both are not NaN or Inf. if(!isnan(new_value)){ // new is not NaN, so use it's +-Inf value. return true; } return false; // Do not replace old_value } // If not in range, don't bother bool range_check = range_min <= new_value && new_value <= range_max; if(!range_check){ return false; } if(!old_finite){ // New value is in range and finite, use it. return true; } // Finally, if they are both numerical and new_value is closer than old_value, use new_value. bool shorter_check = new_value < old_value; return shorter_check; } sensor_msgs::LaserScanPtr DepthImageToLaserScan::convert_msg(const sensor_msgs::ImageConstPtr& depth_msg, const sensor_msgs::CameraInfoConstPtr& info_msg){ // Set camera model cam_model_.fromCameraInfo(info_msg); // Calculate angle_min and angle_max by measuring angles between the left ray, right ray, and optical center ray cv::Point2d raw_pixel_left(0, cam_model_.cy()); cv::Point2d rect_pixel_left = cam_model_.rectifyPoint(raw_pixel_left); cv::Point3d left_ray = cam_model_.projectPixelTo3dRay(rect_pixel_left); cv::Point2d raw_pixel_right(depth_msg->width-1, cam_model_.cy()); cv::Point2d rect_pixel_right = cam_model_.rectifyPoint(raw_pixel_right); cv::Point3d right_ray = cam_model_.projectPixelTo3dRay(rect_pixel_right); cv::Point2d raw_pixel_center(cam_model_.cx(), cam_model_.cy()); cv::Point2d rect_pixel_center = cam_model_.rectifyPoint(raw_pixel_center); cv::Point3d center_ray = cam_model_.projectPixelTo3dRay(rect_pixel_center); double angle_max = angle_between_rays(left_ray, center_ray); double angle_min = -angle_between_rays(center_ray, right_ray); // Negative because the laserscan message expects an opposite rotation of that from the depth image // double angle_max = 0.506145483; // double angle_min = -0.506145483; // Calculate vertical field of view angle cv::Point2d raw_pixel_top(0, cam_model_.cx()); cv::Point2d rect_pixel_top = cam_model_.rectifyPoint(raw_pixel_top); cv::Point3d top_ray = cam_model_.projectPixelTo3dRay(rect_pixel_top); cv::Point2d raw_pixel_bottom(depth_msg->height-1, cam_model_.cx()); cv::Point2d rect_pixel_bottom = cam_model_.rectifyPoint(raw_pixel_bottom); cv::Point3d bottom_ray = cam_model_.projectPixelTo3dRay(rect_pixel_bottom); double camFOVy = angle_between_rays(top_ray, bottom_ray); // float camFOVy = 0.785398163; // Fill in laserscan message sensor_msgs::LaserScanPtr scan_msg(new sensor_msgs::LaserScan()); scan_msg->header = depth_msg->header; if(output_frame_id_.length() > 0){ scan_msg->header.frame_id = output_frame_id_; } scan_msg->angle_min = angle_min; scan_msg->angle_max = angle_max; scan_msg->angle_increment = (scan_msg->angle_max - scan_msg->angle_min) / (depth_msg->width - 1); scan_msg->time_increment = 0.0; scan_msg->scan_time = scan_time_; scan_msg->range_min = range_min_; scan_msg->range_max = range_max_; // Check scan_height vs image_height if(scan_height_/2 > cam_model_.cy() || scan_height_/2 > depth_msg->height - cam_model_.cy()){ std::stringstream ss; ss << "scan_height ( " << scan_height_ << " pixels) is too large for the image height."; throw std::runtime_error(ss.str()); } // Calculate and fill the ranges uint32_t ranges_size = depth_msg->width; scan_msg->ranges.assign(ranges_size, std::numeric_limits<float>::quiet_NaN()); if (depth_msg->encoding == sensor_msgs::image_encodings::TYPE_16UC1) { convert<uint16_t>(depth_msg, cam_model_, scan_msg, scan_height_, camFOVy); } else if (depth_msg->encoding == sensor_msgs::image_encodings::TYPE_32FC1) { convert<float>(depth_msg, cam_model_, scan_msg, scan_height_, camFOVy); } else { std::stringstream ss; ss << "Depth image has unsupported encoding: " << depth_msg->encoding; throw std::runtime_error(ss.str()); } return scan_msg; } void DepthImageToLaserScan::set_scan_time(const float scan_time){ scan_time_ = scan_time; } void DepthImageToLaserScan::set_range_limits(const float range_min, const float range_max){ range_min_ = range_min; range_max_ = range_max; } void DepthImageToLaserScan::set_scan_height(const int scan_height){ scan_height_ = scan_height; } void DepthImageToLaserScan::set_output_frame(const std::string output_frame_id){ output_frame_id_ = output_frame_id; } void DepthImageToLaserScan::set_floorplane_scan_enable(const bool floorplane_scan_enable){ floorplane_scan_enable_ = floorplane_scan_enable; } void DepthImageToLaserScan::set_image_ignore_ratio(const float image_ignore_ratio){ image_ignore_ratio_ = image_ignore_ratio; } void DepthImageToLaserScan::set_frame_z(const float frame_z) { frame_z_ = frame_z; } void DepthImageToLaserScan::set_floorplane_obstacle_height(const float floorplane_obstacle_height) { floorplane_obstacle_height_ = floorplane_obstacle_height; } void DepthImageToLaserScan::set_floorplane_cliff_depth(const float floorplane_cliff_depth) { floorplane_cliff_depth_ = floorplane_cliff_depth; } void DepthImageToLaserScan::set_horiz_angle_offset(const float horiz_angle_offset) { horiz_angle_offset_ = horiz_angle_offset; }
fafd21da7379396cac0c74d0c785a9febc80022c
04b1803adb6653ecb7cb827c4f4aa616afacf629
/content/renderer/renderer_main_platform_delegate_win.cc
f59a53dbc38b5b0f4c4c54b0700cfd49d87c1e94
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
2,726
cc
// Copyright (c) 2012 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 "content/renderer/renderer_main_platform_delegate.h" #include <dwrite.h> #include <memory> #include "base/command_line.h" #include "base/logging.h" #include "base/strings/string16.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" #include "content/child/dwrite_font_proxy/dwrite_font_proxy_init_impl_win.h" #include "content/child/font_warmup_win.h" #include "content/public/common/injection_test_win.h" #include "content/public/renderer/render_thread.h" #include "content/renderer/render_thread_impl.h" #include "sandbox/win/src/sandbox.h" #include "services/service_manager/sandbox/switches.h" #include "third_party/blink/public/platform/web_runtime_features.h" #include "third_party/blink/public/web/win/web_font_rendering.h" #include "third_party/icu/source/i18n/unicode/timezone.h" #include "third_party/skia/include/ports/SkTypeface_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/win/direct_write.h" namespace content { RendererMainPlatformDelegate::RendererMainPlatformDelegate( const MainFunctionParams& parameters) : parameters_(parameters) {} RendererMainPlatformDelegate::~RendererMainPlatformDelegate() { } void RendererMainPlatformDelegate::PlatformInitialize() { const base::CommandLine& command_line = parameters_.command_line; // Be mindful of what resources you acquire here. They can be used by // malicious code if the renderer gets compromised. bool no_sandbox = command_line.HasSwitch(service_manager::switches::kNoSandbox); if (!no_sandbox) { // ICU DateFormat class (used in base/time_format.cc) needs to get the // Olson timezone ID by accessing the registry keys under // HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones. // After TimeZone::createDefault is called once here, the timezone ID is // cached and there's no more need to access the registry. If the sandbox // is disabled, we don't have to make this dummy call. std::unique_ptr<icu::TimeZone> zone(icu::TimeZone::createDefault()); } InitializeDWriteFontProxy(); } void RendererMainPlatformDelegate::PlatformUninitialize() { UninitializeDWriteFontProxy(); } bool RendererMainPlatformDelegate::EnableSandbox() { sandbox::TargetServices* target_services = parameters_.sandbox_info->target_services; if (target_services) { // Cause advapi32 to load before the sandbox is turned on. unsigned int dummy_rand; rand_s(&dummy_rand); target_services->LowerToken(); return true; } return false; } } // namespace content
5444609378ae89ee42b58cac249d57118ad0e7e7
48e97bfd26c2e9af53031313d571a2bcbf7ae62a
/include/x11/composite.hpp
a4de96fe1014f045c658632d8eff23fa3bb9292d
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mrkgnao/polybar
15957f12ef45d7012689a098cad9359b60db9ff2
3d158e8526d363942f7d8c3ca30a764b70846cac
refs/heads/master
2020-06-13T21:52:40.259161
2016-12-06T14:02:08
2016-12-06T14:02:08
75,549,065
1
0
null
2016-12-04T16:21:04
2016-12-04T16:21:04
null
UTF-8
C++
false
false
177
hpp
#pragma once #include "config.hpp" #if not WITH_XCOMPOSITE #error "X Composite extension is disabled..." #endif #include <xcb/composite.h> #include <xpp/proto/composite.hpp>
b1095bd0b50560445b2cd01f105e21f219534e71
39c18cc30a2440aa15645ce73e37a88d4e970b1d
/src/resources/Constants.h
bfa07de06263459a44a0b06540d82374d3f3dcd5
[]
no_license
petrstepanov/roopositrongui
bb967b285508e9858c6f331e5a8efdd644b98fc7
3bfd8b0ba3bd0b935c79fb6c5ac098cb461d3a5c
refs/heads/master
2023-01-06T08:19:45.664240
2023-01-03T19:19:25
2023-01-03T19:19:25
181,575,334
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
h
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Constants.h * Author: petrstepanov * * Created on August 19, 2017, 11:30 PM */ #ifndef CONSTANTS_H #define CONSTANTS_H #include <TROOT.h> #include <TColor.h> #include <RooConstVar.h> class Constants { public: // static constexpr Double_t chbar = 0.19732697 * 1E4; // c*hbar, eV*Å // static constexpr Double_t mc2 = 0.511E6; // electron mc^2, eV // static constexpr Double_t Ry = 13.605; // Rydberg constant, eV // static constexpr Double_t a_B = 0.529177; // Bohr radius, Å static const UInt_t windowWidth = 1200; static const UInt_t windowHeight = 600; static UInt_t leftPanelWidth; // static const Double_t sigmaToFwhm; // static const Double_t fwhmToSigma; // static Double_t bufferFraction; static const char* applicationName; // static RooConstVar* rooFwhmToSigma; // static RooConstVar* pi; }; #endif /* CONSTANTS_H */
c6707ce62b6a8eb0824b31eb71362e377ff52255
03e8d91ea48809ec0d35484fc6c07a12849fb04a
/DDECli/myconv.h
295e76dca7f46aaabf441aabe3f9798122befdb1
[]
no_license
feng-ye/dde_sample
3526a5b9b98048c40e080e56d7baa77b7c3c01d4
ca2bcf8b9133cf16f452ca3f0482f751731b3a4c
refs/heads/master
2020-12-30T11:28:15.399111
2017-06-29T01:41:48
2017-06-29T01:41:48
91,564,173
0
0
null
null
null
null
UTF-8
C++
false
false
300
h
// myconv.h class CDDECliDlg; class CMyConv : public CDDEConv { public: CMyConv(); CMyConv(CDDEServer* pServer, CDDECliDlg* pDlg); virtual BOOL AdviseData(UINT wFmt, LPCTSTR pszTopic, LPCTSTR pszItem, void* pData, DWORD dwSize); CDDECliDlg* m_pDlg; };
0bb18ec4c285e309caa9d014e8e1d6bab7abb02f
54b2d1d6bbfc052faaea2c7a3be681bb90eb82dc
/word-ladder.cpp
d7a47cd23006461de0185158e5ad61dc792eda0f
[ "MIT" ]
permissive
xzwweb/leetcode
a645902e3380007c35cbb325a8f57874a47be465
a9fe99888ce88ad10d36c72080101d2bd8f43ea7
refs/heads/master
2020-03-29T16:12:33.951395
2018-08-29T14:16:25
2018-08-29T14:16:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,267
cpp
class Solution { public: bool oneDiff(string a, string b){ int count = 0; for(int i = 0; i < a.size(); i++){ if(a[i] != b[i]) count++; if(count > 1) return false; } if(count == 1) return true; else return false; } int ladderLength(string beginWord, string endWord, vector<string>& wordList) { if(find(wordList.begin(), wordList.end(), endWord) == wordList.end()) return 0; queue<string> bfs; queue<string> temp; int lvl = 1; bfs.push(endWord); remove(wordList.begin(), wordList.end(), endWord); while(!bfs.empty()){ string s = bfs.front(); bfs.pop(); if(oneDiff(beginWord, s)) return lvl+1; for(auto& str : wordList){ if(oneDiff(str, s)) { temp.push(str); remove(wordList.begin(), wordList.end(), str); } } if(bfs.empty()){ if(!temp.empty()) lvl++; while(!temp.empty()){ string ts = temp.front(); temp.pop(); bfs.push(ts); } } } return 0; } };
0226a6c06ae8d7e7f3b283042e4215ec7e359950
608c7301bf1eaed2b79855fd8030b15e4fc0d4aa
/src/graphics.cpp
2c02a856c2ed768a71b3d2162e94529401ca6c08
[]
no_license
mehmetrizaoz/autonomous_steering_agents
48d0fbba36eafd081c78b825687d156bb02a5764
5d901252f66b68bfcaf48dd7da6145b1bdc462f0
refs/heads/master
2023-05-15T07:28:49.473767
2021-06-14T10:43:48
2021-06-14T10:43:48
356,524,673
1
0
null
null
null
null
UTF-8
C++
false
false
4,954
cpp
/** * @file graphics.cpp * @author Mehmet Rıza Öz - [email protected] * @brief graphics class implementation * @date 15.05.2021 */ #include "graphics.h" #include <GL/glut.h> #include <iostream> #include "math.h" using namespace std; class path; class point; int graphics::target_x = -WIDTH; int graphics::target_y = HEIGHT; point graphics::clickPosition; bool graphics::clicked = false; void graphics::drawText(string text, point p) { glColor3f (0.0, 0.0, 1.0); glRasterPos2f(p.x, p.y); for ( string::iterator it=text.begin(); it!=text.end(); ++it){ glutBitmapCharacter(GLUT_BITMAP_9_BY_15, *it); } } void graphics::refreshScene() { glutSwapBuffers(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); //Switch to the drawing perspective glLoadIdentity(); //Reset the drawing perspective glTranslatef(0.0f, 0.0f, -85.0f); //Move to the center of the triangle } void graphics::initGraphics(int * argv, char** argc, void (*callback)()) { glutInit(argv, argc); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(400, 400); glutCreateWindow("Autonomous Steering Agents"); glClearColor(0.7f, 0.7f, 0.7f, 1.0f); //set background color glEnable(GL_DEPTH_TEST); glutDisplayFunc(*callback); glutMouseFunc(graphics::mouseButton); glutPassiveMotionFunc(graphics::mouseMove); glutKeyboardFunc(graphics::handleKeypress); glutReshapeFunc(graphics::handleResize); glutTimerFunc(20, graphics::timerEvent, 0); glutMainLoop(); } point graphics::getMousePosition() { return point (graphics::target_x, graphics::target_y); } void graphics::forceInScreen(agent &agent) { if(agent.position.x > WIDTH) agent.position.x -= 2 * WIDTH; if(agent.position.x < -WIDTH) agent.position.x += 2 * WIDTH; if(agent.position.y > HEIGHT) agent.position.y -= 2 * HEIGHT; if(agent.position.y < -HEIGHT) agent.position.y += 2 * HEIGHT; } void graphics::mouseMove(int x, int y) { graphics::target_x = x / 5.88 - 34; graphics::target_y = 34 - y / 5.88; } void graphics::handleResize(int w, int h) { glViewport(0, 0, w, h); //Tell OpenGL how to convert from coordinates to pixel values glMatrixMode(GL_PROJECTION); //Switch to setting the camera perspective glLoadIdentity(); //Reset the camera //Set the camera perspective gluPerspective(45.0, //The camera angle (double)w / (double)h, //The width-to-height ratio 1.0, //The near z clipping coordinate 200.0); //The far z clipping coordinate } void graphics::timerEvent(int value) { glutPostRedisplay(); //Tell GLUT that the display has changed glutTimerFunc(value, timerEvent, 20); } void graphics::mouseButton(int button, int state, int x, int y) { if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN){ clicked = true; clickPosition.x = x / 5.88 - 34; clickPosition.y = 34 - y / 5.88; } } void graphics::handleKeypress(unsigned char key, int x, int y) { if (key == ESC){ exit(0); } } void graphics::drawPath(path &path) { point p1, p2; for(auto it = path.points.begin(); it < path.points.end()-1; it++){ p1 = point((*it).x, (*it).y - path.getPathWidth() / 2) ; p2 = point((*(it+1)).x, (*(it+1)).y - path.getPathWidth() / 2); drawLine(p1, p2, path.getColor()); p1 = point((*it).x, (*it).y + path.getPathWidth() / 2) ; p2 = point((*(it+1)).x, (*(it+1)).y + path.getPathWidth() / 2); drawLine(p1, p2, path.getColor()); } } void graphics::drawLine(point p1, point p2, color cl) { glColor3f( cl.R, cl.G, cl.B); glLineWidth(2); glBegin(GL_LINES); glVertex2f(p1.x, p1.y); glVertex2f(p2.x, p2.y); glEnd(); } void graphics::drawCircle(point p, float radius, color color) { glColor3f(color.R, color.G, color.B); glBegin(GL_LINE_STRIP); glLineWidth(2); for (int i = 0; i <= 300; i++) { float angle = 2 * PI * i / 300; float x = cos(angle) * radius; float y = sin(angle) * radius; glVertex2d(p.x + x, p.y + y); } glEnd(); } void graphics::drawPoint(point p ,color cl) { glColor3f(cl.R, cl.G, cl.B); glPointSize(4.0); glBegin(GL_POINTS); glVertex2f(p.x, p.y); glEnd(); } void graphics::drawAgent(agent &agent) { glPushMatrix(); glTranslatef(agent.position.x, agent.position.y, 0.0f); glRotatef(agent.getVelocity().getAngle(), 0.0f, 0.0f, 1.0f); glBegin(GL_TRIANGLES); glColor3f( agent.getColor().R, agent.getColor().G, agent.getColor().B); glVertex3f( 1.0f, 0.0f, 0.0f); glVertex3f(-1.0f, 0.5f, 0.0f); glVertex3f(-1.0f, -0.5f, 0.0f); glEnd(); glPopMatrix(); }
e80e1134fc2005f3a65f0fb06d5b7ae1447bb01d
43a2fbc77f5cea2487c05c7679a30e15db9a3a50
/Cpp/External (Offsets Only)/SDK/EmissaryFramework_functions.cpp
0733e50a88cc4a45e88267ec131799da9d90eaf0
[]
no_license
zH4x/SoT-Insider-SDK
57e2e05ede34ca1fd90fc5904cf7a79f0259085c
6bff738a1b701c34656546e333b7e59c98c63ad7
refs/heads/main
2023-06-09T23:10:32.929216
2021-07-07T01:34:27
2021-07-07T01:34:27
383,638,719
0
0
null
null
null
null
UTF-8
C++
false
false
1,774
cpp
// Name: SoT-Insider, Version: 1.102.2382.0 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void FEmissaryCompanyChangedEvent::AfterRead() { } void FEmissaryCompanyChangedEvent::BeforeDelete() { } void FEmissaryLedgerVisited::AfterRead() { } void FEmissaryLedgerVisited::BeforeDelete() { } void FEmissaryCompanyActionRewardBoostServiceEvent::AfterRead() { } void FEmissaryCompanyActionRewardBoostServiceEvent::BeforeDelete() { } void FEmissaryGlobalActionRewardBoostEvent::AfterRead() { READ_PTR_FULL(GameEventType, UClass); } void FEmissaryGlobalActionRewardBoostEvent::BeforeDelete() { DELE_PTR_FULL(GameEventType); } void FEmissaryGlobalActionRewardBoostServiceEvent::AfterRead() { READ_PTR_FULL(FinishedEventType, UClass); } void FEmissaryGlobalActionRewardBoostServiceEvent::BeforeDelete() { DELE_PTR_FULL(FinishedEventType); } void FEmissaryNonQuestCompanyActionRewardBoostEvent::AfterRead() { } void FEmissaryNonQuestCompanyActionRewardBoostEvent::BeforeDelete() { } void FEmissaryQuestCompanyActionRewardBoostEvent::AfterRead() { } void FEmissaryQuestCompanyActionRewardBoostEvent::BeforeDelete() { } void UEmissaryLevelServiceInterface::AfterRead() { UInterface::AfterRead(); } void UEmissaryLevelServiceInterface::BeforeDelete() { UInterface::BeforeDelete(); } void UEmissaryParticipantInterface::AfterRead() { UInterface::AfterRead(); } void UEmissaryParticipantInterface::BeforeDelete() { UInterface::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
738b0aa1fcdc7495d37bcbd8aa9a4b0e8cc0b30e
e3f023601d07fbc81412817eb318a9c0e41654b1
/iLiveSDK/include/ilivesdk/iLiveSDK.h
fb0ce3c059d9a1c854d8fff53f228b1909b064c0
[]
no_license
JasonXiao001/iLiveSDK_PC_Suixinbo
aae702a476a54e1b0e9a7a63b62a71ff99490530
42ce2f0150d9ff99757db7e424a77df18dfabd0c
refs/heads/master
2020-12-02T19:44:46.160470
2017-05-18T12:00:48
2017-05-18T12:00:48
null
0
0
null
null
null
null
GB18030
C++
false
false
2,333
h
#ifndef iLiveSDK_h_ #define iLiveSDK_h_ #include <imsdk/tim.h> #include <imsdk/tim_comm.h> #include <avsdk/av_context.h> #include <ilivesdk/iLiveCommon.h> namespace ilivesdk { using namespace imcore; using namespace tencent::av; /** @brief iLiveSDK对象代表着一个SDK运行实例。 @note 使用iLiveSDK前,必须调用initSdk()函数初始化SDK。 */ class iLiveAPI iLiveSDK { class ForceOfflineCallBack : public TIMForceOfflineCallBack { public: virtual void OnForceOffline() override; }; public: /** @brief 获取单例对象。 @return 单例对象 */ static iLiveSDK* getInstance(); /** @brief 初始化iLiveSDK。 @note 使用iLiveSDK前,必须调用此函数初始化SDK。 @param [in] appId 腾讯为每个接入方分配的账号id @param [in] accountType 腾讯为每个接入方分配的账号类型 @return 返回操作结果,成功则返回NO_ERR */ int initSdk(const int appId, const int accountType); /** @brief 释放内部资源,程序退出时需要调用。 @remark 此函数会清理7天前的iLiveSDK日志文件。 */ void destroy(); /** @brief 获取TIMManager类单例对象。 @details 用户可以获取TIMManager对象,从而进行一些自定义设置; @return 返回TIMManager单例对象的引用; */ TIMManager& getTIMManager(); /** @brief 获取AppId。 @details 获取在初始化函数中传入的appId @return 返回appId */ int getAppId(); /** @brief 获取App的账号类型。 @details 获取在初始化函数中传入的accountType @return 返回accountType */ int getAccountType(); /** @brief 获取AVContext对象。 @details 获取AVContext对象; @return 返回iLiveSDK内部创建和维护的AVContext对象指针; */ AVContext* getAVContext(); /** @brief 获取版本号。 @return 返回版本号字符串; */ const char* getVersion(); private: iLiveSDK(); ~iLiveSDK(); private: int m_appId; int m_accountType; AVContext* m_pAVContext; std::string m_szVersion; ForceOfflineCallBack m_forceOfflineCB; HMODULE m_hMoude; PROC_AVAPI_GetVersion m_funcGetVersion; PROC_AVAPI_CreateContext m_funcCreateContext; PROC_AVAPI_EnableCrashReport m_funcEnableCrashReport; }; } #endif //iLiveSDK_h_
4919c2bfdb94e4df5da8c863561eb56443f35b81
d766203f49613ed78e4a607c124d21073507a0f8
/backends/twitter/Requests/DestroyFriendRequest.cpp
5468cacea2047c036ffc8d78fd96a663795f866b
[]
no_license
mdonoughe/libtransport
22fac71199d0ae10ad717d73457228d0b1192d76
c7e2635dde99a7b461c370ac87994059fcc12dd4
refs/heads/master
2021-01-15T19:39:37.438367
2012-08-10T12:29:13
2012-08-10T12:29:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
836
cpp
#include "DestroyFriendRequest.h" DEFINE_LOGGER(logger, "DestroyFriendRequest") void DestroyFriendRequest::run() { replyMsg = ""; success = twitObj->friendshipDestroy(frnd, false); if(success) { twitObj->getLastWebResponse(replyMsg); LOG4CXX_INFO(logger, user << replyMsg) friendInfo = getUser(replyMsg); if(friendInfo.getScreenName() == "") LOG4CXX_INFO(logger, user << " - Was unable to fetch user info for " << frnd); } } void DestroyFriendRequest::finalize() { if(!success) { std::string error; twitObj->getLastCurlError(error); LOG4CXX_ERROR(logger, user << " Curl error: " << error) callBack(user, friendInfo, error); } else { std::string error; error = getErrorMessage(replyMsg); if(error.length()) LOG4CXX_ERROR(logger, user << " - " << error) callBack(user, friendInfo, error); } }
d1ab3d2ec4669944f295991efbfdf8e349d1d2f1
7da873e1091534a1957951723034d4f56099bfbe
/BBCrash_Project/BB_Crash/GameClock.cpp
8a78660df61e997051545ce389a5f9dc74c9097b
[]
no_license
smin0219/bbcrash
897eb1007b928111476e7e44e11cb31fc40544ff
27acaa14a59e64b49bfd72130f83bdacade02950
refs/heads/master
2021-01-23T14:34:06.580835
2017-09-07T04:29:46
2017-09-07T04:29:46
102,691,396
0
0
null
null
null
null
UTF-8
C++
false
false
5,813
cpp
/* Author: Richard McKenna Stony Brook University Computer Science Department GameClock.cpp See GameClock.h for a class description. */ #include "stdafx.h" #include "Game.h" #include "GameTypes.h" #include "GameClock.h" #include "EngineConfigProperties.h" #include "GameResources.h" #include "BBEngineConfigImporter.h" #include "TextFileWriter.h" /* GameClock - Default constructor, this method initializes the timer resolution to the best the system has to offer. In order to start timing, call the resetTimer method outside the main game loop, right before it starts. The timeGameLoop method is the only one needed inside the game loop. */ GameClock::GameClock() { } /* ~GameClock - Destructor, we only have to clean up the writer, since we declared it as a pointer instance variable. */ GameClock::~GameClock() {} void GameClock::startUp() { // GET THE GAME SINGLETON Game *game = Game::getSingleton(); GameResources *resources = game->getResources(); BBEngineConfigImporter *importer = (BBEngineConfigImporter*)resources->getEngineConfigImporter(); void* properties = importer->getPropertyTypes(); EngineConfigProperties props; // LOAD THE TARGET FRAME RATE wstring fpsProp = importer->getProperty(props.PROP_NAME_TARGET_FPS); wstringstream(fpsProp) >> targetFPS; // WE SHOULD ASK THE TIMER ITS RESOLUTION timerResolution = std::chrono::steady_clock::period::den; // CALCULATE THE NUMBER OF MILLISECONDS WE // WANT PER FRAME ACCORDING TO THE TARGET_FPS // AND THE TIMER RESOLUTION targetTimePerFrame = (timerResolution / targetFPS); } void GameClock::shutDown() { } /* calculateAverageActualFramerate - This method calculates how long on average a frame takes in the game loop, including time spent sleeping. Note that this calculation is done using the resolution of the system. */ mg_long GameClock::calculateAverageActualFrameRate() { if (loopCounter == 0) return 0; else { mg_int averageTime = totalTime / loopCounter; if (averageTime != 0) return (timerResolution / averageTime); else // IT IS AT LEAST THE TIMER RESOLUTION, BUT WE REALLY // DON'T KNOW DUE TO TIMER RESOLUTION return timerResolution; } } /* calculateAverageSleeplessFramerate - This method calculates how long on average a frame takes in the game loop, not including time spent sleeping. */ mg_long GameClock::calculateAverageSleeplessFrameRate() { if (loopCounter == 0) return 0; else { mg_double averageTime = ((mg_double)sleeplessTotalTime) / (mg_double)loopCounter; if ((int)averageTime != 0) return (timerResolution / averageTime); else // IT IS AT LEAST THE TIMER RESOLUTION, BUT WE REALLY // DON'T KNOW DUE TO TIMER RESOLUTION return timerResolution; } } /* calculateAverageSleepTime - This method calculates on average how much time is spent sleeping each frame since the game loop started. */ mg_long GameClock::calculateAverageSleepTime() { if (loopCounter == 0) return 0; else return totalSleepTime / loopCounter; } /* resetTimer - This method resents all variables used for compiling statistics as well as getting the first start times for the first iteration through the game loop. This should be placed outside the game loop, right before it is to start. */ void GameClock::resetTimer() { gameLoopStartTime = std::chrono::steady_clock::now(); sleeplessGameLoopStartTime = std::chrono::steady_clock::now(); loopCounter = 0; totalTime = 0; sleeplessTotalTime = 0; totalSleepTime = 0; actualLoopRate = 0; sleeplessLoopRate = 0; } /* timeGameLoop - This method gets the current time and then calculates the difference between now and the last time it got the time. This is the game time, which can then be used to calculate the current frame rate. If the current frame rate is too fast, we sleep for a little to clamp it to the TARGET_FPS. If it is too slow, we calculate a scaling factor that can be used for moving sprites and for scrolling. */ void GameClock::timeGameLoop() { // GET THE END OF FRAME TIME gameLoopEndTime = steady_clock::now(); // HOW MUCH TIME PASSED DURING THE LAST FRAME? loopTime = (duration_cast<duration<double>>(gameLoopEndTime - gameLoopStartTime)).count(); // GET THE START TIME FOR NEXT FRAME, IF THERE IS ONE gameLoopStartTime = steady_clock::now(); // ADD THE LAST FRAME'S TIME TO THE TOTAL totalTime += loopTime; // HOW MUCH TIME PASSED NOT INCLUDING // OUR FORCED SLEEPING? sleeplessLoopTime = (gameLoopEndTime - sleeplessGameLoopStartTime).count(); // ADD THE LAST FRAME'S SLEEPLESS TIME TO THE TOTAL sleeplessTotalTime += sleeplessLoopTime; if (loopTime == 0) actualLoopRate = timerResolution; else actualLoopRate = timerResolution / loopTime; if (sleeplessLoopTime == 0) actualLoopRate = timerResolution; else sleeplessLoopRate = timerResolution / sleeplessLoopTime; // IF THIS PAST FRAME RAN TOO FAST IT'S // LIKELY THE NEXT FRAME WILL RUN FAST ALSO if (targetTimePerFrame > sleeplessLoopTime) { // SO LET'S CLAMP IT TO OUR TARGET FRAME RATE sleepTime = targetTimePerFrame - sleeplessLoopTime; totalSleepTime += sleepTime; std::chrono::nanoseconds sleepDuration(sleepTime); sleep_for(sleepDuration); deltaTime = 1; } else { sleepTime = 0; // WE MIGHT USE THIS timeScaleFactor TO SCALE // MOVEMENTS OF GAME SPRITES AND SCROLLING TO // MAKE UP FOR THE SLOWING DOWN OF THE GAME LOOP deltaTime = ((mg_double)targetFPS) / ((mg_double)sleeplessLoopRate); } // GET THE START TIME FOR THE LOOP // NOT INCLUDING THE SLEEP TIME FROM THE LAST LOOP sleeplessGameLoopStartTime = steady_clock::now(); loopCounter++; }
a180bf66aa424116a30fe6bebf16fff29fa1981c
7be47356b22976e615920c1dae8500fce788ddb0
/src/server/game/Guilds/Guild.cpp
749c16e9cac0063c1b1cd0b21786e1054f0db690
[]
no_license
vanasisf/MythCore
20f5eaeb3882fbefeb2854e56d80e5d27c7beae2
4eef4a1fcf374b65c09df539bca1fe6e318444d2
refs/heads/master
2020-12-26T20:10:18.733189
2014-04-21T15:34:32
2014-04-21T15:34:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
95,366
cpp
/* * Copyright (C) 2008 - 2011 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2013 Myth Project <http://mythprojectnetwork.blogspot.com/> * * Myth Project's source is based on the Trinity Project source, you can find the * link to that easily in Trinity Copyrights. Myth Project is a private community. * To get access, you either have to donate or pass a developer test. * You may not share Myth Project's sources! For personal use only. */ #include "DatabaseEnv.h" #include "Guild.h" #include "GuildMgr.h" #include "ScriptMgr.h" #include "Chat.h" #include "Config.h" #include "SocialMgr.h" #include "Log.h" #include "CalendarMgr.h" #include "AccountMgr.h" #define MAX_GUILD_BANK_TAB_TEXT_LEN 500 #define EMBLEM_PRICE 10 * GOLD inline uint32 _GetGuildBankTabPrice(uint8 tabId) { switch(tabId) { case 0: return 100; case 1: return 250; case 2: return 500; case 3: return 1000; case 4: return 2500; case 5: return 5000; default: return 0; } } void Guild::SendCommandResult(WorldSession* session, GuildCommandType type, GuildCommandError errCode, const std::string& param) { WorldPacket data(SMSG_GUILD_COMMAND_RESULT, 8 + param.size() + 1); data << uint32(type); data << param; data << uint32(errCode); session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_COMMAND_RESULT)"); } void Guild::SendSaveEmblemResult(WorldSession* session, GuildEmblemError errCode) { WorldPacket data(MSG_SAVE_GUILD_EMBLEM, 4); data << uint32(errCode); session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (MSG_SAVE_GUILD_EMBLEM)"); } /////////////////////////////////////////////////////////////////////////////// // LogHolder Guild::LogHolder::~LogHolder() { // Cleanup for(GuildLog::iterator itr = m_log.begin(); itr != m_log.end(); ++itr) delete (*itr); } // Adds event loaded from database to collection inline void Guild::LogHolder::LoadEvent(LogEntry* entry) { if(m_nextGUID == uint32(GUILD_EVENT_LOG_GUID_UNDEFINED)) m_nextGUID = entry->GetGUID(); m_log.push_front(entry); } // Adds new event happened in game. // If maximum number of events is reached, oldest event is removed from collection. inline void Guild::LogHolder::AddEvent(SQLTransaction& trans, LogEntry* entry) { // Check max records limit if(m_log.size() >= m_maxRecords) { LogEntry* oldEntry = m_log.front(); delete oldEntry; m_log.pop_front(); } // Add event to list m_log.push_back(entry); // Save to DB entry->SaveToDB(trans); } // Writes information about all events into packet. inline void Guild::LogHolder::WritePacket(WorldPacket& data) const { data << uint8(m_log.size()); for(GuildLog::const_iterator itr = m_log.begin(); itr != m_log.end(); ++itr) (*itr)->WritePacket(data); } inline uint32 Guild::LogHolder::GetNextGUID() { // Next guid was not initialized. It means there are no records for this holder in DB yet. // Start from the beginning. if(m_nextGUID == uint32(GUILD_EVENT_LOG_GUID_UNDEFINED)) m_nextGUID = 0; else m_nextGUID = (m_nextGUID + 1) % m_maxRecords; return m_nextGUID; } /////////////////////////////////////////////////////////////////////////////// // EventLogEntry void Guild::EventLogEntry::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = NULL; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOG); stmt->setUInt32(0, m_guildId); stmt->setUInt32(1, m_guid); CharacterDatabase.ExecuteOrAppend(trans, stmt); uint8 index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_EVENTLOG); stmt->setUInt32( index, m_guildId); stmt->setUInt32(++index, m_guid); stmt->setUInt8 (++index, uint8(m_eventType)); stmt->setUInt32(++index, m_playerGuid1); stmt->setUInt32(++index, m_playerGuid2); stmt->setUInt8 (++index, m_newRank); stmt->setUInt64(++index, m_timestamp); CharacterDatabase.ExecuteOrAppend(trans, stmt); } void Guild::EventLogEntry::WritePacket(WorldPacket& data) const { // Event type data << uint8(m_eventType); // Player 1 data << uint64(MAKE_NEW_GUID(m_playerGuid1, 0, HIGHGUID_PLAYER)); // Player 2 not for left/join guild events if(m_eventType != GUILD_EVENT_LOG_JOIN_GUILD && m_eventType != GUILD_EVENT_LOG_LEAVE_GUILD) data << uint64(MAKE_NEW_GUID(m_playerGuid2, 0, HIGHGUID_PLAYER)); // New Rank - only for promote/demote guild events if(m_eventType == GUILD_EVENT_LOG_PROMOTE_PLAYER || m_eventType == GUILD_EVENT_LOG_DEMOTE_PLAYER) data << uint8(m_newRank); // Event timestamp data << uint32(::time(NULL) - m_timestamp); } /////////////////////////////////////////////////////////////////////////////// // BankEventLogEntry void Guild::BankEventLogEntry::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = NULL; uint8 index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOG); stmt->setUInt32( index, m_guildId); stmt->setUInt32(++index, m_guid); stmt->setUInt8 (++index, m_bankTabId); CharacterDatabase.ExecuteOrAppend(trans, stmt); index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_BANK_EVENTLOG); stmt->setUInt32( index, m_guildId); stmt->setUInt32(++index, m_guid); stmt->setUInt8 (++index, m_bankTabId); stmt->setUInt8 (++index, uint8(m_eventType)); stmt->setUInt32(++index, m_playerGuid); stmt->setUInt32(++index, m_itemOrMoney); stmt->setUInt16(++index, m_itemStackCount); stmt->setUInt8 (++index, m_destTabId); stmt->setUInt64(++index, m_timestamp); CharacterDatabase.ExecuteOrAppend(trans, stmt); } void Guild::BankEventLogEntry::WritePacket(WorldPacket& data) const { data << uint8(m_eventType); data << uint64(MAKE_NEW_GUID(m_playerGuid, 0, HIGHGUID_PLAYER)); data << uint32(m_itemOrMoney); // if(m_eventType != 4 || m_eventType != 5 || m_eventType != 6 || m_eventType != 8 || m_eventType != 9 ) if(m_eventType < GUILD_BANK_LOG_DEPOSIT_MONEY) { data << uint32(m_itemStackCount); if(m_eventType == GUILD_BANK_LOG_MOVE_ITEM || m_eventType == GUILD_BANK_LOG_MOVE_ITEM2) data << uint8(m_destTabId); } data << uint32(time(NULL) - m_timestamp); } /////////////////////////////////////////////////////////////////////////////// // RankInfo void Guild::RankInfo::LoadFromDB(Field* fields) { m_rankId = fields[1].GetUInt8(); m_name = fields[2].GetString(); m_rights = fields[3].GetUInt32(); m_bankMoneyPerDay = fields[4].GetUInt32(); if(m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights m_rights |= GR_RIGHT_ALL; } void Guild::RankInfo::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_RANK); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_rankId); stmt->setString(2, m_name); stmt->setUInt32(3, m_rights); CharacterDatabase.ExecuteOrAppend(trans, stmt); } void Guild::RankInfo::WritePacket(WorldPacket& data) const { data << uint32(m_rights); data << uint32(m_bankMoneyPerDay); // In game set in gold, in packet set in bronze. for(uint8 i = 0; i < GUILD_BANK_MAX_TABS; ++i) { data << uint32(m_bankTabRightsAndSlots[i].rights); data << uint32(m_bankTabRightsAndSlots[i].slots); } } void Guild::RankInfo::SetName(const std::string& name) { if(m_name == name) return; m_name = name; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_RANK_NAME); stmt->setString(0, m_name); stmt->setUInt8 (1, m_rankId); stmt->setUInt32(2, m_guildId); CharacterDatabase.Execute(stmt); } void Guild::RankInfo::SetRights(uint32 rights) { if(m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights rights = GR_RIGHT_ALL; if(m_rights == rights) return; m_rights = rights; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_RANK_RIGHTS); stmt->setUInt32(0, m_rights); stmt->setUInt8 (1, m_rankId); stmt->setUInt32(2, m_guildId); CharacterDatabase.Execute(stmt); } void Guild::RankInfo::SetBankMoneyPerDay(uint32 money) { if(m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights money = uint32(GUILD_WITHDRAW_MONEY_UNLIMITED); if(m_bankMoneyPerDay == money) return; m_bankMoneyPerDay = money; PreparedStatement* stmt = NULL; stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_RANK_BANK_MONEY); stmt->setUInt32(0, money); stmt->setUInt8 (1, m_rankId); stmt->setUInt32(2, m_guildId); CharacterDatabase.Execute(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_RESET_GUILD_RANK_BANK_RESET_TIME); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_rankId); CharacterDatabase.Execute(stmt); } void Guild::RankInfo::SetBankTabSlotsAndRights(uint8 tabId, GuildBankRightsAndSlots rightsAndSlots, bool saveToDB) { if(m_rankId == GR_GUILDMASTER) // Prevent loss of leader rights rightsAndSlots.SetGuildMasterValues(); if(m_bankTabRightsAndSlots[tabId].IsEqual(rightsAndSlots)) return; m_bankTabRightsAndSlots[tabId] = rightsAndSlots; if(saveToDB) { PreparedStatement* stmt = NULL; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHT); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, tabId); stmt->setUInt8 (2, m_rankId); CharacterDatabase.Execute(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_BANK_RIGHT); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, tabId); stmt->setUInt8 (2, m_rankId); stmt->setUInt8 (3, m_bankTabRightsAndSlots[tabId].rights); stmt->setUInt32(4, m_bankTabRightsAndSlots[tabId].slots); CharacterDatabase.Execute(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_RESET_GUILD_RANK_BANK_TIME0 + tabId); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_rankId); CharacterDatabase.Execute(stmt); } } /////////////////////////////////////////////////////////////////////////////// // BankTab bool Guild::BankTab::LoadFromDB(Field* fields) { m_name = fields[2].GetString(); m_icon = fields[3].GetString(); m_text = fields[4].GetString(); return true; } bool Guild::BankTab::LoadItemFromDB(Field* fields) { uint8 slotId = fields[13].GetUInt8(); uint32 itemGuid = fields[14].GetUInt32(); uint32 itemEntry = fields[15].GetUInt32(); if(slotId >= GUILD_BANK_MAX_SLOTS) { sLog->outError("Invalid slot for item (GUID: %u, id: %u) in guild bank, skipped.", itemGuid, itemEntry); return false; } ItemTemplate const* proto = sObjectMgr->GetItemTemplate(itemEntry); if(!proto) { sLog->outError("Unknown item (GUID: %u, id: %u) in guild bank, skipped.", itemGuid, itemEntry); return false; } Item *pItem = NewItemOrBag(proto); if(!pItem->LoadFromDB(itemGuid, 0, fields, itemEntry)) { sLog->outError("Item (GUID %u, id: %u) not found in item_instance, deleting from guild bank!", itemGuid, itemEntry); PreparedStatement *stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_NONEXISTENT_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); CharacterDatabase.Execute(stmt); delete pItem; return false; } pItem->AddToWorld(); m_items[slotId] = pItem; return true; } // Deletes contents of the tab from the world (and from DB if necessary) void Guild::BankTab::Delete(SQLTransaction& trans, bool removeItemsFromDB) { for(uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId) if(Item* pItem = m_items[slotId]) { pItem->RemoveFromWorld(); if(removeItemsFromDB) pItem->DeleteFromDB(trans); delete pItem; pItem = NULL; } } inline void Guild::BankTab::WritePacket(WorldPacket& data) const { data << uint8(GUILD_BANK_MAX_SLOTS); for(uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId) WriteSlotPacket(data, slotId); } // Writes information about contents of specified slot into packet. void Guild::BankTab::WriteSlotPacket(WorldPacket& data, uint8 slotId) const { Item *pItem = GetItem(slotId); uint32 itemEntry = pItem ? pItem->GetEntry() : 0; data << uint8(slotId); data << uint32(itemEntry); if(itemEntry) { data << uint32(0); // 3.3.0 (0x00018020, 0x00018000) data << uint32(pItem->GetItemRandomPropertyId()); // Random item property id if(pItem->GetItemRandomPropertyId()) data << uint32(pItem->GetItemSuffixFactor()); // SuffixFactor data << uint32(pItem->GetCount()); // ITEM_FIELD_STACK_COUNT data << uint32(0); data << uint8(abs(pItem->GetSpellCharges())); // Spell charges uint8 enchCount = 0; size_t enchCountPos = data.wpos(); data << uint8(enchCount); // Number of enchantments for(uint32 i = PERM_ENCHANTMENT_SLOT; i < MAX_ENCHANTMENT_SLOT; ++i) if(uint32 enchId = pItem->GetEnchantmentId(EnchantmentSlot(i))) { data << uint8(i); data << uint32(enchId); ++enchCount; } data.put<uint8>(enchCountPos, enchCount); } } void Guild::BankTab::SetInfo(const std::string& name, const std::string& icon) { if(m_name == name && m_icon == icon) return; m_name = name; m_icon = icon; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_BANK_TAB_INFO); stmt->setString(0, m_name); stmt->setString(1, m_icon); stmt->setUInt32(2, m_guildId); stmt->setUInt8 (3, m_tabId); CharacterDatabase.Execute(stmt); } void Guild::BankTab::SetText(const std::string& text) { if(m_text == text) return; m_text = text; utf8truncate(m_text, MAX_GUILD_BANK_TAB_TEXT_LEN); // DB and client size limitation PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_BANK_TAB_TEXT); stmt->setString(0, m_text); stmt->setUInt32(1, m_guildId); stmt->setUInt8 (2, m_tabId); CharacterDatabase.Execute(stmt); } // Sets/removes contents of specified slot. // If pItem == NULL contents are removed. bool Guild::BankTab::SetItem(SQLTransaction& trans, uint8 slotId, Item* pItem) { if(slotId >= GUILD_BANK_MAX_SLOTS) return false; m_items[slotId] = pItem; PreparedStatement* stmt = NULL; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); CharacterDatabase.ExecuteOrAppend(trans, stmt); if(pItem) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_BANK_ITEM); stmt->setUInt32(0, m_guildId); stmt->setUInt8 (1, m_tabId); stmt->setUInt8 (2, slotId); stmt->setUInt32(3, pItem->GetGUIDLow()); CharacterDatabase.ExecuteOrAppend(trans, stmt); pItem->SetUInt64Value(ITEM_FIELD_CONTAINED, 0); pItem->SetUInt64Value(ITEM_FIELD_OWNER, 0); pItem->FSetState(ITEM_NEW); pItem->SaveToDB(trans); // Not in inventory and can be saved standalone } return true; } void Guild::BankTab::SendText(const Guild* pGuild, WorldSession* session) const { WorldPacket data(MSG_QUERY_GUILD_BANK_TEXT, 1 + m_text.size() + 1); data << uint8(m_tabId); data << m_text; if(session) session->SendPacket(&data); else pGuild->BroadcastPacket(&data); } /////////////////////////////////////////////////////////////////////////////// // Member void Guild::Member::SetStats(Player* player) { m_name = player->GetName(); m_level = player->getLevel(); m_class = player->getClass(); m_zoneId = player->GetZoneId(); m_accountId = player->GetSession()->GetAccountId(); } void Guild::Member::SetStats(const std::string& name, uint8 level, uint8 _class, uint32 zoneId, uint32 accountId) { m_name = name; m_level = level; m_class = _class; m_zoneId = zoneId; m_accountId = accountId; } void Guild::Member::SetPublicNote(const std::string& publicNote) { if(m_publicNote == publicNote) return; m_publicNote = publicNote; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_MEMBER_PNOTE); stmt->setString(0, publicNote); stmt->setUInt32(1, GUID_LOPART(m_guid)); CharacterDatabase.Execute(stmt); } void Guild::Member::SetOfficerNote(const std::string& officerNote) { if(m_officerNote == officerNote) return; m_officerNote = officerNote; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_MEMBER_OFFNOTE); stmt->setString(0, officerNote); stmt->setUInt32(1, GUID_LOPART(m_guid)); CharacterDatabase.Execute(stmt); } void Guild::Member::ChangeRank(uint8 newRank) { m_rankId = newRank; // Update rank information in player's field, if he is online. if(Player* player = FindPlayer()) player->SetRank(newRank); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_MEMBER_RANK); stmt->setUInt8 (0, newRank); stmt->setUInt32(1, GUID_LOPART(m_guid)); CharacterDatabase.Execute(stmt); } void Guild::Member::SaveToDB(SQLTransaction& trans) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_MEMBER); stmt->setUInt32(0, m_guildId); stmt->setUInt32(1, GUID_LOPART(m_guid)); stmt->setUInt8 (2, m_rankId); stmt->setString(3, m_publicNote); stmt->setString(4, m_officerNote); CharacterDatabase.ExecuteOrAppend(trans, stmt); } // Loads member's data from database. // If member has broken fields (level, class) returns false. // In this case member has to be removed from guild. bool Guild::Member::LoadFromDB(Field* fields) { m_publicNote = fields[3].GetString(); m_officerNote = fields[4].GetString(); m_bankRemaining[GUILD_BANK_MAX_TABS].resetTime = fields[5].GetUInt32(); m_bankRemaining[GUILD_BANK_MAX_TABS].value = fields[6].GetUInt32(); for(uint8 i = 0; i < GUILD_BANK_MAX_TABS; ++i) { m_bankRemaining[i].resetTime = fields[7 + i * 2].GetUInt32(); m_bankRemaining[i].value = fields[8 + i * 2].GetUInt32(); } SetStats(fields[19].GetString(), fields[20].GetUInt8(), fields[21].GetUInt8(), fields[22].GetUInt32(), fields[23].GetUInt32()); m_logoutTime = fields[24].GetUInt32(); if(!CheckStats()) return false; if(!m_zoneId) { sLog->outError("Player (GUID: %u) has broken zone-data", GUID_LOPART(m_guid)); m_zoneId = Player::GetZoneIdFromDB(m_guid); } return true; } // Validate player fields. Returns false if corrupted fields are found. bool Guild::Member::CheckStats() const { if(m_level < 1) { sLog->outError("Player (GUID: %u) has a broken data in field `characters`.`level`, deleting him from guild!", GUID_LOPART(m_guid)); return false; } if(m_class < CLASS_WARRIOR || m_class >= MAX_CLASSES) { sLog->outError("Player (GUID: %u) has a broken data in field `characters`.`class`, deleting him from guild!", GUID_LOPART(m_guid)); return false; } return true; } void Guild::Member::WritePacket(WorldPacket& data) const { if(Player* player = FindPlayer()) { data << uint64(player->GetGUID()); data << uint8(1); data << player->GetName(); data << uint32(m_rankId); data << uint8(player->getLevel()); data << uint8(player->getClass()); data << uint8(0); // new 2.4.0 data << uint32(player->GetZoneId()); } else { data << m_guid; data << uint8(0); data << m_name; data << uint32(m_rankId); data << uint8(m_level); data << uint8(m_class); data << uint8(0); // new 2.4.0 data << uint32(m_zoneId); data << float(float(::time(NULL) - m_logoutTime) / DAY); } data << m_publicNote; data << m_officerNote; } // Decreases amount of money/slots left for today. // if(tabId == GUILD_BANK_MAX_TABS) decrease money amount. // Otherwise decrease remaining items amount for specified tab. void Guild::Member::DecreaseBankRemainingValue(SQLTransaction& trans, uint8 tabId, uint32 amount) { m_bankRemaining[tabId].value -= amount; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement( tabId == GUILD_BANK_MAX_TABS ? CHAR_SET_GUILD_MEMBER_BANK_REM_MONEY : CHAR_SET_GUILD_MEMBER_BANK_REM_SLOTS0 + tabId); stmt->setUInt32(0, m_bankRemaining[tabId].value); stmt->setUInt32(1, m_guildId); stmt->setUInt32(2, GUID_LOPART(m_guid)); CharacterDatabase.ExecuteOrAppend(trans, stmt); } // Get amount of money/slots left for today. // if(tabId == GUILD_BANK_MAX_TABS) return money amount. // Otherwise return remaining items amount for specified tab. // If reset time was more than 24 hours ago, renew reset time and reset amount to maximum value. uint32 Guild::Member::GetBankRemainingValue(uint8 tabId, const Guild* pGuild) const { // Guild master has unlimited amount. if(IsRank(GR_GUILDMASTER)) return tabId == GUILD_BANK_MAX_TABS ? GUILD_WITHDRAW_MONEY_UNLIMITED : GUILD_WITHDRAW_SLOT_UNLIMITED; // Check rights for non-money tab. if(tabId != GUILD_BANK_MAX_TABS) if((pGuild->_GetRankBankTabRights(m_rankId, tabId) & GUILD_BANK_RIGHT_VIEW_TAB) != GUILD_BANK_RIGHT_VIEW_TAB) return 0; uint32 curTime = uint32(::time(NULL) / MINUTE); // minutes if(curTime > m_bankRemaining[tabId].resetTime + 24 * HOUR / MINUTE) { RemainingValue& rv = const_cast <RemainingValue&> (m_bankRemaining[tabId]); rv.resetTime = curTime; rv.value = tabId == GUILD_BANK_MAX_TABS ? pGuild->_GetRankBankMoneyPerDay(m_rankId) : pGuild->_GetRankBankTabSlotsPerDay(m_rankId, tabId); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement( tabId == GUILD_BANK_MAX_TABS ? CHAR_SET_GUILD_MEMBER_BANK_TIME_MONEY : CHAR_SET_GUILD_MEMBER_BANK_TIME_REM_SLOTS0 + tabId); stmt->setUInt32(0, m_bankRemaining[tabId].resetTime); stmt->setUInt32(1, m_bankRemaining[tabId].value); stmt->setUInt32(2, m_guildId); stmt->setUInt32(3, GUID_LOPART(m_guid)); CharacterDatabase.Execute(stmt); } return m_bankRemaining[tabId].value; } inline void Guild::Member::ResetTabTimes() { for(uint8 tabId = 0; tabId < GUILD_BANK_MAX_TABS; ++tabId) m_bankRemaining[tabId].resetTime = 0; } inline void Guild::Member::ResetMoneyTime() { m_bankRemaining[GUILD_BANK_MAX_TABS].resetTime = 0; } /////////////////////////////////////////////////////////////////////////////// // EmblemInfo void EmblemInfo::LoadFromDB(Field* fields) { m_style = fields[3].GetUInt8(); m_color = fields[4].GetUInt8(); m_borderStyle = fields[5].GetUInt8(); m_borderColor = fields[6].GetUInt8(); m_backgroundColor = fields[7].GetUInt8(); } void EmblemInfo::WritePacket(WorldPacket& data) const { data << uint32(m_style); data << uint32(m_color); data << uint32(m_borderStyle); data << uint32(m_borderColor); data << uint32(m_backgroundColor); } void EmblemInfo::SaveToDB(uint32 guildId) const { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_EMBLEM_INFO); stmt->setUInt32(0, m_style); stmt->setUInt32(1, m_color); stmt->setUInt32(2, m_borderStyle); stmt->setUInt32(3, m_borderColor); stmt->setUInt32(4, m_backgroundColor); stmt->setUInt32(5, guildId); CharacterDatabase.Execute(stmt); } /////////////////////////////////////////////////////////////////////////////// // MoveItemData bool Guild::MoveItemData::CheckItem(uint32& splitedAmount) { ASSERT(m_pItem); if(splitedAmount > m_pItem->GetCount()) return false; if(splitedAmount == m_pItem->GetCount()) splitedAmount = 0; return true; } bool Guild::MoveItemData::CanStore(Item* pItem, bool swap, bool sendError) { m_vec.clear(); InventoryResult msg = _CanStore(pItem, swap); if(sendError && msg != EQUIP_ERR_OK) m_pPlayer->SendEquipError(msg, pItem); return (msg == EQUIP_ERR_OK); } bool Guild::MoveItemData::CloneItem(uint32 count) { ASSERT(m_pItem); m_pClonedItem = m_pItem->CloneItem(count); if(!m_pClonedItem) { m_pPlayer->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, m_pItem); return false; } return true; } void Guild::MoveItemData::LogAction(MoveItemData* pFrom) const { ASSERT(pFrom->GetItem()); sScriptMgr->OnGuildItemMove(m_pGuild, m_pPlayer, pFrom->GetItem(), pFrom->IsBank(), pFrom->GetContainer(), pFrom->GetSlotId(), IsBank(), GetContainer(), GetSlotId()); } inline void Guild::MoveItemData::CopySlots(SlotIds& ids) const { for(ItemPosCountVec::const_iterator itr = m_vec.begin(); itr != m_vec.end(); ++itr) ids.insert(uint8(itr->pos)); } /////////////////////////////////////////////////////////////////////////////// // PlayerMoveItemData bool Guild::PlayerMoveItemData::InitItem() { m_pItem = m_pPlayer->GetItemByPos(m_container, m_slotId); if(m_pItem) { // Anti-WPE protection. Do not move non-empty bags to bank. if(m_pItem->IsNotEmptyBag()) { m_pPlayer->SendEquipError(EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS, m_pItem); m_pItem = NULL; } // Bound items cannot be put into bank. else if(!m_pItem->CanBeTraded()) { m_pPlayer->SendEquipError(EQUIP_ERR_ITEMS_CANT_BE_SWAPPED, m_pItem); m_pItem = NULL; } } return (m_pItem != NULL); } void Guild::PlayerMoveItemData::RemoveItem(SQLTransaction& trans, MoveItemData* /*pOther*/, uint32 splitedAmount) { if(splitedAmount) { m_pItem->SetCount(m_pItem->GetCount() - splitedAmount); m_pItem->SetState(ITEM_CHANGED, m_pPlayer); m_pPlayer->SaveInventoryAndGoldToDB(trans); } else { m_pPlayer->MoveItemFromInventory(m_container, m_slotId, true); m_pItem->DeleteFromInventoryDB(trans); m_pItem = NULL; } } Item* Guild::PlayerMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem) { ASSERT(pItem); m_pPlayer->MoveItemToInventory(m_vec, pItem, true); m_pPlayer->SaveInventoryAndGoldToDB(trans); return pItem; } void Guild::PlayerMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* pFrom, uint32 count) const { ASSERT(pFrom); // Bank -> Char m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_WITHDRAW_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUIDLow(), pFrom->GetItem()->GetEntry(), count); } inline InventoryResult Guild::PlayerMoveItemData::_CanStore(Item* pItem, bool swap) { return m_pPlayer->CanStoreItem(m_container, m_slotId, m_vec, pItem, swap); } /////////////////////////////////////////////////////////////////////////////// // BankMoveItemData bool Guild::BankMoveItemData::InitItem() { m_pItem = m_pGuild->_GetItem(m_container, m_slotId); return (m_pItem != NULL); } bool Guild::BankMoveItemData::HasStoreRights(MoveItemData* pOther) const { ASSERT(pOther); // Do not check rights if item is being swapped within the same bank tab if(pOther->IsBank() && pOther->GetContainer() == m_container) return true; return m_pGuild->_MemberHasTabRights(m_pPlayer->GetGUID(), m_container, GUILD_BANK_RIGHT_DEPOSIT_ITEM); } bool Guild::BankMoveItemData::HasWithdrawRights(MoveItemData* pOther) const { ASSERT(pOther); // Do not check rights if item is being swapped within the same bank tab if(pOther->IsBank() && pOther->GetContainer() == m_container) return true; return (m_pGuild->_GetMemberRemainingSlots(m_pPlayer->GetGUID(), m_container) != 0); } void Guild::BankMoveItemData::RemoveItem(SQLTransaction& trans, MoveItemData* pOther, uint32 splitedAmount) { ASSERT(m_pItem); if(splitedAmount) { m_pItem->SetCount(m_pItem->GetCount() - splitedAmount); m_pItem->FSetState(ITEM_CHANGED); m_pItem->SaveToDB(trans); } else { m_pGuild->_RemoveItem(trans, m_container, m_slotId); m_pItem = NULL; } // Decrease amount of player's remaining items (if item is moved to different tab or to player) if(!pOther->IsBank() || pOther->GetContainer() != m_container) m_pGuild->_DecreaseMemberRemainingSlots(trans, m_pPlayer->GetGUID(), m_container); } Item* Guild::BankMoveItemData::StoreItem(SQLTransaction& trans, Item* pItem) { if(!pItem) return NULL; BankTab* pTab = m_pGuild->GetBankTab(m_container); if(!pTab) return NULL; Item* pLastItem = pItem; for(ItemPosCountVec::const_iterator itr = m_vec.begin(); itr != m_vec.end(); ) { ItemPosCount pos(*itr); ++itr; sLog->outDebug(LOG_FILTER_GUILD, "GUILD STORAGE: StoreItem tab = %u, slot = %u, item = %u, count = %u", m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); pLastItem = _StoreItem(trans, pTab, pItem, pos, itr != m_vec.end()); } return pLastItem; } void Guild::BankMoveItemData::LogBankEvent(SQLTransaction& trans, MoveItemData* pFrom, uint32 count) const { ASSERT(pFrom->GetItem()); if(pFrom->IsBank()) // Bank -> Bank m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_MOVE_ITEM, pFrom->GetContainer(), m_pPlayer->GetGUIDLow(), pFrom->GetItem()->GetEntry(), count, m_container); else // Char -> Bank m_pGuild->_LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_ITEM, m_container, m_pPlayer->GetGUIDLow(), pFrom->GetItem()->GetEntry(), count); } void Guild::BankMoveItemData::LogAction(MoveItemData* pFrom) const { MoveItemData::LogAction(pFrom); if(!pFrom->IsBank() && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE) && m_pPlayer->GetSession()->GetSecurity() > SEC_PLAYER) // TODO: move to scripts sLog->outCommand(m_pPlayer->GetSession()->GetAccountId(), "GM %s (Account: %u) deposit item: %s (Entry: %d Count: %u) to guild bank (Guild ID: %u)", m_pPlayer->GetName(), m_pPlayer->GetSession()->GetAccountId(), pFrom->GetItem()->GetTemplate()->Name1.c_str(), pFrom->GetItem()->GetEntry(), pFrom->GetItem()->GetCount(), m_pGuild->GetId()); } Item* Guild::BankMoveItemData::_StoreItem(SQLTransaction& trans, BankTab* pTab, Item *pItem, ItemPosCount& pos, bool clone) const { uint8 slotId = uint8(pos.pos); uint32 count = pos.count; if(Item* pItemDest = pTab->GetItem(slotId)) { pItemDest->SetCount(pItemDest->GetCount() + count); pItemDest->FSetState(ITEM_CHANGED); pItemDest->SaveToDB(trans); if(!clone) { pItem->RemoveFromWorld(); pItem->DeleteFromDB(trans); delete pItem; } return pItemDest; } if(clone) pItem = pItem->CloneItem(count); else pItem->SetCount(count); if(pItem && pTab->SetItem(trans, slotId, pItem)) return pItem; return NULL; } // Tries to reserve space for source item. // If item in destination slot exists it must be the item of the same entry // and stack must have enough space to take at least one item. // Returns false if destination item specified and it cannot be used to reserve space. bool Guild::BankMoveItemData::_ReserveSpace(uint8 slotId, Item* pItem, Item* pItemDest, uint32& count) { uint32 requiredSpace = pItem->GetMaxStackCount(); if(pItemDest) { // Make sure source and destination items match and destination item has space for more stacks. if(pItemDest->GetEntry() != pItem->GetEntry() || pItemDest->GetCount() >= pItem->GetMaxStackCount()) return false; requiredSpace -= pItemDest->GetCount(); } // Let's not be greedy, reserve only required space requiredSpace = std::min(requiredSpace, count); // Reserve space ItemPosCount pos(slotId, requiredSpace); if(!pos.isContainedIn(m_vec)) { m_vec.push_back(pos); count -= requiredSpace; } return true; } void Guild::BankMoveItemData::_CanStoreItemInTab(Item* pItem, uint8 skipSlotId, bool merge, uint32& count) { for(uint8 slotId = 0; (slotId < GUILD_BANK_MAX_SLOTS) && (count > 0); ++slotId) { // Skip slot already processed in _CanStore (when destination slot was specified) if(slotId == skipSlotId) continue; Item* pItemDest = m_pGuild->_GetItem(m_container, slotId); if(pItemDest == pItem) pItemDest = NULL; // If merge skip empty, if not merge skip non-empty if((pItemDest != NULL) != merge) continue; _ReserveSpace(slotId, pItem, pItemDest, count); } } InventoryResult Guild::BankMoveItemData::_CanStore(Item* pItem, bool swap) { sLog->outDebug(LOG_FILTER_GUILD, "GUILD STORAGE: CanStore() tab = %u, slot = %u, item = %u, count = %u", m_container, m_slotId, pItem->GetEntry(), pItem->GetCount()); uint32 count = pItem->GetCount(); // Soulbound items cannot be moved if(pItem->IsSoulBound()) return EQUIP_ERR_CANT_DROP_SOULBOUND; // Make sure destination bank tab exists if(m_container >= m_pGuild->_GetPurchasedTabsSize()) return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG; // Slot explicitely specified. Check it. if(m_slotId != NULL_SLOT) { Item* pItemDest = m_pGuild->_GetItem(m_container, m_slotId); // Ignore swapped item (this slot will be empty after move) if((pItemDest == pItem) || swap) pItemDest = NULL; if(!_ReserveSpace(m_slotId, pItem, pItemDest, count)) return EQUIP_ERR_ITEM_CANT_STACK; if(count == 0) return EQUIP_ERR_OK; } // Slot was not specified or it has not enough space for all the items in stack // Search for stacks to merge with if(pItem->GetMaxStackCount() > 1) { _CanStoreItemInTab(pItem, m_slotId, true, count); if(count == 0) return EQUIP_ERR_OK; } // Search free slot for item _CanStoreItemInTab(pItem, m_slotId, false, count); if(count == 0) return EQUIP_ERR_OK; return EQUIP_ERR_BANK_FULL; } /////////////////////////////////////////////////////////////////////////////// // Guild Guild::Guild() : m_id(0), m_leaderGuid(0), m_createdDate(0), m_accountsNumber(0), m_bankMoney(0), m_eventLog(NULL) { memset(&m_bankEventLog, 0, (GUILD_BANK_MAX_TABS + 1) * sizeof(LogHolder*)); } Guild::~Guild() { SQLTransaction temp(NULL); _DeleteBankItems(temp); // Cleanup if(m_eventLog) delete m_eventLog; for(uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId) if(m_bankEventLog[tabId]) delete m_bankEventLog[tabId]; for(Members::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) delete itr->second; } // Creates new guild with default data and saves it to database. bool Guild::Create(Player* pLeader, const std::string& name) { // Check if guild with such name already exists if(sGuildMgr->GetGuildByName(name)) return false; WorldSession* pLeaderSession = pLeader->GetSession(); if(!pLeaderSession) return false; m_id = sGuildMgr->GenerateGuildId(); m_leaderGuid = pLeader->GetGUID(); m_name = name; m_info = ""; m_motd = "No message set."; m_bankMoney = 0; m_createdDate = ::time(NULL); _CreateLogHolders(); sLog->outDebug(LOG_FILTER_GUILD, "GUILD: creating guild [%s] for leader %s (%u)", name.c_str(), pLeader->GetName(), GUID_LOPART(m_leaderGuid)); PreparedStatement* stmt = NULL; SQLTransaction trans = CharacterDatabase.BeginTransaction(); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_MEMBERS); stmt->setUInt32(0, m_id); trans->Append(stmt); uint8 index = 0; stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD); stmt->setUInt32( index, m_id); stmt->setString(++index, name); stmt->setUInt32(++index, GUID_LOPART(m_leaderGuid)); stmt->setString(++index, m_info); stmt->setString(++index, m_motd); stmt->setUInt64(++index, uint32(m_createdDate)); stmt->setUInt32(++index, m_emblemInfo.GetStyle()); stmt->setUInt32(++index, m_emblemInfo.GetColor()); stmt->setUInt32(++index, m_emblemInfo.GetBorderStyle()); stmt->setUInt32(++index, m_emblemInfo.GetBorderColor()); stmt->setUInt32(++index, m_emblemInfo.GetBackgroundColor()); stmt->setUInt64(++index, m_bankMoney); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); // Create default ranks _CreateDefaultGuildRanks(pLeaderSession->GetSessionDbLocaleIndex()); // Add guildmaster bool ret = AddMember(m_leaderGuid, GR_GUILDMASTER); if(ret) // Call scripts on successful create sScriptMgr->OnGuildCreate(this, pLeader, name); return ret; } // Disbands guild and deletes all related data from database void Guild::Disband() { // Call scripts before guild data removed from database sScriptMgr->OnGuildDisband(this); _BroadcastEvent(GE_DISBANDED, 0); // Remove all members while(!m_members.empty()) { Members::const_iterator itr = m_members.begin(); DeleteMember(itr->second->GetGUID(), true); } PreparedStatement* stmt = NULL; SQLTransaction trans = CharacterDatabase.BeginTransaction(); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TABS); stmt->setUInt32(0, m_id); trans->Append(stmt); // Free bank tab used memory and delete items stored in them _DeleteBankItems(trans, true); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_ITEMS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_EVENTLOGS); stmt->setUInt32(0, m_id); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_EVENTLOGS); stmt->setUInt32(0, m_id); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); sGuildMgr->RemoveGuild(m_id); } /////////////////////////////////////////////////////////////////////////////// // HANDLE CLIENT COMMANDS void Guild::HandleRoster(WorldSession* session /*= NULL*/) { // Guess size WorldPacket data(SMSG_GUILD_ROSTER, (4 + m_motd.length() + 1 + m_info.length() + 1 + 4 + _GetRanksSize() * (4 + 4 + GUILD_BANK_MAX_TABS * (4 + 4)) + m_members.size() * 50)); data << uint32(m_members.size()); data << m_motd; data << m_info; data << uint32(_GetRanksSize()); for(Ranks::const_iterator ritr = m_ranks.begin(); ritr != m_ranks.end(); ++ritr) ritr->WritePacket(data); for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) itr->second->WritePacket(data); if(session) session->SendPacket(&data); else BroadcastPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_ROSTER)"); } void Guild::HandleQuery(WorldSession* session) { WorldPacket data(SMSG_GUILD_QUERY_RESPONSE, 8 * 32 + 200); // Guess size data << uint32(m_id); data << m_name; for(uint8 i = 0 ; i < GUILD_RANKS_MAX_COUNT; ++i) // Alwayse show 10 ranks { if(i < _GetRanksSize()) data << m_ranks[i].GetName(); else data << uint8(0); // Empty string } m_emblemInfo.WritePacket(data); data << uint32(0); // Something new in WotLK session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_QUERY_RESPONSE)"); } void Guild::HandleSetMOTD(WorldSession* session, const std::string& motd) { if(m_motd == motd) return; // Player must have rights to set MOTD if(!_HasRankRight(session->GetPlayer(), GR_RIGHT_SETMOTD)) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); else { m_motd = motd; sScriptMgr->OnGuildMOTDChanged(this, motd); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_MOTD); stmt->setString(0, motd); stmt->setUInt32(1, m_id); CharacterDatabase.Execute(stmt); _BroadcastEvent(GE_MOTD, 0, motd.c_str()); } } void Guild::HandleSetInfo(WorldSession* session, const std::string& info) { if(m_info == info) return; // Player must have rights to set guild's info if(!_HasRankRight(session->GetPlayer(), GR_RIGHT_MODIFY_GUILD_INFO)) SendCommandResult(session, GUILD_CREATE_S, ERR_GUILD_PERMISSIONS); else { m_info = info; sScriptMgr->OnGuildInfoChanged(this, info); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_INFO); stmt->setString(0, info); stmt->setUInt32(1, m_id); CharacterDatabase.Execute(stmt); } } void Guild::HandleSetEmblem(WorldSession* session, const EmblemInfo& emblemInfo) { Player* player = session->GetPlayer(); if(!_IsLeader(player)) // "Only pGuild leaders can create emblems." SendSaveEmblemResult(session, ERR_GUILDEMBLEM_NOTGUILDMASTER); else if(!player->HasEnoughMoney(EMBLEM_PRICE)) // "You can't afford to do that." SendSaveEmblemResult(session, ERR_GUILDEMBLEM_NOTENOUGHMONEY); else { player->ModifyMoney(-int32(EMBLEM_PRICE)); m_emblemInfo = emblemInfo; m_emblemInfo.SaveToDB(m_id); // "Guild Emblem saved." SendSaveEmblemResult(session, ERR_GUILDEMBLEM_SUCCESS); HandleQuery(session); } } void Guild::HandleSetLeader(WorldSession* session, const std::string& name) { Player* player = session->GetPlayer(); // Only leader can assign new leader if(!_IsLeader(player)) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); // Old leader must be a member of guild else if(Member* pOldLeader = GetMember(player->GetGUID())) { // New leader must be a member of guild if(Member* pNewLeader = GetMember(session, name)) { _SetLeaderGUID(pNewLeader); pOldLeader->ChangeRank(GR_OFFICER); _BroadcastEvent(GE_LEADER_CHANGED, 0, player->GetName(), name.c_str()); } } else SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); } void Guild::HandleSetBankTabInfo(WorldSession* session, uint8 tabId, const std::string& name, const std::string& icon) { if(BankTab* pTab = GetBankTab(tabId)) { pTab->SetInfo(name, icon); SendBankTabsInfo(session); _SendBankContent(session, tabId); } } void Guild::HandleSetMemberNote(WorldSession* session, const std::string& name, const std::string& note, bool officer) { // Player must have rights to set public/officer note if(!_HasRankRight(session->GetPlayer(), officer ? GR_RIGHT_EOFFNOTE : GR_RIGHT_EPNOTE)) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); // Noted player must be a member of guild else if(Member* pMember = GetMember(session, name)) { if(officer) pMember->SetOfficerNote(note); else pMember->SetPublicNote(note); HandleRoster(session); } } void Guild::HandleSetRankInfo(WorldSession* session, uint8 rankId, const std::string& name, uint32 rights, uint32 moneyPerDay, GuildBankRightsAndSlotsVec rightsAndSlots) { // Only leader can modify ranks if(!_IsLeader(session->GetPlayer())) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); else if(RankInfo* rankInfo = GetRankInfo(rankId)) { sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Changed RankName to '%s', rights to 0x%08X", name.c_str(), rights); rankInfo->SetName(name); rankInfo->SetRights(rights); _SetRankBankMoneyPerDay(rankId, moneyPerDay); uint8 tabId = 0; for(GuildBankRightsAndSlotsVec::const_iterator itr = rightsAndSlots.begin(); itr != rightsAndSlots.end(); ++itr) _SetRankBankTabRightsAndSlots(rankId, tabId++, *itr); HandleQuery(session); HandleRoster(); // Broadcast for tab rights update } } void Guild::HandleBuyBankTab(WorldSession* session, uint8 tabId) { if(tabId != _GetPurchasedTabsSize()) return; uint32 tabCost = _GetGuildBankTabPrice(tabId) * GOLD; if(!tabCost) return; Player* player = session->GetPlayer(); if(!player->HasEnoughMoney(tabCost)) // Should not happen, this is checked by client return; if(!_CreateNewBankTab()) return; player->ModifyMoney(-int32(tabCost)); _SetRankBankMoneyPerDay(player->GetRank(), uint32(GUILD_WITHDRAW_MONEY_UNLIMITED)); _SetRankBankTabRightsAndSlots(player->GetRank(), tabId, GuildBankRightsAndSlots(GUILD_BANK_RIGHT_FULL, uint32(GUILD_WITHDRAW_SLOT_UNLIMITED))); HandleRoster(); // Broadcast for tab rights update SendBankTabsInfo(session); } void Guild::HandleInviteMember(WorldSession* session, const std::string& name) { Player* pInvitee = sObjectAccessor->FindPlayerByName(name.c_str()); if(!pInvitee) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PLAYER_NOT_FOUND_S, name); return; } Player* player = session->GetPlayer(); // Do not show invitations from ignored players if(pInvitee->GetSocial()->HasIgnore(player->GetGUIDLow())) return; if(!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && pInvitee->GetTeam() != player->GetTeam()) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_NOT_ALLIED, name); return; } // Invited player cannot be in another guild if(pInvitee->GetGuildId()) { SendCommandResult(session, GUILD_INVITE_S, ERR_ALREADY_IN_GUILD_S, name); return; } // Invited player cannot be invited if(pInvitee->GetGuildIdInvited()) { SendCommandResult(session, GUILD_INVITE_S, ERR_ALREADY_INVITED_TO_GUILD_S, name); return; } // Inviting player must have rights to invite if(!_HasRankRight(player, GR_RIGHT_INVITE)) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); return; } sLog->outDebug(LOG_FILTER_GUILD, "Player %s invited %s to join his Guild", player->GetName(), name.c_str()); pInvitee->SetGuildIdInvited(m_id); _LogEvent(GUILD_EVENT_LOG_INVITE_PLAYER, player->GetGUIDLow(), pInvitee->GetGUIDLow()); WorldPacket data(SMSG_GUILD_INVITE, 8 + 10); // Guess size data << player->GetName(); data << m_name; pInvitee->GetSession()->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_INVITE)"); } void Guild::HandleAcceptMember(WorldSession* session) { Player* player = session->GetPlayer(); if(!sWorld->getBoolConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_GUILD) && player->GetTeam() != sObjectMgr->GetPlayerTeamByGUID(GetLeaderGUID())) return; if(AddMember(player->GetGUID())) { _LogEvent(GUILD_EVENT_LOG_JOIN_GUILD, player->GetGUIDLow()); _BroadcastEvent(GE_JOINED, player->GetGUID(), player->GetName()); } } void Guild::HandleLeaveMember(WorldSession* session) { Player* player = session->GetPlayer(); // If leader is leaving if(_IsLeader(player)) { if(m_members.size() > 1) // Leader cannot leave if he is not the last member SendCommandResult(session, GUILD_QUIT_S, ERR_GUILD_LEADER_LEAVE); else // Guild is disbanded if leader leaves. Disband(); } else { DeleteMember(player->GetGUID(), false, false); _LogEvent(GUILD_EVENT_LOG_LEAVE_GUILD, player->GetGUIDLow()); _BroadcastEvent(GE_LEFT, player->GetGUID(), player->GetName()); SendCommandResult(session, GUILD_QUIT_S, ERR_PLAYER_NO_MORE_IN_GUILD, m_name); } sCalendarMgr->RemovePlayerGuildEventsAndSignups(player->GetGUID(), GetId()); } void Guild::HandleRemoveMember(WorldSession* session, const std::string& name) { Player* player = session->GetPlayer(); // Player must have rights to remove members if(!_HasRankRight(player, GR_RIGHT_REMOVE)) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); // Removed player must be a member of guild else if(Member* pMember = GetMember(session, name)) { // Leader cannot be removed if(pMember->IsRank(GR_GUILDMASTER)) SendCommandResult(session, GUILD_QUIT_S, ERR_GUILD_LEADER_LEAVE); // Do not allow to remove player with the same rank or higher else if(pMember->IsRankNotLower(player->GetRank())) SendCommandResult(session, GUILD_QUIT_S, ERR_GUILD_RANK_TOO_HIGH_S, name); else { const uint64& guid = pMember->GetGUID(); // After call to DeleteMember pointer to member becomes invalid DeleteMember(guid, false, true); _LogEvent(GUILD_EVENT_LOG_UNINVITE_PLAYER, player->GetGUIDLow(), GUID_LOPART(guid)); _BroadcastEvent(GE_REMOVED, 0, name.c_str(), player->GetName()); } } } void Guild::HandleUpdateMemberRank(WorldSession* session, const std::string& name, bool demote) { Player* player = session->GetPlayer(); // Player must have rights to promote if(!_HasRankRight(player, demote ? GR_RIGHT_DEMOTE : GR_RIGHT_PROMOTE)) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); // Promoted player must be a member of guild else if(Member* pMember = GetMember(session, name)) { // Player cannot promote himself if(pMember->IsSamePlayer(player->GetGUID())) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_NAME_INVALID); return; } if(demote) { // Player can demote only lower rank members if(pMember->IsRankNotLower(player->GetRank())) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_RANK_TOO_HIGH_S, name); return; } // Lowest rank cannot be demoted if(pMember->GetRankId() >= _GetLowestRankId()) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_RANK_TOO_LOW_S, name); return; } } else { // Allow to promote only to lower rank than member's rank // pMember->GetRank() + 1 is the highest rank that current player can promote to if(pMember->IsRankNotLower(player->GetRank() + 1)) { SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_RANK_TOO_HIGH_S, name); return; } } // When promoting player, rank is decreased, when demoting - increased uint32 newRankId = pMember->GetRankId() + (demote ? 1 : -1); pMember->ChangeRank(newRankId); _LogEvent(demote ? GUILD_EVENT_LOG_DEMOTE_PLAYER : GUILD_EVENT_LOG_PROMOTE_PLAYER, player->GetGUIDLow(), GUID_LOPART(pMember->GetGUID()), newRankId); _BroadcastEvent(demote ? GE_DEMOTION : GE_PROMOTION, 0, player->GetName(), name.c_str(), _GetRankName(newRankId).c_str()); } } void Guild::HandleAddNewRank(WorldSession* session, const std::string& name) { if(_GetRanksSize() >= GUILD_RANKS_MAX_COUNT) return; // Only leader can add new rank if(!_IsLeader(session->GetPlayer())) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); else { _CreateRank(name, GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); HandleQuery(session); HandleRoster(); // Broadcast for tab rights update } } void Guild::HandleRemoveLowestRank(WorldSession* session) { // Cannot remove rank if total count is minimum allowed by the client if(_GetRanksSize() <= GUILD_RANKS_MIN_COUNT) return; // Only leader can delete ranks if(!_IsLeader(session->GetPlayer())) SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); else { uint8 rankId = _GetLowestRankId(); // Delete bank rights for rank PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS_FOR_RANK); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, rankId); CharacterDatabase.Execute(stmt); // Delete rank stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_LOWEST_RANK); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, rankId); CharacterDatabase.Execute(stmt); m_ranks.pop_back(); HandleQuery(session); HandleRoster(); // Broadcast for tab rights update } } void Guild::HandleMemberDepositMoney(WorldSession* session, uint32 amount) { if(!_GetPurchasedTabsSize()) return; // No guild bank tabs - no money in bank Player* player = session->GetPlayer(); // Call script after validation and before money transfer. sScriptMgr->OnGuildMemberDepositMoney(this, player, amount); SQLTransaction trans = CharacterDatabase.BeginTransaction(); // Add money to bank _ModifyBankMoney(trans, amount, true); // Remove money from player player->ModifyMoney(-int32(amount)); player->SaveGoldToDB(trans); // Log GM action (TODO: move to scripts) if(player->GetSession()->GetSecurity() > SEC_PLAYER && sWorld->getBoolConfig(CONFIG_GM_LOG_TRADE)) { sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) deposit money (Amount: %u) to pGuild bank (Guild ID %u)", player->GetName(), player->GetSession()->GetAccountId(), amount, m_id); } // Log guild bank event _LogBankEvent(trans, GUILD_BANK_LOG_DEPOSIT_MONEY, uint8(0), player->GetGUIDLow(), amount); CharacterDatabase.CommitTransaction(trans); SendBankTabsInfo(session); _SendBankContent(session, 0); _SendBankMoneyUpdate(session); } bool Guild::HandleMemberWithdrawMoney(WorldSession* session, uint32 amount, bool repair) { if(!_GetPurchasedTabsSize()) return false; // No guild bank tabs - no money if(m_bankMoney < amount) // Not enough money in bank return false; Player* player = session->GetPlayer(); if(!_HasRankRight(player, repair ? GR_RIGHT_WITHDRAW_REPAIR : GR_RIGHT_WITHDRAW_GOLD)) return false; uint32 remainingMoney = _GetMemberRemainingMoney(player->GetGUID()); if(!remainingMoney) return false; if(remainingMoney < amount) return false; // Call script after validation and before money transfer. sScriptMgr->OnGuildMemberWitdrawMoney(this, player, amount, repair); SQLTransaction trans = CharacterDatabase.BeginTransaction(); // Update remaining money amount if(remainingMoney < uint32(GUILD_WITHDRAW_MONEY_UNLIMITED)) if(Member* pMember = GetMember(player->GetGUID())) pMember->DecreaseBankRemainingValue(trans, GUILD_BANK_MAX_TABS, amount); // Remove money from bank _ModifyBankMoney(trans, amount, false); // Add money to player (if required) if(!repair) { player->ModifyMoney(amount); player->SaveGoldToDB(trans); } // Log guild bank event _LogBankEvent(trans, repair ? GUILD_BANK_LOG_REPAIR_MONEY : GUILD_BANK_LOG_WITHDRAW_MONEY, uint8(0), player->GetGUIDLow(), amount); CharacterDatabase.CommitTransaction(trans); SendMoneyInfo(session); if(!repair) { SendBankTabsInfo(session); _SendBankContent(session, 0); _SendBankMoneyUpdate(session); } return true; } void Guild::HandleMemberLogout(WorldSession* session) { Player* player = session->GetPlayer(); if(Member* pMember = GetMember(player->GetGUID())) { pMember->SetStats(player); pMember->UpdateLogoutTime(); } _BroadcastEvent(GE_SIGNED_OFF, player->GetGUID(), player->GetName()); } void Guild::HandleDisband(WorldSession* session) { // Only leader can disband guild if(!_IsLeader(session->GetPlayer())) Guild::SendCommandResult(session, GUILD_INVITE_S, ERR_GUILD_PERMISSIONS); else { Disband(); sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Guild Successfully Disbanded"); } } /////////////////////////////////////////////////////////////////////////////// // Send data to client void Guild::SendInfo(WorldSession* session) const { WorldPacket data(SMSG_GUILD_INFO, m_name.size() + 4 + 4 + 4); data << m_name; data.AppendPackedTime(m_createdDate); // 3.x (prev. year + month + day) data << uint32(m_members.size()); // Number of members data << m_accountsNumber; // Number of accounts session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_INFO)"); } void Guild::SendEventLog(WorldSession* session) const { WorldPacket data(MSG_GUILD_EVENT_LOG_QUERY, 1 + m_eventLog->GetSize() * (1 + 8 + 4)); m_eventLog->WritePacket(data); session->SendPacket(&data); sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (MSG_GUILD_EVENT_LOG_QUERY)"); } void Guild::SendBankLog(WorldSession* session, uint8 tabId) const { // GUILD_BANK_MAX_TABS send by client for money log if(tabId < _GetPurchasedTabsSize() || tabId == GUILD_BANK_MAX_TABS) { const LogHolder* pLog = m_bankEventLog[tabId]; WorldPacket data(MSG_GUILD_BANK_LOG_QUERY, pLog->GetSize() * (4 * 4 + 1) + 1 + 1); data << uint8(tabId); pLog->WritePacket(data); session->SendPacket(&data); sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (MSG_GUILD_BANK_LOG_QUERY)"); } } void Guild::SendBankTabData(WorldSession* session, uint8 tabId) const { if(tabId < _GetPurchasedTabsSize()) { SendMoneyInfo(session); _SendBankContent(session, tabId); } } void Guild::SendBankTabsInfo(WorldSession* session) const { WorldPacket data(SMSG_GUILD_BANK_LIST, 500); data << uint64(m_bankMoney); data << uint8(0); // TabInfo packet must be for tabId 0 data << uint32(_GetMemberRemainingSlots(session->GetPlayer()->GetGUID(), 0)); data << uint8(1); // Tell client that this packet includes tab info data << uint8(_GetPurchasedTabsSize()); // Number of tabs for(uint8 i = 0; i < _GetPurchasedTabsSize(); ++i) m_bankTabs[i]->WriteInfoPacket(data); data << uint8(0); // Do not send tab content session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_BANK_LIST)"); } void Guild::SendBankTabText(WorldSession* session, uint8 tabId) const { if(const BankTab* pTab = GetBankTab(tabId)) pTab->SendText(this, session); } void Guild::SendPermissions(WorldSession* session) const { const uint64& guid = session->GetPlayer()->GetGUID(); uint8 rankId = session->GetPlayer()->GetRank(); WorldPacket data(MSG_GUILD_PERMISSIONS, 4 * 15 + 1); data << uint32(rankId); data << uint32(_GetRankRights(rankId)); data << uint32(_GetMemberRemainingMoney(guid)); data << uint8 (_GetPurchasedTabsSize()); // Why sending all info when not all tabs are purchased??? for(uint8 tabId = 0; tabId < GUILD_BANK_MAX_TABS; ++tabId) { data << uint32(_GetRankBankTabRights(rankId, tabId)); data << uint32(_GetMemberRemainingSlots(guid, tabId)); } session->SendPacket(&data); sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent (MSG_GUILD_PERMISSIONS)"); } void Guild::SendMoneyInfo(WorldSession* session) const { WorldPacket data(MSG_GUILD_BANK_MONEY_WITHDRAWN, 4); data << uint32(_GetMemberRemainingMoney(session->GetPlayer()->GetGUID())); session->SendPacket(&data); sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent MSG_GUILD_BANK_MONEY_WITHDRAWN"); } void Guild::SendLoginInfo(WorldSession* session) const { WorldPacket data(SMSG_GUILD_EVENT, 1 + 1 + m_motd.size() + 1); data << uint8(GE_MOTD); data << uint8(1); data << m_motd; session->SendPacket(&data); sLog->outDebug(LOG_FILTER_GUILD, "WORLD: Sent guild MOTD (SMSG_GUILD_EVENT)"); SendBankTabsInfo(session); _BroadcastEvent(GE_SIGNED_ON, session->GetPlayer()->GetGUID(), session->GetPlayer()->GetName()); } /////////////////////////////////////////////////////////////////////////////// // Loading methods bool Guild::LoadFromDB(Field* fields) { m_id = fields[0].GetUInt32(); m_name = fields[1].GetString(); m_leaderGuid = MAKE_NEW_GUID(fields[2].GetUInt32(), 0, HIGHGUID_PLAYER); m_emblemInfo.LoadFromDB(fields); m_info = fields[8].GetString(); m_motd = fields[9].GetString(); m_createdDate = time_t(fields[10].GetUInt32()); m_bankMoney = fields[11].GetUInt64(); uint8 purchasedTabs = uint8(fields[12].GetUInt32()); if(purchasedTabs > GUILD_BANK_MAX_TABS) purchasedTabs = GUILD_BANK_MAX_TABS; m_bankTabs.resize(purchasedTabs); for(uint8 i = 0; i < purchasedTabs; ++i) m_bankTabs[i] = new BankTab(m_id, i); _CreateLogHolders(); return true; } void Guild::LoadRankFromDB(Field* fields) { RankInfo rankInfo(m_id); rankInfo.LoadFromDB(fields); m_ranks.push_back(rankInfo); } bool Guild::LoadMemberFromDB(Field* fields) { uint32 lowguid = fields[1].GetUInt32(); Member *pMember = new Member(m_id, MAKE_NEW_GUID(lowguid, 0, HIGHGUID_PLAYER), fields[2].GetUInt8()); if(!pMember->LoadFromDB(fields)) { _DeleteMemberFromDB(lowguid); delete pMember; return false; } m_members[lowguid] = pMember; return true; } void Guild::LoadBankRightFromDB(Field* fields) { // rights slots GuildBankRightsAndSlots rightsAndSlots(fields[3].GetUInt8(), fields[4].GetUInt32()); // rankId tabId _SetRankBankTabRightsAndSlots(fields[2].GetUInt8(), fields[1].GetUInt8(), rightsAndSlots, false); } bool Guild::LoadEventLogFromDB(Field* fields) { if(m_eventLog->CanInsert()) { m_eventLog->LoadEvent(new EventLogEntry( m_id, // guild id fields[1].GetUInt32(), // guid time_t(fields[6].GetUInt32()), // timestamp GuildEventLogTypes(fields[2].GetUInt8()), // event type fields[3].GetUInt32(), // player guid 1 fields[4].GetUInt32(), // player guid 2 fields[5].GetUInt8())); // rank return true; } return false; } bool Guild::LoadBankEventLogFromDB(Field* fields) { uint8 dbTabId = fields[1].GetUInt8(); bool isMoneyTab = (dbTabId == GUILD_BANK_MONEY_LOGS_TAB); if(dbTabId < _GetPurchasedTabsSize() || isMoneyTab) { uint8 tabId = isMoneyTab ? uint8(GUILD_BANK_MAX_TABS) : dbTabId; LogHolder* pLog = m_bankEventLog[tabId]; if(pLog->CanInsert()) { uint32 guid = fields[2].GetUInt32(); GuildBankEventLogTypes eventType = GuildBankEventLogTypes(fields[3].GetUInt8()); if(BankEventLogEntry::IsMoneyEvent(eventType)) { if(!isMoneyTab) { sLog->outError("GuildBankEventLog ERROR: MoneyEvent(LogGuid: %u, Guild: %u) does not belong to money tab (%u), ignoring...", guid, m_id, dbTabId); return false; } } else if(isMoneyTab) { sLog->outError("GuildBankEventLog ERROR: non-money event (LogGuid: %u, Guild: %u) belongs to money tab, ignoring...", guid, m_id); return false; } pLog->LoadEvent(new BankEventLogEntry( m_id, // guild id guid, // guid time_t(fields[8].GetUInt32()), // timestamp dbTabId, // tab id eventType, // event type fields[4].GetUInt32(), // player guid fields[5].GetUInt32(), // item or money fields[6].GetUInt16(), // itam stack count fields[7].GetUInt8())); // dest tab id } } return true; } bool Guild::LoadBankTabFromDB(Field* fields) { uint32 tabId = fields[1].GetUInt8(); if(tabId >= _GetPurchasedTabsSize()) { sLog->outError("Invalid tab (tabId: %u) in guild bank, skipped.", tabId); return false; } return m_bankTabs[tabId]->LoadFromDB(fields); } bool Guild::LoadBankItemFromDB(Field* fields) { uint8 tabId = fields[12].GetUInt8(); if(tabId >= _GetPurchasedTabsSize()) { sLog->outError("Invalid tab for item (GUID: %u, id: #%u) in guild bank, skipped.", fields[14].GetUInt32(), fields[15].GetUInt32()); return false; } return m_bankTabs[tabId]->LoadItemFromDB(fields); } // Validates guild data loaded from database. Returns false if guild should be deleted. bool Guild::Validate() { // Validate ranks data // GUILD RANKS represent a sequence starting from 0 = GUILD_MASTER (ALL PRIVILEGES) to max 9 (lowest privileges). // The lower rank id is considered higher rank - so promotion does rank-- and demotion does rank++ // Between ranks in sequence cannot be gaps - so 0, 1, 2, 4 is impossible // Min ranks count is 5 and max is 10. bool broken_ranks = false; if(_GetRanksSize() < GUILD_RANKS_MIN_COUNT || _GetRanksSize() > GUILD_RANKS_MAX_COUNT) { sLog->outError("Guild %u has invalid number of ranks, creating new...", m_id); broken_ranks = true; } else { for(uint8 rankId = 0; rankId < _GetRanksSize(); ++rankId) { RankInfo* rankInfo = GetRankInfo(rankId); if(rankInfo->GetId() != rankId) { sLog->outError("Guild %u has broken rank id %u, creating default set of ranks...", m_id, rankId); broken_ranks = true; } } } if(broken_ranks) { m_ranks.clear(); _CreateDefaultGuildRanks(DEFAULT_LOCALE); } // Validate members' data for(Members::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(itr->second->GetRankId() > _GetRanksSize()) itr->second->ChangeRank(_GetLowestRankId()); // Repair the structure of the guild. // If the guildmaster doesn't exist or isn't member of the guild // attempt to promote another member. Member* pLeader = GetMember(m_leaderGuid); if(!pLeader) { DeleteMember(m_leaderGuid); // If no more members left, disband guild if(m_members.empty()) { Disband(); return false; } } else if(!pLeader->IsRank(GR_GUILDMASTER)) _SetLeaderGUID(pLeader); _UpdateAccountsNumber(); return true; } /////////////////////////////////////////////////////////////////////////////// // Broadcasts void Guild::BroadcastToGuild(WorldSession* session, bool officerOnly, const std::string& msg, uint32 language) const { if(session && session->GetPlayer() && _HasRankRight(session->GetPlayer(), officerOnly ? GR_RIGHT_OFFCHATSPEAK : GR_RIGHT_GCHATSPEAK)) { WorldPacket data; ChatHandler::FillMessageData(&data, session, officerOnly ? CHAT_MSG_OFFICER : CHAT_MSG_GUILD, language, NULL, 0, msg.c_str(), NULL); for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(Player* player = itr->second->FindPlayer()) if(player->GetSession() && _HasRankRight(player, officerOnly ? GR_RIGHT_OFFCHATLISTEN : GR_RIGHT_GCHATLISTEN) && !player->GetSocial()->HasIgnore(session->GetPlayer()->GetGUIDLow())) player->GetSession()->SendPacket(&data); } } void Guild::BroadcastPacketToRank(WorldPacket* packet, uint8 rankId) const { for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(itr->second->IsRank(rankId)) if(Player* player = itr->second->FindPlayer()) player->GetSession()->SendPacket(packet); } void Guild::BroadcastPacket(WorldPacket* packet) const { for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(Player* player = itr->second->FindPlayer()) player->GetSession()->SendPacket(packet); } void Guild::MassInviteToEvent(WorldSession* session, uint32 minLevel, uint32 maxLevel, uint32 minRank) { uint32 count = 0; WorldPacket data(SMSG_CALENDAR_FILTER_GUILD); data << uint32(count); // count placeholder for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) { // not sure if needed, maybe client checks it as well if(count >= CALENDAR_MAX_INVITES) { if(Player* player = session->GetPlayer()) sCalendarMgr->SendCalendarCommandResult(player->GetGUID(), CALENDAR_ERROR_INVITES_EXCEEDED); return; } Member* member = itr->second; uint32 level = Player::GetLevelFromDB(member->GetGUID()); if(member->GetGUID() != session->GetPlayer()->GetGUID() && level >= minLevel && level <= maxLevel && member->IsRankNotLower(minRank)) { data.appendPackGUID(member->GetGUID()); data << uint8(0); // unk ++count; } } data.put<uint32>(0, count); session->SendPacket(&data); } /////////////////////////////////////////////////////////////////////////////// // Members handling bool Guild::AddMember(const uint64& guid, uint8 rankId) { Player* player = sObjectMgr->GetPlayer(guid); // Player cannot be in guild if(player) { if(player->GetGuildId() != 0) return false; } else if(Player::GetGuildIdFromDB(guid) != 0) return false; // Remove all player signs from another petitions // This will be prevent attempt to join many guilds and corrupt guild data integrity Player::RemovePetitionsAndSigns(guid, GUILD_CHARTER_TYPE); uint32 lowguid = GUID_LOPART(guid); // If rank was not passed, assing lowest possible rank if(rankId == GUILD_RANK_NONE) rankId = _GetLowestRankId(); Member* pMember = new Member(m_id, guid, rankId); if(player) pMember->SetStats(player); else { bool ok = false; // Player must exist PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_LOAD_CHAR_DATA_FOR_GUILD); stmt->setUInt32(0, lowguid); if(PreparedQueryResult result = CharacterDatabase.Query(stmt)) { Field* fields = result->Fetch(); pMember->SetStats( fields[0].GetString(), fields[1].GetUInt8(), fields[2].GetUInt8(), fields[3].GetUInt16(), fields[4].GetUInt32()); ok = pMember->CheckStats(); } if(!ok) { delete pMember; return false; } } m_members[lowguid] = pMember; SQLTransaction trans(NULL); pMember->SaveToDB(trans); // If player not in game data in will be loaded from guild tables, so no need to update it! if(player) { player->SetInGuild(m_id); player->SetRank(rankId); player->SetGuildIdInvited(0); } _UpdateAccountsNumber(); // Call scripts if member was succesfully added (and stored to database) sScriptMgr->OnGuildAddMember(this, player, rankId); return true; } void Guild::DeleteMember(const uint64& guid, bool isDisbanding, bool isKicked) { uint32 lowguid = GUID_LOPART(guid); Player* player = sObjectMgr->GetPlayer(guid); // Guild master can be deleted when loading guild and guid doesn't exist in characters table // or when he is removed from guild by gm command if(m_leaderGuid == guid && !isDisbanding) { Member* oldLeader = NULL; Member* newLeader = NULL; for(Guild::Members::iterator i = m_members.begin(); i != m_members.end(); ++i) { if(i->first == lowguid) oldLeader = i->second; else if(!newLeader || newLeader->GetRankId() > i->second->GetRankId()) newLeader = i->second; } if(!newLeader) { Disband(); return; } _SetLeaderGUID(newLeader); // If player not online data in data field will be loaded from guild tabs no need to update it !! if(Player* newLeaderPlayer = newLeader->FindPlayer()) newLeaderPlayer->SetRank(GR_GUILDMASTER); // If leader does not exist (at guild loading with deleted leader) do not send broadcasts if(oldLeader) { _BroadcastEvent(GE_LEADER_CHANGED, 0, oldLeader->GetName().c_str(), newLeader->GetName().c_str()); _BroadcastEvent(GE_LEFT, guid, oldLeader->GetName().c_str()); } } // Call script on remove before member is acutally removed from guild (and database) sScriptMgr->OnGuildRemoveMember(this, player, isDisbanding, isKicked); if(Member* pMember = GetMember(guid)) delete pMember; m_members.erase(lowguid); // If player not online data in data field will be loaded from guild tabs no need to update it !! if(player) { player->SetInGuild(0); player->SetRank(0); } _DeleteMemberFromDB(lowguid); if(!isDisbanding) _UpdateAccountsNumber(); } bool Guild::ChangeMemberRank(const uint64& guid, uint8 newRank) { if(newRank <= _GetLowestRankId()) // Validate rank (allow only existing ranks) if(Member* pMember = GetMember(guid)) { pMember->ChangeRank(newRank); return true; } return false; } /////////////////////////////////////////////////////////////////////////////// // Bank (items move) void Guild::SwapItems(Player* player, uint8 tabId, uint8 slotId, uint8 destTabId, uint8 destSlotId, uint32 splitedAmount) { if(tabId >= _GetPurchasedTabsSize() || slotId >= GUILD_BANK_MAX_SLOTS || destTabId >= _GetPurchasedTabsSize() || destSlotId >= GUILD_BANK_MAX_SLOTS) return; if(tabId == destTabId && slotId == destSlotId) return; BankMoveItemData from(this, player, tabId, slotId); BankMoveItemData to(this, player, destTabId, destSlotId); _MoveItems(&from, &to, splitedAmount); } void Guild::SwapItemsWithInventory(Player* player, bool toChar, uint8 tabId, uint8 slotId, uint8 playerBag, uint8 playerSlotId, uint32 splitedAmount) { if((slotId >= GUILD_BANK_MAX_SLOTS && slotId != NULL_SLOT) || tabId >= _GetPurchasedTabsSize()) return; BankMoveItemData bankData(this, player, tabId, slotId); PlayerMoveItemData charData(this, player, playerBag, playerSlotId); if(toChar) _MoveItems(&bankData, &charData, splitedAmount); else _MoveItems(&charData, &bankData, splitedAmount); } /////////////////////////////////////////////////////////////////////////////// // Bank tabs void Guild::SetBankTabText(uint8 tabId, const std::string& text) { if(BankTab* pTab = GetBankTab(tabId)) { pTab->SetText(text); pTab->SendText(this, NULL); } } /////////////////////////////////////////////////////////////////////////////// // Private methods void Guild::_CreateLogHolders() { m_eventLog = new LogHolder(m_id, sWorld->getIntConfig(CONFIG_GUILD_EVENT_LOG_COUNT)); for(uint8 tabId = 0; tabId <= GUILD_BANK_MAX_TABS; ++tabId) m_bankEventLog[tabId] = new LogHolder(m_id, sWorld->getIntConfig(CONFIG_GUILD_BANK_EVENT_LOG_COUNT)); } bool Guild::_CreateNewBankTab() { if(_GetPurchasedTabsSize() >= GUILD_BANK_MAX_TABS) return false; uint8 tabId = _GetPurchasedTabsSize(); // Next free id m_bankTabs.push_back(new BankTab(m_id, tabId)); PreparedStatement* stmt = NULL; SQLTransaction trans = CharacterDatabase.BeginTransaction(); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_TAB); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, tabId); trans->Append(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_BANK_TAB); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, tabId); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); return true; } void Guild::_CreateDefaultGuildRanks(LocaleConstant loc) { PreparedStatement* stmt = NULL; stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_RANKS); stmt->setUInt32(0, m_id); CharacterDatabase.Execute(stmt); stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_BANK_RIGHTS); stmt->setUInt32(0, m_id); CharacterDatabase.Execute(stmt); _CreateRank(sObjectMgr->GetTrinityString(LANG_GUILD_MASTER, loc), GR_RIGHT_ALL); _CreateRank(sObjectMgr->GetTrinityString(LANG_GUILD_OFFICER, loc), GR_RIGHT_ALL); _CreateRank(sObjectMgr->GetTrinityString(LANG_GUILD_VETERAN, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); _CreateRank(sObjectMgr->GetTrinityString(LANG_GUILD_MEMBER, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); _CreateRank(sObjectMgr->GetTrinityString(LANG_GUILD_INITIATE, loc), GR_RIGHT_GCHATLISTEN | GR_RIGHT_GCHATSPEAK); } void Guild::_CreateRank(const std::string& name, uint32 rights) { if(_GetRanksSize() >= GUILD_RANKS_MAX_COUNT) return; // Ranks represent sequence 0, 1, 2, ... where 0 means guildmaster uint8 newRankId = _GetRanksSize(); RankInfo info(m_id, newRankId, name, rights, 0); m_ranks.push_back(info); SQLTransaction trans = CharacterDatabase.BeginTransaction(); for(uint8 i = 0; i < _GetPurchasedTabsSize(); ++i) { // Create bank rights with default values PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_ADD_GUILD_BANK_RIGHT_DEFAULT); stmt->setUInt32(0, m_id); stmt->setUInt8 (1, i); stmt->setUInt8 (2, newRankId); trans->Append(stmt); } info.SaveToDB(trans); CharacterDatabase.CommitTransaction(trans); } // Updates the number of accounts that are in the guild // Player may have many characters in the guild, but with the same account void Guild::_UpdateAccountsNumber() { // We use a set to be sure each element will be unique std::set<uint32> accountsIdSet; for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) accountsIdSet.insert(itr->second->GetAccountId()); m_accountsNumber = accountsIdSet.size(); } // Detects if player is the guild master. // Check both leader guid and player's rank (otherwise multiple feature with // multiple guild masters won't work) bool Guild::_IsLeader(Player* player) const { if(player->GetGUID() == m_leaderGuid) return true; if(const Member* pMember = GetMember(player->GetGUID())) return pMember->IsRank(GR_GUILDMASTER); return false; } void Guild::_DeleteBankItems(SQLTransaction& trans, bool removeItemsFromDB) { for(uint8 tabId = 0; tabId < _GetPurchasedTabsSize(); ++tabId) { m_bankTabs[tabId]->Delete(trans, removeItemsFromDB); delete m_bankTabs[tabId]; m_bankTabs[tabId] = NULL; } m_bankTabs.clear(); } bool Guild::_ModifyBankMoney(SQLTransaction& trans, const uint64& amount, bool add) { if(add) m_bankMoney += amount; else { // Check if there is enough money in bank. if(m_bankMoney < amount) return false; m_bankMoney -= amount; } PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_BANK_MONEY); stmt->setUInt64(0, m_bankMoney); stmt->setUInt32(1, m_id); trans->Append(stmt); return true; } void Guild::_SetLeaderGUID(Member* pLeader) { if(!pLeader) return; m_leaderGuid = pLeader->GetGUID(); pLeader->ChangeRank(GR_GUILDMASTER); PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SET_GUILD_LEADER); stmt->setUInt32(0, GUID_LOPART(m_leaderGuid)); stmt->setUInt32(1, m_id); CharacterDatabase.Execute(stmt); } void Guild::_SetRankBankMoneyPerDay(uint8 rankId, uint32 moneyPerDay) { if(RankInfo* rankInfo = GetRankInfo(rankId)) { for(Members::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(itr->second->IsRank(rankId)) itr->second->ResetMoneyTime(); rankInfo->SetBankMoneyPerDay(moneyPerDay); } } void Guild::_SetRankBankTabRightsAndSlots(uint8 rankId, uint8 tabId, GuildBankRightsAndSlots rightsAndSlots, bool saveToDB) { if(tabId >= _GetPurchasedTabsSize()) return; if(RankInfo* rankInfo = GetRankInfo(rankId)) { for(Members::iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(itr->second->IsRank(rankId)) itr->second->ResetTabTimes(); rankInfo->SetBankTabSlotsAndRights(tabId, rightsAndSlots, saveToDB); } } inline std::string Guild::_GetRankName(uint8 rankId) const { if(const RankInfo* rankInfo = GetRankInfo(rankId)) return rankInfo->GetName(); return "<unknown>"; } inline uint32 Guild::_GetRankRights(uint8 rankId) const { if(const RankInfo* rankInfo = GetRankInfo(rankId)) return rankInfo->GetRights(); return 0; } inline uint32 Guild::_GetRankBankMoneyPerDay(uint8 rankId) const { if(const RankInfo* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankMoneyPerDay(); return 0; } inline uint32 Guild::_GetRankBankTabSlotsPerDay(uint8 rankId, uint8 tabId) const { if(tabId < _GetPurchasedTabsSize()) if(const RankInfo* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabSlotsPerDay(tabId); return 0; } inline uint8 Guild::_GetRankBankTabRights(uint8 rankId, uint8 tabId) const { if(const RankInfo* rankInfo = GetRankInfo(rankId)) return rankInfo->GetBankTabRights(tabId); return 0; } inline uint32 Guild::_GetMemberRemainingSlots(const uint64& guid, uint8 tabId) const { if(const Member* pMember = GetMember(guid)) return pMember->GetBankRemainingValue(tabId, this); return 0; } inline uint32 Guild::_GetMemberRemainingMoney(const uint64& guid) const { if(const Member* pMember = GetMember(guid)) return pMember->GetBankRemainingValue(GUILD_BANK_MAX_TABS, this); return 0; } inline void Guild::_DecreaseMemberRemainingSlots(SQLTransaction& trans, const uint64& guid, uint8 tabId) { // Remaining slots must be more then 0 if(uint32 remainingSlots = _GetMemberRemainingSlots(guid, tabId)) // Ignore guild master if(remainingSlots < uint32(GUILD_WITHDRAW_SLOT_UNLIMITED)) if(Member* pMember = GetMember(guid)) pMember->DecreaseBankRemainingValue(trans, tabId, 1); } inline bool Guild::_MemberHasTabRights(const uint64& guid, uint8 tabId, uint32 rights) const { if(const Member* pMember = GetMember(guid)) { // Leader always has full rights if(pMember->IsRank(GR_GUILDMASTER) || m_leaderGuid == guid) return true; return (_GetRankBankTabRights(pMember->GetRankId(), tabId) & rights) == rights; } return false; } // Add new event log record inline void Guild::_LogEvent(GuildEventLogTypes eventType, uint32 playerGuid1, uint32 playerGuid2, uint8 newRank) { SQLTransaction trans = CharacterDatabase.BeginTransaction(); m_eventLog->AddEvent(trans, new EventLogEntry(m_id, m_eventLog->GetNextGUID(), eventType, playerGuid1, playerGuid2, newRank)); CharacterDatabase.CommitTransaction(trans); sScriptMgr->OnGuildEvent(this, uint8(eventType), playerGuid1, playerGuid2, newRank); } // Add new bank event log record void Guild::_LogBankEvent(SQLTransaction& trans, GuildBankEventLogTypes eventType, uint8 tabId, uint32 lowguid, uint32 itemOrMoney, uint16 itemStackCount, uint8 destTabId) { if(tabId > GUILD_BANK_MAX_TABS) return; uint8 dbTabId = tabId; if(BankEventLogEntry::IsMoneyEvent(eventType)) { tabId = GUILD_BANK_MAX_TABS; dbTabId = GUILD_BANK_MONEY_LOGS_TAB; } LogHolder* pLog = m_bankEventLog[tabId]; pLog->AddEvent(trans, new BankEventLogEntry(m_id, pLog->GetNextGUID(), eventType, dbTabId, lowguid, itemOrMoney, itemStackCount, destTabId)); sScriptMgr->OnGuildBankEvent(this, uint8(eventType), tabId, lowguid, itemOrMoney, itemStackCount, destTabId); } inline Item* Guild::_GetItem(uint8 tabId, uint8 slotId) const { if(const BankTab* tab = GetBankTab(tabId)) return tab->GetItem(slotId); return NULL; } inline void Guild::_RemoveItem(SQLTransaction& trans, uint8 tabId, uint8 slotId) { if(BankTab* pTab = GetBankTab(tabId)) pTab->SetItem(trans, slotId, NULL); } void Guild::_MoveItems(MoveItemData* pSrc, MoveItemData* pDest, uint32 splitedAmount) { // 1. Initialize source item if(!pSrc->InitItem()) return; // No source item // 2. Check source item if(!pSrc->CheckItem(splitedAmount)) return; // Source item or splited amount is invalid /* if(pItemSrc->GetCount() == 0) { sLog->outCrash("Guild::SwapItems: Player %s(GUIDLow: %u) tried to move item %u from tab %u slot %u to tab %u slot %u, but item %u has a stack of zero!", player->GetName(), player->GetGUIDLow(), pItemSrc->GetEntry(), tabId, slotId, destTabId, destSlotId, pItemSrc->GetEntry()); //return; // Commented out for now, uncomment when it's verified that this causes a crash!! } // */ // 3. Check destination rights if(!pDest->HasStoreRights(pSrc)) return; // Player has no rights to store item in destination // 4. Check source withdraw rights if(!pSrc->HasWithdrawRights(pDest)) return; // Player has no rights to withdraw items from source // 5. Check split if(splitedAmount) { // 5.1. Clone source item if(!pSrc->CloneItem(splitedAmount)) return; // Item could not be cloned // 5.2. Move splited item to destination _DoItemsMove(pSrc, pDest, true, splitedAmount); } else // 6. No split { // 6.1. Try to merge items in destination (pDest->GetItem() == NULL) if(!_DoItemsMove(pSrc, pDest, false)) // Item could not be merged { // 6.2. Try to swap items // 6.2.1. Initialize destination item if(!pDest->InitItem()) return; // 6.2.2. Check rights to store item in source (opposite direction) if(!pSrc->HasStoreRights(pDest)) return; // Player has no rights to store item in source (opposite direction) if(!pDest->HasWithdrawRights(pSrc)) return; // Player has no rights to withdraw item from destination (opposite direction) // 6.2.3. Swap items (pDest->GetItem() != NULL) _DoItemsMove(pSrc, pDest, true); } } // 7. Send changes _SendBankContentUpdate(pSrc, pDest); } bool Guild::_DoItemsMove(MoveItemData* pSrc, MoveItemData* pDest, bool sendError, uint32 splitedAmount) { Item* pDestItem = pDest->GetItem(); bool swap = (pDestItem != NULL); Item* pSrcItem = pSrc->GetItem(splitedAmount); // 1. Can store source item in destination if(!pDest->CanStore(pSrcItem, swap, sendError)) return false; // 2. Can store destination item in source if(swap) if(!pSrc->CanStore(pDestItem, true, true)) return false; // GM LOG (TODO: move to scripts) pDest->LogAction(pSrc); if(swap) pSrc->LogAction(pDest); SQLTransaction trans = CharacterDatabase.BeginTransaction(); // 3. Log bank events pDest->LogBankEvent(trans, pSrc, pSrcItem->GetCount()); if(swap) pSrc->LogBankEvent(trans, pDest, pDestItem->GetCount()); // 4. Remove item from source pSrc->RemoveItem(trans, pDest, splitedAmount); // 5. Remove item from destination if(swap) pDest->RemoveItem(trans, pSrc); // 6. Store item in destination pDest->StoreItem(trans, pSrcItem); // 7. Store item in source if(swap) pSrc->StoreItem(trans, pDestItem); CharacterDatabase.CommitTransaction(trans); return true; } void Guild::_SendBankContent(WorldSession* session, uint8 tabId) const { const uint64& guid = session->GetPlayer()->GetGUID(); if(_MemberHasTabRights(guid, tabId, GUILD_BANK_RIGHT_VIEW_TAB)) if(const BankTab* pTab = GetBankTab(tabId)) { WorldPacket data(SMSG_GUILD_BANK_LIST, 1200); data << uint64(m_bankMoney); data << uint8(tabId); data << uint32(_GetMemberRemainingSlots(guid, tabId)); data << uint8(0); // Tell client that there's no tab info in this packet pTab->WritePacket(data); session->SendPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_BANK_LIST)"); } } void Guild::_SendBankMoneyUpdate(WorldSession* session) const { WorldPacket data(SMSG_GUILD_BANK_LIST, 8 + 1 + 4 + 1 + 1); data << uint64(m_bankMoney); data << uint8(0); // tabId, default 0 data << uint32(_GetMemberRemainingSlots(session->GetPlayer()->GetGUID(), 0)); data << uint8(0); // Tell that there's no tab info in this packet data << uint8(0); // No items BroadcastPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_BANK_LIST)"); } void Guild::_SendBankContentUpdate(MoveItemData* pSrc, MoveItemData* pDest) const { ASSERT(pSrc->IsBank() || pDest->IsBank()); uint8 tabId = 0; SlotIds slots; if(pSrc->IsBank()) // B -> { tabId = pSrc->GetContainer(); slots.insert(pSrc->GetSlotId()); if(pDest->IsBank()) // B -> B { // Same tab - add destination slots to collection if(pDest->GetContainer() == pSrc->GetContainer()) pDest->CopySlots(slots); else // Different tabs - send second message { SlotIds destSlots; pDest->CopySlots(destSlots); _SendBankContentUpdate(pDest->GetContainer(), destSlots); } } } else if(pDest->IsBank()) // C -> B { tabId = pDest->GetContainer(); pDest->CopySlots(slots); } _SendBankContentUpdate(tabId, slots); } void Guild::_SendBankContentUpdate(uint8 tabId, SlotIds slots) const { if(const BankTab* pTab = GetBankTab(tabId)) { WorldPacket data(SMSG_GUILD_BANK_LIST, 1200); data << uint64(m_bankMoney); data << uint8(tabId); size_t rempos = data.wpos(); data << uint32(0); // Item withdraw amount, will be filled later data << uint8(0); // Tell client that there's no tab info in this packet data << uint8(slots.size()); for(uint8 slotId = 0; slotId < GUILD_BANK_MAX_SLOTS; ++slotId) if(slots.find(slotId) != slots.end()) pTab->WriteSlotPacket(data, slotId); for(Members::const_iterator itr = m_members.begin(); itr != m_members.end(); ++itr) if(_MemberHasTabRights(itr->second->GetGUID(), tabId, GUILD_BANK_RIGHT_VIEW_TAB)) if(Player* player = itr->second->FindPlayer()) { data.put<uint32>(rempos, uint32(_GetMemberRemainingSlots(player->GetGUID(), tabId))); player->GetSession()->SendPacket(&data); } sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent (SMSG_GUILD_BANK_LIST)"); } } void Guild::_BroadcastEvent(GuildEvents guildEvent, const uint64& guid, const char* param1, const char* param2, const char* param3) const { uint8 count = !param3 ? (!param2 ? (!param1 ? 0 : 1) : 2) : 3; WorldPacket data(SMSG_GUILD_EVENT, 1 + 1 + count + (guid ? 8 : 0)); data << uint8(guildEvent); data << uint8(count); if(param3) data << param1 << param2 << param3; else if(param2) data << param1 << param2; else if(param1) data << param1; if(guid) data << uint64(guid); BroadcastPacket(&data); sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Sent SMSG_GUILD_EVENT"); }
6d9c4197ae3281e5cc871b579abc6b0d772a04ff
5a60d60fca2c2b8b44d602aca7016afb625bc628
/aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/CreateAccessResult.h
43fa8fb219df643d81c73954c18212b4b70c3208
[ "Apache-2.0", "MIT", "JSON" ]
permissive
yuatpocketgems/aws-sdk-cpp
afaa0bb91b75082b63236cfc0126225c12771ed0
a0dcbc69c6000577ff0e8171de998ccdc2159c88
refs/heads/master
2023-01-23T10:03:50.077672
2023-01-04T22:42:53
2023-01-04T22:42:53
134,497,260
0
1
null
2018-05-23T01:47:14
2018-05-23T01:47:14
null
UTF-8
C++
false
false
4,184
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/awstransfer/Transfer_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Transfer { namespace Model { class CreateAccessResult { public: AWS_TRANSFER_API CreateAccessResult(); AWS_TRANSFER_API CreateAccessResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); AWS_TRANSFER_API CreateAccessResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The identifier of the server that the user is attached to.</p> */ inline const Aws::String& GetServerId() const{ return m_serverId; } /** * <p>The identifier of the server that the user is attached to.</p> */ inline void SetServerId(const Aws::String& value) { m_serverId = value; } /** * <p>The identifier of the server that the user is attached to.</p> */ inline void SetServerId(Aws::String&& value) { m_serverId = std::move(value); } /** * <p>The identifier of the server that the user is attached to.</p> */ inline void SetServerId(const char* value) { m_serverId.assign(value); } /** * <p>The identifier of the server that the user is attached to.</p> */ inline CreateAccessResult& WithServerId(const Aws::String& value) { SetServerId(value); return *this;} /** * <p>The identifier of the server that the user is attached to.</p> */ inline CreateAccessResult& WithServerId(Aws::String&& value) { SetServerId(std::move(value)); return *this;} /** * <p>The identifier of the server that the user is attached to.</p> */ inline CreateAccessResult& WithServerId(const char* value) { SetServerId(value); return *this;} /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline const Aws::String& GetExternalId() const{ return m_externalId; } /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline void SetExternalId(const Aws::String& value) { m_externalId = value; } /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline void SetExternalId(Aws::String&& value) { m_externalId = std::move(value); } /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline void SetExternalId(const char* value) { m_externalId.assign(value); } /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline CreateAccessResult& WithExternalId(const Aws::String& value) { SetExternalId(value); return *this;} /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline CreateAccessResult& WithExternalId(Aws::String&& value) { SetExternalId(std::move(value)); return *this;} /** * <p>The external identifier of the group whose users have access to your Amazon * S3 or Amazon EFS resources over the enabled protocols using Transfer Family.</p> */ inline CreateAccessResult& WithExternalId(const char* value) { SetExternalId(value); return *this;} private: Aws::String m_serverId; Aws::String m_externalId; }; } // namespace Model } // namespace Transfer } // namespace Aws
70f43f84695ce03ae835f3b0836fdf3003e06108
b0fa6a9dd581676e727a507a292662afeaff7b2b
/include/Plus/Graphics.hpp
66b20de00570ea34e74f4b641f2b4b00d58c912b
[]
no_license
gabteles/RGSSPlus
d3ba72ada72a16699353fdac136ebc56ac826550
4e5a44003158525b98b4f73c0651310b96226f84
refs/heads/master
2021-05-16T02:51:42.577238
2018-01-01T21:00:56
2018-01-01T21:00:56
7,790,329
1
0
null
null
null
null
UTF-8
C++
false
false
1,551
hpp
#ifndef PLUS_GRAPHICS_HPP #define PLUS_GRAPHICS_HPP namespace Plus { class _MGraphics { public: void initialize(unsigned int width, unsigned int height, string title); void initialize(unsigned int width, unsigned int height); void initialize(string title); void initialize(); unsigned int getWidth(); unsigned int getHeight(); unsigned char getBrightness(); unsigned int getFrameRate(); unsigned int getRealFrameRate(); void setFrameRate(unsigned int frameRate); void setBrightness(unsigned char brightness); void addObject(Viewport* object); void removeObject(Viewport* object); void update(); void draw(); void wait(unsigned int duration); void fadein(unsigned int duration); void fadeout(unsigned int duration); static void resizeScreen(int width, int height); void playMovie(std::string filename); private: unsigned int width; unsigned int height; string title; unsigned char brightness; unsigned int frameRate; Timer* timer; Timer* secTimer; unsigned int realFrameRate; unsigned int realFrameRateBuffer; double microsecByFrame; forward_list<Viewport*>* objects; }; }; #endif /* PLUS_GRAPHICS_HPP */
31b5915866b8baf8913e0d3912b981ea8ac924e3
2405a2f2cc21a7d52461e14ee4eb6b13b3c90d44
/hello.cpp
67a1ca39329ca7f7ec0562b76d21825a8be2b304
[]
no_license
swarneswaran-it19/myfirstprogram
754eb1f54f866f51de6a6ff6d06614f2342bd673
35d48b1c508aec204bc0599795fde7895f1583d5
refs/heads/master
2020-07-06T20:46:08.472212
2019-09-06T06:27:10
2019-09-06T06:27:10
203,134,812
0
0
null
null
null
null
UTF-8
C++
false
false
85
cpp
#include<iostream> #include<conio> void main() { clrscr(); cout<<"hello"; getch(); }
f75f190709ba3582e43a88c26624a047e16c4ea8
e9d86e4f5b1becf6f1355ba8eb99f910cfe90194
/src/rogue_game/action/action_handler.cpp
36cf2edd35d37873643ea1ea1554487ce2b44781
[ "MIT" ]
permissive
tanacchi/rogue_game
fec8a41220d6a743d9d1f4b9015801dffb54b838
fd8f655f95932513f6aa63e0c413bbe110a4418a
refs/heads/master
2021-06-01T14:33:49.713762
2020-11-12T16:34:10
2020-11-12T16:34:10
143,470,202
11
0
MIT
2020-11-13T12:43:38
2018-08-03T20:23:12
C++
UTF-8
C++
false
false
481
cpp
#include <action/action_handler.hpp> #include <action/any_action.hpp> #include <game_master/game_status.hpp> std::queue<AnyAction> ActionHandler::actions_; void ActionHandler::push(AnyAction&& action) { actions_.push(action); } GameStatus ActionHandler::invoke(const std::shared_ptr<GameMaster>& master) { const auto current_action{actions_.front()}; actions_.pop(); return current_action.do_action(master); } bool ActionHandler::empty() { return actions_.empty(); }
95f121bd6db2e067be4a2ca0361a8d63a21425a8
4cd9cf94e373877034ff9b90af8be566ad42c6b7
/libgpopt/include/gpopt/xforms/CXformInlineCTEConsumerUnderSelect.h
082ab7cb360cfe80d13a1db465b6c5b28db6a848
[ "Apache-2.0" ]
permissive
ppmht/gporca
6a912edac14b52d67636f6d51c90ef3b63f41304
7131e3e134e6e608f7e9fef9152a8b5d71e6a59e
refs/heads/master
2020-03-15T16:06:19.229839
2018-05-04T19:16:11
2018-05-04T19:17:14
132,228,406
1
0
null
null
null
null
UTF-8
C++
false
false
2,077
h
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CXformInlineCTEConsumerUnderSelect.h // // @doc: // Transform logical Select on top of a CTE consumer to a select on top of // a copy of the expression under its corresponding producer then attempt // push the selection down //--------------------------------------------------------------------------- #ifndef GPOPT_CXformInlineCTEConsumerUnderSelect_H #define GPOPT_CXformInlineCTEConsumerUnderSelect_H #include "gpos/base.h" #include "gpopt/xforms/CXformExploration.h" namespace gpopt { using namespace gpos; //--------------------------------------------------------------------------- // @class: // CXformInlineCTEConsumerUnderSelect // // @doc: // Transform logical Select on top of a CTE consumer to a select on top of // a copy of the expression under its corresponding producer then attempt // push the selection down // //--------------------------------------------------------------------------- class CXformInlineCTEConsumerUnderSelect : public CXformExploration { private: // private copy ctor CXformInlineCTEConsumerUnderSelect(const CXformInlineCTEConsumerUnderSelect &); public: // ctor explicit CXformInlineCTEConsumerUnderSelect(IMemoryPool *pmp); // dtor virtual ~CXformInlineCTEConsumerUnderSelect() {} // ident accessors virtual EXformId Exfid() const { return ExfInlineCTEConsumerUnderSelect; } // return a string for xform name virtual const CHAR *SzId() const { return "CXformInlineCTEConsumerUnderSelect"; } // compute xform promise for a given expression handle virtual EXformPromise Exfp(CExpressionHandle &exprhdl) const; // actual transform virtual void Transform ( CXformContext *pxfctxt, CXformResult *pxfres, CExpression *pexpr ) const; }; // class CXformInlineCTEConsumerUnderSelect } #endif // !GPOPT_CXformInlineCTEConsumerUnderSelect_H // EOF
cd46ab7fb379c80d661281890f1f3d9d5ad05768
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_K3000390762.h
3b63a31b88f3401bb43bfc90d1f8b5e6d1f45d5b
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
1,439
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Collections.Generic.Dictionary`2<System.Type,Newtonsoft.Json.Utilities.BidirectionalDictionary`2<System.String,System.String>> struct Dictionary_2_t516892991; #include "mscorlib_System_Object2689449295.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/KeyCollection<System.Type,Newtonsoft.Json.Utilities.BidirectionalDictionary`2<System.String,System.String>> struct KeyCollection_t3000390762 : public Il2CppObject { public: // System.Collections.Generic.Dictionary`2<TKey,TValue> System.Collections.Generic.Dictionary`2/KeyCollection::dictionary Dictionary_2_t516892991 * ___dictionary_0; public: inline static int32_t get_offset_of_dictionary_0() { return static_cast<int32_t>(offsetof(KeyCollection_t3000390762, ___dictionary_0)); } inline Dictionary_2_t516892991 * get_dictionary_0() const { return ___dictionary_0; } inline Dictionary_2_t516892991 ** get_address_of_dictionary_0() { return &___dictionary_0; } inline void set_dictionary_0(Dictionary_2_t516892991 * value) { ___dictionary_0 = value; Il2CppCodeGenWriteBarrier(&___dictionary_0, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
ef9bd9823d9073802abcac868757eb5b955c3660
af8191cb9206f4e6ce2daf82c079189cd9b5f93b
/src/DBase3File.cpp
9efa61e9ee0a11863420f2c4710e5762546882f5
[ "MIT" ]
permissive
Sometrik/graphlib
ea9b3db13582e98c5ce1acd5ec24fc1f62d7555a
8cc888182d7c1184b5f1e6f211da45d9849f77f4
refs/heads/master
2021-01-17T12:19:27.196303
2017-03-29T13:52:26
2017-03-29T13:52:26
49,238,342
2
0
null
null
null
null
UTF-8
C++
false
false
2,781
cpp
#include "DBase3File.h" #include "utf8.h" #include <cstring> #include <cassert> #include <shapefil.h> #include <iostream> using namespace std; using namespace table; class table::DBase3Handle { public: DBase3Handle() { } ~DBase3Handle() { if (h) { DBFClose(h); } } void open(const std::string & fn) { h = DBFOpen(fn.c_str(), "rb"); if (!h) { cerr << "failed to open DBF " << fn << endl; } } int readIntegerAttribute(int rec, int field) { return DBFReadIntegerAttribute(h, rec, field); } double readDoubleAttribute(int rec, int field) { return DBFReadDoubleAttribute(h, rec, field); } std::string readStringAttribute(int rec, int field) { const char * tmp = DBFReadStringAttribute(h, rec, field); if (tmp) { string output; while (!tmp) { utf8::append((unsigned char)*tmp, back_inserter(output)); tmp++; } return output; } return ""; } bool readBoolAttribute(int rec, int field) { return DBFReadLogicalAttribute(h, rec, field); } bool isNull(int rec, int field) { return DBFIsAttributeNULL(h, rec, field); } unsigned int getRecordCount() { return h ? DBFGetRecordCount(h) : 0; } unsigned int getFieldCount() { return h ? DBFGetFieldCount(h) : 0; } string getFieldName(int field) { char fieldname[255]; DBFFieldType type = DBFGetFieldInfo(h, field, fieldname, 0, 0); return fieldname; } private: DBFHandle h = 0; }; DBase3File::DBase3File(const string & filename) { record_count = 0; openDBF(filename); } bool DBase3File::openDBF(const string & filename) { dbf = std::make_shared<DBase3Handle>(); dbf->open(filename); record_count = dbf->getRecordCount(); unsigned int field_count = dbf->getFieldCount(); for (unsigned int i = 0; i < field_count; i++) { string name = dbf->getFieldName(i); columns[name] = std::make_shared<DBase3Column>(dbf, i, record_count); } return true; } DBase3Column::DBase3Column(const std::shared_ptr<DBase3Handle> _dbf, int _column_index, int _num_rows) : dbf(_dbf), column_index(_column_index), num_rows(_num_rows) { } long long DBase3Column::getInt64(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } } std::string DBase3Column::getText(int i) const { if (i >= 0 && i < num_rows) { return dbf->readStringAttribute(i, column_index); } else { return ""; } } double DBase3Column::getDouble(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } } int DBase3Column::getInt(int i) const { if (i >= 0 && i < num_rows) { return dbf->readIntegerAttribute(i, column_index); } else { return 0; } }
813a5d58f06fa2de2d87a2223556f9df15273347
c6e9d1e01ab6b6db0371f66cc1dbef2739b0393e
/qt/exercise01/MyLCD.h
034b645a80cbf092eef9c8802c7383e751296d83
[]
no_license
osmar106/idi
15c8981060f3028d74b9d3bea7de02551dffb036
50c29ccbd23df6ba2181ab76b1bd7b1024b38e65
refs/heads/master
2021-01-19T12:43:33.565049
2013-12-17T00:44:29
2013-12-17T00:44:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
186
h
#include <QLCDNumber> class MyLCD: public QLCDNumber { Q_OBJECT; public: MyLCD(QWidget *parent); public slots: void display(int); void reset(); };
d08fbeefa61c865862d52174cdac112e7b4ecd89
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/update_notifier/thirdparty/wxWidgets/src/stc/scintilla/lexers/LexPowerShell.cxx
bf1ee29d14acb8d1284dd3fcde174f9a12e707b2
[ "LicenseRef-scancode-scintilla", "BSD-3-Clause" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C++
false
false
7,872
cxx
// Scintilla source code edit control /** @file LexPowerShell.cxx ** Lexer for PowerShell scripts. **/ // Copyright 2008 by Tim Gerundt <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdarg.h> #include <assert.h> #include <ctype.h> #include "ILexer.h" #include "Scintilla.h" #include "SciLexer.h" #include "WordList.h" #include "LexAccessor.h" #include "Accessor.h" #include "StyleContext.h" #include "CharacterSet.h" #include "LexerModule.h" #ifdef SCI_NAMESPACE using namespace Scintilla; #endif // Extended to accept accented characters static inline bool IsAWordChar(int ch) { return ch >= 0x80 || isalnum(ch) || ch == '-' || ch == '_'; } static void ColourisePowerShellDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *keywordlists[], Accessor &styler) { WordList &keywords = *keywordlists[0]; WordList &keywords2 = *keywordlists[1]; WordList &keywords3 = *keywordlists[2]; WordList &keywords4 = *keywordlists[3]; WordList &keywords5 = *keywordlists[4]; WordList &keywords6 = *keywordlists[5]; styler.StartAt(startPos); StyleContext sc(startPos, length, initStyle, styler); for (; sc.More(); sc.Forward()) { if (sc.state == SCE_POWERSHELL_COMMENT) { if (sc.atLineEnd) { sc.SetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_COMMENTSTREAM) { if(sc.atLineStart) { while(IsASpaceOrTab(sc.ch)) { sc.Forward(); } if (sc.ch == '.' && IsAWordChar(sc.chNext)) { sc.SetState(SCE_POWERSHELL_COMMENTDOCKEYWORD); } } if (sc.ch == '>' && sc.chPrev == '#') { sc.ForwardSetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_COMMENTDOCKEYWORD) { if(!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (!keywords6.InList(s + 1)) { sc.ChangeState(SCE_POWERSHELL_COMMENTSTREAM); } sc.SetState(SCE_POWERSHELL_COMMENTSTREAM); } } else if (sc.state == SCE_POWERSHELL_STRING) { // This is a doubles quotes string if (sc.ch == '\"') { sc.ForwardSetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_CHARACTER) { // This is a single quote string if (sc.ch == '\'') { sc.ForwardSetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_HERE_STRING) { // This is a doubles quotes here-string if (sc.atLineStart && sc.ch == '\"' && sc.chNext == '@') { sc.Forward(2); sc.SetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_HERE_CHARACTER) { // This is a single quote here-string if (sc.atLineStart && sc.ch == '\'' && sc.chNext == '@') { sc.Forward(2); sc.SetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_NUMBER) { if (!IsADigit(sc.ch)) { sc.SetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_VARIABLE) { if (!IsAWordChar(sc.ch)) { sc.SetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_OPERATOR) { if (!isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_POWERSHELL_DEFAULT); } } else if (sc.state == SCE_POWERSHELL_IDENTIFIER) { if (!IsAWordChar(sc.ch)) { char s[100]; sc.GetCurrentLowered(s, sizeof(s)); if (keywords.InList(s)) { sc.ChangeState(SCE_POWERSHELL_KEYWORD); } else if (keywords2.InList(s)) { sc.ChangeState(SCE_POWERSHELL_CMDLET); } else if (keywords3.InList(s)) { sc.ChangeState(SCE_POWERSHELL_ALIAS); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_POWERSHELL_FUNCTION); } else if (keywords5.InList(s)) { sc.ChangeState(SCE_POWERSHELL_USER1); } sc.SetState(SCE_POWERSHELL_DEFAULT); } } // Determine if a new state should be entered. if (sc.state == SCE_POWERSHELL_DEFAULT) { if (sc.ch == '#') { sc.SetState(SCE_POWERSHELL_COMMENT); } else if (sc.ch == '<' && sc.chNext == '#') { sc.SetState(SCE_POWERSHELL_COMMENTSTREAM); } else if (sc.ch == '\"') { sc.SetState(SCE_POWERSHELL_STRING); } else if (sc.ch == '\'') { sc.SetState(SCE_POWERSHELL_CHARACTER); } else if (sc.ch == '@' && sc.chNext == '\"') { sc.SetState(SCE_POWERSHELL_HERE_STRING); } else if (sc.ch == '@' && sc.chNext == '\'') { sc.SetState(SCE_POWERSHELL_HERE_CHARACTER); } else if (sc.ch == '$') { sc.SetState(SCE_POWERSHELL_VARIABLE); } else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) { sc.SetState(SCE_POWERSHELL_NUMBER); } else if (isoperator(static_cast<char>(sc.ch))) { sc.SetState(SCE_POWERSHELL_OPERATOR); } else if (IsAWordChar(sc.ch)) { sc.SetState(SCE_POWERSHELL_IDENTIFIER); } else if (sc.ch == '`') { sc.Forward(); // skip next escaped character } } } sc.Complete(); } // Store both the current line's fold level and the next lines in the // level store to make it easy to pick up with each increment // and to make it possible to fiddle the current level for "} else {". static void FoldPowerShellDoc(Sci_PositionU startPos, Sci_Position length, int initStyle, WordList *[], Accessor &styler) { bool foldComment = styler.GetPropertyInt("fold.comment") != 0; bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0; bool foldAtElse = styler.GetPropertyInt("fold.at.else", 0) != 0; Sci_PositionU endPos = startPos + length; int visibleChars = 0; Sci_Position lineCurrent = styler.GetLine(startPos); int levelCurrent = SC_FOLDLEVELBASE; if (lineCurrent > 0) levelCurrent = styler.LevelAt(lineCurrent-1) >> 16; int levelMinCurrent = levelCurrent; int levelNext = levelCurrent; char chNext = styler[startPos]; int styleNext = styler.StyleAt(startPos); int style = initStyle; for (Sci_PositionU i = startPos; i < endPos; i++) { char ch = chNext; chNext = styler.SafeGetCharAt(i + 1); int stylePrev = style; style = styleNext; styleNext = styler.StyleAt(i + 1); bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n'); if (style == SCE_POWERSHELL_OPERATOR) { if (ch == '{') { // Measure the minimum before a '{' to allow // folding on "} else {" if (levelMinCurrent > levelNext) { levelMinCurrent = levelNext; } levelNext++; } else if (ch == '}') { levelNext--; } } else if (foldComment && style == SCE_POWERSHELL_COMMENTSTREAM) { if (stylePrev != SCE_POWERSHELL_COMMENTSTREAM && stylePrev != SCE_POWERSHELL_COMMENTDOCKEYWORD) { levelNext++; } else if (styleNext != SCE_POWERSHELL_COMMENTSTREAM && styleNext != SCE_POWERSHELL_COMMENTDOCKEYWORD) { levelNext--; } } else if (foldComment && style == SCE_POWERSHELL_COMMENT) { if (ch == '#') { Sci_PositionU j = i + 1; while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) { j++; } if (styler.Match(j, "region")) { levelNext++; } else if (styler.Match(j, "endregion")) { levelNext--; } } } if (!IsASpace(ch)) visibleChars++; if (atEOL || (i == endPos-1)) { int levelUse = levelCurrent; if (foldAtElse) { levelUse = levelMinCurrent; } int lev = levelUse | levelNext << 16; if (visibleChars == 0 && foldCompact) lev |= SC_FOLDLEVELWHITEFLAG; if (levelUse < levelNext) lev |= SC_FOLDLEVELHEADERFLAG; if (lev != styler.LevelAt(lineCurrent)) { styler.SetLevel(lineCurrent, lev); } lineCurrent++; levelCurrent = levelNext; levelMinCurrent = levelCurrent; visibleChars = 0; } } } static const char * const powershellWordLists[] = { "Commands", "Cmdlets", "Aliases", "Functions", "User1", "DocComment", 0 }; LexerModule lmPowerShell(SCLEX_POWERSHELL, ColourisePowerShellDoc, "powershell", FoldPowerShellDoc, powershellWordLists);
5d3f8238d4bbeda56f82a3131048e2215e578558
3632b418456887af9068dcb3262fcdcf99752cb7
/Course Planner/Scheduler.cpp
fe80bcca9431a6388181082e537fcff24bd9ac90
[]
no_license
ntaylor562/Course-Planner
6a73f89de50cef8771f0ebde14c236139b98a2fa
c10ef1e2866e1ae9ba2465184ea844e95221c424
refs/heads/master
2023-04-07T02:35:20.311731
2021-04-12T21:25:20
2021-04-12T21:25:20
343,010,258
1
0
null
2021-03-07T22:14:21
2021-02-28T03:16:12
C++
UTF-8
C++
false
false
9,420
cpp
#include <queue> #include "Scheduler.h" void Scheduler::nextSemester(Semester::Seasons &s, int &y) const { bool foundSeason = false; Semester::Seasons formerSeason(s); while (!foundSeason) { if (static_cast<int>(s) == 3) ++y; s = static_cast<Semester::Seasons>((static_cast<int>(s) + 1) % 4); if (s == Semester::WINTER && winterAllowed) foundSeason = true; else if (s == Semester::SPRING && springAllowed) foundSeason = true; else if (s == Semester::SUMMER && summerAllowed) foundSeason = true; else if (s == Semester::FALL && fallAllowed) foundSeason = true; } } Scheduler::Scheduler() { Courses = CourseGraph(); springAllowed = true; fallAllowed = true; winterAllowed = false; summerAllowed = false; } Scheduler::Scheduler(const CourseGraph &g, const std::list<CourseModule> &completed) { Courses = g; completedCourses = completed; for (auto &i : completedCourses) { Courses.remove(i); } springAllowed = true; fallAllowed = true; winterAllowed = false; summerAllowed = false; maxUnits = 15; } void Scheduler::updateCourses(const CourseGraph &g) { Courses = g; } const std::list<CourseModule> &Scheduler::getCompletedCourses() const { return completedCourses; } void Scheduler::markComplete(const CourseModule &c) { if (std::find(completedCourses.begin(), completedCourses.end(), c) == completedCourses.end()) completedCourses.push_back(c); } void Scheduler::markComplete(const std::vector<CourseModule> &vect) { for (const auto &i : vect) { if (std::find(completedCourses.begin(), completedCourses.end(), i) == completedCourses.end()) completedCourses.push_back(i); } } void Scheduler::uncomplete(const CourseModule &c) { std::list<CourseModule>::iterator it = completedCourses.begin(); while (it != completedCourses.end()) { if (*it == c) break; ++it; } if (it != completedCourses.end()) completedCourses.erase(it); } void Scheduler::uncomplete(const std::vector<CourseModule> &vect) { for (const auto &i : vect) { std::list<CourseModule>::iterator it = completedCourses.begin(); while (it != completedCourses.end()) { if (*it == i) break; ++it; } if (it != completedCourses.end()) completedCourses.erase(it); } } void Scheduler::addRestriction(const CourseModule &c, Semester::Seasons season, int year) { Semester sem; sem.season = season; sem.year = year; std::vector<Semester>::iterator semIt = std::find(semsWithRestrictions.begin(), semsWithRestrictions.end(), sem); if (semIt != semsWithRestrictions.end()) { semIt->restricted.push_back(c); } else { sem.restricted.push_back(c); semsWithRestrictions.push_back(sem); } } void Scheduler::addRestriction(Semester s) { addRestriction(s.season, s.year); } void Scheduler::addRestriction(Semester::Seasons season, int year) { Semester sem; sem.season = season; sem.year = year; std::vector<Semester>::iterator semIt = std::find(semsWithRestrictions.begin(), semsWithRestrictions.end(), sem); if (semIt != semsWithRestrictions.end()) { semIt->semesterRestricted = true; } else { sem.semesterRestricted = true; semsWithRestrictions.push_back(sem); } } void Scheduler::setSemesterUnitLimit(Semester s, int lim) { std::vector<Semester>::iterator semIt = std::find(semsWithRestrictions.begin(), semsWithRestrictions.end(), s); if (semIt != semsWithRestrictions.end()) { semIt->maxUnits = (lim >= 4 || lim == 0) ? lim : 4; } else { s.maxUnits = (lim >= 4 || lim == 0) ? lim : 4; semsWithRestrictions.push_back(s); semIt = semsWithRestrictions.end(); --semIt; } if (lim == 0 && semIt->restricted.empty() && !semIt->semesterRestricted) //Semester no longer has restrictions semsWithRestrictions.erase(semIt); } void Scheduler::setSemesterUnitLimit(Semester::Seasons season, int year, int lim) { Semester sem; sem.season = season; sem.year = year; setSemesterUnitLimit(sem, lim); } void Scheduler::removeRestriction(const CourseModule &c, Semester::Seasons season, int year) { Semester sem; sem.season = season; sem.year = year; std::vector<Semester>::iterator resSem = std::find(semsWithRestrictions.begin(), semsWithRestrictions.end(), sem); if (resSem == semsWithRestrictions.end()) return; std::vector<CourseModule>::iterator courseLocation = std::find(resSem->restricted.begin(), resSem->restricted.end(), c); if (courseLocation == resSem->restricted.end()) return; resSem->restricted.erase(courseLocation); if (resSem->restricted.empty() && !resSem->semesterRestricted && maxUnits == 0) //Semester no longer has restrictions semsWithRestrictions.erase(resSem); } void Scheduler::removeRestriction(const CourseModule &c, const Semester &s) { removeRestriction(c, s.season, s.year); } void Scheduler::removeRestriction(Semester::Seasons season, int year) { Semester sem; sem.season = season; sem.year = year; std::vector<Semester>::iterator resSem = std::find(semsWithRestrictions.begin(), semsWithRestrictions.end(), sem); if (resSem == semsWithRestrictions.end()) return; resSem->semesterRestricted = false; if (resSem->restricted.empty() && !resSem->semesterRestricted && maxUnits == 0) //Semester no longer has restrictions semsWithRestrictions.erase(resSem); } void Scheduler::setUnitLimit(int lim) { if (lim == 0) maxUnits = 15; else maxUnits = (lim >= 4) ? lim : 4; } void Scheduler::deletePrereqs(CourseGraph &g, vertex &v) const { while (!v.prerequisites.empty()) { deletePrereqs(g, *v.prerequisites.front()); } g.remove(v.course); } Schedule Scheduler::generateSchedule(Semester::Seasons currentSeason, int currentYear) const { //Return an empty schedule if there are no allowed seasons if (!(winterAllowed || springAllowed || summerAllowed || fallAllowed)) return Schedule(); std::list<CourseModule> toBeRemoved(completedCourses); CourseGraph remainingCourses(Courses); while(!toBeRemoved.empty()) { vertex *v = remainingCourses.search(toBeRemoved.front()); if (v != nullptr) { deletePrereqs(remainingCourses, *v); toBeRemoved.pop_front(); } } Schedule schedule; while (!remainingCourses.empty()) { //Queue containing leaf courses that will be added to the semester std::queue<CourseModule> queuedCourses; Semester currentSem; currentSem.season = currentSeason; currentSem.year = currentYear; std::vector<Semester>::const_iterator restrictedSem = semsWithRestrictions.begin(); while (restrictedSem != semsWithRestrictions.end()) { if (restrictedSem->season == currentSem.season && restrictedSem->year == currentSem.year) break; ++restrictedSem; } if (restrictedSem != semsWithRestrictions.end()) { currentSem = *restrictedSem; } int maxSemUnits = (currentSem.maxUnits > 0) ? currentSem.maxUnits : maxUnits; //Contains all courses that will be added std::vector<vertex *> leaves; for (auto &i : remainingCourses) { if (i->prerequisites.empty()) { if (std::find(currentSem.restricted.begin(), currentSem.restricted.end(), i->course) == currentSem.restricted.end()) { //Checking if course is not restricted for this semester leaves.push_back(i); } } } //Insertion sort to sort the leaf courses by highest outdegree //We do this to get courses that are more important out of the way first so we can take more courses the next semester for (int i = 1; i < leaves.size(); ++i) { vertex *key = leaves[i]; int j = i - 1; while (j >= 0 && leaves[j]->prerequisiteFor.size() < key->prerequisiteFor.size()) { leaves[j + 1] = leaves[j]; --j; } leaves[j + 1] = key; } int sum = 0; for (const auto &i : leaves) { if (sum + i->course.getUnits() <= maxSemUnits) { queuedCourses.push(i->course); sum += i->course.getUnits(); remainingCourses.remove(i->course); //Remove course from the graph } } if (!currentSem.semesterRestricted) { //If this semester is allowed to have courses while (!queuedCourses.empty()) { //Add courses from the queue into the current semester if (std::find(currentSem.restricted.begin(), currentSem.restricted.end(), queuedCourses.front()) == currentSem.restricted.end()) { currentSem.courses.push_back(queuedCourses.front()); queuedCourses.pop(); } } schedule.CoursePlan.push_back(currentSem); //Push the semester to the schedule } nextSemester(currentSeason, currentYear); } return schedule; } void Scheduler::setWinterAllowed(bool allowed) { winterAllowed = allowed; } void Scheduler::setSpringAllowed(bool allowed) { springAllowed = allowed; } void Scheduler::setSummerAllowed(bool allowed) { summerAllowed = allowed; } void Scheduler::setFallAllowed(bool allowed) { fallAllowed = allowed; } const bool Scheduler::getWinterAllowed() const { return winterAllowed; } const bool Scheduler::getSpringAllowed() const { return springAllowed; } const bool Scheduler::getSummerAllowed() const { return summerAllowed; } const bool Scheduler::getFallAllowed() const { return fallAllowed; } std::vector<Semester::Seasons> Scheduler::getRestrictedSeasons() const { std::vector<Semester::Seasons> v; if (!winterAllowed) v.push_back(Semester::WINTER); if (!springAllowed) v.push_back(Semester::SPRING); if (!summerAllowed) v.push_back(Semester::SUMMER); if (!fallAllowed) v.push_back(Semester::FALL); return v; } std::vector<Semester> Scheduler::getRestrictedSemesters() const { return semsWithRestrictions; } int Scheduler::getMaxUnits() const { return maxUnits; }
d9eb640a26420c0c4eb29f816cc258fd92611cf1
943b8a1d008eb51105167dd3f326c26c697e4a30
/GT/gt_plugins/Tank_Nostradamus/tank.cpp
fb4b7f678cd31b036812118ea4751c4c5c857d25
[]
no_license
patadejaguar/GuerraDeTanques
2f6ceb07388202afd550ef34cc6c2b04efee0cee
d78108baacd4cc0fbb7db46e957c3284cafba31b
refs/heads/master
2016-09-02T20:01:18.138991
2014-08-30T11:50:50
2014-08-30T11:50:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,439
cpp
#include "tank.h" Tank::Tank(TankInfo tank_info, QString nick, int rank, ColorTeam color_team) :ITank(tank_info, nick, rank, color_team) { //atributos para las animaciones _frame_animation_whell_1 = 0; _frame_animation_whell_2 = 0; //crea las piezas del tanque !!! _animation_whell = getListOfPixmapFromStripImage(":/xavier_tank_nostradamus/sprites/whell.png",18); _body = QPixmap(":/xavier_tank_nostradamus/sprites/body.png"); _turret = QPixmap(":/xavier_tank_nostradamus/sprites/turret.png"); //posiciones relativas de los objetos que componen el tanque para que queden en el centro _body_position = QPoint(-16,-19); _turret_position = QPoint(-11,-27); _whell_1_position = QPoint(-24,-20); _whell_2_position = QPoint(6,-20); //para detección de colisiones _rect_body = QRect(0, 0, 46, 38); _shape_body.addRect(_rect_body); } Tank::~Tank() { } void Tank::reborn() { ITank::reborn(); _frame_animation_whell_1 = 0; _frame_animation_whell_2 = 0; } QPainterPath Tank::shape() const { QPainterPath shape; QTransform transformation_turret; transformation_turret.translate(0,-3); transformation_turret.rotate(_turret_rotation); transformation_turret.translate(-4,-24); shape.addPath(_shape_body.translated(_body_position.x()-7, _body_position.y())); return shape; } void Tank::paintForEnemies(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { paintForFriends(painter,option,widget); } void Tank::paintForFriends(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); Q_UNUSED(widget); painter->drawPixmap(_whell_1_position,_animation_whell.at(_frame_animation_whell_1)); painter->drawPixmap(_whell_2_position,_animation_whell.at(_frame_animation_whell_2)); painter->drawPixmap(_body_position,_body); painter->translate(0,-3); painter->rotate(_turret_rotation-rotation()); painter->translate(-11,-24); painter->drawPixmap(0,0,_turret); } void Tank::createSkills() { _skill_1 = new Skill1Factory(this, tankInfo()._skill_info_1); _skill_2 = new Skill2Factory(this, tankInfo()._skill_info_2); _skill_3 = new Skill3Factory(this, tankInfo()._skill_info_3); } QPoint Tank::getTurretPosition() { return _turret_position; } void Tank::gameLoop() { } void Tank::move() { ITank::move(); int roll = 0; if(_move_forward) ++roll; if(_move_backward) --roll; _frame_animation_whell_1 += roll; if(_frame_animation_whell_1 > 9) _frame_animation_whell_1 = 0; else if(_frame_animation_whell_1 < 0) _frame_animation_whell_1 = 9; _frame_animation_whell_2 += roll; if(_frame_animation_whell_2 > 9) _frame_animation_whell_2 = 0; else if(_frame_animation_whell_2 < 0) _frame_animation_whell_2 = 9; } void Tank::rotate() { ITank::rotate(); int roll = 0; if(_rotate_left) ++roll; if(_rotate_right) --roll; _frame_animation_whell_1 -= roll; if(_frame_animation_whell_1 > 9) _frame_animation_whell_1 = 0; else if(_frame_animation_whell_1 < 0) _frame_animation_whell_1 = 9; _frame_animation_whell_2 += roll; if(_frame_animation_whell_2 > 9) _frame_animation_whell_2 = 0; else if(_frame_animation_whell_2 < 0) _frame_animation_whell_2 = 9; }
2ed4b58af214c00eb54a6a1f73b42292a7115ae0
963c69c8f40e19d6b1a558e24d660a73188debe0
/src/player.cpp
6dfa6580951ace3d3d3703adbabfde73c59ae442
[]
no_license
adharshkamath/Maze-Runner
c4322301861f8b8df4b0bd4beec5d708856a20c5
4b3a6e24eb0b87ee9ccc008eb4f01a7056f772cc
refs/heads/master
2022-05-25T22:22:04.812979
2022-05-03T05:27:19
2022-05-03T05:27:19
174,572,941
2
3
null
null
null
null
UTF-8
C++
false
false
2,375
cpp
#include "include/maze.h" #include "include/player.h" Player::Player() { generate_maze(); srand(time(NULL)); for(; maze[locationY][locationX] != ' ';) { locationX = rand()%55; locationY = rand()%34; } maze[locationY][locationX] = '@'; } void Player::Display(float beginX, float beginY, float blockWidth, float blockHeight) { if(Player::SpeedBoost == 0 && Player::Armed == 0 ) { glBegin(GL_TRIANGLES); glColor3f(0.0f, 1.0f, 0.0f); glVertex2f(beginX + (1.0/61.0), beginY - (0.05/15.0)); glVertex2f(beginX + (0.65 / 305.0), beginY -blockHeight + (0.3/34.0)); glVertex2f(beginX + (8.0 / 305.0), beginY -blockHeight + (0.3/34.0)); glVertex2f(beginX + (0.65 / 305.0), beginY - (0.3/34.0)); glVertex2f(beginX + (1.0/61.0), beginY -blockHeight + (0.05/15.0)); glVertex2f(beginX + (8.0 / 305.0), beginY - (0.3/34.0)); glEnd(); } else if(Player::SpeedBoost == 0 && Player::Armed == 1) { glBegin(GL_TRIANGLES); glColor3f(1.0f, 1.0f, 0.0f); glVertex2f(beginX + (1.0/61.0), beginY - (0.05/15.0)); glVertex2f(beginX + (0.65 / 305.0), beginY -blockHeight + (0.3/34.0)); glVertex2f(beginX + (8.0 / 305.0), beginY -blockHeight + (0.3/34.0)); glVertex2f(beginX + (0.65 / 305.0), beginY - (0.3/34.0)); glVertex2f(beginX + (1.0/61.0), beginY -blockHeight + (0.05/15.0)); glVertex2f(beginX + (8.0 / 305.0), beginY - (0.3/34.0)); glEnd(); } else if(Player::SpeedBoost == 1 && Player::Armed == 0) { glBegin(GL_TRIANGLES); glColor3f(0.5f, 0.0f, 0.5f); glVertex2f(beginX + (1.0/61.0), beginY - (0.05/15.0)); glVertex2f(beginX + (0.65 / 305.0), beginY -blockHeight + (0.3/34.0)); glVertex2f(beginX + (8.0 / 305.0), beginY -blockHeight + (0.3/34.0)); glVertex2f(beginX + (0.65 / 305.0), beginY - (0.3/34.0)); glVertex2f(beginX + (1.0/61.0), beginY -blockHeight + (0.05/15.0)); glVertex2f(beginX + (8.0 / 305.0), beginY - (0.3/34.0)); glEnd(); } } int Player::SpeedBoost = 0; int Player::Armed = 0; int Player::SpeedBoostCount = 0;
c7086252d5f8e7c0ead6f0457da54e0ce5b4b15d
fb9e4f0d391aac969f30118f50544ce07f38454a
/Test/GetPos.h
c302fffbb8d8c6af5252b4ce3f5897740f1ec1f3
[]
no_license
sykzhong/CalcLoc
421f397d528372908e6d01d01c642a15df29dea2
f36e080b97332c1ff8fcc118f0900fa8b627f560
refs/heads/master
2021-01-23T06:54:26.539941
2018-01-18T03:38:45
2018-01-18T03:38:45
86,407,309
0
0
null
null
null
null
UTF-8
C++
false
false
157
h
#ifndef _GETPOS_H_ #define _GETPOS_H_ #include "GlobalHeader.h" #include "HSVHist.h" class GetPos :public HSVHist { public: GetPos(); ~GetPos(); }; #endif
9e9b1404b3e8086173bf5ddacac7765af7dc18a2
c4a68067b35d86607edb14c7c694706b07b6653c
/libraries/ros_lib/open_manipulator_msgs/GetJointPosition.h
0d173f1fe5a06736bdfb108eddaf35ff5c63b169
[]
no_license
MikhailBertrand/ArduinoProjects
0ce37aee5a01f97a23ddf0e99ad851bd8709ec15
969936396e52ad96710f5c570ebe20efdf9420f9
refs/heads/master
2020-06-26T20:42:13.484545
2019-07-31T01:16:00
2019-07-31T01:16:00
199,752,305
0
0
null
null
null
null
UTF-8
C++
false
false
1,689
h
#ifndef _ROS_SERVICE_GetJointPosition_h #define _ROS_SERVICE_GetJointPosition_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "open_manipulator_msgs/JointPosition.h" namespace open_manipulator_msgs { static const char GETJOINTPOSITION[] = "open_manipulator_msgs/GetJointPosition"; class GetJointPositionRequest : public ros::Msg { public: GetJointPositionRequest() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; return offset; } const char * getType(){ return GETJOINTPOSITION; }; const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; }; }; class GetJointPositionResponse : public ros::Msg { public: typedef open_manipulator_msgs::JointPosition _joint_position_type; _joint_position_type joint_position; GetJointPositionResponse(): joint_position() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->joint_position.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->joint_position.deserialize(inbuffer + offset); return offset; } const char * getType(){ return GETJOINTPOSITION; }; const char * getMD5(){ return "e1f1ee99b5e77308297dc4eeedd305d4"; }; }; class GetJointPosition { public: typedef GetJointPositionRequest Request; typedef GetJointPositionResponse Response; }; } #endif
70a3f932822c49f011f3d9d47cab5f9354fe623e
ace6ec6e68df878e39c561fa2e73f7b4ef387cc6
/src/common-lib/material.cpp
69fa2560c5d6344775f0ca8693bc183f7ac04eaf
[ "MIT" ]
permissive
SakibSaikia/CPURayTracer
d7b4b29eaea77ce235a007b978181b998f10d7c0
9c603ffcf06f8bd6ce9bb95d40c508f2338e4c95
refs/heads/master
2020-03-12T13:54:22.879718
2018-10-01T14:30:30
2018-10-01T14:30:30
130,653,353
5
1
null
null
null
null
UTF-8
C++
false
false
5,153
cpp
#include "material.h" #include "quasi-random.h" XMVECTOR Material::Shade(const Payload& payload, const std::vector<std::unique_ptr<Light>>& lights, const XMVECTOR& viewOrigin) const { XMVECTOR directLighting = XM_Zero; for (const auto& light : lights) { directLighting += light->Shade(this, payload, viewOrigin); } return directLighting; } DielectricOpaque::DielectricOpaque(const Texture* albedo, const XMVECTOR& smoothness) : m_albedo{ albedo }, m_smoothness{ smoothness } { } bool DielectricOpaque::Scatter(const Ray& ray, const Payload& hit, XMVECTOR& outAttenuation, Ray& outRay) const { if (XMVector3Greater(XMVector3Dot(-ray.direction, hit.normal), XM_Zero)) { // Use ray direction to calculate incident angle. This is same as view direction for primary rays. XMVECTOR f0 = GetReflectance(hit.uv); XMVECTOR nDotV = XMVectorSaturate(XMVector3Dot(-ray.direction, hit.normal)); XMVECTOR reflectance = f0 + (XM_One - f0) * XMVectorPow(XM_One - nDotV, XMVectorReplicate(5.f)); const XMVECTOR rand = XMVectorReplicate(Random::HaltonSample(m_reflectionProbabilitySampleIndex++, 3)); bool bReflect = XMVector3Greater(reflectance, rand); if (bReflect) { outAttenuation = XM_One; const XMVECTOR reflectDir = XMVector3Normalize(XMVector3Reflect(ray.direction, hit.normal)); outRay = { hit.pos, reflectDir }; return true; } else { outAttenuation = m_albedo->Evaluate(hit.uv); // Random sample direction in unit hemisphere XMFLOAT3 dir = Random::HaltonSampleHemisphere(m_sampleIndex++, 5, 7); // Orthonormal basis about hit normal XMVECTOR b3 = hit.normal; XMFLOAT3 temp; XMStoreFloat3(&temp, b3); XMVECTOR up = std::abs(temp.x) < 0.5f ? XMVECTORF32{ 1.0f, 0.0f, 0.0f } : XMVECTORF32{ 0.0f, 1.0f, 0.0f }; XMVECTOR b1 = XMVector3Cross(up, b3); XMVECTOR b2 = XMVector3Cross(b3, b1); // Project sample direction into ortho basis const XMVECTOR scatterDir = dir.x * b1 + dir.y * b2 + dir.z * b3; outRay = { hit.pos, XMVector3Normalize(scatterDir) }; return true; } } else { return false; } } Metal::Metal(const Texture* reflectance, const XMVECTOR& smoothness) : m_reflectance{ reflectance }, m_smoothness{ smoothness } { } bool Metal::Scatter(const Ray& ray, const Payload& hit, XMVECTOR& outAttenuation, Ray& outRay) const { if (XMVector3Greater(XMVector3Dot(-ray.direction, hit.normal), XM_Zero)) { // Use ray direction to calculate incident angle. This is same as view direction for primary rays. XMVECTOR f0 = GetReflectance(hit.uv); XMVECTOR nDotV = XMVectorSaturate(XMVector3Dot(-ray.direction, hit.normal)); XMVECTOR reflectance = f0 + (XM_One - f0) * XMVectorPow(XM_One - nDotV, XMVectorReplicate(5.f)); uint32_t bReflect; const XMVECTOR rand = XMVectorReplicate(Random::HaltonSample(m_reflectionProbabilitySampleIndex++, 3)); XMVectorGreaterR(&bReflect, reflectance, rand); if (XMComparisonAnyTrue(bReflect)) { outAttenuation = m_reflectance->Evaluate(hit.uv); const XMVECTOR reflectDir = XMVector3Normalize(XMVector3Reflect(ray.direction, hit.normal)); outRay = { hit.pos, reflectDir }; return true; } else { return false; } } else { return false; } } DielectricTransparent::DielectricTransparent(const XMVECTOR& smoothness, const float ior) : m_smoothness{ smoothness } { m_ior = XMVectorReplicate(ior); } bool DielectricTransparent::Scatter(const Ray& ray, const Payload& hit, XMVECTOR& outAttenuation, Ray& outRay) const { // Attenuation of 1 for glass (no absorption) outAttenuation = { 1.f, 1.f, 1.f }; XMVECTOR outwardNormal{}; XMVECTOR niOverNt{}; XMVECTOR cosineIncidentAngle{}; XMVECTOR reflectionProbability{}; if (XMVector3Greater(XMVector3Dot(ray.direction, hit.normal), XM_Zero)) { // Air-to-medium outwardNormal = -hit.normal; niOverNt = m_ior; cosineIncidentAngle = XMVector3Dot(ray.direction, hit.normal); } else { // Medium-to-air outwardNormal = hit.normal; niOverNt = XMVectorReciprocalEst(m_ior); cosineIncidentAngle = XMVector3Dot(ray.direction, -hit.normal); } // Returns < 0.0f, 0.0f, 0.0f, undefined > if result is a total internal reflection XMVECTOR refractDir = XMVector3RefractV(ray.direction, outwardNormal, niOverNt); bool canRefract = XMVector3NotEqual(refractDir, XM_Zero); if (canRefract) { // Valid refraction, but can still be reflected based on fresnel term reflectionProbability = XMFresnelTerm(cosineIncidentAngle, m_ior); } else { // Total Internal Reflection reflectionProbability = XM_One; } const XMVECTOR rand = XMVectorReplicate(Random::HaltonSample(m_sampleIndex++, 7)); if (XMVector3Greater(reflectionProbability, rand)) { const XMVECTOR reflectDir = XMVector3Normalize(XMVector3Reflect(ray.direction, hit.normal)); outRay = { hit.pos, reflectDir }; return true; } else { outRay = { hit.pos, XMVector3Normalize(refractDir) }; return true; } } Emissive::Emissive(const float luminance, const Texture* color) : m_luminance{ luminance }, m_color { color } { } XMVECTOR Emissive::Emit(const Payload& payload) const { return m_luminance * m_color->Evaluate(payload.uv); }
6569592c97f700d9fc6a77d8f6105e879d5c15a8
f8a7b7fbc9001568ace8ff7557ac11c2a4388ce2
/test/include/TestUtil.h
f190de2b6a07fcb924463254d892cce9d825c931
[ "MIT" ]
permissive
m4n1c22/opovlint
9337a78843af9e84c8aa1569492368e64234939d
5e0925650cd469fdcd74240dd0d6ac603097e6f3
refs/heads/master
2021-01-20T05:51:57.684343
2015-10-29T10:03:31
2015-10-29T10:03:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,667
h
/* * TestUtil.h * * Created on: Jun 1, 2014 * Author: ahueck */ #ifndef TESTUTIL_H_ #define TESTUTIL_H_ #include <string> #include <locale> #define T_STRINGIFY_(A) # A #define T_STRINGIFY__(A) T_STRINGIFY_(A) #define T_STRINGIFY(A) T_STRINGIFY__(A) #define REMOVE_WS(_CODE_)\ _CODE_.erase(\ std::remove_if(_CODE_.begin(), _CODE_.end(),\ [](char c) -> bool\ {\ return std::isspace<char>(c, std::locale::classic());\ })\ , _CODE_.end()); static inline std::string trim_str(std::string code) { REMOVE_WS(code) return code; } #define KICKOFF_TEST(_MODULE_, _CODE_MACRO_, _CODE_MACRO_RESULT_)\ SCENARIO("Test the system (state) with " T_STRINGIFY(_MODULE_) " executed 2 times against the same code.", "[kickoff]") {\ GIVEN("The static analyzer with the '" T_STRINGIFY(_MODULE_) "' module.") {\ opov::test::TestApp app;\ app.init();\ app.addModule(new _MODULE_);\ WHEN("A simple code example.") {\ std::string code =_CODE_MACRO_;\ app.executeOnCode(code);\ auto reporter = app.getReporter();\ THEN("One issue is raised.") {\ REQUIRE(reporter->issues.size() == 1);\ AND_THEN("The issues code matches as expected.") {\ auto the_issue = reporter->issues[0];\ std::string code = the_issue->getCode();\ REQUIRE(trim_str(the_issue->getCode()) == trim_str(_CODE_MACRO_RESULT_));\ }\ AND_WHEN("The code again.") {\ app.executeOnCode(code);\ auto reporter = app.getReporter();\ THEN("The same, single issue is raised.") {\ REQUIRE(reporter->issues.size() == 1);\ AND_THEN("The issue resolved to the same code again.") {\ auto the_issue = reporter->issues[0];\ REQUIRE(trim_str(the_issue->getCode()) == trim_str(_CODE_MACRO_RESULT_));\ }\ }\ }\ }\ }\ }\ } #define SIMPLE_TEST1(_WHEN_, _CODE_, _RESULT_)\ WHEN(_WHEN_) {\ app.executeOnCode(_CODE_);\ auto reporter = app.getReporter();\ THEN("One issue is raised.") {\ REQUIRE(reporter->issues.size() == 1);\ AND_THEN("The issues code is the string: " T_STRINGIFY(_RESULT_)) {\ auto the_issue = reporter->issues[0];\ REQUIRE(trim_str(the_issue->getCode()) == trim_str(_RESULT_));\ }\ }\ } #define SIMPLE_TEST0(_WHEN_, _CODE_)\ WHEN(_WHEN_) {\ app.executeOnCode(_CODE_);\ auto reporter = app.getReporter();\ THEN("Zero issues are raised.") {\ if(reporter->issues.size() != 0) {\ auto the_issue = reporter->issues[0];\ REQUIRE(the_issue->getCode() == "");\ }\ REQUIRE(reporter->issues.size() == 0);\ }\ } #endif /* TESTUTIL_H_ */
8c69c4dfd15a996573e62a632b93e115e43e21d7
7bcc95713a4b1be26b601012b2d00825f24a72cf
/lib/Box2D/Box2D/Dynamics/Joints/b2PulleyJoint.cpp
4ec42e3105c3a5cad0c18718ebb8c9400e7c0bb9
[ "Zlib" ]
permissive
aeubanks/mapgen
62066e5c55afd2cc5dee92758133f4a22c6a692d
88bb84dfd498448d97c33affcd066a315e603b34
refs/heads/master
2021-01-11T12:00:17.514803
2017-02-19T06:01:46
2017-02-19T06:01:46
76,683,559
0
0
null
null
null
null
UTF-8
C++
false
false
9,501
cpp
/* * Copyright (c) 2007 Erin Catto http://www.box2d.org * * 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 <Box2D/Dynamics/Joints/b2PulleyJoint.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> // Pulley: // length1 = norm(p1 - s1) // length2 = norm(p2 - s2) // C0 = (length1 + ratio * length2)_initial // C = C0 - (length1 + ratio * length2) // u1 = (p1 - s1) / norm(p1 - s1) // u2 = (p2 - s2) / norm(p2 - s2) // Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) // J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) void b2PulleyJointDef::Initialize(b2Body * bA, b2Body * bB, const b2Vec2 & groundA, const b2Vec2 & groundB, const b2Vec2 & anchorA, const b2Vec2 & anchorB, float32 r) { bodyA = bA; bodyB = bB; groundAnchorA = groundA; groundAnchorB = groundB; localAnchorA = bodyA->GetLocalPoint(anchorA); localAnchorB = bodyB->GetLocalPoint(anchorB); b2Vec2 dA = anchorA - groundA; lengthA = dA.Length(); b2Vec2 dB = anchorB - groundB; lengthB = dB.Length(); ratio = r; b2Assert(ratio > b2_epsilon); } b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef * def) : b2Joint(def) { m_groundAnchorA = def->groundAnchorA; m_groundAnchorB = def->groundAnchorB; m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_lengthA = def->lengthA; m_lengthB = def->lengthB; b2Assert(def->ratio != 0.0f); m_ratio = def->ratio; m_constant = def->lengthA + m_ratio * def->lengthB; m_impulse = 0.0f; } void b2PulleyJoint::InitVelocityConstraints(const b2SolverData & data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // Get the pulley axes. m_uA = cA + m_rA - m_groundAnchorA; m_uB = cB + m_rB - m_groundAnchorB; float32 lengthA = m_uA.Length(); float32 lengthB = m_uB.Length(); if (lengthA > 10.0f * b2_linearSlop) { m_uA *= 1.0f / lengthA; } else { m_uA.SetZero(); } if (lengthB > 10.0f * b2_linearSlop) { m_uB *= 1.0f / lengthB; } else { m_uB.SetZero(); } // Compute effective mass. float32 ruA = b2Cross(m_rA, m_uA); float32 ruB = b2Cross(m_rB, m_uB); float32 mA = m_invMassA + m_invIA * ruA * ruA; float32 mB = m_invMassB + m_invIB * ruB * ruB; m_mass = mA + m_ratio * m_ratio * mB; if (m_mass > 0.0f) { m_mass = 1.0f / m_mass; } if (data.step.warmStarting) { // Scale impulses to support variable time steps. m_impulse *= data.step.dtRatio; // Warm starting. b2Vec2 PA = -(m_impulse)*m_uA; b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; vA += m_invMassA * PA; wA += m_invIA * b2Cross(m_rA, PA); vB += m_invMassB * PB; wB += m_invIB * b2Cross(m_rB, PB); } else { m_impulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData & data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Vec2 vpA = vA + b2Cross(wA, m_rA); b2Vec2 vpB = vB + b2Cross(wB, m_rB); float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); float32 impulse = -m_mass * Cdot; m_impulse += impulse; b2Vec2 PA = -impulse * m_uA; b2Vec2 PB = -m_ratio * impulse * m_uB; vA += m_invMassA * PA; wA += m_invIA * b2Cross(m_rA, PA); vB += m_invMassB * PB; wB += m_invIB * b2Cross(m_rB, PB); data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData & data) { b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Rot qA(aA), qB(aB); b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // Get the pulley axes. b2Vec2 uA = cA + rA - m_groundAnchorA; b2Vec2 uB = cB + rB - m_groundAnchorB; float32 lengthA = uA.Length(); float32 lengthB = uB.Length(); if (lengthA > 10.0f * b2_linearSlop) { uA *= 1.0f / lengthA; } else { uA.SetZero(); } if (lengthB > 10.0f * b2_linearSlop) { uB *= 1.0f / lengthB; } else { uB.SetZero(); } // Compute effective mass. float32 ruA = b2Cross(rA, uA); float32 ruB = b2Cross(rB, uB); float32 mA = m_invMassA + m_invIA * ruA * ruA; float32 mB = m_invMassB + m_invIB * ruB * ruB; float32 mass = mA + m_ratio * m_ratio * mB; if (mass > 0.0f) { mass = 1.0f / mass; } float32 C = m_constant - lengthA - m_ratio * lengthB; float32 linearError = b2Abs(C); float32 impulse = -mass * C; b2Vec2 PA = -impulse * uA; b2Vec2 PB = -m_ratio * impulse * uB; cA += m_invMassA * PA; aA += m_invIA * b2Cross(rA, PA); cB += m_invMassB * PB; aB += m_invIB * b2Cross(rB, PB); data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; data.positions[m_indexB].c = cB; data.positions[m_indexB].a = aB; return linearError < b2_linearSlop; } b2Vec2 b2PulleyJoint::GetAnchorA() const { return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2PulleyJoint::GetAnchorB() const { return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const { b2Vec2 P = m_impulse * m_uB; return inv_dt * P; } float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const { B2_NOT_USED(inv_dt); return 0.0f; } b2Vec2 b2PulleyJoint::GetGroundAnchorA() const { return m_groundAnchorA; } b2Vec2 b2PulleyJoint::GetGroundAnchorB() const { return m_groundAnchorB; } float32 b2PulleyJoint::GetLengthA() const { return m_lengthA; } float32 b2PulleyJoint::GetLengthB() const { return m_lengthB; } float32 b2PulleyJoint::GetRatio() const { return m_ratio; } float32 b2PulleyJoint::GetCurrentLengthA() const { b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); b2Vec2 s = m_groundAnchorA; b2Vec2 d = p - s; return d.Length(); } float32 b2PulleyJoint::GetCurrentLengthB() const { b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); b2Vec2 s = m_groundAnchorB; b2Vec2 d = p - s; return d.Length(); } void b2PulleyJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2PulleyJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); b2Log(" jd.ratio = %.15lef;\n", m_ratio); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); } void b2PulleyJoint::ShiftOrigin(const b2Vec2 & newOrigin) { m_groundAnchorA -= newOrigin; m_groundAnchorB -= newOrigin; }
c3eaf2dd4144da86754a23540d5aecd0761d2782
c019737868718fab1a2603c5c7ab4bf221946e76
/work dialog/jliu/test/build-myTimer-Desktop_Qt_5_9_9_MinGW_32bit-Debug/ui_widget.h
7bb9e88827d410dc0f0a3d645524053b3856b7b6
[ "MIT" ]
permissive
SecretMG/Flower-Mail
af45c0ccb813a87ebc30bdba8c447c6459beb7b5
8f9104b11e2a6380355010ebe7e085a6383dd094
refs/heads/master
2023-07-13T17:23:36.852235
2021-08-04T08:04:42
2021-08-04T08:04:42
293,402,516
2
3
null
null
null
null
UTF-8
C++
false
false
1,493
h
/******************************************************************************** ** Form generated from reading UI file 'widget.ui' ** ** Created by: Qt User Interface Compiler version 5.9.9 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_WIDGET_H #define UI_WIDGET_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Widget { public: QLabel *timeUpdate; void setupUi(QWidget *Widget) { if (Widget->objectName().isEmpty()) Widget->setObjectName(QStringLiteral("Widget")); Widget->resize(800, 600); timeUpdate = new QLabel(Widget); timeUpdate->setObjectName(QStringLiteral("timeUpdate")); timeUpdate->setGeometry(QRect(150, 230, 391, 16)); retranslateUi(Widget); QMetaObject::connectSlotsByName(Widget); } // setupUi void retranslateUi(QWidget *Widget) { Widget->setWindowTitle(QApplication::translate("Widget", "Widget", Q_NULLPTR)); timeUpdate->setText(QApplication::translate("Widget", "TextLabel", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class Widget: public Ui_Widget {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_WIDGET_H
72b0d45a48da5fbf5a5deb0de3a140d268b1ade7
b7979e7bb0a6a4d11829c30533bb68f548c07edb
/src/terrain_generator.hpp
61f7662f445da9c3a29581c024b5f932a63e7830
[ "Apache-2.0" ]
permissive
sweetkristas/roguelike
3ee54cae64b68cd8cae4687357a42a3404b75498
11683c574b34bfc0679c2eed2132653129129e04
refs/heads/master
2021-01-22T11:47:26.686662
2014-09-22T17:59:24
2014-09-22T17:59:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,971
hpp
#pragma once #include <memory> #include <unordered_map> #include "color.hpp" #include "node.hpp" #include "geometry.hpp" #include "surface.hpp" class engine; namespace terrain { typedef unsigned TerrainType; class chunk; typedef std::shared_ptr<chunk> chunk_ptr; struct point_hash { std::size_t operator()(const point& p) const; }; typedef std::unordered_map<point, chunk_ptr, point_hash> terrain_map_type; class terrain_tile { public: terrain_tile(float threshold, TerrainType tt, const std::string& name, const std::string& image, const std::string& transitions_file); TerrainType get_terrain_type() const { return terrain_type_; } float get_threshold() const { return threshold_; } const std::string& get_name() const { return name_; } surface_ptr get_surface() { return surface_; } surface_ptr get_transitions() { return transitions_; } private: float threshold_; TerrainType terrain_type_; std::string name_; surface_ptr surface_; surface_ptr transitions_; }; typedef std::shared_ptr<terrain_tile> terrain_tile_ptr; inline bool operator<(const terrain_tile& lhs, const terrain_tile& rhs) { return lhs.get_threshold() < rhs.get_threshold(); } inline bool operator<(const terrain_tile_ptr& lhs, const terrain_tile_ptr& rhs) { return *lhs < *rhs; } class chunk { public: chunk(const point& pos, int width, int height); ~chunk(); void set_at(int x, int y, float tt); terrain_tile_ptr get_at(int x, int y); TerrainType get_terrain_at(int x, int y); int width() const { return width_; } int height() const { return height_; } const point& get_position() const { return pos_; } void set_surface(surface_ptr surf) { chunk_surface_ = surf; } surface_ptr get_surface() { return chunk_surface_; } void set_transitions_surface(surface_ptr surf) { transitions_surface_ = surf; } surface_ptr get_transitions_surface() { return transitions_surface_; } static surface_ptr make_surface_from_chunk(chunk_ptr chk); void draw(const engine& eng, const point& cam) const; private: point pos_; int width_; int height_; std::vector<std::vector<terrain_tile_ptr>> terrain_; // should make this a texture. surface_ptr chunk_surface_; surface_ptr transitions_surface_; mutable SDL_Texture* texture_; }; typedef std::shared_ptr<chunk> chunk_ptr; class terrain { public: terrain(); //terrain(const node& n); // Find all the chunks which are in the given area, including partials. // Will generate chunks as needed for complete coverage. std::vector<chunk_ptr> get_chunks_in_area(const rect& r); // Pos is the worldspace position. chunk_ptr generate_terrain_chunk(const point& pos); terrain_tile_ptr get_tile_at(const point& p); surface_ptr build_transitions(chunk_ptr chk); static void load_terrain_data(const node& n); static point get_terrain_size(); //node write(); private: int chunk_size_w_; int chunk_size_h_; terrain_map_type chunks_; }; }
568ef1af5991fa2520f9dac21af66e1d21dd56cd
c2fa4e138fa2e605ab594d19aa9c5f8ab75579f8
/google/string_functions.cpp
809451d5d94b8c53a4d3bce28e7526f8bd7eed53
[]
no_license
obedtandadjaja/cpp_exercises
6874ebf561cdf257512d60e8a9cc7e1205ed944f
5082bd27eb3d522203fffc925b77f987ae843a4c
refs/heads/master
2021-04-06T10:58:07.970759
2018-11-17T01:04:38
2018-11-17T01:04:38
124,710,755
0
0
null
null
null
null
UTF-8
C++
false
false
472
cpp
// string_functions: Obed Tandadjaja // Description: substr, insert, replace, find, erase, [] #include <iostream> using namespace std; int main() { string str1 = "To be or not to be, that is the question"; string str2 = "only "; string str3 = str1.substr(6, 12); str1.insert(32, str2); str1.replace(str1.find("to be", 0), 5, "to jump"); str1.erase(9, 4); cout << str1 << endl; for (int i = 0; i < str3.length(); i++) cout << str3[i]; cout << endl; }
59bfb07bc65466d23e29ee048dc0f90c4a915248
d22e7a298458cf2bb7fc050b59fd585cd1f7e0c4
/source/ControlsLib/AdvancedEditControl/BCGPOutlineParser.h
4b52629fecf7440d0e689a3c828bf33279062185
[ "MIT", "CC-BY-4.0" ]
permissive
egorpushkin/neurolab
9cad44104dcfe199aa63dd6fd9669c063e29d5e8
08daa763f13982d2214bbc9cd9060a0709542d7e
refs/heads/master
2021-05-04T18:49:01.131630
2017-10-19T21:52:40
2017-10-19T21:52:40
106,142,310
2
0
null
2017-10-09T03:21:07
2017-10-08T01:34:09
null
UTF-8
C++
false
false
4,722
h
// BCGPOutlineParser.h: interface for the CBCGPOutlineParser class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_BCGPOUTLINEPARSER_H__042FF594_A696_4902_A475_119896175319__INCLUDED_) #define AFX_BCGPOUTLINEPARSER_H__042FF594_A696_4902_A475_119896175319__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 enum LexemType { LT_CompleteBlock = 1, LT_BlockStart = 2, LT_BlockEnd = 3, LT_EndOfText = -1, LT_Eps = 0 }; struct BCGCBPRODLLEXPORT Lexeme { Lexeme () : m_nBlockType (0), m_nType (LT_Eps), m_nStart (0), m_nEnd (0) { } Lexeme (int nBlockType, LexemType nLexemType, int nStart, int nEnd) : m_nBlockType (nBlockType), m_nType (nLexemType), m_nStart (nStart), m_nEnd (nEnd) { } LexemType m_nType; int m_nBlockType; int m_nStart; int m_nEnd; }; struct BCGCBPRODLLEXPORT BlockType { BlockType () : m_bAllowNestedBlocks (TRUE), m_bIgnore (FALSE) { } BlockType ( LPCTSTR lpszOpen, LPCTSTR lpszClose, LPCTSTR lpszReplace, BOOL bNested, BOOL bIgnore = FALSE, CStringList* pKeywords = NULL) : m_strOpen (lpszOpen), m_strClose (lpszClose), m_strReplace (lpszReplace), m_bAllowNestedBlocks (bNested), m_bIgnore (bIgnore) { if (pKeywords != NULL) { m_lstKeywords.AddTail (pKeywords); } } CString m_strOpen; CString m_strClose; CString m_strReplace; BOOL m_bAllowNestedBlocks; BOOL m_bIgnore; CStringList m_lstKeywords; }; ///////////////////////////////////////// // Default parser for outlining support: // class CBCGPOutlineBaseNode; class CBCGPOutlineNode; struct BCGP_EDIT_OUTLINE_CHANGES; class BCGCBPRODLLEXPORT CBCGPOutlineParser : public CObject { public: CBCGPOutlineParser(); virtual ~CBCGPOutlineParser(); virtual void UpdateOutlining (CString& strBuffer, int nOffsetFrom, int nCharsCount, CBCGPOutlineNode* pOutlineNode, BCGP_EDIT_OUTLINE_CHANGES& changes); virtual void Init (); virtual void AddBlockType ( LPCTSTR lpszOpen, LPCTSTR lpszClose, LPCTSTR lpszReplace = NULL, BOOL bNested = TRUE, BOOL bIgnore = FALSE, CStringList* pKeywordsList = NULL); virtual void AddEscapeSequence (LPCTSTR lpszStr); virtual void RemoveAllBlockTypes (); const BlockType* GetBlockType (int nIndex) const; BOOL IsValuedChar (TCHAR ch) const; protected: // Text processing: virtual Lexeme GetNext (const CString& strIn, int& nOffset, const int nSearchTo); virtual void PushResult (Lexeme lexem, CObList& lstResults); virtual void DoParse (const CString& strBuffer, const int nStartOffset, const int nEndOffset, CObList& lstResults); BOOL IsEscapeSequence (const CString& strBuffer, int& nBufferOffset) const; BOOL Compare (const CString& strBuffer, const int nBufferOffset, const CString& strCompareWith, int& nEndOffset) const; virtual void DoUpdateOffsets (const CString& strBuffer, const int nStartOffset, const int nEndOffset, CObList& lstBlocks); virtual int GetNameOffset (const CString& strIn, int nStartFrom, int nSearchTo, const BlockType* pBlockType, CObList& lstIgnore, CString& strName); virtual int GetStartOffset (const CString& strIn, int nStartFrom, int nSearchTo, CObList& lstIgnore); virtual int GetEndOffset (const CString& strIn, int nStartFrom, int nSearchTo); virtual int GetPrevWord (const CString& strIn, int nStartFrom, int nSearchTo, LPCTSTR lpszStopDelimiters, CString& strWord); virtual BOOL IsBlockName (const CString& strIn, CString& strWord, const int nOffset, const int nSearchTo); // Outline tree updating methods: virtual BOOL AddMarker (CBCGPOutlineNode* pMarkerBlock, CBCGPOutlineNode* pParentNode, BCGP_EDIT_OUTLINE_CHANGES& changes) const; virtual CBCGPOutlineNode* FindFittingBlock (CBCGPOutlineNode* pBlock, CBCGPOutlineNode* pStartFrom) const; virtual CBCGPOutlineNode* GetRangeToReparse (CBCGPOutlineNode* pOutlineNode, int& nStartOffset, int& nEndOffset) const; inline CBCGPOutlineNode* AddNode (CBCGPOutlineNode* pNewNode, CBCGPOutlineNode* pParentNode, BCGP_EDIT_OUTLINE_CHANGES& changes) const; inline CBCGPOutlineNode* RemoveNode (CBCGPOutlineNode* pNode, CBCGPOutlineNode* pParentNode, BCGP_EDIT_OUTLINE_CHANGES& changes, BOOL bRemoveSubNodes = FALSE) const; public: // data: CArray <BlockType*, BlockType*> m_arrBlockTypes; CStringList m_lstEscapeSequences; CString m_strDelimiters; BOOL m_bCaseSensitive; BOOL m_bWholeWords; CString m_strOut; // for test purpose only }; #endif // !defined(AFX_BCGPOUTLINEPARSER_H__042FF594_A696_4902_A475_119896175319__INCLUDED_)
46cb8d306fb6d0f31b85a8741b0010c6d9ad55f9
1468339480904af236c936cb293941e6dab4e47e
/_includes/leet050/leet050_1.cpp
3c29856a4f81f3ff24c2bb5c1902346889245753
[ "MIT" ]
permissive
mingdaz/leetcode
3ede40f2e9550bc0d7f8d42768a28dd84865446e
64f2e5ad0f0446d307e23e33a480bad5c9e51517
refs/heads/master
2023-02-04T14:31:25.837909
2020-01-25T05:39:47
2020-01-25T05:39:47
45,284,439
0
0
MIT
2023-01-20T10:00:53
2015-10-31T01:30:02
C++
UTF-8
C++
false
false
564
cpp
class Solution { public: double myPow(double x, long n) { if(n==0) return 1.0; if(n<0) return 1.0/myPow(x,-n); vector<double> ret(32,1.0); long pow = 1; int i; double tmp = x; for(i=1;i<32&&pow<=n/2;i++){ ret[i] = tmp; tmp = tmp*tmp; pow = pow*2; } n -= pow; while(n>0){ while(pow >n){ pow/=2; i--; } tmp *= ret[i]; n -= pow; } return tmp; } };
3bdb9979e224b73fc227e044c2785dabf20a773b
42188e37fa104a2928b619ad8d985b870575857d
/homicidio.hpp
8dce52b0539224730432fc682c8646803a330a82
[]
no_license
wecarrasco/Laboratorio7
654d44f7197eb09b079ac089ed5303c0f2d3ac0c
abf8c89e22210f5514fc3b72c9259f18a0c6ac04
refs/heads/master
2021-01-21T13:18:24.977146
2015-06-19T23:49:17
2015-06-19T23:49:17
37,344,709
0
0
null
null
null
null
UTF-8
C++
false
false
600
hpp
#pragma once #include "casos.hpp" #include <string> using namespace std; class homicidio: public casos{ public: homicidio(string sospechoso_p, string culpable, string victima, int num_caso, string hour, string date, bool closed); homicidio(const homicidio&); virtual ~homicidio(); virtual string toString()const; string getSospechoso_p()const; void setSospechoso_p(string); string getCulpable()const; void setCulpable(string); string getVictima()const; void setVictima(string); protected: vector<string>sospechosos; string sospechoso_p; string culpable; string victima; };
716478a8f4e23e989a47606e820a8ead015b679b
66b74bae8bafcb471d657359ced6fb4fcea1f0a9
/src/rotors_simulator/rotors_gazebo_plugins/include/rotors_gazebo_plugins/gazebo_multirotor_base_plugin.h
b28422a073dbf704597265546824f31243ea6139
[ "BSD-2-Clause" ]
permissive
kant/CLDrone
41f1c01b2fbc52ad5b34ad69f0942af114aec2f1
fe18ccde70052390861b2c000100f8eaa122b99b
refs/heads/master
2020-05-24T22:38:58.139961
2016-11-18T02:45:49
2016-11-18T02:45:49
187,500,820
0
0
BSD-2-Clause
2019-05-19T16:24:44
2019-05-19T16:24:44
null
UTF-8
C++
false
false
3,187
h
/* * Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland * Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland * Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland * Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland * Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef ROTORS_GAZEBO_PLUGINS_GAZEBO_MULTIROTOR_BASE_PLUGIN_H #define ROTORS_GAZEBO_PLUGINS_GAZEBO_MULTIROTOR_BASE_PLUGIN_H #include <string> #include <gazebo/common/common.hh> #include <gazebo/common/Plugin.hh> #include <gazebo/gazebo.hh> #include <gazebo/physics/physics.hh> #include <mav_msgs/MotorSpeed.h> #include <ros/ros.h> #include "rotors_gazebo_plugins/common.h" namespace gazebo { // Default values static const std::string kDefaultNamespace = ""; static const std::string kDefaultMotorPubTopic = "motors"; static const std::string kDefaultLinkName = "base_link"; static const std::string kDefaultFrameId = "base_link"; static constexpr double kDefaultRotorVelocitySlowdownSim = 10.0; /// \brief This plugin publishes the motor speeds of your multirotor model. class GazeboMultirotorBasePlugin : public ModelPlugin { typedef std::map<const unsigned int, const physics::JointPtr> MotorNumberToJointMap; typedef std::pair<const unsigned int, const physics::JointPtr> MotorNumberToJointPair; public: GazeboMultirotorBasePlugin() : ModelPlugin(), namespace_(kDefaultNamespace), motor_pub_topic_(kDefaultMotorPubTopic), link_name_(kDefaultLinkName), frame_id_(kDefaultFrameId), rotor_velocity_slowdown_sim_(kDefaultRotorVelocitySlowdownSim), node_handle_(NULL) {} virtual ~GazeboMultirotorBasePlugin(); protected: /// \brief Load the plugin. /// \param[in] _model Pointer to the model that loaded this plugin. /// \param[in] _sdf SDF element that describes the plugin. void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf); /// \brief Called when the world is updated. /// \param[in] _info Update timing information. void OnUpdate(const common::UpdateInfo& /*_info*/); private: /// \brief Pointer to the update event connection. event::ConnectionPtr update_connection_; physics::WorldPtr world_; physics::ModelPtr model_; physics::LinkPtr link_; physics::Link_V child_links_; MotorNumberToJointMap motor_joints_; std::string namespace_; std::string motor_pub_topic_; std::string link_name_; std::string frame_id_; double rotor_velocity_slowdown_sim_; ros::Publisher motor_pub_; ros::NodeHandle *node_handle_; }; } #endif // ROTORS_GAZEBO_PLUGINS_GAZEBO_MULTIROTOR_BASE_PLUGIN_H
06fe85477c77aa6d58dcbe3e95f73cd21fb3259c
8f3d9eb1d632282a55ea5a5c3dfe6f23e6d1b76c
/Wawaji-Server-Windows/wwj_demo/tool_kits/duilib/Core/GlobalManager.h
b0d09964e997d74120bd8980f6a19c0279f319a4
[ "MIT" ]
permissive
jzsplk/Wawaji
086580efb5ecf952b990a36bb5cd8a6a9a1fc6f7
45c51c3cd1b49a4a926b76b6e4e31a331ede66ee
refs/heads/master
2020-03-12T15:29:40.437612
2018-04-23T12:03:00
2018-04-23T12:03:00
130,691,413
1
0
null
2018-04-23T12:13:28
2018-04-23T12:13:28
null
GB18030
C++
false
false
4,956
h
#ifndef UI_CORE_WINDOWHELPER_H_ #define UI_CORE_WINDOWHELPER_H_ #pragma once #include "Image.h" #include "Window.h" namespace ui { ///////////////////////////////////////////////////////////////////////////////////// // typedef Control* (*LPCREATECONTROL)(const std::wstring& pstrType); class UILIB_API GlobalManager { public: static void Startup(const std::wstring& resourcePath, const CreateControlCallback& callback); static void Shutdown(); static std::wstring GetCurrentPath(); static std::wstring GetResourcePath(); static void SetCurrentPath(const std::wstring& strPath); static void SetResourcePath(const std::wstring& strPath); static void MessageLoop(); static bool TranslateMessage(const LPMSG pMsg); static std::wstring GetDefaultFontName() { return m_pStrDefaultFontName; } static void AddTextColor(const std::wstring& strName, const std::wstring& strValue); static std::wstring GetTextColor(const std::wstring& strName); static DWORD ConvertTextColor(const std::wstring& strName); static void AddClass(const std::wstring& strClassName, const std::wstring& strControlAttrList); static std::wstring GetClassAttributes(const std::wstring& strClassName); static void AddPreMessage(Window* windowManagerUI) { m_aPreMessages.push_back(windowManagerUI); } static void RemovePreMessage(Window* windowManagerUI) { auto it = std::find(m_aPreMessages.begin(), m_aPreMessages.end(), windowManagerUI); if (it != m_aPreMessages.end()) { m_aPreMessages.erase(it); } } static std::shared_ptr<ImageInfo> IsImageCached(const std::wstring& bitmap); static void OnImageInfoDestroy(ImageInfo* imageInfo); static std::shared_ptr<ImageInfo> AddImageCached(const std::shared_ptr<ImageInfo>& shared_image); static std::shared_ptr<ImageInfo> GetImage(const std::wstring& bitmap); static void RemoveFromImageCache(const std::wstring& imageFullPath); static HFONT AddFont(const std::wstring& strFontName, int nSize, bool bBold, bool bUnderline, bool bItalic); static TFontInfo* GetTFontInfo(std::size_t index); static HFONT GetFont(std::size_t index); static HFONT GetFont(const std::wstring& strFontName, int nSize, bool bBold, bool bUnderline, bool bItalic); static TFontInfo* GetFontInfo(std::size_t index, HDC hDcPaint); static TFontInfo* GetFontInfo(HFONT hFont, HDC hDcPaint); static bool FindFont(HFONT hFont); static bool FindFont(const std::wstring& strFontName, int nSize, bool bBold, bool bUnderline, bool bItalic); static bool RemoveFontAt(std::size_t index); static void RemoveAllFonts(); static std::wstring GetDefaultDisabledTextColor(); static void SetDefaultDisabledTextColor(const std::wstring& dwColor); static std::wstring GetDefaultTextColor(); static void SetDefaultTextColor(const std::wstring& dwColor); static DWORD GetDefaultLinkFontColor(); static void SetDefaultLinkFontColor(DWORD dwColor); static DWORD GetDefaultLinkHoverFontColor(); static void SetDefaultLinkHoverFontColor(DWORD dwColor); static DWORD GetDefaultSelectedBkColor(); static void SetDefaultSelectedBkColor(DWORD dwColor); static bool IsOsOverXp(); static Box* CreateBox(const std::wstring& xmlPath, CreateControlCallback callback = CreateControlCallback()); static Box* CreateBoxWithCache(const std::wstring& xmlPath, CreateControlCallback callback = CreateControlCallback()); static void FillBox(Box* userDefinedBox, const std::wstring& xmlPath, CreateControlCallback callback = CreateControlCallback()); static void FillBoxWithCache(Box* userDefinedBox, const std::wstring& xmlPath, CreateControlCallback callback = CreateControlCallback()); static Control* CreateControl(const std::wstring& controlStr); private: class ImageCacheKeyCompare { public: // 这个比较函数不是比较字典序的,而是按照以下法则: // 首先比较,长度小的更小 // 再逆向比较,可以认为是逆向字典序 bool operator()(const std::wstring& key1, const std::wstring& key2) const; }; typedef std::map<std::wstring, std::weak_ptr<ImageInfo>, ImageCacheKeyCompare> MapStringToImagePtr; static std::vector<TFontInfo*> m_aCustomFonts; static MapStringToImagePtr m_mImageHash; static std::vector<Window*> m_aPreMessages; static std::map<std::wstring, std::wstring> m_mapTextColor; static std::map<std::wstring, std::wstring> m_GlobalClass; static std::wstring m_pStrResourcePath; //全局的资源路径,换肤的时候修改这个变量 static short m_H; static short m_S; static short m_L; static std::wstring m_pStrDefaultFontName; static std::wstring m_dwDefaultDisabledColor; static std::wstring m_dwDefaultFontColor; static DWORD m_dwDefaultLinkFontColor; static DWORD m_dwDefaultLinkHoverFontColor; static DWORD m_dwDefaultSelectedBkColor; static std::map<std::wstring, std::unique_ptr<WindowBuilder>> m_winowBuilderMap; static CreateControlCallback m_createControlCallback; }; } // namespace ui #endif // UI_CORE_WINDOWHELPER_H_
b0d0ce69be9b12ecaf5f5b038e2a03a9e4109db1
029b4ff88fe5a5b52ded9f96fba3730b283678a6
/PDFWriterTestPlayground/DFontTest.cpp
7018a398ca152baf79fe1e7c03e292c6b0c92faa
[ "Apache-2.0" ]
permissive
CornerZhang/PDF-Writer
6e913804219a8679ede96daa57bea990ca6e769e
de12df009d54830600ef45c62e1a747d4260f071
refs/heads/master
2021-01-16T21:01:06.699193
2016-05-23T06:08:59
2016-05-23T06:08:59
61,166,742
1
0
null
2016-06-15T01:05:14
2016-06-15T01:05:13
null
UTF-8
C++
false
false
3,236
cpp
/* Source File : DFontTest.cpp Copyright 2013 Gal Kahana PDFWriter Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "DFontTest.h" #include "TestsRunner.h" #include "PDFWriter.h" #include "PDFPage.h" #include "PageContentContext.h" #include <iostream> using namespace PDFHummus; DFontTest::DFontTest() { } DFontTest::~DFontTest() { } EStatusCode DFontTest::Run(const TestConfiguration& inTestConfiguration) { PDFWriter pdfWriter; EStatusCode status; do { status = pdfWriter.StartPDF( RelativeURLToLocalPath(inTestConfiguration.mSampleFileBase,"DFontTest.PDF"), ePDFVersion13, LogConfiguration(true,true,RelativeURLToLocalPath(inTestConfiguration.mSampleFileBase,"DFontTest.log"))); if(status != eSuccess) { cout<<"failed to start PDF\n"; break; } PDFUsedFont* courierFonts[4]; for(int i=0; i < 4 && eSuccess == status; ++i) { courierFonts[i] = pdfWriter.GetFontForFile(RelativeURLToLocalPath(inTestConfiguration.mSampleFileBase,"TestMaterials/fonts/courier.dfont"),i); if(!courierFonts[i]) { status = eFailure; cout<<"Failed to create font object for lucida Grande font at "<<i<<"\n"; break; } } if(status != eSuccess) break; PDFPage* page = new PDFPage(); page->SetMediaBox(PDFRectangle(0,0,595,842)); PageContentContext* contentContext = pdfWriter.StartPageContentContext(page); if(NULL == contentContext) { status = eFailure; cout<<"failed to create content context for page\n"; break; } for(int i=0;i<4;++i) { contentContext->BT(); contentContext->k(0,0,0,1); contentContext->Tf(courierFonts[i],1); contentContext->Tm(30,0,0,30,78.4252,662.8997 - i*100); EStatusCode encodingStatus = contentContext->Tj("Hello World!"); if(encodingStatus != eSuccess) cout<<"Could not find some of the glyphs for this font"; contentContext->ET(); } status = pdfWriter.EndPageContentContext(contentContext); if(status != eSuccess) { cout<<"failed to end page content context\n"; break; } status = pdfWriter.WritePageAndRelease(page); if(status != eSuccess) { cout<<"failed to write page\n"; break; } status = pdfWriter.EndPDF(); if(status != eSuccess) { cout<<"failed in end PDF\n"; break; } }while(false); return status; } ADD_CATEGORIZED_TEST(DFontTest,"Font Packages")
c809129d566855ca7660fdfe75b49973d698ce3d
b146e1042c8ef3f9d16b7273f6d73a13ae5a79be
/app/src/main/cpp/thirdparty/include/glm/ext/matrix_double4x4_precision.hpp
36f1c826bcf3b21c113d0e0173d72d3cc0b306b4
[]
no_license
Bo007/android_opengl
3efe3be882ff6f9e5d93d4d972f0d1acf8d715ec
ae95b1b58bfc8b142532ef8425e40020cc566b60
refs/heads/master
2020-06-13T03:02:31.136486
2019-07-21T11:10:02
2019-07-21T11:10:02
194,510,556
1
0
null
null
null
null
UTF-8
C++
false
false
3,068
hpp
/// @ref core /// @file glm/ext/matrix_double4x4_precision.hpp #pragma once #include "../detail/type_mat4x4.hpp" namespace glm { /// @addtogroup core_matrix_precision /// @{ /// 4 columns of 4 components matrix of double-precision floating-point numbers using low precision arithmetic in term of ULPs. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef mat<4, 4, double, lowp> lowp_dmat4; /// 4 columns of 4 components matrix of double-precision floating-point numbers using medium precision arithmetic in term of ULPs. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef mat<4, 4, double, mediump> mediump_dmat4; /// 4 columns of 4 components matrix of double-precision floating-point numbers using medium precision arithmetic in term of ULPs. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef mat<4, 4, double, highp> highp_dmat4; /// 4 columns of 4 components matrix of double-precision floating-point numbers using low precision arithmetic in term of ULPs. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef mat<4, 4, double, lowp> lowp_dmat4x4; /// 4 columns of 4 components matrix of double-precision floating-point numbers using medium precision arithmetic in term of ULPs. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef mat<4, 4, double, mediump> mediump_dmat4x4; /// 4 columns of 4 components matrix of double-precision floating-point numbers using medium precision arithmetic in term of ULPs. /// /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.1.6 Matrices</a> /// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 4.7.2 Precision Qualifier</a> typedef mat<4, 4, double, highp> highp_dmat4x4; /// @} }//namespace glm
5575d58c3b9fa17677cce118a8bb7cb8ea691530
62b4591685eb0af553ffba1486dd2ed96a9d56da
/example/server/httpservice/HttpSession.h
a21dd3d6d08bac5fc397968bef757bdecf43a7cb
[]
no_license
kspine/sframe
4cabce5c415bc99949b773a63f36552b63d8eea3
ee6b066643b2a7f496e8a614572af8bddd1a7cc4
refs/heads/master
2021-01-25T09:38:10.410637
2017-03-24T20:04:06
2017-03-24T20:04:06
null
0
0
null
null
null
null
GB18030
C++
false
false
966
h
#ifndef __HTTP_SESSION_H__ #define __HTTP_SESSION_H__ #include <inttypes.h> #include <memory> #include "net/net.h" #include "util/Http.h" class HttpService; class HttpSession : public sframe::TcpSocket::Monitor { public: HttpSession(HttpService * http_service, const std::shared_ptr<sframe::TcpSocket> & sock, int64_t session_id); ~HttpSession() {} // 接收到数据 // 返回剩余多少数据 int32_t OnReceived(char * data, int32_t len) override; // Socket关闭 // by_self: true表示主动请求的关闭操作 void OnClosed(bool by_self, sframe::Error err) override; void StartClose(); int64_t GetSessionId() const { return _session_id; } void OnMsg_HttpRequest(std::shared_ptr<sframe::HttpRequest> http_req); void OnMsg_HttpSessionClosed(); private: HttpService * _http_service; std::shared_ptr<sframe::TcpSocket> _sock; int64_t _session_id; sframe::HttpDecoder _http_decoder; }; #endif
4363823993429fdae8d4ad2f3fe070d3988c99ec
b490b4fb291c7c9ab4aef55e543b315637813474
/OpenGL.h
95cb9943a0d097fdfbb2fdf1c7ab97133bb3863d
[]
no_license
ignore444/RSM-2
9d5eb59de836b940e6abece34fb0bc8e14bf3fd2
42d7aa1186cb6eb7ac76e9eb104c7fc551694837
refs/heads/master
2022-01-11T20:20:17.406009
2019-03-13T01:27:42
2019-03-13T01:27:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,303
h
#ifndef OpenGL_h #define OpenGL_h #define BUFFER_OFFSET(bytes) ((void*) (bytes)) #define ELEMENTS_PER_VERTEX 3 #define ELEMENTS_PER_MATRIX 16 #define HOMOGENEOUS_VECTOR_SIZE 4 #define VECTOR_SIZE_3D 3 #define TEX_ELEMENTS_PER_VERTEX 2 #include <iostream> #include <armadillo> #include <OpenGL/gl3.h> #include <vector> #include <map> #include "Shaders.h" #include "OpenGLGeometry.h" #include "Atlas.h" #include "Object3D.h" #include "Light.h" #include <ft2build.h> #include FT_FREETYPE_H #include "Configuration.h" using namespace std; using namespace arma; class OpenGL { private: ///////////////////////////////////////// Lighting and material variables ////////////////////////////////////////// struct Lighting { vec4 ambient; vec4 diffuse; vec4 specular; float shininess; }; // Shading state variables. Lighting material = { // Material properties (to be changed). { 0.8, 0.8, 0.8, 1.0 }, // Ambient: k_a. { 0.8, 0.8, 0.8, 1.0 }, // Diffuse: k_d. { 0.8, 0.8, 0.8, 1.0 }, // Specular: k_s. 64.0 // Shininess. }; //////////////////////////////////////////// OpenGL rendering variables //////////////////////////////////////////// struct GeometryBuffer { GLuint bufferID; // Buffer ID given by OpenGL. GLuint verticesCount; // Number of vertices stored in buffer. }; enum GeometryTypes { CUBE, SPHERE, CYLINDER, PRISM }; GLuint renderingProgram; // Geom/sequence full color renderer's shader program. GLuint vao; // Vertex array object for usual data layout. GeometryBuffer* cube = nullptr; // Buffers for solids. GeometryBuffer* sphere = nullptr; GeometryBuffer* cylinder = nullptr; GeometryBuffer* prism = nullptr; GeometryBuffer* path = nullptr; // Buffer for dots and paths (sequences). GeometryBuffer* ndcQuad = nullptr; // Normalized device coordinates quad. bool usingUniformScaling = true; // True if only uniform scaling is used. map<string, Object3D> objectModels; // Store 3D object models per kind. /////////////////////////////////////////////// FreeType variables ///////////////////////////////////////////////// struct GlyphPoint { GLfloat x; GLfloat y; GLfloat s; GLfloat t; }; FT_Library ft = nullptr; FT_Face face = nullptr; GLuint glyphsProgram; // Glyphs shaders program. GLuint glyphsBufferID; // Glyphs buffer ID. void sendShadingInformation( const mat44& Projection, const mat44& Camera, const mat44& Model, bool usingBlinnPhong, bool usingTexture = false ); GLint setSequenceInformation( const mat44& Projection, const mat44& Camera, const mat44& Model, const vector<vec3>& vertices ); void drawGeom( const mat44& Projection, const mat44& Camera, const mat44& Model, GeometryBuffer** G, GeometryTypes t ); void initGlyphs(); public: Atlas* atlas48 = nullptr; // Atlases (i.e. font texture maps). Atlas* atlas24 = nullptr; Atlas* atlas12 = nullptr; OpenGL(); ~OpenGL(); void init(); void setColor( float r, float g, float b, float a = 1.0f, float shininess = 64.0f ); void drawCube( const mat44& Projection, const mat44& Camera, const mat44& Model ); void drawSphere( const mat44& Projection, const mat44& Camera, const mat44& Model ); void drawCylinder( const mat44& Projection, const mat44& Camera, const mat44& Model ); void drawPrism( const mat44& Projection, const mat44& Camera, const mat44& Model ); void drawPath( const mat44& Projection, const mat44& Camera, const mat44& Model, const vector<vec3>& vertices ); void drawPoints( const mat44& Projection, const mat44& Camera, const mat44& Model, const vector<vec3>& vertices, float size = 10.0f ); void render3DObject( const mat44& Projection, const mat44& Camera, const mat44& Model, const char* objectType, bool useTexture = false, int textureUnit = 1 ); void renderNDCQuad(); void renderText( const char* text, const Atlas* a, float x, float y, float sx, float sy, const float* color ); GLuint getGlyphsProgram(); void setUsingUniformScaling( bool u ); void create3DObject( const char* name, const char* filename, const char* textureFilename = nullptr ); void useProgram( GLuint program ); void setLighting( const Light& light, const mat44& View, bool lightInViewCoordinates = true ); }; #endif /* OpenGL_h */
6ba2297d3e080d5d4dde783acc7b57488d8e4fc6
cbed802efec5d700794f170b2a83684bf05813fb
/src/chrome/browser/speech/chrome_speech_recognition_manager_delegate.cc
00e36dfbbaec6442b218417b497f36231f7f8e29
[ "BSD-3-Clause" ]
permissive
oddish314/Aviator
4affc878c9061ca14ac08a226c0f3b181f2bc91c
91c4d4b6343166d702413b1403d325e4935839e5
refs/heads/master
2021-01-22T09:50:36.731707
2015-02-09T11:34:05
2015-02-09T11:34:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,664
cc
// Copyright (c) 2012 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/speech/chrome_speech_recognition_manager_delegate.h" #include <set> #include <string> #include "base/bind.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/lock.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/tab_contents/tab_util.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/resource_context.h" #include "content/public/browser/speech_recognition_manager.h" #include "content/public/browser/speech_recognition_session_config.h" #include "content/public/browser/speech_recognition_session_context.h" #include "content/public/browser/web_contents.h" #include "content/public/common/speech_recognition_error.h" #include "content/public/common/speech_recognition_result.h" #include "extensions/browser/view_type_utils.h" #include "net/url_request/url_request_context_getter.h" #if defined(OS_WIN) #include "chrome/installer/util/wmi.h" #endif using content::BrowserThread; using content::SpeechRecognitionManager; using content::WebContents; namespace speech { namespace { void TabClosedCallbackOnIOThread(int render_process_id, int render_view_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); SpeechRecognitionManager* manager = SpeechRecognitionManager::GetInstance(); // |manager| becomes NULL if a browser shutdown happens between the post of // this task (from the UI thread) and this call (on the IO thread). In this // case we just return. if (!manager) return; manager->AbortAllSessionsForRenderView(render_process_id, render_view_id); } } // namespace // Asynchronously fetches the PC and audio hardware/driver info if // the user has opted into UMA. This information is sent with speech input // requests to the server for identifying and improving quality issues with // specific device configurations. class ChromeSpeechRecognitionManagerDelegate::OptionalRequestInfo : public base::RefCountedThreadSafe<OptionalRequestInfo> { public: OptionalRequestInfo() : can_report_metrics_(false) { } void Refresh() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // UMA opt-in can be checked only from the UI thread, so switch to that. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&OptionalRequestInfo::CheckUMAAndGetHardwareInfo, this)); } void CheckUMAAndGetHardwareInfo() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // prefs::kMetricsReportingEnabled is not registered for OS_CHROMEOS. #if !defined(OS_CHROMEOS) if (g_browser_process->local_state()->GetBoolean( prefs::kMetricsReportingEnabled)) { // Access potentially slow OS calls from the FILE thread. BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE, base::Bind(&OptionalRequestInfo::GetHardwareInfo, this)); } #endif } void GetHardwareInfo() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); base::AutoLock lock(lock_); can_report_metrics_ = true; base::string16 device_model = SpeechRecognitionManager::GetInstance()->GetAudioInputDeviceModel(); #if defined(OS_WIN) value_ = base::UTF16ToUTF8( installer::WMIComputerSystem::GetModel() + L"|" + device_model); #else // defined(OS_WIN) value_ = base::UTF16ToUTF8(device_model); #endif // defined(OS_WIN) } std::string value() { base::AutoLock lock(lock_); return value_; } bool can_report_metrics() { base::AutoLock lock(lock_); return can_report_metrics_; } private: friend class base::RefCountedThreadSafe<OptionalRequestInfo>; ~OptionalRequestInfo() {} base::Lock lock_; std::string value_; bool can_report_metrics_; DISALLOW_COPY_AND_ASSIGN(OptionalRequestInfo); }; // Simple utility to get notified when a WebContent (a tab or an extension's // background page) is closed or crashes. The callback will always be called on // the UI thread. // There is no restriction on the constructor, however this class must be // destroyed on the UI thread, due to the NotificationRegistrar dependency. class ChromeSpeechRecognitionManagerDelegate::TabWatcher : public base::RefCountedThreadSafe<TabWatcher>, public content::NotificationObserver { public: typedef base::Callback<void(int render_process_id, int render_view_id)> TabClosedCallback; explicit TabWatcher(TabClosedCallback tab_closed_callback) : tab_closed_callback_(tab_closed_callback) { } // Starts monitoring the WebContents corresponding to the given // |render_process_id|, |render_view_id| pair, invoking |tab_closed_callback_| // if closed/unloaded. void Watch(int render_process_id, int render_view_id) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &TabWatcher::Watch, this, render_process_id, render_view_id)); return; } WebContents* web_contents = tab_util::GetWebContentsByID(render_process_id, render_view_id); // Sessions initiated by speech input extension APIs will end up in a NULL // WebContent here, but they are properly managed by the // chrome::SpeechInputExtensionManager. However, sessions initiated within a // extension using the (new) speech JS APIs, will be properly handled here. // TODO(primiano) turn this line into a DCHECK once speech input extension // API is deprecated. if (!web_contents) return; // Avoid multiple registrations on |registrar_| for the same |web_contents|. if (FindWebContents(web_contents) != registered_web_contents_.end()) { return; } registered_web_contents_.push_back( WebContentsInfo(web_contents, render_process_id, render_view_id)); // Lazy initialize the registrar. if (!registrar_.get()) registrar_.reset(new content::NotificationRegistrar()); registrar_->Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<WebContents>(web_contents)); registrar_->Add(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::Source<WebContents>(web_contents)); } // content::NotificationObserver implementation. virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(type == content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED || type == content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED); WebContents* web_contents = content::Source<WebContents>(source).ptr(); std::vector<WebContentsInfo>::iterator iter = FindWebContents(web_contents); DCHECK(iter != registered_web_contents_.end()); int render_process_id = iter->render_process_id; int render_view_id = iter->render_view_id; registered_web_contents_.erase(iter); registrar_->Remove(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED, content::Source<WebContents>(web_contents)); registrar_->Remove(this, content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED, content::Source<WebContents>(web_contents)); tab_closed_callback_.Run(render_process_id, render_view_id); } private: struct WebContentsInfo { WebContentsInfo(content::WebContents* web_contents, int render_process_id, int render_view_id) : web_contents(web_contents), render_process_id(render_process_id), render_view_id(render_view_id) {} ~WebContentsInfo() {} content::WebContents* web_contents; int render_process_id; int render_view_id; }; friend class base::RefCountedThreadSafe<TabWatcher>; virtual ~TabWatcher() { // Must be destroyed on the UI thread due to |registrar_| non thread-safety. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); } // Helper function to find the iterator in |registered_web_contents_| which // contains |web_contents|. std::vector<WebContentsInfo>::iterator FindWebContents( content::WebContents* web_contents) { for (std::vector<WebContentsInfo>::iterator i( registered_web_contents_.begin()); i != registered_web_contents_.end(); ++i) { if (i->web_contents == web_contents) return i; } return registered_web_contents_.end(); } // Lazy-initialized and used on the UI thread to handle web contents // notifications (tab closing). scoped_ptr<content::NotificationRegistrar> registrar_; // Keeps track of which WebContent(s) have been registered, in order to avoid // double registrations on |registrar_| and to pass the correct render // process id and render view id to |tab_closed_callback_| after the process // has gone away. std::vector<WebContentsInfo> registered_web_contents_; // Callback used to notify, on the thread specified by |callback_thread_| the // closure of a registered tab. TabClosedCallback tab_closed_callback_; DISALLOW_COPY_AND_ASSIGN(TabWatcher); }; ChromeSpeechRecognitionManagerDelegate ::ChromeSpeechRecognitionManagerDelegate() { } ChromeSpeechRecognitionManagerDelegate ::~ChromeSpeechRecognitionManagerDelegate() { } void ChromeSpeechRecognitionManagerDelegate::TabClosedCallback( int render_process_id, int render_view_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Tell the S.R. Manager (which lives on the IO thread) to abort all the // sessions for the given renderer view. BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind( &TabClosedCallbackOnIOThread, render_process_id, render_view_id)); } void ChromeSpeechRecognitionManagerDelegate::OnRecognitionStart( int session_id) { const content::SpeechRecognitionSessionContext& context = SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id); // Register callback to auto abort session on tab closure. // |tab_watcher_| is lazyly istantiated on the first call. if (!tab_watcher_.get()) { tab_watcher_ = new TabWatcher( base::Bind(&ChromeSpeechRecognitionManagerDelegate::TabClosedCallback, base::Unretained(this))); } tab_watcher_->Watch(context.render_process_id, context.render_view_id); } void ChromeSpeechRecognitionManagerDelegate::OnAudioStart(int session_id) { } void ChromeSpeechRecognitionManagerDelegate::OnEnvironmentEstimationComplete( int session_id) { } void ChromeSpeechRecognitionManagerDelegate::OnSoundStart(int session_id) { } void ChromeSpeechRecognitionManagerDelegate::OnSoundEnd(int session_id) { } void ChromeSpeechRecognitionManagerDelegate::OnAudioEnd(int session_id) { } void ChromeSpeechRecognitionManagerDelegate::OnRecognitionResults( int session_id, const content::SpeechRecognitionResults& result) { } void ChromeSpeechRecognitionManagerDelegate::OnRecognitionError( int session_id, const content::SpeechRecognitionError& error) { } void ChromeSpeechRecognitionManagerDelegate::OnAudioLevelsChange( int session_id, float volume, float noise_volume) { } void ChromeSpeechRecognitionManagerDelegate::OnRecognitionEnd(int session_id) { } void ChromeSpeechRecognitionManagerDelegate::GetDiagnosticInformation( bool* can_report_metrics, std::string* hardware_info) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!optional_request_info_.get()) { optional_request_info_ = new OptionalRequestInfo(); // Since hardware info is optional with speech input requests, we start an // asynchronous fetch here and move on with recording audio. This first // speech input request would send an empty string for hardware info and // subsequent requests may have the hardware info available if the fetch // completed before them. This way we don't end up stalling the user with // a long wait and disk seeks when they click on a UI element and start // speaking. optional_request_info_->Refresh(); } *can_report_metrics = optional_request_info_->can_report_metrics(); *hardware_info = optional_request_info_->value(); } void ChromeSpeechRecognitionManagerDelegate::CheckRecognitionIsAllowed( int session_id, base::Callback<void(bool ask_user, bool is_allowed)> callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); const content::SpeechRecognitionSessionContext& context = SpeechRecognitionManager::GetInstance()->GetSessionContext(session_id); // Make sure that initiators (extensions/web pages) properly set the // |render_process_id| field, which is needed later to retrieve the profile. DCHECK_NE(context.render_process_id, 0); int render_process_id = context.render_process_id; int render_view_id = context.render_view_id; if (context.embedder_render_process_id) { // If this is a request originated from a guest, we need to re-route the // permission check through the embedder (app). render_process_id = context.embedder_render_process_id; render_view_id = context.embedder_render_view_id; } // Check that the render view type is appropriate, and whether or not we // need to request permission from the user. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&CheckRenderViewType, callback, render_process_id, render_view_id)); } content::SpeechRecognitionEventListener* ChromeSpeechRecognitionManagerDelegate::GetEventListener() { return this; } bool ChromeSpeechRecognitionManagerDelegate::FilterProfanities( int render_process_id) { content::RenderProcessHost* rph = content::RenderProcessHost::FromID(render_process_id); if (!rph) // Guard against race conditions on RPH lifetime. return true; return Profile::FromBrowserContext(rph->GetBrowserContext())->GetPrefs()-> GetBoolean(prefs::kSpeechRecognitionFilterProfanities); } // static. void ChromeSpeechRecognitionManagerDelegate::CheckRenderViewType( base::Callback<void(bool ask_user, bool is_allowed)> callback, int render_process_id, int render_view_id) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); const content::RenderViewHost* render_view_host = content::RenderViewHost::FromID(render_process_id, render_view_id); bool allowed = false; bool check_permission = false; if (!render_view_host) { // This happens for extensions. Manifest should be checked for permission. allowed = true; check_permission = false; BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(callback, check_permission, allowed)); return; } WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host); // aviator://app-list/ uses speech recognition. if (web_contents->GetCommittedWebUI() && web_contents->GetLastCommittedURL().spec() == chrome::kChromeUIAppListStartPageURL) { allowed = true; check_permission = false; } extensions::ViewType view_type = extensions::GetViewType(web_contents); if (view_type == extensions::VIEW_TYPE_TAB_CONTENTS || view_type == extensions::VIEW_TYPE_APP_WINDOW || view_type == extensions::VIEW_TYPE_VIRTUAL_KEYBOARD || view_type == extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) { // If it is a tab, we can check for permission. For apps, this means // manifest would be checked for permission. allowed = true; check_permission = true; } BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(callback, check_permission, allowed)); } } // namespace speech
f52994d4de0a8ff01752f007f62d12572bea16fc
481ff5af691f12dd066547538f6b0d3610f8804a
/IkembX00-SDK/NetServerApp/NetServerApp/stdWait.cpp
202a9344acce1c7786343fc7c37d2f424688dc8e
[]
no_license
lightindarkgit/irisembx00
909a1ff0fe10165537cf03f78f310f2329c62da4
3fa3ca437246172dfa0b6adbbddda418c60ee7a6
refs/heads/master
2020-04-11T06:45:09.549740
2018-03-09T03:32:23
2018-03-09T03:32:23
124,330,594
1
0
null
null
null
null
GB18030
C++
false
false
3,888
cpp
/****************************************************************************************** ** 文件名: stdWait.cpp ×× 主要类: StdWait ** ** Copyright (c) 中科虹霸有限公司 ** 创建人: fjf ** 日 期: 2013-12-16 ** 修改人: ** 日 期: ** 描 述: 标准库状态条件封装类文件 ** ×× 主要模块说明: ** ** 版 本: 1.0.0 ** 备 注: ** ******************************************************************************************/ #include "stdafx.h" #include "stdWait.h" #include "../../Common/Exectime.h" StdWait::StdWait() { Exectime etm(__FUNCTION__); } StdWait ::~StdWait() { Exectime etm(__FUNCTION__); } /***************************************************************************** * 唤醒线程函数 * 函 数 名:NoticeAll * 功 能:唤醒所有等待此条件的线程 * 说 明: * 参 数:无 * 返 回 值:无 * 创 建 人:fjf * 创建时间:2013-12-17 * 修 改 人: * 修改时间: *****************************************************************************/ void StdWait::NoticeAll() { Exectime etm(__FUNCTION__); std::unique_lock<std::mutex> uniqueLocker(_mutex); this->_flag = true; this->_conVar.notify_all(); } /***************************************************************************** * 唤醒线程函数 * 函 数 名:NoticeOne * 功 能:唤醒等待况态条件的一个线程 * 说 明: * 参 数:无 * 返 回 值:无 * 创 建 人:fjf * 创建时间:2013-12-17 * 修 改 人: * 修改时间: *****************************************************************************/ void StdWait::NoticeOne() { Exectime etm(__FUNCTION__); std::unique_lock<std::mutex> uniqueLocker(_mutex); //锁住后对标志变量重新赋值,防止假唤醒操作 this->_flag = true; this->_conVar.notify_one(); } /***************************************************************************** * 线程退出通知函数 * 函 数 名:NoticeAllExit * 功 能:通知所有等待函数此线程退出 * 说 明: * 参 数:无 * 返 回 值:无 * 创 建 人:fjf * 创建时间:2013-12-17 * 修 改 人: * 修改时间: *****************************************************************************/ void StdWait::NoticeAllExit() { Exectime etm(__FUNCTION__); // std::unique_lock<std::mutex> uniqueLocker(_mutex); // std::notify_all_at_thread_exit(this->_conVar,std::move(uniqueLocker)); // this->_flag = true; } /***************************************************************************** * 线程等待函数 * 函 数 名:Wait * 功 能:封装的C++11的线程等待函数 * 说 明: * 参 数: * 返 回 值: * 创 建 人:fjf * 创建时间:2013-12-17 * 修 改 人: * 修改时间: *****************************************************************************/ void StdWait::Wait() { Exectime etm(__FUNCTION__); std::unique_lock<std::mutex> uniqueLocker(_mutex); //防止假唤醒,但会影响效率 while (!this->_flag) { this->_conVar.wait(uniqueLocker); } } /***************************************************************************** * 线程重置函数 * 函 数 名:ResetState * 功 能:线程标志位重置函数 * 说 明: * 参 数: * 返 回 值: * 创 建 人:fjf * 创建时间:2013-12-17 * 修 改 人: * 修改时间: *****************************************************************************/ void StdWait::ResetState() { Exectime etm(__FUNCTION__); //不在Wait成功能控制此标志,目的是防止对假唤醒判断的冲击 std::unique_lock<std::mutex> uniqueLocker(_mutex); this->_flag = false; }
dc217c693ec6c151d4fa8ab9247bb71415c09f79
63e7472c7559b619b87b1eb34ff6b8efe0275719
/lab05/main.cpp
a9762234d2b5e0d6a5ce5bd0a7bf7139812197e7
[]
no_license
v-ilya99/lab_05
6ea50d93c0df82ddd79477226896ef27f1d19552
654669da0ead7790ca057b1331b517eae0fa2019
refs/heads/master
2020-04-10T23:52:29.467918
2018-12-13T19:24:45
2018-12-13T19:24:45
161,367,257
0
0
null
null
null
null
UTF-8
C++
false
false
2,090
cpp
//#include <iostream> //#include "boost/filesystem.hpp" //#include <vector> //#include <boost/regex.hpp> #include "dirparser.h" using namespace boost::filesystem; int main(int argc, char *argv[]) { if (argc < 2){ std::cerr << "error" << std::endl; return 1; } //path p(argv[1]); //try { // if (exists(p)){ // std::cout << argv[1] << " is exists" << std::endl; // if (is_regular_file(p)){ // std::cout << p << " is file. Size = " << file_size(p) << std::endl; // // const boost::regex file_filter("balance_[0-9]{8}_[0-9]{8}.txt"); // if (boost::regex_match(p.filename().string(), file_filter, boost::regex_constants::match_default)){ // std::cout << "File is good" << std::endl; // } // } // else if (is_directory(p)){ // std::cout << p << " is directory" << std::endl; // /* std::vector<path> vec; // copy(directory_iterator(p), directory_iterator(), std::back_inserter(vec)); // for (std::vector<path>::const_iterator it(vec.begin()); it != vec.end(); ++it){ // std::cout << " " << *it << std::endl; // }*/ // for (const directory_entry& x : directory_iterator{p}) // { // std::cout << x.path() << std::endl; // } // } // else if (is_symlink(p)){ // std::cout << p << " is symlink" << std::endl; // } // else{ // // } // } // else{ // std::cout << argv[1] << " is not exists" << std::endl; // } //} //catch (const filesystem_error &ex){ // std::cerr << ex.what() << std::endl; //} try { dirparser parser(argv[1]); parser.parse(); } catch (const std::exception &ex){ std::cerr << ex.what() << std::endl; } catch (...) { std::cerr << "unknown exception" << std::endl; } std::cin.get(); return 0; }
c9beaf1e0cecd573c821e8663035a4738610045c
e6e99a9d5a8879614584fa75bea6c92e11d374d7
/Cajas_de_dulces.cpp
dbffa0ecdd63776fc49146edad3284982a2e746f
[]
no_license
JuanMBriones/OMI
740e86ad8b1871c7ece92d8e5f44097f151a6637
be73e56ab6e34a08e93e6490db5688591113fd0a
refs/heads/master
2021-08-22T01:59:23.559880
2020-09-22T14:23:49
2020-09-22T14:23:49
224,791,946
0
0
null
null
null
null
UTF-8
C++
false
false
385
cpp
#include <iostream> using namespace std; int main() { int i, j, n, k; cin >> n >> k; int x[n]; for(i=0; i<n; i++) { cin >> x[i]; } int max = 0, s = 0; for(i=0; i<=n-k; i++) { for(j=0; j<k; j++) { s += x[i+j]; } max = (s>max)? s : max; s = 0; } cout << max << endl; cin.get(); return 0; }
34378f2c2b53e7261bde7cc341d17314ec803257
c9ee44662b0818da4797cf2446075b5abcc4dade
/Math/Rearrange Array.cpp
408c6fd35f6b068702debdeb31ca9f259a985c6d
[]
no_license
flapy/InterviewBit-Solutions
578671912c60ef38e0795889639ec0f9fe55f2e5
d58ea619cf16a1d693bc944cfc7da0923bc2fc05
refs/heads/master
2021-01-13T02:51:53.651440
2017-02-16T16:47:25
2017-02-16T16:47:25
77,127,036
0
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
void Solution::arrange(vector<int> &A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details int n=A.size(); for(int i=0;i<n;i++) { int oldValue=A[i]%n; int point=A[oldValue]; int oldPoint=point%n; A[i]=(oldPoint*n)+oldValue; } for(int i=0;i<n;i++) A[i]/=n; }
64bf6cfba660048338708fdf7616a78616b538f9
abff3f461cd7d740cfc1e675b23616ee638e3f1e
/opencascade/NLPlate_HPG2Constraint.hxx
04c76d54e68634509ffff1ca31e21dd7ff4d530a
[ "Apache-2.0" ]
permissive
CadQuery/pywrap
4f93a4191d3f033f67e1fc209038fc7f89d53a15
f3bcde70fd66a2d884fa60a7a9d9f6aa7c3b6e16
refs/heads/master
2023-04-27T04:49:58.222609
2023-02-10T07:56:06
2023-02-10T07:56:06
146,502,084
22
25
Apache-2.0
2023-05-01T12:14:52
2018-08-28T20:18:59
C++
UTF-8
C++
false
false
1,734
hxx
// Created on: 1998-04-17 // Created by: Andre LIEUTIER // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _NLPlate_HPG2Constraint_HeaderFile #define _NLPlate_HPG2Constraint_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Plate_D2.hxx> #include <NLPlate_HPG1Constraint.hxx> #include <Standard_Integer.hxx> class gp_XY; class Plate_D1; class Plate_D2; class NLPlate_HPG2Constraint; DEFINE_STANDARD_HANDLE(NLPlate_HPG2Constraint, NLPlate_HPG1Constraint) //! define a PinPoint (no G0) G2 Constraint used to load a Non //! Linear Plate class NLPlate_HPG2Constraint : public NLPlate_HPG1Constraint { public: Standard_EXPORT NLPlate_HPG2Constraint(const gp_XY& UV, const Plate_D1& D1T, const Plate_D2& D2T); Standard_EXPORT virtual Standard_Integer ActiveOrder() const Standard_OVERRIDE; Standard_EXPORT virtual const Plate_D2& G2Target() const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(NLPlate_HPG2Constraint,NLPlate_HPG1Constraint) protected: private: Plate_D2 myG2Target; }; #endif // _NLPlate_HPG2Constraint_HeaderFile
6570e322abf2432cff140e59fa2c94c35013e27f
f81170be38ea78716b68f3fa05406dfddc022869
/libopenmpt/openmpt-trunk/soundlib/plugins/PluginManager.cpp
01bcfe4d2f4abfbb9634d48a2c3a6c301ca25a01
[ "BSD-3-Clause" ]
permissive
tarasis/modizer
65896cae869baa60bb88779bbeadcfe0798025c3
ea7080d40011a4cf66454ac3c6d4785c7a4e4583
refs/heads/master
2020-12-25T15:32:16.788352
2020-11-12T21:59:19
2020-11-12T21:59:19
4,281,105
1
0
null
null
null
null
UTF-8
C++
false
false
19,632
cpp
/* * PluginManager.cpp * ----------------- * Purpose: Implementation of the plugin manager, which keeps a list of known plugins and instantiates them. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #ifndef NO_PLUGINS #include "../../common/version.h" #include "PluginManager.h" #include "PlugInterface.h" #include "../../common/mptUUID.h" // Built-in plugins #include "DigiBoosterEcho.h" #include "dmo/DMOPlugin.h" #include "dmo/Compressor.h" #include "dmo/Distortion.h" #include "dmo/Echo.h" #include "dmo/Gargle.h" #include "dmo/ParamEq.h" #include "dmo/WavesReverb.h" #ifdef MODPLUG_TRACKER #include "../../plugins/MidiInOut/MidiInOut.h" #endif // MODPLUG_TRACKER #include "../../common/StringFixer.h" #include "../Sndfile.h" #include "../Loaders.h" #ifndef NO_VST #include "../../mptrack/Vstplug.h" #include "../../pluginBridge/BridgeWrapper.h" #endif // NO_VST #ifndef NO_DMO #include <winreg.h> #include <strmif.h> #include <tchar.h> #endif // NO_DMO #ifdef MODPLUG_TRACKER #include "../../mptrack/Mptrack.h" #include "../../mptrack/TrackerSettings.h" #include "../../mptrack/AbstractVstEditor.h" #include "../../soundlib/AudioCriticalSection.h" #include "../common/mptCRC.h" #endif // MODPLUG_TRACKER OPENMPT_NAMESPACE_BEGIN //#define VST_LOG //#define DMO_LOG #ifdef MODPLUG_TRACKER static const MPT_UCHAR_TYPE *const cacheSection = MPT_ULITERAL("PluginCache"); #endif // MODPLUG_TRACKER uint8 VSTPluginLib::GetDllBits(bool fromCache) const //-------------------------------------------------- { // Built-in plugins are always native. if(dllPath.empty()) return sizeof(void *) * CHAR_BIT; #ifndef NO_VST if(!dllBits || !fromCache) { dllBits = static_cast<uint8>(BridgeWrapper::GetPluginBinaryType(dllPath)); } #else MPT_UNREFERENCED_PARAMETER(fromCache); #endif // NO_VST return dllBits; } // PluginCache format: // FullDllPath = <ID1><ID2><CRC32> (hex-encoded) // <ID1><ID2><CRC32>.Flags = Plugin Flags (see VSTPluginLib::DecodeCacheFlags). // <ID1><ID2><CRC32>.Vendor = Plugin Vendor String. #ifdef MODPLUG_TRACKER void VSTPluginLib::WriteToCache() const //------------------------------------- { SettingsContainer &cacheFile = theApp.GetPluginCache(); const std::string crcName = dllPath.ToUTF8(); const uint32 crc = mpt::crc32(crcName); const mpt::ustring IDs = mpt::ufmt::HEX0<8>(SwapBytesLE(pluginId1)) + mpt::ufmt::HEX0<8>(SwapBytesLE(pluginId2)) + mpt::ufmt::HEX0<8>(SwapBytesLE(crc)); mpt::PathString writePath = dllPath; if(theApp.IsPortableMode()) { writePath = theApp.AbsolutePathToRelative(writePath); } cacheFile.Write<mpt::ustring>(cacheSection, writePath.ToUnicode(), IDs); cacheFile.Write<CString>(cacheSection, IDs + MPT_USTRING(".Vendor"), vendor); cacheFile.Write<int32>(cacheSection, IDs + MPT_USTRING(".Flags"), EncodeCacheFlags()); } #endif // MODPLUG_TRACKER bool CreateMixPluginProc(SNDMIXPLUGIN &mixPlugin, CSoundFile &sndFile) //-------------------------------------------------------------------- { #ifdef MODPLUG_TRACKER CVstPluginManager *that = theApp.GetPluginManager(); if(that) { return that->CreateMixPlugin(mixPlugin, sndFile); } return false; #else if(!sndFile.m_PluginManager) { sndFile.m_PluginManager = std::make_shared<CVstPluginManager>(); } return sndFile.m_PluginManager->CreateMixPlugin(mixPlugin, sndFile); #endif // MODPLUG_TRACKER } CVstPluginManager::CVstPluginManager() //------------------------------------ #if MPT_OS_WINDOWS && !defined(NO_DMO) : MustUnInitilizeCOM(false) #endif { #if MPT_OS_WINDOWS && !defined(NO_DMO) HRESULT COMinit = CoInitializeEx(NULL, COINIT_MULTITHREADED); if(COMinit == S_OK || COMinit == S_FALSE) { MustUnInitilizeCOM = true; } #endif // DirectX Media Objects EnumerateDirectXDMOs(); // Hard-coded "plugins" VSTPluginLib *plug; if(pluginList.empty()) { // DirectX Media Objects Emulation plug = new (std::nothrow) VSTPluginLib(DMO::Compressor::Create, true, MPT_PATHSTRING("{EF011F79-4000-406D-87AF-BFFB3FC39D57}"), MPT_PATHSTRING("Compressor")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = 0xEF011F79; plug->category = VSTPluginLib::catDMO; } plug = new (std::nothrow) VSTPluginLib(DMO::Distortion::Create, true, MPT_PATHSTRING("{EF114C90-CD1D-484E-96E5-09CFAF912A21}"), MPT_PATHSTRING("Distortion")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = 0xEF114C90; plug->category = VSTPluginLib::catDMO; } plug = new (std::nothrow) VSTPluginLib(DMO::Echo::Create, true, MPT_PATHSTRING("{EF3E932C-D40B-4F51-8CCF-3F98F1B29D5D}"), MPT_PATHSTRING("Echo")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = 0xEF3E932C; plug->category = VSTPluginLib::catDMO; } plug = new (std::nothrow) VSTPluginLib(DMO::Gargle::Create, true, MPT_PATHSTRING("{DAFD8210-5711-4B91-9FE3-F75B7AE279BF}"), MPT_PATHSTRING("Gargle")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = 0xDAFD8210; plug->category = VSTPluginLib::catDMO; } plug = new (std::nothrow) VSTPluginLib(DMO::ParamEq::Create, true, MPT_PATHSTRING("{120CED89-3BF4-4173-A132-3CB406CF3231}"), MPT_PATHSTRING("ParamEq")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = 0x120CED89; plug->category = VSTPluginLib::catDMO; } plug = new (std::nothrow) VSTPluginLib(DMO::WavesReverb::Create, true, MPT_PATHSTRING("{87FC0268-9A55-4360-95AA-004A1D9DE26C}"), MPT_PATHSTRING("WavesReverb")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = 0x87FC0268; plug->category = VSTPluginLib::catDMO; } } // DigiBooster Pro Echo DSP plug = new (std::nothrow) VSTPluginLib(DigiBoosterEcho::Create, true, mpt::PathString(), MPT_PATHSTRING("DigiBooster Pro Echo")); if(plug != nullptr) { pluginList.push_back(plug); memcpy(&plug->pluginId1, "DBM0", 4); memcpy(&plug->pluginId2, "Echo", 4); plug->category = VSTPluginLib::catRoomFx; } #ifdef MODPLUG_TRACKER plug = new (std::nothrow) VSTPluginLib(MidiInOut::Create, true, mpt::PathString(), MPT_PATHSTRING("MIDI Input Output")); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = PLUGMAGIC('V','s','t','P'); plug->pluginId2 = PLUGMAGIC('M','M','I','D'); plug->category = VSTPluginLib::catSynth; plug->isInstrument = true; } #endif // MODPLUG_TRACKER } CVstPluginManager::~CVstPluginManager() //------------------------------------- { for(const_iterator p = begin(); p != end(); p++) { while((**p).pPluginsList != nullptr) { (**p).pPluginsList->Release(); } delete *p; } #if MPT_OS_WINDOWS && !defined(NO_DMO) if(MustUnInitilizeCOM) { CoUninitialize(); MustUnInitilizeCOM = false; } #endif } bool CVstPluginManager::IsValidPlugin(const VSTPluginLib *pLib) const //------------------------------------------------------------------- { for(const_iterator p = begin(); p != end(); p++) { if(*p == pLib) return true; } return false; } void CVstPluginManager::EnumerateDirectXDMOs() //-------------------------------------------- { #ifndef NO_DMO HKEY hkEnum; WCHAR keyname[128]; LONG cr = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("software\\classes\\DirectShow\\MediaObjects\\Categories\\f3602b3f-0592-48df-a4cd-674721e7ebeb"), 0, KEY_READ, &hkEnum); DWORD index = 0; while (cr == ERROR_SUCCESS) { if ((cr = RegEnumKeyW(hkEnum, index, keyname, CountOf(keyname))) == ERROR_SUCCESS) { CLSID clsid; std::wstring formattedKey = std::wstring(L"{") + std::wstring(keyname) + std::wstring(L"}"); if(Util::VerifyStringToCLSID(formattedKey, clsid)) { HKEY hksub; formattedKey = std::wstring(L"software\\classes\\DirectShow\\MediaObjects\\") + std::wstring(keyname); if (RegOpenKeyW(HKEY_LOCAL_MACHINE, formattedKey.c_str(), &hksub) == ERROR_SUCCESS) { WCHAR name[64]; DWORD datatype = REG_SZ; DWORD datasize = sizeof(name); if(ERROR_SUCCESS == RegQueryValueExW(hksub, nullptr, 0, &datatype, (LPBYTE)name, &datasize)) { mpt::String::SetNullTerminator(name); VSTPluginLib *plug = new (std::nothrow) VSTPluginLib(DMOPlugin::Create, true, mpt::PathString::FromNative(Util::GUIDToString(clsid)), mpt::PathString::FromNative(name)); if(plug != nullptr) { pluginList.push_back(plug); plug->pluginId1 = kDmoMagic; plug->pluginId2 = clsid.Data1; plug->category = VSTPluginLib::catDMO; #ifdef DMO_LOG Log(mpt::String::Print(L"Found \"%1\" clsid=%2\n", plug->libraryName, plug->dllPath)); #endif } } RegCloseKey(hksub); } } } index++; } if (hkEnum) RegCloseKey(hkEnum); #endif // NO_DMO } // Extract instrument and category information from plugin. #ifndef NO_VST static void GetPluginInformation(AEffect *effect, VSTPluginLib &library) //---------------------------------------------------------------------- { unsigned long exception = 0; library.category = static_cast<VSTPluginLib::PluginCategory>(CVstPlugin::DispatchSEH(effect, effGetPlugCategory, 0, 0, nullptr, 0, exception)); library.isInstrument = ((effect->flags & effFlagsIsSynth) || !effect->numInputs); if(library.isInstrument) { library.category = VSTPluginLib::catSynth; } else if(library.category >= VSTPluginLib::numCategories) { library.category = VSTPluginLib::catUnknown; } #ifdef MODPLUG_TRACKER CStringA s; CVstPlugin::DispatchSEH(effect, effGetVendorString, 0, 0, s.GetBuffer(256), 0, exception); s.ReleaseBuffer(); library.vendor = mpt::ToCString(mpt::CharsetLocale, s); #endif // MODPLUG_TRACKER } #endif // NO_VST #ifdef MODPLUG_TRACKER // Add a plugin to the list of known plugins. VSTPluginLib *CVstPluginManager::AddPlugin(const mpt::PathString &dllPath, const mpt::ustring &tags, bool fromCache, const bool checkFileExistence, std::wstring *const errStr) //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- { const mpt::PathString fileName = dllPath.GetFileName(); // Check if this is already a known plugin. for(const_iterator dupePlug = begin(); dupePlug != end(); dupePlug++) { if(!dllPath.CompareNoCase(dllPath, (**dupePlug).dllPath)) return *dupePlug; } if(checkFileExistence && errStr != nullptr && !dllPath.IsFile()) { *errStr += L"\nUnable to find " + dllPath.ToWide(); } // Look if the plugin info is stored in the PluginCache if(fromCache) { SettingsContainer & cacheFile = theApp.GetPluginCache(); // First try finding the full path mpt::ustring IDs = cacheFile.Read<mpt::ustring>(cacheSection, dllPath.ToUnicode(), MPT_USTRING("")); if(IDs.length() < 16) { // If that didn't work out, find relative path mpt::PathString relPath = theApp.AbsolutePathToRelative(dllPath); IDs = cacheFile.Read<mpt::ustring>(cacheSection, relPath.ToUnicode(), MPT_USTRING("")); } if(IDs.length() >= 16) { VSTPluginLib *plug = new (std::nothrow) VSTPluginLib(nullptr, false, dllPath, fileName, tags); if(plug == nullptr) { return nullptr; } pluginList.push_back(plug); // Extract plugin IDs for (int i = 0; i < 16; i++) { int32 n = IDs[i] - '0'; if (n > 9) n = IDs[i] + 10 - 'A'; n &= 0x0f; if (i < 8) { plug->pluginId1 = (plug->pluginId1 << 4) | n; } else { plug->pluginId2 = (plug->pluginId2 << 4) | n; } } const mpt::ustring flagKey = IDs + MPT_USTRING(".Flags"); plug->DecodeCacheFlags(cacheFile.Read<int32>(cacheSection, flagKey, 0)); plug->vendor = cacheFile.Read<CString>(cacheSection, IDs + MPT_USTRING(".Vendor"), CString()); #ifdef VST_LOG Log("Plugin \"%s\" found in PluginCache\n", plug->libraryName.ToLocale().c_str()); #endif // VST_LOG return plug; } else { #ifdef VST_LOG Log("Plugin \"%s\" mismatch in PluginCache: \"%s\" [%s]=\"%s\"\n", s, dllPath, (LPCTSTR)IDs, (LPCTSTR)strFullPath); #endif // VST_LOG } } // If this key contains a file name on program launch, a plugin previously crashed OpenMPT. theApp.GetSettings().Write<mpt::PathString>(MPT_USTRING("VST Plugins"), MPT_USTRING("FailedPlugin"), dllPath, SettingWriteThrough); bool validPlug = false; VSTPluginLib *plug = new (std::nothrow) VSTPluginLib(nullptr, false, dllPath, fileName, tags); if(plug == nullptr) { return nullptr; } #ifndef NO_VST unsigned long exception = 0; // Always scan plugins in a separate process HINSTANCE hLib = NULL; AEffect *pEffect = CVstPlugin::LoadPlugin(*plug, hLib, true); if(pEffect != nullptr && pEffect->magic == kEffectMagic && pEffect->dispatcher != nullptr) { CVstPlugin::DispatchSEH(pEffect, effOpen, 0, 0, 0, 0, exception); plug->pluginId1 = pEffect->magic; plug->pluginId2 = pEffect->uniqueID; GetPluginInformation(pEffect, *plug); #ifdef VST_LOG int nver = CVstPlugin::DispatchSEH(pEffect, effGetVstVersion, 0,0, nullptr, 0, exception); if (!nver) nver = pEffect->version; Log("%-20s: v%d.0, %d in, %d out, %2d programs, %2d params, flags=0x%04X realQ=%d offQ=%d\n", plug->libraryName.ToLocale().c_str(), nver, pEffect->numInputs, pEffect->numOutputs, pEffect->numPrograms, pEffect->numParams, pEffect->flags, pEffect->realQualities, pEffect->offQualities); #endif // VST_LOG CVstPlugin::DispatchSEH(pEffect, effClose, 0, 0, 0, 0, exception); validPlug = true; } FreeLibrary(hLib); if(exception != 0) { CVstPluginManager::ReportPlugException(mpt::String::Print(L"Exception %1 while trying to load plugin \"%2\"!\n", mpt::wfmt::HEX<8>(exception), plug->libraryName)); } #endif // NO_VST // Now it should be safe to assume that this plugin loaded properly. :) theApp.GetSettings().Remove(MPT_USTRING("VST Plugins"), MPT_USTRING("FailedPlugin")); // If OK, write the information in PluginCache if(validPlug) { pluginList.push_back(plug); plug->WriteToCache(); } else { delete plug; } return (validPlug ? plug : nullptr); } // Remove a plugin from the list of known plugins and release any remaining instances of it. bool CVstPluginManager::RemovePlugin(VSTPluginLib *pFactory) //---------------------------------------------------------- { for(const_iterator p = begin(); p != end(); p++) { VSTPluginLib *plug = *p; if(plug == pFactory) { // Kill all instances of this plugin CriticalSection cs; while(plug->pPluginsList != nullptr) { plug->pPluginsList->Release(); } pluginList.erase(p); delete plug; return true; } } return false; } #endif // MODPLUG_TRACKER // Create an instance of a plugin. bool CVstPluginManager::CreateMixPlugin(SNDMIXPLUGIN &mixPlugin, CSoundFile &sndFile) //----------------------------------------------------------------------------------- { VSTPluginLib *pFound = nullptr; #ifdef MODPLUG_TRACKER mixPlugin.SetAutoSuspend(TrackerSettings::Instance().enableAutoSuspend); #endif // MODPLUG_TRACKER // Find plugin in library int8 match = 0; // "Match quality" of found plugin. Higher value = better match. for(const_iterator p = begin(); p != end(); p++) { VSTPluginLib *plug = *p; const bool matchID = (plug->pluginId1 == mixPlugin.Info.dwPluginId1) && (plug->pluginId2 == mixPlugin.Info.dwPluginId2); #if MPT_OS_WINDOWS const bool matchName = !mpt::PathString::CompareNoCase(plug->libraryName, mpt::PathString::FromUTF8(mixPlugin.GetLibraryName())); #else const bool matchName = (mpt::ToLowerCaseAscii(plug->libraryName.ToUTF8()) == mpt::ToLowerCaseAscii(mixPlugin.GetLibraryName())); #endif if(matchID && matchName) { pFound = plug; if(plug->IsNative(false)) { break; } // If the plugin isn't native, first check if a native version can be found. match = 3; } else if(matchID && match < 2) { pFound = plug; match = 2; } else if(matchName && match < 1) { pFound = plug; match = 1; } } if(pFound != nullptr && pFound->Create != nullptr) { IMixPlugin *plugin = pFound->Create(*pFound, sndFile, &mixPlugin); return plugin != nullptr; } #ifdef MODPLUG_TRACKER if(!pFound && strcmp(mixPlugin.GetLibraryName(), "")) { // Try finding the plugin DLL in the plugin directory or plugin cache instead. mpt::PathString fullPath = TrackerSettings::Instance().PathPlugins.GetDefaultDir(); if(fullPath.empty()) { fullPath = theApp.GetAppDirPath() + MPT_PATHSTRING("Plugins\\"); } fullPath += mpt::PathString::FromUTF8(mixPlugin.GetLibraryName()) + MPT_PATHSTRING(".dll"); pFound = AddPlugin(fullPath); if(!pFound) { // Try plugin cache (search for library name) SettingsContainer &cacheFile = theApp.GetPluginCache(); mpt::ustring IDs = cacheFile.Read<mpt::ustring>(cacheSection, mpt::ToUnicode(mpt::CharsetUTF8, mixPlugin.GetLibraryName()), MPT_USTRING("")); if(IDs.length() >= 16) { fullPath = cacheFile.Read<mpt::PathString>(cacheSection, IDs, MPT_PATHSTRING("")); if(!fullPath.empty()) { fullPath = theApp.RelativePathToAbsolute(fullPath); if(fullPath.IsFile()) { pFound = AddPlugin(fullPath); } } } } } #ifndef NO_VST if(pFound && mixPlugin.Info.dwPluginId1 == kEffectMagic) { AEffect *pEffect = nullptr; HINSTANCE hLibrary = nullptr; bool validPlugin = false; pEffect = CVstPlugin::LoadPlugin(*pFound, hLibrary, TrackerSettings::Instance().bridgeAllPlugins); if(pEffect != nullptr && pEffect->dispatcher != nullptr && pEffect->magic == kEffectMagic) { validPlugin = true; GetPluginInformation(pEffect, *pFound); // Update cached information pFound->WriteToCache(); CVstPlugin *pVstPlug = new (std::nothrow) CVstPlugin(hLibrary, *pFound, mixPlugin, *pEffect, sndFile); if(pVstPlug == nullptr) { validPlugin = false; } } if(!validPlugin) { FreeLibrary(hLibrary); CVstPluginManager::ReportPlugException(mpt::String::Print(L"Unable to create plugin \"%1\"!\n", pFound->libraryName)); } return validPlugin; } else { // "plug not found" notification code MOVED to CSoundFile::Create #ifdef VST_LOG Log("Unknown plugin\n"); #endif } #endif // NO_VST #endif // MODPLUG_TRACKER return false; } #ifdef MODPLUG_TRACKER void CVstPluginManager::OnIdle() //------------------------------ { for(const_iterator pFactory = begin(); pFactory != end(); pFactory++) { // Note: bridged plugins won't receive these messages and generate their own idle messages. IMixPlugin *p = (**pFactory).pPluginsList; while (p) { //rewbs. VSTCompliance: A specific plug has requested indefinite periodic processing time. p->Idle(); //We need to update all open editors CAbstractVstEditor *editor = p->GetEditor(); if (editor && editor->m_hWnd) { editor->UpdateParamDisplays(); } //end rewbs. VSTCompliance: p = p->GetNextInstance(); } } } void CVstPluginManager::ReportPlugException(const std::string &msg) //----------------------------------------------------------------- { Reporting::Notification(msg.c_str()); #ifdef VST_LOG Log("%s", msg.c_str()); #endif } void CVstPluginManager::ReportPlugException(const std::wstring &msg) //-------------------------------------------------------------- { Reporting::Notification(msg); #ifdef VST_LOG Log(mpt::ToUnicode(msg)); #endif } #endif // MODPLUG_TRACKER OPENMPT_NAMESPACE_END #endif // NO_PLUGINS
af6b1e4f02124a483b8fb6f8e2dee01b41f13ddf
4e5bfb584214a410389770706a45bd51222681df
/examples/du.cpp
95b95807e4d75effc522370497215a115de7adbb
[ "BSD-3-Clause" ]
permissive
kmribti/filesystem
8e36ca972755d30a6f5e835fa1daf3d381bd5327
91e02dc2c44ed8a915a67b83c86b508ac0f4a82a
refs/heads/master
2020-05-23T11:38:49.628540
2019-05-14T06:42:29
2019-05-14T06:42:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,554
cpp
#include <iostream> #include <iomanip> #include <chrono> #if defined(__cplusplus) && __cplusplus >= 201703L && defined(__has_include) && __has_include(<filesystem>) #include <filesystem> namespace fs = std::filesystem; #else #include <ghc/filesystem.hpp> namespace fs = ghc::filesystem; #endif int main(int argc, char* argv[]) { #ifdef GHC_FILESYSTEM_VERSION fs::u8arguments u8guard(argc, argv); if(!u8guard.valid()) { std::cerr << "Invalid character encoding, UTF-8 based encoding needed." << std::endl; std::exit(EXIT_FAILURE); } #endif if(argc > 2) { std::cerr << "USAGE: du <path>" << std::endl; exit(1); } fs::path dir{"."}; if(argc == 2) { dir = fs::u8path(argv[1]); } uint64_t totalSize = 0; int totalDirs = 0; int totalFiles = 0; int maxDepth = 0; try { auto rdi = fs::recursive_directory_iterator(dir); for(auto de : rdi) { if(rdi.depth() > maxDepth) { maxDepth = rdi.depth(); } if(de.is_regular_file()) { totalSize += de.file_size(); ++totalFiles; } else if(de.is_directory()) { ++totalDirs; } } } catch(fs::filesystem_error fe) { std::cerr << "Error: " << fe.what() << std::endl; exit(1); } std::cout << totalSize << " bytes in " << totalFiles << " files and " << totalDirs << " directories, maximum depth: " << maxDepth << std::endl; return 0; }
2199d2e780f5be683955a370c10c06d8ce6311aa
5456502f97627278cbd6e16d002d50f1de3da7bb
/chrome/browser/themes/browser_theme_pack_unittest.cc
6f4f8e17bc91b38eb297936846fc3a00fa6594ce
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,516
cc
// Copyright (c) 2012 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/themes/browser_theme_pack.h" #include <stddef.h> #include "base/files/scoped_temp_dir.h" #include "base/json/json_file_value_serializer.h" #include "base/json/json_reader.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/values.h" #include "build/build_config.h" #include "chrome/browser/themes/theme_properties.h" #include "chrome/common/chrome_paths.h" #include "chrome/grit/theme_resources.h" #include "content/public/test/test_browser_thread.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/color_utils.h" #include "ui/gfx/image/image.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_rep.h" using content::BrowserThread; using extensions::Extension; // Maps scale factors (enum values) to file path. // A similar typedef in BrowserThemePack is private. typedef std::map<ui::ScaleFactor, base::FilePath> TestScaleFactorToFileMap; // Maps image ids to maps of scale factors to file paths. // A similar typedef in BrowserThemePack is private. typedef std::map<int, TestScaleFactorToFileMap> TestFilePathMap; class BrowserThemePackTest : public ::testing::Test { public: BrowserThemePackTest() : message_loop(), fake_ui_thread(BrowserThread::UI, &message_loop), fake_file_thread(BrowserThread::FILE, &message_loop) { std::vector<ui::ScaleFactor> scale_factors; scale_factors.push_back(ui::SCALE_FACTOR_100P); scale_factors.push_back(ui::SCALE_FACTOR_200P); scoped_set_supported_scale_factors_.reset( new ui::test::ScopedSetSupportedScaleFactors(scale_factors)); theme_pack_ = new BrowserThemePack(); } // Transformation for link underline colors. SkColor BuildThirdOpacity(SkColor color_link) { return SkColorSetA(color_link, SkColorGetA(color_link) / 3); } void GenerateDefaultFrameColor(std::map<int, SkColor>* colors, int color, int tint, bool otr) { (*colors)[color] = HSLShift( ThemeProperties::GetDefaultColor(ThemeProperties::COLOR_FRAME, false), ThemeProperties::GetDefaultTint(tint, otr)); } // Returns a mapping from each COLOR_* constant to the default value for this // constant. Callers get this map, and then modify expected values and then // run the resulting thing through VerifyColorMap(). std::map<int, SkColor> GetDefaultColorMap() { std::map<int, SkColor> colors; GenerateDefaultFrameColor(&colors, ThemeProperties::COLOR_FRAME, ThemeProperties::TINT_FRAME, false); GenerateDefaultFrameColor(&colors, ThemeProperties::COLOR_FRAME_INACTIVE, ThemeProperties::TINT_FRAME_INACTIVE, false); GenerateDefaultFrameColor(&colors, ThemeProperties::COLOR_FRAME_INCOGNITO, ThemeProperties::TINT_FRAME, true); GenerateDefaultFrameColor( &colors, ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE, ThemeProperties::TINT_FRAME_INACTIVE, true); // For the rest, use default colors. for (int i = ThemeProperties::COLOR_FRAME_INCOGNITO_INACTIVE + 1; i <= ThemeProperties::COLOR_BUTTON_BACKGROUND; ++i) { colors[i] = ThemeProperties::GetDefaultColor(i, false); } return colors; } void VerifyColorMap(const std::map<int, SkColor>& color_map) { for (std::map<int, SkColor>::const_iterator it = color_map.begin(); it != color_map.end(); ++it) { SkColor color; if (!theme_pack_->GetColor(it->first, &color)) color = ThemeProperties::GetDefaultColor(it->first, false); EXPECT_EQ(it->second, color) << "Color id = " << it->first; } } void LoadColorJSON(const std::string& json) { std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); LoadColorDictionary(static_cast<base::DictionaryValue*>(value.get())); } void LoadColorDictionary(base::DictionaryValue* value) { theme_pack_->BuildColorsFromJSON(value); } void LoadTintJSON(const std::string& json) { std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); LoadTintDictionary(static_cast<base::DictionaryValue*>(value.get())); } void LoadTintDictionary(base::DictionaryValue* value) { theme_pack_->BuildTintsFromJSON(value); } void LoadDisplayPropertiesJSON(const std::string& json) { std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); LoadDisplayPropertiesDictionary( static_cast<base::DictionaryValue*>(value.get())); } void LoadDisplayPropertiesDictionary(base::DictionaryValue* value) { theme_pack_->BuildDisplayPropertiesFromJSON(value); } void ParseImageNamesJSON(const std::string& json, TestFilePathMap* out_file_paths) { std::unique_ptr<base::Value> value = base::JSONReader::Read(json); ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY)); ParseImageNamesDictionary(static_cast<base::DictionaryValue*>(value.get()), out_file_paths); } void ParseImageNamesDictionary( base::DictionaryValue* value, TestFilePathMap* out_file_paths) { theme_pack_->ParseImageNamesFromJSON(value, base::FilePath(), out_file_paths); // Build the source image list for HasCustomImage(). theme_pack_->BuildSourceImagesArray(*out_file_paths); } bool LoadRawBitmapsTo(const TestFilePathMap& out_file_paths) { return theme_pack_->LoadRawBitmapsTo(out_file_paths, &theme_pack_->images_on_ui_thread_); } // This function returns void in order to be able use ASSERT_... // The BrowserThemePack is returned in |pack|. void BuildFromUnpackedExtension(const base::FilePath& extension_path, scoped_refptr<BrowserThemePack>& pack) { base::FilePath manifest_path = extension_path.AppendASCII("manifest.json"); std::string error; JSONFileValueDeserializer deserializer(manifest_path); std::unique_ptr<base::DictionaryValue> valid_value = base::DictionaryValue::From(deserializer.Deserialize(NULL, &error)); EXPECT_EQ("", error); ASSERT_TRUE(valid_value.get()); scoped_refptr<Extension> extension( Extension::Create( extension_path, extensions::Manifest::INVALID_LOCATION, *valid_value, Extension::REQUIRE_KEY, &error)); ASSERT_TRUE(extension.get()); ASSERT_EQ("", error); pack = BrowserThemePack::BuildFromExtension(extension.get()); ASSERT_TRUE(pack.get()); } base::FilePath GetStarGazingPath() { base::FilePath test_path; if (!PathService::Get(chrome::DIR_TEST_DATA, &test_path)) { NOTREACHED(); return test_path; } test_path = test_path.AppendASCII("profiles"); test_path = test_path.AppendASCII("profile_with_complex_theme"); test_path = test_path.AppendASCII("Default"); test_path = test_path.AppendASCII("Extensions"); test_path = test_path.AppendASCII("mblmlcbknbnfebdfjnolmcapmdofhmme"); test_path = test_path.AppendASCII("1.1"); return base::FilePath(test_path); } base::FilePath GetHiDpiThemePath() { base::FilePath test_path; if (!PathService::Get(chrome::DIR_TEST_DATA, &test_path)) { NOTREACHED(); return test_path; } test_path = test_path.AppendASCII("extensions"); test_path = test_path.AppendASCII("theme_hidpi"); return base::FilePath(test_path); } // Verifies the data in star gazing. We do this multiple times for different // BrowserThemePack objects to make sure it works in generated and mmapped // mode correctly. void VerifyStarGazing(BrowserThemePack* pack) { // First check that values we know exist, exist. SkColor color; EXPECT_TRUE(pack->GetColor(ThemeProperties::COLOR_BOOKMARK_TEXT, &color)); EXPECT_EQ(SK_ColorBLACK, color); EXPECT_TRUE(pack->GetColor(ThemeProperties::COLOR_NTP_BACKGROUND, &color)); EXPECT_EQ(SkColorSetRGB(57, 137, 194), color); color_utils::HSL expected = { 0.6, 0.553, 0.5 }; color_utils::HSL actual; EXPECT_TRUE(pack->GetTint(ThemeProperties::TINT_BUTTONS, &actual)); EXPECT_DOUBLE_EQ(expected.h, actual.h); EXPECT_DOUBLE_EQ(expected.s, actual.s); EXPECT_DOUBLE_EQ(expected.l, actual.l); int val; EXPECT_TRUE(pack->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT, &val)); EXPECT_EQ(ThemeProperties::ALIGN_TOP, val); // The stargazing theme defines the following images: EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_BUTTON_BACKGROUND)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_FRAME)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_NTP_BACKGROUND)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_TAB_BACKGROUND)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_TOOLBAR)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_WINDOW_CONTROL_BACKGROUND)); // Here are a few images that we shouldn't expect because even though // they're included in the theme pack, they were autogenerated and // therefore shouldn't show up when calling HasCustomImage(). EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_FRAME_INACTIVE)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_FRAME_INCOGNITO)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_FRAME_INCOGNITO_INACTIVE)); #if !defined(OS_MACOSX) EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_TAB_BACKGROUND_INCOGNITO)); #endif // Make sure we don't have phantom data. EXPECT_FALSE(pack->GetColor(ThemeProperties::COLOR_CONTROL_BACKGROUND, &color)); EXPECT_FALSE(pack->GetTint(ThemeProperties::TINT_FRAME, &actual)); } void VerifyHiDpiTheme(BrowserThemePack* pack) { // The high DPI theme defines the following images: EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_FRAME)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_FRAME_INACTIVE)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_FRAME_INCOGNITO)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_FRAME_INCOGNITO_INACTIVE)); EXPECT_TRUE(pack->HasCustomImage(IDR_THEME_TOOLBAR)); // The high DPI theme does not define the following images: EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_TAB_BACKGROUND)); #if !defined(OS_MACOSX) EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_TAB_BACKGROUND_INCOGNITO)); #endif EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_TAB_BACKGROUND_V)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_NTP_BACKGROUND)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_FRAME_OVERLAY)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_FRAME_OVERLAY_INACTIVE)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_BUTTON_BACKGROUND)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_NTP_ATTRIBUTION)); EXPECT_FALSE(pack->HasCustomImage(IDR_THEME_WINDOW_CONTROL_BACKGROUND)); // Compare some known pixel colors at know locations for a theme // image where two different PNG files were specified for scales 100% // and 200% respectively. int idr = IDR_THEME_FRAME; gfx::Image image = pack->GetImageNamed(idr); EXPECT_FALSE(image.IsEmpty()); const gfx::ImageSkia* image_skia = image.ToImageSkia(); ASSERT_TRUE(image_skia); // Scale 100%. const gfx::ImageSkiaRep& rep1 = image_skia->GetRepresentation(1.0f); ASSERT_FALSE(rep1.is_null()); EXPECT_EQ(80, rep1.sk_bitmap().width()); EXPECT_EQ(80, rep1.sk_bitmap().height()); rep1.sk_bitmap().lockPixels(); EXPECT_EQ(SkColorSetRGB(255, 255, 255), rep1.sk_bitmap().getColor(4, 4)); EXPECT_EQ(SkColorSetRGB(255, 255, 255), rep1.sk_bitmap().getColor(8, 8)); EXPECT_EQ(SkColorSetRGB(0, 241, 237), rep1.sk_bitmap().getColor(16, 16)); EXPECT_EQ(SkColorSetRGB(255, 255, 255), rep1.sk_bitmap().getColor(24, 24)); EXPECT_EQ(SkColorSetRGB(0, 241, 237), rep1.sk_bitmap().getColor(32, 32)); rep1.sk_bitmap().unlockPixels(); // Scale 200%. const gfx::ImageSkiaRep& rep2 = image_skia->GetRepresentation(2.0f); ASSERT_FALSE(rep2.is_null()); EXPECT_EQ(160, rep2.sk_bitmap().width()); EXPECT_EQ(160, rep2.sk_bitmap().height()); rep2.sk_bitmap().lockPixels(); EXPECT_EQ(SkColorSetRGB(255, 255, 255), rep2.sk_bitmap().getColor(4, 4)); EXPECT_EQ(SkColorSetRGB(223, 42, 0), rep2.sk_bitmap().getColor(8, 8)); EXPECT_EQ(SkColorSetRGB(223, 42, 0), rep2.sk_bitmap().getColor(16, 16)); EXPECT_EQ(SkColorSetRGB(223, 42, 0), rep2.sk_bitmap().getColor(24, 24)); EXPECT_EQ(SkColorSetRGB(255, 255, 255), rep2.sk_bitmap().getColor(32, 32)); rep2.sk_bitmap().unlockPixels(); // TODO(sschmitz): I plan to remove the following (to the end of the fct) // Reason: this test may be brittle. It depends on details of how we scale // an 100% image to an 200% image. If there's filtering etc, this test would // break. Also High DPI is new, but scaling from 100% to 200% is not new // and need not be tested here. But in the interrim it is useful to verify // that this image was scaled and did not appear in the input. // Compare pixel colors and locations for a theme image that had // only one PNG file specified (for scale 100%). The representation // for scale of 200% was computed. idr = IDR_THEME_FRAME_INCOGNITO_INACTIVE; image = pack->GetImageNamed(idr); EXPECT_FALSE(image.IsEmpty()); image_skia = image.ToImageSkia(); ASSERT_TRUE(image_skia); // Scale 100%. const gfx::ImageSkiaRep& rep3 = image_skia->GetRepresentation(1.0f); ASSERT_FALSE(rep3.is_null()); EXPECT_EQ(80, rep3.sk_bitmap().width()); EXPECT_EQ(80, rep3.sk_bitmap().height()); rep3.sk_bitmap().lockPixels(); // We take samples of colors and locations along the diagonal whenever // the color changes. Note these colors are slightly different from // the input PNG file due to input processing. std::vector<std::pair<int, SkColor> > normal; int xy = 0; SkColor color = rep3.sk_bitmap().getColor(xy, xy); normal.push_back(std::make_pair(xy, color)); for (int xy = 0; xy < 40; ++xy) { SkColor next_color = rep3.sk_bitmap().getColor(xy, xy); if (next_color != color) { color = next_color; normal.push_back(std::make_pair(xy, color)); } } EXPECT_EQ(static_cast<size_t>(9), normal.size()); rep3.sk_bitmap().unlockPixels(); // Scale 200%. const gfx::ImageSkiaRep& rep4 = image_skia->GetRepresentation(2.0f); ASSERT_FALSE(rep4.is_null()); EXPECT_EQ(160, rep4.sk_bitmap().width()); EXPECT_EQ(160, rep4.sk_bitmap().height()); rep4.sk_bitmap().lockPixels(); // We expect the same colors and at locations scaled by 2 // since this bitmap was scaled by 2. for (size_t i = 0; i < normal.size(); ++i) { int xy = 2 * normal[i].first; SkColor color = normal[i].second; EXPECT_EQ(color, rep4.sk_bitmap().getColor(xy, xy)); } rep4.sk_bitmap().unlockPixels(); } base::MessageLoop message_loop; content::TestBrowserThread fake_ui_thread; content::TestBrowserThread fake_file_thread; typedef std::unique_ptr<ui::test::ScopedSetSupportedScaleFactors> ScopedSetSupportedScaleFactors; ScopedSetSupportedScaleFactors scoped_set_supported_scale_factors_; scoped_refptr<BrowserThemePack> theme_pack_; }; TEST_F(BrowserThemePackTest, DeriveUnderlineLinkColor) { // If we specify a link color, but don't specify the underline color, the // theme provider should create one. std::string color_json = "{ \"ntp_link\": [128, 128, 128]," " \"ntp_section_link\": [128, 128, 128] }"; LoadColorJSON(color_json); std::map<int, SkColor> colors = GetDefaultColorMap(); SkColor link_color = SkColorSetRGB(128, 128, 128); colors[ThemeProperties::COLOR_NTP_LINK] = link_color; colors[ThemeProperties::COLOR_NTP_LINK_UNDERLINE] = BuildThirdOpacity(link_color); colors[ThemeProperties::COLOR_NTP_SECTION_LINK] = link_color; colors[ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE] = BuildThirdOpacity(link_color); VerifyColorMap(colors); } TEST_F(BrowserThemePackTest, ProvideUnderlineLinkColor) { // If we specify the underline color, it shouldn't try to generate one. std::string color_json = "{ \"ntp_link\": [128, 128, 128]," " \"ntp_link_underline\": [255, 255, 255]," " \"ntp_section_link\": [128, 128, 128]," " \"ntp_section_link_underline\": [255, 255, 255]" "}"; LoadColorJSON(color_json); std::map<int, SkColor> colors = GetDefaultColorMap(); SkColor link_color = SkColorSetRGB(128, 128, 128); SkColor underline_color = SkColorSetRGB(255, 255, 255); colors[ThemeProperties::COLOR_NTP_LINK] = link_color; colors[ThemeProperties::COLOR_NTP_LINK_UNDERLINE] = underline_color; colors[ThemeProperties::COLOR_NTP_SECTION_LINK] = link_color; colors[ThemeProperties::COLOR_NTP_SECTION_LINK_UNDERLINE] = underline_color; VerifyColorMap(colors); } TEST_F(BrowserThemePackTest, UseSectionColorAsNTPHeader) { std::string color_json = "{ \"ntp_section\": [190, 190, 190] }"; LoadColorJSON(color_json); std::map<int, SkColor> colors = GetDefaultColorMap(); SkColor ntp_color = SkColorSetRGB(190, 190, 190); colors[ThemeProperties::COLOR_NTP_HEADER] = ntp_color; colors[ThemeProperties::COLOR_NTP_SECTION] = ntp_color; VerifyColorMap(colors); } TEST_F(BrowserThemePackTest, ProvideNtpHeaderColor) { std::string color_json = "{ \"ntp_header\": [120, 120, 120], " " \"ntp_section\": [190, 190, 190] }"; LoadColorJSON(color_json); std::map<int, SkColor> colors = GetDefaultColorMap(); colors[ThemeProperties::COLOR_NTP_HEADER] = SkColorSetRGB(120, 120, 120); colors[ThemeProperties::COLOR_NTP_SECTION] = SkColorSetRGB(190, 190, 190); VerifyColorMap(colors); } TEST_F(BrowserThemePackTest, SupportsAlpha) { std::string color_json = "{ \"toolbar\": [0, 20, 40, 1], " " \"tab_text\": [60, 80, 100, 1], " " \"tab_background_text\": [120, 140, 160, 0.0], " " \"bookmark_text\": [180, 200, 220, 1.0], " " \"ntp_text\": [240, 255, 0, 0.5] }"; LoadColorJSON(color_json); std::map<int, SkColor> colors = GetDefaultColorMap(); // Verify that valid alpha values are parsed correctly. // The toolbar color's alpha value is intentionally ignored by theme provider. colors[ThemeProperties::COLOR_TOOLBAR] = SkColorSetARGB(255, 0, 20, 40); colors[ThemeProperties::COLOR_TAB_TEXT] = SkColorSetARGB(255, 60, 80, 100); colors[ThemeProperties::COLOR_BACKGROUND_TAB_TEXT] = SkColorSetARGB(0, 120, 140, 160); colors[ThemeProperties::COLOR_BOOKMARK_TEXT] = SkColorSetARGB(255, 180, 200, 220); colors[ThemeProperties::COLOR_NTP_TEXT] = SkColorSetARGB(128, 240, 255, 0); VerifyColorMap(colors); } TEST_F(BrowserThemePackTest, OutOfRangeColors) { // Ensure colors with out-of-range values are simply ignored. std::string color_json = "{ \"toolbar\": [0, 20, 40, -1], " " \"tab_text\": [60, 80, 100, 2], " " \"tab_background_text\": [120, 140, 160, 47.6], " " \"bookmark_text\": [256, 0, 0], " " \"ntp_text\": [0, -100, 100] }"; LoadColorJSON(color_json); VerifyColorMap(GetDefaultColorMap()); } TEST_F(BrowserThemePackTest, CanReadTints) { std::string tint_json = "{ \"buttons\": [ 0.5, 0.5, 0.5 ] }"; LoadTintJSON(tint_json); color_utils::HSL expected = { 0.5, 0.5, 0.5 }; color_utils::HSL actual = { -1, -1, -1 }; EXPECT_TRUE(theme_pack_->GetTint( ThemeProperties::TINT_BUTTONS, &actual)); EXPECT_DOUBLE_EQ(expected.h, actual.h); EXPECT_DOUBLE_EQ(expected.s, actual.s); EXPECT_DOUBLE_EQ(expected.l, actual.l); } TEST_F(BrowserThemePackTest, CanReadDisplayProperties) { std::string json = "{ \"ntp_background_alignment\": \"bottom\", " " \"ntp_background_repeat\": \"repeat-x\", " " \"ntp_logo_alternate\": 0 }"; LoadDisplayPropertiesJSON(json); int out_val; EXPECT_TRUE(theme_pack_->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT, &out_val)); EXPECT_EQ(ThemeProperties::ALIGN_BOTTOM, out_val); EXPECT_TRUE(theme_pack_->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_TILING, &out_val)); EXPECT_EQ(ThemeProperties::REPEAT_X, out_val); EXPECT_TRUE(theme_pack_->GetDisplayProperty( ThemeProperties::NTP_LOGO_ALTERNATE, &out_val)); EXPECT_EQ(0, out_val); } TEST_F(BrowserThemePackTest, CanParsePaths) { std::string path_json = "{ \"theme_button_background\": \"one\", " " \"theme_toolbar\": \"two\" }"; TestFilePathMap out_file_paths; ParseImageNamesJSON(path_json, &out_file_paths); size_t expected_file_paths = 2u; EXPECT_EQ(expected_file_paths, out_file_paths.size()); // "12" and "5" are internal constants to BrowserThemePack and are // PRS_THEME_BUTTON_BACKGROUND and PRS_THEME_TOOLBAR, but they are // implementation details that shouldn't be exported. // By default the scale factor is for 100%. EXPECT_TRUE(base::FilePath(FILE_PATH_LITERAL("one")) == out_file_paths[12][ui::SCALE_FACTOR_100P]); EXPECT_TRUE(base::FilePath(FILE_PATH_LITERAL("two")) == out_file_paths[5][ui::SCALE_FACTOR_100P]); } TEST_F(BrowserThemePackTest, InvalidPathNames) { std::string path_json = "{ \"wrong\": [1], " " \"theme_button_background\": \"one\", " " \"not_a_thing\": \"blah\" }"; TestFilePathMap out_file_paths; ParseImageNamesJSON(path_json, &out_file_paths); // We should have only parsed one valid path out of that mess above. EXPECT_EQ(1u, out_file_paths.size()); } TEST_F(BrowserThemePackTest, InvalidColors) { std::string invalid_color = "{ \"toolbar\": [\"dog\", \"cat\", [12]], " " \"sound\": \"woof\" }"; LoadColorJSON(invalid_color); std::map<int, SkColor> colors = GetDefaultColorMap(); VerifyColorMap(colors); } TEST_F(BrowserThemePackTest, InvalidTints) { std::string tints = "{ \"buttons\": [ \"dog\", \"cat\", [\"x\"]], " " \"frame\": [-2, 2, 3]," " \"frame_incognito_inactive\": [-1, 2, 0.6]," " \"invalid\": \"entry\" }"; LoadTintJSON(tints); // We should ignore completely invalid (non-numeric) tints. color_utils::HSL actual = { -1, -1, -1 }; EXPECT_FALSE(theme_pack_->GetTint(ThemeProperties::TINT_BUTTONS, &actual)); // We should change invalid numeric HSL tint components to the special -1 "no // change" value. EXPECT_TRUE(theme_pack_->GetTint(ThemeProperties::TINT_FRAME, &actual)); EXPECT_EQ(-1, actual.h); EXPECT_EQ(-1, actual.s); EXPECT_EQ(-1, actual.l); // We should correct partially incorrect inputs as well. EXPECT_TRUE(theme_pack_->GetTint( ThemeProperties::TINT_FRAME_INCOGNITO_INACTIVE, &actual)); EXPECT_EQ(-1, actual.h); EXPECT_EQ(-1, actual.s); EXPECT_EQ(0.6, actual.l); } TEST_F(BrowserThemePackTest, InvalidDisplayProperties) { std::string invalid_properties = "{ \"ntp_background_alignment\": [15], " " \"junk\": [15.3] }"; LoadDisplayPropertiesJSON(invalid_properties); int out_val; EXPECT_FALSE(theme_pack_->GetDisplayProperty( ThemeProperties::NTP_BACKGROUND_ALIGNMENT, &out_val)); } // These three tests should just not cause a segmentation fault. TEST_F(BrowserThemePackTest, NullPaths) { TestFilePathMap out_file_paths; ParseImageNamesDictionary(NULL, &out_file_paths); } TEST_F(BrowserThemePackTest, NullTints) { LoadTintDictionary(NULL); } TEST_F(BrowserThemePackTest, NullColors) { LoadColorDictionary(NULL); } TEST_F(BrowserThemePackTest, NullDisplayProperties) { LoadDisplayPropertiesDictionary(NULL); } TEST_F(BrowserThemePackTest, TestHasCustomImage) { // HasCustomImage should only return true for images that exist in the // extension and not for autogenerated images. std::string images = "{ \"theme_frame\": \"one\" }"; TestFilePathMap out_file_paths; ParseImageNamesJSON(images, &out_file_paths); EXPECT_TRUE(theme_pack_->HasCustomImage(IDR_THEME_FRAME)); EXPECT_FALSE(theme_pack_->HasCustomImage(IDR_THEME_FRAME_INCOGNITO)); } TEST_F(BrowserThemePackTest, TestNonExistantImages) { std::string images = "{ \"theme_frame\": \"does_not_exist\" }"; TestFilePathMap out_file_paths; ParseImageNamesJSON(images, &out_file_paths); EXPECT_FALSE(LoadRawBitmapsTo(out_file_paths)); } // TODO(erg): This test should actually test more of the built resources from // the extension data, but for now, exists so valgrind can test some of the // tricky memory stuff that BrowserThemePack does. TEST_F(BrowserThemePackTest, CanBuildAndReadPack) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); base::FilePath file = dir.GetPath().AppendASCII("data.pak"); // Part 1: Build the pack from an extension. { base::FilePath star_gazing_path = GetStarGazingPath(); scoped_refptr<BrowserThemePack> pack; BuildFromUnpackedExtension(star_gazing_path, pack); ASSERT_TRUE(pack->WriteToDisk(file)); VerifyStarGazing(pack.get()); } // Part 2: Try to read back the data pack that we just wrote to disk. { scoped_refptr<BrowserThemePack> pack = BrowserThemePack::BuildFromDataPack( file, "mblmlcbknbnfebdfjnolmcapmdofhmme"); ASSERT_TRUE(pack.get()); VerifyStarGazing(pack.get()); } } TEST_F(BrowserThemePackTest, HiDpiThemeTest) { base::ScopedTempDir dir; ASSERT_TRUE(dir.CreateUniqueTempDir()); base::FilePath file = dir.GetPath().AppendASCII("theme_data.pak"); // Part 1: Build the pack from an extension. { base::FilePath hidpi_path = GetHiDpiThemePath(); scoped_refptr<BrowserThemePack> pack; BuildFromUnpackedExtension(hidpi_path, pack); ASSERT_TRUE(pack->WriteToDisk(file)); VerifyHiDpiTheme(pack.get()); } // Part 2: Try to read back the data pack that we just wrote to disk. { scoped_refptr<BrowserThemePack> pack = BrowserThemePack::BuildFromDataPack(file, "gllekhaobjnhgeag"); ASSERT_TRUE(pack.get()); VerifyHiDpiTheme(pack.get()); } }
8d8d948b5c733c2e6df39fb4b041f00a1246c637
7df555bbd5f91989331f1f184b1cf56c0f6b463e
/src/SPIHelpers.cpp
bf5c2cf056668d6fd613421d98ab4b5224518c4d
[]
no_license
vpamrit/ArduinoSPIClientLib
d7ec9a50fe8b7ae6545433574ac3f2de1febc62f
051ee710acc370d11ec1037779dc3e5ba1f8548f
refs/heads/main
2023-05-30T18:36:41.755237
2021-07-03T15:06:53
2021-07-03T15:06:53
365,106,574
1
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
#include <SPIHelpers.h> uint8_t computeHeaderChecksum(const SPIPacketHeader &header) { uint8_t checksum = 0; checksum ^= header.packetPos; checksum ^= header.numPackets; checksum ^= header.structType; checksum ^= header.length; checksum ^= header.request; return checksum; } bool verifyHeaderChecksum(const SPIPacketHeader &header) { return computeHeaderChecksum(header) == header.headerChecksum; } bool verifyDataChecksum(volatile char* data, const SPIPacketHeader &header) { if (header.length > NUM_BYTES_DATA) { return false; } uint8_t checksumData = computeDataChecksum(data, header.length); return checksumData == header.checksum; } uint8_t computeDataChecksum(volatile char* data, uint8_t packetSize) { uint8_t checksum; for (int i = 0; i < packetSize; ++i) { checksum ^= data[i]; } return checksum; };
8c6c02bfd049c5c6e8becb71d62213b53a6b9ef6
622c4b5193bb164e1ec03e0d54a75b5e60369187
/arduino/pressure/pressure-bmp180/pressure-bmp180.ino
043d4a8d798377f2114ad370c8b30ffdcad6109f
[]
no_license
mkurdej/mkvp
3e34e81456a756d4302372b2117b67e0ad37cc85
d0c539cae3a32ba1bfacb22caec96fe4feaf57d7
refs/heads/master
2021-06-19T14:11:08.639070
2021-02-22T12:51:13
2021-02-22T12:51:13
3,922,369
0
0
null
null
null
null
UTF-8
C++
false
false
5,265
ino
#include <Adafruit_BMP085_U.h> #include <Adafruit_Sensor.h> #include <Wire.h> /* This driver uses the Adafruit unified sensor library (Adafruit_Sensor), which provides a common 'type' for sensor data and some helper functions. To use this driver you will also need to download the Adafruit_Sensor library and include it in your libraries folder. You should also assign a unique ID to this sensor for use with the Adafruit Sensor API so that you can identify this particular sensor in any data logs, etc. To assign a unique ID, simply provide an appropriate value in the constructor below (12345 is used by default in this example). Connections =========== Connect SCL to analog 5 Connect SDA to analog 4 Connect VDD to 3.3V DC Connect GROUND to common ground History ======= 2013/JUN/17 - Updated altitude calculations (KTOWN) 2013/FEB/13 - First version (KTOWN) */ Adafruit_BMP085_Unified bmp = Adafruit_BMP085_Unified(10085); /**************************************************************************/ /* Displays some basic information on this sensor from the unified sensor API sensor_t type (see Adafruit_Sensor for more information) */ /**************************************************************************/ void displaySensorDetails(void) { sensor_t sensor; bmp.getSensor(&sensor); Serial.println("------------------------------------"); Serial.print("Sensor: "); Serial.println(sensor.name); Serial.print("Driver Ver: "); Serial.println(sensor.version); Serial.print("Unique ID: "); Serial.println(sensor.sensor_id); Serial.print("Max Value: "); Serial.print(sensor.max_value); Serial.println(" hPa"); Serial.print("Min Value: "); Serial.print(sensor.min_value); Serial.println(" hPa"); Serial.print("Resolution: "); Serial.print(sensor.resolution); Serial.println(" hPa"); Serial.println("------------------------------------"); Serial.println(""); delay(500); } /**************************************************************************/ /* Arduino setup function (automatically called at startup) */ /**************************************************************************/ void setup(void) { Serial.begin(9600); Serial.println("Pressure Sensor Test"); Serial.println(""); /* Initialise the sensor */ if (!bmp.begin()) { /* There was a problem detecting the BMP085 ... check your connections */ Serial.print( "Ooops, no BMP085 detected ... Check your wiring or I2C ADDR!"); while (1) ; } /* Display some basic information on this sensor */ displaySensorDetails(); } /**************************************************************************/ /* Arduino loop function, called once 'setup' is complete (your own code should go here) */ /**************************************************************************/ void loop(void) { delay(1000); /* Get a new sensor event */ sensors_event_t event; bmp.getEvent(&event); /* Display the results (barometric pressure is measure in hPa) */ if (!event.pressure) return; /* Display atmospheric pressue in hPa */ Serial.print("Pressure: "); Serial.print(event.pressure); Serial.print(" hPa"); Serial.print("\t"); /* Calculating altitude with reasonable accuracy requires pressure * * sea level pressure for your position at the moment the data is * * converted, as well as the ambient temperature in degress * * celcius. If you don't have these values, a 'generic' value of * * 1013.25 hPa can be used (defined as SENSORS_PRESSURE_SEALEVELHPA * * in sensors.h), but this isn't ideal and will give variable * * results from one day to the next. * * * * You can usually find the current SLP value by looking at weather * * websites or from environmental information centers near any major * * airport. * * * * For example, for Paris, France you can check the current mean * * pressure and sea level at: http://bit.ly/16Au8ol */ /* First we get the current temperature from the BMP085 */ float temperature; bmp.getTemperature(&temperature); Serial.print("Temperature: "); Serial.print(temperature); Serial.print(" C"); Serial.print("\t"); constexpr float AltitudeHere = 428; Serial.print("Pressure at sea level: "); float seaLevelPressure = bmp.seaLevelForAltitude(AltitudeHere, event.pressure); Serial.print(seaLevelPressure); Serial.print(" hPa"); Serial.println(""); /* Then convert the atmospheric pressure, and SLP to altitude */ /* Update this next line with the current SLP for better results */ /* float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA; Serial.print("Altitude: "); //Serial.print(bmp.pressureToAltitude(seaLevelPressure, event.pressure)); Serial.print(bmp.pressureToAltitude(seaLevelPressure, event.pressure, temperature)); Serial.println(" m"); Serial.println(""); */ }
c75df45aa435613cb930bd993a1e0d32ee7b3c46
103a857a1f6771a5a1568df6556d1b495b1d03f3
/ipc/chromium/src/base/platform_thread_os2.cc
9344bdefb2568e5316e1018977a500b1282fa12e
[ "BSD-3-Clause" ]
permissive
dryeo/Pale-Moon
24d9ba93686de790b7790f69fdd586b01bbe7bf3
2314392a385c0ca8ab9dd26dc4eee774c9a401e6
refs/heads/master
2021-01-16T00:10:16.445416
2016-09-04T17:05:20
2016-09-04T17:05:20
46,599,880
0
0
null
2015-11-21T03:43:41
2015-11-21T03:43:41
null
UTF-8
C++
false
false
2,292
cc
// Copyright (c) 2006-2008 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. // exceptq trap file generator #define INCL_BASE #define INCL_PM #include <os2.h> #define INCL_LIBLOADEXCEPTQ #include <exceptq.h> #include "base/platform_thread.h" #include "base/logging.h" #include "private/pprthred.h" namespace { void ThreadFunc(void* closure) { // For arrays it's guaranteed that &[0] < &[1] which we use to make sure that the registration // record of the top (last) exception handler has a smaller address (i.e. located lower on the // stack) — this is a requirement of the SEH logic. EXCEPTIONREGISTRATIONRECORD excpreg[2]; LibLoadExceptq(&excpreg[1]); PR_OS2_SetFloatExcpHandler(&excpreg[0]); PlatformThread::Delegate* delegate = static_cast<PlatformThread::Delegate*>(closure); delegate->ThreadMain(); PR_OS2_UnsetFloatExcpHandler(&excpreg[0]); UninstallExceptq(&excpreg[1]); } } // namespace // static PlatformThreadId PlatformThread::CurrentId() { PTIB ptib; ::DosGetInfoBlocks(&ptib, NULL); return ptib->tib_ptib2->tib2_ultid; } // static void PlatformThread::YieldCurrentThread() { ::DosSleep(0); } // static void PlatformThread::Sleep(int duration_ms) { ::DosSleep(duration_ms); } // static void PlatformThread::SetName(const char* name) { // no way to set thread name on OS/2 return; } // static bool PlatformThread::Create(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle) { int result = _beginthread(ThreadFunc, NULL, stack_size, delegate); if (result != -1) { *thread_handle = result; return true; } return false; } // static bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { PlatformThreadHandle thread_handle; bool result = Create(stack_size, delegate, &thread_handle); return result; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { DCHECK(thread_handle); // Wait for the thread to exit. It should already have terminated but make // sure this assumption is valid. TID tid = thread_handle; APIRET result = ::DosWaitThread(&tid, DCWW_WAIT); DCHECK_EQ(NO_ERROR, result); }
7b5b0015f1c9ea2fef2384a5dd427126c3e6df2b
4bfcee530252964efb193cc3f3ca08d91b80524a
/OI/VIII/kom.cpp
3d51b2cc4399a59434f8cc9cc58aef1c765018c8
[]
no_license
Neverous/individual
63e1bcd12e54f4871d06036f3af31da2e56c40bc
bc16b259d16b09526ed39217eca4a3122d3e0466
refs/heads/master
2021-05-04T10:17:43.557190
2016-09-07T19:09:08
2016-09-07T19:09:08
54,484,436
0
0
null
null
null
null
UTF-8
C++
false
false
2,458
cpp
/* 2009 Maciej Szeptuch XIV LO WROCŁAW */ #include <cstdio> #include <vector> using namespace std; bool value [ 16016 ], color [ 16016 ], reverseColor [ 16016 ]; int verts, edges, st, nd, list2; vector < int > graph [ 16016 ], reverse [ 16016 ], list; int opposite ( int vert ) { return vert ^ 1; } bool setTrue ( int vert ) { if ( color [ vert ] && value [ vert ] ) return false; color [ vert ] = true; value [ vert ] = false; return true; } bool setFalse ( int vert ) { if ( color [ vert ] && ! value [ vert ] ) return false; color [ vert ] = true; if ( value [ vert ] ) return true; value [ vert ] = true; for ( int v = 0; v < graph [ vert ] . size ( ) ; ++ v ) { if ( ! value [ graph [ vert ] [ v ] ] ) if ( ! setTrue ( opposite ( graph [ vert ] [ v ] ) ) || ! setFalse ( graph [ vert ] [ v ] ) ) return false; } return true; } void dfsTopOrder ( int vert ) { color [ vert ] = true; for ( int v = 0; v < graph [ vert ] . size ( ); ++ v ) { if ( color [ graph [ vert ] [ v ] ] ) continue; dfsTopOrder ( graph [ vert ] [ v ] ); } list . push_back ( vert ); } void dfsResult ( int vert ) { reverseColor [ vert ] = true; for ( int v = 0; v < reverse [ vert ] . size ( ); ++ v ) { if ( reverseColor [ reverse [ vert ] [ v ] ] ) continue; dfsResult ( reverse [ vert ] [ v ] ) ; } } bool solve ( void ) { for ( int v = 0; v < 2 * verts; ++ v ) { if ( color [ v ] ) continue; dfsTopOrder ( v ); } for ( int v = 0; v < 2 * verts; ++ v ) color [ v ] = false; for ( int v = list . size ( ) - 1; v >= 0; -- v ) { if ( reverseColor [ list [ v ] ] ) continue; dfsResult ( list [ v ] ); if ( ! color [ list [ v ] ] ) if ( ! setTrue ( list [ v ] ) || ! setFalse ( opposite ( list [ v ] ) ) ) return false; } for ( int v = 0; v < 2 * verts; v += 2 ) if ( value [ v ] == value [ opposite ( v ) ] ) return false; for ( int v = 0; v < 2 * verts; ++ v ) if ( value [ v ] ) printf ( "%d\n", v + 1 ); return true; } int main ( void ) { scanf ( "%d %d", & verts, & edges ); for ( int e = 0; e < edges; ++ e ) { scanf ( "%d %d", & st, & nd ); -- st; -- nd; graph [ st ] . push_back ( opposite ( nd ) ); reverse [ opposite ( nd ) ] . push_back ( st ); //REV graph [ nd ] . push_back ( opposite ( st ) ); reverse [ opposite ( st ) ] . push_back ( nd ); //REV } if ( ! solve ( ) ) printf ( "NIE\n" ); return 0; }
a132c6350f633f3f76f16cbff5074f16b5dcc828
c554d52a8e2d8f65b512d59a2b158ae294276c32
/barkhausen_studio/kernel/core/data_buffer/include/ui_data.h
c3864a3dd1cf536919061db05aac67a57b0aec87
[]
no_license
xKafka/BarkhausenStudio
a0e6b9ed5a8fa37061e920f4d7d83a62e01d1536
1628b5198d63fb8f294070116818432471400e32
refs/heads/master
2023-04-29T11:00:18.958049
2021-05-14T10:30:58
2021-05-14T10:30:58
349,774,429
0
0
null
null
null
null
UTF-8
C++
false
false
454
h
// // Created by fkafka on 15. 4. 2021. // #ifndef BARKHAUSEN_STUDIO_UI_DATA_H #define BARKHAUSEN_STUDIO_UI_DATA_H #include <QVector> #include <QPointF> struct UiData { QVector<QPointF> barkhausen_ui_data; std::size_t barkhausen_ui_data_size{ 0 }; QVector<QPointF> B_H_ui_data; std::size_t B_H_ui_data_size{ 0 }; QVector<QPointF> hysteresis_data; std::size_t hysteresis_data_size{ 0 }; }; #endif //BARKHAUSEN_STUDIO_UI_DATA_H
[ "Kafka" ]
Kafka
ae66228fda72d5977118f7c357fda8345ce08c41
13bfcfd7492f3f4ee184aeafd0153a098e0e2fa5
/CodeForces/1360/D.cpp
4f7fde1eefe1b588f964005ac741233b2672d717
[]
no_license
jqk6/CodeArchive
fc59eb3bdf60f6c7861b82d012d298f2854d7f8e
aca7db126e6e6f24d0bbe667ae9ea2c926ac4a5f
refs/heads/master
2023-05-05T09:09:54.032436
2021-05-20T07:10:02
2021-05-20T07:10:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
430
cpp
#include<iostream> using namespace std; #define OW0 ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0); inline int min(int a, int b){ return a < b ? a : b; } int main(){OW0 int t, n, k, ans; cin >> t; for(;t;t--){ cin >> n >> k; ans = 1e9 + 10; for(int i = 1; i * i <= n; i++){ if(n % i == 0){ if(i <= k) ans = min(ans, n/i); if(n/i <= k) ans = min(ans, i); } } cout << ans << endl; } return 0; }
9ed8ad310e8a6f8fd4cd4d076906452f786dcd55
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE36_Absolute_Path_Traversal/s04/CWE36_Absolute_Path_Traversal__wchar_t_file_w32CreateFile_34.cpp
2d74a8f270b1039c5c00077402ac98c76e2975eb
[]
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
4,592
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_file_w32CreateFile_34.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-34.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: file Read input from a file * GoodSource: Full path and file name * Sinks: w32CreateFile * BadSink : Open the file named in data using CreateFile() * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif #ifdef _WIN32 #define FILENAME "C:\\temp\\file.txt" #else #define FILENAME "/tmp/file.txt" #endif #include <windows.h> namespace CWE36_Absolute_Path_Traversal__wchar_t_file_w32CreateFile_34 { typedef union { wchar_t * unionFirst; wchar_t * unionSecond; } unionType; #ifndef OMITBAD void bad() { wchar_t * data; unionType myUnion; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; { /* Read input from a file */ size_t dataLen = wcslen(data); FILE * pFile; /* if there is room in data, attempt to read the input from a file */ if (FILENAME_MAX-dataLen > 1) { pFile = fopen(FILENAME, "r"); if (pFile != NULL) { /* POTENTIAL FLAW: Read data from a file */ if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL) { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } fclose(pFile); } } } myUnion.unionFirst = data; { wchar_t * data = myUnion.unionSecond; { HANDLE hFile; /* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */ hFile = CreateFileW(data, (GENERIC_WRITE|GENERIC_READ), 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } } } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; unionType myUnion; wchar_t dataBuffer[FILENAME_MAX] = L""; data = dataBuffer; #ifdef _WIN32 /* FIX: Use a fixed, full path and file name */ wcscat(data, L"c:\\temp\\file.txt"); #else /* FIX: Use a fixed, full path and file name */ wcscat(data, L"/tmp/file.txt"); #endif myUnion.unionFirst = data; { wchar_t * data = myUnion.unionSecond; { HANDLE hFile; /* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */ hFile = CreateFileW(data, (GENERIC_WRITE|GENERIC_READ), 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { CloseHandle(hFile); } } } } void good() { goodG2B(); } #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 CWE36_Absolute_Path_Traversal__wchar_t_file_w32CreateFile_34; /* 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
681b00e323cde948f7828f487a6376878107c5e7
ca2cedfb1a150777c6732921dfe5b1aa4b9d341f
/cs452_lab3_f15-master/src/RTS.hpp
93a07ba51091f5d93032a62d1cf147423d5d8b18
[]
no_license
arcanexanth/cs452
fa5515cdc09429f9456a1b3e85070be961830750
6404185c716c33dd13470b0b6eba384e41e91b08
refs/heads/master
2020-05-16T21:19:56.037110
2019-04-24T20:34:13
2019-04-24T20:34:13
183,302,631
0
0
null
null
null
null
UTF-8
C++
false
false
347
hpp
#ifndef RTS_HPP #define RTS_HPP #include "Scheduler.hpp" class RTS : public Scheduler { public: RTS(vector<Process *> &processes); void run(); virtual ~RTS(); //void loadArrivals(int clock, int jobsLoaded, deque<Process*> rtsQueue, char softOrHard, bool hardRealTimeStop); private: }; #endif /* RTS_HPP */