text
stringlengths
8
6.88M
#define ERROR 0x01 #define SUCCESS 0x00 namespace TWI { void TWIInit(void); void TWIStart(void); void TWIStop(void); void TWIWrite(uint8_t u8data); uint8_t TWIReadACK(void); uint8_t TWIReadNACK(void); uint8_t WriteByte(uint8_t u8device_addr, uint8_t u8register_addr, uint8_t u8data); uint8_t ReadByte(uint8_t u8device_addr, uint8_t u8register_addr, uint8_t *u8data); uint8_t ReadByte(uint8_t u8device_addr, uint8_t u8register_addr, uint8_t *u8data, int length); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Manuela Hutter (manuelah) */ #include "core/pch.h" #include "adjunct/quick_toolkit/readers/UIReader.h" #include "adjunct/ui_parser/ParserIterators.h" #include "adjunct/quick_toolkit/creators/QuickDialogCreator.h" #include "adjunct/quick_toolkit/creators/QuickWidgetCreator.h" #include "adjunct/desktop_util/adt/typedobjectcollection.h" ////////// ~UIReader UIReader::~UIReader() { m_logger.EndLogging(); } ////////// Init OP_STATUS UIReader::Init(const OpStringC8& node_name, const OpStringC& file_path, OpFileFolder folder, const OpStringC& logfile) { if (logfile.HasContent()) { RETURN_IF_ERROR(m_logger.Init(logfile)); m_logger.StartLogging(); } m_ui_document.SetLogger(&m_logger); RETURN_IF_ERROR(m_ui_document.Init(file_path, folder)); ParserLogger::AutoIndenter indenter(m_logger, "Reading %s definitions into map", node_name); ParserNodeMapping node; if (!m_ui_document.GetRootNode(node)) { m_logger.OutputEntry("ERROR: could not retrieve the document's root node"); return OpStatus::OK; } // read first hash level: retrieve the '<node_name>' node ParserNodeSequence relevant_node; if (!node.GetChildNodeByID(node.FindValueForKey(node_name), relevant_node)) { m_logger.OutputEntry("ERROR: document doesn't contain a '%s' top-level node", node_name); return OpStatus::OK; } // traverse all nodes under 'node_name', get their name // store name and YAML node ID in a hash for (ParserSequenceIterator it(relevant_node); it; ++it) { ParserNodeMapping ui_element; if (!m_ui_document.GetNodeByID(it.Get(), ui_element)) { m_logger.OutputEntry("WARNING: Couldn't retrieve node in '%s' sequence. It is probably not of type 'MAPPING'. Ignoring entry.", node_name); continue; } ParserNodeScalar name_node; if (!ui_element.GetChildNodeByID(ui_element.FindValueForKey("name"), name_node)) { m_logger.OutputEntry("ERROR: %s node doesn't have a child node called 'name'. Ignoring...", node_name); continue; } OpAutoPtr<ParserNodeIDTableData> data (OP_NEW(ParserNodeIDTableData, (it.Get()))); RETURN_OOM_IF_NULL(data.get()); RETURN_IF_ERROR(m_logger.Evaluate(name_node.GetString(data->key), "ERROR retrieving string from name node")); RETURN_IF_ERROR(m_ui_element_hash.Add(data->key.CStr(), data.get())); m_logger.OutputEntry("Read '%s'", data->key); data.release(); } indenter.Done(); return OpStatus::OK; } OP_STATUS UIReader::GetNodeFromMap(const OpStringC8 &name, ParserNodeMapping* node) { ParserNodeIDTableData * data; RETURN_IF_ERROR(m_logger.Evaluate(m_ui_element_hash.GetData(name.CStr(), &data), "ERROR: could not find widget with name '%s'", name)); if (!m_ui_document.GetNodeByID(data->data_id, *node)) { m_logger.OutputEntry("ERROR: could not retrieve widget node"); return OpStatus::ERR; } return OpStatus::OK;; } ////////// DialogReader BOOL DialogReader::HasQuickDialog(const OpStringC8 & dialog_name) { ParserNodeMapping node; if (OpStatus::IsError(GetNodeFromMap(dialog_name, &node))) return FALSE; return TRUE; } OP_STATUS DialogReader::CreateQuickDialog(const OpStringC8 & dialog_name, QuickDialog & dialog) { QuickDialogCreator creator(m_logger); ParserNodeMapping node; RETURN_IF_ERROR(GetNodeFromMap(dialog_name, &node)); RETURN_IF_ERROR(creator.Init(&node)); return creator.CreateQuickDialog(dialog); } ////////// WidgetReader OP_STATUS WidgetReader::CreateQuickWidget(const OpStringC8 & widget_name, OpAutoPtr<QuickWidget>& widget, TypedObjectCollection &collection) { QuickWidgetCreator creator(collection, m_logger, false); ParserNodeMapping node; RETURN_IF_ERROR(GetNodeFromMap(widget_name, &node)); RETURN_IF_ERROR(creator.Init(&node)); return creator.CreateWidget(widget); }
// // Created by Felix Winter on 08.04.2019. // #ifndef CHUFFED_EDEXPLFINDER_H #define CHUFFED_EDEXPLFINDER_H #include <chuffed/core/propagator.h> #include <chuffed/support/vec.h> #include <queue> #include <vector> /** * Class that will help to find variable inequalities used to explain propagation of lcs bounds */ class EdExplFinder { public: /** * * @param _max_char: maximum character of alphabet * @param _insertion_cost: vector containing character insertion costs * @param _deletion_cost: vector containing character deletion costs * @param _substitution_cost: vector containing character substitution costs * @param seq1: string sequence 1 * @param seq2: string sequence 2 * @param dpMatrix: a matrix including the shortest edit distance to each position of the dynamic * programming matrix * @param lb: a valid lowerbound for the edit distance of two sequences that have been used to * build the dp matrices * @param seqSize: the size of the sequences for which explanation inequalities should be * determined * @param min_id_cost: minimum insertion/deletion cost to determine which "diagonal" of the matrix * should be calculated * @return An explanation clause for a propagation on the edit distance lower bound */ Clause* FindEdExplanation(int _max_char, const vec<int>* _insertion_cost, const vec<int>* _deletion_cost, const vec<int>* _substitution_cost, IntView<>* _seq1, IntView<>* _seq2, const vec<int>* _dpMatrix, int _lb, int _seqSize, int _min_id_cost); ~EdExplFinder(); EdExplFinder(); private: IntView<>* seq1{}; IntView<>* seq2; // maximum character of alphabet int max_char; // minimum insertion/deletion cost int min_id_cost; // vector of character insertion costs const vec<int>* insertion_cost; // vector of character deletion costs const vec<int>* deletion_cost; // vector of character substitution costs const vec<int>* substitution_cost; // structures to capture the characters that should be excluded for the sequence positions // flat 2d vectors (sequence positions * characters) std::vector<bool>* seq1ExcludedCharacters{}; std::vector<bool>* seq2ExcludedCharacters{}; // read only pointer to dpMatrix const vec<int>* dpMatrix; // size of the sequences that are compared int seqSize; // valid lower bound for the edit distance int lb; /** * Do a breadth first search to fill shortest path matrix */ void bfs_shortest_path(); int excludedCharCoord(int i, int c) const; int matrixCoord(int i, int j) const; int substCoord(int c1, int c2) const; void clean_data_structures(); /** * print final state of shortest path matrix and found inequalities */ void debug_print(std::vector<int>* shortestPathMatrix) const; }; #endif // CHUFFED_EDEXPLFINDER_H
#include<test> main() { int a; int b; int c; double d; c=a+b; d=c; d=a-b; new c - b; }
/*#include "perf_precomp.hpp" #include "distransform.cpp" using namespace std; using namespace cv; using namespace perf; typedef perf::TestBaseWithParam<Size> Size_DistanceTransform; PERF_TEST_P(Size_DistanceTransform, icvTrueDistTrans, testing::Values(TYPICAL_MAT_SIZES)) { Size size = GetParam(); Mat src(size, CV_8UC1); Mat dst(size, CV_32FC1); CvMat srcStub = src; CvMat dstStub = dst; declare.in(src, WARMUP_RNG).out(dst); TEST_CYCLE() icvTrueDistTrans(&srcStub, &dstStub); SANITY_CHECK(dst, 1); }*/ #include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; CV_ENUM(DistanceType, DIST_L1, DIST_L2 , DIST_C) CV_ENUM(MaskSize, DIST_MASK_3, DIST_MASK_5, DIST_MASK_PRECISE) CV_ENUM(DstType, CV_8U, CV_32F) CV_ENUM(LabelType, DIST_LABEL_CCOMP, DIST_LABEL_PIXEL) typedef std::tr1::tuple<Size, DistanceType, MaskSize, DstType> SrcSize_DistType_MaskSize_DstType; typedef std::tr1::tuple<Size, DistanceType, MaskSize, LabelType> SrcSize_DistType_MaskSize_LabelType; typedef perf::TestBaseWithParam<SrcSize_DistType_MaskSize_DstType> DistanceTransform_Test; typedef perf::TestBaseWithParam<SrcSize_DistType_MaskSize_LabelType> DistanceTransform_NeedLabels_Test; PERF_TEST_P(DistanceTransform_Test, distanceTransform, testing::Combine( testing::Values(cv::Size(640, 480), cv::Size(800, 600), cv::Size(1024, 768), cv::Size(1280, 1024)), DistanceType::all(), MaskSize::all(), DstType::all() ) ) { Size srcSize = get<0>(GetParam()); int distanceType = get<1>(GetParam()); int maskSize = get<2>(GetParam()); int dstType = get<3>(GetParam()); Mat src(srcSize, CV_8U); Mat dst(srcSize, dstType); declare .in(src, WARMUP_RNG) .out(dst, WARMUP_RNG) .time(30); TEST_CYCLE() distanceTransform( src, dst, distanceType, maskSize, dstType); double eps = 2e-4; SANITY_CHECK(dst, eps); } PERF_TEST_P(DistanceTransform_NeedLabels_Test, distanceTransform_NeedLabels, testing::Combine( testing::Values(cv::Size(640, 480), cv::Size(800, 600), cv::Size(1024, 768), cv::Size(1280, 1024)), DistanceType::all(), MaskSize::all(), LabelType::all() ) ) { Size srcSize = get<0>(GetParam()); int distanceType = get<1>(GetParam()); int maskSize = get<2>(GetParam()); int labelType = get<3>(GetParam()); Mat src(srcSize, CV_8U); Mat label(srcSize, CV_32S); Mat dst(srcSize, CV_32F); declare .in(src, WARMUP_RNG) .out(label, WARMUP_RNG) .out(dst, WARMUP_RNG) .time(30); TEST_CYCLE() distanceTransform( src, dst, label, distanceType, maskSize, labelType); double eps = 2e-4; SANITY_CHECK(label, eps); SANITY_CHECK(dst, eps); }
#ifndef LASER_MACHINE_H #define LASER_MACHINE_H #include <QObject> #include "vector" #include "opencv2/core/core.hpp" #include <QDebug> using namespace std; class Laser_Machine : public QObject { Q_OBJECT // Structures: enum StateLaserMachine { WAIT, WORK, }; struct DotCoordinateState { double x; double y; bool laserOn; unsigned int power; DotCoordinateState(double x_, double y_, bool laserOn_, unsigned int power_) : x(x_), y(y_), laserOn(laserOn_), power(power_){ } DotCoordinateState() : x(0), y(0), laserOn(0), power(0){ } friend QDebug operator << (QDebug qd, DotCoordinateState &dcs) { qd << "x=" << dcs.x << ": y=" << dcs.y << ": power=" << dcs.power << ": laser state=" << dcs.laserOn; return qd.maybeSpace(); } }; public: explicit Laser_Machine(QObject * parent = NULL); ~Laser_Machine(); signals: bool sendCommand(QString); void talking(const QString &); void setSendingFlag(bool); public slots: // Commands: void command_X00(); void command_X01(DotCoordinateState); void command_X01(double, double, bool, unsigned int); void command_X02(); void command_X02(unsigned int); void command_X03(); void command_X04(); void command_X04(bool); void command_X05(); void command_X05(bool); void command_X42(); // Recieve part void prepareContour(vector<vector<cv::Point> >, double, double); void sendToLaser(); void nextPacket(); // Seters: void setShift(int x, int y) { shiftX_ = x; shiftY_ = y; } void setSizePacket(int sp){ sizePacket_ = sp; } void setPowerLaser(unsigned int p){ power_ = p; } void setSpeed(int s){ speed_ = s; } void setBurnyState(bool s){ burnyState_ = s; } void setShift(double i){ shift_ = i; } int GetStateMachine(){ return stateLaserMachine_; } // Other: void initMoves(); void resetState(); private: vector<DotCoordinateState> dotsToBurn_; DotCoordinateState home_ = { 0, 0, 0, 0 }; StateLaserMachine stateLaserMachine_; int shiftX_, shiftY_; int speed_; double shift_; unsigned int power_; int sizePacket_; bool coolingState_, burnyState_; unsigned int cons_; bool flagReadyGo_ = false; bool flagReadySend_ = false; }; #endif // LASER_MACHINE_H
#ifndef GRADDESC_H #define GRADDESC_H #include <vector> #include <utility> #include <memory> class Network; class Node { friend class Network; public: Node(Network* net); virtual ~Node(); double GetValue() { return value; } double GetPartial() { return dcost; } protected: virtual void Eval() = 0; virtual void PushPartial() = 0; virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx) = 0; double value; double dcost; static void PushPartial(Node* n, double d); }; class InputNode : public Node { public: InputNode(Network* net, double val = 0); void SetValue(double val) { value = val; } protected: virtual void Eval() { } virtual void PushPartial() { } virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx) { } }; class ParameterNode : public Node { public: ParameterNode(Network* net, double val = 0); protected: virtual void Eval() { } virtual void PushPartial() { } virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx) { } }; class LinearReducer : public Node { public: LinearReducer(Network* net, Node* bias); void AddTerm(Node* a, Node* b); protected: virtual void Eval(); virtual void PushPartial(); virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx); private: Node* bias; std::vector<std::pair<Node*, Node*> > terms; }; class SigmoidNode : public Node { public: SigmoidNode(Network* net, Node* input); protected: virtual void Eval(); virtual void PushPartial(); virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx); private: Node* input; }; class SquaredError : public Node { public: SquaredError(Network* net); void AddTerm(Node* a, Node* b); protected: virtual void Eval(); virtual void PushPartial(); virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx); private: std::vector<std::pair<Node*, Node*> > terms; }; class L2Regularizer : public Node { public: L2Regularizer(Network* net, Node* base_cost); virtual ~L2Regularizer() {}; void AddParam(Node* a); protected: virtual void Eval(); virtual void PushPartial(); virtual void EnumDeps(void (*callback)(Node*, void*), void* ctx); private: Node* base_cost; }; class Network { friend class Node; friend class ParameterNode; public: void TopoSort(); void ComputeValues(); void ComputePartials(Node* cost); void UpdateParameters(double learning_rate); uint32_t NumParameters() { return parameters.size(); } Node* GetParameter(uint32_t index) { return parameters[index]; } private: void AddNode(Node* n); void AddParameter(ParameterNode* n); std::vector<ParameterNode*> parameters; std::vector<std::unique_ptr<Node> > nodes; }; #endif
#include "gtest/gtest.h" #include "../../../../options/OptionCall.hpp" #include "../../../../binomial_method/case/Case.hpp" #include "../../../../binomial_method/case/Wilmott2Case.hpp" #include "../../../../binomial_method/method/regular/euro/EuroBinomialMethod.hpp" double dividend_euro_call_Wilmott2(int iT, int iM) { double r = 0.06; double s0 = 12; double E = 10; double sigma = 0.3; double d0 = 0.04; double T[] = {0.25, 0.5, 0.75, 1.0}; int M[] = {16, 32, 64, 128, 256}; OptionCall<double> aOption(T[iT], s0, r, sigma, E, d0); Wilmott2Case<double> aCase(&aOption, M[iM]); EuroBinomialMethod<double> method(&aCase); method.solve(); double result = method.getResult(); return result; } TEST(CntiniousDividendEuroCallWilmott2, test16_025) { double result = dividend_euro_call_Wilmott2(0, 0); EXPECT_NEAR(result, 2.1132, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test32_025) { double result = dividend_euro_call_Wilmott2(0, 1); EXPECT_NEAR(result, 2.1123, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test64_025) { double result = dividend_euro_call_Wilmott2(0, 2); EXPECT_NEAR(result, 2.1121, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test128_025) { double result = dividend_euro_call_Wilmott2(0, 3); EXPECT_NEAR(result, 2.1119, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test256_025) { double result = dividend_euro_call_Wilmott2(0, 4); EXPECT_NEAR(result, 2.1118, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test16_050) { double result = dividend_euro_call_Wilmott2(1, 0); EXPECT_NEAR(result, 2.2906, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test32_050) { double result = dividend_euro_call_Wilmott2(1, 1); EXPECT_NEAR(result, 2.2839, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test64_050) { double result = dividend_euro_call_Wilmott2(1, 2); EXPECT_NEAR(result, 2.2824, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test128_050) { double result = dividend_euro_call_Wilmott2(1, 3); EXPECT_NEAR(result, 2.2831, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test256_050) { double result = dividend_euro_call_Wilmott2(1, 4); EXPECT_NEAR(result, 2.2825, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test16_075) { double result = dividend_euro_call_Wilmott2(2, 0); EXPECT_NEAR(result, 2.4436, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test32_075) { double result = dividend_euro_call_Wilmott2(2, 1); EXPECT_NEAR(result, 2.4406, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test64_075) { double result = dividend_euro_call_Wilmott2(2, 2); EXPECT_NEAR(result, 2.4407, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test128_075) { double result = dividend_euro_call_Wilmott2(2, 3); EXPECT_NEAR(result, 2.4390, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test256_075) { double result = dividend_euro_call_Wilmott2(2, 4); EXPECT_NEAR(result, 2.4368, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test16_010) { double result = dividend_euro_call_Wilmott2(3, 0); EXPECT_NEAR(result, 2.5667, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test32_010) { double result = dividend_euro_call_Wilmott2(3, 1); EXPECT_NEAR(result, 2.5840, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test64_010) { double result = dividend_euro_call_Wilmott2(3, 2); EXPECT_NEAR(result, 2.5745, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test128_010) { double result = dividend_euro_call_Wilmott2(3, 3); EXPECT_NEAR(result, 2.5741, 0.0001); } TEST(CntiniousDividendEuroCallWilmott2, test256_010) { double result = dividend_euro_call_Wilmott2(3, 4); EXPECT_NEAR(result, 2.5756, 0.0001); }
#include <iostream> using namespace std; int main() { // your code goes here long long t; cin>>t; while(t--) { long long n,a,b,n1=0,n2=0; cin>>n>>a>>b; while(n--) { string s; cin>>s; if (s[0]=='E'||s[0]=='Q'||s[0]=='U'||s[0]=='I'||s[0]=='N'||s[0]=='O'||s[0]=='X') n1 += a; else n2 += b; } if (n1 > n2) cout<<"SARTHAK"<<endl; else if (n1 == n2) cout<<"DRAW"<<endl; else cout<<"ANURADHA"<<endl; } return 0; }
// Created on: 1999-08-11 // Created by: Roman LYGIN // Copyright (c) 1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TransferBRep_TransferResultInfo_HeaderFile #define _TransferBRep_TransferResultInfo_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <Standard_Transient.hxx> class TransferBRep_TransferResultInfo; DEFINE_STANDARD_HANDLE(TransferBRep_TransferResultInfo, Standard_Transient) //! Data structure for storing information on transfer result. //! At the moment it dispatches information for the following types: //! - result, //! - result + warning(s), //! - result + fail(s), //! - result + warning(s) + fail(s) //! - no result, //! - no result + warning(s), //! - no result + fail(s), //! - no result + warning(s) + fail(s), class TransferBRep_TransferResultInfo : public Standard_Transient { public: //! Creates object with all fields nullified. Standard_EXPORT TransferBRep_TransferResultInfo(); //! Resets all the fields. Standard_EXPORT void Clear(); Standard_Integer& Result(); Standard_Integer& ResultWarning(); Standard_Integer& ResultFail(); Standard_Integer& ResultWarningFail(); Standard_Integer& NoResult(); Standard_Integer& NoResultWarning(); Standard_Integer& NoResultFail(); Standard_Integer& NoResultWarningFail(); DEFINE_STANDARD_RTTIEXT(TransferBRep_TransferResultInfo,Standard_Transient) protected: private: Standard_Integer myR; Standard_Integer myRW; Standard_Integer myRF; Standard_Integer myRWF; Standard_Integer myNR; Standard_Integer myNRW; Standard_Integer myNRF; Standard_Integer myNRWF; }; #include <TransferBRep_TransferResultInfo.lxx> #endif // _TransferBRep_TransferResultInfo_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2000 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef _WML_H_ #define _WML_H_ #ifdef _WML_SUPPORT_ #include "modules/hardcore/mh/messobj.h" #include "modules/util/simset.h" #include "modules/logdoc/elementref.h" class HTML_Element; class FormObject; class DocumentManager; class FramesDocument; class WML_Context; //----------------------------------------------------------- // tables for the WML elements //----------------------------------------------------------- #include "modules/logdoc/wmlenum.h" /// \enum enum for the WML event codes enum WML_EventType { WEVT_ONPICK = 128, WEVT_ONTIMER, WEVT_ONENTERFORWARD, WEVT_ONENTERBACKWARD, WEVT_ONCLICK, ///< mock event for clicking on URLs WEVT_UNKNOWN = 511 }; /// constants for the WML status fields, manual bit-thingy /// DO NOT CHANGE THE VALUES TO ANYTHING OTHER THAN 2^n #define WS_AOK 0x00000000 ///< all ok, zero state #define WS_ERROR 0x00000001 ///< a general error #define WS_NOACCESS 0x00000002 ///< access to the card is denied #define WS_GO 0x00000004 ///< a GO-navigation is in progress #define WS_ENTERBACK 0x00000008 ///< a backward navigation going on #define WS_REFRESH 0x00000010 ///< a refresh navigation going on #define WS_NOOP 0x00000020 ///< a task is set to do no navigation #define WS_TIMING 0x00000040 ///< if the timer is ticking #define WS_USERINIT 0x00000080 ///< user initiated navigation #define WS_CLEANHISTORY 0x00000100 ///< clean up the WML history // internal status #define WS_FIRSTCARD 0x00000200 ///< not started parsing second card yet #define WS_INVAR 0x00000400 ///< inside a variable #define WS_NEWCONTEXT 0x00000800 ///< the WML context must be reset #define WS_ODDTIME 0x00001000 ///< used by timer to even out time fractions #define WS_INRIGHTCARD 0x00002000 ///< the addressed card is found #define WS_NOSECWARN 0x00004000 ///< suppress form-warning if <go>-element have no <postfield>/<setvar> #define WS_SENDREF 0x00008000 ///< send referer only when this flag is set #define WS_ILLEGALFORM 0x00010000 ///< set when the form input is not valid #define WS_CHECKTIMER 0x00020000 ///< first card timer might be wrong #define WS_CHECKFORWARD 0x00040000 ///< first card onenterforward might be wrong #define WS_CHECKBACK 0x00080000 ///< first card onenterbackward might be wrong //----------------------------------------------------------- // Various defines //----------------------------------------------------------- ///\enum handler indices enum { WH_TIMER = 0, WH_FORWARD = 1, WH_BACKWARD = 2, WH_ABSOLUTLY_LAST_ENUM = 3 }; ///\enum WML variable expansion constants enum { WML_CONV_NONE = 0, WML_CONV_ESC = 1, WML_CONV_UNESC = 2 }; ///\enum values for the wrap attribute enum { WATTR_VALUE_nowrap = 0, WATTR_VALUE_wrap = 1 }; ///\enum values for the cache attribute enum { WATTR_VALUE_nocache = 0, WATTR_VALUE_cache = 1 }; /// Class for storing WML variables. /// Variables can be set explicitly by SETVAR and POSTVAR or implicitly by a TIMER /// or form control during the execution of a task. /// Variables can be inserted into the WML document by using the $varname notation. class WMLVariableElm : public ListElement<WMLVariableElm> { private: uni_char *m_name; ///< Variable name uni_char *m_value; ///< Variable value public: WMLVariableElm() : m_name(NULL), m_value(NULL) {} ~WMLVariableElm(); OP_STATUS SetVal(const uni_char *new_value, int new_len); ///< Set the value, replacing existing value OP_STATUS SetName(const uni_char *new_name, int new_len); ///< Set the name, replacing existing name const uni_char* GetValue() { return m_value; } const uni_char* GetName() { return m_name; } /// Compare the name of the variable with equal_name. ///\param[in] equal_name. String containing name, need not be nul terminated ///\param[in] n_len. Length of equal_name BOOL IsNamed(const uni_char *equal_name, unsigned int n_len); /// Copies the variable to the existing variable src_var. ///\param[out] src_var. Preallocated variable that will get the values of this variable OP_STATUS Copy(WMLVariableElm *src_var); }; /// The class for storing WML tasks. /// Tasks in WML are essentially navigations between cards or internally within a card. /// Tasks are GO (to another card), PREV (the previous card), REFRESH (the same card) /// or NOOP (do nothing) /// Tasks can be bound to links like for A, DO or ANCHOR elements or to events like /// ONPICK or ONENTERFORWARD. /// When performing a task the WML context will be updated with the new variables /// associated with the task in form of a SETVAR or POSTVAR element or intrinsic /// variables like values of form controls. class WMLNewTaskElm : public ListElement<WMLNewTaskElm> , public ElementRef { private: /// Searching the logical tree for the next variable associated with the task. ///\param[out] last_found Iterator used by subsequent searches for variables ///\param[out] out_name The name of the next variable found, NULL if none found ///\param[out] value_name The value of the next variable found ///\param[in] find_first Must be TRUE if there has been no previous searches ///\param[in] internal Must be TRUE if searching for SETVAR variablees, else it will search for POSTVAR variables void LocalGetNextVariable(HTML_Element **last_found, const uni_char **out_name, const uni_char **out_value, BOOL find_first, BOOL internal = TRUE); public: WMLNewTaskElm(HTML_Element *new_he) : ElementRef(new_he) {} WMLNewTaskElm(WMLNewTaskElm *src_task); ///< Copy constructor ~WMLNewTaskElm() {} BOOL IsNamed(const uni_char *equal_name); ///< Return TRUE if the taskname matches equal_name \param[in] equal_name /// Searching for the first internal (SETVAR) variable for the task. ///\param[out] last_found is used as an iterator for subsequent searches ///\param[out] out_name is the name of the next variable found, NULL if none found ///\param[out] value_name is the value of the next variable found void GetFirstIntVar(HTML_Element **last_found, const uni_char **out_name, const uni_char **out_value) { LocalGetNextVariable(last_found, out_name, out_value, TRUE, TRUE); } /// Searching for the next internal (SETVAR) variable for the task. ///\param[out] last_found is an iterator returned by GetFirstIntVar() ///\param[out] out_name is the name of the next variable found, NULL if none found ///\param[out] value_name is the value of the next variable found void GetNextIntVar(HTML_Element **last_found, const uni_char **out_name, const uni_char **out_value) { LocalGetNextVariable(last_found, out_name, out_value, FALSE, TRUE); } /// Searching for the first external (POSTVAR) variable for the task. ///\param[out] last_found is used as an iterator for subsequent searches ///\param[out] out_name is the name of the next variable found, NULL if none found ///\param[out] value_name is the value of the next variable found void GetFirstExtVar(HTML_Element **last_found, const uni_char **out_name, const uni_char **out_value) { LocalGetNextVariable(last_found, out_name, out_value, TRUE, FALSE); } /// Searching for the next external (POSTVAR) variable for the task. ///\param[out] last_found is an iterator returned by GetFirstExtVar() ///\param[out] out_name is the name of the next variable found, NULL if none found ///\param[out] value_name is the value of the next variable found void GetNextExtVar(HTML_Element **last_found, const uni_char **out_name, const uni_char **out_value) { LocalGetNextVariable(last_found, out_name, out_value, FALSE, FALSE); } const uni_char* GetName(); /// Returns the element associated with the task. HTML_Element* GetHElm() { return GetElm(); } /// @See ElementRef::OnDelete(). virtual void OnDelete(FramesDocument *document); /// @See ElementRef::OnRemove(). virtual void OnRemove(FramesDocument *document) { OnDelete(document); } }; /// The class for mapping elements to WML tasks. /// Several elements can map to the same task. For instance all the child elements in a DO element /// will trigger the same task. class WMLTaskMapElm : public ListElement<WMLTaskMapElm> , public ElementRef { private: WMLNewTaskElm *m_task; ///< The associated WML task public: WMLTaskMapElm(WMLNewTaskElm *new_task, HTML_Element *new_he) : ElementRef(new_he), m_task(new_task) {} WMLTaskMapElm(WMLTaskMapElm *src_task_map); ///< Copy constructor ~WMLTaskMapElm() {} /// Returns TRUE if this WMLTaskMapElm is associated with the element he. \param[in] he Element to check BOOL BelongsTo(HTML_Element *he) { return he == GetElm(); } HTML_Element* GetHElm() { return GetElm(); } WMLNewTaskElm* GetTask() { return m_task; } ///< Returns the associated WML task void SetTask(WMLNewTaskElm *new_task) { m_task = new_task; } /// @See ElementRef::OnDelete(). virtual void OnDelete(FramesDocument *document); /// @See ElementRef::OnRemove(). virtual void OnRemove(FramesDocument *document) { OnDelete(document); } }; /// The WML lexical lookup tool. /// Used primarily by the parser to convert between strings and internal codes for elements and attributes. class WML_Lex { public: /// Returns the numeric code corresponding to the event evt. ///\param[in] evt Nul terminated name of event static WML_EventType GetEventType(const uni_char *evt); }; //----------------------------------------------------------- // class for easy manipulation of internal lists and status //----------------------------------------------------------- class WMLStats { public: WMLStats(int first_in_stssion); ~WMLStats(); /// Copies the contents of src_stats to this stat. Usually without the tasks ///\param[in] src_stats. Stat block that this stat will receive the contents of ///\param[in] merge_active_vars. Merge the variables of the active task to this task ///\param[in] include_tasks. Copy the tasks from src_stats as well OP_STATUS Copy(WMLStats *src_stats, BOOL merge_active_vars, BOOL include_tasks); void RemoveReferencesToTask(WMLNewTaskElm *task, WML_Context *context); UINT32 m_status; ///< WML status bitfield. Uses values from the WS_* values BOOL m_variables_changed; ///< TRUE if any variables have changed int m_first_in_session; ///< History number of the first WML page on the current site AutoDeleteList<WMLVariableElm>* m_var_list; ///< List of the current WML variables. AutoDeleteList<WMLVariableElm>* m_active_vars; ///< List of variables that will be merged when navigation is successful AutoDeleteList<WMLNewTaskElm>* m_task_list; ///< List of the current WML tasks AutoDeleteList<WMLTaskMapElm>* m_task_map_list; ///< List of bindings between HTML_Elements and tasks in the task list WMLNewTaskElm** m_event_handlers; ///< List of event handler tasks WMLVariableElm* m_timer_val; ///< The WML variable holding the timer value }; //----------------------------------------------------------- // the WML context class //----------------------------------------------------------- class WML_Context : public MessageObject { private: WMLStats* m_old_stats; ///< stats of the previous card during navigation to another card WMLStats* m_tmp_stats; ///< store stats before first card if we haven't found target yet WMLStats* m_current_stats; // stats of the current card BOOL m_preparse_called; ///< TRUE if PreParse() has been called since the last call to PostParse() BOOL m_postparse_called; ///< TRUE if PostParse() has been called since the last call to PreParse() DocumentManager* m_doc_manager; uni_char* m_substitute_buffer; ///< buffer used to store results of a variable substitution int m_substitute_buffer_len; ///< length of the buffer above AutoNullElementRef m_pending_current_card; ///< Card that will be current if navigation succeeds UINT m_refs; ///< number of references to this context. can be deleted only when 0 OP_STATUS SetCurrentCard(); ///< Prepare the current card for display public: WML_Context(DocumentManager *dm = NULL); ~WML_Context(); OP_STATUS Init(); ///< Secondary constructor static BOOL IsHtmlElement(WML_ElementType type); static BOOL IsWmlAttribute(WML_AttrType type); static BOOL IsHtmlAttribute(WML_AttrType type); static BOOL NeedSubstitution(const uni_char *s, size_t s_len); int SubstituteVars(const uni_char *s, int s_len, uni_char *&tmp_buf, int len_tb, BOOL esc_by_default = FALSE, OutputConverter *converter = NULL); OP_STATUS GrowSubstituteBufferIfNeeded(uni_char*& buffer, int& length, int wanted_index); int GetFirstInSession() { return m_current_stats->m_first_in_session; } void SetFirstInSession(int new_first) { m_current_stats->m_first_in_session = new_first; } OP_STATUS SetNewContext(int new_first = -1); void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); AutoDeleteList<WMLVariableElm>* GetVarList() { return m_current_stats->m_var_list; } void RemoveTimer(BOOL delete_task); void StartTimer(BOOL start = TRUE); OP_STATUS SetTimer(const uni_char *name, const uni_char *time); OP_STATUS Copy(WML_Context *src_wc, DocumentManager* doc_man = NULL); OP_STATUS DenyAccess(); OP_STATUS PreParse(); OP_STATUS PostParse(); BOOL IsParsing() { return m_preparse_called && !m_postparse_called; } void ScrapTmpCurrentCard(); OP_STATUS PushTmpCurrentCard(); OP_STATUS RestartParsing(); AutoDeleteList<WMLVariableElm>* GetActiveVars() { return m_current_stats->m_active_vars; } OP_STATUS SetActiveTask(WMLNewTaskElm *new_active_task); WMLNewTaskElm* GetTaskByElement(HTML_Element *he); OP_STATUS SetTaskByElement(WMLNewTaskElm *new_task, HTML_Element *he); WMLNewTaskElm* GetEventHandler(WML_EventType event); OP_STATUS SetEventHandler(WML_EventType event, WMLNewTaskElm *handler); WMLNewTaskElm* NewTask(HTML_Element *task_he); void DeleteTask(WMLNewTaskElm *task); WMLNewTaskElm* GetTask(const uni_char *task_name); OP_STATUS PerformTask(WMLNewTaskElm *task, BOOL& noop, BOOL is_user_requested, WML_EventType event = WEVT_UNKNOWN); UINT32 GetStatus() { return m_current_stats->m_status; }; BOOL IsSet(UINT32 mask) { return (m_current_stats->m_status & mask) == mask; } void SetStatus(UINT32 new_status) { m_current_stats->m_status = new_status; } void SetStatusOn(UINT32 mask) { m_current_stats->m_status |= mask; } void SetStatusOff(UINT32 mask) { m_current_stats->m_status &= ~mask; } WMLVariableElm* SetVariable(const uni_char *name, const uni_char *value); const uni_char* GetVariable(const uni_char *name, int n_len = -1); URL GetWmlUrl(HTML_Element* he, UINT32* action = NULL, WML_EventType event = WEVT_UNKNOWN); OP_STATUS UpdateWmlSelection(HTML_Element* he, BOOL use_value); OP_STATUS UpdateWmlInput(HTML_Element* he, FormObject* form_obj); void SetInitialSelectValue(HTML_Element *select_elm); DocumentManager* GetDocManager() { return m_doc_manager; } HTML_Element* GetPendingCurrentCard() { return m_pending_current_card.GetElm(); } void SetPendingCurrentCard(HTML_Element *card) { m_pending_current_card.SetElm(card); } void IncRef() { m_refs++; } void DecRef(); }; #endif // _WML_SUPPORT_ #endif // _WML_H
#ifndef MINISERVER_CONNECTION_H #define MINISERVER_CONNECTION_H #include <string> #include "buffer.h" namespace miniserver{ class Connection { public: Connection(); virtual ~Connection(); // for prototype static Connection* newInstace(); static void initRootDir(const std::string &root_dir); static int getEpollfd(); static void setEpollfd(int epollfd); bool connectionClose(); bool connectionRead(); bool connectionWrite(); // for function process in threadpoll virtual void process() = 0; void setConnfd(int connfd); int getConnfd(); protected: // for protoatype static void _addPrototype(Connection *conn); static std::string& _getRootDir(); virtual Connection* _clone() = 0; // for prototype, return instance of subclass virtual bool _clear() = 0; // pass msg for subclass to process after close connectoin. bool _processDone(); bool _dumpRead(Buffer *other_buffer); // read/write buffter to other buffer bool _dumpWrite(Buffer *other_buffer); bool _dumpToRead(Buffer &other_buffer); // other buffer to read/write buffer bool _dumpToWrite(Buffer &other_buffer); private: static Connection* _prototype; static int _epollfd; static std::string _root_dir; Buffer _read_buffer; Buffer _write_buffer; int _connfd; void _reset(); }; } #endif
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define L 666666 #define N 111111 char pat[L]; char s[L]; int n, p[N], st[N], stn, pf[L], lr, ans = 0; vector<int> g[N]; void dfs(int x, int cpf) { for (int i = st[x]; s[i]; ++i) { while (cpf > 0 && pat[cpf] != s[i]) cpf = pf[cpf - 1]; if (pat[cpf] == s[i]) ++cpf;else cpf = 0; if (cpf == lr) { ++ans; } } for (size_t i = 0; i < g[x].size(); ++i) { dfs(g[x][i], cpf); } } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d", &n); stn = 1; st[1] = 0; for (int i = 2; i <= n; ++i) { scanf("%d %s\n", &p[i], s + stn); st[i] = stn; stn += strlen(s + stn) + 1; g[p[i]].push_back(i); } gets(pat); lr = strlen(pat); pf[0] = 0; for (int i = 1; i < lr; ++i) { int& k = pf[i] = pf[i - 1]; while (k > 0 && pat[k] != pat[i]) k = pf[k - 1]; if (pat[k] == pat[i]) ++k;else k = 0; } dfs(1, 0); cout << ans << endl; return 0; }
/************************************************************************/ /* File name : Decrypt.cpp */ /************************************************************************/ /* Contents : 復号化処理 (コールバック関数) */ /* */ /* Auther : Yasuhiro ARAKAWA Version 0.00 2000.09.12 */ /* Version 0.01 2000.09.14 */ /* Version 0.10 2000.09.27 */ /* Version 0.20 2000.10.03 */ /* Version 0.30 2000.10.08 */ /* Version 1.0.0 2000.11.08 */ /* Modified : Yasuhiro ARAKAWA, hex */ /* Version 1.0.4 2003.05.01 */ /************************************************************************/ /**** Incude Files ****/ #include "BkGnuPGDef.h" #include "BkGnuPGInfo.h" #include "CallBacks.h" #include "MIMEMessage.h" #include "PassDialog.h" #include "ViewDialog.h" #include "LogFile.h" #include <string> #include <fstream> using namespace std; #include "debug.h" //最後に定義 /**** Internal Macro ****/ /**** Typedef ****/ /**** Prototyping ****/ static void ExecDecript(HWND hWnd, LPARAM lParam); static bool ExecGPG(HWND hWnd, LPARAM lParam, CGnuPGModule::EMODE mode, const char* ascPath, const char* txtPath); static bool GetMIMEMessage(CMIMEMessage* pTop, CGnuPGModule::EMODE mode, string& ascPath, string& msgPath); static char* GetMessage(char* lpStr, CGnuPGModule::EMODE& mode, string& ascPath, char* szCharSet); /*----------------------------------------------------------------------*/ /* Purpose : 復号化処理 (メニューからの呼び出し) */ /* Inputs : -- */ /* Ootput : なし */ /*----------------------------------------------------------------------*/ void WINAPI Decript(HWND hWnd, LPARAM lParam) { try { ExecDecript(hWnd, lParam); } catch(...) { FatalErrorMessage(hWnd, __FILE__, __LINE__); //致命的エラー内容を出力 } } /*----------------------------------------------------------------------*/ /* Purpose : 復号化処理 */ /* Inputs : -- */ /* Ootput : なし */ /*----------------------------------------------------------------------*/ static void ExecDecript(HWND hWnd, LPARAM lParam) { //入出力ファイル作成 string ascPath = g_Info.m_BkApi.GetTempFileName("asc"); string msgPath = g_Info.m_BkApi.GetTempFileName("msg"); RemoveFiles(ascPath); RemoveFiles(msgPath); // 現在のメールidを取得 LPCSTR mailid = NULL; mailid = g_Info.m_BkApi.GetCurrentMail(); //現在のメールからヘッダ部分を抜き出す? //char* lpSource = g_Info.m_BkApi.GetSource(NULL); //メール内容 (未デコード) を取り出す char* lpSource = g_Info.m_BkApi.GetSource(mailid); //メール内容 (未デコード) を取り出す if(lpSource==NULL) { ErrorMessage(hWnd, IDS_GPG_ERROR); return; } CMIMEMessage item; item.FromString(lpSource); g_Info.m_BkApi.Free(lpSource); //もう不要なのでfree //PGP/MIMEに関連するフィールドを探す CGnuPGModule::EMODE mode = CGnuPGModule::Decript; CMIMEMessage* pTop = item.FindCMIMEMessage("multipart", "signed"); if(pTop!=NULL) { //署名されたメール mode = CGnuPGModule::Verify; } else { //暗号化(PGP/MIME)されたメールか? pTop = item.FindCMIMEMessage("multipart", "encrypted"); } if(pTop!=NULL) { //署名(PGP/MIME)された,または暗号化(PGP/MIME)されたメール //署名/暗号化されたメッセージを取り出す if((GetMIMEMessage(pTop, mode, ascPath, msgPath))==false) { ErrorMessage(hWnd, IDS_GPG_ERROR); RemoveFiles(ascPath); //念の為の後始末 return; } //gpg処理 g_Info.m_PassPhrase = ""; if(mode==CGnuPGModule::Verify) { //署名検証 ExecGPG(hWnd, lParam, mode, ascPath.c_str(), msgPath.c_str()); } else if(mode==CGnuPGModule::Decript) { //復号化 if((ExecGPG(hWnd, lParam, mode, ascPath.c_str(), msgPath.c_str()))==true) { char* lpArea = FileToString(msgPath); if (lpArea!=NULL) { //Header string szData = "multipart/mixed;\r\n boundary=\""; szData += pTop->GetBoundary(); szData += "\"; \r\n"; pTop->SetHeader("Content-Type", szData.c_str()); //Content-Type を差し替える CMIMEMessage itemDecrypt; itemDecrypt.FromString(lpArea); g_Info.m_BkApi.Free(lpArea); pTop->ClearBody(); //ボディをクリア pTop->ClearChild(); //子パートをクリア //pTop->ClearNext(); //子パートをクリア pTop->AddChild(itemDecrypt); //子パートとしてセットする lpArea = item.ToString(); //g_Info.m_BkApi.SetText(-2, lpArea); // for debug g_Info.m_BkApi.SetSource("TEMP", lpArea); g_Info.m_BkApi.Free(lpArea); } } } else { //公開鍵のインポート? ExecGPG(hWnd, lParam, mode, ascPath.c_str(), NULL); } //後始末 g_Info.m_PassPhrase = ""; RemoveFiles(ascPath); RemoveFiles(msgPath); } else { //平文 (でももしかしたら署名・暗号化されてるかもしれない) char szMimeType[80]; char* lpData = g_Info.m_BkApi.GetText(szMimeType, 80); char* lpStr; if(strncmp(lpData, "-----BEGIN PGP ", 15) == 0) { //署名または暗号化されている? lpStr = lpData; } else { //署名または暗号化されている部分がある? lpStr = strstr(lpData, "\n-----BEGIN PGP "); if(lpStr==NULL) { ErrorMessage(hWnd, IDS_GPG_ERROR); g_Info.m_BkApi.Free(lpData); return; } lpStr++; } char szCharSet[80]; g_Info.m_BkApi.GetCharSet(NULL, szCharSet, 80); //テキストのキャラクタセットを取得する g_Info.m_PassPhrase = ""; int count = 0; for(;;) { //PGPブロックを取得する char* lpNext = GetMessage(lpStr, mode, ascPath, szCharSet); if(lpNext==NULL) { //メッセージなし RemoveFiles(ascPath); //念の為の後始末 break; } //gpg処理 bool rtn; if(mode==CGnuPGModule::Verify) { //署名検証 rtn = ExecGPG(hWnd, lParam, mode, ascPath.c_str(), NULL); } else if(mode==CGnuPGModule::Decript) { //復号化 rtn = ExecGPG(hWnd, lParam, mode, ascPath.c_str(), msgPath.c_str()); if(rtn==true) { char* lpArea = FileToString(msgPath); if (lpArea!=NULL) { if (stricmp(szCharSet, "ISO-2022-JP") == 0) { char* lpSJIS = g_Info.m_BkApi.ISO_2022_JP(lpArea, FALSE); g_Info.m_BkApi.SetText(-2, lpSJIS); g_Info.m_BkApi.Free(lpSJIS); } else { g_Info.m_BkApi.SetText(-2, lpArea); } g_Info.m_BkApi.Free(lpArea); } } } else { //公開鍵のインポート? rtn = ExecGPG(hWnd, lParam, mode, ascPath.c_str(), NULL); } //後始末 RemoveFiles(ascPath); RemoveFiles(msgPath); count++; //後処理 if(rtn==false) { //正常終了しなかった(中止を含む) break; } //他にもPGPブロックがある? if(lpNext[0]=='\0') { //メッセージの終端 break; } lpStr = strstr(lpNext, "\n-----BEGIN PGP "); if(lpStr==NULL) { //これ以上はない break; } lpStr++; } g_Info.m_PassPhrase = ""; g_LogFile.AppendValue("number of Decryption and Verification", count); if(count==0) { ErrorMessage(hWnd, IDS_GPG_ERROR); } g_Info.m_BkApi.Free(lpData); } return; } /*----------------------------------------------------------------------*/ /* Purpose : 復号化処理 (メニューからの呼び出し) */ /* Inputs : 処理モード */ /* PGP署名/暗号化ブロック格納ファイル */ /* 検証テキスト格納ファイル */ /* Ootput : なし */ /*----------------------------------------------------------------------*/ static bool ExecGPG(HWND hWnd, LPARAM lParam, CGnuPGModule::EMODE mode, const char* ascPath, const char* msgPath) { g_Info.m_UserID = ""; //ユーザIDは空白にしておく if(mode==CGnuPGModule::Decript && (g_Info.m_PassPhrase.length())==0) { //復号化を行う かつ パスワード未設定 CPassPhraseDialog dlg; //PassPhrase ダイアログ if((dlg.ExecDialog(hWnd, lParam, g_Info, true))==false) { return false; } } bool rtn; switch(mode) { case CGnuPGModule::Verify: rtn = g_Info.m_GPG.ExecVerify(ascPath, msgPath); break; case CGnuPGModule::Decript: rtn = g_Info.m_GPG.ExecDecrypt(ascPath, msgPath, g_Info.m_PassPhrase.c_str(), g_Info.m_bUseAgent); break; case CGnuPGModule::ImpPubKey: default : rtn = g_Info.m_GPG.ExecImport(ascPath); break; } if(rtn==false) { ErrorMessage(hWnd, IDS_GPG_NOTPROCESSED); return false; } CViewDialog vdlg; vdlg.ExecDialog(hWnd, lParam, g_Info, g_Info.m_GPG.GetOutputMsg()); return true; } /*----------------------------------------------------------------------*/ /* Purpose : 暗号化メッセージ(PGP/MIME)の取り出し */ /* Inputs : メールメッセージ (Top) */ /* 処理モード */ /* PGP署名/暗号化ブロック格納ファイル */ /* 検証テキスト格納ファイル */ /* Ootput : Boolearn */ /*----------------------------------------------------------------------*/ static bool GetMIMEMessage(CMIMEMessage* pTop, CGnuPGModule::EMODE mode, string& ascPath, string& msgPath) { if(pTop==NULL) { return false; } if(mode==CGnuPGModule::Verify) { //署名(PGP/MIME)されたメールとして処理 //署名パートを探す CMIMEMessage* pSign = pTop->FindCMIMEMessage("application", "pgp-signature"); if(pSign==NULL) { //署名パートがない g_LogFile.AppendMessage("CMIMEMessage::FindCMIMEMessage(): 署名パートがありませんでした"); return false; } //署名パートを格納する ofstream ascFile(ascPath.c_str(), ios_base::binary); if((ascFile.is_open())==false) { g_LogFile.AppendValue("ファイルオープンエラー", ascPath); return false; } char* lpSign = pSign->ToString(); char* lpPGP = strstr(lpSign, "-----BEGIN PGP "); //PGP署名(?)ブロックを格納 if (lpPGP==NULL) { g_LogFile.AppendMessage("PGP署名ブロックがありませんでした"); g_Info.m_BkApi.Free(lpSign); return false; } ascFile << lpPGP; ascFile.close(); g_Info.m_BkApi.Free(lpSign); //被署名パートを探す CMIMEMessage* pContent = pTop->GetChild(); while (stricmp(pContent->GetSubType().c_str(), "pgp-signature") == 0 && pContent) { pContent = pContent->GetNext(); } if(pContent==NULL) { //被署名パートがなかった g_LogFile.AppendMessage("被署名パートがありませんでした"); return false; } //被署名パートを格納する ofstream msgFile(msgPath.c_str(), ios_base::binary); if((msgFile.is_open())==false) { g_LogFile.AppendValue("ファイルオープンエラー", msgPath); return false; } char* lpBody = pContent->ToString(); msgFile << lpBody; msgFile.close(); g_Info.m_BkApi.Free(lpBody); } else { //(多分)暗号化(PGP/MIME)されたメール //暗号化されたパートを探す CMIMEMessage* pContent = pTop->FindCMIMEMessage("application", "octet-stream"); if(pContent==NULL) { //暗号化されたパートがない g_LogFile.AppendMessage("暗号化されたパートがありませんでした"); return false; } //暗号化されたブロックを格納 ofstream ascFile(ascPath.c_str(), ios_base::binary); if((ascFile.is_open())==false) { g_LogFile.AppendValue("ファイルオープンエラー", ascPath); return false; } char* lpContent = pContent->ToString(); if(lpContent==NULL) { g_LogFile.AppendMessage("暗号化されたパートがありませんでした"); return false; } char* lpPGP = strstr(lpContent, "-----BEGIN PGP "); if(lpPGP==NULL) { g_LogFile.AppendMessage("暗号化されたブロックがありませんでした"); g_Info.m_BkApi.Free(lpContent); return false; } ascFile << lpPGP; ascFile.close(); g_Info.m_BkApi.Free(lpContent); } return true; } /*----------------------------------------------------------------------*/ /* Purpose : 暗号化メッセージの取り出し */ /* Inputs : メールメッセージ (本文) */ /* 処理モード(Out) */ /* PGP署名/暗号化ブロック格納ファイル */ /* キャラクタセット */ /* Ootput : 次のメッセージ */ /*----------------------------------------------------------------------*/ static char* GetMessage(char* lpStr, CGnuPGModule::EMODE& mode, string& ascPath, char* szCharSet) { //署名/暗号ブロックの種類を調べる if(strncmp(lpStr, "-----BEGIN PGP PUBLIC KEY BLOCK-----", 36) == 0) { //公開鍵 mode = CGnuPGModule::ImpPubKey; } else if(strncmp(lpStr, "-----BEGIN PGP SIGNED MESSAGE-----",34) == 0) { //署名 mode = CGnuPGModule::Verify; } else { mode = CGnuPGModule::Decript; } //PGPブロックの終わりを探す char* lpEnd = strstr(lpStr, "\n-----END PGP "); if(lpEnd==NULL) { //終わりの部分がなかった g_LogFile.AppendMessage("不完全なブロック"); return NULL; } //行末を探す lpEnd++; char* lpTmp = strchr(lpEnd,'\n'); if(lpTmp!=NULL) { lpEnd = lpTmp; } else { lpEnd = strchr(lpEnd, '\0'); } //PGPブロックを格納する ofstream ascFile(ascPath.c_str(), ios_base::binary); if((ascFile.is_open())==false) { //ErrorMessage(hWnd, IDS_GPG_FATALERROR); g_LogFile.AppendValue("ファイルオープンエラー", ascPath); return NULL; } int nLen = lpEnd - lpStr; if(stricmp(szCharSet, "ISO-2022-JP") == 0 || (szCharSet[0] == '\0' && GetACP() == 932)) { //日本語 char* lpTemp = new char[nLen + 4]; //数字に根拠はない? strncpy(lpTemp, lpStr, nLen); lpTemp[nLen] = '\0'; char* lpJIS = g_Info.m_BkApi.ISO_2022_JP(lpTemp, TRUE); //JISに変換する delete [] lpTemp; ascFile << lpJIS; g_Info.m_BkApi.Free(lpJIS); } else { ascFile << lpStr; } ascFile.close(); return lpEnd; } /* Copyright (C) Yasuhiro ARAKAWA **************************************/
#include <iostream> #include <string> #include <windows.h> #include <mmsystem.h> #include <GL/glew.h> #include <GL/glut.h> #include <FreeImage.h> #include "GestioneModelli3d.h" #include "Palla.h" #include "Pavimento.h" #include "Camera.h" #include "GestioneTexture.h" #include "GestioneModelli3d.h" #include "SetBirilli.h" #include "Luce.h" #include "Parallelepipedo.h" #include "Audio.h" #include <fstream> #include <stdio.h> #include <string.h> #include <map> using std::string; using std::cout; using std::endl; GLint finestraPrincipale; GLint finestraDirezione; GLfloat As = 0.5; bool blend = false; bool zbuffer = false; static GLenum spinMode = GL_TRUE; static GLenum singleStep = GL_FALSE; GLfloat movimentoZ = 0.0; GLfloat muoviPallaLateralmente = 0.0; bool muoviDestra = false; bool muoviSinistra = false; bool muoviFlip = true; bool fermaCamera = false; GLfloat distanzaFermaCamera = -23; bool aumentaPotenza = false; float potenza = 0; int contaAumento = 0; int contaAudio = 0; float direzione = 0; bool aumenta = true; int contaSpazio = 0; bool aumentaVelocita = true; bool strike = false; GestioneModelli3d gestoreModelli3d(1); GestioneModelli3d gestoreModelli3dCopy(2); GestioneTexture gT; Parallelepipedo rettangoloDirezione(1.0, 0.1, 0.0); Parallelepipedo rettangoloPotenza(1.0, 0.1, 0.0); Palla palla(0.28); Pavimento pavimento(28.0, 4.0); Pavimento pavimentoAnteriore(1.0, 10.0); Pavimento muroDestro(28, 10); Pavimento muroSinistro(28.0, 10.0); Pavimento muroDietro(30, 4.0); Pavimento muroFrontale1(4.4, 3.4); Pavimento muroFrontale2(4.4, 3.4); Pavimento muroFrontale3(4.4, 3.4); Pavimento muroFrontale4(4.4, 3.4); Pavimento muroFrontale5(4.4, 3.4); Pavimento pannelloStrike(4, 3); Pavimento muroBirilli(4.4, 1); Pavimento televisore(1, 0.5); Pavimento muroFrontaleAlto(23.5, 5.0); Camera camera; SetBirilli birilli; SetBirilli birilli1; Luce luce; Audio *audio = new Audio(); void initObject() { rettangoloDirezione.setPosizione(Posizione(-2.2, 3, 0.0)); rettangoloPotenza.setPosizione(Posizione(1.2, 3, 0.0)); palla.setPosizione(Posizione(0, palla.getRaggio(), 0)); palla.setVisible(true); palla.setAvviata(false); palla.setRotate(0); muoviFlip = true; contaSpazio = 0; movimentoZ = 0; contaAudio = 0; fermaCamera = false; potenza = 0; muoviPallaLateralmente = 0; movimentoZ = 0; aumentaVelocita = true; birilli.calcolaBirilliCaduti(); } static void Key_v(void) { palla.cambiaTexture(); } static void Key_c(void) { birilli.cambiaTexture(); birilli1.cambiaTexture(); } static void Key_b(void) { blend = !blend; if (blend) { glEnable(GL_BLEND); // Turn Blending On glDisable(GL_DEPTH_TEST); // Turn Depth Testing Off } else { glDisable(GL_BLEND); // Turn Blending Off glEnable(GL_DEPTH_TEST); // Turn Depth Testing On } } static void Key_r(void) { //restart initObject(); } static void Key_space(void) { if (contaSpazio == 0) { muoviFlip = false; } else { aumentaPotenza = true; contaAumento++; } contaSpazio++; } static void Key_right(void) { if (!palla.isAvviata()) { muoviDestra = true; muoviSinistra = false; } } static void Key_left(void) { if (!palla.isAvviata()) { muoviDestra = false; muoviSinistra = true; } } static void KeyPressFunc(unsigned char Key, int x, int y) { switch (Key) { case 'C': case 'c': Key_c(); break; case 'v': case 'V': Key_v(); break; case 'r': case 'R': Key_r(); break; case 'b': case 'B': Key_b(); break; case 'z': if (As < 1.0) As += 0.05; else As = 1.0; break; case 'x': if (As > 0.0) As -= 0.05; else As = 0.0; break; case 'd': zbuffer = !zbuffer; if (zbuffer) { //glEnable(GL_BLEND); // Turn Blending On glDisable(GL_DEPTH_TEST); // Turn Depth Testing Off } else { //glDisable(GL_BLEND); // Turn Blending Off glEnable(GL_DEPTH_TEST); // Turn Depth Testing On } break; case ' ': Key_space(); break; case 27: // Escape key exit(1); } } static void KeyPressFuncUp(unsigned char Key, int x, int y) { switch (Key) { case ' ': if (contaSpazio > 1) { aumentaPotenza = false; palla.setAvviata(true); } break; } } static void SpecialKeyFunc(int Key, int x, int y) { switch (Key) { case GLUT_KEY_RIGHT: Key_right(); break; case GLUT_KEY_LEFT: Key_left(); break; } } static void keySpecialUp(int key, int x, int y) { switch (key) { case GLUT_KEY_LEFT: muoviSinistra = false; muoviDestra = false; break; case GLUT_KEY_RIGHT: muoviDestra = false; muoviSinistra = false; break; } } void initTexture() { palla.setIdTexture(7); pavimento.setIdTexture(16); pavimentoAnteriore.setIdTexture(17); muroFrontale1.setIdTexture(20); muroFrontale2.setIdTexture(19); muroFrontale3.setIdTexture(18); muroFrontale4.setIdTexture(19); muroFrontale5.setIdTexture(20); muroFrontaleAlto.setIdTexture(23); muroDestro.setIdTexture(15); muroSinistro.setIdTexture(15); muroDietro.setIdTexture(15); //muroBirilli.setIdTexture(40); //televisore.setIdTexture(45); pannelloStrike.setIdTexture(22); } void disegnaBarraDirezione() { glBegin(GL_QUADS); glColor3f(0, 1, 0); glVertex3f(0, 0, 0.01); glColor3f(1, 0, 0); glVertex3f(0.5, 0, 0.01); glColor3f(1, 0, 0); glVertex3f(0.5, rettangoloDirezione.getAltezza() - 0.01, 0.01); glColor3f(0, 1, 0); glVertex3f(0, rettangoloDirezione.getAltezza() - 0.01, 0.01); glEnd(); glColor3f(1, 1, 1); } void disegnaBarraPotenza() { glBegin(GL_QUADS); glColor3f(0, 1, 0); glVertex3f(0, 0, 0.01); glColor3f(1, 0, 0); glVertex3f(0.1, 0, 0.01); glColor3f(1, 0, 0); glVertex3f(0.1, rettangoloPotenza.getAltezza() - 0.01, 0.01); glColor3f(0, 1, 0); glVertex3f(0, rettangoloPotenza.getAltezza() - 0.01, 0.01); glEnd(); glColor3f(1, 1, 1); } void disegnaFlipDirezione() { glBegin(GL_TRIANGLES); /*glColor3f(0, 1, 0);*/ glVertex3f(0, 0, 0.01); /*glColor3f(1, 0, 0);*/ glVertex3f(0.1, 0, 0.01); /*glColor3f(1, 0, 0);*/ glVertex3f(0.05, 0.05, 0.01); glEnd(); //glColor3f(1, 1, 1); } void valutaDirezione() { if (direzione >= 0.5) { aumenta = false; } if (direzione <= -0.5) { aumenta = true; } } void disegnaLuce() { GLfloat light_position[] = {0, 2, 0, 1.0 }; glLightfv(GL_LIGHT0, GL_POSITION, light_position); GLfloat light_ambient[] = { 1.0, 1.0, 1.0, 1.0 }; glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); //GLfloat light_diffuse[] = { 1.0, 1.0, 0.0, 1.0 }; //glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse); GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 }; glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular); glEnable(GL_LIGHT0); } void disegnaCanalina() { float PI = 3.14; float step = 1.5;// How far is the next point i.e it should be small value glBegin(GL_LINE_STRIP); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, 34); for (float angle = 0.0f; angle <= 180; angle += step) { float rad = PI*angle / 180; float x = 0 + 0.3*cos(rad); float y = 0 + 0.3*sin(rad); glNormal3f(1.0f, 0.0f, 0.0f); for (int i = 0; i < pavimento.getLunghezza()+1; i++) { glColor3f(0.2, 0.2, 0.2); glVertex3f(x, y, i); } } glEnd(); glDisable(GL_TEXTURE_2D); glColor3f(1, 1, 1); } void disegnaSalone() { //muro frontale 1 glPushMatrix(); glTranslatef(pavimento.getLarghezza() / 2 - 8.6, 3, -pavimento.getLunghezza()); glRotatef(90, 0, 0, 1); glRotatef(-20, 0, 1, 0); muroFrontale1.disegna(); glPopMatrix(); glPushMatrix(); glTranslatef(-9, 0.5, -25); birilli1.reset(gestoreModelli3dCopy); glPopMatrix(); //muro frontale 2 glPushMatrix(); glTranslatef(pavimento.getLarghezza() / 2 - 4.2, 3, -pavimento.getLunghezza()); glRotatef(90, 0, 0, 1); glRotatef(-20, 0, 1, 0); muroFrontale2.disegna(); glPopMatrix(); glPushMatrix(); glTranslatef(-4.5, 0.5, -25); birilli1.reset(gestoreModelli3dCopy); glPopMatrix(); //muro frontale 3 //corsia principale glPushMatrix(); glTranslatef(pavimento.getLarghezza()/2 + 0.2, 3, -pavimento.getLunghezza()); glRotatef(90, 0, 0, 1); glRotatef(-20, 0, 1, 0); muroFrontale3.disegna(); glPopMatrix(); //muro frontale 4 glPushMatrix(); glTranslatef(pavimento.getLarghezza() / 2 + 4.6, 3, -pavimento.getLunghezza()); glRotatef(90, 0, 0, 1); glRotatef(-20, 0, 1, 0); muroFrontale4.disegna(); glPopMatrix(); glPushMatrix(); glTranslatef(4.5, 0.5, -25); birilli1.reset(gestoreModelli3dCopy); glPopMatrix(); //muro frontale 5 glPushMatrix(); glTranslatef(pavimento.getLarghezza() / 2 + 9, 3, -pavimento.getLunghezza()); glRotatef(90, 0, 0, 1); glRotatef(-20, 0, 1, 0); muroFrontale5.disegna(); glPopMatrix(); glPushMatrix(); glTranslatef(9, 0.5, -25); birilli1.reset(gestoreModelli3dCopy); glPopMatrix(); //muro frontale alto glPushMatrix(); glTranslatef(pavimento.getLarghezza() / 2 + 9.8, 7.2, -pavimento.getLunghezza()); //glRotatef(180, 0, 0, 1); glRotatef(90, 0, 0, 1); muroFrontaleAlto.disegna(); glPopMatrix(); //muro destro glPushMatrix(); glTranslated(pavimento.getLarghezza()*2.5+1.5, 4.5, -30); glRotatef(90, 1, 0, 0); glRotatef(90, 0, 1, 0); muroDestro.disegna(); glPopMatrix(); //muro sinistro glPushMatrix(); glTranslated(-pavimento.getLarghezza()*2.5-1.5, 4.5, -30); glRotatef(90, 1, 0, 0); glRotatef(90, 0, 1, 0); muroSinistro.disegna(); glPopMatrix(); //disegna pavimenti glPushMatrix(); glRotated(-90, 1.0, 0, 0); //metto il pavimento sul piano xz pavimento.disegna(); //prima canalina destra glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated(pavimento.getLarghezza() / 2 + 0.3, -0.01, 0); disegnaCanalina(); glPopMatrix(); //prima canalina sinistra glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated(-pavimento.getLarghezza() / 2 - 0.3, -0.01, 0); disegnaCanalina(); glPopMatrix(); //seconda canalina sinistra glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated((-pavimento.getLarghezza() / 2 - 0.3)*3, -0.01, 0); disegnaCanalina(); glPopMatrix(); //seconda canalina destra glPushMatrix(); glRotatef(-90, 1, 0, 0); glTranslated((pavimento.getLarghezza() / 2 + 0.3)*3, -0.01, 0); disegnaCanalina(); glPopMatrix(); glPushMatrix(); //1o pavimento a destra glTranslatef(pavimento.getLarghezza() + 0.6, 0, 0); pavimento.disegna(); glPushMatrix(); //2o pavimento a destra glTranslatef(pavimento.getLarghezza() + 0.6, 0, 0); pavimento.disegna(); glPopMatrix(); glPopMatrix(); glPushMatrix(); //1o pavimento a sinistra glTranslatef(-pavimento.getLarghezza() - 0.6, 0, 0); pavimento.disegna(); glPushMatrix(); //2o pavimento a sinistra glTranslatef(-pavimento.getLarghezza() - 0.6, 0, 0); pavimento.disegna(); glPopMatrix(); glPopMatrix(); glPopMatrix(); glPushMatrix(); //pavimentoAnteriore glTranslatef(0, 0, 1); glRotated(-90, 1, 0, 0); pavimentoAnteriore.disegna(); glPopMatrix(); } void disegnaPannelloVittoria() { glPushMatrix(); glTranslatef(2,0,-pavimento.getLunghezza()); glRotatef(90, 0, 0, 1); pannelloStrike.disegna(); glPopMatrix(); } void output(float x, float y, float z, float r, float g, float b, char* string, void* font) { glColor3f(r, g, b); glRasterPos3f(x, y, z); int len, i; len = (int)strlen(string); for (i = 0; i < len; i++) { glutBitmapCharacter(font, string[i]); } } void disegnaInput() { glPushMatrix(); glTranslated(rettangoloDirezione.getPosizione().getX(), rettangoloDirezione.getPosizione().getY(), rettangoloDirezione.getPosizione().getZ()); output(0.2, 0.12, 0, 1.0, 1.0, 1.0, "Direzione del tiro", GLUT_BITMAP_TIMES_ROMAN_24); output(0.0, -0.12, 0, 1.0, 1.0, 1.0, "1. Premi spazio per bloccare il flip in movimento", GLUT_BITMAP_HELVETICA_12); rettangoloDirezione.disegna(); glPopMatrix(); glPushMatrix(); glTranslated(rettangoloPotenza.getPosizione().getX(), rettangoloPotenza.getPosizione().getY(), rettangoloPotenza.getPosizione().getZ()); output(0.2, 0.12, 0, 1.0, 1.0, 1.0, "Potenza del tiro", GLUT_BITMAP_TIMES_ROMAN_24); output(0.0, -0.12, 0, 1.0, 1.0, 1.0, "2. Tieni premuto spazio per aumentare la potenza del tiro", GLUT_BITMAP_HELVETICA_12); rettangoloPotenza.disegna(); glPopMatrix(); glPushMatrix(); output(-1.2, 0.1, 0.6, 0.0, 0.0, 1.0, "<-- Usa le frecce direzionali per muovere la palla -->", GLUT_BITMAP_TIMES_ROMAN_24); glColor3f(1, 1, 1); glPopMatrix(); glPushMatrix(); output(-0.65, 0.1, 1.0, 0.0, 0.0, 1.0, "Premi il tasto R per ricominciare", GLUT_BITMAP_TIMES_ROMAN_24); glColor3f(1, 1, 1); glPopMatrix(); glPushMatrix(); output(2.0, 0.5, 1.0, 0.0, 0.0, 1.0, "Birilli Abbattuti:", GLUT_BITMAP_HELVETICA_18); char buffer[10] = { '\0' }; sprintf_s(buffer, "%d", birilli.getBirilliCaduti()); output(2.3, 0.4, 1.0, 0.0, 0.0, 1.0, buffer, GLUT_BITMAP_HELVETICA_18); output(2.4, 0.4, 1.0, 0.0, 0.0, 1.0, "/10", GLUT_BITMAP_HELVETICA_18); glColor3f(1, 1, 1); glPopMatrix(); glPushMatrix(); output(-2.5, 0.5, 1.0, 0.0, 0.0, 1.0, "Premi C per cambiare i birilli", GLUT_BITMAP_HELVETICA_18); output(-2.55, 0.35, 1.0, 0.0, 0.0, 1.0, "Premi V per cambiare la palla", GLUT_BITMAP_HELVETICA_18); glColor3f(1, 1, 1); glPopMatrix(); glPushMatrix(); glTranslated(rettangoloPotenza.getPosizione().getX(), rettangoloPotenza.getPosizione().getY(), rettangoloPotenza.getPosizione().getZ()); glScalef(potenza, 1, 1); disegnaBarraPotenza(); glPopMatrix(); glPushMatrix(); glTranslated(rettangoloDirezione.getPosizione().getX() + 0.5, rettangoloDirezione.getPosizione().getY(), rettangoloDirezione.getPosizione().getZ()); disegnaBarraDirezione(); //barra destra glPopMatrix(); glPushMatrix(); glTranslated(rettangoloDirezione.getPosizione().getX() + 0.5, rettangoloDirezione.getPosizione().getY() + 0.005, rettangoloDirezione.getPosizione().getZ()); glRotatef(180, 0, 1, 0); //barra sinistra disegnaBarraDirezione(); glPopMatrix(); glPushMatrix(); //se la voglio mettere sopra >> /*glTranslated(rettangoloDirezione.getPosizione().getX() + 0.45, rettangoloDirezione.getPosizione().getY() + 0.15, rettangoloDirezione.getPosizione().getZ()); glRotatef(180, 1, 0, 0);*/ //se la voglio mettere sotto >> glTranslated(rettangoloDirezione.getPosizione().getX() + 0.45 + direzione, rettangoloDirezione.getPosizione().getY() - 0.05, rettangoloDirezione.getPosizione().getZ()); if (muoviFlip) { valutaDirezione(); if (aumenta) { direzione += 0.01; } else { direzione -= 0.01; } } disegnaFlipDirezione(); glPopMatrix(); } void valutaPotenza() { if (aumentaVelocita) { movimentoZ += 0.001; } else { movimentoZ -= 0.00001 * (potenza/10000); } if (movimentoZ >= (potenza / 20)) { aumentaVelocita = false; } } void mainDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (palla.getPosizione().getZ() < distanzaFermaCamera) { fermaCamera = true; } if (strike) { disegnaPannelloVittoria(); } glLoadIdentity(); //senza movimento orizzontale della camera - quando fermo la camera, blocco la gluLookAt if (fermaCamera) { gluLookAt(camera.getEyeX(), camera.getEyeY(), camera.getEyeZ() + distanzaFermaCamera, camera.getCenterX(), camera.getCenterY(), camera.getCenterZ() + distanzaFermaCamera, camera.getUpX(), camera.getUpY(), camera.getUpZ()); } else { gluLookAt(camera.getEyeX(), camera.getEyeY(), camera.getEyeZ() + palla.getPosizione().getZ(), camera.getCenterX(), camera.getCenterY(), camera.getCenterZ() + palla.getPosizione().getZ(), camera.getUpX(), camera.getUpY(), camera. getUpZ()); } glPushMatrix(); glTranslatef(0, -1.5, 0); //mi serve per spostare palla e pavimento piu giu rispetto a y = 0; glColor4f(1.0f, 1.0f, 1.0f, 1); //disegnaLuce(); disegnaSalone(); glColor3f(1.0, 1.0, 1.0); glPushMatrix(); glTranslated(0, 0.5, -25); //porto i birilli infondo eh li posizioni sul pavimento (alzo di 0.5) birilli.reset(gestoreModelli3d); //disegna riflesso birilli /*glPushMatrix(); glTranslatef(0, -0.5, 0.2); glScalef(1, 0.01, 0.5); glRotated(90, 1, 0, 0); glColor3f(0.3, 0.3, 0.3); birilli.resetRiflesso(); glColor3f(1, 1, 1); glPopMatrix();*/ birilli.collisionePalla(palla); birilli.collisioneBirilli(); glPopMatrix(); if (!palla.isAvviata()) { disegnaInput(); } glPushMatrix(); glTranslated(palla.getPosizione().getX(), palla.getPosizione().getY(), palla.getPosizione().getZ()); palla.disegna(); //palla riflessa glPushMatrix(); glTranslatef(0, -palla.getRaggio(), 0); glScalef(0.8, 0.01, 1.2); glRotated(180, 1, 0, 0); glColor3f(0.3, 0.3, 0.3); palla.disegna(); glColor3f(1, 1, 1); glPopMatrix(); //seconda palla - specchio /*glPushMatrix(); glTranslatef(palla.getPosizione().getX(), -palla.getPosizione().getY()*2, palla.getPosizione().getZ()); glRotated(-90, 1, 0, 0); glColor4f(1.0f, 1.0f, 1.0f, As); palla.disegna(); glColor3f(1.0, 1.0, 1.0); glPopMatrix(); */ glPopMatrix(); if (palla.isAvviata()) { palla.setPotenza(potenza); birilli.setPotenza(potenza); if (palla.isInPista()) { palla.move(direzione / 50, 0, -movimentoZ); } else { if (palla.getPosizione().getX() < 0) { palla.move(+0.05, -0.0015, -movimentoZ); } else { palla.move(-0.05, -0.0015, -movimentoZ); } } } else { if (muoviDestra) { if (muoviPallaLateralmente < 1.25) { muoviPallaLateralmente += 0.1; palla.move(0.1, 0, 0); } } else if (muoviSinistra) { if (muoviPallaLateralmente > -1.25) { muoviPallaLateralmente -= 0.1; palla.move(-0.1, 0, 0); } } if (aumentaPotenza && potenza < 9.9) { potenza += 0.1; } } glPopMatrix(); glutSwapBuffers(); glutPostRedisplay(); // Request a re-draw for animation purposes } void myIdle() { birilli.calcolaBirilliCaduti(); if (birilli.getBirilliCaduti() == 10) { //audio->playAL(0); //audio->stopAL(3); strike = true; } if (palla.isAvviata()) { if (contaAudio == 0) { //PlaySound(TEXT("./suoni/palla.wav"), NULL, SND_ASYNC | SND_LOOP); //audio->playAsStream(3); contaAudio++; } valutaPotenza(); } if (birilli.getBirilliCaduti() != 0 && contaAudio == 1) { //PlaySound(TEXT("./suoni/birilli.wav"), NULL, SND_ASYNC); //audio->playAL(1); contaAudio++; } if (birilli.getBirilliCaduti() > 8 && contaAudio == 2) { //PlaySound(TEXT("./suoni/applausi.wav"), NULL, SND_ASYNC); //audio->playAL(0); contaAudio++; } if (!palla.isVisible()) { //PlaySound(NULL, 0, 0); //audio->stopAL(0); //audio->stopAL(1); //audio->stopAL(3); } glutPostRedisplay(); } void mainReshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0, 1.0, 1.0, -50.0); glMatrixMode(GL_MODELVIEW); } int myInit() { gT.caricaTexture(); initTexture(); initObject(); audio->initAL(); audio->playAsStream(4); //4 o 7 glEnable(GL_TEXTURE_2D); glDisable(GL_COLOR_MATERIAL); glClearColor(0.0f, 0.0f, 0.0f, 0.5f); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); // Blending Off glEnable(GL_DEPTH_TEST); // Depth Testing On glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(90, 1, 0.1, 100.0); glMatrixMode(GL_MODELVIEW); glClearColor(0.0, 0.0, 0.0, 0.0); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculation return TRUE; } static void ResizeMainWindow(int w, int h) { float aspectRatio; h = (h == 0) ? 1 : h; w = (w == 0) ? 1 : w; glViewport(0, 0, w, h); // View port uses whole window aspectRatio = (float)w / (float)h; //// Set up the projection view matrix (not very well!) glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(65.0, aspectRatio, 1.0, 3000.0); //gluLookAt(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ) //gluLookAt(0, 5, -110+palla.getPosizione().getZ(), 0, 0, 0, 0, 1, 1); //// Select the Modelview matrix glMatrixMode(GL_MODELVIEW); } void mainWindow() { finestraPrincipale = glutCreateWindow("Bowling 3d - Claudio Dema & Giuzio Riccardo"); glutFullScreen(); // per aprire la finestra a tutto schermo glutReshapeFunc(mainReshape); glutDisplayFunc(mainDisplay); glutReshapeFunc(ResizeMainWindow); glutKeyboardFunc(KeyPressFunc); glutKeyboardUpFunc(KeyPressFuncUp); glutSpecialFunc(SpecialKeyFunc); glutSpecialUpFunc(keySpecialUp); if (!myInit()) { cout << "Initialization failed" << endl; } } int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(1000, 800); //Main Window mainWindow(); GLenum err = glewInit(); if (GLEW_OK != err) { /* Problem: glewInit failed, something is seriously wrong. */ fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); } fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION)); glutIdleFunc(myIdle); glutMainLoop(); }
#pragma once #include <iberbar/Paper2d/Component.h> #include <iberbar/Paper2d/Component_Updatable.h> #include <iberbar/Paper2d/Component_HandleMouseInput.h> #include <iberbar/Paper2d/Component_HandleKeyboardInput.h> namespace iberbar { namespace Paper2d { template < typename TComponent > class TComponentSystem { public: TComponentSystem(); ~TComponentSystem(); public: void AddComponent( TComponent* pComponent ); template < typename... Ts > void ExecuteList( Ts&&... xs ); private: std::list<TComponent*> m_ComponentList; std::list<TComponent*> m_ComponentList_NewComing; }; class CComponent_HandleMouseInput; class CComponent_HandleKeyboardInput; struct UComponentMouseEventData; struct UComponentKeyboardEventData; void ExecuteComponent( CComponent_HandleMouseInput* pComponent, const UComponentMouseEventData* EventData ); void ExecuteComponent( CComponent_HandleKeyboardInput* pComponent, const UComponentKeyboardEventData* EventData ); class CComponentSystem_HandleMouseInput : public TComponentSystem< CComponent_HandleMouseInput > { public: void HandleMouse( const UComponentMouseEventData* EventData ); }; class CComponentSystem_HandleKeyboardInput : public TComponentSystem< CComponent_HandleKeyboardInput > { public: void HandleKeyboard( const UComponentKeyboardEventData* EventData ); }; } } template < typename TComponent > iberbar::Paper2d::TComponentSystem<TComponent>::TComponentSystem() : m_ComponentList() , m_ComponentList_NewComing() { } template < typename TComponent > iberbar::Paper2d::TComponentSystem<TComponent>::~TComponentSystem() { if ( m_ComponentList_NewComing.empty() == false ) { auto iter = m_ComponentList_NewComing.begin(); auto end = m_ComponentList_NewComing.end(); for ( ; iter != end; iter++ ) { UNKNOWN_SAFE_RELEASE_NULL( *iter ); } } if ( m_ComponentList.empty() == false ) { auto iter = m_ComponentList.begin(); auto end = m_ComponentList.end(); for ( ; iter != end; iter++ ) { UNKNOWN_SAFE_RELEASE_NULL( *iter ); } } m_ComponentList_NewComing.clear(); m_ComponentList.clear(); } template < typename TComponent > void iberbar::Paper2d::TComponentSystem<TComponent>::AddComponent( TComponent* pComponent ) { if ( pComponent == nullptr ) return; if ( m_ComponentList_NewComing.empty() == false ) { auto iter = m_ComponentList_NewComing.begin(); auto end = m_ComponentList_NewComing.end(); for ( ; iter != end; iter++ ) { if ( (*iter) == pComponent ) return; } } if ( m_ComponentList.empty() == false ) { auto iter = m_ComponentList.begin(); auto end = m_ComponentList.end(); for ( ; iter != end; iter++ ) { if ( (*iter) == pComponent ) return; } } pComponent->AddRef(); m_ComponentList_NewComing.push_back( pComponent ); } template < typename TComponent > template < typename... Ts > void iberbar::Paper2d::TComponentSystem<TComponent>::ExecuteList( Ts&&... xs ) { if ( m_ComponentList_NewComing.empty() == false ) { auto iter = m_ComponentList_NewComing.begin(); auto end = m_ComponentList_NewComing.end(); for ( ; iter != end; iter++ ) { m_ComponentList.push_back( (*iter) ); } m_ComponentList_NewComing.clear(); } if ( m_ComponentList.empty() == false ) { auto iter = m_ComponentList.begin(); auto end = m_ComponentList.end(); for ( ; iter != end; ) { if ( (*iter)->WillRemoveFromSystem() == true ) { UNKNOWN_SAFE_RELEASE_NULL( *iter ); iter = m_ComponentList.erase( iter ); } else { if ( (*iter)->IsEnable() ) { ExecuteComponent( *iter, std::forward<Ts>( xs )... ); //(*iter)->Update( nDelta ); } iter++; } } } } FORCEINLINE void iberbar::Paper2d::CComponentSystem_HandleMouseInput::HandleMouse( const UComponentMouseEventData* EventData ) { ExecuteList( EventData ); } FORCEINLINE void iberbar::Paper2d::ExecuteComponent( CComponent_HandleMouseInput* pComponent, const UComponentMouseEventData* EventData ) { pComponent->OnMouseEvent( EventData ); } FORCEINLINE void iberbar::Paper2d::CComponentSystem_HandleKeyboardInput::HandleKeyboard( const UComponentKeyboardEventData* EventData ) { ExecuteList( EventData ); } FORCEINLINE void iberbar::Paper2d::ExecuteComponent( CComponent_HandleKeyboardInput* pComponent, const UComponentKeyboardEventData* EventData ) { pComponent->OnKeyboardEvent( EventData ); }
#include "ETableManager.h" #include "EEntityTable.h" #include "ERender2DComponentTable.h" DEFINITION_SINGLE(ETableManager) ETableManager::ETableManager() : SystemBase() { } ETableManager::~ETableManager() { } // Job = 0, // Entity = 1, // Input = 2, // Movement = 3, // Network = 4, // Render2D = 5, // Timer = 6, // UnitController = 7, // World = 8, // GameMode = 9, // Collision = 10, // UnitStatus = 11 bool ETableManager::LoadTableFromFile() { //**************************************************************************************************// // 엔티티 로드 // //**************************************************************************************************// // 1 EntityDTRecord RenderTarget_Record; RenderTarget_Record.m_NumSubEntity = 0; RenderTarget_Record.m_NumComponent = 3; RenderTarget_Record.m_vComponentDTID.push_back(RenderBase_2DRenderCompDTID); RenderTarget_Record.m_vComponentDTID.push_back(AlphaBase_2DRenderCompDTID); RenderTarget_Record.m_vComponentDTID.push_back(FadeBase_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(RenderTarget_EntityDTID, RenderTarget_Record)); // 2 EntityDTRecord LobbyHUD_Record; LobbyHUD_Record.m_NumSubEntity = 0; LobbyHUD_Record.m_NumComponent = 1; LobbyHUD_Record.m_vComponentDTID.push_back(Lobby_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(LobbyHUD_EntityDTID, LobbyHUD_Record)); // 3 EntityDTRecord PlayHUD_Record; PlayHUD_Record.m_NumSubEntity = 0; PlayHUD_Record.m_NumComponent = 5; PlayHUD_Record.m_vComponentDTID.push_back(Press_2DRenderCompID); PlayHUD_Record.m_vComponentDTID.push_back(Ready_2DRenderCompID); PlayHUD_Record.m_vComponentDTID.push_back(Start_2DRenderCompID); PlayHUD_Record.m_vComponentDTID.push_back(Pause_2DRenderCompID); PlayHUD_Record.m_vComponentDTID.push_back(Clear_2DRenderCompID); m_mapEntityTable.insert(make_pair(PlayHUD_EntityDTID, PlayHUD_Record)); // 4 EntityDTRecord Playe_Record; Playe_Record.m_NumSubEntity = 0; Playe_Record.m_NumComponent = 1; Playe_Record.m_vComponentDTID.push_back(Player_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(Player_EntityDTID, Playe_Record)); // 5 EntityDTRecord Enemy_Record; Enemy_Record.m_NumSubEntity = 0; Enemy_Record.m_NumComponent = 1; Enemy_Record.m_vComponentDTID.push_back(Enemy_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(Enemy_EntityDTID, Enemy_Record)); // 6 EntityDTRecord Bullet_Record; Bullet_Record.m_NumSubEntity = 0; Bullet_Record.m_NumComponent = 1; Bullet_Record.m_vComponentDTID.push_back(Bullet_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(Bullet_EntityDTID, Bullet_Record)); // 7 EntityDTRecord Explode_Record; Explode_Record.m_NumSubEntity = 0; Explode_Record.m_NumComponent = 1; Explode_Record.m_vComponentDTID.push_back(Explode_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(Explode_EntityDTID, Explode_Record)); // 8 EntityDTRecord BG_1_Record; BG_1_Record.m_NumSubEntity = 0; BG_1_Record.m_NumComponent = 1; BG_1_Record.m_vComponentDTID.push_back(BG_1_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(BG_1_EntityDTID, BG_1_Record)); // 9 EntityDTRecord BG_2_Record; BG_2_Record.m_NumSubEntity = 0; BG_2_Record.m_NumComponent = 1; BG_2_Record.m_vComponentDTID.push_back(BG_2_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(BG_2_EntityDTID, BG_2_Record)); // 10 EntityDTRecord BG_3_Record; BG_3_Record.m_NumSubEntity = 0; BG_3_Record.m_NumComponent = 1; BG_3_Record.m_vComponentDTID.push_back(BG_3_2DRenderCompDTID); m_mapEntityTable.insert(make_pair(BG_3_EntityDTID, BG_3_Record)); //**************************************************************************************************// // 컴포넌트 로드 // //**************************************************************************************************// // 1 Render2DComponentDTRecord RanderBase__Render2DComponentRecord; RanderBase__Render2DComponentRecord.m_2DTextrueFilePath = RanderBase_BmpPath; m_mapRender2DComponentTable.insert(make_pair(RenderBase_2DRenderCompDTID, RanderBase__Render2DComponentRecord)); // 2 Render2DComponentDTRecord AlphaBase_Render2DComponentRecord; AlphaBase_Render2DComponentRecord.m_2DTextrueFilePath = AlphaBase_BmpPath; m_mapRender2DComponentTable.insert(make_pair(AlphaBase_2DRenderCompDTID, AlphaBase_Render2DComponentRecord)); // 3 Render2DComponentDTRecord FadeBase_Render2DComponentRecord; FadeBase_Render2DComponentRecord.m_2DTextrueFilePath = Fade_BmpPath; m_mapRender2DComponentTable.insert(make_pair(FadeBase_2DRenderCompDTID, FadeBase_Render2DComponentRecord)); // 4 Render2DComponentDTRecord Lobby_Render2DComponentRecord; Lobby_Render2DComponentRecord.m_2DTextrueFilePath = LobbyBmpPath; m_mapRender2DComponentTable.insert(make_pair(Lobby_2DRenderCompDTID, Lobby_Render2DComponentRecord)); // 5 Render2DComponentDTRecord Press_Render2DComponentRecord; Press_Render2DComponentRecord.m_2DTextrueFilePath = PressBmpPath; m_mapRender2DComponentTable.insert(make_pair(Press_2DRenderCompID, Press_Render2DComponentRecord)); // 6 Render2DComponentDTRecord Ready_Render2DComponentRecord; Ready_Render2DComponentRecord.m_2DTextrueFilePath = ReadyBmpPath; m_mapRender2DComponentTable.insert(make_pair(Ready_2DRenderCompID, Ready_Render2DComponentRecord)); // 7 Render2DComponentDTRecord Start_Render2DComponentRecord; Start_Render2DComponentRecord.m_2DTextrueFilePath = StartBmpPath; m_mapRender2DComponentTable.insert(make_pair(Start_2DRenderCompID, Start_Render2DComponentRecord)); // 8 Render2DComponentDTRecord Pause_Render2DComponentRecord; Pause_Render2DComponentRecord.m_2DTextrueFilePath = PauseBmpPath; m_mapRender2DComponentTable.insert(make_pair(Pause_2DRenderCompID, Pause_Render2DComponentRecord)); // 9 Render2DComponentDTRecord Clear_Render2DComponentRecord; Clear_Render2DComponentRecord.m_2DTextrueFilePath = ClearBmpPath; m_mapRender2DComponentTable.insert(make_pair(Clear_2DRenderCompID, Clear_Render2DComponentRecord)); // 10 Render2DComponentDTRecord Player_Render2DComponentRecord; Player_Render2DComponentRecord.m_2DTextrueFilePath = Player_BmpPath; m_mapRender2DComponentTable.insert(make_pair(Player_2DRenderCompDTID, Player_Render2DComponentRecord)); // 11 Render2DComponentDTRecord Enemy_Render2DComponentRecord; Enemy_Render2DComponentRecord.m_2DTextrueFilePath = Enemy_BmpPath; m_mapRender2DComponentTable.insert(make_pair(Enemy_2DRenderCompDTID, Enemy_Render2DComponentRecord)); // 12 Render2DComponentDTRecord Bullet_Render2DComponentRecord; Bullet_Render2DComponentRecord.m_2DTextrueFilePath = Bullet_BmpPath; m_mapRender2DComponentTable.insert(make_pair(Bullet_2DRenderCompDTID, Bullet_Render2DComponentRecord)); // 13 Render2DComponentDTRecord Explode_Render2DComponentRecord; Explode_Render2DComponentRecord.m_2DTextrueFilePath = Explode_BmpPath; m_mapRender2DComponentTable.insert(make_pair(Explode_2DRenderCompDTID, Explode_Render2DComponentRecord)); // 14 Render2DComponentDTRecord BG_1_Render2DComponentRecord; BG_1_Render2DComponentRecord.m_2DTextrueFilePath = BG_1; m_mapRender2DComponentTable.insert(make_pair(BG_1_2DRenderCompDTID, BG_1_Render2DComponentRecord)); // 15 Render2DComponentDTRecord BG_2_Render2DComponentRecord; BG_2_Render2DComponentRecord.m_2DTextrueFilePath = BG_2; m_mapRender2DComponentTable.insert(make_pair(BG_2_2DRenderCompDTID, BG_2_Render2DComponentRecord)); // 16 Render2DComponentDTRecord BG_3_Render2DComponentRecord; BG_3_Render2DComponentRecord.m_2DTextrueFilePath = BG_3; m_mapRender2DComponentTable.insert(make_pair(BG_3_2DRenderCompDTID, BG_3_Render2DComponentRecord)); // unordered_map<LPCWCHAR, const _PlayerDataTableRecord *>::const_iterator iter = m_mapPlayerDataRecord.find(assetOwner->GetID()); // // // 다 뒤져도 해당 문자열로 등록된 키가 없다는 말이다. // if (iter == m_mapPlayerDataRecord.end()) // return nullptr; // // // End가 아니면 값을 찾은거다. // // 반복자는 찾은 노드를 포인팅하고 있다. // return iter->second; // TODO : 여기에 파일로부터 Talble 로드룰 추가하세요. // m_mapKey.insert(make_pair(m_pNewCreatedKey->strName, m_pNewCreatedKey)); // 삽입 return true; } void ETableManager::SetSystemOperationSlot() { } bool ETableManager::Init() { LoadTableFromFile(); return true; } LPCWCHAR ETableManager::GetFilePathByComponentDTID(int componentDTID) const { // unordered_map<LPCWCHAR, LPCWCHAR>::const_iterator iter = m_mapKey.find(strKey); // // 다 뒤져도 해당 문자열로 등록된 키가 없다는 말이다.! // if (iter == m_mapKey.end()) // return nullptr; // return iter->second; unordered_map<uint32, Render2DComponentDTRecord>::const_iterator iter = m_mapRender2DComponentTable.find(componentDTID); // 찾는 요소가 없으면 null반환 if (iter == m_mapRender2DComponentTable.end()) return nullptr; // End가 아니면 값을 찾은거다. // 반복자는 찾은 노드를 포인팅하고 있다. return iter->second.m_2DTextrueFilePath; }
#include <iostream> #include <vector> #include <list> #include <queue> #include <algorithm> #include <iomanip> #include <map> #include <string> #include <cstdio> #include <cstring> #include <climits> using namespace std; int perfect, minSend = INT_MAX, minBack = INT_MAX; struct Edge { int from, to, time; Edge(int f, int t, int ti):from(f), to(t), time(ti) {} Edge(){} }; struct Node { int u, time; Node(int u, int t):u(u), time(t) {} Node() {} bool operator< (const Node& rhs) const { return time > rhs.time; } }; vector<vector<Edge> > graph; vector<vector<int> > path; vector<int> dist; vector<int> collect; vector<bool> visited; vector<int> temppath; vector<int> respath; void dijkstra(int s) { fill(dist.begin(), dist.end(), INT_MAX); fill(visited.begin(), visited.end(), false); priority_queue<Node> q; dist[s] = 0; q.push(Node(s, 0)); while (!q.empty()) { Node node = q.top(); q.pop(); if (visited[node.u]) continue; visited[node.u] = true; for (auto e = graph[node.u].begin(); e != graph[node.u].end(); e++) { if (dist[e->to] > dist[node.u] + e->time) { dist[e->to] = dist[node.u] + e->time; path[e->to].clear(); path[e->to].push_back(node.u); q.push(Node(e->to, dist[e->to])); } else if (dist[e->to] == dist[node.u] + e->time) { path[e->to].push_back(node.u); } } } } void dfs(int d) { if (d == 0) { //temppath.push_back(d); int send = 0, back = 0; for (auto it = temppath.rbegin(); it != temppath.rend(); it++) { if (collect[*it] > perfect) { back += collect[*it] - perfect; } else if (collect[*it] < perfect) { if (back + collect[*it] < perfect) { send += perfect - collect[*it] - back; back = 0; } else { back -= perfect - collect[*it]; } } } if ((send < minSend) || (send == minSend && back < minBack)) { minSend = send; minBack = back; respath = temppath; } //temppath.pop_back(); return; } temppath.push_back(d); for (auto it = path[d].begin(); it != path[d].end(); it++) dfs(*it); temppath.pop_back(); } int main() { int cmax, n, sp, m; int from, to, time; cin >> cmax >> n >> sp >> m; perfect = cmax / 2; graph.resize(n + 1); path.resize(n + 1); dist.resize(n + 1); collect.resize(n + 1); visited.resize(n + 1); for (int i = 1; i <= n; i++) cin >> collect[i]; while (m--) { cin >> from >> to >> time; graph[from].push_back(Edge(from, to, time)); graph[to].push_back(Edge(to, from, time)); } dijkstra(0); dfs(sp); cout << minSend << " 0"; for (auto it = respath.rbegin(); it != respath.rend(); it++) { cout << "->" << *it; } cout << " " << minBack << endl; return 0; }
#include <chuffed/core/propagator.h> // y = |ub(x) - lb(y) + 1| class RangeSize : public Propagator { public: IntVar* x; IntVar* y; RangeSize(IntVar* _x, IntVar* _y) : x(_x), y(_y) { priority = 1; x->attach(this, 0, EVENT_LU); } bool propagate() override { if (y->getMin() < 1) { setDom((*y), setMin, 1, y->getMinLit()); } setDom((*y), setMax, x->getMax() - x->getMin() + 1, x->getMinLit(), x->getMaxLit()); return true; } }; void range_size(IntVar* x, IntVar* y) { new RangeSize(x, y); } template <class Var, class Val> class LastVal : public Propagator { public: Var* x; Val* v; LastVal(Var* _x, Val* _v) : x(_x), v(_v) { priority = 0; x->attach(this, 0, EVENT_F); } void wakeup(int i, int c) override { assert(x->isFixed()); pushInQueue(); } bool propagate() override { (*v) = x->getVal(); return true; } }; void last_val(IntVar* x, int* v) { new LastVal<IntVar, int>(x, v); } void last_val(BoolView* x, bool* v) { new LastVal<BoolView, bool>(x, v); } class Complete : public Propagator { public: BoolView x; bool* v; Complete(BoolView _x, bool* _v) : x(std::move(_x)), v(_v) { priority = 0; x.attach(this, 0, EVENT_F); } void wakeup(int i, int c) override { assert(x.isFixed()); pushInQueue(); } bool propagate() override { if (x.isTrue()) { (*v) = true; } return true; } }; void mark_complete(BoolView x, bool* v) { new Complete(x, v); }
#include <bitset> #include <iostream> #include <map> #include <string> std::bitset<21> bit; void add() { int x; std::cin >> x; bit.set(x); } void remove() { int x; std::cin >> x; bit.reset(x); } void check() { int x; std::cin >> x; std::cout << bit.test(x) << '\n'; } void toggle() { int x; std::cin >> x; bit.flip(x); } void all() { bit.set(); } void empty() { bit.reset(); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int m; std::cin >> m; while (m--) { std::string s; std::cin >> s; static std::map<std::string, void (*)()> func = { { "add", add }, { "remove", remove }, { "check", check }, { "toggle", toggle }, { "all", all }, { "empty", empty } }; func[s](); } return 0; }
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "KVBinaryOutputStreamSerializer.h" #include "KVBinaryCommon.h" #include <limits> #include <cassert> #include <stdexcept> #include <Common/StreamTools.h> using namespace common; using namespace cn; namespace { template <typename T> void writePod(IOutputStream& s, const T& value) { write(s, &value, sizeof(T)); } template<class T> size_t packVarint(IOutputStream& s, uint8_t type_or, size_t pv) { T v = static_cast<T>(pv << 2); v |= type_or; write(s, &v, sizeof(T)); return sizeof(T); } void writeElementName(IOutputStream& s, common::StringView name) { if (name.getSize() > std::numeric_limits<uint8_t>::max()) { throw std::runtime_error("Element name is too long"); } uint8_t len = static_cast<uint8_t>(name.getSize()); write(s, &len, sizeof(len)); write(s, name.getData(), len); } size_t writeArraySize(IOutputStream& s, size_t val) { if (val <= 63) { return packVarint<uint8_t>(s, PORTABLE_RAW_SIZE_MARK_BYTE, val); } else if (val <= 16383) { return packVarint<uint16_t>(s, PORTABLE_RAW_SIZE_MARK_WORD, val); } else if (val <= 1073741823) { return packVarint<uint32_t>(s, PORTABLE_RAW_SIZE_MARK_DWORD, val); } else { if (val > 4611686018427387903) { throw std::runtime_error("failed to pack varint - too big amount"); } return packVarint<uint64_t>(s, PORTABLE_RAW_SIZE_MARK_INT64, val); } } } namespace cn { KVBinaryOutputStreamSerializer::KVBinaryOutputStreamSerializer() { beginObject(std::string()); } void KVBinaryOutputStreamSerializer::dump(IOutputStream& target) { assert(m_objectsStack.size() == 1); assert(m_stack.size() == 1); KVBinaryStorageBlockHeader hdr; hdr.m_signature_a = PORTABLE_STORAGE_SIGNATUREA; hdr.m_signature_b = PORTABLE_STORAGE_SIGNATUREB; hdr.m_ver = PORTABLE_STORAGE_FORMAT_VER; common::write(target, &hdr, sizeof(hdr)); writeArraySize(target, m_stack.front().count); write(target, stream().data(), stream().size()); } ISerializer::SerializerType KVBinaryOutputStreamSerializer::type() const { return ISerializer::OUTPUT; } bool KVBinaryOutputStreamSerializer::beginObject(common::StringView name) { checkArrayPreamble(BIN_KV_SERIALIZE_TYPE_OBJECT); m_stack.push_back(Level(name)); m_objectsStack.push_back(MemoryStream()); return true; } void KVBinaryOutputStreamSerializer::endObject() { assert(m_objectsStack.size()); auto level = std::move(m_stack.back()); m_stack.pop_back(); auto objStream = std::move(m_objectsStack.back()); m_objectsStack.pop_back(); auto& out = stream(); writeElementPrefix(BIN_KV_SERIALIZE_TYPE_OBJECT, level.name); writeArraySize(out, level.count); write(out, objStream.data(), objStream.size()); } bool KVBinaryOutputStreamSerializer::beginArray(size_t& size, common::StringView name) { m_stack.push_back(Level(name, size)); return true; } void KVBinaryOutputStreamSerializer::endArray() { bool validArray = m_stack.back().state == State::Array; m_stack.pop_back(); if (m_stack.back().state == State::Object && validArray) { ++m_stack.back().count; } } bool KVBinaryOutputStreamSerializer::operator()(uint8_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_UINT8, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(uint16_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_UINT16, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(int16_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_INT16, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(uint32_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_UINT32, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(int32_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_INT32, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(int64_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_INT64, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(uint64_t& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_UINT64, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(bool& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_BOOL, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(double& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_DOUBLE, name); writePod(stream(), value); return true; } bool KVBinaryOutputStreamSerializer::operator()(std::string& value, common::StringView name) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_STRING, name); auto& out = stream(); writeArraySize(out, value.size()); write(out, value.data(), value.size()); return true; } bool KVBinaryOutputStreamSerializer::binary(void* value, size_t size, common::StringView name) { if (size > 0) { writeElementPrefix(BIN_KV_SERIALIZE_TYPE_STRING, name); auto& out = stream(); writeArraySize(out, size); write(out, value, size); } return true; } bool KVBinaryOutputStreamSerializer::binary(std::string& value, common::StringView name) { return binary(const_cast<char*>(value.data()), value.size(), name); } void KVBinaryOutputStreamSerializer::writeElementPrefix(uint8_t type, common::StringView name) { assert(m_stack.size()); checkArrayPreamble(type); Level& level = m_stack.back(); if (level.state != State::Array) { if (!name.isEmpty()) { auto& s = stream(); writeElementName(s, name); write(s, &type, 1); } ++level.count; } } void KVBinaryOutputStreamSerializer::checkArrayPreamble(uint8_t type) { if (m_stack.empty()) { return; } Level& level = m_stack.back(); if (level.state == State::ArrayPrefix) { auto& s = stream(); writeElementName(s, level.name); char c = BIN_KV_SERIALIZE_FLAG_ARRAY | type; write(s, &c, 1); writeArraySize(s, level.count); level.state = State::Array; } } MemoryStream& KVBinaryOutputStreamSerializer::stream() { assert(m_objectsStack.size()); return m_objectsStack.back(); } }
#include <string.h> #include <QString> #include <QMap> #include <QFormLayout> #include <QLineEdit> #include <QVariant> #include <QCheckBox> #include <QComboBox> #include <QDataStream> #include <QDebug> #include <QSizePolicy> #include "FormWidget.h" #include "FileChooserButton.h" FormWidget::FormWidget(QWidget* parent) : QWidget(parent) { formMap = new QMap<QString, FormFieldDescriptor*>; layout = new QFormLayout(); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum); setLayout(layout); } void FormWidget::addTextItem(QString name, QString label, QString defaultValue) { QLineEdit* inputField = new QLineEdit(this); inputField -> setText(defaultValue); connect(inputField, SIGNAL(textChanged(QString)), this, SIGNAL(formChanged())); FormFieldDescriptor* descriptor = (FormFieldDescriptor*) malloc(sizeof(FormFieldDescriptor)); descriptor -> type = TYPE_TEXT; descriptor -> field = inputField; layout -> addRow(label, inputField); formMap -> insert(name, descriptor); } void FormWidget::addBooleanItem(QString name, QString label, bool def) { QCheckBox* inputField = new QCheckBox(); connect(inputField, SIGNAL(stateChanged(int)), this, SIGNAL(formChanged())); FormFieldDescriptor* descriptor = (FormFieldDescriptor*) malloc(sizeof(FormFieldDescriptor)); if (def) { inputField -> setChecked(true); } descriptor -> type = TYPE_BOOLEAN; descriptor -> field = inputField; layout -> addRow(label, inputField); formMap -> insert(name, descriptor); } void FormWidget::addFileItem(QString name, QString label, QString defaultValue, int type) { FileChooserButton* inputField = new FileChooserButton("Browse...", this); inputField->setDefaultPath(defaultValue); inputField->setPath(defaultValue); inputField->setType(type); connect(inputField, SIGNAL(changed()), this, SIGNAL(formChanged())); FormFieldDescriptor* descriptor = (FormFieldDescriptor*) malloc(sizeof(FormFieldDescriptor)); descriptor -> type = TYPE_FILE; descriptor -> field = inputField; layout -> addRow(label, inputField); formMap -> insert(name, descriptor); } void FormWidget::addDropDownItem(QString name, QString label, QString defaultValue, QList<DropDownListEntry>* entries) { QComboBox* inputField = new QComboBox(this); connect(inputField, SIGNAL(currentIndexChanged(int)), this, SIGNAL(formChanged())); inputField -> addItem("---", ""); int defaultIndex = 0; for (int i = 0; i < entries -> length(); i++) { inputField -> addItem(((entries -> at(i)).label), QVariant(((entries -> at(i)).value))); if (defaultValue == (entries -> at(i)).value) { defaultIndex = i + 1; } } inputField -> setCurrentIndex(defaultIndex); FormFieldDescriptor* descriptor = (FormFieldDescriptor*) malloc(sizeof(FormFieldDescriptor)); descriptor -> type = TYPE_DROPDOWN; descriptor -> field = inputField; layout -> addRow(label, inputField); formMap -> insert(name, descriptor); } QMap<std::string, std::string>* FormWidget::getFormData() { QMap<std::string, std::string>* map = new QMap<std::string, std::string>; QMap<QString, FormFieldDescriptor*>::iterator iterator = formMap -> begin(); FormFieldDescriptor* descriptor; QString name; QString value; while (iterator != formMap -> end()) { name = iterator.key(); descriptor = iterator.value(); value = ""; QWidget* field = descriptor -> field; switch (descriptor -> type) { case FormWidget::TYPE_TEXT: value = ((QLineEdit*) field) -> text(); break; case FormWidget::TYPE_BOOLEAN: if (((QCheckBox*) field) -> isChecked()) value = "true"; else value = "false"; break; case FormWidget::TYPE_FILE: value = ((FileChooserButton*) field)->getFilePath(); break; case FormWidget::TYPE_DROPDOWN: value = (((QComboBox*) field) -> currentData()).toString(); break; } map -> insert( name.toStdString(), value.toStdString() ); iterator++; } return map; } FormWidget::~FormWidget() { delete formMap; }
// // Physics.h // NeheGL // // Created by Andong Li on 10/27/13. // Copyright (c) 2013 Andong Li. All rights reserved. // #ifndef NeheGL_Physics_h #define NeheGL_Physics_h #include <math.h> class Vector3D_PHY{ public: float x; float y; float z; Vector3D_PHY(){ x = 0; y = 0; z = 0; } Vector3D_PHY(float x, float y, float z){ this->x = x; this->y = y; this->z = z; } Vector3D_PHY& operator= (Vector3D_PHY v){ x = v.x; y = v.y; z = v.z; return *this; } Vector3D_PHY operator+ (Vector3D_PHY v){ return Vector3D_PHY(x + v.x, y + v.y, z + v.z); } Vector3D_PHY operator- (Vector3D_PHY v){ return Vector3D_PHY(x - v.x, y - v.y, z - v.z); } Vector3D_PHY operator* (float value){ return Vector3D_PHY(x * value, y * value, z * value); } Vector3D_PHY operator/ (float value){ return Vector3D_PHY(x / value, y / value, z / value); } Vector3D_PHY& operator+= (Vector3D_PHY v){ x += v.x; y += v.y; z += v.z; return *this; } Vector3D_PHY& operator-= (Vector3D_PHY v){ x -= v.x; y -= v.y; z -= v.z; return *this; } Vector3D_PHY& operator*= (float value){ x *= value; y *= value; z *= value; return *this; } Vector3D_PHY& operator/= (float value){ x /= value; y /= value; z /= value; return *this; } Vector3D_PHY operator- (){ return Vector3D_PHY(-x, -y, -z); } float length(){ return sqrtf(x*x + y*y + z*z); }; void unitize(){ float length = this->length(); if (length == 0) return; x /= length; y /= length; z /= length; } Vector3D_PHY unit(){ float length = this->length(); if (length == 0) return *this; return Vector3D_PHY(x / length, y / length, z / length); } }; class Mass_PHY{ public: float m; Vector3D_PHY pos; Vector3D_PHY vel; Vector3D_PHY force; Mass_PHY(float m){ this->m = m; } void applyForce(Vector3D_PHY force){ this->force += force; } void init(){ force.x = 0; force.y = 0; force.z = 0; } void simulate(float dt){ vel += (force / m) * dt; pos += vel * dt; } }; class Simulation_PHY{ public: int numOfMasses; Mass_PHY** masses; Simulation_PHY(int numOfMasses, float m){ this->numOfMasses = numOfMasses; masses = new Mass_PHY*[numOfMasses]; for (int a = 0; a < numOfMasses; ++a) masses[a] = new Mass_PHY(m); } virtual void release(){ for (int a = 0; a < numOfMasses; ++a){ delete(masses[a]); masses[a] = NULL; } delete(masses); masses = NULL; } Mass_PHY* getMass(int index){ if (index < 0 || index >= numOfMasses) return NULL; return masses[index]; } virtual void init(){ for (int a = 0; a < numOfMasses; ++a) masses[a]->init(); } virtual void solve(){ } virtual void simulate(float dt){ for (int a = 0; a < numOfMasses; ++a) masses[a]->simulate(dt); } virtual void operate(float dt){ init(); solve(); simulate(dt); } }; /* class ConstantVelocity is derived from class Simulation It creates 1 mass with mass value 1 kg and sets its velocity to (1.0f, 0.0f, 0.0f) so that the mass moves in the x direction with 1 m/s velocity. */ class ConstantVelocity : public Simulation_PHY{ public: //Constructor firstly constructs its super class with 1 mass and 1 kg ConstantVelocity() : Simulation_PHY(1, 1.0f){ masses[0]->pos = Vector3D_PHY(0.0f, 0.0f, 0.0f); masses[0]->vel = Vector3D_PHY(1.0f, 0.0f, 0.0f); } }; /* class MotionUnderGravitation is derived from class Simulation It creates 1 mass with mass value 1 kg and sets its velocity to (10.0f, 15.0f, 0.0f) and its position to (-10.0f, 0.0f, 0.0f). The purpose of this application is to apply a gravitational force to the mass and observe the path it follows. The above velocity and position provides a fine projectile path with a 9.81 m/s/s downward gravitational acceleration. 9.81 m/s/s is a very close value to the gravitational acceleration we experience on the earth. */ class MotionUnderGravitation : public Simulation_PHY{ public: Vector3D_PHY gravitation; MotionUnderGravitation(Vector3D_PHY gravitation) : Simulation_PHY(1, 1.0f){ this->gravitation = gravitation; masses[0]->pos = Vector3D_PHY(-10.0f, 0.0f, 0.0f); masses[0]->vel = Vector3D_PHY(10.0f, 15.0f, 0.0f); } virtual void solve(){ for (int a = 0; a < numOfMasses; ++a) masses[a]->applyForce(gravitation * masses[a]->m); } }; /* class MassConnectedWithSpring is derived from class Simulation It creates 1 mass with mass value 1 kg and binds the mass to an arbitrary constant point with a spring. This point is refered as the connectionPos and the spring has a springConstant value to represent its stiffness. */ class MassConnectedWithSpring : public Simulation_PHY{ public: float springConstant; Vector3D_PHY connectionPos; MassConnectedWithSpring(float springConstant) : Simulation_PHY(1, 1.0f){ this->springConstant = springConstant; connectionPos = Vector3D_PHY(0.0f, -5.0f, 0.0f); masses[0]->pos = connectionPos + Vector3D_PHY(10.0f, 0.0f, 0.0f); masses[0]->vel = Vector3D_PHY(0.0f, 0.0f, 0.0f); } virtual void solve(){ for (int a = 0; a < numOfMasses; ++a){ Vector3D_PHY springVector = masses[a]->pos - connectionPos; masses[a]->applyForce(-springVector * springConstant); } } }; #endif
#pragma once #include <aePrerequisitesUtil.h> namespace aeEngineSDK { typedef enum AEG_FORMAT { AEG_FORMAT_UNKNOWN = 0, AEG_FORMAT_R32G32B32A32_TYPELESS = 1, AEG_FORMAT_R32G32B32A32_FLOAT = 2, AEG_FORMAT_R32G32B32A32_UINT = 3, AEG_FORMAT_R32G32B32A32_SINT = 4, AEG_FORMAT_R32G32B32_TYPELESS = 5, AEG_FORMAT_R32G32B32_FLOAT = 6, AEG_FORMAT_R32G32B32_UINT = 7, AEG_FORMAT_R32G32B32_SINT = 8, AEG_FORMAT_R16G16B16A16_TYPELESS = 9, AEG_FORMAT_R16G16B16A16_FLOAT = 10, AEG_FORMAT_R16G16B16A16_UNORM = 11, AEG_FORMAT_R16G16B16A16_UINT = 12, AEG_FORMAT_R16G16B16A16_SNORM = 13, AEG_FORMAT_R16G16B16A16_SINT = 14, AEG_FORMAT_R32G32_TYPELESS = 15, AEG_FORMAT_R32G32_FLOAT = 16, AEG_FORMAT_R32G32_UINT = 17, AEG_FORMAT_R32G32_SINT = 18, AEG_FORMAT_R32G8X24_TYPELESS = 19, AEG_FORMAT_D32_FLOAT_S8X24_UINT = 20, AEG_FORMAT_R32_FLOAT_X8X24_TYPELESS = 21, AEG_FORMAT_X32_TYPELESS_G8X24_UINT = 22, AEG_FORMAT_R10G10B10A2_TYPELESS = 23, AEG_FORMAT_R10G10B10A2_UNORM = 24, AEG_FORMAT_R10G10B10A2_UINT = 25, AEG_FORMAT_R11G11B10_FLOAT = 26, AEG_FORMAT_R8G8B8A8_TYPELESS = 27, AEG_FORMAT_R8G8B8A8_UNORM = 28, AEG_FORMAT_R8G8B8A8_UNORM_SRGB = 29, AEG_FORMAT_R8G8B8A8_UINT = 30, AEG_FORMAT_R8G8B8A8_SNORM = 31, AEG_FORMAT_R8G8B8A8_SINT = 32, AEG_FORMAT_R16G16_TYPELESS = 33, AEG_FORMAT_R16G16_FLOAT = 34, AEG_FORMAT_R16G16_UNORM = 35, AEG_FORMAT_R16G16_UINT = 36, AEG_FORMAT_R16G16_SNORM = 37, AEG_FORMAT_R16G16_SINT = 38, AEG_FORMAT_R32_TYPELESS = 39, AEG_FORMAT_D32_FLOAT = 40, AEG_FORMAT_R32_FLOAT = 41, AEG_FORMAT_R32_UINT = 42, AEG_FORMAT_R32_SINT = 43, AEG_FORMAT_R24G8_TYPELESS = 44, AEG_FORMAT_D24_UNORM_S8_UINT = 45, AEG_FORMAT_R24_UNORM_X8_TYPELESS = 46, AEG_FORMAT_X24_TYPELESS_G8_UINT = 47, AEG_FORMAT_R8G8_TYPELESS = 48, AEG_FORMAT_R8G8_UNORM = 49, AEG_FORMAT_R8G8_UINT = 50, AEG_FORMAT_R8G8_SNORM = 51, AEG_FORMAT_R8G8_SINT = 52, AEG_FORMAT_R16_TYPELESS = 53, AEG_FORMAT_R16_FLOAT = 54, AEG_FORMAT_D16_UNORM = 55, AEG_FORMAT_R16_UNORM = 56, AEG_FORMAT_R16_UINT = 57, AEG_FORMAT_R16_SNORM = 58, AEG_FORMAT_R16_SINT = 59, AEG_FORMAT_R8_TYPELESS = 60, AEG_FORMAT_R8_UNORM = 61, AEG_FORMAT_R8_UINT = 62, AEG_FORMAT_R8_SNORM = 63, AEG_FORMAT_R8_SINT = 64, AEG_FORMAT_A8_UNORM = 65, AEG_FORMAT_R1_UNORM = 66, AEG_FORMAT_R9G9B9E5_SHAREDEXP = 67, AEG_FORMAT_R8G8_B8G8_UNORM = 68, AEG_FORMAT_G8R8_G8B8_UNORM = 69, AEG_FORMAT_BC1_TYPELESS = 70, AEG_FORMAT_BC1_UNORM = 71, AEG_FORMAT_BC1_UNORM_SRGB = 72, AEG_FORMAT_BC2_TYPELESS = 73, AEG_FORMAT_BC2_UNORM = 74, AEG_FORMAT_BC2_UNORM_SRGB = 75, AEG_FORMAT_BC3_TYPELESS = 76, AEG_FORMAT_BC3_UNORM = 77, AEG_FORMAT_BC3_UNORM_SRGB = 78, AEG_FORMAT_BC4_TYPELESS = 79, AEG_FORMAT_BC4_UNORM = 80, AEG_FORMAT_BC4_SNORM = 81, AEG_FORMAT_BC5_TYPELESS = 82, AEG_FORMAT_BC5_UNORM = 83, AEG_FORMAT_BC5_SNORM = 84, AEG_FORMAT_B5G6R5_UNORM = 85, AEG_FORMAT_B5G5R5A1_UNORM = 86, AEG_FORMAT_B8G8R8A8_UNORM = 87, AEG_FORMAT_B8G8R8X8_UNORM = 88, AEG_FORMAT_R10G10B10_XR_BIAS_A2_UNORM = 89, AEG_FORMAT_B8G8R8A8_TYPELESS = 90, AEG_FORMAT_B8G8R8A8_UNORM_SRGB = 91, AEG_FORMAT_B8G8R8X8_TYPELESS = 92, AEG_FORMAT_B8G8R8X8_UNORM_SRGB = 93, AEG_FORMAT_BC6H_TYPELESS = 94, AEG_FORMAT_BC6H_UF16 = 95, AEG_FORMAT_BC6H_SF16 = 96, AEG_FORMAT_BC7_TYPELESS = 97, AEG_FORMAT_BC7_UNORM = 98, AEG_FORMAT_BC7_UNORM_SRGB = 99, AEG_FORMAT_AYUV = 100, AEG_FORMAT_Y410 = 101, AEG_FORMAT_Y416 = 102, AEG_FORMAT_NV12 = 103, AEG_FORMAT_P010 = 104, AEG_FORMAT_P016 = 105, AEG_FORMAT_420_OPAQUE = 106, AEG_FORMAT_YUY2 = 107, AEG_FORMAT_Y210 = 108, AEG_FORMAT_Y216 = 109, AEG_FORMAT_NV11 = 110, AEG_FORMAT_AI44 = 111, AEG_FORMAT_IA44 = 112, AEG_FORMAT_P8 = 113, AEG_FORMAT_A8P8 = 114, AEG_FORMAT_B4G4R4A4_UNORM = 115, AEG_FORMAT_FORCE_UINT = 0xffffffff } AEG_FORMAT; typedef enum AEG_MODE_SCANLINE_ORDER { AEG_MODE_SCANLINE_ORDER_UNSPECIFIED = 0, AEG_MODE_SCANLINE_ORDER_PROGRESSIVE = 1, AEG_MODE_SCANLINE_ORDER_UPPER_FIELD_FIRST = 2, AEG_MODE_SCANLINE_ORDER_LOWER_FIELD_FIRST = 3 } AEG_MODE_SCANLINE_ORDER; typedef enum AEG_MODE_SCALING { AEG_MODE_SCALING_UNSPECIFIED = 0, AEG_MODE_SCALING_CENTERED = 1, AEG_MODE_SCALING_STRETCHED = 2 } AEG_MODE_SCALING; typedef enum AEG_MODE_ROTATION { AEG_MODE_ROTATION_UNSPECIFIED = 0, AEG_MODE_ROTATION_IDENTITY = 1, AEG_MODE_ROTATION_ROTATE90 = 2, AEG_MODE_ROTATION_ROTATE180 = 3, AEG_MODE_ROTATION_ROTATE270 = 4 } AEG_MODE_ROTATION; typedef enum AEG_SWAP_EFFECT { AEG_SWAP_EFFECT_DISCARD = 0, AEG_SWAP_EFFECT_SEQUENTIAL = 1, AEG_SWAP_EFFECT_FLIP_SEQUENTIAL = 3 } AEG_SWAP_EFFECT; typedef enum AEG_BIND_FLAG { AEG_BIND_VERTEX_BUFFER = 0x1L, AEG_BIND_INDEX_BUFFER = 0x2L, AEG_BIND_CONSTANT_BUFFER = 0x4L, AEG_BIND_SHADER_RESOURCE = 0x8L, AEG_BIND_STREAM_OUTPUT = 0x10L, AEG_BIND_RENDER_TARGET = 0x20L, AEG_BIND_DEPTH_STENCIL = 0x40L, AEG_BIND_UNORDERED_ACCESS = 0x80L, AEG_BIND_DECODER = 0x200L, AEG_BIND_VIDEO_ENCODER = 0x400L } AEG_BIND_FLAG; typedef enum AEG_CPU_ACCESS { AEG_CPU_ACCESS_NONE = (0), AEG_CPU_ACCESS_DYNAMIC = (1), AEG_CPU_ACCESS_READ_WRITE = (2), AEG_CPU_ACCESS_SCRATCH = (3), AEG_CPU_ACCESS_FIELD = 15 } AEG_CPU_ACCESS; typedef enum AEG_CPU_ACCESS_FLAG { AEG_CPU_ACCESS_WRITE = 0x10000L, AEG_CPU_ACCESS_READ = 0x20000L } AEG_CPU_ACCESS_FLAG; typedef enum AEG_USAGE : uint32 { AEG_USAGE_SHADER_INPUT = (1L << (0 + 4)), AEG_USAGE_RENDER_TARGET_OUTPUT = (1L << (1 + 4)), AEG_USAGE_BACK_BUFFER = (1L << (2 + 4)), AEG_USAGE_SHARED = (1L << (3 + 4)), AEG_USAGE_READ_ONLY = (1L << (4 + 4)), AEG_USAGE_DISCARD_ON_PRESENT = (1L << (5 + 4)), AEG_USAGE_UNORDERED_ACCESS = (1L << (6 + 4)), AEG_USAGE_DEFAULT = 0, AEG_USAGE_IMMUTABLE = 1, AEG_USAGE_DYNAMIC = 2, AEG_USAGE_STAGING = 3 } AEG_USAGE; typedef enum AEG_COMPILE : uint32 { AEG_COMPILE_DEBUG = (1 << 0), AEG_COMPILE_SKIP_VALIDATION=(1 << 1), AEG_COMPILE_SKIP_OPTIMIZATION=(1 << 2), AEG_COMPILE_PACK_MATRIX_ROW_MAJOR=(1 << 3), AEG_COMPILE_PACK_MATRIX_COLUMN_MAJOR=(1 << 4), AEG_COMPILE_PARTIAL_PRECISION=(1 << 5), AEG_COMPILE_FORCE_VS_SOFTWARE_NO_OPT=(1 << 6), AEG_COMPILE_FORCE_PS_SOFTWARE_NO_OPT=(1 << 7), AEG_COMPILE_NO_PRESHADER=(1 << 8), AEG_COMPILE_AVOID_FLOW_CONTROL=(1 << 9), AEG_COMPILE_PREFER_FLOW_CONTROL=(1 << 10), AEG_COMPILE_ENABLE_STRICTNESS=(1 << 11), AEG_COMPILE_ENABLE_BACKWARDS_COMPATIBILITY=(1 << 12), AEG_COMPILE_IEEE_STRICTNESS=(1 << 13), AEG_COMPILE_OPTIMIZATION_LEVEL0=(1 << 14), AEG_COMPILE_OPTIMIZATION_LEVEL1 = 0, AEG_COMPILE_OPTIMIZATION_LEVEL2=((1 << 14) | (1 << 15)), AEG_COMPILE_OPTIMIZATION_LEVEL3=(1 << 15), AEG_COMPILE_RESERVED16=(1 << 16), AEG_COMPILE_RESERVED17=(1 << 17), AEG_COMPILE_WARNINGS_ARE_ERRORS=(1 << 18), AEG_COMPILE_RESOURCES_MAY_ALIAS=(1 << 19), }AEG_COMPILE; typedef enum AEG_DRIVER_TYPE { AEG_DRIVER_TYPE_UNKNOWN = 0, AEG_DRIVER_TYPE_HARDWARE = (AEG_DRIVER_TYPE_UNKNOWN + 1), AEG_DRIVER_TYPE_REFERENCE = (AEG_DRIVER_TYPE_HARDWARE + 1), AEG_DRIVER_TYPE_NULL = (AEG_DRIVER_TYPE_REFERENCE + 1), AEG_DRIVER_TYPE_SOFTWARE = (AEG_DRIVER_TYPE_NULL + 1), AEG_DRIVER_TYPE_WARP = (AEG_DRIVER_TYPE_SOFTWARE + 1) } AEG_DRIVER_TYPE; typedef enum AEG_INPUT_CLASSIFICATION { AEG_INPUT_PER_VERTEX_DATA = 0, AEG_INPUT_PER_INSTANCE_DATA = 1 } AEG_INPUT_CLASSIFICATION; typedef enum AEG_PRIMITIVE_TOPOLOGY { AEG_PRIMITIVE_TOPOLOGY_UNDEFINED = 0, AEG_PRIMITIVE_TOPOLOGY_POINTLIST = 1, AEG_PRIMITIVE_TOPOLOGY_LINELIST = 2, AEG_PRIMITIVE_TOPOLOGY_LINESTRIP = 3, AEG_PRIMITIVE_TOPOLOGY_TRIANGLELIST = 4, AEG_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP = 5, AEG_PRIMITIVE_TOPOLOGY_LINELIST_ADJ = 10, AEG_PRIMITIVE_TOPOLOGY_LINESTRIP_ADJ = 11, AEG_PRIMITIVE_TOPOLOGY_TRIANGLELIST_ADJ = 12, AEG_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP_ADJ = 13, AEG_PRIMITIVE_TOPOLOGY_1_CONTROL_POINT_PATCHLIST = 33, AEG_PRIMITIVE_TOPOLOGY_2_CONTROL_POINT_PATCHLIST = 34, AEG_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST = 35, AEG_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST = 36, AEG_PRIMITIVE_TOPOLOGY_5_CONTROL_POINT_PATCHLIST = 37, AEG_PRIMITIVE_TOPOLOGY_6_CONTROL_POINT_PATCHLIST = 38, AEG_PRIMITIVE_TOPOLOGY_7_CONTROL_POINT_PATCHLIST = 39, AEG_PRIMITIVE_TOPOLOGY_8_CONTROL_POINT_PATCHLIST = 40, AEG_PRIMITIVE_TOPOLOGY_9_CONTROL_POINT_PATCHLIST = 41, AEG_PRIMITIVE_TOPOLOGY_10_CONTROL_POINT_PATCHLIST = 42, AEG_PRIMITIVE_TOPOLOGY_11_CONTROL_POINT_PATCHLIST = 43, AEG_PRIMITIVE_TOPOLOGY_12_CONTROL_POINT_PATCHLIST = 44, AEG_PRIMITIVE_TOPOLOGY_13_CONTROL_POINT_PATCHLIST = 45, AEG_PRIMITIVE_TOPOLOGY_14_CONTROL_POINT_PATCHLIST = 46, AEG_PRIMITIVE_TOPOLOGY_15_CONTROL_POINT_PATCHLIST = 47, AEG_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST = 48, AEG_PRIMITIVE_TOPOLOGY_17_CONTROL_POINT_PATCHLIST = 49, AEG_PRIMITIVE_TOPOLOGY_18_CONTROL_POINT_PATCHLIST = 50, AEG_PRIMITIVE_TOPOLOGY_19_CONTROL_POINT_PATCHLIST = 51, AEG_PRIMITIVE_TOPOLOGY_20_CONTROL_POINT_PATCHLIST = 52, AEG_PRIMITIVE_TOPOLOGY_21_CONTROL_POINT_PATCHLIST = 53, AEG_PRIMITIVE_TOPOLOGY_22_CONTROL_POINT_PATCHLIST = 54, AEG_PRIMITIVE_TOPOLOGY_23_CONTROL_POINT_PATCHLIST = 55, AEG_PRIMITIVE_TOPOLOGY_24_CONTROL_POINT_PATCHLIST = 56, AEG_PRIMITIVE_TOPOLOGY_25_CONTROL_POINT_PATCHLIST = 57, AEG_PRIMITIVE_TOPOLOGY_26_CONTROL_POINT_PATCHLIST = 58, AEG_PRIMITIVE_TOPOLOGY_27_CONTROL_POINT_PATCHLIST = 59, AEG_PRIMITIVE_TOPOLOGY_28_CONTROL_POINT_PATCHLIST = 60, AEG_PRIMITIVE_TOPOLOGY_29_CONTROL_POINT_PATCHLIST = 61, AEG_PRIMITIVE_TOPOLOGY_30_CONTROL_POINT_PATCHLIST = 62, AEG_PRIMITIVE_TOPOLOGY_31_CONTROL_POINT_PATCHLIST = 63, AEG_PRIMITIVE_TOPOLOGY_32_CONTROL_POINT_PATCHLIST = 64, } AEG_PRIMITIVE_TOPOLOGY; typedef struct AEG_RATIONAL { uint32 Numerator; uint32 Denominator; } AEG_RATIONAL; typedef struct AEG_SAMPLE_DESC { uint32 Count; uint32 Quality; } AEG_SAMPLE_DESC; struct AEG_MODE_DESC { uint32 Width; uint32 Height; AEG_RATIONAL RefreshRate; AEG_FORMAT Format; AEG_MODE_SCANLINE_ORDER ScanlineOrdering; AEG_MODE_SCALING Scaling; }; typedef struct AEG_SWAP_CHAIN_DESC { AEG_MODE_DESC BufferDesc; AEG_SAMPLE_DESC SampleDesc; uint32 BufferUsage; uint32 BufferCount; SIZE_T OutputWindow; uint32 Windowed; AEG_SWAP_EFFECT SwapEffect; uint32 Flags; } AEG_SWAP_CHAIN_DESC; typedef struct AEG_VIEWPORT { float TopLeftX; float TopLeftY; float Width; float Height; float MinDepth; float MaxDepth; } AEG_VIEWPORT; typedef struct AEG_TEXTURE2D_DESC { uint32 Width; uint32 Height; uint32 MipLevels; uint32 ArraySize; AEG_FORMAT Format; AEG_SAMPLE_DESC SampleDesc; uint32 Usage; uint32 BindFlags; uint32 CPUAccessFlags; uint32 MiscFlags; } AEG_TEXTURE2D_DESC; typedef struct AEG_BUFFER_DESC { uint32 ByteWidth; uint32 Usage; uint32 BindFlags; uint32 CPUAccessFlags; uint32 MiscFlags; uint32 StructureByteStride; } AEG_BUFFER_DESC; typedef struct AEG_SUBRESOURCE_DATA { const void *pSysMem; uint32 SysMemPitch; uint32 SysMemSlicePitch; } AEG_SUBRESOURCE_DATA; typedef struct AEG_SHADER_MACRO { const ANSICHAR* Name; const ANSICHAR* Definition; } AEG_SHADER_MACRO; typedef struct AEG_COMPILE_SHADER_DESC { wString FileName; AEG_SHADER_MACRO* ShaderMacro; String EntryPoint; String Profile; uint32 CompileOptimazation; uint32 Flags; } AEG_COMPILE_SHADER_DESC; typedef struct AEG_INPUT_ELEMENT_DESC { const ANSICHAR* SemanticName; uint32 SemanticIndex; AEG_FORMAT Format; uint32 InputSlot; uint32 AlignedByteOffset; AEG_INPUT_CLASSIFICATION InputSlotClass; uint32 InstanceDataStepRate; } AEG_INPUT_ELEMENT_DESC; typedef struct AEG_VERTEX_BUFFER_DESC { AEG_PRIMITIVE_TOPOLOGY Topology; uint32 StartSlot; uint32 IndexSize; uint32 VertexSize; uint32 NumBuffers; } AEG_VERTEX_BUFFER_DESC; #define AEG_APPEND_ALIGNED_ELEMENT ( 0xffffffff ) }
#include "../../idlib/precompiled.h" #pragma hdrstop #include "../Game_local.h" /* ================ idDebugGraph::idDebugGraph ================ */ idDebugGraph::idDebugGraph() { index = 0; } /* ================ idDebugGraph::SetNumSamples ================ */ void idDebugGraph::SetNumSamples( int num ) { index = 0; samples.Clear(); samples.SetNum( num ); memset( samples.Ptr(), 0, samples.MemoryUsed() ); } /* ================ idDebugGraph::AddValue ================ */ void idDebugGraph::AddValue( float value ) { samples[ index ] = value; index++; if ( index >= samples.Num() ) { index = 0; } } /* ================ idDebugGraph::Draw ================ */ void idDebugGraph::Draw( const idVec4 &color, float scale ) const { int i; float value1; float value2; idVec3 vec1; idVec3 vec2; const idMat3 &axis = gameLocal.GetLocalPlayer()->viewAxis; const idVec3 pos = gameLocal.GetLocalPlayer()->GetPhysics()->GetOrigin() + axis[ 1 ] * samples.Num() * 0.5f; value1 = samples[ index ] * scale; for( i = 1; i < samples.Num(); i++ ) { value2 = samples[ ( i + index ) % samples.Num() ] * scale; vec1 = pos + axis[ 2 ] * value1 - axis[ 1 ] * ( i - 1 ) + axis[ 0 ] * samples.Num(); vec2 = pos + axis[ 2 ] * value2 - axis[ 1 ] * i + axis[ 0 ] * samples.Num(); // RAVEN BEGIN // bdube: use GetMSec access rather than USERCMD_TIME gameRenderWorld->DebugLine( color, vec1, vec2, gameLocal.GetMSec ( ), false ); // RAVEN END value1 = value2; } }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <quic/QuicConstants.h> namespace quic { struct QuicStreamGroupRetransmissionPolicy { // Params controlling retransmission. DurationRep timeReorderingThreshDividend{ kDefaultTimeReorderingThreshDividend}; DurationRep timeReorderingThreshDivisor{kDefaultTimeReorderingThreshDivisor}; uint32_t reorderingThreshold{kReorderingThreshold}; // Disables retransmission. completely. bool disableRetransmission{false}; }; } // namespace quic
/* ***** BEGIN LICENSE BLOCK ***** * FW4SPL - Copyright (C) IRCAD, 2012-2013. * Distributed under the terms of the GNU Lesser General Public License (LGPL) as * published by the Free Software Foundation. * ****** END LICENSE BLOCK ****** */ #ifndef _GDCMIO_DICOMSURFACE_HPP_ #define _GDCMIO_DICOMSURFACE_HPP_ #include <stdint.h> // for uint16_t on Windows #include <fwData/Reconstruction.hpp> #include "gdcmIO/config.hpp" namespace gdcmIO { /** * @brief This class define one surface mesh item in order to translate * in DICOM/FW4SPL form. * * @class DicomSurface * @author IRCAD (Research and Development Team). * @date 2011. */ class GDCMIO_CLASS_API DicomSurface { public : GDCMIO_API DicomSurface(); GDCMIO_API ~DicomSurface(); /** * @brief Set members from a reconstruction. * * @param a_reconstruction Source reconstruction */ GDCMIO_API void setFromData(fwData::Reconstruction::csptr a_reconstruction); /** * @brief Set a reconstruction from DicomSurface data. * * @note All members have to be set before. * * @param a_reconstruction Destination reconstruction */ GDCMIO_API void convertToData(fwData::Reconstruction::sptr a_reconstruction); GDCMIO_API ::fwData::Mesh::sptr convertToData(const float *coord, const unsigned long coordSize, const uint32_t *index, const unsigned long indexSize, const float * normalCoord); GDCMIO_API const ::boost::shared_ptr<float> getPointCoordData() const; GDCMIO_API unsigned long getPointCoordSize() const; GDCMIO_API const ::boost::shared_ptr<uint32_t> getPointIndexList() const; GDCMIO_API unsigned long getPointIndexSize() const; GDCMIO_API const ::boost::shared_ptr<float> getNormalCoordData() const; GDCMIO_API unsigned long getNormalCoordSize() const; GDCMIO_API void setPointCoordData(const ::boost::shared_ptr<float> a_array); GDCMIO_API void setPointCoordSize(const unsigned long a_size); GDCMIO_API void setPointIndexList(const ::boost::shared_ptr<uint32_t> a_array); GDCMIO_API void setPointIndexSize(const unsigned long a_size); GDCMIO_API void setNormalCoordData(const ::boost::shared_ptr<float> a_array); GDCMIO_API void setNormalCoordSize(const unsigned long a_size); private : //** Data for one surface **// ::boost::shared_ptr<float> m_pointCoordData; ///< Surface Points Coordinates (List of points coordinates for one surface) ///< (eg : x1,y1,z1, x2,y2,z2, ...). unsigned long m_pointCoordSize; ///< Number of points. // ::boost::shared_ptr<uint16_t> m_pointIndexList; ///< Surface Mesh Primitives (List of points index for all triangle of one surface) // ///< (eg : p1,p3,p2, p2,p3,p4, ...). // Primitives will be written in Triangle Point Index List ( Tag(0066,0023) ) which has a VR equal to OW // VR::OW is a string of 16-bit words where the encoding of the contents is specified by the negotiated Transfer Syntax // Here, we try to force VR::OW to have a length of 32 bits for each primitive ::boost::shared_ptr<uint32_t> m_pointIndexList; ///< Surface Mesh Primitives (List of points index for all triangle of one surface) ///< (eg : p1,p3,p2, p2,p3,p4, ...). unsigned long m_pointIndexSize; ///< Number of primitives/cells. ::boost::shared_ptr<float> m_normalCoordData; ///< Surface Point Normal Coordinates (List of point normal coordinates for one surface) ///< (eg : x1,y1,z1, x2,y2,z2, ...). unsigned long m_normalCoordSize; ///< Number of normals. }; } // namespace gdcmIO #endif /* _GDCMIO_DICOMSURFACE_HPP_ */
#ifndef METHODS_HPP #define METHODS_HPP #include <string> class methods { private: template <typename Type> Type get_num(); /* It gets the number from the std input stream */ long long int fact(int number); /* This function calculates the factorial of the _number_ */ public: long long int f2d(); /* Translates a number from the factorial numsys to the decimal */ std::string d2f(); /* Vice versa: * It translates a number from the decimal numsys to the factorial */ }; #endif
#include <vector> #include <string> class Node { public: std::string val; Node* left; Node* right; Node(std::string initialVal) { val = initialVal; left = nullptr; right = nullptr; } }; std::vector<std::string> leafList(Node* root, std::vector<std::string> &leafs) { // todo if(root == nullptr) return leafs; if(root->left == nullptr && root->right == nullptr) leafs.push_back(root->val); leafList(root->left,leafs); leafList(root->right,leafs); return leafs; } std::vector<std::string> leafList(Node* root) { std::vector<std::string> leafs; leafList(root,leafs); return leafs; } int main(){ return 0; }
// Nama : Naufal Dean Anugrah // NIM : 13518123 // Tanggal : 13 Februari 2020 // Topik : Inheritance, Polymorphism, Abstract Base Class #include "WarungNasgor.hpp" // Masukan: Jumlah uang, nasi, telur, dan kecap WarungNasgor::WarungNasgor(int uang, int nasi, int telur, int kecap) : WarungNasi(uang, telur, nasi) { this->kecap = kecap; } // Memasak menu Nasi Goreng // Resep Nasi Goreng: // 1 buah nasi // 1 buah telur // 1 buah kecap // Jika bahan yang dibutuhkan kurang, kembalikan false. // Jika cukup, hitung pendapatan total. Pendapatan total dihitung dengan jumlah pesanan dikali 15000 // Setelah itu, tambahkan pendapatan total ke uang. Kembalikan true. bool WarungNasgor::masak(int pesanan) { if (pesanan <= getNasi() && pesanan <= getTelur() && pesanan <= this->kecap) { setUang(getUang() + (15000 * pesanan)); return true; } else { return false; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef CLEAR_PRIVATE_DATA_CONTROLLER_H #define CLEAR_PRIVATE_DATA_CONTROLLER_H #include "adjunct/desktop_util/adt/opproperty.h" #include "adjunct/quick/managers/PrivacyManager.h" #include "adjunct/quick_toolkit/contexts/OkCancelDialogContext.h" #include "adjunct/quick_toolkit/widgets/DialogListener.h" class ClearPrivateDataController : public OkCancelDialogContext , public DialogListener { public: ClearPrivateDataController(); // UiContext virtual BOOL DisablesAction(OpInputAction* action); virtual OP_STATUS HandleAction(OpInputAction* action); // DialogListener virtual void OnOk(Dialog* dialog, UINT32 result); private: // DialogContext virtual void InitL(); OP_STATUS InitOptions(); void ClearPrivateData(); PrivacyManager::Flags m_flags; UINT32 m_sync_passwords_deletion; bool m_disable_action_handling; OpProperty<bool> m_del_all_cookies; OpProperty<bool> m_del_tmp_cookies; OpProperty<bool> m_del_pwddocs_data; OpProperty<bool> m_clear_cache; OpProperty<bool> m_clear_plugin_data; OpProperty<bool> m_clear_geoloc_data; OpProperty<bool> m_clear_camera_permissions; OpProperty<bool> m_clear_visited_pages; OpProperty<bool> m_clear_trnsf_files_hist; OpProperty<bool> m_clear_email_acc_pwds; OpProperty<bool> m_clear_wand_pwds; OpProperty<bool> m_clear_bkmrk_visited_time; OpProperty<bool> m_close_all_windows; OpProperty<bool> m_clear_web_storage; OpProperty<bool> m_clear_extension_data; }; #endif // CLEAR_PRIVATE_DATA_CONTROLLER_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "platforms/mac/util/macutils.h" #include "platforms/mac/util/CTextConverter.h" #include "platforms/mac/File/FileUtils_Mac.h" #include "platforms/mac/folderdefines.h" #include "platforms/mac/Resources/buildnum.h" #include "platforms/mac/bundledefines.h" #ifndef NO_CARBON #include "platforms/mac/model/MacSound.h" #endif #include "adjunct/embrowser/EmBrowser_main.h" #include "adjunct/quick/dialogs/SimpleDialog.h" #include "adjunct/quick/hotlist/HotlistModel.h" #include "platforms/mac/pi/MacOpSystemInfo.h" #include "modules/locale/oplanguagemanager.h" #include "modules/url/url_tools.h" #include "modules/util/opfile/opfile.h" #include "modules/prefs/prefsmanager/collections/pc_doc.h" #include "modules/prefs/prefsmanager/collections/pc_app.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/encodings/encoders/utf8-encoder.h" #include "modules/encodings/decoders/utf8-decoder.h" #ifdef USE_COMMON_RESOURCES #include "adjunct/desktop_util/resources/pi/opdesktopresources.h" #endif // USE_COMMON_RESOURCES #include "adjunct/desktop_pi/desktop_pi_util.h" #include "platforms/mac/pi/CocoaOpWindow.h" #include "modules/libgogi/pi_impl/mde_opview.h" #include "platforms/mac/util/MachOCompatibility.h" #include "modules/scope/src/scope_manager.h" #include "adjunct/desktop_scope/src/scope_desktop_window_manager.h" #include "platforms/mac/pi/desktop/MacSystemInputPI.h" #include <OpenGL/OpenGL.h> #define kBundleNoSubDir NULL #define MAX_DISPLAYS 8 char *GetVersionString() { return VER_NUM_STR; #if 0 Handle versionHandle; static char str[32] = {'\0'}; // We don't need much space for this string. long l; versionHandle = GetResource('vers', 1); if(versionHandle) { l = (*versionHandle)[6]; memcpy(str, &(*versionHandle)[7], l); str[l] = '\0'; ReleaseResource(versionHandle); } return(str); // "5.0 tp4.303" #endif } long GetBuildNumber() { return(VER_BUILD_NUMBER); } int GetVideoRamSize() { static int videomemory = 0; if (videomemory == 0) { CGLError err; GLint rendCount; CGLRendererInfoObj rendInfo; GLint value; err = CGLQueryRendererInfo(CGDisplayIDToOpenGLDisplayMask(CGMainDisplayID()), &rendInfo, &rendCount); if (err == kCGLNoError) { /* Not interested in multiple renderers, just get the first */ err = CGLDescribeRenderer(rendInfo, 0, kCGLRPVideoMemory, &value); if (err == kCGLNoError) videomemory = value; CGLDestroyRendererInfo(rendInfo); } } return videomemory; } int GetMaxScreenSize() { static int maxscreensize = 0; if (maxscreensize == 0) { CGDirectDisplayID displayId[MAX_DISPLAYS]; CGError err; uint32_t count, i = 0; err = CGGetActiveDisplayList(MAX_DISPLAYS, displayId, &count); while (err == kCGErrorSuccess && i < count) { CGRect r = CGDisplayBounds(displayId[i++]); maxscreensize = MAX(maxscreensize, r.size.width*r.size.height); } } return maxscreensize; } int GetMaxScreenDimension() { static int maxscreendim = 0; if (maxscreendim == 0) { CGDirectDisplayID displayId[MAX_DISPLAYS]; CGError err; uint32_t count, i = 0; err = CGGetActiveDisplayList(MAX_DISPLAYS, displayId, &count); while (err == kCGErrorSuccess && i < count) { CGRect r = CGDisplayBounds(displayId[i++]); maxscreendim = MAX(MAX(maxscreendim, r.size.width), r.size.height); } } return maxscreendim; } OSErr FindPSN(ProcessSerialNumber& inoutViewerProcess, FourCharCode inAppCreatorCode, FourCharCode inType) { ProcessInfoRec info = {sizeof(ProcessInfoRec),}; while (noErr == GetNextProcess(&inoutViewerProcess)) { if (noErr == GetProcessInformation(&inoutViewerProcess, &info)) { if (info.processSignature == inAppCreatorCode) { return noErr; } } } return -1; } void ActivateFinder(Boolean firstWindowOnly) { ProcessSerialNumber psnFinder = {kNoProcess, kNoProcess}; OSStatus status = FindPSN(psnFinder, FOUR_CHAR_CODE('MACS'), FOUR_CHAR_CODE('FNDR') ); if (status == noErr) { if (firstWindowOnly) ::SetFrontProcessWithOptions(&psnFinder, kSetFrontProcessFrontWindowOnly); else ::SetFrontProcess(&psnFinder); } } Boolean OpenFileOrFolder(FSRefPtr inSpec) { OSErr err; AppleEvent theAEvent, theReply; AEAddressDesc fndrAddress; AEDescList targetListDesc; OSType fndrCreator = 'MACS'; Boolean eventSent = false; AliasHandle targetAlias = NULL; /* set up locals */ AECreateDesc(typeNull, NULL, 0, &theAEvent); AECreateDesc(typeNull, NULL, 0, &fndrAddress); AECreateDesc(typeNull, NULL, 0, &theReply); AECreateDesc(typeNull, NULL, 0, &targetListDesc); /* create an open documents event targeting the finder */ err = AECreateDesc(typeApplSignature, (Ptr) &fndrCreator, sizeof(fndrCreator), &fndrAddress); if (noErr == err) { err = AECreateAppleEvent(kCoreEventClass, kAEOpenDocuments, &fndrAddress, kAutoGenerateReturnID, kAnyTransactionID, &theAEvent); if (noErr == err) { /* create the list of files to open */ err = AECreateList(NULL, 0, false, &targetListDesc); if (noErr == err) { err = FSNewAlias(NULL, inSpec, &targetAlias); if (noErr == err) { HLock((Handle) targetAlias); err = AEPutPtr(&targetListDesc, 1, typeAlias, *targetAlias, GetHandleSize((Handle) targetAlias)); HUnlock((Handle) targetAlias); if (noErr == err) { /* add the file list to the apple event */ err = AEPutParamDesc(&theAEvent, keyDirectObject, &targetListDesc); if (noErr == err) { /* send the event to the Finder */ #ifdef NO_CARBON err = AESendMessage(&theAEvent, &theReply, kAENoReply, kAEDefaultTimeout); #else err = AESend(&theAEvent, &theReply, kAENoReply, kAENormalPriority, kAEDefaultTimeout, NULL, NULL); #endif if (err == noErr) { eventSent = true; } } } DisposeHandle((Handle) targetAlias); } } } } /* clean up and leave */ AEDisposeDesc(&targetListDesc); AEDisposeDesc(&theAEvent); AEDisposeDesc(&fndrAddress); AEDisposeDesc(&theReply); return eventSent; } Boolean MacGetDefaultApplicationPath(IN const uni_char* url, OUT OpString& appName, OUT OpString& appPath) { CFURLRef macURL = 0; Boolean result = false; FSRef appFSRef; if(url) { macURL = CFURLCreateWithBytes(NULL, (const UInt8*)url, sizeof(uni_char)*uni_strlen(url), kCFStringEncodingUnicode, NULL); if(macURL) { if(LSGetApplicationForURL(macURL, kLSRolesAll, &appFSRef, NULL) == noErr) { char p[MAX_PATH]; memset(p, '\0', MAX_PATH*sizeof(char)); if (noErr != FSRefMakePath(&appFSRef, (UInt8*)p, MAX_PATH-1)) return result; RETURN_VALUE_IF_ERROR(appPath.SetFromUTF8(p), result); const uni_char* uni_appname = uni_strrchr(appPath.CStr(), UNI_L(PATHSEPCHAR)); if(uni_appname) { RETURN_VALUE_IF_ERROR(appName.Set(++uni_appname), result); // skip PATHSEPCHAR } result = true; } CFRelease(macURL); } } return result; } Boolean MacOpenFileInApplication(const uni_char *file, const uni_char *application) { FSRef appFSRef; LSLaunchFSRefSpec launchInfo; FSRef docFSRef; OpString filepath; #ifdef WIDGET_RUNTIME_SUPPORT bool asApp = false; bool asWidget = false; OpString rawParams; rawParams.Set(file, uni_strlen(file)); int pos; if ((pos = rawParams.Find("-widget")) != KNotFound) { asWidget = true; } else if ((pos = rawParams.Find("-app")) != KNotFound) { asApp = true; } if (asApp) { filepath.Set(rawParams.SubString((unsigned int)op_strlen("-app"), KAll, NULL).CStr()); } else if (asWidget) { filepath.Set(rawParams.SubString((unsigned int)op_strlen("-widget"), KAll, NULL).CStr()); } else { filepath.Set(file); } filepath.Strip(TRUE, TRUE); #else if(OpStatus::IsError(filepath.Set(file))) { return false; } #endif // if we get enclosed in quotes this is the time to remove them... if(filepath.Length() > 2) { uni_char qoute = UNI_L('"'); if( (filepath[0] == qoute) && (filepath[filepath.Length() - 1] == qoute) ) { filepath.Set(filepath.SubString(1, filepath.Length()-2).CStr()); } } if(OpFileUtils::ConvertUniPathToFSRef(filepath, docFSRef)) { FSCatalogInfoBitmap what = kFSCatInfoNodeFlags; FSCatalogInfo folder_info; // FIXME: ismailp - following fsspec may be invalid. check folder_fss FSGetCatalogInfo(&docFSRef, what, &folder_info, NULL, NULL, NULL); if (folder_info.nodeFlags & (1 << 4)) { // This is a folder. Open it in Finder and activate if (OpenFileOrFolder(&docFSRef /*&folder_fss*/)) ActivateFinder(true); } #ifdef WIDGET_RUNTIME_SUPPORT else if (application && (asApp || asWidget)) { { CFStringRef param1Ref = asApp ? CFSTR("-app") : CFSTR("-widget"); CFStringRef param2Ref = CFStringCreateWithCharacters(NULL, (UniChar *)filepath.CStr(), filepath.Size()); CFMutableArrayRef paramRef = CFArrayCreateMutable(NULL, 2, NULL); CFArrayInsertValueAtIndex(paramRef, 0, param1Ref); CFArrayInsertValueAtIndex(paramRef, 1, param2Ref); LSApplicationParameters params; OpFileUtils::ConvertUniPathToFSRef(application, appFSRef); params.version = 0; params.flags = kLSLaunchNewInstance; params.environment = NULL; params.application = &appFSRef; params.asyncLaunchRefCon = NULL; params.initialEvent = NULL; params.argv = paramRef; LSOpenApplication(&params, NULL); CFRelease(param1Ref); CFRelease(param2Ref); CFRelease(paramRef); return true; } } #endif // WIDGET_RUNTIME_SUPPORT else { if(application) { if(!OpFileUtils::ConvertUniPathToFSRef(application, appFSRef)) { return false; } } else { OpString content_type; OpString file_handler; if(OpStatus::IsError(g_op_system_info->GetFileHandler(&filepath, content_type, file_handler))) { return false; } if(!OpFileUtils::ConvertUniPathToFSRef(file_handler, appFSRef)) { return false; } } launchInfo.appRef = &appFSRef; launchInfo.numDocs = 1; launchInfo.itemRefs = &docFSRef; launchInfo.passThruParams = NULL; launchInfo.launchFlags = kLSLaunchDefaults; launchInfo.asyncRefCon = 0; if(noErr == LSOpenFromRefSpec(&launchInfo, NULL)) { return true; } } } else if (uni_strchr(file, ':')) { return MacOpenURLInApplication(file, application); } return false; } Boolean MacOpenURLInTrustedApplication(const uni_char *url) { OpString protocol; OpString appname; BOOL bHandled = FALSE; uni_char *p = uni_strstr(url,UNI_L("://")); if(p) { OpString urlcopy; urlcopy.Set(url); protocol.Set(urlcopy.SubString(0, p - url).CStr()); TrustedProtocolData data; int index = g_pcdoc->GetTrustedProtocolInfo(protocol, data); if (index >= 0) { if (data.viewer_mode == UseDefaultApplication) { OpString appname; if (OpStatus::IsSuccess(appname.Set(data.filename))) { OpString defaultAppName; OpString app; OpString protocolstring; protocolstring.Set(protocol); protocolstring.Append(UNI_L(":")); if(MacGetDefaultApplicationPath(protocolstring.CStr(), app, defaultAppName)) { appname.Set(defaultAppName); } bHandled = MacOpenURLInApplication(url, appname.CStr()); } } } } return bHandled; } void SetMailtoString(OpString &mailto, const uni_char* to, const uni_char* cc, const uni_char* bcc, const uni_char* subject, const uni_char* message) { mailto.Set(UNI_L("mailto:")); if(to) { mailto.Append(to); } mailto.Append(UNI_L("?")); if(cc) { mailto.AppendFormat(UNI_L("cc=%s"),cc); mailto.Append(UNI_L("&")); } if(bcc) { mailto.AppendFormat(UNI_L("bcc=%s"),bcc); mailto.Append(UNI_L("&")); } if(subject) { mailto.Append(UNI_L("subject=")); uni_char* escaped = new uni_char[uni_strlen(subject)*3+1]; EscapeFileURL(escaped, (uni_char *)subject); mailto.Append(escaped); delete [] escaped; mailto.Append(UNI_L("&")); } if(message) { mailto.Append(UNI_L("body=")); uni_char* escaped = new uni_char[uni_strlen(message)*3+1]; EscapeFileURL(escaped, (uni_char*)message, TRUE); mailto.Append(escaped); delete [] escaped; } } void ComposeExternalMail(const uni_char* to, const uni_char* cc, const uni_char* bcc, const uni_char* subject, const uni_char* message, const uni_char* raw_address, int mailhandler) { #ifdef M2_SUPPORT if (mailhandler == _MAILHANDLER_FIRST_ENUM) { mailhandler = g_pcui->GetIntegerPref(PrefsCollectionUI::MailHandler); #else mailhandler = MAILHANDLER_SYSTEM; #endif // M2_SUPPORT } switch (mailhandler) { case MAILHANDLER_SYSTEM: { OpString mailto; if (raw_address) mailto.Set(raw_address); else SetMailtoString(mailto,to,cc,bcc,subject,message); MacOpenURLInDefaultApplication(mailto); break; } case MAILHANDLER_APPLICATION: { OpStringC extApp; extApp = g_pcapp->GetStringPref(PrefsCollectionApp::ExternalMailClient); if(0 == extApp.Length()) { OpStatus::Ignore(SimpleDialog::ShowDialog(WINDOW_NAME_MESSAGE_DIALOG, NULL, Str::SI_IDSTR_MSG_NO_EXT_MAIL_APP_DEFINED_TXT, Str::SI_IDSTR_MSG_NO_EXT_MAIL_APP_DEFINED_CAP, Dialog::TYPE_OK, Dialog::IMAGE_ERROR)); return; } OpString mailto; if (raw_address) mailto.Set(raw_address); else SetMailtoString(mailto,to,cc,bcc,subject,message); if(!MacOpenURLInApplication(mailto, extApp.CStr())) { OpString errMsg; TRAPD(err, g_languageManager->GetStringL(Str::SI_IDSTR_MSG_FAILED_STARTING_EXT_MAIL_APP_TXT, errMsg)); errMsg.Append(UNI_L("\n")); errMsg.Append(extApp.CStr()); OpString title, msg; if (OpStatus::IsSuccess(g_languageManager->GetString(Str::SI_IDSTR_MSG_FAILED_STARTING_EXT_MAIL_APP_CAP, title))) OpStatus::Ignore(SimpleDialog::ShowDialog(WINDOW_NAME_MESSAGE_DIALOG, NULL, errMsg.CStr(), title.CStr(), Dialog::TYPE_OK, Dialog::IMAGE_ERROR)); } } break; } } Boolean stripquotes(OpString& str) { static const uni_char qoute = UNI_L('"'); if(str.Length() > 2) { if (str[0] == qoute) { const uni_char* start = str.CStr() + 1; const uni_char* end = uni_strchr(start, qoute); if (end) str.Set(start, end-start); else return false; } } return true; } Boolean MacOpenURLInApplication(const uni_char* url, const uni_char* appPath, bool new_instance) { CFURLRef macURL = 0; CFURLRef appURL = 0; FSRef appFSRef; CFMutableArrayRef urlArray; Boolean result = false; LSLaunchURLSpec launchInfo; OpString filepath; OpString strippedurl; // if we get enclosed in quotes this is the time to remove them... if(OpStatus::IsSuccess(filepath.Set(appPath))) { if (!stripquotes(filepath)) return false; } if(OpStatus::IsSuccess(strippedurl.Set(url))) { if (!stripquotes(strippedurl)) return false; } if(url) { macURL = CFURLCreateWithBytes(NULL, (const UInt8*)strippedurl.CStr(), 2*uni_strlen(strippedurl.CStr()), kCFStringEncodingUnicode, NULL); CFShow(macURL); if(macURL) { appURL = CFURLCreateWithBytes(NULL, (const UInt8*)filepath.CStr(), 2*uni_strlen(filepath.CStr()), kCFStringEncodingUnicode, NULL); CFShow(appURL); if(appURL) { // This is just to test that the appPath is valid if(CFURLGetFSRef(appURL, &appFSRef)) { urlArray = CFArrayCreateMutable(NULL, 1, NULL); if(urlArray) { CFArrayAppendValue(urlArray, macURL); launchInfo.appURL = appURL; launchInfo.itemURLs = urlArray; launchInfo.passThruParams = NULL; launchInfo.launchFlags = kLSLaunchDefaults; if (new_instance) { launchInfo.launchFlags |= kLSLaunchNewInstance; } launchInfo.asyncRefCon = 0; if(noErr == LSOpenFromURLSpec(&launchInfo, NULL)) { result = true; } CFRelease(urlArray); } } CFRelease(appURL); } } } if(macURL) CFRelease(macURL); return result; } Boolean MacOpenURLInDefaultApplication(const uni_char* url, bool inOpera) { CFURLRef macURL = 0; OSStatus err; CFURLRef appURL = 0; CFMutableArrayRef urlArray; Boolean result = false; LSLaunchURLSpec launchInfo; if(url) { macURL = CFURLCreateWithBytes(NULL, (const UInt8*)url, 2*uni_strlen(url), kCFStringEncodingUnicode, NULL); if(macURL) { if (inOpera) { err = LSFindApplicationForInfo(kLSUnknownCreator, GetCFBundleID(), NULL, NULL, &appURL); } else err = LSGetApplicationForURL(macURL, kLSRolesAll, NULL, &appURL); if(err == noErr) { urlArray = CFArrayCreateMutable(NULL, 1, NULL); if(urlArray) { CFArrayAppendValue(urlArray, macURL); launchInfo.appURL = appURL; launchInfo.itemURLs = urlArray; launchInfo.passThruParams = NULL; launchInfo.launchFlags = kLSLaunchDefaults; launchInfo.asyncRefCon = 0; if(noErr == LSOpenFromURLSpec(&launchInfo, NULL)) { result = true; } CFRelease(urlArray); } } else if(err == kLSApplicationNotFoundErr) { result = false; } } } if(macURL) CFRelease(macURL); return result; } Boolean MacExecuteProgram(const uni_char* program, const uni_char* parameters) { if (program && uni_strstr(program, UNI_L("://"))) { return MacOpenURLInDefaultApplication(program); } else { if (parameters && uni_strstr(parameters, UNI_L("://"))) { if (program) return MacOpenURLInApplication(parameters, program); else return MacOpenURLInDefaultApplication(parameters); } else if (program && parameters) { return MacOpenFileInApplication(parameters, program); } else if (program) { // Without parameters it's trying to just open a folder // so dump it into the parameters without an application, confused? :) return MacOpenFileInApplication(program, NULL); } } return false; } #ifndef NO_CARBON BOOL MacPlaySound(const uni_char* fullfilepath, BOOL async) { MacOpSound *snd = MacOpSound::GetSound(fullfilepath); if(snd) { if(OpStatus::IsSuccess(snd->Init())) { if(OpStatus::IsSuccess(snd->Play(async))) { return TRUE; } } } return FALSE; } #endif #pragma mark - Boolean FindUniqueFileName(OpString &path, const OpString &suggested) { OpString8 utf8; int val; if (suggested.HasContent()) { path.Reserve(suggested.Length()+8); path.Append(suggested.CStr()); OpFile file; BOOL exists; file.Construct(path); if (OpStatus::IsSuccess(file.Exists(exists)) && !exists) { return TRUE; } else { path.Delete(path.FindLastOf(UNI_L('/'))+1); int index = suggested.FindLastOf(UNI_L('.')); if (index >= 0) { path.Append(suggested.CStr(), index); path.Append(UNI_L("XXXXXX")); path.Append(suggested.CStr()+index); utf8.SetUTF8FromUTF16(path.CStr()); val = mkstemps(utf8.CStr(), uni_strlen(suggested.CStr()+index)); path.SetFromUTF8(utf8.CStr()); return (val != -1); } else { path.Append(suggested.CStr()); path.Append(UNI_L("XXXXXX")); utf8.SetUTF8FromUTF16(path.CStr()); val = mkstemp(utf8.CStr()); path.SetFromUTF8(utf8.CStr()); return (val != -1); } } } else { path.Append(UNI_L("XXXXXX")); utf8.SetUTF8FromUTF16(path.CStr()); val = mkstemp(utf8.CStr()); path.SetFromUTF8(utf8.CStr()); return (val != -1); } } #pragma mark - Boolean IsCacheFolderOwner() { static Boolean initialized = false; static Boolean owner = true; if (!initialized) { ProcessSerialNumber psn = {0,0}; ProcessSerialNumber this_psn = {0,0}; FSRef folderref, fileref; Boolean dir; OpString folder, file; FSIORefNum refNum; ByteCount len; Boolean same = false; if (gVendorDataID == 'OPRA') { GetCurrentProcess(&this_psn); OpFileUtils::SetToMacFolder(MAC_OPFOLDER_CACHES, folder); OpString8 utf8; HFSUniStr255 dataForkName; FSGetDataForkName(&dataForkName); utf8.SetUTF8FromUTF16(folder.CStr()); if (noErr == FSPathMakeRef((const UInt8*)utf8.CStr(), &folderref, &dir)) { file.Set(folder); file.Append(OPERA_CACHE_LOCKFILE_NAME); utf8.SetUTF8FromUTF16(file.CStr()); if (noErr == FSPathMakeRef((const UInt8*)utf8.CStr(), &fileref, &dir)) { if (noErr == FSOpenFork(&fileref, dataForkName.length, dataForkName.unicode, fsRdPerm, &refNum)) { len = sizeof(psn); if (noErr == FSReadFork(refNum, fsFromStart, 0, len, &psn, &len) && (len == sizeof(psn))) { if (noErr == SameProcess(&psn, &this_psn, &same) && !same) { ProcessInfoRec info = {sizeof(ProcessInfoRec),}; if (noErr == GetProcessInformation(&psn, &info)) { if (info.processSignature == 'OPRA') { owner = false; } } } } FSCloseFork(refNum); } } if (owner) { file.Set(OPERA_CACHE_LOCKFILE_NAME); if (noErr == FSCreateFileUnicode(&folderref, file.Length(), (const UniChar*)file.CStr(), kFSCatInfoNone, NULL, NULL, NULL)) { file.Set(folder); file.Append(OPERA_CACHE_LOCKFILE_NAME); utf8.SetUTF8FromUTF16(file.CStr()); if (noErr == FSPathMakeRef((const UInt8*)utf8.CStr(), &fileref, &dir)) { if (noErr == FSOpenFork(&fileref, dataForkName.length, dataForkName.unicode, fsWrPerm, &refNum)) { len = sizeof(psn); FSWriteFork(refNum, fsFromStart, 0, len, &this_psn, &len); FSCloseFork(refNum); } } } } } } else { owner = false; } initialized = true; } return owner; } class DeleteFolder { public: DeleteFolder() {} void operator()(size_t count, const FSCatalogInfo* info, const FSRef* item) { if (info->nodeFlags & kFSNodeIsDirectoryMask) MacForEachItemInFolder(*item, DeleteFolder()); FSDeleteObject(item); } }; class DeleteUnusedCacheFolder { public: DeleteUnusedCacheFolder(OpStringC& cachePath, int iCache) { mCachePath.Set(cachePath.CStr()); mCache = iCache; } DeleteUnusedCacheFolder(const DeleteUnusedCacheFolder& copy) { mCachePath.Set(copy.mCachePath.CStr()); mCache = copy.mCache; } void operator()(size_t count, const FSCatalogInfo* info, const FSRef* item) { OpString path; Boolean same = false; ProcessSerialNumber psn = {0,0}; ProcessSerialNumber this_psn = {0,kCurrentProcess}; OpFileUtils::ConvertFSRefToUniPath(item, &path); #ifdef USE_COMMON_RESOURCES const uni_char* format = mCache ? UNI_L("opcache %08X%08X") : UNI_L("cache %08X%08X"); #else const uni_char* format = UNI_L("Cache %08X%08X"); #endif // USE_COMMON_RESOURCES int name_off = path.FindLastOf(PATHSEPCHAR); if (name_off != KNotFound) { uni_char* name = path.CStr()+name_off+1; if (2 == uni_sscanf(name, format, (unsigned int*)&psn.highLongOfPSN, (unsigned int*)&psn.lowLongOfPSN)) { if (noErr == SameProcess(&psn, &this_psn, &same) && !same) { ProcessInfoRec pinfo = {sizeof(ProcessInfoRec),}; OSStatus err = GetProcessInformation(&psn, &pinfo); if ((noErr != err) || (pinfo.processSignature != 'OPRA')) { MacForEachItemInFolder(*item, DeleteFolder()); FSDeleteObject(item); } } } } } OpString mCachePath; int mCache; }; void RemoveCacheLock() { OSStatus err = noErr; if (IsCacheFolderOwner()) { OpString folder; OpFileUtils::SetToMacFolder(MAC_OPFOLDER_CACHES, folder); FSRef cache_folder, to_delete; OpFileUtils::ConvertUniPathToFSRef(folder, cache_folder); static OpStringC cache_file(UNI_L(OPERA_CACHE_LOCKFILE_NAME)); err = FSMakeFSRefUnicode(&cache_folder, cache_file.Length(), (const UniChar*)cache_file.CStr(), kTextEncodingUnknown, &to_delete); if (noErr == err) { err = FSDeleteObject(&to_delete); } } else { // Loop twice for the Cache and OpCache folders for (int iCache = 0; iCache <= 1; iCache++) { OpString cachePath; FSRef out_folder; GetOperaCacheFolderName(cachePath, (BOOL)iCache); if (OpFileUtils::ConvertUniPathToFSRef(cachePath, out_folder)) MacForEachItemInFolder(out_folder, DeleteUnusedCacheFolder(cachePath, iCache)); } } } void CleanupOldCacheFolders() { // Loop twice for the Cache and OpCache folders for (int iCache = 0; iCache <= 1; iCache++) { OpString cachePath; GetOperaCacheFolderName(cachePath, (BOOL)iCache, TRUE); FSRef cache_folder; if (OpFileUtils::ConvertUniPathToFSRef(cachePath, cache_folder)) MacForEachItemInFolder(cache_folder, DeleteUnusedCacheFolder(cachePath, iCache)); } } extern long gVendorDataID; void RandomCharFill(void *dest, int size); void GetOperaCacheFolderName(OpString &path, BOOL bOpCache, BOOL bParentOnly) { OpFileUtils::SetToMacFolder(MAC_OPFOLDER_CACHES, path); //FIXME: Look at this code and work out what it was supposed to do... //if (bOpCache) // OpFileUtils::AppendFolder(path, UNI_L("CacheOp")); if (!bParentOnly) { // Avoid cache conflicts for vendors of Opera. if (!gVendorDataID) { RandomCharFill(&gVendorDataID, 4); } if (gVendorDataID != 'OPRA') { uni_char destBuff[8]; int len = gTextConverter->ConvertBufferFromMac((char*)&gVendorDataID,4,destBuff,7); destBuff[len] = 0; OpFileUtils::AppendFolder(path, destBuff); } else { if (IsCacheFolderOwner()) { OpFileUtils::AppendFolder(path, UNI_L("Cache")); } else { uni_char destBuff[32]; ProcessSerialNumber psn; MacGetCurrentProcess(&psn); uni_sprintf(destBuff, UNI_L("Cache %08X%08X"), psn.highLongOfPSN, psn.lowLongOfPSN); OpFileUtils::AppendFolder(path, destBuff); } } } } void CheckAndFixCacheFolderName(OpString &path) { // Avoid cache conflicts for vendors of Opera. if (!gVendorDataID) { RandomCharFill(&gVendorDataID, 4); } if (gVendorDataID != 'OPRA') { uni_char destBuff[8]; int len = gTextConverter->ConvertBufferFromMac((char*)&gVendorDataID,4,destBuff,7); destBuff[len] = 0; // Remove any slashes from the end if (path[path.Length() - 1] == PATHSEPCHAR) path.Delete(path.Length() - 1); OpFileUtils::AppendFolder(path, destBuff); } else { // Only add to the end when the cache folder is already owned by another // instance of Opera if (!IsCacheFolderOwner()) { uni_char destBuff[32]; ProcessSerialNumber psn; MacGetCurrentProcess(&psn); uni_sprintf(destBuff, UNI_L(" %08X%08X"), psn.highLongOfPSN, psn.lowLongOfPSN); // Remove any slashes from the end if (path[path.Length() - 1] == PATHSEPCHAR) path.Delete(path.Length() - 1); // Append the process id path.Append(destBuff); } } } #pragma mark - const uni_char * GetDefaultLanguage() { static uni_char language[6]; *language = 0; CFBundleRef mainBundle = NULL; CFURLRef url; FSRef fsref; OpString resPath; #ifdef USE_COMMON_RESOURCES // Create the PI interface object OpDesktopResources *dr_temp; // Just for the autopointer RETURN_VALUE_IF_ERROR(OpDesktopResources::Create(&dr_temp), NULL); OpAutoPtr<OpDesktopResources> desktop_resources(dr_temp); if(desktop_resources.get() && OpStatus::IsSuccess(desktop_resources->GetResourceFolder(resPath))) { #else OpFileUtils::SetToSpecialFolder(OPFILE_RESOURCES_FOLDER, resPath); #endif // USE_COMMON_RESOURCES if (OpFileUtils::ConvertUniPathToFSRef(resPath, fsref)) { url = CFURLCreateFromFSRef(NULL, &fsref); if (url) { mainBundle = CFBundleCreate(NULL, url); CFRelease(url); } } #ifdef USE_COMMON_RESOURCES } #endif // USE_COMMON_RESOURCES if (mainBundle) { CFURLRef langFileURL = CFBundleCopyResourceURL(mainBundle, CFSTR(""), CFSTR("lng"), kBundleNoSubDir); if (langFileURL) { CFStringRef langFilePath = CFURLCopyPath(langFileURL); if (langFilePath) { CFIndex len = CFStringGetLength(langFilePath); uni_char* pathStr = new uni_char[len + 1]; uni_char* search, * search2; CFStringGetCharacters(langFilePath, CFRangeMake(0,len), (UniChar *)pathStr); pathStr[len] = 0; search = uni_strrchr(pathStr, '/'); if (!search) { search = pathStr; } search2 = uni_strchr(search, '.'); if (search2) { *search2 = 0; if (uni_strlen(search) <= 5) { uni_strcpy(language, search); } } delete [] pathStr; CFRelease(langFilePath); } CFRelease(langFileURL); } CFRelease(mainBundle); } return language; } OP_STATUS SetBackgroundUsingAppleEvents(URL& url) { AEDesc tAEDesc = {typeNull, nil}; // always init AEDescs OSErr anErr = noErr; AliasHandle aliasHandle=nil; OpFile pictureOpFile; Boolean wasSuccess = false; FSRef pictureFSRef; OpString pictureFullPath; if(OpFileUtils::FindFolder(kPictureDocumentsFolderType, pictureFullPath, TRUE)) { OpString tmp; TRAPD(err, url.GetAttributeL(URL::KSuggestedFileName_L, tmp, TRUE)); RETURN_IF_ERROR(err); if(FindUniqueFileName(pictureFullPath, tmp)) { if( OpStatus::IsSuccess(url.SaveAsFile(pictureFullPath)) ) { wasSuccess = true; } } if(wasSuccess) { if (OpFileUtils::ConvertUniPathToFSRef(pictureFullPath.CStr(), pictureFSRef)) { // Now we create an AEDesc containing the alias to the picture if(noErr == FSNewAlias(NULL, &pictureFSRef, &aliasHandle)) { if(aliasHandle) { char handleState = HGetState( (Handle) aliasHandle ); HLock( (Handle) aliasHandle); anErr = AECreateDesc( typeAlias, *aliasHandle, GetHandleSize((Handle) aliasHandle), &tAEDesc); HSetState( (Handle) aliasHandle, handleState ); DisposeHandle( (Handle)aliasHandle ); if(anErr == noErr) { // Now we need to build the actual Apple Event that we're going to send the Finder AppleEvent tAppleEvent; OSType sig = 'MACS'; // The app signature for the Finder AEBuildError tAEBuildError; anErr = AEBuildAppleEvent(kAECoreSuite,kAESetData,typeApplSignature,&sig,sizeof(OSType), kAutoGenerateReturnID,kAnyTransactionID,&tAppleEvent,&tAEBuildError, "'----':'obj '{want:type(prop),form:prop,seld:type('dpic'),from:'null'()},data:(@)",&tAEDesc); // Finally we can go ahead and send the Apple Event using AESend if (noErr == anErr) { AppleEvent theReply = {typeNull, nil}; #ifdef NO_CARBON anErr = AESendMessage(&tAppleEvent,&theReply,kAENoReply,kAEDefaultTimeout); #else anErr = AESend(&tAppleEvent,&theReply,kAENoReply,kAENormalPriority,kNoTimeOut,nil,nil); #endif AEDisposeDesc(&tAppleEvent); // Always dispose ASAP return OpStatus::OK; } } } } } } } return OpStatus::ERR; } void MacGetBookmarkFileLocation(int format, OpString &oplocationStr) { FSRef fsref; OSErr err; switch(format) { case HotlistModel::OperaBookmark: err = FSFindFolder(kUserDomain, kPreferencesFolderType, kDontCreateFolder, &fsref); if(err == noErr) { if(OpStatus::IsSuccess(OpFileUtils::ConvertFSRefToUniPath(&fsref, &oplocationStr))) { oplocationStr.Append(PATHSEP); oplocationStr.Append("Opera 6 Preferences"); oplocationStr.Append(PATHSEP); oplocationStr.Append("Bookmarks"); } } break; case HotlistModel::ExplorerBookmark: err = FSFindFolder(kUserDomain, kPreferencesFolderType, kDontCreateFolder, &fsref); if(err == noErr) { if(OpStatus::IsSuccess(OpFileUtils::ConvertFSRefToUniPath(&fsref, &oplocationStr))) { oplocationStr.Append(PATHSEP); oplocationStr.Append("Explorer"); oplocationStr.Append(PATHSEP); oplocationStr.Append("Favorites.html"); } } break; case HotlistModel::NetscapeBookmark: // Since FireFox is more popular now it will try and grab their bookmarks first then, // if the folder doesn't exist it will just flip back to the preferences folder err = FSFindFolder(kUserDomain, kApplicationSupportFolderType, kDontCreateFolder, &fsref); if(err == noErr) { if(OpStatus::IsSuccess(OpFileUtils::ConvertFSRefToUniPath(&fsref, &oplocationStr))) { oplocationStr.Append(PATHSEP); oplocationStr.Append("Firefox"); oplocationStr.Append(PATHSEP); // Check if the folder exists OpFile file; BOOL exists = FALSE; file.Construct(oplocationStr); if(OpStatus::IsSuccess(file.Exists(exists)) && !exists) { // Could be in "Phoenix" (firebird), "Mozilla", "Netscape" or the OmniWeb folder so let's just stop here. err = FSFindFolder(kUserDomain, kPreferencesFolderType, kDontCreateFolder, &fsref); if (err == noErr) OpFileUtils::ConvertFSRefToUniPath(&fsref, &oplocationStr); } } } break; case HotlistModel::KonquerorBookmark: err = FSFindFolder(kUserDomain, kDomainLibraryFolderType, kDontCreateFolder, &fsref); if(err == noErr) { if(OpStatus::IsSuccess(OpFileUtils::ConvertFSRefToUniPath(&fsref, &oplocationStr))) { oplocationStr.Append(PATHSEP); oplocationStr.Append("Safari"); oplocationStr.Append(PATHSEP); oplocationStr.Append("Bookmarks.plist"); } } break; default: break; } } #ifdef HC_CAP_NEWUNISTRLIB char *StrToLocaleEncoding(const uni_char *str) { if (!str) return NULL; int len = uni_strlen(str); UTF16toUTF8Converter converter; int len2 = converter.BytesNeeded(str, len*sizeof(uni_char)); char * result = new char [len2 + 1]; int read = 0; len2 = converter.Convert(str, len*sizeof(uni_char), result, len2, &read); result[len2] = '\0'; return result; } uni_char *StrFromLocaleEncoding(const char *str) { if (!str) return NULL; int len = strlen(str) + 1; uni_char * result = new uni_char[len]; UTF8toUTF16Converter converter; int read = 0; int written = converter.Convert(str, len-1, result, (len-1)*sizeof(uni_char), &read); result[written/sizeof(uni_char)] = '\0'; return result; } #endif /** * Fills a buffer with random characters A - Z. * * @param dest The destination buffer * @param size The number of characters to put into the buffer. */ void RandomCharFill(void *dest, int size) { const int range = 'z' - 'a'; char *pch = (char*) dest; // srand( (unsigned)time( NULL )); for( int i=0; i<size; i++) { pch[i] = 'a' + (rand() % range); } } BOOL SetOpString(OpString& dest, CFStringRef source) { if (source) { int len = CFStringGetLength(source); if (dest.Reserve(len + 1)) { CFStringGetCharacters(source, CFRangeMake(0,len), (UniChar*)dest.CStr()); dest.CStr()[len] = 0; return TRUE; } } return FALSE; } bool GetSignatureAndVersionFromBundle(CFURLRef bundleURL, OpString *signature, OpString *short_version) { // We need to grab the signature and CFBundleRef bundle_ref = CFBundleCreate(NULL, bundleURL); if(bundle_ref != NULL) { // CFBundleShortVersionString && CFBundleSignature CFStringRef bundleSignature = (CFStringRef)::CFBundleGetValueForInfoDictionaryKey(bundle_ref, CFSTR("CFBundleSignature")); CFStringRef bundleShortVersion = (CFStringRef)::CFBundleGetValueForInfoDictionaryKey(bundle_ref, CFSTR("CFBundleShortVersionString")); // Save the values into the local arrays for checking SetOpString(*signature, bundleSignature); SetOpString(*short_version, bundleShortVersion); CFRelease(bundle_ref); return true; } return false; } OpPoint ConvertToScreen(const OpPoint &point, OpWindow* pw, MDE_OpView* pv) { OpPoint p = point; INT32 dx, dy; while(pv || pw) { if(pv) { pv->GetPos(&dx, &dy); pw = pv->GetParentWindow(); pv = pv->GetParentView(); } else { pw->GetInnerPos(&dx, &dy); BOOL native = ((CocoaOpWindow*)pw)->IsNativeWindow(); if(!native) { pv = (MDE_OpView*)pw->GetParentView(); pw = pw->GetParentWindow(); } else { pv = NULL; pw = NULL; } } p.x += dx; p.y += dy; } return p; } void SendMenuHighlightToScope(CFStringRef item_title, BOOL main_menu, BOOL is_submenu) { // If scope is up and running send the information about the menu item that was just highlighted to it if (g_scope_manager->desktop_window_manager && g_scope_manager->desktop_window_manager->GetSystemInputPI()) { OpString menu_item_title; // Convert to OpString if (SetOpString(menu_item_title, item_title)) static_cast<MacSystemInputPI*>(g_scope_manager->desktop_window_manager->GetSystemInputPI())->MenuItemHighlighted(menu_item_title, main_menu, is_submenu); } } void SendMenuTrackingToScope(BOOL tracking) { // If scope is up and running send the information if a menu is up if (g_scope_manager->desktop_window_manager && g_scope_manager->desktop_window_manager->GetSystemInputPI()) { static_cast<MacSystemInputPI*>(g_scope_manager->desktop_window_manager->GetSystemInputPI())->MenuTracking(tracking); } } void SendSetActiveNSMenu(void *nsmenu) { // If scope is up and running send the information about which is the currently active menu if (g_scope_manager->desktop_window_manager && g_scope_manager->desktop_window_manager->GetSystemInputPI()) { static_cast<MacSystemInputPI*>(g_scope_manager->desktop_window_manager->GetSystemInputPI())->SetActiveNSMenu(nsmenu); } } void *GetActiveMenu() { void *active_menu = NULL; // Need to loop the menu and list all the items in it if (g_scope_manager->desktop_window_manager && g_scope_manager->desktop_window_manager->GetSystemInputPI()) active_menu = static_cast<MacSystemInputPI*>(g_scope_manager->desktop_window_manager->GetSystemInputPI())->GetActiveNSMenu(); return active_menu; } void SendSetActiveNSPopUpButton(void *nspopupbutton) { // If scope is up and running send the information about which is the currently active menu if (g_scope_manager->desktop_window_manager && g_scope_manager->desktop_window_manager->GetSystemInputPI()) { static_cast<MacSystemInputPI*>(g_scope_manager->desktop_window_manager->GetSystemInputPI())->SetActiveNSPopUpButton(nspopupbutton); } } void PressScopeKey(OpKey::Code key, ShiftKeyState modifier) { if (g_scope_manager->desktop_window_manager && g_scope_manager->desktop_window_manager->GetSystemInputPI()) { g_scope_manager->desktop_window_manager->GetSystemInputPI()->PressKey(0, key, modifier); } }
#include "card.h" #include <cstdlib> using namespace std; string card::get_card_suit(){ return suit; } int card::get_card_rank(){ return rank; } void card::set_card_suit(string card_suit){ suit = card_suit; } void card::set_card_rank(int card_rank){ rank = card_rank; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ /** @file user.cpp * Misc userinterface functions. * (interface for this file is in user.h) */ #include "core/pch.h" #include "platforms/windows/user.h" #include "adjunct/quick/managers/KioskManager.h" #include "adjunct/desktop_pi/desktop_pi_util.h" #include "adjunct/desktop_util/sound/SoundUtils.h" #include "modules/dochand/winman.h" #include "modules/dochand/winman_constants.h" #include "modules/history/direct_history.h" #include "modules/history/OpHistoryModel.h" #include "modules/logdoc/urlimgcontprov.h" #include "modules/prefs/prefsmanager/collections/pc_doc.h" #include "modules/prefs/prefsmanager/collections/pc_mswin.h" #include "modules/display/prn_info.h" #include "modules/util/filefun.h" #include "adjunct/desktop_util/filelogger/desktopfilelogger.h" #ifdef _DDE_SUPPORT_ # include "platforms/windows/userdde.h" #endif //_DDE_SUPPORT_ #include "platforms/windows/windows_ui/printwin.h" #include "platforms/windows/windows_ui/res/opera.h" #include "platforms/windows/pi/WindowsOpMessageLoop.h" #include "platforms/windows/pi/WindowsOpScreenInfo.h" #include "platforms/windows/pi/WindowsOpTimeInfo.h" #include "platforms/windows/pi/WindowsOpSystemInfo.h" #include "platforms/windows/windows_ui/menubar.h" #include "platforms/windows/user_fun.h" #include "platforms/windows/windows_ui/rasex.h" #include "platforms/windows/windows_ui/msghook.h" #include <locale.h> class NullAppMenuListener; #undef PostMessage #define PostMessage PostMessageU NullAppMenuListener* g_null_menu_listener = NULL; HCURSOR hWaitCursor, hArrowCursor, hArrowWaitCursor, hLinkCursor, hSplitterCursor, hVSplitterCursor, hSizeAllCursor; HCURSOR hDragCopyCursor, hDragMoveCursor, hDragBadCursor; WindowsOpWindow* g_main_opwindow = NULL; UINT main_timer_id = 0; #if defined(_DDE_SUPPORT_) && !defined(_NO_GLOBALS_) DDEHandler *ddeHandler = 0; #endif // _DDE_SUPPORT_ && _NO_GLOBALS_ time_t LastUserInteraction = -1; BOOL OnCreateMainWindow() { OP_PROFILE_METHOD("Created main window"); if ((g_main_opwindow = new WindowsOpWindow) == NULL) return FALSE; g_main_opwindow->m_hwnd = g_main_hwnd; main_timer_id = 1; main_timer_id = SetTimer(g_main_hwnd, main_timer_id, 100, NULL); { OP_PROFILE_METHOD("Bootstrap booted"); RETURN_VALUE_IF_ERROR(g_desktop_bootstrap->Boot(), FALSE); } #ifdef _PRINT_SUPPORT_ { OP_PROFILE_METHOD("Initialized printer settings"); InitPrinterSettings(g_main_hwnd); } #endif // _PRINT_SUPPORT_ hArrowCursor = LoadCursor(NULL, IDC_ARROW); hWaitCursor = LoadCursor(NULL, IDC_WAIT); hArrowWaitCursor = LoadCursor(NULL, IDC_APPSTARTING); hLinkCursor = LoadCursor(NULL, MAKEINTRESOURCE(32649)); // IDC_HAND if (hLinkCursor == NULL) { hLinkCursor = LoadCursorA(hInst, "SELECT"); // (was: hLinkCursor) } hDragCopyCursor = LoadCursorA(hInst, "DRAGCOPY"); hDragMoveCursor = LoadCursorA(hInst, "DRAGMOVE"); hDragBadCursor = LoadCursorA(hInst, "NODROP"); hSplitterCursor = LoadCursor(NULL, IDC_SIZENS); hVSplitterCursor = LoadCursor(NULL, IDC_SIZEWE); hSizeAllCursor = LoadCursor(NULL, IDC_SIZEALL); return TRUE; } void OnDestroyMainWindow() { // we are going down /** * DSK-330450 * * This is a workaround and the problem it fixes should be looked more closely at. * julienp: The problem is that core gets destroyed as a result of the main window being destroyed while core still holds resources * related to other windows that haven't been destroyed, if something happen to send WM_CLOSE to the main window before the other * windows are closed. */ if (g_application && g_application->GetActiveDesktopWindow()) g_application->GetActiveDesktopWindow()->Close(TRUE); #ifndef NS4P_COMPONENT_PLUGINS g_windows_message_loop->SetIsExiting(); #endif // !NS4P_COMPONENT_PLUGINS g_desktop_bootstrap->ShutDown(); g_main_opwindow->m_hwnd = NULL; delete g_main_opwindow; g_main_opwindow = NULL; if (main_timer_id) { KillTimer(g_main_hwnd, main_timer_id); } if(hWaitCursor) { DestroyCursor(hWaitCursor); } if(hArrowCursor) { DestroyCursor(hArrowCursor); } if(hArrowWaitCursor) { DestroyCursor(hArrowWaitCursor); } if(hLinkCursor) { DestroyCursor(hLinkCursor); } if(hSplitterCursor) { DestroyCursor(hSplitterCursor); } if(hVSplitterCursor) { DestroyCursor(hVSplitterCursor); } if(hSizeAllCursor) { DestroyCursor(hSizeAllCursor); } if (hLinkCursor) { DestroyCursor(hLinkCursor); } if (hDragCopyCursor) { DestroyCursor(hDragCopyCursor); } if (hDragMoveCursor) { DestroyCursor(hDragMoveCursor); } if (hDragBadCursor) { DestroyCursor(hDragBadCursor); } #ifdef _PRINT_SUPPORT_ ClearPrinterSettings(); #endif // _PRINT_SUPPORT_ #ifdef _DDE_SUPPORT_ if (ddeHandler) ddeHandler->Stop(TRUE); #endif PostQuitMessage(0); } BOOL IsPluginWnd( HWND hWnd, BOOL fTestParents) { BOOL fMatch=FALSE; #ifdef _PLUGIN_SUPPORT_ extern ATOM atomPluginWindowClass; HWND hWndToCheck = hWnd; do { fMatch = IsOfWndClass( hWndToCheck, atomPluginWindowClass); if (fTestParents) hWndToCheck = GetParent(hWndToCheck); } while( fTestParents && !fMatch && hWndToCheck); #endif if (fMatch) { return fMatch; } return fMatch; } BOOL SetFontDefault(PLOGFONT pLFont) { pLFont->lfHeight = 13; pLFont->lfWidth = 0; pLFont->lfEscapement = 0; pLFont->lfOrientation = 0; pLFont->lfWeight = FW_NORMAL; pLFont->lfItalic = FALSE; pLFont->lfUnderline = FALSE; pLFont->lfStrikeOut = FALSE; pLFont->lfCharSet = DEFAULT_CHARSET; pLFont->lfOutPrecision = OUT_DEFAULT_PRECIS; pLFont->lfClipPrecision = CLIP_DEFAULT_PRECIS; pLFont->lfQuality = DEFAULT_QUALITY; pLFont->lfPitchAndFamily = DEFAULT_PITCH|FF_DONTCARE; lstrcpy(pLFont->lfFaceName, UNI_L("System")); return TRUE; } // WINDOW MESSAGE LRESULT ucClose(HWND hWnd, BOOL fAskUser) { // we cannot exit if in SDI and main window is disabled.. that means dialogs are up and running! if (!IsWindowEnabled(g_main_hwnd)) return FALSE; if (KioskManager::GetInstance()->GetNoExit()) { BOOL correct_password = FALSE; if (!correct_password) { return FALSE; } } // Close dial-up connections ? #if defined(_RAS_SUPPORT_) OpRasEnableAskCloseConnections(g_pcmswin->GetIntegerPref(PrefsCollectionMSWIN::ShowCloseRasDialog)); // prefsManager might be gone in few moments if ( OpRasAskCloseConnections( GetDesktopWindow(), TRUE) == IDCANCEL) return FALSE; #endif OpStringC endsound = g_pcui->GetStringPref(PrefsCollectionUI::EndSound); OpStatus::Ignore(SoundUtils::SoundIt(endsound, FALSE, FALSE));//FIXME:OOM // else handle OOM condition return DefWindowProc(hWnd,WM_CLOSE,0,0); } // ___________________________________________________________________________ // ��������������������������������������������������������������������������� // ucTimer4TimesASecond // // Returns TRUE if a 1/4 sec (or more) has elapsed since the prev. // time it was called. // // Timer resolution (using SetTimer) is 55 ms. This functions will return // TRUE for each 1/4 second at average. One single call might be off but // at average it will be correct. // ___________________________________________________________________________ // BOOL ucTimer4TimesASecond() { BOOL f250msElapsed = FALSE; static DWORD dw250msCounter = 0; static DWORD dwPrev = GetTickCount(); DWORD dwNow = GetTickCount(); DWORD dwElap = dwNow - dwPrev; dw250msCounter += dwElap; dwPrev = dwNow; if (dw250msCounter>=250) { dw250msCounter %= 250; f250msElapsed = TRUE; } return f250msElapsed; } // ___________________________________________________________________________ // ��������������������������������������������������������������������������� // ucTimer // Called for each 110 ms (SetTimer() does not give excact values) // ___________________________________________________________________________ // LRESULT ucTimer(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) { static BYTE count = 0; static ST_MESSAGETYPE stringType = ST_ASTRING; // Window* window = g_application ? g_application->GetActiveWindow() : NULL; if (!g_windowManager || !g_timecache) return FALSE; if (wParam == ID_TIMER_DELAYED_MSG_CONTROL) return FALSE; BOOL fQuarterOfASecondsHasElapsed = ucTimer4TimesASecond(); if (fQuarterOfASecondsHasElapsed) { if (g_windowManager) g_windowManager->OnTimer(); } if (!((count+1)%3)) CheckForValidOperaWindowBelowCursor(); count ++; if (count == 9) { count = 0; #ifdef HAVE_TIMECACHE g_timecache->UpdateCurrentTime(); #elif defined(PREFSMAN_USE_TIMECACHE) prefsManager->UpdateCurrentTime(); #endif g_url_api->CheckTimeOuts(); #ifdef _TRANSFER_WINDOW_SUPPORT_ if (transferWindow) transferWindow->UpdateProgress(); #endif } return DefWindowProc(hWnd,message,wParam,lParam); } BOOL ResetStation() { if(KioskManager::GetInstance()->GetEnabled()) //be more agressive in kioskmode { if(KioskManager::GetInstance()->GetKioskResetStation() || KioskManager::GetInstance()->GetResetOnExit()) { if(g_url_api) { g_url_api->CleanUp(); g_url_api->PurgeData(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE); } if(globalHistory) { g_globalHistory->DeleteAllItems(); g_globalHistory->Save(TRUE); } if(directHistory) { g_directHistory->DeleteAllItems(); g_directHistory->Save(TRUE); } } } return TRUE; } LRESULT ucWMDrawItem(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { LPDRAWITEMSTRUCT item = (LPDRAWITEMSTRUCT) lParam; if (item->CtlType == ODT_MENU && g_windows_menu_manager) { return g_windows_menu_manager->OnDrawItem(hWnd, item); } return DefWindowProc(hWnd, message, wParam, lParam); } // WM_MEASUREITEM LRESULT ucMeasureItem(HWND hWnd,UINT message,WPARAM wParam,LPARAM lParam) { LPMEASUREITEMSTRUCT item = (LPMEASUREITEMSTRUCT) lParam; if (item->CtlType == ODT_MENU && g_windows_menu_manager) { return g_windows_menu_manager->OnMeasureItem(hWnd, item); } return DefWindowProc(hWnd, message, wParam, lParam); } // ___________________________________________________________________________ // ��������������������������������������������������������������������������� // OnSystemSettingChanged // ___________________________________________________________________________ // void OnSettingsChanged() { if (g_op_system_info) { ((WindowsOpSystemInfo*)g_op_system_info)->OnSettingsChanged(); } if (g_op_time_info) { ((WindowsOpTimeInfo*)g_op_time_info)->OnSettingsChanged(); } if (g_op_screen_info) { ((WindowsOpScreenInfo*)g_op_screen_info)->OnSettingsChanged(); } if (g_application) { g_application->SettingsChanged(SETTINGS_SYSTEM_SKIN); } } //----------------------------------------------------------------------------------------- static BOOL WriteBitmapToFile(OpString* filename, OpBitmap* bitmap) { if( !(bitmap && filename && filename->HasContent()) ) { return FALSE; } HANDLE fh; DWORD dwWritten; UINT32 width = bitmap->Width(); UINT32 height = bitmap->Height(); UINT8 bpp = 32; // always get bitmap data in 32 bit //First set up headers UINT32 header_size = sizeof(BITMAPINFOHEADER); BITMAPINFO bmpi; bmpi.bmiHeader.biSize = header_size; bmpi.bmiHeader.biWidth = width; bmpi.bmiHeader.biHeight = height; bmpi.bmiHeader.biPlanes = 1; bmpi.bmiHeader.biBitCount = bpp; bmpi.bmiHeader.biCompression = BI_RGB; bmpi.bmiHeader.biSizeImage = 0; bmpi.bmiHeader.biXPelsPerMeter = 0; bmpi.bmiHeader.biYPelsPerMeter = 0; bmpi.bmiHeader.biClrUsed = 0; bmpi.bmiHeader.biClrImportant = 0; UINT32 bytes_per_line = width * (bpp >> 3); UINT32 len = bytes_per_line * height + header_size; BITMAPFILEHEADER fileheader; fileheader.bfType = ((WORD) ('M' << 8) | 'B'); // is always "BM" fileheader.bfSize = len + sizeof(BITMAPFILEHEADER); fileheader.bfReserved1 = 0; fileheader.bfReserved2 = 0; fileheader.bfOffBits= (DWORD) (sizeof( fileheader ) + bmpi.bmiHeader.biSize ) + sizeof(RGBQUAD); HANDLE hGmem = GlobalAlloc(GHND | GMEM_DDESHARE, len); if (!hGmem) { return FALSE; } LPSTR buffer = (LPSTR) GlobalLock(hGmem); memcpy(buffer, &bmpi, header_size); // write all bitmap data into the clipboard bitmap for (UINT32 line = 0; line < height; line++) { bitmap->GetLineData(&buffer[line * bytes_per_line + header_size], height - line - 1); } GlobalUnlock(hGmem); fh = CreateFile(filename->CStr(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (fh == INVALID_HANDLE_VALUE) { GlobalFree(hGmem); return FALSE; } // Write the file header WriteFile(fh, (LPSTR)&fileheader, sizeof(BITMAPFILEHEADER), &dwWritten, NULL); // Write the DIB WriteFile(fh, buffer, len, &dwWritten, NULL); CloseHandle(fh); GlobalFree(hGmem); return TRUE; } OP_STATUS DesktopPiUtil::SetDesktopBackgroundImage(URL& url) { OpString tmp; RETURN_IF_LEAVE(url.GetAttributeL(URL::KSuggestedFileName_L, tmp, TRUE)); OpString osTmp; RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_PICTURES_FOLDER, osTmp)); RETURN_IF_ERROR(osTmp.Append(tmp)); OpString osNewSkinFile; RETURN_IF_ERROR(GetUniqueFileName(osTmp, osNewSkinFile)); Image img = UrlImageContentProvider::GetImageFromUrl(url); if(img.IsEmpty()) { return OpStatus::ERR; } osNewSkinFile.Delete(osNewSkinFile.FindLastOf('.')); RETURN_IF_ERROR(osNewSkinFile.Append(".bmp")); OpBitmap* bitmap = img.GetBitmap(NULL); if(!bitmap) { return OpStatus::ERR; } if(!WriteBitmapToFile(&osNewSkinFile, bitmap) ) { img.ReleaseBitmap(); return OpStatus::ERR; } img.ReleaseBitmap(); if( !SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID)osNewSkinFile.CStr(), SPIF_SENDCHANGE) ) { return OpStatus::ERR; } if (!SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID)osNewSkinFile.CStr(), SPIF_UPDATEINIFILE) ) { return OpStatus::ERR; } return OpStatus::OK; }
// Copyright (c) 2013 Nick Porcino, All rights reserved. // License is MIT: http://opensource.org/licenses/MIT #include "LandruCompiler/AST.h" #include "LandruCompiler/lcRaiseError.h" #include <string> #include <map> #include <set> namespace Landru { int ASTNode::inParamList = 0; ASTNode::~ASTNode() { for (ASTConstIter i = children.begin(); i != children.end(); ++i) delete *i; } void ASTNode::printParameters(int tabs) const { ++inParamList; switch (token) { case kTokenParameters: if (children.begin() != children.end()) { ASTConstIter i = children.begin(); for ( ; i != children.end(); ++i) { (*i)->print(tabs); } } break; default: lcRaiseError("AST Error: This node is supposed to be a parameter node", 0, 0); break; } --inParamList; } void ASTNode::printQualifier() const { switch (token) { case kTokenEq: case kTokenLte0: case kTokenGte0: case kTokenLt0: case kTokenGt0: case kTokenEq0: case kTokenNotEq0: printf("%s", tokenName(token)); break; case kTokenFunction: printf("%s", str2.c_str()); break; default: lcRaiseError("AST Error: Unknown qualifier\n", 0, 0); break; } } void ASTNode::printChildParameters() const { ASTConstIter i = children.begin(); if (i != children.end()) { (*i)->printParameters(); ++i; if (i != children.end()) lcRaiseError("AST Error: Found more than just parameters under this node", 0, 0); } else { lcRaiseError("AST Error: parameters missing", 0, 0); } } void ASTNode::printChildStatements(int tabs) const { ASTConstIter i = children.begin(); if (i != children.end()) { (*i)->printStatements(tabs); ++i; if (i != children.end()) lcRaiseError("AST Error: Found more than just statements under this node\n", 0, 0); } else { lcRaiseError("AST Error: statements missing\n", 0, 0); } } void ASTNode::printStatements(int tabs) const { if (token != kTokenStatements) { lcRaiseError("AST Error: should be statements token\n", 0, 0); } for (ASTConstIter i = children.begin(); i != children.end(); ++i) { (*i)->print(tabs); } } void ASTNode::print(int tabs) const { static char* tabChars = (char*) "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; static int maxTabs = (int) strlen(tabChars); if (tabs > maxTabs) tabs = maxTabs; const char* tabStr = tabChars + maxTabs - tabs; ASTConstIter i = children.begin(); switch (token) { case kTokenDeclare: printf("%s%s:\n", tabStr, tokenName(token)); for ( ; i != children.end(); ++i) (*i)->print(tabs+1); printf("%s;\n\n", tabStr); break; case kTokenDataObject: if (children.size() == 0) printf("%s{}\n", tabStr); else { printf("%s{", tabStr); for ( ; i != children.end(); ++i) (*i)->print(tabs+1); printf("%s}\n", tabStr); } break; case kTokenDataArray: if (children.size() == 0) printf("%s[]\n", tabStr); else { printf("%s[", tabStr); for ( ; i != children.end(); ++i) (*i)->print(tabs+1); printf("%s]\n", tabStr); } break; case kTokenStaticData: for ( ; i != children.end(); ++i) (*i)->print(tabs+1); break; case kTokenRequire: printf("%srequire(\"%s\")\n", tabStr, str2.c_str()); break; case kTokenDataElement: printf("%s\"%s\" : ", tabStr, str2.c_str()); break; case kTokenStringLiteral: printf("%s\"%s\" ", tabStr, str2.c_str()); break; case kTokenIntLiteral: printf("%s%d ", tabStr, intVal); break; case kTokenFloatLiteral: printf("%s%f ", tabStr, floatVal1); break; case kTokenRangedLiteral: printf("%s<%f, %f> ", tabStr, floatVal1, floatVal2); break; case kTokenGetVariable: printf("%s%s ", tabStr, str2.c_str()); break; case kTokenGetVariableReference: printf("%s@%s ", tabStr, str2.c_str()); break; case kTokenAssignment: printf("%s%s = ", tabStr, str2.c_str()); /// @TODO, assignment should have a parameter list under it (*i)->print(tabs+1); ++i; break; case kTokenInitialAssignment: printf("%sinitialAssignment %s = ", tabStr, str2.c_str()); /// @TODO, assignment should have a parameter list under it (*i)->print(tabs + 1); ++i; break; case kTokenSharedVariable: printf("%sshared %s %s\n", tabStr, str1.c_str(), str2.c_str()); break; case kTokenLocalVariable: printf("%s%s %s\n", tabStr, str1.c_str(), str2.c_str()); break; case kTokenGlobalVariable: printf("\n%s%s = ", tabStr, str2.c_str()); for ( ; i != children.end(); ++i) (*i)->print(tabs); break; case kTokenIf: case kTokenOn: printf("%s%s ", tabStr, tokenName(token)); if (i != children.end()) { (*i)->printQualifier(); if ((*i)->children.size() > 0) { printf("("); (*i)->printChildParameters(); printf(")"); } printf(":\n"); ++i; (*i)->printStatements(tabs+1); ++i; printf("%s;\n", tabStr); if (i != children.end()) { // else printf("%s%s:\n", tabStr, tokenName((*i)->token)); (*i)->printChildStatements(tabs+1); ++i; printf("%s;\n", tabStr); } } break; case kTokenFunction: case kTokenLaunch: if (token == kTokenFunction) printf("%s%s(", tabStr, str2.c_str()); else printf("%s%s(", tabStr, tokenName(token)); (*i)->printParameters(); printf(")%s", inParamList ? " " : "\n"); ++i; break; case kTokenDotChain: case kTokenTrue: case kTokenFalse: printf("%s ", tokenName(token)); break; case kTokenMachine: printf("\n%s%s %s:\n", tabStr, tokenName(token), str2.c_str()); for ( ; i != children.end(); ++i) (*i)->print(tabs+1); printf("%s;\n\n", tabStr); break; case kTokenState: printf("%s%s %s:\n", tabStr, tokenName(token), str2.c_str()); (*i)->printStatements(tabs+1); ++i; printf("%s;\n\n", tabStr); break; case kTokenProgram: printf("//%s%s %s:\n", tabStr, tokenName(token), str2.c_str()); for ( ; i != children.end(); ++i) (*i)->print(tabs); break; case kTokenGoto: printf("%s%s %s\n", tabStr, tokenName(token), str2.c_str()); break; default: { const char* tn = tokenName(token); lcRaiseError("AST Error: Unhandled token\n", tn, (int) strlen(tn)); } break; } if (i != children.end()) { lcRaiseError("AST Error: children dangling\n", 0, 0); } } void ASTNode::dump(int tabs) const { static char* tabChars = (char*) "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t"; static int maxTabs = static_cast<int>(strlen(tabChars)); if (tabs > maxTabs) tabs = maxTabs; const char* tabStr = tabChars + maxTabs - tabs; switch (token) { case kTokenStringLiteral: printf("%s%s: %s\n", tabStr, tokenName(token), str2.c_str()); break; case kTokenIntLiteral: printf("%s%s: %d\n", tabStr, tokenName(token), intVal); break; case kTokenFloatLiteral: printf("%s%s: %f\n", tabStr, tokenName(token), floatVal1); break; case kTokenRangedLiteral: printf("%s%s: <%f, %f>\n", tabStr, tokenName(token), floatVal1, floatVal2); break; default: printf("%s%s: %s\n", tabStr, tokenName(token), str2.c_str()); break; } for (auto i : children) i->dump(tabs+1); } std::string ASTNode::toJson() const { printf("{ \"%s\" : \"%s\"", tokenName(token), str2.c_str()); if (children.size() > 0) { printf(", c : [\n"); for (ASTConstIter i = children.begin(); i != children.end(); ++i) { (*i)->toJson(); printf(","); } printf("]\n"); } printf("}\n"); return ""; } } // Landru
class Solution { public: bool isPerfectSquare(int num) { for (long int i=1; i*i <= num; i++) { if ((num > 0 ) && (num % i == 0) && (num/i == i)) { return true; } } return false; // long int i =1; // for( ; i*i<num; i++); // return i*i==num; // OR // 1 = 1 // 1+3 = 4 // 1 + 3 + 5 = 9 // 1 + 3 + 5 + 7 = 16 // int i=1; // while(num>0){ // num -= i; //Subtracting odd number from num and updating num // i +=2; // Updating i to the next odd number // if(!num) return true; // } // return false; } };
#include "eventplanner.h" #include "ui_eventplanner.h" EventPlanner::EventPlanner(QWidget *parent) : QMainWindow(parent), ui(new Ui::EventPlanner) { ui->setupUi(this); setWindowTitle("EventPlanner"); } EventPlanner::~EventPlanner() { delete ui; } void EventPlanner::on_pushButton_clicked() { this->hide(); emit AddingModeshow(); } void EventPlanner::on_pushButton_2_clicked() { this->hide(); emit AdminModeshow(); } void EventPlanner::getMode1() { this->show(); } void EventPlanner::getMode2() { this->show(); } void EventPlanner::on_pushButton_3_clicked() { QMessageBox::about(this,"About us",tr("We are team J-Hawk!!\n" "\n" "Email: whatever@ku.edu\n" "\n" "Team members: Martin, Kevin, Jean, Simon\n")); } void EventPlanner::on_pushButton_4_clicked() { QMessageBox::about(this,"Help",tr("How to use EventPlanner:\n" "You can choose two different Modes by click their Button \n\n" " A.In EventAdmin Mode:\n" " ...You can add any event you want, but you have to have all the detail for your event.\n" " ...The time slots do not have to be contiguous but must fall within the 24-hours of a given date.\n" " ...An event can span multiple time slots (e.g. a two-hour event would occupy four time slots).\n" " ...The date must be a real one (e.g. no February 30th).\n\n" " B.In Adding Mode:\n" " ...You can search by EventName or date or directly.\n" " ...Clicking An Event, it will ask you 'Do you want it?'.\n" " ...You can canncel an Event, click the canncel button.")); }
/* -*- coding: utf-8 -*- !@time: 2019-09-16 15:00 !@author: superMC @email: 18758266469@163.com !@fileName: environment.h */ #ifndef SELF_LEETCODE_ENVIROMENT_H #define SELF_LEETCODE_ENVIROMENT_H #include <algorithm> #include <iostream> #include <utility> #include <vector> #include <unordered_map> #include <sstream> #include <stack> #include <map> #include <queue> #include <functional> #include <cmath> using std::stack; using std::unordered_map; using std::map; using std::pair; using std::vector; using std::string; using std::cout; using std::endl; using std::cin; using std::to_string; using std::stringstream; using std::sort; using std::map; using std::max; using std::min; using std::function; namespace self_envs { struct RandomListNode { int label; struct RandomListNode *next, *random; explicit RandomListNode(int x) : label(x), next(nullptr), random(nullptr) { } }; struct ListNode { int val; ListNode *next; //make me can use ListNode(5) //lambda; explicit ListNode(int x) : val(x), next(nullptr) { } }; struct TreeNode { int val; TreeNode *left; TreeNode *right; explicit TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} }; struct graphNode { int val{}; vector<graphNode *> neighbors; graphNode() = default; explicit graphNode(int _val) { val = _val; } graphNode(int _val, vector<graphNode *> _neighbors) { val = _val; neighbors = std::move(_neighbors); } }; struct TreeLinkNode { int val; struct TreeLinkNode *left; struct TreeLinkNode *right; struct TreeLinkNode *next; explicit TreeLinkNode(int x) : val(x), left(nullptr), right(nullptr), next(nullptr) { } }; } #endif //SELF_LEETCODE_ENVIROMENT_H
#include <vector> #include <string> #include <iostream> #include <fstream> #include <sstream> #include <list> #include <algorithm> #include <sstream> #include <set> #include <cmath> #include <map> #include <stack> #include <queue> #include <stdio.h> #include <string.h> using namespace std; class ColorfulRabbits { public: int getMinimum(vector <int> replies) { map<int , int> cnt; for (int i=0; i<replies.size(); ++i) { cnt[replies[i]]++; } int ans = 0; for (map<int, int>::iterator s=cnt.begin(),e=cnt.end(); s!=e; ++s) { int num = ( (*s).second-1 ) / ( (*s).first+1 ) + 1; ans += num * ((*s).first+1); } return ans; } };
// Author: Miles Meacham // Course: CS-1410-X01-deBry-Fall 2015 // Instructor: Professor deBry // File: Driver.cpp // Date: 9/10/2015 // Contents: lab03 Assignment Rectangle Class Driver File // I delcare that the following source code was written solely by me, or provided by the instructor. // I understand that copying any source code, in whole or in part, constitutes cheating, and // that I will receive a zero in this assignment if I am found in violation of this policy. // ---------------------------------------- #include <iostream> #include "MyRectangle.h" using namespace std; //declaring variables to be used const int HEIGHT = 4; const int WIDTH = 7; int main() { //creating a new rectangle named "rectangle" MyRectangle rectangle(HEIGHT, WIDTH); //Outputing the height, width, and area of the rectangle using the class functions cout << "The height of your rectangle is " << rectangle.getHeight() << endl; cout << "The width of your rectangle is " << rectangle.getWidth() << endl; cout << "The area of your rectangle is " << rectangle.getArea() << endl << endl; system("Pause"); }
#include <cppunit/extensions/HelperMacros.h> #include "util/ThreadWrapperAsyncWork.h" using namespace Poco; using namespace std; namespace BeeeOn { class ThreadWrapperAsyncWorkTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(ThreadWrapperAsyncWorkTest); CPPUNIT_TEST(testJoin); CPPUNIT_TEST(testCancel); CPPUNIT_TEST_SUITE_END(); public: void testJoin(); void testCancel(); protected: void runFast(); }; CPPUNIT_TEST_SUITE_REGISTRATION(ThreadWrapperAsyncWorkTest); void ThreadWrapperAsyncWorkTest::testJoin() { Thread thread; ThreadWrapperAsyncWork<> work(thread); thread.startFunc([]() {}); CPPUNIT_ASSERT(work.tryJoin(10 * Timespan::SECONDS)); CPPUNIT_ASSERT(!thread.isRunning()); } void ThreadWrapperAsyncWorkTest::testCancel() { Thread thread; ThreadWrapperAsyncWork<> work(thread); thread.startFunc([]() {}); CPPUNIT_ASSERT_NO_THROW(work.cancel()); CPPUNIT_ASSERT(!thread.isRunning()); } }
#include<iostream> using namespace std; typedef struct node { int a; struct node *next; }Node; node *head, *end1; void create(){ node *temp = new Node; cin>>temp->a; temp->next=NULL; if(head == NULL) { head = temp; end1 = temp; } else { end1->next = temp; end1 = temp; } } void reverselist() { node *temp, *p1, *p2, *p3; temp = head; p1 = NULL; p2 = head; p3 = p2->next; while(p3!=NULL) { p2->next = p1; p1 = p2; p2 = p3; p3 = p2->next; } p2->next = p1; p1 = p2; p2 = p3; head = p1; } void recursivereverse(node *head) { node *first, *rest; first = head; rest = first->next; if(rest == NULL) return; recursivereverse(rest); first->next->next = first; first->next = NULL; head = rest; } void traverse() { node *temp = head; while(temp!=NULL) { cout<<temp->a; temp=temp->next; } } int main() { head = NULL; int n; cin>>n; while(n--) { create(); } //reverselist(); recursivereverse(head); traverse(); }
#include "SubmitWidget.h" #include "MainWindow.h" #include <QMessageBox> SubmitWidget::SubmitWidget(QMainWindow *parent, Json::Value &loginResponse, SocketManager *socketManager) : QWidget(), parentWindow(parent), loginResponse(loginResponse), socketManager(socketManager) { setGUI(); //TODO : make thread //createReadThread(); //readThread = new ReadThread(socketManager); //readThread->start(); } void SubmitWidget::setGUI() { setFixedSize(600, 400); widget_tab = new QTabWidget(); widget_tab->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored); widget_tab->setTabShape(QTabWidget::Rounded); //Submit Tab tab_submit = new QWidget(); label_problem = new QLabel("Problem"); label_language = new QLabel("Language"); label_upload = new QLabel("Upload"); label_code = new QLabel("Source Code"); text_code = new QTextEdit(); combo_problem = new QComboBox(); setProblems(loginResponse["problems"]); //combo_problem->addItem("p1"); //combo_problem->addItem("p2"); combo_language = new QComboBox(); setLanguages(loginResponse["languages"]); //combo_language->addItem("C++"); //combo_language->addItem("JAVA"); layout_grid_submit = new QGridLayout(); layout_grid_submit->addWidget(label_problem, 0, 0); layout_grid_submit->addWidget(combo_problem, 0, 1, 1, 4); layout_grid_submit->addWidget(label_language, 1, 0); layout_grid_submit->addWidget(combo_language, 1, 1, 1, 4); layout_grid_submit->addWidget(label_code, 2, 0); layout_grid_submit->addWidget(text_code, 2, 1); tab_submit->setLayout(layout_grid_submit); //buttons button_logout = new QPushButton("Logout"); button_submit = new QPushButton("Submit"); layout_grid_buttons = new QGridLayout(); layout_grid_buttons->addWidget(button_logout, 0, 0); layout_grid_buttons->addWidget(button_submit, 0, 1); //History Tab //tab_history = new QWidget(); //Add Tab, Icon Img? static QIcon Img_submit(QPixmap("./image/submit.png")); widget_tab->addTab(tab_submit, Img_submit, tr("Submit")); //static QIcon Img_history(QPixmap("history.png")); //widget_tab->addTab(tab_history, Img_history, tr("History")); //add tab widget and buttons to layout_main layout_main = new QVBoxLayout; layout_main->addWidget(widget_tab); layout_main->addLayout(layout_grid_buttons); setLayout(layout_main); //Setting Slot connect(button_submit, SIGNAL(clicked()), this, SLOT(submit())); connect(button_logout, SIGNAL(clicked()), this, SLOT(logOut())); } void SubmitWidget::setProblems(Json::Value &problems) { for(auto it = problems.begin(); it != problems.end(); ++it) { Json::Value prob = (*it); Json::Value tmp = prob["title"]; QString item = QString::fromStdString(tmp.asString()); combo_problem->addItem(item); } } void SubmitWidget::setLanguages(Json::Value &languages) { for(auto it = languages.begin(); it != languages.end(); ++it) { Json::Value lang = (*it); Json::Value tmp = lang["lang"]; QString item = QString::fromStdString(tmp.asString()); combo_language->addItem(item); } } void SubmitWidget::createReadThread() { //readThread = new Thread(); } void SubmitWidget::setLabel(QString msg) { label->setText(msg); } void SubmitWidget::submit() { QString problem = combo_problem->currentText(); QString language = combo_language->currentText(); QString code = text_code->toPlainText(); Json::Value root; root["type"] = "submit"; root["id"] = loginResponse.get("id", "").asString(); root["title"] = problem.toStdString(); root["lang"] = language.toStdString(); root["code"] = code.toStdString(); submitResponse = socketManager->send(root); doResponse(); } void SubmitWidget::doResponse() { Json::Value t = submitResponse["result"]; QString result= QString::fromStdString(t.asString()); QMessageBox msgBox; if(QString::compare(result, "true") == 0) { msgBox.setText("Correct!"); } else { //Json::Value t = submitResponse["message"]; //QString result = QString::fromStdString(t.asString()); //msgBox.setText("Wrong Answer : \n" + result); msgBox.setText("Wrong Answer"); } msgBox.setWindowTitle("Submit Result"); msgBox.exec(); } void SubmitWidget::logOut() { //this->deleteLater(); //TODO : thread detach, socket close socketManager->close(); //readThread->detach(); MainWindow *mainWindow = dynamic_cast<MainWindow *>(parentWindow); mainWindow->setLoginWidget(); } SubmitWidget::~SubmitWidget() { }
// Created on: 1993-06-22 // Created by: Martine LANGLOIS // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomToStep_MakeSurface_HeaderFile #define _GeomToStep_MakeSurface_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <GeomToStep_Root.hxx> class StepGeom_Surface; class Geom_Surface; //! This class implements the mapping between classes //! Surface from Geom and the class Surface from StepGeom which //! describes a Surface from prostep. As Surface is an abstract //! Surface this class is an access to the sub-class required. class GeomToStep_MakeSurface : public GeomToStep_Root { public: DEFINE_STANDARD_ALLOC Standard_EXPORT GeomToStep_MakeSurface(const Handle(Geom_Surface)& C); Standard_EXPORT const Handle(StepGeom_Surface)& Value() const; protected: private: Handle(StepGeom_Surface) theSurface; }; #endif // _GeomToStep_MakeSurface_HeaderFile
/* * window_manager.cpp * * * */ #include "window_manager.h" /* * private defines * */ /* * private variables * */ /* * constructor * */ window_manager::window_manager(uLCD_4DLibrary* p_lcd) : win_1(p_lcd), win_2(p_lcd), win_3(p_lcd), button_win_1(p_lcd), button_win_2(p_lcd), button_win_3(p_lcd), title(p_lcd) { m_lcd = p_lcd; win_1.set_delegate(this); win_2.set_delegate(this); win_3.set_delegate(this); button_win_1.set_delegate(this); button_win_2.set_delegate(this); button_win_3.set_delegate(this); set_manger_window(); } window_manager::~window_manager() { } /* * private functions * */ void window_manager::did_select_button(ulcd_button* button) { if(button == &button_win_1) { touch_dispatcher::shared_instance()->clear_components(); win_1.set_exemple_window_1(); } else if(button == &button_win_2) { touch_dispatcher::shared_instance()->clear_components(); win_2.set_exemple_window_2(); } else if(button == &button_win_3) { touch_dispatcher::shared_instance()->clear_components(); win_3.set_exemple_window_3(); } } void window_manager::did_select_return_button() { touch_dispatcher::shared_instance()->clear_components(); set_manger_window(); } void window_manager::set_manger_window() { m_lcd->gfx_clear_screen(); button_win_1.creat_button("Button & progress bar", Color::WHITE, Color::BLACK, 10, 10, 150, 50, ulcd_font_size_1); button_win_1.creat_button("Button & progress bar", Color::WHITE, Color::BLACK, 10, 10, 150, 50, ulcd_font_size_1); button_win_2.creat_button("Num pad & Label", Color::WHITE, Color::BLACK, 10, 2*10 + 50, 150, 50, ulcd_font_size_1); button_win_3.creat_button("Slider & progress bar", Color::WHITE, Color::BLACK, 10, 3*10 + 2*50, 150, 50, ulcd_font_size_1); title.new_label("Widgets exemples by G.S", Color::WHITE, 170, 0, 140, 300, ulcd_font_size_2, h_center, v_center); } /* * public functions * */ void window_manager::run() { touch_dispatcher::shared_instance()->touch_periodic_task(); }
// Created by: NW,JPB,CAL // Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Aspect_HatchStyle_HeaderFile #define _Aspect_HatchStyle_HeaderFile //! Definition of all available hatch styles. enum Aspect_HatchStyle { Aspect_HS_SOLID = 0, // TEL_HS_SOLID (no hatching) Aspect_HS_HORIZONTAL = 7, // TEL_HS_HORIZONTAL Aspect_HS_HORIZONTAL_WIDE = 11, // TEL_HS_HORIZONTAL_SPARSE Aspect_HS_VERTICAL = 8, // TEL_HS_VERTICAL Aspect_HS_VERTICAL_WIDE = 12, // TEL_HS_VERTICAL_SPARSE Aspect_HS_DIAGONAL_45 = 5, // TEL_HS_DIAG_45 Aspect_HS_DIAGONAL_45_WIDE = 9, // TEL_HS_DIAG_45_SPARSE Aspect_HS_DIAGONAL_135 = 6, // TEL_HS_DIAG_135 Aspect_HS_DIAGONAL_135_WIDE = 10, // TEL_HS_DIAG_135_SPARSE Aspect_HS_GRID = 3, // TEL_HS_GRID Aspect_HS_GRID_WIDE = 4, // TEL_HS_GRID_SPARSE Aspect_HS_GRID_DIAGONAL = 1, // TEL_HS_CROSS Aspect_HS_GRID_DIAGONAL_WIDE = 2, // TEL_HS_CROSS_SPARSE Aspect_HS_NB = 13, }; #endif // _Aspect_HatchStyle_HeaderFile
/* -*-C++-*- */ /* * Copyright 2016 EU Project ASAP 619706. * * 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 <iostream> #include <sstream> #include <fstream> #include <unistd.h> #include <climits> #include <limits> #include <cilk/cilk.h> #include <cilk/reducer.h> #include <cilk/cilk_api.h> #include "asap/utils.h" #include "asap/imrformat.h" #include "asap/dense_vector.h" #include "asap/sparse_vector.h" #include "asap/kmeans.h" #include "asap/normalize.h" #include <stddefines.h> #define DEF_NUM_MEANS 8 #define DEF_NUM_RUNS 1 size_t num_clusters; size_t num_runs; size_t max_iters; bool force_dense; char const * infile = nullptr; char const * outfile = nullptr; static void help(char *progname) { std::cout << "Usage: " << progname << " [-d] -i <infile> -o <outfile> -c <numclusters> " << " -m <maxiters>\n"; } static void parse_args(int argc, char **argv) { int c; extern char *optarg; num_clusters = DEF_NUM_MEANS; num_runs = DEF_NUM_RUNS; max_iters = 20; // default #ifndef NOFLAGS while ((c = getopt(argc, argv, "c:i:o:m:r:d")) != EOF) { #else while ((c = getopt(argc, argv, "c:m:r:d")) != EOF) { #endif switch (c) { case 'd': force_dense = true; break; case 'm': max_iters = atoi(optarg); break; case 'c': num_clusters = atoi(optarg); break; case 'r': num_runs = atoi(optarg); break; #ifndef NOFLAGS case 'i': infile = optarg; break; case 'o': outfile = optarg; break; #endif case '?': help(argv[0]); exit(1); } } if( num_clusters <= 0 ) fatal( "Number of clusters must be larger than 0." ); #ifndef NOFLAGS if( !infile ) fatal( "Input file must be supplied." ); if( !outfile ) fatal( "Output file must be supplied." ); #else infile = argv[1]; outfile = argv[2]; #endif std::cerr << "Number of clusters = " << num_clusters << '\n'; std::cerr << "Input file = " << infile << '\n'; std::cerr << "Output file = " << outfile << '\n'; } typedef double real; #if !VECTORIZED // real sq_dist(point const& p) const { real sq_dist(const real * d, real * p, int num_dimensions) { real sum = 0; for (int i = 0; i < num_dimensions; i++) { real diff = d[i] - p[i]; sum += diff * diff; } return sum; } #endif int main(int argc, char **argv) { struct timespec begin, end; struct timespec veryStart, veryEnd; srand( time(NULL) ); get_time( begin ); get_time( veryStart ); //read args parse_args(argc,argv); std::cerr << "Available threads: " << __cilkrts_get_nworkers() << "\n"; #if 0 typedef asap::dense_vector<size_t, real, true, asap::mm_ownership_policy> vector_type; #else typedef asap::sparse_vector<size_t, real, true, asap::mm_ownership_policy> vector_type; #endif typedef asap::word_list<std::vector<const char *>, asap::word_bank_pre_alloc> word_list; typedef asap::data_set<vector_type,word_list> data_set_type; bool is_sparse; data_set_type data_set = asap::array_read<data_set_type>( std::string( infile ), is_sparse ); std::cout << "Relation: " << data_set.get_relation() << std::endl; std::cout << "Dimensions: " << data_set.get_dimensions() << std::endl; std::cout << "Points: " << data_set.get_num_points() << std::endl; // Normalize data for improved clustering results // std::vector<std::pair<real, real>> extrema // = asap::normalize( data_set ); get_time (end); print_time("input", begin, end); // for reproducibility // srand(1); /* for( auto I=data_set.vector_cbegin(), E=data_set.vector_cend(); I != E; ++I ) { std::cout << *I << std::endl; } */ // K-means get_time (begin); typedef decltype(asap::kmeans( data_set, num_clusters, max_iters )) dset_type; dset_type* kmeans_op = nullptr; get_time (end); int stored_sse=INT_MAX; for (int j = 0 ; j < num_runs ; ++j) { dset_type *kmeans_op_j = new dset_type(std::move(asap::kmeans( data_set, num_clusters, max_iters, 1e-4 ))); if (j == 0) { stored_sse = kmeans_op_j->within_sse(); kmeans_op = kmeans_op_j; } else { if (kmeans_op_j->within_sse() < stored_sse) { delete kmeans_op; kmeans_op = kmeans_op_j; stored_sse = kmeans_op_j->within_sse(); } else { delete kmeans_op_j; } } } // std::cout << "Stored_sse after clustering is " << stored_sse << std::endl; print_time("kmeans", begin, end); // Unscale data get_time (begin); // asap::denormalize( extrema, data_set ); get_time (end); print_time("denormalize", begin, end); // Output get_time (begin); fprintf( stdout, "sparse? %s\n", ( is_sparse && !force_dense ) ? "yes" : "no" ); fprintf( stdout, "iterations: %lu\n", kmeans_op->num_iterations() ); fprintf( stdout, "within cluster SSE: %11.4lf\n", kmeans_op->within_sse() ); std::ofstream of( outfile, std::ios_base::out ); // Setup datastructure to hold the training/model data typedef asap::dense_vector<size_t, real, true, asap::mm_ownership_policy> centres_vector_type; std::vector<int> ids = {0,1,2,3,4,5,5,6,7,8,9,10,11,12,13,14,15}; std::vector<std::string> cats = {"resident","resident","resident","dynamic_resident", "dynamic_resident","dynamic_resident","commuter","commuter","commuter","visitor", "visitor","visitor","resident","resident","visitor","visitor","visitor"}; real modelFloats[17][24] = { {0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5}, {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1}, {0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0}, {0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0,0.5,0.5,0.5}, {0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0, 0.1, 0.1, 0.1}, {1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0}, {0.5,0.5,0.5,0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0}, {0.1, 0.1, 0.1,0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0}, {1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}, {0.5,0.5,0.5,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}, {0.1, 0.1, 0.1,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}, {1.0,1.0,1.0,1.0,1.0,1.0,0.5,0.5,0.5,0.5,0.5,0.5, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,0.0,0.0,0.0,0.0,0.0,0.0}, {0.5,0.5,0.5,0.5,0.5,0.5, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}, {0.0,0.0,0.0,1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}, {0.0,0.0,0.0,0.5,0.5,0.5,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0}, {0.0,0.0,0.0, 0.1, 0.1, 0.1,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0} }; // Struct to hold each training record together in a struct with dense vector for the centres struct archetipiRecord { // archetipiRecord(int i, std::string str, centres_vector_type cvt) archetipiRecord(int i, std::string str, real * cvt) : id(i), name(str), centres(cvt) {} int id; std::string name; // centres_vector_type centres; real * centres; }; // Vector of training records std::vector<archetipiRecord> archetipi; std::vector<int>::iterator itid ; std::vector<std::string>::iterator itname = cats.begin(); int ct=0; // centres_vector_type cvt(17); real* cvt; for(itid = ids.begin(); itid != ids.end(); ++itid, ++itname, ++ct) { real * fPtr = modelFloats[ct]; // cvt[ct] = modelFloats[ct]; // archetipiRecord rec(*itid, *itname, cvt); archetipiRecord rec(*itid, *itname, modelFloats[ct]); archetipi.push_back( rec ); } #if 1 // For each test cluster, find the minimum euclidean distance of the provided training clusters auto I = kmeans_op->centres().cbegin(); auto E = kmeans_op->centres().cend(); int cnt=0; for( auto II=I; II != E; ++II ) { real lowestDistance = std::numeric_limits<real>::max(); std::vector<archetipiRecord>::iterator targetCategory; // std::cout << "Classifications from Centres number " << cnt << ":" << std::endl; for(std::vector<archetipiRecord>::iterator it = archetipi.begin(); it != archetipi.end(); ++it) { // std::cout << "[ centres- " << (*II).get_value()<< std::endl; // std::cout << "[ archi- " << (*it).centres << std::endl; real distance = sq_dist((*II).get_value(), (*it).centres, 17 ); // std::cout << "II : " << *II << std::endl << "it: " << (*it).centres << std::endl; // std::cout << "Category : " << (*it).name << "Distance: " << distance << std::endl; if (distance < lowestDistance) { lowestDistance = distance; targetCategory = it; } } std::ostringstream os; os << "('" << (*targetCategory).name << "', " << *II << ")" << std::endl; std::string s = os.str(); std::replace( s.begin(), s.end(), '{', '['); std::replace( s.begin(), s.end(), '}', ']'); of << s ;// << std::endl; } #endif // Check that classifies datapoints directly with training data: #if 0 auto Idata = data_set.vector_cbegin(); auto Edata = data_set.vector_cend(); for( auto II=Idata; II != Edata; ++II ) { real lowestDistance = std::numeric_limits<real>::max(); std::vector<archetipiRecord>::iterator targetCategory; std::cout << "Classifications from Data point" << ":" << std::endl; for(std::vector<archetipiRecord>::iterator it = archetipi.begin(); it != archetipi.end(); ++it) { real distance = sq_dist((*II).get_value(), &(*it).centres[0], 24 ); std::cout << "II : " << *II << std::endl << "it: " << (*it).centres << std::endl; std::cout << "Category : " << (*it).name << " Distance: " << distance << std::endl; if (distance < lowestDistance) { lowestDistance = distance; targetCategory = it; } } // os << std::endl << "Classifications from Data Points" << std::endl; std::ostringstream os; os << "('" << (*targetCategory).name << "', " << *II << ")"; std::string s = os.str(); std::replace( s.begin(), s.end(), '{', '['); std::replace( s.begin(), s.end(), '}', ']'); of << s << std::endl; // *II == or within mcentres[?] } #endif of.close(); get_time (end); print_time("output", begin, end); print_time("complete time", veryStart, end); return 0; }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <folly/io/async/EventBase.h> #include <folly/io/async/EventBaseBackendBase.h> #include <quic/server/QuicServer.h> namespace quic { #if _WIN32 #include <mmsystem.h> #include <timeapi.h> #pragma comment(lib, "winmm.lib") struct GetBetterWindowsTimers { GetBetterWindowsTimers() { CHECK_EQ(timeBeginPeriod(1), TIMERR_NOERROR); } ~GetBetterWindowsTimers() { timeEndPeriod(1); } }; GetBetterWindowsTimers timerGetter; class WindowsEventBaseBackend : public folly::EventBaseBackendBase { public: WindowsEventBaseBackend(); explicit WindowsEventBaseBackend(event_base* evb); ~WindowsEventBaseBackend() override; event_base* getEventBase() override { return evb_; } int eb_event_base_loop(int flags) override; int eb_event_base_loopbreak() override; int eb_event_add(Event& event, const struct timeval* timeout) override; int eb_event_del(EventBaseBackendBase::Event& event) override; bool eb_event_active(Event& event, int res) override; private: event_base* evb_; }; WindowsEventBaseBackend::WindowsEventBaseBackend() { evb_ = event_base_new(); } WindowsEventBaseBackend::WindowsEventBaseBackend(event_base* evb) : evb_(evb) { if (UNLIKELY(evb_ == nullptr)) { LOG(ERROR) << "EventBase(): Pass nullptr as event base."; throw std::invalid_argument("EventBase(): event base cannot be nullptr"); } } int WindowsEventBaseBackend::eb_event_base_loop(int flags) { return event_base_loop(evb_, flags); } int WindowsEventBaseBackend::eb_event_base_loopbreak() { return event_base_loopbreak(evb_); } int WindowsEventBaseBackend::eb_event_add( Event& event, const struct timeval* timeout) { return event_add(event.getEvent(), timeout); } int WindowsEventBaseBackend::eb_event_del(EventBaseBackendBase::Event& event) { return event_del(event.getEvent()); } bool WindowsEventBaseBackend::eb_event_active(Event& event, int res) { event_active(event.getEvent(), res, 1); return true; } WindowsEventBaseBackend::~WindowsEventBaseBackend() { event_base_free(evb_); } static std::unique_ptr<folly::EventBaseBackendBase> getWindowsEventBaseBackend() { auto config = event_config_new(); event_config_set_flag(config, EVENT_BASE_FLAG_PRECISE_TIMER); auto evb = event_base_new_with_config(config); event_config_free(config); std::unique_ptr<folly::EventBaseBackendBase> backend = std::make_unique<WindowsEventBaseBackend>(evb); return backend; } #endif QuicServer::EventBaseBackendDetails QuicServer::getEventBaseBackendDetails() { EventBaseBackendDetails ret; #if _WIN32 ret.factory = &getWindowsEventBaseBackend; #else ret.factory = &folly::EventBase::getDefaultBackend; #endif return ret; } } // namespace quic
// -*- c++ -*- /* * Copyright 2016 EU Project ASAP 619706. * * 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. * * This is based on code from Pheonix++ Version 1.0, license below applies. */ /* Copyright (c) 2016, Queen's University Belfast. */ /* Based on: * Copyright (c) 2007-2011, Stanford University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Stanford University 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 STANFORD UNIVERSITY ``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 STANFORD UNIVERSITY 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 ASAP_HASHTABLE_H #define ASAP_HASHTABLE_H #include <unordered_map> #include <vector> #include <functional> #include <memory> #include <cassert> namespace asap { // storage for flexible cardinality keys template<typename Key, typename T, class Hash=std::hash<Key>, class KeyEqual = std::equal_to<Key>, class Allocator = std::allocator<std::pair<Key,T>>> class hash_table { public: typedef Key key_type; typedef T mapped_type; typedef std::pair<Key, T> value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef Hash hasher; typedef KeyEqual key_equal; typedef Allocator allocator_type; typedef value_type& reference; typedef const value_type& const_reference; // typedef typename std::allocator_traits<Allocator>::pointer pointer; // typedef typename std::allocator_traits<Allocator>::const_pointer const_pointer; // typedef iterator; // typedef const_iterator; private: typedef typename allocator_type::template rebind<bool>::other bool_allocator_type; typedef hash_table<Key, T, Hash, KeyEqual, Allocator> self_type; private: std::vector<value_type, allocator_type> table; std::vector<bool, bool_allocator_type> occupied; hasher kh; key_equal keql; size_type msize; size_type load; size_type log_grow; size_type log_grow_by; public: hash_table(size_type init_size = 256, size_type log_grow_ = 1, size_type log_grow_by_ = 1) : msize(0), load(0), log_grow(log_grow_), log_grow_by(log_grow_by_) { assert( (init_size & (init_size-size_type(1))) == 0 ); rehash(init_size); } void set_growth( size_type log_grow_ = 1, size_type log_grow_by_ = 1 ) { log_grow = log_grow_; log_grow_by = log_grow_by_; } ~hash_table() { } // unimplemented, assuming no destructor for Key, T hasher hash_function() const { return kh; } key_equal key_eq() const { return keql; } void swap( self_type & h ) { table.swap( h.table ); occupied.swap( h.occupied ); std::swap( kh, h.kh ); std::swap( msize, h.msize ); std::swap( load, h.load ); } void clear() { table.clear(); occupied.clear(); msize = 0; load = 0; } size_t size() const { return load; } void rehash(size_type newsize) { assert( (newsize & (newsize-size_type(1))) == 0 ); // New storage decltype(table) newtable(newsize); decltype(occupied) newoccupied(newsize, false); // Move over contents for(size_type i = 0; i < msize; i++) { if(occupied[i]) { size_type index = kh(table[i].first) & (newsize-1); while(newoccupied[index]) index = (index+1) & (newsize-1); // std::swap( newtable[index], table[i] ); newtable[index] = table[i]; newoccupied[index] = true; } } newtable.swap(table); newoccupied.swap(occupied); msize = newsize; } size_t capacity() const { return msize; } mapped_type& operator[] (Key const& key) { size_type index = kh(key) & (msize-1); while(occupied[index] && !keql(table[index].first, key)) { index = (index+1) & (msize-1); } if(occupied[index]) return table[index].second; else { load++; if(load >= msize>>log_grow) { rehash(msize<<log_grow_by); index = kh(key) & (msize-1); while(occupied[index] && !keql(table[index].first, key)) { index = (index+1) & (msize-1); } } table[index].first = key; occupied[index] = true; return table[index].second; } } class const_iterator : public std::iterator< std::input_iterator_tag, value_type> { hash_table const* a; size_type index; public: const_iterator(hash_table const& a, int index) { this->a = &a; this->index = index; while(this->index < this->a->msize && !this->a->occupied[this->index]) { this->index++; } // assert( this->index <= this->a->msize ); } bool operator == (const_iterator const& other) const { return a == other.a && index == other.index; } bool operator != (const_iterator const& other) const { return index != other.index; } const_iterator& operator++() { if(index < a->msize) { index++; while(index < a->msize && !a->occupied[index]) { index++; } // assert( index <= a->msize ); } return *this; } const_reference operator*() { return a->table[index]; } value_type const* operator->() { return &a->table[index]; } }; class iterator : public std::iterator< std::forward_iterator_tag, value_type> { hash_table * a; size_type index; public: iterator(hash_table & a, int index) { this->a = &a; this->index = index; while(this->index < this->a->msize && !this->a->occupied[this->index]) { this->index++; } // assert( this->index <= this->a->msize ); } operator const_iterator () const { return const_iterator( *a, index ); } bool operator != (iterator const& other) const { return index != other.index; } iterator& operator++() { if(index < a->msize) { index++; while(index < a->msize && !a->occupied[index]) { index++; } } // assert( index <= a->msize ); return *this; } value_type & operator*() { // key in entry should be const return a->table[index]; } value_type * operator->() { // key in entry should be const return &a->table[index]; } value_type & operator*() const { // key in entry should be const return a->table[index]; } value_type * operator->() const { // key in entry should be const return &a->table[index]; } bool operator == ( const iterator & I ) const { return &a == &I.a && index == I.index; } }; std::pair<iterator,bool> insert( const value_type & kv ) { const key_type & key = kv.first; size_type index = kh(key) & (msize-1); while(occupied[index] && !keql(table[index].first, key)) { index = (index+1) & (msize-1); } if(occupied[index]) return std::make_pair( iterator( *this, index ), false ); else { load++; if(load >= msize>>log_grow) { rehash(msize<<log_grow_by); index = kh(key) & (msize-1); while(occupied[index] && !keql(table[index].first, key)) { index = (index+1) & (msize-1); } } table[index] = kv; occupied[index] = true; return std::make_pair( iterator( *this, index ), true ); } } template<typename Iterator> void insert( Iterator from, Iterator to ) { /* // If it is cheap to calculate the number of elements that will be // inserted, do so and estimate that half of them are new. if( std::is_same<typename std::iterator_traits<Iterator>::iterator_tag, std::random_access_iterator_tag>::value ) { size_t n = std::distance( from, to ); // O(1) if( load + n/2 >= msize>>1 ) rehash(msize<<1); // to incorporate n/2 possibly more than x2 } */ while( from != to ) { insert( *from ); ++from; } } const_iterator find( const key_type &key ) const { size_type index = kh(key) & (msize-1); while(occupied[index] && !keql(table[index].first, key)) { index = (index+1) & (msize-1); } if(occupied[index]) return const_iterator( *this, index ); else return cend(); } iterator find( const key_type &key ) { size_type index = kh(key) & (msize-1); while(occupied[index] && !keql(table[index].first, key)) { index = (index+1) & (msize-1); } if(occupied[index]) return iterator( *this, index ); else return end(); } iterator begin() { return iterator(*this, 0); } iterator end() { return iterator(*this, msize); } const_iterator begin() const { return const_iterator(*this, 0); } const_iterator end() const { return const_iterator(*this, msize); } const_iterator cbegin() const { return const_iterator(*this, 0); } const_iterator cend() const { return const_iterator(*this, msize); } }; } // namespace asap #endif // ASAP_HASHTABLE_H
#ifndef EIGENHEADERS_H #define EIGENHEADERS_H // include eigen libraries #include "/usr/include/eigen3/Eigen/*.h" #include "/usr/include/eigen3/Eigen/src/Core/*.h" #include "/usr/include/eigen3/Eigen/src/Cholesky/*.h" #include "/usr/include/eigen3/Eigen/src/CholmodSupport/*.h" #include "/usr/include/eigen3/Eigen/src/Eigenvalues/*.h" #include "/usr/include/eigen3/Eigen/src/Geometry/*.h" #include "/usr/include/eigen3/Eigen/src/Householder/*.h" #include "/usr/include/eigen3/Eigen/src/IterativeLinearSolvers/*.h" #include "/usr/include/eigen3/Eigen/src/Jacobi/*.h" #include "/usr/include/eigen3/Eigen/src/LU/*.h" #include "/usr/include/eigen3/Eigen/src/MetisSupport/*.h" #include "/usr/include/eigen3/Eigen/src/misc/*.h" #include "/usr/include/eigen3/Eigen/src/OrderingMethods/*.h" #include "/usr/include/eigen3/Eigen/src/PardisoSupport/*.h" #include "/usr/include/eigen3/Eigen/src/LU/*.h" #include "/usr/include/eigen3/Eigen/src/LU/*.h" #include "/usr/include/eigen3/Eigen/src/PaStiXSupport/*.h" #include "/usr/include/eigen3/Eigen/src/plugins/*.h" #include "/usr/include/eigen3/Eigen/src/QR/*.h" #include "/usr/include/eigen3/Eigen/src/SparseCholesky/*.h" #include "/usr/include/eigen3/Eigen/src/SparseCore/*.h" #include "/usr/include/eigen3/Eigen/src/SparseLU/*.h" #include "/usr/include/eigen3/Eigen/src/SparseQR/*.h" #include "/usr/include/eigen3/Eigen/src/SPQRSupport/*.h" #include "/usr/include/eigen3/Eigen/src/StlSupport/*.h" #include "/usr/include/eigen3/Eigen/src/SuperLUSupport/*.h" #include "/usr/include/eigen3/Eigen/src/SVD/*.h" #include "/usr/include/eigen3/Eigen/src/UmfPackSupport/*.h" using namespace eigen; #endif // EIGENHEADERS_H
#include "global.h" #include "siet.h" #include <iomanip> float X,Y; float Xn,Yn,Zn; //poloha bodu kam sa siri vlna v ciarkovanej sustave x AB, y CD Approximation app = Approximation(); bool sir_na_z(const short& i,const short &j,const short &k,const short &smer,const Bod &z) { Bod b(smer,i,j,k); b.sir2(z.i,z.j,z.k); #ifdef DEBUG if (b.t != b.t) {cout<<"ERR1402050920 "<<b.t<<" "<<i<<","<<j<<","<<k<<endl; cin.get();} #endif if (b.t>0) { at[i][j][k] = b.t; pq.push(b); #ifdef DEBUG if (at[i][j][k]<at[z.i][z.j][z.k]) {cout<<"ERR1402051107 "<<i<<","<<j<<","<<k<<" z "<<z.i<<","<<z.j<<","<<z.k<<" "<<at[i][j][k]<<" z "<<at[z.i][z.j][z.k]<<endl;} #endif return true; } return false; } bool sir_at_boundary_to_from(const short &i,const short &j,const short &k,const short &smer,const Bod &z) { Bod b(smer,i,j,k); b.sir_at_boundary(z.i,z.j,z.k); if (b.t>0) { at[i][j][k] = b.t; pq.push(b); #ifdef DEBUG if (at[i][j][k]<at[z.i][z.j][z.k]) {cout<<"ERR1402051259 BND "<<i<<","<<j<<","<<k<<" z "<<z.i<<","<<z.j<<","<<z.k<<" "<<at[i][j][k]<<" z "<<at[z.i][z.j][z.k]<<endl;} #endif return true; } return false; } void Bod::sir() { //vyber najmensieho prvku z haldy a sirenie vlny z neho if ((i == 0) || (j == 0) || (i == nx-1) || (j == ny-1) || (k == 0) || (k == nz-1)) { bool all = true; if ((i>0) && (i<nx-1)) { if (at[i-1][j][k]<-1) all &= sir_at_boundary_to_from(i-1,j,k,-1,*this); if (at[i+1][j][k]<-1) all &= sir_at_boundary_to_from(i+1,j,k, 1,*this); } if ((j>0) && (j<ny-1)) { if (at[i][j-1][k]<-1) all &= sir_at_boundary_to_from(i,j-1,k,-2,*this); if (at[i][j+1][k]<-1) all &= sir_at_boundary_to_from(i,j+1,k, 2,*this); } if ((k>0) && (k<nz-1)) { if (at[i][j][k-1]<-1) all &= sir_at_boundary_to_from(i,j,k-1,-3,*this); if (at[i][j][k+1]<-1) all &= sir_at_boundary_to_from(i,j,k+1, 3,*this); } if (!all) { t += 0.1f/v[i][j][k]; Bod b = Bod(s,i,j,k); b.t = t; pq.push(b); } else { if ((j>0)&&(j<ny-1)&&(k>0)&&(k<nz-1)){ if (i==0) if (at[i+1][j][k]<-1) sir_na_z(i+1,j,k, 1,*this); if (i==nx-1) if (at[i-1][j][k]<-1) sir_na_z(i-1,j,k,-1,*this); } if ((i>0)&&(i<nx-1)&&(k>0)&&(k<nz-1)){ if (j==0) if (at[i][j+1][k]<-1) sir_na_z(i,j+1,k, 2,*this); if (j==ny-1) if (at[i][j-1][k]<-1) sir_na_z(i,j-1,k,-2,*this); } if ((i>0)&&(i<nx-1)&&(j>0)&&(j<ny-1)){ if (k==0) if (at[i][j][k+1]<-1) sir_na_z(i,j,k+1, 3,*this); if (k==nz-1) if (at[i][j][k-1]<-1) sir_na_z(i,j,k-1,-3,*this); } } return; } bool all = sir_inside(); if (!all) { all = sir_inside(); if (!all) { t += 0.1f/v[i][j][k]; Bod b = Bod(s,i,j,k); b.t = t; pq.push(b); } } } bool Bod::sir_inside() { bool all = true; /* if (s != 1) if (at[i-1][j][k]<-1) all &= sir_na_z(i-1,j,k,-1,*this); if (s !=-1) if (at[i+1][j][k]<-1) all &= sir_na_z(i+1,j,k, 1,*this); if (s != 2) if (at[i][j-1][k]<-1) all &= sir_na_z(i,j-1,k,-2,*this); if (s !=-2) if (at[i][j+1][k]<-1) all &= sir_na_z(i,j+1,k, 2,*this); if (s != 3) if (at[i][j][k-1]<-1) all &= sir_na_z(i,j,k-1,-3,*this); if (s !=-3) if (at[i][j][k+1]<-1) all &= sir_na_z(i,j,k+1, 3,*this); */ if (s == 1) { if (at[i][j-1][k]<-1) all &= sir_na_z(i,j-1,k,-2,*this); if (at[i][j+1][k]<-1) all &= sir_na_z(i,j+1,k, 2,*this); if (at[i][j][k-1]<-1) all &= sir_na_z(i,j,k-1,-3,*this); if (at[i][j][k+1]<-1) all &= sir_na_z(i,j,k+1, 3,*this); if (at[i+1][j][k]<-1) all &= sir_na_z(i+1,j,k, 1,*this); } else if (s ==-1) { if (at[i][j-1][k]<-1) all &= sir_na_z(i,j-1,k,-2,*this); if (at[i][j+1][k]<-1) all &= sir_na_z(i,j+1,k, 2,*this); if (at[i][j][k-1]<-1) all &= sir_na_z(i,j,k-1,-3,*this); if (at[i][j][k+1]<-1) all &= sir_na_z(i,j,k+1, 3,*this); if (at[i-1][j][k]<-1) all &= sir_na_z(i-1,j,k,-1,*this); } else if (s == 2) { if (at[i-1][j][k]<-1) all &= sir_na_z(i-1,j,k,-1,*this); if (at[i+1][j][k]<-1) all &= sir_na_z(i+1,j,k, 1,*this); if (at[i][j][k-1]<-1) all &= sir_na_z(i,j,k-1,-3,*this); if (at[i][j][k+1]<-1) all &= sir_na_z(i,j,k+1, 3,*this); if (at[i][j+1][k]<-1) all &= sir_na_z(i,j+1,k, 2,*this); } else if (s ==-2) { if (at[i-1][j][k]<-1) all &= sir_na_z(i-1,j,k,-1,*this); if (at[i+1][j][k]<-1) all &= sir_na_z(i+1,j,k, 1,*this); if (at[i][j][k-1]<-1) all &= sir_na_z(i,j,k-1,-3,*this); if (at[i][j][k+1]<-1) all &= sir_na_z(i,j,k+1, 3,*this); if (at[i][j-1][k]<-1) all &= sir_na_z(i,j-1,k,-2,*this); } else if (s == 3) { if (at[i-1][j][k]<-1) all &= sir_na_z(i-1,j,k,-1,*this); if (at[i+1][j][k]<-1) all &= sir_na_z(i+1,j,k, 1,*this); if (at[i][j-1][k]<-1) all &= sir_na_z(i,j-1,k,-2,*this); if (at[i][j+1][k]<-1) all &= sir_na_z(i,j+1,k, 2,*this); if (at[i][j][k+1]<-1) all &= sir_na_z(i,j,k+1, 3,*this); } else { if (at[i-1][j][k]<-1) all &= sir_na_z(i-1,j,k,-1,*this); if (at[i+1][j][k]<-1) all &= sir_na_z(i+1,j,k, 1,*this); if (at[i][j-1][k]<-1) all &= sir_na_z(i,j-1,k,-2,*this); if (at[i][j+1][k]<-1) all &= sir_na_z(i,j+1,k, 2,*this); if (at[i][j][k-1]<-1) all &= sir_na_z(i,j,k-1,-3,*this); } return all; } void Bod::plane_approx(const short &si, const short &sj,const short &sk,const float &w) { float tx = app.at_Z + 1,ty = app.at_Z + 1; if (abs(s) == 1) { if (at[si][sj+1][sk]>-1) { if (at[si][sj-1][sk]>-1) tx = min(at[si][sj-1][sk],at[si][sj+1][sk]); else tx = at[si][sj+1][sk]; } if (at[si][sj-1][sk]>-1) tx = at[si][sj-1][sk]; if (at[si][sj][sk+1]>-1) { if (at[si][sj][sk-1]>-1) ty = min(at[si][sj][sk-1],at[si][sj][sk+1]); else ty = at[si][sj][sk+1]; } if (at[si][sj][sk-1]>-1) ty = at[si][sj][sk-1]; } else if (abs(s) == 2) { if (at[si+1][sj][sk]>-1) { if (at[si-1][sj][sk]>-1) tx = min(at[si-1][sj][sk],at[si+1][sj][sk]); else tx = at[si+1][sj][sk]; } if (at[si-1][sj][sk]>-1) tx = at[si-1][sj][sk]; if (at[si][sj][sk+1]>-1) { if (at[si][sj][sk-1]>-1) ty = min(at[si][sj][sk-1],at[si][sj][sk+1]); else ty = at[si][sj][sk+1]; } if (at[si][sj][sk-1]>-1) ty = at[si][sj][sk-1]; } else { if (at[si+1][sj][sk]>-1) { if (at[si-1][sj][sk]>-1) tx = min(at[si-1][sj][sk],at[si+1][sj][sk]); else tx = at[si+1][sj][sk]; } if (at[si-1][sj][sk]>-1) tx = at[si-1][sj][sk]; if (at[si][sj+1][sk]>-1) { if (at[si][sj-1][sk]>-1) ty = min(at[si][sj-1][sk],at[si][sj+1][sk]); else ty = at[si][sj+1][sk]; } if (at[si][sj-1][sk]>-1) ty = at[si][sj-1][sk]; } if ((app.at_Z < tx) && (app.at_Z < ty)) { t = app.at_Z + 1/w; return; } if (app.at_Z < tx) { float k = app.at_Z - ty; float kkww = SQR(k*w); if (kkww >= 0.5) { t = ty + sqrtf(2.f)/w; return; } float opt = sqrtf(kkww / (1-kkww)); t = app.at_Z - k*opt + sqrtf(1+SQR(opt))/w; return; } if (app.at_Z < ty) { float k = app.at_Z - tx; float kkww = SQR(k*w); if (kkww >= 0.5) { t = tx + sqrtf(2.f)/w; return; } float opt = sqrtf(kkww / (1-kkww)); t = app.at_Z - k*opt + sqrtf(1+SQR(opt))/w; return; } float vv = SQR(w); float kk = SQR(app.at_Z - tx); float ll = SQR(app.at_Z - ty); float div = max(1 - ll*vv - kk*vv, 0.5f); float optx = sqrtf(kk*vv / div); float opty = sqrtf(ll*vv / div); t = app.at_Z - (app.at_Z-tx)*optx - (app.at_Z-ty)*opty + sqrtf(1+SQR(optx)+SQR(opty))/w; #ifdef DEBUG if (t<at[si][sj][sk]) {cout<<"ERR1402070955 FD plane app "<<i<<","<<j<<","<<k<<" z "<<si<<","<<sj<<","<<sk<<" "<<t<<" z "<<at[si][sj][sk]<<endl;} #endif } void Bod::sir2(const short &si, const short &sj, const short &sk) { app.prep_arrivals(s,si,sj,sk); nastav_polohu_primaca_a_dlzku(); app.prep_param_O2(X,Y); float w = (v[i][j][k] + v[si][sj][sk])/2.f; if ((abs(app.m*w)<0.015) || (abs(app.p*w)<0.015) || (app.m*app.p<=0)) { sirFD(si,sj,sk); if (t > at[si][sj][sk] + 1.f/w) t = at[si][sj][sk] + 1.f/w; if (t != t) //usually in a point next to slow velocity zone t = at[si][sj][sk] + 1.f/w; if (t < at[si][sj][sk]) { #ifdef DEBUG cout<<"ERR1402051141 FD "<<i<<","<<j<<","<<k<<" z "<<si<<","<<sj<<","<<sk<<" "<<t<<" z "<<at[si][sj][sk]<<endl;print_point_neighbours(i,j,k);print_point_neighbours_slowness(i,j,k); #endif t = at[si][sj][sk]; } return; } app.find_virtual_source(X,Y,w); if (app.sz != app.sz) { //sqrt of negative number //happens, when time distances between ABCDZ points are too long //planar approximation from early points //could be much improved plane_approx(si,sj,sk,w); return; } app.correct_Yn_for_NOG(Yn); if (app.sz<=0) { t = app.st + sqrtf(SQR(Xn-app.sx) + SQR(Yn-app.sy) + SQR(Zn-app.sz)) / w; } else if (app.sz<=1) { plane_approx(si,sj,sk,w); return; } else { t = app.st - sqrtf(SQR(Xn-app.sx) + SQR(Yn-app.sy) + SQR(Zn-app.sz)) / w; } if (t<at[si][sj][sk]) { #ifdef DEBUG cout<<"ERR1402070939 arrival sphere t "<<t<<" from "<<at[si][sj][sk]<<" at "<<i<<","<<j<<","<<k<<endl; cout<<app.st<<" "<<sqrtf(SQR(Xn-app.sx) + SQR(Yn-app.sy) + SQR(Zn-app.sz)) / w<<" "<<Xn<<" "<<Yn<<" "<<Zn<<endl; app.print_virtual();print_point_neighbours(i,j,k);print_point_neighbours_slowness(i,j,k);cin.get(); #endif t = at[si][sj][sk]; } #ifdef DEBUG if (t != t) {cout<<"ERR1402050921 arrival sphere t "<<t<<" at "<<i<<","<<j<<","<<k<<endl;} #endif }
#ifndef MATH_IS_POWER_OF_TEN_HPP #define MATH_IS_POWER_OF_TEN_HPP #include <sstream> #include <string> namespace Math { template <typename T> static bool isPowerOfTen(T num) { std::stringstream ss; std::string numVal; ss << num; ss >> numVal; if(numVal[0] != '1') return false; for (size_t i = 1; i < numVal.length(); i++) if (numVal[i] != '0') return false; return true; } } // namespace Math #endif /* end of include guard : MATH_IS_POWER_OF_TEN_HPP */
#pragma once #include <cutil_inline.h> #include <cutil_math.h> #include "MatrixConversion.h" #include "VoxelUtilHashSDF.h" #include "DepthCameraUtil.h" #include "CUDAScan.h" #include "GlobalAppState.h" #include "TimingLog.h" #include "Profiler.h" extern "C" void resetCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams); extern "C" void resetHashBucketMutexCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams); extern "C" void allocCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams, const DepthCameraData& depthCameraData, const DepthCameraParams& depthCameraParams, const unsigned int* d_bitMask); extern "C" void fillDecisionArrayCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams, const DepthCameraData& depthCameraData); extern "C" void compactifyHashCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams); extern "C" void integrateDepthMapCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams, const DepthCameraData& depthCameraData, const DepthCameraParams& depthCameraParams); extern "C" void bindInputDepthColorTextures(const DepthCameraData& depthCameraData); extern "C" void starveVoxelsKernelCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams); extern "C" void garbageCollectIdentifyCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams); extern "C" void garbageCollectFreeCUDA(VoxelHashData& voxelHashData, const HashParams& hashParams); /** * CUDASceneRepHashSDF * CUDASceneRepHashSDF manages the Voxel data and hash data on GPU, and * implements the whole work flow of integration. * */ class CUDASceneRepHashSDF { public: CUDASceneRepHashSDF(const HashParams& params) { create(params); } ~CUDASceneRepHashSDF() { destroy(); } static HashParams parametersFromGlobalAppState(const GlobalAppState& gas) { HashParams params; params.m_rigidTransform.setIdentity(); params.m_rigidTransformInverse.setIdentity(); params.m_hashNumBuckets = gas.s_hashNumBuckets; params.m_hashBucketSize = HASH_BUCKET_SIZE; params.m_hashMaxCollisionLinkedListSize = gas.s_hashMaxCollisionLinkedListSize; params.m_SDFBlockSize = SDF_BLOCK_SIZE; params.m_numSDFBlocks = gas.s_hashNumSDFBlocks; params.m_virtualVoxelSize = gas.s_SDFVoxelSize; params.m_maxIntegrationDistance = gas.s_SDFMaxIntegrationDistance; params.m_truncation = gas.s_SDFTruncation; params.m_truncScale = gas.s_SDFTruncationScale; params.m_integrationWeightSample = gas.s_SDFIntegrationWeightSample; params.m_integrationWeightMax = gas.s_SDFIntegrationWeightMax; params.m_streamingChunkExtents = MatrixConversion::toCUDA(gas.s_streamingChunkExtents); params.m_streamingGridDimensions = MatrixConversion::toCUDA(gas.s_streamingGridDimensions); params.m_streamingMinGridPos = MatrixConversion::toCUDA(gas.s_streamingMinGridPos); params.m_streamingInitialChunkListSize = gas.s_streamingInitialChunkListSize; return params; } void bindDepthCameraTextures(const DepthCameraData& depthCameraData) { bindInputDepthColorTextures(depthCameraData); } #define ENABLE_PROFILE #ifdef ENABLE_PROFILE #define PROFILE_CODE(CODE) CODE #else #define PROFILE_CODE(CODE) #endif void integrate(const mat4f& lastRigidTransform, const DepthCameraData& depthCameraData, const DepthCameraParams& depthCameraParams, unsigned int* d_bitMask) { // hotfix bindDepthCameraTextures(depthCameraData); setLastRigidTransform(lastRigidTransform); //make the rigid transform available on the GPU m_hashData.updateParams(m_hashParams); //allocate all hash blocks which are corresponding to depth map entries PROFILE_CODE(profile.startTiming("alloc", m_numIntegratedFrames)); alloc(depthCameraData, depthCameraParams, d_bitMask); PROFILE_CODE(profile.stopTiming("alloc", m_numIntegratedFrames)); //generate a linear hash array with only occupied entries PROFILE_CODE(profile.startTiming("compactifyHashEntries", m_numIntegratedFrames)); compactifyHashEntries(depthCameraData); PROFILE_CODE(profile.stopTiming("compactifyHashEntries", m_numIntegratedFrames)); //volumetrically integrate the depth data into the depth SDFBlocks PROFILE_CODE(profile.startTiming("integrateDepthMap", m_numIntegratedFrames)); integrateDepthMap(depthCameraData, depthCameraParams); PROFILE_CODE(profile.stopTiming("integrateDepthMap", m_numIntegratedFrames)); PROFILE_CODE(profile.startTiming("garbageCollect", m_numIntegratedFrames)); garbageCollect(depthCameraData); PROFILE_CODE(profile.stopTiming("garbageCollect", m_numIntegratedFrames)); m_numIntegratedFrames++; } void integrate_multisensor(const std::vector<const mat4f*>& lastRigidTransforms, const std::vector<const DepthCameraData*>& depthCameraDatas, const std::vector<const DepthCameraParams*>& depthCameraParams, const std::vector<unsigned int*>& d_bitMasks){ // A stub temporarily processing only the first element from each array // TODO streaming should probably be moved here too ... setLastRigidTransform(*lastRigidTransforms[0]); //make the rigid transform available on the GPU m_hashData.updateParams(m_hashParams); // TODO Confirm no change is need here //allocate all hash blocks which are corresponding to depth map entries alloc(*depthCameraDatas[0], *depthCameraParams[0], d_bitMasks[0]); //generate a linear hash array with only occupied entries compactifyHashEntries(*depthCameraDatas[0]); //volumetrically integrate the depth data into the depth SDFBlocks integrateDepthMap(*depthCameraDatas[0], *depthCameraParams[0]); garbageCollect(*depthCameraDatas[0]); m_numIntegratedFrames++; } void setLastRigidTransform(const mat4f& lastRigidTransform) { m_hashParams.m_rigidTransform = MatrixConversion::toCUDA(lastRigidTransform); m_hashParams.m_rigidTransformInverse = m_hashParams.m_rigidTransform.getInverse(); } void setLastRigidTransformAndCompactify(const mat4f& lastRigidTransform, const DepthCameraData& depthCameraData) { setLastRigidTransform(lastRigidTransform); compactifyHashEntries(depthCameraData); } const mat4f getLastRigidTransform() const { return MatrixConversion::toMlib(m_hashParams.m_rigidTransform); } //! resets the hash to the initial state (i.e., clears all data) void reset() { m_numIntegratedFrames = 0; m_hashParams.m_rigidTransform.setIdentity(); m_hashParams.m_rigidTransformInverse.setIdentity(); m_hashParams.m_numOccupiedBlocks = 0; m_hashData.updateParams(m_hashParams); resetCUDA(m_hashData, m_hashParams); } VoxelHashData& getHashData() { return m_hashData; } const HashParams& getHashParams() const { return m_hashParams; } #pragma region debugHash //! debug only! void checkHeapValRange() { unsigned int* heapCPU = new unsigned int[m_hashParams.m_numSDFBlocks]; MLIB_CUDA_SAFE_CALL(cudaMemcpy(heapCPU, m_hashData.d_heap, sizeof(unsigned int)*m_hashParams.m_numSDFBlocks, cudaMemcpyDeviceToHost)); bool isOk = true; for (int i = 0; i < (int)m_hashParams.m_numSDFBlocks; i++) { unsigned int blockIdx = heapCPU[i]; if (blockIdx >= (int)m_hashParams.m_numSDFBlocks) { std::cout << "heap validity check failed: block idx at "<< i << " is" << blockIdx << std::endl; isOk = false; } } if (isOk) { std::cout << "heap validity check passed!" << std::endl; } else { getchar(); } free(heapCPU); } //! debug only! unsigned int getHeapFreeCount() { unsigned int count; MLIB_CUDA_SAFE_CALL(cudaMemcpy(&count, m_hashData.d_heapCounter, sizeof(unsigned int), cudaMemcpyDeviceToHost)); return count + 1; //there is one more free than the address suggests (0 would be also a valid address) } //! debug only! void debugHash() { HashEntry* hashCPU = new HashEntry[m_hashParams.m_hashBucketSize*m_hashParams.m_hashNumBuckets]; unsigned int* heapCPU = new unsigned int[m_hashParams.m_numSDFBlocks]; unsigned int heapCounterCPU; MLIB_CUDA_SAFE_CALL(cudaMemcpy(&heapCounterCPU, m_hashData.d_heapCounter, sizeof(unsigned int), cudaMemcpyDeviceToHost)); heapCounterCPU++; //points to the first free entry: number of blocks is one more MLIB_CUDA_SAFE_CALL(cudaMemcpy(heapCPU, m_hashData.d_heap, sizeof(unsigned int)*m_hashParams.m_numSDFBlocks, cudaMemcpyDeviceToHost)); MLIB_CUDA_SAFE_CALL(cudaMemcpy(hashCPU, m_hashData.d_hash, sizeof(HashEntry)*m_hashParams.m_hashBucketSize*m_hashParams.m_hashNumBuckets, cudaMemcpyDeviceToHost)); //Check for duplicates class myint3Voxel { public: myint3Voxel() {} ~myint3Voxel() {} bool operator<(const myint3Voxel& other) const { if (x == other.x) { if (y == other.y) { return z < other.z; } return y < other.y; } return x < other.x; } bool operator==(const myint3Voxel& other) const { return x == other.x && y == other.y && z == other.z; } int x, y, z, i; int offset; int ptr; }; std::unordered_set<unsigned int> pointersFreeHash; std::vector<unsigned int> pointersFreeVec(m_hashParams.m_numSDFBlocks, 0); for (unsigned int i = 0; i < heapCounterCPU; i++) { pointersFreeHash.insert(heapCPU[i]); pointersFreeVec[heapCPU[i]] = FREE_ENTRY; } if (pointersFreeHash.size() != heapCounterCPU) { throw MLIB_EXCEPTION("ERROR: duplicate free pointers in heap array"); } unsigned int numOccupied = 0; unsigned int numMinusOne = 0; unsigned int listOverallFound = 0; std::list<myint3Voxel> l; //std::vector<myint3Voxel> v; for (unsigned int i = 0; i < m_hashParams.m_hashBucketSize*m_hashParams.m_hashNumBuckets; i++) { if (hashCPU[i].ptr == -1) { numMinusOne++; } if (hashCPU[i].ptr != -2) { numOccupied++; // != FREE_ENTRY myint3Voxel a; a.x = hashCPU[i].pos.x; a.y = hashCPU[i].pos.y; a.z = hashCPU[i].pos.z; l.push_back(a); //v.push_back(a); unsigned int linearBlockSize = m_hashParams.m_SDFBlockSize*m_hashParams.m_SDFBlockSize*m_hashParams.m_SDFBlockSize; if (pointersFreeHash.find(hashCPU[i].ptr / linearBlockSize) != pointersFreeHash.end()) { throw MLIB_EXCEPTION("ERROR: ptr is on free heap, but also marked as an allocated entry"); } pointersFreeVec[hashCPU[i].ptr / linearBlockSize] = LOCK_ENTRY; } } unsigned int numHeapFree = 0; unsigned int numHeapOccupied = 0; for (unsigned int i = 0; i < m_hashParams.m_numSDFBlocks; i++) { if (pointersFreeVec[i] == FREE_ENTRY) numHeapFree++; else if (pointersFreeVec[i] == LOCK_ENTRY) numHeapOccupied++; else { throw MLIB_EXCEPTION("memory leak detected: neither free nor allocated"); } } if (numHeapFree + numHeapOccupied == m_hashParams.m_numSDFBlocks) std::cout << "HEAP OK!" << std::endl; else throw MLIB_EXCEPTION("HEAP CORRUPTED"); l.sort(); size_t sizeBefore = l.size(); l.unique(); size_t sizeAfter = l.size(); std::cout << "diff: " << sizeBefore - sizeAfter << std::endl; std::cout << "minOne: " << numMinusOne << std::endl; std::cout << "numOccupied: " << numOccupied << "\t numFree: " << getHeapFreeCount() << std::endl; std::cout << "numOccupied + free: " << numOccupied + getHeapFreeCount() << std::endl; std::cout << "numInFrustum: " << m_hashParams.m_numOccupiedBlocks << std::endl; SAFE_DELETE_ARRAY(heapCPU); SAFE_DELETE_ARRAY(hashCPU); } #pragma endregion private: void create(const HashParams& params) { m_hashParams = params; m_hashData.allocate(m_hashParams); reset(); } void destroy() { m_hashData.free(); } void alloc(const DepthCameraData& depthCameraData, const DepthCameraParams& depthCameraParams, const unsigned int* d_bitMask) { //Start Timing if (GlobalAppState::get().s_timingsDetailledEnabled) { cutilSafeCall(cudaDeviceSynchronize()); m_timer.start(); } resetHashBucketMutexCUDA(m_hashData, m_hashParams); allocCUDA(m_hashData, m_hashParams, depthCameraData, depthCameraParams, d_bitMask); // Stop Timing if (GlobalAppState::get().s_timingsDetailledEnabled) { cutilSafeCall(cudaDeviceSynchronize()); m_timer.stop(); TimingLog::totalTimeAlloc += m_timer.getElapsedTimeMS(); TimingLog::countTimeAlloc++; } } void compactifyHashEntries(const DepthCameraData& depthCameraData) { //Start Timing if (GlobalAppState::get().s_timingsDetailledEnabled) { cutilSafeCall(cudaDeviceSynchronize()); m_timer.start(); } fillDecisionArrayCUDA(m_hashData, m_hashParams, depthCameraData); m_hashParams.m_numOccupiedBlocks = m_cudaScan.prefixSum( m_hashParams.m_hashNumBuckets*m_hashParams.m_hashBucketSize, m_hashData.d_hashDecision, m_hashData.d_hashDecisionPrefix); m_hashData.updateParams(m_hashParams); //make sure numOccupiedBlocks is updated on the GPU compactifyHashCUDA(m_hashData, m_hashParams); // Stop Timing if (GlobalAppState::get().s_timingsDetailledEnabled) { cutilSafeCall(cudaDeviceSynchronize()); m_timer.stop(); TimingLog::totalTimeCompactifyHash += m_timer.getElapsedTimeMS(); TimingLog::countTimeCompactifyHash++; } //std::cout << "numOccupiedBlocks: " << m_hashParams.m_numOccupiedBlocks << std::endl; } void integrateDepthMap(const DepthCameraData& depthCameraData, const DepthCameraParams& depthCameraParams) { if(GlobalAppState::get().s_timingsDetailledEnabled) { cutilSafeCall(cudaDeviceSynchronize()); m_timer.start(); } integrateDepthMapCUDA(m_hashData, m_hashParams, depthCameraData, depthCameraParams); if(GlobalAppState::get().s_timingsDetailledEnabled) { cutilSafeCall(cudaDeviceSynchronize()); m_timer.stop(); TimingLog::totalTimeIntegrate += m_timer.getElapsedTimeMS(); TimingLog::countTimeIntegrate++; } } void garbageCollect(const DepthCameraData& depthCameraData) { //only perform if enabled by global app state if (GlobalAppState::get().s_garbageCollectionEnabled) { if (m_numIntegratedFrames > 0 && m_numIntegratedFrames % GlobalAppState::get().s_garbageCollectionStarve == 0) { starveVoxelsKernelCUDA(m_hashData, m_hashParams); } garbageCollectIdentifyCUDA(m_hashData, m_hashParams); resetHashBucketMutexCUDA(m_hashData, m_hashParams); //needed if linked lists are enabled -> for memeory deletion garbageCollectFreeCUDA(m_hashData, m_hashParams); } } HashParams m_hashParams; VoxelHashData m_hashData; CUDAScan m_cudaScan; unsigned int m_numIntegratedFrames; //used for garbage collect static Timer m_timer; };
#include<bits/stdc++.h> using namespace std; int main(){ int arr[]={1,2,3,4,5,6,7}; int n=sizeof(arr)/sizeof(arr[0]); int temp[n]; int ls=n-2,j=0; for(int i=ls;i<n;i++) { temp[j++]=arr[i]; } for(int i=0;i<ls;i++) { temp[j++]=arr[i]; } for(int i=0;i<n;i++) { cout<<temp[i]; } }
#include <fstream> #include <string> #include <iostream> #include "Hashbook.h" #include "password.h" using namespace std; Hashbook::Hashbook() { fstream hashbook; string line; string password; string compname; int line_location = 0; } void Hashbook::write_to_hashbook(string password, string company_name) { hashbook.open("Hashbook.txt", ios::app); hashbook << company_name << "/" << password << "\n"; hashbook.close(); } void Hashbook::search_hashbook(string company_name) { do { string line; getline(hashbook, line); if (line.length() == 0) { return; } if (line.find(company_name) != -1) { return; } else if (line.find(EOF) != -1) { return; } line_location++; } while (true); } string Hashbook::get_line() { string line; hashbook.open("Hashbook", ios::in); }
/** * Created by K. Suwatchai (Mobizt) * * Email: k_suwatchai@hotmail.com * * Github: https://github.com/mobizt/Firebase-ESP8266 * * Copyright (c) 2023 mobizt * */ /** This example will show how to authenticate as user using * the hard coded Service Account to create the custom token to sign in. * * From this example, the user will be granted to access the specific location that matches * the unique user ID (uid) assigned in the token. * * The anonymous user with user UID will be created if not existed. * * This example will modify the database rules to set up the security rule which need to * guard the unauthorized access with the uid and custom claims assigned in the token. */ #include <Arduino.h> #if defined(ESP32) #include <WiFi.h> #include <FirebaseESP32.h> #elif defined(ESP8266) #include <ESP8266WiFi.h> #include <FirebaseESP8266.h> #elif defined(ARDUINO_RASPBERRY_PI_PICO_W) #include <WiFi.h> #include <FirebaseESP8266.h> #endif // Provide the token generation process info. #include <addons/TokenHelper.h> // Provide the RTDB payload printing info and other helper functions. #include <addons/RTDBHelper.h> /* 1. Define the WiFi credentials */ #define WIFI_SSID "WIFI_AP" #define WIFI_PASSWORD "WIFI_PASSWORD" /** 2. Define the API key * * The API key can be obtained since you created the project and set up * the Authentication in Firebase console. * * You may need to enable the Identity provider at https://console.cloud.google.com/customer-identity/providers * Select your project, click at ENABLE IDENTITY PLATFORM button. * The API key also available by click at the link APPLICATION SETUP DETAILS. * */ #define API_KEY "API_KEY" /** 3. Define the Service Account credentials (required for token generation) * * This information can be taken from the service account JSON file. * * To download service account file, from the Firebase console, goto project settings, * select "Service accounts" tab and click at "Generate new private key" button */ #define FIREBASE_PROJECT_ID "PROJECT_ID" #define FIREBASE_CLIENT_EMAIL "CLIENT_EMAIL" const char PRIVATE_KEY[] PROGMEM = "-----BEGIN PRIVATE KEY-----XXXXXXXXXXXX-----END PRIVATE KEY-----\n"; /* 4. If work with RTDB, define the RTDB URL */ #define DATABASE_URL "URL" //<databaseName>.firebaseio.com or <databaseName>.<region>.firebasedatabase.app /* This is Google root CA certificate */ /** From the test on July 2021, GlobalSign Root CA was missing from Google server * when checking with https://www.sslchecker.com/sslchecker. * The certificate chain, GTS Root R1 can be used instead. * */ /* const char rootCACert[] PROGMEM = "-----BEGIN CERTIFICATE-----\n" "MIIFVzCCAz+gAwIBAgINAgPlk28xsBNJiGuiFzANBgkqhkiG9w0BAQwFADBHMQsw\n" "CQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExMQzEU\n" "MBIGA1UEAxMLR1RTIFJvb3QgUjEwHhcNMTYwNjIyMDAwMDAwWhcNMzYwNjIyMDAw\n" "MDAwWjBHMQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZp\n" "Y2VzIExMQzEUMBIGA1UEAxMLR1RTIFJvb3QgUjEwggIiMA0GCSqGSIb3DQEBAQUA\n" "A4ICDwAwggIKAoICAQC2EQKLHuOhd5s73L+UPreVp0A8of2C+X0yBoJx9vaMf/vo\n" "27xqLpeXo4xL+Sv2sfnOhB2x+cWX3u+58qPpvBKJXqeqUqv4IyfLpLGcY9vXmX7w\n" "Cl7raKb0xlpHDU0QM+NOsROjyBhsS+z8CZDfnWQpJSMHobTSPS5g4M/SCYe7zUjw\n" "TcLCeoiKu7rPWRnWr4+wB7CeMfGCwcDfLqZtbBkOtdh+JhpFAz2weaSUKK0Pfybl\n" "qAj+lug8aJRT7oM6iCsVlgmy4HqMLnXWnOunVmSPlk9orj2XwoSPwLxAwAtcvfaH\n" "szVsrBhQf4TgTM2S0yDpM7xSma8ytSmzJSq0SPly4cpk9+aCEI3oncKKiPo4Zor8\n" "Y/kB+Xj9e1x3+naH+uzfsQ55lVe0vSbv1gHR6xYKu44LtcXFilWr06zqkUspzBmk\n" "MiVOKvFlRNACzqrOSbTqn3yDsEB750Orp2yjj32JgfpMpf/VjsPOS+C12LOORc92\n" "wO1AK/1TD7Cn1TsNsYqiA94xrcx36m97PtbfkSIS5r762DL8EGMUUXLeXdYWk70p\n" "aDPvOmbsB4om3xPXV2V4J95eSRQAogB/mqghtqmxlbCluQ0WEdrHbEg8QOB+DVrN\n" "VjzRlwW5y0vtOUucxD/SVRNuJLDWcfr0wbrM7Rv1/oFB2ACYPTrIrnqYNxgFlQID\n" "AQABo0IwQDAOBgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4E\n" "FgQU5K8rJnEaK0gnhS9SZizv8IkTcT4wDQYJKoZIhvcNAQEMBQADggIBAJ+qQibb\n" "C5u+/x6Wki4+omVKapi6Ist9wTrYggoGxval3sBOh2Z5ofmmWJyq+bXmYOfg6LEe\n" "QkEzCzc9zolwFcq1JKjPa7XSQCGYzyI0zzvFIoTgxQ6KfF2I5DUkzps+GlQebtuy\n" "h6f88/qBVRRiClmpIgUxPoLW7ttXNLwzldMXG+gnoot7TiYaelpkttGsN/H9oPM4\n" "7HLwEXWdyzRSjeZ2axfG34arJ45JK3VmgRAhpuo+9K4l/3wV3s6MJT/KYnAK9y8J\n" "ZgfIPxz88NtFMN9iiMG1D53Dn0reWVlHxYciNuaCp+0KueIHoI17eko8cdLiA6Ef\n" "MgfdG+RCzgwARWGAtQsgWSl4vflVy2PFPEz0tv/bal8xa5meLMFrUKTX5hgUvYU/\n" "Z6tGn6D/Qqc6f1zLXbBwHSs09dR2CQzreExZBfMzQsNhFRAbd03OIozUhfJFfbdT\n" "6u9AWpQKXCBfTkBdYiJ23//OYb2MI3jSNwLgjt7RETeJ9r/tSQdirpLsQBqvFAnZ\n" "0E6yove+7u7Y/9waLd64NnHi/Hm3lCXRSHNboTXns5lndcEZOitHTtNCjv0xyBZm\n" "2tIMPNuzjsmhDYAPexZ3FL//2wmUspO8IFgV6dtxQ/PeEMMA3KgqlbbC1j+Qa3bb\n" "bP6MvPJwNQzcmRk13NfIRmPVNnGuV/u3gm3c\n" "-----END CERTIFICATE-----\n"; */ /** 4. Define the database secret (optional) * * This database secret needed only for this example to modify the database rules * * If you edit the database rules yourself, this is not required. */ #define DATABASE_SECRET "DATABASE_SECRET" /* 5. Define the Firebase Data object */ FirebaseData fbdo; /* 6. Define the FirebaseAuth data for authentication data */ FirebaseAuth auth; /* 7. Define the FirebaseConfig data for config data */ FirebaseConfig config; unsigned long dataMillis = 0; int count = 0; #if defined(ARDUINO_RASPBERRY_PI_PICO_W) WiFiMulti multi; #endif void setup() { Serial.begin(115200); #if defined(ARDUINO_RASPBERRY_PI_PICO_W) multi.addAP(WIFI_SSID, WIFI_PASSWORD); multi.run(); #else WiFi.begin(WIFI_SSID, WIFI_PASSWORD); #endif Serial.print("Connecting to Wi-Fi"); unsigned long ms = millis(); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(300); #if defined(ARDUINO_RASPBERRY_PI_PICO_W) if (millis() - ms > 10000) break; #endif } Serial.println(); Serial.print("Connected with IP: "); Serial.println(WiFi.localIP()); Serial.println(); Serial.printf("Firebase Client v%s\n\n", FIREBASE_CLIENT_VERSION); /* Assign the certificate data (optional) */ // config.cert.data = rootCACert; /* Assign the api key (required) */ config.api_key = API_KEY; /* Assign the sevice account credentials and private key (required) */ config.service_account.data.client_email = FIREBASE_CLIENT_EMAIL; config.service_account.data.project_id = FIREBASE_PROJECT_ID; config.service_account.data.private_key = PRIVATE_KEY; /** Assign the unique user ID (uid) (required) * This uid will be compare to the auth.uid variable in the database rules. * * If the assigned uid (user UID) was not existed, the new user will be created. * * If the uid is empty or not assigned, the library will create the OAuth2.0 access token * instead. * * With OAuth2.0 access token, the device will be signed in as admin which has * the full ggrant access and no database rules and custom claims are applied. * This similar to sign in using the database secret but no admin rights. */ auth.token.uid = "Node1"; /** Assign the custom claims (optional) * This uid will be compare to the auth.token.premium_account variable * (for this case) in the database rules. */ FirebaseJson claims; claims.add("premium_account", true); claims.add("admin", true); auth.token.claims = claims.raw(); /* Assign the RTDB URL */ config.database_url = DATABASE_URL; Firebase.reconnectWiFi(true); fbdo.setResponseSize(4096); /* path for user data is now "/UsersData/Node1" */ String base_path = "/UsersData/"; /* Assign the callback function for the long running token generation task */ config.token_status_callback = tokenStatusCallback; // see addons/TokenHelper.h // The WiFi credentials are required for Pico W // due to it does not have reconnect feature. #if defined(ARDUINO_RASPBERRY_PI_PICO_W) config.wifi.clearAP(); config.wifi.addAP(WIFI_SSID, WIFI_PASSWORD); #endif /* Now we start to signin using custom token */ /** Initialize the library with the Firebase authen and config. * * The device time will be set by sending request to the NTP server * befor token generation and exchanging. * * The signed RSA256 jwt token will be created and used for id token exchanging. * * Theses process may take time to complete. */ Firebase.begin(&config, &auth); /** Now modify the database rules (if not yet modified) * * The user, Node1 in this case will be granted to read and write * at the curtain location i.e. "/UsersData/Node1" and we will also check the * custom claims in the rules which must be matched. * * If you database rules has been modified, please comment this code out. * * The character $ is to make a wildcard variable (can be any name) represents any node key * which located at some level in the rule structure and use as reference variable * in .read, .write and .validate rules * * For this case $userId represents any <user uid> node that places under UsersData node i.e. * /UsersData/<user uid> which <user uid> is user UID or "Node1" in this case. * * Please check your the database rules to see the changes after run the below code. */ String var = "$userId"; String val = "($userId === auth.uid && auth.token.premium_account === true && auth.token.admin === true)"; Firebase.setReadWriteRules(fbdo, base_path, var, val, val, DATABASE_SECRET); /** * The custom token which created internally in this library will use * to exchange with the id token returns from the server. * * The id token is the token which used to sign in as a user. * * The id token was already saved to the config data (FirebaseConfig data variable) that * passed to the Firebase.begin function. * * The id token can be accessed from Firebase.getToken(). * * The refresh token can be accessed from Firebase.getRefreshToken(). */ } void loop() { // Firebase.ready() should be called repeatedly to handle authentication tasks. if (millis() - dataMillis > 5000 && Firebase.ready()) { dataMillis = millis(); String path = "/UsersData/"; path += auth.token.uid.c_str(); //<- user uid or "Node1" path += "/test/int"; Serial.printf("Set int... %s\n", Firebase.setInt(fbdo, path, count++) ? "ok" : fbdo.errorReason().c_str()); } }
// ---------------------------------------------------------------------------- // nexus | LiquidArgonProperties.cc // // This class collects the relevant physical properties of liquid xenon. // // The NEXT Collaboration // ---------------------------------------------------------------------------- #ifndef XENON_LIQUID_PROPERTIES_H #define XENON_LIQUID_PROPERTIES_H 1 #include <globals.hh> #include <vector> class G4MaterialPropertiesTable; class LiquidArgonProperties { public: /// Constructor LiquidArgonProperties(); /// Destructor ~LiquidArgonProperties(); // G4double Density(); /// Return the refractive index of xenon gas for a given photon energy G4double RefractiveIndex(G4double energy); G4double Scintillation(G4double energy); void Scintillation(std::vector<G4double>& energy, std::vector<G4double>& intensity); private: // G4double density_; }; #endif
//********************************************************** // PROJECT VIDEO LIBRARY //********************************************************** //********************************************************** // INCLUDED HEADER FILES //********************************************************** #include <iostream.h> #include <fstream.h> #include <process.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <ctype.h> #include <conio.h> #include <dos.h> //********************************************************** // THIS CLASS CONTAINS ALL THE DRAWING FUNCTIONS //********************************************************** class LINES { public : void LINE_HOR(int, int, int, char) ; void LINE_VER(int, int, int, char) ; void BOX(int,int,int,int,char) ; } ; //********************************************************** // THIS CLASS CONTROL ALL THE FUNCTIONS IN THE MENU //********************************************************** class MENU { public : void MAIN_MENU(void) ; char *CHOICE_MENU(void) ; private : void EDIT_MENU(void) ; void DISPLAY_MENU(void) ; } ; //********************************************************** // THIS CLASS CONTROL ALL THE FUNCTIONS RELATED TO CASSETTE //********************************************************** class CASSETTE { public : void ADDITION(void) ; void MODIFICATION(void) ; void DELETION(void) ; void LIST(void) ; void DISPLAY(void) ; char *CASNAME(char[], int) ; void UPDATE(char[], int, int, char) ; protected : int ISSUED(char[], int) ; int FOUND_CODE(char[], int) ; void DISPLAY_RECORD(char[], int) ; void DISPLAY_LIST(char[]) ; private : int RECORDNO(char[], int) ; void ADD_RECORD(char[], int, char[], char,int) ; int LASTCODE(char[]) ; void DELETE_RECORD(char[], int) ; int code, custcode ; char name[36], status ; } ; //********************************************************** // THIS CLASS CONTROL ALL THE FUNCTIONS RELATED TO CUSTOMER //********************************************************** class CUSTOMER { public : void LIST(void) ; void DISPLAY(void) ; char *CUSTNAME(int) ; protected : void ADD_RECORD(int, char[], char[], char[], int, int, int, int) ; void DELETE_RECORD(int) ; int FOUND_CODE(int) ; int LASTCODE(void) ; void DISPLAY_RECORD(int) ; int FINE(int) ; private : int code, cassette ; char name[26], phone[10], fname[13] ; int dd, mm, yy ; // DATE OF RETURN } ; //********************************************************** // THIS CLASS CONTROL ALL THE FUNCTIONS RELATED TO ISSUE & // RETURN & CALCULATING FINE ETC. //********************************************************** class ISSUE_RETURN : public CASSETTE, public CUSTOMER { public : void ISSUE(void) ; void RETURN(void) ; int DIFF(int, int, int, int, int, int) ; private : void EXTEND_DATE(int,int,int,int) ; int day, mon, year ; } ; //********************************************************** // THIS FUNCTION CONTROL ALL THE FUNCTIONS IN THE MAIN MENU //********************************************************** void MENU :: MAIN_MENU(void) { char ch ; LINES line ; do { textmode(C40) ; clrscr() ; line.BOX(2,1,39,25,219) ; line.BOX(6,5,35,21,218) ; line.BOX(12,7,26,9,218) ; gotoxy(13,8) ; cout <<"VIDEO LIBRARY" ; gotoxy(11,11) ; cout <<"1: ADD NEW CASSETTE" ; gotoxy(11,12) ; cout <<"2: ISSUE CASSETTE" ; gotoxy(11,13) ; cout <<"3: RETURN CASSETTE" ; gotoxy(11,14) ; cout <<"4: DISPLAY" ; gotoxy(11,15) ; cout <<"5: EDIT" ; gotoxy(11,16) ; cout <<"0: QUIT" ; gotoxy(11,19) ; cout <<"Enter your choice:" ; ch = getch() ; textmode(C80) ; clrscr() ; CASSETTE cas ; ISSUE_RETURN ir ; switch(ch) { case 27,'0' : break ; case '1' : cas.ADDITION() ; break ; case '2' : ir.ISSUE() ; break ; case '3' : ir.RETURN() ; break ; case '4' : DISPLAY_MENU() ; break ; case '5' : EDIT_MENU() ; break ; } } while (ch != 27 && ch != '0') ; } //********************************************************** // THIS FUNCTION RETURNS THE NAME OF THE FILE SELECTED //********************************************************** char *MENU :: CHOICE_MENU(void) { char ch ; LINES line ; do { textmode(C40) ; clrscr() ; line.BOX(2,1,39,25,219) ; line.BOX(6,5,35,21,218) ; gotoxy(11,9) ; cout <<"SELECT CASSETTE FOR..." ; gotoxy(12,12) ; cout <<"H: HINDI FILMS" ; gotoxy(12,13) ; cout <<"E: ENGLISH FILMS" ; gotoxy(12,14) ; cout <<"N: NON FILMS" ; gotoxy(12,17) ; cout <<"Enter your choice:" ; ch = getch() ; ch = toupper(ch) ; textmode(C80) ; clrscr() ; switch(ch) { case 27,'0' : break ; case 'H' : return "HINDI.DAT" ; case 'E' : return "ENGLISH.DAT" ; case 'N' : return "NONFILM.DAT" ; } } while (ch != 27 && ch != '0') ; return "FAILED" ; } //********************************************************** // THIS FUNCTION CONTROL ALL THE FUNCTIONS IN THE EDIT MENU // (MODIFICATION, DELETION). //********************************************************** void MENU :: EDIT_MENU(void) { char ch ; LINES line ; do { textmode(C40) ; clrscr() ; line.BOX(2,1,39,25,219) ; line.BOX(6,5,35,21,218) ; line.BOX(14,8,24,10,218) ; gotoxy(15,9) ; cout <<"EDIT MENU" ; gotoxy(10,12) ; cout <<"1: MODIFY CASSETTE" ; gotoxy(10,14) ; cout <<"2: DELETE CASSETTE" ; gotoxy(10,16) ; cout <<"0: EXIT" ; gotoxy(10,18) ; cout <<"Enter your choice:" ; ch = getch() ; textmode(C80) ; clrscr() ; CASSETTE cas ; switch(ch) { case 27,'0' : break ; case '1' : cas.MODIFICATION() ; break ; case '2' : cas.DELETION() ; break ; } } while (ch != 27 && ch != '0') ; } //********************************************************** // THIS FUNCTION CONTROL ALL THE FUNCTIONS RELATED TO // DISPLAY (LIST, ETC.) //********************************************************** void MENU :: DISPLAY_MENU(void) { char ch ; LINES line ; do { textmode(C40) ; clrscr() ; line.BOX(2,1,39,25,219) ; line.BOX(6,5,35,21,218) ; line.BOX(14,8,25,10,218) ; gotoxy(15,9) ; cout <<"DISPLAY..." ; gotoxy(10,12) ; cout <<"1: LIST OF CASSETTE" ; gotoxy(10,13) ; cout <<"2: LIST OF CUSTOMER" ; gotoxy(10,14) ; cout <<"3: CASSETTE RECORD" ; gotoxy(10,15) ; cout <<"4: CUSTOMER RECORD" ; gotoxy(10,16) ; cout <<"0: EXIT" ; gotoxy(10,18) ; cout <<"Enter your choice:" ; ch = getch() ; textmode(C80) ; clrscr() ; CASSETTE cas ; CUSTOMER cust ; switch(ch) { case 27,'0' : break ; case '1' : cas.LIST() ; break ; case '2' : cust.LIST() ; break ; case '3' : cas.DISPLAY() ; break ; case '4' : cust.DISPLAY() ; break ; } } while (ch != 27 && ch != '0') ; } //********************************************************** // THIS FUNCTION DRAWS THE HORRIZONTAL LINE //********************************************************** void LINES :: LINE_HOR(int column1, int column2, int row, char c) { for ( column1; column1<=column2; column1++ ) { gotoxy(column1,row) ; cout <<c ; } } //********************************************************** // THIS FUNCTION DRAWS THE VERTICAL LINE //********************************************************** void LINES :: LINE_VER(int row1, int row2, int column, char c) { for ( row1; row1<=row2; row1++ ) { gotoxy(column,row1) ; cout <<c ; } } //********************************************************** // THIS FUNCTION DRAWS THE BOX //********************************************************** void LINES :: BOX(int column1, int row1, int column2, int row2, char c) { char ch=218 ; char c1, c2, c3, c4 ; char l1=196, l2=179 ; if (c == ch) { c1=218 ; c2=191 ; c3=192 ; c4=217 ; l1 = 196 ; l2 = 179 ; } else { c1=c ; c2=c ; c3=c ; c4=c ; l1 = c ; l2 = c ; } gotoxy(column1,row1) ; cout <<c1 ; gotoxy(column2,row1) ; cout <<c2 ; gotoxy(column1,row2) ; cout <<c3 ; gotoxy(column2,row2) ; cout <<c4 ; column1++ ; column2-- ; LINE_HOR(column1,column2,row1,l1) ; LINE_HOR(column1,column2,row2,l1) ; column1-- ; column2++ ; row1++ ; row2-- ; LINE_VER(row1,row2,column1,l2) ; LINE_VER(row1,row2,column2,l2) ; } //********************************************************** // THIS FUNCTION RETURNS THE LAST CASSETTE'S CODE //********************************************************** int CASSETTE :: LASTCODE(char filename[13]) { fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; int count=0 ; while (file.read((char *) this, sizeof(CASSETTE))) count = code ; file.close() ; return count ; } //********************************************************** // THIS FUNCTION RETURNS 0 IF THE GIVEN CODE NOT FOUND //********************************************************** int CASSETTE :: FOUND_CODE(char filename[13], int cascode) { fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; int found=0 ; while (file.read((char *) this, sizeof(CASSETTE))) { if (code == cascode) { found = 1 ; break ; } } file.close() ; return found ; } //********************************************************** // THIS FUNCTION RETURNS RECORD NO. OF THE GIVEN CODE //********************************************************** int CASSETTE :: RECORDNO(char filename[13], int cascode) { fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; int recno=0 ; while (file.read((char *) this, sizeof(CASSETTE))) { recno++ ; if (code == cascode) break ; } file.close() ; return recno ; } //********************************************************** // THIS FUNCTION RETURNS 1 IF CASSETTE IS ISSUDE FOR THE // GIVEN CODE //********************************************************** int CASSETTE :: ISSUED(char filename[13], int cascode) { fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; int issued=0 ; while (file.read((char *) this, sizeof(CASSETTE))) { if (code == cascode && status == 'N') { issued = 1 ; break ; } } file.close() ; return issued ; } //********************************************************** // THIS FUNCTION RETURNS NAME OF THE CASSETTE FOR THE GIVEN // CODE //********************************************************** char *CASSETTE :: CASNAME(char filename[13], int cascode) { fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; char casname[36] ; while (file.read((char *) this, sizeof(CASSETTE))) { if (code == cascode) { strcpy(casname,name) ; break ; } } file.close() ; return casname ; } //********************************************************** // THIS FUNCTION DISPLAYS THE LIST OF THE CASSETTES //********************************************************** void CASSETTE :: DISPLAY_LIST(char filename[13]) { int row = 6 , found=0, flag=0 ; char ch ; gotoxy(31,2) ; cout <<"LIST OF CASSETTES" ; gotoxy(30,3) ; cout <<"~~~~~~~~~~~~~~~~~~~" ; gotoxy(3,4) ; cout <<"CODE NAME STATUS" ; gotoxy(1,5) ; cout <<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ; fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; while (file.read((char *) this, sizeof(CASSETTE))) { flag = 0 ; delay(20) ; found = 1 ; gotoxy(4,row) ; cout <<code ; gotoxy(10,row) ; cout <<name ; gotoxy(59,row) ; cout <<status ; if ( row == 23 ) { flag = 1 ; row = 6 ; gotoxy(1,25) ; cout <<"Press any key to continue or Press <ESC> to exit" ; ch = getch() ; if (ch == 27) break ; clrscr() ; gotoxy(31,2) ; cout <<"LIST OF CASSETTES" ; gotoxy(30,3) ; cout <<"~~~~~~~~~~~~~~~~~~~" ; gotoxy(3,4) ; cout <<"CODE NAME STATUS" ; gotoxy(1,5) ; cout <<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ; } else row++ ; } if (!found) { gotoxy(5,10) ; cout <<"\7Records not found" ; } if (!flag) { gotoxy(1,25) ; cout <<"Press any key to continue..." ; getche() ; } file.close () ; } //********************************************************** // THIS FUNCTION DISPLAYS THE LIST OF THE CASSETTES //********************************************************** void CASSETTE :: LIST(void) { MENU menu ; char filename[13] ; strcpy(filename,menu.CHOICE_MENU()) ; if (!strcmpi(filename,"FAILED")) return ; DISPLAY_LIST(filename) ; } //********************************************************** // THIS FUNCTION DISPLAYS THE RECORD OF CASSETTE FOR THE // GIVEN CODE //********************************************************** void CASSETTE :: DISPLAY_RECORD(char filename[13], int cascode) { CUSTOMER cust ; fstream file ; file.open(filename, ios::in) ; file.seekg(0,ios::beg) ; while (file.read((char *) this, sizeof(CASSETTE))) { if (code == cascode) { gotoxy(5,4) ; cout <<"Cassette Code # " <<code ; gotoxy(5,6) ; cout <<"Cassette Name : " <<name ; gotoxy(5,7) ; cout <<"Status : " <<status ; if (status == 'N' && custcode != 0) { gotoxy(5,9) ; cout <<"Cassette is issued by : " <<cust.CUSTNAME(custcode) ; } break ; } } file.close() ; } //********************************************************** // THIS FUNCTION GIVES CODE TO DISPLAYS THE RECORD OF // CASSETTE //********************************************************** void CASSETTE :: DISPLAY(void) { MENU menu ; char filename[13] ; strcpy(filename,menu.CHOICE_MENU()) ; if (!strcmpi(filename,"FAILED")) return ; char t1[10] ; int t2, cascode ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; gotoxy(5,5) ; cout <<"Enter code of the Cassette " ; gets(t1) ; t2 = atoi(t1) ; cascode = t2 ; if (cascode == 0) return ; clrscr() ; if (!FOUND_CODE(filename,cascode)) { gotoxy(5,5) ; cout <<"\7Record not found" ; getch() ; return ; } LINES line ; line.BOX(2,1,79,25,218) ; DISPLAY_RECORD(filename,cascode) ; gotoxy(5,24) ; cout <<"Press any key to continue..." ; getch() ; } //********************************************************** // THIS FUNCTION UPDATE THE GIVEN DATA IN THE CASSETTE'S // FILE //********************************************************** void CASSETTE :: UPDATE(char filename[13], int cascode, int ccode, char casstatus) { int recno ; recno = RECORDNO(filename,cascode) ; fstream file ; file.open(filename, ios::out | ios::ate) ; custcode = ccode ; status = casstatus ; int location ; location = (recno-1) * sizeof(CASSETTE) ; file.seekp(location) ; file.write((char *) this, sizeof(CASSETTE)) ; file.close() ; } //********************************************************** // THIS FUNCTION DELETES THE RECORD OF THE GIVEN CODE. //********************************************************** void CASSETTE :: DELETE_RECORD(char filename[13], int cascode) { fstream file ; file.open(filename, ios::in) ; fstream temp ; temp.open("temp.dat", ios::out) ; file.seekg(0,ios::beg) ; while (!file.eof()) { file.read((char *) this, sizeof(CASSETTE)) ; if (file.eof()) break ; if (code != cascode) temp.write((char *) this, sizeof(CASSETTE)) ; } file.close() ; temp.close() ; file.open(filename, ios::out) ; temp.open("temp.dat", ios::in) ; temp.seekg(0,ios::beg) ; while ( !temp.eof() ) { temp.read((char *) this, sizeof(CASSETTE)) ; if ( temp.eof() ) break ; file.write((char *) this, sizeof(CASSETTE)) ; } file.close() ; temp.close() ; } //********************************************************** // THIS FUNCTION ADD THE GIVEN DATA IN THE CASSETTE FILE //********************************************************** void CASSETTE :: ADD_RECORD(char filename[13], int cascode, char casname[36], char casstatus, int ccode) { fstream file ; file.open(filename, ios::app) ; code = cascode ; strcpy(name,casname) ; status = casstatus ; custcode = ccode ; file.write((char *) this, sizeof(CASSETTE)) ; file.close() ; } //********************************************************** // THIS FUNCTION GIVES DATA TO ADD RECORD IN CASSETTE FILE //********************************************************** void CASSETTE :: ADDITION(void) { MENU menu ; char filename[13], casname[36], ch ; int cascode, valid ; do { strcpy(filename,menu.CHOICE_MENU()) ; if (!strcmpi(filename,"FAILED")) return ; cascode = LASTCODE(filename) + 1 ; LINES line ; line.BOX(10,6,71,21,219) ; line.LINE_HOR(11,70,10,196) ; gotoxy(72,1) ; cout <<"<0>=EXIT" ; gotoxy(27,8) ; cout <<"ADDITION OF NEW CASSETTES" ; gotoxy(20,12) ; cout <<"Code # " <<cascode ; do { valid = 1 ; gotoxy(5,25) ; clreol() ; cout <<"ENTER NAME OF THE CASSETTE" ; gotoxy(20,14) ; cout <<" " ; gotoxy(20,14) ; cout <<"Name : " ; gets(casname) ; if (casname[0] == '0') return ; if (strlen(casname) < 1 || strlen(casname) > 35) { valid = 0 ; gotoxy(5,25) ; clreol() ; cout <<"\7Enter Correctly (Range: 1..35)" ; getch() ; } } while (!valid) ; gotoxy(5,25) ; clreol() ; do { gotoxy(20,17) ; cout <<" " ; gotoxy(20,17) ; cout <<"Do you want to save (y/n) " ; ch = getche() ; ch = toupper(ch) ; if (ch == '0') return ; } while (ch != 'Y' && ch != 'N') ; if (ch == 'Y') { char casstatus='A' ; int ccode=0 ; ADD_RECORD(filename,cascode,casname,casstatus,ccode) ; cascode++ ; } do { gotoxy(20,19) ; cout <<" " ; gotoxy(20,19) ; cout <<"Do you want to Add more (y/n) " ; ch = getche() ; ch = toupper(ch) ; if (ch == '0') return ; } while (ch != 'Y' && ch != 'N') ; if (ch == 'N') return ; } while (ch == 'Y') ; } //********************************************************** // THIS FUNCTION MODIFY THE CASSETTE RECORD //********************************************************** void CASSETTE :: MODIFICATION(void) { MENU menu ; char t1[10], ch, filename[13] ; int t2, cascode, valid ; strcpy(filename,menu.CHOICE_MENU()) ; if (!strcmpi(filename,"FAILED")) return ; do { valid = 1 ; do { clrscr() ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; gotoxy(5,5) ; cout <<"Enter code of the Cassette or <ENTER> for help " ; gets(t1) ; t2 = atoi(t1) ; cascode = t2 ; if (cascode == 0 && strlen(t1) != 0) return ; if (strlen(t1) == 0) DISPLAY_LIST(filename) ; } while (strlen(t1) == 0) ; if (!FOUND_CODE(filename,cascode)) { valid = 0 ; gotoxy(5,20) ; cout <<"\7Cassette code not found." ; getch() ; } } while (!valid) ; clrscr() ; gotoxy(72,1) ; cout <<"<0>=EXIT" ; DISPLAY_RECORD(filename,cascode) ; do { gotoxy(5,12) ; clreol() ; cout <<"Modify Cassette Name (y/n) " ; ch = getche() ; ch = toupper(ch) ; if (ch == '0') return ; } while (ch != 'Y' && ch != 'N') ; if (ch == 'N') return ; char casname[36] ; do { valid = 1 ; gotoxy(5,25) ; clreol() ; cout <<"ENTER NAME OF THE CASSETTE" ; gotoxy(5,15) ; clreol() ; cout <<"Name : " ; gets(casname) ; if (casname[0] == '0') return ; if (strlen(casname) < 1 || strlen(casname) > 35) { valid = 0 ; gotoxy(5,25) ; clreol() ; cout <<"\7Enter Correctly (Range: 1..35)" ; getch() ; } } while (!valid) ; gotoxy(5,25) ; clreol() ; do { gotoxy(5,17) ; clreol() ; cout <<"Do you want to save (y/n) " ; ch = getche() ; ch = toupper(ch) ; if (ch == '0') return ; } while (ch != 'Y' && ch != 'N') ; if (ch == 'N') return ; int recno ; recno = RECORDNO(filename,cascode) ; fstream file ; file.open(filename, ios::out | ios::ate) ; strcpy(name,casname) ; int location ; location = (recno-1) * sizeof(CASSETTE) ; file.seekp(location) ; file.write((char *) this, sizeof(CASSETTE)) ; file.close() ; gotoxy(5,20) ; cout <<"\7Record Modified" ; gotoxy(5,25) ; cout <<"Press any key to continue..." ; getch() ; } //********************************************************** // THIS FUNCTION GIVES CODE TO DELETE THE CASSETTE RECORD //********************************************************** void CASSETTE :: DELETION(void) { MENU menu ; char t1[10], ch, filename[13] ; int t2, cascode, valid ; strcpy(filename,menu.CHOICE_MENU()) ; if (!strcmpi(filename,"FAILED")) return ; do { valid = 1 ; do { clrscr() ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; gotoxy(5,5) ; cout <<"Enter code of the Cassette or <ENTER> for help " ; gets(t1) ; t2 = atoi(t1) ; cascode = t2 ; if (cascode == 0 && strlen(t1) != 0) return ; if (strlen(t1) == 0) DISPLAY_LIST(filename) ; } while (strlen(t1) == 0) ; if (!FOUND_CODE(filename,cascode)) { valid = 0 ; gotoxy(5,20) ; cout <<"\7Cassette code not found." ; getch() ; } } while (!valid) ; clrscr() ; gotoxy(72,1) ; cout <<"<0>=EXIT" ; DISPLAY_RECORD(filename,cascode) ; do { gotoxy(5,12) ; clreol() ; cout <<"Delete this Cassette Record (y/n) " ; ch = getche() ; ch = toupper(ch) ; if (ch == '0') return ; } while (ch != 'Y' && ch != 'N') ; if (ch == 'N') return ; DELETE_RECORD(filename,cascode) ; gotoxy(5,20) ; cout <<"\7Record Deleted" ; gotoxy(5,25) ; cout <<"Press any key to continue..." ; getch() ; } //********************************************************** // THIS FUNCTION RETURNS THE LAST CUSTOMER'S CODE //********************************************************** int CUSTOMER :: LASTCODE(void) { fstream file ; file.open("CUSTOMER.DAT", ios::in) ; file.seekg(0,ios::beg) ; int count=0 ; while (file.read((char *) this, sizeof(CUSTOMER))) count = code ; file.close() ; return count ; } //********************************************************** // THIS FUNCTION RETURNS 0 IF THE GIVEN CODE NOT FOUND //********************************************************** int CUSTOMER :: FOUND_CODE(int custcode) { fstream file ; file.open("CUSTOMER.DAT", ios::in) ; file.seekg(0,ios::beg) ; int found=0 ; while (file.read((char *) this, sizeof(CUSTOMER))) { if (code == custcode) { found = 1 ; break ; } } file.close() ; return found ; } //********************************************************** // THIS FUNCTION RETURNS NAME OF THE CUSTOMER FOR THE GIVEN // CODE //********************************************************** char *CUSTOMER :: CUSTNAME(int custcode) { fstream file ; file.open("CUSTOMER.DAT", ios::in) ; file.seekg(0,ios::beg) ; char custname[26] ; while (file.read((char *) this, sizeof(CUSTOMER))) { if (code == custcode) { strcpy(custname,name) ; break ; } } file.close() ; return custname ; } //********************************************************** // THIS FUNCTION DISPLAYS THE LIST OF THE CUSTOMER //********************************************************** void CUSTOMER :: LIST(void) { int row = 6 , found=0, flag=0 ; char ch ; gotoxy(31,2) ; cout <<"LIST OF CUSTOMERS" ; gotoxy(30,3) ; cout <<"~~~~~~~~~~~~~~~~~~~" ; gotoxy(3,4) ; cout <<"CODE NAME PHONE" ; gotoxy(1,5) ; cout <<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ; fstream file ; file.open("CUSTOMER.DAT", ios::in) ; file.seekg(0,ios::beg) ; while (file.read((char *) this, sizeof(CUSTOMER))) { flag = 0 ; delay(20) ; found = 1 ; gotoxy(4,row) ; cout <<code ; gotoxy(10,row) ; cout <<name ; gotoxy(57,row) ; cout <<phone ; if ( row == 23 ) { flag = 1 ; row = 6 ; gotoxy(1,25) ; cout <<"Press any key to continue or Press <ESC> to exit" ; ch = getch() ; if (ch == 27) break ; clrscr() ; gotoxy(31,2) ; cout <<"LIST OF CUSTOMERS" ; gotoxy(30,3) ; cout <<"~~~~~~~~~~~~~~~~~~~" ; gotoxy(3,4) ; cout <<"CODE NAME PHONE" ; gotoxy(1,5) ; cout <<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ; } else row++ ; } if (!found) { gotoxy(5,10) ; cout <<"\7Records not found" ; } if (!flag) { gotoxy(1,25) ; cout <<"Press any key to continue..." ; getche() ; } file.close () ; } //********************************************************** // THIS FUNCTION DISPLAYS THE RECORD OF CUSTOMER FOR THE // GIVEN CODE //********************************************************** void CUSTOMER :: DISPLAY_RECORD(int ccode) { CASSETTE cas ; fstream file ; file.open("CUSTOMER.DAT", ios::in) ; file.seekg(0,ios::beg) ; while (file.read((char *) this, sizeof(CUSTOMER))) { if (code == ccode) { gotoxy(5,4) ; cout <<"Customer Code # " <<code ; gotoxy(5,6) ; cout <<"Customer Name : " <<name ; gotoxy(5,7) ; cout <<"Customer Phone : " <<phone ; gotoxy(5,9) ; cout <<"Cassette Issued : " <<cas.CASNAME(fname,cassette) ; gotoxy(5,10) ; cout <<"Date of Return : " <<dd <<"/" <<mm <<"/" <<yy ; break ; } } file.close() ; } //********************************************************** // THIS FUNCTION GIVES CODE TO DISPLAYS THE RECORD OF // CUSTOMER //********************************************************** void CUSTOMER :: DISPLAY(void) { char t1[10] ; int t2, custcode ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; gotoxy(5,5) ; cout <<"Enter code of the Customer " ; gets(t1) ; t2 = atoi(t1) ; custcode = t2 ; if (custcode == 0) return ; clrscr() ; if (!FOUND_CODE(custcode)) { gotoxy(5,5) ; cout <<"\7Record not found" ; getch() ; return ; } LINES line ; line.BOX(2,1,79,25,218) ; DISPLAY_RECORD(custcode) ; gotoxy(5,24) ; cout <<"Press any key to continue..." ; getch() ; } //********************************************************** // THIS FUNCTION DELETES THE RECORD OF THE GIVEN CODE. //********************************************************** void CUSTOMER :: DELETE_RECORD(int ccode) { CASSETTE cas ; fstream file ; file.open("CUSTOMER.DAT", ios::in) ; fstream temp ; temp.open("temp.dat", ios::out) ; file.seekg(0,ios::beg) ; while ( !file.eof() ) { file.read((char *) this, sizeof(CUSTOMER)) ; if ( file.eof() ) break ; if ( code != ccode ) temp.write((char *) this, sizeof(CUSTOMER)) ; else cas.UPDATE(fname,cassette,0,'A') ; } file.close() ; temp.close() ; file.open("CUSTOMER.DAT", ios::out) ; temp.open("temp.dat", ios::in) ; temp.seekg(0,ios::beg) ; while ( !temp.eof() ) { temp.read((char *) this, sizeof(CUSTOMER)) ; if ( temp.eof() ) break ; file.write((char *) this, sizeof(CUSTOMER)) ; } file.close() ; temp.close() ; } //********************************************************** // THIS FUNCTION ADDS THE GIVEN DATA IN THE CUSTOMER'S FILE //********************************************************** void CUSTOMER :: ADD_RECORD(int custcode, char custname[26], char custphone[10], char filename[13], int cascode, int d, int m, int y) { fstream file ; file.open("CUSTOMER.DAT", ios::app) ; code = custcode ; strcpy(name,custname) ; strcpy(phone,custphone) ; strcpy(fname,filename) ; cassette = cascode ; dd = d ; mm = m ; yy = y ; file.write((char *) this, sizeof(CUSTOMER)) ; file.close() ; } //********************************************************** // THIS FUNCTION CALCULATE AND RETURN FINE FOR THE GIVEN // CUSTOMER CODE. //********************************************************** int CUSTOMER :: FINE(int ccode) { ISSUE_RETURN ir ; int d1, m1, y1 ; struct date d; getdate(&d); d1 = d.da_day ; m1 = d.da_mon ; y1 = d.da_year ; fstream file ; file.open("CUSTOMER.DAT", ios::in) ; file.seekg(0,ios::beg) ; int days, t_fine ; while (file.read((char *) this, sizeof(CUSTOMER))) { if (code == ccode) { days = ir.DIFF(dd,mm,yy,d1,m1,y1) ; t_fine = days * 20 ; break ; } } file.close() ; return t_fine ; } //********************************************************** // FUNCTION TO EXTEND GIVEN DATE BY 5 DAYS //********************************************************** void ISSUE_RETURN :: EXTEND_DATE(int d1, int m1, int y1, int days) { static int month[] = {31,29,31,30,31,30,31,31,30,31,30,31} ; for (int i=1; i<=days; i++) { d1++ ; if ((d1 > month[m1-1]) || (y1%4 != 0 && m1 == 2 && d1 > 28)) { d1 = 1 ; m1++ ; } if (m1 > 12) { m1 = 1 ; y1++ ; } } day = d1 ; mon = m1 ; year = y1 ; } //********************************************************** // THIS FUNCTION RETURN THE DIFFERENCE BETWEEN TWO GIVEN // DATES //********************************************************** int ISSUE_RETURN :: DIFF(int d1, int m1, int y1, int d2, int m2, int y2) { int days = 0 ; if ((y2<y1) || (y2==y1 && m2<m1) || (y2==y1 && m2==m1 && d2<d1)) return days ; static int month[] = {31,29,31,30,31,30,31,31,30,31,30,31} ; while (d1 != d2 || m1 != m2 || y1 != y2) { days++ ; d1++ ; if ((d1 > month[m1-1]) || (y1%4 != 0 && m1 == 2 && d1 > 28)) { d1 = 1 ; m1++ ; } if (m1 > 12) { m1 = 1 ; y1++ ; } } return days ; } //********************************************************** // THIS FUNCTION ISSUE CASSETTE TO THE CUSTOMER & GIVE DATA // TO ADD RECORD IN CUSTOMER'S FILE //********************************************************** void ISSUE_RETURN :: ISSUE(void) { MENU menu ; CUSTOMER cust ; CASSETTE cas ; char filename[13] ; strcpy(filename,menu.CHOICE_MENU()) ; if (!strcmpi(filename,"FAILED")) return ; char t1[10] ; int t2, cascode, valid ; do { valid = 1 ; do { clrscr() ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; gotoxy(5,5) ; cout <<"Enter code of the Cassette or <ENTER> for help " ; gets(t1) ; t2 = atoi(t1) ; cascode = t2 ; if (cascode == 0 && strlen(t1) != 0) return ; if (strlen(t1) == 0) DISPLAY_LIST(filename) ; } while (strlen(t1) == 0) ; if (!CASSETTE::FOUND_CODE(filename,cascode)) { valid = 0 ; gotoxy(5,20) ; cout <<"\7Cassette code not found. Kindly choose another." ; getch() ; } if (valid && ISSUED(filename,cascode)) { valid = 0 ; gotoxy(5,20) ; cout <<"\7Cassette already issued. Kindly choose another." ; getch() ; } } while (!valid) ; clrscr() ; int ccode ; ccode = CUSTOMER::LASTCODE() + 1 ; char custname[26], custphone[10] ; int d1, m1, y1 ; struct date d; getdate(&d); d1 = d.da_day ; m1 = d.da_mon ; y1 = d.da_year ; gotoxy(5,2) ; cout <<"Date: " <<d1 <<"/" <<m1 <<"/" <<y1 ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; CASSETTE::DISPLAY_RECORD(filename,cascode) ; gotoxy(5,10) ; cout <<"Customer Code # " <<ccode ; gotoxy(5,12) ; cout <<"Name : " ; gotoxy(5,13) ; cout <<"Phone : " ; do { valid = 1 ; gotoxy(5,25) ; clreol() ; cout <<"Enter the name of the Customer" ; gotoxy(14,12) ; clreol() ; gets(custname) ; strupr(custname) ; if (custname[0] == '0') return ; if (strlen(custname) < 1 || strlen(custname) > 25) { valid = 0 ; gotoxy(5,25) ; clreol() ; cout <<"\7Enter correctly (Range: 1..25)" ; getch() ; } } while (!valid) ; do { valid = 1 ; gotoxy(5,25) ; clreol() ; cout <<"Enter Phone no. of the Customer" ; gotoxy(14,13) ; clreol() ; gets(custphone) ; if (custphone[0] == '0') return ; if ((strlen(custphone) < 7 && strlen(custphone) > 0) || (strlen(custphone) > 9)) { valid = 0 ; gotoxy(5,25) ; clreol() ; cout <<"\7Enter correctly" ; getch() ; } } while (!valid) ; gotoxy(5,25) ; clreol() ; UPDATE(filename,cascode,ccode,'N') ; EXTEND_DATE(d1,m1,y1,5) ; d1 = day ; m1 = mon ; y1 = year ; CUSTOMER::ADD_RECORD(ccode,custname,custphone,filename,cascode,d1,m1,y1) ; gotoxy(5,17) ; cout <<"\7CASSETTE ISSUED" ; gotoxy(5,19) ; cout <<"Date of Return : " <<d1 <<"/" <<m1 <<"/" <<y1 ; gotoxy(5,25) ; cout <<"Press any key to continue..." ; getch() ; } //********************************************************** // THIS FUNCTION RETURN CASSETTE FROM THE CUSTOMER //********************************************************** void ISSUE_RETURN :: RETURN(void) { CUSTOMER cust ; char t1[10], ch ; int t2, ccode, valid ; do { valid = 1 ; do { clrscr() ; gotoxy(72,2) ; cout <<"<0>=EXIT" ; gotoxy(5,5) ; cout <<"Enter code of the Customer or <ENTER> for help " ; gets(t1) ; t2 = atoi(t1) ; ccode = t2 ; if (ccode == 0 && strlen(t1) != 0) return ; if (strlen(t1) == 0) cust.LIST() ; } while (strlen(t1) == 0) ; if (!CUSTOMER::FOUND_CODE(ccode)) { valid = 0 ; gotoxy(5,20) ; cout <<"\7Customer code not found." ; getch() ; } } while (!valid) ; clrscr() ; CUSTOMER::DISPLAY_RECORD(ccode) ; int d1, m1, y1 ; struct date d; getdate(&d); d1 = d.da_day ; m1 = d.da_mon ; y1 = d.da_year ; gotoxy(5,2) ; cout <<"Date: " <<d1 <<"/" <<m1 <<"/" <<y1 ; do { gotoxy(5,13) ; clreol() ; cout <<"Return Cassette (y/n) " ; ch = getche() ; ch = toupper(ch) ; if (ch == '0') return ; } while (ch != 'Y' && ch != 'N') ; if (ch == 'N') return ; int f=FINE(ccode) ; if (f != 0) { gotoxy(5,16) ; cout <<"You have to pay a fine of Rs." <<f ; gotoxy(5,17) ; cout <<"Please do not delay the Return of Cassette again" ; } CUSTOMER::DELETE_RECORD(ccode) ; gotoxy(5,20) ; cout <<"\7Cassette Returned" ; gotoxy(5,25) ; cout <<"Press any key to continue..." ; getch() ; } //********************************************************** // MAIN FUNCTION CALLING MAIN MENU //********************************************************** void main(void) { MENU menu ; menu.MAIN_MENU() ; }
/** * @file mini_sdp/mini_sdp.h * @brief * @version 0.1 * @date 2021-01-14 * * @copyright Copyright (c) 2021 Tencent. All rights reserved. * */ #ifndef MINI_SDP_MINI_SDP_H_ #define MINI_SDP_MINI_SDP_H_ #include <string> #include <vector> #include "sdp.h" namespace mini_sdp { /** * @brief Return Code * 统一返回码 */ enum SdpRetcode { kSdpRetWrongFormat = -1, // 格式错误 kSdpRetSizeExceeded = -2, // 打包结果超过所提供的 buffer 大小 kSdpRetUrlExceeded = -3 // 流 URL 过长,使得无法存入所有提供的 buffer }; /** * @brief Stream Direction * 流类型(传输方向) * - 可为拉流、推流或者默认 */ enum StreamDirection { kStreamDefault = -1, kStreamPull = 0, // 拉流 kStreamPush = 1, // 推流 }; /** * @brief Origin SDP Attribute * 原始 SDP 属性,原始 SDP 与 mini sdp 互转的参数结构 */ struct OriginSdpAttr { // SDP Type // - SDP 类型,offer 或者 answer // - SdpType的定义见 mini_sdp/sdp.h SdpType sdp_type; // Origin SDP // - 原始SDP std::string origin_sdp; // Stream Url // - 流URL,格式如:webrtc://<domain>/[<path>/]<stream id> std::string stream_url; // Server Signature // - 服务端标识,唯一标识 Session // - 停流请求需要设置该值 // - offer 不需要该值 // - 格式: <ip>:<ice-ufrag in answer>:<ice-ufrag in offer> // * 服务端需要保存 answer (响应UDP)中的 svrsig std::string svrsig; // Status Code // - 响应状态码,仅在 answer 中为有效值 int status_code = 0; // Sequence // - 请求序号 // - UDP 可能会有丢包的情况,为保证到达服务端,需要有一定的重试策略, // 相同请求的 seq 需要保持一致,并且需要确保同一客户端不同请求的 seq 是不一致, // 建议客户端本地对 seq 递增处理。 // - 服务端可以根据 seq 来过滤重复 UDP 请求 // * 客户端需要保存当前请求的 seq uint16_t seq = 0; // Flag: Immediately Sneding // - 立即发送标志位,即 0-RTT // - 若开启,表示客户端有能力直接立即接收媒体数据, // 服务端可以向该 UDP 请求的源地址发送媒体数据 bool is_imm_send = false; // Flag: Aac Fmtp Supported // - Aac 参数标志位 // - 表示是否保留 ADTS 和 LATM 音频的 fmtp属性,默认开启 // - 这是用于 v0 版本兼容不同子版本的标志位,v1 版本将不再需要 bool is_support_aac_fmtp = true; // Flag: Stream Direction // - 流类型标志位,指示拉流或者推流 // - 默认表示依据原始 SDP 的描述 StreamDirection is_push = kStreamDefault; // -1 not have field , 0 false, 1 true }; // struct OriginSdpAttr /** * @brief Status Code * 响应码,与 http 接口保持一致 */ enum StatusCode { kStatCodeSuccess = 0, kStatCodeFormatError = 100, // sdp format error kStatCodeParamError = 101, // parameters of request error kStatCodeInfoError = 102, // stream info error kStatCodeAuthError = 103, // auth error kStatCodeNotFound = 104 // stream not existed }; /** * @brief Check Request Packet * 检查 UDP 包是否为 mini sdp 请求 * @param data * @param len * @return true * @return false */ bool IsMiniSdpReqPack(const char* data, size_t len); /** * @brief Load mini_sdp to origin_sdp * 将 mini sdp 转换成原始 SDP * @param buff mini_sdp * @param len mini_sdp * @param attr result * @return int SdpRetCode or size of mini_sdp */ ssize_t LoadMiniSdpToOriginSdp(const char* buff, size_t len, OriginSdpAttr& attr); /** * @brief Parse origin_sdp to mini_sdp * 将原始 SDP 转换成 mini sdp * @param attr origin sdp * @param buff mini_sdp * @param len mini_sdp * @return int SdpRetCode or size of mini_sdp */ ssize_t ParseOriginSdpToMiniSdp(const OriginSdpAttr& attr, char* buff, size_t len); /** * @brief Stop Stream Attribute * 停流参数 */ struct StopStreamAttr { // Server Signature // - 服务端标识 // * 与 answer (响应 UDP)的 svrsig 保持一致 std::string svrsig; // Status Code // - 响应状态码,仅在响应中为有效值 uint16_t status = 0; // Sequence // - 请求序号 // * 与请求的 seq 保持一致 uint16_t seq = 0; }; // struct StopStreamAttr /** * @brief Check Stop Packet * 检查 UDP 包是否为 mini sdp 停流包 * @param data * @param len * @return true * @return false */ bool IsMiniSdpStopPack(const char* data, size_t len); /** * @brief Build packet for stop stream * 构建 mini sdp 停流 UDP 包 * @param buff packet * @param len packet * @param attr * @return ssize_t */ ssize_t BuildStopStreamPacket(char* buff, size_t len, const StopStreamAttr& attr); /** * @brief Load Response of Stop Stream Packet * 解析 mini sdp 停流 UDP 包 * @param buff * @param len * @param attr * @return ssize_t */ ssize_t LoadStopStreamPacket(const char* buff, size_t len, StopStreamAttr& attr); } // namespace mini_sdp #endif // MINI_SDP_MINI_SDP_H_
// Wed Aug 24 15:46:50 EDT 2016 // Evan S Weinberg // Include file for CG-M #ifndef ESW_INVERTER_CG_M #define ESW_INVERTER_CG_M #include <string> #include <complex> using std::complex; #include "inverter_struct.h" #include "verbosity.h" // Multishift CG defined in http://arxiv.org/pdf/hep-lat/9612014.pdf inversion_info minv_vector_cg_m(double **phi, double *phi0, int n_shift, int size, int resid_freq_check, int max_iter, double eps, double* shifts, void (*matrix_vector)(double*,double*,void*), void* extra_info, bool worst_first = false, inversion_verbose_struct* verbosity = 0); inversion_info minv_vector_cg_m(complex<double> **phi, complex<double> *phi0, int n_shift, int size, int resid_freq_check, int max_iter, double eps, double* shifts, void (*matrix_vector)(complex<double>*,complex<double>*,void*), void* extra_info, bool worst_first = false, inversion_verbose_struct* verbosity = 0); // multishift CG starts with 0 initial guess, so a restarted version wouldn't work. #endif
#include<stdio.h> #include<stdlib.h> typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; }; main() { int price,c; float n; SYSTEMTIME str_t; GetSystemTime(&str_t); printf("1:Rice(kg) 2:salt(500g) 3:sugar(pkt) 4:tomatoes(kg) 5:potatoes(kg) "); printf("6:Ladies fingers(kg) 7:cucumber(kg) 8:brinjal(kg) 9:onions(kg) 10:raddish(kg)\n"); printf("%d/%d/%d %d:%d:%d \n",str_t.wDay,str_t.wMonth,str_t.wYear,str_r.wHour,str_t.wMinute,str_t.wSecond); }
#ifndef VULKANLAB_CLOCK_H #define VULKANLAB_CLOCK_H #include <GLFW/glfw3.h> class Clock { public: Clock() {} ~Clock() {} /** * Return the time in milliseconds from the GLFW get time function. * - TODO Improve it with a more precise timer. * @return */ inline double getTime() { return time = glfwGetTime(); } private: double time; }; #endif //VULKANLAB_CLOCK_H
// // Created by silvman on 3/3/19. // #ifndef EESKORKA_TYPES_H #define EESKORKA_TYPES_H #include <functional> enum connectionAction { rearmConnection = 100, closeConnection, waitUntillReaded, }; typedef std::function<void(int, connectionAction)> loopCallbackType; typedef std::function<int(int, loopCallbackType &)> clientCallbackType; #endif //EESKORKA_TYPES_H
TurnManager::TurnManager(QObject *parent) : QObject(parent) { } QVector<Move*> TurnManager::sort(const QVector<Move*> &array) { //Do something return array; }
/* Copyright 2021 University of Manchester 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 "addition.hpp" using orkhestrafs::dbmstodspi::Addition; void Addition::DefineInput(int stream_id, int chunk_id) { AccelerationModule::WriteToModule(0, (chunk_id << 8) + stream_id); } void Addition::SetInputSigns(std::bitset<8> is_value_negative) { AccelerationModule::WriteToModule(4, is_value_negative.to_ulong()); } void Addition::SetLiteralValues( std::array<std::pair<uint32_t, uint32_t>, 8> literal_values) { for (int i = 0; i < literal_values.size(); i++) { AccelerationModule::WriteToModule(64 + (i * 8), literal_values.at(i).first); AccelerationModule::WriteToModule(64 + (i * 8) + 4, literal_values.at(i).second); } }
// Problem: Swastika // Author: babang #include <algorithm> #include <iostream> #include <map> #include <set> #include <vector> #include <math.h> #define forn(i, n) for(int i = 0; i < n; i++) #define rofn(i, n) for(int i = n-1; i >= 0; i--) #define foran(i, a, n) for(int i = a; i < n; i++) #define rofan(i, a, n) for(int i = a-1; i >= n; i--) #define T() int t; cin>>t; while(t--) #define scan(x) scanf("%lld",&x) #define print(x) printf("%lld ",x) #define eb emplace_back #define pb push_back #define mp make_pair #define fi first #define se second #define be begin() #define en end() #define YES printf("YES\n") #define NO printf("NO\n") #define br printf("\n"); using namespace std; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef vector<ll> vll; typedef pair<ll, ll> pll; typedef map<ll, ll> mll; typedef set<ll, ll> sll; ll N, t; int main() { cin >> N >> t; forn(qq, N) { forn(ww, N) { if (qq < t) { if (ww < (N+t)/2 || ww >= (N-t)) cout << "* "; else cout << " "; } if (qq >= t && qq < (N-t)/2) { if ((ww >= (N-t)/2 && ww < (N+t)/2) || ww >= (N-t)) cout << "* "; else cout << " "; } if (qq >= (N-t)/2 && qq < (N+t)/2) { cout << "* "; } if (qq >= (N+t)/2 && qq < (N-t)) { if (ww < t || (ww >= (N-t)/2 && ww < (N+t)/2)) cout << "* "; else cout << " "; } if (qq >= (N-t)) { if (ww < t || ww >= (N-t)/2) cout << "* "; else cout << " "; } } cout << endl; } return 0; }
#pragma once #include <Tanker/Network/AConnection.hpp> #include <Tanker/Network/SdkInfo.hpp> #include <optional> namespace Tanker { namespace Network { struct ConnectionFactory { static ConnectionPtr create(std::string url, std::optional<SdkInfo> info); }; } }
#include <initializer_list> #include <algorithm> class vector2 { int sz; double* elem; public: vector2(int); vector2(const vector2&); vector2(std::initializer_list<double>); vector2(vector2&&); vector2& operator=(const vector2&); vector2& operator=(vector2&&); double operator[](int) const; double& operator[](int); ~vector2(); int size(); double get(int) const; void set(int, double); };
#include "Node.h" void Node::SetLeft(Node *temp) { m_left = temp; } void Node::SetRight(Node *temp) { m_right = temp; } void Node::SetParent(Node *temp) { m_parent = temp; } Node *Node::GetLeft() { return m_left; } Node *Node::GetRight() { return m_right; } Node *Node::GetParent() { return m_parent; } void Node::SetValue(int temp) { value = temp; } int Node::GetValue() { return value; } Node::Node() { m_left = nullptr; m_right = nullptr; m_parent = nullptr; value = 0; } Node::Node(int value) { m_left = m_right = m_parent = nullptr; this->value = value; } Node::~Node() {}
// // Created by user on 2017/4/6. // #ifndef DD_GAMES_ROOMCARDUTIL_H #define DD_GAMES_ROOMCARDUTIL_H #include <stdint.h> #include "RedisAccess.h" namespace RoomCardUtil { int randomTableID(int gameID, int min = 1000, int max = 9999); int getOwnerUidByTableId(int gameId, int tid); bool getRemainMoney(int ownerid, int uid, int64_t& moneyValue, int64_t& maxWins); /// <summary> /// 获取房卡配置信息 /// std::map<int, int> round==>price /// round 可玩局数 /// price 房卡价格 /// </summary> bool getRoomCardMenu(RedisAccess* redis, std::map<int, int> &pricelist); int getCardRoomPrice(int matchCount); bool updateUserRoomCard(int uid, int64_t money); }; #endif //DD_GAMES_ROOMCARDUTIL_H
#include "../includes/monom.h" using namespace std; bool operator < (const link& x, const link& y) { if (x.deg_x < y.deg_x) return true; if (x.deg_x == y.deg_x) { if (x.deg_y < y.deg_y) return true; if (x.deg_y == y.deg_y) { if (x.deg_z < y.deg_z) return true; } } return false; } bool operator >= (const link& x, const link& y) { if (x.deg_x < y.deg_x) return false; if (x.deg_x == y.deg_x) { if (x.deg_y < y.deg_y) return false; if (x.deg_y == y.deg_y) { if (x.deg_z < y.deg_z) return false; } } return true; } bool operator == (const link& x, const link& y) { if (x.deg_x == y.deg_x && x.deg_y == y.deg_y && x.deg_z == y.deg_z) return true; return false; } link operator*(const link& x, const link& y) { link res; res.deg_x = x.deg_x + y.deg_x; res.deg_y = x.deg_y + y.deg_y; res.deg_z = x.deg_z + y.deg_z; res.a = x.a * y.a; return res; } ostream& operator<<(ostream& out, const link& t) { out << "(" << t.a << " * "; out << "x^" << t.deg_x << " * y^" << t.deg_y << " * z^" << t.deg_z << ")"; } istream& operator>>(istream& in, link& t) { in >> t.a >> t.deg_x >> t.deg_y >> t.deg_z; }
#include "dialog.h" #include "ui_dialog.h" #include <algorithm> Dialog::Dialog(QWidget *parent) : QDialog(parent), ui(new Ui::Dialog) { ui->setupUi(this); } Dialog::~Dialog(){ delete ui; } int Dialog::getDimX(){ return ui->horizontalSliderX->value(); } int Dialog::getDimY(){ return ui->horizontalSliderY->value(); } int Dialog::getDimZ(){ return ui->horizontalSliderZ->value(); }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #ifdef ECMASCRIPT_REMOTE_DEBUGGER #include "modules/ecmascript_utils/esremotemessageparts.h" #include "modules/ecmascript_utils/esremotedebugger.h" #include "modules/ecmascript_utils/esdebugger.h" ES_HelloMessagePart::ES_HelloMessagePart() : ES_DebugMessagePart(BODY_HELLO), os(NULL), platform(NULL), useragent(NULL), delete_strings(TRUE) { } /* virtual */ ES_HelloMessagePart::~ES_HelloMessagePart() { if (delete_strings) { FreeItemDataString(os, os_length); FreeItemDataString(platform, platform_length); FreeItemDataString(useragent, useragent_length); } } /* virtual */ unsigned ES_HelloMessagePart::GetLength() { return 6; } /* virtual */ void ES_HelloMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_HELLO); return; case 1: GetItemDataUnsigned(data, length, ES_DebugMessage::PROTOCOL_VERSION); return; case 2: data = os; length = os_length; GetItemDataString(data, length); return; case 3: data = platform; length = platform_length; GetItemDataString(data, length); return; case 4: data = useragent; length = useragent_length; GetItemDataString(data, length); return; default: #define SUPPORTED_COMMAND(command) (1 << (ES_DebugMessage::command - 1)) GetItemDataUnsigned(data, length, (SUPPORTED_COMMAND(TYPE_NEW_SCRIPT) | SUPPORTED_COMMAND(TYPE_THREAD_STARTED) | SUPPORTED_COMMAND(TYPE_THREAD_FINISHED) | SUPPORTED_COMMAND(TYPE_STOPPED_AT) | SUPPORTED_COMMAND(TYPE_CONTINUE) | SUPPORTED_COMMAND(TYPE_EVAL) | SUPPORTED_COMMAND(TYPE_EVAL_REPLY) | SUPPORTED_COMMAND(TYPE_EXAMINE) | SUPPORTED_COMMAND(TYPE_EXAMINE_REPLY) | SUPPORTED_COMMAND(TYPE_ADD_BREAKPOINT) | SUPPORTED_COMMAND(TYPE_REMOVE_BREAKPOINT) | SUPPORTED_COMMAND(TYPE_SET_CONFIGURATION) | SUPPORTED_COMMAND(TYPE_BACKTRACE) | SUPPORTED_COMMAND(TYPE_BACKTRACE_REPLY) | SUPPORTED_COMMAND(TYPE_BREAK))); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_HelloMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { OP_ASSERT(FALSE); } ES_SetConfigurationMessagePart::ES_SetConfigurationMessagePart() : ES_DebugMessagePart(BODY_SET_CONFIGURATION) { } /* virtual */ unsigned ES_SetConfigurationMessagePart::GetLength() { return 6; } /* virtual */ void ES_SetConfigurationMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND BOOL value; switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_SET_CONFIGURATION; return; case 1: value = stop_at_script; break; case 2: value = stop_at_exception; break; case 3: value = stop_at_error; break; case 4: value = stop_at_abort; break; default: value = stop_at_gc; break; } GetItemDataBoolean(data, length, value); #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_SetConfigurationMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND ES_DebugMessage::ParseBooleanL(data, size, length, stop_at_script); ES_DebugMessage::ParseBooleanL(data, size, length, stop_at_exception); ES_DebugMessage::ParseBooleanL(data, size, length, stop_at_error); ES_DebugMessage::ParseBooleanL(data, size, length, stop_at_abort); ES_DebugMessage::ParseBooleanL(data, size, length, stop_at_gc); #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_NewScriptMessagePart::ES_NewScriptMessagePart() : ES_DebugMessagePart(BODY_NEW_SCRIPT), source(NULL), uri(NULL), delete_strings(TRUE) { } /* virtual */ ES_NewScriptMessagePart::~ES_NewScriptMessagePart() { if (delete_strings) { FreeItemDataString(source, source_length); if (script_type == SCRIPT_TYPE_LINKED) FreeItemDataString(uri, uri_length); } } /* virtual */ unsigned ES_NewScriptMessagePart::GetLength() { return script_type == SCRIPT_TYPE_LINKED ? 6 : 5; } /* virtual */ void ES_NewScriptMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_NEW_SCRIPT); return; case 1: GetItemDataUnsigned(data, length, runtime_id); return; case 2: GetItemDataUnsigned(data, length, script_id); return; case 3: GetItemDataUnsigned(data, length, script_type); return; case 4: data = source; length = source_length; GetItemDataString(data, length); return; default: data = uri; length = uri_length; GetItemDataString(data, length); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_NewScriptMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND delete_strings = FALSE; ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, script_id); ES_DebugMessage::ParseUnsignedL(data, size, length, script_type); ES_DebugMessage::ParseStringL(data, size, length, source, source_length); if (script_type == SCRIPT_TYPE_LINKED) ES_DebugMessage::ParseStringL(data, size, length, uri, uri_length); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_ThreadStartedMessagePart::ES_ThreadStartedMessagePart() : ES_DebugMessagePart(BODY_THREAD_STARTED), event_namespace_uri(NULL), event_type(NULL), delete_strings(TRUE) { } /* virtual */ ES_ThreadStartedMessagePart::~ES_ThreadStartedMessagePart() { if (delete_strings && thread_type == THREAD_TYPE_EVENT) { FreeItemDataString(event_namespace_uri, event_namespace_uri_length); FreeItemDataString(event_type, event_type_length); } } /* virtual */ unsigned ES_ThreadStartedMessagePart::GetLength() { return thread_type == THREAD_TYPE_EVENT ? 7 : 5; } /* virtual */ void ES_ThreadStartedMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_THREAD_STARTED); return; case 1: GetItemDataUnsigned(data, length, runtime_id); return; case 2: GetItemDataUnsigned(data, length, thread_id); return; case 3: GetItemDataUnsigned(data, length, parent_thread_id); return; case 4: GetItemDataUnsigned(data, length, thread_type); return; case 5: data = event_namespace_uri; length = event_namespace_uri_length; GetItemDataString(data, length); return; default: data = event_type; length = event_type_length; GetItemDataString(data, length); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_ThreadStartedMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND delete_strings = FALSE; ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, parent_thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_type); if (thread_type == THREAD_TYPE_EVENT) { ES_DebugMessage::ParseStringL(data, size, length, event_namespace_uri, event_namespace_uri_length); ES_DebugMessage::ParseStringL(data, size, length, event_type, event_type_length); } #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_ThreadFinishedMessagePart::ES_ThreadFinishedMessagePart() : ES_DebugMessagePart(BODY_THREAD_FINISHED) { } /* virtual */ unsigned ES_ThreadFinishedMessagePart::GetLength() { return 4; } /* virtual */ void ES_ThreadFinishedMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_THREAD_FINISHED); return; case 1: GetItemDataUnsigned(data, length, runtime_id); return; case 2: GetItemDataUnsigned(data, length, thread_id); return; default: GetItemDataUnsigned(data, length, status); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_ThreadFinishedMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_StoppedAtMessagePart::ES_StoppedAtMessagePart() : ES_DebugMessagePart(BODY_STOPPED_AT) { } /* virtual */ unsigned ES_StoppedAtMessagePart::GetLength() { return 5; } /* virtual */ void ES_StoppedAtMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_STOPPED_AT); return; case 1: GetItemDataUnsigned(data, length, runtime_id); return; case 2: GetItemDataUnsigned(data, length, thread_id); return; case 3: GetItemDataUnsigned(data, length, position.scriptid); return; default: GetItemDataUnsigned(data, length, position.linenr); return; } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_StoppedAtMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, position.scriptid); ES_DebugMessage::ParseUnsignedL(data, size, length, position.linenr); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_ContinueMessagePart::ES_ContinueMessagePart() : ES_DebugMessagePart(BODY_CONTINUE) { } /* virtual */ unsigned ES_ContinueMessagePart::GetLength() { return 4; } /* virtual */ void ES_ContinueMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_CONTINUE); return; case 1: GetItemDataUnsigned(data, length, runtime_id); return; case 2: GetItemDataUnsigned(data, length, thread_id); return; default: GetItemDataUnsigned(data, length, mode); return; } #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_ContinueMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, mode); #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_EvalMessagePart::ES_EvalMessagePart() : ES_DebugMessagePart(BODY_EVAL), script(NULL), delete_strings(TRUE) { } ES_EvalMessagePart::~ES_EvalMessagePart() { if (delete_strings) FreeItemDataString(script, script_length); } /* virtual */ unsigned ES_EvalMessagePart::GetLength() { return 6; } /* virtual */ void ES_EvalMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_EVAL); return; case 1: GetItemDataUnsigned(data, length, tag); return; case 2: GetItemDataUnsigned(data, length, runtime_id); return; case 3: GetItemDataUnsigned(data, length, thread_id); return; case 4: GetItemDataUnsigned(data, length, frame_index); return; default: data = script; length = script_length; GetItemDataString(data, length); } #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_EvalMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND delete_strings = FALSE; ES_DebugMessage::ParseUnsignedL(data, size, length, tag); ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, frame_index); ES_DebugMessage::ParseStringL(data, size, length, script, script_length); #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_EvalReplyMessagePart::ES_EvalReplyMessagePart() : ES_DebugMessagePart(BODY_EVAL_REPLY) { } /* virtual */ unsigned ES_EvalReplyMessagePart::GetLength() { return 3; } /* virtual */ void ES_EvalReplyMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_EVAL_REPLY); return; case 1: GetItemDataUnsigned(data, length, tag); return; default: GetItemDataUnsigned(data, length, status); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_EvalReplyMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND ES_DebugMessage::ParseUnsignedL(data, size, length, tag); ES_DebugMessage::ParseUnsignedL(data, size, length, status); #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_ExamineMessagePart::ES_ExamineMessagePart() : ES_DebugMessagePart(BODY_EXAMINE), objects_count(0), object_ids(NULL) { } /* virtual */ unsigned ES_ExamineMessagePart::GetLength() { return 4 + objects_count; } /* virtual */ void ES_ExamineMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_EXAMINE); return; case 1: GetItemDataUnsigned(data, length, tag); return; case 2: GetItemDataUnsigned(data, length, runtime_id); return; case 3: GetItemDataUnsigned(data, length, objects_count); return; default: OP_ASSERT(index - 3 < objects_count); GetItemDataUnsigned(data, length, object_ids[index - 3]); } #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_ExamineMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND ES_DebugMessage::ParseUnsignedL(data, size, length, tag); ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseBooleanL(data, size, length, in_scope); if (in_scope) { ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, frame_index); } else { ES_DebugMessage::ParseUnsignedL(data, size, length, objects_count); object_ids = new (ELeave) unsigned[objects_count]; for (unsigned index = 0; index < objects_count; ++index) ES_DebugMessage::ParseUnsignedL(data, size, length, object_ids[index]); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_ExamineReplyMessagePart::ES_ExamineReplyMessagePart() : ES_DebugMessagePart(BODY_EXAMINE_REPLY), objects_count(0), objects(NULL) { } /* virtual */ ES_ExamineReplyMessagePart::~ES_ExamineReplyMessagePart() { for (unsigned oindex = 0; oindex < objects_count; ++oindex) { if (delete_strings) for (unsigned pindex = 0; pindex < objects[oindex]->properties_count; ++pindex) { const char *data = objects[oindex]->names[pindex]; unsigned length = objects[oindex]->name_lengths[pindex]; FreeItemDataString(data, length); } delete[] objects[oindex]->names; delete[] objects[oindex]->name_lengths; delete[] objects[oindex]->values; } delete[] objects; } /* virtual */ unsigned ES_ExamineReplyMessagePart::GetLength() { unsigned length = 3; for (unsigned index = 0; index < objects_count; ++index) length += 2 + objects[index]->properties_count * 3; return length; } /* virtual */ void ES_ExamineReplyMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_EXAMINE_REPLY); return; case 1: GetItemDataUnsigned(data, length, tag); return; case 2: GetItemDataUnsigned(data, length, objects_count); return; default: index -= 3; for (unsigned oindex = 0; oindex < objects_count; ++oindex) if (index < 2 + objects[oindex]->properties_count * 3) switch (index) { case 0: GetItemDataUnsigned(data, length, objects[oindex]->object_id); return; case 1: GetItemDataUnsigned(data, length, objects[oindex]->properties_count); return; default: index -= 2; unsigned pindex = index / 3; switch (index % 3) { case 0: data = objects[oindex]->names[pindex]; length = objects[oindex]->name_lengths[pindex]; GetItemDataString(data, length); return; case 1: GetItemDataValueType(data, length, objects[oindex]->values[pindex]); return; case 2: GetItemDataValueValue(data, length, objects[oindex]->values[pindex]); return; } } else index -= 2 + objects[oindex]->properties_count * 3; OP_ASSERT(FALSE); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_ExamineReplyMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND ES_DebugMessage::ParseUnsignedL(data, size, length, tag); ES_DebugMessage::ParseUnsignedL(data, size, length, objects_count); OP_ASSERT(FALSE); #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } void ES_ExamineReplyMessagePart::AddObjectL(unsigned id, unsigned properties_count) { Object **new_objects = new (ELeave) Object *[objects_count + 1]; op_memcpy(new_objects, objects, objects_count * sizeof objects[0]); delete[] objects; objects = new_objects; Object *object = objects[objects_count] = new (ELeave) Object; object->object_id = id; object->properties_count = 0; object->names = new (ELeave) char *[properties_count]; object->name_lengths = new (ELeave) unsigned[properties_count]; object->values = new (ELeave) ES_DebugValue[properties_count]; objects_count += 1; } void ES_ExamineReplyMessagePart::SetPropertyL(const uni_char *name, const ES_DebugValue &value) { Object *object = objects[objects_count - 1]; unsigned pindex = object->properties_count; object->names[pindex] = NULL; object->values[pindex].type = VALUE_UNDEFINED; ++object->properties_count; SetString16L(object->names[pindex], object->name_lengths[pindex], name); SetValueL(object->values[pindex], value); } ES_BacktraceMessagePart::ES_BacktraceMessagePart() : ES_DebugMessagePart(BODY_BACKTRACE) { } /* virtual */ unsigned ES_BacktraceMessagePart::GetLength() { return 4; } /* virtual */ void ES_BacktraceMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_BACKTRACE); return; case 1: GetItemDataUnsigned(data, length, tag); return; case 2: GetItemDataUnsigned(data, length, runtime_id); return; default: GetItemDataUnsigned(data, length, thread_id); } #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_BacktraceMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND ES_DebugMessage::ParseUnsignedL(data, size, length, tag); ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); ES_DebugMessage::ParseUnsignedL(data, size, length, max_frames); #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_BacktraceReplyMessagePart::ES_BacktraceReplyMessagePart() : ES_DebugMessagePart(BODY_BACKTRACE_REPLY), stack(NULL) { } /* virtual */ ES_BacktraceReplyMessagePart::~ES_BacktraceReplyMessagePart() { delete[] stack; } /* virtual */ unsigned ES_BacktraceReplyMessagePart::GetLength() { return 3 + 5 * stack_length; } /* virtual */ void ES_BacktraceReplyMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_BACKTRACE_REPLY); return; case 1: GetItemDataUnsigned(data, length, tag); return; case 2: GetItemDataUnsigned(data, length, stack_length); return; default: index -= 3; ES_DebugStackFrame &frame = stack[index / 5]; switch (index % 5) { case 0: GetItemDataUnsigned(data, length, frame.function.id); return; case 1: GetItemDataUnsigned(data, length, frame.arguments); return; case 2: GetItemDataUnsigned(data, length, frame.variables); return; case 3: GetItemDataUnsigned(data, length, frame.script_no); return; default: GetItemDataUnsigned(data, length, frame.line_no); } } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_BacktraceReplyMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { OP_ASSERT(FALSE); } ES_ObjectInfoMessagePart::ES_ObjectInfoMessagePart() : ES_DebugMessagePart(AUXILIARY_OBJECT_INFO), name(NULL), delete_strings(TRUE) { } /* virtual */ ES_ObjectInfoMessagePart::~ES_ObjectInfoMessagePart() { if (delete_strings && name) FreeItemDataString(name, name_length); } /* virtual */ unsigned ES_ObjectInfoMessagePart::GetLength() { return 6; } /* virtual */ void ES_ObjectInfoMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_OBJECT_INFO); return; case 1: GetItemDataUnsigned(data, length, object_id); return; case 2: GetItemDataUnsigned(data, length, prototype_id); return; case 3: GetItemDataBoolean(data, length, is_callable); return; case 4: GetItemDataBoolean(data, length, is_function); return; default: data = name; length = name_length; GetItemDataString(data, length); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_ObjectInfoMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND delete_strings = FALSE; ES_DebugMessage::ParseUnsignedL(data, size, length, object_id); ES_DebugMessage::ParseBooleanL(data, size, length, is_callable); ES_DebugMessage::ParseBooleanL(data, size, length, is_function); ES_DebugMessage::ParseStringL(data, size, length, name, name_length); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_WatchUpdateMessagePart::ES_WatchUpdateMessagePart() : ES_DebugMessagePart(AUXILIARY_WATCH_UPDATE), changed(NULL), delete_strings(TRUE) { } /* virtual */ ES_WatchUpdateMessagePart::~ES_WatchUpdateMessagePart() { if (delete_strings) for (unsigned index = 0; index < changed_count; ++index) delete[] changed[index].property_name; delete[] changed; } /* virtual */ unsigned ES_WatchUpdateMessagePart::GetLength() { return 3 + changed_count * 3; } /* virtual */ void ES_WatchUpdateMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_WATCH_UPDATE); return; case 1: GetItemDataUnsigned(data, length, object_id); return; case 2: GetItemDataUnsigned(data, length, changed_count); return; default: Changed &c = changed[index / 3 - 1]; switch (index % 3) { case 0: data = c.property_name; length = c.property_name_length; GetItemDataString(data, length); return; case 1: GetItemDataValueType(data, length, c.property_value); return; default: GetItemDataValueValue(data, length, c.property_value); } } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_WatchUpdateMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_StackMessagePart::ES_StackMessagePart() : ES_DebugMessagePart(AUXILIARY_STACK), frame(NULL) { } /* virtual */ ES_StackMessagePart::~ES_StackMessagePart() { delete[] frame; } /* virtual */ unsigned ES_StackMessagePart::GetLength() { return 2 + frame_count * 5; } /* virtual */ void ES_StackMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_STACK); return; case 1: GetItemDataUnsigned(data, length, frame_count); return; default: Frame &f = frame[(index - 2) / 5]; switch ((index - 2) % 5) { case 0: GetItemDataUnsigned(data, length, f.script_id); return; case 1: GetItemDataUnsigned(data, length, f.linenr); return; case 2: GetItemDataUnsigned(data, length, f.function_object_id); return; case 3: GetItemDataUnsigned(data, length, f.arguments_object_id); return; default: GetItemDataUnsigned(data, length, f.variables_object_id); return; } } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_StackMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_BreakpointTriggeredMessagePart::ES_BreakpointTriggeredMessagePart() : ES_DebugMessagePart(AUXILIARY_BREAKPOINT_TRIGGERED) { } /* virtual */ unsigned ES_BreakpointTriggeredMessagePart::GetLength() { return 2; } /* virtual */ void ES_BreakpointTriggeredMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_BREAKPOINT_TRIGGERED); return; case 1: GetItemDataUnsigned(data, length, id); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_BreakpointTriggeredMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND ES_DebugMessage::ParseUnsignedL(data, size, length, id); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_ReturnValueMessagePart::ES_ReturnValueMessagePart() : ES_DebugMessagePart(AUXILIARY_RETURN_VALUE) { } /* virtual */ ES_ReturnValueMessagePart::~ES_ReturnValueMessagePart() { } /* virtual */ unsigned ES_ReturnValueMessagePart::GetLength() { return 4; } /* virtual */ void ES_ReturnValueMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_RETURN_VALUE); return; case 1: GetItemDataUnsigned(data, length, function_object_id); return; case 2: GetItemDataValueType(data, length, value); return; default: GetItemDataValueValue(data, length, value); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_ReturnValueMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_ExceptionThrownMessagePart::ES_ExceptionThrownMessagePart() : ES_DebugMessagePart(AUXILIARY_EXCEPTION_THROWN) { exception.type = VALUE_UNDEFINED; } /* virtual */ ES_ExceptionThrownMessagePart::~ES_ExceptionThrownMessagePart() { } /* virtual */ unsigned ES_ExceptionThrownMessagePart::GetLength() { return 3; } /* virtual */ void ES_ExceptionThrownMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_EXCEPTION_THROWN); return; case 1: GetItemDataValueType(data, length, exception); return; default: GetItemDataValueValue(data, length, exception); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_ExceptionThrownMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_EvalVariableMessagePart::ES_EvalVariableMessagePart() : ES_DebugMessagePart(AUXILIARY_EVAL_VARIABLE), name(NULL), delete_strings(TRUE) { } /* virtual */ ES_EvalVariableMessagePart::~ES_EvalVariableMessagePart() { } /* virtual */ unsigned ES_EvalVariableMessagePart::GetLength() { return 4; } /* virtual */ void ES_EvalVariableMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_EVAL_VARIABLE); return; case 1: data = name; length = name_length; GetItemDataString(data, length); return; case 2: GetItemDataValueType(data, length, value); return; default: GetItemDataValueValue(data, length, value); } #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_EvalVariableMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND delete_strings = FALSE; ES_DebugMessage::ParseStringL(data, size, length, name, name_length); ES_DebugMessage::ParseValueL(data, size, length, value); #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_ChangeBreakpointMessagePart::ES_ChangeBreakpointMessagePart(BOOL add) : ES_DebugMessagePart(add ? BODY_ADD_BREAKPOINT : BODY_REMOVE_BREAKPOINT), add(add) { } /* virtual */ ES_ChangeBreakpointMessagePart::~ES_ChangeBreakpointMessagePart() { } /* virtual */ unsigned ES_ChangeBreakpointMessagePart::GetLength() { if (add) if (bpdata.type == ES_DebugBreakpointData::TYPE_FUNCTION) return 3; else return 4; else return 2; } /* virtual */ void ES_ChangeBreakpointMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, add ? ES_DebugMessage::BODY_ADD_BREAKPOINT : ES_DebugMessage::BODY_REMOVE_BREAKPOINT); return; case 1: GetItemDataUnsigned(data, length, tag); return; } #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_ChangeBreakpointMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND ES_DebugMessage::ParseUnsignedL(data, size, length, id); if (add) { unsigned type; ES_DebugMessage::ParseUnsignedL(data, size, length, type); bpdata.type = (ES_DebugBreakpointData::Type) type; switch (bpdata.type) { case ES_DebugBreakpointData::TYPE_POSITION: ES_DebugMessage::ParseUnsignedL(data, size, length, bpdata.data.position.scriptid); ES_DebugMessage::ParseUnsignedL(data, size, length, bpdata.data.position.linenr); break; case ES_DebugBreakpointData::TYPE_FUNCTION: ES_DebugMessage::ParseUnsignedL(data, size, length, bpdata.data.function.id); break; case ES_DebugBreakpointData::TYPE_EVENT: const char *tmp_namespaceuri; unsigned namespaceuri_length; const char *tmp_eventtype; unsigned eventtype_length; ES_DebugMessage::ParseStringL(data, size, length, tmp_namespaceuri, namespaceuri_length); ES_DebugMessage::ParseStringL(data, size, length, tmp_eventtype, eventtype_length); namespaceuri.SetFromUTF8L(tmp_namespaceuri, namespaceuri_length); eventtype.SetFromUTF8L(tmp_eventtype, eventtype_length); bpdata.data.event.namespace_uri = namespaceuri.CStr(); bpdata.data.event.event_type = eventtype.CStr(); } } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } ES_RuntimeInformationMessagePart::ES_RuntimeInformationMessagePart() : ES_DebugMessagePart(AUXILIARY_RUNTIME_INFORMATION), framepath(NULL), documenturi(NULL), delete_strings(TRUE) { } /* virtual */ ES_RuntimeInformationMessagePart::~ES_RuntimeInformationMessagePart() { if (delete_strings) { FreeItemDataString(framepath, framepath_length); FreeItemDataString(documenturi, documenturi_length); } } /* virtual */ unsigned ES_RuntimeInformationMessagePart::GetLength() { return 5; } /* virtual */ void ES_RuntimeInformationMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_RUNTIME_INFORMATION); return; case 1: GetItemDataUnsigned(data, length, dbg_runtime_id); return; case 2: GetItemDataUnsigned(data, length, dbg_window_id); return; case 3: data = framepath; length = framepath_length; GetItemDataString(data, length); return; case 4: data = documenturi; length = documenturi_length; GetItemDataString(data, length); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_RuntimeInformationMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND delete_strings = FALSE; ParseUnsignedL(data, size, length, windowid); ParseStringL(data, size, length, framepath, framepath_length); ParseStringL(data, size, length, documenturi, documenturi_length); #else // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } ES_HeapStatisticsMessagePart::ES_HeapStatisticsMessagePart() : ES_DebugMessagePart(AUXILIARY_HEAP_STATISTICS) { } /* virtual */ unsigned ES_HeapStatisticsMessagePart::GetLength() { return 13; } /* virtual */ void ES_HeapStatisticsMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::AUXILIARY_HEAP_STATISTICS); return; case 1: GetItemDataDouble(data, length, load_factor); return; default: index -= 2; GetItemDataUnsigned(data, length, unsigneds[index]); } #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } /* virtual */ void ES_HeapStatisticsMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { OP_ASSERT(FALSE); } ES_BreakMessagePart::ES_BreakMessagePart() : ES_DebugMessagePart(BODY_BREAK) { } /* virtual */ unsigned ES_BreakMessagePart::GetLength() { return 3; } /* virtual */ void ES_BreakMessagePart::GetItemData(unsigned index, const char *&data, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_BACKEND switch (index) { case 0: GetItemDataUnsigned(data, length, ES_DebugMessage::TYPE_BREAK); return; case 1: GetItemDataUnsigned(data, length, runtime_id); return; default: GetItemDataUnsigned(data, length, thread_id); return; } #endif // ECMASCRIPT_REMOTE_DEBUGGER_BACKEND } /* virtual */ void ES_BreakMessagePart::ParseL(const char *&data, unsigned &size, unsigned &length) { #ifdef ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND ES_DebugMessage::ParseUnsignedL(data, size, length, runtime_id); ES_DebugMessage::ParseUnsignedL(data, size, length, thread_id); #else // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND OP_ASSERT(FALSE); #endif // ECMASCRIPT_REMOTE_DEBUGGER_FRONTEND } #endif /* ECMASCRIPT_REMOTE_DEBUGGER */
// // AcidAudioBufferSource.cpp // SRXvert // // Created by Dennis Lapchenko on 04/05/2016. // // #include "AcidAudioBufferSource.h" using namespace AcidR; /* This class allows for AudioBuffer playback/real-time resampling using Juce's AudioSource classes. Was initially written for this project to use AudioSource's resampling, however later own resampling solution was written */ AcidAudioBufferSource::AcidAudioBufferSource(AcidAudioBuffer *buffer) : _position(0), _start(0), _repeat(false), _buffer(buffer) {} AcidAudioBufferSource::~AcidAudioBufferSource() { _buffer = NULL; } void AcidAudioBufferSource::getNextAudioBlock(const AudioSourceChannelInfo &info) { int bufferSamples = _buffer->getNumSamples(); int bufferChannels = _buffer->getNumChannels(); if(info.numSamples > 0) { int start = _position; int numToCopy = 0; if(start + info.numSamples <= bufferSamples) { numToCopy = info.numSamples; //copy all samples } else if(start > bufferSamples) { numToCopy = 0; //dont copy } else if(bufferSamples - start > 0) { numToCopy = bufferSamples - start; //copy the remainder in the buffer } else { numToCopy = 0; //dont copy } if(numToCopy > 0) { //loop through channels and copy samples for(int channel = 0; channel < bufferChannels; channel++) { info.buffer->copyFrom(channel, info.startSample, *_buffer, channel, start, numToCopy); } _position += numToCopy; //update source position; } } } void AcidAudioBufferSource::prepareToPlay(int expedtedSamplesPerBlock, double sampleRate) { } void AcidAudioBufferSource::releaseResources() {} void AcidAudioBufferSource::setNextReadPosition(long long newPosition) { if(newPosition >= 0 && newPosition < _buffer->getNumSamples()) { _position = newPosition; } } long long AcidAudioBufferSource::getNextReadPosition() const { return _position; } long long AcidAudioBufferSource::getTotalLength() const { return _buffer->getNumSamples(); } bool AcidAudioBufferSource::isLooping() const { return _repeat; } void AcidAudioBufferSource::setLooping(bool shouldLoop) { _repeat = shouldLoop; } void AcidAudioBufferSource::setBuffer(AcidAudioBuffer *buffer) { _buffer = buffer; setNextReadPosition(0); }
#pragma once #include <iberbar/RHI/Resource.h> #include <iberbar/Utility/Result.h> namespace iberbar { namespace RHI { class IDevice; class IShaderReflection; class __iberbarRHIApi__ IShader : public IResource { public: IShader( EShaderType eShaderType ) : IResource( UResourceType::Shader ) , m_eShaderType( eShaderType ) { } public: virtual CResult Load( const void* pCodes, uint32 nCodeLen ) = 0; virtual CResult LoadFromFile( const char* pstrFile ) = 0; virtual CResult LoadFromSource( const char* pstrSource ) = 0; virtual IShaderReflection* GetReflection() = 0; EShaderType GetShaderType() const { return m_eShaderType; } protected: EShaderType m_eShaderType; }; class __iberbarRHIApi__ IShaderProgram abstract : public IResource { public: IShaderProgram( IShader* pVS, IShader* pPS, IShader* pHS, IShader* pGS, IShader* pDS ); virtual ~IShaderProgram(); IShader* GetShader( EShaderType nShaderType ) { return m_pShaders[ (int)nShaderType ]; } protected: IShader* m_pShaders[ (int)EShaderType::__Count ]; }; //class __iberbarRHIApi__ IVertexShader // : public IShader //{ //public: // IVertexShader() : IShader( EShaderType::VertexShader ) {} //}; //class __iberbarRHIApi__ IPixelShader // : public IShader //{ //public: // IPixelShader() : IShader( EShaderType::PixelShader ) {} //}; //class __iberbarRHIApi__ IHullShader // : public IShader //{ //public: // IHullShader() : IShader( EShaderType::HullShader ) {} //}; //class __iberbarRHIApi__ IGeometryShader // : public IShader //{ //public: // IGeometryShader() : IShader( EShaderType::GeometryShader ) {} //}; //class __iberbarRHIApi__ IDomainShader // : public IShader //{ //public: // IDomainShader() : IShader( EShaderType::DomainShader ) {} //}; //class __iberbarRHIApi__ IComputeShader // : public IShader //{ //public: // IComputeShader() : IShader( EShaderType::ComputeShader ) {} //}; } }
// // Created by HHPP on 2020/5/2. // #ifndef ACM032_POINT_H #define ACM032_POINT_H class Point { friend class Vector; friend class PointStack; private: double x,y; int depth; int index; public: Point(); Point(double, double); void set(double, double); void setDepth(int); void setIndex(int); int getIndex(); int getDepth(); double getX(); double getY(); }; #endif //ACM032_POINT_H
/* * Created by Peng Qixiang on 2018/8/14. */ /* * 左旋转字符串 * 对于一个给定的字符序列S,请你把其循环左移K位后的序列输出。 * 例如,字符序列S=”abcXYZdef”,要求输出循环左移3位后的结果,即“XYZdefabc”。 * */ # include <iostream> # include <string> # include <queue> using namespace std; class Solution { public: string LeftRotateString(string str, int n) { if(str.empty()) return str; queue<char> tmp; for(int i = 0; i < str.size(); i++){ tmp.push(str[i]); } for(int i = 0; i < n; i++){ char cur = tmp.front(); tmp.pop(); tmp.push(cur); } for(int i = 0; i < str.size(); i++){ str[i] = tmp.front(); tmp.pop(); } return str; } //还可以三次翻转 }; int main(){ Solution s = Solution(); string test = "abcdef"; cout << s.LeftRotateString(test, 2) << endl; return 0; }
// // EndingScene.h // BaseGame02 // // Created by P on 2014/07/17. // // #ifndef __BaseGame02__EndingScene__ #define __BaseGame02__EndingScene__ #include "cocos2d.h" // エンディングクラス class EndingScene : public cocos2d::Layer { public: // シーン生成静的関数 //(この関数名がcreateだとCREATE_FUNCで生成される関数名とかぶってエラーになるっぽい) static cocos2d::Scene* createScene(); // レイヤーの初期化処理(cocos2d::Layerクラスの仮想関数オーバーライド) virtual bool init(); // OpeningLayer* OpeningLayer::create() 関数の自動生成(autorelease付きのインスタンスを返す) CREATE_FUNC(EndingScene); private: void transitionToTitleScene(float delta); }; #endif /* defined(__BaseGame02__EndingScene__) */
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <ext/rope> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int c[1111111]; LL gcd(LL x, LL y) { if (y == 0) return x; return gcd(y, x % y); } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int n; scanf("%d", &n); for (int i = 0; i < n; ++i) scanf("%d", &c[i]); sort(c, c + n); LL ans = 0; for (int i = 0; i < n; ++i) { ans += LL(c[i]) * ((i + 1) - (n - i - 1)); ans += LL(c[i]) * (i - (n - i - 1)); } LL g = gcd(ans, n); cout << ans / g << ' ' << n / g << endl; return 0; }
#pragma GCC optimize("Ofast") #include <algorithm> #include <bitset> #include <deque> #include <iostream> #include <iterator> #include <string> #include <map> #include <queue> #include <set> #include <stack> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; void abhisheknaiidu() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif } int main(int argc, char* argv[]) { abhisheknaiidu(); int t; cin >> t; while(t--) { int n, m; cin >> n >> m; vector <int> a; vector <int> b; int i,x; int a_total = 0; int b_total = 0; for(i=0; i<n; i++) { cin >> x; a.push_back(x); a_total += x; } for(i=0; i<m; i++) { cin >> x; b.push_back(x); b_total+=x; } sort(a.begin(), a.end()); sort(b.begin(), b.end(), greater<int>()); int j=0; int ans = 0; if(a_total > b_total) { cout << "0" << endl; continue; } for(int i=0; i<a.size(); i++) { a_total += (b[j] - a[i]); b_total += (a[i] - b[j]); ans++; j++; if(a_total > b_total || j>=b.size()) { break; } } if(a_total > b_total) { cout << ans << endl; } else { cout << "-1" << endl; } } return 0; }
/* * File: Waypoint.h * Author: mohammedheader * * Created on November 24, 2014, 2:22 PM */ #ifndef WAYPOINT_H #define WAYPOINT_H #include "cocos2d.h" class HelloWorld; class Waypoint : public cocos2d::Node{ public: static Waypoint* create(HelloWorld* game, cocos2d::Vec2 location); virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, unsigned int flags); void setNextWayPoint(Waypoint* wayPoint); Waypoint* getNextWayPoint(); cocos2d::Vec2 getMyPosition(); cocos2d::CustomCommand _customCommand; private: Waypoint* init(HelloWorld* game, cocos2d::Vec2 location); void onDrawPrimitives(const cocos2d::Mat4 &transform); HelloWorld* myGame; cocos2d::Vec2 myPosition; Waypoint* nextWayPoint; }; #endif /* WAYPOINT_H */
#pragma once #include "component/component.h" #include "entity/interfaces.h" #include "component/poscomponent.h" namespace component { struct CameraComponentDesc : public ComponentDesc { string transform; }; class CameraComponent : public Component, public ICamera { public: // typedefs typedef CameraComponentDesc desc_type; typedef CameraComponent component_type; // constructor/destructor CameraComponent(entity::Entity* entity, const string& name, const desc_type& desc); ~CameraComponent(); // Component overloads int getType() { return CAMERACOMPONENT; } void acquire(); void release(); // methods // properties ComponentLink<PosComponent> transform; // script class static ScriptedObject::ScriptClass m_scriptClass; protected: // methods // ScriptedObject overrides JSObject* createScriptObject(); void destroyScriptObject(); // members }; }
#include<bits/stdc++.h> using namespace std; int main(){ int e,a = 0,b = 0; vector<vector<int>>v; for (int i = 0; i < 5 ; i++) { vector<int>v1; for (int j = 0; j < 5; j++) { cin>>e; if(e == 1){ a += i; b += j; } v1.push_back(e); } v.push_back(v1); } cout<<abs(2-a) +abs(2-b); return 0; }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef XMRIG_OCLBASERUNNER_H #define XMRIG_OCLBASERUNNER_H #include <string> #include "3rdparty/cl.h" #include "backend/opencl/interfaces/IOclRunner.h" #include "base/crypto/Algorithm.h" namespace xmrig { class OclLaunchData; class OclBaseRunner : public IOclRunner { public: XMRIG_DISABLE_COPY_MOVE_DEFAULT(OclBaseRunner) OclBaseRunner(size_t id, const OclLaunchData &data); ~OclBaseRunner() override; protected: inline cl_context ctx() const override { return m_ctx; } inline const Algorithm &algorithm() const override { return m_algorithm; } inline const char *buildOptions() const override { return m_options.c_str(); } inline const char *deviceKey() const override { return m_deviceKey.c_str(); } inline const char *source() const override { return m_source; } inline const OclLaunchData &data() const override { return m_data; } inline size_t intensity() const override { return m_intensity; } inline size_t threadId() const override { return m_threadId; } inline uint32_t roundSize() const override { return m_intensity; } inline uint32_t processedHashes() const override { return m_intensity; } inline void jobEarlyNotification(const Job&) override {} size_t bufferSize() const override; uint32_t deviceIndex() const override; void build() override; void init() override; protected: cl_mem createSubBuffer(cl_mem_flags flags, size_t size); size_t align(size_t size) const; void enqueueReadBuffer(cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void *ptr); void enqueueWriteBuffer(cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, const void *ptr); void finalize(uint32_t *hashOutput); cl_command_queue m_queue = nullptr; cl_context m_ctx; cl_mem m_buffer = nullptr; cl_mem m_input = nullptr; cl_mem m_output = nullptr; cl_program m_program = nullptr; const Algorithm m_algorithm; const char *m_source; const OclLaunchData &m_data; const size_t m_align; const size_t m_threadId; const uint32_t m_intensity; size_t m_offset = 0; std::string m_deviceKey; std::string m_options; }; } /* namespace xmrig */ #endif // XMRIG_OCLBASERUNNER_H
//知识点:搜索 /* By:Luckyblock 题目中 , 棋子可以向空格子移动 那么可以进行转换 , 将棋子移动,变为空格子移动. 使用记忆化dfs , 记录 [空格子坐标],[目标棋子坐标] 状态 所需要的最小步数 使用dfs进行更新, 当目标棋子坐标 = 目标位置坐标时,记录最小答案即可. 可以拿到45分的好成绩(大雾 */ #include<cstdio> #include<cstring> #include<ctype.h> #define min(a,b) a<b?a:b const int INF = 1e9+7; const int cx[5] = {114514, 0,0,1,-1}; //change_x , change_y const int cy[5] = {114514, 1,-1,0,0}; //============================================================= int n,m,q , ans, ex,ey,sx,sy,tx,ty; bool map[31][31];//棋盘 int step[31][31][31][31];//记忆化, 记录 [空格子坐标],[目标棋子坐标] 状态 所需要的最小步数 //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } void dfs(int wx,int wy,int nx,int ny,int sum) //white_x,white_y and now_x,now_y { if(sum > step[wx][wy][nx][ny]) return ;//非较优解 step[wx][wy][nx][ny]=min(sum,step[wx][wy][nx][ny]);//更新 if(nx==tx && ny==ty)//到达目标位置 { ans = min(ans,sum); return ; } for(int i=1;i<=4;i++)//移动空格子 { int nwx=wx+cx[i] , nwy=wy+cy[i]; //new_white_x,new_white_y if(nwx<1 || nwx>n || nwy<1 || nwy>m || map[nwx][nwy]==0) continue;//越界 if(nwx==nx && nwy==ny) dfs(nwx,nwy,wx,wy,sum+1);//空格子与目标棋子交换位置 else dfs(nwx,nwy,nx,ny,sum+1);//空格子不与目标棋子交换位置 } } //============================================================= signed main() { n=read(),m=read(),q=read(); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) map[i][j]= read(); while(q--) { ans=INF; memset(step,INF,sizeof(step));//初始化 ex=read(),ey=read(),sx=read(),sy=read(),tx=read(),ty=read(); dfs(ex,ey,sx,sy,0);//搜索 printf("%d\n",ans==INF?-1:ans); } }
/** * created: 2013-4-8 15:40 * filename: FKThread * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #include <process.h> #include <wchar.h> #include "../Include/FKThread.h" #include "../Include/STLTemplate/FKFrameAllocator.h" #include "../Include/FKError.h" #include "../Include/Dump/FKDumpErrorBase.h" #include "../Include/STLTemplate/FKSyncList.h" #include <Ole2.h> //------------------------------------------------------------------------ CLD_ThreadBase* CLD_ThreadBase::getThreadObj() { FUNCTION_BEGIN; if (_TH_VAR_GET(tls_CurrThreadObj).pCurrThreadObj!=NULL && _TH_VAR_GET(tls_CurrThreadObj).PID==::GetCurrentProcessId() && _TH_VAR_GET(tls_CurrThreadObj).ThreadId==CLD_ThreadBase::getcurid()) { return _TH_VAR_GET(tls_CurrThreadObj).pCurrThreadObj; } return NULL; } //------------------------------------------------------------------------ bool CLD_ThreadBase::Start(bool boCreateSuspended) { FUNCTION_BEGIN; if (m_hThread){ if (m_boSuspended && !boCreateSuspended) { Resume(); } }else{ m_ThreadId=0; m_hThread=NULL; m_Terminated=false; m_nDestroyTimeOut=INFINITE; m_dwExitCode=0; m_boSuspended=false; if(boCreateSuspended){ m_hThread=smBeginThread(NULL,0,ThreadProxy, this ,CREATE_SUSPENDED,&m_ThreadId); }else{ m_hThread=smBeginThread(NULL,0,ThreadProxy, this ,0,&m_ThreadId); } if (m_hThread){ m_nPriority=GetThreadPriority(m_hThread); m_boSuspended=boCreateSuspended; }else{ m_ThreadId=0; m_hThread=NULL; throw CLDError("CLD_ThreadBase Create Error!!",GetLastError(),true); } } return m_hThread?true:false; } //------------------------------------------------------------------------ CLD_ThreadBase::CLD_ThreadBase(bool boCreateSuspended,bool boDelThisOnTerminate) { FUNCTION_BEGIN; m_ThreadId=0; m_hThread=NULL; m_Terminated=false; m_nDestroyTimeOut=INFINITE; m_boSuspended=false; m_dwExitCode=0; m_nPriority=0; m_boDelThisOnTerminate=boDelThisOnTerminate; if (!boCreateSuspended){Start(false);} } //------------------------------------------------------------------------ CLD_ThreadBase::~CLD_ThreadBase() { FUNCTION_BEGIN; DWORD dwExitCode; if (m_hThread && Destroy(_dtWAIT,dwExitCode,m_nDestroyTimeOut)!=0) { Destroy(_dtTERMINATE,dwExitCode,INFINITE); } } //------------------------------------------------------------------------ unsigned int CLD_ThreadBase::ThreadProxy( void *pvParam ) { unsigned int nRet=0; try { _TH_VAR_GET(tls_CurrThreadObj).pCurrThreadObj=NULL; _TH_VAR_GET(tls_CurrThreadObj).ThreadId=0; _TH_VAR_GET(tls_CurrThreadObj).PID=0; CLD_ThreadBase *ThreadObj=(CLD_ThreadBase*)pvParam; if (ThreadObj){ OleInitialize(NULL); _TH_VAR_GET(tls_CurrThreadObj).pCurrThreadObj=ThreadObj; _TH_VAR_GET(tls_CurrThreadObj).ThreadId=CLD_ThreadBase::getcurid(); _TH_VAR_GET(tls_CurrThreadObj).PID=::GetCurrentProcessId(); ThreadObj->m_dwExitCode=0; nRet= (unsigned int)ThreadObj->runthread(); ThreadObj->m_dwExitCode=nRet; ThreadObj->OnTerminate(); ThreadObj->m_ThreadId=0; ThreadObj->m_hThread=NULL; ThreadObj->m_Terminated=false; ThreadObj->m_boSuspended=false; _TH_VAR_GET(tls_CurrThreadObj).pCurrThreadObj=NULL; _TH_VAR_GET(tls_CurrThreadObj).ThreadId=0; _TH_VAR_GET(tls_CurrThreadObj).PID=0; if (ThreadObj->m_boDelThisOnTerminate){SAFE_DELETE(ThreadObj); } OleUninitialize(); } }catch (std::exception& e){ g_logger.error("[ %s : PID=%d : TID=%d ] exception: %s \r\nCallStack:--------------------------------------------------\r\n", __FUNC_LINE__,::GetCurrentProcessId(),CLD_ThreadBase::getcurid(),e.what()); PrintThreadCallStack(NULL); g_logger.error("======================================\r\n\r\n"); } _TH_VAR_FREE; return nRet; } //------------------------------------------------------------------------ bool CLD_ThreadBase::Suspend() { FUNCTION_BEGIN; if (!m_boSuspended && m_hThread){ (SuspendThread(m_hThread)==1); m_boSuspended=true; } return m_boSuspended; } //------------------------------------------------------------------------ bool CLD_ThreadBase::Resume() { FUNCTION_BEGIN; if (m_boSuspended && m_hThread){ (ResumeThread(m_hThread)!=1); m_boSuspended=false; } return (!m_boSuspended); } //------------------------------------------------------------------------ void CLD_ThreadBase::Terminate() { m_Terminated=true; } //----------------------------------------------------------------------- bool CLD_ThreadBase::IsTerminated() { return m_Terminated; } //------------------------------------------------------------------------ HANDLE CLD_ThreadBase::GetHandle() { return m_hThread; } //------------------------------------------------------------------------ DWORD CLD_ThreadBase::GetId() { return m_ThreadId; } //------------------------------------------------------------------------ bool CLD_ThreadBase::getruntime() { FILETIME lpCreationTime; FILETIME lpExitTime; FILETIME lpKernelTime; FILETIME lpUserTime; ::GetThreadTimes(GetHandle(),&lpCreationTime,&lpExitTime,&lpKernelTime,&lpUserTime); m_i64Kerneltime=( QWORD) lpKernelTime.dwHighDateTime<<32 | lpKernelTime.dwLowDateTime; m_i64Usertime=( QWORD) lpUserTime.dwHighDateTime<<32 | lpUserTime.dwLowDateTime; return true; } //------------------------------------------------------------------------ DWORD CLD_ThreadBase::GetExitCode() { return m_dwExitCode; } //------------------------------------------------------------------------ bool CLD_ThreadBase::SetPriority(int pri) { FUNCTION_BEGIN; if (!m_hThread){ return false; } bool boRet=false; if (m_nPriority!=pri){ boRet=(SetThreadPriority(m_hThread,pri)!=0); if (boRet){ m_nPriority=pri; } }else{ boRet=true; } return boRet; } //------------------------------------------------------------------------ bool CLD_ThreadBase::IsRunning(void) { FUNCTION_BEGIN; DWORD status; if(m_boSuspended || !m_hThread){ return false; } if (GetExitCodeThread(m_hThread,&status)==0){ return false; } if (status == STILL_ACTIVE){ return true; } return false; } //------------------------------------------------------------------------ int CLD_ThreadBase::Waitfor(DWORD const dwWaitTimes) { FUNCTION_BEGIN; DWORD dwExitCode=0; return Destroy(_dtWAIT,dwExitCode,dwWaitTimes); } //------------------------------------------------------------------------ int CLD_ThreadBase::TerminateForce(DWORD dwExitCode) { FUNCTION_BEGIN; DWORD tempdwExitCode=dwExitCode; return Destroy(_dtTERMINATE,tempdwExitCode); } //------------------------------------------------------------------------ int CLD_ThreadBase::Destroy(_DESTROY_TYPE dt,DWORD & dwExitCode, DWORD const dwWaitTimes ) { FUNCTION_BEGIN; int iRet; if (!m_hThread){ m_ThreadId=0; return -1; } switch(dt) { case _dtTRY: if (GetExitCodeThread(m_hThread,&dwExitCode)==0){ return -2; } if (dwExitCode==STILL_ACTIVE){ return 1; } if (m_hThread){ m_dwExitCode=dwExitCode; m_boSuspended=false; CloseHandle(m_hThread); m_ThreadId=0; m_hThread=NULL; m_Terminated=false; m_boSuspended=false; } break; case _dtWAIT: Terminate(); Resume(); Sleep(1); iRet=WaitForSingleObject(m_hThread,dwWaitTimes); if (iRet==WAIT_TIMEOUT){ dwExitCode=STILL_ACTIVE; return 1; } if (iRet==WAIT_OBJECT_0){ GetExitCodeThread(m_hThread,&dwExitCode); if (m_hThread){ m_dwExitCode=dwExitCode; m_boSuspended=false; CloseHandle(m_hThread); m_ThreadId=0; m_hThread=NULL; m_Terminated=false; m_boSuspended=false; } } break; case _dtTERMINATE: if (::GetExitCodeThread(m_hThread,&dwExitCode)==0){ return -2; } if (dwExitCode==STILL_ACTIVE){ Terminate(); Resume(); Sleep(1); TerminateThread(m_hThread,dwExitCode); WaitForSingleObject(m_hThread, INFINITE); if (m_hThread){ m_dwExitCode=dwExitCode; m_boSuspended=false; CloseHandle(m_hThread); m_ThreadId=0; m_hThread=NULL; m_Terminated=false; m_boSuspended=false; } } break; } return 0; } //------------------------------------------------------------------------
#include <iostream> #include "AccountArray.h" using namespace std; AccountArray::AccountArray(int len) :arrlen(len) { arr = new ACCOUNT_PTR[len]; } ACCOUNT_PTR& AccountArray::operator[](int idx) { if (idx < 0 || arrlen <= idx) { cout << "Array index out of bound exception" << endl; exit(1); } return arr[idx]; } ACCOUNT_PTR AccountArray::operator[](int idx) const { if (idx < 0 || arrlen <= idx) { cout << "Array index out of bound exception" << endl; exit(1); } return arr[idx]; }
#ifndef CSVPARSER_H #define CSVPARSER_H #include <iostream> #include <sstream> #include <string> #include <fstream> using namespace std; using Column = pair<string,vector<string>>; class CsvParser { // Class used to read csv files and store column information std::pairs (pair having string for column name and vector of strings for values) public: CsvParser(string file_name); vector<string> GetColumn(int col); private: string CsvName; vector<Column> Columns; }; #endif
#ifndef _CHUNK_TERRAIN_H_ #define _CHUNK_TERRAIN_H_ #include <vector> #include <memory> #include <d3d11.h> #include "Chunk.h" #include "../Engine/Shader.h" #include "../Engine/Texture.h" #include "../Engine/Shape.h" #include "../Engine/Camera.h" #pragma once class ChunkTerrain { public: ChunkTerrain(); ~ChunkTerrain(); void Initialize(std::shared_ptr<Graphics> graphics); bool Render(std::shared_ptr<Shader>Shader, std::shared_ptr<Camera> camera); private: std::vector<std::shared_ptr<Chunk>> m_Chunks; }; #endif
#ifndef __INCLUDE_TS_FILE_READER_H__ #define __INCLUDE_TS_FILE_READER_H__ #include "Def.h" #include <stdio.h> #include "TsParser.h" class CTsFileReader { public: CTsFileReader(); ~CTsFileReader(); public: int Init( const char* filename ); int GetFileRange(); bool SeekByTime( uint64_t sec ); int GetTsPkt( char* buf, int len, uint64_t& pcr ); private: int init_file(); private: FILE* m_file; char m_data_buf[TS_PKT_LEN]; uint64_t m_file_size; uint64_t m_cur_pcr; uint64_t m_first_pcr; uint64_t m_last_pcr; }; #endif
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); double x,y,r; while( kase-- ){ scanf("%lf %lf %lf", &x, &y, &r); double dis = sqrt(x*x + y*y); printf("%.2lf %.2lf\n", r-dis, r+dis); } return 0; }
#ifndef CABAL_TOKEN_H #define CABAL_TOKEN_H #include <string> #include <utility> class Token { private: std::string type; std::string val; public: Token() = default; Token(std::string type, std::string val); ~Token() = default; const std::string &getType() const; void setType(const std::string &type); const std::string &getVal() const; void setVal(const std::string &val); enum { IDENTIFIER, INTEGER, DOUBLE, INVALID_NUMBER, PLUS, MINUS, MUL, DIV, MOD, NEGATE, EQUALS, LEFT_PAREN, RIGHT_PAREN, SEMI_COLON, UNKNOWN_TOKEN }; enum keywords { EOF_, EOL_, CARRIAGE_RET_, NEWLINE_, PRINT_, DEF_ }; }; #endif //CABAL_TOKEN_H
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; #define N 111111 int n, a[N], g[N], ba[N], ans, dsum[N], ddif[N]; int kx[8] = {2, 2, 1, -1, -2, -2, -1, 1}, ky[8] = {-1, 1, 2, 2, 1, -1, -2, -2}; double get_rand(){ return ((rand() * 1ll * rand() * rand()) % 1000000001) / 1000000000.0; } void get_next(int k) { int p[N], r[N]; for (int i = 0; i < n; ++i) p[i] = r[i] = i; for (int i = 0; i < k; ++i) swap(p[i], p[n - 1 - rand() % (n - i)]); for (int i = k - 1; i > 0; --i) swap(r[i], r[rand() % (i + 1)]); for (int i = 0; i < n; ++i) g[i] = a[i]; for (int i = 0; i < k; ++i) g[p[i]] = a[p[r[i]]]; } int eval(){ int res = 0; memset(dsum, 0, sizeof(dsum)); memset(ddif, 0, sizeof(ddif)); for (int i = 0; i < n; ++i) { res += dsum[i + g[i]]; ++dsum[i + g[i]]; res += ddif[i - g[i] + n]; ++ddif[i - g[i] + n]; for (int j = 0; j < 4; ++j) { if (i + kx[j] >= 0 && i + kx[j] < n && g[i + kx[j]] == g[i] + ky[j]) { ++res; } } } return res; } double prob(int cur, int nw, double t){ int delta = nw - cur; if (delta < 0) return 1.0; else return exp(-delta / t); } int main(){ int f1 = 1, f2 = 1, f0; for (int i = 0; i < 100000000; ++i) { f0 = (f1 + f2) % 1000000007; f2 = f1; f1 = f0; } srand(time(0) + clock()); // scanf("%d",&n); n = 10000; int cure; for (int i = 0; i < n; ++i) g[i]=i; random_shuffle(g, g + n); for (int i = 0; i < n; ++i) a[i] = ba[i] = g[i]; cure = ans = eval(); double mxt = 100.0; for (double t = mxt; ans; t*=0.999999999999){ int k = max(2, (int)(t / mxt * n)); get_next(k); int ne = eval(); if (prob(cure, ne, t) >= get_rand()){ cure = ne; for (int i = 0; i < n; ++i) a[i] = g[i]; } if (cure < ans){ ans = cure; for (int i = 0; i < n; ++i) ba[i] = a[i]; } } cout << f1 << "\t" << f2 << "\t"; for (int i = 0; i < n; ++i) printf("%d ", ba[i] + 1); return 0; }
/* * Copyright (c) 2015-2021 Morwenn * SPDX-License-Identifier: MIT */ #ifndef CPPSORT_DETAIL_SORTING_NETWORK_SORT25_H_ #define CPPSORT_DETAIL_SORTING_NETWORK_SORT25_H_ namespace cppsort { namespace detail { template<> struct sorting_network_sorter_impl<25u> { template< typename RandomAccessIterator, typename Compare = std::less<>, typename Projection = utility::identity, typename = std::enable_if_t<is_projection_iterator_v< Projection, RandomAccessIterator, Compare >> > auto operator()(RandomAccessIterator first, RandomAccessIterator, Compare compare={}, Projection projection={}) const -> void { iter_swap_if(first, first + 2u, compare, projection); iter_swap_if(first + 1u, first + 8u, compare, projection); iter_swap_if(first + 3u, first + 18u, compare, projection); iter_swap_if(first + 4u, first + 17u, compare, projection); iter_swap_if(first + 5u, first + 20u, compare, projection); iter_swap_if(first + 6u, first + 19u, compare, projection); iter_swap_if(first + 7u, first + 9u, compare, projection); iter_swap_if(first + 10u, first + 11u, compare, projection); iter_swap_if(first + 12u, first + 13u, compare, projection); iter_swap_if(first + 14u, first + 16u, compare, projection); iter_swap_if(first + 15u, first + 22u, compare, projection); iter_swap_if(first + 21u, first + 23u, compare, projection); iter_swap_if(first, first + 3u, compare, projection); iter_swap_if(first + 1u, first + 15u, compare, projection); iter_swap_if(first + 2u, first + 18u, compare, projection); iter_swap_if(first + 4u, first + 12u, compare, projection); iter_swap_if(first + 5u, first + 21u, compare, projection); iter_swap_if(first + 6u, first + 10u, compare, projection); iter_swap_if(first + 7u, first + 14u, compare, projection); iter_swap_if(first + 8u, first + 22u, compare, projection); iter_swap_if(first + 9u, first + 16u, compare, projection); iter_swap_if(first + 11u, first + 19u, compare, projection); iter_swap_if(first + 13u, first + 17u, compare, projection); iter_swap_if(first + 20u, first + 23u, compare, projection); iter_swap_if(first, first + 4u, compare, projection); iter_swap_if(first + 1u, first + 7u, compare, projection); iter_swap_if(first + 2u, first + 13u, compare, projection); iter_swap_if(first + 3u, first + 12u, compare, projection); iter_swap_if(first + 5u, first + 6u, compare, projection); iter_swap_if(first + 8u, first + 14u, compare, projection); iter_swap_if(first + 9u, first + 15u, compare, projection); iter_swap_if(first + 10u, first + 21u, compare, projection); iter_swap_if(first + 11u, first + 20u, compare, projection); iter_swap_if(first + 16u, first + 22u, compare, projection); iter_swap_if(first + 17u, first + 18u, compare, projection); iter_swap_if(first + 19u, first + 23u, compare, projection); iter_swap_if(first, first + 5u, compare, projection); iter_swap_if(first + 2u, first + 11u, compare, projection); iter_swap_if(first + 3u, first + 6u, compare, projection); iter_swap_if(first + 4u, first + 10u, compare, projection); iter_swap_if(first + 7u, first + 16u, compare, projection); iter_swap_if(first + 8u, first + 9u, compare, projection); iter_swap_if(first + 12u, first + 21u, compare, projection); iter_swap_if(first + 13u, first + 19u, compare, projection); iter_swap_if(first + 14u, first + 15u, compare, projection); iter_swap_if(first + 17u, first + 20u, compare, projection); iter_swap_if(first + 18u, first + 23u, compare, projection); iter_swap_if(first + 2u, first + 7u, compare, projection); iter_swap_if(first + 6u, first + 9u, compare, projection); iter_swap_if(first + 8u, first + 11u, compare, projection); iter_swap_if(first + 14u, first + 24u, compare, projection); iter_swap_if(first + 18u, first + 21u, compare, projection); iter_swap_if(first + 3u, first + 8u, compare, projection); iter_swap_if(first + 7u, first + 10u, compare, projection); iter_swap_if(first + 11u, first + 12u, compare, projection); iter_swap_if(first + 13u, first + 14u, compare, projection); iter_swap_if(first + 15u, first + 21u, compare, projection); iter_swap_if(first + 18u, first + 20u, compare, projection); iter_swap_if(first + 22u, first + 24u, compare, projection); iter_swap_if(first + 4u, first + 13u, compare, projection); iter_swap_if(first + 10u, first + 16u, compare, projection); iter_swap_if(first + 11u, first + 15u, compare, projection); iter_swap_if(first + 18u, first + 24u, compare, projection); iter_swap_if(first + 19u, first + 22u, compare, projection); iter_swap_if(first + 1u, first + 4u, compare, projection); iter_swap_if(first + 8u, first + 11u, compare, projection); iter_swap_if(first + 9u, first + 19u, compare, projection); iter_swap_if(first + 13u, first + 17u, compare, projection); iter_swap_if(first + 14u, first + 18u, compare, projection); iter_swap_if(first + 16u, first + 20u, compare, projection); iter_swap_if(first + 23u, first + 24u, compare, projection); iter_swap_if(first, first + 1u, compare, projection); iter_swap_if(first + 4u, first + 5u, compare, projection); iter_swap_if(first + 6u, first + 13u, compare, projection); iter_swap_if(first + 9u, first + 14u, compare, projection); iter_swap_if(first + 10u, first + 17u, compare, projection); iter_swap_if(first + 12u, first + 16u, compare, projection); iter_swap_if(first + 18u, first + 19u, compare, projection); iter_swap_if(first + 20u, first + 21u, compare, projection); iter_swap_if(first + 22u, first + 23u, compare, projection); iter_swap_if(first + 2u, first + 6u, compare, projection); iter_swap_if(first + 3u, first + 4u, compare, projection); iter_swap_if(first + 5u, first + 13u, compare, projection); iter_swap_if(first + 7u, first + 9u, compare, projection); iter_swap_if(first + 12u, first + 18u, compare, projection); iter_swap_if(first + 15u, first + 17u, compare, projection); iter_swap_if(first + 16u, first + 19u, compare, projection); iter_swap_if(first + 20u, first + 22u, compare, projection); iter_swap_if(first + 21u, first + 23u, compare, projection); iter_swap_if(first + 1u, first + 2u, compare, projection); iter_swap_if(first + 5u, first + 8u, compare, projection); iter_swap_if(first + 6u, first + 7u, compare, projection); iter_swap_if(first + 9u, first + 10u, compare, projection); iter_swap_if(first + 11u, first + 13u, compare, projection); iter_swap_if(first + 14u, first + 15u, compare, projection); iter_swap_if(first + 17u, first + 20u, compare, projection); iter_swap_if(first + 21u, first + 22u, compare, projection); iter_swap_if(first + 1u, first + 3u, compare, projection); iter_swap_if(first + 2u, first + 4u, compare, projection); iter_swap_if(first + 5u, first + 6u, compare, projection); iter_swap_if(first + 7u, first + 11u, compare, projection); iter_swap_if(first + 8u, first + 9u, compare, projection); iter_swap_if(first + 10u, first + 13u, compare, projection); iter_swap_if(first + 12u, first + 14u, compare, projection); iter_swap_if(first + 15u, first + 16u, compare, projection); iter_swap_if(first + 17u, first + 18u, compare, projection); iter_swap_if(first + 19u, first + 20u, compare, projection); iter_swap_if(first + 2u, first + 3u, compare, projection); iter_swap_if(first + 4u, first + 8u, compare, projection); iter_swap_if(first + 6u, first + 7u, compare, projection); iter_swap_if(first + 9u, first + 12u, compare, projection); iter_swap_if(first + 10u, first + 11u, compare, projection); iter_swap_if(first + 13u, first + 14u, compare, projection); iter_swap_if(first + 15u, first + 17u, compare, projection); iter_swap_if(first + 16u, first + 18u, compare, projection); iter_swap_if(first + 20u, first + 21u, compare, projection); iter_swap_if(first + 3u, first + 5u, compare, projection); iter_swap_if(first + 4u, first + 6u, compare, projection); iter_swap_if(first + 7u, first + 8u, compare, projection); iter_swap_if(first + 9u, first + 10u, compare, projection); iter_swap_if(first + 11u, first + 12u, compare, projection); iter_swap_if(first + 13u, first + 15u, compare, projection); iter_swap_if(first + 14u, first + 17u, compare, projection); iter_swap_if(first + 16u, first + 19u, compare, projection); iter_swap_if(first + 4u, first + 5u, compare, projection); iter_swap_if(first + 6u, first + 7u, compare, projection); iter_swap_if(first + 8u, first + 9u, compare, projection); iter_swap_if(first + 10u, first + 11u, compare, projection); iter_swap_if(first + 12u, first + 13u, compare, projection); iter_swap_if(first + 14u, first + 15u, compare, projection); iter_swap_if(first + 16u, first + 17u, compare, projection); iter_swap_if(first + 18u, first + 19u, compare, projection); } template<typename DifferenceType=std::ptrdiff_t> static constexpr auto index_pairs() -> std::array<utility::index_pair<DifferenceType>, 132> { return {{ {0, 2}, {1, 8}, {3, 18}, {4, 17}, {5, 20}, {6, 19}, {7, 9}, {10, 11}, {12, 13}, {14, 16}, {15, 22}, {21, 23}, {0, 3}, {1, 15}, {2, 18}, {4, 12}, {5, 21}, {6, 10}, {7, 14}, {8, 22}, {9, 16}, {11, 19}, {13, 17}, {20, 23}, {0, 4}, {1, 7}, {2, 13}, {3, 12}, {5, 6}, {8, 14}, {9, 15}, {10, 21}, {11, 20}, {16, 22}, {17, 18}, {19, 23}, {0, 5}, {2, 11}, {3, 6}, {4, 10}, {7, 16}, {8, 9}, {12, 21}, {13, 19}, {14, 15}, {17, 20}, {18, 23}, {2, 7}, {6, 9}, {8, 11}, {14, 24}, {18, 21}, {3, 8}, {7, 10}, {11, 12}, {13, 14}, {15, 21}, {18, 20}, {22, 24}, {4, 13}, {10, 16}, {11, 15}, {18, 24}, {19, 22}, {1, 4}, {8, 11}, {9, 19}, {13, 17}, {14, 18}, {16, 20}, {23, 24}, {0, 1}, {4, 5}, {6, 13}, {9, 14}, {10, 17}, {12, 16}, {18, 19}, {20, 21}, {22, 23}, {2, 6}, {3, 4}, {5, 13}, {7, 9}, {12, 18}, {15, 17}, {16, 19}, {20, 22}, {21, 23}, {1, 2}, {5, 8}, {6, 7}, {9, 10}, {11, 13}, {14, 15}, {17, 20}, {21, 22}, {1, 3}, {2, 4}, {5, 6}, {7, 11}, {8, 9}, {10, 13}, {12, 14}, {15, 16}, {17, 18}, {19, 20}, {2, 3}, {4, 8}, {6, 7}, {9, 12}, {10, 11}, {13, 14}, {15, 17}, {16, 18}, {20, 21}, {3, 5}, {4, 6}, {7, 8}, {9, 10}, {11, 12}, {13, 15}, {14, 17}, {16, 19}, {4, 5}, {6, 7}, {8, 9}, {10, 11}, {12, 13}, {14, 15}, {16, 17}, {18, 19}, }}; } }; }} #endif // CPPSORT_DETAIL_SORTING_NETWORK_SORT25_H_
// Created on: 1999-11-26 // Created by: Andrey BETENEV // Copyright (c) 1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StepBasic_Contract_HeaderFile #define _StepBasic_Contract_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Transient.hxx> class TCollection_HAsciiString; class StepBasic_ContractType; class StepBasic_Contract; DEFINE_STANDARD_HANDLE(StepBasic_Contract, Standard_Transient) //! Representation of STEP entity Contract class StepBasic_Contract : public Standard_Transient { public: //! Empty constructor Standard_EXPORT StepBasic_Contract(); //! Initialize all fields (own and inherited) Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(TCollection_HAsciiString)& aPurpose, const Handle(StepBasic_ContractType)& aKind); //! Returns field Name Standard_EXPORT Handle(TCollection_HAsciiString) Name() const; //! Set field Name Standard_EXPORT void SetName (const Handle(TCollection_HAsciiString)& Name); //! Returns field Purpose Standard_EXPORT Handle(TCollection_HAsciiString) Purpose() const; //! Set field Purpose Standard_EXPORT void SetPurpose (const Handle(TCollection_HAsciiString)& Purpose); //! Returns field Kind Standard_EXPORT Handle(StepBasic_ContractType) Kind() const; //! Set field Kind Standard_EXPORT void SetKind (const Handle(StepBasic_ContractType)& Kind); DEFINE_STANDARD_RTTIEXT(StepBasic_Contract,Standard_Transient) protected: private: Handle(TCollection_HAsciiString) theName; Handle(TCollection_HAsciiString) thePurpose; Handle(StepBasic_ContractType) theKind; }; #endif // _StepBasic_Contract_HeaderFile
#include "platforms/quix/toolkits/gtk2/GtkToolkitUiSettings.cpp"
#include "common/protobuf/utility.h" #include "include/sqlparser/SQLParser.h" namespace Envoy { namespace Extensions { namespace Common { namespace SQLUtils { class SQLUtils { public: /** * Method parses SQL query string and writes output to metadata. * @param query supplies SQL statement. * @param metadata supplies placeholder where metadata should be written. * @return True if parsing was successful and False if parsing failed. * If True was returned the metadata contains result of parsing. The results are * stored in metadata.mutable_fields. **/ static bool setMetadata(const std::string& query, ProtobufWkt::Struct& metadata); }; } // namespace SQLUtils } // namespace Common } // namespace Extensions } // namespace Envoy
#pragma once #ifndef Component_H #define Component_H #include <memory> #include <SDL2/SDL.h> #include <GL/glew.h> #include <exception> class Object; class Input; class World; class Core; class Screen; class GUI; //! The Component class to add features to an Object /*! Components are to add a feature or components to Objects. To make your own Component to add to an Object please make your class and then make it a child of Component. Example #Include <GEPEngine/GEPEngine.h> Class Exapmle : Public Component { } */ class Component { public: //! Use as a shortcut to access the Input /*! Use this function to access the Input class and it's functions */ std::shared_ptr<Input> GetInput(); //! Use as a shortcut to access the GUI /*! Use this function to access the GUI class and it's functions */ std::shared_ptr<GUI> GetGUI(); //! Use as a shortcut to access the Object /*! Use this function to access the Object that holds the componenet */ std::shared_ptr<Object> GetObject(); //! Use as a shortcut to access the World /*! Use this function to access the World class and it's functions */ std::shared_ptr<World> GetWorld(); //! Use as a shortcut to access the Screen /*! Use this function to access the Screen class and it's functions */ std::shared_ptr<Screen> GetScreen(); //! Use as a shortcut to access Core /*! Use this function to access the Core class and it's functions */ std::shared_ptr<Core> GetCore(); void SetIsActive(bool _value) { isActive = _value; } protected: friend class Object; //! This is a vertual function to Initalise the component /*! Use this function to run any lines of code once when the compenent is created and added to the Object. */ virtual void OnInit() {}; //! This is a vertual function to Initalise the component /*! Use this function to run any lines of code once at the very start of the project. */ virtual void OnStart() {}; //! This is a vertual function to Initalise the component /*! Use this function to run any lines of code every frame of the game. */ virtual void OnUpdate() {}; //! This is a vertual function to Initalise the component /*! Use this function to run lines of code every frame after the update is called. This is use for rendering 3D models and meshes. */ virtual void OnDisplay() {}; //! This is a vertual function to Initalise the component /*! Use this function to run lines of code at the end of the every Frame. Use this for rendering your UI, like buttons and Images. */ virtual void OnGUI() {}; std::weak_ptr<Object> object;//! This is referience to the Object that holds this Component bool isActive = true;//! This is for the comenent to run in that frame }; #endif // Component_H
#define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #ifdef _DEBUG #ifndef DBG_NEW #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ , __LINE__ ) #define new DBG_NEW #endif #endif // _DEBUG #include "Core.h" #include "ModuleRegistry.h" using namespace ServerEngine; void main() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); SETUP_MODULES(); NetModule& Module = ModuleManager::GetModuleChecked<NetModule>(); SHUTDOWN_MODULES(); system("pause"); }
/* * ===================================================================================== * * Filename: test.cpp * * Description: * * Version: 1.0 * Created: 01/22/2014 19:06:46 * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include<iostream> using namespace std; class Test{ public: void foo1(const char*a){ cout << "hello"; } }; class Test2 : public Test{ public: void foo1(const char* a){ //remove the constant and it will be throw error cout << "bye"; } }; int main(void){ Test2 t; char *a = "bkjwbkfwfwf"; t.foo1(a); }