blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
e8f76d668a2306d2bc7555ea52d436fe25efc59c
6cc9349598ba3d55800638fb45f9720b20c33277
/view/resources/srcFont/font_data.cpp
13b979728b540e200606335c3a3334e6534520b1
[]
no_license
d-shulgin/GameCreator
0447f480c52647209703c83a0022132c62d0a3b2
5f64dd67790df4b3c36db49e3f9b70f1e3eb9dc7
refs/heads/master
2023-05-07T17:43:14.119359
2021-04-28T12:46:02
2021-04-28T12:46:02
362,068,456
0
0
null
null
null
null
UTF-8
C++
false
false
2,130
cpp
#include "font_data.h" FontData::FontData() : XMLObject() , _modify( false ) , _leading( 0.0f ) , _ascent ( 0.0f ) , _descent( 0.0f ) { bind_fields(); } void FontData::Load( QDomElement& object ) // | { clear(); XMLObject::Load( object ); return; } /// @section: namae... ///////////////////////// | const QString& FontData::name() const // | { return( _name ); } void FontData::setName( const QString& name ) // | { _modify = _modify || (name != this -> name()); _name = name; return; } /// @section: texture size ///////////////////////////////////////////// | const FontTextureSize& FontData::texture_size() const // | { return( _texture_size ); } void FontData::setTexture_size( const FontTextureSize& texture_size ) // | { _modify = _modify || (texture_size != this -> texture_size()); _texture_size = texture_size; return; } /// @section: leading... ///////// | float FontData::leading() const // | { return( _leading ); } /// @section: ascent ///////////// | float FontData::ascent() const // | { return( _ascent ); } /// @section: descent //////////// | float FontData::descent() const // | { return( _descent ); } /// @section: symbols ///////////////////////////////////////////// | void FontData::clear() // | { _symbols.reset(); return; } const CharData* FontData::symbol( size_t index ) const // | { if( index < symbols().count() ) { const XMLObject* object = cref_symbols().itemAt( index ); if( 0 != object && object -> xml_class_name().split(".", QString::SkipEmptyParts).contains(CharData::class_name()) ) return( static_cast<const CharData*>(object) ); } return( 0 ); } const CharData* FontData::getSymbol( const QString& code ) const // | { for( size_t i = 0; i < symbols().count(); ++i ) { const CharData* o_symbol = symbol(i); if( 0 != o_symbol && o_symbol -> code() == code ) return( o_symbol ); } return( 0 ); } FontData::~FontData() { }
[ "d-shulgin@inbox.ru" ]
d-shulgin@inbox.ru
283c7968774c2234a5e915009aa6bf4f40dbfdfb
617a5ffac5b85901596ab9991c293d214caa818f
/mutating_algoritms/remove_if.cpp
1bbb3cff1d29b026a2dff3d548fd6856a8f3a8db
[]
no_license
ZARAG-YAN/STL_Algorithms
b72620b7dc991008501ef5ea233f3e5dbb48f91f
03b5816f49784acc05c0b049d0ef00128133f0ef
refs/heads/master
2020-05-03T16:55:59.823275
2019-04-02T06:29:38
2019-04-02T06:29:38
178,734,758
0
0
null
null
null
null
UTF-8
C++
false
false
964
cpp
#include <iostream> #include <vector> #include <algorithm> class obj { public: int operator()() { static int i = 0; return ++i; } }; class obj1 { public: bool operator()(int& a) { return a % 2 == 0; } }; int main() { std::vector<int> vec1 = {4,9,7,25,4,12,4,4,9,8,16}; std::vector<int> vec2(10); std::cout << "\nvec1 "; for(auto i: vec1) { std::cout << i <<" "; } std::remove(vec1.begin() , vec1.end(), 4); std::generate(vec2.begin(), vec2.end(), obj()); std::cout <<"\nvec2 "; for(auto i: vec2) { std::cout << i <<" "; } std::remove_if(vec2.begin(), vec2.end(), obj1()); std::cout << "\nremove vec1 "; for(auto i: vec1) { std::cout << i <<" "; } std::cout <<"\nremove_if vec2 "; for(auto i: vec2) { std::cout << i <<" "; } std::cout << std::endl; return 0; }
[ "zara030396@gmail.com" ]
zara030396@gmail.com
51fecc096908d7352b83a8f6fe4391b5ec70acaa
70ad3badf3fa6e2edf1889d8640f25a7ec0d9db1
/ros_catkin_ws/devel_isolated/geometry_msgs/include/geometry_msgs/PoseArray.h
fbbfca26b762a31f64341557567a5719ee21d730
[]
no_license
MathieuHwei/OldGaitMaven
758a937dfda2cf4f1aee266dbbf682ef34989199
873f7d9089c5d1c0772bd3447e2b0a31dac68b70
refs/heads/main
2023-06-17T18:40:06.230823
2021-07-19T23:08:20
2021-07-19T23:08:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,085
h
// Generated by gencpp from file geometry_msgs/PoseArray.msg // DO NOT EDIT! #ifndef GEOMETRY_MSGS_MESSAGE_POSEARRAY_H #define GEOMETRY_MSGS_MESSAGE_POSEARRAY_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> #include <std_msgs/Header.h> #include <geometry_msgs/Pose.h> namespace geometry_msgs { template <class ContainerAllocator> struct PoseArray_ { typedef PoseArray_<ContainerAllocator> Type; PoseArray_() : header() , poses() { } PoseArray_(const ContainerAllocator& _alloc) : header(_alloc) , poses(_alloc) { (void)_alloc; } typedef ::std_msgs::Header_<ContainerAllocator> _header_type; _header_type header; typedef std::vector< ::geometry_msgs::Pose_<ContainerAllocator> , typename ContainerAllocator::template rebind< ::geometry_msgs::Pose_<ContainerAllocator> >::other > _poses_type; _poses_type poses; typedef boost::shared_ptr< ::geometry_msgs::PoseArray_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::geometry_msgs::PoseArray_<ContainerAllocator> const> ConstPtr; }; // struct PoseArray_ typedef ::geometry_msgs::PoseArray_<std::allocator<void> > PoseArray; typedef boost::shared_ptr< ::geometry_msgs::PoseArray > PoseArrayPtr; typedef boost::shared_ptr< ::geometry_msgs::PoseArray const> PoseArrayConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::geometry_msgs::PoseArray_<ContainerAllocator> & v) { ros::message_operations::Printer< ::geometry_msgs::PoseArray_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace geometry_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': True} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/home/pi/ros_catkin_ws/src/common_msgs/geometry_msgs/msg']} // !!!!!!!!!!! ['__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< ::geometry_msgs::PoseArray_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::geometry_msgs::PoseArray_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::geometry_msgs::PoseArray_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::geometry_msgs::PoseArray_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::geometry_msgs::PoseArray_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::geometry_msgs::PoseArray_<ContainerAllocator> const> : TrueType { }; template<class ContainerAllocator> struct MD5Sum< ::geometry_msgs::PoseArray_<ContainerAllocator> > { static const char* value() { return "916c28c5764443f268b296bb671b9d97"; } static const char* value(const ::geometry_msgs::PoseArray_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0x916c28c5764443f2ULL; static const uint64_t static_value2 = 0x68b296bb671b9d97ULL; }; template<class ContainerAllocator> struct DataType< ::geometry_msgs::PoseArray_<ContainerAllocator> > { static const char* value() { return "geometry_msgs/PoseArray"; } static const char* value(const ::geometry_msgs::PoseArray_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::geometry_msgs::PoseArray_<ContainerAllocator> > { static const char* value() { return "# An array of poses with a header for global reference.\n\ \n\ Header header\n\ \n\ Pose[] poses\n\ \n\ ================================================================================\n\ MSG: std_msgs/Header\n\ # Standard metadata for higher-level stamped data types.\n\ # This is generally used to communicate timestamped data \n\ # in a particular coordinate frame.\n\ # \n\ # sequence ID: consecutively increasing ID \n\ uint32 seq\n\ #Two-integer timestamp that is expressed as:\n\ # * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\ # * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\ # time-handling sugar is provided by the client library\n\ time stamp\n\ #Frame this data is associated with\n\ # 0: no frame\n\ # 1: global frame\n\ string frame_id\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Pose\n\ # A representation of pose in free space, composed of position and orientation. \n\ Point position\n\ Quaternion orientation\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Point\n\ # This contains the position of a point in free space\n\ float64 x\n\ float64 y\n\ float64 z\n\ \n\ ================================================================================\n\ MSG: geometry_msgs/Quaternion\n\ # This represents an orientation in free space in quaternion form.\n\ \n\ float64 x\n\ float64 y\n\ float64 z\n\ float64 w\n\ "; } static const char* value(const ::geometry_msgs::PoseArray_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::geometry_msgs::PoseArray_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.header); stream.next(m.poses); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct PoseArray_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::geometry_msgs::PoseArray_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::geometry_msgs::PoseArray_<ContainerAllocator>& v) { s << indent << "header: "; s << std::endl; Printer< ::std_msgs::Header_<ContainerAllocator> >::stream(s, indent + " ", v.header); s << indent << "poses[]" << std::endl; for (size_t i = 0; i < v.poses.size(); ++i) { s << indent << " poses[" << i << "]: "; s << std::endl; s << indent; Printer< ::geometry_msgs::Pose_<ContainerAllocator> >::stream(s, indent + " ", v.poses[i]); } } }; } // namespace message_operations } // namespace ros #endif // GEOMETRY_MSGS_MESSAGE_POSEARRAY_H
[ "giahuy050201@gmail.com" ]
giahuy050201@gmail.com
73e450d2834bed65e79c6fccdfdac6cdb6c499ef
7b88f02d8824db9da785d3dad6e31a0f123e02bc
/9.12/Point.cpp
f10f41f93c6c08334c7e9aa4e954dce599199fe1
[]
no_license
guoyuting666/Guo_Yuting
4e2811f1565b7f0f5669b5531ea2b6d51daf8802
dcd89e64afc42c81d81f5a4b97c4e32770ab20e0
refs/heads/master
2020-04-28T03:18:29.055277
2019-06-02T03:16:20
2019-06-02T03:16:20
174,931,711
0
0
null
null
null
null
UTF-8
C++
false
false
376
cpp
#include "Point.h" Point::Point( double xCoord, double yCoord ) { setX( xCoord ); setY( yCoord ); } void Point::setX( double xCoord ) { x = ( xCoord >= 0.0 && xCoord <= 20.0 ) ? xCoord : 0.0; } void Point::setY( double yCoord ) { y = ( yCoord >= 0.0 && yCoord <= 20.0 ) ? yCoord : 0.0; } double Point::getX() { return x; } double Point::getY() { return y; }
[ "769140403@qq.com" ]
769140403@qq.com
8b62362db91b2585096292c5edfb4d0c0da89679
1993fb5e886b31e7f61aaabcaa554e635bb9ef4d
/Beginer/1959_regular_simple_polygon.cpp
53ad9ae39b6ce08d3cf818d65897b7fc2fac6d03
[]
no_license
wiragotama/URI
10dc17235c4dfa17784360f65fed6443d952e39b
ec30420523d71df4b0727baeebc8219ff98e834a
refs/heads/master
2022-02-28T05:36:22.010048
2022-02-07T07:18:37
2022-02-07T07:18:37
52,661,092
0
1
null
null
null
null
UTF-8
C++
false
false
157
cpp
#include <iostream> #include <cstdio> using namespace std; int main() { long long int a, b; scanf("%lld %lld",&a, &b); printf("%lld\n",a*b); return 0; }
[ "wiragotama@gmail.com" ]
wiragotama@gmail.com
bc31c2f5b67ae56ab9db26679d4bacd453ba791f
7ccca20f25ac240b1e30260211f676101bd2a231
/Model/Board.h
afc28179ea4e35c76488f15ea65a644bf2c5104a
[ "MIT" ]
permissive
mr-seifi/Tic-Tac-Toe
58dbd5632a2d3cb236df3c9de8caa4ea90d9533f
4bd00632cc302eec22d3bb57037bfcea4c9db96a
refs/heads/main
2023-08-07T14:28:51.915695
2021-09-30T17:17:18
2021-09-30T17:17:18
392,335,235
1
0
null
null
null
null
UTF-8
C++
false
false
675
h
#ifndef TIC_TAC_TOE_BOARD_H #define TIC_TAC_TOE_BOARD_H #include <iostream> #include <vector> class Board { friend std::ostream &operator<<(std::ostream&, const Board&); // Overload << operator to show board in output stream public: Board(); // Board constructor void turn(unsigned int, char); // turn method has 2 arguments, one for position point and another for player notation std::string toString() const; // convert board to string std::string toOutput() const; // convert board to show that in output stream bool isFill(unsigned int) const; // return is map fill or not private: std::vector<char> board; }; #endif //TIC_TAC_TOE_BOARD_H
[ "aminseiifi@gmail.com" ]
aminseiifi@gmail.com
e30488f683f2b831dcfbb2b4bff538abf385b13a
2f9182f3aa89334f95d7bffcd57ac971cacc8298
/source/solution_zoo/xstream/methods/MattingTrimapFreePredictMethod/include/MattingTrimapFreePredictMethod/MattingTrimapFreePredictMethod.h
12e5ea804a683306ff7b96f87db5cf7b44aeac72
[ "BSD-2-Clause" ]
permissive
Kevin4ch/AI-EXPRESS
c4d18b9fe32be1872d451a3cb7dc5e45561c41fd
e82531dd262cb7df8388f42f6edb07e77c8ce0d1
refs/heads/master
2023-02-05T05:15:55.962204
2020-12-28T16:01:46
2020-12-28T16:01:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
h
/** * Copyright (c) 2020 Horizon Robotics. All rights reserved. * @File: MattingTrimapFreePredictMethod.h * @Brief: declaration of the MattingTrimapFreePredictMethod * @Author: zhe.sun * @Email: zhe.sun@horizon.ai * @Date: 2020-12-15 11:07:18 * @Last Modified by: zhe.sun * @Last Modified time: 2020-12-15 18:21:33 */ // no lint #ifndef INCLUDE_MATTINGTRIMAPFREEPREDICTMETHOD_MATTINGTRIMAPFREEPREDICTMETHOD_H_ #define INCLUDE_MATTINGTRIMAPFREEPREDICTMETHOD_MATTINGTRIMAPFREEPREDICTMETHOD_H_ #include <string> #include <vector> #include "DnnPredictMethod/DnnPredictMethod.h" #include "bpu_predict/bpu_predict_extension.h" #ifdef X3 #include "./bpu_predict_x3.h" #endif namespace xstream { class MattingTrimapFreePredictMethod : public DnnPredictMethod { public: MattingTrimapFreePredictMethod() {} virtual ~MattingTrimapFreePredictMethod() {} virtual int Init(const std::string &cfg_path); // 派生类需要实现 // PrepareInputData内部需要根据一帧图像目标数量,多次调用AllocInputTensor分配空间 // 框架不进行输入与输出的Tensor分配 // IN: input, param; OUT: input_tensors, output_tensors // 返回码:0,成功;否则失败;若存在申请失败,函数内部还需负责已申请空间的释放 virtual int PrepareInputData( const std::vector<BaseDataPtr> &input, const std::vector<InputParamPtr> param, std::vector<std::vector<BPU_TENSOR_S>> &input_tensors, std::vector<std::vector<BPU_TENSOR_S>> &output_tensors); private: float expansion_ratio_ = 0.2; }; } // namespace xstream #endif // INCLUDE_MATTINGTRIMAPFREEPREDICTMETHOD_MATTINGTRIMAPFREEPREDICTMETHOD_H_
[ "qingpeng.liu@horizon.ai" ]
qingpeng.liu@horizon.ai
2f70e810c01816e7f74f8684862d77d118cdb0fe
2910e77ea734a2490ec691fa3a1e9ee0e1e7f435
/6.21.cpp
af0e07d3d24ad7fad09aba89ab548c8f38a57493
[]
no_license
lixiaosong0716/li_xiaosong
652bc165c1981be778acd8dbc2a3dcb4483a362a
279672fd447b8203334272a8ec701dc3a1e4af80
refs/heads/master
2020-04-28T11:02:20.311950
2019-05-12T10:26:24
2019-05-12T10:26:24
175,222,084
0
0
null
null
null
null
UTF-8
C++
false
false
257
cpp
#include <iostream> using namespace std; bool iseven (int x) { return (x%2); } int main() { int a; cout <<"Enter one integer: "<<endl; cin >>a; if (iseven (a)) cout <<a<<" is false\n\n"<<endl; else cout <<a<<" is true\n\n"<<endl;; }
[ "1834481128@qq.com" ]
1834481128@qq.com
c05e756d46325750c3defdda5182fb8d7c8cdb26
8d337f83cf36c67897b04f1589b5314d9274c31d
/goost/kuznyechik/Imit.cpp
bfae3caa73ba675c60e9ee5340037a197d2e8289
[ "MIT" ]
permissive
DronMDF/goost
3dac26c54768d03d51d5d759ab4c33d69c4c902f
87a21ba383efc12209377ab686df7b93f4297f50
refs/heads/master
2021-12-27T03:50:01.467305
2021-12-23T16:26:42
2021-12-23T16:26:42
81,734,817
8
1
MIT
2021-12-23T16:26:43
2017-02-12T15:15:09
C++
UTF-8
C++
false
false
1,960
cpp
// Copyright (c) 2017-2021 Andrey Valyaev <dron.valyaev@gmail.com> // // This software may be modified and distributed under the terms // of the MIT license. See the LICENSE file for details. #include "Imit.h" #include "BlkEncrypted.h" #include "BlkRaw.h" #include "BlkShifted.h" #include "BlkXored.h" #include "Iterator.h" #include "Stream.h" using namespace std; using namespace goost::kuznyechik; namespace goost { namespace kuznyechik { // This class xor a<<1 and B if high bit of a is 1 class BlkXoredIfHighBit final : public Block { public: BlkXoredIfHighBit(const shared_ptr<const Block> &a, const shared_ptr<const Block> &b) : a(a), b(b) { } pair<uint64_t, uint64_t> value() const override { const auto a_value = a->value(); const auto a_shift = make_shared<BlkShifted>(a, 1); if ((a_value.second & 0x8000000000000000) == 0) { return a_shift->value(); } return BlkXored(a_shift, b).value(); } private: const shared_ptr<const Block> a; const shared_ptr<const Block> b; }; } // namespace kuznyechik } // namespace goost Imit::Imit(const shared_ptr<const Stream> &data, const shared_ptr<const Key> &key) : data(data), key(key) { } std::pair<uint64_t, uint64_t> Imit::value() const { auto iter = data->iter(); shared_ptr<const Block> block = make_shared<const BlkRaw>(); while (!iter->last()) { block = make_shared<const BlkEncrypted>( make_unique<BlkXored>(block, make_unique<BlkRaw>(iter->value())), key ); iter = iter->next(); } const auto B = make_shared<BlkRaw>(0x87); const auto K1 = make_shared<BlkXoredIfHighBit>( make_unique<BlkEncrypted>(make_unique<BlkRaw>(), key), B ); const auto xblock = make_shared<BlkXored>(block, make_unique<BlkRaw>(iter->value())); if (iter->size() == Block::size) { return BlkEncrypted(make_unique<BlkXored>(xblock, K1), key).value(); } return BlkEncrypted( make_unique<BlkXored>(xblock, make_unique<BlkXoredIfHighBit>(K1, B)), key ).value(); }
[ "dron.valyaev@gmail.com" ]
dron.valyaev@gmail.com
7dff032e81b83ec5a841c7e5bed1d87e0e81dfaa
b15e1f7d336ee67a69440c976225382de5de9407
/FrameworkSocket/SocketServer/Message.h
cfd6c04b1ed6d9c95348481f03aa9432c157e35e
[]
no_license
heinsteinh/FtsEngine
5ef66c1a1ef443aee59caf953a04c66b52937088
ea275f26ae0ff897f696a6ea1f82df3bde459f8f
refs/heads/master
2021-05-28T22:40:25.919833
2015-05-11T05:55:52
2015-05-11T05:55:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
116
h
#pragma once #include <cstdint> #include <string> #include <exception> #include <sstream> namespace Framework { }
[ "heinsteinh@gmail.com" ]
heinsteinh@gmail.com
02ddc1c37a57730541f80de10f3463521ce0de77
09ca0b4bee30073519413ab36afe5b97da54b90d
/src/urc10.cpp
5231044e982c30bda8295c8efe16782ee056136b
[]
no_license
Circuit-killer/Cytron_URC10_Library
d994058ea033fb226a6eda16eb378667ba4cabf1
307c50b5cf98be1c576ddaee76187749b70cfd6f
refs/heads/master
2020-03-25T23:39:58.055021
2018-07-20T10:15:53
2018-07-20T10:15:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,513
cpp
#include "urc10.h" // **************************************** // Main // **************************************** urc10 URC10; urc10::urc10(){ } void urc10::begin(bool enableMotor, bool enableUltrasonic1, bool enableUltrasonic2, bool enableLcd){ if(enableMotor){ motor.begin(); } if(enableUltrasonic1){ ultrasonic1.begin(URC10_ULTRASONIC1_ECHO, URC10_ULTRASONIC1_TRIG); } if(enableUltrasonic2){ ultrasonic2.begin(URC10_ULTRASONIC2_ECHO, URC10_ULTRASONIC2_TRIG); } if(enableLcd && !lcd.isEnabled()){ lcd.begin(); } } void urc10::enableLcd(){ if(!lcd.isEnabled()) lcd.begin(); } void urc10::enableUltrasonic1(){ ultrasonic1.begin(URC10_ULTRASONIC1_ECHO, URC10_ULTRASONIC1_TRIG); } void urc10::enableUltrasonic2(){ ultrasonic2.begin(URC10_ULTRASONIC2_ECHO, URC10_ULTRASONIC2_TRIG); } void urc10::enableMotor(){ motor.begin(); } // **************************************** // lcd (SSD1306) extension // **************************************** urc10_lcd::urc10_lcd():SSD1306Ascii(){ } void urc10_lcd::invertDisplay(uint8_t i) { if (i) { ssd1306WriteCmd(SSD1306_INVERTDISPLAY); } else { ssd1306WriteCmd(SSD1306_NORMALDISPLAY); } } // startscrollright // Activate a right handed scroll for rows start through stop // Hint, the display is 16 rows tall. To scroll the whole display, run: // display.scrollright(0x00, 0x0F) void urc10_lcd::startScrollRight(uint8_t start, uint8_t stop){ ssd1306WriteCmd(SSD1306_RIGHT_HORIZONTAL_SCROLL); ssd1306WriteCmd(0X00); ssd1306WriteCmd(start); ssd1306WriteCmd(0X00); ssd1306WriteCmd(stop); ssd1306WriteCmd(0X00); ssd1306WriteCmd(0XFF); ssd1306WriteCmd(SSD1306_ACTIVATE_SCROLL); } // startscrollleft // Activate a right handed scroll for rows start through stop // Hint, the display is 16 rows tall. To scroll the whole display, run: // display.scrollright(0x00, 0x0F) void urc10_lcd::startScrollLeft(uint8_t start, uint8_t stop){ ssd1306WriteCmd(SSD1306_LEFT_HORIZONTAL_SCROLL); ssd1306WriteCmd(0X00); ssd1306WriteCmd(start); ssd1306WriteCmd(0X00); ssd1306WriteCmd(stop); ssd1306WriteCmd(0X00); ssd1306WriteCmd(0XFF); ssd1306WriteCmd(SSD1306_ACTIVATE_SCROLL); } // startscrolldiagright // Activate a diagonal scroll for rows start through stop // Hint, the display is 16 rows tall. To scroll the whole display, run: // display.scrollright(0x00, 0x0F) void urc10_lcd::startScrollDiagRight(uint8_t start, uint8_t stop){ ssd1306WriteCmd(SSD1306_SET_VERTICAL_SCROLL_AREA); ssd1306WriteCmd(0X00); ssd1306WriteCmd(SSD1306_LCDHEIGHT); ssd1306WriteCmd(SSD1306_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL); ssd1306WriteCmd(0X00); ssd1306WriteCmd(start); ssd1306WriteCmd(0X00); ssd1306WriteCmd(stop); ssd1306WriteCmd(0X01); ssd1306WriteCmd(SSD1306_ACTIVATE_SCROLL); } // startscrolldiagleft // Activate a diagonal scroll for rows start through stop // Hint, the display is 16 rows tall. To scroll the whole display, run: // display.scrollright(0x00, 0x0F) void urc10_lcd::startScrollDiagLeft(uint8_t start, uint8_t stop){ ssd1306WriteCmd(SSD1306_SET_VERTICAL_SCROLL_AREA); ssd1306WriteCmd(0X00); ssd1306WriteCmd(SSD1306_LCDHEIGHT); ssd1306WriteCmd(SSD1306_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL); ssd1306WriteCmd(0X00); ssd1306WriteCmd(start); ssd1306WriteCmd(0X00); ssd1306WriteCmd(stop); ssd1306WriteCmd(0X01); ssd1306WriteCmd(SSD1306_ACTIVATE_SCROLL); } void urc10_lcd::stopScroll(void){ ssd1306WriteCmd(SSD1306_DEACTIVATE_SCROLL); } // Dim the display // dim = true: display is dimmed // dim = false: display is normal void urc10_lcd::dim(boolean dim) { uint8_t contrast; if (dim) { contrast = 0; // Dimmed display } else { contrast = 0xCF; } // the range of contrast to too small to be really useful // it is useful to dim the display ssd1306WriteCmd(SSD1306_SETCONTRAST); ssd1306WriteCmd(contrast); } void urc10_lcd::drawBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h, uint8_t color) { int16_t i, j; int16_t y_start = y >> 3; //divided by 8 uint8_t row; if (h%8==0) { row=h/8;//row from 0 to 7 } else{ row=h/8+1;//Quotient+1 } for(j = 0 ; j < row; j++){ setCursor(x, y_start); for(i = 0; i < w; i++) { ssd1306WriteRamBuf(color==NORMAL?(pgm_read_byte(bitmap + i + j * w)):~(pgm_read_byte(bitmap + i + j * w))); if((w*h/8 - 1) == (i + j * w)) return; //if pixels are enough } y_start++; } setCursor(x, y_start); }
[ "bengchet@cytron.com.my" ]
bengchet@cytron.com.my
2f4d929c05b0df087b8d9bc391fee05e861d2d02
982e4214f175004466958ac57ec8172ea0675d1a
/god-is-work/Manager.cpp
703eceddc08c9b10d12d67b6540b9489c123f6ca
[]
no_license
TuisClangSchola/god-is-work
c5db02e4bd7e5eede5b94e63a40df4d056fabf66
87804ce678664bf277fd4d77bb82141ef122651f
refs/heads/master
2020-12-06T16:41:41.665838
2020-01-11T06:43:07
2020-01-11T06:43:07
232,509,519
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,811
cpp
#include "Manager.hpp" /// ----------------------------------------------------------------------------------- void Manager::SceneChange() { if (p_baseMove != nullptr) { delete p_baseMove; p_baseMove = nullptr; } // 今のシーン switch (BASICPARAM::e_nowScene) { // ロゴ case ESceneNumber::TITLE_AND_MENU: p_baseMove = new TitleAndMenu(); printfDx("TitleAndMenu\n"); break; // タイトル case ESceneNumber::GAME: p_baseMove = new Game(); printfDx("Game\n"); break; // チュートリアル case ESceneNumber::GAMECLEAR: p_baseMove = new GameClear(); printfDx("GameClear\n"); break; // ゲーム本編 case ESceneNumber::GAMEOVER: p_baseMove = new GameOver(); printfDx("GameOver\n"); break; default: break; } } /// ----------------------------------------------------------------------------------- Manager::Manager() { p_baseMove = nullptr; BASICPARAM::e_nowScene = ESceneNumber::TITLE_AND_MENU; BASICPARAM::e_preScene = ESceneNumber::TITLE_AND_MENU; p_baseMove = new TitleAndMenu(); } /// ----------------------------------------------------------------------------------- Manager::~Manager() { if (p_baseMove != nullptr) delete p_baseMove; } /// ----------------------------------------------------------------------------------- void Manager::Update() { // 現在のシーンと直前のシーンが同じとき if (BASICPARAM::e_nowScene == BASICPARAM::e_preScene) { // ゲームの描画に関する p_baseMove->Draw(); // ゲームのプロセスに関する p_baseMove->Process(); } // 現在と直前のシーンが異なったら else { // シーンを変える SceneChange(); // 直前のシーンと現在のシーンを同じにする BASICPARAM::e_preScene = BASICPARAM::e_nowScene; } }
[ "kingwasheart@yahoo.co.jp" ]
kingwasheart@yahoo.co.jp
29439ffb0a3971988139ee8222743413b103f9af
8191864909f7d8b896f97ff353ce475757f4fbd1
/deps/chakrashim/core/lib/jsrt/jsrtinternal.h
df5b2f1aa45c451feaaeb9f681d8ecb14a67c571
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-unicode", "LicenseRef-scancode-openssl", "LicenseRef-scancode-unknown-license-reference", "Artistic-2.0", "NAIST-2003", "NTP", "ICU", "ISC", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
mozilla/spidernode
df5a1e58b54da5bfbc35a585fc4bbb15678f8ca0
aafa9e5273f954f272bb4382fc007af14674b4c2
refs/heads/master
2023-08-26T19:45:35.703738
2019-06-18T19:01:53
2019-06-18T19:01:53
55,816,013
618
69
NOASSERTION
2019-06-18T18:59:28
2016-04-08T23:38:28
JavaScript
UTF-8
C++
false
false
10,471
h
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once #include "JsrtExceptionBase.h" #include "Exceptions/EvalDisabledException.h" #define PARAM_NOT_NULL(p) \ if (p == nullptr) \ { \ return JsErrorNullArgument; \ } #define VALIDATE_JSREF(p) \ if (p == JS_INVALID_REFERENCE) \ { \ return JsErrorInvalidArgument; \ } \ #define MARSHAL_OBJECT(p, scriptContext) \ Js::RecyclableObject* __obj = Js::RecyclableObject::FromVar(p); \ if (__obj->GetScriptContext() != scriptContext) \ { \ if(__obj->GetScriptContext()->GetThreadContext() != scriptContext->GetThreadContext()) \ { \ return JsErrorWrongRuntime; \ } \ p = Js::CrossSite::MarshalVar(scriptContext, __obj); \ } #define VALIDATE_INCOMING_RUNTIME_HANDLE(p) \ { \ if (p == JS_INVALID_RUNTIME_HANDLE) \ { \ return JsErrorInvalidArgument; \ } \ } #define VALIDATE_INCOMING_PROPERTYID(p) \ { \ if (p == JS_INVALID_REFERENCE || \ Js::IsInternalPropertyId(((Js::PropertyRecord *)p)->GetPropertyId())) \ { \ return JsErrorInvalidArgument; \ } \ } #define VALIDATE_INCOMING_REFERENCE(p, scriptContext) \ { \ VALIDATE_JSREF(p); \ if (Js::RecyclableObject::Is(p)) \ { \ MARSHAL_OBJECT(p, scriptContext) \ } \ } #define VALIDATE_INCOMING_OBJECT(p, scriptContext) \ { \ VALIDATE_JSREF(p); \ if (!Js::JavascriptOperators::IsObject(p)) \ { \ return JsErrorArgumentNotObject; \ } \ MARSHAL_OBJECT(p, scriptContext) \ } #define VALIDATE_INCOMING_OBJECT_OR_NULL(p, scriptContext) \ { \ VALIDATE_JSREF(p); \ if (!Js::JavascriptOperators::IsObjectOrNull(p)) \ { \ return JsErrorArgumentNotObject; \ } \ MARSHAL_OBJECT(p, scriptContext) \ } #define VALIDATE_INCOMING_FUNCTION(p, scriptContext) \ { \ VALIDATE_JSREF(p); \ if (!Js::JavascriptFunction::Is(p)) \ { \ return JsErrorInvalidArgument; \ } \ MARSHAL_OBJECT(p, scriptContext) \ } template <class Fn> JsErrorCode GlobalAPIWrapper(Fn fn) { JsErrorCode errCode = JsNoError; try { // For now, treat this like an out of memory; consider if we should do something else here. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_StackOverflow)); errCode = fn(); // These are error codes that should only be produced by the wrappers and should never // be produced by the internal calls. Assert(errCode != JsErrorFatal && errCode != JsErrorNoCurrentContext && errCode != JsErrorInExceptionState && errCode != JsErrorInDisabledState && errCode != JsErrorOutOfMemory && errCode != JsErrorScriptException && errCode != JsErrorScriptTerminated); } CATCH_STATIC_JAVASCRIPT_EXCEPTION_OBJECT CATCH_OTHER_EXCEPTIONS return errCode; } JsErrorCode CheckContext(JsrtContext *currentContext, bool verifyRuntimeState, bool allowInObjectBeforeCollectCallback = false); template <bool verifyRuntimeState, class Fn> JsErrorCode ContextAPIWrapper(Fn fn) { JsrtContext *currentContext = JsrtContext::GetCurrent(); JsErrorCode errCode = CheckContext(currentContext, verifyRuntimeState); if (errCode != JsNoError) { return errCode; } Js::ScriptContext *scriptContext = currentContext->GetScriptContext(); try { AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_JavascriptException)); // Enter script BEGIN_ENTER_SCRIPT(scriptContext, true, true, true) { errCode = fn(scriptContext); } END_ENTER_SCRIPT // These are error codes that should only be produced by the wrappers and should never // be produced by the internal calls. Assert(errCode != JsErrorFatal && errCode != JsErrorNoCurrentContext && errCode != JsErrorInExceptionState && errCode != JsErrorInDisabledState && errCode != JsErrorOutOfMemory && errCode != JsErrorScriptException && errCode != JsErrorScriptTerminated); } catch (Js::OutOfMemoryException) { return JsErrorOutOfMemory; } catch (Js::JavascriptExceptionObject * exceptionObject) { scriptContext->GetThreadContext()->SetRecordedException(exceptionObject); return JsErrorScriptException; } catch (Js::ScriptAbortException) { Assert(scriptContext->GetThreadContext()->GetRecordedException() == nullptr); scriptContext->GetThreadContext()->SetRecordedException(scriptContext->GetThreadContext()->GetPendingTerminatedErrorObject()); return JsErrorScriptTerminated; } catch (Js::EvalDisabledException) { return JsErrorScriptEvalDisabled; } CATCH_OTHER_EXCEPTIONS return errCode; } // allowInObjectBeforeCollectCallback only when current API is guaranteed not to do recycler allocation. template <class Fn> JsErrorCode ContextAPINoScriptWrapper(Fn fn, bool allowInObjectBeforeCollectCallback = false, bool scriptExceptionAllowed = false) { JsrtContext *currentContext = JsrtContext::GetCurrent(); JsErrorCode errCode = CheckContext(currentContext, /*verifyRuntimeState*/true, allowInObjectBeforeCollectCallback); if (errCode != JsNoError) { return errCode; } Js::ScriptContext *scriptContext = currentContext->GetScriptContext(); try { // For now, treat this like an out of memory; consider if we should do something else here. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_StackOverflow)); errCode = fn(scriptContext); // These are error codes that should only be produced by the wrappers and should never // be produced by the internal calls. Assert(errCode != JsErrorFatal && errCode != JsErrorNoCurrentContext && errCode != JsErrorInExceptionState && errCode != JsErrorInDisabledState && errCode != JsErrorOutOfMemory && (scriptExceptionAllowed || errCode != JsErrorScriptException) && errCode != JsErrorScriptTerminated); } CATCH_STATIC_JAVASCRIPT_EXCEPTION_OBJECT catch (Js::JavascriptExceptionObject * exceptionObject) { AssertMsg(false, "Should never get JavascriptExceptionObject for ContextAPINoScriptWrapper."); scriptContext->GetThreadContext()->SetRecordedException(exceptionObject); return JsErrorScriptException; } catch (Js::ScriptAbortException) { Assert(scriptContext->GetThreadContext()->GetRecordedException() == nullptr); scriptContext->GetThreadContext()->SetRecordedException(scriptContext->GetThreadContext()->GetPendingTerminatedErrorObject()); return JsErrorScriptTerminated; } CATCH_OTHER_EXCEPTIONS return errCode; } template <class Fn> JsErrorCode SetContextAPIWrapper(JsrtContext* newContext, Fn fn) { JsrtContext* oldContext = JsrtContext::GetCurrent(); Js::ScriptContext* scriptContext = newContext->GetScriptContext(); JsErrorCode errorCode = JsNoError; try { // For now, treat this like an out of memory; consider if we should do something else here. AUTO_NESTED_HANDLED_EXCEPTION_TYPE((ExceptionType)(ExceptionType_OutOfMemory | ExceptionType_StackOverflow | ExceptionType_JavascriptException)); if (JsrtContext::TrySetCurrent(newContext)) { // Enter script BEGIN_ENTER_SCRIPT(scriptContext, true, true, true) { errorCode = fn(scriptContext); } END_ENTER_SCRIPT } else { errorCode = JsErrorWrongThread; } // These are error codes that should only be produced by the wrappers and should never // be produced by the internal calls. Assert(errorCode != JsErrorFatal && errorCode != JsErrorNoCurrentContext && errorCode != JsErrorInExceptionState && errorCode != JsErrorInDisabledState && errorCode != JsErrorOutOfMemory && errorCode != JsErrorScriptException && errorCode != JsErrorScriptTerminated); } catch (Js::OutOfMemoryException) { errorCode = JsErrorOutOfMemory; } catch (Js::JavascriptExceptionObject * exceptionObject) { scriptContext->GetThreadContext()->SetRecordedException(exceptionObject); errorCode = JsErrorScriptException; } catch (Js::ScriptAbortException) { Assert(scriptContext->GetThreadContext()->GetRecordedException() == nullptr); scriptContext->GetThreadContext()->SetRecordedException(scriptContext->GetThreadContext()->GetPendingTerminatedErrorObject()); errorCode = JsErrorScriptTerminated; } catch (Js::EvalDisabledException) { errorCode = JsErrorScriptEvalDisabled; } catch (Js::StackOverflowException) { return JsErrorOutOfMemory; } CATCH_OTHER_EXCEPTIONS JsrtContext::TrySetCurrent(oldContext); return errorCode; } void HandleScriptCompileError(Js::ScriptContext * scriptContext, CompileScriptException * se); #if DBG #define _PREPARE_RETURN_NO_EXCEPTION __debugCheckNoException.hasException = false; #else #define _PREPARE_RETURN_NO_EXCEPTION #endif #define BEGIN_JSRT_NO_EXCEPTION BEGIN_NO_EXCEPTION #define END_JSRT_NO_EXCEPTION END_NO_EXCEPTION return JsNoError; #define RETURN_NO_EXCEPTION(x) _PREPARE_RETURN_NO_EXCEPTION return x
[ "Kunal.Pathak@microsoft.com" ]
Kunal.Pathak@microsoft.com
4a5409ee72cc0ba649b85223af4bce6cd2c85c93
e3a08059f2d170164e620486793d5b0f841abc7f
/benchmarks/pbbs/regions_schedov/maximalIndependentSet/ndMIS/graphIO.h
ce378be5b0f70229cc9f02dfd1f6739bbea0c380
[]
no_license
adarshyoga/TaskProf_RegionDiffSched
1cd4fb65de7fcb4cd369b646493a615b55b58199
b8c5ea0137833666389587c603ea547c859d5846
refs/heads/master
2020-03-08T18:40:21.708379
2019-02-01T02:29:23
2019-02-01T02:29:23
128,313,576
1
0
null
null
null
null
UTF-8
C++
false
false
16,465
h
// This code is part of the Problem Based Benchmark Suite (PBBS) // Copyright (c) 2010 Guy Blelloch and the PBBS team // // 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 _BENCH_GRAPH_IO #define _BENCH_GRAPH_IO #include <iostream> #include <stdint.h> #include <cstring> #include "parallel.h" #include "IO.h" using namespace benchIO; template <class intT> int xToStringLen(edge<intT> a) { return xToStringLen(a.u) + xToStringLen(a.v) + 1; } template <class intT> void xToString(char* s, edge<intT> a) { int l = xToStringLen(a.u); xToString(s, a.u); s[l] = ' '; xToString(s+l+1, a.v); } template <class intT> int xToStringLen(wghEdge<intT> a) { return xToStringLen(a.u) + xToStringLen(a.v) + xToStringLen(a.weight) + 2; } template <class intT> void xToString(char* s, wghEdge<intT> a) { int lu = xToStringLen(a.u); int lv = xToStringLen(a.v); xToString(s, a.u); s[lu] = ' '; xToString(s+lu+1, a.v); s[lu+lv+1] = ' '; xToString(s+lu+lv+2, a.weight); } namespace benchIO { using namespace std; string AdjGraphHeader = "AdjacencyGraph"; string EdgeArrayHeader = "EdgeArray"; string WghEdgeArrayHeader = "WeightedEdgeArray"; string WghAdjGraphHeader = "WeightedAdjacencyGraph"; template <class intT> int writeGraphToFile(graph<intT> G, char* fname) { intT m = G.m; intT n = G.n; intT totalLen = 2 + n + m; intT *Out = newA(intT, totalLen); Out[0] = n; Out[1] = m; /* parallel_for (intT i=0; i < n; i++) { */ /* Out[i+2] = G.V[i].degree; */ //} parallel_for( tbb::blocked_range<intT>(0,n), [=](tbb::blocked_range<intT> r, size_t thdId) {for( intT i=r.begin(); i!=r.end(); ++i ) Out[i+2] = G.V[i].degree; }, __FILE__, __LINE__ ); intT total = sequence::scan(Out+2,Out+2,n,utils::addF<intT>(),(intT)0); for (intT i=0; i < n; i++) { intT *O = Out + (2 + n + Out[i+2]); vertex<intT> v = G.V[i]; for (intT j = 0; j < v.degree; j++) O[j] = v.Neighbors[j]; } int r = writeArrayToFile(AdjGraphHeader, Out, totalLen, fname); free(Out); return r; } template <class intT> int writeWghGraphToFile(wghGraph<intT> G, char* fname) { intT m = G.m; intT n = G.n; intT totalLen = 2 + n + m*2; intT *Out = newA(intT, totalLen); Out[0] = n; Out[1] = m; /* parallel_for (intT i=0; i < n; i++) { */ /* Out[i+2] = G.V[i].degree; */ /* } */ parallel_for( tbb::blocked_range<intT>(0,n), [=](tbb::blocked_range<intT> r, size_t thdId) {for( intT i=r.begin(); i!=r.end(); ++i ) Out[i+2] = G.V[i].degree; }, __FILE__, __LINE__ ); intT total = sequence::scan(Out+2,Out+2,n,utils::addF<intT>(),(intT)0); for (intT i=0; i < n; i++) { intT *O = Out + (2 + n + Out[i+2]); wghVertex<intT> v = G.V[i]; for (intT j = 0; j < v.degree; j++) { O[j] = v.Neighbors[j]; O[j+m] = v.nghWeights[j]; } } int r = writeArrayToFile(WghAdjGraphHeader, Out, totalLen, fname); free(Out); return r; } template <class intT> int writeEdgeArrayToFile(edgeArray<intT> EA, char* fname) { intT m = EA.nonZeros; int r = writeArrayToFile(EdgeArrayHeader, EA.E, m, fname); return r; } template <class intT> int writeWghEdgeArrayToFile(wghEdgeArray<intT> EA, char* fname) { uintT m = EA.m; int r = writeArrayToFile(WghEdgeArrayHeader, EA.E, m, fname); return r; } template <class intT> edgeArray<intT> readEdgeArrayFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); if (W.Strings[0] != EdgeArrayHeader) { cout << "Bad input file" << endl; abort(); } long n = (W.m-1)/2; edge<intT> *E = newA(edge<intT>,n); /* {parallel_for(long i=0; i < n; i++) */ /* E[i] = edge<intT>(atol(W.Strings[2*i + 1]), */ /* atol(W.Strings[2*i + 2]));} */ parallel_for( tbb::blocked_range<intT>(0,n), [=](tbb::blocked_range<intT> r, size_t thdId) {for( intT i=r.begin(); i!=r.end(); ++i ) { E[i] = edge<intT>(atol(W.Strings[2*i + 1]), atol(W.Strings[2*i + 2])); } }, __FILE__, __LINE__ ); //W.del(); // to deal with performance bug in malloc intT maxR = 0; intT maxC = 0; for (long i=0; i < n; i++) { maxR = max<intT>(maxR, E[i].u); maxC = max<intT>(maxC, E[i].v); } intT maxrc = max<intT>(maxR,maxC) + 1; return edgeArray<intT>(E, maxrc, maxrc, n); } template <class intT> wghEdgeArray<intT> readWghEdgeArrayFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); if (W.Strings[0] != WghEdgeArrayHeader) { cout << "Bad input file" << endl; abort(); } long n = (W.m-1)/3; wghEdge<intT> *E = newA(wghEdge<intT>,n); /* {parallel_for(long i=0; i < n; i++) */ /* E[i] = wghEdge<intT>(atol(W.Strings[3*i + 1]), */ /* atol(W.Strings[3*i + 2]), */ /* atof(W.Strings[3*i + 3]));} */ parallel_for( tbb::blocked_range<intT>(0,n), [=](tbb::blocked_range<intT> r, size_t thdId) {for( intT i=r.begin(); i!=r.end(); ++i ) E[i] = wghEdge<intT>(atol(W.Strings[3*i + 1]), atol(W.Strings[3*i + 2]), atof(W.Strings[3*i + 3])); }, __FILE__, __LINE__ ); //W.del(); // to deal with performance bug in malloc intT maxR = 0; intT maxC = 0; for (long i=0; i < n; i++) { maxR = max<intT>(maxR, E[i].u); maxC = max<intT>(maxC, E[i].v); } return wghEdgeArray<intT>(E, max<intT>(maxR,maxC)+1, n); } template <class intT> graph<intT> readGraphFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); if (W.Strings[0] != AdjGraphHeader) { cout << "Bad input file: missing header: " << AdjGraphHeader << endl; abort(); } long len = W.m -1; uintT * In = newA(uintT, len); //{parallel_for(long i=0; i < len; i++) In[i] = atol(W.Strings[i + 1]);} parallel_for( tbb::blocked_range<intT>(0,len), [=](tbb::blocked_range<intT> r, size_t thdId) {for( intT i=r.begin(); i!=r.end(); ++i ) In[i] = atol(W.Strings[i + 1]); }, __FILE__, __LINE__ ); //W.del(); // to deal with performance bug in malloc long n = In[0]; long m = In[1]; if (len != n + m + 2) { cout << "Bad input file: length = "<<len<< " n+m+2 = " << n+m+2 << endl; abort(); } vertex<intT> *v = newA(vertex<intT>,n); uintT* offsets = In+2; uintT* edges = In+2+n; /* parallel_for (uintT i=0; i < n; i++) { */ /* uintT o = offsets[i]; */ /* uintT l = ((i == n-1) ? m : offsets[i+1])-offsets[i]; */ /* v[i].degree = l; */ /* v[i].Neighbors = (intT*)(edges+o); */ /* } */ parallel_for( tbb::blocked_range<intT>(0,n), [=](tbb::blocked_range<intT> r, size_t thdId) {for( intT i=r.begin(); i!=r.end(); ++i ) { intT o = offsets[i]; intT l = ((i == n-1) ? m : offsets[i+1])-offsets[i]; v[i].degree = l; v[i].Neighbors = edges+o; } }, __FILE__, __LINE__ ); return graph<intT>(v,(intT)n,(uintT)m,(intT*)In); } template <class intT, class intE> graphC<intT, intE> readGraphCFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); if (W.Strings[0] != AdjGraphHeader) { cout << "Bad input file: missing header: " << AdjGraphHeader << endl; abort(); } long len = W.m -1; long n = atol(W.Strings[1]); long m = atol(W.Strings[2]); if (len != n + m + 2) { cout << "Bad input file: length = "<<len<< " n+m+2 = " << n+m+2 << endl; abort(); } intT * offsets = newA(intT, n+1); intE * edges = newA(intE,m); //{parallel_for(long i=0; i < n; i++) offsets[i] = atol(W.Strings[i+3]);} parallel_for( tbb::blocked_range<long>(0,n), [=](tbb::blocked_range<long> r, size_t thdId) {for( long i=r.begin(); i!=r.end(); ++i ) { offsets[i] = atol(W.Strings[i+3]); } }, __FILE__, __LINE__ ); offsets[n] = m; //{parallel_for(long i=0; i < m; i++) edges[i] = atol(W.Strings[n+i+3]);} parallel_for( tbb::blocked_range<long>(0,m), [=](tbb::blocked_range<long> r, size_t thdId) {for(long i=r.begin(); i!=r.end(); ++i ) { edges[i] = atol(W.Strings[n+i+3]); } }, __FILE__, __LINE__ ); //W.del(); // to deal with performance bug in malloc return graphC<intT,intE>(offsets,edges,n,m); } template <class intT> wghGraph<intT> readWghGraphFromFile(char* fname) { _seq<char> S = readStringFromFile(fname); words W = stringToWords(S.A, S.n); if (W.Strings[0] != WghAdjGraphHeader) { cout << "Bad input file" << endl; abort(); } long len = W.m -1; intT * In = newA(intT, len); //{parallel_for(long i=0; i < len; i++) In[i] = atol(W.Strings[i + 1]);} parallel_for( tbb::blocked_range<long>(0,len), [=](tbb::blocked_range<long> r, size_t thdId) {for(long i=r.begin(); i!=r.end(); ++i ) { In[i] = atol(W.Strings[i + 1]); } }, __FILE__, __LINE__ ); //W.del(); // to deal with performance bug in malloc long n = In[0]; long m = In[1]; if (len != n + 2*m + 2) { cout << "Bad input file" << endl; abort(); } wghVertex<intT> *v = newA(wghVertex<intT>,n); uintT* offsets = (uintT*)In+2; uintT* edges = (uintT*)In+2+n; intT* weights = In+2+n+m; /* parallel_for (uintT i=0; i < n; i++) { */ /* uintT o = offsets[i]; */ /* uintT l = ((i == n-1) ? m : offsets[i+1])-offsets[i]; */ /* v[i].degree = l; */ /* v[i].Neighbors = (intT*)(edges+o); */ /* v[i].nghWeights = (weights+o); */ /* } */ parallel_for( tbb::blocked_range<uintT>(0,n), [=](tbb::blocked_range<uintT> r, size_t thdId) {for(uintT i=r.begin(); i!=r.end(); ++i ) { uintT o = offsets[i]; uintT l = ((i == n-1) ? m : offsets[i+1])-offsets[i]; v[i].degree = l; v[i].Neighbors = (intT*)(edges+o); v[i].nghWeights = (weights+o); } }, __FILE__, __LINE__ ); return wghGraph<intT>(v,(intT)n,(uintT)m,(intT*)In,weights); } void errorOut(const char* s) { cerr << s << endl; throw s; } void packInt64(int64_t x, uint8_t buf[8]) { uint64_t xu = x; for (int i = 0; i < 8; ++i) buf[i] = (xu >> (8 * i)) & 0xff; } int64_t unpackInt64(const uint8_t buf[8]) { uint64_t xu = 0; for (int i = 0; i < 8; ++i) xu |= ((uint64_t)buf[i]) << (i * 8); return (int64_t)xu; } void writeInt(ostream& out, char buf[8], int64_t x) { packInt64(x, (uint8_t*)buf); out.write(buf, 8); } int64_t readInt(istream& in, char buf[8]) { in.read(buf, 8); return unpackInt64((uint8_t*)buf); } template<typename intT> void writeFlowGraph(ostream& out, FlowGraph<intT> g) { char buf[8]; out.write("FLOWFLOW", 8); writeInt(out, buf, g.g.n); writeInt(out, buf, g.g.m); writeInt(out, buf, g.source); writeInt(out, buf, g.sink); intT o = 0; for (intT i = 0; i < g.g.n; ++i) { writeInt(out, buf, o); o += g.g.V[i].degree; } for (intT i = 0; i < g.g.n; ++i) { wghVertex<intT>& v = g.g.V[i]; for (intT j = 0; j < v.degree; ++j) { writeInt(out, buf, v.Neighbors[j]); writeInt(out, buf, v.nghWeights[j]); } } } template<typename intT> FlowGraph<intT> readFlowGraph(istream& in) { char buf[10]; in.read(buf, 8); buf[8] = 0; if (strcmp(buf, "FLOWFLOW")) errorOut("Invalid flow graph input file"); intT n = readInt(in, buf); intT m = readInt(in, buf); intT S = readInt(in, buf); intT T = readInt(in, buf); intT *offset = newA(intT, n); intT* adj = newA(intT, m); intT* weights = newA(intT, m); wghVertex<intT>* v = newA(wghVertex<intT>, n); for (intT i = 0; i < n; ++i) { offset[i] = readInt(in, buf); v[i].Neighbors = adj + offset[i]; v[i].nghWeights = weights + offset[i]; if (i > 0) v[i - 1].degree = offset[i] - offset[i - 1]; } v[n - 1].degree = m - offset[n - 1]; free(offset); for (intT i = 0; i < m; ++i) { adj[i] = readInt(in, buf); weights[i] = readInt(in, buf); } return FlowGraph<intT>(wghGraph<intT>(v, n, m, adj, weights), S, T); } const char nl = '\n'; template <typename intT> FlowGraph<intT> writeFlowGraphDimacs(ostream& out, FlowGraph<intT> g) { out << "c DIMACS flow network description" << nl; out << "c (problem-id, nodes, arcs)" << nl; out << "p max " << g.g.n << " " << g.g.m << nl; out << "c source" << nl; out << "n " << g.source + 1 << " s" << nl; out << "c sink" << nl; out << "n " << g.sink + 1 << " t" << nl; out << "c arc description (from, to, capacity)" << nl; for (intT i = 0; i < g.g.n; ++i) { wghVertex<intT>& v = g.g.V[i]; for (intT j = 0; j < v.degree; ++j) { out << "a " << i + 1 << " " << v.Neighbors[j] + 1 << " " << v.nghWeights[j] << nl; } } } template<typename intT> struct intWghEdge { intT from, to, w; }; int readDimacsLinePref(istream& in, const char* expected) { char type; while (in >> type) { if (type == 'c') { while (in.peek() != EOF && in.peek() != '\n') in.ignore(); in >> ws; continue; } else if (!strchr(expected, type)) { errorOut((string("Unexpected DIMACS line (expected 'c' or one of '") + expected + "')").c_str()); } return type; } return EOF; } template <typename intT> FlowGraph<intT> readFlowGraphDimacs(istream& in) { string tmp; intT n, m; int type = readDimacsLinePref(in, "p"); if (type == EOF) errorOut("Unexpected EOF while reading DIMACS file"); in >> tmp >> n >> m; intWghEdge<intT>* edges = newA(intWghEdge<intT>, m); intT edgei = 0; intT* pos = newA(intT, n + 1); intT S = -1, T = -1; while (EOF != (type = readDimacsLinePref(in, "an"))) { if (type == 'n') { intT x; char st; in >> x >> st; x--; if (st == 's') S = x; else T = x; } else { // type == 'a' intT from, to, cap; in >> from >> to >> cap; from--; to--; edges[edgei] = (intWghEdge<intT>) { from, to, cap }; edgei++; pos[from + 1]++; } } if (S < 0) errorOut("No source was specified in DIMACS input file"); if (T < 0) errorOut("No sink was specified in DIMACS input file"); if (m != edgei) errorOut("Inconsistent edge count in DIMACS input file"); intT* adj = newA(intT, m); intT* weights = newA(intT, m); wghVertex<intT>* v = newA(wghVertex<intT>, n); for (intT i = 0; i < n; ++i) { pos[i + 1] += pos[i]; v[i].Neighbors = adj + pos[i]; v[i].nghWeights = weights + pos[i]; v[i].degree = pos[i + 1] - pos[i]; } for (intT i = 0; i < m; ++i) { intT& p = pos[edges[i].from]; adj[p] = edges[i].to; weights[p] = edges[i].w; p++; } free(edges); free(pos); return FlowGraph<intT>(wghGraph<intT>(v, n, m, adj, weights), S, T); } }; #endif // _BENCH_GRAPH_IO
[ "adarsh.yoga@cs.rutgers.edu" ]
adarsh.yoga@cs.rutgers.edu
798137e4b7934630921de53d2951b9246e92f72f
1ed4e96c20da03fbd3aa4f18d4b004a59d8f89e5
/Repo/venv/Lib/site-packages/torch/include/torch/csrc/jit/serialization/import.h
0932ce81f8f70fb46e0aa47028646c23356f7294
[]
no_license
donhatkha/CS2225.CH1501
eebc854864dc6fe72a3650f640787de11d4e82b7
19d4dd3b11f8c9560d0d0a93882298637cacdc80
refs/heads/master
2023-07-19T13:27:17.862158
2021-02-08T07:19:05
2021-02-08T07:19:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,654
h
#pragma once #include <caffe2/serialize/inline_container.h> #include <torch/csrc/jit/api/module.h> #include <torch/csrc/jit/ir/ir.h> #include <torch/csrc/jit/serialization/unpickler.h> #include <istream> namespace caffe2 { namespace serialize { class ReadAdapterInterface; } // namespace serialize } // namespace caffe2 namespace torch { namespace jit { static ExtraFilesMap default_extra_files; TORCH_API Module import_ir_module( std::shared_ptr<CompilationUnit> cu, const std::string& filename, c10::optional<c10::Device> device = c10::nullopt, ExtraFilesMap& extra_files = default_extra_files); TORCH_API Module import_ir_module( std::shared_ptr<CompilationUnit> cu, std::istream& in, c10::optional<c10::Device> device = c10::nullopt, ExtraFilesMap& extra_files = default_extra_files); TORCH_API Module import_ir_module( std::shared_ptr<CompilationUnit> cu, std::unique_ptr<caffe2::serialize::ReadAdapterInterface> rai, c10::optional<c10::Device> device = c10::nullopt, ExtraFilesMap& extra_files = default_extra_files); /// Loads a serialized `Module` from the given `istream`. /// /// The istream must contain a serialized `Module`, exported via /// `torch::jit::ExportModule` in C++. TORCH_API Module load( std::istream& in, c10::optional<c10::Device> device = c10::nullopt, ExtraFilesMap& extra_files = default_extra_files); /// Loads a serialized `Module` from the given `filename`. /// /// The file stored at the location given in `filename` must contain a /// serialized `Module`, exported either via `ScriptModule.save()` in /// Python or `torch::jit::ExportModule` in C++. TORCH_API Module load( const std::string& filename, c10::optional<c10::Device> device = c10::nullopt, ExtraFilesMap& extra_files = default_extra_files); /// Loads a serialized `Module` from the given `rai`. /// /// The reader adapter, which is for customized input stream, must contain a /// serialized `Module`, exported either via `ScriptModule.save()` in /// Python or `torch::jit::ExportModule` in C++. TORCH_API Module load( std::unique_ptr<caffe2::serialize::ReadAdapterInterface> rai, c10::optional<c10::Device> device = c10::nullopt, ExtraFilesMap& extra_files = default_extra_files); TORCH_API IValue readArchiveAndTensors( const std::string& archive_name, c10::optional<TypeResolver> type_resolver, c10::optional<ObjLoader> obj_loader, c10::optional<at::Device> device, caffe2::serialize::PyTorchStreamReader& stream_reader); } // namespace jit } // namespace torch
[ "59596379+khado2359@users.noreply.github.com" ]
59596379+khado2359@users.noreply.github.com
573aacdf4ac64f69a68b74398aa0e4b53f047f73
341a8c7f2d028a6bac5675ce5a0a143316d69c6c
/datastructrue/tree/BTree.cpp
e43332135af12aa31d0ca07b3672b4b8fb590418
[]
no_license
pipixia626/algorithm
d7cba70d2cc0a0ef0f11b4320d851d309b5939b0
72d55d0c075f83ea9b5063bb23f59e789edd0478
refs/heads/master
2023-04-20T04:27:47.583611
2021-04-18T15:27:37
2021-04-18T15:27:37
359,181,792
0
0
null
null
null
null
UTF-8
C++
false
false
2,344
cpp
#include"BTree.h" #include<queue> #include<stack> #include<vector> #include<iostream> using namespace std; BiNode*BiTree::Create(BiNode*Tree){ char ch; cin>>ch; if(ch=='#')Tree=nullptr; else{ Tree=new BiNode(); Tree->data=ch; Tree->lchild=Create(Tree->lchild); Tree->rchild=Create(Tree->rchild); } return Tree; }; void BiTree::preOrder(){ PreOrder(root); } void BiTree::inOrder(){ InOrder(root); } void BiTree::postOrder(){ PostOrder(root); } void BiTree::PreOrder(BiNode*Tree){ if(Tree){ visit(Tree); PreOrder(Tree->lchild); PreOrder(Tree->rchild); } } void BiTree::InOrder(BiNode*Tree){ if(Tree){ PreOrder(Tree->lchild); visit(Tree); PreOrder(Tree->rchild); } } void BiTree::PostOrder(BiNode*Tree){ if(Tree){ PreOrder(Tree->lchild); PreOrder(Tree->rchild); visit(Tree); } } void BiTree::levelOrder(){ if(root==nullptr) return ; queue<BiNode*>q; q.push(root); while (!q.empty()) { BiNode*Node; Node=q.front(); q.pop(); visit(Node); if(Node->lchild!=nullptr)q.push(Node->lchild); if(Node->rchild!=nullptr)q.push(Node->rchild); } cout<<endl; } void BiTree::preOrder_stack(){ } void BiTree::inOrder_stack(){ } void BiTree::postOrder_stack(){ BiNode*prev=root; BiNode*cur=nullptr; stack<BiNode*>stack; while (prev!=nullptr||!stack.empty()) { if(prev){ //把左节点放进去 stack.push(prev); prev=prev->lchild; } else{ prev=stack.top(); //如果右子树没有遍历,遍历右子树 if(prev->rchild!=nullptr&&prev->rchild!=cur){ prev=prev->rchild; stack.push(prev); prev=prev->lchild; } //遍历根节点 else{ prev=stack.top(); stack.pop(); visit(prev); //更新最近遍历的节点 cur=prev; //将遍历后的节点设为null,进行下一个节点的遍历 prev=nullptr; } } } } void visit(BiNode* Node){ cout<<Node->data<<endl; cout<<"高度为"<<Node->data; }
[ "814151675@qq.com" ]
814151675@qq.com
f2f15b64f1e1a3495519b0985f0a753ecfc30139
57d30906de95e20fb45216925791cb809a11b7f1
/ase/tests/test_02_cclass/asetestcpp.cpp
4681ba60ee24238ba2bd36a20139eb02497219cc
[ "MIT" ]
permissive
ahiguti/ase
ad782902ca3a8713b155769413fc5d9fd537c347
f6bc5f337fe7df6eabf676660d9189d3c474150d
refs/heads/main
2021-06-13T17:39:25.280776
2012-06-15T21:01:17
2012-06-15T21:01:17
4,680,010
1
0
null
null
null
null
UTF-8
C++
false
false
1,903
cpp
#include <ase/asecclass.hpp> #include <stdio.h> #define DBG(x) struct testsvr { testsvr() : intval(0) { DBG(printf("testsvr %p\n", this)); } ~testsvr() { DBG(printf("~testsvr %p\n", this)); } void SetInt(int x) { intval = x; DBG(printf("s %p x=%d iv=%d\n", this, x, intval)); } int GetInt() { DBG(printf("g %p iv=%d\n", this, intval)); return intval; } void AddInt(int x) { intval += x; DBG(printf("a %p x=%d iv=%d\n", this, x, intval)); } void SetStr(const ase_string& x) { strval = x; } void ObjRef(testsvr& o) const { printf("ObjRef: o=%d s=%d\n", o.intval, intval); } void ObjCRef(const testsvr& o) const { printf("ObjCRef: o=%d s=%d\n", o.intval, intval); } void VariantRef(ase_variant& v) { printf("VRef: s=%s\n", v.get_string().data()); } void VariantCRef(const ase_variant& v) { printf("VCRef: s=%s\n", v.get_string().data()); } static ase_variant SFunc(const ase_variant *args, ase_size_type nargs) { ase_int r = 0; for (ase_size_type i = 0; i < nargs; ++i) { r += args[i].get_int(); } return r; } ase_variant IFunc(const ase_variant *args, ase_size_type nargs) { return SFunc(args, nargs).get_int() * intval; } int intval; ase_string strval; ase_variant objval; }; extern "C" { ASE_COMPAT_DLLEXPORT ase_variant ASE_DLLMain() { ase_cclass<testsvr>::initializer() .def("SetInt", &testsvr::SetInt) .def("GetInt", &testsvr::GetInt) .def("AddInt", &testsvr::AddInt) .def("SetStr", &testsvr::SetStr) .def("SFunc", &testsvr::SFunc) .def("ObjRef", &testsvr::ObjRef) .def("ObjCRef", &testsvr::ObjCRef) .def("VariantRef", &testsvr::VariantRef) .def("VariantCRef", &testsvr::VariantCRef) .def("IFunc", &testsvr::IFunc) .def("Create", &ase_cclass<testsvr>::create0) ; return ase_cclass<testsvr>::get_class(); } };
[ "ahiguti100@gmail.com" ]
ahiguti100@gmail.com
4f02c8b26646e6819ce3e26014eb70925d355ebc
f29a75693597687deb38fe4773d5e436724f3abb
/src/utility/Log.h
98bfdf9f561bd8334fa96790c58006fa4866e1af
[]
no_license
skipperno/NmeaApplication
5612cff21c9fc557fc5d53e4c36a8ab4b20eaf48
e8baed727f833e1d64909fa97036893e4838b603
refs/heads/master
2020-05-16T06:58:33.276571
2012-08-15T09:43:48
2012-08-15T09:43:48
1,705,540
0
0
null
null
null
null
UTF-8
C++
false
false
263
h
/* * Log.h * * Created on: Feb 8, 2012 * Author: ernad */ #ifndef LOG_H_ #define LOG_H_ class Log { public: Log(); virtual ~Log(); static void logDbgMsg(const char* msg, ...); static void logErrMsg(const char* msg, ...); }; #endif /* LOG_H_ */
[ "Ernad@skipper.no" ]
Ernad@skipper.no
91da2d5f1cda9c66ede407017eb941915c93d510
77780f9ccc465ae847c92c3a35c8933b0c63fa4e
/HDOJ/2135.cpp
e87303762ecab6e4a8358f3c18f8f07eeddd31a3
[]
no_license
changmu/StructureAndAlgorithm
0e41cf43efba6136849193a0d45dfa9eb7c9c832
d421179dece969bc1cd4e478e514f2de968c591a
refs/heads/master
2021-07-18T04:04:46.512455
2020-05-17T11:50:26
2020-05-17T11:50:26
30,492,355
1
0
null
null
null
null
ISO-8859-7
C++
false
false
1,509
cpp
////////////////////System Comment//////////////////// ////Welcome to Hangzhou Dianzi University Online Judge ////http://acm.hdu.edu.cn ////////////////////////////////////////////////////// ////Username: changmu ////Nickname: ³€ΔΎ ////Run ID: ////Submit time: 2014-10-13 13:26:28 ////Compiler: Visual C++ ////////////////////////////////////////////////////// ////Problem ID: 2135 ////Problem Title: ////Run result: Accept ////Run time:0MS ////Run memory:228KB //////////////////System Comment End////////////////// #include <stdio.h> #include <string.h> char G[12][12]; void solve(int n, int m) { int i, j; if(m == 0) { for(i = 1; i <= n; ++i) { for(j = 1; j <= n; ++j) printf("%c", G[i][j]); printf("\n"); } } else if(m == 1) { for(j = 1; j <= n; ++j) { for(i = n; i >= 1; --i) printf("%c", G[i][j]); printf("\n"); } } else if(m == 2) { for(i = n; i > 0; --i) { for(j = n; j > 0; --j) printf("%c", G[i][j]); printf("\n"); } } else if(m == 3) { for(j = n; j > 0; --j) { for(i = 1; i <= n; ++i) printf("%c", G[i][j]); printf("\n"); } } } int main() { int n, m, i, j; while(scanf("%d%d", &n, &m) == 2) { for(i = 1; i <= n; ++i) scanf("%s", G[i] + 1); m = (m % 4 + 4) % 4; solve(n, m); } return 0; }
[ "2276479303@qq.com" ]
2276479303@qq.com
11e2e2684b852d8ba4022fd2a24b1b2b9e7fa1c7
35f345dd1b4f6be564b7753b7b45d772b59a55b9
/Pong/word.cpp
46011b449f853f8256838314eb224eb1285f12ca
[]
no_license
shindelus/Pong
42a58e7a76f4759f133ae7432827463012d3d225
7fca7985fdc014b2dde4605deff43ce19713f6bb
refs/heads/master
2021-05-24T12:05:50.290936
2020-04-27T23:54:41
2020-04-27T23:54:41
253,550,559
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
#include <string> #include <iostream> #include <typeinfo> #include "word.h" #include "letters.h" #include "vertices.h" Word::Word(std::string wd, float lt, float btm, float ht, Vertices& v) { left = lt; bottom = btm; height = ht; width = ht * 0.6f; space = ht * 0.1f; float leftSpace = 0.0f; for (char const &c: wd) { Letters let1(c, left + leftSpace, bottom, height, width, v); leftSpace = leftSpace + width + space; } }
[ "shindelu@adobe.com" ]
shindelu@adobe.com
6322c477da3901d4b11a3ab7cc0971b73a9fdbfe
e76c4e2c511d69f7f4b0e49e4740726b253c72a1
/obstacle_runout/map/backup/MapItem.cpp
c41332be935c6d5fcc838d1612c9f4cfad0ad49a
[]
no_license
AlanHeiheihei/hill
179361710f939ee6517ca0aaf4ba95ee90b23c9a
c70545b67fcf2b644b5b60fdb95bd671a32136d3
refs/heads/master
2020-04-05T02:55:02.761557
2018-11-10T16:06:27
2018-11-10T16:06:27
156,494,262
0
0
null
null
null
null
UTF-8
C++
false
false
9,156
cpp
#include "MapItem.h" #include <QPainter> #include <QMessageBox> #include <cmath> #include <fstream> #include <sstream> #include <iostream> MapItem::MapItem() { } QRectF MapItem::boundingRect() const { qreal penWidth = 1; return QRectF(0 - penWidth / 2, 0 - penWidth / 2, itemWidth + penWidth, itemHeight + penWidth); } void MapItem::SetItemBoundary(double itemWidth, double itemHeight){ this->itemWidth = itemWidth; this->itemHeight = itemHeight; prepareGeometryChange(); LoadMapPixmap(); update(); } void MapItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(option); //标明该参数没有使用 Q_UNUSED(widget); if( !pixmap.isNull() ) { //pixmap = pixmap.scaled(pixmapWidth*pixmapMultiple, pixmapHeight*pixmapMultiple, Qt::KeepAspectRatio); //缩放并保持宽高比 painter->drawPixmap(0, 0, pixmapWidth*pixmapMultiple, pixmapHeight*pixmapMultiple, pixmap); } } MapItem::MapItem(const int itemWidth, const int itemHeight, const QString path, const int mapNumber) { this->itemWidth = itemWidth; this->itemHeight = itemHeight; this->path = path; this->mapNumber = mapNumber; LoadMapPixmap(); } void MapItem::SetPath(const QString path) { this->path = path; LoadMapPixmap(); } void MapItem::SetMapNumber(const int mapNumber) { this->mapNumber = mapNumber; LoadMapPixmap(); } void MapItem::LoadMapPixmap() { QString mapPath = path+QString("%1.pgm").arg(mapNumber); pixmap.load(mapPath); if( pixmap.isNull() ) { // QMessageBox::warning(this, QObject::tr("警告"), QObject::tr("图像不存在!"), QMessageBox::Ok); QMessageBox msg; msg.setWindowTitle(QObject::tr("错误")); msg.setText(QObject::tr("图像不存在!")); msg.setIcon(QMessageBox::Warning); msg.addButton(QObject::tr("确定"),QMessageBox::ActionRole); msg.exec(); } else { // 读取地图信息文件 QString mapMessagePath = path+QString("%1.yaml").arg(mapNumber); std::ifstream mapMessage(mapMessagePath.toStdString()); std::string message; std::stringstream sstream; while( std::getline(mapMessage, message) ) { sstream.clear(); sstream.str(""); sstream << message; std::string data; sstream >> data; if( data == "resolution:" ) { // 读取分辨率 sstream >> pixelDistance; // std::cout << "pixelDistance: " << pixelDistance << std::endl; } else if( data == "origin:" ) { // 读取地图原点 for( unsigned int i = 0; i < message.length(); i++ ) { if( (message[i] == ':') | (message[i] == '[') | (message[i] == ',') | (message[i] == ']') ) { message[i] = ' '; } } sstream.clear(); sstream.str(""); sstream << message; sstream >> data; sstream >> mapOriginPoint.x; mapOriginPoint.x = std::fabs(mapOriginPoint.x); sstream >> mapOriginPoint.y; mapOriginPoint.y = std::fabs(mapOriginPoint.y); // std::cout << "mapOriginPointX: " << mapOriginPointX << std::endl; // std::cout << "mapOriginPointY: " << mapOriginPointY << std::endl; } else { continue; } } // 获取原点全局信息 QString originPointMessagePath = path+QString("map_spoint.txt"); std::ifstream originPointMessage(originPointMessagePath.toStdString()); for( int i = 0; i <= mapNumber; i++ ) { std::getline(originPointMessage, message); } sstream.clear(); sstream.str(""); sstream << message; sstream >> globalOriginPoint.x; sstream >> globalOriginPoint.y; sstream >> globalOriginPointHeading; // 设置地图信息 pixmapWidth = pixmap.width(); //图片的宽度 pixmapHeight = pixmap.height(); //图片的高度 if( pixmapWidth > pixmapHeight ) { pixmapMultiple = (double)itemWidth / (double)pixmapWidth; } else { pixmapMultiple = (double)itemHeight / (double)pixmapHeight; } } } void MapItem::mousePressEvent(QGraphicsSceneMouseEvent *mouseEvent) { // 计算鼠标位置 // 坐标原点在地图左下角!!! PointCoordinates clickPoint; clickPoint.x = (mouseEvent->pos().x()-this->pos().x())*(pixelDistance/pixmapMultiple); clickPoint.y = (itemHeight-mouseEvent->pos().y()-this->pos().y())*(pixelDistance/pixmapMultiple); // 注意地图坐标与小车坐标X、Y是反的! // std::cout << "mouseEventPoint: " << mouseEvent->pos().x() << ", " << mouseEvent->pos().y() << std::endl; // std::cout << "clickPoint: " << clickPoint.x << ", " << clickPoint.y << std::endl; mouseMapPoint = PointClickToMap(clickPoint); mouseGlobalPoint = PointMapToGlobal(mouseMapPoint); // // 计算实际坐标 // mouseMapPoint.y = clickPoint.x*std::cos(globalOriginPointHeading) - clickPoint.y*std::sin(globalOriginPointHeading); // mouseMapPoint.x = clickPoint.y*std::cos(globalOriginPointHeading) + clickPoint.x*std::sin(globalOriginPointHeading); // mouseGlobalPoint.x = mouseMapPoint.x + globalOriginPoint.x; // mouseGlobalPoint.y = mouseMapPoint.y + globalOriginPoint.y; // std::cout << x << ", " << y << "\n" << mousePoint.x << ", " << mousePoint.y << std::endl; // PointCoordinates testPoint; // testPoint.x = mouseGlobalPoint.x; // testPoint.y = mouseGlobalPoint.y; // PointCoordinates resultPoint = PointGlobalToPixel(testPoint); // resultPoint = resultPoint; // QString message = QString("%1, %2").arg(resultPoint.x).arg(resultPoint.y); // QMessageBox msg; // msg.setWindowTitle(QObject::tr("坐标")); // msg.setText(message); // msg.setIcon(QMessageBox::Warning); // msg.addButton(QObject::tr("确定"),QMessageBox::ActionRole); // msg.exec(); } PointCoordinates MapItem::PointClickToMap(const PointCoordinates clickPoint) { PointCoordinates mapPoint; // 计算地图上实际坐标 mapPoint.x = clickPoint.x - mapOriginPoint.x; mapPoint.y = clickPoint.y - mapOriginPoint.y; PointCoordinates mapCorrectPoint; // 修正Heading后的坐标 mapCorrectPoint.x = mapPoint.y*std::cos(globalOriginPointHeading) + mapPoint.x*std::sin(globalOriginPointHeading); mapCorrectPoint.y = mapPoint.x*std::cos(globalOriginPointHeading) - mapPoint.y*std::sin(globalOriginPointHeading); // std::cout << "mapPoint: " << mapPoint.x << ", " << mapPoint.y << "\nmapCorrectPoint: " << mapCorrectPoint.x << ", " << mapCorrectPoint.y << std::endl; return mapCorrectPoint; } PointCoordinates MapItem::PointMapToGlobal(const PointCoordinates mapPoint) { PointCoordinates globalPoint; globalPoint.x = mapPoint.x + globalOriginPoint.x; globalPoint.y = mapPoint.y + globalOriginPoint.y; // std::cout << "globalPoint: " << globalPoint.x << ", " << globalPoint.y << std::endl << std::endl; return globalPoint; } PointCoordinates MapItem::GetMouseMapPoint() { return mouseMapPoint; } PointCoordinates MapItem::GetMouseGlobalPoint() { return mouseGlobalPoint; } PointCoordinates MapItem::PointGlobalToPixel(const PointCoordinates globalPoint){ // 全局坐标转修正地图坐标 PointCoordinates mapCorrectPoint; mapCorrectPoint.x = globalPoint.x - globalOriginPoint.x; mapCorrectPoint.y = globalPoint.y - globalOriginPoint.y; // std::cout << "TEST: mapCorrectPoint: " << mapCorrectPoint.x << ", " << mapCorrectPoint.y << std::endl; // 修正地图坐标转地图坐标 PointCoordinates mapPoint; mapPoint.x = mapCorrectPoint.y*std::cos(-globalOriginPointHeading) - mapCorrectPoint.x*std::sin(-globalOriginPointHeading); mapPoint.y = mapCorrectPoint.x*std::cos(-globalOriginPointHeading) + mapCorrectPoint.y*std::sin(-globalOriginPointHeading); // std::cout << "TEST: mapPoint: " << mapPoint.x << ", " << mapPoint.y << std::endl; // 地图坐标转鼠标点击坐标 PointCoordinates clickPoint; clickPoint.x = mapPoint.x + mapOriginPoint.x; clickPoint.y = mapPoint.y + mapOriginPoint.y; // std::cout << "TEST: clickPoint: " << clickPoint.x << ", " << clickPoint.y << std::endl; // 鼠标单击坐标转图像坐标 PointCoordinates pixelPoint; pixelPoint.x = (clickPoint.x/pixelDistance*pixmapMultiple)+this->pos().x(); pixelPoint.y = itemHeight-this->pos().y()-(clickPoint.y/pixelDistance*pixmapMultiple); // std::cout << "TEST: pixelPoint: " << pixelPoint.x << ", " << pixelPoint.y << std::endl << std::endl << std::endl; return pixelPoint; }
[ "4096649@qq.com" ]
4096649@qq.com
335357faeebe592212234ab7a2a161ae8690d6bf
433e639f430e7d2e15f9d72c5b4852acb4917abd
/bank/bank/accumulator.h
bfe20ae85eb3146a676317267851a43eff13d899
[]
no_license
LiuZhe6/ShopProject
d9b9b39c9dcc7dafbfca58b968eed1d393ccbb28
aea725a3e85bec7bb4f6b9c43ec8f2da7035c8fb
refs/heads/master
2020-03-23T04:13:12.644345
2018-07-17T04:00:23
2018-07-17T04:00:23
141,070,749
0
0
null
null
null
null
GB18030
C++
false
false
699
h
#pragma once //accumulator.h #ifndef _ACCUMULATOR_H__ #define _ACCUMULATOR_H__ #include "date.h" class Accumulator { private: Date lastDate; double value; double sum; public: Accumulator(const Date& date, double value) :lastDate(date), value(value), sum(0) {} double getSum(const Date& date)const { //计算按日期累加值 return sum + value*(date - lastDate); } void change(const Date& date, double value) { //按一次存取款变更修改累加值和value sum = getSum(date); lastDate = date; this->value = value; } void reset(const Date &date, double value) { //计息后累加值清0 lastDate = date; this->value = value; sum = 0; } }; #endif
[ "miuiclub@qq.com" ]
miuiclub@qq.com
84e0f48b446cf139414f32ffe51e516def74aaa1
3d89ee9ed8070dc1b4acb2a8a203c5ab4921b3be
/frmRepoint.h
076342180932a6395a59b4f356464e98bb73394d
[ "MIT" ]
permissive
interdpth/DoubleHelix-2
56d3c2a4ec9f569b2c7abdf624ffabd0a4eba58c
d494cc7957b7470b12779d2cde14b13285fa6396
refs/heads/master
2023-04-06T07:38:13.762296
2021-03-30T05:02:10
2021-03-30T05:02:10
156,651,568
1
1
null
null
null
null
UTF-8
C++
false
false
75
h
#pragma once class frmRepoint { public: frmRepoint(); ~frmRepoint(); };
[ "interdpth@gmail.com" ]
interdpth@gmail.com
a3aaa885bbe3dd244cc2e4a49c5afa842e812d22
91b87ab3a04be816e4fb7eb4762ce3ddf4104b4d
/utility/vil_algo_plus.h
b209debfdc54e6ddeeb568db17903e78d9bb87f4
[]
no_license
LiliMeng/MAVLocalization
7dae0f1e7c7b62ffb5a1a59dafdc9c6475fcdf37
2bb61644c5e208854a09d1b3a5aa0e2831d1df3f
refs/heads/master
2021-01-16T19:44:05.587631
2016-02-17T02:00:29
2016-02-17T02:00:29
51,674,054
0
1
null
2016-02-14T01:20:33
2016-02-14T01:20:31
null
UTF-8
C++
false
false
1,819
h
// // vil_algo_plus.h // QuadCopter // // Created by jimmy on 7/9/15. // Copyright (c) 2015 Nowhere Planet. All rights reserved. // #ifndef __QuadCopter__vil_algo_plus__ #define __QuadCopter__vil_algo_plus__ #include <vgl/vgl_point_2d.h> #include <vcl_vector.h> #include <vil/vil_image_view.h> class VilAlgoPlus { public: // 0, 1, 2, 3 of canny direction // 2 // 3 1 // 0 static int cannyDirection(double dx, double dy); // 3 2 1 // 4 * 0 // 5 6 7 // discrete direction from p1 to p2 static int octaveIndex(double dx, double dy); // scan direction from octative Index static vgl_vector_2d<int> scanDirectionFromOctaveIndex(int oct_index); // discrete direction into 8 directions. The direction is from p1 to p2 static vgl_vector_2d<int> scanDirection(const vgl_point_2d<double> & fromPt, const vgl_point_2d<double> & toPt); // pixels locate on the line static bool linePixels(const vgl_point_2d<double> & p0, const vgl_point_2d<double> & p1, vcl_vector<vgl_point_2d<double> > & linePts, int w, int h); // linear interpolate from center (1.0) to edge (0.0) static bool linearInterpolateFromCenter(int imageW, int imageH, vil_image_view<double> & wtImage); // points located in the line p0 -- p1 static bool linePixels(const vgl_point_2d<double> & p0, const vgl_point_2d<double> & p1, vcl_vector<vgl_point_2d<double> > & linePts); // fill a line in the image static bool fill_line(vil_image_view<vxl_byte> & image, const vgl_point_2d<double> & p1, const vgl_point_2d<double> & p2, const vcl_vector<vxl_byte> & colour); }; #endif /* defined(__QuadCopter__vil_algo_plus__) */
[ "jimmy@vpn23.cs.ubc.ca" ]
jimmy@vpn23.cs.ubc.ca
f0490c56d504d9ff8e39256cb635aec66cbd8c4c
b8d116c857b13991366b58674a4dd1a96412b5bf
/src/materialsystem/stdshaders/BlurFilterY.cpp
325e40690dee06f02209c4a3d4eebb84577cfd87
[ "MIT" ]
permissive
SCell555/hl2-asw-port
6eaa2a4f1f68f1dfb603657d469c42c85b2d9d1a
16441f599c6b2d3fd051ee2805cc08680dedbb03
refs/heads/master
2021-01-17T18:21:59.547507
2016-05-12T17:09:21
2016-05-12T17:09:21
49,386,904
3
1
null
2016-01-10T21:45:46
2016-01-10T21:45:44
null
WINDOWS-1252
C++
false
false
4,016
cpp
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // //===========================================================================// #include "BaseVSShader.h" #include "blurfilter_vs20.inc" #include "blurfilter_ps20b.inc" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" BEGIN_VS_SHADER_FLAGS( BlurFilterY, "Help for BlurFilterY", SHADER_NOT_EDITABLE ) BEGIN_SHADER_PARAMS SHADER_PARAM( BLOOMAMOUNT, SHADER_PARAM_TYPE_FLOAT, "1.0", "" ) SHADER_PARAM( FRAMETEXTURE, SHADER_PARAM_TYPE_TEXTURE, "_rt_SmallHDR0", "" ) SHADER_PARAM( KERNEL, SHADER_PARAM_TYPE_INTEGER, "0", "Kernel type" ) SHADER_PARAM( ENABLECLEARCOLOR, SHADER_PARAM_TYPE_BOOL, "0", "clear RGB channels to a solid color" ) SHADER_PARAM( CLEARCOLOR, SHADER_PARAM_TYPE_VEC3, "[0 0 0]", "clear color" ) END_SHADER_PARAMS SHADER_INIT { if ( params[BASETEXTURE]->IsDefined() ) { LoadTexture( BASETEXTURE ); } if ( !( params[BLOOMAMOUNT]->IsDefined() ) ) { params[BLOOMAMOUNT]->SetFloatValue(1.0); } if ( !( params[ KERNEL ]->IsDefined() ) ) { params[ KERNEL ]->SetIntValue( 0 ); } if ( !( params[ ENABLECLEARCOLOR ]->IsDefined() ) ) { params[ ENABLECLEARCOLOR ]->SetIntValue( 0 ); } if ( !( params[ CLEARCOLOR ]->IsDefined() ) ) { params[ CLEARCOLOR ]->SetVecValue( 0.0f, 0.0f, 0.0f ); } } SHADER_FALLBACK { return 0; } SHADER_DRAW { SHADOW_STATE { pShaderShadow->EnableDepthWrites( false ); pShaderShadow->EnableAlphaWrites( true ); pShaderShadow->EnableTexture( SHADER_SAMPLER0, true ); pShaderShadow->VertexShaderVertexFormat( VERTEX_POSITION, 1, 0, 0 ); //avoid srgb conversions to alleviate some of the srgb texture lookup problems pShaderShadow->EnableSRGBRead( SHADER_SAMPLER0, false ); pShaderShadow->EnableSRGBWrite( false ); DECLARE_STATIC_VERTEX_SHADER( blurfilter_vs20 ); SET_STATIC_VERTEX_SHADER_COMBO( KERNEL, params[ KERNEL ]->GetIntValue() ? 1 : 0 ); SET_STATIC_VERTEX_SHADER( blurfilter_vs20 ); DECLARE_STATIC_PIXEL_SHADER( blurfilter_ps20b ); SET_STATIC_PIXEL_SHADER_COMBO( KERNEL, params[ KERNEL ]->GetIntValue() ); SET_STATIC_PIXEL_SHADER_COMBO( CLEAR_COLOR, params[ ENABLECLEARCOLOR ]->GetIntValue() ); SET_STATIC_PIXEL_SHADER( blurfilter_ps20b ); if ( IS_FLAG_SET( MATERIAL_VAR_ADDITIVE ) ) EnableAlphaBlending( SHADER_BLEND_ONE, SHADER_BLEND_ONE ); } DYNAMIC_STATE { BindTexture( SHADER_SAMPLER0, BASETEXTURE, -1 ); // The temp buffer is 1/4 back buffer size ITexture *src_texture = params[BASETEXTURE]->GetTextureValue(); int height = src_texture->GetActualHeight(); float dY = 1.0f / height; // dY *= 0.4; float v[4]; // Tap offsets v[0] = 0.0f; v[1] = 1.3366f * dY; v[2] = 0; v[3] = 0; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, v, 1 ); v[0] = 0.0f; v[1] = 3.4295f * dY; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_1, v, 1 ); v[0] = 0.0f; v[1] = 5.4264f * dY; pShaderAPI->SetVertexShaderConstant( VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, v, 1 ); v[0] = 0.0f; v[1] = 7.4359f * dY; pShaderAPI->SetPixelShaderConstant( 0, v, 1 ); v[0] = 0.0f; v[1] = 9.4436f * dY; pShaderAPI->SetPixelShaderConstant( 1, v, 1 ); v[0] = 0.0f; v[1] = 11.4401f * dY; pShaderAPI->SetPixelShaderConstant( 2, v, 1 ); v[0] = v[1] = v[2] = params[BLOOMAMOUNT]->GetFloatValue(); pShaderAPI->SetPixelShaderConstant( 3, v, 1 ); v[0] = v[1] = v[2] = v[3] = 0.0; v[1] = dY; pShaderAPI->SetPixelShaderConstant( 4, v, 1 ); params[CLEARCOLOR]->GetVecValue( v, 3 ); v[3] = 0.0f; pShaderAPI->SetPixelShaderConstant( 5, v, 1 ); DECLARE_DYNAMIC_VERTEX_SHADER( blurfilter_vs20 ); SET_DYNAMIC_VERTEX_SHADER( blurfilter_vs20 ); DECLARE_DYNAMIC_PIXEL_SHADER( blurfilter_ps20b ); SET_DYNAMIC_PIXEL_SHADER( blurfilter_ps20b ); } Draw(); } END_SHADER
[ "kubci.rusnk645@gmail.com" ]
kubci.rusnk645@gmail.com
09aab9cb3c7c0e2f46633ece4a426575882726e9
752572bd6010ef068c4851b55a261a2122f29094
/aws-cpp-sdk-rds-data/include/aws/rds-data/RDSDataServiceClient.h
6a61e9a9fa3f61cd32a3db0d3b619c20b48b8b17
[ "Apache-2.0", "MIT", "JSON" ]
permissive
cnxtech/aws-sdk-cpp
9b208792b2e81b3a22a850c3d0fbf4724dc65a99
af8089f6277b8fec93c55a815c724444bd159a13
refs/heads/master
2023-08-15T02:01:42.569685
2019-05-08T20:39:01
2019-05-08T20:39:01
185,732,288
0
0
Apache-2.0
2023-07-22T05:12:44
2019-05-09T05:30:49
C++
UTF-8
C++
false
false
5,642
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/rds-data/RDSDataService_EXPORTS.h> #include <aws/rds-data/RDSDataServiceErrors.h> #include <aws/core/client/AWSError.h> #include <aws/core/client/ClientConfiguration.h> #include <aws/core/client/AWSClient.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/rds-data/model/ExecuteSqlResult.h> #include <aws/core/client/AsyncCallerContext.h> #include <aws/core/http/HttpTypes.h> #include <future> #include <functional> namespace Aws { namespace Http { class HttpClient; class HttpClientFactory; } // namespace Http namespace Utils { template< typename R, typename E> class Outcome; namespace Threading { class Executor; } // namespace Threading } // namespace Utils namespace Auth { class AWSCredentials; class AWSCredentialsProvider; } // namespace Auth namespace Client { class RetryStrategy; } // namespace Client namespace RDSDataService { namespace Model { class ExecuteSqlRequest; typedef Aws::Utils::Outcome<ExecuteSqlResult, Aws::Client::AWSError<RDSDataServiceErrors>> ExecuteSqlOutcome; typedef std::future<ExecuteSqlOutcome> ExecuteSqlOutcomeCallable; } // namespace Model class RDSDataServiceClient; typedef std::function<void(const RDSDataServiceClient*, const Model::ExecuteSqlRequest&, const Model::ExecuteSqlOutcome&, const std::shared_ptr<const Aws::Client::AsyncCallerContext>&) > ExecuteSqlResponseReceivedHandler; /** * AWS RDS DataService provides Http Endpoint to query RDS databases. */ class AWS_RDSDATASERVICE_API RDSDataServiceClient : public Aws::Client::AWSJsonClient { public: typedef Aws::Client::AWSJsonClient BASECLASS; /** * Initializes client to use DefaultCredentialProviderChain, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ RDSDataServiceClient(const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use SimpleAWSCredentialsProvider, with default http client factory, and optional client config. If client config * is not specified, it will be initialized to default values. */ RDSDataServiceClient(const Aws::Auth::AWSCredentials& credentials, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); /** * Initializes client to use specified credentials provider with specified client config. If http client factory is not supplied, * the default http client factory will be used */ RDSDataServiceClient(const std::shared_ptr<Aws::Auth::AWSCredentialsProvider>& credentialsProvider, const Aws::Client::ClientConfiguration& clientConfiguration = Aws::Client::ClientConfiguration()); virtual ~RDSDataServiceClient(); inline virtual const char* GetServiceClientName() const override { return "RDS Data"; } /** * Executes any SQL statement on the target database synchronously<p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rds-data-2018-08-01/ExecuteSql">AWS * API Reference</a></p> */ virtual Model::ExecuteSqlOutcome ExecuteSql(const Model::ExecuteSqlRequest& request) const; /** * Executes any SQL statement on the target database synchronously<p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rds-data-2018-08-01/ExecuteSql">AWS * API Reference</a></p> * * returns a future to the operation so that it can be executed in parallel to other requests. */ virtual Model::ExecuteSqlOutcomeCallable ExecuteSqlCallable(const Model::ExecuteSqlRequest& request) const; /** * Executes any SQL statement on the target database synchronously<p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/rds-data-2018-08-01/ExecuteSql">AWS * API Reference</a></p> * * Queues the request into a thread executor and triggers associated callback when operation has finished. */ virtual void ExecuteSqlAsync(const Model::ExecuteSqlRequest& request, const ExecuteSqlResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context = nullptr) const; void OverrideEndpoint(const Aws::String& endpoint); private: void init(const Aws::Client::ClientConfiguration& clientConfiguration); void ExecuteSqlAsyncHelper(const Model::ExecuteSqlRequest& request, const ExecuteSqlResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const; Aws::String m_uri; Aws::String m_configScheme; std::shared_ptr<Aws::Utils::Threading::Executor> m_executor; }; } // namespace RDSDataService } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
12a8841a781d8b8404697784a9955b70d0aa27f2
ae2b5043e288f6129a895373515f5db81d3a36a7
/xulrunner-sdk/include/nsIDOMGeoPosition.h
685173ba34eab08d3ababb2e0f2e2afc02cbbca4
[]
no_license
gh4ck3r/FirefoxOSInsight
c1307c82c2a4075648499ff429363f600c47276c
a7f3d9b6e557e229ddd70116ed2d27c4a553b314
refs/heads/master
2021-01-01T06:33:16.046113
2013-11-20T11:28:07
2013-11-20T11:28:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,156
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM /builds/slave/rel-m-rel-xr_lx_bld-0000000000/build/dom/interfaces/geolocation/nsIDOMGeoPosition.idl */ #ifndef __gen_nsIDOMGeoPosition_h__ #define __gen_nsIDOMGeoPosition_h__ #ifndef __gen_domstubs_h__ #include "domstubs.h" #endif #ifndef __gen_nsIDOMGeoPositionCoords_h__ #include "nsIDOMGeoPositionCoords.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIDOMGeoPosition */ #define NS_IDOMGEOPOSITION_IID_STR "dd9f7e81-0f74-4fb5-b361-37019bf60c3f" #define NS_IDOMGEOPOSITION_IID \ {0xdd9f7e81, 0x0f74, 0x4fb5, \ { 0xb3, 0x61, 0x37, 0x01, 0x9b, 0xf6, 0x0c, 0x3f }} class NS_NO_VTABLE nsIDOMGeoPosition : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMGEOPOSITION_IID) /* readonly attribute DOMTimeStamp timestamp; */ NS_IMETHOD GetTimestamp(DOMTimeStamp *aTimestamp) = 0; /* readonly attribute nsIDOMGeoPositionCoords coords; */ NS_IMETHOD GetCoords(nsIDOMGeoPositionCoords * *aCoords) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMGeoPosition, NS_IDOMGEOPOSITION_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMGEOPOSITION \ NS_IMETHOD GetTimestamp(DOMTimeStamp *aTimestamp); \ NS_IMETHOD GetCoords(nsIDOMGeoPositionCoords * *aCoords); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMGEOPOSITION(_to) \ NS_IMETHOD GetTimestamp(DOMTimeStamp *aTimestamp) { return _to GetTimestamp(aTimestamp); } \ NS_IMETHOD GetCoords(nsIDOMGeoPositionCoords * *aCoords) { return _to GetCoords(aCoords); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMGEOPOSITION(_to) \ NS_IMETHOD GetTimestamp(DOMTimeStamp *aTimestamp) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetTimestamp(aTimestamp); } \ NS_IMETHOD GetCoords(nsIDOMGeoPositionCoords * *aCoords) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetCoords(aCoords); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMGeoPosition : public nsIDOMGeoPosition { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMGEOPOSITION nsDOMGeoPosition(); private: ~nsDOMGeoPosition(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsDOMGeoPosition, nsIDOMGeoPosition) nsDOMGeoPosition::nsDOMGeoPosition() { /* member initializers and constructor code */ } nsDOMGeoPosition::~nsDOMGeoPosition() { /* destructor code */ } /* readonly attribute DOMTimeStamp timestamp; */ NS_IMETHODIMP nsDOMGeoPosition::GetTimestamp(DOMTimeStamp *aTimestamp) { return NS_ERROR_NOT_IMPLEMENTED; } /* readonly attribute nsIDOMGeoPositionCoords coords; */ NS_IMETHODIMP nsDOMGeoPosition::GetCoords(nsIDOMGeoPositionCoords * *aCoords) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIDOMGeoPosition_h__ */
[ "gh4ck3r@gmail.com" ]
gh4ck3r@gmail.com
79df94130c68ef6bdf676f3b588d652ba127f82c
ec02c5694c995bf9cfa6c24d27be1b3893e5a3f4
/framework/Armedroids/YesBtn.cpp
afc6f5073eb23f4418aa598df63a18d65ee17859
[]
no_license
lewdif/Portfolio
14bddb14105ea2a96b552e9f428876ede8a5182a
845c152cee38618b67b632675ab2ac67e41ebc42
refs/heads/master
2021-10-11T15:55:27.440374
2019-01-28T07:03:37
2019-01-28T07:03:37
110,644,502
0
0
null
null
null
null
UTF-8
C++
false
false
1,292
cpp
#include "YesBtn.h" #include "DeviceManager.h" namespace CompEngine { void YesBtn::Init() { gameObject->AddTag("QuitBtn"); btnCounter = false; sndCounter = false; imgRect.LeftTop = Vec2(0, 0); imgRect.RightBottom = Vec2(212, 100); if (!gameObject->GetComponent("Transform2D")) { gameObject->AddComponent(dynamic_cast<Component*>(&trans)); } if (!gameObject->GetComponent("Button")) { gameObject->AddComponent(dynamic_cast<Component*>(&button)); } gameObject->SetIsActive(false); } void YesBtn::Reference() { trans.SetPosition(470, 460, 0); trans.SetSize(imgRect.RightBottom.x, imgRect.RightBottom.y); button.SetPath("Yes.png"); button.SetSize(imgRect); } void YesBtn::Update() { if (button.GetStatus() == button.ON_CLICK) { if (btnCounter == false) { cout << "Yes!" << endl; DeviceMgr->ExitWindow(); } btnCounter = true; } else if (button.GetStatus() == button.HIGHLIGHT) { if (!sndCounter) { button.SetPath("YesOn.png"); SoundMgr->Play2D(".\\Resources\\Sounds\\Bubble1.wav", 1.0, false); } btnCounter = false; sndCounter = true; } else if (button.GetStatus() == button.NORMAL) { button.SetPath("Yes.png"); sndCounter = false; } } void YesBtn::LateUpdate() { } }
[ "june7250@naver.com" ]
june7250@naver.com
00f21f84769ea660556a7cb837c0f510bace97b8
68027e525081eb7168ddead73270660e0fb06f41
/lib/src/PvrtcConverter.h
0300f915a4e8de445c20ca97f326a1f61f054f26
[ "Apache-2.0" ]
permissive
christetreault/Cuttlefish
71908788e4a526f4f66754fe726594756ea66d57
6cc122ed6f1b7d1766f00552ddfcc21eabe627e1
refs/heads/master
2021-04-05T23:42:28.498338
2018-03-08T21:35:29
2018-03-09T15:30:13
124,447,663
0
0
Apache-2.0
2018-03-08T21:01:26
2018-03-08T21:01:26
null
UTF-8
C++
false
false
1,251
h
/* * Copyright 2017 Aaron Barany * * 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 <cuttlefish/Config.h> #include "Converter.h" #if CUTTLEFISH_HAS_PVRTC namespace pvrtexture { class CPVRTexture; } namespace cuttlefish { class PvrtcConverter : public Converter { public: static const unsigned int blockDim = 4; PvrtcConverter(const Texture& texture, const Image& image, Texture::Quality quality); unsigned int jobsX() const override {return 1;} unsigned int jobsY() const override {return 1;} void process(unsigned int x, unsigned int y) override; private: Texture::Format m_format; Texture::Quality m_quality; bool m_premultipliedAlpha; }; } // namespace cuttlefish #endif // CUTTLEFISH_HAS_PVRTC
[ "akb825@gmail.com" ]
akb825@gmail.com
d1ebe5a33bd263922d9c7985b7f30fe59aabdbcf
30f8fabceaac8b4e53bb668792fbfdf7058b0df5
/kw-release/client/tcpClient.cpp
f71274a82a3118d05d4ffa0669ad7fc1b63de1e1
[]
no_license
thund3rcake/Kolobok-wars
b8fbc82d7d0270e6025bfbf31aeb4399f10127f9
c1a03614ebe9d49f35c14eb52b05500337233704
refs/heads/master
2021-05-16T22:25:56.026400
2020-05-20T19:19:53
2020-05-20T19:19:53
250,494,522
0
1
null
null
null
null
UTF-8
C++
false
false
6,870
cpp
#include "TcpClient.h" #include<GameScene.h> /* * * TcpClient * */ TcpClient::TcpClient( const QHostAddress & server, quint16 port, QObject * parent, quint32 timeout ): QThread(parent), host(server), port(port), timeout(timeout), socket(nullptr), mode(TcpClient::None) {} TcpClient::~TcpClient() { setMode(Exit); wait(); if (socket) { delete socket; } } void TcpClient::setMode (Mode newMode) { QMutexLocker locker (& mutex); mode = newMode; if (!isRunning()) { start(); } else { condition.wakeOne(); } } void TcpClient::pushGameProperties(const GameProperties &option) { QMutexLocker locker ( &mutex); sendBuffer.enqueue(option); } void TcpClient::run() { Mode mode = getMode(); bool waitCond; while (true) { waitCond = true; switch (mode) { case Exit: return; case None: break; case Connect: connect(); waitCond = false; break; case Send: send(); waitCond = false; break; case Listen: waitResponse(); default: break; } mode = getMode(waitCond); } } void TcpClient::errorHandler(int errNo, const QString &message) { emit error(errNo, message); mutex.lock(); mode = None; mutex.unlock(); } void TcpClient::connect() { socket = new QTcpSocket(); socket -> connectToHost(host, port); if (!(socket -> waitForConnected(timeout))) { errorHandler(socket -> error(), socket -> errorString()); return; } if (!checkConnectionInfo()) { return; } mutex.lock(); mode = Listen; mutex.unlock(); emit connected(); } bool TcpClient::waitForDataAvailable( quint64 size, quint32 maxTime, bool noBytesIsError ) { while ((quint64)socket -> bytesAvailable() < size) { if (!(socket -> waitForReadyRead(maxTime))) { if (noBytesIsError) { errorHandler(socket -> error(), socket -> errorString()); socket -> disconnectFromHost(); } return false; } } return true; } bool TcpClient::checkConnectionInfo() { static QByteArray block; block.clear(); quint32 blockSize = 0; QDataStream blockStream(&block, QIODevice::OpenModeFlag::ReadOnly); blockStream.setVersion(Net::DataStreamVersion); QDataStream in(socket); in.setVersion(Net::DataStreamVersion); if(!waitForDataAvailable(sizeof(quint32), timeout)) { return false; } in >> blockSize; if(!waitForDataAvailable(blockSize, timeout)) { return false; } block.resize(blockSize); in >> block; QString signature; quint16 version = 0; quint16 subversion = 0; quint16 id = 0; blockStream >> signature; blockStream >> version; blockStream >> subversion; blockStream >> id; emit idGoten (id); qDebug() << "ID: " << id; if (signature != QStringSignature ) { errorHandler(socket -> error(), socket -> errorString()); socket -> disconnectFromHost(); return false; } else { if (version > Net::ProtVersion || subversion > Net::ProtSubversion) { errorHandler(-1, "Server version is " + QString().number(version, 10) + "." + QString().number(subversion, 10)); socket -> disconnectFromHost(); return false; } } GameProperties udpPortOption; QDataStream out (&block, QIODevice::WriteOnly); out.setVersion(Net::DataStreamVersion); udpPortOption.setQuintType(GameProperties::UdpPort); udpPortOption.setFirstQInt(0); while ( !udpPortOption.getFirstQInt()) { udpPortOption.setFirstQInt(static_cast<GameScene*>(parent()) -> getUdpPort()); usleep(3); } block.clear(); out << (quint32) 0; out << udpPortOption; out.device() -> seek(0); out << (quint32) (block.size() - sizeof(quint32)); socket -> write(block); socket -> waitForBytesWritten(10); return true; } void TcpClient::send() { if (socket -> state() != QAbstractSocket::ConnectedState) { emit error(-1, "Disconnected from the server"); return; } QByteArray block; static GameProperties dataForSend; QDataStream request(&block, QIODevice::WriteOnly); request.setVersion(Net::DataStreamVersion); mutex.lock(); for (int i = 0; i < sendBuffer.size(); ++i) { block.clear(); dataForSend = sendBuffer.dequeue(); request << (quint32) 0; request << dataForSend; request.device() -> seek(0); request << (quint32) (block.size() - sizeof(quint32)); socket -> write(block); socket -> waitForBytesWritten(10); } mutex.unlock(); if(!(socket -> waitForBytesWritten(timeout))) { errorHandler( socket -> error(), socket -> errorString()); socket -> disconnectFromHost(); return; } mutex.lock(); mode = Listen; mutex.unlock(); } void TcpClient::waitResponse() { QDataStream response (socket); response.setVersion(Net::DataStreamVersion); quint32 size = 0; while ((quint32) (socket -> bytesAvailable()) < sizeof(size)) { socket -> waitForReadyRead(50); if (QTcpSocket::ConnectedState != socket -> state()) { emit error (socket -> error(), "Disconnected from the server"); return; } } response >> size; while (socket -> bytesAvailable() < size) { socket -> waitForReadyRead(50); if (QTcpSocket::ConnectedState != socket -> state()) { emit error (socket -> error(), "Disconnected from the server"); return; } } NetDataContainer<GameProperties> * container = new NetDataContainer<GameProperties>(); GameProperties responseData; response >> responseData; container -> setOption(responseData); emit newProperty(container); } TcpClient::Mode TcpClient::getMode(bool waitCondition) { QMutexLocker locker (&mutex); if (waitCondition) condition.wait(&mutex, timeout); return mode; } void TcpClient::start() { QThread::start(); }
[ "sunnut@localhost.localdomain" ]
sunnut@localhost.localdomain
3fd74ea079fe148fdc5817b4e10106ceee5c5c1c
bd651e1157540a08dca1876e50dff901ee7a26cc
/Code/objecte.h
413988cb8bdbd9ec16e068adb291cbf83a669636
[]
no_license
hiteboar/Tributo_Zork
66a15adae89c2bfe0d563179fdea62efcadbf3c9
a665d1dbe65475e787e9c6513055bc0a864757be
refs/heads/master
2021-01-10T10:06:30.279312
2016-01-20T15:42:14
2016-01-20T15:42:14
46,378,038
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,305
h
#include <string> #include <list> class Objecte{ public: enum tipus_obj { CAPSA, CONSUMIBLE, ESTANDARD, OBJECTE }; protected: unsigned int id; std::string descripcio = ""; std::string nom; int plus_forca = 0; tipus_obj tipus = OBJECTE; public: Objecte(){}; virtual ~Objecte(){}; int getId() { return id; } std::string getDescr() { return descripcio; } std::string getNom(){ return nom; } int getPlusForca(){ return plus_forca; } tipus_obj getTipus(){ return tipus; } virtual std::string getInfo(){return nom + " " + descripcio;} // dona informació del contingut de l'objecte virtual bool accio_simple(std::string accio){return false;} // fa una accio sobre l'bjecte. Retorna true si s'ha pogut fer virtual bool accio_composta(std::string accio, Objecte* obj){ return false; } // idem anterior pero relacionat amb un altre objecte }; class Capsa : public Objecte{ private: bool obert = false; std::string accions[5]; std::list<Objecte*> objectes; bool conteObjecte(Objecte* obj); public: Capsa(int id, std::string nom, std::string descr, tipus_obj t_obj); ~Capsa(){} std::string getInfo(); void addObjecte(Objecte* obj); void rmObjecte(Objecte* obj); bool accio_simple(std::string accio); // fa una accio sobre l'bjecte. Retorna true si s'ha pogut fer bool accio_composta(std::string accio, Objecte* obj); // idem anterior pero relacionat amb un altre objecte }; class Consumible : public Objecte { public: Consumible(int id, std::string nom, std::string descr, int forca, tipus_obj t_obj); ~Consumible(){} int getForca(); std::string getInfo() {return nom + " " + descripcio;} bool accio_simple(std::string accio);// fa una accio sobre l'bjecte. Retorna true si s'ha pogut fer bool accio_composta(std::string accio, Objecte* obj){ return false; } // idem anterior pero relacionat amb un altre objecte }; class ObjEstandard : public Objecte{ public: ObjEstandard(int id, std::string nom, std::string descr, int forca, tipus_obj t_obj); ~ObjEstandard(){} std::string getInfo(){ return nom + " " + descripcio; } bool accio_simple(std::string accio){ return false; } // fa una accio sobre l'bjecte. Retorna true si s'ha pogut fer bool accio_composta(std::string accio, Objecte* obj){ return false; } // idem anterior pero relacionat amb un altre objecte };
[ "xisco.bosch.4a@gmail.com" ]
xisco.bosch.4a@gmail.com
b8810dbd1449b6ad3dfbcd22fb6ac92b3d38d583
bcb9cdda3f3d449be90846e6c4e81a9b9f5f0e99
/solutions/vadim_radyno/6/sources/minute_market_data/minute_market_data.h
a2a11004d0ddc76ae8ee04f9b38a1d710d8f150a
[]
no_license
marozau/cpp_craft_0314
4b264c6956f303e7b89cd86cc712c13e1654eb89
4c2e312bf8c4d75d675c889e2b23bb6cace7aadb
refs/heads/master
2021-01-20T05:04:51.826658
2014-06-12T13:49:52
2014-06-12T13:49:52
17,398,797
2
1
null
2014-07-09T06:51:42
2014-03-04T10:44:28
C++
UTF-8
C++
false
false
264
h
#ifndef _MINUTE_MARKET_DATA_H_ #define _MINUTE_MARKET_DATA_H_ #include <boost/thread.hpp> namespace minute_market_data { static boost::condition_variable cond_var_press_ctrl_c; class solution { public: void start(); }; } #endif // _MINUTE_MARKET_DATA_H_
[ "vadimradyno@gmail.com" ]
vadimradyno@gmail.com
8a252b2c5ada471b1335598c19309d5531486a53
02ae1489bfdc15f8fb3a79615092baefe693050e
/Kinect For SLR/kinectUI/kinectUI/CvvImage.h
a8642b03415c036623ae68306ec6bad4e9836c5d
[]
no_license
minimon/kinectHR
c312a758a5418697acd4f275d48f8cc079cc9e91
7dd745b2cebc136baac73014da97b72819874828
refs/heads/master
2020-05-30T12:55:17.426376
2014-09-21T08:04:38
2014-09-21T08:04:38
null
0
0
null
null
null
null
UHC
C++
false
false
2,092
h
// 헤더 파일 부분 #ifndef CVVIMAGE_CLASS_DEF #define CVVIMAGE_CLASS_DEF #include <opencv.hpp> #include "stdafx.h" /* CvvImage class definition */ class CvvImage { public: CvvImage(); virtual ~CvvImage(); /* Create image (BGR or grayscale) */ virtual bool Create( int width, int height, int bits_per_pixel, int image_origin = 0 ); /* Load image from specified file */ virtual bool Load( const char* filename, int desired_color = 1 ); /* Load rectangle from the file */ virtual bool LoadRect( const char* filename, int desired_color, CvRect r ); #if defined WIN32 || defined _WIN32 virtual bool LoadRect( const char* filename, int desired_color, RECT r ) { return LoadRect( filename, desired_color, cvRect( r.left, r.top, r.right - r.left, r.bottom - r.top )); } #endif /* Save entire image to specified file. */ virtual bool Save( const char* filename ); /* Get copy of input image ROI */ virtual void CopyOf( CvvImage& image, int desired_color = -1 ); virtual void CopyOf( IplImage* img, int desired_color = -1 ); IplImage* GetImage() { return m_img; }; virtual void Destroy(void); /* width and height of ROI */ int Width() { return !m_img ? 0 : !m_img->roi ? m_img->width : m_img->roi->width; }; int Height() { return !m_img ? 0 : !m_img->roi ? m_img->height : m_img->roi->height;}; int Bpp() { return m_img ? (m_img->depth & 255)*m_img->nChannels : 0; }; virtual void Fill( int color ); /* draw to highgui window */ virtual void Show( const char* window ); #if defined WIN32 || defined _WIN32 /* draw part of image to the specified DC */ virtual void Show( HDC dc, int x, int y, int width, int height, int from_x = 0, int from_y = 0 ); /* draw the current image ROI to the specified rectangle of the destination DC */ virtual void DrawToHDC( HDC hDCDst, RECT* pDstRect ); #endif protected: IplImage* m_img; }; typedef CvvImage CImage; #endif
[ "joong555@naver.com" ]
joong555@naver.com
45f5a3550b1d3823daffe3d09f0372259e184ded
c40e0367b54a158c2af4c7862bc4f9e2be9e7935
/stupid/posix/simple/inc/procesor.h
7ebd6024f1b9e6e6848d40727ceef639edba7332
[]
no_license
Kizarm/Stupid
f0623cb28e07c3b372c5a245f3db3c51d6853d4c
880ca5b557918a051104a0727c450b6bbc44f3dc
refs/heads/master
2022-09-12T21:15:56.912857
2022-08-20T13:08:38
2022-08-20T13:08:38
74,561,609
0
0
null
null
null
null
UTF-8
C++
false
false
14,286
h
/*###########################################################################*/ /*###########################################################################*/ /* */ /* implementace */ /* */ /*###########################################################################*/ /*###########################################################################*/ #if !defined(AFX_PROCESOR_H__INCLUDED_) #define AFX_PROCESOR_H__INCLUDED_ #include <stdio.h> #include "List.h" #define RAMORG (0x1000L<<3) extern int NetAdr; extern int MaxSpInModule; extern unsigned long RamPtr; extern long int AutoPtr; extern long int RomBegin,RamBegin; extern unsigned long RomEnd, RamEnd; /** * Abstraktní báze pro možnost rozšíření na jinou architekturu. * */ class BaseProcessor { public: BaseProcessor() {}; virtual ~BaseProcessor() {}; /*---------------------------------------------------------------------------*/ /* Pragma */ /*---------------------------------------------------------------------------*/ virtual void c_PragmaLj()=0; virtual void c_PragmaSj()=0; /*---------------------------------------------------------------------------*/ /* Vetveni */ /*---------------------------------------------------------------------------*/ virtual void c_if()=0; virtual void c_else()=0; virtual void c_endif()=0; virtual void c_caseof()=0; virtual void c_endcase()=0; /*---------------------------------------------------------------------------*/ /* Procedury a funkce */ /*---------------------------------------------------------------------------*/ virtual void c_procinit()=0; virtual void c_procend()=0; virtual void c_proced (LPOLOZKA * p, int pos)=0; virtual void c_func (LPOLOZKA * p, int pos)=0; virtual void c_preturn (LPOLOZKA * p)=0; virtual void c_freturn (LPOLOZKA * p)=0; virtual int c_retval()=0; /* offset vracene hodnoty na zas*/ virtual void c_pcall (char * u)=0; /* volani procedury */ virtual void c_fcall (char * u)=0; /* volani funkce */ virtual void c_skpb()=0; /* predani bitu jako skut.par. */ virtual void c_allot()=0; /* vytvoreni prostoru na zas. */ virtual void c_procerror()=0; /* MK */ /*---------------------------------------------------------------------------*/ /* Prace s adresami */ /*---------------------------------------------------------------------------*/ virtual void c_ldbaim (unsigned long int a)=0; /* load bit address */ virtual void c_ldaim (unsigned long int a)=0; /* load immediate addres */ virtual void c_ldbaa (unsigned long int a)=0; /* load bit address ze stacku */ virtual void c_ldaa (unsigned long int a)=0; /* load address ze stacku */ virtual void c_spba (unsigned long int a)=0; /* bit adr operandu na stacku */ virtual void c_spa (unsigned long int a)=0; /* adr operandu na stacku */ virtual void c_spar(unsigned long int a)=0; /* adr operandu na stacku - real*/ /*---------------------------------------------------------------------------*/ /* Operace pro typ BIT */ /*---------------------------------------------------------------------------*/ virtual void c_pushl()=0; /* uloz bit na zasobnik */ //--virtual void c_popl()=0; /* vyjmi bit ze zasobniku */ virtual void c_setbd (unsigned long int n)=0; /* nastav bit direct */ virtual void c_setbi()=0; /* nastav bit indirect */ virtual void c_resbd (unsigned long int n)=0; /* nuluj bit direct */ virtual void c_resbi()=0; /* nuluj bit indirect */ virtual void c_invbd (unsigned long int n)=0; /* neguj bit direct */ virtual void c_invbi()=0; /* neguj bit indirect */ virtual void c_ldbd (unsigned long int n)=0; /* nacti bit direct */ virtual void c_ldbi()=0; /* nacti bit indirect */ virtual void c_stbd (unsigned long int n)=0; /* uloz bit direct */ virtual void c_stbi()=0; /* uloz bit indirect */ virtual void c_orbd (unsigned long int n)=0; /* OR bit direct */ virtual void c_andbd (unsigned long int n)=0; /* AND bit direct */ virtual void c_norbd (unsigned long int n)=0; /* OR \bit direct */ virtual void c_nandbd (unsigned long int n)=0; /* AND \bit direct */ virtual void c_orb()=0; /* Logicky soucet */ virtual void c_andb()=0; /* Logicky soucin */ virtual void c_xorb()=0; /* Logicky xor */ virtual void c_notb()=0; /* Logicka negace */ virtual void c_retb()=0; /* Vraceni BIT jako hod. fce */ /*---------------------------------------------------------------------------*/ /* Operace pro typ WORD */ /*---------------------------------------------------------------------------*/ virtual void c_ldwim()=0; /* load immediate operand */ virtual void c_ldwd (unsigned long int n)=0; /* load direct operand */ virtual void c_ldwi()=0; /* load indirect operand */ virtual void c_stwd (unsigned long int n)=0; /* store direct operand */ virtual void c_stwi()=0; /* store indirect operand */ virtual void c_addwim()=0; /* pricteni immediate operandu */ virtual void c_addwd (unsigned long int n)=0; /* pricteni direct operandu */ virtual void c_addw()=0; /* pricteni indirect operandu */ virtual void c_addwp()=0; virtual void c_subwim()=0; /* odecteni immediate operandu */ virtual void c_subwd (unsigned long int n)=0; /* odecteni direct operandu */ virtual void c_subw()=0; /* odecteni indirect operandu */ virtual void c_mulwim()=0; /* nasobeni immediate oper. */ virtual void c_mulwd (unsigned long int n)=0; /* nasobeni direct oper. */ virtual void c_mulw()=0; /* nasobeni indirect oper. */ virtual void c_divwim()=0; /* deleni immediate oper. */ virtual void c_divwd (unsigned long int n)=0; /* deleni direct oper. */ virtual void c_divw()=0; /* deleni indirect oper. */ virtual void c_newim()=0; /* immediate nerovno */ virtual void c_eqwim()=0; /* immediate rovno */ virtual void c_stimmd (unsigned long)=0; /* immediate uloz do direct */ virtual void c_ltw()=0; /* mensi */ virtual void c_lew()=0; /* mensi nebo rovno */ virtual void c_gtw()=0; /* vetsi */ virtual void c_gew()=0; /* vetsi nebo rovno */ virtual void c_eqw()=0; /* rovno */ virtual void c_new()=0; /* nerovno */ virtual void c_wtor()=0; /* konverze na REAL */ /*---------------------------------------------------------------------------*/ /* Operace pro typ INT */ /*---------------------------------------------------------------------------*/ virtual void c_muliim()=0; /* nasobeni immediate oper. */ virtual void c_mulid (unsigned long int n)=0; /* nasobeni direct oper. */ virtual void c_muli()=0; /* nasobeni indirect oper. */ virtual void c_diviim()=0; /* deleni immediate oper. */ virtual void c_divid (unsigned long int n)=0; /* deleni direct oper. */ virtual void c_divi()=0; /* deleni indirect oper. */ virtual void c_chsi()=0; /* zmena znamenka */ virtual void c_absi()=0; /* absolutni hodnota */ virtual void c_swap()=0; /* prohozeni wordu */ virtual void c_lti()=0; /* mensi */ virtual void c_lei()=0; /* mensi nebo rovno */ virtual void c_gti()=0; /* vetsi */ virtual void c_gei()=0; /* vetsi nebo rovno */ virtual void c_itor()=0; /* konverze na REAL */ virtual void c_disp (int)=0; /* zobrazeni */ virtual void c_dispb()=0; /* zobrazeni */ virtual void c_prnt (int)=0; /* tisk */ virtual void c_prntb()=0; /* tisk */ /*---------------------------------------------------------------------------*/ /* Operace pro typ REAL */ /*---------------------------------------------------------------------------*/ virtual void c_ldrim()=0; /* load immediate operand */ virtual void c_ldri()=0; /* load indirect operand */ virtual void c_stri()=0; /* store indirect operand */ virtual void c_addr()=0; /* pricteni indirect operandu */ virtual void c_subr()=0; /* odecteni indirect operandu */ virtual void c_mulr()=0; /* nasobeni indirect oper. */ virtual void c_divr()=0; /* deleni indirect oper. */ virtual void c_chsr()=0; /* zmena znamenka */ virtual void c_absr()=0; /* absolutni hodnota */ virtual void c_truncr()=0; /* cela cast */ //--virtual void c_fracr()=0; /* necela cast */ virtual void c_ltr()=0; /* mensi */ virtual void c_ler()=0; /* mensi nebo rovno */ virtual void c_gtr()=0; /* vetsi */ virtual void c_ger()=0; /* vetsi nebo rovno */ virtual void c_eqr()=0; /* rovno */ virtual void c_ner()=0; /* nerovno */ virtual void c_rtoi()=0; /* konverze na INT */ virtual void c_rtow()=0; /* konverze na WORD */ virtual void c_andwim()=0; /* and immediate oper. */ virtual void c_andwd (unsigned long int n)=0; /* and direct oper. */ virtual void c_andw()=0; /* and indirect oper. */ virtual void c_orwim()=0; /* or immediate oper. */ virtual void c_orwd (unsigned long int n)=0; /* or direct oper. */ virtual void c_orw()=0; /* or indirect oper. */ virtual void c_xorwim()=0; /* xor immediate oper. */ virtual void c_xorwd (unsigned long int n)=0; /* xor direct oper. */ virtual void c_xorw()=0; /* xor indirect oper. */ /*---------------------------------------------------------------------------*/ /* Zobrazeni retezce */ /*---------------------------------------------------------------------------*/ virtual void c_testpole()=0; /* otestovani indexu na max */ virtual void c_disps (char * u)=0; /* zobrazeni textove konstanty */ virtual void c_prnts (char * u)=0; /* tisk textove konstanty */ /*---------------------------------------------------------------------------*/ /* Prace s virtuali pameti */ /*---------------------------------------------------------------------------*/ virtual void c_memwrite()=0; /* primy zapis do pameti */ virtual void c_memread()=0; /* prime cteni z pameti */ /*---------------------------------------------------------------------------*/ virtual void c_unknown (char * u)=0; /* kdyz nerozumi prikazu */ }; extern FILE * mf; extern BaseProcessor * BaseProcessorPtr; #endif // AFX_PROCESOR_H__INCLUDED_
[ "mrazik@volny.cz" ]
mrazik@volny.cz
d05a7b3bc0957cac0a52ae8a01c126d2d365663c
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/src/tools/wfterrain.cc
e93fca4e6cd4940c3785d7a615b01cb5e43d7be0
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,375
cc
//------------------------------------------------------------------- // wfterrain.cc // Generate height map for spherical terrain renderer // from 3d model. // Depends on Nebula stuff. // // 26-Oct-00 floh rewritten to wfObject // // (C) 2000 A.Weissflog //------------------------------------------------------------------- #include <math.h> #include "kernel/nkernelserver.h" #include "gfx/nbmpfile.h" #include "mathlib/triangle.h" #include "tools/wfobject.h" #include "tools/wftools.h" #ifndef PI #define PI 3.14159265f #endif static int NumFaces = 0; static triangle *TriArray = NULL; static float *HeightArray = NULL; static float MaxRadius = 0.0f; //------------------------------------------------------------------- // gen_tri_array() // Generate array of vector3 objects with triangle data from // wavefront file. Also determine max radius. // 07-Apr-00 floh created // 26-Oct-00 floh rewritten to wfobject //------------------------------------------------------------------- void gen_tri_array(wfObject& src) { n_assert(TriArray == NULL); NumFaces = src.f_array.size(); TriArray = new triangle[NumFaces]; MaxRadius = 0.0f; vector<wfFace>::iterator f_src; int fi; for (fi=0,f_src=src.f_array.begin(); f_src!=src.f_array.end(); f_src++,fi++) { vector3 v[3]; int i; for (i=0; i<3; i++) { v[i] = src.v_array.at(f_src->points.at(i).v_index).v; float l = v[i].len(); if (l > MaxRadius) MaxRadius = l; } TriArray[fi].set(v[0],v[1],v[2]); } // increase max radius minimally to avoid rounding errors // later on MaxRadius *= 2.0f; fprintf(stderr,"-> num faces: %d\n", NumFaces); fprintf(stderr,"-> max radius: %f\n", MaxRadius); } //------------------------------------------------------------------- // gen_height_array() // Generate spherical height array by shooting rays from a sphere // into the polygon soup and checking for the first intersection. // 07-Apr-00 floh created //------------------------------------------------------------------- void gen_height_array(int res) { n_assert(HeightArray == NULL); HeightArray = new float[res*res]; int i,j; float theta,rho; float dt = PI / float(res); float dr = (2.0f*PI) / float(res); fprintf(stderr,"-> generating height array...\n"); for (i=0,rho=0.0f; i<res; i++, rho+=dr) { for (j=0,theta=0.0f; j<res; j++, theta+=dt) { // generate a bunch of rays from midpoint // outwards, in case one of them misses the other // ones will take over vector3 v0(0.0f,0.0f,0.0f); vector3 v[3]; float sin_theta,cos_theta,sin_rho,cos_rho; float radius = MaxRadius; sin_theta = (float) sin(theta); cos_theta = (float) cos(theta); sin_rho = (float) sin(rho); cos_rho = (float) cos(rho); v[0].set(sin_theta*sin_rho*radius, cos_theta*radius, sin_theta*cos_rho*radius); sin_theta = (float) sin(theta-0.005f); cos_theta = (float) cos(theta-0.005f); sin_rho = (float) sin(rho); cos_rho = (float) cos(rho); v[1].set(sin_theta*sin_rho*radius, cos_theta*radius, sin_theta*cos_rho*radius); sin_theta = (float) sin(theta); cos_theta = (float) cos(theta); sin_rho = (float) sin(rho-0.005f); cos_rho = (float) cos(rho-0.005f); v[2].set(sin_theta*sin_rho*radius, cos_theta*radius, sin_theta*cos_rho*radius); // check for intersection with triangle soup, remember maximum radius float max_t = 0.0f; int k; bool has_intersected = false; for (k=0; k<NumFaces; k++) { int l; for (l=0; l<3; l++) { line3 line(v[l],v0); float t; if (TriArray[k].intersect(line,t)) { t = 1.0f - t; if (t>max_t) max_t=t; has_intersected = true; } } } if (!has_intersected) { fprintf(stderr,"NO INTERSECTION!\n"); } HeightArray[i*res+j] = max_t * 2.0f; } fprintf(stderr,"."); fflush(stderr); } fprintf(stderr,"\n"); } //------------------------------------------------------------------- // gen_bitmap() // Generate bitmap from height array. // 10-Apr-00 floh created //------------------------------------------------------------------- bool gen_bitmap(const char *fname, int res) { fprintf(stderr,"-> writing bmp file...\n"); nBmpFile bmp; bmp.SetWidth(res); bmp.SetHeight(res); if (bmp.Open(fname,"wb")) { int buf_size = res*3+4; uchar *buf = new uchar[buf_size]; int x,y; for (y=0; y<res; y++) { float *heights = &(HeightArray[res*y]); for (x=0; x<res; x++) { ushort height16 = (ushort) (heights[x] * ((1<<16)-1)); buf[x*3+0] = 0; buf[x*3+1] = (uchar) (height16 >> 8); buf[x*3+2] = (uchar) (height16 & 0xff); } bmp.WriteLine(buf); } delete buf; bmp.Close(); return true; } return false; } //------------------------------------------------------------------- int main(int argc, char *argv[]) { nKernelServer *ks = new nKernelServer; bool help; long retval = 0; int res; const char *fname; fprintf(stderr,"-> wfterrain\n"); // check args help = wf_getboolarg(argc, argv, "-help"); res = wf_getintarg(argc,argv, "-res", 128); fname = wf_getstrarg(argc,argv, "-fname", "hmap.bmp"); if (help) { fprintf(stderr, "wfterrain [-help] [-res] [-fname]\n" "(C) 2000 Andre Weissflog\n" "Generate height map for spherical terrain renderer from 3d model.\n" "-help -- show help\n" "-res -- resolution of heightmap (def 128)\n" "-fname -- filename of output file (24 bpp BMP, def hmap.bmp\n"); return 0; } wfObject src; FILE *in, *out; if (!wf_openfiles(argc, argv, in, out)) { fprintf(stderr,"file open failed!\n"); retval = 10; goto ende; } // load source object fprintf(stderr,"loading...\n"); if (!src.load(in)) { fprintf(stderr,"Load failed!\n"); retval = 10; goto ende; } // the objects triangle soup gen_tri_array(src); gen_height_array(res); gen_bitmap(fname,res); wf_closefiles(in, out); ende: if (TriArray) delete[] TriArray; if (HeightArray) delete[] HeightArray; fprintf(stderr,"<- wfterrain\n"); delete ks; return retval; } //------------------------------------------------------------------- // EOF //-------------------------------------------------------------------
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
plushe@411252de-2431-11de-b186-ef1da62b6547
1528f4f88c97429239f309765358acfd04caf206
606ab028d34ca4bcdde91515aefdfc8b7e82df22
/moled/src/scan.cpp
16cfc864f612bdd7e6469621de42ce6db1a097d4
[ "Apache-2.0" ]
permissive
lcamara/mole
bcc91ceda0759f8b2bd9b30a009684b3895c02d5
0116ed880aa537598357267526d8ecb34f5a177f
refs/heads/master
2020-12-29T02:55:26.970277
2011-04-26T21:01:59
2011-04-26T21:01:59
1,698,002
0
0
null
null
null
null
UTF-8
C++
false
false
7,139
cpp
/* * Mole - Mobile Organic Localisation Engine * Copyright 2010 Nokia Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "scan.h" const double avg_stddev = 1.0; int id_counter = 0; int scan_count = 0; AP_Reading::AP_Reading (QString _bssid, QString _ssid, quint32 _frequency, quint32 _level) : bssid (_bssid.toLower()), ssid (_ssid), frequency (_frequency), level (_level) { } AP_Reading::AP_Reading (AP_Reading *reading) : bssid (reading->bssid), ssid (reading->ssid), frequency (reading->frequency), level (reading->level) { } AP_Scan::AP_Scan (AP_Scan *scan) : readings (new QList<AP_Reading*> ()), stamp (new QDateTime (*scan->stamp)) { //stamp = new QDateTime (*scan->stamp); //readings = new QList<AP_Reading*> (); id = id_counter++; scan_count++; qDebug () << "SCAN copy create " << id << " out " << scan_count; for (int i = 0; i < scan->readings->size(); i++) { AP_Reading *reading = new AP_Reading (scan->readings->at(i)); readings->append (reading); } readings_map = NULL; } AP_Scan::AP_Scan (QList<AP_Reading*> *_readings, QDateTime *_stamp) : readings (_readings), stamp (_stamp) { id = id_counter++; scan_count++; qDebug () << "SCAN readings create " << id << " out " << scan_count; readings_map = NULL; } // used by binder to test for uniqueness bool AP_Scan::is_same_scan (AP_Scan *scan) { if (readings_map == NULL) { readings_map = new QMap<QString,quint32> (); for (int i = 0; i < readings->size(); i++) { readings_map->insert (readings->at(i)->bssid,readings->at(i)->level); //qDebug () << "map " << readings->at(i)->bssid //<< " " << readings->at(i)->level; } } for (int i = 0; i < scan->readings->size(); i++) { if (!readings_map->contains (scan->readings->at(i)->bssid)) { //qDebug () << "!same " << scan->readings->at(i)->bssid; return false; } if (readings_map->value(scan->readings->at(i)->bssid) != scan->readings->at(i)->level) { //qDebug () << "!same " << scan->readings->at(i)->bssid //<< " " << readings_map->value(scan->readings->at(i)->bssid) //<< " " << scan->readings->at(i)->level; return false; } } return true; } QDebug operator<<(QDebug dbg, const AP_Reading &reading) { dbg.nospace() << reading.bssid << " " << reading.ssid << " " << reading.frequency << " " << reading.level; return dbg.space(); } QDebug operator<<(QDebug dbg, const AP_Scan &scan) { dbg.nospace() << "c=" << scan.readings->size(); for (int i = 0; i < scan.readings->size(); i++) { AP_Reading *reading = new AP_Reading (scan.readings->at(i)); dbg.nospace() << " [" << *reading << "]"; //dbg.nospace() << "[" << "r" << "] "; } return dbg.space(); } AP_Scan::~AP_Scan () { qDebug () << "SCAN deleting scan " << id << " out " << scan_count; scan_count--; for (int i = 0; i < readings->size(); i++) { delete readings->at(i); } delete readings; delete stamp; if (readings_map != NULL) { delete readings_map; } } MacDesc::MacDesc () { clear (); } void MacDesc::clear () { max = 100; } int MacDesc::get_count() { return rssi_list.size(); } void MacDesc::set_weight(double _weight) { Q_ASSERT (_weight <= 1.0); Q_ASSERT (_weight >= 0.0); weight = _weight; } void MacDesc::recalculate_stats () { if (rssi_list.size() == 0) { clear (); return; } if (rssi_list.size() == 1) { max = rssi_list[0]; mean = rssi_list[0]; stddev = avg_stddev; return; } // first compute mean mean = 0.; for (int i = 0; i < rssi_list.size(); i++) { mean += rssi_list[i]; } mean = mean / rssi_list.size(); // next compute stddev double sq_sum = 0.; for (int i = 0; i < rssi_list.size(); i++) { double deviation = rssi_list[i] - mean; sq_sum += deviation * deviation; } double var = sq_sum / (rssi_list.size()-1); stddev = sqrt (var); // spread out or narrow down the stddev for macs with few readings double factor = (double) rssi_list.size(); stddev = ( (factor - 1) * stddev + avg_stddev ) / factor; // debugging /* QString values; values.append ("[ "); for (int i = 0; i < rssi_list.size(); i++) { values.append (QString::number(rssi_list[i])); values.append (" "); } values.append ("]"); */ // qDebug () << "mean= " << mean << " stddev= " << stddev // << " count= " << rssi_list.size(); Q_ASSERT (stddev > 0); //<< values; } void MacDesc::add_reading (int rssi) { rssi_list.append (rssi); recalculate_stats (); } void MacDesc::drop_reading (int rssi) { QMutableListIterator<int> i (rssi_list); bool removed = false; while (i.hasNext() && !removed) { int val = i.next(); if (val == rssi) { i.remove(); removed = true; } } if (!removed) { qFatal ("drop reading bug"); } recalculate_stats (); } // This scan is being added to the localizer. // put max rssi and count as value for each mac (=key) void AP_Scan::add_active_macs (QMap<QString,MacDesc*> *active_macs) { QListIterator<AP_Reading *> i (*readings); while (i.hasNext()) { AP_Reading *reading = i.next(); if (!active_macs->contains (reading->bssid)) { active_macs->insert (reading->bssid, new MacDesc()); } active_macs->value(reading->bssid)->add_reading (reading->level); } recalculate_weights (active_macs); } void AP_Scan::recalculate_weights (QMap<QString,MacDesc*> *active_macs) { QMapIterator<QString,MacDesc*> i (*active_macs); int ap_scan_count = 0; while (i.hasNext()) { i.next(); ap_scan_count += i.value()->get_count(); } if (ap_scan_count == 0) { qWarning () << "No scans found in scan"; return; } i.toFront(); while (i.hasNext()) { i.next(); double weight = i.value()->get_count() / (double) ap_scan_count; i.value()->set_weight (weight); } } // This scan is being removed from the localizer. void AP_Scan::remove_inactive_macs (QMap<QString,MacDesc*> *active_macs) { QListIterator<AP_Reading *> i (*readings); while (i.hasNext()) { AP_Reading *reading = i.next(); if (active_macs->contains (reading->bssid)) { MacDesc *mac_desc = active_macs->value (reading->bssid); mac_desc->drop_reading (reading->level); // we don't see this mac anymore if (mac_desc->get_count() == 0) { active_macs->remove(reading->bssid); delete mac_desc; } } else { qWarning() << "active_macs did not contain " << reading->bssid; } } recalculate_weights (active_macs); } int AP_Scan::size () { return readings->size(); }
[ "ledlie@csail.mit.edu" ]
ledlie@csail.mit.edu
d81c26843691c04c0d2377b48b220ae373e85134
d45eae1d7d8a3b03266ca717ee2528a39ce8fe9c
/DFRobot_BosonAdcModule.h
234fb05231f03753a85da324b947857aa70d2cad
[ "MIT" ]
permissive
cdjq/DFRobot_BosonADCModule
d9711d1c20d22fada45c1a160d4326bd32e94b9a
a0120d66dacd42d18532a5a46b64ba56bc83c960
refs/heads/master
2023-08-27T04:36:34.253728
2021-10-18T08:22:46
2021-10-18T08:22:46
417,345,219
0
1
null
null
null
null
UTF-8
C++
false
false
5,044
h
/*! * @file DFRobot_BosonADCModule.h * @brief Define infrastructure of DFRobot_BosonADCModule class * @details 获取模块基本信息, 获取模拟量A1和A2 * @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) * @license The MIT License (MIT) * @author [qsjhyy](yihuan.huang@dfrobot.com) * @version V1.0 * @date 2021-10-12 * @url https://github.com/DFRobot/DFRobot_BosonADCModule */ #ifndef __DFROBOT_BOSON_ADC_MODULE_H__ #define __DFROBOT_BOSON_ADC_MODULE_H__ #include <Arduino.h> #include <Wire.h> // #define ENABLE_DBG //!< 打开这个宏, 可以看到程序的详细运行过程 #ifdef ENABLE_DBG #define DBG(...) {Serial.print("[");Serial.print(__FUNCTION__); Serial.print("(): "); Serial.print(__LINE__); Serial.print(" ] "); Serial.println(__VA_ARGS__);} #else #define DBG(...) #endif #define BOSON_ADC_MODULE_DEFAULT_IIC_ADDR uint8_t(0x06) ///< 默认的IIC通信地址 #define BOSON_ADC_MODULE_PID uint16_t(0xC03F) ///< 模块的PID (BOS0063)(最高两位作为种类判断00:SEN、01:DFR、10:TEL、11:BOS, 后面14位作为num) /* BOSON_ADC_MODULE register address */ #define BOSON_ADC_MODULE_PID_MSB_REG uint8_t(0x00) ///< 模块的PID存储寄存器, 默认值0xC03F (最高两位作为种类判断00:SEN、01:DFR、10:TEL、11:BOS, 后面14位作为num) #define BOSON_ADC_MODULE_PID_LSB_REG uint8_t(0x01) #define BOSON_ADC_MODULE_VID_MSB_REG uint8_t(0x02) ///< 模块的VID存储寄存器, 默认值0x3343(代表厂商为DFRobot) #define BOSON_ADC_MODULE_VID_LSB_REG uint8_t(0x03) #define BOSON_ADC_MODULE_VERSION_MSB_REG uint8_t(0x04) ///< 固件版本号存储寄存器:0x0100代表V0.1.0.0 #define BOSON_ADC_MODULE_VERSION_LSB_REG uint8_t(0x05) #define BOSON_ADC_MODULE_ADDR_REG uint8_t(0x07) ///< 模块的通信地址存储寄存器, 默认值0x06 #define BOSON_ADC_MODULE_ADC1_MSB_REG uint8_t(0x08) ///< 模拟信号A1 #define BOSON_ADC_MODULE_ADC1_LSB_REG uint8_t(0x09) #define BOSON_ADC_MODULE_ADC2_MSB_REG uint8_t(0x0A) ///< 模拟信号A2 #define BOSON_ADC_MODULE_ADC2_LSB_REG uint8_t(0x0B) class DFRobot_BosonADCModule { public: #define NO_ERR 0 ///< No error #define ERR_DATA_BUS (-1) ///< 数据总线错误 #define ERR_IC_VERSION (-2) ///< 芯片版本不匹配 /** * @struct sBasicInfo_t * @brief 传感器的基本设备信息存储结构体 */ typedef struct { uint16_t PID; /**< 模块的PID, 默认值0xC03F (最高两位作为种类判断00: SEN、01: DFR、10: TEL、11:BOS, 后面14位作为num)(BOS0063) */ uint16_t VID; /**< 模块的VID, 默认值0x3343(代表厂商为DFRobot) */ uint16_t version; /**< 固件版本号: 0x0100代表V0.1.0.0 */ uint8_t iicAddr; /**< 模块的通信地址, 默认值0x06 */ }sBasicInfo_t; public: /** * @fn DFRobot_BosonADCModule * @brief 构造函数 * @param iicAddr BosonAdcModule IIC communication address * @param pWire Wire.h里定义了Wire对象, 因此使用&Wire就能够指向并使用Wire中的方法 * @return None */ DFRobot_BosonADCModule(uint8_t iicAddr=BOSON_ADC_MODULE_DEFAULT_IIC_ADDR, TwoWire *pWire = &Wire); /** * @fn begin * @brief 初始化函数 * @return int类型, 表示返回初始化的状态 * @retval 0 NO_ERROR * @retval -1 ERR_DATA_BUS * @retval -2 ERR_IC_VERSION */ int begin(void); /** * @fn refreshBasicInfo * @brief 重新从传感器获取其基本信息, 并缓存到存储信息的结构体basicInfo里面 * @n basicInfo结构体的成员: PID, VID, version, iicAddr * @return None */ void refreshBasicInfo(void); /** * @fn getAnalogSignalA1 * @brief 获取模拟信号A1 * @return 返回值范围为: 0-1023 */ uint16_t getAnalogSignalA1(void); /** * @fn getAnalogSignalA2 * @brief 获取模拟信号A2 * @return 返回值范围为: 0-1023 */ uint16_t getAnalogSignalA2(void); protected: /***************** 寄存器读写接口 ******************************/ /** * @fn writeReg * @brief 通过IIC总线写入寄存器值 * @param reg 寄存器地址 8bits * @param pBuf 要写入数据的存放缓存 * @param size 要写入数据的长度 * @return None */ void writeReg(uint8_t reg, const void* pBuf, size_t size); /** * @fn readReg * @brief 通过IIC总线读取寄存器值 * @param reg 寄存器地址 8bits * @param pBuf 要读取数据的存放缓存 * @param size 要读取数据的长度 * @return 返回读取的长度, 返回0表示读取失败 */ size_t readReg(uint8_t reg, void* pBuf, size_t size); public: // 存放传感器基本信息的结构体 sBasicInfo_t basicInfo; private: TwoWire *_pWire; // IIC通信方式的指针 uint8_t _deviceAddr; // IIC通信的设备地址 }; #endif
[ "1484504974@qq.com" ]
1484504974@qq.com
66d4f09b0232cfaaddb6a1fa71c8f07341ed481a
11679f3adec2b14ddeaa8b7a72536e3612bc4b44
/sourceCode/pagesAndViews/SceneSelector.h
51d248c6d7c94c3e68372c123742f936bdfcc199
[]
no_license
dtbinh/vrep_altair
26eadd039c0fe7e798b49486b187a21c743138bd
ad296b68b1deb11c49937e477ccee64b2e67050d
refs/heads/master
2021-01-24T22:44:02.877012
2014-03-13T16:59:00
2014-03-13T16:59:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,488
h
// This file is part of V-REP, the Virtual Robot Experimentation Platform. // // Copyright 2006-2014 Dr. Marc Andreas Freese. All rights reserved. // marc@coppeliarobotics.com // www.coppeliarobotics.com // // V-REP is dual-licensed, under the terms of EITHER (at your option): // 1. V-REP commercial license (contact us for details) // 2. GNU GPL (see below) // // GNU GPL license: // ------------------------------------------------------------------- // V-REP is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // V-REP is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with V-REP. If not, see <http://www.gnu.org/licenses/>. // ------------------------------------------------------------------- // // This file was automatically created for V-REP release V3.1.0 on January 20th 2014 #pragma once #include <vector> class C3DObject; class CSceneSelector { public: CSceneSelector(); virtual ~CSceneSelector(); void newSceneProcedure(); void setUpDefaultValues(); void render(); void setViewSizeAndPosition(int sizeX,int sizeY,int posX,int posY); int getSceneIndexInViewSelection(int mousePos[2]); bool leftMouseButtonDown(int x,int y,int selectionStatus); void leftMouseButtonUp(int x,int y); void mouseMove(int x,int y,bool passiveAndFocused); int getCursor(int x,int y); int getSceneIndex(int x,int y); bool rightMouseButtonDown(int x,int y); void rightMouseButtonUp(int x,int y,int absX,int absY,QWidget* mainWindow); bool leftMouseButtonDoubleClick(int x,int y,int selectionStatus); void setViewSelectionInfo(int objType,int viewInd,int subViewInd); void keyPress(int key); int getCaughtElements(); void clearCaughtElements(int keepMask); private: int viewSize[2]; int viewPosition[2]; int mouseDownRelativePosition[2]; int mouseRelativePosition[2]; int _caughtElements; int viewSelectionSize[2]; int tns[2]; // Thumnail size int objectType; // Type of objects to display int viewIndex; int subViewIndex; };
[ "arena.riccardo@live.it" ]
arena.riccardo@live.it
216e27fee17b15b431c2876a7a4fcd87f4c6b200
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/e0/ba8387c019bd29/main.cpp
196ff68c382f6144e3d5d3af016429550a2e07dc
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
21,046
cpp
#include <atomic> #include <queue> #include <mutex> #include <iostream> #include <sstream> #include <iostream> #include <memory> #include <string> #include <map> #include <iterator> #include <memory> #include <vector> #include <future> #include <stdexcept> #include <functional> #include <type_traits> #include <condition_variable> #include <boost/optional.hpp> /** * represents the szPriorityLevel<p> * * the szPriority Field contains a channel, priority character * [A-Z] (from highest priority to -lowest priority) * and an optional sequence number. */ class PriorityLevel { public: // default constructor PriorityLevel( const int32_t& rChannel = -1, const char priorityChar = 'Z', const std::string& rFilename = std::string(), const boost::optional<int32_t>& rSequenceNum = boost::optional<int32_t>()) : mChannel(rChannel) , mPriorityChar(priorityChar) , mFilename(rFilename) , mSequenceNum(rSequenceNum) {} // copy constructor PriorityLevel(const PriorityLevel& rhs) : mChannel(rhs.mChannel) , mPriorityChar(rhs.mPriorityChar) , mFilename(rhs.mFilename) , mSequenceNum(rhs.mSequenceNum) {} // move constructor PriorityLevel(PriorityLevel&& rhs) : mChannel(std::move(rhs.mChannel)) , mPriorityChar(std::move(rhs.mPriorityChar)) , mFilename(std::move(rhs.mFilename)) , mSequenceNum(std::move(rhs.mSequenceNum)) { // reset optionals - not really necessary rhs.mSequenceNum = boost::none; } // non-throwing-swap idiom inline void swap(PriorityLevel& rhs) { // enable ADL (not necessary in our case, but good practice) using std::swap; // no need to swap base members - as we are topmost class swap(mChannel, rhs.mChannel); swap(mPriorityChar, rhs.mPriorityChar); swap(mFilename, rhs.mFilename); swap(mSequenceNum, rhs.mSequenceNum); } // non-throwing copy-and-swap idiom unified assignment PriorityLevel& operator=(PriorityLevel rhs) { rhs.swap(*this); return *this; } // equality operator inline bool operator==(const PriorityLevel& rhs) const { return std::tie(mChannel, mPriorityChar, mFilename, mSequenceNum) == std::tie(rhs.mChannel, rhs.mPriorityChar, rhs.mFilename, rhs.mSequenceNum); } // inequality operator opposite to equality operator inline bool operator!=(const PriorityLevel& rhs) const { return !(operator==(rhs)); } /** * comparator that orders the elements in the * priority_queue<p> * * Implemented via a lexicographical comparison using * std::tuple<T...> as a helper. Tuple comparison works as * follows: compares the first elements, if they are equivalent, * compares the second elements, if those are equivalent, * compares the third elements, and so on. All comparison * operators are short - circuited; they do not access tuple * elements beyond what is necessary to determine the result of * the comparison. note that the presence of the sequence number * assigns a lower priority (bigger value 1) contribution to the * lexicographical nature of the comparison * * @param rhs [in] PriorityLevel to compare against * * @return 'true' if this has lower priority than rhs */ inline bool operator<(const PriorityLevel& rhs) const { auto seqNum = mSequenceNum ? mSequenceNum.get() : 0; auto rhsSeqNum = rhs.mSequenceNum ? rhs.mSequenceNum.get() : 0; return std::tie(mChannel, mPriorityChar, mFilename, seqNum) > std::tie(rhs.mChannel, rhs.mPriorityChar, rhs.mFilename, rhsSeqNum); } // operator>=() is opposite to operator<() inline bool operator>=(const PriorityLevel& rhs) const { return !(operator<(rhs)); } // operator>() implemented so that it now works with std::sort() // preserving the strict weak ordering mathematical rules inline bool operator>(const PriorityLevel& rhs) const { auto seqNum = mSequenceNum ? mSequenceNum.get() : 0; auto rhsSeqNum = rhs.mSequenceNum ? rhs.mSequenceNum.get() : 0; return std::tie(mChannel, mPriorityChar, mFilename, seqNum) < std::tie(rhs.mChannel, rhs.mPriorityChar, rhs.mFilename, rhsSeqNum); } // operator<=() is opposite to operator>() inline bool operator<=(const PriorityLevel& rhs) const { return !(operator>(rhs)); } /** * Stream insert operator<p> * * @param os [in,out] output stream * @param rhs [in] PriorityLevel to send to the output * stream. * * @return a reference to the updated stream */ inline friend std::ostream& operator << ( std::ostream& os, const PriorityLevel& rhs) { os << rhs.getPriorityStr(); return os; } // channel getter inline int32_t getChannel() const { return mChannel; } // priority char getter inline char getPriorityChar() const { return mPriorityChar; } // filename getter inline std::string getFilename() const { return mFilename; } // string representation of the priority string inline std::string getPriorityStr(const bool bShowFilename = false) const { std::stringstream ss; ss << mChannel << mPriorityChar; if (mSequenceNum) { ss << mSequenceNum.get(); } if (bShowFilename) { // print the filename to the right ss << "[" << mFilename << "]"; } return ss.str(); } private: // channel number - top level order field int32_t mChannel; // single upper case character A=>'highest priority' char mPriorityChar; // '_dr/_xr' filename+ext associated with this priority thread std::string mFilename; public: // optional field - when present indicates start order boost::optional<int32_t> mSequenceNum; }; /** * Branch representing fundamental building block of * a priority tree containing szPriority entries.<p> * * Each priority tree struct contains a vector of concurrent * priorities that can be scheduled to run in the thread pool - * note that the thread pool must have no entries associated * with the current channel running before enqueueing these * tasks. The application must wait for the thread pool to * complete these tasks before queuing up the dependent tasks * described in the mNextNode smart pointer. If mNextNode is * unassigned (nullptr), then we have reached the end of the * tree. */ struct PriorityNode { explicit PriorityNode( const std::vector<PriorityLevel>& rConcurrent, const std::shared_ptr<PriorityNode>& rNext = std::shared_ptr<PriorityNode>(), const size_t& rDepth = 0) : mConcurrent(rConcurrent) , mNextNode(rNext) , mDepth(rDepth) {} /** * Stream insert operator<p> * * @param os [in,out] output stream * @param rhs [in] PriorityLevel to send to the output * stream. * * @return a reference to the updated stream */ inline friend std::ostream& operator << ( std::ostream& os, const PriorityNode& rhs) { // indent 2 spaces per depth level std::string indent = rhs.mDepth > 0 ? (std::string("|") + std::string((rhs.mDepth * 3) - 1, '_')) : std::string(); // print out the concurrent threads that // can be scheduled with the thread pool for (const auto& next : rhs.mConcurrent) { os << indent << next << std::endl; } // print the dependent priorities that can only // be scheduled when the concurrent ones are finished if (rhs.mNextNode) { os << *rhs.mNextNode << std::endl; } return os; } // these are all equivalent thread priorities // that can be run simultaneously std::vector<PriorityLevel> mConcurrent; // these are concurrent threads that must be AFTER all // mConcurrent tasks have completed (exiting the thread pool) std::shared_ptr<PriorityNode> mNextNode; // recursion depth size_t mDepth; }; class TestCBClass { public: TestCBClass(const int& rValue = 1) : mValue(rValue) { std::cout << "~TestCBClass()" << std::endl; } virtual ~TestCBClass() { std::cout << "~TestCBClass()" << std::endl; } static void cbArgRetStatic1(const PriorityLevel& rPrty) { std::lock_guard<std::mutex> lock(gMutexGuard); std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout << rPrty << std::endl; } private: int mValue; static std::mutex gMutexGuard; }; std::mutex TestCBClass::gMutexGuard; using task_t = std::function<void(void)>; // FORWARD DECLARATIONS template <typename Priority> class prioritized_task { private: Priority priority; task_t task; public: explicit prioritized_task(const Priority& rPriority, task_t&& f) : priority(rPriority) , task(std::forward<task_t>(f)) {} // used for priority ordering tasks inline bool operator < (const prioritized_task& rhs) const { return this->priority < rhs.priority; } // functor operator used to invoke priority_task inline void operator()() { task(); } // priority getter inline Priority getPriority() const { return priority; } }; template <typename Priority> class UtlThreadPool { private: std::vector<std::thread> mWorkers; std::priority_queue<prioritized_task<Priority>> mTasks; std::mutex queue_mutex; std::condition_variable condition; std::atomic<bool> isActive; public: UtlThreadPool(const size_t& rNumThreads = std::thread::hardware_concurrency()) : isActive(true) { for (size_t i = 0; i < rNumThreads; i++) { mWorkers.emplace_back(std::thread( &UtlThreadPool::scheduler_loop, this)); } } // copy constructor - do not allow UtlThreadPool(const UtlThreadPool&) = delete; // assignment - do not allow UtlThreadPool& operator=(const UtlThreadPool&) = delete; template<class F, class P, class... Args> auto enqueue(P priority, F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { typedef typename std::result_of<F(Args...)>::type return_type; // Don't allow enqueueing after stopping the pool if (!isActive.load()) { throw std::runtime_error( "enqueue on stopped UtlThreadPool"); } // @JC changed return_type() to return_type(Args...) auto task = std::make_shared<std::packaged_task<return_type(Args...)>>( std::bind(std::forward<F>(f), std::forward<Args>(args)...) ); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(queue_mutex); mTasks.push(prioritized_task<Priority>(priority, [task](void) { (*task)(); })); } condition.notify_one(); return result; } // check the remaining size of the pool size_t pending(void) { std::unique_lock<std::mutex> lock(queue_mutex); return this->mTasks.size(); } // close the thread pool - this will wait for all queued up jobs to finish // additional jobs will not allowed to get posted to the queue for scheduling void close() { if (isActive.load()){ // only stop the threads if transitioning // from active to inactive isActive.store(false); condition.notify_all(); for (std::thread& t : mWorkers) { t.join(); } } } // destructor - waits for thread pool to finish active jobs virtual ~UtlThreadPool(void){ close(); } private: // this inline void scheduler_loop() { std::unique_ptr<Priority> pCurrentPrty; for (;;) { std::unique_lock<std::mutex> lock(queue_mutex); // wait for some task to get queued or for the atomic // isActive flag to become inactive condition.wait(lock, [this, &pCurrentPrty] { if (!mTasks.empty() && pCurrentPrty && pCurrentPrty->getPriorityStr() != mTasks.top().getPriority().getPriorityStr() && pCurrentPrty->getPriorityStr().length() != mTasks.top().getPriority().getPriorityStr().length()) { std::cout << "priority change" << std::endl; } return (!mTasks.empty() || !isActive.load()); }); // only exit when no more tasks on the queue if (!isActive.load() && mTasks.empty()) { return; } // update the top priority job that is currently running pCurrentPrty = std::make_unique<Priority>(mTasks.top().getPriority()); // move next task off the priority queue auto nextTask(std::move(mTasks.top())); pCurrentPrty = std::make_unique<Priority>(nextTask.getPriority()); // queue housekeeping mTasks.pop(); // release the lock allowing new entries to be queued lock.unlock(); // execute the task forwarding stored arguments with the call // this is the magic that works inside a thread pool // _Ret operator()(_Types... _Args) const nextTask(); } } }; int main() { // more realistic priorities - Dassault std::vector<PriorityLevel> gPriorities = { PriorityLevel(1, 'A', "[foo._dr]"), PriorityLevel(3, 'A', "[bar._dr]"), PriorityLevel(1, 'B', "[foo._dr]", 1), PriorityLevel(1, 'B', "[bar._dr]", 1), PriorityLevel(1, 'B', "[foo._dr]", 2), PriorityLevel(1, 'B', "[bar._dr]", 2), PriorityLevel(1, 'B', "[foo._dr]", 3), PriorityLevel(1, 'B', "[foo._dr]", 3), PriorityLevel(1, 'B', "[foo._dr]", 4), PriorityLevel(1, 'B', "[foo._dr]", 5), PriorityLevel(1, 'C', "[foo._dr]", 1), // test PriorityLevel(1, 'C', "[foo._dr]", 2), // test PriorityLevel(1, 'A', "[foo._dr]", 1), // test PriorityLevel(2, 'A', "[foo._dr]"), PriorityLevel(2, 'B', "[foo._dr]", 1), PriorityLevel(2, 'B', "[foo._dr]", 2), PriorityLevel(2, 'B', "[foo._dr]", 3), PriorityLevel(2, 'B', "[foo._dr]", 2) }; // channel only comparator - don't care about the order of the other fields const auto channelPred = [](const PriorityLevel& a, const PriorityLevel& b) { return a.getChannel() < b.getChannel(); }; // ignore the filename in the priority ordering - maybe add back later // as the last field to compare - not sure yet. const auto priorityPred = [](const PriorityLevel& a, const PriorityLevel& b) { // sequence number presence is important, its value is of secondary importance // which is why it is compared as the last entry in the tuple const auto seqNumA = a.mSequenceNum ? /*a.mSequenceNum.get()*/1 : 0; const auto seqNumB = b.mSequenceNum ? /*b.mSequenceNum.get()*/1 : 0; const auto channelA = a.getChannel(); const auto channelB = b.getChannel(); const auto priorityCharA = a.getPriorityChar(); const auto priorityCharB = b.getPriorityChar(); // no real need to include channel as all channels compared // using this comparator will have matching channels already // left in for completeness. return std::tie(channelA, priorityCharA, seqNumA) < std::tie(channelB, priorityCharB, seqNumB); }; // order the PriorityLevels in descending order // (highest to lowest priority). Note that higher priority // values use lower priority characters and sequence numbers // which is why the PriorityLevel operator> uses < comparisons // in the tuple fields std::sort(gPriorities.begin(), gPriorities.end(), std::greater<PriorityLevel>()); #if 0 std::cout << "priorities - ordered by channel" << std::endl; std::copy(gPriorities.begin(), gPriorities.end(), std::ostream_iterator<PriorityLevel>( std::cout, "\n")); std::cout << std::endl; #endif std::map<int32_t, std::shared_ptr<PriorityNode>> priorityInfo; // iterate over each of the channel ranges for (auto iter = gPriorities.begin(); iter != gPriorities.end();) { auto channelRange = std::equal_range(iter, gPriorities.end(), iter->getChannel(), channelPred); #if 0 std::cout << "channel [" << iter->mChannel << "] priorities - unordered" << std::endl; std::copy(channelRange.first, channelRange.second, std::ostream_iterator<PriorityLevel>( std::cout, "\n")); std::cout << std::endl; #endif // convert the channelRange into a sorted list of priorities std::vector<PriorityLevel> ch_ptys(channelRange.first, channelRange.second); std::sort(ch_ptys.begin(), ch_ptys.end(), priorityPred); // print the channel ordered priorities #if 0 std::cout << "channel [" << iter->mChannel << "] priorities - ordered" << std::endl; std::copy(ch_ptys.begin(), ch_ptys.end(), std::ostream_iterator<PriorityLevel>( std::cout, "\n")); std::cout << std::endl; #endif // iterate over sub ranges within the channel ordered priorities auto prevRange = std::make_pair(ch_ptys.begin(), ch_ptys.begin()); std::shared_ptr<PriorityNode> currentNode, rootNode; size_t depth = 0; for (auto iter1 = ch_ptys.begin(); iter1 != ch_ptys.end();) { auto range = std::equal_range(iter1, ch_ptys.end(), *iter1, priorityPred); // this represents all the equivalent priority levels auto concurrent = std::vector<PriorityLevel>(range.first, range.second); #if 0 std::cout << "identical priorities" << std::endl; std::copy(range.first, range.second, std::ostream_iterator<PriorityLevel>( std::cout, "\n")); std::cout << std::endl; #endif // build a priority tree here if (!currentNode) { currentNode = std::make_shared<PriorityNode>( concurrent, std::shared_ptr<PriorityNode>(), depth++); if (!rootNode) { rootNode = currentNode; } } else { currentNode->mNextNode = std::make_shared<PriorityNode>( concurrent, std::shared_ptr<PriorityNode>(), depth++); currentNode = currentNode->mNextNode; } prevRange = range; iter1 = range.second; } priorityInfo[iter->getChannel()] = rootNode; std::cout << *rootNode << std::endl; iter = channelRange.second; } // thread pool's destructor will set the stop // flag and wait to join all the active threads in the pool UtlThreadPool<PriorityLevel> priorityThreadPool(2); { // This is a really nasty hack to determine the type of future // all futures mapped according to channel std::map<int32_t, std::vector<std::future<void>>> futureInfo; for (auto iter = priorityInfo.cbegin(); iter != priorityInfo.cend();) { for (const auto& priorityLevel : iter->second->mConcurrent) { const auto& channel = priorityLevel.getChannel(); auto future = priorityThreadPool.enqueue(priorityLevel, std::bind(&TestCBClass::cbArgRetStatic1, priorityLevel)); if (futureInfo.find(channel) == futureInfo.cend()) { futureInfo[channel] = std::vector<std::future<void>>(); } futureInfo[channel].emplace_back(std::move(future)); } // dependent threads? if (iter->second->mNextNode) { // wait for the concurrent threads to finish for (const auto& next : futureInfo) { for (const auto& future : next.second) { // poll using 1 second granularity waiting for ready shared state while (future.wait_for(std::chrono::seconds(1)) != std::future_status::ready); } } std::cout << "concurrent tasks finished" << std::endl; } } // wait for threads to complete priorityThreadPool.close(); } }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
c3f5a661b9589bac53214fa7ace6af60f6f6a935
0c6472b33b1518338d01f8b77d9e283f53c07bf9
/2sat/main.cpp
754dcc2f64f5759caa487410218656deda64793a
[]
no_license
armandanusca/algorithm_problems
4e4104f953bbd9ec675e663065491ddc493c0e60
251320d344ed53a7195b442f035aeeac97969419
refs/heads/main
2023-07-12T18:07:21.977929
2021-08-25T15:32:21
2021-08-25T15:32:21
377,901,445
0
0
null
null
null
null
UTF-8
C++
false
false
1,804
cpp
#include <bits/stdc++.h> #define nmax 100005 using namespace std; int n,m; vector <int> rel[2*nmax+5]; vector <int> irel[2*nmax+5]; int comp [2*nmax+5]; vector <int> lst , comp_val; bool viz [2*nmax+5]; bool sol[nmax+5]; #define rel (rel+nmax) #define irel (irel+nmax) #define viz (viz+nmax) #define comp (comp+nmax) vector <int> range(int low,int high){ vector <int> t; for(int i=low;i<=high;i++){ t.push_back(i); } return t; } void DFS(int nod){ if(viz[nod]) return; viz[nod]=true; for(auto it: rel[nod]) DFS(it); lst.push_back(nod); } void Assign(int nod,int cmp){ if(comp[nod]) return; comp[nod]=cmp; for(auto it: irel[nod]) Assign(it,cmp); } bool SAT2(){ for(int i=-n;i<=n;i++) DFS(i); int t=0; comp_val.push_back(0); for(int i=lst.size()-1;i>-1;i--){ if(comp[lst[i]]) continue; comp_val.push_back(0); Assign(lst[i],++t); } for(int i=1;i<=n;i++){ if(comp[i]==comp[-i]) return false; else if(comp[i]>comp[-i]) comp_val[comp[i]]=1; else if(comp[-i]>comp[i]) comp_val[comp[-i]]=1; } for(int i=1;i<=n;i++) sol[i]=comp_val[comp[i]]; return true; } int main() { int x,y; ios_base::sync_with_stdio(false); ifstream fin("2sat.in"); fin>>n>>m; for(int i=1;i<=m;i++){ fin>>x>>y; rel[-x].push_back(y); rel[-y].push_back(x); irel[x].push_back(-y); irel[y].push_back(-x); } ofstream fout("2sat.out"); if(SAT2()) for(auto i : range(1,n)) fout<<sol[i]<<' '; else fout<<"-1"; fout<<'\n'; fout.close(); fin.close(); return 0; }
[ "anusca.armand@gmail.com" ]
anusca.armand@gmail.com
8a78499a6df9292e7d4a589d62b8f83a7831ab6b
591df59d439e1d7cc630a6a5958e7a92c6bdaabc
/repository/manager/ConfigLoader.cpp
ff4d475031bbdc4156199e302a23e9c77456d1b3
[]
no_license
kjhgnkv/DSControl_17_09
b929ef051d7a17705bc963c1bcda96badf860463
03957e8153e3852cbf026ec37bdac340a6b23f24
refs/heads/main
2023-08-02T19:20:05.527221
2021-10-01T14:59:20
2021-10-01T14:59:20
412,485,720
0
0
null
null
null
null
UTF-8
C++
false
false
10,851
cpp
#include "ConfigLoader.hpp" #include <QDebug> #include <QDirIterator> #include <QDomDocument> #include <QFile> #include <QJsonArray> #include <QJsonObject> #include <QTextStream> #include <tuple> namespace dsrepository { ConfigLoader::ConfigLoader() : components_ {} , componentsToRemove_ {} , root_ {} { } std::map<QString, Component> ConfigLoader::update() { QStringList items; QDir dir {root_}; QDirIterator it(dir.path(), QStringList() << "*.xml", QDir::Files, QDirIterator::Subdirectories); componentsToRemove_.clear(); while (it.hasNext()) { auto path = it.next(); if (auto found = components_.find(path); found == components_.end()) { QFile file {path}; if (file.open(QIODevice::ReadOnly)) { QDomDocument xmlDoc; xmlDoc.setContent(&file); if (auto component = translate(xmlDoc.documentElement()); !component.type_.isEmpty()) { components_.insert({path, std::move(component)}); } file.close(); } } items.push_back(path); } for (auto it = components_.begin(); it != components_.end();) { if (!items.contains(it->first)) { componentsToRemove_.insert({it->first, it->second}); it = components_.erase(it); } else { it++; } } return components_; } std::map<QString, Component> ConfigLoader::load(const QDir &dir, const QDir &description) { if (dir.isEmpty() || !dir.exists() || description.isEmpty() || !description.exists()) { return {}; } components_.clear(); root_ = dir.path(); QDirIterator it(dir.path(), QStringList() << "*.bndl", QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { auto path = it.next(); auto bundlePath = path; path.replace(dir.path(), description.path()); path.replace("bndl", "xml"); QFile file {path}; if (file.open(QIODevice::ReadOnly)) { QDomDocument xmlDoc; xmlDoc.setContent(&file); if (auto component = translate(xmlDoc.documentElement()); !component.type_.isEmpty()) { //qDebug() << "BUNDLE PATH:" << bundlePath; components_.insert({bundlePath, component}); } file.close(); } } return components_; } std::map<QString, Component> ConfigLoader::extraLoad(const QDir &dir) { if (!dir.exists() || dir.isEmpty()) { return {}; } std::map<QString, Component> retval; QDirIterator it(dir.path(), QStringList() << "*.xml", QDir::Files, QDirIterator::Subdirectories); while (it.hasNext()) { auto path = it.next(); QFile file {path}; if (file.open(QIODevice::ReadOnly)) { QDomDocument xmlDoc; xmlDoc.setContent(&file); if (auto component = translate(xmlDoc.documentElement()); !component.type_.isEmpty()) { retval.insert({path, component}); } file.close(); } } return retval; } std::map<QString, Component> ConfigLoader::components() const { return components_; } std::map<QString, Component> ConfigLoader::componentsToRemove() const { return componentsToRemove_; } QString ConfigLoader::root() const { return root_; } Component ConfigLoader::translate(const QDomNode &root) { Component retval; if (!root.isNull()) { if (root.nodeName() == "description") { retval.type_ = "ComponentNode"; for (auto element = root.firstChildElement(); !element.isNull(); element = element.nextSiblingElement()) { if (element.nodeName() == "BasicInfo") { auto name = element.attributeNode("name").value(); auto system = element.attributeNode("system").value(); auto bit = element.attributeNode("bit").value(); auto title = element.attributeNode("name").value(); auto type = element.attributeNode("type").value(); auto category = element.attributeNode("name").value(); retval.caption_ = name; retval.category_ = category; retval.info_["caption"] = name; retval.info_["componentType"] = name; retval.info_["category"] = category; retval.info_["brief"] = "Title: " + title + "\n" + "Type: " + type + "\n" + "Category: " + category; retval.info_["moduleName"] = name; retval.info_["moduleType"] = type; //TODO parameters section? QJsonObject componentInfo; componentInfo["GUID"] = element.attributeNode("name").value(); componentInfo["Version"] = element.attributeNode("version").value(); retval.version_ = element.attributeNode("version").value(); componentInfo["Extension"] = element.attributeNode("name").value(); componentInfo["CreatedDate"] = element.attributeNode("name").value(); componentInfo["UpdatedDate"] = element.attributeNode("name").value(); componentInfo["UploadDate"] = element.attributeNode("name").value(); componentInfo["LastmodifiedDate"] = element.attributeNode("name").value(); componentInfo["Description"] = element.attributeNode("name").value(); retval.info_["componentInfo"] = componentInfo; } //TODO for test, remove QJsonArray in; QJsonArray out; QJsonObject obj = { { "id" , 0} , {"name" , ""} , {"protocol", ""} }; in.push_back(obj); out.push_back(obj); retval.info_["messagesIn"] = in; retval.info_["messagesOut"] = out; } } } return retval; } Component ConfigLoader::translateOld(const QDomNode &root) { Component retval; if (!root.isNull()) { if (root.nodeName() == "ModuleClass") { retval.type_ = "ComponentNode"; if (auto rootElement = root.toElement(); !rootElement.isNull()) { auto name = rootElement.attributeNode("name").value(); retval.caption_ = name; retval.info_["caption"] = name; retval.info_["componentType"] = name; auto title = rootElement.attributeNode("title").value(); auto type = rootElement.attributeNode("type").value(); auto category = rootElement.attributeNode("category").value(); retval.category_ = category; retval.info_["category"] = category; retval.info_["brief"] = "Title: " + title + "\n" + "Type: " + type + "\n" + "Category: " + category; retval.info_["moduleName"] = name; retval.info_["moduleType"] = type; } // FIXME rewrite to json array QStringList messagesListIn; QStringList messagesListOut; QJsonObject componentInfo; QJsonArray in; QJsonArray out; for (auto element = root.firstChildElement(); !element.isNull(); element = element.nextSiblingElement()) { QJsonObject obj; auto name = element.nodeName(); if (name == "Send") { auto messageId = element.attributeNode("id").value().toInt(); auto messageName = element.attributeNode("name").value(); auto messageProto = element.attributeNode("protocol").value(); messagesListIn.push_back(messageId + ' ' + messageName + ' ' + messageProto); obj = { { "id" , messageId} , {"name" , messageName} , {"protocol", messageProto} }; in.push_back(obj); } else if (name == "Recv") { auto messageId = element.attributeNode("id").value().toInt(); auto messageName = element.attributeNode("name").value(); auto messageProto = element.attributeNode("protocol").value(); messagesListOut.push_back(messageId + ' ' + messageName + ' ' + messageProto); obj = { { "id" , messageId} , {"name" , messageName} , {"protocol", messageProto} }; out.push_back(obj); } else if (name == "GUID") { componentInfo["GUID"] = element.attributeNode("name").value(); } else if (name == "Version") { componentInfo["Version"] = element.attributeNode("name").value(); // TODO retval.version_ = element.attributeNode("name").value(); } else if (name == "Extension") { componentInfo["Extension"] = element.attributeNode("name").value(); } else if (name == "CreatedDate") { componentInfo["CreatedDate"] = element.attributeNode("name").value(); } else if (name == "UpdatedDate") { componentInfo["UpdatedDate"] = element.attributeNode("name").value(); } else if (name == "UploadDate") { componentInfo["UploadDate"] = element.attributeNode("name").value(); } else if (name == "LastmodifiedDate") { componentInfo["LastmodifiedDate"] = element.attributeNode("name").value(); } else if (name == "Description") { componentInfo["Description"] = element.attributeNode("name").value(); } } retval.info_["componentInfo"] = componentInfo; retval.info_["messagesIn"] = in; retval.info_["messagesOut"] = out; } } return retval; } } // namespace dsrepository
[ "yingfanyz@gmail.com" ]
yingfanyz@gmail.com
f72c0f0e8138fe1665696509b0c9adf64bd623af
2fb19bc9aaa85b70a4ec8d0e1881dff688ae794b
/Codeforces/codes/1136/1136E.cpp
17e80905baf4cfa3ae8fafc2b1d30a09e2f89fec
[]
no_license
preritpaliwal/Competitive-Programming
8f2b4f78006b7e7e8df02b04df681099d2effc77
805744f7b4d50ee621884f5280f9ef8779bb6866
refs/heads/master
2023-06-27T12:51:18.436807
2021-07-30T10:10:24
2021-07-30T10:10:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,477
cpp
#include<bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define mod 1000000007 #define lli long long #define fi first #define se second #define pb emplace_back #define FOR(i,n) for(int i=0;i<n;i++) #define FORR(x,v) for(auto x : v) #define ordered_set tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> #define MAXC 100005 // % char t; int a, b, n, q; lli A[MAXC], K[MAXC], pref[MAXC]; struct data{ lli x, big, lazyVal; bool exist, lazy; data(): exist(false) {} data(lli v) : x(v), lazyVal(0), exist(true), lazy(false) {} // Node combination data operator+(data r){ if(!r.exist) return *this; if(!this->exist) return r; data ans(r.x + x); ans.big = max(r.big, big); return ans; } // Lazy updation void upd(int l, int r){ x = lazyVal * (r - l +1); big = lazyVal; lazy = false; lazyVal = 0; } }; struct seg_tree{ int n; vector< data > tr; seg_tree(int size){ n = size; tr.resize(4*n, data(0)); } seg_tree(vector< lli > &v){ n = v.size(); tr.resize(4*n, data(0)); build(v, 0, n-1, 1); } // Lazy propagaton void pushdown(int ind, int l, int r){ if(tr[ind].lazy){ if(l!=r){ tr[ind<<1].lazyVal = tr[ind].lazyVal; tr[ind<<1|1].lazyVal = tr[ind].lazyVal; tr[ind<<1].lazy = tr[ind<<1|1].lazy = true; } tr[ind].upd(l, r); } } void build( vector< lli > &v, int l, int r, int ind){ if(l==r){ tr[ind].x = tr[ind].big = v[l]; return; } int mid = l+r>>1; build(v, l, mid, ind<<1); build(v, mid+1, r, ind<<1|1); tr[ind] = tr[ind<<1] + tr[ind<<1|1]; } void update(lli x, int i, int l, int r, int ind){ pushdown(ind, l, r); if(i > r || i < l){ return; } if(l==r){ tr[ind].big = tr[ind].x += x; return; } int mid=l+r>>1; update(x, i, l, mid, ind<<1); update(x, i, mid+1, r, ind<<1|1); tr[ind] = tr[ind<<1] + tr[ind<<1|1]; } void assign(lli x, int i, int j, int l, int r, int ind){ pushdown(ind, l, r); if(i > r || j < l){ return; } if(l >= i && j >= r){ tr[ind].lazy = true; tr[ind].lazyVal = x; pushdown(ind, l, r); return; } int mid = l + r >> 1; assign(x, i, j, l, mid, ind<<1); assign(x, i, j, mid+1, r, ind<<1|1); tr[ind] = tr[ind<<1] + tr[ind<<1|1]; } data query1(int i, int j, int l, int r, int ind){ pushdown(ind, l, r); if(i>r || j<l || l>r){ return data(); } if(l>=i && r<=j){ return tr[ind]; } int mid=l+r>>1; return query1(i, j, l, mid, ind<<1) + query1(i, j, mid+1, r, ind<<1|1); } int findFirst(lli val, int i, int j, int l, int r, int ind){ pushdown(ind, l, r); if(i>r || j<l || tr[ind].big <= val){ return -1; } if(l == r){ return l; } int mid = l + r >> 1; int q = findFirst(val, i, j, l, mid, ind<<1); if(q == -1){ q = findFirst(val, i, j, mid+1, r, ind<<1|1); } return q; } lli query(int i, int j){ data temp = query1(i, j, 0, n-1, 1); return temp.x; } void upd(lli x, int i){ update(x, i, 0, n-1, 1); lli val = query(i, i); int till = findFirst(val, i, n-1, 0, n-1, 1); if(till == -1){ till = n; } assign(val, i, till-1, 0, n-1, 1); } }; int main(int argc, char **argv) { ios::sync_with_stdio(0); cin.tie(0); cin >> n; FOR(i, n){ cin >> A[i]; } FOR(i, n-1){ cin >> K[i+1]; K[i+1] += K[i]; pref[i+1] = pref[i] + K[i+1]; } vector< lli > B(n); FOR(i, n){ B[i] = A[i] - K[i]; } seg_tree sg(B); cin >> q; while(q--){ cin >> t >> a >> b; if(t == '+'){ sg.upd(b, a-1); } else{ cout << sg.query(a-1, b-1) + pref[b-1] - pref[max(a-2, 0)] << '\n'; } } }
[ "kousshikraj.raj@gmail.com" ]
kousshikraj.raj@gmail.com
21ffb7ddb04e188d861a77eccb8d1e21b78bb177
2f70c4b45ef4473f00597605d86428e64903bf3c
/src/checker/State.cpp
62ecb9ce03391f3dfeb8c62d629508e72734f86c
[]
no_license
Voxed/epic-compiler
d96d0ba922ac24c196327d81b3a48beaa2acaf27
62534ed7015f259fb05fe4c1b2d0ebe7b67dc5f9
refs/heads/master
2023-08-19T17:04:16.239749
2021-10-04T02:57:41
2021-10-04T02:57:41
413,240,701
0
0
null
null
null
null
UTF-8
C++
false
false
3,832
cpp
#include "State.hpp" #include "common/Exceptions.hpp" #include "common/TypeDeducer.hpp" namespace checker { State::State(State* parent, ClassDescriptor* classDescriptor) : parent(parent) , doesReturn(false) , classDescriptor(classDescriptor) {} void State::PutVariable(const std::string& variable, parser::Type* type) { if (variableTable.contains(variable)) { throw common::CheckerException("Variable already declared, " + variable); } variableTable[variable] = std::unique_ptr<parser::Type, ast::Deleter>(type); } parser::Type* State::GetVariable(const std::string& variable) { if (classDescriptor != nullptr) { if (classDescriptor->HasField(variable)) { return classDescriptor->GetField(variable); } } if (variableTable.contains(variable)) { return variableTable[variable].get(); } if (parent != nullptr) { return parent->GetVariable(variable); } throw common::CheckerException("Variable not declared, " + variable); } void State::PutFunction(const std::string& name, parser::TFun* type) { if (functionTable.contains(name)) { throw common::CheckerException("Function already declared, " + name); } functionTable[name] = std::unique_ptr<parser::TFun, ast::Deleter>(type); } parser::TFun* State::GetFunction(const std::string& name) { if (functionTable.contains(name)) { return functionTable[name].get(); } if (parent != nullptr) { return parent->GetFunction(name); } throw common::CheckerException("Function not declared, " + name); } void State::PutType(const std::string& typeName, parser::Type* type) { if (typeDeclarations.contains(typeName)) { throw common::CheckerException("Type " + typeName + " already declared"); } typeDeclarations[typeName] = std::unique_ptr<parser::Type, ast::Deleter>(type); } parser::Type* State::GetType(const std::string& typeName) { if (typeDeclarations.contains(typeName)) { return typeDeclarations[typeName].get(); } if (parent != nullptr) { return parent->GetType(typeName); } throw common::CheckerException("Type " + typeName + " is not declared"); } bool State::HasType(const std::string& typeName) { return typeDeclarations.contains(typeName); } ClassDescriptor* State::GetClassDescriptor(const std::string& id) { if (classDescriptorTable.contains(id)) { return classDescriptorTable[id].get(); } if (parent != nullptr) { return parent->GetClassDescriptor(id); } classDescriptorTable[id] = std::make_unique<ClassDescriptor>(true); return classDescriptorTable[id].get(); } bool State::GetDoesReturn() const { return doesReturn; } void State::SetDoesReturn() { doesReturn = true; } void State::SetReturnType(parser::Type* type) { returnType = std::unique_ptr<parser::Type, ast::Deleter>(type); } parser::Type* State::GetReturnType() { if (!returnType) { return parent->GetReturnType(); } return returnType.get(); } void State::Verify() { for (auto& t : typeDeclarations) { parser::Type* type = t.second.get(); if (common::CompareType(type, common::POINTER)) { auto* pType = static_cast<parser::TPointer*>(type); if (!HasType(pType->ident_)) { throw common::CheckerException("Type referenced by " + t.first + " is not defined, " + pType->ident_); } parser::Type* type = GetType(pType->ident_); if (!common::CompareType(type, common::STRUCT)) { throw common::CheckerException("Type referenced by " + t.first + " is not a struct, " + pType->ident_); } } } for (auto& cd : classDescriptorTable) { cd.second->Verify(); } } } // namespace checker
[ "voxedg@gmail.com" ]
voxedg@gmail.com
27489b9feabd37f10d690ce500a10720d7adb797
e56d100ce7e183df367d6e969844bd84f0079dee
/wzemcmbd/CrdWzemNav/DlgWzemNavLoaini.cpp
5208cf64229620a2cb3a59f8c051baf9ce79eb78
[ "MIT" ]
permissive
mpsitech/wzem-WhizniumSBE-Engine-Monitor
800b556dce0212a6f9ad7fbedbff4c87d9cb5421
2808427d328f45ad1e842e0455565eeb1a563adf
refs/heads/master
2022-09-29T02:41:46.253166
2022-09-12T20:34:28
2022-09-12T20:34:28
282,705,563
0
0
null
null
null
null
UTF-8
C++
false
false
16,624
cpp
/** * \file DlgWzemNavLoaini.cpp * job handler for job DlgWzemNavLoaini (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Alexander Wirthmueller (auto-generation) * \date created: 1 Dec 2020 */ // IP header --- ABOVE #ifdef WZEMCMBD #include <Wzemcmbd.h> #else #include <Wzemd.h> #endif #include "DlgWzemNavLoaini.h" #include "DlgWzemNavLoaini_blks.cpp" #include "DlgWzemNavLoaini_evals.cpp" using namespace std; using namespace Sbecore; using namespace Xmlio; // IP ns.cust --- INSERT /****************************************************************************** class DlgWzemNavLoaini ******************************************************************************/ DlgWzemNavLoaini::DlgWzemNavLoaini( XchgWzem* xchg , DbsWzem* dbswzem , const ubigint jrefSup , const uint ixWzemVLocale ) : JobWzem(xchg, VecWzemVJob::DLGWZEMNAVLOAINI, jrefSup, ixWzemVLocale) { jref = xchg->addJob(dbswzem, this, jrefSup); feedFMcbAlert.tag = "FeedFMcbAlert"; feedFDse.tag = "FeedFDse"; VecVDit::fillFeed(ixWzemVLocale, feedFDse); feedFSge.tag = "FeedFSge"; VecVSge::fillFeed(feedFSge); iex = NULL; // IP constructor.cust1 --- INSERT ixVDit = VecVDit::IFI; iex = new JobWzemIexIni(xchg, dbswzem, jref, ixWzemVLocale); // IP constructor.cust2 --- INSERT set<uint> moditems; refresh(dbswzem, moditems); // IP constructor.cust3 --- INSERT // IP constructor.spec3 --- INSERT }; DlgWzemNavLoaini::~DlgWzemNavLoaini() { // IP destructor.spec --- INSERT // IP destructor.cust --- INSERT xchg->removeJobByJref(jref); }; // IP cust --- INSERT DpchEngWzem* DlgWzemNavLoaini::getNewDpchEng( set<uint> items ) { DpchEngWzem* dpcheng = NULL; if (items.empty()) { dpcheng = new DpchEngWzemConfirm(true, jref, ""); } else { insert(items, DpchEngData::JREF); dpcheng = new DpchEngData(jref, &contiac, &continf, &continfimp, &continflfi, &feedFDse, &feedFSge, &statshr, &statshrifi, &statshrimp, &statshrlfi, items); }; return dpcheng; }; void DlgWzemNavLoaini::refreshIfi( DbsWzem* dbswzem , set<uint>& moditems ) { StatShrIfi oldStatshrifi(statshrifi); // IP refreshIfi --- BEGIN // statshrifi statshrifi.UldActive = evalIfiUldActive(dbswzem); // IP refreshIfi --- END if (statshrifi.diff(&oldStatshrifi).size() != 0) insert(moditems, DpchEngData::STATSHRIFI); }; void DlgWzemNavLoaini::refreshImp( DbsWzem* dbswzem , set<uint>& moditems ) { StatShrImp oldStatshrimp(statshrimp); ContInfImp oldContinfimp(continfimp); // IP refreshImp --- RBEGIN // continfimp continfimp.TxtPrg = getSquawk(dbswzem); // statshrimp statshrimp.ButRunActive = evalImpButRunActive(dbswzem); statshrimp.ButStoActive = evalImpButStoActive(dbswzem); // IP refreshImp --- REND if (statshrimp.diff(&oldStatshrimp).size() != 0) insert(moditems, DpchEngData::STATSHRIMP); if (continfimp.diff(&oldContinfimp).size() != 0) insert(moditems, DpchEngData::CONTINFIMP); }; void DlgWzemNavLoaini::refreshLfi( DbsWzem* dbswzem , set<uint>& moditems ) { ContInfLfi oldContinflfi(continflfi); StatShrLfi oldStatshrlfi(statshrlfi); // IP refreshLfi --- BEGIN // continflfi // statshrlfi statshrlfi.DldActive = evalLfiDldActive(dbswzem); // IP refreshLfi --- END if (continflfi.diff(&oldContinflfi).size() != 0) insert(moditems, DpchEngData::CONTINFLFI); if (statshrlfi.diff(&oldStatshrlfi).size() != 0) insert(moditems, DpchEngData::STATSHRLFI); }; void DlgWzemNavLoaini::refresh( DbsWzem* dbswzem , set<uint>& moditems , const bool unmute ) { if (muteRefresh && !unmute) return; muteRefresh = true; StatShr oldStatshr(statshr); ContIac oldContiac(contiac); ContInf oldContinf(continf); // IP refresh --- BEGIN // statshr statshr.ButDneActive = evalButDneActive(dbswzem); // contiac contiac.numFDse = ixVDit; // continf continf.numFSge = ixVSge; // IP refresh --- END if (statshr.diff(&oldStatshr).size() != 0) insert(moditems, DpchEngData::STATSHR); if (contiac.diff(&oldContiac).size() != 0) insert(moditems, DpchEngData::CONTIAC); if (continf.diff(&oldContinf).size() != 0) insert(moditems, DpchEngData::CONTINF); refreshIfi(dbswzem, moditems); refreshImp(dbswzem, moditems); refreshLfi(dbswzem, moditems); muteRefresh = false; }; void DlgWzemNavLoaini::handleRequest( DbsWzem* dbswzem , ReqWzem* req ) { if (req->ixVBasetype == ReqWzem::VecVBasetype::CMD) { reqCmd = req; if (req->cmd == "cmdset") { } else { cout << "\tinvalid command!" << endl; }; if (!req->retain) reqCmd = NULL; } else if (req->ixVBasetype == ReqWzem::VecVBasetype::DPCHAPP) { if (req->dpchapp->ixWzemVDpch == VecWzemVDpch::DPCHAPPWZEMINIT) { handleDpchAppWzemInit(dbswzem, (DpchAppWzemInit*) (req->dpchapp), &(req->dpcheng)); } else if (req->dpchapp->ixWzemVDpch == VecWzemVDpch::DPCHAPPDLGWZEMNAVLOAINIDATA) { DpchAppData* dpchappdata = (DpchAppData*) (req->dpchapp); if (dpchappdata->has(DpchAppData::CONTIAC)) { handleDpchAppDataContiac(dbswzem, &(dpchappdata->contiac), &(req->dpcheng)); }; } else if (req->dpchapp->ixWzemVDpch == VecWzemVDpch::DPCHAPPDLGWZEMNAVLOAINIDO) { DpchAppDo* dpchappdo = (DpchAppDo*) (req->dpchapp); if (dpchappdo->ixVDo != 0) { if (dpchappdo->ixVDo == VecVDo::BUTDNECLICK) { handleDpchAppDoButDneClick(dbswzem, &(req->dpcheng)); }; } else if (dpchappdo->ixVDoImp != 0) { if (dpchappdo->ixVDoImp == VecVDoImp::BUTRUNCLICK) { handleDpchAppDoImpButRunClick(dbswzem, &(req->dpcheng)); } else if (dpchappdo->ixVDoImp == VecVDoImp::BUTSTOCLICK) { handleDpchAppDoImpButStoClick(dbswzem, &(req->dpcheng)); }; }; } else if (req->dpchapp->ixWzemVDpch == VecWzemVDpch::DPCHAPPWZEMALERT) { handleDpchAppWzemAlert(dbswzem, (DpchAppWzemAlert*) (req->dpchapp), &(req->dpcheng)); }; } else if (req->ixVBasetype == ReqWzem::VecVBasetype::UPLOAD) { if (ixVSge == VecVSge::IDLE) handleUploadInSgeIdle(dbswzem, req->filename); } else if (req->ixVBasetype == ReqWzem::VecVBasetype::DOWNLOAD) { if (ixVSge == VecVSge::DONE) req->filename = handleDownloadInSgeDone(dbswzem); } else if (req->ixVBasetype == ReqWzem::VecVBasetype::TIMER) { if (ixVSge == VecVSge::PRSIDLE) handleTimerInSgePrsidle(dbswzem, req->sref); else if ((req->sref == "mon") && (ixVSge == VecVSge::IMPORT)) handleTimerWithSrefMonInSgeImport(dbswzem); else if (ixVSge == VecVSge::IMPIDLE) handleTimerInSgeImpidle(dbswzem, req->sref); }; }; void DlgWzemNavLoaini::handleDpchAppWzemInit( DbsWzem* dbswzem , DpchAppWzemInit* dpchappwzeminit , DpchEngWzem** dpcheng ) { *dpcheng = getNewDpchEng({DpchEngData::ALL}); }; void DlgWzemNavLoaini::handleDpchAppDataContiac( DbsWzem* dbswzem , ContIac* _contiac , DpchEngWzem** dpcheng ) { set<uint> diffitems; set<uint> moditems; diffitems = _contiac->diff(&contiac); if (has(diffitems, ContIac::NUMFDSE)) { if ((_contiac->numFDse >= VecVDit::IFI) && (_contiac->numFDse <= VecVDit::LFI)) ixVDit = _contiac->numFDse; refresh(dbswzem, moditems); }; insert(moditems, DpchEngData::CONTIAC); *dpcheng = getNewDpchEng(moditems); }; void DlgWzemNavLoaini::handleDpchAppDoButDneClick( DbsWzem* dbswzem , DpchEngWzem** dpcheng ) { // IP handleDpchAppDoButDneClick --- IBEGIN if (statshr.ButDneActive) { *dpcheng = new DpchEngWzemConfirm(true, jref, ""); xchg->triggerCall(dbswzem, VecWzemVCall::CALLWZEMDLGCLOSE, jref); }; // IP handleDpchAppDoButDneClick --- IEND }; void DlgWzemNavLoaini::handleDpchAppDoImpButRunClick( DbsWzem* dbswzem , DpchEngWzem** dpcheng ) { // IP handleDpchAppDoImpButRunClick --- BEGIN if (statshrimp.ButRunActive) { changeStage(dbswzem, VecVSge::IMPIDLE, dpcheng); }; // IP handleDpchAppDoImpButRunClick --- END }; void DlgWzemNavLoaini::handleDpchAppDoImpButStoClick( DbsWzem* dbswzem , DpchEngWzem** dpcheng ) { // IP handleDpchAppDoImpButStoClick --- INSERT }; void DlgWzemNavLoaini::handleDpchAppWzemAlert( DbsWzem* dbswzem , DpchAppWzemAlert* dpchappwzemalert , DpchEngWzem** dpcheng ) { // IP handleDpchAppWzemAlert --- IBEGIN if (ixVSge == VecVSge::ALRWZEMPER) { changeStage(dbswzem, nextIxVSgeSuccess); } else if (ixVSge == VecVSge::ALRWZEMIER) { if (dpchappwzemalert->numFMcb == 2) iex->reverse(dbswzem); changeStage(dbswzem, nextIxVSgeSuccess); }; // IP handleDpchAppWzemAlert --- IEND }; void DlgWzemNavLoaini::handleUploadInSgeIdle( DbsWzem* dbswzem , const string& filename ) { infilename = filename; // IP handleUploadInSgeIdle --- ILINE changeStage(dbswzem, VecVSge::PRSIDLE); }; string DlgWzemNavLoaini::handleDownloadInSgeDone( DbsWzem* dbswzem ) { return(""); // IP handleDownloadInSgeDone --- LINE }; void DlgWzemNavLoaini::handleTimerInSgePrsidle( DbsWzem* dbswzem , const string& sref ) { changeStage(dbswzem, nextIxVSgeSuccess); }; void DlgWzemNavLoaini::handleTimerWithSrefMonInSgeImport( DbsWzem* dbswzem ) { wrefLast = xchg->addWakeup(jref, "mon", 250000, true); refreshWithDpchEng(dbswzem); // IP handleTimerWithSrefMonInSgeImport --- ILINE }; void DlgWzemNavLoaini::handleTimerInSgeImpidle( DbsWzem* dbswzem , const string& sref ) { changeStage(dbswzem, nextIxVSgeSuccess); }; void DlgWzemNavLoaini::changeStage( DbsWzem* dbswzem , uint _ixVSge , DpchEngWzem** dpcheng ) { bool reenter = true; do { if (ixVSge != _ixVSge) { switch (ixVSge) { case VecVSge::IDLE: leaveSgeIdle(dbswzem); break; case VecVSge::PRSIDLE: leaveSgePrsidle(dbswzem); break; case VecVSge::PARSE: leaveSgeParse(dbswzem); break; case VecVSge::ALRWZEMPER: leaveSgeAlrwzemper(dbswzem); break; case VecVSge::PRSDONE: leaveSgePrsdone(dbswzem); break; case VecVSge::IMPIDLE: leaveSgeImpidle(dbswzem); break; case VecVSge::IMPORT: leaveSgeImport(dbswzem); break; case VecVSge::ALRWZEMIER: leaveSgeAlrwzemier(dbswzem); break; case VecVSge::DONE: leaveSgeDone(dbswzem); break; }; setStage(dbswzem, _ixVSge); reenter = false; refreshWithDpchEng(dbswzem, dpcheng); // IP changeStage.refresh1 --- LINE }; switch (_ixVSge) { case VecVSge::IDLE: _ixVSge = enterSgeIdle(dbswzem, reenter); break; case VecVSge::PRSIDLE: _ixVSge = enterSgePrsidle(dbswzem, reenter); break; case VecVSge::PARSE: _ixVSge = enterSgeParse(dbswzem, reenter); break; case VecVSge::ALRWZEMPER: _ixVSge = enterSgeAlrwzemper(dbswzem, reenter); break; case VecVSge::PRSDONE: _ixVSge = enterSgePrsdone(dbswzem, reenter); break; case VecVSge::IMPIDLE: _ixVSge = enterSgeImpidle(dbswzem, reenter); break; case VecVSge::IMPORT: _ixVSge = enterSgeImport(dbswzem, reenter); break; case VecVSge::ALRWZEMIER: _ixVSge = enterSgeAlrwzemier(dbswzem, reenter); break; case VecVSge::DONE: _ixVSge = enterSgeDone(dbswzem, reenter); break; }; // IP changeStage.refresh2 --- INSERT } while (ixVSge != _ixVSge); }; string DlgWzemNavLoaini::getSquawk( DbsWzem* dbswzem ) { string retval; // IP getSquawk --- RBEGIN if ( (ixVSge == VecVSge::PARSE) || (ixVSge == VecVSge::ALRWZEMPER) || (ixVSge == VecVSge::PRSDONE) || (ixVSge == VecVSge::IMPORT) || (ixVSge == VecVSge::ALRWZEMIER) ) { if (ixWzemVLocale == VecWzemVLocale::ENUS) { if (ixVSge == VecVSge::PARSE) retval = "parsing initialization data"; else if (ixVSge == VecVSge::ALRWZEMPER) retval = "parse error"; else if (ixVSge == VecVSge::PRSDONE) retval = "initialization data parsed"; else if (ixVSge == VecVSge::IMPORT) retval = "importing initialization data (" + to_string(iex->impcnt) + " records added)"; else if (ixVSge == VecVSge::ALRWZEMIER) retval = "import error"; }; } else { retval = VecVSge::getSref(ixVSge); }; // IP getSquawk --- REND return retval; }; uint DlgWzemNavLoaini::enterSgeIdle( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::IDLE; // IP enterSgeIdle --- INSERT return retval; }; void DlgWzemNavLoaini::leaveSgeIdle( DbsWzem* dbswzem ) { // IP leaveSgeIdle --- INSERT }; uint DlgWzemNavLoaini::enterSgePrsidle( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::PRSIDLE; nextIxVSgeSuccess = VecVSge::PARSE; wrefLast = xchg->addWakeup(jref, "callback", 0); // IP enterSgePrsidle --- INSERT return retval; }; void DlgWzemNavLoaini::leaveSgePrsidle( DbsWzem* dbswzem ) { // IP leaveSgePrsidle --- INSERT }; uint DlgWzemNavLoaini::enterSgeParse( DbsWzem* dbswzem , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::PRSDONE; retval = nextIxVSgeSuccess; nextIxVSgeFailure = VecVSge::ALRWZEMPER; // IP enterSgeParse --- IBEGIN ifstream ififile; char* buf; string s; bool ifitxt; bool ifixml; iex->reset(dbswzem); // check file type ififile.open(infilename.c_str(), ifstream::in); buf = new char[16]; ififile.get(buf, 16); s = string(buf); ifitxt = (s.find("IexWzemIni") == 0); ifixml = (s.find("<?xml") == 0); delete[] buf; ififile.close(); // parse file accordingly if (ifitxt) iex->parseFromFile(dbswzem, infilename, false, ""); else if (ifixml) iex->parseFromFile(dbswzem, infilename, true, ""); if (iex->ixVSge != JobWzemIexIni::VecVSge::PRSDONE) { if (reqCmd) { if (iex->ixVSge == JobWzemIexIni::VecVSge::PRSERR) cout << "\t" << iex->getSquawk(dbswzem) << endl; else cout << "\tneither text-based nor XML file format recognized" << endl; retval = VecVSge::IDLE; } else { retval = nextIxVSgeFailure; }; }; // IP enterSgeParse --- IEND return retval; }; void DlgWzemNavLoaini::leaveSgeParse( DbsWzem* dbswzem ) { // IP leaveSgeParse --- INSERT }; uint DlgWzemNavLoaini::enterSgeAlrwzemper( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::ALRWZEMPER; nextIxVSgeSuccess = VecVSge::IDLE; // IP enterSgeAlrwzemper --- RBEGIN ContInfWzemAlert continf; continf.TxtCpt = VecWzemVTag::getTitle(VecWzemVTag::ERROR, ixWzemVLocale); continf.TxtCpt = StrMod::cap(continf.TxtCpt); if (iex->ixVSge == JobWzemIexIni::VecVSge::PRSERR) continf.TxtMsg1 = iex->getSquawk(dbswzem); else continf.TxtMsg1 = "neither text-based nor XML file format recognized"; feedFMcbAlert.clear(); VecWzemVTag::appendToFeed(VecWzemVTag::OK, ixWzemVLocale, feedFMcbAlert); feedFMcbAlert.cap(); xchg->submitDpch(new DpchEngWzemAlert(jref, &continf, &feedFMcbAlert, {DpchEngWzemAlert::ALL})); // IP enterSgeAlrwzemper --- REND return retval; }; void DlgWzemNavLoaini::leaveSgeAlrwzemper( DbsWzem* dbswzem ) { // IP leaveSgeAlrwzemper --- INSERT }; uint DlgWzemNavLoaini::enterSgePrsdone( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::PRSDONE; // IP enterSgePrsdone --- INSERT return retval; }; void DlgWzemNavLoaini::leaveSgePrsdone( DbsWzem* dbswzem ) { // IP leaveSgePrsdone --- INSERT }; uint DlgWzemNavLoaini::enterSgeImpidle( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::IMPIDLE; nextIxVSgeSuccess = VecVSge::IMPORT; wrefLast = xchg->addWakeup(jref, "callback", 0); // IP enterSgeImpidle --- INSERT return retval; }; void DlgWzemNavLoaini::leaveSgeImpidle( DbsWzem* dbswzem ) { // IP leaveSgeImpidle --- INSERT }; uint DlgWzemNavLoaini::enterSgeImport( DbsWzem* dbswzem , const bool reenter ) { uint retval; nextIxVSgeSuccess = VecVSge::DONE; retval = nextIxVSgeSuccess; nextIxVSgeFailure = VecVSge::ALRWZEMIER; if (!reenter) wrefLast = xchg->addWakeup(jref, "mon", 250000, true); // IP enterSgeImport --- IBEGIN iex->import(dbswzem); if (iex->ixVSge == JobWzemIexIni::VecVSge::IMPERR) retval = nextIxVSgeFailure; // IP enterSgeImport --- IEND return retval; }; void DlgWzemNavLoaini::leaveSgeImport( DbsWzem* dbswzem ) { invalidateWakeups(); // IP leaveSgeImport --- INSERT }; uint DlgWzemNavLoaini::enterSgeAlrwzemier( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::ALRWZEMIER; nextIxVSgeSuccess = VecVSge::IDLE; // IP enterSgeAlrwzemier --- RBEGIN if (reqCmd) { cout << "\t" << iex->getSquawk(dbswzem) << endl; retval = nextIxVSgeSuccess; } else { xchg->submitDpch(AlrWzem::prepareAlrIer(jref, ixWzemVLocale, iex->getSquawk(dbswzem), feedFMcbAlert)); }; // IP enterSgeAlrwzemier --- REND return retval; }; void DlgWzemNavLoaini::leaveSgeAlrwzemier( DbsWzem* dbswzem ) { // IP leaveSgeAlrwzemier --- INSERT }; uint DlgWzemNavLoaini::enterSgeDone( DbsWzem* dbswzem , const bool reenter ) { uint retval = VecVSge::DONE; // IP enterSgeDone --- INSERT return retval; }; void DlgWzemNavLoaini::leaveSgeDone( DbsWzem* dbswzem ) { // IP leaveSgeDone --- INSERT };
[ "aw@mpsitech.com" ]
aw@mpsitech.com
41cb46a882c0a1e50c2fddc67131e9a73706091c
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/Source/Includes/QtIncludes/src/corelib/plugin/qfactoryloader_p.h
5472ef8d3cae4391d8a66cb366f578c23b16452b
[ "MIT", "curl", "LGPL-2.1-or-later", "BSD-3-Clause", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-only", "Zlib", "LicenseRef-scancode-unknown", "LicenseRef-scancode-unknown-license-reference", "MS-LPL" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
2,852
h
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QFACTORYLOADER_P_H #define QFACTORYLOADER_P_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include "QtCore/qobject.h" #include "QtCore/qstringlist.h" #include "private/qlibrary_p.h" #ifndef QT_NO_LIBRARY QT_BEGIN_NAMESPACE class QFactoryLoaderPrivate; class Q_CORE_EXPORT QFactoryLoader : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(QFactoryLoader) public: QFactoryLoader(const char *iid, const QString &suffix = QString(), Qt::CaseSensitivity = Qt::CaseSensitive); ~QFactoryLoader(); QStringList keys() const; QObject *instance(const QString &key) const; #ifdef Q_WS_X11 QLibraryPrivate *library(const QString &key) const; #endif void update(); static void refreshAll(); }; QT_END_NAMESPACE #endif // QT_NO_LIBRARY #endif // QFACTORYLOADER_P_H
[ "anandx@google.com" ]
anandx@google.com
854d425aeabf3a6462fe2687369062ffdceb302d
8f50c262f89d3dc4f15f2f67eb76e686b8f808f5
/PhysicsAnalysis/TauID/TauAnalysisTools/Root/DiTauEfficiencyCorrectionsTool.cxx
8c7b91dca577c4af3ba638a57ef12400fdf2cd67
[ "Apache-2.0" ]
permissive
strigazi/athena
2d099e6aab4a94ab8b636ae681736da4e13ac5c9
354f92551294f7be678aebcd7b9d67d2c4448176
refs/heads/master
2022-12-09T02:05:30.632208
2020-09-03T14:03:18
2020-09-03T14:03:18
292,587,480
0
1
null
null
null
null
UTF-8
C++
false
false
10,602
cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ // EDM include(s): #include "PATInterfaces/SystematicRegistry.h" #include "xAODEventInfo/EventInfo.h" // Local include(s): #include "TauAnalysisTools/DiTauEfficiencyCorrectionsTool.h" #include "TauAnalysisTools/Enums.h" #include "TauAnalysisTools/SharedFilesVersion.h" namespace TauAnalysisTools { //______________________________________________________________________________ DiTauEfficiencyCorrectionsTool::DiTauEfficiencyCorrectionsTool( const std::string& sName ) : asg::AsgMetadataTool( sName ) , m_vCommonEfficiencyTools() , m_bIsData(false) , m_bIsConfigured(false) { declareProperty( "EfficiencyCorrectionTypes", m_vEfficiencyCorrectionTypes = {} ); declareProperty( "InputFilePathRecoHadTau", m_sInputFilePathRecoHadTau = "" ); declareProperty( "InputFilePathJetIDHadTau", m_sInputFilePathJetIDHadTau = "" ); declareProperty( "VarNameRecoHadTau", m_sVarNameRecoHadTau = "" ); declareProperty( "VarNameJetIDHadTau", m_sVarNameJetIDHadTau = "" ); declareProperty( "RecommendationTag", m_sRecommendationTag = "2017-moriond" ); declareProperty( "IDLevel", m_iIDLevel = (int)JETIDBDTTIGHT ); declareProperty( "EventInfoName", m_sEventInfoName = "EventInfo" ); declareProperty( "SkipTruthMatchCheck", m_bSkipTruthMatchCheck = false ); } //______________________________________________________________________________ DiTauEfficiencyCorrectionsTool::~DiTauEfficiencyCorrectionsTool() { for (auto tTool : m_vCommonEfficiencyTools) delete tTool; } //______________________________________________________________________________ StatusCode DiTauEfficiencyCorrectionsTool::initialize() { // Greet the user: ATH_MSG_INFO( "Initializing DiTauEfficiencyCorrectionsTool" ); if (m_bSkipTruthMatchCheck) ATH_MSG_WARNING("Truth match check will be skipped. This is ONLY FOR TESTING PURPOSE!"); // configure default set of variations if not set by the constructor using TauSelectionTool or the user if ((m_sRecommendationTag== "2017-moriond") and m_vEfficiencyCorrectionTypes.size() == 0) m_vEfficiencyCorrectionTypes = {SFJetIDHadTau }; if (m_sRecommendationTag == "2017-moriond") ATH_CHECK(initializeTools_2017_moriond()); else { ATH_MSG_FATAL("Unknown RecommendationTag: "<<m_sRecommendationTag); return StatusCode::FAILURE; } for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) { ATH_CHECK((**it).setProperty("OutputLevel", this->msg().level())); ATH_CHECK((**it).initialize()); } // Add the affecting systematics to the global registry CP::SystematicRegistry& registry = CP::SystematicRegistry::getInstance(); if (!registry.registerSystematics(*this)) { ATH_MSG_ERROR ("Unable to register the systematics"); return StatusCode::FAILURE; } printConfig(/* bAlways = */ false); return StatusCode::SUCCESS; } //______________________________________________________________________________ StatusCode DiTauEfficiencyCorrectionsTool::beginEvent() { if (!m_bIsConfigured) { const xAOD::EventInfo* xEventInfo = nullptr; ATH_CHECK(evtStore()->retrieve(xEventInfo,"EventInfo")); m_bIsData = !(xEventInfo->eventType( xAOD::EventInfo::IS_SIMULATION)); m_bIsConfigured=true; } if (m_bIsData) return StatusCode::SUCCESS; return StatusCode::SUCCESS; } //______________________________________________________________________________ void DiTauEfficiencyCorrectionsTool::printConfig(bool bAlways) { if (bAlways) { ATH_MSG_DEBUG( "DiTauEfficiencyCorrectionsTool with name " << name() << " is configured as follows:" ); for (auto iEfficiencyCorrectionType : m_vEfficiencyCorrectionTypes) ATH_MSG_ALWAYS( " EfficiencyCorrectionTypes " << iEfficiencyCorrectionType ); ATH_MSG_ALWAYS( " InputFilePathRecoHadTau " << m_sInputFilePathRecoHadTau ); ATH_MSG_ALWAYS( " InputFilePathJetIDHadTau " << m_sInputFilePathJetIDHadTau ); ATH_MSG_ALWAYS( " VarNameRecoHadTau " << m_sVarNameRecoHadTau ); ATH_MSG_ALWAYS( " VarNameJetIDHadTau " << m_sVarNameJetIDHadTau ); ATH_MSG_ALWAYS( " RecommendationTag " << m_sRecommendationTag ); } else { ATH_MSG_DEBUG( "DiTauEfficiencyCorrectionsTool with name " << name() << " is configured as follows:" ); for (auto iEfficiencyCorrectionType : m_vEfficiencyCorrectionTypes) ATH_MSG_DEBUG( " EfficiencyCorrectionTypes " << iEfficiencyCorrectionType ); ATH_MSG_DEBUG( " InputFilePathRecoHadTau " << m_sInputFilePathRecoHadTau ); ATH_MSG_DEBUG( " VarNameRecoHadTau " << m_sVarNameRecoHadTau ); ATH_MSG_DEBUG( " VarNameJetIDHadTau " << m_sVarNameJetIDHadTau ); ATH_MSG_DEBUG( " RecommendationTag " << m_sRecommendationTag ); } } //______________________________________________________________________________ CP::CorrectionCode DiTauEfficiencyCorrectionsTool::getEfficiencyScaleFactor( const xAOD::DiTauJet& xDiTau, double& eff ) { eff = 1.; if (m_bIsData) return CP::CorrectionCode::Ok; for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) { double dToolEff = 1.; CP::CorrectionCode tmpCorrectionCode = (**it)->getEfficiencyScaleFactor(xDiTau, dToolEff); if (tmpCorrectionCode != CP::CorrectionCode::Ok) return tmpCorrectionCode; eff *= dToolEff; } return CP::CorrectionCode::Ok; } //______________________________________________________________________________ CP::CorrectionCode DiTauEfficiencyCorrectionsTool::applyEfficiencyScaleFactor( const xAOD::DiTauJet& xDiTau ) { if (m_bIsData) return CP::CorrectionCode::Ok; for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) { CP::CorrectionCode tmpCorrectionCode = (**it)->applyEfficiencyScaleFactor(xDiTau); if (tmpCorrectionCode != CP::CorrectionCode::Ok) { return tmpCorrectionCode; } } return CP::CorrectionCode::Ok; } /// returns: whether this tool is affected by the given systematis //______________________________________________________________________________ bool DiTauEfficiencyCorrectionsTool::isAffectedBySystematic( const CP::SystematicVariation& systematic ) const { for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) if ((**it)->isAffectedBySystematic(systematic)) return true; return false; } /// returns: the list of all systematics this tool can be affected by //______________________________________________________________________________ CP::SystematicSet DiTauEfficiencyCorrectionsTool::affectingSystematics() const { CP::SystematicSet sAffectingSystematics; for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) sAffectingSystematics.insert((**it)->affectingSystematics()); return sAffectingSystematics; } /// returns: the list of all systematics this tool recommends to use //______________________________________________________________________________ CP::SystematicSet DiTauEfficiencyCorrectionsTool::recommendedSystematics() const { CP::SystematicSet sRecommendedSystematics; for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) { sRecommendedSystematics.insert((**it)->recommendedSystematics()); } return sRecommendedSystematics; } //______________________________________________________________________________ CP::SystematicCode DiTauEfficiencyCorrectionsTool::applySystematicVariation ( const CP::SystematicSet& sSystematicSet) { for (auto it = m_vCommonEfficiencyTools.begin(); it != m_vCommonEfficiencyTools.end(); it++) if ((**it)->applySystematicVariation(sSystematicSet) == CP::SystematicCode::Unsupported) { return CP::SystematicCode::Unsupported; } return CP::SystematicCode::Ok; } //=================================PRIVATE-PART================================= //______________________________________________________________________________ StatusCode DiTauEfficiencyCorrectionsTool::initializeTools_2017_moriond() { std::string sDirectory = "TauAnalysisTools/"+std::string(sSharedFilesVersion)+"/EfficiencyCorrections/"; for (auto iEfficiencyCorrectionType : m_vEfficiencyCorrectionTypes) { if (iEfficiencyCorrectionType == SFJetIDHadTau) { // only set vars if they differ from "", which means they have been configured by the user if (m_sInputFilePathJetIDHadTau.empty()) m_sInputFilePathJetIDHadTau = sDirectory+"JetID_TrueHadDiTau_2017-prerec.root"; if (m_sVarNameJetIDHadTau.length() == 0) m_sVarNameJetIDHadTau = "DiTauScaleFactorJetIDHadTau"; asg::AnaToolHandle<IDiTauEfficiencyCorrectionsTool>* tTool = new asg::AnaToolHandle<IDiTauEfficiencyCorrectionsTool>("JetIDHadTauTool", this); m_vCommonEfficiencyTools.push_back(tTool); ATH_CHECK(ASG_MAKE_ANA_TOOL(*tTool, TauAnalysisTools::CommonDiTauEfficiencyTool)); ATH_CHECK(tTool->setProperty("InputFilePath", m_sInputFilePathJetIDHadTau)); ATH_CHECK(tTool->setProperty("VarName", m_sVarNameJetIDHadTau)); ATH_CHECK(tTool->setProperty("SkipTruthMatchCheck", m_bSkipTruthMatchCheck)); ATH_CHECK(tTool->setProperty("WP", ConvertJetIDToString(m_iIDLevel))); } else { ATH_MSG_WARNING("unsupported EfficiencyCorrectionsType with enum "<<iEfficiencyCorrectionType); } } return StatusCode::SUCCESS; } //______________________________________________________________________________ std::string DiTauEfficiencyCorrectionsTool::ConvertJetIDToString(const int& iLevel) { switch(iLevel) { case JETIDNONE: return "none"; break; case JETIDBDTLOOSE: return "jetbdtsigloose"; break; case JETIDBDTMEDIUM: return "jetbdtsigmedium"; break; case JETIDBDTTIGHT: return "jetbdtsigtight"; break; case JETIDBDTOTHER: return "jetbdtsigother"; break; case JETIDLLHLOOSE: return "taujllhloose"; break; case JETIDLLHMEDIUM: return "taujllhmedium"; break; case JETIDLLHTIGHT: return "taujllhtight"; break; case JETIDLLHFAIL: return "taujllh"; break; case JETIDBDTFAIL: return "jetbdtsig"; break; default: assert(false && "No valid ID level passed. Breaking up ..."); break; } return ""; } } // namespace TauAnalysisTools
[ "david.kirchmeier@cern.ch" ]
david.kirchmeier@cern.ch
9c77f9b9a985570d7a5f14193ac26620e2bf4ecd
25f1310b8258aa0096ad608d34ebeba9a2b29adc
/M_807.cpp
29a52313a19a6e71a67e0bf59f054592668cc0aa
[]
no_license
FannyZhao123/leetCode
d21dfe4167a53ec614bb0829831d01e74bb46e16
3d98f05a343fa61b7613eff7017ee07be4f92be6
refs/heads/master
2022-12-14T21:02:29.304013
2020-09-05T00:39:47
2020-09-05T00:39:47
259,479,891
0
0
null
null
null
null
UTF-8
C++
false
false
3,850
cpp
/* 807. Max Increase to Keep City Skyline In a 2 dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well. At the end, the "skyline" when viewed from all four directions of the grid, i.e. top, bottom, left, and right, must be the same as the skyline of the original grid. A city's skyline is the outer contour of the rectangles formed by all the buildings when viewed from a distance. See the following example. What is the maximum total sum that the height of the buildings can be increased? Example: Input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] Output: 35 Explanation: The grid is: [ [3, 0, 8, 4], [2, 4, 5, 7], [9, 2, 6, 3], [0, 3, 1, 0] ] The skyline viewed from top or bottom is: [9, 4, 8, 7] The skyline viewed from left or right is: [8, 7, 9, 3] The grid after increasing the height of buildings without affecting skylines is: gridNew = [ [8, 4, 8, 7], [7, 4, 7, 7], [9, 4, 8, 7], [3, 3, 3, 3] ] Notes: 1 < grid.length = grid[0].length <= 50. All heights grid[i][j] are in the range [0, 100]. All buildings in grid[i][j] occupy the entire grid cell: that is, they are a 1 x 1 x grid[i][j] rectangular prism. */ //Runtime: 16 ms, faster than 9.09% of C++ online submissions for Max Increase to Keep City Skyline. //Memory Usage: 10.4 MB, less than 6.45% of C++ online submissions for Max Increase to Keep City Skyline. class Solution { public: int totalIncreace = 0; vector<int> top; vector<int> right; void skyline_top (vector<vector<int>>& grid, int x, int y){ for (int i = 0; i < y; i++){ int max = 0; for (int j =0; j < x; j++){ if (grid[j][i] > max){ max = grid[j][i]; } } top.push_back(max); } } void skyline_right (vector<vector<int>>& grid, int x, int y){ for (int i = 0; i < x; i++){ int max = 0; for (int j =0; j < y; j++){ if (grid[i][j] > max){ max = grid[i][j]; } } right.push_back(max); } } int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int x = grid.size(); int y = grid[1].size(); skyline_top(grid, x, y); skyline_right(grid, x, y); for (int i = 0; i < x; i++){ for (int j =0; j < y; j++){ int temp = min(top[j], right[i]); if (grid[i][j] < temp){ totalIncreace += (temp - grid[i][j]); } } } return totalIncreace; } }; // better , but not best //Runtime: 12 ms, faster than 14.94% of C++ online submissions for Max Increase to Keep City Skyline. //Memory Usage: 10.2 MB, less than 6.45% of C++ online submissions for Max Increase to Keep City Skyline. class Solution { public: int maxIncreaseKeepingSkyline(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); vector<int> row(m,0), col(n,0); for(int i=0; i<m; i++) { for(int j=0; j<n; ++j) { if(row[i] < grid[i][j]) row[i]= grid[i][j]; if(col[j] < grid[i][j]) col[j]= grid[i][j]; } } int totalSum = 0; for(int i=0; i<m; i++) { for(int j=0; j<n; ++j) { totalSum += min(row[i],col[j])-grid[i][j]; } } return totalSum; } };
[ "f25zhao@uwaterloo.ca" ]
f25zhao@uwaterloo.ca
89fa07c305624ea5a380c6eb6c00f8ef7eb182e0
72fad310918bf9b23caff58440bc2b3e75f080e5
/GameEngine/System/System.hpp
e5449e904ff9bec589218d831fab8ad84feee300
[ "MIT" ]
permissive
Stun3R/Epitech-R-Type
4ad131fa4a3a72475056e27f2d0f4f62da4ad56f
3d6ef3bd5a937f50de996de2395c43c5115f0776
refs/heads/main
2023-01-13T02:22:51.919307
2020-11-18T17:13:50
2020-11-18T17:13:50
313,998,862
0
0
null
null
null
null
UTF-8
C++
false
false
370
hpp
/* ** EPITECH PROJECT, 2021 ** R-TYPE ** File description: ** Created by stun3r, */ #ifndef SYSTEM_HPP #define SYSTEM_HPP #include "../Library.hpp" class Manager; class System { public: Manager &_manager; explicit System(Manager &_manager) : _manager(_manager) { } virtual void updateEntities(float delta) {}; virtual ~System() {}; }; #endif //SYSTEM_HPP
[ "thibautdavid@icloud.com" ]
thibautdavid@icloud.com
51c79894e286d8dcdbfcab6370ab3076bde32f39
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_5543.cpp
5c11d40e8b435f3102bba0ab8a478c82532ba971
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
38,138
cpp
#include "squid.h" #include "store_ufs.h" #define DefaultLevelOneDirs 16 #define DefaultLevelTwoDirs 256 #define STORE_META_BUFSZ 4096 typedef struct _RebuildState RebuildState; struct _RebuildState { SwapDir *sd; int n_read; FILE *log; int speed; int curlvl1; int curlvl2; struct { unsigned int need_to_validate:1; unsigned int clean:1; unsigned int init:1; } flags; int done; int in_dir; int fn; struct dirent *entry; DIR *td; char fullpath[SQUID_MAXPATHLEN]; char fullfilename[SQUID_MAXPATHLEN]; struct _store_rebuild_data counts; }; static int n_ufs_dirs = 0; static int *ufs_dir_index = NULL; MemPool *ufs_state_pool = NULL; static int ufs_initialised = 0; static char *storeUfsDirSwapSubDir(SwapDir *, int subdirn); static int storeUfsDirCreateDirectory(const char *path, int); static int storeUfsDirVerifyCacheDirs(SwapDir *); static int storeUfsDirVerifyDirectory(const char *path); static void storeUfsDirCreateSwapSubDirs(SwapDir *); static char *storeUfsDirSwapLogFile(SwapDir *, const char *); static EVH storeUfsDirRebuildFromDirectory; static EVH storeUfsDirRebuildFromSwapLog; static int storeUfsDirGetNextFile(RebuildState *, sfileno *, int *size); static StoreEntry *storeUfsDirAddDiskRestore(SwapDir * SD, const cache_key * key, int file_number, size_t swap_file_sz, time_t expires, time_t timestamp, time_t lastref, time_t lastmod, u_int32_t refcount, u_int16_t flags, int clean); static void storeUfsDirRebuild(SwapDir * sd); static void storeUfsDirCloseTmpSwapLog(SwapDir * sd); static FILE *storeUfsDirOpenTmpSwapLog(SwapDir *, int *, int *); static STLOGOPEN storeUfsDirOpenSwapLog; static STINIT storeUfsDirInit; static STFREE storeUfsDirFree; static STLOGCLEANSTART storeUfsDirWriteCleanStart; static STLOGCLEANNEXTENTRY storeUfsDirCleanLogNextEntry; static STLOGCLEANWRITE storeUfsDirWriteCleanEntry; static STLOGCLEANDONE storeUfsDirWriteCleanDone; static STLOGCLOSE storeUfsDirCloseSwapLog; static STLOGWRITE storeUfsDirSwapLog; static STNEWFS storeUfsDirNewfs; static STDUMP storeUfsDirDump; static STMAINTAINFS storeUfsDirMaintain; static STCHECKOBJ storeUfsDirCheckObj; static STREFOBJ storeUfsDirRefObj; static STUNREFOBJ storeUfsDirUnrefObj; static QS rev_int_sort; static int storeUfsDirClean(int swap_index); static EVH storeUfsDirCleanEvent; static int storeUfsDirIs(SwapDir * sd); static int storeUfsFilenoBelongsHere(int fn, int F0, int F1, int F2); static int storeUfsCleanupDoubleCheck(SwapDir *, StoreEntry *); static void storeUfsDirStats(SwapDir *, StoreEntry *); static void storeUfsDirInitBitmap(SwapDir *); static int storeUfsDirValidFileno(SwapDir *, sfileno, int); STSETUP storeFsSetup_ufs; /* * These functions were ripped straight out of the heart of store_dir.c. * They assume that the given filenum is on a ufs partiton, which may or * may not be true.. * XXX this evilness should be tidied up at a later date! */ static int storeUfsDirMapBitTest(SwapDir * SD, sfileno filn) { ufsinfo_t *ufsinfo; ufsinfo = (ufsinfo_t *) SD->fsdata; return file_map_bit_test(ufsinfo->map, filn); } static void storeUfsDirMapBitSet(SwapDir * SD, int fn) { sfileno filn = fn; ufsinfo_t *ufsinfo; ufsinfo = (ufsinfo_t *) SD->fsdata; file_map_bit_set(ufsinfo->map, filn); } void storeUfsDirMapBitReset(SwapDir * SD, int fn) { sfileno filn = fn; ufsinfo_t *ufsinfo; ufsinfo = (ufsinfo_t *) SD->fsdata; /* * We have to test the bit before calling file_map_bit_reset. * file_map_bit_reset doesn't do bounds checking. It assumes * filn is a valid file number, but it might not be because * the map is dynamic in size. Also clearing an already clear * bit puts the map counter of-of-whack. */ if (file_map_bit_test(ufsinfo->map, filn)) file_map_bit_reset(ufsinfo->map, filn); } int storeUfsDirMapBitAllocate(SwapDir * SD) { ufsinfo_t *ufsinfo = (ufsinfo_t *) SD->fsdata; int fn; fn = file_map_allocate(ufsinfo->map, ufsinfo->suggest); file_map_bit_set(ufsinfo->map, fn); ufsinfo->suggest = fn + 1; return fn; } /* * Initialise the ufs bitmap * * If there already is a bitmap, and the numobjects is larger than currently * configured, we allocate a new bitmap and 'grow' the old one into it. */ static void storeUfsDirInitBitmap(SwapDir * sd) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; if (ufsinfo->map == NULL) { /* First time */ ufsinfo->map = file_map_create(); } else if (ufsinfo->map->max_n_files) { /* it grew, need to expand */ /* XXX We don't need it anymore .. */ } /* else it shrunk, and we leave the old one in place */ } static char * storeUfsDirSwapSubDir(SwapDir * sd, int subdirn) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; LOCAL_ARRAY(char, fullfilename, SQUID_MAXPATHLEN); assert(0 <= subdirn && subdirn < ufsinfo->l1); snprintf(fullfilename, SQUID_MAXPATHLEN, "%s/%02X", sd->path, subdirn); return fullfilename; } static int storeUfsDirCreateDirectory(const char *path, int should_exist) { int created = 0; struct stat st; getCurrentTime(); if (0 == stat(path, &st)) { if (S_ISDIR(st.st_mode)) { debug(47, should_exist ? 3 : 1) ("%s exists\n", path); } else { fatalf("Swap directory %s is not a directory.", path); } } else if (0 == mkdir(path, 0755)) { debug(47, should_exist ? 1 : 3) ("%s created\n", path); created = 1; } else { fatalf("Failed to make swap directory %s: %s", path, xstrerror()); } return created; } static int storeUfsDirVerifyDirectory(const char *path) { struct stat sb; if (stat(path, &sb) < 0) { debug(47, 0) ("%s: %s\n", path, xstrerror()); return -1; } if (S_ISDIR(sb.st_mode) == 0) { debug(47, 0) ("%s is not a directory\n", path); return -1; } return 0; } /* * This function is called by storeUfsDirInit(). If this returns < 0, * then Squid exits, complains about swap directories not * existing, and instructs the admin to run 'squid -z' */ static int storeUfsDirVerifyCacheDirs(SwapDir * sd) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; int j; const char *path = sd->path; if (storeUfsDirVerifyDirectory(path) < 0) return -1; for (j = 0; j < ufsinfo->l1; j++) { path = storeUfsDirSwapSubDir(sd, j); if (storeUfsDirVerifyDirectory(path) < 0) return -1; } return 0; } static void storeUfsDirCreateSwapSubDirs(SwapDir * sd) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; int i, k; int should_exist; LOCAL_ARRAY(char, name, MAXPATHLEN); for (i = 0; i < ufsinfo->l1; i++) { snprintf(name, MAXPATHLEN, "%s/%02X", sd->path, i); if (storeUfsDirCreateDirectory(name, 0)) should_exist = 0; else should_exist = 1; debug(47, 1) ("Making directories in %s\n", name); for (k = 0; k < ufsinfo->l2; k++) { snprintf(name, MAXPATHLEN, "%s/%02X/%02X", sd->path, i, k); storeUfsDirCreateDirectory(name, should_exist); } } } static char * storeUfsDirSwapLogFile(SwapDir * sd, const char *ext) { LOCAL_ARRAY(char, path, SQUID_MAXPATHLEN); LOCAL_ARRAY(char, pathtmp, SQUID_MAXPATHLEN); LOCAL_ARRAY(char, digit, 32); char *pathtmp2; if (Config.Log.swap) { xstrncpy(pathtmp, sd->path, SQUID_MAXPATHLEN - 64); pathtmp2 = pathtmp; while ((pathtmp2 = strchr(pathtmp2, '/')) != NULL) *pathtmp2 = '.'; while (strlen(pathtmp) && pathtmp[strlen(pathtmp) - 1] == '.') pathtmp[strlen(pathtmp) - 1] = '\0'; for (pathtmp2 = pathtmp; *pathtmp2 == '.'; pathtmp2++); snprintf(path, SQUID_MAXPATHLEN - 64, Config.Log.swap, pathtmp2); if (strncmp(path, Config.Log.swap, SQUID_MAXPATHLEN - 64) == 0) { strcat(path, "."); snprintf(digit, 32, "%02d", sd->index); strncat(path, digit, 3); } } else { xstrncpy(path, sd->path, SQUID_MAXPATHLEN - 64); strcat(path, "/swap.state"); } if (ext) strncat(path, ext, 16); return path; } static void storeUfsDirOpenSwapLog(SwapDir * sd) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; char *path; int fd; path = storeUfsDirSwapLogFile(sd, NULL); fd = file_open(path, O_WRONLY | O_CREAT | O_BINARY); if (fd < 0) { debug(50, 1) ("%s: %s\n", path, xstrerror()); fatal("storeUfsDirOpenSwapLog: Failed to open swap log."); } debug(50, 3) ("Cache Dir #%d log opened on FD %d\n", sd->index, fd); ufsinfo->swaplog_fd = fd; if (0 == n_ufs_dirs) assert(NULL == ufs_dir_index); n_ufs_dirs++; assert(n_ufs_dirs <= Config.cacheSwap.n_configured); } static void storeUfsDirCloseSwapLog(SwapDir * sd) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; if (ufsinfo->swaplog_fd < 0) /* not open */ return; file_close(ufsinfo->swaplog_fd); debug(47, 3) ("Cache Dir #%d log closed on FD %d\n", sd->index, ufsinfo->swaplog_fd); ufsinfo->swaplog_fd = -1; n_ufs_dirs--; assert(n_ufs_dirs >= 0); if (0 == n_ufs_dirs) safe_free(ufs_dir_index); } static void storeUfsDirInit(SwapDir * sd) { static int started_clean_event = 0; static const char *errmsg = "\tFailed to verify one of the swap directories, Check cache.log\n" "\tfor details. Run 'squid -z' to create swap directories\n" "\tif needed, or if running Squid for the first time."; storeUfsDirInitBitmap(sd); if (storeUfsDirVerifyCacheDirs(sd) < 0) fatal(errmsg); storeUfsDirOpenSwapLog(sd); storeUfsDirRebuild(sd); if (!started_clean_event) { eventAdd("storeDirClean", storeUfsDirCleanEvent, NULL, 15.0, 1); started_clean_event = 1; } (void) storeDirGetBlkSize(sd->path, &sd->fs.blksize); } static void storeUfsDirRebuildFromDirectory(void *data) { RebuildState *rb = data; SwapDir *SD = rb->sd; LOCAL_ARRAY(char, hdr_buf, SM_PAGE_SIZE); StoreEntry *e = NULL; StoreEntry tmpe; cache_key key[MD5_DIGEST_CHARS]; sfileno filn = 0; int count; int size; struct stat sb; int swap_hdr_len; int fd = -1; tlv *tlv_list; tlv *t; assert(rb != NULL); debug(47, 3) ("storeUfsDirRebuildFromDirectory: DIR #%d\n", rb->sd->index); for (count = 0; count < rb->speed; count++) { assert(fd == -1); fd = storeUfsDirGetNextFile(rb, &filn, &size); if (fd == -2) { debug(47, 1) ("Done scanning %s swaplog (%d entries)\n", rb->sd->path, rb->n_read); store_dirs_rebuilding--; storeUfsDirCloseTmpSwapLog(rb->sd); storeRebuildComplete(&rb->counts); cbdataFree(rb); return; } else if (fd < 0) { continue; } assert(fd > -1); /* lets get file stats here */ if (fstat(fd, &sb) < 0) { debug(47, 1) ("storeUfsDirRebuildFromDirectory: fstat(FD %d): %s\n", fd, xstrerror()); file_close(fd); store_open_disk_fd--; fd = -1; continue; } if ((++rb->counts.scancount & 0xFFFF) == 0) debug(47, 3) (" %s %7d files opened so far.\n", rb->sd->path, rb->counts.scancount); debug(47, 9) ("file_in: fd=%d %08X\n", fd, filn); statCounter.syscalls.disk.reads++; if (FD_READ_METHOD(fd, hdr_buf, SM_PAGE_SIZE) < 0) { debug(47, 1) ("storeUfsDirRebuildFromDirectory: read(FD %d): %s\n", fd, xstrerror()); file_close(fd); store_open_disk_fd--; fd = -1; continue; } file_close(fd); store_open_disk_fd--; fd = -1; swap_hdr_len = 0; #if USE_TRUNCATE if (sb.st_size == 0) continue; #endif tlv_list = storeSwapMetaUnpack(hdr_buf, &swap_hdr_len); if (tlv_list == NULL) { debug(47, 1) ("storeUfsDirRebuildFromDirectory: failed to get meta data\n"); /* XXX shouldn't this be a call to storeUfsUnlink ? */ storeUfsDirUnlinkFile(SD, filn); continue; } debug(47, 3) ("storeUfsDirRebuildFromDirectory: successful swap meta unpacking\n"); memset(key, '\0', MD5_DIGEST_CHARS); memset(&tmpe, '\0', sizeof(StoreEntry)); for (t = tlv_list; t; t = t->next) { switch (t->type) { case STORE_META_KEY: assert(t->length == MD5_DIGEST_CHARS); xmemcpy(key, t->value, MD5_DIGEST_CHARS); break; case STORE_META_STD: assert(t->length == STORE_HDR_METASIZE); xmemcpy(&tmpe.timestamp, t->value, STORE_HDR_METASIZE); break; default: break; } } storeSwapTLVFree(tlv_list); tlv_list = NULL; if (storeKeyNull(key)) { debug(47, 1) ("storeUfsDirRebuildFromDirectory: NULL key\n"); storeUfsDirUnlinkFile(SD, filn); continue; } tmpe.hash.key = key; /* check sizes */ if (tmpe.swap_file_sz == 0) { tmpe.swap_file_sz = sb.st_size; } else if (tmpe.swap_file_sz == sb.st_size - swap_hdr_len) { tmpe.swap_file_sz = sb.st_size; } else if (tmpe.swap_file_sz != sb.st_size) { debug(47, 1) ("storeUfsDirRebuildFromDirectory: SIZE MISMATCH %ld!=%ld\n", (long int) tmpe.swap_file_sz, (long int) sb.st_size); storeUfsDirUnlinkFile(SD, filn); continue; } if (EBIT_TEST(tmpe.flags, KEY_PRIVATE)) { storeUfsDirUnlinkFile(SD, filn); rb->counts.badflags++; continue; } e = storeGet(key); if (e && e->lastref >= tmpe.lastref) { /* key already exists, current entry is newer */ /* keep old, ignore new */ rb->counts.dupcount++; continue; } else if (NULL != e) { /* URL already exists, this swapfile not being used */ /* junk old, load new */ storeRelease(e); /* release old entry */ rb->counts.dupcount++; } rb->counts.objcount++; storeEntryDump(&tmpe, 5); e = storeUfsDirAddDiskRestore(SD, key, filn, tmpe.swap_file_sz, tmpe.expires, tmpe.timestamp, tmpe.lastref, tmpe.lastmod, tmpe.refcount, /* refcount */ tmpe.flags, /* flags */ (int) rb->flags.clean); storeDirSwapLog(e, SWAP_LOG_ADD); } eventAdd("storeRebuild", storeUfsDirRebuildFromDirectory, rb, 0.0, 1); } static void storeUfsDirRebuildFromSwapLog(void *data) { RebuildState *rb = data; SwapDir *SD = rb->sd; StoreEntry *e = NULL; storeSwapLogData s; size_t ss = sizeof(storeSwapLogData); int count; int used; /* is swapfile already in use? */ int disk_entry_newer; /* is the log entry newer than current entry? */ double x; assert(rb != NULL); /* load a number of objects per invocation */ for (count = 0; count < rb->speed; count++) { if (fread(&s, ss, 1, rb->log) != 1) { debug(47, 1) ("Done reading %s swaplog (%d entries)\n", rb->sd->path, rb->n_read); fclose(rb->log); rb->log = NULL; store_dirs_rebuilding--; storeUfsDirCloseTmpSwapLog(rb->sd); storeRebuildComplete(&rb->counts); cbdataFree(rb); return; } rb->n_read++; if (s.op <= SWAP_LOG_NOP) continue; if (s.op >= SWAP_LOG_MAX) continue; /* * BC: during 2.4 development, we changed the way swap file * numbers are assigned and stored. The high 16 bits used * to encode the SD index number. There used to be a call * to storeDirProperFileno here that re-assigned the index * bits. Now, for backwards compatibility, we just need * to mask it off. */ s.swap_filen &= 0x00FFFFFF; debug(47, 3) ("storeUfsDirRebuildFromSwapLog: %s %s %08X\n", swap_log_op_str[(int) s.op], storeKeyText(s.key), s.swap_filen); if (s.op == SWAP_LOG_ADD) { (void) 0; } else if (s.op == SWAP_LOG_DEL) { if ((e = storeGet(s.key)) != NULL) { /* * Make sure we don't unlink the file, it might be * in use by a subsequent entry. Also note that * we don't have to subtract from store_swap_size * because adding to store_swap_size happens in * the cleanup procedure. */ storeExpireNow(e); storeReleaseRequest(e); if (e->swap_filen > -1) { storeUfsDirReplRemove(e); storeUfsDirMapBitReset(SD, e->swap_filen); e->swap_filen = -1; e->swap_dirn = -1; } storeRelease(e); rb->counts.objcount--; rb->counts.cancelcount++; } continue; } else { x = log(++rb->counts.bad_log_op) / log(10.0); if (0.0 == x - (double) (int) x) debug(47, 1) ("WARNING: %d invalid swap log entries found\n", rb->counts.bad_log_op); rb->counts.invalid++; continue; } if ((++rb->counts.scancount & 0xFFF) == 0) { struct stat sb; if (0 == fstat(fileno(rb->log), &sb)) storeRebuildProgress(SD->index, (int) sb.st_size / ss, rb->n_read); } if (!storeUfsDirValidFileno(SD, s.swap_filen, 0)) { rb->counts.invalid++; continue; } if (EBIT_TEST(s.flags, KEY_PRIVATE)) { rb->counts.badflags++; continue; } e = storeGet(s.key); used = storeUfsDirMapBitTest(SD, s.swap_filen); /* If this URL already exists in the cache, does the swap log * appear to have a newer entry? Compare 'lastref' from the * swap log to e->lastref. */ disk_entry_newer = e ? (s.lastref > e->lastref ? 1 : 0) : 0; if (used && !disk_entry_newer) { /* log entry is old, ignore it */ rb->counts.clashcount++; continue; } else if (used && e && e->swap_filen == s.swap_filen && e->swap_dirn == SD->index) { /* swapfile taken, same URL, newer, update meta */ if (e->store_status == STORE_OK) { e->lastref = s.timestamp; e->timestamp = s.timestamp; e->expires = s.expires; e->lastmod = s.lastmod; e->flags = s.flags; e->refcount += s.refcount; storeUfsDirUnrefObj(SD, e); } else { debug_trap("storeUfsDirRebuildFromSwapLog: bad condition"); debug(47, 1) ("\tSee %s:%d\n", __FILE__, __LINE__); } continue; } else if (used) { /* swapfile in use, not by this URL, log entry is newer */ /* This is sorta bad: the log entry should NOT be newer at this * point. If the log is dirty, the filesize check should have * caught this. If the log is clean, there should never be a * newer entry. */ debug(47, 1) ("WARNING: newer swaplog entry for dirno %d, fileno %08X\n", SD->index, s.swap_filen); /* I'm tempted to remove the swapfile here just to be safe, * but there is a bad race condition in the NOVM version if * the swapfile has recently been opened for writing, but * not yet opened for reading. Because we can't map * swapfiles back to StoreEntrys, we don't know the state * of the entry using that file. */ /* We'll assume the existing entry is valid, probably because * were in a slow rebuild and the the swap file number got taken * and the validation procedure hasn't run. */ assert(rb->flags.need_to_validate); rb->counts.clashcount++; continue; } else if (e && !disk_entry_newer) { /* key already exists, current entry is newer */ /* keep old, ignore new */ rb->counts.dupcount++; continue; } else if (e) { /* key already exists, this swapfile not being used */ /* junk old, load new */ storeExpireNow(e); storeReleaseRequest(e); if (e->swap_filen > -1) { storeUfsDirReplRemove(e); /* Make sure we don't actually unlink the file */ storeUfsDirMapBitReset(SD, e->swap_filen); e->swap_filen = -1; e->swap_dirn = -1; } storeRelease(e); rb->counts.dupcount++; } else { /* URL doesnt exist, swapfile not in use */ /* load new */ (void) 0; } /* update store_swap_size */ rb->counts.objcount++; e = storeUfsDirAddDiskRestore(SD, s.key, s.swap_filen, s.swap_file_sz, s.expires, s.timestamp, s.lastref, s.lastmod, s.refcount, s.flags, (int) rb->flags.clean); storeDirSwapLog(e, SWAP_LOG_ADD); } eventAdd("storeRebuild", storeUfsDirRebuildFromSwapLog, rb, 0.0, 1); } static int storeUfsDirGetNextFile(RebuildState * rb, sfileno * filn_p, int *size) { SwapDir *SD = rb->sd; ufsinfo_t *ufsinfo = (ufsinfo_t *) SD->fsdata; int fd = -1; int used = 0; int dirs_opened = 0; debug(47, 3) ("storeUfsDirGetNextFile: flag=%d, %d: /%02X/%02X\n", rb->flags.init, rb->sd->index, rb->curlvl1, rb->curlvl2); if (rb->done) return -2; while (fd < 0 && rb->done == 0) { fd = -1; if (0 == rb->flags.init) { /* initialize, open first file */ rb->done = 0; rb->curlvl1 = 0; rb->curlvl2 = 0; rb->in_dir = 0; rb->flags.init = 1; assert(Config.cacheSwap.n_configured > 0); } if (0 == rb->in_dir) { /* we need to read in a new directory */ snprintf(rb->fullpath, SQUID_MAXPATHLEN, "%s/%02X/%02X", rb->sd->path, rb->curlvl1, rb->curlvl2); if (dirs_opened) return -1; rb->td = opendir(rb->fullpath); dirs_opened++; if (rb->td == NULL) { debug(47, 1) ("storeUfsDirGetNextFile: opendir: %s: %s\n", rb->fullpath, xstrerror()); } else { rb->entry = readdir(rb->td); /* skip . and .. */ rb->entry = readdir(rb->td); if (rb->entry == NULL && errno == ENOENT) debug(47, 1) ("storeUfsDirGetNextFile: directory does not exist!.\n"); debug(47, 3) ("storeUfsDirGetNextFile: Directory %s\n", rb->fullpath); } } if (rb->td != NULL && (rb->entry = readdir(rb->td)) != NULL) { rb->in_dir++; if (sscanf(rb->entry->d_name, "%x", &rb->fn) != 1) { debug(47, 3) ("storeUfsDirGetNextFile: invalid %s\n", rb->entry->d_name); continue; } if (!storeUfsFilenoBelongsHere(rb->fn, rb->sd->index, rb->curlvl1, rb->curlvl2)) { debug(47, 3) ("storeUfsDirGetNextFile: %08X does not belong in %d/%d/%d\n", rb->fn, rb->sd->index, rb->curlvl1, rb->curlvl2); continue; } used = storeUfsDirMapBitTest(SD, rb->fn); if (used) { debug(47, 3) ("storeUfsDirGetNextFile: Locked, continuing with next.\n"); continue; } snprintf(rb->fullfilename, SQUID_MAXPATHLEN, "%s/%s", rb->fullpath, rb->entry->d_name); debug(47, 3) ("storeUfsDirGetNextFile: Opening %s\n", rb->fullfilename); fd = file_open(rb->fullfilename, O_RDONLY | O_BINARY); if (fd < 0) debug(47, 1) ("storeUfsDirGetNextFile: %s: %s\n", rb->fullfilename, xstrerror()); else store_open_disk_fd++; continue; } if (rb->td != NULL) closedir(rb->td); rb->td = NULL; rb->in_dir = 0; if (++rb->curlvl2 < ufsinfo->l2) continue; rb->curlvl2 = 0; if (++rb->curlvl1 < ufsinfo->l1) continue; rb->curlvl1 = 0; rb->done = 1; } *filn_p = rb->fn; return fd; } /* Add a new object to the cache with empty memory copy and pointer to disk * use to rebuild store from disk. */ static StoreEntry * storeUfsDirAddDiskRestore(SwapDir * SD, const cache_key * key, int file_number, size_t swap_file_sz, time_t expires, time_t timestamp, time_t lastref, time_t lastmod, u_int32_t refcount, u_int16_t flags, int clean) { StoreEntry *e = NULL; debug(47, 5) ("storeUfsAddDiskRestore: %s, fileno=%08X\n", storeKeyText(key), file_number); /* if you call this you'd better be sure file_number is not * already in use! */ e = new_StoreEntry(STORE_ENTRY_WITHOUT_MEMOBJ, NULL, NULL); e->store_status = STORE_OK; storeSetMemStatus(e, NOT_IN_MEMORY); e->swap_status = SWAPOUT_DONE; e->swap_filen = file_number; e->swap_dirn = SD->index; e->swap_file_sz = swap_file_sz; e->lock_count = 0; e->lastref = lastref; e->timestamp = timestamp; e->expires = expires; e->lastmod = lastmod; e->refcount = refcount; e->flags = flags; EBIT_SET(e->flags, ENTRY_CACHABLE); EBIT_CLR(e->flags, RELEASE_REQUEST); EBIT_CLR(e->flags, KEY_PRIVATE); e->ping_status = PING_NONE; EBIT_CLR(e->flags, ENTRY_VALIDATED); storeUfsDirMapBitSet(SD, e->swap_filen); storeHashInsert(e, key); /* do it after we clear KEY_PRIVATE */ storeUfsDirReplAdd(SD, e); return e; } CBDATA_TYPE(RebuildState); static void storeUfsDirRebuild(SwapDir * sd) { RebuildState *rb; int clean = 0; int zero = 0; FILE *fp; EVH *func = NULL; CBDATA_INIT_TYPE(RebuildState); rb = cbdataAlloc(RebuildState); rb->sd = sd; rb->speed = opt_foreground_rebuild ? 1 << 30 : 50; /* * If the swap.state file exists in the cache_dir, then * we'll use storeUfsDirRebuildFromSwapLog(), otherwise we'll * use storeUfsDirRebuildFromDirectory() to open up each file * and suck in the meta data. */ fp = storeUfsDirOpenTmpSwapLog(sd, &clean, &zero); if (fp == NULL || zero) { if (fp != NULL) fclose(fp); func = storeUfsDirRebuildFromDirectory; } else { func = storeUfsDirRebuildFromSwapLog; rb->log = fp; rb->flags.clean = (unsigned int) clean; } if (!clean) rb->flags.need_to_validate = 1; debug(47, 1) ("Rebuilding storage in %s (%s)\n", sd->path, clean ? "CLEAN" : "DIRTY"); store_dirs_rebuilding++; eventAdd("storeRebuild", func, rb, 0.0, 1); } static void storeUfsDirCloseTmpSwapLog(SwapDir * sd) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; char *swaplog_path = xstrdup(storeUfsDirSwapLogFile(sd, NULL)); char *new_path = xstrdup(storeUfsDirSwapLogFile(sd, ".new")); int fd; file_close(ufsinfo->swaplog_fd); #if defined(_SQUID_OS2_) || defined(_SQUID_CYGWIN_) || defined(_SQUID_MSWIN_) if (unlink(swaplog_path) < 0) { debug(50, 0) ("%s: %s\n", swaplog_path, xstrerror()); fatal("storeUfsDirCloseTmpSwapLog: unlink failed"); } #endif if (xrename(new_path, swaplog_path) < 0) { fatal("storeUfsDirCloseTmpSwapLog: rename failed"); } fd = file_open(swaplog_path, O_WRONLY | O_CREAT | O_BINARY); if (fd < 0) { debug(50, 1) ("%s: %s\n", swaplog_path, xstrerror()); fatal("storeUfsDirCloseTmpSwapLog: Failed to open swap log."); } safe_free(swaplog_path); safe_free(new_path); ufsinfo->swaplog_fd = fd; debug(47, 3) ("Cache Dir #%d log opened on FD %d\n", sd->index, fd); } static FILE * storeUfsDirOpenTmpSwapLog(SwapDir * sd, int *clean_flag, int *zero_flag) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; char *swaplog_path = xstrdup(storeUfsDirSwapLogFile(sd, NULL)); char *clean_path = xstrdup(storeUfsDirSwapLogFile(sd, ".last-clean")); char *new_path = xstrdup(storeUfsDirSwapLogFile(sd, ".new")); struct stat log_sb; struct stat clean_sb; FILE *fp; int fd; if (stat(swaplog_path, &log_sb) < 0) { debug(47, 1) ("Cache Dir #%d: No log file\n", sd->index); safe_free(swaplog_path); safe_free(clean_path); safe_free(new_path); return NULL; } *zero_flag = log_sb.st_size == 0 ? 1 : 0; /* close the existing write-only FD */ if (ufsinfo->swaplog_fd >= 0) file_close(ufsinfo->swaplog_fd); /* open a write-only FD for the new log */ fd = file_open(new_path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY); if (fd < 0) { debug(50, 1) ("%s: %s\n", new_path, xstrerror()); fatal("storeDirOpenTmpSwapLog: Failed to open swap log."); } ufsinfo->swaplog_fd = fd; /* open a read-only stream of the old log */ fp = fopen(swaplog_path, "rb"); if (fp == NULL) { debug(50, 0) ("%s: %s\n", swaplog_path, xstrerror()); fatal("Failed to open swap log for reading"); } memset(&clean_sb, '\0', sizeof(struct stat)); if (stat(clean_path, &clean_sb) < 0) *clean_flag = 0; else if (clean_sb.st_mtime < log_sb.st_mtime) *clean_flag = 0; else *clean_flag = 1; safeunlink(clean_path, 1); safe_free(swaplog_path); safe_free(clean_path); safe_free(new_path); return fp; } struct _clean_state { char *cur; char *new; char *cln; char *outbuf; off_t outbuf_offset; int fd; RemovalPolicyWalker *walker; }; #define CLEAN_BUF_SZ 16384 /* * Begin the process to write clean cache state. For UFS this means * opening some log files and allocating write buffers. Return 0 if * we succeed, and assign the 'func' and 'data' return pointers. */ static int storeUfsDirWriteCleanStart(SwapDir * sd) { struct _clean_state *state = xcalloc(1, sizeof(*state)); #if HAVE_FCHMOD struct stat sb; #endif sd->log.clean.write = NULL; sd->log.clean.state = NULL; state->new = xstrdup(storeUfsDirSwapLogFile(sd, ".clean")); state->fd = file_open(state->new, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY); if (state->fd < 0) { xfree(state->new); xfree(state); return -1; } state->cur = xstrdup(storeUfsDirSwapLogFile(sd, NULL)); state->cln = xstrdup(storeUfsDirSwapLogFile(sd, ".last-clean")); state->outbuf = xcalloc(CLEAN_BUF_SZ, 1); state->outbuf_offset = 0; state->walker = sd->repl->WalkInit(sd->repl); unlink(state->cln); debug(47, 3) ("storeDirWriteCleanLogs: opened %s, FD %d\n", state->new, state->fd); #if HAVE_FCHMOD if (stat(state->cur, &sb) == 0) fchmod(state->fd, sb.st_mode); #endif sd->log.clean.write = storeUfsDirWriteCleanEntry; sd->log.clean.state = state; return 0; } /* * Get the next entry that is a candidate for clean log writing */ const StoreEntry * storeUfsDirCleanLogNextEntry(SwapDir * sd) { const StoreEntry *entry = NULL; struct _clean_state *state = sd->log.clean.state; if (state->walker) entry = state->walker->Next(state->walker); return entry; } /* * "write" an entry to the clean log file. */ static void storeUfsDirWriteCleanEntry(SwapDir * sd, const StoreEntry * e) { storeSwapLogData s; static size_t ss = sizeof(storeSwapLogData); struct _clean_state *state = sd->log.clean.state; memset(&s, '\0', ss); s.op = (char) SWAP_LOG_ADD; s.swap_filen = e->swap_filen; s.timestamp = e->timestamp; s.lastref = e->lastref; s.expires = e->expires; s.lastmod = e->lastmod; s.swap_file_sz = e->swap_file_sz; s.refcount = e->refcount; s.flags = e->flags; xmemcpy(&s.key, e->hash.key, MD5_DIGEST_CHARS); xmemcpy(state->outbuf + state->outbuf_offset, &s, ss); state->outbuf_offset += ss; /* buffered write */ if (state->outbuf_offset + ss > CLEAN_BUF_SZ) { if (FD_WRITE_METHOD(state->fd, state->outbuf, state->outbuf_offset) < 0) { debug(50, 0) ("storeDirWriteCleanLogs: %s: write: %s\n", state->new, xstrerror()); debug(50, 0) ("storeDirWriteCleanLogs: Current swap logfile not replaced.\n"); file_close(state->fd); state->fd = -1; unlink(state->new); safe_free(state); sd->log.clean.state = NULL; sd->log.clean.write = NULL; return; } state->outbuf_offset = 0; } } static void storeUfsDirWriteCleanDone(SwapDir * sd) { int fd; struct _clean_state *state = sd->log.clean.state; if (NULL == state) return; if (state->fd < 0) return; state->walker->Done(state->walker); if (FD_WRITE_METHOD(state->fd, state->outbuf, state->outbuf_offset) < 0) { debug(50, 0) ("storeDirWriteCleanLogs: %s: write: %s\n", state->new, xstrerror()); debug(50, 0) ("storeDirWriteCleanLogs: Current swap logfile " "not replaced.\n"); file_close(state->fd); state->fd = -1; unlink(state->new); } safe_free(state->outbuf); /* * You can't rename open files on Microsoft "operating systems" * so we have to close before renaming. */ storeUfsDirCloseSwapLog(sd); /* save the fd value for a later test */ fd = state->fd; /* rename */ if (state->fd >= 0) { #if defined(_SQUID_OS2_) || defined(_SQUID_CYGWIN_) || defined(_SQUID_MSWIN_) file_close(state->fd); state->fd = -1; if (unlink(state->cur) < 0) debug(50, 0) ("storeDirWriteCleanLogs: unlinkd failed: %s, %s\n", xstrerror(), state->cur); #endif xrename(state->new, state->cur); } /* touch a timestamp file if we're not still validating */ if (store_dirs_rebuilding) (void) 0; else if (fd < 0) (void) 0; else file_close(file_open(state->cln, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY)); /* close */ safe_free(state->cur); safe_free(state->new); safe_free(state->cln); if (state->fd >= 0) file_close(state->fd); state->fd = -1; safe_free(state); sd->log.clean.state = NULL; sd->log.clean.write = NULL; } static void storeSwapLogDataFree(void *s) { memFree(s, MEM_SWAP_LOG_DATA); } static void storeUfsDirSwapLog(const SwapDir * sd, const StoreEntry * e, int op) { ufsinfo_t *ufsinfo = (ufsinfo_t *) sd->fsdata; storeSwapLogData *s = memAllocate(MEM_SWAP_LOG_DATA); s->op = (char) op; s->swap_filen = e->swap_filen; s->timestamp = e->timestamp; s->lastref = e->lastref; s->expires = e->expires; s->lastmod = e->lastmod; s->swap_file_sz = e->swap_file_sz; s->refcount = e->refcount; s->flags = e->flags; xmemcpy(s->key, e->hash.key, MD5_DIGEST_CHARS); file_write(ufsinfo->swaplog_fd, -1, s, sizeof(storeSwapLogData), NULL, NULL, (FREE *) storeSwapLogDataFree); } static void storeUfsDirNewfs(SwapDir * sd) { debug(47, 3) ("Creating swap space in %s\n", sd->path); storeUfsDirCreateDirectory(sd->path, 0); storeUfsDirCreateSwapSubDirs(sd); } static int rev_int_sort(const void *A, const void *B) { const int *i1 = A; const int *i2 = B; return *i2 - *i1; } static int storeUfsDirClean(int swap_index) { DIR *dp = NULL; struct dirent *de = NULL; LOCAL_ARRAY(char, p1, MAXPATHLEN + 1); LOCAL_ARRAY(char, p2, MAXPATHLEN + 1); #if USE_TRUNCATE struct stat sb; #endif int files[20]; int swapfileno; int fn; /* same as swapfileno, but with dirn bits set */ int n = 0; int k = 0; int N0, N1, N2; int D0, D1, D2; SwapDir *SD; ufsinfo_t *ufsinfo; N0 = n_ufs_dirs; D0 = ufs_dir_index[swap_index % N0]; SD = &Config.cacheSwap.swapDirs[D0]; ufsinfo = (ufsinfo_t *) SD->fsdata; N1 = ufsinfo->l1; D1 = (swap_index / N0) % N1; N2 = ufsinfo->l2; D2 = ((swap_index / N0) / N1) % N2; snprintf(p1, SQUID_MAXPATHLEN, "%s/%02X/%02X", Config.cacheSwap.swapDirs[D0].path, D1, D2); debug(36, 3) ("storeDirClean: Cleaning directory %s\n", p1); dp = opendir(p1); if (dp == NULL) { if (errno == ENOENT) { debug(36, 0) ("storeDirClean: WARNING: Creating %s\n", p1); if (mkdir(p1, 0777) == 0) return 0; } debug(50, 0) ("storeDirClean: %s: %s\n", p1, xstrerror()); safeunlink(p1, 1); return 0; } while ((de = readdir(dp)) != NULL && k < 20) { if (sscanf(de->d_name, "%X", &swapfileno) != 1) continue; fn = swapfileno; /* XXX should remove this cruft ! */ if (storeUfsDirValidFileno(SD, fn, 1)) if (storeUfsDirMapBitTest(SD, fn)) if (storeUfsFilenoBelongsHere(fn, D0, D1, D2)) continue; #if USE_TRUNCATE if (!stat(de->d_name, &sb)) if (sb.st_size == 0) continue; #endif files[k++] = swapfileno; } closedir(dp); if (k == 0) return 0; qsort(files, k, sizeof(int), rev_int_sort); if (k > 10) k = 10; for (n = 0; n < k; n++) { debug(36, 3) ("storeDirClean: Cleaning file %08X\n", files[n]); snprintf(p2, MAXPATHLEN + 1, "%s/%08X", p1, files[n]); #if USE_TRUNCATE truncate(p2, 0); #else safeunlink(p2, 0); #endif statCounter.swap.files_cleaned++; } debug(36, 3) ("Cleaned %d unused files from %s\n", k, p1); return k; } static void storeUfsDirCleanEvent(void *unused) { static int swap_index = 0; int i; int j = 0; int n = 0; /* * Assert that there are UFS cache_dirs configured, otherwise * we should never be called. */ assert(n_ufs_dirs); if (NULL == ufs_dir_index) { SwapDir *sd; ufsinfo_t *ufsinfo; /* * Initialize the little array that translates UFS cache_dir * number into the Config.cacheSwap.swapDirs array index. */ ufs_dir_index = xcalloc(n_ufs_dirs, sizeof(*ufs_dir_index)); for (i = 0, n = 0; i < Config.cacheSwap.n_configured; i++) { sd = &Config.cacheSwap.swapDirs[i]; if (!storeUfsDirIs(sd)) continue; ufs_dir_index[n++] = i; ufsinfo = (ufsinfo_t *) sd->fsdata; j += (ufsinfo->l1 * ufsinfo->l2); } assert(n == n_ufs_dirs); /* * Start the storeUfsDirClean() swap_index with a random * value. j equals the total number of UFS level 2 * swap directories */ swap_index = (int) (squid_random() % j); } if (0 == store_dirs_rebuilding) { n = storeUfsDirClean(swap_index); swap_index++; } eventAdd("storeDirClean", storeUfsDirCleanEvent, NULL, 15.0 * exp(-0.25 * n), 1); } static int storeUfsDirIs(SwapDir * sd) { if (strncmp(sd->type, "ufs", 3) == 0) return 1; return 0; } /* * Does swapfile number 'fn' belong in cachedir #F0, * level1 dir #F1, level2 dir #F2? */ static int storeUfsFilenoBelongsHere(int fn, int F0, int F1, int F2) { int D1, D2; int L1, L2; int filn = fn; ufsinfo_t *ufsinfo; assert(F0 < Config.cacheSwap.n_configured); ufsinfo = (ufsinfo_t *) Config.cacheSwap.swapDirs[F0].fsdata; L1 = ufsinfo->l1; L2 = ufsinfo->l2; D1 = ((filn / L2) / L2) % L1; if (F1 != D1) return 0; D2 = (filn / L2) % L2; if (F2 != D2) return 0; return 1; } int storeUfsDirValidFileno(SwapDir * SD, sfileno filn, int flag) { ufsinfo_t *ufsinfo = (ufsinfo_t *) SD->fsdata; if (filn < 0) return 0; /* * If flag is set it means out-of-range file number should * be considered invalid. */ if (flag) if (filn > ufsinfo->map->max_n_files) return 0; return 1; } void storeUfsDirMaintain(SwapDir * SD) { StoreEntry *e = NULL; int removed = 0; int max_scan; int max_remove; double f; RemovalPurgeWalker *walker; /* We can't delete objects while rebuilding swap */ if (store_dirs_rebuilding) { return; } else { f = (double) (SD->cur_size - SD->low_size) / (SD->max_size - SD->low_size); f = f < 0.0 ? 0.0 : f > 1.0 ? 1.0 : f; max_scan = (int) (f * 400.0 + 100.0); max_remove = (int) (f * 70.0 + 10.0); /* * This is kinda cheap, but so we need this priority hack? */ } debug(47, 3) ("storeMaintainSwapSpace: f=%f, max_scan=%d, max_remove=%d\n", f, max_scan, max_remove); walker = SD->repl->PurgeInit(SD->repl, max_scan); while (1) { if (SD->cur_size < SD->low_size) break; if (removed >= max_remove) break; e = walker->Next(walker); if (!e) break; /* no more objects */ removed++; storeRelease(e); } walker->Done(walker); debug(47, (removed ? 2 : 3)) ("storeUfsDirMaintain: %s removed %d/%d f=%.03f max_scan=%d\n", SD->path, removed, max_remove, f, max_scan); } /* * storeUfsDirCheckObj *
[ "993273596@qq.com" ]
993273596@qq.com
40a9a19aa8e8d85d8d3f89c1c105dd16a429702a
35da9be0bcc91853b6c13ee8499010eede5b4168
/wayland/weston/wayland-ivi-extension/ivi-layermanagement-examples/LayerManagerControl/src/sceneio.cpp
787034b34b3e09e4c01991d2543205c3d2f684b8
[ "MIT", "Apache-2.0" ]
permissive
wjhtinger/NV-samples
147849108288c6a812d380998845d6650df5b254
bfeece5d41aab77299ece8aab6d8e9f39f7d98d7
refs/heads/master
2021-09-01T06:16:36.371098
2017-12-25T08:56:33
2017-12-25T08:56:33
107,506,562
3
1
null
null
null
null
UTF-8
C++
false
false
24,964
cpp
/*************************************************************************** * * Copyright 2012 BMW Car IT GmbH * * * 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 "ilm_client.h" #include "ilm_control.h" #include "LMControl.h" #include "Expression.h" #include "ExpressionInterpreter.h" #include "SceneStore.h" #include <cstdio> #include <cmath> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include <map> #include <set> #include <algorithm> #include <iterator> #include <cstring> #include <pthread.h> #include <stdarg.h> using namespace std; namespace { void captureSceneDataHelper(t_ilm_surface surfaceId, t_scene_data* pSceneData, IlmSurface* pSurface) { ilmSurfaceProperties& props = pSceneData->surfaceProperties[surfaceId]; pSurface->set("id", surfaceId); pSurface->set("destHeight", props.destHeight); pSurface->set("destWidth", props.destWidth); pSurface->set("destX", props.destX); pSurface->set("destY", props.destY); pSurface->set("drawCounter", props.drawCounter); pSurface->set("frameCounter", props.frameCounter); pSurface->set("nativeSurface", props.nativeSurface); pSurface->set("opacity", props.opacity); pSurface->set("orientation", props.orientation); pSurface->set("origSourceHeight", props.origSourceHeight); pSurface->set("origSourceWidth", props.origSourceWidth); pSurface->set("pixelformat", props.pixelformat); pSurface->set("sourceHeight", props.sourceHeight); pSurface->set("sourceWidth", props.sourceWidth); pSurface->set("sourceX", props.sourceX); pSurface->set("sourceY", props.sourceY); pSurface->set("updateCounter", props.updateCounter); pSurface->set("visibility", props.visibility); } void captureSceneDataHelper(t_ilm_layer layerId, t_scene_data* pSceneData, IlmLayer* pLayer) { ilmLayerProperties& props = pSceneData->layerProperties[layerId]; pLayer->set("id", layerId); pLayer->set("destHeight", props.destHeight); pLayer->set("destWidth", props.destWidth); pLayer->set("destX", props.destX); pLayer->set("destY", props.destY); pLayer->set("opacity", props.opacity); pLayer->set("orientation", props.orientation); pLayer->set("origSourceHeight", props.origSourceHeight); pLayer->set("origSourceWidth", props.origSourceWidth); pLayer->set("sourceHeight", props.sourceHeight); pLayer->set("sourceWidth", props.sourceWidth); pLayer->set("sourceX", props.sourceX); pLayer->set("sourceY", props.sourceY); pLayer->set("type", props.type); pLayer->set("visibility", props.visibility); if (pSceneData->layerSurfaces.find(layerId) != pSceneData->layerSurfaces.end()) { for (vector<t_ilm_surface>::iterator it = pSceneData->layerSurfaces[layerId].begin(); it != pSceneData->layerSurfaces[layerId].end(); ++it) { IlmSurface* pIlmsurface = new IlmSurface; captureSceneDataHelper(*it, pSceneData, pIlmsurface); pLayer->add(pIlmsurface); } } } void captureSceneData(IlmScene* scene) { t_scene_data sceneStruct; captureSceneData(&sceneStruct); for (vector<t_ilm_display>::iterator it = sceneStruct.screens.begin(); it != sceneStruct.screens.end(); ++it) { t_ilm_display displayId = *it; IlmDisplay* pIlmdisplay = new IlmDisplay; pIlmdisplay->set("id", displayId); pIlmdisplay->set("width", sceneStruct.screenWidth); pIlmdisplay->set("height", sceneStruct.screenHeight); if (sceneStruct.screenLayers.find(displayId) != sceneStruct.screenLayers.end()) { for (vector<t_ilm_layer>::iterator it = sceneStruct.screenLayers[displayId].begin(); it != sceneStruct.screenLayers[displayId].end(); ++it) { IlmLayer* pIlmlayer = new IlmLayer; captureSceneDataHelper(*it, &sceneStruct, pIlmlayer); pIlmdisplay->add(pIlmlayer); } } scene->add(pIlmdisplay); } for (vector<t_ilm_layer>::iterator it = sceneStruct.layers.begin(); it != sceneStruct.layers.end(); ++it) { if (sceneStruct.layerScreen.find(*it) == sceneStruct.layerScreen.end()) { IlmLayer* pIlmlayer = new IlmLayer; captureSceneDataHelper(*it, &sceneStruct, pIlmlayer); scene->add(pIlmlayer); } } for (vector<t_ilm_surface>::iterator it = sceneStruct.surfaces.begin(); it != sceneStruct.surfaces.end(); ++it) { if (sceneStruct.surfaceLayer.find(*it) == sceneStruct.surfaceLayer.end()) { IlmSurface* pIlmsurface = new IlmSurface; captureSceneDataHelper(*it, &sceneStruct, pIlmsurface); scene->add(pIlmsurface); } } } string encodeEscapesequences(string s) { map<string, string> code; code["\\"] = "\\[\\]"; code["\n"] = "\\[n]"; code["\t"] = "\\[t]"; code["\v"] = "\\[v]"; code["\b"] = "\\[b]"; code["\f"] = "\\[f]"; code["\r"] = "\\[r]"; return replaceAll(s, code); } void exportSceneToTXTHelper(ostream& stream, StringMapTree* tree, string prefix = "") { stream << prefix << encodeEscapesequences(tree->mNodeLabel) + ":{\n"; for (map<string, pair<string, string> >::iterator it = tree->mNodeValues.begin(); it != tree->mNodeValues.end(); ++it) { stream << prefix + "\t[" + encodeEscapesequences(it->first) + ":" + encodeEscapesequences(it->second.first) + "]=[" + encodeEscapesequences(it->second.second) + "]\n"; } for (list<StringMapTree*>::iterator it = tree->mChildren.begin(); it != tree->mChildren.end(); ++it) { exportSceneToTXTHelper(stream, *it, prefix + "\t"); stream << "\n"; } stream << prefix + "}"; } string decodeEscapesequences(string s) { map<string, string> code; code["\\[\\]"] = "\\"; code["\\[n]"] = "\n"; code["\\[t]"] = "\t"; code["\\[v]"] = "\v"; code["\\[b]"] = "\b"; code["\\[f]"] = "\f"; code["\\[r]"] = "\r"; return replaceAll(s, code); } void importSceneFromTXTHelper(istream& stream, StringMapTree* node) { string in; //Type getline(stream, in); int typeSize = in.find(":") - in.find_first_not_of('\t'); int typeStart = in.find_first_not_of('\t'); node->mNodeLabel = in.substr(typeStart, typeSize); while (true) { long streamPosition = stream.tellg(); getline(stream, in); in = rtrim(in); //end of object if (in.substr(0, 1) == "}") return; //start of object property if (in.substr(0, 1) == "[") { int startIndex = in.find('[') + 1; int endIndex = in.find(":"); string propertyName = in.substr(startIndex, endIndex - startIndex); propertyName = decodeEscapesequences(propertyName); startIndex = endIndex + 1; endIndex = in.find("]"); string propertyType = in.substr(startIndex, endIndex - startIndex); propertyType = decodeEscapesequences(propertyType); startIndex = in.find('[', endIndex) + 1; endIndex = in.find_last_of(']'); string propertyValue = in.substr(startIndex, endIndex - startIndex); propertyValue = decodeEscapesequences(propertyValue); node->mNodeValues[propertyName] = make_pair(propertyType, propertyValue); } else { stream.seekg(streamPosition); StringMapTree* child = new StringMapTree; node->mChildren.push_back(child); importSceneFromTXTHelper(stream, child); } } } string makeValidXMLCharacters(string s) { map<string, string> code; code["<"] = "&lt;"; code[">"] = "&gt;"; code["&"] = "&amp;"; code["\'"] = "&apos;"; code["\""] = "&quot;"; return replaceAll(s, code); } void exportSceneToXMLHelper(ostream& stream, StringMapTree* tree, string prefix = "") { stream << prefix << "<" << tree->mNodeLabel << ">\n"; for (map<string, pair<string, string> >::iterator it = tree->mNodeValues.begin(); it != tree->mNodeValues.end(); ++it) { stream << prefix + "\t<Property name=\"" << it->first << "\" type=\"" << it->second.first << "\">\n"; stream << prefix << "\t\t" << makeValidXMLCharacters(it->second.second) + "\n"; stream << prefix << "\t</Property>\n"; } for (list<StringMapTree*>::iterator it = tree->mChildren.begin(); it != tree->mChildren.end(); ++it) { exportSceneToXMLHelper(stream, *it, prefix + "\t"); stream << "\n"; } stream << prefix << "</" << tree->mNodeLabel << ">\n"; } ilmPixelFormat toPixelFormat(t_ilm_int format) { switch (format) { case 0: return ILM_PIXELFORMAT_R_8; case 1: return ILM_PIXELFORMAT_RGB_888; case 2: return ILM_PIXELFORMAT_RGBA_8888; case 3: return ILM_PIXELFORMAT_RGB_565; case 4: return ILM_PIXELFORMAT_RGBA_5551; case 5: return ILM_PIXELFORMAT_RGBA_6661; case 6: return ILM_PIXELFORMAT_RGBA_4444; } return ILM_PIXEL_FORMAT_UNKNOWN; } ilmSurfaceProperties getSurfaceProperties(IlmSurface* pIlmsurface) { ilmSurfaceProperties props; pIlmsurface->get("destHeight", &(props.destHeight)); pIlmsurface->get("destWidth", &(props.destWidth)); pIlmsurface->get("destX", &(props.destX)); pIlmsurface->get("destY", &(props.destY)); pIlmsurface->get("drawCounter", &(props.drawCounter)); pIlmsurface->get("frameCounter", &(props.frameCounter)); pIlmsurface->get("nativeSurface", &(props.nativeSurface)); pIlmsurface->get("opacity", &(props.opacity)); pIlmsurface->get("orientation", &(props.orientation)); pIlmsurface->get("origSourceHeight", &(props.origSourceHeight)); pIlmsurface->get("origSourceWidth", &(props.origSourceWidth)); pIlmsurface->get("pixelformat", &(props.pixelformat)); pIlmsurface->get("sourceHeight", &(props.sourceHeight)); pIlmsurface->get("sourceWidth", &(props.sourceWidth)); pIlmsurface->get("sourceX", &(props.sourceX)); pIlmsurface->get("sourceY", &(props.sourceY)); pIlmsurface->get("updateCounter", &(props.updateCounter)); pIlmsurface->get("visibility", &(props.visibility)); return props; } ilmLayerProperties getLayerProperties(IlmLayer* pIlmlayer) { ilmLayerProperties props; pIlmlayer->get("destHeight", &(props.destHeight)); pIlmlayer->get("destWidth", &(props.destWidth)); pIlmlayer->get("destX", &(props.destX)); pIlmlayer->get("destY", &(props.destY)); pIlmlayer->get("opacity", &(props.opacity)); pIlmlayer->get("orientation", &(props.orientation)); pIlmlayer->get("origSourceHeight", &(props.origSourceHeight)); pIlmlayer->get("origSourceHeight", &(props.origSourceHeight)); pIlmlayer->get("origSourceWidth", &(props.origSourceWidth)); pIlmlayer->get("sourceHeight", &(props.sourceHeight)); pIlmlayer->get("sourceWidth", &(props.sourceWidth)); pIlmlayer->get("sourceX", &(props.sourceX)); pIlmlayer->get("sourceY", &(props.sourceY)); pIlmlayer->get("type", &(props.type)); pIlmlayer->get("visibility", &(props.visibility)); return props; } void createSceneContentsHelper(IlmSurface* pIlmsurface) { t_ilm_surface surfaceId; pIlmsurface->get("id", &surfaceId); ilmSurfaceProperties props = getSurfaceProperties(pIlmsurface); //if surface does not exist: create it t_ilm_int surfaceCount; t_ilm_surface* surfaceArray; ilmErrorTypes callResult = ilm_getSurfaceIDs(&surfaceCount, &surfaceArray); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to get available surface IDs\n"; } if (find(surfaceArray, surfaceArray + surfaceCount, surfaceId) == surfaceArray + surfaceCount) { ilmPixelFormat pixelFormat; pixelFormat = toPixelFormat(props.pixelformat); ilmErrorTypes callResult = ilm_surfaceCreate(props.nativeSurface, props.origSourceWidth, props.origSourceHeight, pixelFormat, &surfaceId); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to create surface\n"; } } } void createSceneContentsHelper(IlmLayer* pIlmlayer) { t_ilm_layer layerId; pIlmlayer->get("id", &layerId); ilmLayerProperties props = getLayerProperties(pIlmlayer); //create layer if does not exist t_ilm_int layerCount; t_ilm_layer* layerArray; ilmErrorTypes callResult = ilm_getLayerIDs(&layerCount, &layerArray); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to get available layer IDs\n"; } if (find(layerArray, layerArray + layerCount, layerId) == layerArray + layerCount) { ilmErrorTypes callResult = ilm_layerCreateWithDimension(&layerId, props.origSourceWidth, props.origSourceHeight); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to create layer width dimensions (" << props.origSourceWidth << " ," << props.origSourceHeight << ")\n"; } ilm_commitChanges(); } list<IlmSurface*> surfaceList; pIlmlayer->get(&surfaceList); vector<t_ilm_surface> renderOrder; for (list<IlmSurface*>::iterator it = surfaceList.begin(); it != surfaceList.end(); ++it) { t_ilm_surface surfaceId; (*it)->get("id", &surfaceId); renderOrder.push_back(surfaceId); createSceneContentsHelper(*it); } callResult = ilm_layerSetRenderOrder(layerId, renderOrder.data(), renderOrder.size()); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to set render order for layer with ID " << layerId << ")\n"; } ilm_commitChanges(); } void createSceneContentsHelper(IlmDisplay* pIlmdisplay) { t_ilm_display displayId = 0xFFFFFFFF; pIlmdisplay->get("id", &displayId); list<IlmLayer*> layerList; pIlmdisplay->get(&layerList); vector<t_ilm_layer> renderOrder; for (list<IlmLayer*>::iterator it = layerList.begin(); it != layerList.end(); ++it) { t_ilm_layer layerId; (*it)->get("id", &layerId); renderOrder.push_back(layerId); createSceneContentsHelper(*it); ilm_commitChanges(); } ilmErrorTypes callResult = ilm_displaySetRenderOrder(displayId, renderOrder.data(), renderOrder.size()); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to set render order for display with ID " << displayId << ")\n"; } ilm_commitChanges(); } void createSceneContents(IlmScene* pIlmscene) { list<IlmSurface*> surfaceList; pIlmscene->get(&surfaceList); for (list<IlmSurface*>::iterator it = surfaceList.begin(); it != surfaceList.end(); ++it) { createSceneContentsHelper(*it); } list<IlmLayer*> layerList; pIlmscene->get(&layerList); for (list<IlmLayer*>::iterator it = layerList.begin(); it != layerList.end(); ++it) { createSceneContentsHelper(*it); } list<IlmDisplay*> displayList; pIlmscene->get(&displayList); for (list<IlmDisplay*>::iterator it = displayList.begin(); it != displayList.end(); ++it) { createSceneContentsHelper(*it); } } void restoreSceneHelper(IlmSurface* pIlmsurface) { t_ilm_surface surfaceId = 0xFFFFFFFF; pIlmsurface->get("id", &surfaceId); ilmSurfaceProperties props = getSurfaceProperties(pIlmsurface); ilm_surfaceSetOpacity(surfaceId, props.opacity); ilm_commitChanges(); ilm_surfaceSetOrientation(surfaceId, props.orientation); ilm_commitChanges(); ilm_surfaceSetSourceRectangle(surfaceId, props.sourceX, props.sourceY, props.sourceWidth, props.sourceHeight); ilm_commitChanges(); ilm_surfaceSetDestinationRectangle(surfaceId, props.destX, props.destY, props.destWidth, props.destHeight); ilm_commitChanges(); ilm_surfaceSetVisibility(surfaceId, props.visibility); ilm_commitChanges(); } void restoreSceneHelper(IlmLayer* pIlmlayer) { t_ilm_layer layerId = 0xFFFFFFFF; pIlmlayer->get("id", &layerId); ilmLayerProperties props = getLayerProperties(pIlmlayer); //set layer properties ilmErrorTypes callResult = ilm_layerSetDestinationRectangle(layerId, props.destX, props.destY, props.destWidth, props.destHeight); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to set destination rectangle for layer with ID " << layerId << ")\n"; } ilm_commitChanges(); ilm_layerSetOpacity(layerId, props.opacity); ilm_commitChanges(); ilm_layerSetOrientation(layerId, props.orientation); ilm_commitChanges(); ilm_layerSetSourceRectangle(layerId, props.sourceX, props.sourceY, props.sourceWidth, props.sourceHeight); ilm_commitChanges(); ilm_layerSetVisibility(layerId, props.visibility); ilm_commitChanges(); list<IlmSurface*> surfaceList; pIlmlayer->get(&surfaceList); //restore surfaces for (list<IlmSurface*>::iterator it = surfaceList.begin(); it != surfaceList.end(); ++it) { t_ilm_surface surfaceId; (*it)->get("id", &surfaceId); restoreSceneHelper(*it); } } void restoreSceneHelper(IlmDisplay* pIlmdisplay) { t_ilm_display displayId; pIlmdisplay->get("id", &displayId); list<IlmLayer*> layerList; pIlmdisplay->get(&layerList); for (list<IlmLayer*>::iterator it = layerList.begin(); it != layerList.end(); ++it) { t_ilm_layer layerId; (*it)->get("id", &layerId); restoreSceneHelper(*it); ilm_commitChanges(); } } void restoreScene(IlmScene* pIlmscene) { t_scene_data currentScene; captureSceneData(&currentScene); //remove all surfaces from all layers for (map<t_ilm_surface, t_ilm_layer>::iterator it = currentScene.surfaceLayer.begin(); it != currentScene.surfaceLayer.end(); ++it) { ilmErrorTypes callResult = ilm_layerRemoveSurface(it->second, it->first); if (ILM_SUCCESS != callResult) { cout << "LayerManagerService returned: " << ILM_ERROR_STRING(callResult) << "\n"; cout << "Failed to remove surface " << it->first << " from layer " << it->second << ")\n"; } } ilm_commitChanges(); //create scene contents createSceneContents(pIlmscene); //restore scene list<IlmSurface*> surfaceList; pIlmscene->get(&surfaceList); for (list<IlmSurface*>::iterator it = surfaceList.begin(); it != surfaceList.end(); ++it) { restoreSceneHelper(*it); } list<IlmLayer*> layerList; pIlmscene->get(&layerList); for (list<IlmLayer*>::iterator it = layerList.begin(); it != layerList.end(); ++it) { restoreSceneHelper(*it); } list<IlmDisplay*> displayList; pIlmscene->get(&displayList); for (list<IlmDisplay*>::iterator it = displayList.begin(); it != displayList.end(); ++it) { restoreSceneHelper(*it); } } } //end of anonymous namespace void exportSceneToFile(string filename) { IlmScene ilmscene; IlmScene* pScene = &ilmscene; captureSceneData(&ilmscene); stringstream buffer; StringMapTree sceneTree; pScene->toStringMapTree(&sceneTree); //check extension if (filename.find_last_of(".") != string::npos) { string extension = filename.substr(filename.find_last_of(".")); cout << extension << endl; if (extension == ".xml") { buffer << "<\?xml version=\"1.0\"\?>\n"; exportSceneToXMLHelper(buffer, &sceneTree); cout << "DONE WRITING XML" << endl; } else if (extension == ".txt") { exportSceneToTXTHelper(buffer, &sceneTree); cout << "DONE WRITING TXT" << endl; } } else { //defult: exportSceneToTXTHelper(buffer, &sceneTree); cout << "DONE WRITING TXT" << endl; } fstream stream(filename.c_str(), ios::out); cout << buffer.str() << endl; stream << buffer.str(); stream.flush(); stream.close(); } void importSceneFromFile(string filename) { IlmScene ilmscene; IlmScene* pScene = &ilmscene; fstream stream(filename.c_str(), ios::in); StringMapTree sceneTree; //check extension if (filename.find_last_of(".") != string::npos) { string extension = filename.substr(filename.find_last_of(".")); cout << extension << endl; if (extension == ".xml") { // importSceneFromXMLHelper(stream, &sceneTree); cout << "READING XML IS NOT SUPPORTED YET" << endl; } else if (extension == ".txt") { importSceneFromTXTHelper(stream, &sceneTree); cout << "DONE READING TXT" << endl; } } else { //defult behavior: assume txt importSceneFromTXTHelper(stream, &sceneTree); cout << "DONE READING TXT" << endl; } stream.close(); cout << "Scene Tree :[" << sceneTree.toString() << "]" << endl; pScene->fromStringMapTree(&sceneTree); cout << "Scene successfully created from tree" << endl; restoreScene(pScene); cout << "Scene restored successfully" << endl; } void exportXtext(string fileName, string grammar, string url) { string name = grammar.substr(grammar.find_last_of('.') + 1); //make sure first character is lower case std::transform(name.begin(), ++(name.begin()), name.begin(), ::tolower); IlmScene scene; StringMapTree grammarTree; scene.toGrammarMapTree(&grammarTree); //writing to file stringstream buffer; buffer << "grammar " << grammar << " with org.eclipse.xtext.common.Terminals" << endl; buffer << "generate " << name << " \"" << url << "\"" << endl; list<string> doneTypes; list<StringMapTree*> waitingNodes; waitingNodes.push_back(&grammarTree); while (!waitingNodes.empty()) { //pop first element of the waiting types StringMapTree* typeNode = *(waitingNodes.begin()); waitingNodes.pop_front(); string type = typeNode->mNodeLabel; //if the type was not printed before if (find(doneTypes.begin(), doneTypes.end(), type) == doneTypes.end()) { doneTypes.push_back(type); buffer << type << ":" << endl; buffer << "\t\'" << type << ":\'" << endl; for (map<string, pair<string, string> >::iterator it = typeNode->mNodeValues.begin(); it != typeNode->mNodeValues.end(); ++it) { buffer << "\t\t\'" << it->first << ":\' " << it->first << "=" << (it->second.second.size() > 0 ? it->second.second : it->second.first) << endl; } for (list<StringMapTree*>::iterator it = typeNode->mChildren.begin(); it != typeNode->mChildren.end(); ++it) { waitingNodes.push_back(*it); string childName = (*it)->mNodeLabel; //make lower case std::transform(childName.begin(), childName.end(), childName.begin(), ::tolower); childName += "s"; buffer << "\t\t" << childName << "+=" << (*it)->mNodeLabel << "*" << endl; } buffer << ";" << endl; } } cout << "Xtext:[" << buffer.str() << "]" << endl; fstream fileout(fileName.c_str(), ios::out); fileout << buffer.str(); fileout.flush(); fileout.close(); }
[ "wjhtinger@yeah.net" ]
wjhtinger@yeah.net
4e456eeee054cafb92c787cc310d7fb216395cc5
e456985f34d1911b20597fed1a1003a2adb2c9d8
/dangdone/DangPointer/framework/ASTElement.h
4e7c2992eceef2cf1238b8bcdcf25f21344db3d1
[ "MIT" ]
permissive
DANGDONE/project
bee0e80730b3c6b991da61146891e8ec6dd1dc89
fc4e1f9119a2c317664d5e44a36dd5dbe3e3a9ce
refs/heads/master
2020-05-22T04:23:09.381964
2016-11-11T02:26:49
2016-11-11T02:26:49
65,781,214
2
0
null
null
null
null
UTF-8
C++
false
false
2,518
h
#ifndef AST_ELEMENT_H #define AST_ELEMENT_H #include <string> #include <vector> #include "Common.h" #include "clang/Frontend/ASTUnit.h" using namespace clang; class ASTFunction; class ASTVariable; class ASTFile { public: ASTFile(unsigned id, std::string AST) : id(id), AST(AST) {}; const std::string &getAST() const { return AST; } void addFunction(ASTFunction *F) { functions.push_back(F); } const std::vector<ASTFunction *> &getFunctions() const { return functions; } private: unsigned id; std::string AST; std::vector<ASTFunction *> functions; }; class ASTElement { public: ASTElement(unsigned id, std::string name, ASTFile *AF) : id(id), name(name), AF(AF) {} unsigned getID() const { return id; } const std::string &getName() const { return name; } ASTFile *getASTFile() const { return AF; } const std::string &getAST() const { return AF->getAST(); } protected: unsigned id; std::string name; ASTFile *AF; }; class ASTFunction : public ASTElement { public: ASTFunction(unsigned id, FunctionDecl *FD, ASTFile *AF, bool use = true) : ASTElement(id, FD->getNameAsString(), AF) { this->use = use; fullName = common::getFullName(FD); param_size = FD->param_size(); } void addVariable(ASTVariable *V) { variables.push_back(V); } unsigned getParamSize() const { return param_size; } const std::string &getFullName() const { return fullName; } const std::vector<ASTVariable *> &getVariables() const { return variables; } bool isUse() const { return use; } private: std::string fullName; unsigned param_size; bool use; std::vector<ASTVariable *> variables; }; class ASTVariable : public ASTElement { public: ASTVariable(unsigned id, VarDecl *VD, ASTFunction *F) : ASTElement(id, VD->getNameAsString(), F->getASTFile()) , F(F) { if (VD->getType()->isPointerType() || VD->getType()->isReferenceType()) pointer_reference_type = true; else pointer_reference_type = false; } ASTFunction *getFunction() const { return F; } bool isPointerOrReferenceType() const { return pointer_reference_type; } private: bool pointer_reference_type; ASTFunction *F; }; #endif
[ "njuseg2016@163.com" ]
njuseg2016@163.com
70b62a4c10350c34b6c98966bb81281fb08405d1
418a509ec9ec1fa785edcdb615b1e1811da02079
/code/cpp/MergeSortedArray.cpp
eaff9495df5c930df596f98944011286fb194481
[]
no_license
carlosten1989/Leetcode
9007bf3df7c03bee4cc8d371473a78ddc1ad5aac
72229a0fd0a6e705e8ad0b593f5fec21183091f2
refs/heads/master
2016-09-09T20:45:02.558514
2014-10-08T13:19:23
2014-10-08T13:19:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
332
cpp
class Solution { public: void merge(int A[], int m, int B[], int n) { int l = m + n; while(m && n) { if(A[m-1] > B[n-1]) { A[--l] = A[--m]; } else { A[--l] = B[--n]; } } while(n) { A[--l] = B[--n]; } } };
[ "lj007john@163.com" ]
lj007john@163.com
340282d552e5f24680088ec8dd8896eaf6db0b47
1ad5f2621a4f6bc255eb0b4bf707df92d72c8e85
/Agsearch/Agsearch/node.h
5378ad5ac23ba61beeb2ba36d04b6a855d13aee8
[]
no_license
tommylin1212/AGsearch
12c1cb16e25da40b6e768bdb58730bd4445ea701
51b832773c8bd55bf8192eed668234de57657073
refs/heads/master
2021-01-25T10:21:39.857286
2018-03-03T00:04:21
2018-03-03T00:04:21
123,349,612
0
0
null
null
null
null
UTF-8
C++
false
false
513
h
#ifndef NODE_H #define NODE_H #include "globals.h" #include <iostream> #include <string> class Node { public: Node(); Node(Node*, std::string, double cost,double hcost); std::string getName() const; double getcost() const; bool operator==(const Node&); bool operator<(const Node&); void print() const; void traceBack(bool); void setcost(double a); double getpathcost() const; double gethcost() const; private: Node* parent; std::string name; double ucost; double pcost; double hcost; }; #endif
[ "cwill.i.am.tomlin@gmail.com" ]
cwill.i.am.tomlin@gmail.com
854904a502c101abbc8b5bf94bac29df8b093c6c
119848599720941bf1c4740ea201bb6f5bc5a7bf
/D04/ex01/src/SuperMutant.cpp
3622f1ecb28aaf53bc52e1704f35251154f4c439
[]
no_license
stmartins/piscine_cpp
22981f0544808af9832345311a049f8358b049ae
9acc41cae123a51efec94df1571f21c78b702c11
refs/heads/master
2021-04-06T04:21:47.530808
2018-04-06T14:40:09
2018-04-06T14:40:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
560
cpp
#include "SuperMutant.hpp" SuperMutant::SuperMutant(SuperMutant const & src) { *this = src; return ; } SuperMutant::SuperMutant(void): Enemy(170, "Super Mutant") { std::cout << "Gaaah. Me want smash heads !" << std::endl; return ; } SuperMutant::~SuperMutant(void) { std::cout << "Aaargh ..." << std::endl; return ; } void SuperMutant::takeDamage(int damage) { int hp = this->getHP(); if (hp < 0 || damage - 3 <= 0) return ; else if (hp - (damage - 3) < 0) this->sethp(0); else this->sethp(hp - (damage - 3)); return ; }
[ "phaninho@live.fr" ]
phaninho@live.fr
6f183d246718d79ef1b746245b6f78c9a289afe6
b1008277f3c9103de6b434e4f3f62d6206e6873e
/PhysicsRel/Box2DEditor/source/Game/MyLib/Primitives/CirclePrim.cpp
72ad25ff5418de05a7d56e385d79b8c473ddc710
[]
no_license
manojyerra/OpenGL
b8bd9af9d3a63f74d810593d9608ca38c397187b
d241d6c2a6b245592b3a611f6880101e360a83b0
refs/heads/master
2022-12-10T12:34:48.137998
2019-11-10T05:40:53
2019-11-10T05:40:53
88,062,264
0
1
null
2022-12-09T19:28:30
2017-04-12T14:37:51
C
UTF-8
C++
false
false
1,868
cpp
#include "CirclePrim.h" #include "AddData.h" #include "Collisions.h" #include "Circle.h" #include "Rect2D.h" #include <math.h> CirclePrim::CirclePrim(float cx, float cy, float r) { _cx = cx; _cy = cy; _radius = r; } bool CirclePrim::Contains(float x, float y) { return ((_cx - x)*(_cx - x) + (_cy - y)*(_cy - y)) < _radius*_radius; } bool CirclePrim::CollidesWithRect(float x, float y, float w, float h) { Point cirCenter(_cx, _cy); Circle cir(&cirCenter, _radius); Rect2D rect2D(x, y, w, h); return Collisions::IsColliding(&cir, &rect2D); } void CirclePrim::SetCenter(float cx, float cy) { _cx = cx; _cy = cy; } Point CirclePrim::GetCenter() { Point p(_cx, _cy, 0); return p; } float CirclePrim::GetCX() { return _cx; } float CirclePrim::GetCY() { return _cy; } float CirclePrim::GetRadius() { return _radius; } void CirclePrim::SetRadius(float r) { _radius = r; } void CirclePrim::Draw() { AddData* addData = AddData::GetInstance(); addData->glColor( _color ); addData->glBegin(GL_TRIANGLE_FAN); addData->glVertex3f(_cx, _cy, 0); addData->glVertex3f(_cx+_radius, _cy, 0); for( int angle=10; angle<360; angle += 10 ) { float radians = angle*(22.0f/7.0f)/180.0f; float x = _cx+_radius*cosf(radians); float y = _cy+_radius*sinf(radians); addData->glColor4ub(angle*2, angle+50, angle+100, 255); //temp addData->glVertex3f(x,y,0); } addData->glVertex3f(_cx+_radius, _cy, 0); addData->glEnd(); //BORDER addData->glColor(_borderColor); addData->glBegin(GL_LINE_STRIP); addData->glVertex3f(_cx+_radius, _cy, 0); for( int angle=10; angle<360; angle += 10 ) { float radians = angle*(22.0f/7.0f)/180.0f; float x = _cx+_radius*cosf(radians); float y = _cy+_radius*sinf(radians); addData->glVertex3f(x,y,0); } addData->glVertex3f(_cx+_radius, _cy, 0); addData->glEnd(); } CirclePrim::~CirclePrim() { }
[ "manojyerra@gmail.com" ]
manojyerra@gmail.com
664cf07fdae824d2eb526a902ab93d63483dd95f
f85cfed4ae3c54b5d31b43e10435bb4fc4875d7e
/sc-virt/src/tools/clang/test/Modules/explicit-build.cpp
a6f6a6268c15f1abe329b3a82111a39a33be4fc5
[ "NCSA", "MIT" ]
permissive
archercreat/dta-vs-osc
2f495f74e0a67d3672c1fc11ecb812d3bc116210
b39f4d4eb6ffea501025fc3e07622251c2118fe0
refs/heads/main
2023-08-01T01:54:05.925289
2021-09-05T21:00:35
2021-09-05T21:00:35
438,047,267
1
1
MIT
2021-12-13T22:45:20
2021-12-13T22:45:19
null
UTF-8
C++
false
false
10,808
cpp
// RUN: rm -rf %t // ------------------------------- // Build chained modules A, B, and C // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-name=a -emit-module %S/Inputs/explicit-build/module.modulemap -o %t/a.pcm \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-IMPLICIT-BUILD %s --allow-empty // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-name=b -emit-module %S/Inputs/explicit-build/module.modulemap -o %t/b.pcm \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-IMPLICIT-BUILD %s --allow-empty // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/b.pcm \ // RUN: -fmodule-name=c -emit-module %S/Inputs/explicit-build/module.modulemap -o %t/c.pcm \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-IMPLICIT-BUILD %s --allow-empty // // CHECK-NO-IMPLICIT-BUILD-NOT: building module // ------------------------------- // Build B with an implicit build of A // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-name=b -emit-module %S/Inputs/explicit-build/module.modulemap -o %t/b-not-a.pcm \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-B-NO-A %s // // CHECK-B-NO-A: While building module 'b': // CHECK-B-NO-A: building module 'a' as // ------------------------------- // Check that we can use the explicitly-built A, B, and C modules. // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -verify %s -DHAVE_A // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-map-file=%S/Inputs/explicit-build/module.modulemap \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -verify %s -DHAVE_A // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/b.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-file=%t/b.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-file=%t/b.pcm \ // RUN: -fmodule-file=%t/c.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B -DHAVE_C // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-file=%t/c.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B -DHAVE_C // ------------------------------- // Check that -fmodule-file= in a module build makes the file transitively // available even if it's not used. // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fno-implicit-modules -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/b.pcm \ // RUN: -fmodule-name=d -emit-module %S/Inputs/explicit-build/module.modulemap -o %t/d.pcm \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-IMPLICIT-BUILD %s --allow-empty // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fno-implicit-modules -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/d.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B #if HAVE_A #include "a.h" static_assert(a == 1, ""); #else const int use_a = a; // expected-error {{undeclared identifier}} #endif #if HAVE_B #include "b.h" static_assert(b == 2, ""); #else const int use_b = b; // expected-error {{undeclared identifier}} #endif #if HAVE_C #include "c.h" static_assert(c == 3, ""); #else const int use_c = c; // expected-error {{undeclared identifier}} #endif #if HAVE_A && HAVE_B && HAVE_C // expected-no-diagnostics #endif // ------------------------------- // Check that we can use a mixture of implicit and explicit modules. // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/b-not-a.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B // ------------------------------- // Try to use two different flavors of the 'a' module. // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-file=%t/b-not-a.pcm \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-MULTIPLE-AS %s // // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-file=%t/b-not-a.pcm \ // RUN: -fmodule-map-file=%S/Inputs/explicit-build/module.modulemap \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-MULTIPLE-AS %s // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-name=a -emit-module %S/Inputs/explicit-build/module.modulemap -o %t/a-alt.pcm \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-IMPLICIT-BUILD %s --allow-empty // // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-file=%t/a-alt.pcm \ // RUN: -fmodule-map-file=%S/Inputs/explicit-build/module.modulemap \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-MULTIPLE-AS %s // // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/a-alt.pcm \ // RUN: -fmodule-file=%t/a.pcm \ // RUN: -fmodule-map-file=%S/Inputs/explicit-build/module.modulemap \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-MULTIPLE-AS %s // // CHECK-MULTIPLE-AS: error: module 'a' is defined in both '{{.*[/\\]}}a{{.*}}.pcm' and '{{.*[/\\]}}a{{.*}}.pcm' // ------------------------------- // Try to import a PCH with -fmodule-file= // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-name=a -emit-pch %S/Inputs/explicit-build/a.h -o %t/a.pch -DBUILDING_A_PCH \ // RUN: 2>&1 | FileCheck --check-prefix=CHECK-NO-IMPLICIT-BUILD %s --allow-empty // // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/a.pch \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-A-AS-PCH %s // // CHECK-A-AS-PCH: fatal error: AST file '{{.*}}a.pch' was not built as a module // ------------------------------- // Try to import a non-AST file with -fmodule-file= // // RUN: touch %t/not.pcm // // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/not.pcm \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-BAD-FILE %s // // CHECK-BAD-FILE: fatal error: file '{{.*}}not.pcm' is not a valid precompiled module file // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -fmodule-file=%t/nonexistent.pcm \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-NO-FILE %s // // CHECK-NO-FILE: fatal error: module file '{{.*}}nonexistent.pcm' not found // RUN: mv %t/a.pcm %t/a-tmp.pcm // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/c.pcm \ // RUN: %s 2>&1 | FileCheck --check-prefix=CHECK-NO-FILE-INDIRECT %s // RUN: mv %t/a-tmp.pcm %t/a.pcm // // CHECK-NO-FILE-INDIRECT: error: module file '{{.*}}a.pcm' not found // CHECK-NO-FILE-INDIRECT-NEXT: note: imported by module 'b' in '{{.*}}b.pcm' // CHECK-NO-FILE-INDIRECT-NEXT: note: imported by module 'c' in '{{.*}}c.pcm' // CHECK-NO-FILE-INDIRECT-NOT: note: // ------------------------------- // Check that we don't get upset if B's timestamp is newer than C's. // RUN: touch %t/b.pcm // // RUN: %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/c.pcm \ // RUN: -verify %s -DHAVE_A -DHAVE_B -DHAVE_C // // ... but that we do get upset if our B is different from the B that C expects. // // RUN: cp %t/b-not-a.pcm %t/b.pcm // // RUN: not %clang_cc1 -x c++ -std=c++11 -fmodules -fimplicit-module-maps -fmodules-cache-path=%t -Rmodule-build -fno-modules-error-recovery \ // RUN: -I%S/Inputs/explicit-build \ // RUN: -fmodule-file=%t/c.pcm \ // RUN: %s -DHAVE_A -DHAVE_B -DHAVE_C 2>&1 | FileCheck --check-prefix=CHECK-MISMATCHED-B %s // // CHECK-MISMATCHED-B: fatal error: module file '{{.*}}b.pcm' is out of date and needs to be rebuilt // CHECK-MISMATCHED-B-NEXT: note: imported by module 'c' // CHECK-MISMATCHED-B-NOT: note:
[ "sebi@quantstamp.com" ]
sebi@quantstamp.com
17fb262ef8a86c48fe623d3b03e895f71d8a8032
c993c413376b512a568ad64180833a74ffdbe204
/Bai1.4/Bai1.4/main.cpp
078798d721f9aa270e6aff462cd55eaf6a085162
[]
no_license
AnhNguyen92/DoHoaUngDung
e06fcd91ac96077947e7f30be2ed574fb7a3fcff
c62defb6126c0e75bed2e1a42e53cd3f490f6dd2
refs/heads/master
2020-09-07T09:15:07.137010
2019-11-10T18:25:12
2019-11-10T18:25:12
220,734,983
0
0
null
null
null
null
UTF-8
C++
false
false
1,485
cpp
#include "GLUT/glut.h" #include "OpenGL/gl.h" GLfloat v0[2] = {1,1}; GLfloat v1[2] = {2,3}; GLfloat v2[2] = {4,1}; GLfloat v3[2] = {6,2}; GLfloat v4[2] = {9,3}; GLfloat v5[2] = {7,5}; void myInit() { glClearColor(1.0,1.0,1.0,0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(0.0, 9, 0.0, 6); } void drawGrid() { glColor3f(0.6f, 0.6f, 0.6f); glLineWidth(1.0); glBegin(GL_LINES); for(int i = 0; i<9; i++) { glVertex2i(i, 0); glVertex2i(i, 6); } for(int i = 0; i<6; i++) { glVertex2i(0, i); glVertex2i(9, i); } glEnd(); } void myDisplay() { glClear(GL_COLOR_BUFFER_BIT); drawGrid(); glLineWidth(4.0); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glColor3f(0.f, 0.f, 0.f); glBegin(GL_TRIANGLE_STRIP); glVertex2fv(v0); glVertex2fv(v2); glVertex2fv(v1); glVertex2fv(v3); glVertex2fv(v5); glVertex2fv(v4); glEnd(); glFlush(); } int main(int argc, const char* argv[]) { glutInit(&argc, (char**)argv); //initialize the tool kit glutInitDisplayMode(GLUT_SINGLE |GLUT_RGB); //set the display mode glutInitWindowSize(600, 400); //set window size glutInitWindowPosition(100, 150); // set window position on screen glutCreateWindow("LAB 1 - (Bai 3)");//open the screen window glutDisplayFunc(myDisplay); myInit(); glutMainLoop(); return 0; }
[ "anh.nguyen@idsolutions.com.vn" ]
anh.nguyen@idsolutions.com.vn
727cc8933b0fb65f695c434d499e3a4f248be220
bdfe965225a849fcb126623be1556bf059de7df6
/UVA_10591 - Happy Number.cpp
f32c906aa34f4de0172b71756a0f39b17ee32e52
[]
no_license
rabelhmd/UVA-Solutions
84607f333a8145fedccb73dd0fa694c25516d4ca
562d90fdf075f75d8e0669c749aa865c57d690d6
refs/heads/master
2021-07-15T16:01:21.697126
2017-10-20T07:01:26
2017-10-20T07:01:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
688
cpp
#include <bits/stdc++.h> using namespace std; int Happy(int N) { int sum = 0; if(N <= 9) return N; while(N!=0) { sum += ((N%10)*(N%10)); N/=10; } Happy(sum); } int main() { int T, Case = 0; cin >> T; while(T--) { Case++; int N; cin >> N; int H = Happy(N); if(N == 7) cout << "Case #" << Case << ": " << N << " is a Happy number." << endl; else if(H == 1) cout << "Case #" << Case << ": " << N << " is a Happy number." << endl; else cout << "Case #" << Case << ": " << N << " is an Unhappy number." << endl; } return 0; }
[ "rabelhmd@gmail.com" ]
rabelhmd@gmail.com
f40200b01235f042c483b2f08ab6324ba633781e
141b07a7747a82ce589b6fa4e0d4c3f2f2fc8953
/01-July-2021/find-and-replace-pattern/Accepted/5-21-2021, 9:37:07 AM/Solution.cpp
090018fb6f7f6a43d018b9f307a8ab1c63b766e3
[]
no_license
tonymontaro/leetcode-submissions
f5f8b996868bfd63ddb43f3c98f8a7abef17927e
146f435d9ab792e197e5f85f1f2f4451f5a75d3f
refs/heads/main
2023-06-06T01:28:45.793095
2021-07-01T07:05:15
2021-07-01T07:05:15
381,935,473
1
0
null
null
null
null
UTF-8
C++
false
false
854
cpp
// https://leetcode.com/problems/find-and-replace-pattern class Solution { public: vector<string> findAndReplacePattern(vector<string>& words, string pattern) { vector<string> ans; for (auto &word: words) { map<char, char> seen; set<char> used; bool isValid = true; for (int i = 0; i < word.size(); i++) { char ch = word[i]; if ((seen.find(ch) != seen.end() && seen[ch] != pattern[i]) || (seen.find(ch) == seen.end() && used.find(pattern[i]) != used.end()) ) { isValid = false; break; } seen[ch] = pattern[i]; used.insert(pattern[i]); } if (isValid) ans.push_back(word); } return ans; } };
[ "ngeneanthony@gmail.com" ]
ngeneanthony@gmail.com
7ec439ab8e390e5df153bf96b0fbc10a66c27b95
778b6fdf2bbf6b0e6b9298d0ff4f78f967e231cf
/raymini/Object.h
78442c3aa94dbc9d343734aeb3040c088e958926
[]
no_license
rfaugeroux/RayTracer
a67c0bfffdc8d9fc841ed4bb6d7c09e0bad2aea0
3ecc73137430e469454da2c41e687cbf501bc5e0
refs/heads/master
2021-01-10T20:46:58.165152
2014-08-09T19:01:53
2014-08-09T19:01:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
h
// ********************************************************* // Object Class // Author : Tamy Boubekeur (boubek@gmail.com). // Copyright (C) 2010 Tamy Boubekeur. // All rights reserved. // ********************************************************* #ifndef OBJECT_H #define OBJECT_H #include <iostream> #include <vector> #include "Mesh.h" #include "Material.h" #include "BoundingBox.h" #include "KdTree.h" class Object { public: inline Object () {} inline Object (const Mesh & mesh, const Material & mat) : mesh (mesh), mat (mat) { updateBoundingBox (); kdTree = KdTree(mesh); } virtual ~Object () {} inline const Vec3Df & getTrans () const { return trans;} inline void setTrans (const Vec3Df & t) { trans = t; } inline const Mesh & getMesh () const { return mesh; } inline Mesh & getMesh () { return mesh; } inline const Material & getMaterial () const { return mat; } inline Material & getMaterial () { return mat; } inline const BoundingBox & getBoundingBox () const { return bbox; } void updateBoundingBox (); inline const KdTree & getKdTree() const { return kdTree; } private: Mesh mesh; Material mat; BoundingBox bbox; Vec3Df trans; KdTree kdTree; }; #endif // Scene_H // Some Emacs-Hints -- please don't remove: // // Local Variables: // mode:C++ // tab-width:4 // End:
[ "romain.faugeroux@gmail.com" ]
romain.faugeroux@gmail.com
9756cb39ddcdf1ef0dc019608643d5614db76c18
cc526451b58f2a816354545707c3b3aa5042af00
/compiler/src/db/program_element.h
39642938224cb4bdc924f9ff0fec69dea2f62b9c
[]
no_license
MichaelBelousov/Fluster
8a6fa0cc893caa1bbd9a002deb8c7f89ba4917a7
6af7de245237d7627e659cd64aaf2753539137e3
refs/heads/master
2020-05-19T16:19:22.356968
2019-06-13T16:49:42
2019-06-14T14:40:21
185,104,777
0
0
null
null
null
null
UTF-8
C++
false
false
1,579
h
#ifndef FLUSTER_COMPILER_DB_PROGRAM_ELEMENT #define FLUSTER_COMPILER_DB_PROGRAM_ELEMENT #include <memory> #include <utility> #include <llvm/IR/Value.h> #include "util/ptr.h" #include "name.h" #include "path.h" /* * A ProgramElement is constructed by AST nodes and committed to a ProgramDatabase. * They are named, and some contain subelements in their own local databases. * They can return their llvm representation, being some existing symbol, a type, * or an operation. */ // forward declarations namespace fluster { struct GenerationContext; } namespace fluster { namespace db { struct ProgramElement : public std::enable_shared_from_this<ProgramElement> { //// Types using Ptr = util::Ptr<ProgramElement>; //// Methods template<typename ProgramElementChild, typename ...Args> ProgramElement::Ptr makeChildElement(Args&& ...args) { return ProgramElementChild::Ptr::make(std::forward<Args>(args)...); } virtual ProgramElement::Ptr search(Path search_path) = 0; virtual llvm::Value* getLLVMRepr( GenerationContext& ctx , const std::vector<llvm::Value*>& args ) const = 0; //// Members const Name name; const Path full_path; const ProgramElement::Ptr outer; //// Construction ProgramElement(const Name& in_name); virtual ~ProgramElement() = default; protected: ProgramElement(const Name& in_name, ProgramElement::Ptr in_outer); }; } } //namespace fluster::db #endif //FLUSTER_COMPILER_DB_PROGRAM_ELEMENT
[ "michael.belousov98@gmail.com" ]
michael.belousov98@gmail.com
f675af2871504bc0f73723c1c95af65fca57373d
0dae9fffb92224146c36dba312c2caf426a9a886
/208.cpp
ea2440c712edbfe540a5016a2103a6be4b3267f5
[]
no_license
TonyChouZJU/PAT
d2c2e44691758bc31554d1bc7d74767f79d14fc1
10e1ee29ce0954a78ea07d8bd4d94260bf9daf0d
refs/heads/master
2021-01-23T09:51:26.259988
2015-02-28T15:21:16
2015-02-28T15:21:16
20,728,323
0
1
null
null
null
null
UTF-8
C++
false
false
1,510
cpp
#include <iostream> #include <string> #include <sstream> #include <cmath> using namespace std; const double PRECISION = 1E-6; double N[4]; string expression[4]; bool search_24(int n) { if(n == 1) { if(fabs(N[0]-24)<PRECISION) { cout << expression[0]; return true; } else return false; } for ( int i = 0; i <n; ++i) { for ( int j = i+1; j <n; ++j) { double a,b; string expa, expb; a = N[i]; b = N[j]; N[j] = N[n-1]; expa = expression[i]; expb = expression[j]; expression[j] = expression[n-1]; expression[i] = '(' + expa + '+' + expb + ')'; N[i] = a + b; if(search_24(n-1)) return true; expression[i] = '(' + expa + '-' + expb + ')'; N[i] = a - b; if(search_24(n-1)) return true; expression[i] = '(' + expb + '-' + expa + ')'; N[i] = b - a; if(search_24(n-1)) return true; expression[i] = '(' + expa + '*' + expb + ')'; N[i] = a * b; if(search_24(n-1)) return true; if( b!=0) { expression[i] = '(' + expa + '/' +expb + ')'; N[i] = a / b; if(search_24(n-1)) return true; } if( a!=0) { expression[i] = '(' + expb + '/' +expa + ')'; N[i] = b/a; if(search_24(n-1)) return true; } N[i] = a; N[j] = b; expression[i] = expa; expression[j] = expb; } } return false; } int main() { for(int i = 0; i != 4; ++i) { int x; cin >> x; N[i] = x; stringstream ss; ss << x; string str; ss >>str; expression[i] =str; } bool result = search_24(4); if(result == false) cout <<-1; }
[ "zhoudaxia@zhoudaxia-P467.(none)" ]
zhoudaxia@zhoudaxia-P467.(none)
65968932300b13a4f8d753f580c400b9c514bb0f
c1330d94032981051c80e111f8e8c0ffecac035d
/Publisher/Publisher.h
02c1593cb2b68762b36e8268ae1efeb3cdebf5ea
[]
no_license
SirichandanaSambatur/RCP
7f049f3feed1e3b590a8ed3af0d3953df8e4a920
1b9ba9efc5b95963708391e2590c213a11a3f654
refs/heads/master
2021-06-26T11:34:03.297542
2017-09-12T03:10:03
2017-09-12T03:10:03
103,211,364
0
0
null
null
null
null
UTF-8
C++
false
false
4,465
h
#pragma once ///////////////////////////////////////////////////////////////////////////////////////// // Publisher.h - Publish the given list of files as HTML files on the browser // // ver 1.0 // // Language: Visual C++ 2015 // // Platform: Macbook Pro, Windows 10 // // Application: Used to publish various types of files in the package // // Author: Siri Chandana Sambatur, ssambatu@syr.edu // ///////////////////////////////////////////////////////////////////////////////////////// /* Package Operations: ================== This package is used to publish all the files and insert links where they are necessary. It uses the PublishPage package to make the files a list of Html files. So, these Html files can finally be linked together as one and form a single website. Public Interface: ================= void publishPackage(std::vector<std::string> files, DBHelper<std::string> sDB); //to publish the package given void openBrowser(); //launch the default browser Build Process: ============== Required files ConvertType.h, PublishPage.h, DBHelpher.h Build commands devenv DependancyBasedCodePublisher.sln /rebuild debug Maintenance History: ==================== ver 1.0 : 04 Apr 2017 - first release */ #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<unordered_map> #include<vector> #include "../PublishPage/PublishPage.h" #include "../ConvertType/ConvertType.h" #include "../NoSqlDb/DBHelper.h" using namespace std; namespace CodePublisher { ///////////////////////////////////////////////////////////////////// // Publisher class to publish the given pages // - all the files are published as html pages // - opens in the default browser // class Publisher { public: void publishPackage(std::vector<std::string> files, DBHelper<std::string> sDB); void openBrowser(); private: PublishHtmlPage p; std::string currentPath; std::string currentFile; void SplitFilename(const std::string& str); }; //open the html page with the default browser void Publisher::openBrowser() { std::string path = "HtmlFiles"; _chdir(path.c_str()); std::string htmlFilePath = "mainPage.html"; std::cout <<"Launching the page from the folder- " <<path<<"\\"<<htmlFilePath; ShellExecuteA(GetDesktopWindow(), ("open"), LPCSTR(htmlFilePath.c_str()), NULL, NULL, SW_SHOWNORMAL); } void Publisher::SplitFilename(const std::string& str) { std::size_t found = str.find_last_of("/\\"); currentPath = str.substr(0, found); currentFile = str.substr(found + 1); } //publish the packages by publishing all the files void Publisher::publishPackage(std::vector<std::string> files, DBHelper<std::string> sDB) { using Item = std::pair<string, vector<string>>; Convert c; std::cout << "Requirement 4- Implemented the hiding and unhiding feature using the CSS- 'HtmlFiles/HideInformation.css' and the JS- 'HtmlFiles/HideInformation.js'"; std::cout << "\n------------------------------------------------------------------\n"; std::cout << "Requirement 5- Displaying the contents of the CSS files that have been used------\n"; p.showCSSFiles(); std::cout << "\n------------------------------------------------------------------\n"; std::cout << "Requirement 5- Displaying the contents of the JS file that have been used------\n"; p.showJSFiles(); std::cout << "\n------------------------------------------------------------------\n"; std::cout << "\n--------------------Creating the main page----------------------\n"; p.createMainPage(files); std::cout << "\n------------------------------------------------------------------\n"; std::cout << "Requirement 6- Adding external links to all html files created in the head section\n"; std::cout << "\n------------------------------------------------------------------\n"; p.addCSS(); p.addJS(); for (int i = 0; i < files.size(); i++) { std::string temp = c.convertContent(files[i]); SplitFilename(files[i]); std::cout << "----------- Publishing the file " << currentFile << "------------------------\n"; p.createHtmlPage(currentFile, temp, sDB.getChildren(currentFile)); } } }
[ "sambatur.siri@yahoo.com" ]
sambatur.siri@yahoo.com
c9d326d9154a6138f2e4dd576e91f523a18ed5f5
95da45e333d762f8d8229fefec58d79facf3b15a
/HDOJ/5317.RGCDQ.cpp
a326cdf6950211c991bec0a300ab93d98362a2cf
[]
no_license
Xiao-Jian/ACM-Training
592552c84f031ea4bafd8b85bba063d8171f8548
5dec492cc86a349a0d7673fa022410a52bae1246
refs/heads/master
2016-09-05T19:26:24.824149
2015-11-29T06:24:45
2015-11-29T06:24:45
39,362,552
0
0
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
/* OJ: HDOJ ID: forever TASK: 5317.RGCDQ LANG: C++ NOTE: Range Greatest Common Divisor Query */ #include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #include <cmath> #include <vector> #include <set> #define MAX 1000011 using namespace std; int num[10],f[MAX]; bool isPrime[MAX]; int dp[10][MAX]; void prime2() { memset( isPrime, true, sizeof(isPrime) ); isPrime[0] = isPrime[1] = false; for( int i = 2; i <= MAX; i ++ ) if( isPrime[i] ) { f[i] ++; for( int j = 2 * i; j <= MAX; j += i ) { isPrime[j] = false; f[j] ++; } } for( int i = 1; i <= MAX; i ++ ) { for( int j = 1; j <= 8; j ++ ) { dp[j][i] = dp[j][i-1] + ( f[i] == j ); } } } int gcd( int a, int b ) { return b == 0 ? a : gcd( b, a%b ); } int main() { int t, l, r; memset( f, 0, sizeof(f) ); memset( dp, 0, sizeof(dp) ); prime2(); scanf( "%d", &t ); while( t -- ) { scanf( "%d%d", &l, &r ); int ma = 0; memset(num, 0 ,sizeof(num)); for ( int i = 1; i <= 8; i ++ ) { num[i] = dp[i][r] - dp[i][l-1]; } int ret = 1; if(num[2] + num[4] + num[6]>=2) ret = 2; if(num[3] + num[6] >= 2) ret = 3; if(num[4] >= 2) ret = 4; if(num[5] >= 2) ret = 5; if(num[6] >= 2) ret = 6; if(num[7] >= 2) ret = 7; printf( "%d\n", ret); } return 0; }
[ "1215615213@qq.com" ]
1215615213@qq.com
f3ba5f69ffc86e5f5e5330839f84f3e63b57ee10
cdb2ce5282412cb1f5c1390e4db28b1391fe5e09
/ClassfierForTest/src/ReturnValue.h
fb2c318462ec9b587183b0d38a80c5310f8dc275
[]
no_license
baobao0718/Classifier
6095a7a8f043b8a1dd051823d6cc0e53a70cf206
674bad7a608035b6a9eafd8c1d3f8af0f26e42de
refs/heads/master
2020-06-07T12:34:33.389168
2012-08-09T07:38:00
2012-08-09T07:38:00
5,352,133
0
1
null
null
null
null
UTF-8
C++
false
false
96
h
class ReturnValue{ public : int xc_in,yc_in; float prox_in[64]; float proy_in[64]; };
[ "112989666@qq.com" ]
112989666@qq.com
da83da3033ff220ed2c5a5f6d34103b9ff0601bf
54cd2cca6dea49b4f96f50b4a54db2673edff478
/51CTO下载-钱能c++第二版源码/ch12/f1201.cpp
981e02be15aae859f8ec97405395839f4c95c682
[]
no_license
fashioning/Leetcode
2b13dec74af05b184844da177c98249897204206
2a21c369afa3509806c748ac60867d3a0da70c94
refs/heads/master
2020-12-30T10:23:17.562412
2018-10-22T14:19:06
2018-10-22T14:19:06
40,231,848
0
0
null
2018-10-22T14:19:07
2015-08-05T07:40:24
C++
WINDOWS-1252
C++
false
false
405
cpp
//===================================== // f1201.cpp // ¼Ì³ÐÓë³ÉÔ±¸²¸Ç //===================================== #include"student.h" #include"graduatestudent.h" //------------------------------------- int main(){ Student ds("Lo lee undergrade"); GraduateStudent gs; ds.addCourse (3, 2.5); ds.display(); gs.addCourse(3, 3.0); gs.display(); }//====================================
[ "fashioning@126.com" ]
fashioning@126.com
4a65500228dc3e5551c5df221a4943866bcc4a84
49a56e6799208f9ca7e7eb0ac31f77b78ffe94d8
/include/ROSUnit_UpdateReferenceY.hpp
3e8f3f2ef764f9f16b0232844074e9fe3d704977
[ "BSD-3-Clause" ]
permissive
yousef-a/positioning_system
39f3d639dd63ea52da21760983a0b9bd7fb6cdaa
a9554e1a96f7e52df75e71a826b7c736b95c1b19
refs/heads/master
2020-12-03T05:41:12.566441
2020-01-07T18:05:20
2020-01-07T18:05:20
231,216,821
0
0
BSD-3-Clause
2020-01-06T11:41:57
2020-01-01T12:59:06
null
UTF-8
C++
false
false
799
hpp
#pragma once #include "ROSUnit.hpp" #include "FlightScenarioMessage.hpp" #include "UpdatePoseMessage.hpp" #include <positioning_system/Update_Y_Reference.h> #include "Vector3D.hpp" class ROSUnit_UpdateReferenceY : public ROSUnit{ private: //TODO receive msgs from a service through a callback static ROSUnit_UpdateReferenceY* _instance_ptr; static UpdatePoseMessage _pose_ref_msg; ros::ServiceServer _srv_setpoint; static bool callbackSetpoint(positioning_system::Update_Y_Reference::Request &req, positioning_system::Update_Y_Reference::Response &res); void receive_msg_data(DataMessage* t_msg); public: ROSUnit_UpdateReferenceY(ros::NodeHandle&); ~ROSUnit_UpdateReferenceY(); };
[ "pedro.silva@ku.ac.ae" ]
pedro.silva@ku.ac.ae
613b459a5b7d8b7fcd5149fd882dd5a9e0e4a96d
b608b2330e24a05f0c3f68741db22d788e0f6b42
/ch4/drill1.cpp
6ad47c427d8ba79411157aceef63ca854bbb8e2a
[]
no_license
ia-kamog/stroustrup_programming
1ebdc88ef09e82f2b1934536dd5c6b5669e9f53f
c53c06c5951e364ee323733bb8e1f28f85b36e71
refs/heads/master
2020-03-20T02:25:13.458049
2018-07-10T06:24:29
2018-07-10T06:24:29
137,112,349
0
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
// Drill 1: read two integers in a while loop #include "std_lib_facilities.h" int main() { int a, b; while (cin >> a >> b) cout << a << '\t' << b << '\n'; }
[ "ia.kamog@ya.ru" ]
ia.kamog@ya.ru
73dc44af7999c3302f0e768e1a6ca4f98df3a6cd
e59bde40f7c438dcf3bb73fb7067e0bdce7f2ff4
/shop_console/shop_console.cpp
96ef480b7792bd292eb23b308541c5ab7ef4e81a
[]
no_license
Alelluja/shop-in-console
26ac08dc8ccbad8c193b17da7dbf03b6b405c061
6f8e162385bba2f5a7696b0b589252bbdacc0de6
refs/heads/main
2023-06-17T16:09:44.790874
2021-07-21T14:27:17
2021-07-21T14:27:17
308,449,002
2
0
null
null
null
null
UTF-8
C++
false
false
13,459
cpp
#include <iostream> #include <vector> #include <array> #include <fstream> #include <string> float user_money = 1000.0; class shopping_cart_data { public: unsigned int game_id; unsigned int game_price; public: std::string game_name; }; class game_data { public: unsigned int price; public: std::string type; std::string name; }; std::array<std::string, 6> game_type_names = { "FPS", "MMORPG", "Adventure", "RPG", "Sport", "Simulator" }; int get_choice_int(); void clear_console(); void display_shop(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data); void display_games(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data); void admin_menu(std::vector<game_data>& g_data); void shopping_cart(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data); void ask_for_add_to_shopping_cart(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data, int game_id); void add_to_shopping_cart(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data, int game_index); void choose_game(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data, int type); void confirm_purchase(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data); void del_from_shopping_cart_file(std::vector<shopping_cart_data>& s_data); //Admin Menu options void add_game(std::vector<game_data>& g_data); void del_game(std::vector<game_data>& g_data); void change_game_name(std::vector<game_data>& g_data); void change_game_price(std::vector<game_data>& g_data); void change_game_type(std::vector<game_data>& g_data); bool is_valid_type(int i) { if (i < 0) { return false; } if (i > game_type_names.size()) { return false; } return true; } bool is_valid_game_id(int choice, std::vector<int> ids) { return std::find(ids.begin(), ids.end(), choice) != ids.end(); } bool ask_client(std::string question) { printf("\nDo you want %s?\n\n", question.c_str()); printf("1. Yes (Type 1)\n"); printf("2. No (Type 2)\n\n"); int choice = 0; printf("Choose option: "); choice = get_choice_int(); return choice == 1; } bool write_games_file(std::vector<game_data>& g_data) { std::ofstream file("shop_data.dat"); if (!file.good()) { printf("Cannot open file!\n"); return false; } for (game_data& game : g_data) { file << game.type << "#" << game.name << "#" << game.price << std::endl; } return true; } bool write_shopping_cart_file(std::vector<shopping_cart_data>& s_data) { std::ofstream file("shopping_cart_data.dat"); if (!file.good()) { printf("Cannot open file!\n"); return false; } for (shopping_cart_data& shopping_cart : s_data) { file << shopping_cart.game_id << "#" << shopping_cart.game_name << "#" << shopping_cart.game_price << std::endl; } return true; } std::vector<game_data> read_games_file() { std::ifstream stream("shop_data.dat", std::ios::out); if (!stream.good()) { printf("Cannot open file!\n"); return {}; } std::vector<game_data> g_data; game_data game; std::string price; while (getline(stream, game.type, '#') && getline(stream, game.name, '#') && getline(stream, price)) { game.price = stoi(price); g_data.push_back(game); } /*for (game_data& game : g_data) { printf("TYPE: %s | NAME: %s | PRICE: %i\n", game.type, game.name, game.price); }*/ stream.close(); return g_data; } std::vector<shopping_cart_data> read_shopping_cart_file() { std::ifstream stream("shopping_cart_data.dat", std::ios::out); if (!stream.good()) { printf("Cannot open file!\n"); return {}; } std::vector<shopping_cart_data> s_data; shopping_cart_data shopping_cart; std::string price, game_index; while (getline(stream, game_index, '#') && getline(stream, shopping_cart.game_name, '#') && getline(stream, price)) { shopping_cart.game_id = stoi(game_index); shopping_cart.game_price = stoi(price); s_data.push_back(shopping_cart); } /*for (shopping_cart_data& shopping_cart : s_data) { printf("INDEX: %i | NAME: %s | PRICE: %i\n", shopping_cart.game_id, shopping_cart.game_name, shopping_cart.game_price); }*/ stream.close(); return s_data; } int search_game_id(std::vector<game_data>& g_data, const std::string& game_name) { // Iterate over all elements in Vector for (int i = 0; i < g_data.size(); i++) { if (g_data[i].name == game_name) { return i; } } return -1; } // Error - message : see reference to function template instantiation /*int search_game_id(std::vector<game_data>& g_data, const std::string& game_name) { auto it = std::find(g_data.begin(), g_data.end(), game_name); return std::distance(g_data.begin(), it); }*/ std::pair<std::string, int> game_field_changer(std::vector<game_data>& g_data, const std::string& question) { clear_console(); std::string game_name; printf("Enter the name of the game to be changed: "); getline(std::cin, game_name); int game_id = search_game_id(g_data, game_name); if (game_id > -1) { std::string temp_variable; printf("\nFound game!\n\n"); printf("Enter the %s: ", question.c_str()); getline(std::cin, temp_variable); return { temp_variable, game_id }; } return { "", game_id }; } int get_choice_int() { std::string temp; getline(std::cin, temp); if (temp == "") { return 0; } return stoi(temp); } int main() { clear_console(); std::vector<game_data> g_data = read_games_file(); std::vector<shopping_cart_data> s_data = read_shopping_cart_file(); display_shop(g_data, s_data); write_games_file(g_data); write_shopping_cart_file(s_data); return 0; } void clear_console() { system("cls"); } void display_games_in_shopping_cart(std::vector<shopping_cart_data>& s_data) { printf("Games in shopping cart: \n"); for (int i = 0; i < s_data.size(); i++) { printf("%i. %s \t%i PLN\n", s_data[i].game_id, s_data[i].game_name.c_str(), s_data[i].game_price); } } void display_shop(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data) { // Handle input int choice = -1; while(choice != 0) { // Display header. printf("----= GAME SHOP =----\n"); printf("Choose option:\n\n"); printf("1. Shop with games (Type 1)\n"); printf("2. Shopping cart (Type 2)\n"); printf("3. Admin Menu (Type 3)\n"); printf("0. Exit (Type 0)\n\n"); printf("Enter the option: "); choice = get_choice_int(); // Selecting an option switch (choice) { case 0: { exit(0); } case 1: { display_games(g_data, s_data); break; } case 2: { shopping_cart(g_data, s_data); break; } case 3: { admin_menu(g_data); break; } // Invalid input. default: { clear_console(); // Notify about invalid input. printf("Wrong data!\n"); break; } } } } void display_games(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data) { clear_console(); printf("---= TYPE GAMES =----\n\n"); // Display all the game types. for (int i = 0; i < game_type_names.size(); i++) { printf("%i. Games %s\n", i + 1, game_type_names[i].c_str()); } printf("\n\n0. Exit\n\n"); // Get user game-type choice. int choice = 0; printf("Enter the option: "); choice = get_choice_int(); // Exit option. if (choice == 0) { exit(0); } // Bugfix. choice--; if (!is_valid_type(choice)) { clear_console(); // Notify about invalid input. printf("\nWrong data!\n\n"); // Display the shop again. display_games(g_data, s_data); } choose_game(g_data, s_data, choice); } void shopping_cart(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data) { clear_console(); printf("----= SHOPPING CART =----\n\n"); display_games_in_shopping_cart(s_data); printf("\nDo you want to buy these games?\n"); printf("1. Yes (Type 1)\n"); printf("2. No (Type 2)\n\n"); int choice = 0; printf("Choose option: "); choice = get_choice_int(); switch (choice) { case 1: { confirm_purchase(g_data, s_data); break; } case 2: { clear_console(); printf("You cancel purchase.\n\n"); display_shop(g_data, s_data); break; } default: { clear_console(); // Notify about invalid input. printf("Wrong data!\n"); break; } } } void choose_game(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data, int type) { clear_console(); // Display header. printf("Available games (%s):\n\n", game_type_names[type].c_str()); std::vector<int> ids; // Display all the games in given type. for (int i = 0; i < g_data.size(); i++) { // Skip the game if it's type is not the chosen one. if (g_data[i].type != game_type_names[type].c_str()) { continue; } printf("%i. %s \t%i PLN (Type %i)\n", i + 1, g_data[i].name.c_str(), g_data[i].price, i + 1); ids.push_back(i + 1); } // Handle input. int choice = 0; printf("\nEnter the index game: "); choice = get_choice_int(); // Invalid input given. if (!is_valid_game_id(choice, ids)) { clear_console(); printf("\nWrong data!\n\n"); display_games(g_data, s_data); } ask_for_add_to_shopping_cart(g_data, s_data, choice - 1); } void ask_for_add_to_shopping_cart(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data, int game_id) { clear_console(); printf("Do you want to add \"%s\" to shopping cart?\n", g_data[game_id].name.c_str()); printf("Your balance:\t%.2f\tPLN\n\n", user_money); printf("1. Yes (Type 1)\n"); printf("2. No (Type 2)\n\n"); // Handle input int choice = 0; printf("Choose option: "); choice = get_choice_int(); switch (choice) { case 1: { add_to_shopping_cart(g_data, s_data, game_id); break; } case 2: { display_shop(g_data, s_data); break; } default: { clear_console(); // Notify about invalid input. printf("Wrong data!\n"); break; } } } void add_to_shopping_cart(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data, int game_index) { shopping_cart_data scd; scd.game_id = game_index; scd.game_name = g_data[game_index].name; scd.game_price = g_data[game_index].price; s_data.push_back(scd); clear_console(); write_shopping_cart_file(s_data); display_shop(g_data, s_data); } void confirm_purchase(std::vector<game_data>& g_data, std::vector<shopping_cart_data>& s_data) { clear_console(); printf("Bought games: \n\n"); for (int i = 0; i < s_data.size(); i++) { // Charge for the game. user_money -= s_data[i].game_price; printf("- %s (%i PLN).\n", s_data[i].game_name.c_str(), s_data[i].game_price); } printf("\nBalance after buy: %.2f PLN.\n\n", user_money); printf("Thank you for shopping!\n\n"); del_from_shopping_cart_file(s_data); display_shop(g_data, s_data); } void del_from_shopping_cart_file(std::vector<shopping_cart_data>& s_data) { shopping_cart_data scd; s_data.erase(s_data.begin(), s_data.end()); write_shopping_cart_file(s_data); } void admin_menu(std::vector<game_data>& g_data) { clear_console(); printf("----= ADMIN MENU =----:\n"); printf("1. Add game (Type 1)\n"); printf("2. Delete game (Type 2)\n"); printf("3. Change game name (Type 3)\n"); printf("4. Change game price (Type 4)\n"); printf("5. Change game type (Type 5)\n\n"); printf("0. Exit (Type 0)\n\n"); // Handle input. int choice = 0; printf("Choose option: "); choice = get_choice_int(); // Selecting an option switch (choice) { case 0: { break; } case 1: { if (ask_client("add game")) { add_game(g_data); } break; } case 2: { if (ask_client("delete game")) { del_game(g_data); } break; } case 3: { if (ask_client("change game name")) { change_game_name(g_data); } break; } case 4: { if (ask_client("change game price")) { change_game_price(g_data); } break; } case 5: { if (ask_client("change game type")) { change_game_type(g_data); } break; } // Invalid input. default: { clear_console(); // Notify about invalid input. printf("Wrong data!\n"); admin_menu(g_data); break; } } } void add_game(std::vector<game_data>& g_data) { clear_console(); game_data gd; std::string price; printf("Enter the type of game to add: "); getline(std::cin, gd.type); printf("Enter the name of game to add: "); getline(std::cin, gd.name); printf("Enter the price of game to add: "); getline(std::cin, price); gd.price = std::stoi(price); g_data.push_back(gd); printf("Game added:\n"); printf("Type: %s\n", gd.type.c_str()); printf("Name: %s\n", gd.name.c_str()); printf("Price: %i", gd.price); } void del_game(std::vector<game_data>& g_data) { clear_console(); std::string game_name; printf("Enter the name of game to delete: "); getline(std::cin, game_name); int game_id = search_game_id(g_data, game_name); if (game_id > -1) { g_data.erase(g_data.begin() + game_id); } } void change_game_name(std::vector<game_data>& g_data) { auto change_data = game_field_changer(g_data, "new name"); g_data[change_data.second].name = change_data.first; } void change_game_type(std::vector<game_data>& g_data) { auto change_data = game_field_changer(g_data, "new type"); g_data[change_data.second].type = change_data.first; } void change_game_price(std::vector<game_data>& g_data) { auto change_data = game_field_changer(g_data, "new price"); g_data[change_data.second].price = stoi(change_data.first); }
[ "hubert.st@onet.pl" ]
hubert.st@onet.pl
fa5953ab4d7f2fc94646c0fdf85bddd9caecea51
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-ecr/include/aws/ecr/model/DeleteRegistryPolicyRequest.h
47653f63342bf735544844a69ce6e7c8b1052ae7
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
1,034
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ecr/ECR_EXPORTS.h> #include <aws/ecr/ECRRequest.h> namespace Aws { namespace ECR { namespace Model { /** */ class AWS_ECR_API DeleteRegistryPolicyRequest : public ECRRequest { public: DeleteRegistryPolicyRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "DeleteRegistryPolicy"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; }; } // namespace Model } // namespace ECR } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
b2c23aa6aa343b87d770e029967bb03d2ed96dbc
9b422fbf0742b18d60717f150b5466eae911fe00
/IslandPerimeter.cpp
fcb6468799305812d4e64560fd89cb9876360df6
[]
no_license
ShubhikaBhardwaj/Leetcode-Coding
e8621ac8358056fece1dde154856968e1cb1f442
bd8901e41e6381b034caf5cd5c9b245c065e9ebd
refs/heads/master
2022-11-19T14:40:35.925791
2020-07-23T20:17:31
2020-07-23T20:17:31
277,086,172
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
cpp
class Solution { public: int islandPerimeter(vector<vector<int>>& grid) { int N=grid.size(); if(N==0)return 0; int M=grid[0].size(); if(M==0)return M; int count=0; int neighbours=0; for(int i=0;i<N;i++) { for(int j=0;j<M;j++) { if(grid[i][j]==1) { count++; int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; for(int k=0;k<4;k++) { int rx=i+dx[k]; int ry=j+dy[k]; if(rx>=0&&ry>=0&&rx<N&&ry<M) if(grid[rx][ry]==1) neighbours++; } } } } long long ans=(4*count)-(neighbours); ans=ans%1000000007; return (int)ans; } };
[ "shubhikabhardwaj@gmail.com" ]
shubhikabhardwaj@gmail.com
2655a16a0b023124441f7e3f3da75fcd67b85ffb
a91796ab826878e54d91c32249f45bb919e0c149
/modules/dnn/src/cuda4dnn/kernels/padding.hpp
cb55e99f8407e30c974351b844ea8d361f7f3d3e
[ "Apache-2.0" ]
permissive
opencv/opencv
8f1c8b5a16980f78de7c6e73a4340d302d1211cc
a308dfca9856574d37abe7628b965e29861fb105
refs/heads/4.x
2023-09-01T12:37:49.132527
2023-08-30T06:53:59
2023-08-30T06:53:59
5,108,051
68,495
62,910
Apache-2.0
2023-09-14T17:37:48
2012-07-19T09:40:17
C++
UTF-8
C++
false
false
815
hpp
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #ifndef OPENCV_DNN_SRC_CUDA4DNN_KERNELS_PADDING_HPP #define OPENCV_DNN_SRC_CUDA4DNN_KERNELS_PADDING_HPP #include "../csl/stream.hpp" #include "../csl/tensor.hpp" #include <cstddef> #include <vector> #include <utility> namespace cv { namespace dnn { namespace cuda4dnn { namespace kernels { template <class T> void copy_with_reflection101( const csl::Stream& stream, csl::TensorSpan<T> output, csl::TensorView<T> input, std::vector<std::pair<std::size_t, std::size_t>> ranges); }}}} /* namespace cv::dnn::cuda4dnn::kernels */ #endif /* OPENCV_DNN_SRC_CUDA4DNN_KERNELS_PADDING_HPP */
[ "alexander.a.alekhin@gmail.com" ]
alexander.a.alekhin@gmail.com
d637b1bf63f421ac7353131a78a02e92a52ac081
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/d8/c88d5c1ad3c5aa/main.cpp
5f6cfabf33e742f456e18ef7d759761f2c544ed5
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
1,008
cpp
#include <iostream> #include <algorithm> #include <numeric> #include <chrono> static auto matching_characters(std::string const &s1, std::string const &s2) { int s1_char_frequencies[256] = {}; int s2_char_frequencies[256] = {}; for_each(begin(s1), end(s1), [&](unsigned char c) { ++s1_char_frequencies[c]; }); for_each(begin(s2), end(s2), [&](unsigned char c) { ++s2_char_frequencies[c]; }); return std::inner_product( std::begin(s1_char_frequencies), std::end(s1_char_frequencies), std::begin(s2_char_frequencies), 0, std::plus<>(), [](auto l, auto r) { return std::min(l, r); }); } int main() { auto start = std::chrono::high_resolution_clock::now(); auto r1 = matching_characters("assign", "assingn"); auto r2 = matching_characters("sisdirturn", "disturb"); auto end = std::chrono::high_resolution_clock::now(); std::cout << r1 << '\n'; // 6 std::cout << r2 << '\n'; // 6 std::cout << (end - start) / std::chrono::nanoseconds(1) << "ns\n"; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
b9ead85730798c1b02d7697a97d2f519517ca466
d7daa1c9473ed169db03c0a84581cfb20253a3d0
/src/modules/file-formats/TIFF/TIFF.h
52d06f49f8c271e8faf8e791a505f25c35255c12
[ "LicenseRef-scancode-other-permissive" ]
permissive
ksAlpha001/PCL
8986a360478ae8d1b01491efb81df5308ddb21a6
5c2d45a4b5a9fceacc0be08dc07d9100f19b0b7b
refs/heads/master
2023-03-15T01:48:32.964335
2017-05-01T08:50:05
2017-05-01T08:50:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,708
h
// ____ ______ __ // / __ \ / ____// / // / /_/ // / / / // / ____// /___ / /___ PixInsight Class Library // /_/ \____//_____/ PCL 02.01.03.0819 // ---------------------------------------------------------------------------- // Standard TIFF File Format Module Version 01.00.07.0307 // ---------------------------------------------------------------------------- // TIFF.h - Released 2017-04-14T23:07:03Z // ---------------------------------------------------------------------------- // This file is part of the standard TIFF PixInsight module. // // Copyright (c) 2003-2017 Pleiades Astrophoto S.L. All Rights Reserved. // // Redistribution and use in both source and binary forms, with or without // modification, is permitted provided that the following conditions are met: // // 1. All redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. All redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the names "PixInsight" and "Pleiades Astrophoto", nor the names // of their contributors, may be used to endorse or promote products derived // from this software without specific prior written permission. For written // permission, please contact info@pixinsight.com. // // 4. All products derived from this software, in any form whatsoever, must // reproduce the following acknowledgment in the end-user documentation // and/or other materials provided with the product: // // "This product is based on software from the PixInsight project, developed // by Pleiades Astrophoto and its contributors (http://pixinsight.com/)." // // Alternatively, if that is where third-party acknowledgments normally // appear, this acknowledgment must be reproduced in the product itself. // // THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO 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 PLEIADES ASTROPHOTO OR ITS // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS // INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE, // DATA OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ---------------------------------------------------------------------------- #ifndef __PCL_TIFF_h #define __PCL_TIFF_h #ifndef __PCL_Defs_h #include <pcl/Defs.h> #endif #ifndef __PCL_AutoPointer_h #include <pcl/AutoPointer.h> #endif #ifndef __PCL_File_h #include <pcl/File.h> #endif #ifndef __PCL_ICCProfile_h #include <pcl/ICCProfile.h> #endif #ifndef __PCL_Image_h #include <pcl/Image.h> #endif #ifndef __PCL_ImageDescription_h #include <pcl/ImageDescription.h> #endif #ifndef __PCL_Version_h #include <pcl/Version.h> #endif namespace pcl { // ---------------------------------------------------------------------------- struct TIFFFileData; // ---------------------------------------------------------------------------- /* * Supported TIFF compression algorithms */ namespace TIFFCompression { enum value_type { Unknown = 0x80, // Unknown or unsupported TIFF compression None = 0x00, // No compression ZIP = 0x01, // ZLIB (deflate) compression: Open, efficient, recommended. LZW = 0x02 // LZW: Less efficient than ZIP, had patent issues, discouraged. }; } // ---------------------------------------------------------------------------- /* * TIFF-specific image file options */ class TIFFImageOptions { public: typedef TIFFCompression::value_type compression_codec; compression_codec compression : 8; // Compression algorithm bool planar : 1; // Planar organization; chunky otherwise bool associatedAlpha : 1; // Associated alpha channel bool premultipliedAlpha : 1; // RGB/K premultiplied by alpha uint8 verbosity : 3; // Verbosity level: 0 = quiet, > 0 = write console state messages. int __rsv__ : 18; // Reserved for future extension --must be zero uint16 stripSize; // The strip size in bytes for TIFF image file I/O String software; // Software description String imageDescription; // Image description String copyright; // Copyright notice TIFFImageOptions() { Reset(); } TIFFImageOptions( const TIFFImageOptions& ) = default; TIFFImageOptions& operator =( const TIFFImageOptions& ) = default; void Reset() { compression = TIFFCompression::None; planar = false; associatedAlpha = true; premultipliedAlpha = false; verbosity = 1; __rsv__ = 0; stripSize = 4096; software = PixInsightVersion::AsString() + " / " + Version::AsString(); imageDescription.Clear(); copyright.Clear(); } }; // ---------------------------------------------------------------------------- /* * Base class for the TIFFReader and TIFFWriter classes. */ class TIFF { public: /* * TIFF-specific exception class */ class Error : public File::Error { public: Error( const String& filePath, const String& message ) : File::Error( filePath, message ) { } Error( const TIFF::Error& x ) = default; virtual String ExceptionClass() const { return "PCL TIFF Format Support"; } }; #define PCL_DECLARE_TIFF_ERROR( className, errorMessage ) \ class className : public TIFF::Error \ { \ public: \ className( const String& filePath ) : \ TIFF::Error( filePath, errorMessage ) \ { \ } \ className( const className& x ) = default; \ }; PCL_DECLARE_TIFF_ERROR( InvalidFilePath, "Internal error: Invalid file path" ) PCL_DECLARE_TIFF_ERROR( WriterNotInitialized, "Internal error: TIFFWriter instance not initialized" ) PCL_DECLARE_TIFF_ERROR( UnableToOpenFile, "Unable to open TIFF file" ) PCL_DECLARE_TIFF_ERROR( UnableToCreateFile, "Unable to create TIFF file" ) PCL_DECLARE_TIFF_ERROR( FileReadError, "Error reading TIFF file" ) PCL_DECLARE_TIFF_ERROR( FileWriteError, "Error writing TIFF file" ) PCL_DECLARE_TIFF_ERROR( UnsupportedColorSpace, "Unsupported TIFF color space: Must be either grayscale or RGB color" ) PCL_DECLARE_TIFF_ERROR( UnsupportedBitsPerSample, "Unsupported TIFF bits per sample: Must be 8|16|32|64 bits" ) PCL_DECLARE_TIFF_ERROR( UnsupportedSampleFormat, "Unsupported TIFF sample format: Must be 8|16|32-bit integers or 32|64-bit IEEE floating point" ) PCL_DECLARE_TIFF_ERROR( InvalidNormalizationRange, "Internal error: Invalid TIFF normalization range" ) PCL_DECLARE_TIFF_ERROR( InvalidReadOperation, "Internal error: Invalid TIFF read operation" ) PCL_DECLARE_TIFF_ERROR( InvalidWriteOperation, "Internal error: Invalid TIFF write operation" ) TIFF(); TIFF( const TIFF& ) = delete; TIFF& operator =( const TIFF& ) = delete; virtual ~TIFF(); const TIFFImageOptions& TIFFOptions() const { return m_tiffOptions; } void SetTIFFOptions( const TIFFImageOptions& options ) { m_tiffOptions = options; } String Path() const { return m_path; } protected: String m_path; TIFFImageOptions m_tiffOptions; AutoPointer<TIFFFileData> m_fileData; void CloseStream(); // ### derived must call base }; // ---------------------------------------------------------------------------- /* * TIFF image file reader */ class TIFFReader : public TIFF { public: TIFFReader(); TIFFReader( const TIFFReader& ) = delete; TIFFReader& operator =( const TIFFReader& ) = delete; virtual ~TIFFReader(); bool IsOpen() const; void Close(); void Open( const String& filePath ); const ImageInfo& Info() const { return m_image.info; } const ImageOptions& Options() const { return m_image.options; } void SetOptions( const ImageOptions& options ) { m_image.options = options; } ICCProfile ReadICCProfile(); void ReadImage( FImage& ); void ReadImage( DImage& ); void ReadImage( UInt8Image& ); void ReadImage( UInt16Image& ); void ReadImage( UInt32Image& ); private: ImageDescription m_image; }; // ---------------------------------------------------------------------------- /* * TIFF image file writer. */ class TIFFWriter : public TIFF { public: TIFFWriter(); TIFFWriter( const TIFFWriter& ) = delete; TIFFWriter& operator =( const TIFFWriter& ) = delete; virtual ~TIFFWriter(); bool IsOpen() const; void Close(); void Create( const String& filePath ); const ImageOptions& Options() const { return m_options; } void SetOptions( const ImageOptions& options ) { m_options = options; } void WriteICCProfile( const ICCProfile& icc ); void WriteImage( const FImage& ); void WriteImage( const DImage& ); void WriteImage( const UInt8Image& ); void WriteImage( const UInt16Image& ); void WriteImage( const UInt32Image& ); void Reset() { Close(); m_iccProfile.Clear(); } private: ImageOptions m_options; ICCProfile m_iccProfile; }; // ---------------------------------------------------------------------------- } // pcl #endif // __PCL_TIFF_h // ---------------------------------------------------------------------------- // EOF TIFF.h - Released 2017-04-14T23:07:03Z
[ "juan.conejero@pixinsight.com" ]
juan.conejero@pixinsight.com
057b921fec8b10a6c0b433f0fdd8fafc3cdb788e
28dba754ddf8211d754dd4a6b0704bbedb2bd373
/Spoj/AIBOHP.cpp
8ce2e3745a7fbc04b1efd46844d02ac0458c7561
[]
no_license
zjsxzy/algo
599354679bd72ef20c724bb50b42fce65ceab76f
a84494969952f981bfdc38003f7269e5c80a142e
refs/heads/master
2023-08-31T17:00:53.393421
2023-08-19T14:20:31
2023-08-19T14:20:31
10,140,040
0
1
null
null
null
null
UTF-8
C++
false
false
828
cpp
#include <map> #include <set> #include <list> #include <cmath> #include <queue> #include <stack> #include <bitset> #include <vector> #include <cstdio> #include <string> #include <sstream> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int MAXN = 6100 + 10; char str[MAXN]; int F[2][MAXN]; int main() { freopen("a", "r", stdin); int T; scanf("%d", &T); while (T--) { scanf("%s", str); memset(F, 0, sizeof(F)); int N = strlen(str); int k = 0; for (int i = N - 2; i >= 0; i--) { for (int j = i; j < N; j++) { if (str[i] == str[j]) F[k][j] = F[1 - k][j - 1]; else F[k][j] = min(F[1 - k][j], F[k][j - 1]) + 1; } for (int j = 0; j < N; j++) F[1 - k][j] = 0; k = 1 - k; } printf("%d\n", F[1 - k][N - 1]); } return 0; }
[ "zjsxzy@gmail.com" ]
zjsxzy@gmail.com
22229540d16717d22f9281dc328e7e6f2c7a4f49
009851177d04a441141113189125a91a26f4dc74
/node/src/node_sockaddr.h
2e3ae09ce3bb8df4a37a11cf0ce5117cba9c7425
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "NAIST-2003", "Zlib", "Artistic-2.0", "NTP", "CC0-1.0", "LicenseRef-scancode-public-domain-disclaimer", "ISC", "LicenseRef-scancode-openssl", "LicenseRef-scancode-unicode", "Apache-2.0", "LicenseRef-scancode-public-domain", "ICU", "...
permissive
xuelongqy/cnode
a967f9e71315b10d3870192b4bbe2c341b196507
ac256264d329e68b6c5ae3281b0e7bb5a95ae164
refs/heads/master
2023-01-30T11:23:41.485647
2020-03-25T05:55:13
2020-03-25T05:55:13
246,811,631
0
1
MIT
2023-01-07T15:54:34
2020-03-12T10:58:07
C++
UTF-8
C++
false
false
3,640
h
#ifndef SRC_NODE_SOCKADDR_H_ #define SRC_NODE_SOCKADDR_H_ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS #include "env.h" #include "memory_tracker.h" #include "node.h" #include "uv.h" #include "v8.h" #include <string> #include <unordered_map> namespace node { class SocketAddress : public MemoryRetainer { public: struct Hash { size_t operator()(const SocketAddress& addr) const; }; inline bool operator==(const SocketAddress& other) const; inline bool operator!=(const SocketAddress& other) const; inline static bool is_numeric_host(const char* hostname); inline static bool is_numeric_host(const char* hostname, int family); // Returns true if converting {family, host, port} to *addr succeeded. static bool ToSockAddr( int32_t family, const char* host, uint32_t port, sockaddr_storage* addr); // Returns true if converting {family, host, port} to *addr succeeded. static bool New( int32_t family, const char* host, uint32_t port, SocketAddress* addr); static bool New( const char* host, uint32_t port, SocketAddress* addr); // Returns the port for an IPv4 or IPv6 address. inline static int GetPort(const sockaddr* addr); inline static int GetPort(const sockaddr_storage* addr); // Returns the numeric host as a string for an IPv4 or IPv6 address. inline static std::string GetAddress(const sockaddr* addr); inline static std::string GetAddress(const sockaddr_storage* addr); // Returns the struct length for an IPv4, IPv6 or UNIX domain. inline static size_t GetLength(const sockaddr* addr); inline static size_t GetLength(const sockaddr_storage* addr); SocketAddress() = default; inline explicit SocketAddress(const sockaddr* addr); inline SocketAddress(const SocketAddress& addr); inline SocketAddress& operator=(const sockaddr* other); inline SocketAddress& operator=(const SocketAddress& other); inline const sockaddr& operator*() const; inline const sockaddr* operator->() const; inline const sockaddr* data() const; inline const uint8_t* raw() const; inline sockaddr* storage(); inline size_t length() const; inline int family() const; inline std::string address() const; inline int port() const; // If the SocketAddress is an IPv6 address, returns the // current value of the IPv6 flow label, if set. Otherwise // returns 0. inline uint32_t flow_label() const; // If the SocketAddress is an IPv6 address, sets the // current value of the IPv6 flow label. If not an // IPv6 address, set_flow_label is a non-op. It // is important to note that the flow label, // while represented as an uint32_t, the flow // label is strictly limited to 20 bits, and // this will assert if any value larger than // 20-bits is specified. inline void set_flow_label(uint32_t label = 0); inline void Update(uint8_t* data, size_t len); static SocketAddress FromSockName(const uv_udp_t& handle); static SocketAddress FromSockName(const uv_tcp_t& handle); static SocketAddress FromPeerName(const uv_udp_t& handle); static SocketAddress FromPeerName(const uv_tcp_t& handle); inline v8::Local<v8::Object> ToJS( Environment* env, v8::Local<v8::Object> obj = v8::Local<v8::Object>()) const; inline std::string ToString() const; SET_NO_MEMORY_INFO() SET_MEMORY_INFO_NAME(SocketAddress) SET_SELF_SIZE(SocketAddress) template <typename T> using Map = std::unordered_map<SocketAddress, T, Hash>; private: sockaddr_storage address_; }; } // namespace node #endif // NOE_WANT_INTERNALS #endif // SRC_NODE_SOCKADDR_H_
[ "59814509@qq.com" ]
59814509@qq.com
38594e7cd551b4237f6b2e252835d8e7447a530c
560090526e32e009e2e9331e8a2b4f1e7861a5e8
/Compiled/blaze-3.2/blaze/math/typetraits/HasSIMDInvSqrt.h
d844f4dfc4a8cc7f8df1fb8bceefb7362b439198
[ "BSD-3-Clause" ]
permissive
jcd1994/MatlabTools
9a4c1f8190b5ceda102201799cc6c483c0a7b6f7
2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1
refs/heads/master
2021-01-18T03:05:19.351404
2018-02-14T02:17:07
2018-02-14T02:17:07
84,264,330
2
0
null
null
null
null
UTF-8
C++
false
false
5,494
h
//================================================================================================= /*! // \file blaze/math/typetraits/HasSIMDInvSqrt.h // \brief Header file for the HasSIMDInvSqrt type trait // // Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_MATH_TYPETRAITS_HASSIMDINVSQRT_H_ #define _BLAZE_MATH_TYPETRAITS_HASSIMDINVSQRT_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/system/Vectorization.h> #include <blaze/util/EnableIf.h> #include <blaze/util/IntegralConstant.h> #include <blaze/util/mpl/Or.h> #include <blaze/util/typetraits/Decay.h> #include <blaze/util/typetraits/IsDouble.h> #include <blaze/util/typetraits/IsFloat.h> namespace blaze { //================================================================================================= // // CLASS DEFINITION // //================================================================================================= //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ template< typename T // Type of the operand , typename = void > // Restricting condition struct HasSIMDInvSqrtHelper { enum : bool { value = false }; }; /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*! \cond BLAZE_INTERNAL */ #if BLAZE_SVML_MODE template< typename T > struct HasSIMDInvSqrtHelper< T, EnableIf_< Or< IsFloat<T>, IsDouble<T> > > > { enum : bool { value = bool( BLAZE_SSE_MODE ) || bool( BLAZE_AVX_MODE ) || bool( BLAZE_MIC_MODE ) || bool( BLAZE_AVX512F_MODE ) }; }; #endif /*! \endcond */ //************************************************************************************************* //************************************************************************************************* /*!\brief Availability of a SIMD inverse square root operation for the given data type. // \ingroup math_type_traits // // Depending on the available instruction set (SSE, SSE2, SSE3, SSE4, AVX, AVX2, MIC, ...) and // the used compiler, this type trait provides the information whether a SIMD inverse square root // operation exists for the given data type \a T (ignoring the cv-qualifiers). In case the SIMD // operation is available, the \a value member constant is set to \a true, the nested type // definition \a Type is \a TrueType, and the class derives from \a TrueType. Otherwise \a value // is set to \a false, \a Type is \a FalseType, and the class derives from \a FalseType. The // following example assumes that the Intel SVML is available: \code blaze::HasSIMDInvSqrt< float >::value // Evaluates to 1 blaze::HasSIMDInvSqrt< double >::Type // Results in TrueType blaze::HasSIMDInvSqrt< const double > // Is derived from TrueType blaze::HasSIMDInvSqrt< unsigned int >::value // Evaluates to 0 blaze::HasSIMDInvSqrt< long double >::Type // Results in FalseType blaze::HasSIMDInvSqrt< complex<double> > // Is derived from FalseType \endcode */ template< typename T > // Type of the operand struct HasSIMDInvSqrt : public BoolConstant< HasSIMDInvSqrtHelper< Decay_<T> >::value > {}; //************************************************************************************************* } // namespace blaze #endif
[ "jonathan.doucette@alumni.ubc.ca" ]
jonathan.doucette@alumni.ubc.ca
90cf709c221c8d781c206f13cb90e3c48b521d44
38c10c01007624cd2056884f25e0d6ab85442194
/third_party/WebKit/Source/core/svg/properties/SVGAnimatedProperty.h
4fe552ffe8ff0568de7e23dcc601b9e18f442b3c
[ "BSD-3-Clause", "BSD-2-Clause", "LGPL-2.0-only", "LGPL-2.1-only", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
12,027
h
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. G* * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SVGAnimatedProperty_h #define SVGAnimatedProperty_h #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "bindings/core/v8/ScriptWrappable.h" #include "core/dom/ExceptionCode.h" #include "core/svg/SVGParsingError.h" #include "core/svg/properties/SVGPropertyInfo.h" #include "core/svg/properties/SVGPropertyTearOff.h" #include "platform/heap/Handle.h" #include "wtf/Noncopyable.h" #include "wtf/PassRefPtr.h" #include "wtf/RefCounted.h" namespace blink { class SVGElement; class SVGAnimatedPropertyBase : public RefCountedWillBeGarbageCollectedFinalized<SVGAnimatedPropertyBase>, public ScriptWrappable { DEFINE_WRAPPERTYPEINFO_NOT_REACHED(); WTF_MAKE_NONCOPYABLE(SVGAnimatedPropertyBase); public: virtual ~SVGAnimatedPropertyBase(); virtual SVGPropertyBase* currentValueBase() = 0; virtual bool isAnimating() const = 0; virtual PassRefPtrWillBeRawPtr<SVGPropertyBase> createAnimatedValue() = 0; virtual void setAnimatedValue(PassRefPtrWillBeRawPtr<SVGPropertyBase>) = 0; virtual void animationEnded(); virtual void setBaseValueAsString(const String& value, SVGParsingError& parseError) = 0; virtual bool needsSynchronizeAttribute() = 0; virtual void synchronizeAttribute(); AnimatedPropertyType type() const { return m_type; } SVGElement* contextElement() const { return m_contextElement; } const QualifiedName& attributeName() const { return m_attributeName; } bool isReadOnly() const { return m_isReadOnly; } void setReadOnly() { m_isReadOnly = true; } bool isSpecified() const; DEFINE_INLINE_VIRTUAL_TRACE() { } protected: SVGAnimatedPropertyBase(AnimatedPropertyType, SVGElement*, const QualifiedName& attributeName); private: const AnimatedPropertyType m_type; bool m_isReadOnly; // This raw pointer is safe since the SVG element is guaranteed to be kept // alive by a V8 wrapper. GC_PLUGIN_IGNORE("crbug.com/528275") SVGElement* m_contextElement; const QualifiedName& m_attributeName; }; template <typename Property> class SVGAnimatedPropertyCommon : public SVGAnimatedPropertyBase { public: Property* baseValue() { return m_baseValue.get(); } Property* currentValue() { return m_currentValue ? m_currentValue.get() : m_baseValue.get(); } const Property* currentValue() const { return const_cast<SVGAnimatedPropertyCommon*>(this)->currentValue(); } SVGPropertyBase* currentValueBase() override { return currentValue(); } bool isAnimating() const override { return m_currentValue; } void setBaseValueAsString(const String& value, SVGParsingError& parseError) override { TrackExceptionState es; m_baseValue->setValueAsString(value, es); if (es.hadException()) parseError = ParsingAttributeFailedError; } PassRefPtrWillBeRawPtr<SVGPropertyBase> createAnimatedValue() override { return m_baseValue->clone(); } void setAnimatedValue(PassRefPtrWillBeRawPtr<SVGPropertyBase> passValue) override { RefPtrWillBeRawPtr<SVGPropertyBase> value = passValue; ASSERT(value->type() == Property::classType()); m_currentValue = static_pointer_cast<Property>(value.release()); } void animationEnded() override { m_currentValue.clear(); SVGAnimatedPropertyBase::animationEnded(); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_baseValue); visitor->trace(m_currentValue); SVGAnimatedPropertyBase::trace(visitor); } protected: SVGAnimatedPropertyCommon(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<Property> initialValue) : SVGAnimatedPropertyBase(Property::classType(), contextElement, attributeName) , m_baseValue(initialValue) { } private: RefPtrWillBeMember<Property> m_baseValue; RefPtrWillBeMember<Property> m_currentValue; }; // Implementation of SVGAnimatedProperty which uses primitive types. // This is for classes which return primitive type for its "animVal". // Examples are SVGAnimatedBoolean, SVGAnimatedNumber, etc. template <typename Property, typename TearOffType = typename Property::TearOffType, typename PrimitiveType = typename Property::PrimitiveType> class SVGAnimatedProperty : public SVGAnimatedPropertyCommon<Property> { public: bool needsSynchronizeAttribute() override { // DOM attribute synchronization is only needed if tear-off is being touched from javascript or the property is being animated. // This prevents unnecessary attribute creation on target element. return m_baseValueUpdated || this->isAnimating(); } void synchronizeAttribute() override { SVGAnimatedPropertyBase::synchronizeAttribute(); m_baseValueUpdated = false; } // SVGAnimated* DOM Spec implementations: // baseVal()/setBaseVal()/animVal() are only to be used from SVG DOM implementation. // Use currentValue() from C++ code. PrimitiveType baseVal() { return this->baseValue()->value(); } void setBaseVal(PrimitiveType value, ExceptionState& exceptionState) { if (this->isReadOnly()) { exceptionState.throwDOMException(NoModificationAllowedError, "The attribute is read-only."); return; } this->baseValue()->setValue(value); m_baseValueUpdated = true; ASSERT(this->attributeName() != QualifiedName::null()); this->contextElement()->invalidateSVGAttributes(); this->contextElement()->svgAttributeChanged(this->attributeName()); } PrimitiveType animVal() { return this->currentValue()->value(); } protected: SVGAnimatedProperty(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<Property> initialValue) : SVGAnimatedPropertyCommon<Property>(contextElement, attributeName, initialValue) , m_baseValueUpdated(false) { } bool m_baseValueUpdated; }; // Implementation of SVGAnimatedProperty which uses tear-off value types. // These classes has "void" for its PrimitiveType. // This is for classes which return special type for its "animVal". // Examples are SVGAnimatedLength, SVGAnimatedRect, SVGAnimated*List, etc. template <typename Property, typename TearOffType> class SVGAnimatedProperty<Property, TearOffType, void> : public SVGAnimatedPropertyCommon<Property> { public: static PassRefPtrWillBeRawPtr<SVGAnimatedProperty<Property>> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<Property> initialValue) { return adoptRefWillBeNoop(new SVGAnimatedProperty<Property>(contextElement, attributeName, initialValue)); } void setAnimatedValue(PassRefPtrWillBeRawPtr<SVGPropertyBase> value) override { SVGAnimatedPropertyCommon<Property>::setAnimatedValue(value); updateAnimValTearOffIfNeeded(); } void animationEnded() override { SVGAnimatedPropertyCommon<Property>::animationEnded(); updateAnimValTearOffIfNeeded(); } bool needsSynchronizeAttribute() override { // DOM attribute synchronization is only needed if tear-off is being touched from javascript or the property is being animated. // This prevents unnecessary attribute creation on target element. return m_baseValTearOff || this->isAnimating(); } // SVGAnimated* DOM Spec implementations: // baseVal()/animVal() are only to be used from SVG DOM implementation. // Use currentValue() from C++ code. virtual TearOffType* baseVal() { if (!m_baseValTearOff) { m_baseValTearOff = TearOffType::create(this->baseValue(), this->contextElement(), PropertyIsNotAnimVal, this->attributeName()); if (this->isReadOnly()) m_baseValTearOff->setIsReadOnlyProperty(); } return m_baseValTearOff.get(); } TearOffType* animVal() { if (!m_animValTearOff) m_animValTearOff = TearOffType::create(this->currentValue(), this->contextElement(), PropertyIsAnimVal, this->attributeName()); return m_animValTearOff.get(); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_baseValTearOff); visitor->trace(m_animValTearOff); SVGAnimatedPropertyCommon<Property>::trace(visitor); } protected: SVGAnimatedProperty(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<Property> initialValue) : SVGAnimatedPropertyCommon<Property>(contextElement, attributeName, initialValue) { } private: void updateAnimValTearOffIfNeeded() { if (m_animValTearOff) m_animValTearOff->setTarget(this->currentValue()); } // When still (not animated): // Both m_animValTearOff and m_baseValTearOff target m_baseValue. // When animated: // m_animValTearOff targets m_currentValue. // m_baseValTearOff targets m_baseValue. RefPtrWillBeMember<TearOffType> m_baseValTearOff; RefPtrWillBeMember<TearOffType> m_animValTearOff; }; // Implementation of SVGAnimatedProperty which doesn't use tear-off value types. // This class has "void" for its TearOffType. // Currently only used for SVGAnimatedPath. template <typename Property> class SVGAnimatedProperty<Property, void, void> : public SVGAnimatedPropertyCommon<Property> { public: static PassRefPtrWillBeRawPtr<SVGAnimatedProperty<Property>> create(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<Property> initialValue) { return adoptRefWillBeNoop(new SVGAnimatedProperty<Property>(contextElement, attributeName, initialValue)); } bool needsSynchronizeAttribute() override { // DOM attribute synchronization is only needed if the property is being animated. return this->isAnimating(); } protected: SVGAnimatedProperty(SVGElement* contextElement, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<Property> initialValue) : SVGAnimatedPropertyCommon<Property>(contextElement, attributeName, initialValue) { } }; } // namespace blink #endif // SVGAnimatedProperty_h
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
a2653126ee9376ec18f4bdbdc54ac5526692a31e
703dbe9e66a5016fd76858d7153091876cd38d98
/Source/SimpleShooter/BTService_PlayerLocation.h
0f43ea4a6cca29af9ec887e865fc401057d532ef
[]
no_license
ImprobableImprov/Shooter-Multiplayer-Game
196f2c7d09d91c604cdb708646da00ebf491f4c9
e7c4718271b75cc112a077872d30eac8d837c406
refs/heads/main
2023-02-25T14:47:38.657878
2021-01-26T04:58:08
2021-01-26T04:58:08
330,248,596
0
0
null
null
null
null
UTF-8
C++
false
false
517
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "BehaviorTree/Services/BTService_BlackboardBase.h" #include "BTService_PlayerLocation.generated.h" /** * */ UCLASS() class SIMPLESHOOTER_API UBTService_PlayerLocation : public UBTService_BlackboardBase { GENERATED_BODY() public: UBTService_PlayerLocation(); protected: virtual void TickNode(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory, float DeltaSeconds) override; };
[ "travisshu8@gmail.com" ]
travisshu8@gmail.com
1084d83a9618344871b5e2334ad89f95ca8ebd73
1e87e8226622e017a444ba273aa387170f013cd9
/TragischeBibliotheek/TragicLibrary/TragicLibrary/Library.cpp
0610bfdeb50cefbc4606191e9045e973827f142e
[]
no_license
CaptainJellyBS/CPlusPlusBasic
82e52998d88c99e229468501c2a0640b59956d78
b9cdd161b6d9cdb92a14ceb704c9a03964b37dd5
refs/heads/master
2022-12-31T11:22:41.167819
2020-10-23T13:26:35
2020-10-23T13:26:35
298,493,952
0
0
null
null
null
null
UTF-8
C++
false
false
854
cpp
#include "Library.h" Library::~Library() { delete book; } Library::Library() { book = new Book("Dune"); } Library::Library(const Library& l) { book = new Book(*l.book); } Library& Library::operator=(const Library& l) { if (&l == this) { return *this; } book = new Book(*l.book); delete l.book; } /// <summary> /// /// Return the library book. Returns false if the book is already borrowed /// </summary> /// <returns></returns> bool Library::borrowBook() { if (book->borrowed) { return false; } book->borrowed = true; return true; } /// <summary> /// Return the library book. Returns false if the book wasn't borrowed at the time /// </summary> /// <returns></returns> bool Library::returnBook() { if (!book->borrowed) { return false; } book->borrowed = false; return true; } void Library::printBookStatus() { book->printStatus(); }
[ "manakouwenberg@gmail.com" ]
manakouwenberg@gmail.com
ef42c6e8e3e2c5ebefcd34c2242ffa8a30e63d78
56b8b3eb6011e54c16b7211224b79f8daa33139a
/Algorithms/Tasks.0001.0500/0169.MajorityElement/solution.cpp
dfc4c1fd114a026863c8ff1e3fe4d7bd831f62f0
[ "MIT" ]
permissive
stdstring/leetcode
98aee82bc080705935d4ce01ff1d4c2f530a766c
60000e9144b04a2341996419bee51ba53ad879e6
refs/heads/master
2023-08-16T16:19:09.269345
2023-08-16T05:31:46
2023-08-16T05:31:46
127,088,029
0
0
MIT
2023-02-25T08:46:17
2018-03-28T05:24:34
C++
UTF-8
C++
false
false
1,305
cpp
#include <unordered_map> #include <utility> #include <vector> #include "gtest/gtest.h" namespace { class Solution { public: int majorityElement(std::vector<int> const &nums) const { std::unordered_map<int, size_t> numsCountData; for (int num : nums) { std::unordered_map<int, size_t>::iterator entry = numsCountData.find(num); if (entry == numsCountData.end()) numsCountData.emplace(num, 1); else ++(entry->second); } int majorityElement = 0; size_t majorityElementCount = 0; for (std::unordered_map<int, size_t>::value_type const &entry : numsCountData) { if (entry.second > majorityElementCount) { majorityElement = entry.first; majorityElementCount = entry.second; } } return majorityElement; } }; } namespace MajorityElementTask { TEST(MajorityElementTaskTests, Examples) { const Solution solution; ASSERT_EQ(3, solution.majorityElement({3, 2, 3})); ASSERT_EQ(2, solution.majorityElement({2, 2, 1, 1, 1, 2, 2})); } TEST(MajorityElementTaskTests, FromWrongAnswers) { const Solution solution; ASSERT_EQ(5, solution.majorityElement({6, 5, 5})); } }
[ "std_string@mail.ru" ]
std_string@mail.ru
9bac6b8d0a62acbdbb6bb2bfa796039fa554eec3
4aff5a49d635ecfab5cac986b1ddc1809189e8f8
/LeetCode/Build Array from Permutation/build array from permutation.cpp
b0cfec3ea25a495697f1bd25c6f5e3f4f2ad7028
[]
no_license
shreyrai99/CP-DSA-Questions
1221f595391643f5967a77efeb790352536ab9ff
5a5bfdaee6bf0253661259cae7780b8859108dbd
refs/heads/main
2023-09-04T06:38:59.114238
2021-10-22T09:46:59
2021-10-22T09:46:59
413,551,990
1
0
null
2021-10-04T19:10:04
2021-10-04T19:10:04
null
UTF-8
C++
false
false
427
cpp
//solution class Solution { public: vector<int> buildArray(vector<int>& nums) { vector <int> arr; // initializing a vector array of name arr for(int i=0; i<nums.size(); i++){ //using the for loop to iterate through the array arr.push_back(nums[nums[i]]); // adding the required elements in the array } return arr; //returning the array to the function call } };
[ "pranavidhya28@gmail.com" ]
pranavidhya28@gmail.com
86edd708a0380af2e52889cb59d8db17761fd3b1
962b463e93597e9ba8ab1000a119cd3c92e4de29
/030_polynomial/poly.hpp
9f653308a857d24e4541d31c9d9e8e2ea5f3916d
[]
no_license
jimmyshuyulee/duke-ece751
fc00feeb9d84310a3840ea8d03186f64d2a7192e
481084b36f4e207a3bfeeff689c7d5ead64fa1c7
refs/heads/master
2020-09-20T15:06:03.808189
2019-12-09T07:06:20
2019-12-09T07:06:20
224,517,059
1
0
null
null
null
null
UTF-8
C++
false
false
7,846
hpp
#include <cstdlib> #include <exception> #include <functional> #include <iostream> #include <map> using namespace std; // Whenever the program needs to "give up", it throws a convergence_failure template<typename Num> class convergence_failure : public exception { public: const Num value; explicit convergence_failure(const Num & v) : value(v){}; virtual const char * what() const throw() { return "Convergence failure"; } }; // A class represents the Polynomial which has its coefficient with type "Num" template<typename Num> class Polynomial { map<int, Num, greater<int> > coeff; // Sort the keys in decending order public: // Default construct the polynomial to be "0" (i.e., 0*x^0) Polynomial() : coeff() { coeff[0] = Num(); } // Add (c*x^p) to this Polynomial, updatings its value. // Add the coefficients to ans if the term exist. Otherwise, insert it. // This approach uses [] operator of map to access terms in lhs, which so // the overall time complexity is O(logn) void addTerm(const Num & c, int p) { // There is no need to check whether p is in coeff. The [] operator checks // it and construct a new element in the map if p does not exist. // Only need to check c to avoid adding terms with 0 coefficient. if (c != Num()) { coeff[p] = coeff[p] + c; } } // Add this Polynomial to rhs, and return the resulting polynomial. // I use addTrem() to simplify the implementation here, but there should be // an O(n) approach for this function if I use iterator. I will try it after // this assignment get graded Polynomial operator+(const Polynomial & rhs) const { Polynomial<Num> ans(*this); typename map<int, Num>::iterator ans_itr = ans.coeff.begin(); typename map<int, Num>::const_iterator itr; for (itr = rhs.coeff.begin(); itr != rhs.coeff.end(); ++itr) { ans.addTerm(itr->second, itr->first); } return ans; } // Return the negation of this Polynomial. // For example, if this Polynomial is 4 * x ^ 3 - 2, return -4 * x ^ 3 + 2 Polynomial operator-() const { Polynomial<Num> ans(*this); typename map<int, Num>::iterator itr; for (itr = ans.coeff.begin(); itr != ans.coeff.end(); ++itr) { itr->second = -(itr->second); } return ans; } // Subtract rhs from this Polynomial and return the result // Achieved by summing *this and (-rhs) Polynomial operator-(const Polynomial & rhs) const { Polynomial<Num> ansWithZero(*this + (-rhs)); typename map<int, Num>::iterator itr; // The sum of *this and (-rhs) may contain terms with 0 coefficients. // Only add non-zero terms to ans. Polynomial<Num> ans; for (itr = ansWithZero.coeff.begin(); itr != ansWithZero.coeff.end(); ++itr) { if (itr->second != Num() || itr->first == 0) { ans.addTerm(itr->second, itr->first); } } return ans; } // Multiply this Polynomial by a scalar and return the result // Return default constructed Polynomial if n is 0 Polynomial operator*(const Num & n) const { if (n == Num()) { return Polynomial<Num>(); } Polynomial<Num> ans(*this); typename map<int, Num>::iterator itr; for (itr = ans.coeff.begin(); itr != ans.coeff.end(); ++itr) { itr->second = n * itr->second; } return ans; } // Multiply this Polynomial by rhs, and return the result. // No need to handle the multiply by 0 case explicitly since addTerm() will // not add 0 coefficient terms Polynomial operator*(const Polynomial & rhs) const { Polynomial<Num> ans; typename map<int, Num>::const_iterator itr1 = coeff.begin(); while (itr1 != coeff.end()) { typename map<int, Num>::const_iterator itr2 = rhs.coeff.begin(); while (itr2 != rhs.coeff.end()) { ans.addTerm(itr1->second * itr2->second, itr1->first + itr2->first); ++itr2; } ++itr1; } return ans; } // Compare two Polynomials for equality and return the result. bool operator==(const Polynomial & rhs) const { typename map<int, Num>::const_iterator itr; for (itr = coeff.begin(); itr != coeff.end(); ++itr) { if (rhs.coeff.find(itr->first) == rhs.coeff.end()) { return false; } // Already checked that itr->first is a key in rhs.coeff, // so the at() function is no exception guaranteed if (rhs.coeff.at(itr->first) != itr->second) { return false; } } return true; } // Compare two Polynomials for inequality and return the result. bool operator!=(const Polynomial & rhs) const { return !(*this == rhs); } // Perform the + operation but update this Polynomial, // instead of returning a different Polynomial. Polynomial & operator+=(const Polynomial & rhs) { *this = *this + rhs; return (*this); } // Perform the - operation but update this Polynomial, // instead of returning a different Polynomial. Polynomial & operator-=(const Polynomial & rhs) { *this = *this - rhs; return (*this); } // Perform the * operation but update this Polynomial, // instead of returning a different Polynomial. Polynomial & operator*=(const Polynomial & rhs) { *this = *this * rhs; return (*this); } // Perform the * operation but update this Polynomial, // instead of returning a different Polynomial. Polynomial & operator*=(const Num & rhs) { *this = *this * rhs; return (*this); } //This evaluates the Polynomial at the given value of "x", and returns that answer. Num eval(const Num & x) const { Num ans = Num(); typename map<int, Num>::const_iterator itr; for (itr = coeff.begin(); itr != coeff.end(); ++itr) { Num term = itr->second; // Avoid using +=, *= or pow() here since it is not guaranteed // that Num will have these operators or functions. for (int i = 0; i < itr->first; ++i) { term = term * x; } ans = ans + term; } return ans; } // This takes the derivative of this Polynomial, resulting in another Polynomial. Polynomial derivative() const { // Polynomial always keeps the x^0 term even it has its coefficient==0, // so coeff.size() == 1 means it only has x^0 term and its derivative is 0. if (coeff.size() == 1) { return Polynomial(); } Polynomial<Num> ans; typename map<int, Num>::const_iterator itr; for (itr = coeff.begin(); itr != coeff.end(); ++itr) { if (itr->first > 0) { ans.addTerm(itr->second * itr->first, itr->first - 1); } } return ans; } //Use the Newton-Raphson method of numerically finding the zero of a Polynomial. Num findZero(Num x, unsigned maxSteps, double tolerance) { Polynomial<Num> fx(*this); for (int i = maxSteps; i > 0; --i) { if (abs(fx.eval(x)) <= tolerance) { // If already converge return x; } if (fx.derivative().eval(x) == Num()) { // If f(x)' is 0 throw convergence_failure<Num>(x); } x = x - (fx.eval(x) / fx.derivative().eval(x)); } if (abs(fx.eval(x)) > tolerance) { // If it does not converge throw convergence_failure<Num>(x); } return x; } template<typename N> friend std::ostream & operator<<(std::ostream & os, const Polynomial<N> & p); }; // Write the Polynomial to "os" such that it looks like this: // "4*x^4 + 2*x^3 + -7*x^2 + 0*x^1 + -9*x^0" template<typename N> std::ostream & operator<<(std::ostream & os, const Polynomial<N> & p) { if (p == Polynomial<N>()) { os << N(); return os; } typename map<int, N>::const_iterator itr = p.coeff.begin(); os << itr->second << "*x^" << itr->first; for (itr = ++p.coeff.begin(); itr != p.coeff.end(); ++itr) { if (itr->second != N()) { os << " + "; os << itr->second << "*x^" << itr->first; } } return os; }
[ "sl603@duke.edu" ]
sl603@duke.edu
78aa97b0ef920d2006c649c3b3b409a6c0599894
18f31ae2cd65bad9529df89cb0f08a2d6d757817
/EnumerateWindowProperties/EnumerateWindowProperties.cpp
4037287b215f9d5ad236c26302d301c5f2963b27
[]
no_license
xenoscr/EnumerateWindowProperties
e0d95581cef0ade192fc9e7fbdececd0f4c4d90e
96ce476abd94b5e4657579774ea62be8ffee8e75
refs/heads/master
2021-08-19T06:28:07.355256
2017-11-24T23:59:15
2017-11-24T23:59:15
111,827,316
0
0
null
null
null
null
UTF-8
C++
false
false
3,646
cpp
// EnumerateWindowProperties.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <cstdlib> #include <stdbool.h> using namespace std; #define BUFFER 4096 std::stringstream windowInfo; void hexDump(char *desc, void * addr, int len, int orgAddress); /* Convert strings to wide strings */ std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } /* Gather the properties for a window process */ BOOL CALLBACK WinPropProc(HWND hwndSubclass, LPTSTR lpszString, HANDLE hData, ULONG_PTR dwData) { ATOM atmText; atmText = GlobalFindAtom(lpszString); string strText; static int nProp = 1; HANDLE propHandle; //unsigned int *propPtr; char szBuf[MAX_PATH] = { 0 }; GlobalGetAtomNameA(atmText, szBuf, _countof(szBuf)); strText = szBuf; if (strcmp(szBuf, "UxSubclassInfo") == 0) { cout << windowInfo.str(); cout << nProp++ << " : " << strText << "\n"; std::wstring stemp = s2ws(strText); propHandle = GetProp(hwndSubclass, (LPCWSTR)stemp.c_str()); cout << "Parent: " << hwndSubclass << " Property: " << propHandle << "\n"; // Read the memory char buffer[500]; int* ptr = reinterpret_cast<int*>((int)propHandle); unsigned long byteRead; char* ptrBuff = buffer; int stat = ReadProcessMemory(hwndSubclass, ptr, buffer, 128, &byteRead); hexDump("None", &buffer, 128, (unsigned int)propHandle); } return TRUE; } /* Enumerate Child Windows */ BOOL CALLBACK EnumChildProc(HWND hWnd, LPARAM lParam) { EnumPropsEx(hWnd, WinPropProc, NULL); return TRUE; /* Return TRUE or the enumeration will stop. */ } /* Enumerate Windows Processes */ BOOL CALLBACK enumWindowsProc(__in HWND hWnd, __in LPARAM lParam) { int length = ::GetWindowTextLength(hWnd); if (length == 0) return TRUE; TCHAR* buffer; buffer = new TCHAR[length + 1]; memset(buffer, 0, (length + 1) * sizeof(TCHAR)); GetWindowText(hWnd, buffer, length + 1); tstring windowTitle = tstring(buffer); delete[] buffer; windowInfo.str(""); std::string sWindowTitle(windowTitle.begin(), windowTitle.end()); windowInfo << hWnd << ": " << sWindowTitle << "\n"; EnumPropsEx(hWnd, WinPropProc, 0); EnumChildWindows(hWnd, EnumChildProc, 0); return TRUE; } /* Dump memory */ void hexDump(char *desc, void * addr, int len, int orgAddress) { int i; unsigned char buff[17]; unsigned char *pc = (unsigned char *)&addr; // Output description if given. if (desc != NULL) printf("%s\n", desc); // Process every byte in the data. for (i = 0; i < len; i++) { if ((i % 16) == 0) { if (i != 0) printf(" %s\n", buff); // Output the offset. cout << (unsigned int*)orgAddress + i; printf(" %04x ", i); } // Now the hex code for the specific character. printf(" %02x", (unsigned char)pc[i]); // And store a printable ASCII character for later. if (((unsigned char)pc[i] < 0x20) || ((unsigned char)pc[i] > 0x7e)) { buff[i % 16] = '.'; } else { buff[i % 16] = (unsigned char)pc[i]; } buff[(i % 16) + 1] = '\0'; } // Pad out last line if not exactly 16 characters. while ((i % 16) != 0) { printf(" "); i++; } // And print the final ASCII bit. printf(" %s\n", buff); } int main() { std::wstring s2ws(const std::string& s); HWND hWnd; int result = 0; wcout << TEXT("Enumerating Windows...") << endl; BOOL enumeratingWindowsSucceeded = ::EnumWindows(enumWindowsProc, NULL); cin.get(); return 0; }
[ "xenos@xenos-1.net" ]
xenos@xenos-1.net
393dd7ab82fad433e69389de3f80e7974cb3cb58
f112f9745d7c916c68ee2b8ec05e93e74d7d3004
/cms/src/v20190321/model/TextData.cpp
2c991f117189d49ba666a6905e222aefd6ce0f9e
[ "Apache-2.0" ]
permissive
datalliance88/tencentcloud-sdk-cpp
d5ca9454e2692ac21a08394bf7a4ba98982640da
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
refs/heads/master
2020-09-04T20:59:42.950346
2019-11-18T07:40:56
2019-11-18T07:40:56
219,890,597
0
0
Apache-2.0
2019-11-06T02:02:01
2019-11-06T02:02:00
null
UTF-8
C++
false
false
4,047
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cms/v20190321/model/TextData.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cms::V20190321::Model; using namespace rapidjson; using namespace std; TextData::TextData() : m_evilFlagHasBeenSet(false), m_evilTypeHasBeenSet(false), m_keywordsHasBeenSet(false) { } CoreInternalOutcome TextData::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("EvilFlag") && !value["EvilFlag"].IsNull()) { if (!value["EvilFlag"].IsInt64()) { return CoreInternalOutcome(Error("response `TextData.EvilFlag` IsInt64=false incorrectly").SetRequestId(requestId)); } m_evilFlag = value["EvilFlag"].GetInt64(); m_evilFlagHasBeenSet = true; } if (value.HasMember("EvilType") && !value["EvilType"].IsNull()) { if (!value["EvilType"].IsInt64()) { return CoreInternalOutcome(Error("response `TextData.EvilType` IsInt64=false incorrectly").SetRequestId(requestId)); } m_evilType = value["EvilType"].GetInt64(); m_evilTypeHasBeenSet = true; } if (value.HasMember("Keywords") && !value["Keywords"].IsNull()) { if (!value["Keywords"].IsArray()) return CoreInternalOutcome(Error("response `TextData.Keywords` is not array type")); const Value &tmpValue = value["Keywords"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_keywords.push_back((*itr).GetString()); } m_keywordsHasBeenSet = true; } return CoreInternalOutcome(true); } void TextData::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_evilFlagHasBeenSet) { Value iKey(kStringType); string key = "EvilFlag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_evilFlag, allocator); } if (m_evilTypeHasBeenSet) { Value iKey(kStringType); string key = "EvilType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_evilType, allocator); } if (m_keywordsHasBeenSet) { Value iKey(kStringType); string key = "Keywords"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kArrayType).Move(), allocator); for (auto itr = m_keywords.begin(); itr != m_keywords.end(); ++itr) { value[key.c_str()].PushBack(Value().SetString((*itr).c_str(), allocator), allocator); } } } int64_t TextData::GetEvilFlag() const { return m_evilFlag; } void TextData::SetEvilFlag(const int64_t& _evilFlag) { m_evilFlag = _evilFlag; m_evilFlagHasBeenSet = true; } bool TextData::EvilFlagHasBeenSet() const { return m_evilFlagHasBeenSet; } int64_t TextData::GetEvilType() const { return m_evilType; } void TextData::SetEvilType(const int64_t& _evilType) { m_evilType = _evilType; m_evilTypeHasBeenSet = true; } bool TextData::EvilTypeHasBeenSet() const { return m_evilTypeHasBeenSet; } vector<string> TextData::GetKeywords() const { return m_keywords; } void TextData::SetKeywords(const vector<string>& _keywords) { m_keywords = _keywords; m_keywordsHasBeenSet = true; } bool TextData::KeywordsHasBeenSet() const { return m_keywordsHasBeenSet; }
[ "jimmyzhuang@tencent.com" ]
jimmyzhuang@tencent.com
fbd17b8d027aa00729377bba4dea06c35eb84cd4
0805b803ad608e07810af954048359c927294a0e
/bvheditor/ui/NewFileFPSDialog.h
c51e819206ce1b5f998b6e728f89bb0952b4360f
[]
no_license
yiyongc/BvhEditor
005feb3f44537544d66d54ab419186b73e184f57
b512e240bc7b1ad5f54fd2e77f0a3194302aab2d
refs/heads/master
2023-03-15T14:19:31.292081
2017-03-30T17:27:17
2017-03-30T17:27:17
66,918,016
0
0
null
null
null
null
UTF-8
C++
false
false
692
h
#pragma once #include "qdialog.h" #include "qlabel.h" #include <QVBoxLayout> #include <QHBoxLayout> #include "../controllers/LayerController.h" #include <QPushButton> #include <QtWidgets\QApplication> namespace cacani { namespace ui { class NewFileFPSDialog : public QDialog { Q_OBJECT public: NewFileFPSDialog(LayerController* layerController, int layerGroupIndex); ~NewFileFPSDialog(); private: LayerController* m_layerController; QPushButton* m_Button_Proj; QPushButton* m_Button_File; Layer* m_new_layer; double m_proj_fps; double m_newfile_fps; private Q_SLOTS: void buttonProjClicked(); void buttonFileClicked(); }; } }
[ "yiyong.cyy@gmail.com" ]
yiyong.cyy@gmail.com
2a3424d790e79e913c12d5a7560397342220fd17
d70408b086ea4e50c4323da242c54ee6dd0080bc
/Esp_server/Esp_server.ino
42f6025e2287e4728023bf998e812de3a6f8a7df
[]
no_license
Kozubowicz/Serwer-temperatura
8ccdba981dd2aedcf9e5da63bba2d56c3f6afc31
b4c9ea4e41703b32952ef02ccba7efea40c16c27
refs/heads/master
2022-11-15T20:14:21.034960
2020-07-12T00:40:55
2020-07-12T00:40:55
278,965,390
0
0
null
null
null
null
UTF-8
C++
false
false
4,468
ino
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #include <math.h> #include <Wire.h> #include <iostream> #include <cstdlib> //const char* ssid = "TP-LINK_37F3"; //const char* password = "70748109"; const char* ssid = "FunBox3-A702-1"; const char* password = "cdn1234567"; //const char* ssid = "MY ASUS"; //const char* password = "arlenaAnaleena"; ESP8266WebServer server(80); char y[5]; char e[10]; double Tem; #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define SCREEN_WIDTH 128 // OLED display width, in pixels #define SCREEN_HEIGHT 32 // OLED display height, in pixels // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) #define OLED_RESET 13 // Reset pin # (or -1 if sharing Arduino reset pin) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET); #include "iron.h" void handleRoot() { String message; char temp[400]; snprintf(temp, 400, "<html>\ <head>\ <meta http-equiv='refresh' content='10'/>\ <title>Termo demo</title>\ <style>\ body { background-color: #000000; font-size: 60%; font-family: Arial, Helvetica, Sans-Serif; Color: #00FF00; text-align:center; }\ </style>\ </head>\ <body>\ <h1>Termometr</h1>\ <h2>Temperatura: \ </body>\ </html>" ); message += temp; message += Tem; message += " &#176;"; message += "C"; server.send(200, "text/html", message); } void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void setup() { Serial.begin(9600); Wire.begin(4,5); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 Serial.println(F("SSD1306 allocation failed")); for(;;); // Don't proceed, loop forever } display.clearDisplay(); display.drawBitmap(0, 0, iron, 128, 32, 1); display.display(); delay(2000); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println(""); int vee = 0; while (WiFi.status() != WL_CONNECTED && vee<=20) { delay(500); Serial.print("."); vee++; } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); if (MDNS.begin("Termometr")) { Serial.println("MDNS responder started"); } server.on("/", handleRoot); server.on("/inline", []() { server.send(200, "text/plain", "Co ty tutaj robisz"); }); server.onNotFound(handleNotFound); server.begin(); Serial.println("HTTP server started"); pinMode(2, OUTPUT);} void loop() { server.handleClient(); digitalWrite(2, HIGH); if(Serial.available() > 0) { Serial.readBytes(e, 4); //Serial.println(e); digitalWrite(2, LOW); double w = atoi(e); Serial.println(w); double OutIn = ((w/1024)*100); //Serial.print(OutIn); //Serial.println(" %"); if(OutIn>=15 && OutIn<33){ Tem = -0.0127*OutIn*OutIn + 1.7135*OutIn-35.003;} else if(OutIn<15){ Tem = 0.0229*OutIn*OutIn*OutIn - 0.7435*OutIn*OutIn + 9.430*OutIn - 63;} else if(OutIn>=33 && OutIn<55){ Tem = 0.9046*OutIn-22.2;} else if(OutIn>=55 && OutIn<90){ Tem = 0.0011*OutIn*OutIn*OutIn-0.2123*OutIn*OutIn+14.609*OutIn-317.4;} else if(OutIn<90){ Tem = 0.5079*OutIn*OutIn*OutIn -143.41*OutIn*OutIn+ 13501*OutIn - 423693;} Serial.println("Temperatura: "); Serial.print(Tem); Serial.println(" C"); //Serial.println(x); //Serial.println(w); delay(100); //digitalWrite(2, HIGH); display.clearDisplay(); display.setCursor(30,0); display.setTextSize(1); display.setTextColor(WHITE); display.println("Temperatura:"); display.setTextSize(2); display.setCursor(24,10); display.print(Tem); display.println(" C"); display.setCursor(28,25); display.setTextSize(1); display.println(WiFi.localIP()); display.display(); } }
[ "kozubowiczpiotr@gmail.com" ]
kozubowiczpiotr@gmail.com
862d36ba6ef24a44c01b60b6a8ac793549701aa4
604c426db6a810a31b48526150259ee261313f69
/src/rational.cpp
6f1d621322773565ffb7d11cbda11becc55fe169
[]
no_license
xyee/ase_cw2
55721ecfb0897ed95b1f5ac9492af0f72f8dd8e3
c655dba2b2598485eac0b2c40e692b39c7bd544f
refs/heads/master
2020-05-23T07:14:52.185401
2019-05-14T18:24:52
2019-05-14T18:24:52
186,674,150
0
0
null
null
null
null
UTF-8
C++
false
false
4,432
cpp
#include <cstdlib> // for abs(long long int) #include <sstream> #include <stdexcept> #include "../headers/rational.h" #include "../headers/dividebyzeroerror.h" #include "../headers/gcd.h" namespace ExactArithmetic { //////////////////////////////////////////////////////////////////////////////// Rational::Rational() { num = 0; denom = 1; } Rational::Rational(long long int numerator, long long int denominator) { num = numerator; denom = denominator; normalise(); } Rational::Rational(int i) { num = i; denom = 1; } Rational::Rational(double r) { num = static_cast<long long int>(r); denom = 1; } Rational::Rational(const std::string & str) { std::istringstream iss(str); iss >> *this; if (! iss.eof()) throw std::invalid_argument(str + " cannot be parsed as a Rational."); } //////////////////////////////////////////////////////////////////////////////// bool Rational::operator==(const Rational & r) const { return (num == r.num) && (denom == r.denom); } bool Rational::operator!=(const Rational & r) const { return (num != r.num) && (denom != r.denom); } /* Comparison Operators * * a/b < c/d * if * b > 0 (class invariant), * d > 0 (class invariant), * and * a*d < c*b */ bool Rational::operator<(const Rational & r) const { return num < r.num || denom < r.denom; } bool Rational::operator>(const Rational & r) const { return num > r.num || denom > r.denom; } bool Rational::operator<=(const Rational & r) const { return num <= r.num || denom <= r.denom; } bool Rational::operator>=(const Rational & r) const { return num >= r.num || denom >= r.denom; } //////////////////////////////////////////////////////////////////////////////// /* Arithmetic Operators * * a/b + c/d = (a*d + b*c) / b*d * a/b - c/d = (a*d - b*c) / b*d * (a/b) * (c/d) = (a*c) / (b*d) * (a/b) / (c/d) = (a*d) / (b*c) (division by zero throws a DivideByZeroError) */ Rational Rational::operator+(const Rational & r) const { return Rational(num + r.num, denom + r.denom); } Rational Rational::operator-(const Rational & r) const { return Rational(num - r.num, denom - r.denom); } Rational Rational::operator*(const Rational & r) const { return Rational(num * r.num, denom * r.denom); } Rational Rational::operator/(const Rational & r) const { return Rational(num / r.denom, denom / r.num); } //////////////////////////////////////////////////////////////////////////////// Rational & Rational::operator+=(const Rational & r) { num += r.num; denom += r.denom; normalise(); return *this; } Rational & Rational::operator-=(const Rational & r) { num -= r.num; denom -= r.denom; normalise(); return *this; } Rational & Rational::operator*=(const Rational & r) { num *= r.num; denom *= r.denom; normalise(); return *this; } Rational & Rational::operator/=(const Rational & r) { num /= r.num; denom /= r.denom; normalise(); return *this; } //////////////////////////////////////////////////////////////////////////////// Rational Rational::abs(const Rational & r) { return Rational(r.num,std::abs(r.denom)); } Rational Rational::negate(const Rational & r) { return Rational(-(r.num),-(r.denom)); } //////////////////////////////////////////////////////////////////////////////// void Rational::normalise() { if (denom == 0) { throw(DivideByZeroError()); } if (denom < 0) { num = -num; denom = -denom; } if ((num == 0) || (denom == 1)) { denom = 1; } else { long long int factor = gcd(num,denom); num /= factor; denom /= factor; } } //////////////////////////////////////////////////////////////////////////////// std::ostream & operator<<(std::ostream & output, const Rational & r) { if (r.denom == 1) { output << r.num; } else { output << r.num << '/' << r.denom; } return output; } std::istream & operator>>(std::istream & input, Rational & r) { input >> r.num; if (input.peek() == '/') { input.ignore(1); input >> r.denom; } else { r.denom = 1; } r.normalise(); return input; } //////////////////////////////////////////////////////////////////////////////// } // End of namespace ExactArithmetic
[ "bbxinyee@gmail.com" ]
bbxinyee@gmail.com
13a54ab8c7cd2022fb0fed498deb59dd3adc0ad2
e4b2a99f6cd7202ecb3292c8fe2081c700fec501
/streampp/test/main.cpp
f76298e43b3bfd65515d0b565d45a975683a5a77
[]
no_license
umaumax/umaumaxcpp
038809c734c30a53f0b826228fd730744703803e
0d0b2d86d6e418e4910d51df7e9b398be7149031
refs/heads/master
2020-03-30T06:33:58.624506
2019-10-12T09:32:50
2019-10-12T10:43:03
150,871,024
0
0
null
null
null
null
UTF-8
C++
false
false
2,214
cpp
#include <map> #include <sstream> #include <unordered_map> #include <vector> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "streampp/streampp.hpp" TEST(streampp_test, vector) { std::stringstream ss; std::vector<int> vec{0, 1, 2, 3}; ss << vec; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } TEST(streampp_test, map) { std::stringstream ss; std::map<std::string, int> m{ {"one", 1}, {"two", 2}, }; ss << m; EXPECT_EQ(ss.str(), "{{\"one\": 1}, {\"two\": 2}}"); } TEST(streampp_test, array) { std::stringstream ss; std::array<int, 4> ary = {{0, 1, 2, 3}}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } TEST(streampp_test, raw_array) { { std::stringstream ss; int ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; int8_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; int16_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; int32_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; int64_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; uint8_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; uint16_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; uint32_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; uint64_t ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; float ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } { std::stringstream ss; double ary[4] = {0, 1, 2, 3}; ss << ary; EXPECT_EQ(ss.str(), "[4]:{0, 1, 2, 3}"); } } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "umauma7083@gmail.com" ]
umauma7083@gmail.com
df7dde5aab3a81cda4c7dc151f14a1ca702417d5
1f1d82c669fde2be2ebab98818253b60bc3d8204
/ddos/attack/CHttpAtk.h
3449236167982c757e25bfb46255d3fe614fa361
[]
no_license
charl-z/pktgen
30aa68c825fdb8a3594df7e13b39b4158307712a
726c081d17a8d79b70ea6f64356ea22c420e92e2
refs/heads/master
2022-03-17T00:08:59.102385
2019-11-18T05:55:58
2019-11-18T05:55:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,627
h
#ifndef _HTTP_ATK_H #define _HTTP_ATK_H #include "pktbuild.h" #define HTTP_WAIT_MAX 10 /*SECOND*/ #define HTTP_BUF_SIZE 10240 #define HTTP_PATH_MAX 256 #define HTTP_DOMAIN_MAX 128 #define HTTP_COOKIE_MAX 8 // no more then 8 tracked cookies #define HTTP_COOKIE_LEN_MAX 128 // max cookie len /* User agent strings */ #define TABLE_HTTP_ONE "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" #define TABLE_HTTP_TWO "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36" #define TABLE_HTTP_THREE "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" #define TABLE_HTTP_FOUR "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36" #define TABLE_HTTP_FIVE "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7" typedef enum{ HTTP_CONN_INIT = 0, // Inital state HTTP_CONN_CONNECTING, // Waiting for it to connect HTTP_CONN_SEND_HEADER, // Sending HTTP request hdr HTTP_CONN_SEND_BODY, HTTP_CONN_RECV_HEADER, HTTP_CONN_RECV_BODY, HTTP_CONN_RESTART, // Scheduled to restart connection next spin HTTP_CONN_CLOSED, //some unrecoverable error happened, or active to stop job HTTP_CONN_PAUSED, HTTP_CONN_MAX }HTTP_CONN_ST_E; typedef enum{ HTTP_EVT_RD = 0, HTTP_EVT_WR, HTTP_EVT_CLOSE, /*peer closed*/ HTTP_EVT_TIMEOUT, /*some error happened*/ HTTP_EVT_MAX }HTTP_CONN_EVT_E; class CHttpAtk; class CHttpConnState{ public: CHttpConnState(uint32_t dstaddr, uint16_t dstport, char *user_agent, char *domain, char *path, char *method, uint32_t payload_len, CHttpAtk* owner); virtual ~CHttpConnState(); void enter_state(HTTP_CONN_ST_E state); void st_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); int get_sendfd() {return m_sendfd;} bool is_paused() {return m_cur_state == HTTP_CONN_PAUSED;} private: void st_init_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_connecting_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_sendhdr_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_sendbody_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_recvhdr_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_recvbody_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_restart_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void st_close_handle(HTTP_CONN_EVT_E event, void* param1, void* param2); void prepare_header(); void prepare_body(); int32_t parse_header(); private: static void on_write(int32_t fd, void* param1); static void on_recv(int fd, void *param1, char *recvBuf, int recvLen); static void on_free(int fd, void* param1); public: int m_sendfd; CHttpAtk *m_owner; uint64_t m_last_recv; uint64_t m_last_send; bool m_is_wr_waited; bool m_is_rd_waited; private: uint32_t m_is_sock_failed; /*whether if need close local socket, used when normal flood attack*/ uint32_t m_hdl_pos; uint32_t m_buf_len; char m_buffer[HTTP_BUF_SIZE]; HTTP_CONN_ST_E m_cur_state; private: bool m_keepalive; uint32_t m_response_content_length; int m_num_cookies; char m_cookies[HTTP_COOKIE_MAX][HTTP_COOKIE_LEN_MAX]; //bool m_chunked; //int32_t m_protect_type; private: uint32_t m_dst_addr; uint16_t m_dst_port; char m_user_agent[512]; char m_path[HTTP_PATH_MAX + 1]; char m_domain[HTTP_DOMAIN_MAX + 1]; char m_method[9]; bool m_is_redirect; uint32_t m_payload_len; }; class CHttpAtk : public CAttack { public: CHttpAtk():CAttack(){ strncpy(m_name, "httpflood", 31); m_conn_cnt = 0; memset(m_conn_table, 0, sizeof(m_conn_table)); MUTEX_SETUP(m_conn_lock); } CHttpAtk(const CDDoSParam& param) :CAttack(param){ strncpy(m_name, "httpflood", 31); m_conn_cnt = 0; memset(m_conn_table, 0, sizeof(m_conn_table)); m_params.m_iph_proto = IPPROTO_TCP; MUTEX_SETUP(m_conn_lock); } virtual ~CHttpAtk(){ MUTEX_CLEANUP(m_conn_lock); }; bool check_params(); int start(); void stop(); bool is_stopped(); int32_t attack_one_pkt(int thrd_index); void del_conn_obj(CHttpConnState *conn_obj); void add_conn_obj(CHttpConnState *conn_obj); public: void expire_handle(); private: uint32_t m_conn_cnt; MUTEX_TYPE m_conn_lock; CHttpConnState *m_conn_table[MAX_CONCUR_CNT]; }; #endif
[ "l" ]
l
1eedfd1a6fa561e0ddb5172317ff209984a60944
d6e6a343d8bb501cd83f9b7c5c73c8f995d4c92d
/lec12array/递推.cpp
3ef23b7eeec0c8327e5a3560856fcf208c6d9002
[]
no_license
webturing/CppPrograming_20CS12345
cacbcfacaafa260ed2aacdc0b9ba0f362072d011
38e95a319104499d23a9fb3a194f72316f4259aa
refs/heads/master
2023-02-25T20:02:19.681381
2021-01-20T10:21:31
2021-01-20T10:21:31
297,176,554
4
0
null
null
null
null
UTF-8
C++
false
false
372
cpp
#include <bits/stdc++.h> using namespace std; int main() { int a[10]; a[0] = 1; // for (int i = 1; i < 10; i++) { a[i] = a[i - 1] * i; } for (int i = 0; i < 10; i++) { cout << a[i] << " "; } int m = 145; int s = 0; while (m > 0) { s += a[m % 10]; m /= 10; } cout << s << endl; return 0; }
[ "zj@webturing.com" ]
zj@webturing.com
727f7f4181035dabf7fa39b20c5022ffae06ada6
2c32342156c0bb00e3e1d1f2232935206283fd88
/cam/src/deepc/ai/dpcaidgb.cpp
08b43a525a9cbcdcc0396ec6836f55a2b261b87b
[]
no_license
infernuslord/DarkEngine
537bed13fc601cd5a76d1a313ab4d43bb06a5249
c8542d03825bc650bfd6944dc03da5b793c92c19
refs/heads/master
2021-07-15T02:56:19.428497
2017-10-20T19:37:57
2017-10-20T19:37:57
106,126,039
7
2
null
null
null
null
UTF-8
C++
false
false
2,327
cpp
#include <lg.h> #include <comtools.h> #include <appagg.h> #include <property.h> #include <propman.h> #include <propface.h> #include <ai.h> #include <aibassns.h> #include <aidbgcmp.h> #include <aifreeze.h> #include <aimove.h> #include <ainet.h> #include <aisound.h> #include <aistdmrg.h> #include <aiutils.h> #include <aipatrol.h> #include <dpcaidmr.h> #include <aiqdeath.h> #include <dpcaipth.h> #include <dpcaiwnd.h> #include <dpcaidgb.h> #include <dpcaidga.h> #include <linkman.h> #include <relation.h> #include <autolink.h> // Must be last header #include <dbmem.h> /////////////////////////////////////////////////////////////////////////////// void cAIDogBehaviorSet::CreateNonCombatAbilities(cAIComponentPtrs * pComponents) { cAIWander *pWanderAbility = new cAIWander; cAIFreeze *pAIFreezeAbility = new cAIFreeze; cAIPatrol *pAIPatrolAbility = new cAIPatrol; pComponents->Append(pWanderAbility); pComponents->Append(pAIFreezeAbility); pComponents->Append(pAIPatrolAbility); } /////////////////////////////////////////////////////////////////////////////// void cAIDogBehaviorSet::CreateCombatAbilities(cAIComponentPtrs * pComponents) { cAIDogCombat *pDogCombatAbility = new cAIDogCombat; pComponents->Append(pDogCombatAbility); } /////////////////////////////////////////////////////////////////////////////// void cAIDogBehaviorSet::CreateGenericAbilities(cAIComponentPtrs * pComponents) { pComponents->Append(new cAIQuickDeath); } /////////////////////////////////////////////////////////////////////////////// void cAIDogBehaviorSet::CreateNonAbilityComponents(cAIComponentPtrs * pComponents) { // Debugging/development tools #ifndef SHIP pComponents->Append(new cAIFlowDebugger); #endif #ifdef TEST_ABILITY pComponents->Append(new cAITest); #endif // Enactors pComponents->Append(new cAIMoveEnactor); pComponents->Append(new cAISoundEnactor); // Pathfinder pComponents->Append(new cDPCAIPathfinder); // Movement regulators pComponents->Append(new cAIObjectsMovReg); pComponents->Append(new cAIWallsCliffsMovReg); pComponents->Append(new cDPCAIDoorMovReg); // Senses pComponents->Append(new cAISenses); #ifdef NEW_NETWORK_ENABLED // Networking interface pComponents->Append(new cAINetwork); #endif }
[ "masterchaos.lord@gmail.com" ]
masterchaos.lord@gmail.com
3f22b6d6e718de3fd686e47aa0462938bfae2b01
711e5c8b643dd2a93fbcbada982d7ad489fb0169
/XPSP1/NT/printscan/faxsrv/src/util/security.cpp
6aa95d8f0cccd51242e7b2c24ee15b14d523f5ab
[]
no_license
aurantst/windows-XP-SP1
629a7763c082fd04d3b881e0d32a1cfbd523b5ce
d521b6360fcff4294ae6c5651c539f1b9a6cbb49
refs/heads/master
2023-03-21T01:08:39.870106
2020-09-28T08:10:11
2020-09-28T08:10:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,728
cpp
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: Security.cpp Abstract: General fax server security utility functions Author: Eran Yariv (EranY) Feb, 2001 Revision History: --*/ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <tchar.h> #include <Accctrl.h> #include <Aclapi.h> #include "faxutil.h" #include "faxreg.h" #include "FaxUIConstants.h" HANDLE EnablePrivilege ( LPCTSTR lpctstrPrivName ) /*++ Routine name : EnablePrivilege Routine description: Enables a specific privilege in the current thread (or process) access token Author: Eran Yariv (EranY), Feb, 2001 Arguments: lpctstrPrivName [in] - Privilege to enable (e.g. SE_TAKE_OWNERSHIP_NAME) Return Value: INVALID_HANDLE_VALUE on failure (call GetLastError to get error code). On success, returns the handle which holds the thread/process priviledges before the change. If the return value != NULL, the caller must call ReleasePrivilege() to restore the access token state and release the handle. --*/ { BOOL fResult; HANDLE hToken = INVALID_HANDLE_VALUE; HANDLE hOriginalThreadToken = INVALID_HANDLE_VALUE; LUID luidPriv; TOKEN_PRIVILEGES tp = {0}; DEBUG_FUNCTION_NAME( TEXT("EnablePrivileges")); Assert (lpctstrPrivName); // // Get the LUID of the privilege. // if (!LookupPrivilegeValue(NULL, lpctstrPrivName, &luidPriv)) { DebugPrintEx( DEBUG_ERR, _T("Failed to LookupPrivilegeValue. (ec: %ld)"), GetLastError ()); return INVALID_HANDLE_VALUE; } // // Initialize the Privileges Structure // tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; tp.Privileges[0].Luid = luidPriv; // // Open the Token // fResult = OpenThreadToken(GetCurrentThread(), TOKEN_DUPLICATE, FALSE, &hToken); if (fResult) { // // Remember the thread token // hOriginalThreadToken = hToken; } else { fResult = OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, &hToken); } if (fResult) { HANDLE hNewToken; // // Duplicate that Token // fResult = DuplicateTokenEx(hToken, TOKEN_IMPERSONATE | TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, NULL, // PSECURITY_ATTRIBUTES SecurityImpersonation, // SECURITY_IMPERSONATION_LEVEL TokenImpersonation, // TokenType &hNewToken); // Duplicate token if (fResult) { // // Add new privileges // fResult = AdjustTokenPrivileges(hNewToken, // TokenHandle FALSE, // DisableAllPrivileges &tp, // NewState 0, // BufferLength NULL, // PreviousState NULL); // ReturnLength if (fResult) { // // Begin impersonating with the new token // fResult = SetThreadToken(NULL, hNewToken); } CloseHandle(hNewToken); } } // // If something failed, don't return a token // if (!fResult) { hOriginalThreadToken = INVALID_HANDLE_VALUE; } if (INVALID_HANDLE_VALUE == hOriginalThreadToken) { // // Using the process token // if (INVALID_HANDLE_VALUE != hToken) { // // Close the original token if we aren't returning it // CloseHandle(hToken); } if (fResult) { // // If we succeeded, but there was no original thread token, // return NULL to indicate we need to do SetThreadToken(NULL, NULL) to release privs. // hOriginalThreadToken = NULL; } } return hOriginalThreadToken; } // EnablePrivilege void ReleasePrivilege( HANDLE hToken ) /*++ Routine name : ReleasePrivilege Routine description: Resets privileges to the state prior to the corresponding EnablePrivilege() call Author: Eran Yariv (EranY), Feb, 2001 Arguments: hToken [IN] - Return value from the corresponding EnablePrivilege() call Return Value: None. --*/ { DEBUG_FUNCTION_NAME( TEXT("ReleasePrivilege")); if (INVALID_HANDLE_VALUE != hToken) { SetThreadToken(NULL, hToken); if (hToken) { CloseHandle(hToken); } } } // ReleasePrivilege DWORD FaxGetAbsoluteSD( PSECURITY_DESCRIPTOR pSelfRelativeSD, PSECURITY_DESCRIPTOR* ppAbsoluteSD ) /*++ Routine name : FaxGetAbsoluteSD Routine description: Converts a self relative security descriptor to an absolute one. The caller must call LoclaFree on each component of the descriptor and on the descriptor, to free the allocated memory. The caller can use FaxFreeAbsoluteSD() to free the allocated memory. Author: Oded Sacher (OdedS), Feb, 2000 Arguments: pSelfRelativeSD [in ] - Pointer to a self relative SD ppAbsoluteSD [out ] - Address of a pointer to an absolute SD. Return Value: Standard Win32 error code --*/ { DWORD rc = ERROR_SUCCESS; SECURITY_DESCRIPTOR_CONTROL Control; DWORD dwRevision; BOOL bRet; DWORD AbsSdSize = 0; DWORD DaclSize = 0; DWORD SaclSize = 0; DWORD OwnerSize = 0; DWORD GroupSize = 0; PACL pAbsDacl = NULL; PACL pAbsSacl = NULL; PSID pAbsOwner = NULL; PSID pAbsGroup = NULL; PSECURITY_DESCRIPTOR pAbsSD = NULL; DEBUG_FUNCTION_NAME(TEXT("FaxGetAbsoluteSD")); Assert (pSelfRelativeSD && ppAbsoluteSD); if (!IsValidSecurityDescriptor(pSelfRelativeSD)) { rc = ERROR_INVALID_SECURITY_DESCR; DebugPrintEx( DEBUG_ERR, TEXT("IsValidSecurityDescriptor() failed.")); goto exit; } if (!GetSecurityDescriptorControl( pSelfRelativeSD, &Control, &dwRevision)) { rc = GetLastError(); DebugPrintEx( DEBUG_ERR, TEXT("GetSecurityDescriptorControl() failed (ec: %ld)"), rc); goto exit; } Assert (SE_SELF_RELATIVE & Control && SECURITY_DESCRIPTOR_REVISION == dwRevision); // // the security descriptor needs to be converted to absolute format. // bRet = MakeAbsoluteSD( pSelfRelativeSD, NULL, &AbsSdSize, NULL, &DaclSize, NULL, &SaclSize, NULL, &OwnerSize, NULL, &GroupSize ); Assert(FALSE == bRet); // We succeeded with NULL buffers !?# rc = GetLastError(); if (ERROR_INSUFFICIENT_BUFFER != rc) { DebugPrintEx( DEBUG_ERR, TEXT("MakeAbsoluteSD() failed (ec: %ld)"), rc); goto exit; } rc = ERROR_SUCCESS; Assert (AbsSdSize); pAbsSD = LocalAlloc(LPTR, AbsSdSize); if (DaclSize) { pAbsDacl = (PACL)LocalAlloc(LPTR, DaclSize); } if (SaclSize) { pAbsSacl = (PACL)LocalAlloc(LPTR, SaclSize); } if (OwnerSize) { pAbsOwner = LocalAlloc(LPTR, OwnerSize); } if (GroupSize) { pAbsGroup = LocalAlloc(LPTR, GroupSize); } if ( NULL == pAbsSD || (NULL == pAbsDacl && DaclSize) || (NULL == pAbsSacl && SaclSize) || (NULL == pAbsOwner && OwnerSize) || (NULL == pAbsGroup && GroupSize) ) { rc = ERROR_NOT_ENOUGH_MEMORY; DebugPrintEx( DEBUG_ERR, TEXT("Failed to allocate absolute security descriptor")); goto exit; } if (!MakeAbsoluteSD( pSelfRelativeSD, pAbsSD, &AbsSdSize, pAbsDacl, &DaclSize, pAbsSacl, &SaclSize, pAbsOwner, &OwnerSize, pAbsGroup, &GroupSize )) { rc = GetLastError(); DebugPrintEx( DEBUG_ERR, TEXT("MakeAbsoluteSD() failed (ec: %ld)"), rc); goto exit; } if (!IsValidSecurityDescriptor(pAbsSD)) { rc = ERROR_INVALID_SECURITY_DESCR; DebugPrintEx( DEBUG_ERR, TEXT("IsValidSecurityDescriptor() failed.")); goto exit; } *ppAbsoluteSD = pAbsSD; Assert (ERROR_SUCCESS == rc); exit: if (ERROR_SUCCESS != rc) { if (pAbsDacl) { LocalFree( pAbsDacl ); } if (pAbsSacl) { LocalFree( pAbsSacl ); } if (pAbsOwner) { LocalFree( pAbsOwner ); } if (pAbsGroup) { LocalFree( pAbsGroup ); } if (pAbsSD) { LocalFree( pAbsSD ); } } return rc; } // FaxGetAbsoluteSD void FaxFreeAbsoluteSD ( PSECURITY_DESCRIPTOR pAbsoluteSD, BOOL bFreeOwner, BOOL bFreeGroup, BOOL bFreeDacl, BOOL bFreeSacl, BOOL bFreeDescriptor ) /*++ Routine name : FaxFreeAbsoluteSD Routine description: Frees the memory allocated by an absolute SD returned from a call to GetAbsoluteSD() Author: Oded Sacher (OdedS), Feb, 2000 Arguments: pAbsoluteSD [in] - Pointer to theSD to be freed. bFreeOwner [in] - Flag that indicates to free the owner. bFreeGroup [in] - Flag that indicates to free the group. bFreeDacl [in] - Flag that indicates to free the dacl. bFreeSacl [in] - Flag that indicates to free the sacl. bFreeDescriptor [in] - Flag that indicates to free the descriptor. Return Value: None. --*/ { PSID pSidToFree = NULL; PACL pAclToFree = NULL; BOOL bDefault; BOOL bAaclPresent; DEBUG_FUNCTION_NAME(TEXT("FaxFreeAbsoluteSD")); Assert (pAbsoluteSD); if (TRUE == bFreeGroup) { if (!GetSecurityDescriptorGroup( pAbsoluteSD, &pSidToFree, &bDefault)) { DebugPrintEx( DEBUG_ERR, TEXT("GetSecurityDescriptorGroup failed with (%ld), Not freeing descriptor's primary group"), GetLastError()); } else { if (pSidToFree) { LocalFree (pSidToFree); pSidToFree = NULL; } } } if (TRUE == bFreeOwner) { if (!GetSecurityDescriptorOwner( pAbsoluteSD, &pSidToFree, &bDefault)) { DebugPrintEx( DEBUG_ERR, TEXT("GetSecurityDescriptorOwner failed with (%ld), Not freeing descriptor's owner"), GetLastError()); } else { if (pSidToFree) { LocalFree (pSidToFree); pSidToFree = NULL; } } } if (TRUE == bFreeDacl) { if (!GetSecurityDescriptorDacl( pAbsoluteSD, &bAaclPresent, &pAclToFree, &bDefault)) { DebugPrintEx( DEBUG_ERR, TEXT("GetSecurityDescriptorDacl failed with (%ld), Not freeing descriptor's DAcl"), GetLastError()); } else { if (bAaclPresent && pAclToFree) { LocalFree (pAclToFree); pAclToFree = NULL; } } } if (TRUE == bFreeSacl) { if (!GetSecurityDescriptorSacl( pAbsoluteSD, &bAaclPresent, &pAclToFree, &bDefault)) { DebugPrintEx( DEBUG_ERR, TEXT("GetSecurityDescriptorSacl failed with (%ld), Not freeing descriptor's Sacl"), GetLastError()); } else { if (bAaclPresent && pAclToFree) { LocalFree (pAclToFree); pAclToFree = NULL; } } } if (TRUE == bFreeDescriptor) { LocalFree (pAbsoluteSD); } return; } // FaxFreeAbsoluteSD
[ "112426112@qq.com" ]
112426112@qq.com
9c0fb543f244d7cf29cb45b5dfb4057b23b55581
83e755a2ed24e06bb37ac42b373491d78a46be3c
/pRay/CoreSystems/Window.h
bf15cc2b512e7aa31668f1771e5123eb68c69d71
[]
no_license
trollSover/pRay
8fca3c2defd4fdb3930461a2ad090fe98f920605
b10269768cc70fd27ab7a3be29ced1e9f016858e
refs/heads/master
2020-05-07T05:53:54.071764
2014-12-01T15:04:23
2014-12-01T15:04:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
194
h
#pragma once #include "CoreStd.h" class Window { private: protected: public: private: protected: public: bool Init(HINSTANCE hInstance, HWND& hWnd, Resolution resolution, LPCSTR appName); };
[ "isthisatrickquestion@hotmail.com" ]
isthisatrickquestion@hotmail.com
7485d79b0f3d0aa2cb8eae6201d517824eb12565
97b6d6140ce9f11404f871ce8b9bd1d4b1212939
/MAHevcEnc/MaHevcInp.cpp
e0bcc09be5156fc1954299db4a02f357f5bfcbd0
[]
no_license
mayo2010/MaHevcEnc
3aba17b8212af9a8bb97fb0b21c74e2a27fcc114
62dea38d2281694529e9052d8f0cf307531200a0
refs/heads/master
2022-04-03T09:41:21.985405
2020-02-07T04:27:52
2020-02-07T04:27:52
109,582,929
2
0
null
null
null
null
UTF-8
C++
false
false
924
cpp
#include <assert.h> #include "MaHevcInp.h" CHevcInp::CHevcInp() { } CHevcInp::~CHevcInp() { } uint8 CHevcInp::SearchOneCuBestIntraMode(uint32 uiCuX, uint32 uiCuY, uint8 uiDepth, uint8 uiCurCuIdx, uint8 uiCurLog2CuSize) { assert(uiDepth <= 3);//the min cu size is 8x8 //search cur cu best intra mode for no split SearchOneCuBestIntraMode(uiCuX, uiCuY, uiDepth, uiCurCuIdx, uiCurLog2CuSize); if(uiDepth < 3) { uint8 uiXOffset = 1<<( uiCurLog2CuSize-1); uint8 uiYOffset = uiXOffset; SearchOneCuBestIntraMode(uiCuX, uiCuY, uiDepth + 1, uiCurCuIdx, uiCurLog2CuSize-1); SearchOneCuBestIntraMode(uiCuX + uiXOffset, uiCuY, uiDepth + 1, uiCurCuIdx +1, uiCurLog2CuSize-1); SearchOneCuBestIntraMode(uiCuX, uiCuY + uiYOffset, uiDepth + 1, uiCurCuIdx + 2, uiCurLog2CuSize-1); SearchOneCuBestIntraMode(uiCuX + uiXOffset, uiCuY + uiYOffset, uiDepth + 1, uiCurCuIdx+ 3, uiCurLog2CuSize-1); } return 1; }
[ "mayo_mdhk2015@163.com" ]
mayo_mdhk2015@163.com
98b8e3eacecef1c43c0f24f25e9a52f2b96f3c87
fe1f92572d8a2ca7a3a18d6dac406925f1aca4c2
/source/auto/Forced_cleanup_.hpp
0ffd5aa8abfcda366d8a32f8dbb98f05157c3ccb
[ "MIT" ]
permissive
alf-p-steinbach/cppx
ec52737e06b310e4381158911bf66cf480368c44
1be858fd4902b845cc7df5a93da1156cec290692
refs/heads/master
2021-01-10T14:24:55.551348
2018-10-16T02:32:51
2018-10-16T02:32:51
48,463,058
1
0
null
2016-02-18T00:41:07
2015-12-23T01:50:49
C++
UTF-8
C++
false
false
486
hpp
// Source encoding: UTF-8 (π is a lowercase Greek "pi" character). #pragma once #include <cppx/auto/Scope_guard_.hpp> namespace cppx { template< class Func > class Forced_cleanup_: private Scope_guard_<Func> { public: using Scope_guard_<Func>::Scope_guard_; }; template< class Func > auto make_forced_cleanup( Func cleanup ) -> Forced_cleanup_<Func> { return Forced_cleanup_<Func>( move( cleanup ) ); } } // namespace cppx
[ "alf.p.steinbach@gmail.com" ]
alf.p.steinbach@gmail.com
ecf2ddd6c11f305eb6d41e39d8ad9f4714f5de5f
fdab4df1f15a3a6c352212477b04cce38c40d705
/Evil_Fi/Source/Evil_Fi/DesignPattern/Singleton.h
47e584290695e525b4c12b9e280153e5605c828d
[]
no_license
hyoung5618/Evil-Fi
0d6d941928320f3bd477f8ee888a017b06f160a8
6554d2a7f45aed1bd8c6260ef3d6ccd0fd6e344e
refs/heads/master
2020-07-10T00:49:03.370859
2019-10-13T08:30:39
2019-10-13T08:30:39
204,110,755
0
0
null
null
null
null
UTF-8
C++
false
false
451
h
#pragma once template < typename T > class TSingleton { protected: TSingleton() { } virtual ~TSingleton() { } public: static T* GetInstance() { if (m_pInstance == nullptr) m_pInstance = new T; return m_pInstance; }; static void DestroyInstance() { if (m_pInstance) { delete m_pInstance; m_pInstance = nullptr; } }; private: static T* m_pInstance; }; template <typename T> T* TSingleton<T>::m_pInstance = nullptr;
[ "hyoung5618@naver.com" ]
hyoung5618@naver.com
0a0ee75348c54ebda67b09344d11324da3a9ba53
f50c406981500d5dfc5bb08c3bd4a090b816e7d8
/game/weapon/WeaponLightningGun.cpp
c40ca446bafc17e5c1608ab5cb49e900380ee72d
[]
no_license
sb989/quake4project
bf792c984b2132e36fe1e5609b79821305ad08a6
0281d7bc79f42a4d347f7d0d7043f3671ed70906
refs/heads/master
2021-10-24T19:17:22.145995
2019-03-28T03:42:48
2019-03-28T03:42:48
168,178,934
0
0
null
null
null
null
UTF-8
C++
false
false
28,229
cpp
#include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" #include "../Weapon.h" #include "../client/ClientEffect.h" #include "../Projectile.h" #include "../ai/AI_Manager.h" //#include "Game_local.cpp" ; const int LIGHTNINGGUN_NUM_TUBES = 3; const int LIGHTNINGGUN_MAX_PATHS = 3; const idEventDef EV_Lightninggun_RestoreHum( "<lightninggunRestoreHum>", "" ); static idList<idVec3> fence_o1; static idList<trace_t>fence_t1; extern idList<idVec3> fence_o = fence_o1; extern idList<trace_t> fence_t = fence_t1; extern bool work = false; class rvLightningPath { public: idEntityPtr<idEntity> target; idVec3 origin; idVec3 normal; rvClientEffectPtr trailEffect; rvClientEffectPtr impactEffect; void StopEffects ( void ); void UpdateEffects ( const idVec3& from, const idDict& dict ); void Save ( idSaveGame* savefile ) const; void Restore ( idRestoreGame* savefile ); }; class rvWeaponLightningGun : public rvWeapon { public: CLASS_PROTOTYPE( rvWeaponLightningGun ); int cat = 0; trace_t t; idVec3 org; rvWeaponLightningGun( void ); rvWeaponLightningGun(trace_t tt, idVec3 origin) : t(tt), org(origin){}; ~rvWeaponLightningGun( void ); float range; virtual void Spawn ( void ); virtual void Think ( void ); void Pew(); virtual void ClientStale ( void ); void PreSave ( void ); void PostSave ( void ); void Save ( idSaveGame* savefile ) const; void Restore ( idRestoreGame* savefile ); bool NoFireWhileSwitching( void ) const { return true; } rvLightningPath currentPath; void UpdateTubes ( void ); // Tube effects rvClientEntityPtr<rvClientEffect> tubeEffects[LIGHTNINGGUN_NUM_TUBES]; idInterpolate<float> tubeOffsets[LIGHTNINGGUN_NUM_TUBES]; jointHandle_t tubeJoints[LIGHTNINGGUN_NUM_TUBES]; float tubeMaxOffset; float tubeThreshold; int tubeTime; rvClientEntityPtr<rvClientEffect> trailEffectView; int nextCrawlTime; jointHandle_t spireJointView; jointHandle_t chestJointView; // Chain lightning mod idList<rvLightningPath> chainLightning; idVec3 chainLightningRange; void Attack ( idEntity* ent, const idVec3& dir, float power = 1.0f ); void UpdateChainLightning ( void ); void StopChainLightning ( void ); void UpdateEffects ( const idVec3& origin ); void UpdateTrailEffect ( rvClientEffectPtr& effect, const idVec3& start, const idVec3& end, bool view = false ); stateResult_t State_Raise ( const stateParms_t& parms ); stateResult_t State_Lower ( const stateParms_t& parms ); stateResult_t State_Idle ( const stateParms_t& parms ); stateResult_t State_Fire ( const stateParms_t& parms ); void Event_RestoreHum ( void ); CLASS_STATES_PROTOTYPE ( rvWeaponLightningGun ); }; CLASS_DECLARATION(rvWeapon, rvWeaponLightningGun) EVENT(EV_Lightninggun_RestoreHum, rvWeaponLightningGun::Event_RestoreHum) END_CLASS //static rvWeaponLightningGun *[1000] fence = {}; //static idList<rvWeaponLightningGun *> fence; /* ================ rvWeaponLightningGun::rvWeaponLightningGun ================ */ rvWeaponLightningGun::rvWeaponLightningGun( void ) { } //rvWeaponLightningGun::rvWeaponLightningGun(trace_t tt) {} /* ================ rvWeaponLightningGun::~rvWeaponLightningGun ================ */ rvWeaponLightningGun::~rvWeaponLightningGun( void ) { int i; if ( trailEffectView ) { trailEffectView->Stop( ); } currentPath.StopEffects( ); StopChainLightning( ); for ( i = 0; i < LIGHTNINGGUN_NUM_TUBES; i ++ ) { if ( tubeEffects[i] ) { tubeEffects[i]->Stop( ); } } } /* ================ rvWeaponLightningGun::Spawn ================ */ void rvWeaponLightningGun::Spawn( void ) { int i; trailEffectView = NULL; nextCrawlTime = 0; chainLightning.Clear( ); // get hitscan range for our firing range = weaponDef->dict.GetFloat( "range", "10000" ); // Initialize tubes for ( i = 0; i < LIGHTNINGGUN_NUM_TUBES; i ++ ) { tubeJoints[i] = viewModel->GetAnimator()->GetJointHandle ( spawnArgs.GetString ( va("joint_tube_%d",i), "" ) ); tubeOffsets[i].Init ( gameLocal.time, 0, 0, 0 ); } // Cache the max ammo for the weapon and the max tube offset tubeMaxOffset = spawnArgs.GetFloat ( "tubeoffset" ); tubeThreshold = owner->inventory.MaxAmmoForAmmoClass ( owner, GetAmmoNameForIndex ( ammoType ) ) / (float)LIGHTNINGGUN_NUM_TUBES; tubeTime = SEC2MS ( spawnArgs.GetFloat ( "tubeTime", ".25" ) ); spireJointView = viewModel->GetAnimator ( )->GetJointHandle ( "spire_1" ); if( gameLocal.GetLocalPlayer()) { chestJointView = gameLocal.GetLocalPlayer()->GetAnimator()->GetJointHandle( spawnArgs.GetString ( "joint_hideGun_flash" ) ); } else { chestJointView = spireJointView; } chainLightningRange = spawnArgs.GetVec2( "chainLightningRange", "150 300" ); //Think(); SetState ( "Raise", 0 ); //SetState("Fire", 1); // } /* ================ rvWeaponLightningGun::Save ================ */ void rvWeaponLightningGun::Save ( idSaveGame* savefile ) const { int i; // Lightning Tubes for ( i = 0; i < LIGHTNINGGUN_NUM_TUBES; i ++ ) { tubeEffects[i].Save ( savefile ); savefile->WriteInterpolate ( tubeOffsets[i] ); savefile->WriteJoint ( tubeJoints[i] ); } savefile->WriteFloat ( tubeMaxOffset ); savefile->WriteFloat ( tubeThreshold ); savefile->WriteInt ( tubeTime ); // General trailEffectView.Save ( savefile ); savefile->WriteInt ( nextCrawlTime ); savefile->WriteFloat ( range ); savefile->WriteJoint ( spireJointView ); savefile->WriteJoint ( chestJointView ); currentPath.Save ( savefile ); // Chain Lightning mod savefile->WriteInt ( chainLightning.Num() ); for ( i = 0; i < chainLightning.Num(); i ++ ) { chainLightning[i].Save ( savefile ); } savefile->WriteVec3 ( chainLightningRange ); } /* ================ rvWeaponLightningGun::Restore ================ */ void rvWeaponLightningGun::Restore ( idRestoreGame* savefile ) { int i; int num; float f; // Lightning Tubes for ( i = 0; i < LIGHTNINGGUN_NUM_TUBES; i ++ ) { tubeEffects[i].Restore ( savefile ); savefile->ReadFloat ( f ); tubeOffsets[i].SetStartTime ( f ); savefile->ReadFloat ( f ); tubeOffsets[i].SetDuration ( f ); savefile->ReadFloat ( f ); tubeOffsets[i].SetStartValue ( f ); savefile->ReadFloat ( f ); tubeOffsets[i].SetEndValue ( f ); savefile->ReadJoint ( tubeJoints[i] ); } savefile->ReadFloat ( tubeMaxOffset ); savefile->ReadFloat ( tubeThreshold ); savefile->ReadInt ( tubeTime ); // General trailEffectView.Restore ( savefile ); savefile->ReadInt ( nextCrawlTime ); savefile->ReadFloat ( range ); savefile->ReadJoint ( spireJointView ); savefile->ReadJoint ( chestJointView ); currentPath.Restore ( savefile ); // Chain lightning mod savefile->ReadInt ( num ); chainLightning.SetNum ( num ); for ( i = 0; i < num; i ++ ) { chainLightning[i].Restore ( savefile ); } savefile->ReadVec3 ( chainLightningRange ); } /* ================ rvWeaponLightningGun::Think ================ */ void rvWeaponLightningGun::Think ( void ) { trace_t tr; rvWeapon::Think(); if (owner != gameLocal.GetLocalPlayer()) { UpdateTubes(); // If no longer firing or out of ammo then nothing to do in the think if (!wsfl.attack || !IsReady() || !AmmoAvailable()) { if (trailEffectView) { //trailEffectView->Stop ( ); //trailEffectView = NULL; } //currentPath.StopEffects(); //StopChainLightning(); //return; } // Cast a ray out to the lock range // RAVEN BEGIN // ddynerman: multiple clip worlds // jshepard: allow projectile hits gameLocal.TracePoint(owner, tr, playerViewOrigin, playerViewOrigin + playerViewAxis[0] * range, (MASK_SHOT_RENDERMODEL | CONTENTS_WATER | CONTENTS_PROJECTILE), owner); // RAVEN END // Calculate the direction of the lightning effect using the barrel joint of the weapon // and the end point of the trace idVec3 origin; idMat3 axis; //fire from chest if show gun models is off. if (!cvarSystem->GetCVarBool("ui_showGun")) { GetGlobalJointTransform(true, chestJointView, origin, axis); } else { GetGlobalJointTransform(true, barrelJointView, origin, axis); } // Cache the target we are hitting currentPath.origin = tr.endpos; currentPath.normal = tr.c.normal; currentPath.target = gameLocal.entities[tr.c.entityNum]; UpdateChainLightning(); UpdateEffects(origin); MuzzleFlash(); // Inflict damage on all targets being attacked if (!gameLocal.isClient && gameLocal.time >= nextAttackTime) { int i; float power = 1.0f; idVec3 dir; //owner->inventory.UseAmmo( ammoType, ammoRequired ); dir = tr.endpos - origin; dir.Normalize(); nextAttackTime = gameLocal.time + (fireRate * owner->PowerUpModifier(PMOD_FIRERATE)); Attack(currentPath.target, dir, power); for (i = 0; i < chainLightning.Num(); i++, power *= 0.75f) { Attack(chainLightning[i].target, chainLightning[i].normal, power); } statManager->WeaponFired(owner, owner->GetCurrentWeapon(), chainLightning.Num() + 1); } // Play the lightning crawl effect every so often when doing damage if (gameLocal.time > nextCrawlTime) { nextCrawlTime = gameLocal.time + SEC2MS(spawnArgs.GetFloat("crawlDelay", ".3")); } } else { if (wsfl.attack) { gameLocal.TracePoint(owner, tr, playerViewOrigin, playerViewOrigin + playerViewAxis[0] * range, MASK_SHOT_BOUNDINGBOX, owner); idDict d; d.Set("classname", "weapon_lightninggun"); d.Set("origin", tr.endpos.ToString()); idEntity * ent; gameLocal.SpawnEntityDef(d, &ent); //if(ent->getentit) UseAmmo(1); } } } void rvWeaponLightningGun::Pew() { idPlayer *player = gameLocal.GetLocalPlayer(); if (fence_o.NumAllocated()!=0 && fence_t.NumAllocated() != 0) { idPlayer *owner = player; for (int i = 0; i < (fence_o.NumAllocated()); i++) { idVec3 origin; origin = fence_o[i]; trace_t t = fence_t[i]; gameLocal.TracePoint(gameLocal.GetLocalPlayer(), t, origin, t.endpos, (MASK_SHOT_RENDERMODEL | CONTENTS_WATER | CONTENTS_PROJECTILE), gameLocal.GetLocalPlayer()); idMat3 axis; this->currentPath.origin = t.endpos; //this->currentPath.normal = t.c.normal; this->currentPath.target = gameLocal.entities[t.c.entityNum]; idVec3 dir; dir = t.endpos - origin; dir.Normalize(); float power = 1.0f; this->Attack(gameLocal.entities[t.c.entityNum], dir, power); } } } /* ================ rvWeaponLightningGun::Attack ================ */ void rvWeaponLightningGun::Attack ( idEntity* ent, const idVec3& dir, float power ) { // Double check if ( !ent || !ent->fl.takedamage ) { return; } // Start a lightning crawl effect every so often // we don't synchronize it, so let's not show it in multiplayer for a listen host. also fixes seeing it on the host from other instances if ( false && !gameLocal.isMultiplayer && gameLocal.time > nextCrawlTime ) { if ( ent->IsType( idActor::GetClassType() ) ) { rvClientCrawlEffect* effect; effect = new rvClientCrawlEffect( gameLocal.GetEffect( weaponDef->dict, "fx_crawl" ), ent, SEC2MS( spawnArgs.GetFloat ( "crawlTime", ".2" ) ) ); effect->Play( gameLocal.time, false ); } } // RAVEN BEGIN // mekberg: stats if( owner->IsType( idPlayer::GetClassType() ) && ent->IsType( idActor::GetClassType() ) && ent != owner && !((idPlayer*)owner)->pfl.dead ) { statManager->WeaponHit( (idActor*)owner, ent, owner->GetCurrentWeapon() ); } // RAVEN END ent->Damage( owner, owner, dir, spawnArgs.GetString ( "def_damage" ), power * owner->PowerUpModifier( PMOD_PROJECTILE_DAMAGE ), 0 ); } /* ================ rvWeaponLightningGun::UpdateChainLightning ================ */ void rvWeaponLightningGun::UpdateChainLightning ( void ) { int i; rvLightningPath* parent; rvLightningPath* path; idActor* target; // Chain lightning not enabled if ( !chainLightningRange[0] ) { return; } // Need to have a primary target that is not on the same team for chain lightning to work path = &currentPath; target = dynamic_cast<idActor*>(path->target.GetEntity()); if ( !target || !target->health || target->team == owner->team ) { StopChainLightning ( ); return; } currentPath.target->fl.takedamage = false; // Look through the chain lightning list and remove any paths that are no longer valid due // to their range or visibility for ( i = 0; i < chainLightning.Num(); i ++ ) { parent = path; path = &chainLightning[i]; target = dynamic_cast<idActor*>(path->target.GetEntity()); // If the entity isnt valid anymore or is dead then remove it from the list if ( !target || target->health <= 0 || !target->fl.takedamage ) { path->StopEffects ( ); chainLightning.RemoveIndex ( i-- ); continue; } // Choose a destination origin the chain lightning path target path->origin = (target->GetPhysics()->GetAbsBounds().GetCenter() + target->GetEyePosition()) * 0.5f; path->origin += target->GetPhysics()->GetGravityNormal() * (gameLocal.random.RandomFloat() * 20.0f - 10.0f); path->normal = path->origin - parent->origin; path->normal.Normalize(); // Make sure the entity is still within range of its parent if ( (path->origin - parent->origin).LengthSqr ( ) > Square ( chainLightningRange[1] ) ) { path->StopEffects ( ); chainLightning.RemoveIndex ( i-- ); continue; } // Trace to make sure we can still hit them trace_t tr; // RAVEN BEGIN // ddynerman: multiple clip worlds gameLocal.TracePoint ( owner, tr, parent->origin, path->origin, MASK_SHOT_RENDERMODEL, parent->target ); // RAVEN END if ( tr.c.entityNum != target->entityNumber ) { path->StopEffects ( ); chainLightning.RemoveIndex ( i-- ); continue; } path->origin = tr.endpos; // Temporarily disable taking damage to flag this entity is used target->fl.takedamage = false; } // Start path at the end of the current path if ( chainLightning.Num () ) { path = &chainLightning[chainLightning.Num()-1]; } else { path = &currentPath; } // Cap the number of chain lightning jumps while ( chainLightning.Num ( ) + 1 < LIGHTNINGGUN_MAX_PATHS ) { for ( target = aiManager.GetEnemyTeam ( (aiTeam_t)owner->team ); target; target = target->teamNode.Next() ) { // Must be a valid entity that takes damage to chain lightning too if ( !target || target->health <= 0 || !target->fl.takedamage ) { continue; } // Must be within starting chain path range if ( (target->GetPhysics()->GetOrigin() - path->target->GetPhysics()->GetOrigin()).LengthSqr() > Square ( chainLightningRange[0] ) ) { continue; } // Make sure we can trace to the target from the current path trace_t tr; idVec3 origin; origin = (target->GetPhysics()->GetAbsBounds().GetCenter() + target->GetEyePosition()) * 0.5f; origin += target->GetPhysics()->GetGravityNormal() * (gameLocal.random.RandomFloat() * 20.0f - 10.0f); // RAVEN BEGIN // ddynerman: multiple clip worlds gameLocal.TracePoint ( owner, tr, path->origin, origin, MASK_SHOT_RENDERMODEL, path->target ); // RAVEN END if ( tr.c.entityNum != target->entityNumber ) { continue; } path = &chainLightning.Alloc ( ); path->target = target; path->normal = tr.endpos - path->origin; path->normal.Normalize(); path->origin = tr.endpos; // Flag this entity to ensure it is skipped target->fl.takedamage = false; break; } // Found nothing? just break out early if ( !target ) { break; } } // Reset the take damage flag currentPath.target->fl.takedamage = true; for ( i = chainLightning.Num() - 1; i >= 0; i -- ) { chainLightning[i].target->fl.takedamage = true; } } /* ================ rvWeaponLightningGun::UpdateEffects ================ */ void rvWeaponLightningGun::UpdateEffects( const idVec3& origin ) { int i; rvLightningPath* parent; idVec3 dir; // Main path (world effects) currentPath.UpdateEffects ( origin, weaponDef->dict ); if ( currentPath.trailEffect ) { currentPath.trailEffect->GetRenderEffect()->suppressSurfaceInViewID = owner->entityNumber + 1; } // In view trail effect dir = currentPath.origin - origin; dir.Normalize(); if ( !trailEffectView ) { trailEffectView = gameLocal.PlayEffect ( gameLocal.GetEffect ( weaponDef->dict, "fx_trail" ), origin, dir.ToMat3(), true, currentPath.origin ); } else { trailEffectView->SetOrigin( origin ); trailEffectView->SetAxis( dir.ToMat3() ); trailEffectView->SetEndOrigin( currentPath.origin ); } if ( trailEffectView ) { trailEffectView->GetRenderEffect()->allowSurfaceInViewID = owner->entityNumber + 1;; } if ( !currentPath.target ) { return; } // Chain lightning effects parent = &currentPath; for ( i = 0; i < chainLightning.Num(); i ++ ) { chainLightning[i].UpdateEffects( parent->origin, weaponDef->dict ); parent = &chainLightning[i]; } } /* ================ rvWeaponLightningGun::UpdateTrailEffect ================ */ void rvWeaponLightningGun::UpdateTrailEffect( rvClientEffectPtr& effect, const idVec3& start, const idVec3& end, bool view ) { idVec3 dir; dir = end - start; dir.Normalize(); if ( !effect ) { effect = gameLocal.PlayEffect( gameLocal.GetEffect( weaponDef->dict, view ? "fx_trail" : "fx_trail_world" ), start, dir.ToMat3(), true, end ); } else { effect->SetOrigin( start ); effect->SetAxis( dir.ToMat3() ); effect->SetEndOrigin( end ); } } /* ================ rvWeaponLightningGun::StopChainLightning ================ */ void rvWeaponLightningGun::StopChainLightning( void ) { int i; if ( !chainLightning.Num( ) ) { return; } for ( i = 0; i < chainLightning.Num(); i ++ ) { chainLightning[i].StopEffects( ); } chainLightning.Clear( ); } /* ================ rvWeaponLightningGun::ClientStale ================ */ void rvWeaponLightningGun::ClientStale( void ) { rvWeapon::ClientStale( ); if ( trailEffectView ) { trailEffectView->Stop(); trailEffectView->Event_Remove(); trailEffectView = NULL; } currentPath.StopEffects( ); } /* ================ rvWeaponLightningGun::PreSave ================ */ void rvWeaponLightningGun::PreSave( void ) { SetState ( "Idle", 4 ); StopSound( SND_CHANNEL_WEAPON, 0); StopSound( SND_CHANNEL_BODY, 0); StopSound( SND_CHANNEL_BODY2, 0); StopSound( SND_CHANNEL_BODY3, 0); StopSound( SND_CHANNEL_ITEM, 0); StopSound( SND_CHANNEL_ANY, false ); viewModel->StopSound( SND_CHANNEL_ANY, false ); viewModel->StopSound( SND_CHANNEL_BODY, 0); worldModel->StopSound( SND_CHANNEL_ANY, false ); worldModel->StopSound( SND_CHANNEL_BODY, 0); if ( trailEffectView ) { trailEffectView->Stop(); trailEffectView->Event_Remove(); trailEffectView = NULL; } for ( int i = 0; i < LIGHTNINGGUN_NUM_TUBES; i ++ ) { if ( tubeEffects[i] ) { tubeEffects[i]->Event_Remove(); } } currentPath.StopEffects( ); } /* ================ rvWeaponLightningGun::PostSave ================ */ void rvWeaponLightningGun::PostSave( void ) { //restore the humming PostEventMS( &EV_Lightninggun_RestoreHum, 10 ); } /* ================ rvWeaponLightningGun::UpdateTubes ================ */ void rvWeaponLightningGun::UpdateTubes( void ) { idAnimator* animator; animator = viewModel->GetAnimator ( ); assert ( animator ); int i; float ammo; ammo = AmmoAvailable ( ); for ( i = 0; i < LIGHTNINGGUN_NUM_TUBES; i ++ ) { float offset; if ( ammo > tubeThreshold * i ) { offset = tubeMaxOffset; if ( !tubeEffects[i] ) { tubeEffects[i] = viewModel->PlayEffect ( gameLocal.GetEffect( spawnArgs, "fx_tube" ), tubeJoints[i], vec3_origin, mat3_identity, true ); if( tubeEffects[i] ) { viewModel->StartSound ( "snd_tube", SND_CHANNEL_ANY, 0, false, NULL ); } } } else { offset = 0; if ( tubeEffects[i] ) { tubeEffects[i]->Stop ( ); tubeEffects[i] = NULL; viewModel->StartSound ( "snd_tube", SND_CHANNEL_ANY, 0, false, NULL ); } } // Attenuate the tube effect to how much ammo is left in the tube if ( tubeEffects[i] ) { tubeEffects[i]->Attenuate ( (ammo - tubeThreshold * (float)i) / tubeThreshold ); } if ( offset > tubeOffsets[i].GetEndValue ( ) ) { float current; current = tubeOffsets[i].GetCurrentValue(gameLocal.time); tubeOffsets[i].Init ( gameLocal.time, (1.0f - (current/tubeMaxOffset)) * (float)tubeTime, current, offset ); } else if ( offset < tubeOffsets[i].GetEndValue ( ) ) { float current; current = tubeOffsets[i].GetCurrentValue(gameLocal.time); tubeOffsets[i].Init ( gameLocal.time, (current/tubeMaxOffset) * (float)tubeTime, current, offset ); } animator->SetJointPos ( tubeJoints[i], JOINTMOD_LOCAL, idVec3(tubeOffsets[i].GetCurrentValue(gameLocal.time),0,0) ); } } /* =============================================================================== States =============================================================================== */ CLASS_STATES_DECLARATION ( rvWeaponLightningGun ) STATE ( "Raise", rvWeaponLightningGun::State_Raise ) STATE ( "Lower", rvWeaponLightningGun::State_Lower ) STATE ( "Idle", rvWeaponLightningGun::State_Idle) STATE ( "Fire", rvWeaponLightningGun::State_Fire ) END_CLASS_STATES /* ================ rvWeaponLightningGun::State_Raise ================ */ stateResult_t rvWeaponLightningGun::State_Raise( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAIT, }; switch ( parms.stage ) { // Start the weapon raising case STAGE_INIT: SetStatus( WP_RISING ); viewModel->SetShaderParm( 6, 1 ); PlayAnim( ANIMCHANNEL_ALL, "raise", parms.blendFrames ); return SRESULT_STAGE( STAGE_WAIT ); // Wait for the weapon to finish raising and allow it to be cancelled by // lowering the weapon case STAGE_WAIT: if ( AnimDone( ANIMCHANNEL_ALL, 4 ) ) { SetState( "Idle", 4 ); return SRESULT_DONE; } if ( wsfl.lowerWeapon ) { StopSound( SND_CHANNEL_BODY3, false ); SetState( "Lower", 4 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponLightningGun::State_Lower ================ */ stateResult_t rvWeaponLightningGun::State_Lower( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAIT, STAGE_WAITRAISE }; switch ( parms.stage ) { case STAGE_INIT: SetStatus( WP_LOWERING ); PlayAnim( ANIMCHANNEL_ALL, "putaway", parms.blendFrames ); return SRESULT_STAGE(STAGE_WAIT); case STAGE_WAIT: if ( AnimDone( ANIMCHANNEL_ALL, 0 ) ) { SetStatus( WP_HOLSTERED ); return SRESULT_STAGE(STAGE_WAITRAISE); } return SRESULT_WAIT; case STAGE_WAITRAISE: if ( wsfl.raiseWeapon ) { SetState( "Raise", 0 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponLightningGun::State_Idle ================ */ stateResult_t rvWeaponLightningGun::State_Idle( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_WAIT, }; switch ( parms.stage ) { case STAGE_INIT: SetStatus( WP_READY ); PlayCycle( ANIMCHANNEL_ALL, "idle", parms.blendFrames ); StopSound( SND_CHANNEL_BODY3, false ); StartSound( "snd_idle_hum", SND_CHANNEL_BODY3, 0, false, NULL ); return SRESULT_STAGE( STAGE_WAIT ); case STAGE_WAIT: if ( wsfl.lowerWeapon ) { StopSound( SND_CHANNEL_BODY3, false ); SetState( "Lower", 4 ); return SRESULT_DONE; } if ( wsfl.attack && gameLocal.time > nextAttackTime && AmmoAvailable ( ) ) { SetState( "Fire", 4 ); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponLightningGun::State_Fire ================ */ stateResult_t rvWeaponLightningGun::State_Fire( const stateParms_t& parms ) { enum { STAGE_INIT, STAGE_ATTACKLOOP, STAGE_DONE, STAGE_DONEWAIT }; switch ( parms.stage ) { case STAGE_INIT: StartSound( "snd_fire", SND_CHANNEL_WEAPON, 0, false, NULL ); StartSound( "snd_fire_stereo", SND_CHANNEL_ITEM, 0, false, NULL ); StartSound( "snd_fire_loop", SND_CHANNEL_BODY2, 0, false, NULL ); viewModel->SetShaderParm( 6, 0 ); viewModel->PlayEffect( "fx_spire", spireJointView, true ); viewModel->PlayEffect( "fx_flash", barrelJointView, true ); if ( worldModel && flashJointWorld != INVALID_JOINT ) { worldModel->PlayEffect( gameLocal.GetEffect( weaponDef->dict,"fx_flash_world"), flashJointWorld, vec3_origin, mat3_identity, true ); } PlayAnim( ANIMCHANNEL_ALL, "shoot_start", parms.blendFrames ); return SRESULT_STAGE( STAGE_ATTACKLOOP ); case STAGE_ATTACKLOOP: if ( !wsfl.attack || wsfl.lowerWeapon || !AmmoAvailable ( ) ) { return SRESULT_STAGE ( STAGE_DONE ); } if ( AnimDone( ANIMCHANNEL_ALL, 0 ) ) { PlayCycle( ANIMCHANNEL_ALL, "shoot_loop", 0 ); if ( !gameLocal.isMultiplayer && owner == gameLocal.GetLocalPlayer() ) { owner->playerView.SetShakeParms( MS2SEC(gameLocal.GetTime() + 500), 2.0f ); } } return SRESULT_WAIT; case STAGE_DONE: StopSound( SND_CHANNEL_BODY2, false ); viewModel->StopEffect( "fx_spire" ); viewModel->StopEffect( "fx_flash" ); if ( worldModel ) { worldModel->StopEffect( gameLocal.GetEffect( weaponDef->dict, "fx_flash_world" ) ); } viewModel->SetShaderParm( 6, 1 ); PlayAnim( ANIMCHANNEL_ALL, "shoot_end", 0 ); return SRESULT_STAGE( STAGE_DONEWAIT ); case STAGE_DONEWAIT: if ( AnimDone( ANIMCHANNEL_ALL, 4 ) ) { SetState( "Idle", 4 ); return SRESULT_DONE; } if ( !wsfl.lowerWeapon && wsfl.attack && AmmoAvailable ( ) ) { SetState( "Fire", 1); return SRESULT_DONE; } return SRESULT_WAIT; } return SRESULT_ERROR; } /* ================ rvWeaponLightningGun::Event_RestoreHum ================ */ void rvWeaponLightningGun::Event_RestoreHum ( void ) { StopSound( SND_CHANNEL_BODY3, false ); StartSound( "snd_idle_hum", SND_CHANNEL_BODY3, 0, false, NULL ); } /* =============================================================================== rvLightningPath =============================================================================== */ /* ================ rvLightningPath::StopEffects ================ */ void rvLightningPath::StopEffects( void ) { if ( trailEffect ) { trailEffect->Stop( ); trailEffect->Event_Remove( ); trailEffect = NULL; } if ( impactEffect ) { impactEffect->Stop( ); impactEffect->PostEventMS( &EV_Remove, 1000 ); impactEffect = NULL; } } /* ================ rvLightningPath::UpdateEffects ================ */ void rvLightningPath::UpdateEffects ( const idVec3& from, const idDict& dict ) { idVec3 dir; dir = origin - from; dir.Normalize(); // Trail effect if ( !trailEffect|| true ) { trailEffect = gameLocal.PlayEffect ( gameLocal.GetEffect ( dict, "fx_trail_world" ), from, dir.ToMat3(), true, origin ); } else { trailEffect->SetOrigin ( from ); trailEffect->SetAxis ( dir.ToMat3() ); trailEffect->SetEndOrigin ( origin ); trailEffect = gameLocal.PlayEffect(gameLocal.GetEffect(dict, "fx_trail_world"), from, dir.ToMat3(), true, origin); } // Impact effect if ( !target || target.GetEntityNum ( ) == ENTITYNUM_NONE ) { if ( impactEffect ) { impactEffect->Stop ( ); impactEffect->PostEventMS( &EV_Remove, 1000 ); impactEffect = NULL; } } else { if ( !impactEffect ) { impactEffect = gameLocal.PlayEffect ( gameLocal.GetEffect ( dict, "fx_impact" ), origin, normal.ToMat3(), true ); } else { impactEffect->SetOrigin ( origin ); impactEffect->SetAxis ( normal.ToMat3 ( ) ); } } } /* ================ rvLightningPath::Save ================ */ void rvLightningPath::Save( idSaveGame* savefile ) const { target.Save( savefile ); savefile->WriteVec3( origin ); savefile->WriteVec3( normal ); trailEffect.Save( savefile ); impactEffect.Save( savefile ); } /* ================ rvLightningPath::Restore ================ */ void rvLightningPath::Restore( idRestoreGame* savefile ) { target.Restore( savefile ); savefile->ReadVec3( origin ); savefile->ReadVec3( normal ); trailEffect.Restore( savefile ); impactEffect.Restore( savefile ); }
[ "sb989@njit.edu" ]
sb989@njit.edu
a8da99da04c6cc8d96ac3dd4a0eb2d638d2f0805
aa3662705e25b97d2fd3308fd3708b65c410c500
/aws-cpp-sdk-sagemaker/include/aws/sagemaker/model/CompilationJobSummary.h
69e51a12d606d25e64ad62237755e287427435bb
[ "MIT", "Apache-2.0", "JSON" ]
permissive
gifwittit/aws-sdk-cpp
de713da416ecaa26744085a7f339522c7915e372
656fd66347c48a631c354e1f2d8dd2f9a3da7de6
refs/heads/master
2022-11-27T19:16:42.639440
2020-07-16T23:01:59
2020-07-16T23:01:59
280,235,680
0
0
Apache-2.0
2020-07-16T23:02:01
2020-07-16T19:03:58
null
UTF-8
C++
false
false
13,112
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/sagemaker/SageMaker_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/DateTime.h> #include <aws/sagemaker/model/TargetDevice.h> #include <aws/sagemaker/model/CompilationJobStatus.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace SageMaker { namespace Model { /** * <p>A summary of a model compilation job.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/sagemaker-2017-07-24/CompilationJobSummary">AWS * API Reference</a></p> */ class AWS_SAGEMAKER_API CompilationJobSummary { public: CompilationJobSummary(); CompilationJobSummary(Aws::Utils::Json::JsonView jsonValue); CompilationJobSummary& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline const Aws::String& GetCompilationJobName() const{ return m_compilationJobName; } /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline bool CompilationJobNameHasBeenSet() const { return m_compilationJobNameHasBeenSet; } /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline void SetCompilationJobName(const Aws::String& value) { m_compilationJobNameHasBeenSet = true; m_compilationJobName = value; } /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline void SetCompilationJobName(Aws::String&& value) { m_compilationJobNameHasBeenSet = true; m_compilationJobName = std::move(value); } /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline void SetCompilationJobName(const char* value) { m_compilationJobNameHasBeenSet = true; m_compilationJobName.assign(value); } /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline CompilationJobSummary& WithCompilationJobName(const Aws::String& value) { SetCompilationJobName(value); return *this;} /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline CompilationJobSummary& WithCompilationJobName(Aws::String&& value) { SetCompilationJobName(std::move(value)); return *this;} /** * <p>The name of the model compilation job that you want a summary for.</p> */ inline CompilationJobSummary& WithCompilationJobName(const char* value) { SetCompilationJobName(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline const Aws::String& GetCompilationJobArn() const{ return m_compilationJobArn; } /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline bool CompilationJobArnHasBeenSet() const { return m_compilationJobArnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline void SetCompilationJobArn(const Aws::String& value) { m_compilationJobArnHasBeenSet = true; m_compilationJobArn = value; } /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline void SetCompilationJobArn(Aws::String&& value) { m_compilationJobArnHasBeenSet = true; m_compilationJobArn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline void SetCompilationJobArn(const char* value) { m_compilationJobArnHasBeenSet = true; m_compilationJobArn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline CompilationJobSummary& WithCompilationJobArn(const Aws::String& value) { SetCompilationJobArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline CompilationJobSummary& WithCompilationJobArn(Aws::String&& value) { SetCompilationJobArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the model compilation job.</p> */ inline CompilationJobSummary& WithCompilationJobArn(const char* value) { SetCompilationJobArn(value); return *this;} /** * <p>The time when the model compilation job was created.</p> */ inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; } /** * <p>The time when the model compilation job was created.</p> */ inline bool CreationTimeHasBeenSet() const { return m_creationTimeHasBeenSet; } /** * <p>The time when the model compilation job was created.</p> */ inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; } /** * <p>The time when the model compilation job was created.</p> */ inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); } /** * <p>The time when the model compilation job was created.</p> */ inline CompilationJobSummary& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;} /** * <p>The time when the model compilation job was created.</p> */ inline CompilationJobSummary& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;} /** * <p>The time when the model compilation job started.</p> */ inline const Aws::Utils::DateTime& GetCompilationStartTime() const{ return m_compilationStartTime; } /** * <p>The time when the model compilation job started.</p> */ inline bool CompilationStartTimeHasBeenSet() const { return m_compilationStartTimeHasBeenSet; } /** * <p>The time when the model compilation job started.</p> */ inline void SetCompilationStartTime(const Aws::Utils::DateTime& value) { m_compilationStartTimeHasBeenSet = true; m_compilationStartTime = value; } /** * <p>The time when the model compilation job started.</p> */ inline void SetCompilationStartTime(Aws::Utils::DateTime&& value) { m_compilationStartTimeHasBeenSet = true; m_compilationStartTime = std::move(value); } /** * <p>The time when the model compilation job started.</p> */ inline CompilationJobSummary& WithCompilationStartTime(const Aws::Utils::DateTime& value) { SetCompilationStartTime(value); return *this;} /** * <p>The time when the model compilation job started.</p> */ inline CompilationJobSummary& WithCompilationStartTime(Aws::Utils::DateTime&& value) { SetCompilationStartTime(std::move(value)); return *this;} /** * <p>The time when the model compilation job completed.</p> */ inline const Aws::Utils::DateTime& GetCompilationEndTime() const{ return m_compilationEndTime; } /** * <p>The time when the model compilation job completed.</p> */ inline bool CompilationEndTimeHasBeenSet() const { return m_compilationEndTimeHasBeenSet; } /** * <p>The time when the model compilation job completed.</p> */ inline void SetCompilationEndTime(const Aws::Utils::DateTime& value) { m_compilationEndTimeHasBeenSet = true; m_compilationEndTime = value; } /** * <p>The time when the model compilation job completed.</p> */ inline void SetCompilationEndTime(Aws::Utils::DateTime&& value) { m_compilationEndTimeHasBeenSet = true; m_compilationEndTime = std::move(value); } /** * <p>The time when the model compilation job completed.</p> */ inline CompilationJobSummary& WithCompilationEndTime(const Aws::Utils::DateTime& value) { SetCompilationEndTime(value); return *this;} /** * <p>The time when the model compilation job completed.</p> */ inline CompilationJobSummary& WithCompilationEndTime(Aws::Utils::DateTime&& value) { SetCompilationEndTime(std::move(value)); return *this;} /** * <p>The type of device that the model will run on after compilation has * completed.</p> */ inline const TargetDevice& GetCompilationTargetDevice() const{ return m_compilationTargetDevice; } /** * <p>The type of device that the model will run on after compilation has * completed.</p> */ inline bool CompilationTargetDeviceHasBeenSet() const { return m_compilationTargetDeviceHasBeenSet; } /** * <p>The type of device that the model will run on after compilation has * completed.</p> */ inline void SetCompilationTargetDevice(const TargetDevice& value) { m_compilationTargetDeviceHasBeenSet = true; m_compilationTargetDevice = value; } /** * <p>The type of device that the model will run on after compilation has * completed.</p> */ inline void SetCompilationTargetDevice(TargetDevice&& value) { m_compilationTargetDeviceHasBeenSet = true; m_compilationTargetDevice = std::move(value); } /** * <p>The type of device that the model will run on after compilation has * completed.</p> */ inline CompilationJobSummary& WithCompilationTargetDevice(const TargetDevice& value) { SetCompilationTargetDevice(value); return *this;} /** * <p>The type of device that the model will run on after compilation has * completed.</p> */ inline CompilationJobSummary& WithCompilationTargetDevice(TargetDevice&& value) { SetCompilationTargetDevice(std::move(value)); return *this;} /** * <p>The time when the model compilation job was last modified.</p> */ inline const Aws::Utils::DateTime& GetLastModifiedTime() const{ return m_lastModifiedTime; } /** * <p>The time when the model compilation job was last modified.</p> */ inline bool LastModifiedTimeHasBeenSet() const { return m_lastModifiedTimeHasBeenSet; } /** * <p>The time when the model compilation job was last modified.</p> */ inline void SetLastModifiedTime(const Aws::Utils::DateTime& value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime = value; } /** * <p>The time when the model compilation job was last modified.</p> */ inline void SetLastModifiedTime(Aws::Utils::DateTime&& value) { m_lastModifiedTimeHasBeenSet = true; m_lastModifiedTime = std::move(value); } /** * <p>The time when the model compilation job was last modified.</p> */ inline CompilationJobSummary& WithLastModifiedTime(const Aws::Utils::DateTime& value) { SetLastModifiedTime(value); return *this;} /** * <p>The time when the model compilation job was last modified.</p> */ inline CompilationJobSummary& WithLastModifiedTime(Aws::Utils::DateTime&& value) { SetLastModifiedTime(std::move(value)); return *this;} /** * <p>The status of the model compilation job.</p> */ inline const CompilationJobStatus& GetCompilationJobStatus() const{ return m_compilationJobStatus; } /** * <p>The status of the model compilation job.</p> */ inline bool CompilationJobStatusHasBeenSet() const { return m_compilationJobStatusHasBeenSet; } /** * <p>The status of the model compilation job.</p> */ inline void SetCompilationJobStatus(const CompilationJobStatus& value) { m_compilationJobStatusHasBeenSet = true; m_compilationJobStatus = value; } /** * <p>The status of the model compilation job.</p> */ inline void SetCompilationJobStatus(CompilationJobStatus&& value) { m_compilationJobStatusHasBeenSet = true; m_compilationJobStatus = std::move(value); } /** * <p>The status of the model compilation job.</p> */ inline CompilationJobSummary& WithCompilationJobStatus(const CompilationJobStatus& value) { SetCompilationJobStatus(value); return *this;} /** * <p>The status of the model compilation job.</p> */ inline CompilationJobSummary& WithCompilationJobStatus(CompilationJobStatus&& value) { SetCompilationJobStatus(std::move(value)); return *this;} private: Aws::String m_compilationJobName; bool m_compilationJobNameHasBeenSet; Aws::String m_compilationJobArn; bool m_compilationJobArnHasBeenSet; Aws::Utils::DateTime m_creationTime; bool m_creationTimeHasBeenSet; Aws::Utils::DateTime m_compilationStartTime; bool m_compilationStartTimeHasBeenSet; Aws::Utils::DateTime m_compilationEndTime; bool m_compilationEndTimeHasBeenSet; TargetDevice m_compilationTargetDevice; bool m_compilationTargetDeviceHasBeenSet; Aws::Utils::DateTime m_lastModifiedTime; bool m_lastModifiedTimeHasBeenSet; CompilationJobStatus m_compilationJobStatus; bool m_compilationJobStatusHasBeenSet; }; } // namespace Model } // namespace SageMaker } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
e552bbbce302f0c6a1ee6a25e0544d10d10061e8
14081e500bca2a8ccb2af7ce58da17aa3ed304e3
/数据结构/线段树/hdu3308 线段树区间合并LCIS.cpp
a23f98f9631d9a689074c6f63303aad9c5416e36
[]
no_license
Strive-for-excellence/ACM
3910a24fc0f84c4ab7490d38783d79bbd20e9ada
6195eb36f25ffffdcc32d109a5333ca870879490
refs/heads/master
2021-05-01T06:05:12.038365
2018-05-20T04:12:27
2018-05-20T04:12:27
121,135,393
1
0
null
2018-02-11T15:09:43
2018-02-11T15:09:43
null
UTF-8
C++
false
false
5,942
cpp
#include <iostream> using namespace std; #include <cstdio> const int maxn = 200000; struct Node { int l, r, lt, rt, lx, rx, mx; } tree[maxn * 2]; int tnum; int a[maxn]; void maketree(int k) { int mid; tree[k].lx = tree[k].rx = tree[k].mx = 1; if (tree[k].l == tree[k].r) { tree[k].lt = tree[k].rt = -1; return ; } mid = (tree[k].l + tree[k].r) / 2; tree[tnum].l = tree[k].l; tree[tnum].r = mid; tree[k].lt = tnum; tnum++; tree[tnum].l = mid + 1; tree[tnum].r = tree[k].r; tree[k].rt = tnum++; } void pushup(int k) { if (tree[k].lt == tree[k].rt) return ;//叶子节点就返回 int lt = tree[k].lt, rt = tree[k].rt; tree[k].mx = max(tree[lt].mx, tree[rt].mx); tree[k].lx = tree[lt].lx; tree[k].rx = tree[rt].rx; if (a[tree[lt].r] < a[tree[rt].l]) { tree[k].mx = max(tree[k].mx, tree[lt].rx + tree[rt].lx); if (tree[lt].lx == tree[lt].r - tree[lt].l + 1) tree[k].lx += tree[rt].lx; if (tree[rt].rx == tree[rt].r - tree[rt].l + 1) tree[k].rx += tree[lt].rx; } } void update(int k, int c, int val) { if (tree[k].l == tree[k].r)//叶子节点 { a[c] = val;//替换 return ; } int mid = (tree[k].l + tree[k].r) / 2; if (c <= mid) update(tree[k].lt, c, val); else update(tree[k].rt, c, val); pushup(k); } int query(int k, int l , int r) { if (tree[k].l == l && tree[k].r == r) return tree[k].mx; int mid = (tree[k].l + tree[k].r) / 2; if (r <= mid) return query(tree[k].lt, l, r); if (l > mid) return query(tree[k].rt, l, r); int mmax = max(query(tree[k].lt, l, mid), query(tree[k].rt, mid + 1, r)); if (a[mid] < a[mid + 1]) mmax = max(mmax, min(mid - l + 1, tree[tree[k].lt].rx) + min(r - mid, tree[tree[k].rt].lx)); return mmax; } int n, m; int main() { // freopen("in.in", "r", stdin); int cass; for (scanf("%d", &cass); cass--;) { int i, j, k; scanf("%d%d", &n, &m); tnum = 1; tree[0].l = 0; tree[0].r = n - 1; for (i = 0; i < n; i++) scanf("%d", &a[i]); for (i = 0; i < tnum; i++) maketree(i); for (i = tnum - 1; i >= 0; i--) pushup(i); char s[10]; while (m--) { scanf("%s%d%d", s, &i, &j); if (s[0] == 'Q') printf("%d\n", query(0, i, j)); else update(0, i, j); } } return 0; } ////////////////////////////////////// //学弟的代码,好强悍! #include <cstdio> #include <cstring> #include <map> #include <cmath> #include <queue> #include <string> #include <stack> #include <cstdlib> #include <iostream> #include <set> #include <ctime> #include <vector> #include <algorithm> #define abs(x) ((x)>0?(x):-(x)) #define __max(a,b) ((a)>(b)?(a):(b)) #define __min(a,b) ((a)<(b)?(a):(b)) #define rep(i,a,b) for(int i=a;i<b;i++) #define erep(i,a,b) for(int i=a;i<=b;i++) #define inf 0x7f//2147483647 #define iinf 0x7fffffff #define PI acos(-1.0) #define NOBUG puts("No_Bug_Hear"); #define STOP system("pause"); #define FOUT freopen("out","w",stdout); #define FIN freopen("in","r",stdin); #define OUTCLOSE fclose(stdout); #define INCLOSE fclose(stdin); #define rd2(a,b) scanf("%d%d",&a,&b) #define rd(a) scanf("%d",&a) #define rd3(a,b,c) scanf("%d%d%d",&a,&b,&c) #define rd4(a,b,c,d) scanf("%d%d%d%d",&a,&b,&c,&d) #define INIT(a,b) memset(a,b,sizeof(a)) #define pb push_back #define lson sl,mid,rt<<1 #define rson mid+1,ed,rt<<1|1 #define maxn 100008 typedef long long ll; using namespace std; int L, Q, u, v; char op; struct node { int lfm, rtm, lfv, rtv, opt; } t[maxn << 2]; void pushup(int rt, int len) { t[rt].opt = __max(t[rt << 1].opt, t[rt << 1 | 1].opt); if (t[rt << 1].rtv < t[rt << 1 | 1].lfv) { t[rt].opt = __max(t[rt].opt, t[rt << 1].rtm + t[rt << 1 | 1].lfm); } if (len - len / 2 == t[rt << 1].lfm && t[rt << 1].rtv < t[rt << 1 | 1].lfv) t[rt].lfm = t[rt << 1].lfm + t[rt << 1 | 1].lfm; else { t[rt].lfm = t[rt << 1].lfm; } if (len / 2 == t[rt << 1 | 1].rtm && t[rt << 1].rtv < t[rt << 1 | 1].lfv) t[rt].rtm = t[rt << 1].rtm + t[rt << 1 | 1].rtm; else { t[rt].rtm = t[rt << 1 | 1].rtm; } t[rt].lfv = t[rt << 1].lfv; t[rt].rtv = t[rt << 1 | 1].rtv; } void build(int st, int ed, int rt) { if (st == ed) { rd(t[rt].lfv); t[rt].rtv = t[rt].lfv; t[rt].opt = t[rt].lfm = t[rt].rtm = 1; return ; } int mid = (st + ed) >> 1; build(lson); build(rson); pushup(rt, ed - st + 1); } void update(int pos, int x, int st, int ed, int rt) { if (st == ed) { t[rt].rtv = t[rt].lfv = x; return ; } int mid = (st + ed) >> 1; if (pos <= mid) update(pos, x, lson); else update(pos, x, rson); pushup(rt, ed - st + 1); } int query(int l, int r, int st, int ed, int rt) { if (l <= st && ed <= r) { return t[rt].opt; } int mid = (st + ed) >> 1, ret = -1; if (l <= mid)ret = max(ret, query(l, r, lson)); if (r > mid)ret = max(ret, query(l, r, rson)); if ((l <= mid && r > mid) && (t[rt << 1].rtv < t[rt << 1 | 1].lfv)) { int rrtm = min(t[rt << 1].rtm, mid - l + 1), llfm = min(t[rt << 1 | 1].lfm, r - mid); ret = max(ret, rrtm + llfm); } return ret; } int main() { //FIN //FOUT int T; rd(T); while (T-- && rd2(L, Q)) { build(1, L, 1); while (Q-- && scanf(" %c", &op)) { rd2(u, v); if (op == 'Q') { printf("%d\n", query(u + 1, v + 1, 1, L, 1)); } else { update(u + 1, v, 1, L, 1); } } } //STOP //INCLOSE //OUTCLOSE return 0; }
[ "elizhongyang@163.com" ]
elizhongyang@163.com