blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
1c2fa79132434fa7f92ae35720a7065b0fe1b002
db8c37dd055d8debc1054beccc7c0e2a7f48f98f
/WordQueue.cpp
bb278d32145fd4748ff93236e06f4a3771577f24
[]
no_license
SeaCastle/WordLadder
3acf44c5c573e1e94542e31d8aff5b7fa3f83d3e
dc8ade853d4bb7e89b84ddb8c2e2967f7d040797
refs/heads/master
2020-04-05T20:14:38.356326
2018-11-12T07:14:12
2018-11-12T07:14:12
157,171,134
0
0
null
null
null
null
UTF-8
C++
false
false
2,055
cpp
// // WordQueue.cpp // Cs3 Assignment 1 // // Created by Spencer Peterson on 1/19/17. // Copyright © 2017 StickmanMafia. All rights reserved. // #include "WordQueue.hpp" WordQueue::WordQueue() { head = NULL; tail = NULL; } void WordQueue::enqueue(vector<string> newWords) { Node* temp = new Node(); temp->wordLadder = newWords; temp->next = nullptr; if (head == nullptr) { head = temp; } else { tail->next = temp; } tail = temp; } bool WordQueue::isEmpty() { bool isEmpty = false; if (head == NULL) { isEmpty = true; } return isEmpty; } bool WordQueue::isWordConnected(string current, string test) { bool isConnected = false; int length = current.length(); int i = 0; // Search for any words that differ from the current word by 1 letter starting with // the first letter and moving toward the end 1 letter at a time while (!isConnected && i < length) { // This first and second if statements are unique for allowing the changing of the first and last letter if (i == 0 && current.substr(i+1, length) == test.substr(i+1, length)) { isConnected = true; } else if (i == length-1 && current.substr(0, i) == test.substr(0, i)) { isConnected = true; } else if (current.substr(0, i) == test.substr(0, i) && current.substr(i+1, length) == test.substr(i+1, length)) { isConnected = true; } ++i; } return isConnected; } void WordQueue::dequeue() { Node* temp = new Node(); if (head == nullptr) { cout << "Queue is empty" << endl; return; } else { temp = head; head = head->next; delete temp; } } vector<string> WordQueue::getFrontLadder() { if (head == nullptr) { vector<string> empty = {"empty"}; return empty; } else { return head->wordLadder; } }
[ "spencerthomasp@gmail.comgit config --global user.email spencerthomasp@gmail.com" ]
spencerthomasp@gmail.comgit config --global user.email spencerthomasp@gmail.com
4d881bd39b427f2463033c2044fd3e89c123784a
54f352a242a8ad6ff5516703e91da61e08d9a9e6
/Source Codes/AtCoder/arc035/B/3024814.cpp
53459cc9c76eb1938cde1c062e7293950ca8402d
[]
no_license
Kawser-nerd/CLCDSA
5cbd8a4c3f65173e4e8e0d7ed845574c4770c3eb
aee32551795763b54acb26856ab239370cac4e75
refs/heads/master
2022-02-09T11:08:56.588303
2022-01-26T18:53:40
2022-01-26T18:53:40
211,783,197
23
9
null
null
null
null
UTF-8
C++
false
false
1,401
cpp
#include <cstdio> #include <cstdlib> #include <iostream> #include <fstream> #include <sstream> #include <set> #include <map> #include <vector> #include <list> #include <algorithm> #include <cstring> #include <cmath> #include <string> #include <queue> #include <bitset> //UWAGA - w czasie kompilacji musi byc znany rozmiar wektora - nie mozna go zmienic #include <cassert> #include <iomanip> //do setprecision #include <ctime> #include <complex> using namespace std; #define FOR(i,b,e) for(int i=(b);i<(e);++i) #define FORQ(i,b,e) for(int i=(b);i<=(e);++i) #define FORD(i,b,e) for(int i=(b)-1;i>=(e);--i) #define REP(x, n) for(int x = 0; x < (n); ++x) #define ST first #define ND second #define PB push_back #define MP make_pair #define LL long long #define ULL unsigned LL #define LD long double #define pii pair<int,int> #define pll pair<LL,LL> const double pi = 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342; const int mod=1000000007; int main(){ int n,t[10101]={}; cin>>n; map<int,int> mp; LL ans=0LL,c=1LL,nw=0LL; FOR(i,0,n){ cin>>t[i]; mp[t[i]]++; } for(auto x:mp){ LL p=x.ST,q=x.ND,t=1LL; FOR(i,0,q){ nw+=p; ans+=nw; t=(t*(q-i))%mod; } c=(c*t)%mod; } cout<<ans<<endl; cout<<c<<endl; return 0; }
[ "kwnafi@yahoo.com" ]
kwnafi@yahoo.com
40f0d611ea4da2cc97fef803d8502603ddeff143
0d084ff09f85061fbb87757f3579361b013e301e
/src/qt/bitcoinaddressvalidator.cpp
b23f3d57b73721b61b6e052890223a1f58724479
[ "MIT" ]
permissive
alik918/dngrcoin
c5a699d6cfd753457b2dde1ea2fb9cc80f882e70
adf8bb68e4c2f8d3b6673c2807d99ba5377d8dd1
refs/heads/master
2023-02-04T11:31:01.342700
2020-12-22T16:34:18
2020-12-22T16:34:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,654
cpp
// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2014-2017 The DNGRcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinaddressvalidator.h" #include "base58.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All upper-case letters except for 'I' and 'O' - All lower-case letters except for 'l' */ BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject *parent) : QValidator(parent) { } QValidator::State BitcoinAddressEntryValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Empty address is "intermediate" input if (input.isEmpty()) return QValidator::Intermediate; // Correction for (int idx = 0; idx < input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch(ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if (ch.isSpace()) removeChar = true; // To next character if (removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for (int idx = 0; idx < input.size(); ++idx) { int ch = input.at(idx).unicode(); if (((ch >= '0' && ch<='9') || (ch >= 'a' && ch<='z') || (ch >= 'A' && ch<='Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Alphanumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } return state; } BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject *parent) : QValidator(parent) { } QValidator::State BitcoinAddressCheckValidator::validate(QString &input, int &pos) const { Q_UNUSED(pos); // Validate the passed DNGRcoin address CBitcoinAddress addr(input.toStdString()); if (addr.IsValid()) return QValidator::Acceptable; return QValidator::Invalid; }
[ "you@example.com" ]
you@example.com
3946df72d7dbe53ae1667203eea4bf0f63b21004
a3caf170c93d2743d1a6c45bd7f2d97fd58252b1
/lite/ComponentForward.hpp
68b3409fc20693c5c18fb0af85f58ac6a74d5d9c
[]
no_license
ItsRoyScott/Lite
295055e32aa98b5ee790b6542e4deca0c21b7b24
e1ac7401d9956f8e25ee4c83ca6e9a3df0089fc5
refs/heads/master
2021-01-25T10:06:49.857186
2014-08-06T04:00:10
2014-08-06T04:00:10
21,678,407
2
0
null
null
null
null
UTF-8
C++
false
false
532
hpp
#pragma once namespace lite { class Model; class PlaneCollision; class RigidBody; class SphereCollision; class Transform; // Null pointers for easy indexing into GameObject // to retrieve a component by type. static const Model* Model_ = nullptr; static const PlaneCollision* PlaneCollision_ = nullptr; static const RigidBody* RigidBody_ = nullptr; static const SphereCollision* SphereCollision_ = nullptr; static const Transform* Transform_ = nullptr; } // namespace lite
[ "roylandscottness@gmail.com" ]
roylandscottness@gmail.com
fb9ac4f70adf0546b2e9462ce5bea97c69746030
bfc078bc9b2484b08146f543ebd2561acdbf0d17
/HW262017.cpp
e73a498cdd416ee47a7f286c594fdfdc69372676
[]
no_license
TheOriginalMomo/C-Exercises-
3ade46c6a9a7a321a9bf989fe0237ae20a6d5970
21b7abf45f6dc4916ffbe1bb30c8327da92abb4e
refs/heads/master
2021-01-16T14:11:44.822041
2020-06-23T01:39:01
2020-06-23T01:39:01
243,149,025
0
0
null
null
null
null
UTF-8
C++
false
false
2,580
cpp
/* --------------------------------------------------------------------------- ** I attest that this following code represents my own work and is subject to ** the plagiarism policy found in the course syllabus. ** ** Semester: Spring 2017 ** Assignment: Hw ** File: filename.cpp ** Description:Query the user to fill two m x n static matrices,display them, calculate and print a third matrix which is the sum of the first two. ** ** Author: Momo ** Date: 2/6/2017 ** -------------------------------------------------------------------------*/ //Resources Atds,C++ through gaming, #include <iostream> #include <stdio.h> using namespace std; int main () { int row,col; int item; int Matrix[2][4]; int Matrix2[2][4]; int Sum[2][4]; int sumrow,sumcol; cout<<"Enter Numbers into the first Array"<<endl; for (row=0;row<2;row++){ for(col=0;col<4;col++){ scanf("%d",&Matrix[row][col]); //Reads the data that the user entered //The data is stored to be read } } for (row=0;row<2;row++){ for(col=0;col<4;col++){ printf(" \t%d ",Matrix[row][col]);//The t is the spacing //Formats the the output using a certain specifier, } //Single Integer printf(" \n "); //Reads the data with a new line cout<<endl; //The data is spaced after it is displayed } cout<<"Enter Numbers into the Second Array"<<endl; for (row=0;row<2;row++){ for(col=0;col<4;col++){ scanf("%d",&Matrix2[row][col]); //Reads the data that the user entered } } for (row=0;row<2;row++){ for(col=0;col<4;col++){ printf(" \t%d ",Matrix2[row][col]);//The t is the spacing //Formats the the output using a certain specifier, } //Single Integer printf(" \n "); //Reads the data with a new line cout<<endl; //The data is spaced } cout<<"The sum of the Matrices"<<endl; for (sumrow=0;sumrow<row;sumrow++){ //Created rows and columns for the new Matrix for (sumcol=0;sumcol<col;sumcol++){ Sum[sumrow][sumcol]=Matrix[sumrow][sumcol]+Matrix2[sumrow][sumcol]; //The new rows and columns are the new values //The First Matrix and the Second Matrix already have rows and columns printf(" \t%d ",Sum[sumrow][sumcol]); //Reads the new array and prints decimals integers } printf(" \n "); } return 0; }
[ "noreply@github.com" ]
noreply@github.com
3ed1496d389bfa93c05c70de9f61f4234c40c300
844969bd953d7300f02172c867725e27b518c08e
/SDK/Title_BoomBones_SkeletonExploder_classes.h
27bd6842804b576f0bed9dd19ea4a75d227c374b
[]
no_license
zanzo420/SoT-Python-Offset-Finder
70037c37991a2df53fa671e3c8ce12c45fbf75a5
d881877da08b5c5beaaca140f0ab768223b75d4d
refs/heads/main
2023-07-18T17:25:01.596284
2021-09-09T12:31:51
2021-09-09T12:31:51
380,604,174
0
0
null
2021-06-26T22:07:04
2021-06-26T22:07:03
null
UTF-8
C++
false
false
843
h
#pragma once // Name: SoT, Version: 2.2.1.1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Title_BoomBones_SkeletonExploder.Title_BoomBones_SkeletonExploder_C // 0x0000 (FullSize[0x00E0] - InheritedSize[0x00E0]) class UTitle_BoomBones_SkeletonExploder_C : public UTitleDesc { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass Title_BoomBones_SkeletonExploder.Title_BoomBones_SkeletonExploder_C"); return ptr; } void AfterRead(); void BeforeDelete(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "51171051+DougTheDruid@users.noreply.github.com" ]
51171051+DougTheDruid@users.noreply.github.com
9cdf105d81cb54b7e16dbd2e27b76a0af134484c
b2df14a1a89c4f28a575bcb232f98b239320bdff
/Utils/utils.h
b5847cd982624cbd9c42753fc682fa1b39909c39
[]
no_license
ArtTemiy/JRBits_SHIT
a8fcb4dc54470a15e093679959089da680aaa287
d7df08aaa0e541d7370d21174bed68068e55528b
refs/heads/master
2022-11-09T19:16:28.798958
2020-06-28T12:44:49
2020-06-28T12:44:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
603
h
# pragma once #include <SFML/Graphics.hpp> #include "../Physics/vectorNd.h" #include <filesystem> #include <iostream> #include <string> #include <unordered_map> #include <vector> void SetSpriteSize(sf::Sprite& sprite, const vector2d& size); struct FileName { //FileName(std::string path); std::string key; std::string path; }; std::vector<FileName> ListOfFiles(std::string path); std::unordered_map<std::string, sf::Texture> LoadTextures(const std::string& path); std::unordered_map<std::string, sf::Sprite> MakeSpritersFromTextures(const std::unordered_map<std::string, sf::Texture>& textures);
[ "artemiy_shvedov@mail.ru" ]
artemiy_shvedov@mail.ru
ea57e36706376dcd83e4c34cd6d52425a66b7ad4
f74256b079b12a02406b0eda5321f2dc22b3226c
/zhangxiaolong/RotateImage.cpp
88120ea83238f6e61a8d7eb5fa66cda35699a556
[ "Apache-2.0" ]
permissive
ylovesy/CodeFun
e716c840c0c08227c4cae0120161e99e15d3c1e2
4469a88b5fe8796054d4d60025c857c18eb374db
refs/heads/master
2021-07-17T19:45:11.099724
2017-12-14T12:34:29
2017-12-14T12:34:29
96,773,933
0
3
null
2017-07-15T06:55:14
2017-07-10T12:16:28
C++
UTF-8
C++
false
false
925
cpp
// // RotateImage.cpp // 数据结构练习 // // Created by zhangxiaolong on 2017/8/10. // Copyright © 2017年 zhangxiaolong. All rights reserved. // #include <stdio.h> #include <vector> using namespace std; class RotateImageSolution { public:void rotate(vector<vector<int>>& matrix) { if(matrix.size() ==0 || matrix[0].size() == 0) return; int layerNum = matrix.size() * 0.5; for(int layer=0;layer<layerNum;layer++) { for(int i=layer;i<matrix.size() - layer - 1;i++) { int temp = matrix[layer][i]; matrix[layer][i] = matrix[matrix.size() - 1 - i][layer]; matrix[matrix.size() - 1 - i][layer] = matrix[matrix.size() - 1 - layer][matrix.size() - 1 - i]; matrix[matrix.size() - 1 - layer][matrix.size() - 1 - i] = matrix[i][matrix.size() - 1 - layer]; matrix[i][matrix.size() - 1 - layer] = temp; } } } };
[ "zhangxiaolong@lianjia.com" ]
zhangxiaolong@lianjia.com
94418ae4fe96765c5dc4dad6c3f150aeadd65851
d7d6678b2c73f46ffe657f37169f8e17e2899984
/controllers/ros/include/webots_ros/camera_get_infoRequest.h
c2cd96d280a2f90bcdedf90f408b045862618e9a
[]
no_license
rggasoto/AdvRobotNav
ad8245618e1cc65aaf9a0d659c4bb1588f035f18
d562ba4fba896dc23ea917bc2ca2d3c9e839b037
refs/heads/master
2021-05-31T12:00:12.452249
2016-04-15T14:02:05
2016-04-15T14:02:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,054
h
#ifndef WEBOTS_ROS_MESSAGE_CAMERA_GET_INFOREQUEST_H #define WEBOTS_ROS_MESSAGE_CAMERA_GET_INFOREQUEST_H #include <string> #include <vector> #include <map> #include "ros/types.h" #include "ros/serialization.h" #include "ros/builtin_message_traits.h" #include "ros/message_operations.h" namespace webots_ros { template <class ContainerAllocator> struct camera_get_infoRequest_ { typedef camera_get_infoRequest_<ContainerAllocator> Type; camera_get_infoRequest_() : ask(0) { } camera_get_infoRequest_(const ContainerAllocator& _alloc) : ask(0) { } typedef uint8_t _ask_type; _ask_type ask; typedef boost::shared_ptr< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> const> ConstPtr; boost::shared_ptr<std::map<std::string, std::string> > __connection_header; }; typedef ::webots_ros::camera_get_infoRequest_<std::allocator<void> > camera_get_infoRequest; typedef boost::shared_ptr< ::webots_ros::camera_get_infoRequest > camera_get_infoRequestPtr; typedef boost::shared_ptr< ::webots_ros::camera_get_infoRequest const> camera_get_infoRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::webots_ros::camera_get_infoRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace webots_ros namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/groovy/share/std_msgs/msg'], 'webots_ros // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > { static const char* value() { return "27c62b916852ab73ab27a40703fb9ea5"; } static const char* value(const ::webots_ros::camera_get_infoRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xf9df5232b65af94fULL; static const uint64_t static_value2 = 0x73f79fe6d84301bbULL; }; template<class ContainerAllocator> struct DataType< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > { static const char* value() { return "webots_ros/camera_get_infoRequest"; } static const char* value(const ::webots_ros::camera_get_infoRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > { static const char* value() { return "uint8 ask\n\\n\ \n\ "; } static const char* value(const ::webots_ros::camera_get_infoRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.ask); } ROS_DECLARE_ALLINONE_SERIALIZER; }; } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::webots_ros::camera_get_infoRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::webots_ros::camera_get_infoRequest_<ContainerAllocator>& v) { s << indent << "ask: "; Printer<uint8_t>::stream(s, indent + " ", v.ask); } }; } // namespace message_operations } // namespace ros #endif // WEBOTS_ROS_MESSAGE_CAMERA_GET_INFOREQUEST_H
[ "rggasoto@wpi.edu" ]
rggasoto@wpi.edu
3a0638f6c94d98aac5efe051de0fa295bd40c4c8
ce8bd73a9cda2d65d0610f2442847bf4ee647da5
/src/com/typesafe/config/impl/SimpleIncluder_NameSource.cpp
bad6e4ab031160abd1ffb9b16c562d3d3eca7a26
[]
no_license
cprice404/j2c-ts-config
5fec505bd0a9d3b7c968e5d60e7f66db323d9cc4
4fe6cc64c7035b92251ef645cace6898344551de
refs/heads/master
2020-12-24T13:29:05.975373
2015-07-08T06:00:04
2015-07-08T06:00:04
38,735,023
0
0
null
null
null
null
UTF-8
C++
false
false
421
cpp
// Generated from /config/src/main/java/com/typesafe/config/impl/SimpleIncluder.java #include <com/typesafe/config/impl/SimpleIncluder_NameSource.hpp> extern java::lang::Class* class_(const char16_t* c, int n); java::lang::Class* com::typesafe::config::impl::SimpleIncluder_NameSource::class_() { static ::java::lang::Class* c = ::class_(u"com.typesafe.config.impl.SimpleIncluder.NameSource", 50); return c; }
[ "chris@puppetlabs.com" ]
chris@puppetlabs.com
be9542b3ace38666acd7080805b14a3de5d65cfd
f7d3f489d2f28d9d57696e95988b09b19f0cfc16
/Division.h
ea90e7b212041023c573a46ba524028b07d6ae71
[]
no_license
qingqingkzhou/MultiplicationDivisionSqrt
d33513281cacf4c9ab9918fc5cb1f2703448e3ed
b578f6096beafa5fd1a855461e0aae7439bee346
refs/heads/master
2020-06-13T19:31:07.602841
2019-07-02T02:00:17
2019-07-02T02:00:17
194,766,825
0
0
null
null
null
null
UTF-8
C++
false
false
1,007
h
// // Division.h // // // Created by Qingqing Zhou on June 29, 2019 // // Using Newton method with Karatsuba multiplication // for precision requirements of longer than 64 bits // #ifndef DIVISION_H #define DIVISION_H #include <iostream> #include <vector> #include <string> class Division { public: // Calculate 1/num and giving precision digits // @Param precision: 10^precision, # of digits std::string Reciprocal(std::string num, int precision); std::string Div(std::string lhs, std::string rhs, size_t precision); std::string DivInt(std::string lhs, std::string rhs, size_t precision); std::string DivFloat(std::string lhs, std::string rhs, size_t precision); private: template <typename T> std::string to_string_with_precision(const T a_value, const int n); std::string ShiftR(std::string str, const int R); std::string Interate(std::string b, std::string xi, int precision); void PrintDetails(int i, std::string text); }; #endif /* DIVISION_H */
[ "qingqing.k.zhou@gmail.com" ]
qingqing.k.zhou@gmail.com
93824eb8fe5e3bdf10f346d20e52ba491eda6dd5
9be246df43e02fba30ee2595c8cec14ac2b355d1
/worldcraft/editprefabdlg.h
d1206501d8f85ad06b6b756351b4579f1452ec6b
[]
no_license
Clepoy3/LeakNet
6bf4c5d5535b3824a350f32352f457d8be87d609
8866efcb9b0bf9290b80f7263e2ce2074302640a
refs/heads/master
2020-05-30T04:53:22.193725
2019-04-12T16:06:26
2019-04-12T16:06:26
189,544,338
18
5
null
2019-05-31T06:59:39
2019-05-31T06:59:39
null
UTF-8
C++
false
false
1,079
h
// EditPrefabDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CEditPrefabDlg dialog class CEditPrefabDlg : public CDialog { // Construction public: CEditPrefabDlg(CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CEditPrefabDlg) enum { IDD = IDD_EDITPREFAB }; CComboBox m_CreateIn; CEdit m_Name; CEdit m_Descript; CString m_strDescript; CString m_strName; //}}AFX_DATA void SetRanges(int iMaxDescript, int iMaxName); void EnableLibrary(BOOL = TRUE); DWORD m_dwLibraryID; // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CEditPrefabDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: int iMaxDescriptChars, iMaxNameChars; BOOL m_bEnableLibrary; // Generated message map functions //{{AFX_MSG(CEditPrefabDlg) virtual BOOL OnInitDialog(); afx_msg void OnSelchangeCreatein(); //}}AFX_MSG DECLARE_MESSAGE_MAP() };
[ "uavxp29@gmail.com" ]
uavxp29@gmail.com
3072f5f765cf004660159331542eb3bac5376c5e
8493efac7db46daa650ea2ca7e6e3fe61f16882d
/DemosC/DemosC/cpp/ImoocPart5/TestPart2_1.cpp
aee6956031ad1e266115630d4a1daecbfe9deb25
[]
no_license
fade4j/FragmentaryDemosC
4e8976f28afbc4175b36b95f54d9a7ca33b6a800
c6e1a2bb9057687c18302e3d6d62e691386dbaa0
refs/heads/master
2021-08-19T14:02:46.768701
2017-11-26T14:03:37
2017-11-26T14:03:37
109,136,717
0
0
null
null
null
null
UTF-8
C++
false
false
384
cpp
#include <iostream> //#include "Circle.h" //#include "Coordinate.h" #include "Time.h" #include "Match.h" using namespace std; void printTime(Time &t); int main() { Time t(21,31,56); Match m; m.printTime(t); //Circle circle; //circle.printXY(coor); system("pause"); return 0; } void printTime(Time &t) { //cout << t.m_iHour << ":" << t.m_iMin << ":" << t.m_iSecond<< endl; }
[ "fade4j@163.com" ]
fade4j@163.com
ca39e6a14a9714a6940c1a1e051438393480b20c
82b788176c45b596980ae178884e7a055c625715
/Codeforces/466/C [Number of Ways].cpp
2815e45ebda6ff38eba5dc7a1653ace7f8cdb2a8
[]
no_license
RanadevVarma/CP
ebf1afa5895cfa461c920a1a93939b28242b5b88
752b89e68296a337d1cc3845c991e8a80522a5fa
refs/heads/master
2020-03-25T06:53:06.954666
2018-08-04T13:12:23
2018-08-04T13:12:23
143,530,105
0
0
null
null
null
null
UTF-8
C++
false
false
960
cpp
#pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #include <iostream> #include <cstring> #include <cmath> #include <iterator> #include <algorithm> #include <stack> #include <vector> #include <queue> #include <stdio.h> using namespace std ; long long int sum,ans,cou; int main() { int n ; cin >> n ; int in[n] ; long long int presum[n+1] = {0} ; for(int i = 0 ; i < n ; i++) { cin >> in[i]; sum = sum + in[i]; } for(int i = 1 ; i <= n ; i++) { presum[i] = presum[i-1] + in[i-1] ; } if(sum%3!=0) { cout << "0" << "\n"; return 0 ; } else { long long int fp = sum/3 ; long long int sp = 2*sum/3 ; for(int i = 1 ; i < n ; i++) { if(presum[i]==sp) { ans = ans + cou ; } if(presum[i]==fp) { cou++; } } cout << ans << "\n"; } }
[ "me16btech11020@iith.ac.in" ]
me16btech11020@iith.ac.in
0a5e16475365d3a386bbd75aec6263a02f44c5c0
347fdd4d3b75c3ab0ecca61cf3671d2e6888e0d1
/apps/addonExamples/exampleNetworkTcpServer/src/MyApp.h
5a55076af135b7cc562ef6ec420478360df42ff2
[]
no_license
sanyaade/VirtualAwesome
29688648aa3f191cdd756c826b5c84f6f841b93f
05f3db98500366be1e79da16f5e353e366aed01f
refs/heads/master
2020-12-01T03:03:51.561884
2010-11-08T00:17:44
2010-11-08T00:17:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
661
h
/* * * * MyApp can handle many events: mouse, key, pen, touch ... * http://labs.nortd.com/va/docs/reference#allHandlers */ #ifndef VA_MYAPP #define VA_MYAPP #include <va/Main.h> #include <vaNetwork/Main.h> class MyApp : public va::App, public vaNetwork::NetworkHandler { public: MyApp(); ~MyApp(); void networkConnect( std::string ip, int port ); void networkDisconnect( std::string ip, int port ); void networkReceive( vaNetwork::Message message ); vaNetwork::AwesomeSocket* server; va::PanelWidget* panel; va::TextShape* textbox; }; #endif
[ "stefan@nortd.com" ]
stefan@nortd.com
f07a54c87d5da7f09da2dbb9133a49104f1768eb
2dfe1a0bd56ba30669e35d4e3216cefa69c5e3ac
/GStreamerUnityPlugin/StreamersAPI.cpp
822e445003cd166b4ffda7e0b420db4c5d7b7085
[]
no_license
ua-i2cat/mrayGStreamerUnity
f50cdf717c50669157fdb21ec2915e1c8a1681d6
9591852b8e5f7bfcd710ad5f7a61e18f2baaebae
refs/heads/master
2020-12-11T01:43:25.472201
2015-12-03T14:25:06
2015-12-03T14:25:06
47,266,854
1
0
null
2015-12-02T14:38:17
2015-12-02T14:38:17
null
UTF-8
C++
false
false
2,357
cpp
#include "StreamersAPI.h" #include "GStreamerCore.h" #include "GraphicsInclude.h" #include "PixelUtil.h" extern "C" EXPORT_API void* mray_gst_createUnityImageGrabber() { GStreamerCore* c = GStreamerCore::Instance(); if (c) { UnityImageGrabber* g = new UnityImageGrabber(); return g; } return 0; } extern "C" EXPORT_API void mray_gst_UnityImageGrabberSetData(UnityImageGrabber* g, void* _TextureNativePtr, int _UnityTextureWidth, int _UnityTextureHeight, int Format) { if (!g) return; g->SetData(_TextureNativePtr, _UnityTextureWidth, _UnityTextureHeight, Format); } extern "C" EXPORT_API void mray_gst_StreamerDestroy(IGStreamerStreamer* p) { if (p != nullptr) { p->Close(); delete p; } } extern "C" EXPORT_API void mray_gst_StreamerStream(IGStreamerStreamer* p) { if (p != nullptr) { p->Stream(); } } extern "C" EXPORT_API void mray_gst_StreamerPause(IGStreamerStreamer* p) { if (p != nullptr) { p->SetPaused(true); } } extern "C" EXPORT_API void mray_gst_StreamerStop(IGStreamerStreamer* p) { if (p != nullptr) { p->Stop(); } } extern "C" EXPORT_API bool mray_gst_StreamerIsStreaming(IGStreamerStreamer* p) { if (p != nullptr) { return p->IsStreaming(); } return false; } extern "C" EXPORT_API void mray_gst_StreamerClose(IGStreamerStreamer* p) { if (p != nullptr) { return p->Close(); } } extern "C" EXPORT_API void* mray_gst_createNetworkStreamer() { GStreamerCore* c = GStreamerCore::Instance(); if (c) { GstCustomVideoStreamer* g = new GstCustomVideoStreamer(); return g; } return 0; } extern "C" EXPORT_API void mray_gst_netStreamerSetIP(GstCustomVideoStreamer* p, const char* ip, int videoPort, bool rtcp) { if (p) { p->BindPorts(ip, videoPort, 0, rtcp); } } extern "C" EXPORT_API bool mray_gst_netStreamerCreateStream(GstCustomVideoStreamer* p) { if (p) { return p->CreateStream(); } return false; } extern "C" EXPORT_API void mray_gst_netStreamerSetGrabber(GstCustomVideoStreamer* p, UnityImageGrabber* g) { if (p) { p->SetVideoGrabber(g); } } extern "C" EXPORT_API void mray_gst_netStreamerSetBitRate(GstCustomVideoStreamer* p, int bitRate) { if (p) { p->SetBitRate(bitRate); } } extern "C" EXPORT_API void mray_gst_netStreamerSetResolution(GstCustomVideoStreamer* p, int width, int height, int fps) { if (p) { p->SetResolution(width,height,fps); } }
[ "mrayyamen@gmail.com" ]
mrayyamen@gmail.com
c30ce89595da482c5d67c405264837c28b87fd5d
fa1eb49c32c78e5ff095d3798a3eb845eaf5e077
/Simulator.h
6e893cb482f5a8f53e3212c86df3350057740717
[]
no_license
diogojs/GenESyS-Reborn
a2e0ce8a39a693cecc09eb037b75ece60ed44747
1a0617679ec3d61442533ac9d34db963f5a8089a
refs/heads/master
2020-03-27T13:54:47.922254
2018-09-26T03:25:01
2018-09-26T03:25:01
146,634,093
0
0
null
2018-09-11T13:47:09
2018-08-29T17:20:36
C++
UTF-8
C++
false
false
1,742
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: Genesys.h * Author: cancian * * Created on 21 de Junho de 2018, 12:48 */ #ifndef GENESYS_H #define GENESYS_H #include <string> #include <iostream> #include "Traits.h" #include "Model.h" #include "Plugin.h" #include "List.h" #include "Fitter_if.h" /*! * The main class of the Genesys KERNEL simulation. It gives access to simulation models and tools. */ class Simulator { typedef void (*eventHandler)(); public: Simulator(); Simulator(const Simulator& orig); virtual ~Simulator(); public: // get & set /*! */ List<Model*>* getModels() const; List<Plugin*>* getPlugins() const; public: // only get std::string getVersion() const; std::string getLicense() const; std::string getName() const; Sampler_if* getSampler() const; Fitter_if* getFitter() const; public: // event handlers private: // attributes 1:n List<Plugin*>* _plugins; List<Model*>* _models; private: // attributes 1:1 objects Fitter_if* _fitter = new Traits<Fitter_if>::Implementation(); Sampler_if* _sampler = new Traits<Sampler_if>::Implementation(); private: // attributes 1:1 native const std::string _name = "GenESyS - Generic and Expansible System Simulator [REBORN]"; const std::string _license = "Academic Mode. In academic mode this software has full functionality and executing training-size simulation models. This software may be duplicated and used for educational purposes only; any commercial application is a violation of the license agreement."; const std::string _version = "2018.2.9"; }; #endif /* GENESYS_H */
[ "cancian@lisha.ufsc.br" ]
cancian@lisha.ufsc.br
68f1d8fbb945fb7a5f5648b73ef7a288f649f54e
c62e654417f64705fc54aca4759b54c73ac756f1
/sources/atcoder/abc073_a/c.cpp
d77b9176ac3be512a7dfff06e184fbeb06e8cd4e
[]
no_license
miguelmartin75/cp-problems
9c56b14e61808650c5ad103ec1024223cfbfc26b
fbafdf7c4e70c18f003e54d4f657980e6e2948e3
refs/heads/master
2021-08-17T21:46:31.237678
2021-04-03T17:59:08
2021-04-03T17:59:08
80,083,158
0
0
null
null
null
null
UTF-8
C++
false
false
341
cpp
#include <bits/stdc++.h> using namespace std; int main(int argc, char *argv[]) { unordered_map<int, bool> m; int n; cin >> n; for(int i = 0; i < n; ++i) { int x; cin >> x; m[x] = !m[x]; } cout << accumulate(m.begin(), m.end(), 0, [](auto& x, auto& y) { return x + y.second; }) << endl; }
[ "miguel@miguel-martin.com" ]
miguel@miguel-martin.com
8cb62393869611d76b5d71851e85067425ae9fc4
58de537f893a5b891ab018a145e24f20e1a52b3c
/mantissa.cpp
63091054ed6fd83e0f03e2ac6d82860e7cbdc22a
[]
no_license
markm208/CodeReview2020BlueGenerators
bc29d7b3a89a3aa6a481897d9462154562593eb4
42328808a808e9ac669116524b1f29c45f5a1a47
refs/heads/master
2021-02-04T00:22:30.995356
2020-05-07T16:58:16
2020-05-07T16:58:16
243,584,981
0
1
null
2020-04-20T22:22:11
2020-02-27T18:13:57
C++
UTF-8
C++
false
false
6,810
cpp
// // Mantissa.cpp // Mantissa // // Created by Noah Lindner on 3/5/20. // Copyright © 2020 Noah Lindner. All rights reserved. // #include <iostream> #include "mantissa.h" using namespace std; //finds the length of the array int stringLength(const char numString[]){ int i = 0; while(numString[i] != '\0'){ i++; } return i; } //checks for a negative bool negativeCheck(const char numstring[]){ for(int i = 0;i < stringLength(numstring);i++){ if(numstring[i] == '-'){ if(numstring[i + 1] == '0' || numstring[i + 1] == '.'){ return true; } } } return false; } //checks for a digit bool digitCheck(char c){ if(c >= 48 && c <= 57){ return true; } return false; } //checks for a space bool spaceCheck(char s){ if(s == 32) { return true; } else { return false; } } //checks to see if numstring contains a period, if not returns false and the number in the cstring is not valid bool floatCheck(const char numstring[]){ int iter = 0; while (numstring[iter] != '\0'){ if(numstring[iter] == '.'){ if(numstring[iter + 1] != '\0' && numstring[iter + 1] != '0'){ //makes sure there is something after the decimal return true; } } if(digitCheck(numstring[iter]) == true && spaceCheck(numstring[iter]) == true){ return true; } iter++; } return false; } //converts numerator array into a integer int solveNumerator(const char numstring[]){ int result = 0; if(numstring[0] != '-'){ for(int i = 0;numstring[i] != '\0';i++){ result = result * 10 + numstring[i] - '0'; } } else{ for(int i = 1;numstring[i] != '\0';i++){ result = result * 10 + numstring[i] - '0'; } result = result * -1; } return result; } //checks for a decimal point bool DecChecker(const char numstring[]){ int iter = 0; int endNum = stringLength(numstring) - 1; while(numstring[iter] != '\0'){ if(numstring[iter] == '.'){ if(numstring[endNum] >= 49 && numstring[endNum] <= 57){ return true; } } iter++; } return false; } //checks to make sure numstring is legal and then creates the mantissa bool mantissa(const char numstring[], int & numerator, int& denominator){ int length = 0; //holds length of whole array int decimalLocation = 0; //keeps track of decimal denominator = 10; //default value of denominator if there is one while(numstring[length] != '\0'){ //solves for length and decimal location if(numstring[length] == '.'){ decimalLocation = length; } length++; } char top[0]; //array that holds the numbers after the decimal that arent 0 int iter = 0; //incrementor in loops int preDec = decimalLocation - 1; //for checking the number before the decimal if(negativeCheck(numstring)){ //if is neagtive and if there is a 0 or - right before the decimal then numerator is - if(numstring[preDec] == '0' || numstring[preDec] == '-'){ top[0] = '-'; iter++; } } for(int i = decimalLocation;i < length;i++){ //runs through the loop and grabs the non zeros after the decimal if(floatCheck(numstring)){ if(digitCheck(numstring[i])){ if(numstring[i] == '0'){ //if there is a zero it breaks break; } top[iter] = numstring[i]; //top now contains nonzeros after the decimal iter++; } } } int iterator = 0; //another incrementor int zeroCounter = 0; //counts number of zeros after decimal int tens = 1; //will hold the amount of tens columns to add up denominator //handles if there is zeros afer the decimal but other significant numbers after the zeros if(floatCheck(numstring) == false && DecChecker(numstring) == true){ for(int i = decimalLocation; i < stringLength(numstring); i++){ if(numstring[i] >= 49 && numstring[i] <= 57){ //only adds the numbers to top if they arent 0 top[iterator] = numstring[i]; iterator++; } if(numstring[i] == '0'){ //if they are zero increment zerocounter zeroCounter++; } } zeroCounter += iterator; //zerocounter now contains the amount of tens columns after the decimal for(int i = 1;i < zeroCounter;i++){ tens *= 10; //10 to that power for solving denominator } numerator = solveNumerator(top); denominator = denominator * tens; return true; } //if negative number how to solve for denominator if(negativeCheck(numstring)){ iter--; if(numstring[preDec] >= 49 && numstring[preDec] <= 57){ iter++; } for (int i = 0;i < iter - 1; i++){ denominator = denominator * 10; } } //if it is a decimal but not negative solves for denominator if(floatCheck(numstring)){ if(negativeCheck(numstring) == false){ for (int i = 0;i < iter - 1; i++){ denominator = denominator * 10; } } } //if a decimal and contains letters than return false otherwise solves if(floatCheck(numstring)){ for(int i = 0; i < stringLength(numstring);i++){ if(numstring[i] >= 97 && numstring[i] <= 122){ return false; } } numerator = solveNumerator(top); return true; } //checks it starts with a non digit and then if the second number is one if(digitCheck(numstring[0]) == false && spaceCheck(numstring[0]) == false) { if(numstring[1] >= 48 && numstring[1] <= 57){ return true; } return false; } //checks if it starts with a space and then checks to see if it contains a digit anywhere if(spaceCheck(numstring[0])){ for(int i = 0; i < stringLength(numstring);i++){ if(digitCheck(numstring[i])){ return true; } } return false; } //if you reached here you set them as there default values for strings that should be parsed else{ numerator = 0; denominator = 10; return true; } return false; }
[ "nlindner@carthage.edu" ]
nlindner@carthage.edu
fb6767896e6d05e76382de0644fee56135ba2343
56ea53b3355be154a285884fd29e22c61e07911e
/mudisp-4-examples/gmc-cdma/src/aiallocator.h
8b3dbee90b47e092b121fb8f23d87f96697c2816
[]
no_license
rongals/MuDiSP4
ee4f80ec58580b36e8884ace40b46fe9f8c14c4b
28aeb5cde46586bb9f9edf7fd727d48125e039f2
refs/heads/master
2021-01-10T21:00:03.357395
2013-10-11T04:23:52
2013-10-11T04:23:52
3,856,214
1
1
null
null
null
null
UTF-8
C++
false
false
1,803
h
// // MuDiSP2 // Multirate Digital Signal Processor 2 // By Luca Simone Ronga (C) Apr 1999 // // #ifndef __MUDISP2_AIALLOCATOR_H #define __MUDISP2_AIALLOCATOR_H #include "mudisp.h" #include "gsl/gsl_vector.h" #include "gsl/gsl_matrix.h" #include "gsl/gsl_complex_math.h" #include "gsl/gsl_blas.h" #include "gsl/gsl_math.h" #include "gsl/gsl_rng.h" #include "gsl/gsl_sort_vector.h" // // SOAR Artificial Intelligence Support // #include "sml_Client.h" using namespace sml; //////// //////// Here put your personal includes //////// // Channel Matrix // class AIAllocator : public Block { private: //////// Parameters instances IntParam J,N,Mode; //////// Local Attributes unsigned int curruser; gsl_matrix_uint *Hperm; gsl_permutation *p; gsl_vector *huserabs; gsl_vector_uint *nextcarr; gsl_vector_uint *usedcarr; gsl_matrix *habs; // Carrier Allocation Matrices gsl_matrix_uint * signature_frequencies, * signature_frequencies_init; gsl_matrix_complex * transform_mat, * Hmat; gsl_vector_complex * Hchan; gsl_rng * ran; // SOAR related Kernel *pKernel; Agent *pAgent; public: //////// InPorts and OutPorts // // Channel coefficient // InPort < gsl_matrix_complex > min1; // // Allocation Matrix // OutPort < gsl_matrix_uint > mout1; AIAllocator():Block("AIAllocator") //////// parameters initializazion ,N("Carriers",16,"number of carriers") ,J("CodedSymbs",16,"coded symbols") ,Mode("AllocatorMode",4,"0=fca,1=bst,2=swp,3=ovl,4=SOAR") { //////// local parameter registration AddParameter(N); AddParameter(J); AddParameter(Mode); } ~AIAllocator() { } void Setup(); void Run(); void Finish(); }; #endif /* __MUDISP_MYBLOCK_H */
[ "luca.simone.ronga@gmail.com" ]
luca.simone.ronga@gmail.com
ea37c1604cb706d3920afad5bfb523701c7b5712
02099155d15b3d65330abc7276b13c8deff68e94
/A/A. Transmigration/main.cpp
dfa5a6f3128a28c690fff14994a6ca06d98126b9
[]
no_license
xUser5000/competitive-programming
d7c760fa6db58956e472dd80e24def0358bbb5a8
90337c982dd3663a69f2d19021e692f1edb1b3a5
refs/heads/master
2023-06-26T21:56:02.452867
2021-07-23T22:39:49
2021-07-23T22:39:49
288,557,139
1
0
null
null
null
null
UTF-8
C++
false
false
543
cpp
#include <iostream> #include <map> #include <math.h> using namespace std; int main() { int n, m; cin >> n >> m; double k; cin >> k; map<string, long> mp; while (n--) { string s; cin >> s; long x; cin >> x; if (floor(x * k) >= 100) { mp[s] = floor(x * k); } } while (m--) { string s; cin >> s; if (mp.find(s) == mp.end()) mp[s] = 0; } cout << mp.size() << endl; for (auto p: mp) cout << p.first << " " << p.second << endl; return 0; }
[ "abdallahar1974@gmail.com" ]
abdallahar1974@gmail.com
0ce6e0d5dde50de9377a8485195d2539342218c9
08d2e24e49b73d9c02d65465ff7a934ce2c47ab0
/src/npvr/ovr_manager.cpp
8f4775a68a75becf3892ac40fa8f330133e35204
[ "Apache-2.0" ]
permissive
nearwood/vr.js
bbdc28214174a2af1b71c49fc4f37b7362932788
d11d664849535bdd419e48c164e642197632a8f6
refs/heads/master
2021-01-15T13:01:31.113352
2014-12-02T16:47:43
2014-12-02T16:47:43
26,233,594
1
0
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
/** * Copyright 2013 Google Inc. 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. */ #include <npvr/ovr_manager.h> using namespace npvr; OVRManager *OVRManager::Instance() { static OVRManager instance; return &instance; } OVRManager::OVRManager(): hmd_device_(NULL) { ovr_Initialize(); //bool defaultOrientation = new ovrQuatf(); defaultPosition = new ovrVector3f(); int numHmds = ovrHmd_Detect(); if (numHmds > 0) { ovrHmd device = ovrHmd_Create(0); if (device != NULL) { SetDevice(device); } } } OVRManager::~OVRManager() { ovrHmd_Destroy(hmd_device_); ovr_Shutdown(); } ovrHmd OVRManager::GetDevice() const { return hmd_device_; } const ovrHmd OVRManager::GetDeviceInfo() const { return hmd_device_; } void OVRManager::SetDevice(ovrHmd device) { if (hmd_device_ == device) { return; } if (hmd_device_) { // Release existing device. ovrHmd_Destroy(hmd_device_); //delete sensor_fusion_; } if (!device) { return; } hmd_device_ = device; //returns bool ovrHmd_ConfigureTracking(hmd_device_, ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0); } bool OVRManager::DevicePresent() const { return hmd_device_ != NULL; //ovrHmd_Detect() > 0 } ovrQuatf* OVRManager::GetOrientation() const { ovrTrackingState ts = ovrHmd_GetTrackingState(hmd_device_, ovr_GetTimeInSeconds()); if (ts.StatusFlags & (ovrStatus_OrientationTracked)) { return &ts.HeadPose.ThePose.Orientation; //Posef pose = ts.HeadPose; } else { return defaultOrientation; } } void OVRManager::ResetOrientation() { ovrHmd_RecenterPose(hmd_device_); } ovrVector3f* OVRManager::GetPosition() const { ovrTrackingState ts = ovrHmd_GetTrackingState(hmd_device_, ovr_GetTimeInSeconds()); if (ts.StatusFlags & (ovrStatus_PositionTracked)) { return &ts.HeadPose.ThePose.Position; //Posef pose = ts.HeadPose; } else { return defaultPosition; //TODO Use last position } } ovrHmd OVRManager::GetConfiguration() const { ovrHmd test = hmd_device_; return test; }
[ "nearwood@gmail.com" ]
nearwood@gmail.com
543e74141e5fd00e5ee8f7816bdae2e28522c56b
be9c5b55ad37681ccf06552ef5912317728ce899
/Array/2475NumberOfUnequalTripletsInArray.cpp
a2343e40c6b3d867417ffe8dbff7b2088857f819
[]
no_license
wenzhejiao/LeetCode
e8ae29a3ef51f9b2e553e128d1d2b93d030a903f
7dda00d604d5ada512c9e5ea97af7bfb1f27494c
refs/heads/master
2023-08-26T07:38:24.724759
2023-08-25T14:00:44
2023-08-25T14:00:44
198,832,070
2
0
null
null
null
null
UTF-8
C++
false
false
535
cpp
#include<iostream> #include<vector> #include<unordered_map> using namespace std; class Solution { public: int unequalTriplets(vector<int>& nums) { int ret = 0; for (int i = 0; i < nums.size() - 2; i++) { for (int j = i + 1; j < nums.size() - 1; j++) { for (int k = j + 1; k < nums.size(); k++) { if (nums[i] != nums[j] && nums[i] != nums[k] && nums[j] != nums[k]) ret++; } } } return ret; } };
[ "wenzhejiao@gmail.com" ]
wenzhejiao@gmail.com
a6babd4b45af0aa4f3863ba2e0da90aff6579784
e2cce3f57042562535ac967f702076ff4924090f
/bamtumors.h
3e63d35b1b4aee65f429bd7f65e029d6ac8ad448
[ "MIT" ]
permissive
ZhaoDanOnGitHub/test-1
8ec2faef8242eacf9ac7f507e7219b80d3ea3677
81cffd0f43fd4fa50c1a40e05ad496785b79d242
refs/heads/master
2020-09-05T03:57:25.318352
2018-09-26T15:25:12
2018-09-26T15:25:12
219,975,815
0
0
null
null
null
null
UTF-8
C++
false
false
1,592
h
/* * bampair.h for MSIsensor * Copyright (c) 2013 Beifang Niu && Kai Ye WUGSC All Rights Reserved. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _BAMTUMORS_H_ #define _BAMTUMORS_H_ #include <map> #include <vector> #include <string> #include <iostream> #include <fstream> #include <algorithm> #include "param.h" // Bam file tumors class BamTumors { public: BamTumors(); ~BamTumors(); // total tumors unsigned int totalTumors; // bam files std::string tumor_bam; protected: //xxx }; #endif //_BAMTUMORS_H_
[ "1881098122@163.com" ]
1881098122@163.com
9e35d451e4d99b382981665a9446b2767fe00021
55b703863042f06f9187b76d4c58025148ee2469
/ABC135/prob5.cpp
5a497fc7da179cb294cc9907236d706664ba5f63
[]
no_license
hmtyj2/AtCoder
08ead4f2f54c066b2b92a71ce42c68ab4e8e7ee6
899fddee920f4d7bfaea0662269ace311d7424b6
refs/heads/master
2020-09-04T05:03:43.465348
2019-11-05T05:19:24
2019-11-05T05:19:24
219,663,628
0
0
null
null
null
null
UTF-8
C++
false
false
77
cpp
#include <stdio.h> #include <iostream> using namespace std; int main(){ }
[ "ghkdalsxkr@naver.com" ]
ghkdalsxkr@naver.com
94d968cca99354924461cc396bbfa1c4d8f96835
54df0ba9377f83b73cdceaea0e98979cb89d7419
/CubicGraphs/CubicGraphs.cpp
8720611aacf62f6e74113365ae60c30e2226d8ba
[]
no_license
jedynak/magisterka
284d9a3c5b78522f7236a69556f65d4e1bc993d5
a9ff40b6d1fa48685e9a901f4413597186e13d12
refs/heads/master
2021-01-10T18:43:36.297271
2015-04-14T20:25:04
2015-04-14T20:25:04
28,879,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,805
cpp
/* * Author: Tomasz Jedynak * * This program generates cubic graphs * */ #include "CubicGraphGenerator.h" #include "Halldorsson.h" #include <iostream> #include <time.h> #include "IsBipartite.h" #include "tools.h" using namespace std; void testQubicGraphs(){ int **graph = new int*[MAX_VERTEX_NUMBER]; for(int h=0; h<MAX_VERTEX_NUMBER; ++h){ graph[h] = new int[NUMBER_OF_NEIGHBOURS]; } int *solution; int ratio; int foundNotBipartite=0; srand(time( NULL )); solution = new int[MAX_VERTEX_NUMBER]; int independentSetSize; int isBipartite; int hasSet40,doBipartite; int graphNum=NUMBER_OF_GRAPH; for(int i=MIN_VERTEX_NUMBER;i<=MAX_VERTEX_NUMBER;i+=INCREASE_NUMBER_OF_VERTICES){ hasSet40=0; foundNotBipartite=0; doBipartite=0; for(int j=0;j<graphNum;++j){ isBipartite=1; generateCubicGraph(graph, i); Halldorsson(graph, i, solution); independentSetSize=0; for(int h=0; h<i; ++h){ if(solution[h]==1)++independentSetSize; } //deleteSet(graph,limitedGraph,i,solution); isBipartite = IsBipartite(graph,i,solution); ratio = ((float)(independentSetSize*100)/(float)i); if(ratio>=40){ ++hasSet40; } if(isBipartite==0){ ++doBipartite; } if(isBipartite==0&&ratio>=40){ //cout<<i<<" vertices ratio: "<<ratio<<"% set size:"<<independentSetSize<<"*\n"; ++foundNotBipartite; //printGraph(graph,i,solution); } else{ //cout<<i<<" vertices ratio: "<<ratio<<"% set size:"<<independentSetSize<<"\n"; } } cout<<i<<" notBiparite, ratio>=40 : "<<foundNotBipartite<<" hasSet40+: "<<hasSet40<<" not biparitize: "<<doBipartite<<endl; } //cout<<"found "<<foundNotBipartite<<" not bipartite graphs\n"; for(int h=0; h<NUMBER_OF_NEIGHBOURS; ++h){ delete [] graph[h]; } delete []solution; delete []graph; }
[ "jedynak1991@gmail.com" ]
jedynak1991@gmail.com
8b8642c7cbfd3afa4e16f0392c0a3f13a2969285
66a00fa12465e9e5e00984530baa2cf14f0a4bc9
/stack-queue/stackUsingLL.cpp
8156325318d2eec2b7e4fb9b8d4bdc2388326dcc
[]
no_license
phusdu/c-ds
98cc77230fe2f44cc6b44b2987f2636143a939d9
9badd65e1f86ca036a971294a69a2ae30ad33257
refs/heads/master
2022-04-20T22:16:16.015486
2020-04-12T13:59:47
2020-04-12T13:59:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,335
cpp
#include<iostream> using namespace std; template <typename T> class Node { public : T data; Node<T> *next; Node(T data) { this -> data = data; next = NULL; } }; template <typename T> class Stack { Node<T> *head; int size; // number of elements prsent in stack public : Stack() { this->head = NULL; this->size = 0; } int getSize() { return this->size; } bool isEmpty() { return this->size == 0; } void push(T element) { if(this->head == NULL){ this->head = new Node<T>(element); this->size++; }else{ Node<T>* newNode = new Node<T>(element); newNode->next = head; head = newNode; this->size++; } } T pop() { // Return 0 if stack is empty. Don't display any other message if(this->size == 0){ return 0; }else{ Node<T>* tmp = head; T n = tmp->data; head = head->next; delete tmp; this->size--; return n; } } T top() { // Return 0 if stack is empty. Don't display any other message if(this->size == 0){ return 0; }else{ return this->head->data; } } }; int main() { Stack<int> st; int choice; cin >> choice; int input; while (choice !=-1) { if(choice == 1) { cin >> input; st.push(input); } else if(choice == 2) { int ans = st.pop(); if(ans != 0) { cout << ans << endl; } else { cout << "-1" << endl; } } else if(choice == 3) { int ans = st.top(); if(ans != 0) { cout << ans << endl; } else { cout << "-1" << endl; } } else if(choice == 4) { cout << st.getSize() << endl; } else if(choice == 5) { if(st.isEmpty()){ cout << "true" << endl; }else{ cout << "false" << endl; } } cin >> choice; } }
[ "dubey.mehulkumar@gmail.com" ]
dubey.mehulkumar@gmail.com
d29e148cbe3620bf175e33853889e9e90b708fef
42a27c4eb1a673101a85458243f9f4e7dd5df339
/Binary Search Tree/Search-a-Node-in-a-BST.cpp
83f6b9e24afe8eaa288d7cd209cfb562856609a2
[]
no_license
arnavkundalia/Algorithms-and-Data-Structres_Extra
d5234e4e3537af2479a35b98f73d40d1a29f5668
bf85d18283798605f32b8fed040a9a0a0a96e2cf
refs/heads/master
2023-03-21T22:08:54.557840
2020-07-07T01:07:39
2020-07-07T01:07:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,297
cpp
/* Problem URL :- https://practice.geeksforgeeks.org/problems/search-a-node-in-bst/1 */ // { Driver Code Starts #include<bits/stdc++.h> using namespace std; struct Node { int data; Node* right; Node* left; Node(int x){ data = x; right = NULL; left = NULL; } }; bool search(Node* root, int x); Node *insert(Node *tree, int val) { Node *temp = NULL; if (tree == NULL) return new Node(val); if (val < tree->data) { tree->left = insert(tree->left, val); } else if (val > tree->data) { tree->right = insert(tree->right, val); } return tree; } int main() { int T; cin>>T; while(T--) { Node *root = NULL; int N; cin>>N; for(int i=0;i<N;i++) { int k; cin>>k; root = insert(root, k); } int s; cin>>s; cout<<search(root,s); cout<<endl; } } // } Driver Code Ends /* Node structure struct Node { int data; Node* right; Node* left; Node(int x){ data = x; right = NULL; left = NULL; } }; */ /*You are required to complete this method*/ bool search(Node* root, int x) { //Your code here }
[ "gjainiitr@gmail.com" ]
gjainiitr@gmail.com
d8ae1eaaba2096f85df4474e0c1d1b8b9469a0e5
0f5fa2cc81ce400f828d686ee773303b52f3988d
/unit_tests.common/grid_single_phase_pressure_solver2_tests.cpp
a17a66d88fdd61567baedc898c23959782db51c9
[ "MIT" ]
permissive
StomatoGod/fluid-engine-OpenVDB
700d4d5ecf5bdafe68013aaa32722a0f937f8083
95ccd795b44a0930b49a92ccef2c7c53400fd71b
refs/heads/master
2023-01-15T10:43:19.119914
2020-11-23T04:26:14
2020-11-23T04:26:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,439
cpp
// Copyright (c) 2018 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include "../src.common/cell_centered_scalar_grid2.h" #include "../src.common/face_centered_grid2.h" #include "../src.common/fdm_mg_solver2.h" #include "../src.common/grid_single_phase_pressure_solver2.h" #include "../external/gtest/include/gtest/gtest.h" using namespace vox; TEST(GridSinglePhasePressureSolver2, SolveSinglePhase) { FaceCenteredGrid2 vel(3, 3); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (j == 0 || j == 3) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } GridSinglePhasePressureSolver2 solver; solver.solve(vel, 1.0, &vel, ConstantScalarField2(kMaxD), ConstantVectorField2({0, 0}), ConstantScalarField2(-kMaxD), false); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 1e-6); } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(0.0, vel.v(i, j), 1e-6); } } const auto& pressure = solver.pressure(); for (size_t j = 0; j < 2; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(pressure(i, j + 1) - pressure(i, j), -1.0, 1e-6); } } } TEST(GridSinglePhasePressureSolver2, SolveSinglePhaseCompressed) { FaceCenteredGrid2 vel(3, 3); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (j == 0 || j == 3) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } GridSinglePhasePressureSolver2 solver; solver.solve(vel, 1.0, &vel, ConstantScalarField2(kMaxD), ConstantVectorField2({0, 0}), ConstantScalarField2(-kMaxD), true); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 1e-6); } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(0.0, vel.v(i, j), 1e-6); } } const auto& pressure = solver.pressure(); for (size_t j = 0; j < 2; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(pressure(i, j + 1) - pressure(i, j), -1.0, 1e-6); } } } TEST(GridSinglePhasePressureSolver2, SolveSinglePhaseWithBoundary) { FaceCenteredGrid2 vel(3, 3); CellCenteredScalarGrid2 boundarySdf(3, 3); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (j == 0 || j == 3) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } // Wall on the right-most column boundarySdf.fill([&](const Vector2D& x) { return -x.x + 2.0; }); GridSinglePhasePressureSolver2 solver; solver.solve(vel, 1.0, &vel, boundarySdf); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 1e-6); } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (i == 2 && (j == 1 || j == 2)) { EXPECT_NEAR(1.0, vel.v(i, j), 1e-6); } else { EXPECT_NEAR(0.0, vel.v(i, j), 1e-6); } } } const auto& pressure = solver.pressure(); for (size_t j = 0; j < 2; ++j) { for (size_t i = 0; i < 2; ++i) { EXPECT_NEAR(pressure(i, j + 1) - pressure(i, j), -1.0, 1e-6); } } } TEST(GridSinglePhasePressureSolver2, SolveFreeSurface) { FaceCenteredGrid2 vel(3, 3); CellCenteredScalarGrid2 fluidSdf(3, 3); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (j == 0 || j == 3) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } fluidSdf.fill([&](const Vector2D& x) { return x.y - 2.0; }); GridSinglePhasePressureSolver2 solver; solver.solve(vel, 1.0, &vel, ConstantScalarField2(kMaxD), ConstantVectorField2({0, 0}), fluidSdf); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 1e-6); } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(0.0, vel.v(i, j), 1e-6); } } const auto& pressure = solver.pressure(); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 3; ++i) { double p = static_cast<double>(2 - j); EXPECT_NEAR(p, pressure(i, j), 1e-6); } } } TEST(GridSinglePhasePressureSolver2, SolveFreeSurfaceCompressed) { FaceCenteredGrid2 vel(3, 3); CellCenteredScalarGrid2 fluidSdf(3, 3); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (j == 0 || j == 3) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } fluidSdf.fill([&](const Vector2D& x) { return x.y - 2.0; }); GridSinglePhasePressureSolver2 solver; solver.solve(vel, 1.0, &vel, ConstantScalarField2(kMaxD), ConstantVectorField2({0, 0}), fluidSdf, true); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 1e-6); } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { EXPECT_NEAR(0.0, vel.v(i, j), 1e-6); } } const auto& pressure = solver.pressure(); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 3; ++i) { double p = static_cast<double>(2 - j); EXPECT_NEAR(p, pressure(i, j), 1e-6); } } } TEST(GridSinglePhasePressureSolver2, SolveFreeSurfaceWithBoundary) { FaceCenteredGrid2 vel(3, 3); CellCenteredScalarGrid2 fluidSdf(3, 3); CellCenteredScalarGrid2 boundarySdf(3, 3); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (j == 0 || j == 3) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } // Wall on the right-most column boundarySdf.fill([&](const Vector2D& x) { return -x.x + 2.0; }); fluidSdf.fill([&](const Vector2D& x) { return x.y - 2.0; }); GridSinglePhasePressureSolver2 solver; solver.solve(vel, 1.0, &vel, boundarySdf, ConstantVectorField2({0, 0}), fluidSdf); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 4; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 1e-6); } } for (size_t j = 0; j < 4; ++j) { for (size_t i = 0; i < 3; ++i) { if (i == 2 && (j == 1 || j == 2)) { EXPECT_NEAR(1.0, vel.v(i, j), 1e-6); } else { EXPECT_NEAR(0.0, vel.v(i, j), 1e-6); } } } const auto& pressure = solver.pressure(); for (size_t j = 0; j < 3; ++j) { for (size_t i = 0; i < 2; ++i) { double p = static_cast<double>(2 - j); EXPECT_NEAR(p, pressure(i, j), 1e-6); } } } TEST(GridSinglePhasePressureSolver2, SolveSinglePhaseWithMg) { size_t n = 64; FaceCenteredGrid2 vel(n, n); for (size_t j = 0; j < n; ++j) { for (size_t i = 0; i < n + 1; ++i) { vel.u(i, j) = 0.0; } } for (size_t j = 0; j < n + 1; ++j) { for (size_t i = 0; i < n; ++i) { if (j == 0 || j == n) { vel.v(i, j) = 0.0; } else { vel.v(i, j) = 1.0; } } } GridSinglePhasePressureSolver2 solver; solver.setLinearSystemSolver( std::make_shared<FdmMgSolver2>(5, 10, 10, 40, 10)); solver.solve(vel, 1.0, &vel); for (size_t j = 0; j < n; ++j) { for (size_t i = 0; i < n + 1; ++i) { EXPECT_NEAR(0.0, vel.u(i, j), 0.01); } } for (size_t j = 0; j < n + 1; ++j) { for (size_t i = 0; i < n; ++i) { EXPECT_NEAR(0.0, vel.v(i, j), 0.05); } } }
[ "yangfengzzz@hotmail.com" ]
yangfengzzz@hotmail.com
4953ac7c3741db828e965c80d63fae18d498dc8b
415e315dae2850532d777aec335dc1fbd7566729
/llvm/lib/CodeGen/WasmEHPrepare.cpp
89d7013f488e51108d8f6c7cfa8f00ccd32ca493
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
WYK15/swift-Ollvm12
e5409339b290e0e7f38c9516999b3a684839782e
c1cdde6cc2e99222883c16db63dd6a3ff9592bb4
refs/heads/main
2023-03-31T17:22:21.257139
2021-04-07T02:45:43
2021-04-07T02:45:43
355,389,882
2
0
null
null
null
null
UTF-8
C++
false
false
17,815
cpp
//===-- WasmEHPrepare - Prepare excepton handling for WebAssembly --------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This transformation is designed for use by code generators which use // WebAssembly exception handling scheme. This currently supports C++ // exceptions. // // WebAssembly exception handling uses Windows exception IR for the middle level // representation. This pass does the following transformation for every // catchpad block: // (In C-style pseudocode) // // - Before: // catchpad ... // exn = wasm.get.exception(); // selector = wasm.get.selector(); // ... // // - After: // catchpad ... // exn = wasm.extract.exception(); // // Only add below in case it's not a single catch (...) // wasm.landingpad.index(index); // __wasm_lpad_context.lpad_index = index; // __wasm_lpad_context.lsda = wasm.lsda(); // _Unwind_CallPersonality(exn); // selector = __wasm.landingpad_context.selector; // ... // // // * Background: Direct personality function call // In WebAssembly EH, the VM is responsible for unwinding the stack once an // exception is thrown. After the stack is unwound, the control flow is // transfered to WebAssembly 'catch' instruction. // // Unwinding the stack is not done by libunwind but the VM, so the personality // function in libcxxabi cannot be called from libunwind during the unwinding // process. So after a catch instruction, we insert a call to a wrapper function // in libunwind that in turn calls the real personality function. // // In Itanium EH, if the personality function decides there is no matching catch // clause in a call frame and no cleanup action to perform, the unwinder doesn't // stop there and continues unwinding. But in Wasm EH, the unwinder stops at // every call frame with a catch intruction, after which the personality // function is called from the compiler-generated user code here. // // In libunwind, we have this struct that serves as a communincation channel // between the compiler-generated user code and the personality function in // libcxxabi. // // struct _Unwind_LandingPadContext { // uintptr_t lpad_index; // uintptr_t lsda; // uintptr_t selector; // }; // struct _Unwind_LandingPadContext __wasm_lpad_context = ...; // // And this wrapper in libunwind calls the personality function. // // _Unwind_Reason_Code _Unwind_CallPersonality(void *exception_ptr) { // struct _Unwind_Exception *exception_obj = // (struct _Unwind_Exception *)exception_ptr; // _Unwind_Reason_Code ret = __gxx_personality_v0( // 1, _UA_CLEANUP_PHASE, exception_obj->exception_class, exception_obj, // (struct _Unwind_Context *)__wasm_lpad_context); // return ret; // } // // We pass a landing pad index, and the address of LSDA for the current function // to the wrapper function _Unwind_CallPersonality in libunwind, and we retrieve // the selector after it returns. // //===----------------------------------------------------------------------===// #include "llvm/ADT/BreadthFirstIterator.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/Triple.h" #include "llvm/Analysis/DomTreeUpdater.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/TargetLowering.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/CodeGen/WasmEHFuncInfo.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/IntrinsicsWebAssembly.h" #include "llvm/InitializePasses.h" #include "llvm/Pass.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" using namespace llvm; #define DEBUG_TYPE "wasmehprepare" namespace { class WasmEHPrepare : public FunctionPass { Type *LPadContextTy = nullptr; // type of 'struct _Unwind_LandingPadContext' GlobalVariable *LPadContextGV = nullptr; // __wasm_lpad_context // Field addresses of struct _Unwind_LandingPadContext Value *LPadIndexField = nullptr; // lpad_index field Value *LSDAField = nullptr; // lsda field Value *SelectorField = nullptr; // selector Function *ThrowF = nullptr; // wasm.throw() intrinsic Function *LPadIndexF = nullptr; // wasm.landingpad.index() intrinsic Function *LSDAF = nullptr; // wasm.lsda() intrinsic Function *GetExnF = nullptr; // wasm.get.exception() intrinsic Function *ExtractExnF = nullptr; // wasm.extract.exception() intrinsic Function *GetSelectorF = nullptr; // wasm.get.ehselector() intrinsic FunctionCallee CallPersonalityF = nullptr; // _Unwind_CallPersonality() wrapper bool prepareEHPads(Function &F); bool prepareThrows(Function &F); bool IsEHPadFunctionsSetUp = false; void setupEHPadFunctions(Function &F); void prepareEHPad(BasicBlock *BB, bool NeedPersonality, bool NeedLSDA = false, unsigned Index = 0); public: static char ID; // Pass identification, replacement for typeid WasmEHPrepare() : FunctionPass(ID) {} void getAnalysisUsage(AnalysisUsage &AU) const override; bool doInitialization(Module &M) override; bool runOnFunction(Function &F) override; StringRef getPassName() const override { return "WebAssembly Exception handling preparation"; } }; } // end anonymous namespace char WasmEHPrepare::ID = 0; INITIALIZE_PASS_BEGIN(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions", false, false) INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) INITIALIZE_PASS_END(WasmEHPrepare, DEBUG_TYPE, "Prepare WebAssembly exceptions", false, false) FunctionPass *llvm::createWasmEHPass() { return new WasmEHPrepare(); } void WasmEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<DominatorTreeWrapperPass>(); } bool WasmEHPrepare::doInitialization(Module &M) { IRBuilder<> IRB(M.getContext()); LPadContextTy = StructType::get(IRB.getInt32Ty(), // lpad_index IRB.getInt8PtrTy(), // lsda IRB.getInt32Ty() // selector ); return false; } // Erase the specified BBs if the BB does not have any remaining predecessors, // and also all its dead children. template <typename Container> static void eraseDeadBBsAndChildren(const Container &BBs, DomTreeUpdater *DTU) { SmallVector<BasicBlock *, 8> WL(BBs.begin(), BBs.end()); while (!WL.empty()) { auto *BB = WL.pop_back_val(); if (!pred_empty(BB)) continue; WL.append(succ_begin(BB), succ_end(BB)); DeleteDeadBlock(BB, DTU); } } bool WasmEHPrepare::runOnFunction(Function &F) { IsEHPadFunctionsSetUp = false; bool Changed = false; Changed |= prepareThrows(F); Changed |= prepareEHPads(F); return Changed; } bool WasmEHPrepare::prepareThrows(Function &F) { auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); DomTreeUpdater DTU(&DT, /*PostDominatorTree*/ nullptr, DomTreeUpdater::UpdateStrategy::Eager); Module &M = *F.getParent(); IRBuilder<> IRB(F.getContext()); bool Changed = false; // wasm.throw() intinsic, which will be lowered to wasm 'throw' instruction. ThrowF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_throw); // Insert an unreachable instruction after a call to @llvm.wasm.throw and // delete all following instructions within the BB, and delete all the dead // children of the BB as well. for (User *U : ThrowF->users()) { // A call to @llvm.wasm.throw() is only generated from __cxa_throw() // builtin call within libcxxabi, and cannot be an InvokeInst. auto *ThrowI = cast<CallInst>(U); if (ThrowI->getFunction() != &F) continue; Changed = true; auto *BB = ThrowI->getParent(); SmallVector<BasicBlock *, 4> Succs(successors(BB)); auto &InstList = BB->getInstList(); InstList.erase(std::next(BasicBlock::iterator(ThrowI)), InstList.end()); IRB.SetInsertPoint(BB); IRB.CreateUnreachable(); eraseDeadBBsAndChildren(Succs, &DTU); } return Changed; } bool WasmEHPrepare::prepareEHPads(Function &F) { auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); bool Changed = false; // There are two things to decide: whether we need a personality function call // and whether we need a `wasm.lsda()` call and its store. // // For the personality function call, catchpads with `catch (...)` and // cleanuppads don't need it, because exceptions are always caught. Others all // need it. // // For `wasm.lsda()` and its store, in order to minimize the number of them, // we need a way to figure out whether we have encountered `wasm.lsda()` call // in any of EH pads that dominates the current EH pad. To figure that out, we // now visit EH pads in BFS order in the dominator tree so that we visit // parent BBs first before visiting its child BBs in the domtree. // // We keep a set named `ExecutedLSDA`, which basically means "Do we have // `wasm.lsda() either in the current EH pad or any of its parent EH pads in // the dominator tree?". This is to prevent scanning the domtree up to the // root every time we examine an EH pad, in the worst case: each EH pad only // needs to check its immediate parent EH pad. // // - If any of its parent EH pads in the domtree has `wasm.lsda`, this means // we don't need `wasm.lsda()` in the current EH pad. We also insert the // current EH pad in `ExecutedLSDA` set. // - If none of its parent EH pad has `wasm.lsda()`, // - If the current EH pad is a `catch (...)` or a cleanuppad, done. // - If the current EH pad is neither a `catch (...)` nor a cleanuppad, // add `wasm.lsda()` and the store in the current EH pad, and add the // current EH pad to `ExecutedLSDA` set. // // TODO Can we not store LSDA address in user function but make libcxxabi // compute it? DenseSet<Value *> ExecutedLSDA; unsigned Index = 0; for (auto DomNode : breadth_first(&DT)) { auto *BB = DomNode->getBlock(); auto *Pad = BB->getFirstNonPHI(); if (!Pad || (!isa<CatchPadInst>(Pad) && !isa<CleanupPadInst>(Pad))) continue; Changed = true; Value *ParentPad = nullptr; if (CatchPadInst *CPI = dyn_cast<CatchPadInst>(Pad)) { ParentPad = CPI->getCatchSwitch()->getParentPad(); if (ExecutedLSDA.count(ParentPad)) { ExecutedLSDA.insert(CPI); // We insert its associated catchswitch too, because // FuncletPadInst::getParentPad() returns a CatchSwitchInst if the child // FuncletPadInst is a CleanupPadInst. ExecutedLSDA.insert(CPI->getCatchSwitch()); } } else { // CleanupPadInst ParentPad = cast<CleanupPadInst>(Pad)->getParentPad(); if (ExecutedLSDA.count(ParentPad)) ExecutedLSDA.insert(Pad); } if (CatchPadInst *CPI = dyn_cast<CatchPadInst>(Pad)) { if (CPI->getNumArgOperands() == 1 && cast<Constant>(CPI->getArgOperand(0))->isNullValue()) // In case of a single catch (...), we need neither personality call nor // wasm.lsda() call prepareEHPad(BB, false); else { if (ExecutedLSDA.count(CPI)) // catch (type), but one of parents already has wasm.lsda() call prepareEHPad(BB, true, false, Index++); else { // catch (type), and none of parents has wasm.lsda() call. We have to // add the call in this EH pad, and record this EH pad in // ExecutedLSDA. ExecutedLSDA.insert(CPI); ExecutedLSDA.insert(CPI->getCatchSwitch()); prepareEHPad(BB, true, true, Index++); } } } else if (isa<CleanupPadInst>(Pad)) { // Cleanup pads need neither personality call nor wasm.lsda() call prepareEHPad(BB, false); } } return Changed; } void WasmEHPrepare::setupEHPadFunctions(Function &F) { Module &M = *F.getParent(); IRBuilder<> IRB(F.getContext()); assert(F.hasPersonalityFn() && "Personality function not found"); // __wasm_lpad_context global variable LPadContextGV = cast<GlobalVariable>( M.getOrInsertGlobal("__wasm_lpad_context", LPadContextTy)); LPadIndexField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 0, "lpad_index_gep"); LSDAField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 1, "lsda_gep"); SelectorField = IRB.CreateConstGEP2_32(LPadContextTy, LPadContextGV, 0, 2, "selector_gep"); // wasm.landingpad.index() intrinsic, which is to specify landingpad index LPadIndexF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_landingpad_index); // wasm.lsda() intrinsic. Returns the address of LSDA table for the current // function. LSDAF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_lsda); // wasm.get.exception() and wasm.get.ehselector() intrinsics. Calls to these // are generated in clang. GetExnF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_exception); GetSelectorF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_get_ehselector); // wasm.extract.exception() is the same as wasm.get.exception() but it does // not take a token argument. This will be lowered down to EXTRACT_EXCEPTION // pseudo instruction in instruction selection, which will be expanded using // 'br_on_exn' instruction later. ExtractExnF = Intrinsic::getDeclaration(&M, Intrinsic::wasm_extract_exception); // _Unwind_CallPersonality() wrapper function, which calls the personality CallPersonalityF = M.getOrInsertFunction( "_Unwind_CallPersonality", IRB.getInt32Ty(), IRB.getInt8PtrTy()); if (Function *F = dyn_cast<Function>(CallPersonalityF.getCallee())) F->setDoesNotThrow(); } // Prepare an EH pad for Wasm EH handling. If NeedPersonality is false, Index is // ignored. void WasmEHPrepare::prepareEHPad(BasicBlock *BB, bool NeedPersonality, bool NeedLSDA, unsigned Index) { if (!IsEHPadFunctionsSetUp) { IsEHPadFunctionsSetUp = true; setupEHPadFunctions(*BB->getParent()); } assert(BB->isEHPad() && "BB is not an EHPad!"); IRBuilder<> IRB(BB->getContext()); IRB.SetInsertPoint(&*BB->getFirstInsertionPt()); auto *FPI = cast<FuncletPadInst>(BB->getFirstNonPHI()); Instruction *GetExnCI = nullptr, *GetSelectorCI = nullptr; for (auto &U : FPI->uses()) { if (auto *CI = dyn_cast<CallInst>(U.getUser())) { if (CI->getCalledOperand() == GetExnF) GetExnCI = CI; if (CI->getCalledOperand() == GetSelectorF) GetSelectorCI = CI; } } // Cleanup pads w/o __clang_call_terminate call do not have any of // wasm.get.exception() or wasm.get.ehselector() calls. We need to do nothing. if (!GetExnCI) { assert(!GetSelectorCI && "wasm.get.ehselector() cannot exist w/o wasm.get.exception()"); return; } Instruction *ExtractExnCI = IRB.CreateCall(ExtractExnF, {}, "exn"); GetExnCI->replaceAllUsesWith(ExtractExnCI); GetExnCI->eraseFromParent(); // In case it is a catchpad with single catch (...) or a cleanuppad, we don't // need to call personality function because we don't need a selector. if (!NeedPersonality) { if (GetSelectorCI) { assert(GetSelectorCI->use_empty() && "wasm.get.ehselector() still has uses!"); GetSelectorCI->eraseFromParent(); } return; } IRB.SetInsertPoint(ExtractExnCI->getNextNode()); // This is to create a map of <landingpad EH label, landingpad index> in // SelectionDAGISel, which is to be used in EHStreamer to emit LSDA tables. // Pseudocode: wasm.landingpad.index(Index); IRB.CreateCall(LPadIndexF, {FPI, IRB.getInt32(Index)}); // Pseudocode: __wasm_lpad_context.lpad_index = index; IRB.CreateStore(IRB.getInt32(Index), LPadIndexField); auto *CPI = cast<CatchPadInst>(FPI); if (NeedLSDA) // Pseudocode: __wasm_lpad_context.lsda = wasm.lsda(); IRB.CreateStore(IRB.CreateCall(LSDAF), LSDAField); // Pseudocode: _Unwind_CallPersonality(exn); CallInst *PersCI = IRB.CreateCall(CallPersonalityF, ExtractExnCI, OperandBundleDef("funclet", CPI)); PersCI->setDoesNotThrow(); // Pseudocode: int selector = __wasm.landingpad_context.selector; Instruction *Selector = IRB.CreateLoad(IRB.getInt32Ty(), SelectorField, "selector"); // Replace the return value from wasm.get.ehselector() with the selector value // loaded from __wasm_lpad_context.selector. assert(GetSelectorCI && "wasm.get.ehselector() call does not exist"); GetSelectorCI->replaceAllUsesWith(Selector); GetSelectorCI->eraseFromParent(); } void llvm::calculateWasmEHInfo(const Function *F, WasmEHFuncInfo &EHInfo) { // If an exception is not caught by a catchpad (i.e., it is a foreign // exception), it will unwind to its parent catchswitch's unwind destination. // We don't record an unwind destination for cleanuppads because every // exception should be caught by it. for (const auto &BB : *F) { if (!BB.isEHPad()) continue; const Instruction *Pad = BB.getFirstNonPHI(); if (const auto *CatchPad = dyn_cast<CatchPadInst>(Pad)) { const auto *UnwindBB = CatchPad->getCatchSwitch()->getUnwindDest(); if (!UnwindBB) continue; const Instruction *UnwindPad = UnwindBB->getFirstNonPHI(); if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(UnwindPad)) // Currently there should be only one handler per a catchswitch. EHInfo.setEHPadUnwindDest(&BB, *CatchSwitch->handlers().begin()); else // cleanuppad EHInfo.setEHPadUnwindDest(&BB, UnwindBB); } } }
[ "wangyankun@ishumei.com" ]
wangyankun@ishumei.com
2d42f4977e29d25469fe1d38b0dbba5f9c432431
18ba917b4f59a543c7aaa952a91547600e0dd5d9
/textdisplay.h
079eabfad925f03ab7319ffd1a08e3fadf30ab3c
[]
no_license
phoebelll/ChamberCrawler3000
c1aba6acab406f71ad2b1bcd76f86cee9a2cbfc4
adc0e1f1a4374069c9e91219dc3ddd60c4ee9604
refs/heads/master
2020-06-17T09:20:41.523753
2019-07-08T20:07:18
2019-07-08T20:07:18
195,878,706
0
0
null
null
null
null
UTF-8
C++
false
false
596
h
#ifndef __TEXTDISPLAY_H__ #define __TEXTDISPLAY_H__ #include <iostream> #include <vector> #include <string> #include "observer.h" class TextDisplay: public Observer { const int rows, cols; std::vector<std::vector<char>> boardDisplay; std::string raceAndGold, hp, atk, def, act; public: TextDisplay(int rows = 25, int cols = 79); void notify(int row, int col, char symbol) override; void notify(std::shared_ptr<Hero> h, int floor) override; void notify(std::string action) override; ~TextDisplay(); friend std::ostream &operator<<(std::ostream &out, const TextDisplay &td); }; #endif
[ "noreply@github.com" ]
noreply@github.com
b09e41429d2725542e84abf883e10cfd5d915d72
1154814c89c84b7e23ec1feed96be67491a5b7eb
/src/listviews.cpp
b0dc9f7853e70c6a611c19d3db2f7de0971a9b1b
[]
no_license
linlut/View3dn
cc8e741a9a6967277a65a01793ddc61f7ac5ead9
4ba9a3b5414d95ac358d0e05f2834ebb451efedd
refs/heads/master
2020-03-26T23:43:41.132808
2014-02-21T01:28:11
2014-02-21T01:28:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,565
cpp
#include <assert.h> #include "listviews.h" #include <qinputdialog.h> #include <qlabel.h> #include <qpainter.h> #include <qpalette.h> #include <qobjectlist.h> #include <qpopupmenu.h> #include <qheader.h> #include <qregexp.h> const int _BUFFLENGTH = 3; static char *nodalSettingStr[_BUFFLENGTH]={ "Velocity", "Displacement", "Shell Thickness" }; static char *typeStr[_BUFFLENGTH]={ "VEC3 ", "VEC3", "VEC3" }; QListViewItem* CFemAttribListView::_setAttribData(const CFemObjAttrib *pAttrib, const char*name) { int i = 0; static char *typestr=" "; //Option for analysis package m_table[i++]=CNameTableItem("Object Load", 'V', &pAttrib->m_vLoad); m_table[i++]=CNameTableItem("Velocity", 'V', &pAttrib->m_vVelocity); m_table[i++]=CNameTableItem("Displacement", 'V', &pAttrib->m_vDisplacement); m_table[i++]=CNameTableItem("Layer Count", 'i', &pAttrib->m_nLayer); m_table[i++]=CNameTableItem("Shell Thickness", 'd', &pAttrib->m_lfShellThickness); m_nTableLen = i; QListViewItem * globalSetting = new QListViewItem ( this, name ); for (i=0; i<m_nTableLen; i++){ CNameTableItem *ptab = &m_table[i]; char *sname, *stype, *sval, *soption, *scomm; ptab->toString(sname, stype, sval, soption, scomm); QListViewItem *f = new QListViewItem(globalSetting, sname, stype, sval); } return globalSetting; } void CFemAttribListView::setAttribData(CSceneNode *pnode) { if (m_pActiveSceneNode == pnode) return; this->clear(); m_pActiveSceneNode = pnode; m_pPickAttribItem = NULL; if (pnode==NULL) return; m_pPickAttribItem=_setAttribData(&pnode->m_FemAttrib, "Nodal settings"); } static inline void TXT2VEC(const char * s, Vector3d & v) { double x, y, z; sscanf(s, "%lf,%lf,%lf", &x, &y, &z); v.x = x, v.y=y, v.z=z; } void CFemAttribListView::_restoreFromItem(const QListViewItem *pItem, CFemObjAttrib *pAttrib) { ASSERT(0); /* int i; assert(pItem!=NULL); assert(pAttrib!=NULL); QListViewItem* p[100]; int nchild = pItem->childCount(); p[0]=pItem->firstChild(); for (i=1; i<nchild; i++) p[i]=p[i-1]->nextSibling(); for (i=0; i<nchild; i++){ QString name=p[i]->text(0); QString value=p[i]->text(2); const char *sname = name.ascii(); const char *tname = value.ascii(); if (strcmp(sname, nodalSettingStr[0])==0) TXT2VEC(tname, pAttrib->m_vVelocity); else if (strcmp(sname, nodalSettingStr[1])==0) TXT2VEC(tname, pAttrib->m_vDisplacement); else if (strcmp(sname, nodalSettingStr[2])==0) TXT2VEC(tname, pAttrib->m_vLoad); else assert(0); } */ } CFemAttribListView::CFemAttribListView(CSceneNode * pActiveNode, QWidget *parent, const char *name): QListView(parent, name) { m_pAttribItem = NULL; m_pPickAttribItem = NULL; header()->setClickEnabled( TRUE ); addColumn( "Attributes " ); addColumn( " Type " ); addColumn( " Values " ); setRootIsDecorated( TRUE ); setSorting(-1); m_pActiveSceneNode = pActiveNode; setAttribData(pActiveNode); connect(this, SIGNAL( doubleClicked(QListViewItem *, const QPoint &, int)), this, SLOT(slotDoubleClicked(QListViewItem *, const QPoint &, int))); resize(200, 100); } void CFemAttribListView::initFolders() { ASSERT0(0); /* unsigned int mcount = 1; char *nodalSettingStr[3]={ "Load", "Velocity", "Displacement" }; Folder * globalSetting = new Folder( 0, "Global settings"); Folder * nodalSetting = new Folder( 0, "Nodal settings"); for (i=0; i<3; i++){ Folder *f2 = new Folder(globalSetting, nodalSettingStr[i]); } for (i=0; i<3; i++){ Folder *f2 = new Folder(nodalSetting, nodalSettingStr[i]); } lstFolders.append( globalSetting ); lstFolders.append( nodalSetting ); */ } void CFemAttribListView::setupFolders() { } void CFemAttribListView::slotDoubleClicked ( QListViewItem *pListViewItem, const QPoint & pt, int x) { bool ok; if (pListViewItem==NULL) return; QString existingStr = pListViewItem->text(2); if (existingStr.isEmpty()) return; QString text = QInputDialog::getText( "Input/change value", "Change the value:", QLineEdit::Normal, existingStr, &ok, this ); if ( ok && !text.isEmpty() ) { pListViewItem->setText(2, text); QString attribname = pListViewItem->text(0); if (m_pActiveSceneNode){ for (int i=0; i<m_nTableLen; i++){ CNameTableItem *ptab = &m_table[i]; if (strcmp(attribname, ptab->m_sName)==0){ ptab->setValue(text); break; } } } } }
[ "nanzhang790@gmail.com" ]
nanzhang790@gmail.com
204a5a0084b2dcf41f11a5415c880d33c6d0dc37
9cfe50c529f3b7d42d5a9c6723d8bf8615cbc854
/while.cpp
07faca574947598cfc2b86b152b764195220346d
[]
no_license
stormvolt/Ejercicios
7d8d02764194dea331edecefcd021b567bf71369
db3814ecfb8fbc6a98dfa2a6ef71052bca1545db
refs/heads/master
2021-01-01T06:34:07.788602
2015-12-03T01:22:30
2015-12-03T01:22:30
41,460,228
0
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
#include <iostream> int total, contador, num; double promedio; int main() { total = 0; contador = 1; while (contador <= 5 ) { std::cout<<"Ingrese un numero: "<< std::endl; std::cin >> num; total = total + num; contador ++; } promedio = total / 5.0; std::cout<<"El promedio es "<< promedio<< std::endl; return 0; }
[ "luisnu97@hotmail.com" ]
luisnu97@hotmail.com
fbc0ea3a299a3a319604002638bcf27c08296db1
31020160411e01e93ed79e1253fbf9b1fa694f34
/7_Reverse_Integer.cpp
0f76d51254c8031a2e3fb4ec258e80a4332852da
[ "BSD-3-Clause" ]
permissive
bozhiyou/LeetCode
b0a458c8c27cb66ec7ecfa57380f54336a0eeb0e
2632e65850dcc8604fd96acb5a89712ecea5ec65
refs/heads/master
2020-12-03T06:59:03.291297
2020-02-01T04:45:41
2020-02-01T04:45:41
231,234,836
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
/** * Given a 32-bit signed integer, reverse digits of an integer. */ class Solution { public: int reverse(int x) { try { if (-10 < x && x < 10) return x; std::string s = std::to_string(x); std::reverse(s.begin()+(x<0), s.end()); return std::stoi(s) | (x & 0x80000000); } catch (std::exception) { return 0; } } }; int stringToInteger(string input) { return stoi(input); } int main() { string line; while (getline(cin, line)) { int x = stringToInteger(line); int ret = Solution().reverse(x); string out = to_string(ret); cout << out << endl; } return 0; }
[ "youbozhi1996@gmail.com" ]
youbozhi1996@gmail.com
806f32d9c96c977b05a6070ef0d86e621a98ff0b
7d33f48bfd809f9f54e420ab5c8f45e3eea4e4de
/src/InitializeArea.cpp
8d1ffc8e87059cac0a16ab4ade779677f8baea22
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
zzymwj/itm-1
185f4a94784fcd981912807ef2bcd25eb13d886b
a3020f15508a9218ad4bedb477f10d5543101d2e
refs/heads/master
2023-07-15T21:35:04.830031
2021-09-03T12:49:51
2021-09-03T12:49:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,216
cpp
#include "..\include\itm.h" #include "..\include\Enums.h" /*============================================================================= | | Description: Initialize area mode calculations | | Input: site_criteria[2] - Siting criteria of the terminals | + 0 : SITING_CRITERIA__RANDOM | + 1 : SITING_CRITERIA__CAREFUL | + 2 : SITING_CRITERIA__VERY_CAREFUL | gamma_e - Curvature of the effective earth | delta_h__meter - Terrain irregularity parameter, in meters | h__meter[2] - Terminal structural heights, in meters | | Outputs: h_e__meter[2] - Effective terminal heights, in meters | d_hzn__meter[2] - Terminal horizon distances, in meters | theta_hzn[2] - Terminal horizon angle | | Returns: [None] | *===========================================================================*/ void InitializeArea(int site_criteria[2], double gamma_e, double delta_h__meter, double h__meter[2], double h_e__meter[2], double d_hzn__meter[2], double theta_hzn[2]) { for (int i = 0; i < 2; i++) { if (site_criteria[i] == SITING_CRITERIA__RANDOM) h_e__meter[i] = h__meter[i]; else { double B; if (site_criteria[i] == SITING_CRITERIA__CAREFUL) B = 4.0; else // SITING_CRITERIA__VERY_CAREFUL B = 9.0; if (h__meter[i] < 5.0) B = B * sin(0.1 * PI * h__meter[i]); // [Algorithm, Eqn 3.2] h_e__meter[i] = h__meter[i] + (1.0 + B) * exp(-MIN(20.0, 2.0 * h__meter[i] / MAX(1e-3, delta_h__meter))); } double d_Ls__meter = sqrt(2.0 * h_e__meter[i] / gamma_e); // [Algorithm, Eqn 3.3] double H_3__meter = 5; d_hzn__meter[i] = d_Ls__meter * exp(-0.07 * sqrt(delta_h__meter / MAX(h_e__meter[i], H_3__meter))); // [Algorithm, Eqn 3.4] theta_hzn[i] = (0.65 * delta_h__meter * (d_Ls__meter / d_hzn__meter[i] - 1.0) - 2.0 * h_e__meter[i]) / d_Ls__meter; } }
[ "wkozma@ntia.doc.gov" ]
wkozma@ntia.doc.gov
22c6a95eacb19131cb0e125767fb20ed83f0cce2
635e5db668285d4c168481965f523a944edfba7b
/src/Magnum/Platform/AndroidApplication.h
a31ca868856c6cd0602f2f79d2bf102beb30d8ea
[ "MIT" ]
permissive
erikwijmans/magnum
dad30f604fb6d8101910e80f95f3d994fbfc4a61
9c35b115219750e2ecf04b9fc50e8a3eba109341
refs/heads/master
2021-06-22T05:02:52.472991
2019-01-24T11:26:09
2019-01-24T11:26:40
167,704,259
0
0
null
null
null
null
UTF-8
C++
false
false
30,216
h
#ifndef Magnum_Platform_AndroidApplication_h #define Magnum_Platform_AndroidApplication_h /* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if defined(CORRADE_TARGET_ANDROID) || defined(DOXYGEN_GENERATING_OUTPUT) /** @file * @brief Class @ref Magnum::Platform::AndroidApplication, macro @ref MAGNUM_ANDROIDAPPLICATION_MAIN() */ #endif #include <memory> #include <EGL/egl.h> #include "Magnum/Magnum.h" #include "Magnum/Tags.h" #include "Magnum/GL/GL.h" #include "Magnum/Math/Vector4.h" #include "Magnum/Platform/Platform.h" #if defined(CORRADE_TARGET_ANDROID) || defined(DOXYGEN_GENERATING_OUTPUT) #include <android/input.h> /* Undef Xlib nonsense which might get pulled in by EGL */ #undef None struct android_app; struct ANativeActivity; namespace Magnum { namespace Platform { /** @nosubgrouping @brief Android application Application running on Android. This application library is available only on @ref CORRADE_TARGET_ANDROID "Android", see respective sections in the @ref building-corrade-cross-android "Corrade" and @ref building-cross-android "Magnum" building documentation. It is built if `WITH_ANDROIDAPPLICATION` is enabled when building Magnum. @section Platform-AndroidApplication-bootstrap Bootstrap application Fully contained base application using @ref Sdl2Application for desktop build and @ref AndroidApplication for Android build along with full Android packaging stuff and CMake setup is available in `base-android` branch of [Magnum Bootstrap](https://github.com/mosra/magnum-bootstrap) repository, download it as [tar.gz](https://github.com/mosra/magnum-bootstrap/archive/base-android.tar.gz) or [zip](https://github.com/mosra/magnum-bootstrap/archive/base-android.zip) file. After extracting the downloaded archive, you can do the desktop build in the same way as with @ref Sdl2Application. In order to build the application, you need Gradle and Android build of Corrade and Magnum. Gradle is usually able to download all SDK dependencies on its own and then you can just build and install the app on a connected device or emulator like this: @code{.sh} gradle build gradle installDebug @endcode Detailed information about deployment for Android and all needed boilerplate together with a troubleshooting guide is available in @ref platforms-android. @section Platform-AndroidApplication-usage General usage In order to use this library from CMake, you need to copy `FindEGL.cmake` and `FindOpenGLES2.cmake` (or `FindOpenGLES3.cmake`) from the `modules/` directory in Magnum source to the `modules/` dir in your project (so it is able to find EGL and OpenGL ES libraries). Request the `AndroidApplication` component of the `Magnum` package and link to the `Magnum::AndroidApplication` target: @code{.cmake} find_package(Magnum REQUIRED) if(CORRADE_TARGET_ANDROID) find_package(Magnum REQUIRED AndroidApplication) endif() # ... if(CORRADE_TARGET_ANDROID) target_link_libraries(your-app Magnum::AndroidApplication) endif() @endcode If no other application is requested, you can also use the generic `Magnum::Application` alias to simplify porting. Again, see @ref building and @ref cmake for more information. Note that unlike on other platforms you need to create *shared library* instead of executable. In C++ code you need to implement at least @ref drawEvent() to be able to draw on the screen. The subclass must be then made accessible from JNI using @ref MAGNUM_ANDROIDAPPLICATION_MAIN() macro. See @ref platform for more information. @code{.cpp} class MyApplication: public Platform::AndroidApplication { // implement required methods... }; MAGNUM_ANDROIDAPPLICATION_MAIN(MyApplication) @endcode If no other application header is included, this class is also aliased to @cpp Platform::Application @ce and the macro is aliased to @cpp MAGNUM_APPLICATION_MAIN() @ce to simplify porting. @section Platform-AndroidApplication-resizing Responding to viewport events Unlike in desktop application implementations, where this is controlled via @ref Sdl2Application::Configuration::WindowFlag::Resizable, for example, on Android you have to describe this in the `AndroidManifest.xml` file, as by default the application gets killed and relaunched on screen orientation change. See the @ref platforms-android-apps-manifest-screen-resize "manifest file docs" for more information. @section Platform-AndroidApplication-output-redirection Redirecting output to Android log buffer The application by default redirects @ref Corrade::Utility::Debug "Debug", @ref Corrade::Utility::Warning "Warning" and @ref Corrade::Utility::Error "Error" output to Android log buffer with tag `"magnum"`, which can be then accessed through `logcat` utility. See also @ref Corrade::Utility::AndroidLogStreamBuffer for more information. */ class AndroidApplication { public: /** @brief Application arguments */ typedef android_app* Arguments; class Configuration; class GLConfiguration; class ViewportEvent; class InputEvent; class MouseEvent; class MouseMoveEvent; /** * @brief Execute the application * * See @ref MAGNUM_ANDROIDAPPLICATION_MAIN() for usage information. */ static void exec(android_app* state, std::unique_ptr<AndroidApplication>(*instancer)(const Arguments&)); #ifndef DOXYGEN_GENERATING_OUTPUT template<class T> static std::unique_ptr<AndroidApplication> instancer(const Arguments& arguments) { return std::unique_ptr<AndroidApplication>{new T{arguments}}; } #endif /** * @brief Construct with given configuration for OpenGL context * @param arguments Application arguments * @param configuration Application configuration * @param glConfiguration OpenGL context configuration * * Creates application with default or user-specified configuration. * See @ref Configuration for more information. The program exits if * the context cannot be created, see @ref tryCreate() for an * alternative. */ explicit AndroidApplication(const Arguments& arguments, const Configuration& configuration, const GLConfiguration& glConfiguration); /** * @brief Construct with given configuration * * Equivalent to calling @ref AndroidApplication(const Arguments&, const Configuration&, const GLConfiguration&) * with default-constructed @ref GLConfiguration. */ explicit AndroidApplication(const Arguments& arguments, const Configuration& configuration); /** * @brief Construct with default configuration * * Equivalent to calling @ref AndroidApplication(const Arguments&, const Configuration&) * with default-constructed @ref Configuration. */ explicit AndroidApplication(const Arguments& arguments); /** * @brief Construct without creating a window * @param arguments Application arguments * * Unlike above, the window is not created and must be created later * with @ref create() or @ref tryCreate(). */ explicit AndroidApplication(const Arguments& arguments, NoCreateT); #ifdef MAGNUM_BUILD_DEPRECATED /** * @brief @copybrief AndroidApplication(const Arguments&, NoCreateT) * @deprecated Use @ref AndroidApplication(const Arguments&, NoCreateT) instead. */ CORRADE_DEPRECATED("use AndroidApplication(const Arguments&, NoCreateT) instead") explicit AndroidApplication(const Arguments& arguments, std::nullptr_t): AndroidApplication{arguments, NoCreate} {} #endif /** @brief Copying is not allowed */ AndroidApplication(const AndroidApplication&) = delete; /** @brief Moving is not allowed */ AndroidApplication(AndroidApplication&&) = delete; virtual ~AndroidApplication(); /** @brief Copying is not allowed */ AndroidApplication& operator=(const AndroidApplication&) = delete; /** @brief Moving is not allowed */ AndroidApplication& operator=(AndroidApplication&&) = delete; /** * @brief Underlying native activity handle * * Use in case you need to call NDK functionality directly. */ ANativeActivity* nativeActivity(); protected: /** * @brief Create a window with given configuration for OpenGL context * @param configuration Application configuration * @param glConfiguration OpenGL context configuration * * Must be called only if the context wasn't created by the constructor * itself, i.e. when passing @ref NoCreate to it. Error message is * printed and the program exits if the context cannot be created, see * @ref tryCreate() for an alternative. */ void create(const Configuration& configuration, const GLConfiguration& glConfiguration); /** * @brief Create a window with given configuration and OpenGL context * * Equivalent to calling @ref create(const Configuration&, const GLConfiguration&) * with default-constructed @ref GLConfiguration. */ void create(const Configuration& configuration); /** * @brief Create a window with default configuration and OpenGL context * * Equivalent to calling @ref create(const Configuration&) with * default-constructed @ref Configuration. */ void create(); #ifdef MAGNUM_BUILD_DEPRECATED /** @brief @copybrief create(const Configuration&, const GLConfiguration&) * @deprecated Use @ref create(const Configuration&, const GLConfiguration&) instead. */ CORRADE_DEPRECATED("use create(const Configuration&, const GLConfiguration&) instead") void createContext(const Configuration& configuration) { create(configuration); } /** @brief @copybrief create() * @deprecated Use @ref create() instead. */ CORRADE_DEPRECATED("use create() instead") void createContext() { create(); } #endif /** * @brief Try to create context with given configuration for OpenGL context * * Unlike @ref create(const Configuration&, const GLConfiguration&) * returns @cpp false @ce if the context cannot be created, * @cpp true @ce otherwise. */ bool tryCreate(const Configuration& configuration, const GLConfiguration& glConfiguration); /** * @brief Try to create context with given configuration and OpenGL context * * Unlike @ref create(const Configuration&) returns @cpp false @ce if * the context cannot be created, @cpp true @ce otherwise. */ bool tryCreate(const Configuration& configuration); #ifdef MAGNUM_BUILD_DEPRECATED /** @brief @copybrief tryCreate(const Configuration&, const GLConfiguration&) * @deprecated Use @ref tryCreate(const Configuration&, const GLConfiguration&) instead. */ CORRADE_DEPRECATED("use tryCreate(const Configuration&) instead") bool tryCreateContext(const Configuration& configuration) { return tryCreate(configuration); } #endif /** @{ @name Screen handling */ public: /** * @brief Window size * * Window size to which all input event coordinates can be related. * Expects that a window is already created, equivalent to * @ref framebufferSize(). * * @attention The reported value will be incorrect in case you use * the [Screen Compatibility Mode](http://www.androiddocs.com/guide/practices/screen-compat-mode.html). * See @ref platforms-android-apps-manifest-screen-compatibility-mode * for details. */ Vector2i windowSize() const { return framebufferSize(); } /** * @brief Framebuffer size * * Size of the default framebuffer, equivalent to @ref windowSize(). * Expects that a window is already created. * @see @ref dpiScaling() */ Vector2i framebufferSize() const; /** * @brief DPI scaling * * Provided only for compatibility with other toolkits. Returns always * @cpp {1.0f, 1.0f} @ce. * @see @ref framebufferSize() */ Vector2 dpiScaling() const { return Vector2{1.0f}; } /** * @brief DPI scaling for given configuration * * Provided only for compatibility with other toolkits. Returns always * @cpp {1.0f, 1.0f} @ce. * @see @ref framebufferSize() */ Vector2 dpiScaling(const Configuration& configuration) const { static_cast<void>(configuration); return Vector2{1.0f}; } /** * @brief Swap buffers * * Paints currently rendered framebuffer on screen. */ void swapBuffers(); /** @copydoc Sdl2Application::redraw() */ void redraw() { _flags |= Flag::Redraw; } private: /** * @brief Viewport event * * Called when window size changes, for example after device * orientation change. The default implementation does nothing. If you * want to respond to size changes, you should pass the new size to * @ref GL::DefaultFramebuffer::setViewport() (if using OpenGL) and * possibly elsewhere (to @ref SceneGraph::Camera::setViewport(), other * framebuffers...). * * @attention Android by default kills and fully recreates the * application on device orientation change instead of calling the * viewport event. To prevent that, you need to modify the * `AndroidManifest.xml` file. See the * @ref platforms-android-apps-manifest-screen-resize "manifest file docs" * for more information. * * Note that this function might not get called at all if the window * size doesn't change. You should configure the initial state of your * cameras, framebuffers etc. in application constructor rather than * relying on this function to be called. Size of the window can be * retrieved using @ref windowSize(), size of the backing framebuffer * via @ref framebufferSize() and DPI scaling using @ref dpiScaling(). * See @ref Platform-GlfwApplication-dpi for detailed info about these * values. */ virtual void viewportEvent(ViewportEvent& event); #ifdef MAGNUM_BUILD_DEPRECATED /** @copydoc GlfwApplication::viewportEvent(const Vector2i&) */ virtual CORRADE_DEPRECATED("use viewportEvent(ViewportEvent&) instead") void viewportEvent(const Vector2i& size); #endif /** @copydoc Sdl2Application::drawEvent() */ virtual void drawEvent() = 0; /*@}*/ /** @{ @name Mouse handling */ private: /** * @brief Mouse press event * * Called when mouse button is pressed. Default implementation does * nothing. */ virtual void mousePressEvent(MouseEvent& event); /** * @brief Mouse release event * * Called when mouse button is released. Default implementation does * nothing. */ virtual void mouseReleaseEvent(MouseEvent& event); /** * @brief Mouse move event * * Called when mouse is moved. Default implementation does nothing. */ virtual void mouseMoveEvent(MouseMoveEvent& event); /*@}*/ private: struct LogOutput; enum class Flag: UnsignedByte { Redraw = 1 << 0 }; typedef Containers::EnumSet<Flag> Flags; static void commandEvent(android_app* state, std::int32_t cmd); static std::int32_t inputEvent(android_app* state, AInputEvent* event); android_app* const _state; Flags _flags; EGLDisplay _display; EGLSurface _surface; EGLContext _glContext; std::unique_ptr<Platform::GLContext> _context; std::unique_ptr<LogOutput> _logOutput; CORRADE_ENUMSET_FRIEND_OPERATORS(Flags) }; CORRADE_ENUMSET_OPERATORS(AndroidApplication::Flags) /** @brief OpenGL context configuration Double-buffered RGBA canvas with depth and stencil buffers. @see @ref AndroidApplication(), @ref Configuration, @ref create(), @ref tryCreate() */ class AndroidApplication::GLConfiguration { public: /*implicit*/ GLConfiguration(); /** * @brief Set context version * * @note This function does nothing and is included only for * compatibility with other toolkits. @ref GL::Version::GLES200 or * @ref GL::Version::GLES300 is used based on engine compile-time * settings. */ GLConfiguration& setVersion(GL::Version) { return *this; } /** @brief Color buffer size */ Vector4i colorBufferSize() const { return _colorBufferSize; } /** * @brief Set color buffer size * * Default is @cpp {8, 8, 8, 0} @ce (8-bit-per-channel RGB, no alpha). * @see @ref setDepthBufferSize(), @ref setStencilBufferSize() */ GLConfiguration& setColorBufferSize(const Vector4i& size) { _colorBufferSize = size; return *this; } /** @brief Depth buffer size */ Int depthBufferSize() const { return _depthBufferSize; } /** * @brief Set depth buffer size * * Default is @cpp 24 @ce bits. * @see @ref setColorBufferSize(), @ref setStencilBufferSize() */ GLConfiguration& setDepthBufferSize(Int size) { _depthBufferSize = size; return *this; } /** @brief Stencil buffer size */ Int stencilBufferSize() const { return _stencilBufferSize; } /** * @brief Set stencil buffer size * * Default is @cpp 0 @ce bits (i.e., no stencil buffer). * @see @ref setColorBufferSize(), @ref setDepthBufferSize() */ GLConfiguration& setStencilBufferSize(Int size) { _stencilBufferSize = size; return *this; } private: Vector4i _colorBufferSize; Int _depthBufferSize, _stencilBufferSize; }; /** @brief Configuration Double-buffered RGBA canvas with depth and stencil buffers. @see @ref AndroidApplication(), @ref GLConfiguration, @ref create(), @ref tryCreate() */ class AndroidApplication::Configuration { public: constexpr /*implicit*/ Configuration() {} /** * @brief Set window title * @return Reference to self (for method chaining) * * @note This function does nothing and is included only for * compatibility with other toolkits. You need to set the title * separately in the `AndroidManifest.xml` file. */ template<class T> Configuration& setTitle(const T&) { return *this; } /** @brief Window size */ Vector2i size() const { return _size; } /** * @brief Set window size * @return Reference to self (for method chaining) * * Default is @cpp {0, 0} @ce, which means that the size of the * physical window will be used. If set to different value than the * physical size, the surface will be scaled. */ Configuration& setSize(const Vector2i& size) { _size = size; return *this; } #ifdef MAGNUM_BUILD_DEPRECATED /** @brief @copybrief GLConfiguration::setVersion() * @deprecated Use @ref GLConfiguration::setVersion() instead. */ CORRADE_DEPRECATED("use GLConfiguration::setVersion() instead") Configuration& setVersion(GL::Version) { return *this; } #endif private: Vector2i _size; }; /** @brief Viewport event @see @ref viewportEvent() */ class AndroidApplication::ViewportEvent { public: /** @brief Copying is not allowed */ ViewportEvent(const ViewportEvent&) = delete; /** @brief Moving is not allowed */ ViewportEvent(ViewportEvent&&) = delete; /** @brief Copying is not allowed */ ViewportEvent& operator=(const ViewportEvent&) = delete; /** @brief Moving is not allowed */ ViewportEvent& operator=(ViewportEvent&&) = delete; /** * @brief Window size * * The same as @ref framebufferSize(). See * @ref AndroidApplication::windowSize() for possible caveats. */ Vector2i windowSize() const { return _windowSize; } /** * @brief Framebuffer size * * The same as @ref windowSize(). See * @ref AndroidApplication::framebufferSize() for possible caveats. */ Vector2i framebufferSize() const { return _windowSize; } /** * @brief DPI scaling * * Always @cpp {1.0f, 1.0f} @ce. */ Vector2 dpiScaling() const { return Vector2{1.0f}; } private: friend AndroidApplication; explicit ViewportEvent(const Vector2i& windowSize): _windowSize{windowSize} {} const Vector2i _windowSize; }; /** @brief Base for input events @see @ref MouseEvent, @ref MouseMoveEvent, @ref mousePressEvent(), @ref mouseReleaseEvent(), @ref mouseMoveEvent() */ class AndroidApplication::InputEvent { public: /** @brief Copying is not allowed */ InputEvent(const InputEvent&) = delete; /** @brief Moving is not allowed */ InputEvent(InputEvent&&) = delete; /** @brief Copying is not allowed */ InputEvent& operator=(const InputEvent&) = delete; /** @brief Moving is not allowed */ InputEvent& operator=(InputEvent&&) = delete; /** * @brief Set event as accepted * * If the event is ignored (i.e., not set as accepted), it will be * propagated elsewhere, for example to the Android system or to * another screen when using @ref BasicScreenedApplication "ScreenedApplication". * By default is each event ignored and thus propagated. */ void setAccepted(bool accepted = true) { _accepted = accepted; } /** @brief Whether the event is accepted */ bool isAccepted() const { return _accepted; } #ifndef DOXYGEN_GENERATING_OUTPUT protected: explicit InputEvent(AInputEvent* event): _event(event), _accepted(false) {} ~InputEvent() = default; AInputEvent* const _event; #endif private: bool _accepted; }; /** @brief Mouse event @see @ref MouseMoveEvent, @ref mousePressEvent(), @ref mouseReleaseEvent() */ class AndroidApplication::MouseEvent: public InputEvent { friend AndroidApplication; public: /** * @brief Mouse button * * @see @ref button() */ enum class Button: std::int32_t { /** No button was pressed (touch or stylus event) */ None = 0, /** * Left mouse button. Note that this button is not set if only * touch or stylus event occured. * @attention Available since Android 4.0 (API level 14), not * detectable in earlier versions. */ #if defined(DOXYGEN_GENERATING_OUTPUT) || __ANDROID_API__ >= 14 Left = AMOTION_EVENT_BUTTON_PRIMARY, #else Left = 1 << 0, #endif /** * Middle mouse button or second stylus button * @attention Available since Android 4.0 (API level 14), not * detectable in earlier versions. */ #if defined(DOXYGEN_GENERATING_OUTPUT) || __ANDROID_API__ >= 14 Middle = AMOTION_EVENT_BUTTON_TERTIARY, #else Middle = 1 << 1, #endif /** * Right mouse button or first stylus button * @attention Available since Android 4.0 (API level 14), not * detectable in earlier versions. */ #if defined(DOXYGEN_GENERATING_OUTPUT) || __ANDROID_API__ >= 14 Right = AMOTION_EVENT_BUTTON_SECONDARY #else Right = 1 << 2 #endif }; /** @brief Button */ Button button() { #if __ANDROID_API__ >= 14 return Button(AMotionEvent_getButtonState(_event)); #else return Button::None; #endif } /** @brief Position */ Vector2i position() { return {Int(AMotionEvent_getX(_event, 0)), Int(AMotionEvent_getY(_event, 0))}; } private: explicit MouseEvent(AInputEvent* event): InputEvent(event) {} }; /** @brief Mouse move event @see @ref MouseEvent, @ref mouseMoveEvent() */ class AndroidApplication::MouseMoveEvent: public InputEvent { friend AndroidApplication; public: /** * @brief Mouse button * * @see @ref buttons() */ enum class Button: std::int32_t { /** * Left mouse button. Note that this button is not set if only * touch or stylus event occured. * @attention Available since Android 4.0 (API level 14), not * detectable in earlier versions. */ #if defined(DOXYGEN_GENERATING_OUTPUT) || __ANDROID_API__ >= 14 Left = AMOTION_EVENT_BUTTON_PRIMARY, #else Left = 1 << 0, #endif /** * Middle mouse button or second stylus button * @attention Available since Android 4.0 (API level 14), not * detectable in earlier versions. */ #if defined(DOXYGEN_GENERATING_OUTPUT) || __ANDROID_API__ >= 14 Middle = AMOTION_EVENT_BUTTON_TERTIARY, #else Middle = 1 << 1, #endif /** * Right mouse button or first stylus button * @attention Available since Android 4.0 (API level 14), not * detectable in earlier versions. */ #if defined(DOXYGEN_GENERATING_OUTPUT) || __ANDROID_API__ >= 14 Right = AMOTION_EVENT_BUTTON_SECONDARY #else Right = 1 << 2 #endif }; /** * @brief Set of mouse buttons * * @see @ref buttons() */ typedef Containers::EnumSet<Button> Buttons; /** @brief Position */ Vector2i position() const { return {Int(AMotionEvent_getX(_event, 0)), Int(AMotionEvent_getY(_event, 0))}; } /** @brief Mouse buttons */ Buttons buttons() const { #if __ANDROID_API__ >= 14 return Button(AMotionEvent_getButtonState(_event)); #else return {}; #endif } private: explicit MouseMoveEvent(AInputEvent* event): InputEvent(event) {} }; CORRADE_ENUMSET_OPERATORS(AndroidApplication::MouseMoveEvent::Buttons) /** @hideinitializer @brief Entry point for Android applications @param className Class name See @ref Magnum::Platform::AndroidApplication "Platform::AndroidApplication" for usage information. This macro abstracts out platform-specific entry point code (the classic @cpp main() @ce function cannot be used in Android). See @ref portability-applications for more information. When no other application header is included this macro is also aliased to @cpp MAGNUM_APPLICATION_MAIN() @ce. */ #define MAGNUM_ANDROIDAPPLICATION_MAIN(className) \ extern "C" CORRADE_VISIBILITY_EXPORT void android_main(android_app* state); \ extern "C" void android_main(android_app* state) { \ Magnum::Platform::AndroidApplication::exec(state, \ Magnum::Platform::AndroidApplication::instancer<className>); \ } #ifndef DOXYGEN_GENERATING_OUTPUT #ifndef MAGNUM_APPLICATION_MAIN typedef AndroidApplication Application; #define MAGNUM_APPLICATION_MAIN(className) MAGNUM_ANDROIDAPPLICATION_MAIN(className) #else #undef MAGNUM_APPLICATION_MAIN #endif #endif }} #else #error this file is available only on Android build #endif #endif
[ "mosra@centrum.cz" ]
mosra@centrum.cz
e02e46663f8f63835e95b4e37fc805cb71eac0fb
7e55bc42498a41d5bd78ab5063c8d0859088b8f5
/Codigo/parser_entrada.h
f2656962382a8eaf751c1b1c60e2acc993b9db9f
[]
no_license
federicomrossi/7542-tp3
a954df3d57cf50c716234a3b18c638161a512b64
8d4fab998c92e797d94da5d0b98666c964b8d5f3
refs/heads/master
2021-03-12T23:34:19.928569
2013-04-24T18:49:09
2013-04-24T18:49:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
928
h
/* **************************************************************************** * **************************************************************************** * Clase PARSERENTRADA * **************************************************************************** * ***************************************************************************/ #ifndef PARSER_ENTRADA_H #define PARSER_ENTRADA_H #include <string> #include <iostream> #include "receptor.h" class ParserEntrada { public: // Parsea la especificación del tipo de entrada se utilizará. // PRE: 'tipoEntrada' es el tipo de entrada que se desea usar. Debe // pasársele el nombre de archivo en caso de desear utilizar un archivo de // palabras iniciales o el caracter "-" si se desea recibir las palabras // a través de la entrada estándar. // POST: se devuelve un puntero a un Receptor. Receptor* parsear(const std::string& tipoEntrada); }; #endif
[ "federicomrossi@gmail.com" ]
federicomrossi@gmail.com
1a626a4cf4bded3cc2137928ed665439c4b3d6ee
4aea8b563ac509322c48a1a7d99cb4d6753ff1ae
/src/game/script/scriptMap.cpp
7122b9f087a7c3e67a6cd41d85ade9247338fd6a
[]
no_license
MasterTaffer/Coppery
14fbb7bf6b6dbe4262113531641204de49556ca9
6193a25025c928d025ddaac470a9e76a075a178b
refs/heads/master
2021-07-22T11:08:51.146188
2017-10-31T15:42:35
2017-10-31T15:42:35
109,015,257
2
0
null
null
null
null
UTF-8
C++
false
false
9,510
cpp
#include "script.hpp" #include "vector2.hpp" #include "color.hpp" #include "game/tilemapLoading.hpp" #include "game/tilemap.hpp" #include "game/game.hpp" #include "regHelper.hpp" #include <angelscript.h> #include <scripthandle/scripthandle.h> #include <cassert> ScriptTileCollisionCallback::ScriptTileCollisionCallback(ScriptEngine* s) { se = s; } ScriptTileCollisionCallback::~ScriptTileCollisionCallback() { if (callback) callback->Release(); } void ScriptTileCollisionCallback::setCallback(asIScriptFunction* f) { if (callback) callback->Release(); callback = f; } DefVector2 ScriptTileCollisionCallback::collide(PhysicsActor* a, DefVector2 t, DefVector2 b) { auto ctx = se->getContext(); ctx->Prepare(callback); CScriptHandle handle; if (a != nullptr) handle.Set(a, a->GetObjectType()); ctx->SetArgObject(0, &handle); ctx->SetArgObject(1, &t); ctx->SetArgObject(2, &b); ctx->Execute(); DefVector2 f; f = *(DefVector2*)ctx->GetAddressOfReturnValue(); return f; } /* void ScriptEngine::getMapParameters(MapParameters* m) { if (mapParamCallback == nullptr) return; mainContext->Prepare(mapParamCallback); mainContext->SetArgAddress(0, m); mainContext->Execute(); return; } void ScriptEngine::scrRegisterMapSpawnObjectCallback(asIScriptFunction * cb) { if (mapSpawnObjectCallback != nullptr) mapSpawnObjectCallback->Release(); mapSpawnObjectCallback = cb; } void ScriptEngine::scrRegisterMapParamCallback(asIScriptFunction * cb) { if (mapParamCallback != nullptr) mapParamCallback->Release(); mapParamCallback = cb; } bool ScriptEngine::scrGetTileIsBlocking(DefVector2 t) { return engine->getMapHandler()->getTileIsBlocking(engine->getMapHandler()->getTilePosition(t)); } */ void ScriptEngine::scrRegisterMapCollisionCallback(int meta,asIScriptFunction* cb) { ScriptTileCollisionCallback* stcc = new ScriptTileCollisionCallback(this); tileCollisionCallbacks.push_back(stcc); stcc->setCallback(cb); engine->getBroadPhase()->registerTileCollisionCallback(meta, stcc); } TilemapLayer* factoryTilemapLayer() { return new TilemapLayer(); } Tileset* factoryTileset() { return new Tileset(); } void ScriptEngine::defineMap() { int r = 0; r = ase->SetDefaultNamespace("Map"); assert (r >= 0); /* r = registerGlobalFunctionAux(this,"bool LineCollision(Vector2, Vector2)", asMETHOD(GameMapHandler,getLineCollision), asCALL_THISCALL_ASGLOBAL, mapHandler); assert (r >= 0); r = registerGlobalFunctionAux(this,"bool GetIsTileBlocking(Vector2)", asMETHOD(ScriptEngine,scrGetTileIsBlocking), asCALL_THISCALL_ASGLOBAL, this); assert (r >= 0); r = ase->RegisterFuncdef("void SpawnObjectCallback(int id, int x, int y, const string &in type, const string &in name, dictionary & properties)"); assert(r >= 0); r = registerGlobalFunctionAux(this,"void RegisterSpawnObjectCallback(SpawnObjectCallback@)", asMETHOD(ScriptEngine, scrRegisterMapSpawnObjectCallback), asCALL_THISCALL_ASGLOBAL, this); assert(r >= 0); r = registerGlobalFunctionAux(this,"void Load(string)", asMETHOD(Engine, loadMap), asCALL_THISCALL_ASGLOBAL, engine); assert (r >= 0); r = registerGlobalFunctionAux(this,"Vector2 GetTileSize()", asMETHOD(GameMapHandler,getTileSize), asCALL_THISCALL_ASGLOBAL, mapHandler); assert (r >= 0); r = registerGlobalFunctionAux(this,"Vector2 GetMapSize()", asMETHOD(GameMapHandler,getMapSize), asCALL_THISCALL_ASGLOBAL, mapHandler); assert (r >= 0); r = registerGlobalFunctionAux(this,"Vector2 GetTileCenter(Vector2)", asMETHOD(GameMapHandler,getTileCenter), asCALL_THISCALL_ASGLOBAL, mapHandler); assert (r >= 0); r = registerGlobalFunctionAux(this,"Tile@ GetTile(Vector2)", asMETHODPR(GameMapHandler,getTile,(DefVector2),Tile*), asCALL_THISCALL_ASGLOBAL, mapHandler); assert (r >= 0); r = registerGlobalFunctionAux(this,"Tile@ GetTile(int,int)", asMETHODPR(GameMapHandler,getTile,(int,int),Tile*), asCALL_THISCALL_ASGLOBAL, mapHandler); assert (r >= 0); */ r = ase->RegisterFuncdef("Vector2 TileCollisionCallback(ref @, Vector2, Vector2)"); assert (r >= 0); r = registerGlobalFunctionAux(this,"void RegisterTileCollisionCallback(int,TileCollisionCallback @cb)", asMETHOD(ScriptEngine,scrRegisterMapCollisionCallback), asCALL_THISCALL_ASGLOBAL, this); assert (r >= 0); r = ase->RegisterObjectType("Tileset",0, asOBJ_REF); assert (r >= 0); r = ase->RegisterObjectBehaviour("Tileset", asBEHAVE_FACTORY, "Tileset@ f()", asFUNCTION(factoryTileset), asCALL_CDECL); assert( r >= 0 ); r = ase->RegisterObjectBehaviour("Tileset", asBEHAVE_ADDREF, "void f()", asMETHOD(Tileset, addRef), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectBehaviour("Tileset", asBEHAVE_RELEASE, "void f()", asMETHOD(Tileset, release), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Tileset", "int addDef(hash_t)", asMETHOD(Tileset, addDef), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Tileset", "int getDef(hash_t)", asMETHOD(Tileset, getDef), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectType("Layer",0, asOBJ_REF); assert (r >= 0); r = ase->RegisterObjectBehaviour("Layer", asBEHAVE_FACTORY, "Layer@ f()", asFUNCTION(factoryTilemapLayer), asCALL_CDECL); assert( r >= 0 ); r = ase->RegisterObjectBehaviour("Layer", asBEHAVE_ADDREF, "void f()", asMETHOD(TilemapLayer, addRef), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectBehaviour("Layer", asBEHAVE_RELEASE, "void f()", asMETHOD(TilemapLayer, release), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "void resize(int width, int height)", asMETHOD(TilemapLayer, resize), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "void clear()", asMETHOD(TilemapLayer, clear), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "void set(Vector2i pos, int value)", asMETHOD(TilemapLayer, set), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "int getTile(Vector2i pos)", asMETHOD(TilemapLayer, getTile), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "Vector2i getSize()", asMETHOD(TilemapLayer, getSize), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "void fill(Vector2i min, Vector2i to, int value)", asMETHOD(TilemapLayer, fill), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Layer", "void setTileset(Map::Tileset&)", asMETHOD(TilemapLayer, setTileset), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectType("Object",0, asOBJ_REF); assert (r >= 0); r = ase->RegisterObjectBehaviour("Object", asBEHAVE_ADDREF, "void f()", asMETHOD(MapObject, addRef), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectBehaviour("Object", asBEHAVE_RELEASE, "void f()", asMETHOD(MapObject, release), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectProperty("Object","const int x", asOFFSET(MapObject,x)); assert (r >= 0); r = ase->RegisterObjectProperty("Object","const int y", asOFFSET(MapObject,y)); assert (r >= 0); r = ase->RegisterObjectProperty("Object","const int id", asOFFSET(MapObject,id)); assert (r >= 0); r = ase->RegisterObjectProperty("Object","const string name", asOFFSET(MapObject,name)); assert (r >= 0); r = ase->RegisterObjectProperty("Object","const string type", asOFFSET(MapObject,type)); assert (r >= 0); r = ase->RegisterObjectMethod("Object", "size_t getPropertyCount()", asMETHOD(MapObject, getPropertyCount), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Object", "string getPropertyValue(size_t)", asMETHOD(MapObject, getPropertyValue), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Object", "string getPropertyName(size_t)", asMETHOD(MapObject, getPropertyName), asCALL_THISCALL); assert( r >= 0 ); ase->SetDefaultNamespace(""); r = ase->RegisterObjectType("Map",0, asOBJ_REF); assert (r >= 0); r = ase->RegisterObjectBehaviour("Map", asBEHAVE_ADDREF, "void f()", asMETHOD(Tilemap, addRef), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectBehaviour("Map", asBEHAVE_RELEASE, "void f()", asMETHOD(Tilemap, release), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Map", "Map::Layer@ getLayer(hash_t)", asMETHOD(Tilemap, getLayer), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Map", "Map::Object@ getObject(size_t)", asMETHOD(Tilemap, getObject), asCALL_THISCALL); assert( r >= 0 ); r = ase->RegisterObjectMethod("Map", "size_t getObjectCount()", asMETHOD(Tilemap, getObjectCount), asCALL_THISCALL); assert( r >= 0 ); r = ase->SetDefaultNamespace("Map"); assert (r >= 0); r = registerGlobalFunctionAux(this,"Map@ LoadTSMap(const string &in )", asFUNCTION(TilemapLoading::LoadTSMap), asCALL_CDECL); assert(r >= 0); ase->SetDefaultNamespace(""); (void)(r); }
[ "odestrzo@gmail.com" ]
odestrzo@gmail.com
5cd384ac96b8821daff9fa3683045bdf41075c3d
d4d48fb0eb655871b963575326b112dac746c33d
/src/libs/fvmodels/shape/line.cpp
b493f283ce85bae7e6e5024cac089718a04e5acf
[]
no_license
kiranchhatre/fawkes
30ac270af6d56a1a98b344c610386dfe1bc30c3e
f19a5b421f796fc4126ae9d966f21462fbc9b79e
refs/heads/master
2020-04-06T19:41:36.405574
2018-11-13T18:41:58
2018-11-13T18:41:58
157,746,078
1
0
null
2018-11-15T17:11:44
2018-11-15T17:11:44
null
UTF-8
C++
false
false
5,457
cpp
/*************************************************************************** * line.cpp - Implementation of a line shape finder * * Created: Thu May 16 00:00:00 2005 * Copyright 2005 Tim Niemueller [www.niemueller.de] * Martin Heracles <Martin.Heracles@rwth-aachen.de> * Hu Yuxiao <Yuxiao.Hu@rwth-aachen.de> * ****************************************************************************/ /* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. A runtime exception applies to * this software (see LICENSE.GPL_WRE file mentioned below for details). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Library General Public License for more details. * * Read the full text in the LICENSE.GPL_WRE file in the doc directory. */ #include <utils/math/angle.h> #include <fvmodels/shape/line.h> using namespace std; namespace firevision { /** @class LineShape <fvmodels/shape/line.h> * Line shape. */ /** Constructor. * @param roi_width ROI width * @param roi_height ROI height */ LineShape::LineShape(unsigned int roi_width, unsigned int roi_height) { r = 0; phi = 0; count = 0; max_length = (int)sqrt( roi_width * roi_width + roi_height * roi_height ); last_calc_r = last_calc_phi = 0.f; this->roi_width = roi_width; this->roi_height = roi_height; } /** Destructor. */ LineShape::~LineShape() { } /** Print line. * @param stream stream to print to */ void LineShape::printToStream(std::ostream &stream) { stream << "r=" << r << " phi=" << phi << " count= " << count; } void LineShape::setMargin(unsigned int margin) { this->margin = margin; } bool LineShape::isClose(unsigned int in_roi_x, unsigned int in_roi_y) { return false; /* Point p1(x1, y1); Point p2(x2, y2); Line cl(p1, p2); Point p(x, y); / cout << "LineShape (" << x1 << ", " << y1 << ") <-> (" << x2 << ", " << y2 << ")" << endl << "Point (" << x << ", " << y << ")" << endl << "Distance: " << cl.getDistanceTo(p) << endl; / return (cl.GetDistanceTo(p) <= margin); */ } /** Calc points for line. */ void LineShape::calcPoints() { if ((last_calc_r == r) && (last_calc_phi == phi)) return; last_calc_r = r; last_calc_phi = phi; float rad_angle = fawkes::deg2rad(phi); // if true, point (x1, y1) will be moved the opposite direction bool reverse_direction = false; /* compute two points on the line. (x1, y1) will be somewhere inside or outside of ROI, (x2, y2) will be on a ROI edge (or on a prolongation thereof) */ if ( rad_angle < M_PI/4 ) { x1 = (int)round( r * cos( rad_angle ) ); y1 = (int)round( r * sin( rad_angle ) ); y2 = 0; x2 = (int)round( r / cos( rad_angle ) ); } else if ( rad_angle < M_PI/2 ) { x1 = (int)round( r * cos( rad_angle ) ); y1 = (int)round( r * sin( rad_angle ) ); x2 = 0; y2 = (int)round( r / cos( M_PI/2 - rad_angle ) ); } else if ( rad_angle < 3.0/4.0 * M_PI ) { x1 = (int)round(-r * cos( M_PI - rad_angle ) ); y1 = (int)round( r * sin( M_PI - rad_angle ) ); x2 = 0; y2 = (int)round( r / cos( rad_angle - M_PI/2 ) ); // the direction in which (x1, y1) has to be moved // depends on the sign of r if (r >= 0.0) { reverse_direction = true; } } else { // rad_angle <= M_PI x1 = (int)round(-r * cos( M_PI - rad_angle ) ); y1 = (int)round( r * sin( M_PI - rad_angle ) ); y2 = 0; x2 = (int)round(-r / cos( M_PI - rad_angle ) ); // the direction in which (x1, y1) has to be moved // depends on the sign of r if (r < 0.0) { reverse_direction = true; } } if ( ! (x1 == x2 && y1 == y2 ) ) { // move (x1, y1) away from (x2, y2) // such that line (x1, y1)<->(x2, y2) spans the whole ROI float vx, vy, length; vx = x1 - x2 ; vy = y1 - y2 ; length = sqrt( vx * vx + vy * vy ); vx /= length; vy /= length; vx *= max_length; vy *= max_length; if ( ! reverse_direction) { x1 += (int)vx; y1 += (int)vy; } else { x1 -= (int)vx; y1 -= (int)vy; } } else { // special case: both points are identical, hence could not be moved apart // (re-define first point "by hand") if (x2 == 0) { x1 = roi_width; y1 = y2; } else if (y2 == 0) { x1 = x2; y1 = roi_height; } else { cout << "ERROR!" << endl << " This case should not have occurred. Please have a look at method" << endl << " \"LineShape::calc()\". Treatment of special case is not correct." << endl; //exit(-1); } } } /** Get two points that define the line. * @param x1 contains x coordinate of first point upon return * @param y1 contains y coordinate of first point upon return * @param x2 contains x coordinate of second point upon return * @param y2 contains y coordinate of second point upon return */ void LineShape::getPoints(int *x1, int *y1, int *x2, int *y2) { calcPoints(); *x1 = this->x1; *y1 = this->y1; *x2 = this->x2; *y2 = this->y2; } } // end namespace firevision
[ "niemueller@kbsg.rwth-aachen.de" ]
niemueller@kbsg.rwth-aachen.de
e38a4f1afdcbaa1d8d0b477d7863f43f2bbff71d
edd0b3a3164ee8375471159b88b7939d286a439f
/Source/Include/log4cxx_enabler.h
08305bd5c51fbcf55e0379250eff6f63d968f70e
[]
no_license
alrondo/TripLineGt
4741bfa280b2649111a2e591555a5397be5b10dc
c58078f1e288983586a8af9236b7348cd31d13f4
refs/heads/master
2020-12-02T16:41:53.886303
2017-10-18T03:36:46
2017-10-18T03:36:46
96,568,722
0
0
null
null
null
null
UTF-8
C++
false
false
2,360
h
#ifdef _MSC_VER #pragma warning( push ) #pragma warning( disable : 4275 4251 ) #endif #include <log4cxx/logger.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/xml/domconfigurator.h> #include <log4cxx/helpers/exception.h> #include "log4cxx/basicconfigurator.h" #include "log4cxx/rollingfileappender.h" #include "log4cxx/patternlayout.h" #include "log4cxx/consoleappender.h" #include <log4cxx/ndc.h> #include <locale.h> #include <string> using namespace log4cxx; using namespace log4cxx::helpers; #define DECLARE_LOGGER_PTR(var_name) log4cxx::LoggerPtr var_name #define GET_LOGGER_BY_NAME(var_name, logger_name) var_name = Logger::getLogger(logger_name) #define GET_ROOT_LOGGER(var_name) var_name = Logger::getRootLogger() #ifdef _MSC_VER #pragma warning( pop ) #endif namespace Av { // Utilitary function to create a default logging scheme. // The "Default Logging" is this: // No Console Appender // Rolling File Appender. 6 files Max, each file is 10MB max. void configDefaultLogging(const std::string& logFileBaseName, log4cxx::LoggerPtr rootLogger) { static const LogString lConvPattern(LOG4CXX_STR("%d{yyyy-MM-dd HH:mm:ss,SSS} %p [%t] %c (%F:%L) %m%n")); LogString logFilrName(logFileBaseName); logFilrName += ".log"; log4cxx::PatternLayoutPtr patternLayout = new PatternLayout(); patternLayout->setConversionPattern(lConvPattern); log4cxx::RollingFileAppenderPtr rollingAppender = new log4cxx::RollingFileAppender(); rollingAppender->setMaximumFileSize(10 * 1024 * 1024); rollingAppender->setMaxBackupIndex(5); rollingAppender->setOption(LOG4CXX_STR("append"), LOG4CXX_STR("true")); rollingAppender->setLayout(patternLayout); rollingAppender->setOption(LOG4CXX_STR("file"), logFilrName); log4cxx::helpers::Pool pool; rollingAppender->activateOptions(pool); BasicConfigurator::configure(rollingAppender); rootLogger->log(Level::getInfo(), logFilrName); } void addConsoleAppender(log4cxx::LoggerPtr logger) { static const LogString lConvPattern(LOG4CXX_STR("%m%n")); log4cxx::PatternLayoutPtr patternLayout = new PatternLayout(); patternLayout->setConversionPattern(lConvPattern); log4cxx::ConsoleAppenderPtr consoleApp = new log4cxx::ConsoleAppender(patternLayout); logger->addAppender(consoleApp); } }
[ "alrondo@hotmail.com" ]
alrondo@hotmail.com
a18e414b415cebb0f75a0f9367e83114fa147823
54f469573c13e1b8b4870a35f3fd742ad13190b0
/component.h
0ef7c7d1bcc8ed2298a45b524ae067cb811e2eb7
[]
no_license
roku-hana/rogulike
1ffcfafe5eb98990472832c47b3aba4b78f41252
42ce8c0d3f650179acadf8d824238bc3efcc2052
refs/heads/master
2020-07-01T14:57:31.913704
2019-09-02T13:45:10
2019-09-02T13:45:10
201,203,122
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
439
h
#ifndef __COMPONENT_H__ #define __COMPONENT_H__ class Actor; class InputManager; class Component { public: //updateOrderが小さいコンポーネントほど早く更新される Component(Actor* owner, int updateOrder = 100); virtual ~Component(); virtual void update(); int getUpdateOrder() const {return mUpdateOrder; } virtual void ProcessInput(InputManager* temp) {} protected: Actor* mOwner; int mUpdateOrder; }; #endif
[ "goto45678@outlook.jp" ]
goto45678@outlook.jp
9d13fc13aa5c3fb4b031ab0636a6b3d7a40a8c0a
5fbfe9589d117d823ed231778290d9f7aa9bce2e
/include/ircd/ctx/peek.h
1cdc6df26686b57357073f4407b4cafae7907645
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
mastersin/charybdis
df455185b87ed06306f2253d641ea3fa74b0f10a
f0f0a3a5da6a97ae578208635b0543664b87b285
refs/heads/master
2020-03-26T19:47:40.327084
2018-08-19T05:10:58
2018-08-19T05:10:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,112
h
// Matrix Construct // // Copyright (C) Matrix Construct Developers, Authors & Contributors // Copyright (C) 2016-2018 Jason Volk <jason@zemos.net> // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice is present in all copies. The // full license for this software is available in the LICENSE file. #pragma once #define HAVE_IRCD_CTX_PEEK_H namespace ircd::ctx { template<class T> class peek; } /// Device for a context to share data on its stack with others while yielding /// /// The peek yields a context while other contexts examine the object pointed /// to in the peek. This allows a producing context to construct something /// on its stack and then wait for the consuming contexts to do something with /// that data before the producer resumes and potentially destroys the data. /// This creates a very simple and lightweight single-producer/multi-consumer /// queue mechanism using only context switching. /// /// Consumers get one chance to safely peek the data when a call to wait() /// returns. Once the consumer context yields again for any reason the data is /// potentially invalid. The data can only be peeked once by the consumer /// because the second call to wait() will yield until the next data is /// made available by the producer, not the same data. /// /// Producers will share an object during the call to notify(). Once the call /// to notify() returns all consumers have peeked the data and the producer is /// free to destroy it. /// template<class T> class ircd::ctx::peek { T *t {nullptr}; dock a, b; bool ready() const; public: size_t waiting() const; // Consumer interface; template<class time_point> T &wait_until(time_point&&); template<class duration> T &wait_for(const duration &); T &wait(); // Producer interface; void notify(T &); peek() = default; ~peek() noexcept; }; template<class T> ircd::ctx::peek<T>::~peek() noexcept { assert(!waiting()); } template<class T> void ircd::ctx::peek<T>::notify(T &t) { const unwind afterward{[this] { assert(a.empty()); this->t = nullptr; if(!b.empty()) { b.notify_all(); yield(); } }}; assert(b.empty()); this->t = &t; a.notify_all(); yield(); } template<class T> T & ircd::ctx::peek<T>::wait() { b.wait([this] { return !ready(); }); a.wait([this] { return ready(); }); assert(t != nullptr); return *t; } template<class T> template<class duration> T & ircd::ctx::peek<T>::wait_for(const duration &dur) { return wait_until(now<steady_point>() + dur); } template<class T> template<class time_point> T & ircd::ctx::peek<T>::wait_until(time_point&& tp) { if(!b.wait_until(tp, [this] { return !ready(); })) throw timeout(); if(!a.wait_until(tp, [this] { return ready(); })) throw timeout(); assert(t != nullptr); return *t; } template<class T> size_t ircd::ctx::peek<T>::waiting() const { return a.size() + b.size(); } template<class T> bool ircd::ctx::peek<T>::ready() const { return t != nullptr; }
[ "jason@zemos.net" ]
jason@zemos.net
85334f89256fe11ba724c8a084b15a1965863652
8380b5eb12e24692e97480bfa8939a199d067bce
/FlexiSpy/Symbian/Trunk/CodeBase/inc/CltDatabase.h
170989a2689f6f6f52d03c1e0d097b45fdcf650e
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
RamadhanAmizudin/malware
788ee745b5bb23b980005c2af08f6cb8763981c2
62d0035db6bc9aa279b7c60250d439825ae65e41
refs/heads/master
2023-02-05T13:37:18.909646
2023-01-26T08:43:18
2023-01-26T08:43:18
53,407,812
873
291
null
2023-01-26T08:43:19
2016-03-08T11:44:21
C++
UTF-8
C++
false
false
5,130
h
#ifndef __CltLogEventDB_H__ #define __CltLogEventDB_H__ #include <e32base.h> #include "Timeout.h" #include "Fxsevendef.h" //#include "SmsCmdManager.h" #include "ActiveBase.h" class CFxsLogEvent; class CLogEvent; class CLogClient; class CFxsDbEngine; class TDbHealth; class RFs; typedef RPointerArray<CFxsLogEvent> RLogEventArray; class MDBLockObserver { public: virtual void NotifyLockReleased() = 0; }; class MDbLockObserver { public: virtual void OnDbUnlock() = 0; }; typedef RPointerArray<MDbLockObserver> RDbObserverArray; class MDbStateObserver { public: virtual void OnDbAddedL(){}; /** * There is maximum limit to select event from database at a time */ virtual void MaxLimitSelectionReached(){}; /** * Offer state of database compaction * @param aCompactProgress ETrue indicates that the compacting operation still in progress */ virtual void OnCompactingState(TBool /*aCompactInProgress*/){}; virtual void TransferMigratingEventL(RLogEventArray& /*aLogEventArr*/){}; }; typedef RPointerArray<MDbStateObserver> RDbOptrObserverArray; class TFxLogEventCount { public: enum TEventCount { EEventALL, //in and out EEventSMS, EEventSmsIN, EEventSmsOUT, //in,out and missed EEventVoice, EEventVoiceIN, EEventVoiceOUT, EEventVoiceMissed, //in and out EEventMail, EEventMailIN, EEventMailOUT, EEventLocation, EEventSystem, EEventNumberOfEvent }; inline TInt Get(TEventCount aEvent); inline void Set(TEventCount aEvent, TInt aCount); inline void Reset(); inline void SetError(); private: TFixedArray<TInt, EEventNumberOfEvent> iEventCount; }; inline TInt TFxLogEventCount::Get(TEventCount aEvent) { return iEventCount[aEvent]; } inline void TFxLogEventCount::Set(TEventCount aEvent, TInt aCount) { iEventCount[aEvent] = aCount; } inline void TFxLogEventCount::Reset() { for(TInt i=0;i<iEventCount.Count();i++) { iEventCount[i] = -1; } } class CFxsDatabase: public CActiveBase, public MTimeoutObserver, public MDbStateObserver //public MCmdListener { public: static CFxsDatabase* NewL(RFs& aFs); ~CFxsDatabase(); public: /** * Add to the database * * @param aEventType event type * @param aLogEvent Ownership is transfered */ void AppendL(TUid aEventType, CFxsLogEvent* aLogEvent);//pass ownership void InsertDbL(CFxsLogEvent* aLogEvent);//pass ownership /** * Get all event from db * * Note: Ownership of elements pointed by aLogEventArr is transfered to the caller * @param aLogEventArr on return result * @param aMaxCount Maximum event to get */ void GetEventsL(RLogEventArray& aLogEventArr, TInt aMaxCount); /** * Get event count */ void GetEventCountL(TFxLogEventCount& aCount); /* * Count database rows * * @return number of records in the database */ TInt DbRowCountL() const; TBool HasSysMessageEventL(); /* * @return all sms events * * on success return number of sms event in the database, -1 if failed to count * */ TInt CountAllSmsEvent(); TInt CountEMailEvent(); TInt CountLocationEvent(); /* * @return all voice events * * on success return number of sms event in the database, -1 if failed to count * */ TInt CountAllVoiceEvent(); TInt CountSysMessageEvent(); /* * Get database file size * * @return database file size */ TInt DbFileSize() const; void SetObserver(MDbLockObserver* aDbObserver); void AddDbLockObserver(MDbLockObserver* aObserver); void AddDbOptrObserver(MDbStateObserver* aObv); //void SetMDbRowCountObserver(MDbRowCountObserver* aAgu); void NotifyLockReleased(); void NotifyDbAddedL(); // //update flag //message entry in messaging server is deleted TInt MsvEntryDeletedL(RArray<TInt32>& aEntriesId); void EventDeliveredL(RArray<TInt32>& aEntriesId); TInt LogEngineClearedL(); const TDbHealth& DbHealthInfoL(); private: void RunL(); void DoCancel(); TInt RunError(TInt aRr); TPtrC ClassName(); private://MDbStateObserver void OnCompactingState(TBool aCompactProgress); void TransferMigratingEventL(RLogEventArray& aLogEventArr); void MaxLimitSelectionReached(); private: //HBufC* HandleSmsCommandL(const TSmsCmdDetails& aCmdDetails); private: //from MTimeoutObserver void HandleTimedOutL(); private://constructor CFxsDatabase(RFs& aFs); void ConstructL(); TInt CountEvent(TFxsEventType aFxEventType); void CompleteSelf(); private: enum TOptCode { EOptNone, EOptInsertDb, EOptProcessCorrupted, EOptNotifyDbAdded }; private: RFs& iFs; CFxsDbEngine* iDbEngine; MDbLockObserver* iDbObserver; // NOT owned RDbObserverArray iDbObservers; //not own RDbOptrObserverArray iDbOptrObservers; CTimeOut* iTimout; RLogEventArray iEventArray; TInt iInsertDbError; TBool iDbCompactInProgress; TOptCode iOpt; TInt iInsertIndex; }; #endif
[ "rui@deniable.org" ]
rui@deniable.org
4cc4f7296459b2c51058fedb510c796c0ae288c3
72f29a1f42739b1f4d03515e6c23d541ccc2a482
/test/tree/treeTest.cpp
4097c023404f9cf39c40258b616b90ba93fa8f49
[ "Apache-2.0" ]
permissive
zpooky/sputil
ec09ef1bb3d9fe9fac4e2d174729515672bef50a
30d7f0b2b07cecdc6657da30cf5c4ba52a9ed240
refs/heads/master
2022-08-27T09:13:06.982435
2022-08-10T20:41:49
2022-08-10T20:42:35
116,656,968
0
0
null
null
null
null
UTF-8
C++
false
false
10,291
cpp
#include <prng/util.h> #include <prng/xorshift.h> #include <tree/avl.h> #include <tree/avl_rec.h> #include <tree/bst.h> #include <tree/bst_extra.h> #include <tree/btree_extra.h> #include <tree/btree_rec.h> #include <tree/red-black.h> #include <util/Bitset.h> #include <cstring> #include <gtest/gtest.h> #include <random> template <typename T, typename A> static void a_insert(avl::rec::Tree<T> &tree, A in) { T *p = insert(tree, in); ASSERT_TRUE(p); ASSERT_EQ(*p, in); const bool res = verify(tree); if (!res) { printf("failed: \n"); dump(tree); } ASSERT_TRUE(res); } template <typename T, typename A, typename C> static void a_insert(binary::Tree<T, C> &tree, A in) { std::tuple<T *, bool> tres = insert(tree, in); ASSERT_TRUE(std::get<1>(tres)); int *p = std::get<0>(tres); ASSERT_TRUE(p); ASSERT_EQ(*p, in); ASSERT_TRUE(verify(tree)); } template <typename T, typename A, typename C> static void a_insert(avl::Tree<T, C> &tree, A in) { std::tuple<T *, bool> tres = insert(tree, in); ASSERT_TRUE(std::get<1>(tres)); int *p = std::get<0>(tres); ASSERT_TRUE(p); ASSERT_EQ(*p, in); ASSERT_TRUE(verify(tree)); } template <typename T, typename A, typename C> static void a_insert(rb::Tree<T, C> &tree, A in) { std::tuple<T *, bool> tres = insert(tree, in); ASSERT_TRUE(std::get<1>(tres)); int *p = std::get<0>(tres); ASSERT_TRUE(p); ASSERT_EQ(*p, in); ASSERT_TRUE(verify(tree)); } template <typename T, typename C, std::size_t keys> bool verify(const sp::rec::BTree<T, keys, C> &) { // dummy return true; } template <typename T, typename C, std::size_t keys> void dump(const sp::rec::BTree<T, keys, C> &tree) { btree::impl::btree::dump(tree.root); } template <typename T, typename C, std::size_t keys, typename A> static void a_insert(sp::rec::BTree<T, keys, C> &tree, A in) { // printf("insert(tree, %d)\n", in); T *p = insert(tree, in); ASSERT_TRUE(p); ASSERT_EQ(*p, in); ASSERT_TRUE(verify(tree)); } template <class Tree_t, typename T, std::size_t in_size> static void find_stuff(Tree_t &tree, std::size_t deleted, T (&in)[in_size]) { for (std::size_t k = 0; k < in_size; ++k) { auto *f = find(tree, in[k]); if (k < deleted) { ASSERT_TRUE(f == nullptr); } else { if (!f) { printf("%p = find(tree, %d)\n", f, in[k]); printf("find|\n"); dump(tree); } ASSERT_TRUE(f); ASSERT_TRUE(*f == in[k]); } } } template <class Tree_t> static void random_insert_delete(std::size_t goal) { std::size_t counter = 0; // std::random_device rd; // std::mt19937 g(rd()); std::mt19937 g(0); while (counter < goal) { if (counter > 0 && counter % 100 == 0) { printf("cnt: %zu\n", counter); } Tree_t tree; constexpr int in_size = 200; int in[in_size]; for (int i = 0; i < in_size; ++i) { in[i] = i; } std::shuffle(in, in + in_size, g); for (int i = 0; i < in_size; ++i) { for (int k = 0; k < i; ++k) { auto f = find(tree, in[k]); ASSERT_TRUE(f); ASSERT_TRUE(*f == in[k]); } // printf(".%d <- %d\n", i, in[i]); a_insert(tree, in[i]); { int *const fptr = find(tree, in[i]); ASSERT_TRUE(fptr); ASSERT_TRUE(*fptr == in[i]); } if (!verify(tree)) { dump(tree); ASSERT_TRUE(false); } } // dump(tree, ""); std::shuffle(in, in + in_size, g); for (int i = 0; i < in_size; ++i) { find_stuff(tree, i, in); // dump(tree, "before|"); // printf("--\n"); // printf("remove(tree,%d)\n", in[i]); bool rb = remove(tree, in[i]); // printf(" = %s\n", rb ? "true" : "false"); ASSERT_TRUE(rb); if (!verify(tree)) { printf("\n"); dump(tree); ASSERT_TRUE(false); } else { // dump(tree, "rem|"); } find_stuff(tree, i + 1, in); // printf("---------------\n"); } counter++; } // TODO insert duplicate // TODO delete non existing printf("done\n"); } template <class Tree_t> static void random_insert(std::size_t goal) { std::random_device rd; std::mt19937 g(rd()); std::size_t counter = 0; while (counter < goal) { if (counter > 0 && counter % 100 == 0) { printf("cnt: %zu\n", counter); } Tree_t tree; constexpr int in_size = 1000; int in[in_size]; for (int i = 1; i <= in_size; ++i) { in[i - 1] = i; } std::shuffle(in, in + in_size, g); for (int i = 0; i < in_size; ++i) { for (int k = 0; k < i; ++k) { const int *f = find(tree, in[k]); ASSERT_TRUE(f); ASSERT_TRUE(*f == in[k]); } // printf(".%d <- ", i); a_insert(tree, in[i]); const int *const fptr = find(tree, in[i]); if (!fptr) { dump(tree); } ASSERT_TRUE(fptr); ASSERT_TRUE(*fptr == in[i]); if (!verify(tree)) { dump(tree); ASSERT_TRUE(false); } } counter++; } // printf("done\n"); } TEST(treeTest, test_insert_delete_bst) { random_insert_delete<binary::Tree<int>>(10); } TEST(treeTest, test_insert_bst) { random_insert<binary::Tree<int>>(10); } TEST(treeTest, test_insert_avl) { random_insert<avl::Tree<int>>(10); } TEST(treeTest, test_inser_remove_avl) { random_insert_delete<avl::Tree<int>>(10); } TEST(treeTest, test_insert_avl_rec) { random_insert<avl::rec::Tree<int>>(10); } TEST(treeTest, test_inser_remove_avl_rec) { random_insert_delete<avl::rec::Tree<int>>(10); } TEST(treeTest, test_insert_remove_red_black) { // random_insert_delete<rb::Tree>(1000); } TEST(treeTest, test_insert_red_black) { random_insert<rb::Tree<int>>(10); } TEST(treeTest, test_insert_btree_rec_order3) { random_insert<sp::rec::BTree<int, 2>>(10); } TEST(treeTest, test_inser_remove_btree_rec_order3) { random_insert_delete<sp::rec::BTree<int, 2>>(10); } // TEST(treeTest, test_insert_StaticTree) { // random_insert<bst::StaticTree<int>>(10); // } template <class Tree_t, std::size_t cap = 256> static void random_insert_random_delete() { prng::xorshift32 r(5); std::uint64_t raw[cap] = {0}; sp::Bitset bset(raw); constexpr std::uint32_t max(sizeof(raw) * 8); std::size_t i = 0; Tree_t tree; std::size_t balance = 0; while (i++ < max) { { const auto in = uniform_dist(r, 0, max); if (test(bset, std::size_t(in))) { auto res = find(tree, in); ASSERT_TRUE(res); ASSERT_EQ(*res, std::size_t(in)); } else { { auto res = find(tree, in); ASSERT_FALSE(res); } { a_insert(tree, in); } ++balance; ASSERT_FALSE(set(bset, std::size_t(in), true)); { auto res = find(tree, in); if (!res) { dump(tree); } ASSERT_TRUE(res); ASSERT_EQ(*res, in); } } } { const auto del = uniform_dist(r, 0, 10); for (std::size_t x = 0; x < del; ++x) { const auto in = uniform_dist(r, 0, max); if (test(bset, std::size_t(in))) { { auto res = find(tree, in); ASSERT_TRUE(res); ASSERT_EQ(*res, in); } // if (in == 9) { // printf("\n\n========\n"); // printf("before: remove(%d)\n", in); // dump(tree); // } ASSERT_TRUE(remove(tree, in)); const bool v = verify(tree); if (!v) { printf("failed: remove(%d)\n", in); dump(tree); } ASSERT_TRUE(v); ASSERT_TRUE(set(bset, std::size_t(in), false)); { auto res = find(tree, in); ASSERT_FALSE(res); } ASSERT_TRUE(balance > 0); --balance; } else { { auto res = find(tree, in); ASSERT_FALSE(res); } ASSERT_FALSE(remove(tree, in)); } } } } for_each(bset, [&tree, &balance](auto idx, bool set) { // printf("idx[%zu]\n", idx); if (set) { { auto res = find(tree, idx); ASSERT_TRUE(res); ASSERT_EQ(*res, idx); } { ASSERT_TRUE(remove(tree, idx)); ASSERT_TRUE(verify(tree)); ASSERT_TRUE(balance > 0); --balance; } { auto res = find(tree, idx); ASSERT_FALSE(res); } } else { { ASSERT_FALSE(remove(tree, idx)); } const bool v = verify(tree); if (!v) { dump(tree); } ASSERT_TRUE(v); { auto res = find(tree, idx); ASSERT_FALSE(res); } } }); ASSERT_EQ(std::size_t(0), balance); ASSERT_TRUE(is_empty(tree)); } TEST(treeTest, test_rand_ins_rand_remove_bst) { random_insert_random_delete<binary::Tree<int>>(); } TEST(treeTest, test_rand_ins_rand_remove_avl) { random_insert_random_delete<avl::Tree<int>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_avl) { random_insert_random_delete<avl::rec::Tree<int>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order3) { random_insert_random_delete<sp::rec::BTree<int, 2>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order4) { random_insert_random_delete<sp::rec::BTree<int, 3>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order5) { random_insert_random_delete<sp::rec::BTree<int, 4>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order6) { random_insert_random_delete<sp::rec::BTree<int, 5>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order7) { random_insert_random_delete<sp::rec::BTree<int, 6>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order8) { random_insert_random_delete<sp::rec::BTree<int, 7>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order9) { random_insert_random_delete<sp::rec::BTree<int, 8>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order10) { random_insert_random_delete<sp::rec::BTree<int, 9>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order11) { random_insert_random_delete<sp::rec::BTree<int, 10>>(); } TEST(treeTest, test_rand_ins_rand_remove_rec_btree_order12) { random_insert_random_delete<sp::rec::BTree<int, 11>>(); }
[ "spooky.bender@gmail.com" ]
spooky.bender@gmail.com
51c7fcb7da97dd621c9d4f8214bcb4bf33f177d9
bcad67e4911cfb471a62600d203f9fa80ab39063
/GuardianCombat2/Source/Vector3/Vector3.h
eff292990a06febcacae6135fd0550a89dbc2e0f
[]
no_license
TanakaHirokiHalTokyo/GuardianCombat2
0b9aca7eae7f3c3c69219487a869ad5dd4a22e70
647115c71df0a4e88afbb8e8c5750ca3b29dea30
refs/heads/master
2020-04-03T05:15:30.083228
2019-02-20T01:26:51
2019-02-20T01:26:51
155,039,991
0
0
null
null
null
null
UTF-8
C++
false
false
459
h
#pragma once #include <d3d9.h> #include <d3dx9.h> class Vector3 { public: Vector3(); void SetFront(float x,float y,float z); void SetRight(float x,float y,float z); void SetUp(float x,float y,float z); void SetFront(D3DXVECTOR3 front); void SetRight(D3DXVECTOR3 right); void SetUp(D3DXVECTOR3 up); D3DXVECTOR3 GetFront(); D3DXVECTOR3 GetRight(); D3DXVECTOR3 GetUp(); private: D3DXVECTOR3 frontVec_; D3DXVECTOR3 rightVec_; D3DXVECTOR3 upVec_; };
[ "hiroki.tanaka53@gmail.com" ]
hiroki.tanaka53@gmail.com
ed0a8849d11ffee686eb0503be19e0458b8acb42
66ce4862f1de35f0da2cf4c83048859486432cf0
/EditorAPI/BaseFormComponent.h
70719396c62723af149682e78f20e9cc64e5e26f
[]
no_license
stavrossk/Construction-Set-Extender
4e8483d9dd99593d794fef7bf81e4a7695c9aa50
aab85ad206b47e76729939f98428fa927417c1f1
refs/heads/master
2021-01-15T23:58:20.148989
2014-07-23T11:44:41
2014-07-23T11:44:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,287
h
#pragma once #include "BSString.h" // EditorAPI: BaseFormComponent class and its derivatives. // A number of class definitions are directly derived from the COEF API; Credit to JRoush for his comprehensive decoding /* BaseFormComponents define the various 'components' that true TESForm classes can inherit, e.g. Name, Texture, Model, Weight, etc. The root of the hierarchy is the BaseFormComponent class, which exposes a common interface for Comparison, Copying, Serialization, etc. NOTE: "Form" or "Component" References refer to members that point to another form, which are tracked by the CS. */ class TESFile; class TESForm; class NiNode; struct FULL_HASH; // Usage unknown - struct {void* unk00; void* unk04; void* unk08;} class Script; class SpellItem; class TESLevSpell; class TESContainer; class TESObjectREFR; class TESActorBase; class TESObjectARMO; class TESObjectCLOT; class TESObjectWEAP; class KFModel; // (OBSE,GameTasks.h) may not be an explicitly named object class TESFaction; class TESPackage; class EnchantmentItem; class IngredientItem; class TESRace; class TESLevItem; // 04 class BaseFormComponent { public: // members ///*00*/ void** vtbl; virtual void Dtor(void); }; STATIC_ASSERT(sizeof(BaseFormComponent) == 0x4); // 0C class TESFullName : public BaseFormComponent { public: // members // /00*/ void** vtbl; /*04*/ BSString name; }; STATIC_ASSERT(sizeof(TESFullName) == 0xC); // 10 class TESDescription : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ BSString description; /*0C*/ UInt32 descDialogItem; // Dialog Control ID for description control }; STATIC_ASSERT(sizeof(TESDescription) == 0x10); // 18 class TESTexture : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ BSString texturePath; /*0C*/ UInt32 unkTexture0C; // cached image? struct {UInt32 unkA; UInt32 unkB; void* privateObj;} /*10*/ UInt32 texturePathDlgItem; // Dialog Control ID for texture path control /*14*/ UInt32 textureImageDlgItem; // Dialog Control ID for texture image control }; STATIC_ASSERT(sizeof(TESTexture) == 0x18); // 18 class TESIcon : public TESTexture { public: // no additional members }; STATIC_ASSERT(sizeof(TESIcon) == 0x18); // 18 class TESIconTree : public TESIcon { public: // no additional members }; STATIC_ASSERT(sizeof(TESIconTree) == 0x18); // 24 class TESModel : public BaseFormComponent { public: typedef NiTListBase<FULL_HASH*> ModelHashList; // probably a named class, but without it's own vtbl or RTTI info // members // /*00*/ void** vtbl; /*04*/ BSString modelPath; /*0C*/ float modelBound; /*10*/ ModelHashList modelHashList; // texture hash list ? /*20*/ UInt32 modelPathDlgItem; // Dialog Control ID for model path }; STATIC_ASSERT(sizeof(TESModel) == 0x24); // 24 class TESModelTree : public TESModel { public: // no additional members }; STATIC_ASSERT(sizeof(TESModelTree) == 0x24); // 24 class TESModelAnim : public TESModel { public: // no additional members }; STATIC_ASSERT(sizeof(TESModelAnim) == 0x24); // 0C class TESScriptableForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ Script* script; // script formid stored here during loading /*08*/ bool scriptLinked; // set once formid has been resolved into a Script* /*09*/ UInt8 scriptPad09[3]; }; STATIC_ASSERT(sizeof(TESScriptableForm) == 0xC); // 08 class TESUsesForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ UInt8 uses; /*05*/ UInt8 usesPad05[3]; }; STATIC_ASSERT(sizeof(TESUsesForm) == 0x8); // 08 class TESValueForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ SInt32 goldValue; }; STATIC_ASSERT(sizeof(TESValueForm) == 0x8); // 08 class TESHealthForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ UInt32 health; }; STATIC_ASSERT(sizeof(TESHealthForm) == 0x8); // 08 class TESWeightForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ float weight; }; STATIC_ASSERT(sizeof(TESWeightForm) == 0x8); // 08 class TESQualityForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ float quality; }; STATIC_ASSERT(sizeof(TESQualityForm) == 0x8); // 08 class TESAttackDamageForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ UInt16 damage; /*06*/ UInt16 damagePad06; }; STATIC_ASSERT(sizeof(TESAttackDamageForm) == 0x8); // 0C class TESAttributes : public BaseFormComponent { public: enum Attributes { kAttribute_Strength = 0, kAttribute_Intelligence, kAttribute_Willpower, kAttribute_Agility, kAttribute_Speed, kAttribute_Endurance, kAttribute_Personality, kAttribute_Luck, kAttribute__MAX, }; // members // /*00*/ void** vtbl; /*04*/ UInt8 attributes[8]; }; STATIC_ASSERT(sizeof(TESAttributes) == 0xC); // 14 class TESSpellList : public BaseFormComponent { public: typedef tList<SpellItem> SpellListT; typedef tList<TESLevSpell> LevSpellListT; // members // /*00*/ void** vtbl; /*04*/ SpellListT spells; /*0C*/ LevSpellListT leveledSpells; }; STATIC_ASSERT(sizeof(TESSpellList) == 0x14); // 10 class TESLeveledList : public BaseFormComponent { static bool WalkForCircularPath(std::string& Output, TESLeveledList* Check, TESLeveledList* Against); public: enum LeveledListFlags { kLevListFlag_CalcAllLevels = 0x01, // ignores max level difference, effective level is no greater than highest level in list kLevListFlag_CalcEachInCount = 0x02, // for nested lists }; // 0C struct ListEntry { /*00*/ UInt16 level; /*02*/ UInt16 pad02; /*04*/ TESForm* form; /*08*/ SInt16 count; /*0A*/ UInt16 pad0A; }; typedef tList<ListEntry> LevListT; // members // /*00*/ void** vtbl; /*04*/ LevListT levList; // list is sorted by level /*0C*/ UInt8 chanceNone; /*0D*/ UInt8 levListFlags; /*0E*/ UInt16 padLevList0E; bool CheckForCircularPaths(std::string& Output); }; STATIC_ASSERT(sizeof(TESLeveledList) == 0x10); // 10 class TESContainer : public BaseFormComponent { public: enum ContainerFlags { kContainer_Linked = 0x01, // cleared during loading, set by LinkComponent() }; // 08 struct ContentEntry { /*00*/ SInt32 count; // negative counts have some meaning ... /*04*/ TESForm* form; }; typedef tList<ContentEntry> ContentListT; /// members // /*00*/ void** vtbl; /*04*/ UInt8 containerFlags; /*05*/ UInt8 pad05[3]; /*08*/ ContentListT contents; }; STATIC_ASSERT(sizeof(TESContainer) == 0x10); // 14 class TESAnimation : public BaseFormComponent { public: typedef tList<char> AnimationListT; typedef tList<KFModel> KFModelListT; // members // /*00*/ void** vtbl; /*04*/ KFModelListT kfModelList; // temporary list of animation models used during dialog editing /*0C*/ AnimationListT animations; // animation names, dynamically allocated }; STATIC_ASSERT(sizeof(TESAnimation) == 0x14); // 20 class TESActorBaseData : public BaseFormComponent { public: enum NPCFlags { kNPCFlag_Female = 0x00000001, kNPCFlag_Essential = 0x00000002, kNPCFlag_Respawn = 0x00000008, kNPCFlag_AutoCalcStats = 0x00000010, kNPCFlag_PCLevelOffset = 0x00000080, kNPCFlag_NoLowProc = 0x00000200, kNPCFlag_NoRumors = 0x00002000, kNPCFlag_Summonable = 0x00004000, kNPCFlag_NoPersuasion = 0x00008000, kNPCFlag_CanCorpseCheck = 0x00100000, }; enum CreatureFlags { kCreatureFlag_Biped = 0x00000001, kCreatureFlag_Essential = 0x00000002, kCreatureFlag_WeaponAndShield = 0x00000004, kCreatureFlag_Respawn = 0x00000008, kCreatureFlag_Swims = 0x00000010, kCreatureFlag_Flies = 0x00000020, kCreatureFlag_Walks = 0x00000040, kCreatureFlag_PCLevelOffset = 0x00000080, kCreatureFlag_HasSounds = 0x00000100, // has a CreatureSoundArray (instead of a TESCreature* for inherited sounds) kCreatureFlag_NoLowProc = 0x00000200, kCreatureFlag_NoBloodParticle = 0x00000800, kCreatureFlag_NoBloodTexture = 0x00001000, kCreatureFlag_NoRumors = 0x00002000, kCreatureFlag_Summonable = 0x00004000, kCreatureFlag_NoHead = 0x00008000, kCreatureFlag_NoRightArm = 0x00010000, kCreatureFlag_NoLeftArm = 0x00020000, kCreatureFlag_NoCombatInWater = 0x00040000, kCreatureFlag_NoShadow = 0x00080000, kCreatureFlag_NoCorpseCheck = 0x00100000, // inverse of corresponding flag for NPCs }; // 08 struct FactionInfo { TESFaction* faction; // 00 SInt8 rank; // 04 UInt8 pad[3]; // 05 }; typedef tList<FactionInfo> FactionListT; // members // /*00*/ void** vtbl; /*04*/ UInt32 actorFlags; /*08*/ UInt16 magicka; // init to 50 /*0A*/ UInt16 fatigue; // init to 50 /*0C*/ UInt16 barterGold; /*0E*/ UInt16 level; // init to 1 /*10*/ UInt16 minLevel; // if PCLevelOffset /*12*/ UInt16 maxLevel; // if PCLevelOffset /*14*/ TESLevItem* deathItem; /*18*/ FactionListT factionList; }; STATIC_ASSERT(sizeof(TESActorBaseData) == 0x20); // 18 class TESAIForm : public BaseFormComponent { public: enum AIStats { kAIStat_Aggression = 0, kAIStat_Confidence = 1, kAIStat_Energy = 2, kAIStat_Responsibility = 3, kAIStat__MAX, }; enum ServiceFlags { kService_Weapons = 1 << 0x00, kService_Armor = 1 << 0x01, kService_Clothing = 1 << 0x02, kService_Books = 1 << 0x03, kService_Ingredients = 1 << 0x04, kService_Lights = 1 << 0x07, kService_Apparatus = 1 << 0x08, kService_Misc = 1 << 0x0A, kService_Spells = 1 << 0x0B, kService_MagicItems = 1 << 0x0C, kService_Potions = 1 << 0x0D, kService_Training = 1 << 0x0E, kService_Recharge = 1 << 0x10, kService_Repair = 1 << 0x11, }; typedef tList<TESPackage> PackageListT; // members // /*00*/ void** vtbl; /*04*/ UInt8 aiStats[4]; /*08*/ UInt32 serviceFlags; /*0C*/ UInt8 trainingSkill; // skill offset, i.e. (avCode - 12) /*0D*/ UInt8 trainingLevel; /*0E*/ UInt8 pad0E[2]; /*10*/ PackageListT packages; }; STATIC_ASSERT(sizeof(TESAIForm) == 0x18); // 10 class TESReactionForm : public BaseFormComponent { public: // 08 struct ReactionInfo { TESForm* target; SInt32 reaction; }; typedef tList<ReactionInfo> ReactionListT; // members // /*00*/ void** vtbl; /*04*/ ReactionListT reactionList; /*0C*/ UInt8 unk0C; // intialized to 6 /*0D*/ UInt8 pad0D[3]; }; STATIC_ASSERT(sizeof(TESReactionForm) == 0x10); // 0C class TESSoundFile : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ BSString soundFilePath; }; STATIC_ASSERT(sizeof(TESSoundFile) == 0xC); // C8 class TESBipedModelForm : public BaseFormComponent { public: enum SlotMask { kSlotMask_Head = /*00*/ 0x0001, kSlotMask_Hair = /*01*/ 0x0002, kSlotMask_UpperBody = /*02*/ 0x0004, kSlotMask_LowerBody = /*03*/ 0x0008, kSlotMask_Hand = /*04*/ 0x0010, kSlotMask_Foot = /*05*/ 0x0020, kSlotMask_RightRing = /*06*/ 0x0040, kSlotMask_LeftRing = /*07*/ 0x0080, kSlotMask_Amulet = /*08*/ 0x0100, kSlotMask_Weapon = /*09*/ 0x0200, kSlotMask_BackWeapon = /*0A*/ 0x0400, kSlotMask_SideWeapon = /*0B*/ 0x0800, kSlotMask_Quiver = /*0C*/ 0x1000, kSlotMask_Shield = /*0D*/ 0x2000, kSlotMask_Torch = /*0E*/ 0x4000, kSlotMask_Tail = /*0F*/ 0x8000, kSlotMask__MAX }; enum BipedModelFlags { kBipedModelFlags_HidesRings = /*00*/ 0x0001, kBipedModelFlags_HidesAmulets = /*01*/ 0x0002, kBipedModelFlags_Unk02 = /*02*/ 0x0004, kBipedModelFlags_Unk03 = /*03*/ 0x0008, kBipedModelFlags_Unk04 = /*04*/ 0x0010, kBipedModelFlags_Unk05 = /*05*/ 0x0020, kBipedModelFlags_NotPlayable = /*06*/ 0x0040, kBipedModelFlags_HeavyArmor = /*07*/ 0x0080, kBipedModelFlags_Unk08 = /*08*/ 0x0100 }; // members // /*00*/ void** vtbl; /*04*/ UInt16 slotMask; /*06*/ UInt8 bipedModelFlags; /*07*/ UInt8 pad07; /*08*/ TESModel maleBipedModel; /*2C*/ TESModel femaleBipedModel; /*50*/ TESModel maleGroundModel; /*74*/ TESModel femaleGroundModel; /*98*/ TESIcon maleIcon; /*B0*/ TESIcon femaleIcon; }; STATIC_ASSERT(sizeof(TESBipedModelForm) == 0xC8); // 10 class TESEnchantableForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ EnchantmentItem* enchantment; /*08*/ UInt16 enchantmentAmount; // only valid for weapons /*0A*/ UInt16 pad0A; /*0C*/ UInt32 enchantmentType; // init by derived class's InitializeAllComponents() fn, to values from EnchantmentItem::EnchantmentType }; STATIC_ASSERT(sizeof(TESEnchantableForm) == 0x10); // 0C class TESProduceForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ IngredientItem* ingredient; /*08*/ UInt8 springHarvestChance; /*09*/ UInt8 summerHarvestChance; /*0A*/ UInt8 fallHarvestChance; /*0B*/ UInt8 winterHarvestChance; }; STATIC_ASSERT(sizeof(TESProduceForm) == 0xC); // 08 class TESRaceForm : public BaseFormComponent { public: // members // /*00*/ void** vtbl; /*04*/ TESRace* race; }; STATIC_ASSERT(sizeof(TESRaceForm) == 0x8); // 14 class TESModelList : public BaseFormComponent { public: typedef tList<char> ModelListT; // members // /*00*/ void** vtbl; /*04*/ ModelListT modelList; /*0C*/ UInt32 unk0C; // init to 0 /*10*/ UInt32 unk10; // init to 0 }; STATIC_ASSERT(sizeof(TESModelList) == 0x14); // misc. utility components. not derived from BaseFormComponent // 04 struct RGBA { /*01*/ UInt8 r; /*02*/ UInt8 g; /*03*/ UInt8 b; /*04*/ UInt8 a; };
[ "thechaosfactory@gmail.com" ]
thechaosfactory@gmail.com
f758dea5b54306bfcdeff34861621aac317fc34c
05f5abf9f3f90320ffe231110b787e615da32814
/04-Advanced-Class-Members/homework/05-Lectures/Resource.h
d6251ba8549c5230bc2c5613ddd84571249481be
[ "Apache-2.0" ]
permissive
KostadinovK/Cpp-Advanced
0a20989b2d1e12ce576ecfa69ef04d5d874bf103
ae2ef3185baecc887dcd231dec900cf8c7da44c9
refs/heads/master
2020-03-27T05:03:21.256827
2018-11-18T14:04:21
2018-11-18T14:04:21
145,991,212
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
h
#pragma once #include <iostream> #include <string> namespace SoftUni{ class Resource{ private: std::string id; ResourceType type; std::string link; public: Resource() {} Resource(std::string id, ResourceType type, std::string link) : id(id),type(type), link(link){} std::string getId() const { return this->id; } ResourceType getType() const { return this->type; } std::string getLink() const { return this->link; } bool operator< (Resource& other) const{ return stoi(this->id) < stoi(other.id); } friend std::ostream& operator<< (std::ostream& out,const Resource& r){ out << r.id << " " << r.type << " " << r.link; return out; } friend std::istream& operator>> (std::istream& in, Resource& r){ std::string type; in >> r.id >> type >> r.link; if(type == "Demo"){ r.type = ResourceType::DEMO; }else if(type == "Presentation"){ r.type = ResourceType::PRESENTATION; }else{ r.type = ResourceType::VIDEO; } return in; } }; }
[ "kostadinovk2001@gmail.com" ]
kostadinovk2001@gmail.com
f0f144c656185d0bc7652c05857a56f66dc304d9
3a2dd77bca6dcea4b5b80c2a7ed51d630f9d749a
/Sources/BuiltInNodes/BI_BasicUINode.cpp
f0ed0d60b76ead9457ff3308fe05a2c54e0f9e5c
[ "MIT" ]
permissive
yes7rose/VisualScriptEngine
b35afdc8288488cd44bbea1955a53152d0bf39e4
3a52bc97b2d240c8b9efbd7f55454a55319b2c06
refs/heads/master
2022-12-28T06:01:45.652488
2020-10-10T18:55:47
2020-10-10T18:55:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,301
cpp
#include "BI_BasicUINode.hpp" #include "BI_UINodeLayouts.hpp" #include <cmath> namespace BI { SERIALIZATION_INFO (BasicUINode, 1); BasicUINode::BasicUINode () : BasicUINode (NE::LocString (), NUIE::Point ()) { } BasicUINode::BasicUINode (const NE::LocString& name, const NUIE::Point& position) : BasicUINode (name, position, UINodeLayoutPtr (new HeaderWithSlotsLayout ())) { } BasicUINode::BasicUINode (const NE::LocString& name, const NUIE::Point& position, const UINodeLayoutPtr& layout) : BasicUINode (name, position, layout, NUIE::InvalidIconId) { } BasicUINode::BasicUINode (const NE::LocString& name, const NUIE::Point& position, const UINodeLayoutPtr& layout, const NUIE::IconId& iconId) : NUIE::UINode (name, position), layout (layout), iconId (iconId) { } BasicUINode::~BasicUINode () { } bool BasicUINode::HasIconId () const { return iconId != NUIE::InvalidIconId; } const NUIE::IconId& BasicUINode::GetIconId () const { return iconId; } void BasicUINode::SetIconId (const NUIE::IconId& newIconId) { iconId = newIconId; } bool BasicUINode::HasFeature (const FeatureId& featureId) const { return nodeFeatureSet.HasFeature (featureId); } const NodeFeaturePtr& BasicUINode::GetFeature (const FeatureId& featureId) const { return nodeFeatureSet.GetFeature (featureId); } NE::Stream::Status BasicUINode::Read (NE::InputStream& inputStream) { NE::ObjectHeader header (inputStream); NUIE::UINode::Read (inputStream); iconId.Read (inputStream); nodeFeatureSet.Read (inputStream); return inputStream.GetStatus (); } NE::Stream::Status BasicUINode::Write (NE::OutputStream& outputStream) const { NE::ObjectHeader header (outputStream, serializationInfo); NUIE::UINode::Write (outputStream); iconId.Write (outputStream); nodeFeatureSet.Write (outputStream); return outputStream.GetStatus (); } void BasicUINode::OnFeatureChange (const FeatureId&, NE::EvaluationEnv&) const { } void BasicUINode::RegisterParameters (NUIE::NodeParameterList& parameterList) const { UINode::RegisterParameters (parameterList); nodeFeatureSet.RegisterParameters (parameterList); } void BasicUINode::RegisterCommands (NUIE::NodeCommandRegistrator& commandRegistrator) const { UINode::RegisterCommands (commandRegistrator); nodeFeatureSet.RegisterCommands (commandRegistrator); } bool BasicUINode::RegisterFeature (const NodeFeaturePtr& newFeature) { nodeFeatureSet.AddFeature (newFeature->GetId (), newFeature); return true; } NUIE::EventHandlerResult BasicUINode::HandleMouseClick (NUIE::NodeUIEnvironment& env, const NUIE::ModifierKeys& modifierKeys, NUIE::MouseButton mouseButton, const NUIE::Point& position, NUIE::UINodeCommandInterface& commandInterface) { return layout->HandleMouseClick (*this, env, modifierKeys, mouseButton, position, commandInterface); } NUIE::EventHandlerResult BasicUINode::HandleMouseDoubleClick (NUIE::NodeUIEnvironment& env, const NUIE::ModifierKeys& modifierKeys, NUIE::MouseButton mouseButton, const NUIE::Point& position, NUIE::UINodeCommandInterface& commandInterface) { return HandleMouseClick (env, modifierKeys, mouseButton, position, commandInterface); } void BasicUINode::UpdateNodeDrawingImage (NUIE::NodeUIDrawingEnvironment& env, NUIE::NodeDrawingImage& drawingImage) const { layout->Draw (*this, env, drawingImage); } }
[ "viktorkovacs@gmail.com" ]
viktorkovacs@gmail.com
91859a4372d1aa25a16a5b4aa691779c694afdae
7fd5e6156d6a42b305809f474659f641450cea81
/boost/range/detail/extract_optional_type.hpp
afb970babee1e8b0fb5c0b6eddaedab71ab29341
[]
no_license
imos/icfpc2015
5509b6cfc060108c9e5df8093c5bc5421c8480ea
e998055c0456c258aa86e8379180fad153878769
refs/heads/master
2020-04-11T04:30:08.777739
2015-08-10T11:53:12
2015-08-10T11:53:12
40,011,767
8
0
null
null
null
null
UTF-8
C++
false
false
2,066
hpp
// Boost.Range library // // Copyright Arno Schoedl & Neil Groves 2009. // Use, modification and distribution is subject to 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) // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_DETAIL_EXTRACT_OPTIONAL_TYPE_HPP_INCLUDED #define BOOST_RANGE_DETAIL_EXTRACT_OPTIONAL_TYPE_HPP_INCLUDED #if defined(_MSC_VER) # pragma once #endif #include "boost/config.hpp" #include "boost/preprocessor/cat.hpp" #include "boost/mpl/has_xxx.hpp" #if !defined(BOOST_MPL_CFG_NO_HAS_XXX) // Defines extract_some_typedef<T> which exposes T::some_typedef as // extract_some_typedef<T>::type if T::some_typedef exists. Otherwise // extract_some_typedef<T> is empty. #define BOOST_RANGE_EXTRACT_OPTIONAL_TYPE( a_typedef ) \ BOOST_MPL_HAS_XXX_TRAIT_DEF(a_typedef) \ template< typename C, bool B = BOOST_PP_CAT(has_, a_typedef)<C>::value > \ struct BOOST_PP_CAT(extract_, a_typedef) \ {}; \ template< typename C > \ struct BOOST_PP_CAT(extract_, a_typedef)< C, true > \ { \ typedef BOOST_DEDUCED_TYPENAME C::a_typedef type; \ }; #else #define BOOST_RANGE_EXTRACT_OPTIONAL_TYPE( a_typedef ) \ template< typename C > \ struct BOOST_PP_CAT(extract_, a_typedef) \ { \ typedef BOOST_DEDUCED_TYPENAME C::a_typedef type; \ }; #endif #endif // include guard
[ "git@imoz.jp" ]
git@imoz.jp
fd094640ebd0e22b425eb20b2831361a7db66307
fbdeda54ff3d07d7e4923391a4b49ab0bd6c1868
/CSE/libInstrument/PM_rsnrp.cpp
63b84dfe4ebba1fa40da9b10999931db3a49b6f1
[]
no_license
Andydingbing/git
86e4267d90577b616befedef4ea781ea18cd02e7
ff6b4daaa14c9e6cae0df4c3f2372afe7a4ae8bd
refs/heads/master
2016-09-01T12:56:17.099418
2016-04-30T08:14:54
2016-04-30T08:14:54
47,169,255
2
0
null
null
null
null
UTF-8
C++
false
false
3,707
cpp
// PM_rsnrp.cpp: implementation of the PM_rsnrp class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "PM_rsnrp.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// #if defined NRP_DEBUG #define NRP_CHECK(func) \ do { \ ViStatus ret; \ char errMsg[256]; \ ZeroMemory(errMsg, 256); \ if ((ret = (func)) != 0) { \ FILE *fp; \ fopen_s(&fp, "C:\\nrp.log", "a"); \ rsnrp_error_message(m_hVisa, ret, errMsg); \ fprintf(fp, "F : %s\n\t%s\n", #func, errMsg); \ } else { \ printf("T : %s\n", #func); \ } \ } while (0); #else #define NRP_CHECK(func) func; #endif PM_rsnrp::PM_rsnrp() : m_isInitialized(false) { } PM_rsnrp::~PM_rsnrp() { // Close(); m_hVisa = 0; } bool PM_rsnrp::Init(ViRsrc rsrcName) { // char sensorString[256]; uint32_t usbid = 0, serialNumber = 0; ViBoolean isMeasComplete; // sscanf_s(rsrcName, "RSNRP::%x::%d::INSTR", &usbid, &serialNumber); // if (usbid == 0 || serialNumber == 0) { // return false; // } // ZeroMemory(sensorString, 256); // sprintf_s(sensorString, 256, "USB::0x0AAD::0x%04x::%d", usbid, serialNumber); // NRP_CHECK(rsnrpz_init(sensorString, FALSE, FALSE, &m_hVisa)); NRP_CHECK(rsnrpz_init(rsrcName, FALSE, FALSE, &m_hVisa)); Sleep(100); // do { // Sleep (50); // rsnrpz_chan_isMeasurementComplete(m_hVisa, 1, &isMeasComplete); // } while ((isMeasComplete == VI_FALSE)); m_isInitialized = true; return true; } bool PM_rsnrp::Reset() { ViBoolean isMeasComplete; NRP_CHECK(rsnrpz_status_preset(m_hVisa)); NRP_CHECK(rsnrpz_avg_setAutoEnabled(m_hVisa, 1, VI_FALSE)); NRP_CHECK(rsnrpz_avg_setCount(m_hVisa, 1, 3)); NRP_CHECK(rsnrpz_trigger_setSource(m_hVisa, 1, RSNRPZ_TRIGGER_SOURCE_IMMEDIATE)); // NRP_CHECK(rsnrp_system_setSpeed(m_hVisa, RSNRP_SPEED_FAST)); // this always return "The given session or object reference is invalid" // rsnrp_system_setSpeed(m_hVisa, RSNRP_SPEED_FAST); NRP_CHECK(rsnrpz_reset(m_hVisa)); NRP_CHECK(rsnrpz_chans_initiate(m_hVisa)); do { Sleep (50); NRP_CHECK(rsnrpz_chan_isMeasurementComplete(m_hVisa, 1, &isMeasComplete)); } while ((isMeasComplete == VI_FALSE)); Sleep(100); return true; } bool PM_rsnrp::SetFrequency(double freqHz) { NRP_CHECK(rsnrpz_chan_setCorrectionFrequency(m_hVisa, 1, freqHz)); return true; } bool PM_rsnrp::GetPwr(double & dbm) { double nrpResult; ViBoolean isMeasComplete; NRP_CHECK(rsnrpz_chan_initiate(m_hVisa, 1)); do { Sleep (50); NRP_CHECK(rsnrpz_chan_isMeasurementComplete(m_hVisa, 1, &isMeasComplete)); } while ((isMeasComplete == VI_FALSE)); NRP_CHECK(rsnrpz_meass_readMeasurement(m_hVisa, 1, 10000, &nrpResult)); dbm = 10 * log10(fabs(nrpResult * 1000)); return true; } bool PM_rsnrp::GetPwr(double freqHz,double &dbm) { if (!SetFrequency(freqHz)) { return false; } if (!GetPwr(dbm)) { return false; } return true; } bool PM_rsnrp::Close() { if (m_hVisa != 0) { rsnrpz_status_preset(m_hVisa); rsnrpz_CloseSensor(m_hVisa, 1); rsnrpz_close(m_hVisa); m_hVisa = 0; } return true; }
[ "307841640@qq.com" ]
307841640@qq.com
47da2d84aba7c932c0cca06efcf90847e4a8a997
77102e7daee558d1f4bde3a49f5e7db794c60e87
/Tugas 2/4.cpp
11b7ecef0d64884ad9bbbc6d1905b86db5264b76
[]
no_license
puls1r/TugasAnalgo
af54ca179306c59893a8b6966613c81c1f5adde9
fc837e1aff7f620a85ee8e2937034ede6d4e2993
refs/heads/master
2022-02-21T10:28:48.186854
2019-04-30T19:22:47
2019-04-30T19:22:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
/* Nama : Rafi Chandra Kelas : A NPM : 140810170037 Nama Program : Insertion */ #include <iostream> #include <conio.h> using namespace std; int data[100],data2[100],n; void insertion_sort() { int temp,i,j; for(i=1;i<=n;i++){ temp = data[i]; j = i -1; while(data[j]>temp && j>=0){ data[j+1] = data[j]; j--; } data[j+1] = temp; } } int main() { cout << "\n=================================="<<endl; cout<<"Masukkan Jumlah Data : "; cin>>n; cout<<endl; cout << "\n----------------------------------" << endl; for(int i=1;i<=n;i++) { cout<<"Masukkan data ke-"<<i<<" : "; cin>>data[i]; data2[i]=data[i]; } cout << "\n----------------------------------" << endl; insertion_sort(); cout<<"\nData Setelah di Sort : "<<endl; for(int i=1; i<=n; i++) { cout<<data[i]<<" "; } cout << "\n=================================="<<endl; getch(); }
[ "whatthefapmc@gmail.com" ]
whatthefapmc@gmail.com
7c622695d27f6fc52e6cd50bc0f998359b0a49dd
83b9cf5b89f869d8ae2e50b820909c3a3ba82d05
/1135 Is It A Red-Black Tree.cpp
e76cd45326f7cce15d3b47be9b88d7dc2e9e3fba
[]
no_license
YingChengJun/PAT-Code
5679607d15e70a86034e6abe9983f437b642cc57
17c90a8466978ea02c184702b489704ad77472f6
refs/heads/master
2022-12-08T12:11:06.178770
2020-08-27T15:57:31
2020-08-27T15:57:31
280,049,765
4
0
null
null
null
null
UTF-8
C++
false
false
1,945
cpp
#include <cstdio> #include <algorithm> using namespace std; typedef enum {BLACK, RED} Color; struct TreeNode { Color color; int val; int bh = 0; TreeNode* left = NULL; TreeNode* right = NULL; TreeNode(int v) { if (v < 0) { color = RED; val = -v; } else { color = BLACK; val = v; } } }; Color getColor(TreeNode* root) { if (root == NULL) return BLACK; return root->color; } void makeTree(TreeNode* &root, int val) { if (root == NULL) { root = new TreeNode(val); return; } else if (abs(val) < root->val) { makeTree(root->left, val); } else if (abs(val) > root->val) { makeTree(root->right, val); } } void dfs(TreeNode* root, int curBlack, int &totBlack, bool &flag) { if (!flag) return; if (root == NULL) { if (totBlack == -1) { totBlack = curBlack; } else if (totBlack != curBlack) { flag = false; } return; } if (root->color == RED && (getColor(root->left) == RED || getColor(root->right) == RED)) { flag = false; return; } curBlack = root->color == BLACK ? curBlack + 1 : curBlack; dfs(root->left, curBlack, totBlack, flag); dfs(root->right, curBlack, totBlack, flag); } bool isRBTree(TreeNode* root) { if (root->color == RED) return false; int totBlack = -1; bool flag = true; dfs(root, 0, totBlack, flag); return flag; } int main() { int query, n, num; scanf("%d", &query); for (int i = 0; i < query; i++) { scanf("%d", &n); TreeNode* root = NULL; for (int j = 0; j < n; j++) { scanf("%d", &num); makeTree(root, num); } printf("%s\n", isRBTree(root) ? "Yes" : "No"); } }
[ "1052257712@qq.com" ]
1052257712@qq.com
818765c83ecae6f431368e7e5ee11d9c2128d8ef
102931367f077635ed8139db230bfa62c72622bb
/URI/Strings/2174.cpp
63d1ee27a13704743a24f992fa89b6c5fb701c05
[]
no_license
PedroHMNobrega/Programming-Problems
5fda516e497be78c2d7254ff0034f9a08bef4278
a61fe31316a2c6f18883e2a5cf9a09a3a62a2864
refs/heads/master
2021-07-22T02:24:02.911540
2021-01-19T00:07:30
2021-01-19T00:07:30
235,905,835
1
0
null
null
null
null
UTF-8
C++
false
false
872
cpp
//Coleção de Pomekon //Assunto: String/ Set; #include <bits/stdc++.h> #define fi first #define se second #define pb push_back #define all(x) x.begin(), x.end() #define rall(x) x.rbegin(), x.rend() #define loop(i, a, b) for(int i = a; i < b; i++) #define loopBack(i, a, b) for(int i = a; i >= b; i--) #define INF INT_MAX #define LINF LLONG_MAX #define DINF DBL_MAX #define MAX 1000005 #define MOD 1000000007 using namespace std; typedef long long int ll; typedef pair<int, int> ii; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); int n; string s; set<string> pokes; cin >> n; while(n--) { cin >> s; loop(i, 0, s.size()) s[i] = tolower(s[i]); pokes.insert(s); } printf("Falta(m) %d pomekon(s).\n", (151 - pokes.size())); }
[ "pedrohmnobrega@gmail.com" ]
pedrohmnobrega@gmail.com
c812f7baaf748bd1a19ce92ac8e80b1d0342115e
711dd4025ef549cf8ebb1f616372fe971d5ec5a8
/src/quickSort.cpp
97f4ff516fc90288f9f6cd1f6d4e0734097722ac
[]
no_license
Nammur/projetoEDB1
2f901acc622ed7b23af5bd847432ec1f20af625d
3ef1ea6067932f830b9c0e728079aa8282c275ff
refs/heads/master
2020-07-29T01:59:13.205158
2019-09-23T21:36:17
2019-09-23T21:36:17
209,625,365
3
0
null
null
null
null
UTF-8
C++
false
false
995
cpp
#include "../include/quickSort.h" #include <chrono> //Implementacao do QuickSort int quickPartition (int *Array, int begin, int tamanhoVetor){ // Pivot para particionamento int pivot = Array[tamanhoVetor]; // Indice para o menor elemento int i = (begin - 1); // Percorrer todo o vetor for (int j = begin; j <= tamanhoVetor - 1; j++){ // Condional para testar se o elemento é menor // que o pivot if (Array[j] < pivot){ i++; std::swap(Array[i], Array[j]); } } // Troca dos elementos std::swap(Array[i + 1], Array[tamanhoVetor]); return (i + 1); } void quickSort(int *Array, int begin, int tamanhoVetor){ if (begin < tamanhoVetor){ int pi = quickPartition(Array, begin, tamanhoVetor); // Particionamento do vetor quickSort(Array, begin, pi - 1); quickSort(Array, pi + 1, tamanhoVetor); } } // Fim QuickSort
[ "noreply@github.com" ]
noreply@github.com
d591866ae8370d5ae6dc54ea4e30dbb88558b700
fa21a16149fec2b2a04647d69674f5b8a228bf15
/Assets/AssetSetManager.cpp
51b89bf56aa2aadf5b9fabc8daa02c3feac8d7d1
[ "MIT" ]
permissive
yorung/XLE
3581cbe3ed455b8a27e97ed615e1f6f96d42ae85
083ce4c9d3fe32002ff5168e571cada2715bece4
refs/heads/master
2020-03-29T10:07:35.485095
2015-08-29T07:51:02
2015-08-29T07:51:02
30,400,035
1
0
null
null
null
null
UTF-8
C++
false
false
2,138
cpp
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "AssetSetManager.h" #include "../Utility/Threading/ThreadingUtils.h" #include "../Utility/IteratorUtils.h" #include <vector> #include <memory> #include <assert.h> namespace Assets { IAssetSet::~IAssetSet() {} class AssetSetManager::Pimpl { public: std::vector<std::pair<size_t, std::unique_ptr<IAssetSet>>> _sets; unsigned _boundThreadId; }; IAssetSet* AssetSetManager::GetSetForTypeCode(size_t typeCode) { auto i = LowerBound(_pimpl->_sets, typeCode); if (i != _pimpl->_sets.end() && i->first == typeCode) return i->second.get(); return nullptr; } void AssetSetManager::Add(size_t typeCode, std::unique_ptr<IAssetSet>&& set) { auto i = LowerBound(_pimpl->_sets, typeCode); assert(i == _pimpl->_sets.end() || i->first != typeCode); _pimpl->_sets.insert( i, std::make_pair( typeCode, std::forward<std::unique_ptr<IAssetSet>>(set))); } void AssetSetManager::Clear() { for (auto i=_pimpl->_sets.begin(); i!=_pimpl->_sets.end(); ++i) { i->second->Clear(); } } void AssetSetManager::LogReport() { for (auto i=_pimpl->_sets.begin(); i!=_pimpl->_sets.end(); ++i) { i->second->LogReport(); } } bool AssetSetManager::IsBoundThread() const { return _pimpl->_boundThreadId == Threading::CurrentThreadId(); } unsigned AssetSetManager::GetAssetSetCount() { return unsigned(_pimpl->_sets.size()); } const IAssetSet* AssetSetManager::GetAssetSet(unsigned index) { return _pimpl->_sets[index].second.get(); } AssetSetManager::AssetSetManager() { auto pimpl = std::make_unique<Pimpl>(); pimpl->_boundThreadId = Threading::CurrentThreadId(); _pimpl = std::move(pimpl); } AssetSetManager::~AssetSetManager() {} }
[ "djewsbury@xlgames.com" ]
djewsbury@xlgames.com
524941911244e9f2e9a837110aeca0a58498c258
a44e9c993fb548535221378ad170adfecfc21fb8
/DataStructure/EightQueen/EightQueen/main.cpp
7ea95a0013461d0fd6891fe4396177e66a925f89
[]
no_license
GochenRyan/Algorithm
15c985fbe0582c5f1c22e3cdbd13547dd931ef6e
d04c80b9cb6697dde2cd5e5bf1e1fd4cfcd9fa3d
refs/heads/master
2022-12-22T05:47:23.673447
2020-09-27T06:01:52
2020-09-27T06:01:52
107,021,905
1
0
null
null
null
null
WINDOWS-1256
C++
false
false
914
cpp
#include <iostream> using namespace std; static int vis[3][15]={0}; static int gEightQueen[8]={0}; static int tot=0; //تن³ِ void print(){ int outer; int inner; for (outer=0;outer<8;outer++){ for(inner=0;inner<gEightQueen[outer];inner++) cout<<"* "; cout<<"# "; for(inner=gEightQueen[outer]+1;inner<8;inner++) cout<<"* "; cout<<endl; } cout<<"====================================="<<endl; } void search(int cur){ if(cur==8){ print(); tot++; cout<<tot<<endl; } else for(int i=0;i<8;i++){ if(!vis[0][i] && !vis[1][cur+i] && !vis[2][7-i+cur]){ gEightQueen[cur]=i; vis[0][i]=vis[1][cur+i]=vis[2][7-i+cur]=1; search(cur+1); vis[0][i]=vis[1][cur+i]=vis[2][7-i+cur]=0; } } } int main(){ search(0); cout<<"total="<<tot<<endl; return 0; }
[ "rangaocheng@outlook.com" ]
rangaocheng@outlook.com
8496f24cafbb6873711ca9d583206b9ae05db535
b6a5e07b7fcc99f21f39ea7c68f4dbf23d087c52
/QtRenCode/main.cpp
c5f0b9535c2bedcf3a0884325f070e326e752acd
[]
no_license
wenwushq/QRenCodeLib
dd15c8ecf0dbb10ae46fb84e9bd5066ebedb6269
e8a7e275759cea3b5d0096fe32ee5ce9438cdae6
refs/heads/main
2022-12-25T22:39:52.531467
2020-10-10T06:41:14
2020-10-10T06:41:14
302,831,743
1
0
null
null
null
null
UTF-8
C++
false
false
189
cpp
#include "QtRenCode.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QtRenCode w; w.show(); return a.exec(); }
[ "noreply@github.com" ]
noreply@github.com
c7a3cf52f4d18ba3ab14ffd7be9d3cf9e99f8592
f851bc59f4ab3906836aa3ce20294e49622477d9
/source/util/Timer.h
2adacac4e667a678306bf2b072258053e7ae91b4
[]
no_license
AlexKoukoulas2074245K/Hardcore2D
8ab16f39f58165b0a07d82f3e166f4423e3d5ba1
5951b63c643277692b108ad3784a615527e0df20
refs/heads/master
2020-04-15T00:49:14.259427
2019-03-19T20:15:05
2019-03-19T20:15:05
164,253,069
1
0
null
null
null
null
UTF-8
C++
false
false
1,304
h
// // Timer.h // Hardcore2D // // Created by Alex Koukoulas on 09/03/2019. // #ifndef Timer_h #define Timer_h #include <functional> class Timer final { public: using TimerTickCallback = std::function<void()>; Timer(const float period, TimerTickCallback timerTickCallback) : mPeriod(period) , mTimerTickCallback(timerTickCallback) , mIsRunning(true) , mTimeCounter(mPeriod) { } inline float GetTimerValue() { return mTimeCounter; } inline void SetTimerTickCallback(const TimerTickCallback timerTickCallback) { mTimerTickCallback = timerTickCallback; } inline void Update(const float dt) { if (!mIsRunning) { return; } mTimeCounter -= dt; if (mTimeCounter <= 0.0f) { mTimeCounter = mPeriod; mTimerTickCallback(); } } inline void Pause() { mIsRunning = false; } inline void Resume() { mIsRunning = true; } inline void Reset() { mTimeCounter = mPeriod; } private: const float mPeriod; TimerTickCallback mTimerTickCallback; bool mIsRunning; float mTimeCounter; }; #endif /* Timer_h */
[ "alex.koukoulas@king.com" ]
alex.koukoulas@king.com
42f791f717fefeb13166c02bbadd087d9ccca08f
1749b2c4b996e3c24b56b22196f987ed84ada8e1
/myqlinklist.cpp
e7f0ea10b5ac0658cd075a8c50b8b09411972e54
[]
no_license
Streeeeck/qt-home-work-1
9f9614ced517c1028dedee31d58ce518e9bacd3b
6d90ef384cc39ae9d090228fa4ae22d0eaf99256
refs/heads/master
2023-05-02T08:00:47.716896
2021-05-28T15:25:11
2021-05-28T15:25:11
371,743,910
2
0
null
null
null
null
UTF-8
C++
false
false
2,430
cpp
#include "myqlinklist.h" MyQLinkList::MyQLinkList(QStandardItemModel *_model) { model = _model; } void MyQLinkList::push(Storage st) { this->push_back(st); int row = model->rowCount(); item = new QStandardItem(QString::number(st.getId())); model->setItem(row, 0, item); item = new QStandardItem(QString::number(st.getCapacity())); model->setItem(row, 1, item); item = new QStandardItem(st.getCity()); model->setItem(row, 2, item); item = new QStandardItem(st.getAddress()); model->setItem(row, 3, item); model->setHeaderData(0, Qt::Horizontal, QObject::tr("Id")); model->setHeaderData(1, Qt::Horizontal, QObject::tr("Capacity")); model->setHeaderData(2, Qt::Horizontal, QObject::tr("City")); model->setHeaderData(3, Qt::Horizontal, QObject::tr("address")); } void MyQLinkList::del(int _id) { model->removeRows(_id,1); QLinkedList<Storage>::iterator it = this->begin(); for(int i = 0;i < _id; i++) { ++it; } it = this->erase(it); } void MyQLinkList::clean() { this->clear(); } void MyQLinkList::edit(Storage st, int _id) { QLinkedList<Storage>::iterator it = this->begin(); for(int i = 0;i < _id; i++) { ++it; } it->setId(st.getId()); it->setCity(st.getCity()); it->setCapacity(st.getCapacity()); it->setAddress(st.getAddress()); item = new QStandardItem(QString::number(st.getId())); model->setItem(_id,0,item); item = new QStandardItem(QString::number(st.getCapacity())); model->setItem(_id,1,item); item = new QStandardItem(st.getCity()); model->setItem(_id,2,item); item = new QStandardItem(st.getAddress()); model->setItem(_id,3,item); } Storage MyQLinkList::getData(int _id) { QLinkedList<Storage>::iterator it = this->begin(); for(int i = 0;i < _id; i++) { ++it; } return Storage(it->getId(),it->getCapacity(),it->getCity(),it->getAddress()); } QJsonArray MyQLinkList::toJSON() { QJsonArray dataArray; QLinkedList<Storage>::iterator it = this->begin(); while (it != this->end()) { QJsonObject textObject; textObject["address"] = it->getAddress(); textObject["city"] = it->getCity(); textObject["capacity"] = QString::number(it->getCapacity()); textObject["id"] = QString::number(it->getId()); dataArray.append(textObject); ++it; } return dataArray; }
[ "52788224+Streeeeck@users.noreply.github.com" ]
52788224+Streeeeck@users.noreply.github.com
7d4e4bb5a9d022cbd3a056ab8f18cb08bf1a9261
1f070217eed4fb22b013fee7146760e79df2188b
/ZombieShooter/Zombie.cpp
3cc81dfe4e94fb6b665a22e7695b5f5c8eb5b399
[]
no_license
edlym96/GameEngine
caf19776b84705d707217fb33a806e7dc182084f
9ef59cf8fb3b6de579bc7b06d365b706cb6714a1
refs/heads/master
2020-04-29T01:11:37.705484
2019-08-22T00:12:31
2019-08-22T00:12:31
175,722,405
1
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
#include "Zombie.h" Zombie::Zombie() { } Zombie::~Zombie() { } void Zombie::init(float speed, glm::vec2 pos) { m_speed = speed; m_position = pos; m_health = 150; m_color = DawnEngine::ColorRGBA8(0, 160, 0, 255); /*_color.r = 0; _color.g = 160; _color.b = 0; _color.a = 255;*/ } void Zombie::update(const std::vector<std::string>& levelData, std::vector<Human*> humans, std::vector<Zombie*> zombies, float deltaTime) { Human* closestHuman = m_getNearestHuman(humans); if (closestHuman) { glm::vec2 direction = glm::normalize(closestHuman->getPosition() - m_position); m_position += direction * m_speed*deltaTime; } collideWithLevel(levelData); } Human* Zombie::m_getNearestHuman(std::vector<Human*> humans) { Human* closestHuman = nullptr; float smallestDistance = 99999999.0f; for (int i = 0; i < humans.size(); ++i) { glm::vec2 distVec = humans[i]->getPosition() - m_position; float distance = glm::length(distVec); if (distance < smallestDistance) { smallestDistance = distance; closestHuman = humans[i]; } } return closestHuman; }
[ "edlym96@hotmail.com" ]
edlym96@hotmail.com
0b62e1f9ca23450b579eeb9fa4a8c1ea9f698051
b004200019382d75a8574685a4566294a4008a6a
/Ajay.cpp
b13db055dc1f2c73b1be361fe7c9ff87b12eff8d
[]
no_license
Ajay-191883/Power-Function
5ccd779fe1044e791b8790807cfc5f3da1792b9f
dfc91fa21fe0aa4ead36d799e3e6de1c955d74a2
refs/heads/main
2023-03-20T17:23:42.582734
2021-03-03T12:21:19
2021-03-03T12:21:19
344,112,407
0
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
#include <iostream> #include <math.h> using namespace std; double m, totalValue; int temp; void inputValue(){ cout<<"Enter base value : "<<endl; cin>>m; cout<<"Enter power value (Enter 0 if you want to omit it, square of base value will be the final value) : "<<endl; cin>>temp; } double powerValue(double m, int n = 2) { double value; value = pow(m,n); return value; } void printValue(){ cout<<m<<" raised to the power "<<temp<<" becomes : "<<totalValue; } int main() { inputValue(); if(temp == 0){ totalValue = powerValue(m); temp = 2; }else { totalValue = powerValue(m, temp); } printValue(); }
[ "noreply@github.com" ]
noreply@github.com
af14f55425551a519747ec378565cd773f14aa82
666f8a47e10fe05bfe1b19775936b95ab9db8259
/trees_graph/getLevelofNode.cpp
9c3b11a8cfcb2afb3b8d561ddbbc173038bc5043
[]
no_license
invrev/ctci
a92dc4dde0647dd9a9ac77879a0e55f18745beb1
15f13dbfdbf83fec3beb63eda37c6cf8228f6c8a
refs/heads/master
2021-01-16T18:30:01.791455
2015-03-24T18:56:20
2015-03-24T18:56:20
28,522,615
0
0
null
null
null
null
UTF-8
C++
false
false
538
cpp
#include<iostream> using namespace std; struct BTNode { }; //Find the level of the node from binary tree w.r.t. root //return 0 means no node found int getLevelOfNode (BTNode *root,BTNode *node,int level) { if (!root) { return 0; } if (root == node) { return level; } int retL = getLevelNode (root,node->left,level+1); if (retL != 0) { return retL; } retL = getLevelNode (root,node->right,level+1); return retL; } int level = getLevelOfNode (root,node,1);
[ "vikramsi@buffalo.edu" ]
vikramsi@buffalo.edu
974247f6b2d85c3681811cd78cbde9b5c37d8513
4562549b0e909c9fd14436eb2b3673075cad8675
/StacksAndQueues/stacks_and_queues_9_9.cc
4f22a12fc38343f8b91af62cb0463d4e3653821a
[]
no_license
operationoverlord/EPI
e4a591a3f2b8b8b60309da1b2a82f970cb659ad3
d3093f95f773a49fff2336b919c2f9a6b11b3386
refs/heads/master
2021-01-21T14:52:56.695236
2017-09-24T19:02:56
2017-09-24T19:02:56
95,350,301
0
0
null
null
null
null
UTF-8
C++
false
false
868
cc
#include <iostream> #include <stack> using namespace std; class Q { private: stack<int> s1; stack<int> s2; void switch_stack(); public: void pop(); void push(int e); int front(); }; void Q::push(int e) { s1.push(e); } void Q::pop() { if(s1.empty() && s2.empty()) { cout << "the queue is empty!\n"; } else { switch_stack(); s2.pop(); } } void Q::switch_stack() { if(s2.empty()) { while(!s1.empty()) { s2.push(s1.top()); s1.pop(); } } } int Q::front() { int result = -1; if(s1.empty() && s2.empty()) { cout << "empty queue!\n"; } else { switch_stack(); result = s2.top(); } return result; } int main() { // your code goes here Q q; q.push(1); q.push(2); q.push(3); q.push(4); cout << q.front() << "\n"; q.push(5); q.push(6); q.pop(); q.pop(); q.pop(); q.pop(); cout << q.front() << "\n"; return 0; }
[ "mayurmohite1433@gmail.com" ]
mayurmohite1433@gmail.com
c2a45e78ab5a30c759593daa4d26958ff35f6cf9
d03aa19edf11eca56f7515e5280750e8cff549d7
/Bt_mang/BT_level1/b3_xoa_trung.cpp
bbd1e223c856dfc1c71353555e94343861db607d
[]
no_license
vidongls/Cbasic
477b64086474d06077f6004a749fd1974fc7e19f
9e796187f369a4bb697ff29e0c47e69b872ecd39
refs/heads/main
2023-05-03T07:57:40.620503
2021-05-16T13:55:30
2021-05-16T13:55:30
349,915,107
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
cpp
#include<iostream> #define MAX 100 using namespace std; void nhap(int a[], int n) ; void xuat(int a[], int n); void xoa(int a[], int &n, int vt); void xoa_trung(int a[], int &n); int main() { int a[MAX]; int n; do { cout << "Nhap sl pt cua mang: "; cin >> n; } while (n <= 0 || n > MAX); nhap(a, n); cout << "==========Xuat===========" << endl; xuat(a, n); xoa_trung(a,n); cout << "==========Sau khi xoa !=========="<<endl; xuat(a, n); } void nhap(int a[], int n) { cout << "\t\t=========== Moi nhap =========" << endl; for (int i = 0; i < n; i++) { cout << "Nhap phan tu thu " << i+1 << " :"; cin >> a[i]; } } void xuat(int a[], int n) { for (int i = 0; i < n; i++) { cout << "Phan tu thu " << i+1 << " :"<<a[i]<<endl; } } void xoa(int a[], int &n, int vt) { for (int i = vt; i < n-1; i++) { a[i] = a[i + 1]; } n--; } void xoa_trung(int a[], int &n) { for (int i = 0; i < n; i++) { for (int j = i+1; j < n; j++) { if (a[i]==a[j]) { xoa(a, n, j); j--; } } } }
[ "vidongls12345@gmail.com" ]
vidongls12345@gmail.com
9cbcc5e3fb661c8f6f0a173f6e82710bfc2caee1
5235612e47d976edd8b5285c39e94521486ec157
/uppsrc/TCtrlLib/Help/DlgHelp.cpp
9009a3d3a51bdc94476ce8717b547e3caf38d820
[ "BSD-2-Clause" ]
permissive
15831944/uppgit
139e40445a4044a908b46716c4fba77046dc72b1
f956ab4f48df2149c3133d4f248fe37a501f43ff
refs/heads/master
2022-04-08T19:52:15.750184
2012-10-02T13:39:19
2012-10-02T13:39:19
null
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
46,466
cpp
#if 0 #include "TCtrlLibHelp.h" #pragma hdrstop #pragma BLITZ_APPROVE #include <Draw/PixelUtil.h> #define LAYOUTFILE <TCtrlLib/Help/DlgHelp.lay> #include <CtrlCore/lay.h> class DisplayTopicName : public Display { public: DisplayTopicName() {} virtual void Paint(Draw& draw, const Rect& rc, const Value& v, Color i, Color p, dword style) const { if(!HelpTopicGet(v).added) i = LtRed; RichTextDisplay().Paint(draw, rc, HelpTopicGet(v).GetTitle(), i, p, style); } }; static bool RawTopicMatch(const char *pattern, const char *file, const char *& endptr) { for(char c; c = *pattern++;) if(c == '*') { do if(RawTopicMatch(pattern, file, endptr)) return true; while(*file++); endptr = pattern; return false; } else if(c == '?') { if(*file++ == 0) { endptr = pattern - 1; return false; } } else if(ToLower(c) != ToLower(*file++)) { endptr = pattern - 1; return false; } endptr = file; return true; } static const char *FindTopicMatch(const char *pattern, const char *file, String& cont) { const char *endptr; while(!RawTopicMatch(pattern, file, endptr)) { while(!(file[0] == '/' && file[1] == '/')) if(*file++ == 0) return endptr; file += 2; } if(cont.IsVoid()) { cont = endptr; return NULL; } const char *p = cont; while(*p && ToLower(*p) == ToLower(*endptr++)) p++; cont.Trim(p - cont.Begin()); return NULL; } struct RichObjectExchangeNew : public RichObjectExchange { RichObjectExchangeNew(RichObjectType *type) : object(type, Null) {} virtual RichObject GetRichObject() const { return object; } virtual void SetRichObject(const RichObject& data) { object = data; } RichObject object; }; class DlgHelpEditorLink : public WithHelpEditorLinkLayout<TopWindow> { public: typedef DlgHelpEditorLink CLASSNAME; DlgHelpEditorLink(); bool Run(String& target, String& text, String& style); private: void OnMask(); void OnPreview(); void SyncList(); private: Vector<String> map; int prev; DisplayTopicName tn; }; RegisterHelpTopicObjectTitle(DlgHelpEditorLink, t_("Link to topic")) DlgHelpEditorLink::DlgHelpEditorLink() { prev = 0; CtrlLayoutOKCancel(*this, DlgHelpEditorLinkHelpTitle()); Sizeable().MaximizeBox(); HelpTopic("DlgHelpEditorLink"); list.AddColumn(t_("Code"), 10); list.AddColumnAt(0, t_("Topic name"), 10).SetDisplay(tn); dyna_preview.SetZoom(Zoom(DOC_SCREEN_ZOOM, 1024)); dyna_preview.NoSb(); book_preview.SetZoom(Zoom(DOC_SCREEN_ZOOM, 1024)); book_preview.NoSb(); style.AddList(" (viz str. #)"); style.AddList(", str. #"); style.AddList(" (str. #)"); style.AddList("-|#"); mask <<= THISBACK(OnMask); list.WhenCursor = text <<= style <<= THISBACK(OnPreview); } bool DlgHelpEditorLink::Run(String& tg, String& tx, String& st) { map <<= HelpTopicMap().GetKeys(); Sort(map, GetLanguageInfo()); CtrlRetriever rtvr; rtvr(text, tx) (style, st); mask <<= tg; SyncList(); OnPreview(); while(TopWindow::Run() == IDOK) { if(!list.IsCursor()) { BeepExclamation(); continue; } tg = list.Get(0); rtvr.Retrieve(); return true; } return false; } void DlgHelpEditorLink::SyncList() { list.Clear(); String m = mask.GetText().ToString(); String rem = String::GetVoid(); const char *best_err = NULL; for(int p = 0; p < map.GetCount(); p++) { String fn = map[p]; String rr = rem; const char *errptr = FindTopicMatch(m, fn, rr); if(!errptr) { rem = rr; list.Add(fn); } else if(!best_err || errptr > best_err) best_err = errptr; } if(list.GetCount() == 0) { int px = best_err - m.Begin(); mask.SetSelection(px, mask.GetLength()); BeepExclamation(); } else if(!rem.IsEmpty() && prev < mask.GetLength()) { int l, h; mask.GetSelection(l, h); if(l == m.GetLength()) { mask.SetText((mask + rem).ToWString()); mask.SetSelection(l, l + rem.GetLength()); } } prev = m.GetLength(); if(list.GetCount() > 0) list.SetCursor(0); } void DlgHelpEditorLink::OnMask() { SyncList(); } void DlgHelpEditorLink::OnPreview() { RichPara::CharFormat cfmt; RichPara para; String target; if(list.IsCursor()) target = list.Get(0); para.Cat(FieldTypeLinkID(), EncodeLink(~target, ~text, ~style), cfmt); RichText text; text.Cat(para); { VectorMap<String, Value> vars; vars.Add("$link", 1); text.EvaluateFields(vars); } RichText copy; copy.Cat(para); { VectorMap<String, Value> vars; vars.Add("$book", 1); vars.Add(~target, 1234); copy.EvaluateFields(vars); } dyna_preview.Pick(text); book_preview.Pick(copy); } class DlgHelpEditorNewTopic : public WithHelpEditorNewTopicLayout<TopWindow> { public: typedef DlgHelpEditorNewTopic CLASSNAME; DlgHelpEditorNewTopic(); bool Run(String& space, String& nesting, String& topic, String& folder); private: void OnSpace(); void OnNesting(); void OnFolderBrowse(); private: ExtendedButton folder_browse; }; RegisterHelpTopicObjectTitle(DlgHelpEditorNewTopic, t_("New help topic")) DlgHelpEditorNewTopic::DlgHelpEditorNewTopic() { CtrlLayoutOKCancel(*this, DlgHelpEditorNewTopicHelpTitle()); HelpTopic("DlgHelpEditorNewTopic"); Vector<String> hsp = HelpTopicEnumSpace(); int i; for(i = 0; i < hsp.GetCount(); i++) dpp_space.Add(Nvl(hsp[i], "::")); if(hsp.GetCount() == 1) dpp_space.SetIndex(0); dpp_space <<= THISBACK(OnSpace); dpp_nesting <<= THISBACK(OnNesting); folder.AddFrame(folder_browse); folder_browse <<= THISBACK(OnFolderBrowse); } bool DlgHelpEditorNewTopic::Run(String& spc, String& nest, String& top, String& fold) { dpp_space <<= spc; OnSpace(); dpp_nesting <<= nest; OnNesting(); dpp_topic <<= top; folder <<= fold; if(TopWindow::Run() != IDOK) return false; spc = ~dpp_space; nest = ~dpp_nesting; top = ~dpp_topic; fold = ~folder; return true; } void DlgHelpEditorNewTopic::OnSpace() { Vector<String> nest = HelpTopicEnumNesting(~dpp_space); dpp_nesting.Clear(); for(int i = 0; i < nest.GetCount(); i++) dpp_nesting.Add(Nvl(nest[i], "::")); if(nest.GetCount() == 1) dpp_nesting.SetIndex(0); OnNesting(); } void DlgHelpEditorNewTopic::OnNesting() { String sp = ~dpp_space, ne = ~dpp_nesting; Vector<String> names = HelpTopicList(sp, ne); dpp_topic.ClearList(); for(int i = 0; i < names.GetCount(); i++) { String drl = names[i]; String s, n, t; HelpParseDPP(drl, s, n, t); dpp_topic.AddList(t); } } void DlgHelpEditorNewTopic::OnFolderBrowse() { FileSel fsel; fsel <<= ~folder; if(fsel.ExecuteSelectDir("Složka tématu")) folder <<= ~fsel; } class DlgHelpEditorSection : public WithHelpEditorSectionLayout<TopWindow> { public: typedef DlgHelpEditorSection CLASSNAME; DlgHelpEditorSection(); bool Run(RichTextSection& section); public: Option header_opt[3], footer_opt[3]; EditField header[3], footer[3]; private: void Pump(RichTextSection& section, bool write); void UpdateUI(); }; RegisterHelpTopicObjectTitle(DlgHelpEditorSection, "Textový oddíl (tisk)"); DlgHelpEditorSection::DlgHelpEditorSection() { CtrlLayoutOKCancel(*this, DlgHelpEditorSectionHelpTitle()); HelpTopic("DlgHelpEditorSection"); static String lcr[] = { t_("Left:"), t_("Center:"), t_("Right:") }; for(int i = 0; i < 3; i++) { header_opt[i].SetLabel(lcr[i]); footer_opt[i].SetLabel(lcr[i]); header_opt[i] <<= footer_opt[i] <<= THISBACK(UpdateUI); } columns_opt <<= column_space_opt <<= firstpage_opt <<= margin_left_opt <<= margin_top_opt <<= margin_right_opt <<= margin_bottom_opt <<= header_space_opt <<= footer_space_opt <<= THISBACK(UpdateUI); } static void PumpOpt(int& value, Option& opt, Ctrl& editor, bool write) { if(!write) { opt = !IsNull(value); editor <<= value; } else value = opt ? (int)~editor : int(Null); } void DlgHelpEditorSection::Pump(RichTextSection& section, bool write) { if(!write) { columns_opt = !IsNull(section.columns); columns <<= !IsNull(section.columns) ? section.columns - 1 : int(Null); nested <<= section.nested; } else { section.columns = columns_opt ? Nvl((int)~columns) + 1 : int(Null); section.nested = nested; } PumpOpt(section.column_space, column_space_opt, column_space, write); PumpOpt(section.firstpage, firstpage_opt, firstpage, write); PumpOpt(section.margin.left, margin_left_opt, margin_left, write); PumpOpt(section.margin.top, margin_top_opt, margin_top, write); PumpOpt(section.margin.right, margin_right_opt, margin_right, write); PumpOpt(section.margin.bottom, margin_bottom_opt, margin_bottom, write); PumpOpt(section.header_space, header_space_opt, header_space, write); PumpOpt(section.footer_space, footer_space_opt, footer_space, write); for(int i = 0; i < 3; i++) { if(!write) { header_opt[i] = !section.header[i].IsVoid(); footer_opt[i] = !section.footer[i].IsVoid(); header[i] <<= section.header[i]; footer[i] <<= section.footer[i]; } else { section.header[i] = (header_opt[i] ? (String)~header[i] : String::GetVoid()); section.footer[i] = (footer_opt[i] ? (String)~footer[i] : String::GetVoid()); } } } bool DlgHelpEditorSection::Run(RichTextSection& section) { Pump(section, false); UpdateUI(); if(TopWindow::Run() != IDOK) return false; Pump(section, true); return true; } void DlgHelpEditorSection::UpdateUI() { columns.Enable(columns_opt); column_space.Enable(column_space_opt); firstpage.Enable(firstpage_opt); margin_left.Enable(margin_left_opt); margin_top.Enable(margin_top_opt); margin_right.Enable(margin_right_opt); margin_bottom.Enable(margin_bottom_opt); header_space.Enable(header_space_opt); footer_space.Enable(footer_space_opt); for(int i = 0; i < 3; i++) { header[i].Enable(header_opt[i]); footer[i].Enable(footer_opt[i]); } } static HelpTopicInfoMap& StoredHelpTopicMap() { static HelpTopicInfoMap map; return map; } void StoreHelpInfo() { StoredHelpTopicMap() <<= HelpTopicMap(); } void LoadAppHelpFile() { HelpInit::Run(); StoreHelpInfo(); String dir = AppendFileName(GetFileDirectory(ConfigFile()), "doc.dpp"); FindFile ff; if(ff.Search(AppendFileName(dir, "*.dpp"))) do if(ff.IsFile()) { String path = AppendFileName(dir, ff.GetName()); try { HelpTopicLoad(path, LoadFile(path)); } catch(Exc e) { if(!PromptOKCancel(NFormat("[* \1%s\1]: %s\nPokračovat?", path, e))) break; } } while(ff.Next()); } class ConvertParaCount : public Convert { public: ConvertParaCount() : language(Null) {} void Language(int lang) { language = lang; } virtual Value Format(const Value& value) const; private: int language; }; Value ConvertParaCount::Format(const Value& value) const { // return Null; String topic = value; if(IsNull(topic) || IsNull(language)) return Null; RichText rt = ParseQTF(HelpTopicGet(HelpDPPStyle()).GetText(language) + "\r\n" + HelpTopicGet(topic).GetText(language)); return rt.IsEmpty() ? int(Null) : rt.GetPartCount(); } class ConvertIndexCount : public Convert { public: ConvertIndexCount() : language(Null) {} void Language(int lang) { language = lang; } virtual Value Format(const Value& value) const; private: int language; }; Value ConvertIndexCount::Format(const Value& value) const { // return Null; String topic = value; if(IsNull(topic) || IsNull(language)) return Null; RichText rt = ParseQTF(HelpTopicGet(HelpDPPStyle()).GetText(language) + "\r\n" + HelpTopicGet(topic).GetText(language)); Vector<RichValPos> vp = rt.GetValPos(Size(10000, INT_MAX), RichText::INDEXENTRIES); Index<WString> ie; for(int i = 0; i < vp.GetCount(); i++) ie.FindAdd(vp[i].data); if(ie.IsEmpty()) return Null; return ie.GetCount(); } typedef VectorMap< String, VectorMap<int, int> > EditPosMap; GLOBAL_VAR(EditPosMap, _sPosMap) class DlgHelpEditor : public TopWindow { public: typedef WithHelpEditorEditLayout<TopWindow> EditorCtrl; typedef DlgHelpEditor CLASSNAME; DlgHelpEditor(); virtual void Serialize(Stream& stream); static ConfigItem& config(); void Run(Ctrl *ctrl, const Image& still); virtual void ChildGotFocus(); virtual bool HotKey(dword key); TOOL(Main) TOOL(File) TOOL(FileOpen) TOOL(FileSave) // TOOL(FileSaveAs) TOOL(FileTopicIndex) TOOL(FileTopicView) TOOL(FileClose) TOOL(Edit) TOOL(EditUp) TOOL(EditDown) TOOL(EditGoto) TOOL(EditFormula) TOOL(EditLink) TOOL(EditSection) TOOL(EditNewTopic) TOOL(EditPaste) TOOL(System) // TOOL(SystemExport) TOOL(SystemExportProject) void Rescan() { menubar.Set(THISBACK(ToolMain)); toolbar.Set(THISBACK(ToolMain)); } private: static bool SaveTopic(String topic, int lang, const EditorCtrl& editor); static String LoadTopic(String topic, int lang, EditorCtrl& editor); void OnTopicListCursor(); void OnTopicListAction(); void OnTopicLanguage(); void OnAuxLanguage(); void OnDPPSpace(); void OnDPPNesting(); void OnScreenshot(); void OnPasteIcon(); void UpdateTopicList() { OnDPPSpace(); } void UpdateAvail(); void UpdateIconModules(); void UpdateIconGallery(); bool SaveFile(); bool PromptSave(); private: Splitter hsplitter; ArrayCtrl topic_list; enum { C_DRL, C_NAME, C_COUNT }; Splitter vsplitter; EditorCtrl edit, aux_edit; TabCtrl aux_tab; Ctrl aux_pane; WithHelpEditorIconLayout<TopWindow> aux_icons; EditorCtrl *last_edit; ConvertParaCount cv_para; ConvertIndexCount cv_index; bool is_dirty; Label dpp_space_tag; DropList dpp_space; Label dpp_nesting_tag; DropList dpp_nesting; Ctrl *master; One<Ctrl> screenshot; MenuBar menubar; ToolBar toolbar; StatusBar statusbar; String old_topic; int old_lang1, old_lang2; String recent_dlg; String recent_exp_dir; String init_topic; enum { IFRM_NONE, IFRM_BUTTON, IFRM_INSET }; }; void RunDlgHelpEditor(Ctrl *ctrl, const Image& still) { DlgHelpEditor().Run(ctrl, still); } RegisterHelpTopicObjectTitle(DlgHelpEditor, t_("Application documentation editor")) DlgHelpEditor::DlgHelpEditor() { master = NULL; is_dirty = false; // topic_text.SpellCheck(); // topic_aux.SpellCheck(); //CtrlLayout(*this, "Editor aplikační dokumentace"); Title(DlgHelpEditorHelpTitle().ToWString()); HelpTopic("DlgHelpEditor"); WhenClose = THISBACK(OnFileClose); Sizeable().Zoomable(); // CalcWindowRect(*this, (Stock.GetScreenSize() * 3) >> 2); AddFrame(menubar); AddFrame(toolbar); AddFrame(statusbar); Add(hsplitter.SizePos()); hsplitter.Horz(topic_list, vsplitter); hsplitter.SetPos(3000); topic_list.AutoHideSb(); topic_list.NoVertGrid(); ASSERT(topic_list.GetIndexCount() == C_DRL); topic_list.AddIndex(); ASSERT(topic_list.GetIndexCount() == C_NAME); topic_list.AddColumn(t_("Topic"), 20); topic_list.AddColumnAt(C_DRL, t_("Para"), 4).SetConvert(cv_para).Cache(); topic_list.AddColumnAt(C_DRL, t_("Index"), 4).SetConvert(cv_index).Cache(); topic_list.WhenCursor = THISBACK(OnTopicListCursor); topic_list <<= THISBACK(OnTopicListAction); vsplitter.Vert(edit, aux_tab); CtrlLayout(edit); aux_tab.Add(aux_pane.SizePos(), t_("Screenshot")); aux_pane.NoWantFocus().Transparent(); CtrlLayout(aux_edit); int wd = 4000; //edit.text.GetPage().cx; edit.text.SetPage(Size(wd, 0x10000000)); aux_edit.text.SetPage(Size(wd, 0x10000000)); aux_tab.Add(aux_edit.SizePos(), t_("Text")); CtrlLayout(aux_icons); aux_tab.Add(aux_icons.SizePos(), t_("Icons")); aux_icons.module.AddIndex(); aux_icons.module.AddColumn(); aux_icons.module.WhenCursor = THISBACK(UpdateIconGallery); aux_icons.gallery.Columns(3); aux_icons.frame <<= IFRM_BUTTON; aux_icons.size <<= 80; aux_icons.raise <<= -3; aux_icons.gallery.WhenLeftDouble = THISBACK(OnPasteIcon); last_edit = &edit; edit.text.WhenRefreshBar = aux_edit.text.WhenRefreshBar = THISBACK(Rescan); // edit.topic_module.SetReadOnly(); edit.title.SetFont(StdFont().Bold()); aux_edit.title.SetFont(StdFont().Bold()); edit.title.SetConvert(CFormatConvert()); aux_edit.title.SetConvert(CFormatConvert()); // menubar <<= THISBACK(ToolMain); dpp_space_tag.SetLabel(t_("Namespace: ")); dpp_space <<= THISBACK(OnDPPSpace); dpp_nesting_tag.SetLabel(t_("Nesting: ")); dpp_nesting <<= THISBACK(OnDPPNesting); Vector<String> hsp = HelpTopicEnumSpace(); dpp_space.Add(String::GetVoid(), t_("(all)")); int i; for(i = 0; i < hsp.GetCount(); i++) dpp_space.Add(Nvl(hsp[i], "::")); if(hsp.GetCount() == 1) dpp_space.SetIndex(1); Vector<int> lcodes = HelpTopicEnumLang(); if(FindIndex(lcodes, LNG_CZECH) < 0) lcodes.Add(LNG_CZECH); if(FindIndex(lcodes, LNG_ENGLISH) < 0) lcodes.Add(LNG_ENGLISH); aux_edit.language.Add(Null, "---"); old_lang1 = old_lang2 = Null; for(i = 0; i < lcodes.GetCount(); i++) { int l = lcodes[i]; String n = LNGAsText(l); edit.language.Add(l, n); aux_edit.language.Add(l, n); if(l == GetCurrentLanguage()) old_lang1 = l; else if(IsNull(old_lang2)) old_lang2 = l; } edit.language <<= old_lang1; edit.language <<= THISBACK(OnTopicLanguage); aux_edit.language <<= old_lang2; aux_edit.language <<= THISBACK(OnAuxLanguage); ActiveFocus(topic_list); UpdateAvail(); UpdateIconModules(); } CONFIG_ITEM(DlgHelpEditor::config, "DlgHelpEditor", 6, 3, 6) void DlgHelpEditor::Serialize(Stream& stream) { SerializePlacement(stream); stream % hsplitter % vsplitter; stream % recent_exp_dir; if(config() >= 4) { String module; if(aux_icons.module.IsCursor()) module = aux_icons.module.Get(0); stream % CtrlData<int>(aux_icons.frame) % CtrlData<int>(aux_icons.size) % CtrlData<double>(aux_icons.raise) % module; if(stream.IsLoading()) aux_icons.module.FindSetCursor(module); } if(config() >= 5) stream % aux_icons.gallery; if(config() >= 6) stream % CtrlData<int>(aux_icons.grayed) % CtrlData<int>(aux_icons.etched); } void DlgHelpEditor::Run(Ctrl *master_, const Image& still_) { master = master_; if(master) { screenshot = GetDlgShot(master_, still_); *screenshot <<= THISBACK(OnScreenshot); aux_pane.Add(screenshot->SizePos()); Ctrl *m = master; while(IsNull(init_topic = m->GetHelpTopic())) if(m->GetParent()) m = m->GetParent(); else if(m->GetOwner()) m = m->GetOwner(); else break; } ReadConfigSelf(); Open(); Rescan(); OnDPPSpace(); OnTopicLanguage(); OnTopicListCursor(); ActiveFocus(edit.text); TopWindow::Run(); OnTopicListCursor(); // topic_list.KillCursor(); WriteConfigSelf(); // text = editor.Get(); // String text = ~editor; // PromptOK(String() << "Output text:\n\n" << text); } void DlgHelpEditor::ToolMain(Bar& bar) { bar.Add(t_("File"), THISBACK(ToolFile)) .Help(t_("Help files maintenance")); bar.Add(t_("Edit"), THISBACK(ToolEdit)) .Help(t_("Edit theme topics")); if(bar.IsToolBar()) { bar.Separator(); bar.Add(dpp_space_tag); bar.Add(dpp_space, 120); bar.Separator(); bar.Add(dpp_nesting_tag); bar.Add(dpp_nesting, 120); } bar.Add(t_("System"), THISBACK(ToolSystem)) .Help(t_("System tools")); if(bar.IsToolBar()) { last_edit->text.DefaultBar(bar); } /* if(bar.IsToolBar()) { bar_edit->StyleTool(bar); bar.Gap(); bar_edit->FontTools(bar); bar.Gap(); bar_edit->InkTool(bar); bar_edit->PaperTool(bar); bar.Gap(); bar_edit->LanguageTool(bar); bar_edit->SpellCheckTool(bar); bar.Break(); bar_edit->IndexEntryTool(bar); bar.Break(); bar_edit->HyperlinkTool(bar); bar.Gap(); bar_edit->ParaTools(bar); bar.Gap(); bar_edit->PrintTool(bar); } */ } void DlgHelpEditor::ToolFile(Bar& bar) { ToolFileOpen(bar); ToolFileSave(bar); // ToolFileSaveAs(bar); bar.MenuSeparator(); ToolFileTopicIndex(bar); ToolFileTopicView(bar); bar.MenuSeparator(); ToolFileClose(bar); } void DlgHelpEditor::ToolFileOpen(Bar& bar) { bar.Add(t_("Open"), CtrlImg::open(), THISBACK(OnFileOpen)) .Key(K_CTRL_O) .Help(t_("Read help files from a given disk file")); } //RegisterHelpTopicObjectTitle(DlgHelpEditorMissingTopics, s_(DlgHelpEditorMissingTopicsHelpTitle)) void DlgHelpEditor::OnFileOpen() { FileSelector fsel; fsel.Type("Dokumentace (*.dpp, *.dpx)", "*.dpp;*.dpx"); fsel.AllFilesType(); fsel.DefaultExt("dpp"); fsel.Multi(); if(fsel.ExecuteOpen(t_("Open"))) { int cs = topic_list.GetCursor(); int sc = topic_list.GetCursorSc(); topic_list.KillCursor(); Progress progress("Načítám soubory", fsel.GetCount()); Index<String> loaded; for(int i = 0; i < fsel.GetCount(); i++) try { if(progress.StepCanceled()) break; String data = LoadFile(fsel[i]); if(IsNull(data)) throw Exc(t_("error loading file")); HelpTopicLoad(fsel[i], data, &loaded); } catch(Exc e) { if(!PromptOKCancel(NFormat("Chyba v souboru [* \1%s\1]:\n[* \1%s\1]\nPokračovat?", fsel[i], e))) break; } UpdateTopicList(); if(!topic_list.FindSetCursor(loaded[0], C_DRL)) topic_list.SetCursor(cs); topic_list.ScCursor(sc); } UpdateAvail(); } void DlgHelpEditor::ToolFileSave(Bar& bar) { bar.Add(t_("Save"), CtrlImg::save(), THISBACK(OnFileSave)) .Key(K_CTRL_S) .Help(t_("Save help topics into a common application file")); } void DlgHelpEditor::OnFileSave() { SaveFile(); } bool DlgHelpEditor::SaveFile() { OnTopicListCursor(); String outpath = GetFileFolder(ConfigFile()); try { Vector<String> folders = HelpTopicEnumTextFolders(); Progress progress("Ukládám nápovědu", folders.GetCount()); for(int i = 0; i < folders.GetCount(); i++) { if(progress.StepCanceled()) throw AbortExc(); Vector<String> files; HelpTopicSave(files, folders[i], StoredHelpTopicMap(), outpath); } } catch(Exc e) { Exclamation(NFormat(t_("Error writing help into folder [* \1%s\1]."), outpath)); return false; } is_dirty = false; return true; } /* void DlgHelpEditor::ToolFileSaveAs(Bar& bar) { bar.Add(s_(DlgHelpEditorToolFileSaveAs), CtrlImg::save_as(), THISBACK(OnFileSaveAs)) .Help(s_(DlgHelpEditorToolFileSaveAsHelp)); } */ /* void DlgHelpEditor::OnFileSaveAs() { SaveFile(Null); } */ void DlgHelpEditor::ToolFileTopicIndex(Bar& bar) { bar.Add(t_("Contents, index"), THISBACK(OnFileTopicIndex)) .Help(t_("Show help contents and search index")); } void DlgHelpEditor::OnFileTopicIndex() { OnTopicListCursor(); OpenHelpTopicIndex(old_topic); } void DlgHelpEditor::ToolFileTopicView(Bar& bar) { bar.Add(topic_list.IsCursor(), "Prohlížeč tématu", THISBACK(OnFileTopicView)) .Help("Zobrazit aktivní téma v prohlížeči dokumentace"); } void DlgHelpEditor::OnFileTopicView() { if(!topic_list.IsCursor()) { BeepExclamation(); return; } String drl = topic_list.Get(C_DRL); RunDlgHelpTopic(drl); } void DlgHelpEditor::ToolFileClose(Bar& bar) { bar.Add(t_("Close"), THISBACK(OnFileClose)) .Help(t_("Close documentation editor")); } void DlgHelpEditor::OnFileClose() { // if(PromptSave()) AcceptBreak(IDOK); } bool DlgHelpEditor::PromptSave() { OnTopicListCursor(); if(!is_dirty) return true; switch(PromptYesNoCancel(t_("Do you want to save changes to the documentation?"))) { case 1: return SaveFile(); case 0: return true; default: return false; } } void DlgHelpEditor::ToolEdit(Bar& bar) { /* bar_edit->UndoTool(bar); bar_edit->RedoTool(bar); bar.Gap(); bar_edit->CutTool(bar); bar_edit->CopyTool(bar); ToolEditPaste(bar); bar.Gap(); */ last_edit->text.FindReplaceTool(bar); bar.Separator(); ToolEditUp(bar); ToolEditDown(bar); ToolEditGoto(bar); bar.Separator(); ToolEditFormula(bar); ToolEditLink(bar); ToolEditSection(bar); ToolEditNewTopic(bar); } /* void DlgHelpEditor::ToolEditPaste(Bar& bar) { bar.Add("Paste", CtrlImg::paste(), THISBACK(OnEditPaste)) .Key(K_CTRL_V); } */ /* void DlgHelpEditor::OnEditPaste() { int rtf = GetClipboardFormatCode("Rich Text Format"); if(!IsClipboardFormatAvailable(GetClipboardFormatCode("QTF")) && IsClipboardFormatAvailable(rtf)) { String rtfdata = ReadClipboard(rtf); RichText rt = ParseRTF(rtfdata); if(!rt.IsEmpty()) { bar_edit->PasteText(rt); return; } } bar_edit->Paste(); } */ void DlgHelpEditor::ToolEditUp(Bar& bar) { bar.Add(t_("Previous theme"), THISBACK(OnEditUp)) .Key(K_ALT_UP) .Help(t_("Go up one theme in the list")); } void DlgHelpEditor::OnEditUp() { if(topic_list.GetCursor() > 0) topic_list.SetCursor(topic_list.GetCursor() - 1); ActiveFocus(last_edit->text); } void DlgHelpEditor::ToolEditDown(Bar& bar) { bar.Add(t_("Next topic"), THISBACK(OnEditDown)) .Key(K_ALT_DOWN) .Help(t_("Go down one topic in the list")); } void DlgHelpEditor::OnEditDown() { if(topic_list.GetCursor() + 1 < topic_list.GetCount()) topic_list.SetCursor(topic_list.GetCursor() + 1); ActiveFocus(last_edit->text); } void DlgHelpEditor::ToolEditGoto(Bar& bar) { bar.Add(t_("Go to..."), THISBACK(OnEditGoto)) .Key(K_CTRL_D) .Help(t_("Locate help topic using initial letters or wildcard mask (*, ?)")); } RegisterHelpTopicObjectTitle(DlgHelpEditorGoto, t_("Go to topic")); void DlgHelpEditor::OnEditGoto() { WithHelpEditorGotoLayout<TopWindow> ffdlg; CtrlLayoutOKCancel(ffdlg, DlgHelpEditorGotoHelpTitle()); ffdlg.HelpTopic("DlgHelpEditorGoto"); ffdlg.list.AddColumn(t_("Code"), 10); DisplayTopicName tn; ffdlg.list.AddColumnAt(0, t_("Topic name"), 10).SetDisplay(tn); ffdlg.mask <<= ffdlg.Breaker(IDYES); int prev = 0; Vector<String> map; map <<= HelpTopicMap().GetKeys(); Sort(map, GetLanguageInfo()); for(;;) { ffdlg.list.Clear(); String mask = ffdlg.mask.GetText().ToString(); String rem = String::GetVoid(); const char *best_err = NULL; for(int p = 0; p < map.GetCount(); p++) { String fn = map[p]; String rr = rem; const char *errptr = FindTopicMatch(mask, fn, rr); if(!errptr) { rem = rr; ffdlg.list.Add(fn); } else if(!best_err || errptr > best_err) best_err = errptr; } if(ffdlg.list.GetCount() == 0) { int px = best_err - mask.Begin(); ffdlg.mask.SetSelection(px, ffdlg.mask.GetLength()); BeepExclamation(); } else if(!rem.IsEmpty() && prev < mask.GetLength()) { int l, h; ffdlg.mask.GetSelection(l, h); if(l == mask.GetLength()) { ffdlg.mask.SetText((mask + rem).ToWString()); ffdlg.mask.SetSelection(l, l + rem.GetLength()); } } prev = mask.GetLength(); if(ffdlg.list.GetCount() > 0) ffdlg.list.SetCursor(0); switch(ffdlg.Run()) { case IDCANCEL: return; case IDOK: if(ffdlg.list.IsCursor()) { if(topic_list.FindSetCursor(ffdlg.list.Get(0))) { ActiveFocus(last_edit->text); return; } BeepExclamation(); } break; case IDYES: break; } } } void DlgHelpEditor::ToolEditFormula(Bar& bar) { bar.Add(!!master, t_("Formula"), THISBACK(OnEditFormula)) .Key(K_CTRL_W) .Help(t_("Open formula editor")); } void DlgHelpEditor::OnEditFormula() { RichObjectExchangeNew ren(RichObjectTypeFormula()); RichObjectTypeFormula()->DefaultAction(ren); if(!IsNull(ren.object.GetData())) { if(last_edit->text.IsSelection()) last_edit->text.RemoveSelection(); RichPara rpara; rpara.Cat(ren.object, RichPara::CharFormat()); RichText rtext; rtext.Cat(rpara); last_edit->text.PasteText(rtext); // BeepInformation(); ActiveFocus(last_edit->text); } } void DlgHelpEditor::ToolSystem(Bar& bar) { // ToolSystemExport(bar); ToolSystemExportProject(bar); } /* void DlgHelpEditor::ToolSystemExport(Bar& bar) { bar.Add(s_(DlgHelpEditorToolSystemExport), THISBACK(OnSystemExport)) .Key(K_CTRL_E) .Help(s_(DlgHelpEditorToolSystemExportHelp)); } */ /* void DlgHelpEditor::OnSystemExport() { OnTopicListCursor(); FileSel fsel; fsel.ActiveDir(recent_exp_dir); if(!fsel.ExecuteSelectDir(s_(DlgHelpEditorSystemExportDirSelTitle))) return; recent_exp_dir = ~fsel; Vector<String> mmap = HelpTopicEnumTextFolders(&StoredHelpTopicMap()); Progress progress(s_(DlgHelpEditorSystemExportProgress), mmap.GetCount()); int count_done = 0; for(int i = 0; i < mmap.GetCount(); i++) { String mod = mmap[i]; String outfile = AppendFileName(~fsel, GetFileTitle(mod) + ".hpp"); String diffile = HelpTopicSave(mod, StoredHelpTopicMap()); if(IsNull(diffile)) DeleteFile(outfile); else if(!::SaveFile(outfile, diffile)) { if(!PromptOKCancel(NFormat(s_(DlgHelpEditorSystemExportSaveError), outfile))) break; } else count_done++; if(progress.StepCanceled()) { PromptOK(s_(DlgHelpEditorSystemExportAbort)); return; } } PromptOK(NFormat(s_(DlgHelpEditorSystemExportCountInfo), count_done, ~fsel)); } */ void DlgHelpEditor::ToolSystemExportProject(Bar& bar) { bar.Add(t_("Export into project"), THISBACK(OnSystemExportProject)) .Key(K_CTRL_E) .Help(t_("Export help topics into the application source code")); } RegisterHelpTopicObjectTitle(DlgHelpEditorProjectExport, t_("Export help into project")); void DlgHelpEditor::OnSystemExportProject() { OnTopicListCursor(); Vector<String> mmap = HelpTopicEnumTextFolders(); if(mmap.IsEmpty()) { Exclamation(t_("No help files found.")); return; } int count_done = 0; WithHelpEditorExportProjectLayout<TopWindow> dlgexp; CtrlLayoutOKCancel(dlgexp, DlgHelpEditorProjectExportHelpTitle()); dlgexp.list.AddColumn(t_("Folder"), 50); dlgexp.list.AddColumn("Počet", 20); // dlgexp.list.AddColumn(s_(DlgHelpEditorSystemExportProjectLengthColumn), 20); // dlgexp.list.AddColumn(s_(DlgHelpEditorSystemExportProjectNewColumn), 20); ArrayOption todo; todo.AddColumn(dlgexp.list, t_("Overwrite"), 10); dlgexp.list.AddIndex(); // data Progress progress("Procházím seznam témat...", mmap.GetCount()); String host_dph_fn = AppendFileName(HelpTopicHostDir(), "host.dph"); String host_dph; for(int i = 0; i < mmap.GetCount(); i++) { if(progress.StepCanceled()) { Exclamation(t_("Export aborted by user.")); return; } int fdir = HelpTopicGetFolderDirty(mmap[i], StoredHelpTopicMap()); dlgexp.list.Add(mmap[i], fdir, fdir > 0); } dlgexp.list.SetCursor(0); if(dlgexp.Run() != IDOK) return; Vector<String> files; { Progress progress(t_("Exporting changed files"), dlgexp.list.GetCount()); for(int i = 0; i < dlgexp.list.GetCount(); i++) { if(progress.StepCanceled()) { Exclamation(t_("Export aborted by user.")); return; } dlgexp.list.SetCursor(i); bool do_save = (int)dlgexp.list.Get(2); String fold = dlgexp.list.Get(0); // String data = dlgexp.list.Get(4); try { host_dph << HelpTopicSave(files, fold, StoredHelpTopicMap(), Null, !do_save); } catch(Exc e) { if(!PromptOKCancel(NFormat(t_("Error exporting folder [* \1%s\1]: [* \1%s\1]. Continue?"), fold, e))) return; } } } if(!IsSameTextFile(LoadFile(host_dph_fn), host_dph)) { RealizePath(host_dph_fn); if(!::SaveFileBackup(host_dph_fn, host_dph)) Exclamation(NFormat("Nelze uložit soubor [* \1%s\1].", host_dph_fn)); else files.Add(host_dph_fn); } if(files.IsEmpty()) Exclamation(t_("No help files were saved.")); else { dlgexp.Close(); WithHelpEditorSavedFilesLayout<TopWindow> sfdlg; sfdlg.Sizeable().MaximizeBox(); CtrlLayoutExit(sfdlg, "Export byl úspěšně dokončen"); sfdlg.list.AddColumn(); Append(sfdlg.list, files); sfdlg.count.SetLabel(FormatInt(files.GetCount())); sfdlg.Run(); } } /* void DlgHelpEditor::OnEditDialog() { DlgHelpEditorDialogObject dlg; if(dlg.Run(recent_dlg)) { RichPara para; para.Cat(RichObject(RichObjectTypeDialogHelp(), recent_dlg)); RichText text; text.Cat(para); String s = AsQTF(text); LOG("RichText: " << s); LOGHEXDUMP(s, s.GetLength()); #ifdef PLATFORM_WIN32 WriteClipboard(RegisterClipboardFormat("Ultimate Development QTF format"), s); #else WriteClipboardText(s); #endif // editor.Paste(); } } */ void DlgHelpEditor::ToolEditLink(Bar& bar) { bar.Add(topic_list.IsCursor(), "Odkaz", THISBACK(OnEditLink)) .Key(K_CTRL_L) .Help("Vložit do textu odkaz na zvolené téma nápovědy"); } static int LocateField(const RichText& rt, int cursor, Id fieldid, String& param) { RichPos rpos; if(cursor < rt.GetLength() && (rpos = rt.GetRichPos(cursor)).field == fieldid) { param = rpos.fieldparam; return cursor; } if(cursor > 0 && (rpos = rt.GetRichPos(cursor - 1)).field == fieldid) { param = rpos.fieldparam; return cursor - 1; } return -1; } void DlgHelpEditor::OnEditLink() { if(!topic_list.IsCursor()) { BeepExclamation(); return; } DlgHelpEditorLink linkdlg; // String s, n, t; // HelpParseDPP((String)topic_list.Get(C_DRL), s, n, t); String drl, text, style; String param; int cur = last_edit->text.GetCursor(); const RichText& rt = last_edit->text.Get(); int old_pos = LocateField(rt, cur, FieldTypeLinkID(), param); int old_len = 0; RichPara::CharFormat fmt = last_edit->text.GetFormatInfo(); if(old_pos >= 0) { old_len = 1; DecodeLink(param, drl, text, style); fmt = rt.GetFormatInfo(old_pos, 1); } else { old_pos = cur; int l, h; if(cur < rt.GetLength()) { RichText::FormatInfo fi = rt.GetFormatInfo(cur, 1); if(!IsNull(fi.link)) { while(old_pos > 0 && rt.GetFormatInfo(old_pos - 1, 1).link == fi.link) --old_pos; while(cur < rt.GetLength() && rt.GetFormatInfo(cur, 1).link == fi.link) cur++; old_len = cur - old_pos; drl = fi.link; WString wtext; for(int i = 0; i < old_len; i++) wtext.Cat(last_edit->text[old_pos + i]); text = wtext.ToString(); } else if(last_edit->text.GetSelection(l, h)) { old_pos = l; old_len = h - l; WString rtt; while(l < h) rtt.Cat(rt[l++]); text = rtt.ToString(); } fmt = rt.GetFormatInfo(old_pos, old_len); fmt.link = Null; } } if(linkdlg.Run(/*Nvl(s, "::"), Nvl(n, "::"),*/ drl, text, style)) { if(old_len > 0) { last_edit->text.Move(old_pos, false); last_edit->text.RemoveText(old_len); } RichPara para; para.Cat(FieldTypeLinkID(), EncodeLink(drl, text, style), fmt); RichText text; text.Cat(para); last_edit->text.Move(old_pos, false); last_edit->text.PasteText(text); } } void DlgHelpEditor::ToolEditSection(Bar& bar) { bar.Add(topic_list.IsCursor(), "Tiskový oddíl", THISBACK(OnEditSection)) .Help("Vložit do textu značku začátku nového tiskového oddílu"); } void DlgHelpEditor::OnEditSection() { if(!topic_list.IsCursor()) { BeepExclamation(); return; } DlgHelpEditorSection secdlg; RichTextSection sect; int cur = last_edit->text.GetCursor(); String param; int pos = LocateField(last_edit->text.Get(), cur, FieldTypeSectionID(), param); if(pos >= 0) sect = DecodeSection(param); if(secdlg.Run(sect)) { RichPara::CharFormat fmt = last_edit->text.GetFormatInfo(); if(pos >= 0) { last_edit->text.Move(pos, false); last_edit->text.RemoveText(1); } RichPara para; para.Cat(FieldTypeSectionID(), EncodeSection(sect), fmt); RichText text; text.Cat(para); last_edit->text.Move(cur, false); last_edit->text.PasteText(text); } } void DlgHelpEditor::ToolEditNewTopic(Bar& bar) { bar.Add("Nové téma", THISBACK(OnEditNewTopic)) .Help("Vytvořit nové téma nápovědy"); } void DlgHelpEditor::OnEditNewTopic() { String drl; if(topic_list.IsCursor()) drl = topic_list.Get(C_DRL); String space, nesting, topic, folder; HelpParseDPP(drl, space, nesting, topic); DlgHelpEditorNewTopic newdlg; while(newdlg.Run(space, nesting, topic, folder)) { drl = HelpFormatDPP(space, nesting, topic); if(HelpTopicMap().Find(drl) >= 0) { Exclamation(NFormat("Objekt [* \1%s\1] již v systému dokumentace existuje.", drl)); continue; } HelpTopicSet(drl, AppendFileName(folder, ""), ~edit.language, "", ""); dpp_space <<= space; OnDPPSpace(); dpp_nesting <<= nesting; OnDPPNesting(); topic_list.FindSetCursor(drl); return; } } bool DlgHelpEditor::SaveTopic(String topic_name, int lang, const WithHelpEditorEditLayout<TopWindow>& editor) { _sPosMap().GetAdd(topic_name).GetAdd(lang) = editor.text.GetCursor(); if(IsNull(topic_name) || IsNull(lang) || !editor.title.IsModified() && !editor.text.IsModified()) return false; if(lang != GetCurrentLanguage()) SetLanguage(lang); int s = HelpTopicMap().Find(HelpDPPStyle()); int f = HelpTopicMap().Find(topic_name); if(f < 0) return false; byte cs = GetLangStdCharset(lang); HelpTopicInfo& topic = HelpTopicMap()[f]; String old_tit = ~editor.title; String old_styles = StylesAsQTF(editor.text.Get(), cs); String old_txt; if(!editor.text.Get().IsEmpty()) old_txt = BodyAsQTF(editor.text.Get(), cs); if(old_tit == topic.GetDefaultTitle()) old_tit = Null; String tqtf; if(s >= 0) tqtf = HelpTopicMap()[s].GetText(lang) + "\r\n"; if(old_txt == BodyAsQTF(ParseQTF(tqtf + topic.GetDefaultText()), cs)) //topic.GetText(old_language)) old_txt = Null; bool is_dirty = (old_tit != topic.GetTitle(lang) || old_txt != BodyAsQTF(ParseQTF(tqtf + topic.GetText(lang)), cs)); topic.Set(lang, old_tit, old_txt); if(s >= 0) HelpTopicMap()[s].Set(lang, Null, old_styles); return is_dirty; } String DlgHelpEditor::LoadTopic(String topic_name, int lang, WithHelpEditorEditLayout<TopWindow>& editor) { int s = HelpTopicMap().Find(HelpDPPStyle()); int f = HelpTopicMap().Find(topic_name); bool is_topic = (f >= 0 && !IsNull(lang)); editor.title.Enable(is_topic); editor.text.Enable(is_topic); String app_title, title; RichText text; if(is_topic) { if(lang != GetCurrentLanguage() && lang != 0 && !IsNull(lang)) SetLanguage(lang); RichText styles; if(s >= 0) styles = ParseQTF(HelpTopicMap()[s].GetText(lang)); HelpTopicInfo& topic = HelpTopicMap()[f]; title = topic.GetTitle(); text = ParseQTF(topic.GetText()); text.OverrideStyles(styles.GetStyles(), true); app_title = NFormat(t_("%s: %s - documentation editor"), topic_name, title); } editor.title <<= title; editor.text.Pick(text); editor.title.ClearModify(); editor.text.ClearModify(); int pos = _sPosMap().GetAdd(topic_name).Get(lang, 0); if(pos >= 0 && pos <= editor.text.GetLength()) editor.text.Move(pos); return app_title; } void DlgHelpEditor::OnTopicListCursor() { int lang = GetCurrentLanguage(); if(!IsNull(old_topic)) { String space, nesting, item; HelpParseDPP(old_topic, space, nesting, item); if(nesting != "sys") { if(SaveTopic(old_topic, old_lang1, edit)) is_dirty = true; if(SaveTopic(old_topic, old_lang2, aux_edit)) is_dirty = true; int ff = topic_list.Find(old_topic); if(ff >= 0) topic_list.InvalidateCache(ff); // topic_list.Set(ff, 1, !IsNull(old_txt) ? 1 : 0); } } old_topic = Null; if(topic_list.IsCursor()) old_topic = topic_list.Get(0); old_lang1 = ~edit.language; old_lang2 = ~aux_edit.language; String app_title = Nvl(LoadTopic(old_topic, old_lang1, edit), LoadTopic(old_topic, old_lang2, aux_edit)); if(GetCurrentLanguage() != lang) SetLanguage(lang); if(IsNull(app_title)) app_title = t_("Documentation editor"), Title(MQTFStrip(app_title).ToWString()); } void DlgHelpEditor::UpdateAvail() { // int cs = topic_list.GetCursor(); // topic_list.KillCursor(); int lng = ~edit.language; topic_list.ClearCache(); // const HelpTopicInfoMap& hmap = HelpTopicMap(); // for(int i = 0; i < topic_list.GetCount(); i++) // { // String topic = topic_list.Get(i, 0); // int f = hmap.Find(topic); // topic_list.Set(i, C_, f >= 0 && !IsNull(hmap[f].GetText(lng)) ? 1 : 0); // } // if(cs >= 0) // topic_list.SetCursor(cs); } void DlgHelpEditor::OnTopicLanguage() { int c = topic_list.GetCursor(); topic_list.KillCursor(); int lang = ~edit.language; byte cs = GetLangStdCharset(lang); cv_para.Language(lang); cv_index.Language(lang); topic_list.ClearCache(); // edit.topic_title.Charset(cs); // topic_text.Charset(cs); UpdateAvail(); if(c >= 0) topic_list.SetCursor(c); } void DlgHelpEditor::OnAuxLanguage() { OnTopicListCursor(); } void DlgHelpEditor::OnTopicListAction() { // topic_list.Sync(); } void DlgHelpEditor::ChildGotFocus() { if(edit.HasFocusDeep() && last_edit != &edit) { last_edit = &edit; Rescan(); } else if(aux_edit.HasFocusDeep() && last_edit != &aux_edit) { last_edit = &aux_edit; Rescan(); } } bool DlgHelpEditor::HotKey(dword key) { if(key == K_ESCAPE) { vsplitter.Zoom(vsplitter.GetZoom() == -1 ? 0 : -1); ActiveFocus(edit.text); return true; } return Ctrl::HotKey(key); } void DlgHelpEditor::OnScreenshot() { if(!screenshot) return; Value v = ~*screenshot; if(IsNull(v)) return; if(IsTypeRaw<Image>(v)) { Image dwg = v; Size dot_size = PixelsToDots(ScreenInfo(), dwg.GetSize()); RichObject object("PNG", PngEncoder().SaveImage(dwg), dot_size); //CreateDrawingObject(dwg, dot_size); if(last_edit->text.IsSelection()) last_edit->text.RemoveSelection(); RichPara rpara; rpara.Cat(object, last_edit->text.GetFormatInfo()); RichText rtext; rtext.Cat(rpara); last_edit->text.PasteText(rtext); // BeepInformation(); ActiveFocus(last_edit->text); } } void DlgHelpEditor::OnDPPSpace() { Vector<String> nest = HelpTopicEnumNesting(~dpp_space); dpp_nesting.Clear(); dpp_nesting.Add(Null, t_("(all)")); for(int i = 0; i < nest.GetCount(); i++) dpp_nesting.Add(Nvl(nest[i], "::")); dpp_nesting <<= Null; if(nest.GetCount() == 1) dpp_nesting.SetIndex(1); OnDPPNesting(); } void DlgHelpEditor::OnDPPNesting() { String sp = ~dpp_space, ne = ~dpp_nesting; Vector<String> names = HelpTopicList(sp, ne); topic_list.Clear(); topic_list.SetCount(names.GetCount()); int i; for(i = 0; i < names.GetCount(); i++) { String drl = names[i], name; if(!IsNull(sp) || !IsNull(ne)) { String space, nesting, topic; HelpParseDPP(drl, space, nesting, topic); if(IsNull(space)) space = "::"; if(IsNull(nesting)) nesting = "::"; if(IsNull(sp)) if(IsNull(ne)) name << space << "//" << nesting << "//"; else name << space << "//"; else if(IsNull(ne)) name << nesting << "//"; name << topic; } topic_list.Set(i, C_DRL, drl); topic_list.Set(i, C_NAME, Nvl(name, drl)); } if(!IsNull(init_topic)) { if(!topic_list.FindSetCursor(init_topic, C_DRL) && !topic_list.FindSetCursor(HelpAppDPP(init_topic), C_DRL)) topic_list.SetCursor(0); init_topic = Null; } } void DlgHelpEditor::UpdateIconModules() { Index<String> mods; const Vector<String>& names = ImageCache::Get().GetNameMap().GetKeys(); for(int i = 0; i < names.GetCount(); i++) { const char *p = names[i], *e = p; while(*e && !(e[0] == ':' && e[1] == ':')) e++; if(*e && e > p) mods.FindAdd(String(p, e)); } Vector<String> mlist = mods.PickKeys(); Sort(mlist, GetLanguageInfo()); aux_icons.module.Clear(); aux_icons.module.Add(Null, "(všechny)"); for(int i = 0; i < mlist.GetCount(); i++) aux_icons.module.Add(mlist[i], mlist[i]); } void DlgHelpEditor::UpdateIconGallery() { aux_icons.gallery.Clear(); aux_icons.gallery.Enable(aux_icons.module.IsCursor()); Size limit_size(aux_icons.gallery.GetIconWidth(), aux_icons.gallery.GetItemHeight()); if(aux_icons.module.IsCursor()) { String module = aux_icons.module.Get(0); int ml = module.GetLength(); const VectorMap<String, Image>& icons = ImageCache::Get().GetNameMap(); Vector<String> out; Vector<Image> outicon; for(int i = 0; i < icons.GetCount(); i++) { String n = icons.GetKey(i); if(ml) { if(memcmp(n, module, ml) || n[ml] != ':' || n[ml + 1] != ':') continue; n.Remove(0, ml + 2); } out.Add(n); Image out_image = icons[i]; if(out_image.GetHeight() > limit_size.cx || out_image.GetWidth() > limit_size.cy) { Size outsize = GetFitSize(out_image.GetSize(), limit_size); AlphaArray array = ImageToAlphaArray(out_image); AlphaArray out(outsize, -3); PixelCopyAntiAliasMaskOut(out, outsize, array, array.GetSize(), false); out_image = AlphaArrayToImage(out); } outicon.Add(out_image); } IndexSort(out, outicon, GetLanguageInfo()); for(int i = 0; i < out.GetCount(); i++) { aux_icons.gallery.Add(out[i], outicon[i]); } } } void DlgHelpEditor::OnPasteIcon() { if(!aux_icons.Accept()) return; if(!aux_icons.module.IsCursor() || !aux_icons.gallery.IsCursor()) { BeepExclamation(); return; } String module = aux_icons.module.Get(0); if(!IsNull(module)) module.Cat("::"); module.Cat(aux_icons.gallery.GetCurrentName()); Image img = ImageCache::Get().GetNameMap().Get(module, Null); if(IsNull(img)) { BeepExclamation(); return; } const ColorF *border = NULL; switch((int)~aux_icons.frame) { case IFRM_BUTTON: border = ButtonBorder(); break; case IFRM_INSET: border = InsetBorder(); break; } int width = (border ? (int)*border + 2 : 0); Size outsize = img.GetSize() + 2 * width; Image outimg(outsize); ImageDraw idraw(outimg); idraw.DrawRect(outsize, width ? SLtGray() : White()); DrawBorder(idraw, outsize, border); idraw.DrawImage(width, width, img, aux_icons.etched ? Image::ETCHED : aux_icons.grayed ? Image::GRAYED : 0); idraw.Close(); Size dot_size = PixelsToDots(ScreenInfo(), outimg.GetSize()); RichObject object("PNG", PngEncoder().DotSize(dot_size).SaveImage(outimg)); object.SetSize(object.GetPhysicalSize() * (int)~aux_icons.size / 100); object.KeepRatio(true); object.SetYDelta(fround((double)~aux_icons.raise * (-600.0 / 72.0))); //CreateDrawingObject(dwg, dot_size); if(last_edit->text.IsSelection()) last_edit->text.RemoveSelection(); RichPara rpara; rpara.Cat(object, last_edit->text.GetFormatInfo()); RichText rtext; rtext.Cat(rpara); last_edit->text.PasteText(rtext); // BeepInformation(); ActiveFocus(last_edit->text); } #endif
[ "mdelfede@05275033-79c2-2956-22f4-0a99e774df92" ]
mdelfede@05275033-79c2-2956-22f4-0a99e774df92
f2fd3680fd0111f3053d903fa03777b667d14feb
01bcef56ade123623725ca78d233ac8653a91ece
/vphysics/physics_shadow.cpp
12c741aa6ba5679117f5ddb5a45f055b8a9c17f5
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
SwagSoftware/Kisak-Strike
1085ba3c6003e622dac5ebc0c9424cb16ef58467
4c2fdc31432b4f5b911546c8c0d499a9cff68a85
refs/heads/master
2023-09-01T02:06:59.187775
2022-09-05T00:51:46
2022-09-05T00:51:46
266,676,410
921
123
null
2022-10-01T16:26:41
2020-05-25T03:41:35
C++
UTF-8
C++
false
false
43,100
cpp
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #include "cbase.h" #include "physics_shadow.h" #include "vphysics/player_controller.h" #include "physics_friction.h" #include "vphysics/friction.h" // IsInContact #include "ivp_mindist.hxx" #include "ivp_core.hxx" #include "ivp_friction.hxx" #include "ivp_listener_object.hxx" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" struct vphysics_save_cshadowcontroller_t; struct vphysics_save_shadowcontrolparams_t; // UNDONE: Try this controller! //damping is usually 1.0 //frequency is usually in the range 1..16 void ComputePDControllerCoefficients( float *coefficientsOut, const float frequency, const float damping, const float dt ) { const float ks = 9.0f * frequency * frequency; const float kd = 4.5f * frequency * damping; const float scale = 1.0f / ( 1.0f + kd * dt + ks * dt * dt ); coefficientsOut[0] = ks * scale; coefficientsOut[1] = ( kd + ks * dt ) * scale; // Use this controller like: // speed += (coefficientsOut[0] * (targetPos - currentPos) + coefficientsOut[1] * (targetSpeed - currentSpeed)) * dt } void ComputeController( IVP_U_Float_Point &currentSpeed, const IVP_U_Float_Point &delta, float maxSpeed, float maxDampSpeed, float scaleDelta, float damping, IVP_U_Float_Point *pOutImpulse = NULL ) { if ( currentSpeed.quad_length() < 1e-6 ) { currentSpeed.set_to_zero(); } // scale by timestep IVP_U_Float_Point acceleration; if ( maxSpeed > 0 ) { acceleration.set_multiple( &delta, scaleDelta ); float speed = acceleration.real_length(); if ( speed > maxSpeed ) { speed = maxSpeed / speed; acceleration.mult( speed ); } } else { acceleration.set_to_zero(); } IVP_U_Float_Point dampAccel; if ( maxDampSpeed > 0 ) { dampAccel.set_multiple( &currentSpeed, -damping ); float speed = dampAccel.real_length(); if ( speed > maxDampSpeed ) { speed = maxDampSpeed / speed; dampAccel.mult( speed ); } } else { dampAccel.set_to_zero(); } currentSpeed.add( &dampAccel ); currentSpeed.add( &acceleration ); if ( pOutImpulse ) { *pOutImpulse = acceleration; } } void ComputeController( IVP_U_Float_Point &currentSpeed, const IVP_U_Float_Point &delta, const IVP_U_Float_Point &maxSpeed, float scaleDelta, float damping, IVP_U_Float_Point *pOutImpulse ) { // scale by timestep IVP_U_Float_Point acceleration; acceleration.set_multiple( &delta, scaleDelta ); if ( currentSpeed.quad_length() < 1e-6 ) { currentSpeed.set_to_zero(); } acceleration.add_multiple( &currentSpeed, -damping ); for(int i=2; i>=0; i--) { if(IVP_Inline_Math::fabsd(acceleration.k[i]) < maxSpeed.k[i]) continue; // clip force acceleration.k[i] = (acceleration.k[i] < 0) ? -maxSpeed.k[i] : maxSpeed.k[i]; } currentSpeed.add( &acceleration ); if ( pOutImpulse ) { *pOutImpulse = acceleration; } } static bool IsOnGround( IVP_Real_Object *pivp ) { IPhysicsFrictionSnapshot *pSnapshot = CreateFrictionSnapshot( pivp ); bool bGround = false; while (pSnapshot->IsValid()) { Vector normal; pSnapshot->GetSurfaceNormal( normal ); if ( normal.z < -0.7f ) { bGround = true; break; } pSnapshot->NextFrictionData(); } DestroyFrictionSnapshot( pSnapshot ); return bGround; } class CPlayerController : public IVP_Controller_Independent, public IPhysicsPlayerController, public IVP_Listener_Object { public: CPlayerController( CPhysicsObject *pObject ); ~CPlayerController( void ); // ipion interfaces void do_simulation_controller( IVP_Event_Sim *es,IVP_U_Vector<IVP_Core> *cores); virtual IVP_CONTROLLER_PRIORITY get_controller_priority() { return (IVP_CONTROLLER_PRIORITY) (IVP_CP_MOTION+1); } virtual const char *get_controller_name() { return "vphysics:player"; } void SetObject( IPhysicsObject *pObject ); void SetEventHandler( IPhysicsPlayerControllerEvent *handler ); void Update( const Vector& position, const Vector& velocity, float secondsToArrival, bool onground, IPhysicsObject *ground ); void MaxSpeed( const Vector &velocity ); bool IsInContact( void ); virtual bool WasFrozen() { IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); return pCore->temporarily_unmovable ? true : false; } //lwss add missing func // returns bitfield e.g. 0 (no contacts), 1 (has physics contact), 2 (contact matching nGameFlags), 3 (both 1 & 2) virtual uint32 GetContactState( uint16 nGameFlags ) { uint32 state = 0; IVP_Real_Object *pivp = m_pObject->GetObject(); if ( !pivp->flags.collision_detection_enabled ) return state; IVP_Synapse_Friction *pfriction = pivp->get_first_friction_synapse(); while ( pfriction ) { extern IVP_Real_Object *GetOppositeSynapseObject( IVP_Synapse_Friction *pfriction ); IVP_Real_Object *pobj = GetOppositeSynapseObject( pfriction ); if ( pobj->flags.collision_detection_enabled ) { // skip if this is a static object if ( !pobj->get_core()->physical_unmoveable && !pobj->get_core()->pinned ) { CPhysicsObject *pPhys = static_cast<CPhysicsObject *>(pobj->client_data); int v7 = state | ( pPhys->IsControlledByGame() ^ 1 ); state = v7 | 2; if( !(pPhys->GetGameFlags() & nGameFlags) ) state = v7; } } pfriction = pfriction->get_next(); } return state; } //lwss end void ForceTeleportToCurrentPosition() { m_forceTeleport = true; } int GetShadowPosition( Vector *position, QAngle *angles ) { IVP_U_Matrix matrix; IVP_Environment *pEnv = m_pObject->GetObject()->get_environment(); double psi = pEnv->get_next_PSI_time().get_seconds(); m_pObject->GetObject()->calc_at_matrix( psi, &matrix ); if ( angles ) { ConvertRotationToHL( matrix, *angles ); } if ( position ) { ConvertPositionToHL( matrix.vv, *position ); } return 1; } void GetShadowVelocity( Vector *velocity ); virtual void GetLastImpulse( Vector *pOut ) { ConvertPositionToHL( m_lastImpulse, *pOut ); } virtual void StepUp( float height ); virtual void Jump(); virtual IPhysicsObject *GetObject() { return m_pObject; } virtual void SetPushMassLimit( float maxPushMass ) { m_pushableMassLimit = maxPushMass; } virtual void SetPushSpeedLimit( float maxPushSpeed ) { m_pushableSpeedLimit = maxPushSpeed; } virtual float GetPushMassLimit() { return m_pushableMassLimit; } virtual float GetPushSpeedLimit() { return m_pushableSpeedLimit; } // Object listener virtual void event_object_deleted( IVP_Event_Object *pEvent) { Assert( pEvent->real_object == m_pGround->GetObject() ); m_pGround = NULL; } virtual void event_object_created( IVP_Event_Object *) {} virtual void event_object_revived( IVP_Event_Object *) {} virtual void event_object_frozen ( IVP_Event_Object *) {} private: void AttachObject( void ); void DetachObject( void ); int TryTeleportObject( void ); void SetGround( CPhysicsObject *pGroundObject ); CPhysicsObject *m_pObject; IVP_U_Float_Point m_saveRot; CPhysicsObject *m_pGround; // Uses object listener to clear - so ok to hold over frames IPhysicsPlayerControllerEvent *m_handler; float m_maxDeltaPosition; float m_dampFactor; float m_secondsToArrival; float m_pushableMassLimit; float m_pushableSpeedLimit; IVP_U_Point m_targetPosition; IVP_U_Float_Point m_groundPosition; IVP_U_Float_Point m_maxSpeed; IVP_U_Float_Point m_currentSpeed; IVP_U_Float_Point m_lastImpulse; bool m_enable : 1; bool m_onground : 1; bool m_forceTeleport : 1; bool m_updatedSinceLast : 5; }; CPlayerController::CPlayerController( CPhysicsObject *pObject ) { m_pGround = NULL; m_pObject = pObject; m_handler = NULL; m_maxDeltaPosition = ConvertDistanceToIVP( 24 ); m_dampFactor = 1.0f; m_targetPosition.k[0] = m_targetPosition.k[1] = m_targetPosition.k[2] = 0; m_pushableMassLimit = VPHYSICS_MAX_MASS; m_pushableSpeedLimit = 1e4f; m_forceTeleport = false; AttachObject(); } CPlayerController::~CPlayerController( void ) { DetachObject(); } void CPlayerController::SetGround( CPhysicsObject *pGroundObject ) { if ( m_pGround != pGroundObject ) { if ( m_pGround && m_pGround->GetObject() ) { m_pGround->GetObject()->remove_listener_object(this); } m_pGround = pGroundObject; if ( m_pGround && m_pGround->GetObject() ) { m_pGround->GetObject()->add_listener_object(this); } } } void CPlayerController::AttachObject( void ) { m_pObject->EnableDrag( false ); IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); m_saveRot = pCore->rot_speed_damp_factor; pCore->rot_speed_damp_factor = IVP_U_Float_Point( 100, 100, 100 ); pCore->calc_calc(); BEGIN_IVP_ALLOCATION(); pivp->get_environment()->get_controller_manager()->add_controller_to_core( this, pCore ); END_IVP_ALLOCATION(); m_pObject->AddCallbackFlags( CALLBACK_IS_PLAYER_CONTROLLER ); } void CPlayerController::DetachObject( void ) { if ( !m_pObject ) return; IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); pCore->rot_speed_damp_factor = m_saveRot; pCore->calc_calc(); m_pObject->RemoveCallbackFlags( CALLBACK_IS_PLAYER_CONTROLLER ); m_pObject = NULL; pivp->get_environment()->get_controller_manager()->remove_controller_from_core( this, pCore ); SetGround(NULL); } void CPlayerController::SetObject( IPhysicsObject *pObject ) { CPhysicsObject *obj = (CPhysicsObject *)pObject; if ( obj == m_pObject ) return; DetachObject(); m_pObject = obj; AttachObject(); } int CPlayerController::TryTeleportObject( void ) { if ( m_handler && !m_forceTeleport ) { Vector hlPosition; ConvertPositionToHL( m_targetPosition, hlPosition ); if ( !m_handler->ShouldMoveTo( m_pObject, hlPosition ) ) return 0; } IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_U_Quat targetOrientation; IVP_U_Point outPosition; pivp->get_quat_world_f_object_AT( &targetOrientation, &outPosition ); if ( pivp->is_collision_detection_enabled() ) { m_pObject->EnableCollisions( false ); pivp->beam_object_to_new_position( &targetOrientation, &m_targetPosition, IVP_TRUE ); m_pObject->EnableCollisions( true ); } else { pivp->beam_object_to_new_position( &targetOrientation, &m_targetPosition, IVP_TRUE ); } m_forceTeleport = false; return 1; } void CPlayerController::StepUp( float height ) { if ( height == 0.0f ) return; Vector step( 0, 0, height ); IVP_Real_Object *pIVP = m_pObject->GetObject(); IVP_U_Quat world_f_object; IVP_U_Point positionIVP, deltaIVP; ConvertPositionToIVP( step, deltaIVP ); pIVP->get_quat_world_f_object_AT( &world_f_object, &positionIVP ); positionIVP.add( &deltaIVP ); pIVP->beam_object_to_new_position( &world_f_object, &positionIVP, IVP_TRUE ); } void CPlayerController::Jump() { #if 0 // float for one tick to allow stepping and jumping to work properly IVP_Real_Object *pIVP = m_pObject->GetObject(); const IVP_U_Point *pgrav = pIVP->get_environment()->get_gravity(); IVP_U_Float_Point gravSpeed; gravSpeed.set_multiple( pgrav, pIVP->get_environment()->get_delta_PSI_time() ); pIVP->get_core()->speed.subtract( &gravSpeed ); #endif } const int MAX_LIST_NORMALS = 8; class CNormalList { public: bool IsFull() { return m_Normals.Count() == MAX_LIST_NORMALS; } void AddNormal( const Vector &normal ) { if ( IsFull() ) return; for ( int i = m_Normals.Count(); --i >= 0; ) { if ( DotProduct( m_Normals[i], normal ) > 0.99f ) return; } m_Normals.AddToTail( normal ); } bool HasPositiveProjection( const Vector &vec ) { for ( int i = m_Normals.Count(); --i >= 0; ) { if ( DotProduct( m_Normals[i], vec ) > 0 ) return true; } return false; } // UNDONE: Handle the case better where we clamp to multiple planes // and still have a projection, but don't exceed limitVel. Currently that will stop. // when this is done, remove the ground exception below. Vector ClampVector( const Vector &inVector, float limitVel ) { if ( m_Normals.Count() > 2 ) { for ( int i = 0; i < m_Normals.Count(); i++ ) { if ( DotProduct(inVector, m_Normals[i]) > 0 ) { return vec3_origin; } } } else { if ( m_Normals.Count() == 2 ) { Vector crease; CrossProduct( m_Normals[0], m_Normals[1], crease ); float dot = DotProduct( inVector, crease ); return crease * dot; } else if (m_Normals.Count() == 1) { float dot = DotProduct( inVector, m_Normals[0] ); if ( dot > limitVel ) { return inVector + m_Normals[0]*(limitVel - dot); } } } return inVector; } private: CUtlVectorFixed<Vector, MAX_LIST_NORMALS> m_Normals; }; void CPlayerController::do_simulation_controller( IVP_Event_Sim *es,IVP_U_Vector<IVP_Core> *) { if ( !m_enable ) return; IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); Assert(!pCore->pinned && !pCore->physical_unmoveable); // current situation const IVP_U_Matrix *m_world_f_core = pCore->get_m_world_f_core_PSI(); const IVP_U_Point *cur_pos_ws = m_world_f_core->get_position(); IVP_U_Float_Point baseVelocity; baseVelocity.set_to_zero(); // --------------------------------------------------------- // Translation // --------------------------------------------------------- if ( m_pGround ) { const IVP_U_Matrix *pMatrix = m_pGround->GetObject()->get_core()->get_m_world_f_core_PSI(); pMatrix->vmult4( &m_groundPosition, &m_targetPosition ); m_pGround->GetObject()->get_core()->get_surface_speed( &m_groundPosition, &baseVelocity ); pCore->speed.subtract( &baseVelocity ); } IVP_U_Float_Point delta_position; delta_position.subtract( &m_targetPosition, cur_pos_ws); if (!pivp->flags.shift_core_f_object_is_zero) { IVP_U_Float_Point shift_cs_os_ws; m_world_f_core->vmult3( pivp->get_shift_core_f_object(), &shift_cs_os_ws); delta_position.subtract( &shift_cs_os_ws ); } IVP_DOUBLE qdist = delta_position.quad_length(); // UNDONE: This is totally bogus! Measure error using last known estimate // not current position! if ( m_forceTeleport || qdist > m_maxDeltaPosition * m_maxDeltaPosition ) { if ( TryTeleportObject() ) return; } // float to allow stepping const IVP_U_Point *pgrav = es->environment->get_gravity(); IVP_U_Float_Point gravSpeed; gravSpeed.set_multiple( pgrav, es->delta_time ); if ( m_onground ) { pCore->speed.subtract( &gravSpeed ); } float fraction = 1.0; if ( m_secondsToArrival > 0 ) { fraction = es->delta_time / m_secondsToArrival; if ( fraction > 1 ) { fraction = 1; } } if ( !m_updatedSinceLast ) { // we haven't received an update from the game code since the last controller step // This means we haven't gotten feedback integrated into the motion plan, so the error may be // exaggerated. Assume that the first updated tick had valid information, and limit // all subsequent ticks to the same size impulses. // NOTE: Don't update the saved impulse - so any subsequent ticks will still have the last // known good information. float len = m_lastImpulse.real_length(); // cap the max speed to the length of the last known good impulse IVP_U_Float_Point tmp; tmp.set( len, len, len ); ComputeController( pCore->speed, delta_position, tmp, fraction / es->delta_time, m_dampFactor, NULL ); } else { ComputeController( pCore->speed, delta_position, m_maxSpeed, fraction / es->delta_time, m_dampFactor, &m_lastImpulse ); } pCore->speed.add( &baseVelocity ); m_updatedSinceLast = false; // UNDONE: Assumes gravity points down Vector lastImpulseHL; ConvertPositionToHL( pCore->speed, lastImpulseHL ); IPhysicsFrictionSnapshot *pSnapshot = CreateFrictionSnapshot( pivp ); bool bGround = false; float invMass = pivp->get_core()->get_inv_mass(); float limitVel = m_pushableSpeedLimit; CNormalList normalList; while (pSnapshot->IsValid()) { Vector normal; pSnapshot->GetSurfaceNormal( normal ); if ( normal.z < -0.7f ) { bGround = true; } // remove this when clamp works better if ( normal.z > -0.99f ) { IPhysicsObject *pOther = pSnapshot->GetObject(1); if ( !pOther->IsMoveable() || pOther->GetMass() > m_pushableMassLimit ) { limitVel = 0.0f; } float pushSpeed = DotProduct( lastImpulseHL, normal ); float contactVel = pSnapshot->GetNormalForce() * invMass; float pushTotal = pushSpeed + contactVel; if ( pushTotal > limitVel ) { normalList.AddNormal( normal ); } } pSnapshot->NextFrictionData(); } DestroyFrictionSnapshot( pSnapshot ); Vector clamped = normalList.ClampVector( lastImpulseHL, limitVel ); Vector limit = clamped - lastImpulseHL; IVP_U_Float_Point limitIVP; ConvertPositionToIVP( limit, limitIVP ); pivp->get_core()->speed.add( &limitIVP ); m_lastImpulse.add( &limitIVP ); if ( bGround ) { float gravDt = gravSpeed.real_length(); // moving down? Press down with full gravity and no more if ( m_lastImpulse.k[1] >= 0 ) { float delta = gravDt - m_lastImpulse.k[1]; pivp->get_core()->speed.k[1] += delta; m_lastImpulse.k[1] += delta; } } // if we have time left, subtract it off m_secondsToArrival -= es->delta_time; if ( m_secondsToArrival < 0 ) { m_secondsToArrival = 0; } } void CPlayerController::SetEventHandler( IPhysicsPlayerControllerEvent *handler ) { m_handler = handler; } void CPlayerController::Update( const Vector& position, const Vector& velocity, float secondsToArrival, bool onground, IPhysicsObject *ground ) { IVP_U_Point targetPositionIVP; IVP_U_Float_Point targetSpeedIVP; ConvertPositionToIVP( position, targetPositionIVP ); ConvertPositionToIVP( velocity, targetSpeedIVP ); m_updatedSinceLast = true; // if the object hasn't moved, abort if ( targetSpeedIVP.quad_distance_to( &m_currentSpeed ) < 1e-6 ) { if ( targetPositionIVP.quad_distance_to( &m_targetPosition ) < 1e-6 ) { return; } } m_targetPosition.set( &targetPositionIVP ); m_secondsToArrival = secondsToArrival < 0 ? 0 : secondsToArrival; // Sanity check to make sure the position is good. #ifdef _DEBUG float large = 1024 * 512; Assert( m_targetPosition.k[0] >= -large && m_targetPosition.k[0] <= large ); Assert( m_targetPosition.k[1] >= -large && m_targetPosition.k[1] <= large ); Assert( m_targetPosition.k[2] >= -large && m_targetPosition.k[2] <= large ); #endif m_currentSpeed.set( &targetSpeedIVP ); IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); IVP_Environment *pEnv = pivp->get_environment(); pEnv->get_controller_manager()->ensure_core_in_simulation(pCore); m_enable = true; // m_onground makes this object anti-grav // UNDONE: Re-evaluate this m_onground = false;//onground; if ( velocity.LengthSqr() <= 0.1f ) { // no input velocity, just go where physics takes you. m_enable = false; ground = NULL; } else { MaxSpeed( velocity ); } CPhysicsObject *pGroundObject = static_cast<CPhysicsObject *>(ground); SetGround( pGroundObject ); if ( m_pGround ) { const IVP_U_Matrix *pMatrix = m_pGround->GetObject()->get_core()->get_m_world_f_core_PSI(); pMatrix->vimult4( &m_targetPosition, &m_groundPosition ); } } void CPlayerController::MaxSpeed( const Vector &velocity ) { IVP_Core *pCore = m_pObject->GetObject()->get_core(); IVP_U_Float_Point ivpVel; ConvertPositionToIVP( velocity, ivpVel ); IVP_U_Float_Point available = ivpVel; // normalize and save length float length = ivpVel.real_length_plus_normize(); IVP_U_Float_Point baseVelocity; baseVelocity.set_to_zero(); float dot = ivpVel.dot_product( &pCore->speed ); if ( dot > 0 ) { ivpVel.mult( dot * length ); available.subtract( &ivpVel ); } pCore->speed.add( &baseVelocity ); IVP_Float_PointAbs( m_maxSpeed, available ); } void CPlayerController::GetShadowVelocity( Vector *velocity ) { IVP_Core *core = m_pObject->GetObject()->get_core(); if ( velocity ) { IVP_U_Float_Point speed; speed.add( &core->speed, &core->speed_change ); if ( m_pGround ) { IVP_U_Float_Point baseVelocity; m_pGround->GetObject()->get_core()->get_surface_speed( &m_groundPosition, &baseVelocity ); speed.subtract( &baseVelocity ); } ConvertPositionToHL( speed, *velocity ); } } bool CPlayerController::IsInContact( void ) { IVP_Real_Object *pivp = m_pObject->GetObject(); if ( !pivp->flags.collision_detection_enabled ) return false; IVP_Synapse_Friction *pfriction = pivp->get_first_friction_synapse(); while ( pfriction ) { extern IVP_Real_Object *GetOppositeSynapseObject( IVP_Synapse_Friction *pfriction ); IVP_Real_Object *pobj = GetOppositeSynapseObject( pfriction ); if ( pobj->flags.collision_detection_enabled ) { // skip if this is a static object if ( !pobj->get_core()->physical_unmoveable && !pobj->get_core()->pinned ) { CPhysicsObject *pPhys = static_cast<CPhysicsObject *>(pobj->client_data); // If this is a game-controlled shadow object, then skip it. // otherwise, we're in contact with something physically simulated if ( !pPhys->IsControlledByGame() ) return true; } } pfriction = pfriction->get_next(); } return false; } IPhysicsPlayerController *CreatePlayerController( CPhysicsObject *pObject ) { return new CPlayerController( pObject ); } void DestroyPlayerController( IPhysicsPlayerController *pController ) { delete pController; } void QuaternionDiff( const IVP_U_Quat &p, const IVP_U_Quat &q, IVP_U_Quat &qt ) { IVP_U_Quat q2; // decide if one of the quaternions is backwards q2.set_invert_unit_quat( &q ); qt.set_mult_quat( &q2, &p ); qt.normize_quat(); } void QuaternionAxisAngle( const IVP_U_Quat &q, Vector &axis, float &angle ) { angle = 2 * acos(q.w); if ( angle > M_PI ) { angle -= 2*M_PI; } axis.Init( q.x, q.y, q.z ); VectorNormalize( axis ); } void GetObjectPosition_IVP( IVP_U_Point &origin, IVP_Real_Object *pivp ) { const IVP_U_Matrix *m_world_f_core = pivp->get_core()->get_m_world_f_core_PSI(); origin.set( m_world_f_core->get_position() ); if (!pivp->flags.shift_core_f_object_is_zero) { IVP_U_Float_Point shift_cs_os_ws; m_world_f_core->vmult3( pivp->get_shift_core_f_object(), &shift_cs_os_ws ); origin.add(&shift_cs_os_ws); } } bool IsZeroVector( const IVP_U_Point &vec ) { return (vec.k[0] == 0.0 && vec.k[1] == 0.0 && vec.k[2] == 0.0 ) ? true : false; } float ComputeShadowControllerIVP( IVP_Real_Object *pivp, shadowcontrol_params_t &params, float secondsToArrival, float dt ) { // resample fraction // This allows us to arrive at the target at the requested time float fraction = 1.0; if ( secondsToArrival > 0 ) { fraction = dt / secondsToArrival; if ( fraction > 1 ) { fraction = 1; } } secondsToArrival -= dt; if ( secondsToArrival < 0 ) { secondsToArrival = 0; } if ( fraction <= 0 ) return secondsToArrival; // --------------------------------------------------------- // Translation // --------------------------------------------------------- IVP_U_Point positionIVP; GetObjectPosition_IVP( positionIVP, pivp ); IVP_U_Float_Point delta_position; delta_position.subtract( &params.targetPosition, &positionIVP); // BUGBUG: Save off velocities and estimate final positions // measure error against these final sets // also, damp out 100% saved velocity, use max additional impulses // to correct error and damp out error velocity // extrapolate position if ( params.teleportDistance > 0 ) { IVP_DOUBLE qdist; if ( !IsZeroVector(params.lastPosition) ) { IVP_U_Float_Point tmpDelta; tmpDelta.subtract( &positionIVP, &params.lastPosition ); qdist = tmpDelta.quad_length(); } else { // UNDONE: This is totally bogus! Measure error using last known estimate // not current position! qdist = delta_position.quad_length(); } if ( qdist > params.teleportDistance * params.teleportDistance ) { if ( pivp->is_collision_detection_enabled() ) { pivp->enable_collision_detection( IVP_FALSE ); pivp->beam_object_to_new_position( &params.targetRotation, &params.targetPosition, IVP_TRUE ); pivp->enable_collision_detection( IVP_TRUE ); } else { pivp->beam_object_to_new_position( &params.targetRotation, &params.targetPosition, IVP_TRUE ); } delta_position.set_to_zero(); } } float invDt = 1.0f / dt; IVP_Core *pCore = pivp->get_core(); ComputeController( pCore->speed, delta_position, params.maxSpeed, params.maxDampSpeed, fraction * invDt, params.dampFactor, &params.lastImpulse ); params.lastPosition.add_multiple( &positionIVP, &pCore->speed, dt ); IVP_U_Float_Point deltaAngles; // compute rotation offset IVP_U_Quat deltaRotation; QuaternionDiff( params.targetRotation, pCore->q_world_f_core_next_psi, deltaRotation ); // convert offset to angular impulse Vector axis; float angle; QuaternionAxisAngle( deltaRotation, axis, angle ); VectorNormalize(axis); deltaAngles.k[0] = axis.x * angle; deltaAngles.k[1] = axis.y * angle; deltaAngles.k[2] = axis.z * angle; ComputeController( pCore->rot_speed, deltaAngles, params.maxAngular, params.maxDampAngular, fraction * invDt, params.dampFactor, NULL ); return secondsToArrival; } void ConvertShadowControllerToIVP( const hlshadowcontrol_params_t &in, shadowcontrol_params_t &out ) { ConvertPositionToIVP( in.targetPosition, out.targetPosition ); ConvertRotationToIVP( in.targetRotation, out.targetRotation ); out.teleportDistance = ConvertDistanceToIVP( in.teleportDistance ); out.maxSpeed = ConvertDistanceToIVP( in.maxSpeed ); out.maxDampSpeed = ConvertDistanceToIVP( in.maxDampSpeed ); out.maxAngular = ConvertAngleToIVP( in.maxAngular ); out.maxDampAngular = ConvertAngleToIVP( in.maxDampAngular ); out.dampFactor = in.dampFactor; } void ConvertShadowControllerToHL( const shadowcontrol_params_t &in, hlshadowcontrol_params_t &out ) { ConvertPositionToHL( in.targetPosition, out.targetPosition ); ConvertRotationToHL( in.targetRotation, out.targetRotation ); out.teleportDistance = ConvertDistanceToHL( in.teleportDistance ); out.maxSpeed = ConvertDistanceToHL( in.maxSpeed ); out.maxDampSpeed = ConvertDistanceToHL( in.maxDampSpeed ); out.maxAngular = ConvertAngleToHL( in.maxAngular ); out.maxDampAngular = ConvertAngleToHL( in.maxDampAngular ); out.dampFactor = in.dampFactor; } float ComputeShadowControllerHL( CPhysicsObject *pObject, const hlshadowcontrol_params_t &params, float secondsToArrival, float dt ) { shadowcontrol_params_t ivpParams; ConvertShadowControllerToIVP( params, ivpParams ); return ComputeShadowControllerIVP( pObject->GetObject(), ivpParams, secondsToArrival, dt ); } class CShadowController : public IVP_Controller_Independent, public IPhysicsShadowController, public CAlignedNewDelete<16> { public: CShadowController(); CShadowController( CPhysicsObject *pObject, bool allowTranslation, bool allowRotation ); ~CShadowController( void ); // ipion interfaces void do_simulation_controller( IVP_Event_Sim *es,IVP_U_Vector<IVP_Core> *cores); virtual IVP_CONTROLLER_PRIORITY get_controller_priority() { return IVP_CP_MOTION; } virtual const char *get_controller_name() { return "vphysics:shadow"; } void SetObject( IPhysicsObject *pObject ); void Update( const Vector &position, const QAngle &angles, float secondsToArrival ); void MaxSpeed( float maxSpeed, float maxAngularSpeed ); virtual void StepUp( float height ); virtual void SetTeleportDistance( float teleportDistance ); virtual bool AllowsTranslation() { return m_allowsTranslation; } virtual bool AllowsRotation() { return m_allowsRotation; } virtual void GetLastImpulse( Vector *pOut ) { ConvertPositionToHL( m_shadow.lastImpulse, *pOut ); } bool IsEnabled() { return m_enabled; } void Enable( bool bEnable ) { m_enabled = bEnable; } void WriteToTemplate( vphysics_save_cshadowcontroller_t &controllerTemplate ); void InitFromTemplate( const vphysics_save_cshadowcontroller_t &controllerTemplate ); virtual void SetPhysicallyControlled( bool isPhysicallyControlled ) { m_isPhysicallyControlled = isPhysicallyControlled; } virtual bool IsPhysicallyControlled() { return m_isPhysicallyControlled; } virtual void UseShadowMaterial( bool bUseShadowMaterial ) { if ( !m_pObject ) return; int current = m_pObject->GetMaterialIndexInternal(); int target = bUseShadowMaterial ? MATERIAL_INDEX_SHADOW : m_savedMaterialIndex; if ( target != current ) { m_pObject->SetMaterialIndex( target ); } } virtual void ObjectMaterialChanged( int materialIndex ) { if ( !m_pObject ) return; m_savedMaterialIndex = materialIndex; } //Basically get the last inputs to IPhysicsShadowController::Update(), returns last input to timeOffset in Update() virtual float GetTargetPosition( Vector *pPositionOut, QAngle *pAnglesOut ); virtual float GetTeleportDistance( void ); virtual void GetMaxSpeed( float *pMaxSpeedOut, float *pMaxAngularSpeedOut ); private: void AttachObject( void ); void DetachObject( void ); shadowcontrol_params_t m_shadow; IVP_U_Float_Point m_saveRot; IVP_U_Float_Point m_savedRI; CPhysicsObject *m_pObject; float m_secondsToArrival; float m_savedMass; unsigned int m_savedFlags; unsigned short m_savedMaterialIndex; bool m_enabled : 1; bool m_allowsTranslation : 1; bool m_allowsRotation : 1; bool m_isPhysicallyControlled : 1; }; CShadowController::CShadowController() { m_shadow.targetPosition.set_to_zero(); m_shadow.targetRotation.init(); } CShadowController::CShadowController( CPhysicsObject *pObject, bool allowTranslation, bool allowRotation ) { m_pObject = pObject; m_shadow.dampFactor = 1.0f; m_shadow.teleportDistance = 0; m_shadow.maxDampSpeed = 0; m_shadow.maxDampAngular = 0; m_shadow.targetPosition.set_to_zero(); m_shadow.targetRotation.init(); m_allowsTranslation = allowTranslation; m_allowsRotation = allowRotation; m_isPhysicallyControlled = false; m_enabled = false; AttachObject(); } CShadowController::~CShadowController( void ) { DetachObject(); } void CShadowController::AttachObject( void ) { IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); m_saveRot = pCore->rot_speed_damp_factor; m_savedRI = *pCore->get_rot_inertia(); m_savedMass = pCore->get_mass(); m_savedMaterialIndex = m_pObject->GetMaterialIndexInternal(); Vector position; QAngle angles; m_pObject->GetPosition( &position, &angles ); ConvertPositionToIVP( position, m_shadow.targetPosition ); ConvertRotationToIVP( angles, m_shadow.targetRotation ); UseShadowMaterial( true ); pCore->rot_speed_damp_factor = IVP_U_Float_Point( 100, 100, 100 ); if ( !m_allowsRotation ) { IVP_U_Float_Point ri( 1e15f, 1e15f, 1e15f ); pCore->set_rotation_inertia( &ri ); } if ( !m_allowsTranslation ) { m_pObject->SetMass( VPHYSICS_MAX_MASS ); //pCore->inv_rot_inertia.hesse_val = 0.0f; m_pObject->EnableGravity( false ); } m_savedFlags = m_pObject->CallbackFlags(); unsigned int flags = m_savedFlags | CALLBACK_SHADOW_COLLISION; flags &= ~CALLBACK_GLOBAL_FRICTION; flags &= ~CALLBACK_GLOBAL_COLLIDE_STATIC; m_pObject->SetCallbackFlags( flags ); m_pObject->EnableDrag( false ); pCore->calc_calc(); pivp->get_environment()->get_controller_manager()->add_controller_to_core( this, pCore ); m_shadow.lastPosition.set_to_zero(); } void CShadowController::DetachObject( void ) { IVP_Real_Object *pivp = m_pObject->GetObject(); IVP_Core *pCore = pivp->get_core(); // don't bother if we're just doing this to delete the object if ( !(m_pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) ) { pCore->rot_speed_damp_factor = m_saveRot; pCore->set_mass( m_savedMass ); m_pObject->SetCallbackFlags( m_savedFlags ); m_pObject->EnableDrag( true ); m_pObject->EnableGravity( true ); UseShadowMaterial( false ); pCore->set_rotation_inertia( &m_savedRI ); // this calls calc_calc() } m_pObject = NULL; pivp->get_environment()->get_controller_manager()->remove_controller_from_core( this, pCore ); } void CShadowController::SetObject( IPhysicsObject *pObject ) { CPhysicsObject *obj = (CPhysicsObject *)pObject; if ( obj == m_pObject ) return; DetachObject(); m_pObject = obj; AttachObject(); } void CShadowController::StepUp( float height ) { Vector step( 0, 0, height ); IVP_Real_Object *pIVP = m_pObject->GetObject(); IVP_U_Quat world_f_object; IVP_U_Point positionIVP, deltaIVP; ConvertPositionToIVP( step, deltaIVP ); pIVP->get_quat_world_f_object_AT( &world_f_object, &positionIVP ); positionIVP.add( &deltaIVP ); pIVP->beam_object_to_new_position( &world_f_object, &positionIVP, IVP_TRUE ); } void CShadowController::SetTeleportDistance( float teleportDistance ) { m_shadow.teleportDistance = ConvertDistanceToIVP( teleportDistance ); } float CShadowController::GetTeleportDistance( void ) { return ConvertDistanceToHL( m_shadow.teleportDistance ); } void CShadowController::do_simulation_controller( IVP_Event_Sim *es,IVP_U_Vector<IVP_Core> *) { if ( IsEnabled() ) { IVP_Real_Object *pivp = m_pObject->GetObject(); Assert(!pivp->get_core()->pinned && !pivp->get_core()->physical_unmoveable); ComputeShadowControllerIVP( pivp, m_shadow, m_secondsToArrival, es->delta_time ); if ( m_allowsTranslation ) { // UNDONE: Assumes gravity points down const IVP_U_Point *pgrav = pivp->get_environment()->get_gravity(); float gravDt = pgrav->k[1] * es->delta_time; if ( m_shadow.lastImpulse.k[1] > gravDt ) { if ( IsOnGround( pivp ) ) { float delta = gravDt - m_shadow.lastImpulse.k[1]; pivp->get_core()->speed.k[1] += delta; m_shadow.lastImpulse.k[1] += delta; } } } // if we have time left, subtract it off m_secondsToArrival -= es->delta_time; if ( m_secondsToArrival < 0 ) { m_secondsToArrival = 0; } } else { m_shadow.lastPosition.set_to_zero(); } } // NOTE: This isn't a test for equivalent orientations, it's a test for calling update // with EXACTLY the same data repeatedly static bool IsEqual( const IVP_U_Point &pt0, const IVP_U_Point &pt1 ) { return pt0.quad_distance_to( &pt1 ) < 1e-8f ? true : false; } // NOTE: This isn't a test for equivalent orientations, it's a test for calling update // with EXACTLY the same data repeatedly static bool IsEqual( const IVP_U_Quat &pt0, const IVP_U_Quat &pt1 ) { float delta = fabs(pt0.x - pt1.x); delta += fabs(pt0.y - pt1.y); delta += fabs(pt0.z - pt1.z); delta += fabs(pt0.w - pt1.w); return delta < 1e-8f ? true : false; } void CShadowController::Update( const Vector &position, const QAngle &angles, float secondsToArrival ) { IVP_U_Point targetPosition = m_shadow.targetPosition; IVP_U_Quat targetRotation = m_shadow.targetRotation; ConvertPositionToIVP( position, m_shadow.targetPosition ); m_secondsToArrival = secondsToArrival < 0 ? 0 : secondsToArrival; ConvertRotationToIVP( angles, m_shadow.targetRotation ); Enable( true ); if ( IsEqual( targetPosition, m_shadow.targetPosition ) && IsEqual( targetRotation, m_shadow.targetRotation ) ) return; m_pObject->Wake(); } float CShadowController::GetTargetPosition( Vector *pPositionOut, QAngle *pAnglesOut ) { if( pPositionOut ) ConvertPositionToHL( m_shadow.targetPosition, *pPositionOut ); if( pAnglesOut ) ConvertRotationToHL( m_shadow.targetRotation, *pAnglesOut ); return m_secondsToArrival; } void CShadowController::MaxSpeed( float maxSpeed, float maxAngularSpeed ) { // UNDONE: Turn this on when shadow controllers are having velocity updated per frame // right now this has the effect of making dampspeed zero by default. #if 0 IVP_Core *pCore = m_pObject->GetObject()->get_core(); { // limit additional velocity to that which is not amplifying the current velocity float availableSpeed = ConvertDistanceToIVP( maxSpeed ); float currentSpeed = pCore->speed.real_length(); m_shadow.maxDampSpeed = min(currentSpeed, availableSpeed); m_shadow.maxSpeed = availableSpeed - m_shadow.maxDampSpeed; } { // limit additional velocity to that which is not amplifying the current velocity float availableAngularSpeed = ConvertAngleToIVP( maxAngularSpeed ); float currentAngularSpeed = pCore->rot_speed.real_length(); m_shadow.maxDampAngular = min(currentAngularSpeed, availableAngularSpeed); m_shadow.maxAngular = availableAngularSpeed - m_shadow.maxDampAngular; } #else m_shadow.maxSpeed = maxSpeed; m_shadow.maxDampSpeed = maxSpeed; m_shadow.maxAngular = maxAngularSpeed; m_shadow.maxDampAngular = maxAngularSpeed; #endif } void CShadowController::GetMaxSpeed( float *pMaxSpeedOut, float *pMaxAngularSpeedOut ) { if( pMaxSpeedOut ) *pMaxSpeedOut = m_shadow.maxSpeed; if( pMaxAngularSpeedOut ) *pMaxAngularSpeedOut = m_shadow.maxAngular; } struct vphysics_save_shadowcontrolparams_t : public hlshadowcontrol_params_t { DECLARE_SIMPLE_DATADESC(); }; BEGIN_SIMPLE_DATADESC( vphysics_save_shadowcontrolparams_t ) DEFINE_FIELD( targetPosition, FIELD_POSITION_VECTOR ), DEFINE_FIELD( targetRotation, FIELD_VECTOR ), DEFINE_FIELD( maxSpeed, FIELD_FLOAT ), DEFINE_FIELD( maxDampSpeed, FIELD_FLOAT ), DEFINE_FIELD( maxAngular, FIELD_FLOAT ), DEFINE_FIELD( maxDampAngular, FIELD_FLOAT ), DEFINE_FIELD( dampFactor, FIELD_FLOAT ), DEFINE_FIELD( teleportDistance, FIELD_FLOAT ), END_DATADESC() struct vphysics_save_cshadowcontroller_t { CPhysicsObject *pObject; float secondsToArrival; IVP_U_Float_Point saveRot; IVP_U_Float_Point savedRI; IVP_U_Float_Point currentSpeed; float savedMass; int savedMaterial; unsigned int savedFlags; bool enable; bool allowPhysicsMovement; bool allowPhysicsRotation; bool isPhysicallyControlled; hlshadowcontrol_params_t shadowParams; DECLARE_SIMPLE_DATADESC(); }; BEGIN_SIMPLE_DATADESC( vphysics_save_cshadowcontroller_t ) //DEFINE_VPHYSPTR( pObject ), DEFINE_FIELD( secondsToArrival, FIELD_FLOAT ), DEFINE_ARRAY( saveRot.k, FIELD_FLOAT, 3 ), DEFINE_ARRAY( savedRI.k, FIELD_FLOAT, 3 ), DEFINE_ARRAY( currentSpeed.k, FIELD_FLOAT, 3 ), DEFINE_FIELD( savedMass, FIELD_FLOAT ), DEFINE_FIELD( savedFlags, FIELD_INTEGER ), DEFINE_CUSTOM_FIELD( savedMaterial, MaterialIndexDataOps() ), DEFINE_FIELD( enable, FIELD_BOOLEAN ), DEFINE_FIELD( allowPhysicsMovement, FIELD_BOOLEAN ), DEFINE_FIELD( allowPhysicsRotation, FIELD_BOOLEAN ), DEFINE_FIELD( isPhysicallyControlled, FIELD_BOOLEAN ), DEFINE_EMBEDDED_OVERRIDE( shadowParams, vphysics_save_shadowcontrolparams_t ), END_DATADESC() void CShadowController::WriteToTemplate( vphysics_save_cshadowcontroller_t &controllerTemplate ) { controllerTemplate.pObject = m_pObject; controllerTemplate.secondsToArrival = m_secondsToArrival; controllerTemplate.saveRot = m_saveRot; controllerTemplate.savedRI = m_savedRI; controllerTemplate.savedMass = m_savedMass; controllerTemplate.savedFlags = m_savedFlags; controllerTemplate.savedMaterial = m_savedMaterialIndex; controllerTemplate.enable = IsEnabled(); controllerTemplate.allowPhysicsMovement = m_allowsTranslation; controllerTemplate.allowPhysicsRotation = m_allowsRotation; controllerTemplate.isPhysicallyControlled = m_isPhysicallyControlled; ConvertShadowControllerToHL( m_shadow, controllerTemplate.shadowParams ); } void CShadowController::InitFromTemplate( const vphysics_save_cshadowcontroller_t &controllerTemplate ) { m_pObject = controllerTemplate.pObject; m_secondsToArrival = controllerTemplate.secondsToArrival; m_saveRot = controllerTemplate.saveRot; m_savedRI = controllerTemplate.savedRI; m_savedMass = controllerTemplate.savedMass; m_savedFlags = controllerTemplate.savedFlags; m_savedMaterialIndex = controllerTemplate.savedMaterial; Enable( controllerTemplate.enable ); m_allowsTranslation = controllerTemplate.allowPhysicsMovement; m_allowsRotation = controllerTemplate.allowPhysicsRotation; m_isPhysicallyControlled = controllerTemplate.isPhysicallyControlled; ConvertShadowControllerToIVP( controllerTemplate.shadowParams, m_shadow ); m_pObject->GetObject()->get_environment()->get_controller_manager()->add_controller_to_core( this, m_pObject->GetObject()->get_core() ); } IPhysicsShadowController *CreateShadowController( CPhysicsObject *pObject, bool allowTranslation, bool allowRotation ) { return new CShadowController( pObject, allowTranslation, allowRotation ); } bool SavePhysicsShadowController( const physsaveparams_t &params, IPhysicsShadowController *pIShadow ) { vphysics_save_cshadowcontroller_t controllerTemplate; memset( &controllerTemplate, 0, sizeof(controllerTemplate) ); CShadowController *pShadowController = (CShadowController *)pIShadow; pShadowController->WriteToTemplate( controllerTemplate ); params.pSave->WriteAll( &controllerTemplate ); return true; } bool RestorePhysicsShadowController( const physrestoreparams_t &params, IPhysicsShadowController **ppShadowController ) { return false; } bool RestorePhysicsShadowControllerInternal( const physrestoreparams_t &params, IPhysicsShadowController **ppShadowController, CPhysicsObject *pObject ) { vphysics_save_cshadowcontroller_t controllerTemplate; memset( &controllerTemplate, 0, sizeof(controllerTemplate) ); params.pRestore->ReadAll( &controllerTemplate ); // HACKHACK: pass this in controllerTemplate.pObject = pObject; CShadowController *pShadow = new CShadowController(); pShadow->InitFromTemplate( controllerTemplate ); *ppShadowController = pShadow; return true; } bool SavePhysicsPlayerController( const physsaveparams_t &params, CPlayerController *pPlayerController ) { return false; } bool RestorePhysicsPlayerController( const physrestoreparams_t &params, CPlayerController **ppPlayerController ) { return false; } //HACKHACK: The physics object transfer system needs to temporarily detach a shadow controller from an object, then reattach without other repercussions void ControlPhysicsShadowControllerAttachment_Silent( IPhysicsShadowController *pController, IVP_Real_Object *pivp, bool bAttach ) { if( bAttach ) { pivp->get_environment()->get_controller_manager()->add_controller_to_core( (CShadowController *)pController, pivp->get_core() ); } else { pivp->get_environment()->get_controller_manager()->remove_controller_from_core( (CShadowController *)pController, pivp->get_core() ); } } void ControlPhysicsPlayerControllerAttachment_Silent( IPhysicsPlayerController *pController, IVP_Real_Object *pivp, bool bAttach ) { if( bAttach ) { pivp->get_environment()->get_controller_manager()->add_controller_to_core( (CPlayerController *)pController, pivp->get_core() ); } else { pivp->get_environment()->get_controller_manager()->remove_controller_from_core( (CPlayerController *)pController, pivp->get_core() ); } }
[ "bbchallenger100@gmail.com" ]
bbchallenger100@gmail.com
367a1dcda0b4ae5df73f370677c0162d8221dd17
cc89829e63f89d225272af943054d22a6b37ed9d
/deps/common/log/log.h
e7c76c8893264213144073e681067e4d9590e681
[]
no_license
ZZZping/minidb
5dd5e79b2a7258e01ba2802813548e4d6def2ce8
b9e59749f97ebbf3b14caae4b254d43d16edbdc4
refs/heads/main
2023-04-21T11:34:55.339151
2021-05-05T15:34:08
2021-05-05T15:34:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,826
h
// __CR__ // Copyright (c) 2021 LongdaFeng All Rights Reserved // // This software contains the intellectual property of LongdaFeng // or is licensed to LongdaFeng from third parties. Use of this // software and the intellectual property contained therein is // expressly limited to the terms and conditions of the License Agreement // under which it is provided by or on behalf of LongdaFeng. // __CR__ // // Created by Longda on 2010 // #ifndef __COMMON_LOG_LOG_H__ #define __COMMON_LOG_LOG_H__ #include <assert.h> #include <errno.h> #include <fstream> #include <iostream> #include <map> #include <pthread.h> #include <set> #include <string.h> #include <string> #include <time.h> #include "common/defs.h" namespace common { const int LOG_STATUS_OK = 0; const int LOG_STATUS_ERR = 1; const int LOG_MAX_LINE = 100000; typedef enum { LOG_LEVEL_PANIC = 0, LOG_LEVEL_ERR = 1, LOG_LEVEL_WARN = 2, LOG_LEVEL_INFO = 3, LOG_LEVEL_DEBUG = 4, LOG_LEVEL_TRACE = 5, LOG_LEVEL_LAST } LOG_LEVEL; typedef enum { LOG_ROTATE_BYDAY = 0, LOG_ROTATE_BYSIZE, LOG_ROTATE_LAST } LOG_ROTATE; class Log { public: Log(const std::string &logName, const LOG_LEVEL logLevel = LOG_LEVEL_INFO, const LOG_LEVEL consoleLevel = LOG_LEVEL_WARN); ~Log(void); static int init(const std::string &logFile); /** * These functions won't output header information such as __FUNCTION__, * The user should control these information * If the header information should be outputed * please use LOG_PANIC, LOG_ERROR ... */ template<class T> Log &operator<<(T message); template<class T> int Panic(T message); template<class T> int Error(T message); template<class T> int Warnning(T message); template<class T> int Info(T message); template<class T> int Debug(T message); template<class T> int Trace(T message); int Output(const LOG_LEVEL level, const char *module, const char *prefix, const char *f, ...); int SetConsoleLevel(const LOG_LEVEL consoleLevel); LOG_LEVEL GetConsoleLevel(); int SetLogLevel(const LOG_LEVEL logLevel); LOG_LEVEL GetLogLevel(); int SetRotateType(LOG_ROTATE rotateType); LOG_ROTATE GetRotateType(); const char *PrefixMsg(const LOG_LEVEL level); /** * Set Default Module list * if one module is default module, * it will output whatever output level is lower than mLogLevel or not */ void SetDefaultModule(const std::string &modules); bool CheckOutput(const LOG_LEVEL logLevel, const char *module); int Rotate(const int year = 0, const int month = 0, const int day = 0); private: void CheckParamValid(); int RotateBySize(); int RenameOldLogs(); int RotateByDay(const int year, const int month, const int day); template<class T> int Out(const LOG_LEVEL consoleLevel, const LOG_LEVEL logLevel, T &message); private: pthread_mutex_t mLock; std::ofstream mOfs; std::string mLogName; LOG_LEVEL mLogLevel; LOG_LEVEL mConsoleLevel; typedef struct _LogDate { int mYear; int mMon; int mDay; } LogDate; LogDate mLogDate; int mLogLine; int mLogMaxLine; LOG_ROTATE mRotateType; typedef std::map<LOG_LEVEL, std::string> LogPrefixMap; LogPrefixMap mPrefixMap; typedef std::set<std::string> DefaultSet; DefaultSet mDefaultSet; }; class LoggerFactory { public: LoggerFactory(); virtual ~LoggerFactory(); static int init(const std::string &logFile, Log **logger, LOG_LEVEL logLevel = LOG_LEVEL_INFO, LOG_LEVEL consoleLevel = LOG_LEVEL_WARN, LOG_ROTATE rotateType = LOG_ROTATE_BYDAY); static int initDefault(const std::string &logFile, LOG_LEVEL logLevel = LOG_LEVEL_INFO, LOG_LEVEL consoleLevel = LOG_LEVEL_WARN, LOG_ROTATE rotateType = LOG_ROTATE_BYDAY); }; extern Log *gLog; #define LOG_HEAD(prefix, level) \ if (gLog) { \ time_t now_time; \ time(&now_time); \ struct tm *p = localtime(&now_time); \ char szHead[64] = {0}; \ if (p) { \ sprintf(szHead, "%d-%d-%d %d:%d:%u pid:%u tid:%llx ", p->tm_year + 1900, \ p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec, \ (u32_t)getpid(), gettid()); \ gLog->Rotate(p->tm_year + 1900, p->tm_mon + 1, p->tm_mday); \ } \ snprintf(prefix, sizeof(prefix), "[%s %s %s %u %s]>>", szHead, __FILE__, \ __FUNCTION__, (u32_t)__LINE__, (gLog)->PrefixMsg(level)); \ } #define LOG_OUTPUT(level, fmt, ...) \ if (gLog && gLog->CheckOutput(level, __FILE__)) { \ char prefix[ONE_KILO] = {0}; \ LOG_HEAD(prefix, level); \ gLog->Output(level, __FILE__, prefix, fmt, ##__VA_ARGS__); \ } #define LOG_DEFAULT(fmt, ...) \ LOG_OUTPUT(gLog->GetLogLevel(), fmt, ##__VA_ARGS__) #define LOG_PANIC(fmt, ...) LOG_OUTPUT(LOG_LEVEL_PANIC, fmt, ##__VA_ARGS__) #define LOG_ERROR(fmt, ...) LOG_OUTPUT(LOG_LEVEL_ERR, fmt, ##__VA_ARGS__) #define LOG_WARN(fmt, ...) LOG_OUTPUT(LOG_LEVEL_WARN, fmt, ##__VA_ARGS__) #define LOG_INFO(fmt, ...) LOG_OUTPUT(LOG_LEVEL_INFO, fmt, ##__VA_ARGS__) #define LOG_DEBUG(fmt, ...) LOG_OUTPUT(LOG_LEVEL_DEBUG, fmt, ##__VA_ARGS__) #define LOG_TRACE(fmt, ...) LOG_OUTPUT(LOG_LEVEL_TRACE, fmt, ##__VA_ARGS__) template<class T> Log &Log::operator<<(T msg) { // at this time, the input level is the default log level Out(mConsoleLevel, mLogLevel, msg); return *this; } template<class T> int Log::Panic(T message) { return Out(LOG_LEVEL_PANIC, LOG_LEVEL_PANIC, message); } template<class T> int Log::Error(T message) { return Out(LOG_LEVEL_ERR, LOG_LEVEL_ERR, message); } template<class T> int Log::Warnning(T message) { return Out(LOG_LEVEL_WARN, LOG_LEVEL_WARN, message); } template<class T> int Log::Info(T message) { return Out(LOG_LEVEL_INFO, LOG_LEVEL_INFO, message); } template<class T> int Log::Debug(T message) { return Out(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, message); } template<class T> int Log::Trace(T message) { return Out(LOG_LEVEL_TRACE, LOG_LEVEL_TRACE, message); } template<class T> int Log::Out(const LOG_LEVEL consoleLevel, const LOG_LEVEL logLevel, T &msg) { bool locked = false; if (consoleLevel < LOG_LEVEL_PANIC || consoleLevel > mConsoleLevel || logLevel < LOG_LEVEL_PANIC || logLevel > mLogLevel) { return LOG_STATUS_OK; } try { char prefix[ONE_KILO] = {0}; LOG_HEAD(prefix, logLevel); if (LOG_LEVEL_PANIC <= consoleLevel && consoleLevel <= mConsoleLevel) { std::cout << mPrefixMap[consoleLevel] << msg; } if (LOG_LEVEL_PANIC <= logLevel && logLevel <= mLogLevel) { pthread_mutex_lock(&mLock); locked = true; mOfs << prefix; mOfs << msg; mOfs.flush(); mLogLine++; pthread_mutex_unlock(&mLock); locked = false; } } catch (std::exception &e) { if (locked) { pthread_mutex_unlock(&mLock); } std::cerr << e.what() << std::endl; return LOG_STATUS_ERR; } return LOG_STATUS_OK; } #ifndef ASSERT #define ASSERT(expression, description, ...) \ do { \ if (!(expression)) { \ if (gLog) { \ LOG_PANIC(description, ##__VA_ARGS__); \ LOG_PANIC("\n"); \ } \ assert(expression); \ } \ } while (0) #endif // ASSERT #define SYS_OUTPUT_FILE_POS \ ", File:" << __FILE__ << ", line:" << __LINE__ << ",function:" << __FUNCTION__ #define SYS_OUTPUT_ERROR ",error:" << errno << ":" << strerror(errno) } //namespace common #endif //__COMMON_LOG_LOG_H__
[ "hustjackie@outlook.com" ]
hustjackie@outlook.com
07cbe39c69ced466d24db7f1bacd5df4014c691e
54792756ffbbf51f6b088713fd9a791539d95f1f
/Algorithm(2020.04.21)/SwTestPrepare/SwTestPrepare/17822 원판 돌리기.cpp
86d1be24fd41865b2a356ec2401a91850c3ee886
[]
no_license
3DPIT/algorithmTest
bef932d2b83b3e661b9db47672f0ad50ab4f8cb6
8c1fc46536b8962a2944056574e5a5a4b4c0f94b
refs/heads/master
2021-07-16T20:33:57.362620
2020-10-22T06:26:06
2020-10-22T06:26:06
220,213,352
0
0
null
null
null
null
UHC
C++
false
false
2,548
cpp
#include<stdio.h> #include<string.h> using namespace std; #define NS 52 int N, M, T; int map[NS][NS]; int chk[NS][NS]; int flag = 0; int dFlag = 0; int dy[] = { 0,1,0,-1 }; int dx[] = { 1,0,-1,0 }; int ret = 0; struct CircleRotation { CircleRotation() { scanf("%d %d %d", &N, &M, &T); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { scanf("%d", &map[i][j]); } } for (int ti = 0; ti < T; ti++) { int num, dir, cnt; scanf("%d %d %d", &num, &dir, &cnt); Rotation(num, dir, cnt); } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { ret += map[i][j]; } } printf("%d\n", ret); } void Rotation(int num, int dir, int cnt) { for (int i = 1; i <= N; i++) { if (i%num == 0) { if (dir == 0) { for (int cnti = 0; cnti < cnt; cnti++)//줄일 수 있음 clock(i - 1); } else { for (int cnti = 0; cnti < cnt; cnti++)//줄일 수 있음 reclock(i - 1); } } } pDfs(); if (dFlag == 0) { sumArr(); } dFlag = 0; } void sumArr() { int sum = 0; int cnt = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (map[i][j] != 0) { sum += map[i][j]; cnt++; } } } float dsum = 0; if (sum != 0) dsum = (float)sum / cnt; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (map[i][j]!=0&&map[i][j] < dsum)map[i][j]++; else if (map[i][j] != 0 && map[i][j] > dsum)map[i][j]--; } } } void pDfs() { memset(chk, 0, sizeof(chk)); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (chk[i][j] == 0) { chk[i][j] = 1; int num = map[i][j]; if (num != 0) { dfs(i, j, num); } if (flag == 1) { dFlag = 1; map[i][j] = 0; } chk[i][j] = 0; flag = 0; } } } } void dfs(int y, int x, int num) { for (int dir = 0; dir < 4; dir++) { int ny = y + dy[dir]; int nx = x + dx[dir]; if (0 > ny)continue; if (0 > nx)nx = M - 1; if (ny >= N)continue; if (nx >= M)nx = 0; if (map[ny][nx]!=0&&chk[ny][nx] == 0 && map[ny][nx] == num) { flag = 1; chk[ny][nx] = 1; map[ny][nx] = 0; dfs(ny, nx,num); } } } void reclock(int idx) { int num = map[idx][0]; for (int i = 1; i < M; i++) { map[idx][i-1] = map[idx][i]; } map[idx][M-1] = num; } void clock(int idx) { int num = map[idx][M-1]; for (int i = M-2; i >=0; i--) { map[idx][i + 1] = map[idx][i]; } map[idx][0] = num; } }ca; int main(void) { //CircleRotation ca; return 0; }
[ "47946136+3DPIT@users.noreply.github.com" ]
47946136+3DPIT@users.noreply.github.com
243ea43a1747bd44abc0c9aca4af0def87776d40
94a61fcf44a93ba39f0dff165814b423950f0229
/StandaloneCode/C_C++/old/binary_node.h
e8030a113397ed75f40733ff8907c0b45fad88ba
[]
no_license
jstty/OlderProjects
e9c8438dc6fe066e3d1bc2f36e937e7c72625192
4e64babeef2384d3882484a50e1c788784b08a05
refs/heads/master
2021-01-23T22:53:21.630742
2013-07-08T01:58:27
2013-07-08T01:58:27
10,214,450
1
0
null
null
null
null
UTF-8
C++
false
false
754
h
/* filename: binary_node.h binary tree node */ #ifndef BINARY_NODE_H #define BINARY_NODE_H /* error codes */ enum Error_code { success = 0, fail, range_error, underflow, overflow, fatal, not_present, duplicate_error, entry_inserted, entry_found, internal_error }; template <class T> class Binary_node { public: Binary_node(); Binary_node(const T &x); const T & getData() const { return data; } void setData( T x ) { data = x; } T data; Binary_node<T> *left; Binary_node<T> *right; }; template <class T> Binary_node<T>::Binary_node() { left = right = NULL; } template <class T> Binary_node<T>::Binary_node(const T &x) { left = right = NULL; data = x; } #endif
[ "joe@jstty.com" ]
joe@jstty.com
38fae2c10e860e345ac4f03203d25af2b76681b8
5f39f1f5ee701fc265674f40286aa2e7c428a1e2
/count_number_with_unique_digits.cpp
41354cced58643cc52e170e8a53727e7af2e602f
[]
no_license
apassi99/LeetCode
4e2126d8dbfa6396d646a829228fbd8b35fb4895
94174962031ede2aef031273d7d92536d0ede0aa
refs/heads/master
2021-09-14T10:52:52.012884
2021-08-18T05:40:04
2021-08-18T05:40:04
44,773,452
0
1
null
null
null
null
UTF-8
C++
false
false
417
cpp
class Solution { public: int countNumbersWithUniqueDigits(int n) { if (n == 0) return 1; if (n == 1) return 10; int cpy_n = n; int result = 1; if (n > 9) { cpy_n = 9; } for (int i = 0; i < cpy_n; i++) { result *= (i+1 == cpy_n) ? 9 : (9 - i); } return result + countNumbersWithUniqueDigits(n-1); } };
[ "apassi@live.com" ]
apassi@live.com
9992af64ed07f086e9aac5dfeb50adea132f7ac9
4ee11cdd0b47b467d4572315e45310265a1fbbd3
/application/sources/skeleton_graphics_node_item.h
6d55ace46b4ac1b80e96211d30122a56d1e58e3b
[ "MIT" ]
permissive
huxingyi/dust3d
88d9e3d3a927bbb4a762c963f98e581dc90ea628
94901fa67ca672061bd0b1d0b754a5aef768dd98
refs/heads/master
2023-08-16T13:05:15.397377
2023-08-13T07:14:30
2023-08-13T08:41:12
76,565,839
2,829
219
MIT
2023-08-26T02:46:58
2016-12-15T14:17:55
C++
UTF-8
C++
false
false
1,037
h
#ifndef DUST3D_APPLICATION_SKELETON_NODE_ITEM_H_ #define DUST3D_APPLICATION_SKELETON_NODE_ITEM_H_ #include "document.h" #include <QGraphicsEllipseItem> class SkeletonGraphicsNodeItem : public QGraphicsEllipseItem { public: SkeletonGraphicsNodeItem(Document::Profile profile = Document::Profile::Unknown); void setRotated(bool rotated); void updateAppearance(); void setOrigin(QPointF point); QPointF origin(); float radius(); void setRadius(float radius); void setMarkColor(QColor color); Document::Profile profile(); dust3d::Uuid id(); void setId(dust3d::Uuid id); void setHovered(bool hovered); void setChecked(bool checked); void setDeactivated(bool deactivated); bool deactivated(); bool checked(); bool hovered(); private: dust3d::Uuid m_uuid; Document::Profile m_profile = Document::Profile::Unknown; bool m_hovered = false; bool m_checked = false; QColor m_markColor; bool m_deactivated = false; bool m_rotated = false; }; #endif
[ "huxingyi@msn.com" ]
huxingyi@msn.com
07ab20e8c0039a7fa8285388b34012ff2aaa34d2
a091d500abbda0a3e36898b23075744c5a36433d
/ecs/src/view_synchronizer_test.cpp
ed7fbe36e07fce05cdfe95251a1645a29daa04b1
[ "MIT" ]
permissive
FabianHahn/shoveler
e996a50dd9d9e40442bd5e562fdbc45b1760b06c
2f602fe2edc4bb99f74e570115fc733ecc80503c
refs/heads/master
2023-08-31T00:52:54.630367
2023-08-28T12:45:01
2023-08-28T13:28:42
60,905,873
34
1
MIT
2022-12-14T16:43:36
2016-06-11T12:23:16
C
UTF-8
C++
false
false
20,750
cpp
#include <gmock/gmock.h> #include <gtest/gtest.h> #include "client_network_adapter_event_wrapper.h" #include <vector> extern "C" { #include <shoveler/component.h> #include <shoveler/in_memory_network_adapter.h> #include <shoveler/schema.h> #include <shoveler/server_op.h> #include <shoveler/system.h> #include <shoveler/view_synchronizer.h> #include "test_component_types.h" } using ::testing::ElementsAre; using ::testing::IsEmpty; using ::testing::SizeIs; using ::testing::UnorderedElementsAre; namespace { const long long int testEntityId1 = 1; const long long int testEntityId2 = 2; const long long int testEntityId3 = 3; const long long int testEntityId4 = 4; const long long int testEntityId5 = 5; const auto* testDisconnectReason = "goodbye"; void onClientConnected( ShovelerViewSynchronizer* viewSynchronizer, int64_t clientId, void* userData); void onClientDisconnected( ShovelerViewSynchronizer* viewSynchronizer, int64_t clientId, const char* reason, void* userData); static bool receiveClientEvent( const ShovelerClientNetworkAdapterEvent* event, void* resultPointer) { auto& result = *static_cast<ShovelerClientNetworkAdapterEventWrapper*>(resultPointer); result.Assign(event); return true; } class ShovelerViewSynchronizerTest : public ::testing::Test { public: virtual void SetUp() { inMemoryNetworkAdapter = shovelerInMemoryNetworkAdapterCreate(); schema = shovelerSchemaCreate(); ShovelerComponentType* componentType1 = shovelerCreateTestComponentType1(); ShovelerComponentType* componentType2 = shovelerCreateTestComponentType2(); ShovelerComponentType* componentType3 = shovelerCreateTestComponentType3(); shovelerSchemaAddComponentType(schema, componentType1); shovelerSchemaAddComponentType(schema, componentType2); shovelerSchemaAddComponentType(schema, componentType3); system = shovelerSystemCreate(); callbacks.onClientConnected = onClientConnected; callbacks.onClientDisconnected = onClientDisconnected; callbacks.userData = this; ShovelerServerNetworkAdapter* serverNetworkAdapter = shovelerInMemoryNetworkAdapterGetServer(inMemoryNetworkAdapter); viewSynchronizer = shovelerViewSynchronizerCreate(schema, system, serverNetworkAdapter, &callbacks); server = shovelerViewSynchronizerGetServerController(viewSynchronizer); world = shovelerViewSynchronizerGetWorld(viewSynchronizer); entity1 = shovelerWorldAddEntity(world, testEntityId1); entity1Component1 = shovelerWorldEntityAddComponent(entity1, componentType1Id); entity1Component2 = shovelerWorldEntityAddComponent(entity1, componentType2Id); entity2 = shovelerWorldAddEntity(world, testEntityId2); entity2Component1 = shovelerWorldEntityAddComponent(entity2, componentType1Id); entity3 = shovelerWorldAddEntity(world, testEntityId3); entity3Component3 = shovelerWorldEntityAddComponent(entity3, componentType3Id); } virtual void TearDown() { shovelerViewSynchronizerFree(viewSynchronizer); shovelerSystemFree(system); shovelerSchemaFree(schema); shovelerInMemoryNetworkAdapterFree(inMemoryNetworkAdapter); } bool SendAddEntityInterest(ShovelerClientNetworkAdapter* client, long long int entityId) { ShovelerServerOp serverOp = shovelerServerOp(); serverOp.type = SHOVELER_SERVER_OP_ADD_ENTITY_INTEREST; serverOp.addEntityInterest.entityId = entityId; return SendServerOp(client, &serverOp); } bool SendRemoveEntityInterest(ShovelerClientNetworkAdapter* client, long long int entityId) { ShovelerServerOp serverOp = shovelerServerOp(); serverOp.type = SHOVELER_SERVER_OP_REMOVE_ENTITY_INTEREST; serverOp.removeEntityInterest.entityId = entityId; return SendServerOp(client, &serverOp); } bool SendUpdateComponent( ShovelerClientNetworkAdapter* client, long long int entityId, const char* componentTypeId, int fieldId, const ShovelerComponentFieldValue* fieldValue) { ShovelerServerOp serverOp = shovelerServerOp(); serverOp.type = SHOVELER_SERVER_OP_UPDATE_COMPONENT; serverOp.updateComponent.entityId = entityId; serverOp.updateComponent.componentTypeId = componentTypeId; serverOp.updateComponent.fieldId = fieldId; serverOp.updateComponent.fieldValue = fieldValue; return SendServerOp(client, &serverOp); } bool SendServerOp(ShovelerClientNetworkAdapter* client, const ShovelerServerOp* serverOp) { auto deleter = [](GString* string) { g_string_free(string, /* freeSegment */ true); }; std::unique_ptr<GString, decltype(deleter)> buffer{g_string_new(""), deleter}; if (!shovelerServerOpSerialize( serverOp, viewSynchronizer->componentTypeIndexer, buffer.get())) { return false; } return client->sendMessage( reinterpret_cast<const unsigned char*>(buffer->str), static_cast<int>(buffer->len), client->userData); } std::vector<ShovelerClientOpWrapper> ReceiveClientOps( ShovelerClientNetworkAdapter* client, int maxOps = -1) { std::vector<ShovelerClientOpWrapper> result; ShovelerClientNetworkAdapterEventWrapper event; int numOps = 0; while (client->receiveEvent(receiveClientEvent, &event, client->userData)) { if (event->type == SHOVELER_CLIENT_NETWORK_ADAPTER_EVENT_TYPE_MESSAGE) { ShovelerClientOpWrapper deserializedOp; int readIndex = 0; if (!shovelerClientOpDeserialize( deserializedOp.opWithData, viewSynchronizer->componentTypeIndexer, reinterpret_cast<const unsigned char*>(event->payload->str), static_cast<int>(event->payload->len), &readIndex)) { continue; } result.push_back(deserializedOp); numOps++; if (numOps == maxOps) { break; } } } return result; } ShovelerInMemoryNetworkAdapter* inMemoryNetworkAdapter; ShovelerSchema* schema; ShovelerSystem* system; ShovelerViewSynchronizerCallbacks callbacks; ShovelerViewSynchronizer* viewSynchronizer; ShovelerServerController* server; ShovelerWorld* world; ShovelerWorldEntity* entity1; ShovelerComponent* entity1Component1; ShovelerComponent* entity1Component2; ShovelerWorldEntity* entity2; ShovelerComponent* entity2Component1; ShovelerWorldEntity* entity3; ShovelerComponent* entity3Component3; std::vector<int64_t> clientConnectedCalls; std::vector<int64_t> clientDisconnectedCalls; }; void onClientConnected( ShovelerViewSynchronizer* viewSynchronizer, int64_t clientId, void* testPointer) { auto* test = static_cast<ShovelerViewSynchronizerTest*>(testPointer); test->clientConnectedCalls.push_back(clientId); } void onClientDisconnected( ShovelerViewSynchronizer* viewSynchronizer, int64_t clientId, const char* reason, void* testPointer) { auto* test = static_cast<ShovelerViewSynchronizerTest*>(testPointer); test->clientDisconnectedCalls.push_back(clientId); } } // namespace TEST_F(ShovelerViewSynchronizerTest, connectDisconnect) { void* clientHandle = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); ASSERT_NE(clientHandle, nullptr); shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT(clientConnectedCalls, SizeIs(1)); bool disconnecting = shovelerInMemoryNetworkAdapterDisconnectClient( inMemoryNetworkAdapter, clientHandle, testDisconnectReason); ASSERT_TRUE(disconnecting); shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT(clientDisconnectedCalls, SizeIs(1)); } TEST_F(ShovelerViewSynchronizerTest, checkoutUncheckout) { void* clientHandle = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); auto* client = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle); shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT(clientConnectedCalls, SizeIs(1)); auto clientId = clientConnectedCalls[0]; // Predelegate components on the entity we are going to add interest to. bool delegated = shovelerServerControllerDelegateComponent(server, testEntityId1, componentType3Id, clientId); ASSERT_TRUE(delegated); // Add interest over preexisting entity and assure it gets checked out. bool addEntityInterestSent = SendAddEntityInterest(client, testEntityId1); ASSERT_TRUE(addEntityInterestSent); shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT( ReceiveClientOps(client, 2), ElementsAre( IsAddEntityOp(testEntityId1), IsDelegateComponentOp(testEntityId1, componentType3Id))); ASSERT_THAT( ReceiveClientOps(client, 6), UnorderedElementsAre( IsAddComponentOp(testEntityId1, componentType1Id), IsUpdateComponentOp(testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_PRIMITIVE), IsUpdateComponentOp( testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE), IsUpdateComponentOp( testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE), IsAddComponentOp(testEntityId1, componentType2Id), IsUpdateComponentOp( testEntityId1, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE))); ASSERT_THAT( ReceiveClientOps(client), UnorderedElementsAre( IsActivateComponentOp(testEntityId1, componentType1Id), IsActivateComponentOp(testEntityId1, componentType2Id))); // Remove interest over the entity and assure it gets uncheckouted. bool removeEntityInterestSent = SendRemoveEntityInterest(client, testEntityId1); ASSERT_TRUE(removeEntityInterestSent); shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT(ReceiveClientOps(client), ElementsAre(IsRemoveEntityOp(testEntityId1))); } TEST_F(ShovelerViewSynchronizerTest, addRemove) { void* clientHandle1 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); void* clientHandle2 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); auto* client1 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle1); auto* client2 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle2); // Make client 1 interest in the entity we're going to create and modify, and client 2 in another // entity that will never exist. SendAddEntityInterest(client1, testEntityId4); SendAddEntityInterest(client2, testEntityId5); shovelerViewSynchronizerUpdate(viewSynchronizer); auto clientId1 = clientConnectedCalls[0]; // Mess around with entity 4, and assure that client 1 sees it all while client 2 sees none of it. auto* entity4 = shovelerWorldAddEntity(world, testEntityId4); auto* entity4Component2 = shovelerWorldEntityAddComponent(entity4, componentType2Id); bool updated = shovelerComponentUpdateField( entity4Component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, &entity1Component2->fieldValues[COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE], /* isCanonical */ true); ASSERT_TRUE(updated); shovelerServerControllerDelegateComponent(server, testEntityId4, componentType2Id, clientId1); shovelerServerControllerUndelegateComponent(server, testEntityId4, componentType2Id, clientId1); shovelerServerControllerDeactivateComponent(server, testEntityId4, componentType2Id, clientId1); shovelerServerControllerUndeactivateComponent(server, testEntityId4, componentType2Id, clientId1); shovelerWorldEntityRemoveComponent(entity4, componentType2Id); shovelerWorldRemoveEntity(world, testEntityId4); ASSERT_THAT( ReceiveClientOps(client1), ElementsAre( IsAddEntityOp(testEntityId4), IsAddComponentOp(testEntityId4, componentType2Id), IsActivateComponentOp(testEntityId4, componentType2Id), IsUpdateComponentOp( testEntityId4, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE), IsDelegateComponentOp(testEntityId4, componentType2Id), IsUndelegateComponentOp(testEntityId4, componentType2Id), IsDeactivateComponentOp(testEntityId4, componentType2Id), IsActivateComponentOp(testEntityId4, componentType2Id), IsRemoveComponentOp(testEntityId4, componentType2Id), IsRemoveEntityOp(testEntityId4))); ASSERT_THAT(ReceiveClientOps(client2), IsEmpty()); } TEST_F(ShovelerViewSynchronizerTest, fanout) { void* clientHandle1 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); void* clientHandle2 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); void* clientHandle3 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); auto* client1 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle1); auto* client2 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle2); auto* client3 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle3); SendAddEntityInterest(client1, testEntityId1); SendAddEntityInterest(client1, testEntityId2); SendAddEntityInterest(client2, testEntityId1); shovelerViewSynchronizerUpdate(viewSynchronizer); // Flush received ops for all clients. ReceiveClientOps(client1); ReceiveClientOps(client2); ReceiveClientOps(client3); // Updating entity 1 should be fanned out to clients 1 and 2. shovelerComponentUpdateField( entity1Component1, COMPONENT_TYPE_1_FIELD_PRIMITIVE, &entity1Component1->fieldValues[COMPONENT_TYPE_1_FIELD_PRIMITIVE], /* isCanonical */ true); shovelerComponentUpdateField( entity1Component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, &entity1Component1->fieldValues[COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE], /* isCanonical */ true); shovelerComponentUpdateField( entity1Component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, &entity1Component1->fieldValues[COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE], /* isCanonical */ true); shovelerComponentUpdateField( entity1Component2, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, &entity1Component2->fieldValues[COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE], /* isCanonical */ true); // Updating entity 2 should only be fanned out to client 1. shovelerComponentUpdateField( entity2Component1, COMPONENT_TYPE_1_FIELD_PRIMITIVE, &entity2Component1->fieldValues[COMPONENT_TYPE_1_FIELD_PRIMITIVE], /* isCanonical */ true); shovelerComponentUpdateField( entity2Component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE, &entity2Component1->fieldValues[COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE], /* isCanonical */ true); shovelerComponentUpdateField( entity2Component1, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE, &entity2Component1->fieldValues[COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE], /* isCanonical */ true); // Nobody should see updates to entity 3. shovelerComponentUpdateField( entity3Component3, COMPONENT_TYPE_3_FIELD_DEPENDENCY, &entity3Component3->fieldValues[COMPONENT_TYPE_3_FIELD_DEPENDENCY], /* isCanonical */ true); ASSERT_THAT( ReceiveClientOps(client1), ElementsAre( IsUpdateComponentOp(testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_PRIMITIVE), IsUpdateComponentOp( testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE), IsUpdateComponentOp( testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE), IsUpdateComponentOp( testEntityId1, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE), IsUpdateComponentOp(testEntityId2, componentType1Id, COMPONENT_TYPE_1_FIELD_PRIMITIVE), IsUpdateComponentOp( testEntityId2, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE), IsUpdateComponentOp( testEntityId2, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE))); ASSERT_THAT( ReceiveClientOps(client2), ElementsAre( IsUpdateComponentOp(testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_PRIMITIVE), IsUpdateComponentOp( testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_LIVE_UPDATE), IsUpdateComponentOp( testEntityId1, componentType1Id, COMPONENT_TYPE_1_FIELD_DEPENDENCY_REACTIVATE), IsUpdateComponentOp( testEntityId1, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE))); ASSERT_THAT(ReceiveClientOps(client3), IsEmpty()); } TEST_F(ShovelerViewSynchronizerTest, reassignAuthority) { void* clientHandle1 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); void* clientHandle2 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); auto* client1 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle1); auto* client2 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle2); SendAddEntityInterest(client1, testEntityId1); SendAddEntityInterest(client2, testEntityId1); shovelerViewSynchronizerUpdate(viewSynchronizer); auto clientId1 = clientConnectedCalls[0]; auto clientId2 = clientConnectedCalls[1]; // Flush received ops for all clients. ReceiveClientOps(client1); ReceiveClientOps(client2); // Delegate the two components to one client each. shovelerServerControllerDelegateComponent(server, testEntityId1, componentType1Id, clientId1); shovelerServerControllerDelegateComponent(server, testEntityId1, componentType2Id, clientId2); ASSERT_THAT( ReceiveClientOps(client1), ElementsAre(IsDelegateComponentOp(testEntityId1, componentType1Id))); ASSERT_THAT( ReceiveClientOps(client2), ElementsAre(IsDelegateComponentOp(testEntityId1, componentType2Id))); // Reassign authority over first component to second client. shovelerServerControllerDelegateComponent(server, testEntityId1, componentType1Id, clientId2); ASSERT_THAT( ReceiveClientOps(client1), ElementsAre(IsUndelegateComponentOp(testEntityId1, componentType1Id))); ASSERT_THAT( ReceiveClientOps(client2), ElementsAre(IsDelegateComponentOp(testEntityId1, componentType1Id))); } TEST_F(ShovelerViewSynchronizerTest, authoritativeUpdate) { const char* testComponentFieldValue = "the bird is the word"; void* clientHandle1 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); void* clientHandle2 = shovelerInMemoryNetworkAdapterConnectClient(inMemoryNetworkAdapter); auto* client1 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle1); auto* client2 = shovelerInMemoryNetworkAdapterGetClient(inMemoryNetworkAdapter, clientHandle2); SendAddEntityInterest(client1, testEntityId1); SendAddEntityInterest(client2, testEntityId1); shovelerViewSynchronizerUpdate(viewSynchronizer); auto clientId1 = clientConnectedCalls[0]; shovelerServerControllerDelegateComponent(server, testEntityId1, componentType2Id, clientId1); // Flush received ops for all clients. ReceiveClientOps(client1); ReceiveClientOps(client2); // Send a component update from the authoritative client. ShovelerComponentFieldValue fieldValue; shovelerComponentFieldInitValue(&fieldValue, SHOVELER_COMPONENT_FIELD_TYPE_STRING); fieldValue.isSet = true; fieldValue.stringValue = const_cast<char*>(testComponentFieldValue); // not modified bool sent = SendUpdateComponent( client1, testEntityId1, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, &fieldValue); ASSERT_TRUE(sent); // Assert that the other client receives it. shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT(ReceiveClientOps(client1), IsEmpty()); ASSERT_THAT( ReceiveClientOps(client2), ElementsAre(IsUpdateComponentOp( testEntityId1, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, &fieldValue))); // Send a component update from the non-authoritative client. bool nonAuthoritativeSent = SendUpdateComponent( client2, testEntityId1, componentType2Id, COMPONENT_TYPE_2_FIELD_PRIMITIVE_LIVE_UPDATE, &fieldValue); ASSERT_TRUE(nonAuthoritativeSent); // Assert that the other client doesn't receive it. shovelerViewSynchronizerUpdate(viewSynchronizer); ASSERT_THAT(ReceiveClientOps(client1), IsEmpty()); ASSERT_THAT(ReceiveClientOps(client2), IsEmpty()); }
[ "fabian@hahn.graphics" ]
fabian@hahn.graphics
58c2ff911b7f9dc3bd63848fc78015e0ec97c373
eb40917e1fad041f48d5e941cb30accff72b1fb9
/boosted_tree/cpp/include/boosted_tree/matrix.h
13b94233dbc99396583abc8f52a1a3da0fc4b999
[]
no_license
wkcn/mlkit
2f9426633999995dc66a5baf053993a15aeb1231
87fcd49732e6bf280ce3e507f1a64e3484444b82
refs/heads/master
2022-11-11T14:53:00.719534
2020-06-29T10:57:57
2020-06-29T10:57:57
272,767,153
4
0
null
null
null
null
UTF-8
C++
false
false
2,620
h
#ifndef BOOSTED_TREE_MATRIX_H_ #define BOOSTED_TREE_MATRIX_H_ #include <initializer_list> #include <iostream> #include <memory> #include <vector> #include "./logging.h" typedef int64_t dim_t; template <typename T> class DenseRow; template <typename T> struct DenseChunk { std::vector<std::vector<T>> data; }; template <typename T> class Matrix { public: Matrix(dim_t rows, dim_t cols); Matrix(dim_t rows, dim_t cols, T val); public: DenseRow<T> operator[](dim_t row); dim_t length() const; private: std::shared_ptr<DenseChunk<T>> data_; friend DenseRow<T>; }; template <typename T> class DenseRow { public: DenseRow(std::shared_ptr<DenseChunk<T>> data, dim_t row); T &operator[](dim_t col); dim_t length() const; public: template <typename U, typename VT> friend bool operator==(const DenseRow<U> &a, const VT &b); private: std::shared_ptr<DenseChunk<T>> data_; dim_t row_; }; template <typename T, typename VT> bool operator==(const DenseRow<T> &a, const VT &b) { if (a.length() != b.size()) return false; auto rdata = a.data_->data[a.row_]; for (auto pa = rdata.begin(), pb = b.begin(); pb != b.end(); ++pa, ++pb) { if (*pa != *pb) return false; } return true; } template <typename T> Matrix<T>::Matrix(dim_t rows, dim_t cols) { CHECK_GE(rows, 0); CHECK_GE(cols, 0); data_.reset(new DenseChunk<T>); std::vector<T> tmp(cols); data_->data.resize(rows, tmp); } template <typename T> Matrix<T>::Matrix(dim_t rows, dim_t cols, T val) { CHECK_GE(rows, 0); CHECK_GE(cols, 0); data_.reset(new DenseChunk<T>); std::vector<T> tmp(cols, val); data_->data.resize(rows, tmp); } template <typename T> DenseRow<T> Matrix<T>::operator[](dim_t row) { return DenseRow<T>(data_, row); } template <typename T> dim_t Matrix<T>::length() const { return data_->data.size(); } template <typename T> DenseRow<T>::DenseRow(std::shared_ptr<DenseChunk<T>> data, dim_t row) : data_(data), row_(row) {} template <typename T> T &DenseRow<T>::operator[](dim_t col) { return data_->data[row_][col]; } template <typename T> dim_t DenseRow<T>::length() const { return data_->data[row_].size(); } template <typename T> std::ostream &operator<<(std::ostream &os, const Matrix<T> &mat) { const size_t row = mat.length(); if (row == 0) return os; const size_t col = mat[0].length(); if (col == 0) return os; for (int r = 0; r < row; ++r) { bool first = true; for (int c = 0; c < col; ++c) { if (!first) os << " "; else first = false; os << mat[r][c]; } os << std::endl; } return os; } #endif
[ "wkcn@live.cn" ]
wkcn@live.cn
e159e25d92b34c9c1f1a0f51c36800fe0d6ed2fe
0dca3325c194509a48d0c4056909175d6c29f7bc
/live/src/model/VerifyLiveDomainOwnerRequest.cc
7f780f452e880d463a4d2232962a8fccef9ef6fe
[ "Apache-2.0" ]
permissive
dingshiyu/aliyun-openapi-cpp-sdk
3eebd9149c2e6a2b835aba9d746ef9e6bef9ad62
4edd799a79f9b94330d5705bb0789105b6d0bb44
refs/heads/master
2023-07-31T10:11:20.446221
2021-09-26T10:08:42
2021-09-26T10:08:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,730
cc
/* * 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. */ #include <alibabacloud/live/model/VerifyLiveDomainOwnerRequest.h> using AlibabaCloud::Live::Model::VerifyLiveDomainOwnerRequest; VerifyLiveDomainOwnerRequest::VerifyLiveDomainOwnerRequest() : RpcServiceRequest("live", "2016-11-01", "VerifyLiveDomainOwner") { setMethod(HttpRequest::Method::Post); } VerifyLiveDomainOwnerRequest::~VerifyLiveDomainOwnerRequest() {} std::string VerifyLiveDomainOwnerRequest::getVerifyType()const { return verifyType_; } void VerifyLiveDomainOwnerRequest::setVerifyType(const std::string& verifyType) { verifyType_ = verifyType; setParameter("VerifyType", verifyType); } std::string VerifyLiveDomainOwnerRequest::getDomainName()const { return domainName_; } void VerifyLiveDomainOwnerRequest::setDomainName(const std::string& domainName) { domainName_ = domainName; setParameter("DomainName", domainName); } long VerifyLiveDomainOwnerRequest::getOwnerId()const { return ownerId_; } void VerifyLiveDomainOwnerRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
d9b6a52e6eb5f49d3c1cf4fd402f917c00e20137
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case20/case3/2000/T
2a909d0b56b0d5b17a0a8468b3790c6248b578b4
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
7,229
// -*- C++ -*- // File generated by PyFoam - sorry for the ugliness FoamFile { version 2.0; format ascii; class volScalarField; location "2000"; object T; } dimensions [ 0 0 0 1 0 0 0 ]; internalField nonuniform List<scalar> 459 ( 303.923 303.667 303.656 303.654 303.652 303.649 303.646 303.642 303.638 303.63 303.62 303.607 303.594 303.584 303.578 303.628 303.608 303.607 303.608 303.61 303.611 303.612 303.614 303.615 303.617 303.619 303.622 303.625 303.629 303.634 303.641 303.648 303.659 303.681 304.107 303.708 303.69 303.696 303.701 303.705 303.706 303.705 303.7 303.687 303.665 303.638 303.61 303.586 303.57 303.561 303.556 303.614 303.602 303.602 303.604 303.606 303.606 303.606 303.605 303.604 303.603 303.603 303.603 303.605 303.607 303.611 303.618 303.627 303.642 303.671 304.298 303.755 303.725 303.739 303.756 303.77 303.781 303.786 303.783 303.763 303.727 303.68 303.632 303.595 303.573 303.564 303.562 303.591 303.596 303.603 303.61 303.616 303.618 303.615 303.613 303.61 303.608 303.606 303.606 303.606 303.608 303.611 303.615 303.623 303.636 303.666 304.488 303.813 303.756 303.777 303.805 303.834 303.859 303.876 303.876 303.848 303.793 303.722 303.652 303.601 303.573 303.565 303.567 303.576 303.586 303.601 303.616 303.628 303.637 303.643 303.646 303.649 303.652 303.654 303.655 303.656 303.656 303.656 303.656 303.642 303.634 303.638 303.666 304.669 303.886 303.788 303.803 303.838 303.878 303.919 303.952 303.958 303.922 303.846 303.752 303.66 303.599 303.569 303.563 303.571 303.586 303.604 303.624 303.643 303.658 303.668 303.675 303.68 303.684 303.687 303.688 303.688 303.686 303.683 303.679 303.673 303.66 303.647 303.642 303.662 303.722 303.758 303.765 304.827 303.981 303.844 303.83 303.858 303.897 303.942 303.999 304.01 303.961 303.866 303.754 303.655 303.588 303.559 303.559 303.577 303.602 303.629 303.655 303.676 303.692 303.702 303.708 303.712 303.714 303.715 303.715 303.713 303.709 303.703 303.695 303.686 303.674 303.659 303.649 303.658 303.688 303.701 303.733 304.961 304.135 303.992 303.938 303.932 303.95 303.985 304.037 304.032 303.961 303.845 303.721 303.618 303.557 303.54 303.555 303.589 303.628 303.664 303.692 303.712 303.725 303.733 303.736 303.738 303.739 303.739 303.737 303.733 303.727 303.718 303.708 303.698 303.685 303.67 303.659 303.659 303.671 303.68 303.707 305.168 304.553 304.393 304.269 304.188 304.15 304.15 304.125 304.041 303.907 303.756 303.625 303.538 303.504 303.517 303.56 303.616 303.668 303.707 303.73 303.744 303.752 303.756 303.758 303.759 303.758 303.756 303.753 303.749 303.742 303.734 303.724 303.714 303.703 303.691 303.682 303.682 303.694 303.714 303.838 305.458 305.182 304.922 304.692 304.513 304.381 304.271 304.104 303.889 303.683 303.525 303.435 303.414 303.446 303.514 303.591 303.67 303.716 303.742 303.757 303.765 303.77 303.773 303.775 303.775 303.774 303.773 303.771 303.768 303.766 303.765 303.766 303.77 303.779 303.795 303.819 303.851 303.884 303.904 303.953 297.121 299.977 301.568 302.202 302.458 302.615 302.756 302.891 303.027 303.17 303.316 303.451 303.583 303.671 303.722 303.75 303.765 303.774 303.78 303.784 303.787 303.79 303.791 303.793 303.794 303.795 303.797 303.799 303.801 303.804 303.81 303.819 303.833 303.852 303.874 303.895 303.909 303.921 297.715 300.089 301.165 301.812 302.191 302.45 302.691 302.911 303.112 303.313 303.488 303.604 303.681 303.727 303.752 303.767 303.776 303.782 303.788 303.792 303.796 303.8 303.804 303.807 303.81 303.813 303.816 303.818 303.821 303.824 303.829 303.835 303.845 303.857 303.872 303.887 303.881 303.905 301.729 300.042 299.776 301.443 302.121 302.529 302.846 303.108 303.297 303.432 303.533 303.611 303.666 303.702 303.727 303.742 303.752 303.758 303.763 303.768 303.773 303.778 303.783 303.788 303.792 303.797 303.802 303.806 303.81 303.815 303.819 303.823 303.828 303.833 303.84 303.849 303.858 303.862 303.861 303.898 ) ; boundaryField { floor { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 29 ( 303.746 303.936 303.878 303.87 303.876 303.885 303.895 303.906 303.917 303.928 303.938 303.948 303.958 303.968 303.978 303.988 304.001 304.016 304.035 304.073 304.073 304.029 304.002 303.985 303.746 303.936 303.866 303.778 303.732 ) ; } ceiling { type wallHeatTransfer; Tinf uniform 303.2; alphaWall uniform 0.24; value nonuniform List<scalar> 43 ( 301.827 300.254 300.003 301.554 302.193 302.577 302.873 303.116 303.288 303.411 303.503 303.571 303.619 303.648 303.665 303.675 303.68 303.684 303.688 303.691 303.695 303.698 303.702 303.705 303.708 303.712 303.716 303.72 303.726 303.731 303.737 303.743 303.75 303.757 303.766 303.778 303.787 303.79 303.786 303.815 305.35 305.101 298.065 ) ; } sWall { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 0.36; value uniform 303.032; } nWall { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 0.36; value nonuniform List<scalar> 6 ( 304.44 304.401 304.358 304.406 304.383 304.452 ) ; } sideWalls { type empty; } glass1 { type wallHeatTransfer; Tinf uniform 315.2; alphaWall uniform 4.3; value nonuniform List<scalar> 9 ( 311.99 311.368 310.957 310.625 310.34 310.079 309.86 309.906 310.104 ) ; } glass2 { type wallHeatTransfer; Tinf uniform 307.2; alphaWall uniform 4.3; value nonuniform List<scalar> 2 ( 305.996 306.062 ) ; } sun { type wallHeatTransfer; Tinf uniform 305.2; alphaWall uniform 0.24; value nonuniform List<scalar> 14 ( 304.077 303.842 303.831 303.823 303.817 303.81 303.804 303.797 303.79 303.781 303.771 303.76 303.751 303.746 ) ; } heatsource1 { type fixedGradient; gradient uniform 0; } heatsource2 { type fixedGradient; gradient uniform 0; } Table_master { type zeroGradient; } Table_slave { type zeroGradient; } inlet { type fixedValue; value uniform 293.15; } outlet { type zeroGradient; } } // ************************************************************************* //
[ "mitsuaki.makino@tryeting.jp" ]
mitsuaki.makino@tryeting.jp
4be693c1c27cce7bd3297bfd113db906c0df1536
c776476e9d06b3779d744641e758ac3a2c15cddc
/examples/litmus/c/run-scripts/tmp_1/MP+dmb.sy+ctrl-[ws-rf]-addr-fri-rfi.c.cbmc.cpp
741b068cb1f199132196f5fbb4bb1471fd0ac574
[]
no_license
ashutosh0gupta/llvm_bmc
aaac7961c723ba6f7ffd77a39559e0e52432eade
0287c4fb180244e6b3c599a9902507f05c8a7234
refs/heads/master
2023-08-02T17:14:06.178723
2023-07-31T10:46:53
2023-07-31T10:46:53
143,100,825
3
4
null
2023-05-25T05:50:55
2018-08-01T03:47:00
C++
UTF-8
C++
false
false
57,345
cpp
// 0:vars:3 // 3:atom_1_X0_1:1 // 4:atom_1_X4_2:1 // 5:atom_1_X6_0:1 // 6:atom_1_X9_1:1 // 7:thr0:1 // 8:thr1:1 // 9:thr2:1 #define ADDRSIZE 10 #define NPROC 4 #define NCONTEXT 1 #define ASSUME(stmt) __CPROVER_assume(stmt) #define ASSERT(stmt) __CPROVER_assert(stmt, "error") #define max(a,b) (a>b?a:b) char __get_rng(); char get_rng( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } char get_rng_th( char from, char to ) { char ret = __get_rng(); ASSUME(ret >= from && ret <= to); return ret; } int main(int argc, char **argv) { // declare arrays for intial value version in contexts int meminit_[ADDRSIZE*NCONTEXT]; #define meminit(x,k) meminit_[(x)*NCONTEXT+k] int coinit_[ADDRSIZE*NCONTEXT]; #define coinit(x,k) coinit_[(x)*NCONTEXT+k] int deltainit_[ADDRSIZE*NCONTEXT]; #define deltainit(x,k) deltainit_[(x)*NCONTEXT+k] // declare arrays for running value version in contexts int mem_[ADDRSIZE*NCONTEXT]; #define mem(x,k) mem_[(x)*NCONTEXT+k] int co_[ADDRSIZE*NCONTEXT]; #define co(x,k) co_[(x)*NCONTEXT+k] int delta_[ADDRSIZE*NCONTEXT]; #define delta(x,k) delta_[(x)*NCONTEXT+k] // declare arrays for local buffer and observed writes int buff_[NPROC*ADDRSIZE]; #define buff(x,k) buff_[(x)*ADDRSIZE+k] int pw_[NPROC*ADDRSIZE]; #define pw(x,k) pw_[(x)*ADDRSIZE+k] // declare arrays for context stamps char cr_[NPROC*ADDRSIZE]; #define cr(x,k) cr_[(x)*ADDRSIZE+k] char iw_[NPROC*ADDRSIZE]; #define iw(x,k) iw_[(x)*ADDRSIZE+k] char cw_[NPROC*ADDRSIZE]; #define cw(x,k) cw_[(x)*ADDRSIZE+k] char cx_[NPROC*ADDRSIZE]; #define cx(x,k) cx_[(x)*ADDRSIZE+k] char is_[NPROC*ADDRSIZE]; #define is(x,k) is_[(x)*ADDRSIZE+k] char cs_[NPROC*ADDRSIZE]; #define cs(x,k) cs_[(x)*ADDRSIZE+k] char crmax_[NPROC*ADDRSIZE]; #define crmax(x,k) crmax_[(x)*ADDRSIZE+k] char sforbid_[ADDRSIZE*NCONTEXT]; #define sforbid(x,k) sforbid_[(x)*NCONTEXT+k] // declare arrays for synchronizations int cl[NPROC]; int cdy[NPROC]; int cds[NPROC]; int cdl[NPROC]; int cisb[NPROC]; int caddr[NPROC]; int cctrl[NPROC]; int cstart[NPROC]; int creturn[NPROC]; // declare arrays for contexts activity int active[NCONTEXT]; int ctx_used[NCONTEXT]; __LOCALS__ buff(0,0) = 0; pw(0,0) = 0; cr(0,0) = 0; iw(0,0) = 0; cw(0,0) = 0; cx(0,0) = 0; is(0,0) = 0; cs(0,0) = 0; crmax(0,0) = 0; buff(0,1) = 0; pw(0,1) = 0; cr(0,1) = 0; iw(0,1) = 0; cw(0,1) = 0; cx(0,1) = 0; is(0,1) = 0; cs(0,1) = 0; crmax(0,1) = 0; buff(0,2) = 0; pw(0,2) = 0; cr(0,2) = 0; iw(0,2) = 0; cw(0,2) = 0; cx(0,2) = 0; is(0,2) = 0; cs(0,2) = 0; crmax(0,2) = 0; buff(0,3) = 0; pw(0,3) = 0; cr(0,3) = 0; iw(0,3) = 0; cw(0,3) = 0; cx(0,3) = 0; is(0,3) = 0; cs(0,3) = 0; crmax(0,3) = 0; buff(0,4) = 0; pw(0,4) = 0; cr(0,4) = 0; iw(0,4) = 0; cw(0,4) = 0; cx(0,4) = 0; is(0,4) = 0; cs(0,4) = 0; crmax(0,4) = 0; buff(0,5) = 0; pw(0,5) = 0; cr(0,5) = 0; iw(0,5) = 0; cw(0,5) = 0; cx(0,5) = 0; is(0,5) = 0; cs(0,5) = 0; crmax(0,5) = 0; buff(0,6) = 0; pw(0,6) = 0; cr(0,6) = 0; iw(0,6) = 0; cw(0,6) = 0; cx(0,6) = 0; is(0,6) = 0; cs(0,6) = 0; crmax(0,6) = 0; buff(0,7) = 0; pw(0,7) = 0; cr(0,7) = 0; iw(0,7) = 0; cw(0,7) = 0; cx(0,7) = 0; is(0,7) = 0; cs(0,7) = 0; crmax(0,7) = 0; buff(0,8) = 0; pw(0,8) = 0; cr(0,8) = 0; iw(0,8) = 0; cw(0,8) = 0; cx(0,8) = 0; is(0,8) = 0; cs(0,8) = 0; crmax(0,8) = 0; buff(0,9) = 0; pw(0,9) = 0; cr(0,9) = 0; iw(0,9) = 0; cw(0,9) = 0; cx(0,9) = 0; is(0,9) = 0; cs(0,9) = 0; crmax(0,9) = 0; cl[0] = 0; cdy[0] = 0; cds[0] = 0; cdl[0] = 0; cisb[0] = 0; caddr[0] = 0; cctrl[0] = 0; cstart[0] = get_rng(0,NCONTEXT-1); creturn[0] = get_rng(0,NCONTEXT-1); buff(1,0) = 0; pw(1,0) = 0; cr(1,0) = 0; iw(1,0) = 0; cw(1,0) = 0; cx(1,0) = 0; is(1,0) = 0; cs(1,0) = 0; crmax(1,0) = 0; buff(1,1) = 0; pw(1,1) = 0; cr(1,1) = 0; iw(1,1) = 0; cw(1,1) = 0; cx(1,1) = 0; is(1,1) = 0; cs(1,1) = 0; crmax(1,1) = 0; buff(1,2) = 0; pw(1,2) = 0; cr(1,2) = 0; iw(1,2) = 0; cw(1,2) = 0; cx(1,2) = 0; is(1,2) = 0; cs(1,2) = 0; crmax(1,2) = 0; buff(1,3) = 0; pw(1,3) = 0; cr(1,3) = 0; iw(1,3) = 0; cw(1,3) = 0; cx(1,3) = 0; is(1,3) = 0; cs(1,3) = 0; crmax(1,3) = 0; buff(1,4) = 0; pw(1,4) = 0; cr(1,4) = 0; iw(1,4) = 0; cw(1,4) = 0; cx(1,4) = 0; is(1,4) = 0; cs(1,4) = 0; crmax(1,4) = 0; buff(1,5) = 0; pw(1,5) = 0; cr(1,5) = 0; iw(1,5) = 0; cw(1,5) = 0; cx(1,5) = 0; is(1,5) = 0; cs(1,5) = 0; crmax(1,5) = 0; buff(1,6) = 0; pw(1,6) = 0; cr(1,6) = 0; iw(1,6) = 0; cw(1,6) = 0; cx(1,6) = 0; is(1,6) = 0; cs(1,6) = 0; crmax(1,6) = 0; buff(1,7) = 0; pw(1,7) = 0; cr(1,7) = 0; iw(1,7) = 0; cw(1,7) = 0; cx(1,7) = 0; is(1,7) = 0; cs(1,7) = 0; crmax(1,7) = 0; buff(1,8) = 0; pw(1,8) = 0; cr(1,8) = 0; iw(1,8) = 0; cw(1,8) = 0; cx(1,8) = 0; is(1,8) = 0; cs(1,8) = 0; crmax(1,8) = 0; buff(1,9) = 0; pw(1,9) = 0; cr(1,9) = 0; iw(1,9) = 0; cw(1,9) = 0; cx(1,9) = 0; is(1,9) = 0; cs(1,9) = 0; crmax(1,9) = 0; cl[1] = 0; cdy[1] = 0; cds[1] = 0; cdl[1] = 0; cisb[1] = 0; caddr[1] = 0; cctrl[1] = 0; cstart[1] = get_rng(0,NCONTEXT-1); creturn[1] = get_rng(0,NCONTEXT-1); buff(2,0) = 0; pw(2,0) = 0; cr(2,0) = 0; iw(2,0) = 0; cw(2,0) = 0; cx(2,0) = 0; is(2,0) = 0; cs(2,0) = 0; crmax(2,0) = 0; buff(2,1) = 0; pw(2,1) = 0; cr(2,1) = 0; iw(2,1) = 0; cw(2,1) = 0; cx(2,1) = 0; is(2,1) = 0; cs(2,1) = 0; crmax(2,1) = 0; buff(2,2) = 0; pw(2,2) = 0; cr(2,2) = 0; iw(2,2) = 0; cw(2,2) = 0; cx(2,2) = 0; is(2,2) = 0; cs(2,2) = 0; crmax(2,2) = 0; buff(2,3) = 0; pw(2,3) = 0; cr(2,3) = 0; iw(2,3) = 0; cw(2,3) = 0; cx(2,3) = 0; is(2,3) = 0; cs(2,3) = 0; crmax(2,3) = 0; buff(2,4) = 0; pw(2,4) = 0; cr(2,4) = 0; iw(2,4) = 0; cw(2,4) = 0; cx(2,4) = 0; is(2,4) = 0; cs(2,4) = 0; crmax(2,4) = 0; buff(2,5) = 0; pw(2,5) = 0; cr(2,5) = 0; iw(2,5) = 0; cw(2,5) = 0; cx(2,5) = 0; is(2,5) = 0; cs(2,5) = 0; crmax(2,5) = 0; buff(2,6) = 0; pw(2,6) = 0; cr(2,6) = 0; iw(2,6) = 0; cw(2,6) = 0; cx(2,6) = 0; is(2,6) = 0; cs(2,6) = 0; crmax(2,6) = 0; buff(2,7) = 0; pw(2,7) = 0; cr(2,7) = 0; iw(2,7) = 0; cw(2,7) = 0; cx(2,7) = 0; is(2,7) = 0; cs(2,7) = 0; crmax(2,7) = 0; buff(2,8) = 0; pw(2,8) = 0; cr(2,8) = 0; iw(2,8) = 0; cw(2,8) = 0; cx(2,8) = 0; is(2,8) = 0; cs(2,8) = 0; crmax(2,8) = 0; buff(2,9) = 0; pw(2,9) = 0; cr(2,9) = 0; iw(2,9) = 0; cw(2,9) = 0; cx(2,9) = 0; is(2,9) = 0; cs(2,9) = 0; crmax(2,9) = 0; cl[2] = 0; cdy[2] = 0; cds[2] = 0; cdl[2] = 0; cisb[2] = 0; caddr[2] = 0; cctrl[2] = 0; cstart[2] = get_rng(0,NCONTEXT-1); creturn[2] = get_rng(0,NCONTEXT-1); buff(3,0) = 0; pw(3,0) = 0; cr(3,0) = 0; iw(3,0) = 0; cw(3,0) = 0; cx(3,0) = 0; is(3,0) = 0; cs(3,0) = 0; crmax(3,0) = 0; buff(3,1) = 0; pw(3,1) = 0; cr(3,1) = 0; iw(3,1) = 0; cw(3,1) = 0; cx(3,1) = 0; is(3,1) = 0; cs(3,1) = 0; crmax(3,1) = 0; buff(3,2) = 0; pw(3,2) = 0; cr(3,2) = 0; iw(3,2) = 0; cw(3,2) = 0; cx(3,2) = 0; is(3,2) = 0; cs(3,2) = 0; crmax(3,2) = 0; buff(3,3) = 0; pw(3,3) = 0; cr(3,3) = 0; iw(3,3) = 0; cw(3,3) = 0; cx(3,3) = 0; is(3,3) = 0; cs(3,3) = 0; crmax(3,3) = 0; buff(3,4) = 0; pw(3,4) = 0; cr(3,4) = 0; iw(3,4) = 0; cw(3,4) = 0; cx(3,4) = 0; is(3,4) = 0; cs(3,4) = 0; crmax(3,4) = 0; buff(3,5) = 0; pw(3,5) = 0; cr(3,5) = 0; iw(3,5) = 0; cw(3,5) = 0; cx(3,5) = 0; is(3,5) = 0; cs(3,5) = 0; crmax(3,5) = 0; buff(3,6) = 0; pw(3,6) = 0; cr(3,6) = 0; iw(3,6) = 0; cw(3,6) = 0; cx(3,6) = 0; is(3,6) = 0; cs(3,6) = 0; crmax(3,6) = 0; buff(3,7) = 0; pw(3,7) = 0; cr(3,7) = 0; iw(3,7) = 0; cw(3,7) = 0; cx(3,7) = 0; is(3,7) = 0; cs(3,7) = 0; crmax(3,7) = 0; buff(3,8) = 0; pw(3,8) = 0; cr(3,8) = 0; iw(3,8) = 0; cw(3,8) = 0; cx(3,8) = 0; is(3,8) = 0; cs(3,8) = 0; crmax(3,8) = 0; buff(3,9) = 0; pw(3,9) = 0; cr(3,9) = 0; iw(3,9) = 0; cw(3,9) = 0; cx(3,9) = 0; is(3,9) = 0; cs(3,9) = 0; crmax(3,9) = 0; cl[3] = 0; cdy[3] = 0; cds[3] = 0; cdl[3] = 0; cisb[3] = 0; caddr[3] = 0; cctrl[3] = 0; cstart[3] = get_rng(0,NCONTEXT-1); creturn[3] = get_rng(0,NCONTEXT-1); // Dumping initializations mem(0+0,0) = 0; mem(0+1,0) = 0; mem(0+2,0) = 0; mem(3+0,0) = 0; mem(4+0,0) = 0; mem(5+0,0) = 0; mem(6+0,0) = 0; mem(7+0,0) = 0; mem(8+0,0) = 0; mem(9+0,0) = 0; // Dumping context matching equalities co(0,0) = 0; delta(0,0) = -1; co(1,0) = 0; delta(1,0) = -1; co(2,0) = 0; delta(2,0) = -1; co(3,0) = 0; delta(3,0) = -1; co(4,0) = 0; delta(4,0) = -1; co(5,0) = 0; delta(5,0) = -1; co(6,0) = 0; delta(6,0) = -1; co(7,0) = 0; delta(7,0) = -1; co(8,0) = 0; delta(8,0) = -1; co(9,0) = 0; delta(9,0) = -1; // Dumping thread 1 int ret_thread_1 = 0; cdy[1] = get_rng(0,NCONTEXT-1); ASSUME(cdy[1] >= cstart[1]); T1BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !39, metadata !DIExpression()), !dbg !48 // br label %label_1, !dbg !49 goto T1BLOCK1; T1BLOCK1: // call void @llvm.dbg.label(metadata !47), !dbg !50 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !40, metadata !DIExpression()), !dbg !51 // call void @llvm.dbg.value(metadata i64 2, metadata !43, metadata !DIExpression()), !dbg !51 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !52 // ST: Guess iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0); cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0)] == 1); ASSUME(active[cw(1,0)] == 1); ASSUME(sforbid(0,cw(1,0))== 0); ASSUME(iw(1,0) >= 0); ASSUME(iw(1,0) >= 0); ASSUME(cw(1,0) >= iw(1,0)); ASSUME(cw(1,0) >= old_cw); ASSUME(cw(1,0) >= cr(1,0)); ASSUME(cw(1,0) >= cl[1]); ASSUME(cw(1,0) >= cisb[1]); ASSUME(cw(1,0) >= cdy[1]); ASSUME(cw(1,0) >= cdl[1]); ASSUME(cw(1,0) >= cds[1]); ASSUME(cw(1,0) >= cctrl[1]); ASSUME(cw(1,0) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0) = 2; mem(0,cw(1,0)) = 2; co(0,cw(1,0))+=1; delta(0,cw(1,0)) = -1; ASSUME(creturn[1] >= cw(1,0)); // call void (...) @dmbsy(), !dbg !53 // dumbsy: Guess old_cdy = cdy[1]; cdy[1] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[1] >= old_cdy); ASSUME(cdy[1] >= cisb[1]); ASSUME(cdy[1] >= cdl[1]); ASSUME(cdy[1] >= cds[1]); ASSUME(cdy[1] >= cctrl[1]); ASSUME(cdy[1] >= cw(1,0+0)); ASSUME(cdy[1] >= cw(1,0+1)); ASSUME(cdy[1] >= cw(1,0+2)); ASSUME(cdy[1] >= cw(1,3+0)); ASSUME(cdy[1] >= cw(1,4+0)); ASSUME(cdy[1] >= cw(1,5+0)); ASSUME(cdy[1] >= cw(1,6+0)); ASSUME(cdy[1] >= cw(1,7+0)); ASSUME(cdy[1] >= cw(1,8+0)); ASSUME(cdy[1] >= cw(1,9+0)); ASSUME(cdy[1] >= cr(1,0+0)); ASSUME(cdy[1] >= cr(1,0+1)); ASSUME(cdy[1] >= cr(1,0+2)); ASSUME(cdy[1] >= cr(1,3+0)); ASSUME(cdy[1] >= cr(1,4+0)); ASSUME(cdy[1] >= cr(1,5+0)); ASSUME(cdy[1] >= cr(1,6+0)); ASSUME(cdy[1] >= cr(1,7+0)); ASSUME(cdy[1] >= cr(1,8+0)); ASSUME(cdy[1] >= cr(1,9+0)); ASSUME(creturn[1] >= cdy[1]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !44, metadata !DIExpression()), !dbg !54 // call void @llvm.dbg.value(metadata i64 1, metadata !46, metadata !DIExpression()), !dbg !54 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !55 // ST: Guess iw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW old_cw = cw(1,0+1*1); cw(1,0+1*1) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM // Check ASSUME(active[iw(1,0+1*1)] == 1); ASSUME(active[cw(1,0+1*1)] == 1); ASSUME(sforbid(0+1*1,cw(1,0+1*1))== 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(iw(1,0+1*1) >= 0); ASSUME(cw(1,0+1*1) >= iw(1,0+1*1)); ASSUME(cw(1,0+1*1) >= old_cw); ASSUME(cw(1,0+1*1) >= cr(1,0+1*1)); ASSUME(cw(1,0+1*1) >= cl[1]); ASSUME(cw(1,0+1*1) >= cisb[1]); ASSUME(cw(1,0+1*1) >= cdy[1]); ASSUME(cw(1,0+1*1) >= cdl[1]); ASSUME(cw(1,0+1*1) >= cds[1]); ASSUME(cw(1,0+1*1) >= cctrl[1]); ASSUME(cw(1,0+1*1) >= caddr[1]); // Update caddr[1] = max(caddr[1],0); buff(1,0+1*1) = 1; mem(0+1*1,cw(1,0+1*1)) = 1; co(0+1*1,cw(1,0+1*1))+=1; delta(0+1*1,cw(1,0+1*1)) = -1; ASSUME(creturn[1] >= cw(1,0+1*1)); // ret i8* null, !dbg !56 ret_thread_1 = (- 1); // Dumping thread 2 int ret_thread_2 = 0; cdy[2] = get_rng(0,NCONTEXT-1); ASSUME(cdy[2] >= cstart[2]); T2BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !59, metadata !DIExpression()), !dbg !102 // br label %label_2, !dbg !84 goto T2BLOCK1; T2BLOCK1: // call void @llvm.dbg.label(metadata !100), !dbg !104 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !62, metadata !DIExpression()), !dbg !105 // %0 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !87 // LD: Guess old_cr = cr(2,0+1*1); cr(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+1*1)] == 2); ASSUME(cr(2,0+1*1) >= iw(2,0+1*1)); ASSUME(cr(2,0+1*1) >= 0); ASSUME(cr(2,0+1*1) >= cdy[2]); ASSUME(cr(2,0+1*1) >= cisb[2]); ASSUME(cr(2,0+1*1) >= cdl[2]); ASSUME(cr(2,0+1*1) >= cl[2]); // Update creg_r0 = cr(2,0+1*1); crmax(2,0+1*1) = max(crmax(2,0+1*1),cr(2,0+1*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+1*1) < cw(2,0+1*1)) { r0 = buff(2,0+1*1); } else { if(pw(2,0+1*1) != co(0+1*1,cr(2,0+1*1))) { ASSUME(cr(2,0+1*1) >= old_cr); } pw(2,0+1*1) = co(0+1*1,cr(2,0+1*1)); r0 = mem(0+1*1,cr(2,0+1*1)); } ASSUME(creturn[2] >= cr(2,0+1*1)); // call void @llvm.dbg.value(metadata i64 %0, metadata !64, metadata !DIExpression()), !dbg !105 // %conv = trunc i64 %0 to i32, !dbg !88 // call void @llvm.dbg.value(metadata i32 %conv, metadata !60, metadata !DIExpression()), !dbg !102 // %tobool = icmp ne i32 %conv, 0, !dbg !89 // br i1 %tobool, label %if.then, label %if.else, !dbg !91 old_cctrl = cctrl[2]; cctrl[2] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[2] >= old_cctrl); ASSUME(cctrl[2] >= creg_r0); ASSUME(cctrl[2] >= 0); if((r0!=0)) { goto T2BLOCK2; } else { goto T2BLOCK3; } T2BLOCK2: // br label %lbl_LC00, !dbg !92 goto T2BLOCK4; T2BLOCK3: // br label %lbl_LC00, !dbg !93 goto T2BLOCK4; T2BLOCK4: // call void @llvm.dbg.label(metadata !101), !dbg !113 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !65, metadata !DIExpression()), !dbg !114 // call void @llvm.dbg.value(metadata i64 1, metadata !67, metadata !DIExpression()), !dbg !114 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !96 // ST: Guess iw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0+2*1); cw(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0+2*1)] == 2); ASSUME(active[cw(2,0+2*1)] == 2); ASSUME(sforbid(0+2*1,cw(2,0+2*1))== 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(iw(2,0+2*1) >= 0); ASSUME(cw(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cw(2,0+2*1) >= old_cw); ASSUME(cw(2,0+2*1) >= cr(2,0+2*1)); ASSUME(cw(2,0+2*1) >= cl[2]); ASSUME(cw(2,0+2*1) >= cisb[2]); ASSUME(cw(2,0+2*1) >= cdy[2]); ASSUME(cw(2,0+2*1) >= cdl[2]); ASSUME(cw(2,0+2*1) >= cds[2]); ASSUME(cw(2,0+2*1) >= cctrl[2]); ASSUME(cw(2,0+2*1) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0+2*1) = 1; mem(0+2*1,cw(2,0+2*1)) = 1; co(0+2*1,cw(2,0+2*1))+=1; delta(0+2*1,cw(2,0+2*1)) = -1; ASSUME(creturn[2] >= cw(2,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !69, metadata !DIExpression()), !dbg !116 // %1 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !98 // LD: Guess old_cr = cr(2,0+2*1); cr(2,0+2*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0+2*1)] == 2); ASSUME(cr(2,0+2*1) >= iw(2,0+2*1)); ASSUME(cr(2,0+2*1) >= 0); ASSUME(cr(2,0+2*1) >= cdy[2]); ASSUME(cr(2,0+2*1) >= cisb[2]); ASSUME(cr(2,0+2*1) >= cdl[2]); ASSUME(cr(2,0+2*1) >= cl[2]); // Update creg_r1 = cr(2,0+2*1); crmax(2,0+2*1) = max(crmax(2,0+2*1),cr(2,0+2*1)); caddr[2] = max(caddr[2],0); if(cr(2,0+2*1) < cw(2,0+2*1)) { r1 = buff(2,0+2*1); } else { if(pw(2,0+2*1) != co(0+2*1,cr(2,0+2*1))) { ASSUME(cr(2,0+2*1) >= old_cr); } pw(2,0+2*1) = co(0+2*1,cr(2,0+2*1)); r1 = mem(0+2*1,cr(2,0+2*1)); } ASSUME(creturn[2] >= cr(2,0+2*1)); // call void @llvm.dbg.value(metadata i64 %1, metadata !71, metadata !DIExpression()), !dbg !116 // %conv4 = trunc i64 %1 to i32, !dbg !99 // call void @llvm.dbg.value(metadata i32 %conv4, metadata !68, metadata !DIExpression()), !dbg !102 // %xor = xor i32 %conv4, %conv4, !dbg !100 creg_r2 = max(creg_r1,creg_r1); ASSUME(active[creg_r2] == 2); r2 = r1 ^ r1; // call void @llvm.dbg.value(metadata i32 %xor, metadata !72, metadata !DIExpression()), !dbg !102 // %add = add nsw i32 0, %xor, !dbg !101 creg_r3 = max(0,creg_r2); ASSUME(active[creg_r3] == 2); r3 = 0 + r2; // %idxprom = sext i32 %add to i64, !dbg !101 // %arrayidx = getelementptr inbounds [3 x i64], [3 x i64]* @vars, i64 0, i64 %idxprom, !dbg !101 r4 = 0+r3*1; ASSUME(creg_r4 >= 0); ASSUME(creg_r4 >= creg_r3); ASSUME(active[creg_r4] == 2); // call void @llvm.dbg.value(metadata i64* %arrayidx, metadata !74, metadata !DIExpression()), !dbg !121 // %2 = load atomic i64, i64* %arrayidx monotonic, align 8, !dbg !101 // LD: Guess old_cr = cr(2,r4); cr(2,r4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,r4)] == 2); ASSUME(cr(2,r4) >= iw(2,r4)); ASSUME(cr(2,r4) >= creg_r4); ASSUME(cr(2,r4) >= cdy[2]); ASSUME(cr(2,r4) >= cisb[2]); ASSUME(cr(2,r4) >= cdl[2]); ASSUME(cr(2,r4) >= cl[2]); // Update creg_r5 = cr(2,r4); crmax(2,r4) = max(crmax(2,r4),cr(2,r4)); caddr[2] = max(caddr[2],creg_r4); if(cr(2,r4) < cw(2,r4)) { r5 = buff(2,r4); } else { if(pw(2,r4) != co(r4,cr(2,r4))) { ASSUME(cr(2,r4) >= old_cr); } pw(2,r4) = co(r4,cr(2,r4)); r5 = mem(r4,cr(2,r4)); } ASSUME(creturn[2] >= cr(2,r4)); // call void @llvm.dbg.value(metadata i64 %2, metadata !76, metadata !DIExpression()), !dbg !121 // %conv8 = trunc i64 %2 to i32, !dbg !103 // call void @llvm.dbg.value(metadata i32 %conv8, metadata !73, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !77, metadata !DIExpression()), !dbg !123 // call void @llvm.dbg.value(metadata i64 1, metadata !79, metadata !DIExpression()), !dbg !123 // store atomic i64 1, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !105 // ST: Guess iw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,0); cw(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,0)] == 2); ASSUME(active[cw(2,0)] == 2); ASSUME(sforbid(0,cw(2,0))== 0); ASSUME(iw(2,0) >= 0); ASSUME(iw(2,0) >= 0); ASSUME(cw(2,0) >= iw(2,0)); ASSUME(cw(2,0) >= old_cw); ASSUME(cw(2,0) >= cr(2,0)); ASSUME(cw(2,0) >= cl[2]); ASSUME(cw(2,0) >= cisb[2]); ASSUME(cw(2,0) >= cdy[2]); ASSUME(cw(2,0) >= cdl[2]); ASSUME(cw(2,0) >= cds[2]); ASSUME(cw(2,0) >= cctrl[2]); ASSUME(cw(2,0) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,0) = 1; mem(0,cw(2,0)) = 1; co(0,cw(2,0))+=1; delta(0,cw(2,0)) = -1; ASSUME(creturn[2] >= cw(2,0)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !81, metadata !DIExpression()), !dbg !125 // %3 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !107 // LD: Guess old_cr = cr(2,0); cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM // Check ASSUME(active[cr(2,0)] == 2); ASSUME(cr(2,0) >= iw(2,0)); ASSUME(cr(2,0) >= 0); ASSUME(cr(2,0) >= cdy[2]); ASSUME(cr(2,0) >= cisb[2]); ASSUME(cr(2,0) >= cdl[2]); ASSUME(cr(2,0) >= cl[2]); // Update creg_r6 = cr(2,0); crmax(2,0) = max(crmax(2,0),cr(2,0)); caddr[2] = max(caddr[2],0); if(cr(2,0) < cw(2,0)) { r6 = buff(2,0); } else { if(pw(2,0) != co(0,cr(2,0))) { ASSUME(cr(2,0) >= old_cr); } pw(2,0) = co(0,cr(2,0)); r6 = mem(0,cr(2,0)); } ASSUME(creturn[2] >= cr(2,0)); // call void @llvm.dbg.value(metadata i64 %3, metadata !83, metadata !DIExpression()), !dbg !125 // %conv14 = trunc i64 %3 to i32, !dbg !108 // call void @llvm.dbg.value(metadata i32 %conv14, metadata !80, metadata !DIExpression()), !dbg !102 // %cmp = icmp eq i32 %conv, 1, !dbg !109 // %conv15 = zext i1 %cmp to i32, !dbg !109 // call void @llvm.dbg.value(metadata i32 %conv15, metadata !84, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !85, metadata !DIExpression()), !dbg !129 // %4 = zext i32 %conv15 to i64 // call void @llvm.dbg.value(metadata i64 %4, metadata !87, metadata !DIExpression()), !dbg !129 // store atomic i64 %4, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !111 // ST: Guess iw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,3); cw(2,3) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,3)] == 2); ASSUME(active[cw(2,3)] == 2); ASSUME(sforbid(3,cw(2,3))== 0); ASSUME(iw(2,3) >= max(creg_r0,0)); ASSUME(iw(2,3) >= 0); ASSUME(cw(2,3) >= iw(2,3)); ASSUME(cw(2,3) >= old_cw); ASSUME(cw(2,3) >= cr(2,3)); ASSUME(cw(2,3) >= cl[2]); ASSUME(cw(2,3) >= cisb[2]); ASSUME(cw(2,3) >= cdy[2]); ASSUME(cw(2,3) >= cdl[2]); ASSUME(cw(2,3) >= cds[2]); ASSUME(cw(2,3) >= cctrl[2]); ASSUME(cw(2,3) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,3) = (r0==1); mem(3,cw(2,3)) = (r0==1); co(3,cw(2,3))+=1; delta(3,cw(2,3)) = -1; ASSUME(creturn[2] >= cw(2,3)); // %cmp19 = icmp eq i32 %conv4, 2, !dbg !112 // %conv20 = zext i1 %cmp19 to i32, !dbg !112 // call void @llvm.dbg.value(metadata i32 %conv20, metadata !88, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64* @atom_1_X4_2, metadata !89, metadata !DIExpression()), !dbg !132 // %5 = zext i32 %conv20 to i64 // call void @llvm.dbg.value(metadata i64 %5, metadata !91, metadata !DIExpression()), !dbg !132 // store atomic i64 %5, i64* @atom_1_X4_2 seq_cst, align 8, !dbg !114 // ST: Guess iw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,4); cw(2,4) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,4)] == 2); ASSUME(active[cw(2,4)] == 2); ASSUME(sforbid(4,cw(2,4))== 0); ASSUME(iw(2,4) >= max(creg_r1,0)); ASSUME(iw(2,4) >= 0); ASSUME(cw(2,4) >= iw(2,4)); ASSUME(cw(2,4) >= old_cw); ASSUME(cw(2,4) >= cr(2,4)); ASSUME(cw(2,4) >= cl[2]); ASSUME(cw(2,4) >= cisb[2]); ASSUME(cw(2,4) >= cdy[2]); ASSUME(cw(2,4) >= cdl[2]); ASSUME(cw(2,4) >= cds[2]); ASSUME(cw(2,4) >= cctrl[2]); ASSUME(cw(2,4) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,4) = (r1==2); mem(4,cw(2,4)) = (r1==2); co(4,cw(2,4))+=1; delta(4,cw(2,4)) = -1; ASSUME(creturn[2] >= cw(2,4)); // %cmp24 = icmp eq i32 %conv8, 0, !dbg !115 // %conv25 = zext i1 %cmp24 to i32, !dbg !115 // call void @llvm.dbg.value(metadata i32 %conv25, metadata !92, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64* @atom_1_X6_0, metadata !93, metadata !DIExpression()), !dbg !135 // %6 = zext i32 %conv25 to i64 // call void @llvm.dbg.value(metadata i64 %6, metadata !95, metadata !DIExpression()), !dbg !135 // store atomic i64 %6, i64* @atom_1_X6_0 seq_cst, align 8, !dbg !117 // ST: Guess iw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,5); cw(2,5) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,5)] == 2); ASSUME(active[cw(2,5)] == 2); ASSUME(sforbid(5,cw(2,5))== 0); ASSUME(iw(2,5) >= max(creg_r5,0)); ASSUME(iw(2,5) >= 0); ASSUME(cw(2,5) >= iw(2,5)); ASSUME(cw(2,5) >= old_cw); ASSUME(cw(2,5) >= cr(2,5)); ASSUME(cw(2,5) >= cl[2]); ASSUME(cw(2,5) >= cisb[2]); ASSUME(cw(2,5) >= cdy[2]); ASSUME(cw(2,5) >= cdl[2]); ASSUME(cw(2,5) >= cds[2]); ASSUME(cw(2,5) >= cctrl[2]); ASSUME(cw(2,5) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,5) = (r5==0); mem(5,cw(2,5)) = (r5==0); co(5,cw(2,5))+=1; delta(5,cw(2,5)) = -1; ASSUME(creturn[2] >= cw(2,5)); // %cmp29 = icmp eq i32 %conv14, 1, !dbg !118 // %conv30 = zext i1 %cmp29 to i32, !dbg !118 // call void @llvm.dbg.value(metadata i32 %conv30, metadata !96, metadata !DIExpression()), !dbg !102 // call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !97, metadata !DIExpression()), !dbg !138 // %7 = zext i32 %conv30 to i64 // call void @llvm.dbg.value(metadata i64 %7, metadata !99, metadata !DIExpression()), !dbg !138 // store atomic i64 %7, i64* @atom_1_X9_1 seq_cst, align 8, !dbg !120 // ST: Guess iw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW old_cw = cw(2,6); cw(2,6) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM // Check ASSUME(active[iw(2,6)] == 2); ASSUME(active[cw(2,6)] == 2); ASSUME(sforbid(6,cw(2,6))== 0); ASSUME(iw(2,6) >= max(creg_r6,0)); ASSUME(iw(2,6) >= 0); ASSUME(cw(2,6) >= iw(2,6)); ASSUME(cw(2,6) >= old_cw); ASSUME(cw(2,6) >= cr(2,6)); ASSUME(cw(2,6) >= cl[2]); ASSUME(cw(2,6) >= cisb[2]); ASSUME(cw(2,6) >= cdy[2]); ASSUME(cw(2,6) >= cdl[2]); ASSUME(cw(2,6) >= cds[2]); ASSUME(cw(2,6) >= cctrl[2]); ASSUME(cw(2,6) >= caddr[2]); // Update caddr[2] = max(caddr[2],0); buff(2,6) = (r6==1); mem(6,cw(2,6)) = (r6==1); co(6,cw(2,6))+=1; delta(6,cw(2,6)) = -1; ASSUME(creturn[2] >= cw(2,6)); // ret i8* null, !dbg !121 ret_thread_2 = (- 1); // Dumping thread 3 int ret_thread_3 = 0; cdy[3] = get_rng(0,NCONTEXT-1); ASSUME(cdy[3] >= cstart[3]); T3BLOCK0: // call void @llvm.dbg.value(metadata i8* %arg, metadata !143, metadata !DIExpression()), !dbg !148 // br label %label_3, !dbg !46 goto T3BLOCK1; T3BLOCK1: // call void @llvm.dbg.label(metadata !147), !dbg !150 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !144, metadata !DIExpression()), !dbg !151 // call void @llvm.dbg.value(metadata i64 2, metadata !146, metadata !DIExpression()), !dbg !151 // store atomic i64 2, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !49 // ST: Guess iw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW old_cw = cw(3,0+2*1); cw(3,0+2*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM // Check ASSUME(active[iw(3,0+2*1)] == 3); ASSUME(active[cw(3,0+2*1)] == 3); ASSUME(sforbid(0+2*1,cw(3,0+2*1))== 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(iw(3,0+2*1) >= 0); ASSUME(cw(3,0+2*1) >= iw(3,0+2*1)); ASSUME(cw(3,0+2*1) >= old_cw); ASSUME(cw(3,0+2*1) >= cr(3,0+2*1)); ASSUME(cw(3,0+2*1) >= cl[3]); ASSUME(cw(3,0+2*1) >= cisb[3]); ASSUME(cw(3,0+2*1) >= cdy[3]); ASSUME(cw(3,0+2*1) >= cdl[3]); ASSUME(cw(3,0+2*1) >= cds[3]); ASSUME(cw(3,0+2*1) >= cctrl[3]); ASSUME(cw(3,0+2*1) >= caddr[3]); // Update caddr[3] = max(caddr[3],0); buff(3,0+2*1) = 2; mem(0+2*1,cw(3,0+2*1)) = 2; co(0+2*1,cw(3,0+2*1))+=1; delta(0+2*1,cw(3,0+2*1)) = -1; ASSUME(creturn[3] >= cw(3,0+2*1)); // ret i8* null, !dbg !50 ret_thread_3 = (- 1); // Dumping thread 0 int ret_thread_0 = 0; cdy[0] = get_rng(0,NCONTEXT-1); ASSUME(cdy[0] >= cstart[0]); T0BLOCK0: // %thr0 = alloca i64, align 8 // %thr1 = alloca i64, align 8 // %thr2 = alloca i64, align 8 // call void @llvm.dbg.value(metadata i32 %argc, metadata !161, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i8** %argv, metadata !162, metadata !DIExpression()), !dbg !227 // %0 = bitcast i64* %thr0 to i8*, !dbg !111 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !111 // call void @llvm.dbg.declare(metadata i64* %thr0, metadata !163, metadata !DIExpression()), !dbg !229 // %1 = bitcast i64* %thr1 to i8*, !dbg !113 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !113 // call void @llvm.dbg.declare(metadata i64* %thr1, metadata !167, metadata !DIExpression()), !dbg !231 // %2 = bitcast i64* %thr2 to i8*, !dbg !115 // call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !115 // call void @llvm.dbg.declare(metadata i64* %thr2, metadata !168, metadata !DIExpression()), !dbg !233 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !169, metadata !DIExpression()), !dbg !234 // call void @llvm.dbg.value(metadata i64 0, metadata !171, metadata !DIExpression()), !dbg !234 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) monotonic, align 8, !dbg !118 // ST: Guess iw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+2*1); cw(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+2*1)] == 0); ASSUME(active[cw(0,0+2*1)] == 0); ASSUME(sforbid(0+2*1,cw(0,0+2*1))== 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(iw(0,0+2*1) >= 0); ASSUME(cw(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cw(0,0+2*1) >= old_cw); ASSUME(cw(0,0+2*1) >= cr(0,0+2*1)); ASSUME(cw(0,0+2*1) >= cl[0]); ASSUME(cw(0,0+2*1) >= cisb[0]); ASSUME(cw(0,0+2*1) >= cdy[0]); ASSUME(cw(0,0+2*1) >= cdl[0]); ASSUME(cw(0,0+2*1) >= cds[0]); ASSUME(cw(0,0+2*1) >= cctrl[0]); ASSUME(cw(0,0+2*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+2*1) = 0; mem(0+2*1,cw(0,0+2*1)) = 0; co(0+2*1,cw(0,0+2*1))+=1; delta(0+2*1,cw(0,0+2*1)) = -1; ASSUME(creturn[0] >= cw(0,0+2*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !172, metadata !DIExpression()), !dbg !236 // call void @llvm.dbg.value(metadata i64 0, metadata !174, metadata !DIExpression()), !dbg !236 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !120 // ST: Guess iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0+1*1); cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0+1*1)] == 0); ASSUME(active[cw(0,0+1*1)] == 0); ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(iw(0,0+1*1) >= 0); ASSUME(cw(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cw(0,0+1*1) >= old_cw); ASSUME(cw(0,0+1*1) >= cr(0,0+1*1)); ASSUME(cw(0,0+1*1) >= cl[0]); ASSUME(cw(0,0+1*1) >= cisb[0]); ASSUME(cw(0,0+1*1) >= cdy[0]); ASSUME(cw(0,0+1*1) >= cdl[0]); ASSUME(cw(0,0+1*1) >= cds[0]); ASSUME(cw(0,0+1*1) >= cctrl[0]); ASSUME(cw(0,0+1*1) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0+1*1) = 0; mem(0+1*1,cw(0,0+1*1)) = 0; co(0+1*1,cw(0,0+1*1))+=1; delta(0+1*1,cw(0,0+1*1)) = -1; ASSUME(creturn[0] >= cw(0,0+1*1)); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !175, metadata !DIExpression()), !dbg !238 // call void @llvm.dbg.value(metadata i64 0, metadata !177, metadata !DIExpression()), !dbg !238 // store atomic i64 0, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !122 // ST: Guess iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,0); cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,0)] == 0); ASSUME(active[cw(0,0)] == 0); ASSUME(sforbid(0,cw(0,0))== 0); ASSUME(iw(0,0) >= 0); ASSUME(iw(0,0) >= 0); ASSUME(cw(0,0) >= iw(0,0)); ASSUME(cw(0,0) >= old_cw); ASSUME(cw(0,0) >= cr(0,0)); ASSUME(cw(0,0) >= cl[0]); ASSUME(cw(0,0) >= cisb[0]); ASSUME(cw(0,0) >= cdy[0]); ASSUME(cw(0,0) >= cdl[0]); ASSUME(cw(0,0) >= cds[0]); ASSUME(cw(0,0) >= cctrl[0]); ASSUME(cw(0,0) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,0) = 0; mem(0,cw(0,0)) = 0; co(0,cw(0,0))+=1; delta(0,cw(0,0)) = -1; ASSUME(creturn[0] >= cw(0,0)); // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !178, metadata !DIExpression()), !dbg !240 // call void @llvm.dbg.value(metadata i64 0, metadata !180, metadata !DIExpression()), !dbg !240 // store atomic i64 0, i64* @atom_1_X0_1 monotonic, align 8, !dbg !124 // ST: Guess iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,3); cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,3)] == 0); ASSUME(active[cw(0,3)] == 0); ASSUME(sforbid(3,cw(0,3))== 0); ASSUME(iw(0,3) >= 0); ASSUME(iw(0,3) >= 0); ASSUME(cw(0,3) >= iw(0,3)); ASSUME(cw(0,3) >= old_cw); ASSUME(cw(0,3) >= cr(0,3)); ASSUME(cw(0,3) >= cl[0]); ASSUME(cw(0,3) >= cisb[0]); ASSUME(cw(0,3) >= cdy[0]); ASSUME(cw(0,3) >= cdl[0]); ASSUME(cw(0,3) >= cds[0]); ASSUME(cw(0,3) >= cctrl[0]); ASSUME(cw(0,3) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,3) = 0; mem(3,cw(0,3)) = 0; co(3,cw(0,3))+=1; delta(3,cw(0,3)) = -1; ASSUME(creturn[0] >= cw(0,3)); // call void @llvm.dbg.value(metadata i64* @atom_1_X4_2, metadata !181, metadata !DIExpression()), !dbg !242 // call void @llvm.dbg.value(metadata i64 0, metadata !183, metadata !DIExpression()), !dbg !242 // store atomic i64 0, i64* @atom_1_X4_2 monotonic, align 8, !dbg !126 // ST: Guess iw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,4); cw(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,4)] == 0); ASSUME(active[cw(0,4)] == 0); ASSUME(sforbid(4,cw(0,4))== 0); ASSUME(iw(0,4) >= 0); ASSUME(iw(0,4) >= 0); ASSUME(cw(0,4) >= iw(0,4)); ASSUME(cw(0,4) >= old_cw); ASSUME(cw(0,4) >= cr(0,4)); ASSUME(cw(0,4) >= cl[0]); ASSUME(cw(0,4) >= cisb[0]); ASSUME(cw(0,4) >= cdy[0]); ASSUME(cw(0,4) >= cdl[0]); ASSUME(cw(0,4) >= cds[0]); ASSUME(cw(0,4) >= cctrl[0]); ASSUME(cw(0,4) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,4) = 0; mem(4,cw(0,4)) = 0; co(4,cw(0,4))+=1; delta(4,cw(0,4)) = -1; ASSUME(creturn[0] >= cw(0,4)); // call void @llvm.dbg.value(metadata i64* @atom_1_X6_0, metadata !184, metadata !DIExpression()), !dbg !244 // call void @llvm.dbg.value(metadata i64 0, metadata !186, metadata !DIExpression()), !dbg !244 // store atomic i64 0, i64* @atom_1_X6_0 monotonic, align 8, !dbg !128 // ST: Guess iw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,5); cw(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,5)] == 0); ASSUME(active[cw(0,5)] == 0); ASSUME(sforbid(5,cw(0,5))== 0); ASSUME(iw(0,5) >= 0); ASSUME(iw(0,5) >= 0); ASSUME(cw(0,5) >= iw(0,5)); ASSUME(cw(0,5) >= old_cw); ASSUME(cw(0,5) >= cr(0,5)); ASSUME(cw(0,5) >= cl[0]); ASSUME(cw(0,5) >= cisb[0]); ASSUME(cw(0,5) >= cdy[0]); ASSUME(cw(0,5) >= cdl[0]); ASSUME(cw(0,5) >= cds[0]); ASSUME(cw(0,5) >= cctrl[0]); ASSUME(cw(0,5) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,5) = 0; mem(5,cw(0,5)) = 0; co(5,cw(0,5))+=1; delta(5,cw(0,5)) = -1; ASSUME(creturn[0] >= cw(0,5)); // call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !187, metadata !DIExpression()), !dbg !246 // call void @llvm.dbg.value(metadata i64 0, metadata !189, metadata !DIExpression()), !dbg !246 // store atomic i64 0, i64* @atom_1_X9_1 monotonic, align 8, !dbg !130 // ST: Guess iw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW old_cw = cw(0,6); cw(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM // Check ASSUME(active[iw(0,6)] == 0); ASSUME(active[cw(0,6)] == 0); ASSUME(sforbid(6,cw(0,6))== 0); ASSUME(iw(0,6) >= 0); ASSUME(iw(0,6) >= 0); ASSUME(cw(0,6) >= iw(0,6)); ASSUME(cw(0,6) >= old_cw); ASSUME(cw(0,6) >= cr(0,6)); ASSUME(cw(0,6) >= cl[0]); ASSUME(cw(0,6) >= cisb[0]); ASSUME(cw(0,6) >= cdy[0]); ASSUME(cw(0,6) >= cdl[0]); ASSUME(cw(0,6) >= cds[0]); ASSUME(cw(0,6) >= cctrl[0]); ASSUME(cw(0,6) >= caddr[0]); // Update caddr[0] = max(caddr[0],0); buff(0,6) = 0; mem(6,cw(0,6)) = 0; co(6,cw(0,6))+=1; delta(6,cw(0,6)) = -1; ASSUME(creturn[0] >= cw(0,6)); // %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !131 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[1] >= cdy[0]); // %call13 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !132 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[2] >= cdy[0]); // %call14 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !133 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cstart[3] >= cdy[0]); // %3 = load i64, i64* %thr0, align 8, !dbg !134, !tbaa !135 // LD: Guess old_cr = cr(0,7); cr(0,7) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,7)] == 0); ASSUME(cr(0,7) >= iw(0,7)); ASSUME(cr(0,7) >= 0); ASSUME(cr(0,7) >= cdy[0]); ASSUME(cr(0,7) >= cisb[0]); ASSUME(cr(0,7) >= cdl[0]); ASSUME(cr(0,7) >= cl[0]); // Update creg_r8 = cr(0,7); crmax(0,7) = max(crmax(0,7),cr(0,7)); caddr[0] = max(caddr[0],0); if(cr(0,7) < cw(0,7)) { r8 = buff(0,7); } else { if(pw(0,7) != co(7,cr(0,7))) { ASSUME(cr(0,7) >= old_cr); } pw(0,7) = co(7,cr(0,7)); r8 = mem(7,cr(0,7)); } ASSUME(creturn[0] >= cr(0,7)); // %call15 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !139 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[1]); // %4 = load i64, i64* %thr1, align 8, !dbg !140, !tbaa !135 // LD: Guess old_cr = cr(0,8); cr(0,8) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,8)] == 0); ASSUME(cr(0,8) >= iw(0,8)); ASSUME(cr(0,8) >= 0); ASSUME(cr(0,8) >= cdy[0]); ASSUME(cr(0,8) >= cisb[0]); ASSUME(cr(0,8) >= cdl[0]); ASSUME(cr(0,8) >= cl[0]); // Update creg_r9 = cr(0,8); crmax(0,8) = max(crmax(0,8),cr(0,8)); caddr[0] = max(caddr[0],0); if(cr(0,8) < cw(0,8)) { r9 = buff(0,8); } else { if(pw(0,8) != co(8,cr(0,8))) { ASSUME(cr(0,8) >= old_cr); } pw(0,8) = co(8,cr(0,8)); r9 = mem(8,cr(0,8)); } ASSUME(creturn[0] >= cr(0,8)); // %call16 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !141 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[2]); // %5 = load i64, i64* %thr2, align 8, !dbg !142, !tbaa !135 // LD: Guess old_cr = cr(0,9); cr(0,9) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,9)] == 0); ASSUME(cr(0,9) >= iw(0,9)); ASSUME(cr(0,9) >= 0); ASSUME(cr(0,9) >= cdy[0]); ASSUME(cr(0,9) >= cisb[0]); ASSUME(cr(0,9) >= cdl[0]); ASSUME(cr(0,9) >= cl[0]); // Update creg_r10 = cr(0,9); crmax(0,9) = max(crmax(0,9),cr(0,9)); caddr[0] = max(caddr[0],0); if(cr(0,9) < cw(0,9)) { r10 = buff(0,9); } else { if(pw(0,9) != co(9,cr(0,9))) { ASSUME(cr(0,9) >= old_cr); } pw(0,9) = co(9,cr(0,9)); r10 = mem(9,cr(0,9)); } ASSUME(creturn[0] >= cr(0,9)); // %call17 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !143 // dumbsy: Guess old_cdy = cdy[0]; cdy[0] = get_rng(0,NCONTEXT-1); // Check ASSUME(cdy[0] >= old_cdy); ASSUME(cdy[0] >= cisb[0]); ASSUME(cdy[0] >= cdl[0]); ASSUME(cdy[0] >= cds[0]); ASSUME(cdy[0] >= cctrl[0]); ASSUME(cdy[0] >= cw(0,0+0)); ASSUME(cdy[0] >= cw(0,0+1)); ASSUME(cdy[0] >= cw(0,0+2)); ASSUME(cdy[0] >= cw(0,3+0)); ASSUME(cdy[0] >= cw(0,4+0)); ASSUME(cdy[0] >= cw(0,5+0)); ASSUME(cdy[0] >= cw(0,6+0)); ASSUME(cdy[0] >= cw(0,7+0)); ASSUME(cdy[0] >= cw(0,8+0)); ASSUME(cdy[0] >= cw(0,9+0)); ASSUME(cdy[0] >= cr(0,0+0)); ASSUME(cdy[0] >= cr(0,0+1)); ASSUME(cdy[0] >= cr(0,0+2)); ASSUME(cdy[0] >= cr(0,3+0)); ASSUME(cdy[0] >= cr(0,4+0)); ASSUME(cdy[0] >= cr(0,5+0)); ASSUME(cdy[0] >= cr(0,6+0)); ASSUME(cdy[0] >= cr(0,7+0)); ASSUME(cdy[0] >= cr(0,8+0)); ASSUME(cdy[0] >= cr(0,9+0)); ASSUME(creturn[0] >= cdy[0]); ASSUME(cdy[0] >= creturn[3]); // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0), metadata !191, metadata !DIExpression()), !dbg !261 // %6 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 0) seq_cst, align 8, !dbg !145 // LD: Guess old_cr = cr(0,0); cr(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0)] == 0); ASSUME(cr(0,0) >= iw(0,0)); ASSUME(cr(0,0) >= 0); ASSUME(cr(0,0) >= cdy[0]); ASSUME(cr(0,0) >= cisb[0]); ASSUME(cr(0,0) >= cdl[0]); ASSUME(cr(0,0) >= cl[0]); // Update creg_r11 = cr(0,0); crmax(0,0) = max(crmax(0,0),cr(0,0)); caddr[0] = max(caddr[0],0); if(cr(0,0) < cw(0,0)) { r11 = buff(0,0); } else { if(pw(0,0) != co(0,cr(0,0))) { ASSUME(cr(0,0) >= old_cr); } pw(0,0) = co(0,cr(0,0)); r11 = mem(0,cr(0,0)); } ASSUME(creturn[0] >= cr(0,0)); // call void @llvm.dbg.value(metadata i64 %6, metadata !193, metadata !DIExpression()), !dbg !261 // %conv = trunc i64 %6 to i32, !dbg !146 // call void @llvm.dbg.value(metadata i32 %conv, metadata !190, metadata !DIExpression()), !dbg !227 // %cmp = icmp eq i32 %conv, 2, !dbg !147 // %conv18 = zext i1 %cmp to i32, !dbg !147 // call void @llvm.dbg.value(metadata i32 %conv18, metadata !194, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1), metadata !196, metadata !DIExpression()), !dbg !265 // %7 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 1) seq_cst, align 8, !dbg !149 // LD: Guess old_cr = cr(0,0+1*1); cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+1*1)] == 0); ASSUME(cr(0,0+1*1) >= iw(0,0+1*1)); ASSUME(cr(0,0+1*1) >= 0); ASSUME(cr(0,0+1*1) >= cdy[0]); ASSUME(cr(0,0+1*1) >= cisb[0]); ASSUME(cr(0,0+1*1) >= cdl[0]); ASSUME(cr(0,0+1*1) >= cl[0]); // Update creg_r12 = cr(0,0+1*1); crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+1*1) < cw(0,0+1*1)) { r12 = buff(0,0+1*1); } else { if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) { ASSUME(cr(0,0+1*1) >= old_cr); } pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1)); r12 = mem(0+1*1,cr(0,0+1*1)); } ASSUME(creturn[0] >= cr(0,0+1*1)); // call void @llvm.dbg.value(metadata i64 %7, metadata !198, metadata !DIExpression()), !dbg !265 // %conv22 = trunc i64 %7 to i32, !dbg !150 // call void @llvm.dbg.value(metadata i32 %conv22, metadata !195, metadata !DIExpression()), !dbg !227 // %cmp23 = icmp eq i32 %conv22, 1, !dbg !151 // %conv24 = zext i1 %cmp23 to i32, !dbg !151 // call void @llvm.dbg.value(metadata i32 %conv24, metadata !199, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2), metadata !201, metadata !DIExpression()), !dbg !269 // %8 = load atomic i64, i64* getelementptr inbounds ([3 x i64], [3 x i64]* @vars, i64 0, i64 2) seq_cst, align 8, !dbg !153 // LD: Guess old_cr = cr(0,0+2*1); cr(0,0+2*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,0+2*1)] == 0); ASSUME(cr(0,0+2*1) >= iw(0,0+2*1)); ASSUME(cr(0,0+2*1) >= 0); ASSUME(cr(0,0+2*1) >= cdy[0]); ASSUME(cr(0,0+2*1) >= cisb[0]); ASSUME(cr(0,0+2*1) >= cdl[0]); ASSUME(cr(0,0+2*1) >= cl[0]); // Update creg_r13 = cr(0,0+2*1); crmax(0,0+2*1) = max(crmax(0,0+2*1),cr(0,0+2*1)); caddr[0] = max(caddr[0],0); if(cr(0,0+2*1) < cw(0,0+2*1)) { r13 = buff(0,0+2*1); } else { if(pw(0,0+2*1) != co(0+2*1,cr(0,0+2*1))) { ASSUME(cr(0,0+2*1) >= old_cr); } pw(0,0+2*1) = co(0+2*1,cr(0,0+2*1)); r13 = mem(0+2*1,cr(0,0+2*1)); } ASSUME(creturn[0] >= cr(0,0+2*1)); // call void @llvm.dbg.value(metadata i64 %8, metadata !203, metadata !DIExpression()), !dbg !269 // %conv28 = trunc i64 %8 to i32, !dbg !154 // call void @llvm.dbg.value(metadata i32 %conv28, metadata !200, metadata !DIExpression()), !dbg !227 // %cmp29 = icmp eq i32 %conv28, 2, !dbg !155 // %conv30 = zext i1 %cmp29 to i32, !dbg !155 // call void @llvm.dbg.value(metadata i32 %conv30, metadata !204, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i64* @atom_1_X0_1, metadata !206, metadata !DIExpression()), !dbg !273 // %9 = load atomic i64, i64* @atom_1_X0_1 seq_cst, align 8, !dbg !157 // LD: Guess old_cr = cr(0,3); cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,3)] == 0); ASSUME(cr(0,3) >= iw(0,3)); ASSUME(cr(0,3) >= 0); ASSUME(cr(0,3) >= cdy[0]); ASSUME(cr(0,3) >= cisb[0]); ASSUME(cr(0,3) >= cdl[0]); ASSUME(cr(0,3) >= cl[0]); // Update creg_r14 = cr(0,3); crmax(0,3) = max(crmax(0,3),cr(0,3)); caddr[0] = max(caddr[0],0); if(cr(0,3) < cw(0,3)) { r14 = buff(0,3); } else { if(pw(0,3) != co(3,cr(0,3))) { ASSUME(cr(0,3) >= old_cr); } pw(0,3) = co(3,cr(0,3)); r14 = mem(3,cr(0,3)); } ASSUME(creturn[0] >= cr(0,3)); // call void @llvm.dbg.value(metadata i64 %9, metadata !208, metadata !DIExpression()), !dbg !273 // %conv34 = trunc i64 %9 to i32, !dbg !158 // call void @llvm.dbg.value(metadata i32 %conv34, metadata !205, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i64* @atom_1_X4_2, metadata !210, metadata !DIExpression()), !dbg !276 // %10 = load atomic i64, i64* @atom_1_X4_2 seq_cst, align 8, !dbg !160 // LD: Guess old_cr = cr(0,4); cr(0,4) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,4)] == 0); ASSUME(cr(0,4) >= iw(0,4)); ASSUME(cr(0,4) >= 0); ASSUME(cr(0,4) >= cdy[0]); ASSUME(cr(0,4) >= cisb[0]); ASSUME(cr(0,4) >= cdl[0]); ASSUME(cr(0,4) >= cl[0]); // Update creg_r15 = cr(0,4); crmax(0,4) = max(crmax(0,4),cr(0,4)); caddr[0] = max(caddr[0],0); if(cr(0,4) < cw(0,4)) { r15 = buff(0,4); } else { if(pw(0,4) != co(4,cr(0,4))) { ASSUME(cr(0,4) >= old_cr); } pw(0,4) = co(4,cr(0,4)); r15 = mem(4,cr(0,4)); } ASSUME(creturn[0] >= cr(0,4)); // call void @llvm.dbg.value(metadata i64 %10, metadata !212, metadata !DIExpression()), !dbg !276 // %conv38 = trunc i64 %10 to i32, !dbg !161 // call void @llvm.dbg.value(metadata i32 %conv38, metadata !209, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i64* @atom_1_X6_0, metadata !214, metadata !DIExpression()), !dbg !279 // %11 = load atomic i64, i64* @atom_1_X6_0 seq_cst, align 8, !dbg !163 // LD: Guess old_cr = cr(0,5); cr(0,5) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,5)] == 0); ASSUME(cr(0,5) >= iw(0,5)); ASSUME(cr(0,5) >= 0); ASSUME(cr(0,5) >= cdy[0]); ASSUME(cr(0,5) >= cisb[0]); ASSUME(cr(0,5) >= cdl[0]); ASSUME(cr(0,5) >= cl[0]); // Update creg_r16 = cr(0,5); crmax(0,5) = max(crmax(0,5),cr(0,5)); caddr[0] = max(caddr[0],0); if(cr(0,5) < cw(0,5)) { r16 = buff(0,5); } else { if(pw(0,5) != co(5,cr(0,5))) { ASSUME(cr(0,5) >= old_cr); } pw(0,5) = co(5,cr(0,5)); r16 = mem(5,cr(0,5)); } ASSUME(creturn[0] >= cr(0,5)); // call void @llvm.dbg.value(metadata i64 %11, metadata !216, metadata !DIExpression()), !dbg !279 // %conv42 = trunc i64 %11 to i32, !dbg !164 // call void @llvm.dbg.value(metadata i32 %conv42, metadata !213, metadata !DIExpression()), !dbg !227 // call void @llvm.dbg.value(metadata i64* @atom_1_X9_1, metadata !218, metadata !DIExpression()), !dbg !282 // %12 = load atomic i64, i64* @atom_1_X9_1 seq_cst, align 8, !dbg !166 // LD: Guess old_cr = cr(0,6); cr(0,6) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM // Check ASSUME(active[cr(0,6)] == 0); ASSUME(cr(0,6) >= iw(0,6)); ASSUME(cr(0,6) >= 0); ASSUME(cr(0,6) >= cdy[0]); ASSUME(cr(0,6) >= cisb[0]); ASSUME(cr(0,6) >= cdl[0]); ASSUME(cr(0,6) >= cl[0]); // Update creg_r17 = cr(0,6); crmax(0,6) = max(crmax(0,6),cr(0,6)); caddr[0] = max(caddr[0],0); if(cr(0,6) < cw(0,6)) { r17 = buff(0,6); } else { if(pw(0,6) != co(6,cr(0,6))) { ASSUME(cr(0,6) >= old_cr); } pw(0,6) = co(6,cr(0,6)); r17 = mem(6,cr(0,6)); } ASSUME(creturn[0] >= cr(0,6)); // call void @llvm.dbg.value(metadata i64 %12, metadata !220, metadata !DIExpression()), !dbg !282 // %conv46 = trunc i64 %12 to i32, !dbg !167 // call void @llvm.dbg.value(metadata i32 %conv46, metadata !217, metadata !DIExpression()), !dbg !227 // %and = and i32 %conv42, %conv46, !dbg !168 creg_r18 = max(creg_r16,creg_r17); ASSUME(active[creg_r18] == 0); r18 = r16 & r17; // call void @llvm.dbg.value(metadata i32 %and, metadata !221, metadata !DIExpression()), !dbg !227 // %and47 = and i32 %conv38, %and, !dbg !169 creg_r19 = max(creg_r15,creg_r18); ASSUME(active[creg_r19] == 0); r19 = r15 & r18; // call void @llvm.dbg.value(metadata i32 %and47, metadata !222, metadata !DIExpression()), !dbg !227 // %and48 = and i32 %conv34, %and47, !dbg !170 creg_r20 = max(creg_r14,creg_r19); ASSUME(active[creg_r20] == 0); r20 = r14 & r19; // call void @llvm.dbg.value(metadata i32 %and48, metadata !223, metadata !DIExpression()), !dbg !227 // %and49 = and i32 %conv30, %and48, !dbg !171 creg_r21 = max(max(creg_r13,0),creg_r20); ASSUME(active[creg_r21] == 0); r21 = (r13==2) & r20; // call void @llvm.dbg.value(metadata i32 %and49, metadata !224, metadata !DIExpression()), !dbg !227 // %and50 = and i32 %conv24, %and49, !dbg !172 creg_r22 = max(max(creg_r12,0),creg_r21); ASSUME(active[creg_r22] == 0); r22 = (r12==1) & r21; // call void @llvm.dbg.value(metadata i32 %and50, metadata !225, metadata !DIExpression()), !dbg !227 // %and51 = and i32 %conv18, %and50, !dbg !173 creg_r23 = max(max(creg_r11,0),creg_r22); ASSUME(active[creg_r23] == 0); r23 = (r11==2) & r22; // call void @llvm.dbg.value(metadata i32 %and51, metadata !226, metadata !DIExpression()), !dbg !227 // %cmp52 = icmp eq i32 %and51, 1, !dbg !174 // br i1 %cmp52, label %if.then, label %if.end, !dbg !176 old_cctrl = cctrl[0]; cctrl[0] = get_rng(0,NCONTEXT-1); ASSUME(cctrl[0] >= old_cctrl); ASSUME(cctrl[0] >= creg_r23); ASSUME(cctrl[0] >= 0); if((r23==1)) { goto T0BLOCK1; } else { goto T0BLOCK2; } T0BLOCK1: // call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([120 x i8], [120 x i8]* @.str.1, i64 0, i64 0), i32 noundef 93, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !177 // unreachable, !dbg !177 r24 = 1; T0BLOCK2: // %13 = bitcast i64* %thr2 to i8*, !dbg !180 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %13) #7, !dbg !180 // %14 = bitcast i64* %thr1 to i8*, !dbg !180 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %14) #7, !dbg !180 // %15 = bitcast i64* %thr0 to i8*, !dbg !180 // call void @llvm.lifetime.end.p0i8(i64 8, i8* %15) #7, !dbg !180 // ret i32 0, !dbg !181 ret_thread_0 = 0; ASSERT(r24== 0); }
[ "tuan-phong.ngo@it.uu.se" ]
tuan-phong.ngo@it.uu.se
1bf51d70878bdf7d276c3ea10332788e999ce2d3
0342fe0e71b63481ffa104eb0f2d127409021bae
/export/mac64/cpp/obj/include/flixel/effects/FlxFlicker.h
9c32d28c61402d0687cf3fbcbe19240bc487ef49
[]
no_license
azlen/LD36
a063027afe49a219eb0a3711e12a3a9f553bc410
2b800e01ee491631974a6abd28a12f5019cb430a
refs/heads/master
2020-12-02T17:10:09.618613
2016-08-29T02:02:00
2016-08-29T02:02:00
66,799,278
0
1
null
null
null
null
UTF-8
C++
false
true
3,464
h
// Generated by Haxe 3.3.0 #ifndef INCLUDED_flixel_effects_FlxFlicker #define INCLUDED_flixel_effects_FlxFlicker #ifndef HXCPP_H #include <hxcpp.h> #endif #ifndef INCLUDED_flixel_util_IFlxDestroyable #include <flixel/util/IFlxDestroyable.h> #endif HX_DECLARE_CLASS1(flixel,FlxBasic) HX_DECLARE_CLASS1(flixel,FlxObject) HX_DECLARE_CLASS2(flixel,effects,FlxFlicker) HX_DECLARE_CLASS2(flixel,util,FlxPool_flixel_effects_FlxFlicker) HX_DECLARE_CLASS2(flixel,util,FlxTimer) HX_DECLARE_CLASS2(flixel,util,IFlxDestroyable) HX_DECLARE_CLASS2(flixel,util,IFlxPool) HX_DECLARE_CLASS1(haxe,IMap) HX_DECLARE_CLASS2(haxe,ds,ObjectMap) namespace flixel{ namespace effects{ class HXCPP_CLASS_ATTRIBUTES FlxFlicker_obj : public hx::Object { public: typedef hx::Object super; typedef FlxFlicker_obj OBJ_; FlxFlicker_obj(); public: void __construct(); inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="flixel.effects.FlxFlicker") { return hx::Object::operator new(inSize,inContainer,inName); } inline void *operator new(size_t inSize, int extra) { return hx::Object::operator new(inSize+extra,true,"flixel.effects.FlxFlicker"); } static hx::ObjectPtr< FlxFlicker_obj > __new(); static Dynamic __CreateEmpty(); static Dynamic __Create(hx::DynamicArray inArgs); //~FlxFlicker_obj(); HX_DO_RTTI_ALL; hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp); static bool __GetStatic(const ::String &inString, Dynamic &outValue, hx::PropertyAccess inCallProp); hx::Val __SetField(const ::String &inString,const hx::Val &inValue, hx::PropertyAccess inCallProp); static bool __SetStatic(const ::String &inString, Dynamic &ioValue, hx::PropertyAccess inCallProp); void __GetFields(Array< ::String> &outFields); static void __register(); void __Mark(HX_MARK_PARAMS); void __Visit(HX_VISIT_PARAMS); void *_hx_getInterface(int inHash); ::String __ToString() const { return HX_HCSTRING("FlxFlicker","\xc6","\x94","\x18","\xa6"); } static void __boot(); static ::flixel::util::FlxPool_flixel_effects_FlxFlicker _pool; static ::haxe::ds::ObjectMap _boundObjects; static ::flixel::effects::FlxFlicker flicker( ::flixel::FlxObject Object,hx::Null< Float > Duration,hx::Null< Float > Interval,hx::Null< Bool > EndVisibility,hx::Null< Bool > ForceRestart, ::Dynamic CompletionCallback, ::Dynamic ProgressCallback); static ::Dynamic flicker_dyn(); static Bool isFlickering( ::flixel::FlxObject Object); static ::Dynamic isFlickering_dyn(); static void stopFlickering( ::flixel::FlxObject Object); static ::Dynamic stopFlickering_dyn(); ::flixel::FlxObject object; Bool endVisibility; ::flixel::util::FlxTimer timer; ::Dynamic completionCallback; ::Dynamic &completionCallback_dyn() { return completionCallback;} ::Dynamic progressCallback; ::Dynamic &progressCallback_dyn() { return progressCallback;} Float duration; Float interval; void destroy(); ::Dynamic destroy_dyn(); void start( ::flixel::FlxObject Object,Float Duration,Float Interval,Bool EndVisibility, ::Dynamic CompletionCallback, ::Dynamic ProgressCallback); ::Dynamic start_dyn(); void stop(); ::Dynamic stop_dyn(); void release(); ::Dynamic release_dyn(); void flickerProgress( ::flixel::util::FlxTimer Timer); ::Dynamic flickerProgress_dyn(); }; } // end namespace flixel } // end namespace effects #endif /* INCLUDED_flixel_effects_FlxFlicker */
[ "azlen@livingcode.org" ]
azlen@livingcode.org
f0c92791bd08c64e5a25ec90705e5b7dbb6831e6
a651de5d663c02a997ad9671e5f60386f0d17599
/src/Base/include/DOFRotation.h
4e83aa31dcf8205c5d1920e13c9e761613d66b4e
[ "MIT" ]
permissive
rarora7777/GAUSS
0cb1469a6e70d0da70e6ee45f29717bd58326a16
d72f0fa84954f93d177ff3fac0fbf4d3b4b17e27
refs/heads/master
2023-04-10T09:33:23.631233
2023-03-18T03:06:25
2023-03-18T03:06:25
201,391,326
2
0
MIT
2019-08-09T04:46:24
2019-08-09T04:46:24
null
UTF-8
C++
false
false
786
h
// // DOFRotation.h // Gauss // // Created by David Levin on 5/8/18. // #ifndef DOFRotation_h #define DOFRotation_h #include "DOF.h" #include "Utilities.h" namespace Gauss { /** Implementation Rotation degree of freedom stored as a four value quaternion */ template<typename DataType, unsigned int Property=0> class DOFRotationImpl { public: explicit DOFRotationImpl() { } inline unsigned int getNumScalarDOF() const { return 4; } protected: private: }; template<typename DataType, unsigned int PropertyIndex=0> using DOFRotation = DOF<DataType, DOFRotationImpl, PropertyIndex>; } #endif /* DOFRotation_h */
[ "dilevin@csail.mit.edu" ]
dilevin@csail.mit.edu
56c1e37299c61262fbc68256b4a351f55b74df07
318dc883a0642299c36c0881d9b58b8a5fdd147f
/tableau.h
87b0c652746c6a4015f04bf9adde8ae3cf3027a4
[]
no_license
link852258/INF3105TP2
cbd3606693c7b139177a527d75caf9e05053ad82
d9755d37b2504d1000499d45f17e3ed300f40ab9
refs/heads/main
2023-06-02T13:16:29.643800
2021-06-21T15:47:10
2021-06-21T15:47:10
378,982,954
0
0
null
null
null
null
UTF-8
C++
false
false
5,854
h
/* Squelette pour classe générique Tableau<T>. * Lab3 -- Tableau dynamique générique * UQAM / Département d'informatique * INF3105 - Structures de données et algorithmes * http://ericbeaudry.uqam.ca/INF3105/lab3/ */ #if !defined(_TABLEAU___H_) #define _TABLEAU___H_ #include <assert.h> template <class T> class Tableau{ public: Tableau(int capacite_initiale=4); Tableau(const Tableau<T>&); ~Tableau(); // Ajouter un element à la fin void ajouter(const T& element); // Vider le tableau void vider(); // Retourne le nombre d'éléments dans le tableau int taille() const; // Insère element à position index. Les éléments à partir de index sont décalés d'une position. void inserer(const T& element, int index=0); // Enlève l'element à position index. Les éléments après index sont décalés d'une position. void enlever(int index=0); // Enlève le dernier éléments. void enlever_dernier(); // Cherche et retourne la position de l'élément. Si non trouvé, retourne -1. int chercher(const T& element); const T& operator[] (int index) const; T& operator[] (int index); bool operator == (const Tableau<T>& autre) const; Tableau<T>& operator = (const Tableau<T>& autre); Tableau<T>& operator += (const Tableau<T>& autre); Tableau<T> operator + (const Tableau<T>& autre) const; void trier(); private: T* elements; int nbElements; int capacite; }; // ---------- Définitions ------------- template <class T> Tableau<T>::Tableau(int capacite_) { capacite = capacite_; nbElements = 0; elements = new T[capacite]; } template <class T> Tableau<T>::Tableau(const Tableau& autre) { nbElements = autre.nbElements; capacite = autre.capacite; elements = new T[capacite]; for(int i = 0; i < nbElements; i++){ elements[i] = autre.elements[i]; } } template <class T> Tableau<T>::~Tableau() { delete[] elements; elements = nullptr; } template <class T> int Tableau<T>::taille() const { return nbElements; } template <class T> void Tableau<T>::ajouter(const T& item) { if(nbElements >= capacite){ capacite *= 2; T* temp = new T[capacite]; for(int i = 0; i < nbElements; i++){ temp[i] = elements[i]; } delete[] elements; elements = temp; } elements[nbElements++] = item; } template <class T> void Tableau<T>::inserer(const T& element, int index) { if(nbElements >= capacite){ capacite *= 2; T* temp = new T[capacite]; for(int i = 0; i < nbElements; i++){ temp[i] = elements[i]; } delete[] elements; elements = temp; } nbElements++; for(int i = nbElements; i > index; i--){ elements[i] = elements[i-1]; } elements[index] = element; } template <class T> void Tableau<T>::enlever(int index) { nbElements--; for(int i = 0; i < nbElements; i++){ if(i >= index){ elements[i] = elements[i+1]; } } } template <class T> void Tableau<T>::enlever_dernier() { nbElements--; } template <class T> int Tableau<T>::chercher(const T& element) { for(int i = 0; i < nbElements; i++){ if(elements[i] == element) return i; } return -1; } template <class T> void Tableau<T>::vider() { nbElements = 0; } template <class T> const T& Tableau<T>::operator[] (int index) const { assert(index < nbElements); return elements[index]; } template <class T> T& Tableau<T>::operator[] (int index) { assert(index < nbElements); return elements[index]; } template <class T> Tableau<T>& Tableau<T>::operator = (const Tableau<T>& autre) { if(elements != autre.elements){ nbElements = autre.nbElements; capacite = autre.capacite; delete[] elements; elements = new T[capacite]; for(int i = 0; i < nbElements; i++){ elements[i] = autre.elements[i]; } } return *this; } template <class T> bool Tableau<T>::operator == (const Tableau<T>& autre) const { if(nbElements != autre.nbElements) return false; if(elements == autre.elements) return true; for(int i = 0; i < nbElements; i++){ if(elements[i] != autre.elements[i]) return false; } return true; } template <class T> Tableau<T>& Tableau<T>::operator += (const Tableau<T>& autre) { int tempNbElements = nbElements + autre.nbElements; while(capacite < tempNbElements){ capacite *= 2; } T* temp = new T[capacite]; for(int i = 0; i < nbElements; i++){ temp[i] = elements[i]; } for(int i = nbElements; i < autre.nbElements + nbElements; i++){ temp[i] = autre.elements[i - nbElements]; } delete[] elements; elements = temp; nbElements += autre.nbElements; return *this; } template <class T> Tableau<T> Tableau<T>::operator + (const Tableau<T>& autre) const { Tableau temp; for(int i = 0; i < nbElements; i++){ temp.ajouter(elements[i]); } for(int i = 0; i < autre.nbElements; i++){ temp.ajouter(autre.elements[i]); } return temp; } template <class T> void Tableau<T>::trier () { T temp; int i = 0; int j = 0; int nbPlusPetit = 0; for(i = 0; i < nbElements; i++){ temp = elements[i]; nbPlusPetit = i; for(j = i; j < nbElements; j++){ if(temp >= elements[j]){ temp = elements[j]; nbPlusPetit = j; } } elements[nbPlusPetit] = elements[i]; elements[i] = temp; } } #endif //define _TABLEAU___H_
[ "link852258" ]
link852258
9dfb37cad344fb871bd2b0856be354c5878435c2
3c85cc067bc9bb9db9015c207b58081ca10fe520
/examples/纸飞机/Classes/GameScene.h
34294aadf60f5b25fc91135f6ac20c929399fd44
[]
no_license
253627764/jowu
37ec3fb35aa87d99256657db0fb6b0dc8d61d33f
95b7d549bf02449a30efdafcfe650042f79b7f68
refs/heads/master
2021-01-21T16:44:14.491477
2015-05-17T16:50:23
2015-05-17T16:50:23
null
0
0
null
null
null
null
GB18030
C++
false
false
851
h
#ifndef GAME_SCENE #define GAME_SCENE #include "cocos2d.h" using namespace cocos2d; class GameScene:Layer{ public: bool init(); CREATE_FUNC(GameScene); static Scene * createScene(); void moveBackground(float t);//滚动背景 virtual bool onTouchBegan(Touch *touch, Event *unused_event); virtual void onTouchMoved(Touch *touch, Event *unused_event); virtual void onTouchEnded(Touch *touch, Event *unused_event); int px,py;//飞机的坐标 Vector<Sprite *> allBullet;//所有子弹 void newBullet(float t); void moveBullet(float t); Vector<Sprite *> allEnemy;//所有敌机 void newEnemy(float t); void moveEnemy(float t); void update(float t); int score;//分数 void newBomb(int x,int y);//爆炸效果 void killMe(Node * pSender);//删除自己 void jumpToMenu();//跳转到主菜单 }; #endif
[ "jowu598@gmail.com" ]
jowu598@gmail.com
5c0700c80f4a6aa8ef0519feeac4f65df75eec84
047404d893efa59565ff2e003193a305ae5bce8d
/Pulio/src/plpch.h
c8b0162544516d943e3eb8209d241c2d665fe767
[ "Apache-2.0" ]
permissive
Felixbuenen/Pulio
bf8a93306ac38349597ce3135eb08e3985b5b42b
085e86741028bdcffdc8d46128f1797e7c91acad
refs/heads/main
2023-02-09T18:57:41.390196
2020-12-26T12:13:20
2020-12-26T12:13:20
322,863,847
0
0
null
null
null
null
UTF-8
C++
false
false
280
h
#pragma once #include <iostream> #include <functional> #include <memory> #include <algorithm> #include <vector> #include <unordered_set> #include <unordered_map> #include <string> #include <sstream> #ifdef PL_PLATFORM_WINDOWS #include <Windows.h> #endif // PL_PLATFORM_WINDOWS
[ "felixbuenen@hotmail.com" ]
felixbuenen@hotmail.com
10b7ddfac6a6c5954c945b47ec0162a4e40e5ce1
453a0f967df3dec6a44ce08eb5a3493d11108e97
/Solution Files/W7_PA2/CashRegister.cpp
6a07fe708ca4943b2b0d7a7e08de32488458d0d5
[]
no_license
acckaufman/Inventory-Mgmt-Cash-Register
7e37449553fdb533a73b356fc1369d79c3590dde
32ed61ead4052dd25888c4b1bae423a0cb4bc790
refs/heads/master
2021-01-23T06:14:38.593295
2017-06-01T12:48:58
2017-06-01T12:48:58
93,015,060
0
0
null
null
null
null
UTF-8
C++
false
false
1,184
cpp
#include "CashRegister.h" //Default constructor CashRegister::CashRegister() { //Set the initial values to 0 unitPrice = 0; //Cost of unit with profit margin added purchaseSubtotal= 0; //Unit price of item ordered by user * quantity ordered by user salesTax = 0; //Amount of sales tax charged on the order purchaseTotal = 0; //Order subtotal for each iteration that the user orders items } //Mutator functions void CashRegister::calcUnitPrice(double c) { const double PROFIT_RATE = 0.3; unitPrice = (c * PROFIT_RATE) + c; } void CashRegister::calcPurchaseSubtotal(int q) { purchaseSubtotal = unitPrice * q; } void CashRegister::calcSalesTax() { const double TAX_RATE = 0.06; salesTax = purchaseSubtotal * TAX_RATE; } void CashRegister::calcPurchaseTotal() { purchaseTotal = purchaseSubtotal + salesTax; } //Accessor functions double CashRegister::getUnitPrice() const { return unitPrice; } double CashRegister::getPurchaseSubtotal() const { return purchaseSubtotal; } double CashRegister::getSalesTax() const { return salesTax; } double CashRegister::getPurchaseTotal() const { return purchaseTotal; } //Deconstructor CashRegister::~CashRegister() { }
[ "user.name" ]
user.name
58d5feb9accdee653523ed8a81220083f1103807
09f872ea3be98ddceb4106c48e3169a3acb7a418
/src/Zlang.UnitTests/grammar/SmokeVariablesTests.cpp
d94c1a82985f2b62dd25f196f2e6fb315541eb47
[]
no_license
obiwanjacobi/Zlang
ce51c3e5cdfcde13510a23b862519ea7947617e1
c9dea8b6a3dc6fd9bb6a556cdf515413d6e299dc
refs/heads/master
2021-07-15T17:48:36.377567
2020-10-11T15:13:43
2020-10-11T15:13:43
216,856,286
1
0
null
null
null
null
UTF-8
C++
false
false
992
cpp
#include "pch.h" #include "../Utils.h" #include <gtest/gtest.h> TEST(SmokeVariablesTests, GlobalAutoVariable) { const char* src = "g = 42\n" ; ASSERT_TRUE(ParserSmokeTest(src)); } TEST(SmokeVariablesTests, GlobalTypedVariable) { const char* src = "g: U8\n" ; ASSERT_TRUE(ParserSmokeTest(src)); } TEST(SmokeVariablesTests, GlobalTypedVariableInit) { const char* src = "g: U8 = 42\n" ; ASSERT_TRUE(ParserSmokeTest(src)); } TEST(SmokeVariablesTests, LocalAutoVariable) { const char* src = "fn()\n" " l = 42\n" ; ASSERT_TRUE(ParserSmokeTest(src)); } TEST(SmokeVariablesTests, LocalTypedVariable) { const char* src = "fn()\n" " l: U8\n" ; ASSERT_TRUE(ParserSmokeTest(src)); } TEST(SmokeVariablesTests, LocalTypedVariableInit) { const char* src = "fn()\n" " l: U8 = 42\n" ; ASSERT_TRUE(ParserSmokeTest(src)); }
[ "marc.jacobi@macaw.nl" ]
marc.jacobi@macaw.nl
b165b01f577b283296e8351a5b3c32397c567aeb
5d01a2a16078b78fbb7380a6ee548fc87a80e333
/EgarCommonLibrary/EgDebugUtil/test/test.cpp
e130e555803e47e9192b6a28a332d467201a530f
[]
no_license
WilliamQf-AI/IVRMstandard
2fd66ae6e81976d39705614cfab3dbfb4e8553c5
761bbdd0343012e7367ea111869bb6a9d8f043c0
refs/heads/master
2023-04-04T22:06:48.237586
2013-04-17T13:56:40
2013-04-17T13:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
// test.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "windows.h" #include "EgDebugUtil.h" void test2() { int* a = NULL; *a = 10; } void test() { test2(); } unsigned WINAPI Thread(LPVOID) { test(); return 0; }; int main(int argc, char* argv[]) { SetMiniDumpDefaultCrashHandler(); WaitForSingleObject((HANDLE)_beginthreadex(NULL, 0, Thread, NULL, 0, NULL), INFINITE); return 0; }
[ "chuchev@egartech.com" ]
chuchev@egartech.com
c7e711a3fddca7a5c497cea4773e8d0a3f6e1012
3cda495f70e60b1ee0198f71f5d98b5b139aec42
/source/Chapter2/Ch2_01_HandShakeWithVulkan/source/common/VulkanApp.h
fb47da13b58f52ba31054955c8912003df15d04c
[]
no_license
giraphics/VulkanByExamples
8636e7e43a5c4abc77cd79d8f13b779894ccbe3b
c189f9487eec3331bd48423451d15d76fd47dcb6
refs/heads/master
2022-01-20T05:49:48.913207
2019-07-28T17:47:15
2019-07-28T17:47:15
199,310,758
0
1
null
null
null
null
UTF-8
C++
false
false
207
h
#pragma once #include "VulkanHelper.h" // Base class for Vulkan application class VulkanApp { public: VulkanApp(); virtual ~VulkanApp(); void Initialize(); // Initialize the Vulkan application };
[ "noreply@github.com" ]
noreply@github.com
8563ff39d32f399a6c05ca2177b78da87d4219ac
7998e94e65d09f8da75fa397edcfc60a56de7c83
/CityProject/cityapp.cpp
cfc6d56c4d73547a4db19790950984575af92290
[]
no_license
richardszeto/CityProject
65959c3f86a658923154b924aae057d4e07923ee
c99d4e4ad0ade85436dabe7ff19795dc74f30695
refs/heads/master
2020-05-19T15:30:20.230396
2014-05-30T06:36:26
2014-05-30T06:36:26
20,243,873
0
0
null
null
null
null
UTF-8
C++
false
false
7,235
cpp
#include "cityapp.h" Street CityApp::ground; Billboards CityApp::bb; MovingCar CityApp::movingCars; Sky CityApp::sky; Buildings *CityApp::buildings; //changed pointer to real object float eyeX = -114.800087; float eyeY = -50.997894; float eyeZ = -69.500092; float lookX = 100.0f; float lookY = 2.7f; float lookZ = 10.0f; int frame = 0; int follow = 0; CityApp::CityApp(int argc, char **argv) { glutInit(&argc,argv); glutInitWindowSize(width, height); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGB); // Init depth buffer, double buffer, and RGB color scheme. glutCreateWindow("City Program"); gluLookAt(lookX,lookY,lookZ,0,0,0,0,1,0); //set up camera position and orientation glutKeyboardFunc(keyDown); //Key down callback glutKeyboardUpFunc(keyUp); //Key up callback glutMotionFunc(mouseMove); //mouse callback glutDisplayFunc(render); //Redraw callback glutIdleFunc(update); //No input callback initOpenGL(); } CityApp::~CityApp() { delete buildings; } void CityApp::run() { glutMainLoop(); } void CityApp::update() { glutPostRedisplay(); frame++; } void CityApp::cameraUpdate(){ int xCamera = movingCars.getX((frame)/10); int zCamera = movingCars.getZ((frame)/10); int xbuff; int zbuff; switch(follow) { case 1: if(xCamera < 0){xbuff +=50;} else{xbuff -=50;} if(zCamera > 0){zbuff +=50;} else{zbuff -=50;} gluLookAt(xCamera,10,zCamera, movingCars.getX((frame-xbuff)/10), 10, movingCars.getZ((frame-zbuff)/10), 0,1,0); //set up camera position and orientation //printf("%f %f\n", movingCars.getX(frame/10), movingCars.getZ(frame/10)); break; case 2: if(xCamera < 0){xbuff +=50; xCamera+=5;} else{xbuff -=50; xCamera-=5;} if(zCamera > 0){zbuff +=50;} else{zbuff -=50;} gluLookAt(xCamera,10,zCamera, movingCars.getX((frame+xbuff)/10), 0, movingCars.getZ((frame+zbuff)/10), 0,1,0); //set up camera position and orientation //printf("%f %f\n", movingCars.getX(frame/10), movingCars.getZ(frame/10)); break; case 3: if(xCamera < 0){xCamera+=10;} else{xCamera-=10;} if(zCamera < 0){zCamera+=10;} else{zCamera-=10;} gluLookAt(xCamera,1,zCamera, movingCars.getX(frame/10), 1, movingCars.getZ(frame/10), 0,1,0); //set up camera position and orientation //printf("%f %f\n", movingCars.getX(frame/10), movingCars.getZ(frame/10)); break; case 4: if(xCamera > 0){xCamera+=10;} else{xCamera-=10;} if(zCamera > 0){zCamera+=10;} else{zCamera-=10;} gluLookAt(xCamera,20,zCamera, movingCars.getX(frame/10), 10, movingCars.getZ(frame/10), 0,1,0); //set up camera position and orientation //printf("%f %f\n", movingCars.getX(frame/10), movingCars.getZ(frame/10)); break; case 5: if(xCamera < 0){xCamera+=10;} else{xCamera-=10;} if(zCamera < 0){zCamera+=10;} else{zCamera-=10;} gluLookAt(xCamera,10,zCamera, movingCars.getX(frame/10), 15, movingCars.getZ(frame/10), 0,1,0); //set up camera position and orientation //printf("%f %f\n", movingCars.getX(frame/10), movingCars.getZ(frame/10)); break; default: gluLookAt(lookX,lookY,lookZ,0,0,0,0,1,0); //set up camera position and orientation //printf("%f %f %f\n", lookX, lookY, lookZ ); glTranslatef(eyeX, eyeY, eyeZ); //printf("%f %f %f\n", eyeX, eyeY, eyeZ); break; } } void CityApp::initOpenGL() { glShadeModel(GL_SMOOTH); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color for glClear() glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glEnable(GL_TEXTURE_2D); initWorld(); // lighting set up glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER, GL_TRUE); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_LIGHT1); glEnable(GL_LIGHT2); glEnable(GL_LIGHT3); //Set lighting intensity and color GLfloat qaAmbientLight[] = {.2, .2, .2, 1.0}; GLfloat qaDiffuseLight[] = {.7, .7, .7, 1.0}; GLfloat qaSpecularLight[] = {1, 1, 1, 1.0}; glLightfv(GL_LIGHT0, GL_AMBIENT, qaAmbientLight); glLightfv(GL_LIGHT0, GL_DIFFUSE, qaDiffuseLight); glLightfv(GL_LIGHT0, GL_SPECULAR, qaSpecularLight); glLightfv(GL_LIGHT1, GL_AMBIENT, qaAmbientLight); glLightfv(GL_LIGHT1, GL_DIFFUSE, qaDiffuseLight); glLightfv(GL_LIGHT1, GL_SPECULAR, qaSpecularLight); glLightfv(GL_LIGHT2, GL_AMBIENT, qaAmbientLight); glLightfv(GL_LIGHT2, GL_DIFFUSE, qaDiffuseLight); glLightfv(GL_LIGHT2, GL_SPECULAR, qaSpecularLight); glLightfv(GL_LIGHT3, GL_AMBIENT, qaAmbientLight); glLightfv(GL_LIGHT3, GL_DIFFUSE, qaDiffuseLight); glLightfv(GL_LIGHT3, GL_SPECULAR, qaSpecularLight); glLightfv(GL_LIGHT4, GL_AMBIENT, qaAmbientLight); glLightfv(GL_LIGHT4, GL_DIFFUSE, qaDiffuseLight); glLightfv(GL_LIGHT4, GL_SPECULAR, qaSpecularLight); //Set the light position GLfloat q1LightPosition[] = {90.0, 90.0, 5.0, 1.0}; GLfloat q2LightPosition[] = {-90.0, 90.0, 140.0, 1.0}; GLfloat q3LightPosition[] = {90.0, 90.0, 5.0, 1.0}; GLfloat q4LightPosition[] = {-90.0, 90.0, 140.0, 1.0}; glLightfv(GL_LIGHT0, GL_POSITION, q1LightPosition); glLightfv(GL_LIGHT1, GL_POSITION, q2LightPosition); glLightfv(GL_LIGHT3, GL_POSITION, q3LightPosition); glLightfv(GL_LIGHT4, GL_POSITION, q4LightPosition); } void CityApp::render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Clear color values in framebuffer glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f,(GLfloat)width/(GLfloat)height,0.1f,10000.0f);//Initializes projection matrix. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //Initializes modelview matrix. cameraUpdate(); drawObjects(); glFlush(); glutSwapBuffers(); } void CityApp::keyDown(unsigned char key, int, int) { switch(key) { case 'a': eyeX += 5; break; case 'd': eyeX -= 5; break; case 'w': eyeZ += 5; break; case 's': eyeZ -= 5; break; case 't': eyeY += 5; break; case 'g': eyeY -= 5; break; case 'l': lookY -= 5; break; case 'o': lookY += 5; break; case 'p': lookX += 5; break; case 'i': lookX -= 5; break; case 'u': lookZ += 5; break; case 'k': lookZ -= 5; break; case '8': follow = (follow+1)%6; break; case 'q': exit(0); break; case 27: exit(0); break; default: break; } } void CityApp::keyUp(unsigned char key, int, int) {} void CityApp::mouseMove(int x, int y) { //camera.mouseMovement(x, y); } void CityApp::initWorld() { sky.init(); movingCars.init(); ground.init(); bb.init(); buildings = new Buildings(); buildings->generateWindowTexture(); //changed method of binding texture } void CityApp::drawObjects() { sky.draw(); buildings->draw(); //changed method of drawing buildings ground.draw(); bb.draw(); movingCars.draw(frame/10); }
[ "richardszeto74@gmail.com" ]
richardszeto74@gmail.com
20314fd425091cc1130bf354a59154b4defb9f16
109096cb09df8bb6648e11ee22f64ca56a06c996
/TronGame/Bike.h
69bfb1430f02d6204bfbcb9ac019f4ac99235550
[]
no_license
ryan-kane/TronGA
7ee554f1d1ffc46c2605490b65088a44946ec709
caf4e3028aa538bc1be1c9bfdf2298ef65427665
refs/heads/master
2020-04-07T18:37:00.753161
2019-01-15T16:03:38
2019-01-15T16:03:38
158,616,950
0
0
null
null
null
null
UTF-8
C++
false
false
501
h
#ifndef BIKE_H #define BIKE_H #include <vector> using namespace std; class Bike{ int color; int directionX; int directionY; int headX; int headY; int tailSize; public: Bike(int, int, int, int, int); int getColor(); int getHeadX(); void setHeadX(int); int getHeadY(); void setHeadY(int); int getDirectionX(); void setDirectionX(int); int getDirectionY(); void setDirectionY(int); }; #endif
[ "ryan@thekanes.ca" ]
ryan@thekanes.ca
93d7080e3583944b983cba46d90fbf9fcbfc524e
0562cf42a0680a32fd3a6a3e272f30c12a494b89
/slvrs/LcCompletePolynomialElement.h
78a16c4294ab78c5317282a0c9790b481d3f07cf
[]
no_license
ammarhakim/gkeyll1
70131876e4a68851a548e4d45e225498911eb2b6
59da9591106207e22787d72b9c2f3e7fbdc1a7e4
refs/heads/master
2020-09-08T05:23:47.974889
2019-02-06T18:09:18
2019-02-06T18:09:18
221,027,635
0
0
null
null
null
null
UTF-8
C++
false
false
17,895
h
/** * @file LcCompletePolynomialElement.h * * @brief Complete polynomial element */ #ifndef LC_COMPLETE_POLYNOMIAL_ELEMENT_H #define LC_COMPLETE_POLYNOMIAL_ELEMENT_H // config stuff #ifdef HAVE_CONFIG_H # include <config.h> #endif // lucee includes #include <LcNodalFiniteElementIfc.h> #include <LcCDIM.h> // std includes #include <cmath> #include <vector> // eigen includes #include <Eigen/Dense> #include <Eigen/LU> //blitz includes #include <blitz/array.h> // etc includes #include <quadrule.hpp> namespace Lucee { /** * Complete polynomial elements in arbitrary dimensions * */ template <unsigned NDIM> class CompletePolynomialElement : public Lucee::NodalFiniteElementIfc<NDIM> { // Number of components for coordinate arrays etc. static const unsigned NC = Lucee::CDIM<NDIM>::N; public: /** Class id: this is used by registration system */ static const char *id; /** * Create a new complete polynomial element. This does not create a usable * object which can only be created from Lua. */ CompletePolynomialElement(); /** * Bootstrap method: Read input from specified table. * * @param tbl Table of input values. */ virtual void readInput(Lucee::LuaTable& tbl); /** * Get local indices of nodes exclusively owned by each cell. * * @param ndIds On output indices. Vector is cleared and data filled in. */ virtual void getExclusiveNodeIndices(std::vector<int>& ndIds); /** * Get number of surface nodes along lower face in specified * direction. * * @param dir Direction to which face is perpendicular. * @return number of nodes in element. */ virtual unsigned getNumSurfLowerNodes(unsigned dir) const; /** * Get number of surface nodes along upper face in specified * direction. * * @param dir Direction to which face is perpendicular. * @return number of nodes in element. */ virtual unsigned getNumSurfUpperNodes(unsigned dir) const; /** * Get number of global nodes in element. * * @return number of nodes in element. */ virtual unsigned getNumGlobalNodes() const; /** * Get mapping of local node numbers in the current cell to global * node number. The input vector must be pre-allocated. * * @param lgMap Local node number to global node number mapping. */ virtual void getLocalToGlobal(std::vector<int>& lgMap) const; /** * Get mapping of local node numbers to global node numbers on lower * face of element in direction 'dir' in the current cell. The output * vector must be pre-allocated. * * @param dir Direction to which face is perpendicular. * @param lgMap Local node number to global node number mapping. */ virtual void getSurfLowerLocalToGlobal(unsigned dir, std::vector<int>& lgMap) const; /** * Get mapping of local node numbers to global node numbers on upper * face of element in direction 'dim' in the current cell. The output * vector must be pre-allocated. * * @param lgMap Local node number to global node number mapping. */ virtual void getSurfUpperLocalToGlobal(unsigned dim, std::vector<int>& lgMap) const; /** * Get node numbers of the nodes on specified face of element. The * output vector must be pre-allocated. * * @param dir Direction to which face is perpendicular. * @param nodeNum Node numbers on face. */ virtual void getSurfLowerNodeNums(unsigned dir, std::vector<int>& nodeNum) const; /** * Get node numbers of the nodes on specified face of element. The * output vector must be pre-allocated. * * @param dir Direction to which face is perpendicular. * @param nodeNum Node numbers on face. */ virtual void getSurfUpperNodeNums(unsigned dir, std::vector<int>& nodeNum) const; /** * Get coordinates of all nodes in element. The output matrix * 'nodeCoords' should be pre-allocated have shape numNodes X 3. * * @param nodeCoords Node coordinates. Should be pre-allocated. */ virtual void getNodalCoordinates(Lucee::Matrix<double>& nodeCoords); /** * Get weights for quadrature. The output vector should be * pre-allocated. * * @param w Weights for quadrature. */ virtual void getWeights(std::vector<double>& w); /** * Get weights for quadrature on upper face. The output vector should * be pre-allocated. * * @param dir Direction to which face is perpendicular. * @param w Weights for quadrature. */ virtual void getSurfUpperWeights(unsigned dir, std::vector<double>& w); /** * Get weights for quadrature on upper face. The output vector should * be pre-allocated. * * @param dir Direction to which face is perpendicular. * @param w Weights for quadrature. */ virtual void getSurfLowerWeights(unsigned dir, std::vector<double>& w); /** * Get mass matrix for this reference element. The output matrix * should be pre-allocated. * * @param NjNk On output, mass matrix of element. */ virtual void getMassMatrix(Lucee::Matrix<double>& NjNk) const; /** * Get mass matrix for this reference element. The output matrix * should be pre-allocated. * * @param dir Direction of face. * @param NjNk On output, mass matrix of element. */ virtual void getLowerFaceMassMatrix(unsigned dir, Lucee::Matrix<double>& NjNk) const; /** * Get mass matrix for this reference element. The output matrix * should be pre-allocated. * * @param dir Direction of face. * @param NjNk On output, mass matrix of element. */ virtual void getUpperFaceMassMatrix(unsigned dir, Lucee::Matrix<double>& NjNk) const; /** * Get stiffness matrix (grad.Nj \dot grad.Nk) for this reference * element. The output matrix should be pre-allocated. * * @param DNjDNk On output, stiffness matrix of element. */ virtual void getStiffnessMatrix(Lucee::Matrix<double>& DNjDNk) const; /** * Get partial stiffness matrix (grad.Nj Nk) for this reference * element. The output matrix should be pre-allocated. * * @param dir Direction for gradient. * @param DNjNk On output, partial stiffness matrix of element. */ virtual void getGradStiffnessMatrix(unsigned dir, Lucee::Matrix<double>& DNjNk) const; /** * Get number of nodes needed for Gaussian quadrature in the element * interior. * * @return Number of nodes needed for Gaussian quadrature. */ virtual unsigned getNumGaussNodes() const; /** * Get number of nodes needed for Gaussian quadrature on the element * surface. * * @return Number of nodes needed for Gaussian quadrature. */ virtual unsigned getNumSurfGaussNodes() const; /** * Get data needed for Gaussian quadrature for this element. All * output matrices and vectors must be pre-allocated. * * @param interpMat On output, interpolation matrix. * @param ordinates On output, quadrature ordinates. * @param weights On output, quadrature weights. */ virtual void getGaussQuadData(Lucee::Matrix<double>& interpMat, Lucee::Matrix<double>& ordinates, std::vector<double>& weights) const; /** * Get data needed for Gaussian quadrature on lower surfaces of this * element. All output matrices and vectors must be pre-allocated. * * @param interpMat On output, interpolation matrix. * @param ordinates On output, quadrature ordinates. * @param weights On output, quadrature weights. */ virtual void getSurfLowerGaussQuadData(unsigned dir, Lucee::Matrix<double>& interpMat, Lucee::Matrix<double>& ordinates, std::vector<double>& weights) const; /** * Get data needed for Gaussian quadrature on upper surfaces of this * element. All output matrices and vectors must be pre-allocated. * * @param interpMat On output, interpolation matrix. * @param ordinates On output, quadrature ordinates. * @param weights On output, quadrature weights. */ virtual void getSurfUpperGaussQuadData(unsigned dir, Lucee::Matrix<double>& interpMat, Lucee::Matrix<double>& ordinates, std::vector<double>& weights) const; /** * Get matrix for projection on a lower-dimensional basis set. This * method returns the moment matrix (in 2D, for example) * * \int y^p \phi(x,y) \psi(x) dx dy * * @param p Required moment. * @param momMatt On output, moment matrix. */ virtual void getMomentMatrix(unsigned p, Lucee::Matrix<double>& momMat) const; /** * Get matrices needed to compute diffusion operator. The matrices are * for the current cell and each of its face neighbors, stored in * "lowerMat" for cells sharing lower faces and "upperMat" for cells * sharing upper faces. A linear combination of these matrices when * multiplied by the nodal data in the corresponding cells should give * the discrete diffusion operator. * * @param iMat Matrix for current cell, split into contributions from each direction. * @param lowerMat Matrices for cells sharing lower faces. * @param upperMat Matrices for cells sharing upper faces. */ void getDiffusionMatrices(std::vector<Lucee::Matrix<double> >& iMat, std::vector<Lucee::Matrix<double> >& lowerMat, std::vector<Lucee::Matrix<double> >& upperMat) const; /** * Get matrices needed to compute hyper-diffusion operator. The * matrices are for the current cell and each of its face neighbors, * stored in "lowerMat" for cells sharing lower faces and "upperMat" * for cells sharing upper faces. A linear combination of these * matrices when multiplied by the nodal data in the corresponding * cells should give the discrete diffusion operator. * * @param iMat Matrix for current cell. * @param lowerMat Matrices for cells sharing lower faces. * @param upperMat Matrices for cells sharing upper faces. */ void getHyperDiffusionMatrices(std::vector<Lucee::Matrix<double> >& iMat, std::vector<Lucee::Matrix<double> >& lowerMat, std::vector<Lucee::Matrix<double> >& upperMat) const; /** * Get coefficients for applying reflecting boundary conditions on * lower side in direction 'dir'. The vector nodeMap[i] is the * reflected node corresponding to node 'i'. * * @param dir Direction to which face is perpendicular. * @param nodeMap Map for reflecting nodes. */ virtual void getLowerReflectingBcMapping(unsigned dir, std::vector<unsigned>& nodeMap) const; /** * Get coefficients for applying reflecting boundary conditions on * upper side in direction 'dir'. The vector nodeMap[i] is the * reflected node corresponding to node 'i'. * * @param dir Direction to which face is perpendicular. * @param nodeMap Map for reflecting nodes. */ virtual void getUpperReflectingBcMapping(unsigned dir, std::vector<unsigned>& nodeMap) const; /** * Compute mapping of nodes from a face to element interior for lower * face in specified direction. The shape of the output matrix * faceToIntMap is (numVolNodes X numFaceNodes). * * @param dir Direction to which face is perpendicular. * @param faceToIntMap Matrix storing the mapping. */ virtual void getLowerFaceToInteriorMapping(unsigned dir, Lucee::Matrix<double>& faceToIntMap) const; /** * Extract nodal data at current grid location from field and copy it * into a vector. This basically "flattens" the nodal data consistent * with the node layout and the stiffness, mass matrices. The output * vector should be pre-allocated. * * @param fld Field to extract nodal data from. * @param data On output, this containts a copy of extracted data. */ virtual void extractFromField(const Lucee::Field<NDIM, double>& fld, std::vector<double>& data); /** * Copy all nodal data from field and put it into the data array. The * data pointer should be pre-allocated. * * @param fld Field to extract data from. * @param data Data space to copy into. */ virtual void copyAllDataFromField(const Lucee::Field<NDIM, double>& fld, double *data); /** * Copy all nodal data to field from a data array. * * @param data Data space to copy from. * @param fld Field to copy data to. */ virtual void copyAllDataToField(const double *data, Lucee::Field<NDIM, double>& fld); /** * Evaluate basis functions at location. The results should be stored * in the pre-allocated 'vals' vector. * * @param xc Coordinates in element. * @param vals Values of basis functions. Pre-allocated. */ virtual void evalBasis(double xc[NDIM], std::vector<double>& vals) const; private : /** Polynomial order of element */ unsigned polyOrder; /** Maximum polynomial power anticipated */ unsigned maxPower; /** Total number of quadrature points in 1-D */ unsigned numGaussPoints; /** Highest moment degree to compute */ int maxMoment; /** Grid spacing in various dimensions */ double dq[NDIM]; /** Grid spacing squared in various dimensions */ double dq2[NDIM]; std::vector<blitz::Array<double,NDIM> > functionVector; /** Matrix containing basis functions evaluated at volume gaussian integration locations Correspondance between column and gaussian node set is kept track of in gaussNodeList Each row is a different quadrature point. Each column is a different basis function evaluated at the same point*/ Eigen::MatrixXd functionEvaluations; /** Matrix containing basis functions evaluated at surface gaussian integration locations Correspondance between row and gaussian node set is kept track of in gaussNodeListUpperSurf Each row is a different evaluation location Each column is a different basis function */ std::vector<Eigen::MatrixXd> upperSurfaceEvaluations; /** Matrix containing basis functions evaluated at surface gaussian integration locations Correspondance between row and gaussian node set is kept track of in gaussNodeListLowerSurf Each row is a different evaluation location Each column is a different basis function */ std::vector<Eigen::MatrixXd> lowerSurfaceEvaluations; /** Matrix whose ith row corresponds to the coordinates of the node at which the ith column of functionEvaluations (and functionDEvaluations) is evaluated at. Size NDIM+1 columns because last entry is net weight */ Eigen::MatrixXd gaussNodeList; /** Vector of gaussian quadrature coordinates on upper surface indexed by dimension Each row is the coordinates of a node + weight in last col */ std::vector<Eigen::MatrixXd> gaussNodeListUpperSurf; /** Vector of gaussian quadrature coordinates on lower surface indexed by dimension*/ std::vector<Eigen::MatrixXd> gaussNodeListLowerSurf; /** Weights for quadrature (one dimension)*/ std::vector<double> gaussWeights; /** Ordinates for (one dimension) quadrature */ std::vector<double> gaussPoints; /** Vector of face-mass matrices indexed by dimension (Lower) */ std::vector<Eigen::MatrixXd> refFaceMassLower; /** Vector of face-mass matrices indexed by dimension (Upper) */ std::vector<Eigen::MatrixXd> refFaceMassUpper; /** Vector of grad stiffness matrices indexed by dimension */ std::vector<Eigen::MatrixXd> refGradStiffness; /** Mass matrix in reference coordinates */ Eigen::MatrixXd refMass; /** Stiffness matrix in reference coordinates */ Eigen::MatrixXd refStiffness; /** Vector of moment matrices indexed by moment value p */ std::vector<Eigen::MatrixXd> momMatrix; /** List of matrices for current cell */ std::vector<Eigen::MatrixXd> iMatDiffusion; std::vector<Eigen::MatrixXd> iMatHyperDiffusion; /** List of matrices on each lower face */ std::vector<Eigen::MatrixXd> lowerMatDiffusion; std::vector<Eigen::MatrixXd> lowerMatHyperDiffusion; /** List of matrices on each upper face */ std::vector<Eigen::MatrixXd> upperMatDiffusion; std::vector<Eigen::MatrixXd> upperMatHyperDiffusion; /** Face to interior mapping matrices */ std::vector<Eigen::MatrixXd> lowerFaceToInteriorMapMatrices; /** * Create necessary matrices needed for complete polynomial elements. */ void setupMatrices(); /** * Resize output matrices computed in setupMatrices() */ void resizeMatrices(); /** * Create basis monomials by populating matrix of rows * [a b c] to represent x^a*y^b*z^c monomials */ void setupBasisMatrix(Eigen::MatrixXi& basisMatrix); /** * Compute the basis functions in terms of the basis monomials */ void computeBasisFunctions(std::vector<blitz::Array<double, NDIM> >& functionVector); /** * Evaluate a polynomial represented by coefficients in a n-d array at a specific location * defined by a vector nodeCoords */ double evalPolynomial(const blitz::Array<double, NDIM>& polyCoeffs, const Eigen::VectorXd& nodeCoords) const; /** * Compute the partial derivative of a polynomial in direction 'dir' */ blitz::Array<double, NDIM> computePolynomialDerivative(const blitz::Array<double, NDIM>& poly, int dir); /** * Compute the mass matrix on the reference element. */ void computeMass(Eigen::MatrixXd& resultMatrix); /** * Compute the face-mass matrices on the reference element in direction num. */ void computeFaceMass(int dir, Eigen::MatrixXd& lowerResultMatrix, Eigen::MatrixXd& upperResultMatrix); /** * Compute the stiffness matrix on the reference element. */ void computeStiffness(const blitz::Array<double, 3>& functionDerivative, Eigen::MatrixXd& resultMatrix); /** * Compute the grad stiffness matrix in direction dir on the reference element. */ void computeGradStiffness(const blitz::Array<double, 3>& functionDerivative, int dir, Eigen::MatrixXd& resultMatrix); /** * Compute 'cross-dimensional' basis functions */ void setupMomentMatrices(); /** * Compute the number of degrees of freedom for this element * with degree r and in dimension n */ int getCompletePolynomialDimension(int degree, int dimension) const; /** * Compute n! */ int factorial(int n) const; }; } #endif // LC_COMPLETE_POLYNOMIAL_ELEMENT_H
[ "eshi@pppl.gov" ]
eshi@pppl.gov
e030bf9f69c1dc05c65ff51d2ca4077dcb91aeab
e5361781992b06eda344f6159bd0d8389ab34347
/MQ2Main/MQ2ParseAPI.cpp
a8f4126964c3b2e56200bfd4ba20d8c64d1fc7f1
[]
no_license
macroquest/macroquest2
891d6d88debcfa8de4973c38ee1c78bebc3abe79
cdd5792d24568259641cd659b8937813d35aa71b
refs/heads/master
2022-01-22T18:08:41.946143
2022-01-19T22:59:08
2022-01-19T22:59:08
73,879,770
23
28
null
2022-10-02T22:37:57
2016-11-16T03:22:54
C++
UTF-8
C++
false
false
5,729
cpp
/***************************************************************************** MQ2Main.dll: MacroQuest2's extension DLL for EverQuest Copyright (C) 2002-2003 Plazmic, 2003-2005 Lax Portions Copyright(C) 2004 Zaphod This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ******************************************************************************/ #ifndef ISXEQ #if !defined(CINTERFACE) #error /DCINTERFACE #endif #define DBG_SPEW #include "MQ2Main.h" VOID InitializeParser() { DebugSpewNoFile("InitializeParser()"); InitializeMQ2DataTypes(); InitializeMQ2Data(); bmParseMacroParameter=AddMQ2Benchmark("ParseMacroParameter"); } VOID ShutdownParser() { DebugSpewNoFile("ShutdownParser()"); ShutdownMQ2Data(); ShutdownMQ2DataTypes(); } // *************************************************************************** // Function: ParseMacroParameter // Description: Parses macro $ parameters ($cursor, etc) // *************************************************************************** /***************************************************************************** * NOTE: New syntax for adding macro parameters! * * Coded and converted by Valerian. * * 1: Make changes in EQLib_MacroParser.h to reflect new function, and text * * to call that function. * * A: PMP funcs: Simply make note of those already there, and make yours * * the same. * * * * B: Parms[] global variable: * * First field is the text that will call the parm func, minus the "$" * * e.g. for $spawn(250,type) this would simply be "spawn". Lowercase. * * * * Second field is the function name to call. * * * * Third field is NULL -- This field will be set to the address of the * * function, the first time ParseMacroParameter is run. * * * * 2: Function definition MUST be: * * DWORD YourFuncName(PCHAR szVar, PCHAR szOutput, PSPAWNINFO pChar) * * A: Parameters are as follows: * * * * DWORD return value: Old "i++" value. e.g. number of chars to skip * * in original string. Size of your parameter, * * without the "$", and minus 1. $spawn(250,type) * * should return 14. Returning 10000 indicates an * * error return. (Bad macro parameter) * * * * szVar: Text of parameter, up to and including trailing * * ")". May contain entire line if there are no ")"* * characters in that parameter. * * * * szOutput: Output string. You will need to strcat your * * output into this string. * * * * **NOTE** The ordering of commands in Parms[] variable may be important! * * They get checked in the order they are in the variable, and * * similar names must have the more specific one first! If there * * are two parms, e.g. "item" and "items", "items" must be first, * * or else the "item" command will be called and fail for a bad * * parm. Also note that you should be able to include a "(" at the * * end of your parm name, or any number of chars there. * * "myparm(thisoption," is acceptable. * *****************************************************************************/ int FindLastParameter(PCSTR szOriginal, PCSTR& szRetCurPos, size_t& len) { PCSTR szCurPos; PCSTR szParamPos = NULL; // iterate over the entire string for (szCurPos = szOriginal; *szCurPos; szCurPos++) if ((*szCurPos == '$') || (*szCurPos == '@')) // note parameter position szParamPos = szCurPos; // calculate the strings length len = (size_t)(szCurPos - szOriginal - 1); // return the parameters position szRetCurPos = szParamPos; if (szParamPos) // return offset into string if paramater found return (int)(szParamPos - szOriginal); return -1; // no parameter found } PCHAR ParseMacroParameter(PSPAWNINFO pChar, PCHAR szOriginal, SIZE_T BufferSize) { PCHARINFO pCharInfo = GetCharInfo(); if (!pCharInfo) return szOriginal; EnterMQ2Benchmark(bmParseMacroParameter); ParseMacroData(szOriginal, BufferSize); ExitMQ2Benchmark(bmParseMacroParameter); return (szOriginal); } #endif
[ "brainiac2k@gmail.com" ]
brainiac2k@gmail.com
07a807417bfe4d9b570891974d3b6b000da70e0a
85e95a51e2d8e4990920721ba7bad6f8b25146eb
/source/extensions/transport_sockets/tls/cert_validator/spiffe/spiffe_validator.h
122f6d56b6af3313cf9b2a12fb3ff502aa8771b5
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
zonghaishang/envoy
337249cef2cedb0e6dd499f92dc8da4f005a942b
19636abfe95ae4d012a347db5ce8f8d5430ff3ad
refs/heads/main
2023-03-15T02:38:40.413303
2022-11-07T05:02:59
2022-11-07T05:02:59
264,844,733
3
0
Apache-2.0
2020-05-18T06:13:12
2020-05-18T06:13:11
null
UTF-8
C++
false
false
3,628
h
#pragma once #include <array> #include <deque> #include <functional> #include <string> #include <vector> #include "envoy/common/pure.h" #include "envoy/network/transport_socket.h" #include "envoy/ssl/context.h" #include "envoy/ssl/context_config.h" #include "envoy/ssl/private_key/private_key.h" #include "envoy/ssl/ssl_socket_extended_info.h" #include "source/common/common/c_smart_ptr.h" #include "source/common/common/matchers.h" #include "source/common/stats/symbol_table.h" #include "source/extensions/transport_sockets/tls/cert_validator/cert_validator.h" #include "source/extensions/transport_sockets/tls/cert_validator/san_matcher.h" #include "source/extensions/transport_sockets/tls/stats.h" #include "openssl/ssl.h" #include "openssl/x509v3.h" namespace Envoy { namespace Extensions { namespace TransportSockets { namespace Tls { using X509StorePtr = CSmartPtr<X509_STORE, X509_STORE_free>; class SPIFFEValidator : public CertValidator { public: SPIFFEValidator(SslStats& stats, TimeSource& time_source) : stats_(stats), time_source_(time_source){}; SPIFFEValidator(const Envoy::Ssl::CertificateValidationContextConfig* config, SslStats& stats, TimeSource& time_source); ~SPIFFEValidator() override = default; // Tls::CertValidator void addClientValidationContext(SSL_CTX* context, bool require_client_cert) override; int doSynchronousVerifyCertChain( X509_STORE_CTX* store_ctx, Ssl::SslExtendedSocketInfo* ssl_extended_info, X509& leaf_cert, const Network::TransportSocketOptions* transport_socket_options) override; ValidationResults doVerifyCertChain(STACK_OF(X509)& cert_chain, Ssl::ValidateResultCallbackPtr callback, Ssl::SslExtendedSocketInfo* ssl_extended_info, const Network::TransportSocketOptionsConstSharedPtr& transport_socket_options, SSL_CTX& ssl_ctx, const CertValidator::ExtraValidationContext& validation_context, bool is_server, absl::string_view host_name) override; int initializeSslContexts(std::vector<SSL_CTX*> contexts, bool provides_certificates) override; void updateDigestForSessionId(bssl::ScopedEVP_MD_CTX& md, uint8_t hash_buffer[EVP_MAX_MD_SIZE], unsigned hash_length) override; absl::optional<uint32_t> daysUntilFirstCertExpires() const override; std::string getCaFileName() const override { return ca_file_name_; } Envoy::Ssl::CertificateDetailsPtr getCaCertInformation() const override; // Utility functions X509_STORE* getTrustBundleStore(X509* leaf_cert); static std::string extractTrustDomain(const std::string& san); static bool certificatePrecheck(X509* leaf_cert); absl::flat_hash_map<std::string, X509StorePtr>& trustBundleStores() { return trust_bundle_stores_; }; bool matchSubjectAltName(X509& leaf_cert); private: bool verifyCertChainUsingTrustBundleStore(Ssl::SslExtendedSocketInfo* ssl_extended_info, X509& leaf_cert, STACK_OF(X509)* cert_chain, X509_VERIFY_PARAM* verify_param, std::string& error_details); bool allow_expired_certificate_{false}; std::vector<bssl::UniquePtr<X509>> ca_certs_; std::string ca_file_name_; std::vector<SanMatcherPtr> subject_alt_name_matchers_{}; absl::flat_hash_map<std::string, X509StorePtr> trust_bundle_stores_; SslStats& stats_; TimeSource& time_source_; }; } // namespace Tls } // namespace TransportSockets } // namespace Extensions } // namespace Envoy
[ "noreply@github.com" ]
noreply@github.com
a8ca37c420c7233e43989956708760dd5380fd39
d76788d21c3eabace58350f6553522ad84094276
/RoadRacer/SplashScreen.cpp
a80d01c5efc371029cc55df6edfde60366f9bf2d
[]
no_license
Himan2104/RoadRacer
e3a66b9702d28b1e5ce1c5d5d2d74129d8ca069e
77dbaca2b2af02e5567aaac0e77b130e8da9f8e1
refs/heads/master
2023-02-24T13:43:30.791604
2021-02-01T11:18:42
2021-02-01T11:18:42
278,268,790
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
#include "pch.h" #include "SplashScreen.hpp" SplashScreen::SplashScreen() { } SplashScreen::~SplashScreen() { } void SplashScreen::initialize() { splash.setTexture(Assets::access()->getTxr("ss_main")); rect1.setSize({ 800, 100 }); rect1.setPosition(0.0f, 150.0f); rect1.setFillColor(sf::Color::Black); rect2.setSize({ 800, 100 }); rect2.setPosition(0.0f, 280.0f); rect2.setFillColor(sf::Color::Black); } void SplashScreen::update(float delTime, sf::Vector2f mpos, int& statevar) { if (rect1.getPosition().x < 1500 && rect2.getPosition().x > -9000) { rect1.move(420 * delTime, 0 * delTime); rect2.move(-420 * delTime, 0 * delTime); } else statevar = 1; } void SplashScreen::render(sf::RenderTarget& renderer) { renderer.draw(splash); renderer.draw(rect1); renderer.draw(rect2); }
[ "himan2104@gmail.com" ]
himan2104@gmail.com
ae7ef35eae43fe19957c60b2959a4fe3015d8753
0bf3a74b47e7303528039678e5b4e81c06e06de9
/LeitorLuminosidade/LeitorLuminosidade/LeitorLuminosidade.ino
63030c07644154e6706d7daf188e1ddb2bd6972b
[]
no_license
phfbertoleti/ProjetoQCON2016
7131dc11fa9d07f43890e4ba2bfade4fe8894290
67e35f38444e3bdd52f8bcd5c2dc16c20f24ab56
refs/heads/master
2021-01-10T05:35:50.260894
2016-03-31T22:22:20
2016-03-31T22:22:20
51,482,659
4
1
null
null
null
null
UTF-8
C++
false
false
10,607
ino
//Software do leitor de luminosidade (demonstração da palestra //"Embedded Systems e IoT: do bare-metal à comunicação wireless segura", //realizado no QCON 2016). //Autor: Pedro Bertoleti //Data: 02/2016 // //IMPORTANTE: este software funciona tanto com shield ZigBEE // quanto com o ZigBEE ligado diretamente a serial //---------------- // Defines gerais //---------------- #define VERSAO "V1.00" #define TAMANHO_VERSAO 5 #define TAMANHO_LUMINOSIDADE 3 #define ENDERECO_BAREMETAL 2 #define SIM 1 #define NAO 0 #define DIA "DIA" #define NOITE "NOI" //defines do protocolo #define MAX_TAM_BUFFER 20 #define STX 0x02 #define CHECKSUM_OK 1 #define FALHA_CHECKSUM 0 #define RECEPCAO_OK 1 #define SEM_RECEPCAO 0 //defines dos estados #define ESTADO_STX 1 #define ESTADO_ENDERECO 2 #define ESTADO_OPCODE 3 #define ESTADO_TAMANHO 4 #define ESTADO_CHECKSUM 5 #define ESTADO_BUFFER 6 //defines dos opcodes do protocolo (para sensor de luminosidade) #define OPCODE_LEITURA_LUMINOSIDADE 'L' #define OPCODE_VERSAO 'V' //define - tamanho da mensagem de resposta #define TAMANHO_MAX_MSG_RESPOSTA 10 //8 bytes = STX (1 byte) + Endereço (1 byte) + Opcode (1 byte) + tamanho (1 byte) + checksum (1 byte) + Buffer (5 bytes) //define - pino de leitura analógica #define PINO_SENSOR_LUMINOSIDADE 0 //usa analog pin 0 //define - valor máximo que o ADC retorna na leitura #define VALOR_MAX_ADC 1023 //---------------- // Estruturas / // typedefs //---------------- typedef struct { char Endereco; char Opcode; char TamanhoMensagem; char CheckSum; char Buffer[MAX_TAM_BUFFER]; } TDadosProtocoloLeitorLuminosidade; //---------------- // variáveis globais //---------------- TDadosProtocoloLeitorLuminosidade DadosProtocoloLeitorLuminosidade; volatile char EstadoSerial; char RecebeuBufferCompleto; char DeveEnviarLuminosidade; char DeveEnviarVersao; char IndiceBuffer; //---------------- // Prototypes //---------------- void TrataMensagem(void); void MontaEEnviaMensagem(char Opcode, char Tamanho, char * Dado); void AguardaSTX(); void AguardaEndereco(char ByteRecebido); void AguardaOpcode(char ByteRecebido); void AguardaTamanho(char ByteRecebido); void AguardaCheckSum(char ByteRecebido); void AguardaBuffer(char ByteRecebido); char CalculaCheckSum(void); void MaquinaEstadoSerial(char ByteRecebido); void EnviaLuminosidade(int LeituraADC); void EnviaVersao(void); //---------------- // Implementação / // funções //---------------- //Aguarda STX - função da máquina de estados da comunicação serial //parametros: byte recebido //saida: nenhum void AguardaSTX(char ByteRecebido) { if (ByteRecebido == STX) { memset(&DadosProtocoloLeitorLuminosidade, 0, sizeof(TDadosProtocoloLeitorLuminosidade)); //limpa dados do protocolo EstadoSerial = ESTADO_ENDERECO; } else EstadoSerial = ESTADO_STX; } //Aguarda endereço do destinatário da mensagem - função da máquina de estados da comunicação serial //parametros: byte recebido //saida: nenhum void AguardaEndereco(char ByteRecebido) { DadosProtocoloLeitorLuminosidade.Endereco = ByteRecebido; if (DadosProtocoloLeitorLuminosidade.Endereco == ENDERECO_BAREMETAL) EstadoSerial = ESTADO_OPCODE; else EstadoSerial = ESTADO_STX; } //Aguarda Opcode da mensagem - função da máquina de estados da comunicação serial //parametros: byte recebido //saida: nenhum void AguardaOpcode(char ByteRecebido) { DadosProtocoloLeitorLuminosidade.Opcode = ByteRecebido; EstadoSerial = ESTADO_TAMANHO; } //Aguarda tamanho da mensagem - função da máquina de estados da comunicação serial //parametros: byte recebido //saida: nenhum void AguardaTamanho(char ByteRecebido) { if (ByteRecebido > MAX_TAM_BUFFER) EstadoSerial = ESTADO_STX; //tamanho recebido é inválido (maior que o máximo permitido). A máquina de estados é resetada. else { DadosProtocoloLeitorLuminosidade.TamanhoMensagem = ByteRecebido; EstadoSerial = ESTADO_CHECKSUM; } } //Aguarda checksum da mensagem - função da máquina de estados da comunicação serial //parametros: byte recebido //saida: nenhum void AguardaCheckSum(char ByteRecebido) { DadosProtocoloLeitorLuminosidade.CheckSum = ByteRecebido; if(DadosProtocoloLeitorLuminosidade.TamanhoMensagem > 0) { IndiceBuffer = 0; EstadoSerial = ESTADO_BUFFER; } else { RecebeuBufferCompleto = RECEPCAO_OK; EstadoSerial = ESTADO_STX; } } //Aguarda buffer da mensagem - função da máquina de estados da comunicação serial //parametros: byte recebido //saida: nenhum void AguardaBuffer(char ByteRecebido) { if(IndiceBuffer < DadosProtocoloLeitorLuminosidade.TamanhoMensagem) { DadosProtocoloLeitorLuminosidade.Buffer[IndiceBuffer] = ByteRecebido; IndiceBuffer++; } else { //buffer completo. Faz o tratamento da mensagem e reinicia máquina de estados if (CalculaCheckSum() == CHECKSUM_OK) RecebeuBufferCompleto = RECEPCAO_OK; else RecebeuBufferCompleto = SEM_RECEPCAO; EstadoSerial = ESTADO_STX; } } //Função: checa o checksum da mensagem recebida pela UART //parametros: nenhum //saida: nenhum char CalculaCheckSum(void) { char CheckSumCalculado; char i; CheckSumCalculado = 0; for(i=0; i<DadosProtocoloLeitorLuminosidade.TamanhoMensagem; i++) CheckSumCalculado = CheckSumCalculado + DadosProtocoloLeitorLuminosidade.Buffer[i]; CheckSumCalculado = (~CheckSumCalculado) +1; if (CheckSumCalculado == DadosProtocoloLeitorLuminosidade.CheckSum) return CHECKSUM_OK; else return FALHA_CHECKSUM; } //Função que faz o gerenciamento dos estados da máquina de estado. É chamada sempre que um byte chega da serial //parametros: byte recebido pela serial //saida: nenhum void MaquinaEstadoSerial(char ByteRecebido) { switch(EstadoSerial) { case ESTADO_STX: { AguardaSTX(ByteRecebido); break; } case ESTADO_ENDERECO: { AguardaEndereco(ByteRecebido); break; } case ESTADO_OPCODE: { AguardaOpcode(ByteRecebido); break; } case ESTADO_TAMANHO: { AguardaTamanho(ByteRecebido); break; } case ESTADO_CHECKSUM: { AguardaCheckSum(ByteRecebido); break; } case ESTADO_BUFFER: { AguardaBuffer(ByteRecebido); break; } default: //se o estado tiver qualquer valro diferente dos esperados, significa que algo corrompeu seu valor (invasão de memória RAM). Logo a máquina de estados é reuniciada. { EstadoSerial=ESTADO_STX; RecebeuBufferCompleto = SEM_RECEPCAO; memset(&DadosProtocoloLeitorLuminosidade, 0, sizeof(TDadosProtocoloLeitorLuminosidade)); //limpa dados do protocolo break; } } } //Função: trata mensagem recebida pela UART //parametros: nenhum //saida: nenhum void TrataMensagem(void) { switch (DadosProtocoloLeitorLuminosidade.Opcode) { case OPCODE_LEITURA_LUMINOSIDADE: { DeveEnviarLuminosidade = SIM; break; } case OPCODE_VERSAO: { DeveEnviarVersao = SIM; break; } default: { DeveEnviarLuminosidade = NAO; DeveEnviarVersao = NAO; RecebeuBufferCompleto = SEM_RECEPCAO; EstadoSerial = ESTADO_STX; //limpa dados do protocolo memset(&DadosProtocoloLeitorLuminosidade, 0, sizeof(TDadosProtocoloLeitorLuminosidade)); } } } //Função: formata e envia a mensagem (em resposta à solicitação) //parametros: opcode, tamanho, ponteiro pro dado ascii //saida: nenhum void MontaEEnviaMensagem(char Opcode, char Tamanho, char * Dado) { char BufferAscii[TAMANHO_MAX_MSG_RESPOSTA]; char CheckSumMsg; char i; CheckSumMsg = 0; //monta mensagem de resposta à solicitação de consumo memset(BufferAscii,0,TAMANHO_MAX_MSG_RESPOSTA); BufferAscii[0]=STX; BufferAscii[1]=ENDERECO_BAREMETAL; BufferAscii[2]=Opcode; BufferAscii[3]=Tamanho; if (Tamanho) { for(i=0; i<Tamanho; i++) { CheckSumMsg = CheckSumMsg + Dado[i]; BufferAscii[5+i]=Dado[i]; } } CheckSumMsg = (~CheckSumMsg) + 1; BufferAscii[4]=CheckSumMsg; //envio da mensagem for (i=0;i<sizeof(BufferAscii);i++) Serial.write(BufferAscii[i]); } //Função: envia para a serial a luminosidade //parametros: nenhum //saida: nenhum void EnviaLuminosidade(int LeituraADC) { int PorcentagemLuminosidade; char LeituraDia[]=DIA; char LeituraNoite[]=NOITE; PorcentagemLuminosidade = LeituraADC; if (PorcentagemLuminosidade < 375) MontaEEnviaMensagem(OPCODE_LEITURA_LUMINOSIDADE, TAMANHO_LUMINOSIDADE, (char *)LeituraNoite); else MontaEEnviaMensagem(OPCODE_LEITURA_LUMINOSIDADE, TAMANHO_LUMINOSIDADE, (char *)LeituraDia); } //Função: envia para a serial a versao do firmware //parametros: nenhum //saida: nenhum void EnviaVersao(void) { char VersaoFW[]=VERSAO; MontaEEnviaMensagem(OPCODE_VERSAO, TAMANHO_VERSAO, (char *)VersaoFW); } void setup() { //inicializa variáveis de controle de envio de luminosidade RecebeuBufferCompleto = SEM_RECEPCAO; DeveEnviarLuminosidade = NAO; DeveEnviarVersao = NAO; //inicia comunicação serial a 9600 bauds Serial.begin(9600); } void loop() { int LeituraADC; char ByteLido; if (Serial.available()) { ByteLido = Serial.read(); MaquinaEstadoSerial(ByteLido); } if (RecebeuBufferCompleto == RECEPCAO_OK) { TrataMensagem(); RecebeuBufferCompleto = SEM_RECEPCAO; } if (DeveEnviarLuminosidade == SIM) { LeituraADC = analogRead(PINO_SENSOR_LUMINOSIDADE); EnviaLuminosidade(LeituraADC); DeveEnviarLuminosidade = NAO; } if (DeveEnviarVersao == SIM) { EnviaVersao(); DeveEnviarVersao = NAO; } }
[ "phfbertoleti@gmail.com" ]
phfbertoleti@gmail.com
bf9c6ab4090f94f814bbb2969d1b5f8c93f23e59
ee5a0ddaacbe4c43b0119d91287277f8000818f1
/PSaposyRanas/Actores/FabricaActor.h
e7b3ab53e6270b3830d54e55436f86e34782b334
[]
no_license
PachecoCarlos/SSaposyRanas
9b28a4a144f3e6c2877813e9476d7642d1af8e38
70ada6bb67bb2ebe566c2c5a4fc086803e9edbd0
refs/heads/master
2022-12-18T22:42:38.325041
2020-09-25T07:31:47
2020-09-25T07:31:47
297,888,228
1
0
null
null
null
null
UTF-8
C++
false
false
2,490
h
#pragma once #include"Actor.h" #include"Tortuga.h" #include"Cocodrilo.h" #include"Sapo.h" #include"Auto.h" #include"Tronco.h" /*esta es la interfaz necesaria en abstract Factory ->clase padre abstracta*/ class FabricaActor { public: //constructor de la clase FabricaActor() { anchoTortuga = anchoCorrect(avatarTortuga); anchoCocodrilo = anchoCorrect(avatarCocodrilo); anchoAuto1 = anchoCorrect(avatarAuto1); anchoAuto2 = anchoCorrect(avatarAuto2); anchoTronco = anchoCorrect(avatarTronco); } //creando metodos que las fabrizas especializadas sobrecargaran obligatoriamente virtual Actor* CrearSapo(int _x, int _y, int _dx, int _dy, MapaElementosPantalla* m) = 0; virtual Actor* CrearCocodrilo(int _x, int _y, int _dx, int _dy, MapaElementosPantalla* m) = 0; virtual Actor* CrearAuto1(int _x, int _y, int _dx, int _dy, MapaElementosPantalla* m) = 0; virtual Actor* CrearAuto2(int _x, int _y, int _dx, int _dy, MapaElementosPantalla* m) = 0; virtual Actor* CrearTortuga(int _x, int _y, int _dx, int _dy, MapaElementosPantalla* m) = 0; virtual Actor* CrearTronco(int _x, int _y, int _dx, int _dy, MapaElementosPantalla* m) = 0; protected: //atributos propios de la clase protegidos int anchoTortuga; int anchoCocodrilo; int anchoAuto1; int anchoAuto2; int anchoTronco; //metodo entero constante que recive un vector de string del avatar y retorna el tamano del vector int anchoCorrect(vector<string> avatar)const { int max = 0; for (int i = 0; i < avatar.size(); i++) { if (avatar[i].size() > max) max = avatar[i].size(); } return max; }; //vector de string de avatares que lo usaran las diferentes fabricas de actores segun al nivel vector<string> avatarSapo = { {"\\o/"}, {"_O_"} }; vector<string> avatarTortuga = { {" ______ ____"}, {"/ \\ | o |"}, {"| |/___\\|"}, {"|______ / "} }; vector<string> avatarCocodrilo = { {" /^^^^\\ "}, {" /^^\\____/0 \\ "}, {"( `-------^^^^^^^"}, {" V^V^V^V^V^V^\\..................."} }; vector<string> avatarAuto1 = { {" ______ "}, {" /|_||_\\`.__ "}, {"(_ _ _ \\"}, {"=`-(_)--(_)-' "} }; vector<string> avatarAuto2 = { {" __"}, {"\\ ii | o|"}, {" |>#########"}, {"/ (_O_O_O_O_)"} }; vector<string> avatarTronco = { {" _________ __ _________"}, {"!#######///////////#\\\\"}, {"!_____________________ _"} }; };
[ "Pacheco.Carlos@usfx.bo" ]
Pacheco.Carlos@usfx.bo
053ad7fc78c0f014b746e7c8feb0fcfb1f85bc95
43b24b57aa204939fd469f06a8ceb38878371232
/ext/couchbase/operations/view_index_get_all.hxx
719941c8e13990f00de6b4577e29aecdbc94116d
[ "Apache-2.0" ]
permissive
RichardSmedley/couchbase-ruby-client
d0f2623d50432a6e832fe52c47a935aa6545006f
9e6e780f288e010942fca8660494916bc8459480
refs/heads/master
2022-11-25T14:55:18.513772
2020-08-04T14:04:56
2020-08-04T15:21:14
285,260,559
0
0
Apache-2.0
2020-08-05T10:52:00
2020-08-05T10:51:59
null
UTF-8
C++
false
false
5,277
hxx
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2020 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <tao/json.hpp> #include <operations/design_document.hxx> namespace couchbase::operations { struct view_index_get_all_response { std::string client_context_id; std::error_code ec; std::vector<design_document> design_documents{}; }; struct view_index_get_all_request { using response_type = view_index_get_all_response; using encoded_request_type = io::http_request; using encoded_response_type = io::http_response; static const inline service_type type = service_type::management; std::string client_context_id{ uuid::to_string(uuid::random()) }; std::chrono::milliseconds timeout{ timeout_defaults::management_timeout }; std::string bucket_name; design_document::name_space name_space; void encode_to(encoded_request_type& encoded) { encoded.method = "GET"; encoded.path = fmt::format("/pools/default/buckets/{}/ddocs", bucket_name); } }; view_index_get_all_response make_response(std::error_code ec, view_index_get_all_request& request, view_index_get_all_request::encoded_response_type encoded) { view_index_get_all_response response{ request.client_context_id, ec }; if (!ec) { if (encoded.status_code == 200) { auto payload = tao::json::from_string(encoded.body); auto* rows = payload.find("rows"); if (rows != nullptr && rows->is_array()) { for (const auto& entry : rows->get_array()) { const auto* dd = entry.find("doc"); if (dd == nullptr || !dd->is_object()) { continue; } const auto* meta = dd->find("meta"); if (meta == nullptr || !meta->is_object()) { continue; } design_document document{}; document.rev = meta->at("rev").get_string(); auto id = meta->at("id").get_string(); static const std::string prefix = "_design/"; if (id.find(prefix) == 0) { document.name = id.substr(prefix.size()); } else { document.name = id; // fall back, should not happen } static const std::string name_space_prefix = "dev_"; if (document.name.find(name_space_prefix) == 0) { document.name = document.name.substr(name_space_prefix.size()); document.ns = couchbase::operations::design_document::name_space::development; } else { document.ns = couchbase::operations::design_document::name_space::production; } if (document.ns != request.name_space) { continue; } const auto* json = dd->find("json"); if (json == nullptr || !json->is_object()) { continue; } const auto* views = json->find("views"); if (views != nullptr && views->is_object()) { for (const auto& view_entry : views->get_object()) { couchbase::operations::design_document::view view; view.name = view_entry.first; if (view_entry.second.is_object()) { const auto* map = view_entry.second.find("map"); if (map != nullptr && map->is_string()) { view.map = map->get_string(); } const auto* reduce = view_entry.second.find("reduce"); if (reduce != nullptr && reduce->is_string()) { view.reduce = reduce->get_string(); } } document.views[view.name] = view; } } response.design_documents.emplace_back(document); } } } else if (encoded.status_code == 404) { response.ec = std::make_error_code(error::common_errc::bucket_not_found); } else { response.ec = std::make_error_code(error::common_errc::internal_server_failure); } } return response; } } // namespace couchbase::operations
[ "sergey.avseyev@gmail.com" ]
sergey.avseyev@gmail.com
8182015b146c72c2a1299460b00c36a93075848e
9aa4e6904de3030dbf4498666edf7ca124e72d83
/springer_verglar problems/baisc/main.cpp
11cb7711d60a868567e505ecbfeb83c78437123d
[]
no_license
sudeepdino008/algorithmic-programs
3703bf8dd72f4643c93fe4d32c18da060c6b8030
d8d9ce6f0974f50f46fb74195c1fbd37c8335a83
refs/heads/master
2021-01-01T19:55:06.622614
2013-07-28T13:29:07
2013-07-28T13:29:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
453
cpp
#include <iostream> #include<cstdlib> #include<cmath> using namespace std; int main() { int v; // 32-bit integer to find the log base 2 of int r; // result of log_2(v) goes here union { unsigned int u[2]; double d; } t; // temp cin>>v; t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] = 0x43300000; t.u[__FLOAT_WORD_ORDER!=LITTLE_ENDIAN] = v; t.d -= 4503599627370496.0; r = (t.u[__FLOAT_WORD_ORDER==LITTLE_ENDIAN] >> 20) - 0x3FF; cout<<r; }
[ "sudeepdino008@gmail.com" ]
sudeepdino008@gmail.com
32c3fb72a7b18f94be7c0f9f5c588c1703aec9de
fc5e57e70f4851372bf60c919a55608358615851
/components/esp32_ble_controller/ble_switch_handler.cpp
49d6257a1539f9a0cdb47ca8427a524c2715f101
[ "MIT" ]
permissive
manju-rn/esphome-ble-controller
d3f853ecb93999284ab5488f3ea341228fc5d361
eb411eb9abcb71402abd8d39c39fccdcd3a1e50f
refs/heads/master
2023-05-28T19:51:43.444566
2021-06-10T18:26:33
2021-06-10T18:28:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
780
cpp
#include "ble_switch_handler.h" #ifdef USE_SWITCH namespace esphome { namespace esp32_ble_controller { static const char *TAG = "ble_switch_handler"; // BLESwitchHandler::BLESwitchHandler(Switch* component, const BLECharacteristicInfoForHandler& characteristic_info) : BLEComponentHandler(component, characteristic_info) // { // set_value(component->state); // do not send yet! // } void BLESwitchHandler::on_characteristic_written() { std::string value = get_characteristic()->getValue(); if (value.length() == 1) { uint8_t on = value[0]; ESP_LOGD(TAG, "Switch chracteristic written: %d", on); if (on) get_component()->turn_on(); else get_component()->turn_off(); } } } // namespace esp32_ble_controller } // namespace esphome #endif
[ "sv.thiel@web.de" ]
sv.thiel@web.de
0528df863da8471380179d5a67cb95629fc3dbd8
32bcbaebc379b3ef3f599d1334269206f7fb6c12
/src/Basis/Basis.hpp
b05cc3edf8801fe494fdcf991e394509a4253ccb
[]
no_license
chengyanlai/ExactDiagonalization
cad10eb52c3003534d26cfcee3d070d54f592c00
f5e4e697597598d7c92e5a5dc0deab5323ac563e
refs/heads/master
2020-04-06T06:07:08.929463
2018-09-29T04:38:37
2018-09-29T04:38:37
44,208,355
0
0
null
null
null
null
UTF-8
C++
false
false
4,308
hpp
#ifndef __BASIS_HPP__ #define __BASIS_HPP__ #include <iostream> #include <vector> #include <cassert> #include <algorithm>//* sort, distance #include "src/EDType.hpp" #include "src/bitwise.h" template<class RandomIt, class T> inline RandomIt binary_locate(RandomIt first, RandomIt last, const T& val) { if(val == *first) return first; auto d = std::distance(first, last); if(d==1) return first; auto center = (first + (d/2)); if(val < *center) return binary_locate(first, center, val); return binary_locate(center, last, val); } class Basis { template<typename Tnum> friend class Hamiltonian; template<typename Tnum> friend class FHM; template<typename Tnum> friend class BHM; template<typename Tnum> friend class Holstein; public: Basis(const bool _isFermion = false); Basis(const size_t _L, const size_t _N, const bool _isFermion = false); virtual ~Basis(); void Save( const std::string filename, const std::string gname ); void Load( const std::string filename, const std::string gname ); inline bool GetType()const{ return isFermion; }; inline size_t GetL()const{ return L; }; inline size_t GetN()const{ return N; }; inline size_t GetHilbertSpace()const{ if (isFermion) { return FStates.size(); } else { return BStates.size(); } }; inline size_t size()const{ return GetHilbertSpace(); }; //* Fermion functions */ void Fermion(); void Fermion( const int IncludeAllU1 );// This has no U(1) symmetry. //* Spin - 1/2, share the Fermion functions */ void SpinOneHalf(); void TIsing(); inline std::vector<int> GetFStates()const{ return FStates; };//* for Fermion and SpinOneHalf inline std::vector<size_t> GetFTags()const{ return FTags; };//* for Fermion and SpinOneHalf inline int GetNfTotal(const size_t idx)const{ return NTotal.at(idx); };//* for fermion without U(1) inline int GetSzTotal(const size_t idx)const{ return NTotal.at(idx); };//* for Transverse Ising spin //* Boson functions */ void Boson(); void PhononLFS(); void PhononR(); void PhononK(const std::vector<int> Kn, const int TargetK, const int WithoutK0Phonon = 1 );//! First element indicates the electron momentum inline std::vector< std::vector<int> > GetBStates()const{ return BStates; }; inline std::vector<RealType> GetBTags()const{ return BTags; }; inline size_t GetIndexFromTag( const RealType tg )const{ assert( !(isFermion) ); auto it = binary_locate(BTags.begin(), BTags.end(), tg); size_t idx = std::distance(BTags.begin(), it); return idx; }; //* Phonon functions */ RealType CreatePhonon( std::vector<int>& state, const int site=0 )const; RealType DestroyPhonon( std::vector<int>& state, const int site=0 )const; //* Holstein Phonon - Limited functional space */ RealType FermionJumpRight( std::vector<int>& state, const int NumJumps = 1 )const; RealType FermionJumpLeft( std::vector<int>& state, const int NumJumps = 1 )const; friend std::ostream& operator<<(std::ostream& os, const Basis& st); private: size_t L; size_t N; bool isFermion; bool HaveU1; std::vector< std::vector<int> > BStates;//for Boson std::vector<RealType> BTags;//for Boson std::vector<int> FStates;//for Fermion, and SpinOneHalf. std::vector<size_t> FTags;//for Fermion, and SpinOneHalf. std::vector<int> NTotal;//for Fermion without U(1). /* Holstein Phonon */ std::vector<std::vector<int> > ApplyOffdiagonal( const std::vector<std::vector<int> >& InputStates ); void DummyCheckState(); }; RealType BosonBasisTag( const std::vector<int> vec ); template<typename T> std::vector<std::vector<int> > SortBTags( const std::vector<std::vector<int> >& st, std::vector<T> &v ); //* Used by PhononK inline int DeltaKIndex( int& DeltaK, const std::vector<int>& KPoints ){ if ( std::abs(DeltaK) == 2 * KPoints.at(KPoints.size()-1) ) DeltaK = 0; while ( DeltaK > KPoints.at(KPoints.size()-1) ) DeltaK -= 2*KPoints.at(KPoints.size()-1); while ( std::abs(DeltaK) >= KPoints.at(KPoints.size()-1) && DeltaK < 0 ) DeltaK += 2*KPoints.at(KPoints.size()-1); size_t index = std::distance(KPoints.begin(), std::find(KPoints.begin(), KPoints.end(), DeltaK)); // assert( index >= 0 ); return index; }; #endif//__BASIS_HPP__
[ "chengyanlai@gmail.com" ]
chengyanlai@gmail.com
702fb956c122f14a9ba282688ba71472a1654afd
956e9c2785db1aaa1f56ef3a0e6b84aff44a51f1
/odyssey-r155188-1.23/BAL/Fonts/WebCore/Embedded/BCSimpleFontDataEmbedded.cpp
dfa5e7878527225b9fac40c0ff5876a814ae9c58
[]
no_license
kas1e/Odyssey
d452826d2648280390e4d6ff1c8df5c228d095ad
947cc7a10be2599d3ed3145ab2af4a445df6d462
refs/heads/master
2023-02-23T15:21:53.806910
2022-06-26T13:47:07
2022-06-26T13:47:07
243,821,888
10
9
null
2023-02-07T20:04:56
2020-02-28T17:48:33
C++
UTF-8
C++
false
false
3,415
cpp
/* * Copyright (C) 2008 Pleyo. 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. Neither the name of Pleyo 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 PLEYO AND ITS CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL PLEYO OR ITS CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "Logging.h" #include "SimpleFontData.h" #include "BALBase.h" #include "FloatRect.h" #include "Font.h" #include "FontCache.h" #include "FontDescription.h" #include "GlyphBuffer.h" #include "NotImplemented.h" #include <unicode/uchar.h> #include <unicode/unorm.h> #include <wtf/MathExtras.h> #include "fonts/pixelfont.h" namespace WebCore { void SimpleFontData::platformInit() { PixelFontType *pixelFont = m_platformData.m_pixelFont; m_ascent = pixelFont->height + 5; //must be 5 else text is misplaced m_descent = 2; m_lineSpacing = pixelFont->height; m_xHeight = pixelFont->height; m_spaceWidth = pixelFont->width; m_lineGap = 4; } void SimpleFontData::platformDestroy() { notImplemented(); } void SimpleFontData::platformCharWidthInit() { m_avgCharWidth = 0.f; m_maxCharWidth = 0.f; initCharWidths(); } SimpleFontData* SimpleFontData::smallCapsFontData(const FontDescription& fontDescription) const { if (!m_smallCapsFontData) { FontDescription desc = FontDescription(fontDescription); desc.setSpecifiedSize(0.70f*fontDescription.computedSize()); const FontPlatformData* pdata = new FontPlatformData(desc, desc.family().family()); m_smallCapsFontData = new SimpleFontData(*pdata); } return m_smallCapsFontData; } bool SimpleFontData::containsCharacters(const UChar* characters, int length) const { notImplemented(); return false; } void SimpleFontData::determinePitch() { m_treatAsFixedPitch = m_platformData.isFixedPitch(); } void SimpleFontData::setFont(BalFont* cr) const { ASSERT(cr); m_platformData.setFont(cr); } FloatRect SimpleFontData::platformBoundsForGlyph(Glyph) const { notImplemented(); return FloatRect(); } float SimpleFontData::platformWidthForGlyph(Glyph glyph) const { return m_spaceWidth; } }
[ "amiga1200@amiga.com" ]
amiga1200@amiga.com
c30f83052dd14b6f8f3605b5df783a48281bedb7
145cb471268ba9127783e27282263844f1055bb1
/Demo/UIFrame/UIFrame.cpp
60c2c8c4af332086de13ee420e8c91d6dad2a7c7
[ "MIT", "BSD-2-Clause" ]
permissive
Runcy/duilib-Ex-Debug
7eac094fe8427995f671b875ca4b669cbd121646
d5c6d7065d54b9a75880ac5fc46551d4ab21cc34
refs/heads/master
2020-12-03T08:15:37.289387
2014-11-10T15:35:42
2014-11-10T15:35:42
null
0
0
null
null
null
null
GB18030
C++
false
false
4,229
cpp
#include "stdafx.h" #include "UIFrame.h" CDYFrameWnd::~CDYFrameWnd() { if (m_paddLocalFont) { delete m_paddLocalFont; } } void CDYFrameWnd::InitWindow() { CButtonUI* pbtn=static_cast<CButtonUI*>(FindControl(_T("ui_btn_maked"))); if (pbtn) { pbtn->OnNotify+=MakeDelegate(this,&CDYFrameWnd::OnMsgBtnClick,DUI_MSGTYPE_CLICK);//处理指定的notify类型 pbtn->OnEvent+= MakeDelegate(this,&CDYFrameWnd::OnMsgBtnMouseEnter,UIEVENT_MOUSEENTER); pbtn->OnEvent+= MakeDelegate(this,&CDYFrameWnd::OnMsgBtnMouseLeave,UIEVENT_MOUSELEAVE);//处理指定的事件 pbtn->OnNotify+=MakeDelegate(this,&CDYFrameWnd::btnOnNotify);//处理所有的notify } CMediaPlayerUI* pMediaUI = dynamic_cast<CMediaPlayerUI*>(FindControl(_T("MediaplayerActiveX"))); if (pMediaUI) { pMediaUI->Play(CPaintManagerUI::GetInstancePath( ) + _T("\\UIFrameSkin\\test.mp4")); } nsldValue_=10; } LRESULT CDYFrameWnd::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam, bool& bHandled) { switch (uMsg) { case WM_TOUCH: MessageBoxA(GetHWND(),"get wm_touch message",NULL,MB_OK); break; default: break; } // __super::MessageHandler(uMsg,wParam,lParam,bHandled); return FALSE; } class WindowCallback:public IDialogBuilderCallback { virtual CControlUI* CreateControl(LPCTSTR pstrClass) { if (_tcsicmp(pstrClass, _T("Window2")) == 0) { CDialogBuilder builderManualOpera; CControlUI* ptemp = builderManualOpera.Create(_T("Window2.xml"),NULL,NULL,NULL,NULL); return ptemp; } return NULL; }; }; CControlUI* CDYFrameWnd::CreateControl(LPCTSTR pstrClass) { if (_tcsicmp(pstrClass, _T("Window1")) == 0) { WindowCallback bk; CDialogBuilder builderManualOpera; // 传入GetPaintManager(),Window窗口受Window1的size影响 //CControlUI* pUIManualOpera_ = builderManualOpera.Create(_T("Window1.xml"), NULL, &bk, GetPaintManager(), NULL); CControlUI* pUIManualOpera_ = builderManualOpera.Create(_T("Window1.xml"), NULL, &bk, NULL, NULL); return pUIManualOpera_; } if (_tcsicmp(pstrClass, _T("Window2")) == 0) { CDialogBuilder builderManualOpera; CControlUI* ptemp = builderManualOpera.Create(_T("Window2.xml")); return ptemp; } return NULL; } void CDYFrameWnd::Notify(TNotifyUI& msg) { char szInfo[128]; if (msg.sType == DUI_MSGTYPE_COLORCHANGED) { CColorPaletteUI* p = (CColorPaletteUI*)msg.pSender; DWORD color = p->GetSelectColor(); //DWORD color = msg.wparam; sprintf(szInfo, "ARGB=(%d,%d,%d,%d)", 0xFF & color >> 24, 0xFF & color >> 16, 0xFF & color >> 8, 0xFF & color); MessageBoxA(GetHWND(), szInfo,"颜色", MB_OK); //p->SetSelectColor(0x00f000f0); } else if (msg.sType==DUI_MSGTYPE_SELECTCHANGED) { if (msg.pSender->GetName()==_T("ut_opt_tab1")) { CTabLayoutUI* pTab = dynamic_cast<CTabLayoutUI*>(FindControl(_T("ui_tablayer_operaswitch"))); if (pTab) { pTab->SelectItem(0); } } else if (msg.pSender->GetName( ) == _T("ut_opt_tab2")) { CTabLayoutUI* pTab = dynamic_cast<CTabLayoutUI*>(FindControl(_T("ui_tablayer_operaswitch"))); if (pTab) { pTab->SelectItem(1); } } } else if (msg.sType==DUI_MSGTYPE_WINDOWINIT) { } __super::Notify(msg); } bool CDYFrameWnd::OnMsgBtnClick( TNotifyUI* pTNotifyUI ) { MessageBox(m_hWnd,_T("绑定的按钮点击消息 OK!"),_T("消息路由"),MB_OK); return true; } bool CDYFrameWnd::OnMsgBtnMouseEnter( TEventUI* pTEventUI ) { pTEventUI->pSender->SetText(_T("鼠标进来了")); pTEventUI->pSender->SetUserData(_T("鼠标进来了")); return true; } bool CDYFrameWnd::OnMsgBtnMouseLeave( TEventUI* pTEventUI ) { pTEventUI->pSender->SetText(_T("鼠标跑路了")); pTEventUI->pSender->SetUserData(_T("鼠标跑路了")); CSliderUI* psld=dynamic_cast<CSliderUI*>(FindControl(_T("ui_sld_test"))); if (psld) { nsldValue_+=10; psld->SetValue(nsldValue_); psld->SetText(_T("dddddddd")); } return true; } bool CDYFrameWnd::btnOnNotify(void* pNotify) { TNotifyUI* pMsg=static_cast<TNotifyUI*>(pNotify); DUITRACE(_T("all notify ")); return true; }
[ "x356982611@gmail.com" ]
x356982611@gmail.com
186504019963cab3666e4d5b3a1249264682cb54
100204a0b444696dbb54a4a11d3ae4ed304f600e
/ZeroPoint4/Core/zpFlag.h
65a2792d142a8ad8c46372fc9b05dfb2be7c6283
[]
no_license
zero0/zp4
5f353ab76185fbd1b705dd66e96d44434f464402
bf0db133bc3794ae91cee8d9d09f74ad164f6d24
refs/heads/master
2021-01-23T04:49:31.749785
2017-01-30T05:20:40
2017-01-30T05:20:40
80,395,863
0
0
null
null
null
null
UTF-8
C++
false
false
1,769
h
#pragma once #ifndef ZP_FLAG_H #define ZP_FLAG_H template<typename F> class zpFlag { public: zpFlag() : m_flag( 0 ) {} zpFlag( F flag ) : m_flag( flag ) {} zpFlag( const zpFlag& flag ) : m_flag( flag.m_flag ) {} zpFlag( zpFlag&& flag ) : m_flag( flag.m_flag ) {} ~zpFlag() {} operator F() const { return m_flag; } void operator=( const zpFlag& flag ) { m_flag = flag; } void operator=( zpFlag&& flag ) { m_flag = flag; } void mark( zp_uint index ) { markAll( (F)( 1 << index ) ); } void markAll( F mask ) { or( mask ); } void unmark( zp_uint index ) { unmarkAll( (F)( 1 << index ) ); } void unmarkAll( F mask ) { and( ~mask ); } void setMarked( zp_uint index, zp_bool marked ) { marked ? mark( index ) : unmark( index ); } zp_bool toggle( zp_uint index ) { xor( (F)( 1 << index ) ); return isMarked( index ); } zp_bool isMarked( zp_uint index ) const { return isAllMarked( (F)( 1 << index ) ); } zp_bool isAnyMarked( F mask ) const { return ( m_flag & mask ) != 0; } zp_bool isAllMarked( F mask ) const { return ( m_flag & mask ) == mask; } zp_bool isZero() const { return m_flag == (F)0; }; void clear() { m_flag = 0; } void set( F flag ) { m_flag = flag; } void and( F flag ) { m_flag &= flag; } void or( F flag ) { m_flag |= flag; } void xor( F flag ) { m_flag ^= flag; } zp_bool operator==( const zpFlag& flag ) const { return m_flag == flag.m_flag; } zp_bool operator!=( const zpFlag& flag ) const { return m_flag != flag.m_flag; } private: F m_flag; }; typedef zpFlag<zp_byte> zpFlag8; typedef zpFlag<zp_ushort> zpFlag16; typedef zpFlag<zp_uint> zpFlag32; typedef zpFlag<zp_ulong> zpFlag64; #endif
[ "phosgene84@gmail.com" ]
phosgene84@gmail.com