text
stringlengths
8
6.88M
#pragma once #include "..\Common\Pch.h" #include "..\Graphic\Direct3D.h" #include "..\System\DirectInput.h" class Camera { public: Camera(); ~Camera(); void Initialize(); void Update(FLOAT delta); void UpdateReflection(FLOAT height); void SetBuffer(); // Get, Set 함수 D3DXVECTOR3 GetPosition(); FLOAT GetPitch(); FLOAT GetYaw(); FLOAT GetRoll(); void SetPosition(FLOAT x, FLOAT y, FLOAT z); void SetPitch(FLOAT angle); void SetYaw(FLOAT angle); void SetRoll(FLOAT angle); FLOAT GetWalkSpeed(); FLOAT GetStrafeSpeed(); FLOAT GetJumpSpeed(); void SetWalkSpeed(FLOAT speed); void SetStrafeSpeed(FLOAT speed); void SetJumpSpeed(FLOAT speed); D3DXMATRIX GetView(); D3DXMATRIX GetProjection(); D3DXMATRIX GetOrtho(); D3DXMATRIX GetReflection(); private: struct BufferData { D3DXMATRIX View; D3DXMATRIX Projection; D3DXMATRIX Ortho; D3DXMATRIX Reflection; D3DXVECTOR3 CameraPosition; FLOAT Pad; }; D3DXVECTOR3 mPosition; FLOAT mPitch; // x축 회전 FLOAT mYaw; // y축 회전 FLOAT mRoll; // z축 회전 FLOAT mWalkSpeed; FLOAT mStrafeSpeed; FLOAT mJumpSpeed; D3DXMATRIX mView; D3DXMATRIX mProjection; D3DXMATRIX mOrtho; D3DXMATRIX mReflection; D3DXMATRIX mFrustumProj; // Frustum을 위한 좀더 짧은 Depth의 Projection ID3D11Buffer* mBuffer; };
#include <EventsStorage.h> #include <cassert> using namespace breakout; EventsStorage::EventsStorage() { } EventsStorage::~EventsStorage() { } EventsStorage& EventsStorage::Get() { static EventsStorage eventStorage; return eventStorage; } void EventsStorage::Init() { } void EventsStorage::Put(BaseEvent& event) { EEventType eventType = event.GetType(); if (IsContain(eventType)) { m_storage[!m_active_storage_index][eventType].emplace_back(event); } else { m_storage[!m_active_storage_index][eventType] = std::move(std::vector<BaseEvent>({ event })); } } std::vector<BaseEvent>& EventsStorage::GetAll(EEventType eventTypeEnum) { assert(IsContain(eventTypeEnum) && "There is no current event, use IsContain to check it before"); return m_storage[m_active_storage_index][eventTypeEnum]; } bool EventsStorage::IsContain(EEventType eventTypeEnum) { auto& currentEventIds = m_storage[m_active_storage_index].find(eventTypeEnum); if (currentEventIds != m_storage[m_active_storage_index].end()) { auto& eventsList = currentEventIds->second; return !eventsList.empty(); } return false; } void EventsStorage::SwapStorages() { m_active_storage_index = !m_active_storage_index; ClearInactiveStorage(); } void EventsStorage::ClearInactiveStorage() { for (auto& inactiveEvents : m_storage[!m_active_storage_index]) { inactiveEvents.second.clear(); } }
// Copyright 2017 Elias Kosunen // // 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 // // https://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 file is a part of scnlib: // https://github.com/eliaskosunen/scnlib #ifndef SCN_DETAIL_VECTORED_H #define SCN_DETAIL_VECTORED_H #include "../ranges/util.h" #include "../util/math.h" namespace scn { SCN_BEGIN_NAMESPACE namespace detail { namespace _get_buffer { struct fn { private: template <typename It> static It _get_end(It begin, It end, size_t max_size) { return begin + min(max_size, static_cast<std::size_t>( ranges::distance(begin, end))); } template <typename CharT> static SCN_CONSTEXPR14 span<typename std::add_const<CharT>::type> impl(span<span<CharT>> s, typename span<CharT>::iterator begin, size_t max_size, priority_tag<3>) noexcept { auto buf_it = s.begin(); for (; buf_it != s.end(); ++buf_it) { if (begin >= buf_it->begin() && begin < buf_it->end()) { break; } if (begin == buf_it->end()) { ++buf_it; begin = buf_it->begin(); break; } } if (buf_it == s.end()) { return {}; } return {begin, _get_end(begin, buf_it->end(), max_size)}; } template < typename Range, typename std::enable_if<SCN_CHECK_CONCEPT( ranges::contiguous_range<Range>)>::type* = nullptr> static SCN_CONSTEXPR14 span<typename std::add_const< ranges::range_value_t<const Range>>::type> impl(const Range& s, ranges::iterator_t<const Range> begin, size_t max_size, priority_tag<2>) noexcept { auto b = ranges::begin(s); auto e = ranges::end(s); return {to_address(begin), _get_end(to_address(begin), to_address_safe(e, b, e), max_size)}; } template <typename Range, typename It> static auto impl( const Range& r, It begin, size_t max_size, priority_tag<1>) noexcept(noexcept(r.get_buffer(begin, max_size))) -> decltype(r.get_buffer(begin, max_size)) { return r.get_buffer(begin, max_size); } template <typename Range, typename It> static auto impl( const Range& r, It begin, size_t max_size, priority_tag<0>) noexcept(noexcept(get_buffer(r, begin, max_size))) -> decltype(get_buffer(r, begin, max_size)) { return get_buffer(r, begin, max_size); } public: template <typename Range, typename It> SCN_CONSTEXPR14 auto operator()(const Range& r, It begin, size_t max_size) const noexcept(noexcept( fn::impl(r, begin, max_size, priority_tag<3>{}))) -> decltype(fn::impl(r, begin, max_size, priority_tag<3>{})) { return fn::impl(r, begin, max_size, priority_tag<3>{}); } template <typename Range, typename It> SCN_CONSTEXPR14 auto operator()(const Range& r, It begin) const noexcept( noexcept(fn::impl(r, begin, std::numeric_limits<size_t>::max(), priority_tag<3>{}))) -> decltype(fn::impl(r, begin, std::numeric_limits<size_t>::max(), priority_tag<3>{})) { return fn::impl(r, begin, std::numeric_limits<size_t>::max(), priority_tag<3>{}); } }; } // namespace _get_buffer namespace { static constexpr auto& get_buffer = detail::static_const<_get_buffer::fn>::value; } // namespace struct provides_buffer_access_concept { template <typename Range, typename Iterator> auto _test_requires(const Range& r, Iterator begin) -> decltype(scn::detail::valid_expr( ::scn::detail::get_buffer(r, begin))); }; template <typename Range, typename = void> struct provides_buffer_access_impl : std::integral_constant< bool, ::scn::custom_ranges::detail::_requires< provides_buffer_access_concept, Range, ::scn::ranges::iterator_t<const Range>>::value> { }; } // namespace detail SCN_END_NAMESPACE } // namespace scn #endif
#pragma once #include "PrimaryRecord.h" #include <vector> #include <string> namespace OpenFlight { class AncillaryRecord; class ColorPaletteRecord; class CommentRecord; class LightPointAnimationPaletteRecord; class LightPointAppearancePaletteRecord; class LightSourcePaletteRecord; class MaterialPaletteRecord; class VertexPaletteRecord; class TexturePaletteRecord; //------------------------------------------------------------------------- // // Current implementation supports the following version: // 15.7 to 16.5 // class OFR_API HeaderRecord : public PrimaryRecord { public: HeaderRecord() = delete; explicit HeaderRecord(PrimaryRecord* ipParent); HeaderRecord(const HeaderRecord&) = delete; HeaderRecord& operator=(const HeaderRecord&) = delete; virtual ~HeaderRecord(); enum vertexCoordinateUnits { vcuMeters = 0, vcuKilometers = 1, vcuFeet = 4, vcuInches = 5, vcuNauticalMiles = 8 }; enum projectionType { ptFlatEarth = 0, ptTrapezoidal = 1, ptRoundEarth = 2, ptLambert = 3, ptUTM = 4, ptGeodetic = 5, Geocentric = 6 }; enum databaseOrigin { doOpenFlight = 100, doDIG_I_DIG_II = 200, doEvans_and_Sutherland_CT5A_CT6 = 300, doPSP_DIG = 400, doGeneral_Electric_CIV_CV_PT2000 = 600 , doEvans_and_Sutherland_GDF = 700}; enum earthEllipsoidModel{ eemWgs1984 = 0, eemWgs1972 = 1, eemBessel = 2, eemClarke1866 = 3, eemNad1927 = 4, eemUserDefined = -1 }; MaterialPaletteRecord* findMaterialPaletteByMaterialIndex(int iIndex); TexturePaletteRecord* findTexturePaletteByTexturePatternIndex(int iIndex); std::string getAsciiId() const; ColorPaletteRecord* getColorPalette(); CommentRecord* getCommentRecord(int) const; std::string getDateAntTimeOfLastRevision() const; databaseOrigin getDatabaseOrigin() const; double getDeltaX() const; double getDeltaY() const; double getDeltaZ() const; earthEllipsoidModel getEarthEllipsoidModel() const; double getEarthMajorAxis() const; double getEarthMinorAxis() const; int getEditRevision() const; std::string getFilePath() const; std::string getFilename() const; std::string getFilenamePath() const; int getFlags() const; int getFormatRevision() const; LightPointAnimationPaletteRecord* getLightPointAnimationPalette(int) const; LightPointAppearancePaletteRecord* getLightPointAppearancePalette(int) const; double getLambertLowerLatitude() const; double getLambertUpperLatitude() const; MaterialPaletteRecord* getMaterialPalette(int) const; uint16_t getNextAdaptiveNodeId() const; uint16_t getNextBspNodeId() const; uint16_t getNextCatNodeId() const; uint16_t getNextClipNodeId() const; uint16_t getNextCurveNodeId() const; int16_t getNextDofNodeId() const; uint16_t getNextFaceNodeId() const; uint16_t getNextGroupNodeId() const; uint16_t getNextLightPointNodeId() const; uint16_t getNextLightPointSystemId() const; uint16_t getNextLightSourceNodeId() const; uint16_t getNextLodNodeId() const; uint16_t getNextMeshNodeId() const; uint16_t getNextObjectNodeId() const; uint16_t getNextPathNodeId() const; uint16_t getNextRoadNodeId() const; uint16_t getNextSoundNodeId() const; uint16_t getNextSwitchNodeId() const; uint16_t getNextTextNodeId() const; double getNorthEastCornerLatitude() const; double getNorthEastCornerLongitude() const; int getNumberOfComments() const; int getNumberOfLightPointAnimationPalettes() const; int getNumberOfLightPointAppearancePalettes() const; int getNumberOfMaterialPalettes() const; int getNumberOfTexturePalettes() const; double getOriginLatitude() const; double getOriginLongitude() const; projectionType getProjection() const; double getRadius() const; bool getShouldSetWhiteTextureOnNewFace() const; double getSouthWestCornerLatitude() const; double getSouthWestCornerLongitude() const; double getSouthWestDbCoordinateX() const; double getSouthWestDbCoordinateY() const; TexturePaletteRecord* getTexturePalette(int) const; uint16_t getUnitMultiplier() const; int16_t getUtmZone() const; vertexCoordinateUnits getVertexCoordinateUnits() const; VertexPaletteRecord* getVertexPalette(); uint16_t getVertexStorageType() const; //setters /*void setAsciiId(std::string); void setDateAntTimeOfLastRevision(std::string); void setDatabaseOrigin(databaseOrigin); void setDeltaX(double); void setDeltaY(double); void setDeltaZ(double); void setEarthEllipsoidModel(EarthEllipsoidModel); void setEarthMajorAxis(double); void setEarthMinorAxis(double); void setEditRevision(int); void setFlags(int); void setFormatRevision(int); void setLambertLowerLatitude(double); void setLambertUpperLatitude(double); void setNextAdaptiveNodeId(uint16_t); void setNextBspNodeId(uint16_t); void setNextCatNodeId(uint16_t); void setNextClipNodeId(uint16_t); void setNextCurveNodeId(uint16_t); void setNextDofNodeId(int16_t); void setNextFaceNodeId(uint16_t); void setNextGroupNodeId(uint16_t); void setNextLightPointNodeId(uint16_t); void setNextLightPointSystemId(uint16_t); void setNextLightSourceNodeId(uint16_t); void setNextLodNodeId(uint16_t); void setNextMeshNodeId(uint16_t); void setNextObjectNodeId(uint16_t); void setNextPathNodeId(uint16_t); void setNextRoadNodeId(uint16_t); void setNextSoundNodeId(uint16_t); void setNextSwitchNodeId(uint16_t); void setNextTextNodeId(uint16_t); void setNorthEastCornerLatitude(double); void setNorthEastCornerLongitude(double); void setOriginLatitude(double); void setOriginLongitude(double); void setProjection(projectionType); void setRadius(double); void setShouldSetWhiteTextureOnNewFace(bool); void setSouthWestCornerLatitude(double); void setSouthWestCornerLongitude(double); void setSouthWestDbCoordinateX(double); void setSouthWestDbCoordinateY(double); void setUnitMultiplier(uint16_t); void setUtmZone(int16_t); void setVertexCoordinateUnits(vertexCoordinateUnits); void setVertexStorageType(uint16_t);*/ protected: friend class OpenFlightReader; virtual void handleAddedAncillaryRecord(AncillaryRecord*) override; virtual bool parseRecord(std::ifstream& iRawRecord, int iVersion) override; void setFileInfo(const std::string& iFilenamePath, const std::string& iFilePath, const std::string& iFilename); std::string mAsciiId; int mFormatRevision; int mEditRevision; std::string mDateAntTimeOfLastRevision; uint16_t mNextGroupNodeId; uint16_t mNextLodNodeId; uint16_t mNextObjectNodeId; uint16_t mNextFaceNodeId; uint16_t mUnitMultiplier; //always 1 vertexCoordinateUnits mVertexCoordinateUnits; bool mShouldSetWhiteTextureOnNewFace; int mFlags; projectionType mProjection; uint16_t mNextDofNodeId; uint16_t mVertexStorageType; //should always be 1 - Double precision float databaseOrigin mDatabaseOrigin; double mSouthWestDbCoordinateX; double mSouthWestDbCoordinateY; double mDeltaX; double mDeltaY; uint16_t mNextSoundNodeId; uint16_t mNextPathNodeId; uint16_t mNextClipNodeId; uint16_t mNextTextNodeId; uint16_t mNextBspNodeId; uint16_t mNextSwitchNodeId; double mSouthWestCornerLatitude; double mSouthWestCornerLongitude; double mNorthEastCornerLatitude; double mNorthEastCornerLongitude; double mOriginLatitude; double mOriginLongitude; double mLambertUpperLatitude; double mLambertLowerLatitude; uint16_t mNextLightSourceNodeId; uint16_t mNextLightPointNodeId; uint16_t mNextRoadNodeId; uint16_t mNextCatNodeId; earthEllipsoidModel mEarthEllipsoidModel; uint16_t mNextAdaptiveNodeId; uint16_t mNextCurveNodeId; int16_t mUtmZone; double mDeltaZ; double mRadius; uint16_t mNextMeshNodeId; uint16_t mNextLightPointSystemId; double mEarthMajorAxis; //in meters double mEarthMinorAxis; //in meters // Ancillary Records // these members are there for convenience. All of them can be found in the PrimaryRecords::ancillaryRecords // ColorPaletteRecord *mpColorPalette; LightSourcePaletteRecord *mpLightSourcePalette; std::vector<MaterialPaletteRecord*> mMaterialPalettes; std::vector<LightPointAppearancePaletteRecord*> mLightPointAppearancePalettes; std::vector<LightPointAnimationPaletteRecord*> mLightPointAnimationPalettes; VertexPaletteRecord *mpVertexPalette; //owned in PrimaryRecords::mAncillaryRecord ; std::vector<TexturePaletteRecord*> mTexturePalettes; std::vector<CommentRecord*> mComments; // additionnal data, not part of the binary flt file std::string mFilenamePath; std::string mFilePath; std::string mFilename; }; }
#include<iostream> using std::cout; using std::cin; using std::endl; //undefined macro initialized with 0 //#define P 5 #define ISEQUAL(x,y) x==y int main(){ #if ISEQUAL(P,0) cout<<"success\a"<<endl; #else cout<<"failure\a"<<endl; #endif return 0; }
#ifndef RECEIVER_H #define RECEIVER_H #include "port/port.h" #include "protocol/receiverprotocol.h" #include <QObject> class Receiver : public QObject { Q_OBJECT public: Receiver(); ~Receiver(); void init (int dataBits, int parity, int stopBits, int baud); public slots: void run(); private: IPort *port; QThread* thread; // ReceiverProtocol *protocol; }; #endif // RECEIVER_H
#include <stdio.h> #include<stdlib.h> int main() { int matriz[100][100]; int *direccion=&matriz[0][0]; int filas,columnas; int i,j,x,b; int num1,num2; printf("Ingrese tamaņo de la matriz\n"); printf("Filas: "); scanf("%d",&filas); printf("\nColumnas: "); scanf("%d",&columnas); printf("\nIngrese elementos de la matriz: \n"); for(i=0;i<filas;i++){ for(j=0;j<columnas;j++){ scanf("%d",&*(direccion+i+j * columnas)); } } printf("\nMostrando matriz:\n"); for(i=0;i<filas;i++){ for(j=0;j<columnas;j++){ printf("%d ",*(direccion+i+j * columnas)); } printf("\n"); } printf("\nModificar Matriz\n"); printf("Ingrese cuantos elementos desea Modificar: "); scanf("%d",&x); for(i=0;i<x;i++){ printf("\n Numero Fila a Modificar: "); scanf("%d",&num1); printf("\n Numero Columna a Modificar: "); scanf("%d",&num2); printf("\nIngrese nuevo elemento:"); scanf("%d",&b); for(i=0;i<filas;i++){ for(j=0;j<columnas;j++){ if(i==num1 && j==num2){ *(direccion+i+j *columnas)=b; } } } } printf("\nMostrando matriz con nuevos elementos:\n"); for(i=0;i<filas;i++){ for(j=0;j<columnas;j++){ printf("%d ",*(direccion+i+j * columnas)); } printf("\n"); } return 0; }
#ifndef CMPRO_DPL_CPP #define CMPRO_DPL_CPP #include "../include/cmpro/deep_process.h" int main(){ DeepProcess learning_method; learning_method.loop_process(); return 0; } #endif
#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 <cstdio> #include <cstdlib> #include <cstring> #include <numeric> #include <bitset> #include <deque> const long long LINF = (5e18); const int INF = (1<<28); #define EPS 1e-6 const int MOD = 1000000007; using namespace std; class TwoStringMasks { public: string shortestCommon(string &s1, string &s2) { string prefix = ""; while (s1[0] != '*' && s2[0] != '*') { if (s1[0] != s2[0]) return "impossible"; prefix += s1[0]; s1 = s1.substr(1); s2 = s2.substr(1); } reverse(s1.begin(), s1.end()); reverse(s2.begin(), s2.end()); string suffix = ""; while (s1[0] != '*' && s2[0] != '*') { if (s1[0] != s2[0]) return "impossible"; suffix += s1[0]; s1 = s1.substr(1); s2 = s2.substr(1); } reverse(s1.begin(), s1.end()); reverse(s2.begin(), s2.end()); reverse(suffix.begin(), suffix.end()); if (s1 == "*") swap(s1, s2); if (s2 == "*") { int p = 0; for (;p<s1.size(); ++p) if (s1[p] == '*') break; return prefix + s1.substr(0,p) + s1.substr(p+1) + suffix; } if (s1[0] != '*') swap(s1, s2); for (int p=0; p<s2.size(); ++p) { if (s2.size() - 1 - p >= s1.size()) continue; int last = p; for (; last<s2.size(); ++last) if (s1[last - p + 1] != s2[last]) break; if (last != s2.size() - 1) continue; return prefix + s2.substr(0, p) + s1.substr(1) + suffix; } return ""; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); if ((Case == -1) || (Case == 7)) test_case_7(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arg0 = "TOPC*DER"; string Arg1 = "T*PCODER"; string Arg2 = "TOPCODER"; verify_case(0, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_1() { string Arg0 = "HELLO*"; string Arg1 = "HI*"; string Arg2 = "impossible"; verify_case(1, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_2() { string Arg0 = "GOOD*LUCK"; string Arg1 = "*"; string Arg2 = "GOODLUCK"; verify_case(2, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_3() { string Arg0 = "*SAMPLETEST"; string Arg1 = "THIRDSAMPLE*"; string Arg2 = "THIRDSAMPLETEST"; verify_case(3, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_4() { string Arg0 = "*TOP"; string Arg1 = "*CODER"; string Arg2 = "impossible"; verify_case(4, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_5() { string Arg0 = "*"; string Arg1 = "A*"; string Arg2 = "A"; verify_case(5, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_6() { string Arg0 = "*A"; string Arg1 = "B*"; string Arg2 = "BA"; verify_case(6, Arg2, shortestCommon(Arg0, Arg1)); } void test_case_7() { string Arg0 = "LASTCASE*"; string Arg1 = "*LASTCASE"; string Arg2 = "LASTCASE"; verify_case(7, Arg2, shortestCommon(Arg0, Arg1)); } // END CUT HERE }; // BEGIN CUT HERE int main() { TwoStringMasks ___test; ___test.run_test(-1); } // END CUT HERE
#include<bits/stdc++.h> #define rep(i, s, n) for (int i = (s); i < (int)(n); i++) #define INF ((1LL<<62)-(1LL<<31)) /*オーバーフローしない程度に大きい数*/ #define MOD 1000000007 using namespace std; using ll = long long; using Graph = vector<vector<int>>; using pint = pair<int,int>; const double PI = 3.14159265358979323846; int main(){ int N; cin >> N; vector<int>A(N+1); rep(i,0,N)cin >> A[i+1]; vector<int>ans; vector<int>ball(200010); //大きいほうからうめる for(int i = N; i >= 1; i--){ int sum = 0; for(int j = i; j <=N; j += i){ sum += ball[j]; } if(sum %2 != A[i]){ ball[i] = 1; //出力はボールが入っている箱の番号 ans.push_back(i); } } cout << ans.size() << endl; for(auto x:ans)cout << x << " "; cout << endl; }
#include "linalg.h" #include <iostream> #include <immintrin.h> #include <cmath> #include <cassert> #include <immintrin.h> #include "fastrand.h" #include "typedefs.h" #include <stdint.h> #include <string.h> //! ------------------------------------------------------- // //! ---------- Linear Algebra Utility Functions ----------- // //! ------------------------------------------------------- // ///////////////////////////////////////////////////////////// //! I did not change these functions to base since this would //! overcomplify the project. Do not edit any functions here, //! rather add new ones if necessary, or do it in place!!! ///////////////////////////////////////////////////////////// //! Prints an array void print(const double *x, size_t rows, size_t cols, std::ostream& stream) { assert( x != NULL ); for (size_t i = 0; i < rows; i++) { stream << std::endl; for (size_t j = 0; j < cols; j++) { stream << "\t" << x[i*cols+j]; } } stream << std::endl; } void iprint(const int *x, size_t rows, size_t cols, std::ostream& stream) { assert( x != NULL ); for (size_t i = 0; i < rows; i++) { stream << std::endl; for (size_t j = 0; j < cols; j++) { stream << "\t" << x[i*cols+j]; } } stream << std::endl; } void stprint(const size_t *x, size_t rows, size_t cols, std::ostream& stream) { assert( x != NULL ); for (size_t i = 0; i < rows; i++) { stream << std::endl; for (size_t j = 0; j < cols; j++) { stream << "\t" << x[i*cols+j]; } } stream << std::endl; } void print256d(__m256d var) { double val[4]; memcpy(val, &var, sizeof(val)); printf("SIMD: <%f %f %f %f> \n", val[0], val[1], val[2], val[3]); } //! Fills an array with a specific value void fill(double *x, size_t size, double val) { assert( x != NULL ); for (size_t i = 0; i < size; i++) { x[i] = val; } } void icopy(const int* ref, size_t N, int* target) { for (size_t i = 0; i < N; i++) { target[i] = ref[i]; } } //! Copies all values from ref to target void copy(const double* ref, size_t N, double* target) { for (size_t i = 0; i < N; i++) { target[i] = ref[i]; } } double copy_flops(const double* ref, size_t N, double* target) { return 0.0; } double copy_memory(const double* ref, size_t N, double* target) { return 0.0; } //! Fills an array with random values in the range [lo, hi] void fill_rand(double *x, size_t size, double lo, double hi) { // assert( x != NULL && hi > lo ); double range = hi - lo; for (size_t i = 0; i < size; i++) { x[i] = lo + range * ((double)rand())/((double)RAND_MAX); } } double fill_rand_flops(double *x, size_t size, double lo, double hi) { return tp.add + size*(tp.add + tp.mul + tp.div + tp.rand); } double fill_rand_memory(double *x, size_t size, double lo, double hi) { return 0; return 2*size; } // Works ;) #ifdef __AVX2__ __m256d fill_rand_avx(double lo, double hi) { __m256d lov = _mm256_set1_pd(lo); __m256d hiv = _mm256_set1_pd(hi); __m256i rand_vec = avx_xorshift128plus(); __m256d intmax = _mm256_set1_pd(2147483647); __m256d uintmax = _mm256_set1_pd(4294967295); // We only use 128bit of the vector atm. E.g. for predict-update, we could make use of the other 128 bit too. __m256d ymm0 = _mm256_cvtepi32_pd(_mm256_extractf128_si256(rand_vec, 0)); //32 bit ymm0 = _mm256_add_pd(ymm0, intmax); __m256d ymm1 = _mm256_div_pd(ymm0, uintmax); __m256d range = _mm256_sub_pd(hiv, lov); #ifdef __FMA__ return _mm256_fmadd_pd(range, ymm1, lov); #else return _mm256_add_pd( _mm256_mul_pd(range, ymm1), lov); #endif } #endif // Fails some tests #ifdef __AVX2__ __m256d fill_rand_avx_abs(double lo, double hi) { __m256d lov = _mm256_set1_pd(lo); __m256d hiv = _mm256_set1_pd(hi); __m256i rand_vec = _mm256_abs_epi32(avx_xorshift128plus()); __m256d intmax = _mm256_set1_pd(2147483647); //2147483647 __m256d ymm0 = _mm256_cvtepi32_pd(_mm256_extractf128_si256(rand_vec, 0)); //32 bit __m256d ymm1 = _mm256_div_pd(ymm0, intmax); __m256d range = _mm256_sub_pd(hiv, lov); #ifdef __FMA__ return _mm256_fmadd_pd(range, ymm1, lov); #else return _mm256_add_pd( _mm256_mul_pd(range, ymm1), lov); #endif } #endif /* void fill_rand_fast(double *x, size_t size, double lo, double hi) { double range = hi - lo; for (size_t i = 0; i < size; i++) { x[i] = lo + range * xorshf96()*1.0/ulong_max; } } */ //! ------------------------------------------------------- // //! -------------- Basic Matrix Operations ---------------- // //! ------------------------------------------------------- // //! Matrix Transpose void transpose(const double *A, size_t mA, size_t nA, double *T) { assert( A != NULL && T != NULL ); for (size_t i = 0; i < nA; i++) { for (size_t j = 0; j < mA; j++) { T[i*mA+j] = A[j*nA+i]; } } } double transpose_flops(const double *A, size_t mA, size_t nA, double *T) { return 0.0; } double transpose_memory(const double *A, size_t mA, size_t nA, double *T) { return 0; return 3*nA*mA; } void transpose_2x2(const double *A, double *T) { T[0] = A[0]; T[1] = A[2]; T[2] = A[1]; T[3] = A[3]; } double transpose_2x2_flops(const double *A, double *T) { return 0.0; } double transpose_2x2_memory(const double *A, double *T) { return 0; return 3*4; } #ifdef __AVX2__ __m256d _transpose_2x2_avx( __m256d A ) { return _mm256_permute4x64_pd( A, 0b11011000 ); } #endif void stranspose_2x2(double *A) { const double tmp = A[1]; A[1] = A[2]; A[2] = tmp; } //! Adds two arrays void add(const double *x, const double *y, size_t size, double* z) { assert( x != NULL && y != NULL && z != NULL ); for (size_t i = 0; i < size; i++) { z[i] = x[i] + y[i]; } } double add_flops(const double *x, const double *y, size_t size, double* z) { return size*tp.add; } double add_memory(const double *x, const double *y, size_t size, double* z) { return 0; return size*4; } //! Subtracts two arrays void sub(const double *x, const double *y, size_t size, double* z) { assert( x != NULL && y != NULL && z != NULL ); for (size_t i = 0; i < size; i++) { z[i] = x[i] - y[i]; } } double sub_flops(const double *x, const double *y, size_t size, double* z) { return size*tp.add; } double sub_memory(const double *x, const double *y, size_t size, double* z) { return 0; return size*4; } //! Scales an array by a scalar void scal(const double *x, size_t size, double a, double *y) { for (size_t i = 0; i < size; i++) { y[i] = a*x[i]; } } double scal_flops(const double *x, size_t size, double a, double *y) { return size*tp.mul; } double scal_memory(const double *x, size_t size, double a, double *y) { return 0; return size*2; } //! Matrix x Matrix Multiplication: C = A * B void mul(const double *A, const double *B, size_t mA, size_t nA, size_t nB, double *C) { assert( A != NULL && B != NULL && C != NULL ); for (size_t i = 0; i < mA; i++) { for (size_t j = 0; j < nB; j++) { double sum = 0.0; for (size_t k = 0; k < nA; k++) { sum += A [i*nA+k] * B[k*nB+j]; } C[i*nB+j] = sum; } } } double mul_flops(const double *A, const double *B, size_t mA, size_t nA, size_t nB, double *C) { return mA*nA*nB*tp.mul + mA*nA*nB*tp.add; } double mul_memory(const double *A, const double *B, size_t mA, size_t nA, size_t nB, double *C) { return 0; return 2*mA*nB + mA*nA + nB*nA; } //! Matrix x Matrix Multiplication ( 2x2 ) void mm_2x2(const double *A, const double *B, double *C) { //mm_2x2_avx_v1(A, B, C); //mm_2x2_avx_v2(A, B, C); C[0] = A[0]*B[0] + A[1]*B[2]; C[1] = A[0]*B[1] + A[1]*B[3]; C[2] = A[2]*B[0] + A[3]*B[2]; C[3] = A[2]*B[1] + A[3]*B[3]; } double mm_2x2_flops(const double *A, const double *B, double *C) { return 4*tp.add + 8*tp.mul; } double mm_2x2_memory(const double *A, const double *B, double *C) { return 0; return 2*4 + 2*4; } //! Matrix x Matrix Multiplication ( 2x2 ) [ AVX ] #ifdef __AVX__ void mm_2x2_avx_v1(const double *A, const double *B, double *C) { __m256d a = _mm256_load_pd( A ); __m256d b = _mm256_load_pd( B ); __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0101 = _mm256_permute2f128_pd( b, b, 0b00000000 ); __m256d b2323 = _mm256_permute2f128_pd( b, b, 0b01010101 ); #ifdef __FMA__ __m256d c = _mm256_fmadd_pd( a1133, b2323, _mm256_mul_pd( a0022, b0101 ) ); #else __m256d c = _mm256_add_pd( _mm256_mul_pd(a1133, b2323), _mm256_mul_pd( a0022, b0101 ) ); #endif _mm256_store_pd(C, c); } #endif #ifdef __AVX__ __m256d _mm_2x2_avx_v1( __m256d a, __m256d b ) { __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0101 = _mm256_permute2f128_pd( b, b, 0b00000000 ); __m256d b2323 = _mm256_permute2f128_pd( b, b, 0b01010101 ); #ifdef __FMA__ __m256d c = _mm256_fmadd_pd( a1133, b2323, _mm256_mul_pd( a0022, b0101 ) ); #else __m256d c = _mm256_add_pd( _mm256_mul_pd(a1133, b2323), _mm256_mul_pd( a0022, b0101 ) ); #endif return c; } #endif //! Matrix x Matrix Multiplication ( 2x2 ) [ AVX ] #ifdef __AVX__ void mm_2x2_avx_v2(const double *A, const double *B, double *C) { __m256d a = _mm256_load_pd( A ); __m256d b = _mm256_load_pd( B ); __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0101 = _mm256_permute2f128_pd( b, b, 0b00000000 ); __m256d b2323 = _mm256_permute2f128_pd( b, b, 0b01010101 ); __m256d c0 = _mm256_mul_pd( a0022, b0101 ); __m256d c1 = _mm256_mul_pd( a1133, b2323 ); _mm256_store_pd(C, _mm256_add_pd( c0, c1 )); } #endif #ifdef __AVX__ void mm_2x2_avx_v3(const double *A, const double *B, double *C) { __m256d a0123 = _mm256_load_pd( A ); __m256d b0123 = _mm256_load_pd( B ); __m256d a1032 = _mm256_permute_pd( a0123, 0b0101 ); __m256d b2301 = _mm256_permute2f128_pd( b0123, b0123, 0b00000001 ); __m256d b0303 = _mm256_blend_pd( b0123, b2301, 0b0110 ); __m256d b2121 = _mm256_blend_pd( b0123, b2301, 0b1001 ); #ifdef __FMA__ __m256d c = _mm256_fmadd_pd( a1032, b2121, _mm256_mul_pd( a0123, b0303 ) ); #else __m256d c = _mm256_add_pd( _mm256_mul_pd(a1032, b2121), _mm256_mul_pd( a0123, b0303 ) ); #endif _mm256_store_pd(C, c); } #endif //! Matrix x Matrix Transpose Multiplication ( 2x2 ) void mmT_2x2(const double *A, const double *B, double *C) { //mmT_2x2_avx_v1(A, B, C); //mmT_2x2_avx_v2(A, B, C); C[0] = A[0]*B[0] + A[1]*B[1]; C[1] = A[0]*B[2] + A[1]*B[3]; C[2] = A[2]*B[0] + A[3]*B[1]; C[3] = A[2]*B[2] + A[3]*B[3]; } double mmT_2x2_flops(const double *A, const double *B, double *C) { return 4*tp.add + 8*tp.mul; } double mmT_2x2_memory(const double *A, const double *B, double *C) { return 0; return 2*4 + 2*4; } //! Matrix x Matrix Transpose Multiplication ( 2x2 ) [ AVX ] #ifdef __AVX2__ void mmT_2x2_avx_v1(const double *A, const double *B, double *C) { __m256d a = _mm256_load_pd( A ); __m256d b = _mm256_load_pd( B ); __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0202 = _mm256_permute4x64_pd( b, 0b10001000 ); __m256d b1313 = _mm256_permute4x64_pd( b, 0b11011101 ); #ifdef __FMA__ __m256d c = _mm256_fmadd_pd( a1133, b1313, _mm256_mul_pd( a0022, b0202 ) ); #else __m256d c = _mm256_add_pd( _mm256_mul_pd(a1133, b1313), _mm256_mul_pd( a0022, b0202 ) ); #endif _mm256_store_pd(C, c); } #endif //! Matrix x Matrix Transpose Multiplication ( 2x2 ) [ AVX ] #ifdef __AVX2__ void mmT_2x2_avx_v2(const double *A, const double *B, double *C) { __m256d a = _mm256_load_pd( A ); __m256d b = _mm256_load_pd( B ); __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0202 = _mm256_permute4x64_pd( b, 0b10001000 ); __m256d b1313 = _mm256_permute4x64_pd( b, 0b11011101 ); __m256d c0 = _mm256_mul_pd( a0022, b0202 ); __m256d c1 = _mm256_mul_pd( a1133, b1313 ); _mm256_store_pd(C, _mm256_add_pd( c0, c1 )); } #endif #ifdef __AVX__ void mmT_2x2_avx_v3(const double *A, const double *B, double *C) { __m256d a0123 = _mm256_load_pd( A ); __m256d b0123 = _mm256_load_pd( B ); __m256d b2301 = _mm256_permute2f128_pd( b0123, b0123, 0b00000001 ); __m256d b0303 = _mm256_blend_pd( b0123, b2301, 0b0110 ); __m256d b2121 = _mm256_blend_pd( b0123, b2301, 0b1001 ); __m256d c0 = _mm256_mul_pd( a0123, b2121 ); __m256d c0_perm = _mm256_permute_pd( c0, 0b0101 ); #ifdef __FMA__ __m256d c = _mm256_fmadd_pd( a0123, b0303, c0_perm ); #else __m256d c = _mm256_add_pd( _mm256_mul_pd(a0123, b0303), c0_perm ); #endif _mm256_store_pd( C, c ); } #endif #ifdef __AVX__ __m256d _mmT_2x2_avx_v3( __m256d a0123, __m256d b0123 ) { __m256d b2301 = _mm256_permute2f128_pd( b0123, b0123, 0b00000001 ); __m256d b0303 = _mm256_blend_pd( b0123, b2301, 0b0110 ); __m256d b2121 = _mm256_blend_pd( b0123, b2301, 0b1001 ); __m256d c0 = _mm256_mul_pd( a0123, b2121 ); __m256d c0_perm = _mm256_permute_pd( c0, 0b0101 ); #ifdef __FMA__ __m256d c = _mm256_fmadd_pd( a0123, b0303, c0_perm ); #else __m256d c = _mm256_add_pd( _mm256_mul_pd(a0123, b0303), c0_perm ); #endif return c; } #endif //! C += A*B ( 2x2 ) void mmadd_2x2(const double *A, const double *B, double *C) { //mmadd_2x2_avx_v1(A, B, C); C[0] += A[0]*B[0] + A[1]*B[2]; C[1] += A[0]*B[1] + A[1]*B[3]; C[2] += A[2]*B[0] + A[3]*B[2]; C[3] += A[2]*B[1] + A[3]*B[3]; } double mmadd_2x2_flops(const double *A, const double *B, double *C) { return 8*tp.add + 8*tp.mul; } double mmadd_2x2_memory(const double *A, const double *B, double *C) { return 0; return 2*4 + 2*4; } #ifdef __AVX__ void mmadd_2x2_avx_v1(const double *A, const double *B, double *C) { __m256d a = _mm256_load_pd( A ); __m256d b = _mm256_load_pd( B ); __m256d c = _mm256_load_pd( C ); __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0101 = _mm256_permute2f128_pd( b, b, 0b00000000 ); __m256d b2323 = _mm256_permute2f128_pd( b, b, 0b01010101 ); #ifdef __FMA__ c = _mm256_fmadd_pd( a0022, b0101, c ); #else c = _mm256_add_pd( _mm256_mul_pd(a0022, b0101), c ); #endif #ifdef __FMA__ c = _mm256_fmadd_pd( a1133, b2323, c ); #else c = _mm256_add_pd( _mm256_mul_pd(a1133, b2323), c ); #endif _mm256_store_pd(C, c); } #endif #ifdef __AVX__ void mmadd_2x2_avx_v2(const double *A, const double *B, double *C) { __m256d a = _mm256_load_pd( A ); __m256d b = _mm256_load_pd( B ); __m256d c = _mm256_load_pd( C ); __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0101 = _mm256_permute2f128_pd( b, b, 0b00000000 ); __m256d b2323 = _mm256_permute2f128_pd( b, b, 0b01010101 ); #ifdef __FMA__ c = _mm256_fmadd_pd( a0022, b0101, c ); #else c = _mm256_add_pd( _mm256_mul_pd(a0022, b0101), c ); #endif __m256d cc = _mm256_mul_pd( a1133, b2323 ); _mm256_store_pd(C, _mm256_add_pd( c, cc ) ); } #endif #ifdef __AVX__ __m256d _mmadd_2x2_avx_v2(__m256d a, __m256d b, __m256d c) { __m256d a0022 = _mm256_permute_pd( a, 0b0000 ); __m256d a1133 = _mm256_permute_pd( a, 0b1111 ); __m256d b0101 = _mm256_permute2f128_pd( b, b, 0b00000000 ); __m256d b2323 = _mm256_permute2f128_pd( b, b, 0b01010101 ); #ifdef __FMA__ c = _mm256_fmadd_pd( a0022, b0101, c ); #else c = _mm256_add_pd( _mm256_mul_pd(a0022, b0101), c ); #endif __m256d cc = _mm256_mul_pd( a1133, b2323 ); return _mm256_add_pd( c, cc ); } #endif #ifdef __AVX__ __m256d _mmTadd_2x2_avx_v2(__m256d a0123, __m256d b0123, __m256d c) { __m256d b2301 = _mm256_permute2f128_pd( b0123, b0123, 0b00000001 ); __m256d b0303 = _mm256_blend_pd( b0123, b2301, 0b0110 ); __m256d b2121 = _mm256_blend_pd( b0123, b2301, 0b1001 ); __m256d c0 = _mm256_mul_pd( a0123, b2121 ); #ifdef __FMA__ __m256d cc = _mm256_fmadd_pd( a0123, b0303, c ); #else __m256d cc = _mm256_add_pd( _mm256_mul_pd(a0123, b0303), c ); #endif __m256d c0_perm = _mm256_permute_pd( c0, 0b0101 ); return _mm256_add_pd(cc, c0_perm); } #endif //! Matrix x Vector Multiplication ( 2x2 ) void mv_2x2(const double *A, const double *b, double *c) { c[0] = A[0]*b[0] + A[1]*b[1]; c[1] = A[2]*b[0] + A[3]*b[1]; } double mv_2x2_flops(const double *A, const double *b, double *c) { return 2*tp.add + 4*tp.mul; } double mv_2x2_memory(const double *A, const double *b, double *c) { return 0; return 4 + 2 + 2*2; } //! c += A*b ( 2x2 ) void mvadd_2x2(const double *A, const double *b, double *c) { c[0] += A[0]*b[0] + A[1]*b[1]; c[1] += A[2]*b[0] + A[3]*b[1]; } double mvadd_2x2_flops(const double *A, const double *b, double *c) { return 4*tp.add + 4*tp.mul; } double mvadd_2x2_memory(const double *A, const double *b, double *c) { return 0; return 4 + 2 + 2*2; } //! Matrix x Vector Multiplication ( 2x2 ) [ AVX ] // a should be 32-byte aligned // b should be 16-byte aligned #ifdef __AVX2__ __m128d _mv_2x2_avx_v1( __m256d const a, __m128d const b ) { __m256d Ab = _mm256_mul_pd( a, _mm256_broadcast_pd( &b ) ); __m256d sum = _mm256_add_pd( Ab, _mm256_permute_pd(Ab, 0b0101) ); return _mm256_castpd256_pd128( _mm256_permute4x64_pd( sum, 0b00001000 ) ); } #endif //! c += A*b ( 2x2 ) [ AVX ] // a should be 32-byte aligned // b should be 16-byte aligned #ifdef __AVX2__ __m128d _mvadd_2x2_avx_v1( __m256d const a, __m128d const b, __m128d const c ) { __m256d Ab = _mm256_mul_pd( a, _mm256_broadcast_pd( &b ) ); __m256d sum = _mm256_add_pd( Ab, _mm256_permute_pd(Ab, 0b0101) ); __m128d slo = _mm256_castpd256_pd128( _mm256_permute4x64_pd( sum, 0b00001000 ) ); return _mm_add_pd(c, slo); } #endif //! Cholesky Factorization of a 2x2 SPD Matrix A = L * L^T, L lower triangular void llt_2x2(const double *A, double *L) { assert( A != NULL && L != NULL ); L[0] = sqrt( A[0] ); // 0*2+0 -> (0,0) L[1] = 0.0; // 0*2+1 -> (0,1) L[2] = A[2] / L[0]; // 1*2+0 -> (1,0) L[3] = sqrt( A[3] - L[2]*L[2] ); // 1*2+1 -> (1,1) } double llt_2x2_flops(const double *A, double *L) { return 2*tp.sqrt + tp.div + tp.mul + tp.add; } double llt_2x2_memory(const double *A, double *L) { return 0; return 3*4; } //! Inverse of a 2x2 Matrix void inv_2x2(const double *A, double *Ainv) { double s = 1.0 / ( A[0]*A[3] - A[1]*A[2] ); Ainv[0] = s * A[3]; Ainv[1] = -s * A[1]; Ainv[2] = -s * A[2]; Ainv[3] = s * A[0]; } double inv_2x2_flops(const double *A, double *Ainv) { return 6*tp.mul + tp.div + tp.add + 2*tp.negation; } double inv_2x2_memory(const double *A, double *Ainv) { return 0; return 3*4; } double determinant_2x2(const double* A) { return A[0] * A[3] - A[1] * A[2]; } double determinant_2x2_flops(const double* A) { return 2*tp.mul + tp.add; } double determinant_2x2_memory(const double* A) { return 0; return 4.0; } #ifdef __AVX2__ /** v.T @ M @ v subroutine * @param m1 2x2 Matrix M1 in row major storage * @param m2 2x2 Matrix M2 in row major storage * @param v12 The 2x1 vectors V1 and V2 stored in order * * @returns AVX2[a, b , c, d] s.t. a + b = V1.T@M1@V1, c + d = V2.T@M2@V2 */ __m256d produce_hvec(const __m256d m1, const __m256d m2, const __m256d v12) { __m256d v12_v12 = _mm256_mul_pd(v12, v12); // [v1^2, v2^2, v3^2, v4^2] __m256d v12_v21 = _mm256_mul_pd(v12, _mm256_permute_pd(v12, 0b0101)); // [v1v2, v1v2, v3v4, v3v4] __m256d m1_perm = _mm256_permute4x64_pd(m1, 0b10011100); // [a, d, b, c] __m256d m2_perm = _mm256_permute4x64_pd(m2, 0b11001001); // [e, h, f, g __m256d m1_ = _mm256_permute2f128_pd(m1_perm, m2_perm, 0b00110000); // [a, d, e, h] __m256d m2_ = _mm256_permute2f128_pd(m1_perm, m2_perm, 0b00100001); // [b, c, f, g] __m256d lhs = _mm256_mul_pd(v12_v12, m1_); // [a11, d22, e33, h44] __m256d rhs = _mm256_mul_pd(v12_v21, m2_); // [b12, c12, f34, g34] __m256d res = _mm256_add_pd(lhs, rhs); // [a11+b12, c12+d22, e33+f34, g34+h44] // ^ needs to be hsum'd to get final result return res; }; #endif #ifdef __AVX2__ __m256d mm_vT_M_v_avx2(const __m256d m1, const __m256d m2, const __m256d m3, const __m256d m4, const __m256d v12, const __m256d v34) { __m256d res1 = produce_hvec(m1, m2, v12); __m256d res2 = produce_hvec(m3, m4, v34); __m256d res_total = _mm256_hadd_pd(res1, res2); // this gives [A, C, B, D] so we have to permute B and C __m256d result = _mm256_permute4x64_pd(res_total, 0b11011000); return result; } #endif #ifdef __AVX2__ __m256d mm_vT_M_v_avx2_phil(const __m256d m1, const __m256d m2, const __m256d m3, const __m256d m4, const __m256d v12, const __m256d v34) { __m256d ymm0, ymm1, ymm2, ymm3, result; ymm0 = _mm256_permute2f128_pd(m1, m2, 0b00100000); ymm2 = _mm256_permute2f128_pd(m1, m2, 0b00110001); ymm1 = _mm256_permute2f128_pd(m3, m4, 0b00100000); ymm3 = _mm256_permute2f128_pd(m3, m4, 0b00110001); ymm0 = _mm256_mul_pd(v12, ymm0); ymm2 = _mm256_mul_pd(v12, ymm2); ymm1 = _mm256_mul_pd(v34, ymm1); ymm3 = _mm256_mul_pd(v34, ymm3); ymm0 = _mm256_hadd_pd(ymm0, ymm2); ymm1 = _mm256_hadd_pd(ymm1, ymm3); ymm2 = _mm256_mul_pd(v12, ymm0); ymm3 = _mm256_mul_pd(v34, ymm1); result = _mm256_hadd_pd(ymm2, ymm3); result = _mm256_permute4x64_pd(result, 0b11011000); return result; } #endif #ifdef __AVX2__ void register_transpose(__m256d const r0, __m256d const r1, __m256d const r2, __m256d const r3, __m256d *t0, __m256d *t1, __m256d *t2, __m256d *t3) { __m256d const lows_r0_r2 = _mm256_insertf128_pd( r0, _mm256_extractf128_pd(r2, 0), 1 ); __m256d const lows_r1_r3 = _mm256_insertf128_pd( r1, _mm256_extractf128_pd(r3, 0), 1 ); *t0 = _mm256_unpacklo_pd( lows_r0_r2, lows_r1_r3 ); *t1 = _mm256_unpackhi_pd( lows_r0_r2, lows_r1_r3 ); __m256d const highs_r0_r2 = _mm256_insertf128_pd( r2, _mm256_extractf128_pd(r0, 1), 0 ); __m256d const highs_r1_r3 = _mm256_insertf128_pd( r3, _mm256_extractf128_pd(r1, 1), 0 ); *t2 = _mm256_unpacklo_pd( highs_r0_r2, highs_r1_r3 ); *t3 = _mm256_unpackhi_pd( highs_r0_r2, highs_r1_r3 ); } #endif #ifdef __AVX2__ void batch_inverse_2x2(__m256d const r0, __m256d const r1, __m256d const r2, __m256d const r3, __m256d *inv0, __m256d *inv1, __m256d *inv2, __m256d *inv3) { __m256d t0, t1, t2, t3; register_transpose(r0, r1, r2, r3, &t0, &t1, &t2, &t3); __m256d det = _mm256_sub_pd( _mm256_mul_pd(t0,t3), _mm256_mul_pd(t1,t2) ); __m256d inv_det = _mm256_div_pd( _mm256_set1_pd( 1.0), det ); __m256d neg_inv_det = _mm256_mul_pd( _mm256_set1_pd(-1.0), inv_det ); t3 = _mm256_mul_pd( inv_det, t3 ); t1 = _mm256_mul_pd( neg_inv_det, t1 ); t2 = _mm256_mul_pd( neg_inv_det, t2 ); t0 = _mm256_mul_pd( inv_det, t0 ); __m256d ymm6 = _mm256_unpacklo_pd(t3, t1); __m256d ymm7 = _mm256_unpackhi_pd(t3, t1); __m256d ymm8 = _mm256_unpacklo_pd(t2, t0); __m256d ymm9 = _mm256_unpackhi_pd(t2, t0); *inv0 = _mm256_permute2f128_pd(ymm6, ymm8, 0b00100000); *inv1 = _mm256_permute2f128_pd(ymm7, ymm9, 0b00100000); *inv2 = _mm256_permute2f128_pd(ymm6, ymm8, 0b00110001); *inv3 = _mm256_permute2f128_pd(ymm7, ymm9, 0b00110001); } #endif
/* * szukaj_bin.cpp */ #include <iostream> using namespace std; void wypelnij(int tab[], int roz) { srand(time(NULL)); // INICJACJIA generatora liczb pseudolosowych for(int i = 0; i < roz; i++) { //~cout << rand() << endl; tab[i] = rand() % 101; } } void drukuj(int tab[], int roz) { for(int i = 0; i < roz; i++) { cout << tab[i] << " "; } cout << endl; } void zamien(int &a, int &b) { //~cout << a << " " << b << endl; int tmp = a; a = b; b = tmp; //~cout << a << " " << b << endl; } void sort_bubble(int tab[], int n) { for (int j = n - 1; j > 0; j--) { for (int i = 0; i < j; i++) { if (tab[i] > tab[i+1]) zamien(tab[i], tab[i + 1]); //~zamien(tab, i); } } } int szukaj_bin_rek(int t[], int p, int k, int szukany) { if (p<=k) { int s = (p + k) / 2; if (t[s] == szukany) return s; if (t[s] > szukany) { return szukaj_bin_rek(t, p, s-1, szukany); } else { return szukaj_bin_rek(t, s+1, k, szukany); } } return -1; } int main(int argc, char **argv) { int n, szukany; cout << "Podaj ilość liczb: "; cin >> n; int t[n]; wypelnij(t, n); sort_bubble(t, n); drukuj(t, n); cout << "Podaj szukaną liczbę: "; cin >> szukany; cout << szukaj_bin_rek(t, 0, n-1, szukany); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2007 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef OUTPUTCONVERTER_H #define OUTPUTCONVERTER_H #include "modules/encodings/charconverter.h" /** Output converter interface */ class OutputConverter : public CharConverter { public: /** * Instantiates and returns a CharConverter object that can convert * from the internal string encoding to the given encoding. This * version uses the IANA charset identifier. * * If you are implementing your own conversion system (that is, have * FEATURE_TABLEMANAGER disabled, you will need to implement this * method on your own. Please note that there are several encoders * that are available without the TableManager that you should make * use of in your own implementation. * * @param charset Name of encoding. * @param obj * A pointer to the created object will be inserted here. * The pointer will be set to NULL if an error occurs. * @param iscanon * TRUE if name is already in canonized form (i.e if you have * already called CharsetManager::Canonize()). * @param allownuls * TRUE if export media can handle octet streams with nul octets. * If FALSE, UTF-8 will be used if UTF-16 is requested. * You need to query the returned CharConverter for its encoding. * @return * A status value. ERR_OUT_OF_RANGE if charset is invalid, * ERR_NULL_POINTER if obj is NULL, ERR_NOT_SUPPORTED if support * is disabled for this build, ERR_NO_MEMORY if an OOM error * occurred. ERR if some other error occured. */ static OP_STATUS CreateCharConverter(const char *charset, OutputConverter **obj, BOOL iscanon = FALSE, BOOL allownuls = FALSE); /** * @overload * @param charset Name of encoding. * @param obj * A pointer to the created object will be inserted here. * The pointer will be set to NULL if an error occurs. * @param iscanon * TRUE if name is already in canonized form (i.e if you have * already called CharsetManager::Canonize()). * @param allownuls * TRUE if export media can handle octet streams with nul octets. * If FALSE, UTF-8 will be used if UTF-16 is requested. * You need to query the returned CharConverter for its encoding. * @return * A status value. ERR_OUT_OF_RANGE if charset is invalid, * ERR_NULL_POINTER if obj is NULL, ERR_NOT_SUPPORTED if support * is disabled for this build, ERR_NO_MEMORY if an OOM error * occurred. ERR if some other error occured. */ static OP_STATUS CreateCharConverter(const uni_char *charset, OutputConverter **obj, BOOL iscanon = FALSE, BOOL allownuls = FALSE); /** * Instantiates and returns a CharConverter object that can convert * from the internal string encoding to the given encoding. This * version uses a charset ID as determined by * CharsetManager::GetCharsetID(). * * @param charsetID Charset ID identifying encoding. * @param obj * A pointer to the created object will be inserted here. * The pointer will be set to NULL if an error occurs. * @param allownuls * TRUE if export media can handle octet streams with nul octets. * If FALSE, UTF-8 will be used if UTF-16 is requested. * You need to query the returned CharConverter for its encoding. * @return * A status value. ERR_OUT_OF_RANGE if charset is invalid, * ERR_NULL_POINTER if obj is NULL, ERR_NOT_SUPPORTED if support * is disabled for this build, ERR_NO_MEMORY if an OOM error * occurred. ERR if some other error occured. */ static OP_STATUS CreateCharConverterFromID(unsigned short id, OutputConverter **obj, BOOL allownuls = FALSE); virtual const char *GetCharacterSet(); #if defined ENCODINGS_HAVE_SPECIFY_INVALID || defined ENCODINGS_HAVE_ENTITY_ENCODING OutputConverter(); #endif /** * Reset the encoder to initial state, writing any escape sequence or * similar necessary to make the current converted data self-contained. * * The output buffer must have at least the number of bytes available * returned by calling this function with a NULL parameter. This number * is always smaller than the number returned by * LongestSelfContainedSequenceForCharacter(). The number of bytes * that are required may vary according to the current state of the * encoder. * * The internal state of the encoder is changed when this method is * called with a non-NULL parameter. * * This method will NOT flush a surrogate code unit (non-BMP codepoint), * if such a code unit has been consumed as the last code unit, nor * will it reset the invalid character counter. To do this, call * Reset() after calling this method. * * @param dest A buffer to write to. Specifying NULL will just return * the number of bytes necessary. * @return The number of bytes (that would be) written to the output * buffer to make the current string self-contained. */ virtual int ReturnToInitialState(void *dest) = 0; /** * Reset the encoder to initial state without writing any data to the * output stream. Also remove any information about invalid characters * and any unconverted data in the buffer. * * The mode set by EnableEntityEncoding() is not changed. * * NB! If you call Reset during conversion, you may end up with invalid * output, only use this method if you are actually starting over. For * a more graceful reset operation, please use ReturnToInitialState(). */ virtual void Reset(); /** * Check space required (worst case) to add one UTF-16 code unit to the * output stream, and then call ReturnToInitialState(). This value may * vary according to the current state of the encoder. * * The number returned is (obviously) always larger than the number * returned by ReturnToInitialState(NULL). */ virtual int LongestSelfContainedSequenceForCharacter() = 0; #ifdef ENCODINGS_HAVE_SPECIFY_INVALID /** * Retrieve a string describing characters in the input that could not * be represented in the output. The character string is limited to * represent the 16 first unconvertible characters. * * @return Unconvertible characters. */ inline const uni_char *GetInvalidCharacters() const { return m_invalid_characters; } #endif #ifdef ENCODINGS_HAVE_ENTITY_ENCODING /** * Enable conversion of characters not available in the output encoding * as numerical entities. This is not strictly according to the HTML * specification, but is used by MSIE and accepted by most web based * forums. The default is not to use entities. * * @param enable TRUE to allow entities. */ inline void EnableEntityEncoding(BOOL enable) { m_entity_encoding = enable; } #endif protected: #ifdef ENCODINGS_HAVE_ENTITY_ENCODING BOOL m_entity_encoding; BOOL CannotRepresent(const uni_char ch, int input_offset, char **dest, int *written, int maxlen, const char *substitute = NULL); #endif #if defined ENCODINGS_HAVE_SPECIFY_INVALID || defined ENCODINGS_HAVE_ENTITY_ENCODING void CannotRepresent(const uni_char ch, int input_offset); #else inline void CannotRepresent(const uni_char, int input_offset) { ++m_num_invalid; if (m_first_invalid_offset == -1) m_first_invalid_offset = m_num_converted + input_offset; } #endif private: #ifdef ENCODINGS_HAVE_SPECIFY_INVALID uni_char m_invalid_characters[17]; ///< Unconvertible characters. /* ARRAY OK 2009-03-02 johanh - boundary checked */ #endif #if defined ENCODINGS_HAVE_SPECIFY_INVALID || defined ENCODINGS_HAVE_ENTITY_ENCODING uni_char m_invalid_high_surrogate; ///< Half of an unconvertible surrogate. #endif }; #endif // OUTPUTCONVERTER_H
#include <bits/stdc++.h> using namespace std; int G,N,i,j; int GCD ( int a, int b ) { int c; while ( a != 0 ) { c = a; a = b%a; b = c; } return b; } int main() { while(scanf("%d",&N)!=EOF){ if(N==0) break; G=0; for(i=1;i<N;i++) for(j=i+1;j<=N;j++) { G+=GCD(i,j); } printf("%d\n",G); } return 0; }
// // Param.cpp for Param in /home/paumar_a/projet/git/AW_like // // Made by cedric paumard // Login <paumar_a@epitech.net> // // Started on Sat Jul 26 17:43:53 2014 cedric paumard // Last update Mon Aug 4 17:30:14 2014 cedric paumard // #include "Param.hh" #include <fstream> #include <sstream> #include <iostream> Param::Param() { this->_size_x = MIN_SIZE_X; this->_size_y = MIN_SIZE_Y; this->_type_name = MT_CITY; this->_fog = BEGIN_FOG; this->initMapList(); } Param::~Param() { } void Param::initMapList() { this->_list_map.push_back(std::make_pair(std::string(NAME_MAP_01), std::string(PATH_MAP_01))); this->_list_map.push_back(std::make_pair(std::string(NAME_MAP_RAND), std::string("\0"))); this->_list_map.push_back(std::make_pair(std::string(NAME_MAP_CUST), std::string("\0"))); this->_list_unit.push_back(std::make_pair(std::string(NAME_UNIT_MAP), std::string(BEGIN_UNIT))); this->_list_unit.push_back(std::make_pair(std::string(NAME_MAP_RAND), std::string("\0"))); this->_list_unit.push_back(std::make_pair(std::string(NAME_MAP_CUST), std::string("\0"))); this->_ai.push_back(std::make_pair(AI_EASY, std::string("Easy"))); this->_ai.push_back(std::make_pair(AI_MEDIUM, std::string("Medium"))); this->_ai.push_back(std::make_pair(AI_HARD, std::string("Hard"))); this->_ai.push_back(std::make_pair(AI_PLAYER, std::string("Player"))); } void Param::assignUnit(const std::string unit) { std::ifstream file(unit.c_str(), std::ios::in); std::string str; std::string tmp; std::size_t pos; int nb; if (!file) { std::cerr << "Error: " << unit << ": opening failed" << std::endl; return; } while(getline(file, str)) { pos = str.find_first_of("="); std::istringstream (&str[pos + 1]) >> nb; tmp = str.substr(0, pos); this->_unit[tmp] = nb; } file.close(); } void Param::assignMap(std::string map) { std::ifstream file((map.c_str()), std::ios::in); std::string str; this->_map.clear(); if (!file) { std::cerr << "Error: " << map << ": opening failed" << std::endl; return; } file >> this->_size_x; file >> this->_size_y; while (getline(file, str)) { if (str[0] != '\0') this->_map = this->_map + str + '\n'; } std::cout << this->_size_x << " <=> " << this->_size_y << std::endl; std::cout << this->_map << std::endl; file.close(); }
#include <bits/stdc++.h> #define ll long long #define ull unsigned long long #define FOR(i,n) for(ll i=0;i<n;i++) #define FOR1(i,n) for(ll i=1;i<n;i++) #define FORn1(i,n) for(ll i=1;i<=n;i++) #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define mod 1000000007; using namespace std; int main() { // your code goes here fast; ll t; cin>>t; while(t--) { ll a,give=1,i=0,pro=0,tmp,sumc=0,suma=0,j=0; cin>>a; while(a>give || suma>sumc) { suma+=a; sumc+=give; if(suma>=sumc) j++; else break; tmp=a-give; if(tmp>0) i++; pro+=tmp; give*=2; //i++; } cout<<j<<" "<<i<<endl; } return 0; }
#include <asio.hpp> #include <iostream> #include "../include/sender.hpp" using asio::ip::tcp; int main() { asio::io_context io_context; Sender sender(io_context, "127.0.0.1", "3000"); // An explanation of the API // data_ready(): returns true if a message is available, otherwise false // get_msg(): gets an available message // request_msg(id): requests a message at id [0, NUM_MSGS) // You will need to make significant modifications to the logic below // As a starting point, run the server as follows: // ./server --no-delay --no-packet-drops which makes the below code work // As an example, you could start by requesting the first 10 messages int32_t curr_msg = 0; for (int i = 0; i < 10; i++) { sender.request_msg(i); curr_msg++; } while (true) { if (sender.data_ready()) { // Get a response Msg: // A Msg has a msg_id (corresponds to id in request_msg) and // a char array of CHUNK_SIZE (128) storing the data auto msg = sender.get_msg(); // Eventually, you will combine these chunks to write the file auto data_str = std::string(msg.data.data(), CHUNK_SIZE); // Print the msg id and message recieved (may be out of order) std::cout << "msg_id(" << msg.msg_id << ")::" << data_str << std::endl; } } return 0; }
#include<stdio.h> int main() { int i,n,max,sum; float aug; for(i=0;i++) scanf("%d",&i); for(i=0;i++) { sum+=i; aug=s } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*- ** ** Copyright (C) 2003 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Morten Stenshorne */ #ifndef X11_OPFILECHOOSER_H #define X11_OPFILECHOOSER_H #if !defined WIDGETS_CAP_WIC_FILESELECTION || !defined WIC_CAP_FILESELECTION typedef const class OpWindow SELECTOR_PARENT; class X11OpFileChooser : public OpFileChooser { public: OP_STATUS ShowOpenSelector(SELECTOR_PARENT *parent, const OpString &caption, const OpFileChooserSettings &settings); OP_STATUS ShowSaveSelector(SELECTOR_PARENT* parent, const OpString& caption, const OpFileChooserSettings &settings); OP_STATUS ShowFolderSelector(SELECTOR_PARENT *parent, const OpString &caption, const OpFileChooserSettings &settings); }; #endif // !WIDGETS_CAP_WIC_FILESELECTION || !WIC_CAP_FILESELECTION #endif // X11_OPFILECHOOSER_H
//Phoenix_RK /* https://leetcode.com/problems/pascals-triangle-ii/ Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. */ class Solution { public: vector<int> getRow(int rowIndex) { vector<int> res(rowIndex+1); res[0]=res[rowIndex]=1; if (rowIndex == 0 || rowIndex==1) return res; vector<int> prev = getRow(rowIndex-1); for (int i = 1; i<rowIndex; i++) { res[i] = prev[i-1] + prev[i]; } return res; } };
// // cross_validation.cpp // BPNN // // Created by Lnrd on 2018/7/14. // Copyright © 2018年 LNRD. All rights reserved. // #include "cross_validation.hpp" void cross_validate(BPNN& net, vector<sample>& v){ time_t start,stop; random_shuffle(v.begin(), v.end()); vector<double> max; vector<double> min; max_min(v, max, min); int partition_size = (int) v.size() / 10; int i = 0; vector<sample> training_set; vector<sample> test_set; double average_prec = 0.f; cout << endl << "start cross validating..." << endl; cout << "------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------" << endl; cout << "iteration\t|\t1\t|\t2\t|\t3\t|\t4\t|\t5\t|\t6\t|\t7\t|\t8\t|\t9\t|\t10\t" << endl; cout << "------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------" << endl; cout << "precision\t" ; cout.flush(); start = time(NULL); for(int iter = 0; iter < 10; iter++){ training_set.clear(); test_set.clear(); for(i = 0; i < iter * partition_size; i++){ training_set.push_back(v[i]); } for(i = iter * partition_size; i < (iter + 1) * partition_size; i++){ test_set.push_back(v[i]); } for(i = (iter + 1) * partition_size; i < partition_size * 10; i++){ training_set.push_back(v[i]); } net.initialize(); normalize(training_set, max, min); net.train(training_set, THRESHOLD); double prec = 0.f; for(i = 0; i < test_set.size(); i++){ string accurate = translate_result(test_set[i].out); normalize(test_set[i], max, min); net.predict(test_set[i]); string prediction = translate_result(test_set[i].out); if(accurate.compare(prediction) == 0){ prec += 1.f; } } prec /= test_set.size(); cout << "| " << setprecision(3) << prec * 100 << "%\t"; cout.flush(); average_prec += prec; } stop = time(NULL); cout << endl << "------------+-------+-------+-------+-------+-------+-------+-------+-------+-------+-------" << endl; average_prec /= 10; cout << "Takes " << (stop - start) << " seconds" << endl; cout << "Average precision: " << average_prec * 100 << "%" << endl << endl; }
template<typename T> struct Kruskal{ struct edge{ int u,v; T c; edge(){} edge(int x,int y,T z):u(x),v(y),c(z){} }; vector<edge>e; void clear(){e.clear();} void addedge(int u,int v,T c){e.emplace_back(edge(u,v,c));} T query(int n){ Dsu dsu;int cnt=0;T tot=0; sort(e.begin(),e.end(),[&](const edge&e1,const edge&e2){ return e1.c<e2.c; }); for(const auto&t:e){ if(dsu.join(t.u,t.v)){ ++cnt;tot+=t.c; } if(cnt+1==n) break; } return tot; } };
#include<bits/stdc++.h> using namespace std; char str[1000][1000]; int m, n; void dfs(int x, int y) { if(x<0 || y<0 || x==m || y==n)return; if(str[x][y]!='@')return; if(str[x][y]=='@')str[x][y]='*'; dfs(x, y+1); dfs(x, y-1); dfs(x+1, y); dfs(x-1, y); dfs(x+1, y+1); dfs(x+1, y-1); dfs(x-1, y+1); dfs(x-1, y-1); } main() { while(cin>>m>>n) { int i, j, total=0; if(m==0)break; for(i=0; i<m; i++) for(j=0; j<n; j++) cin>>str[i][j]; for(i=0; i<m; i++) for(j=0; j<n; j++) { if(str[i][j]!='*') { dfs(i, j); total++; } } cout<<total<<endl; } return 0; }
// Copyright 2011 Yandex #ifndef LTR_CROSSVALIDATION_VALIDATION_RESULT_H_ #define LTR_CROSSVALIDATION_VALIDATION_RESULT_H_ #include <string> #include <vector> #include "ltr/scorers/scorer.h" using std::string; using std::vector; namespace ltr { namespace cv { /** * For every split of crossvalidation done ValidationResult holds scorer * with it's learner's report and array of measure values on some test data */ class ValidationResult { public: /** * @param in_measure_names - names (aliases) of measures, which values * are held in ValidationResult */ explicit ValidationResult(const vector<string>& in_measure_names); /** * Adds information about one split - resulted scorer, learner's report * and values of measures * @param in_scorer - scorer, received by learner after it's work on train data * @param in_report - report of learner about scorer received * @param in_measure_value - measure values of recieved scorer on test data */ void addSplitInfo(Scorer::Ptr in_scorer, const string& in_report, const vector<double>& in_measure_value); /** * Returns number of splits, about which holds information ValidationResult */ size_t getSplitCount() const; /** * Gets scorer by split index */ Scorer::Ptr getScorer(int split_index) const; /** * Gets report by split index */ const string& getReport(int split_index) const; /** * Gets measure values by split index */ const vector<double>& getMeasureValues(int split_index) const; /** * Gets names (aliases) of measures, which values * are held in ValidationResult */ const vector<string>& getMeasureNames() const; private: /** * Holds whole information about one split */ struct OneSplitData { // now scorer here is not used // but holding it is cheap and could be useful in future Scorer::Ptr scorer; string report; vector<double> measure_values; /** * @param in_scorer - scorer, received by learner after it's work on train data * @param in_report - report of learner about scorer received * @param in_measure_value - measure values of recieved scorer on test data */ OneSplitData(Scorer::Ptr in_scorer, const string& in_report, const vector<double>& in_measure_value) : scorer(in_scorer), report(in_report), measure_values(in_measure_value) {} }; vector<OneSplitData> datas_; vector<string> measure_names; }; }; }; #endif // LTR_CROSSVALIDATION_VALIDATION_RESULT_H_
#include <iostream> #include <string> #include <fstream> #include <cstdlib> #include <sstream> bool parseArgs (int argc, char **argv, std::string& fnme, int& width, int& height) { if (argc != 4) { std::cout << "Usage: yuvtest yuvClip width height\n\n" << std::endl; return false; } fnme = argv [1]; width = std::atoi (argv [2]); height = std::atoi (argv [3]); return true; } bool savePpm (const std::string& fnme, char *p_frame, int width, int height) { std::ofstream ofs (fnme. c_str ()); if (!ofs) { std::cout << "Failed to write file " << fnme << std::endl; return false; } ofs << "P6\n" << width << " " << height << "\n255\n"; for (int h=0; h<height; ++h) { for (int w=0; w<width; ++w) { char c = p_frame [h*width + w]; ofs << c << c << c; } } ofs.close (); return true; } bool savePpmScaled (const std::string& fnme, char *p_frame, int width, int height, int scale, int padRows) { std::ofstream ofs (fnme. c_str ()); if (!ofs) { std::cout << "Failed to write file " << fnme << std::endl; return false; } ofs << "P6\n" << width*scale << " " << height*scale+padRows << "\n255\n"; char padPix=0; for (int pad=0; pad<padRows/2; ++pad) for (int w=0; w<width*scale; ++w) { ofs << padPix << padPix << padPix; } for (int h=0; h<height; ++h) { for (int sr=0; sr<scale; ++sr) { for (int w=0; w<width; ++w) { char c = p_frame [h*width + w]; for (int sc=0; sc<scale; ++sc) { ofs << c << c << c; } } } } for (int pad=0; pad<padRows-padRows/2; ++pad) for (int w=0; w<width*scale; ++w) { ofs << padPix << padPix << padPix; } ofs.close (); return true; } int main (int argc, char **argv) { std::string yuvFnme; int width, height; if (!parseArgs (argc, argv, yuvFnme, width, height)) { return 1; } std::ifstream ifs (yuvFnme. c_str (), std::ios::binary); if (!ifs) { std::cout << "Failed to open " << yuvFnme << std::endl; return 1; } int pixPerFrame = width * height * 3/2; int yPerFrame = width*height; int uvPerFrame = width*height/2; int dstWidth = 1280; int dstHeight = 800; int scale = 2; int padRows = dstHeight - height * scale; if (padRows < 0) padRows=0; char *p_yBuf = new char [yPerFrame]; char *p_uvBuf = new char [uvPerFrame]; int f=0; bool hasUv = true; while (1) { ifs. read (p_yBuf, yPerFrame); if (!ifs) { std::cout << "Failed to read y frame " << f << std::endl; break; } if (hasUv) { ifs. read (p_uvBuf, uvPerFrame); if (!ifs) { std::cout << "Failed to read uv frame " << f << std::endl; break; } } if (f%60==0) { std::stringstream ss; ss << "frame_" << f << ".ppm"; savePpm (ss.str (), p_yBuf, width, height); ss. str (""); ss << "sframe_" << f << ".ppm"; savePpmScaled (ss.str (), p_yBuf, width, height, scale, padRows); } ++f; } std::cout << "Total frames " << f << std::endl; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2008 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #ifndef _URL_LHN_H_ #define _URL_LHN_H_ // URL NameResolver Load Handlers class Comm; struct NameCandidate : public Link { private: NameCandidate(); /** * Second phase constructor. This method must be called prior to using the object, * unless it was created using the Create() method. */ OP_STATUS Construct(const OpStringC &prefix, const OpStringC &kernel, const OpStringC &postfix); public: OpString name; /** * Creates and initializes a NameCandidate object. * * @param namecandidate Set to the created object if successful and to NULL otherwise. * DON'T use this as a way to check for errors, check the * return value instead! * @param prefix * @param kernel * @param postfix * * @return OP_STATUS - Always check this. */ static OP_STATUS Create(NameCandidate **namecandidate, const OpStringC &prefix, const OpStringC &kernel, const OpStringC &postfix); virtual ~NameCandidate(){}; }; class URL_NameResolve_LoadHandler : public URL_LoadHandler { private: ServerName_Pointer base; AutoDeleteHead candidates; ServerName_Pointer candidate; Comm *lookup; URL *proxy_request; URL_InUse proxy_block; BOOL force_direct_lookup; /* char *permuted_host; char *permute_front; char *permute_end; char *permute_front_pos; char *permute_end_pos; const char *permute_template; struct{ BYTE checkexpandedhostname:1; BYTE name_completetion_mode:1; } info; */ private: void HandleHeaderLoaded(); void HandleLoadingFailed(MH_PARAM_1 par1, MH_PARAM_2 par2); void HandleLoadingFinished(); CommState StartNameResolve(); public: URL_NameResolve_LoadHandler(URL_Rep *url_rep, MessageHandler *mh); virtual ~URL_NameResolve_LoadHandler(); virtual void HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2); virtual CommState Load(); virtual unsigned ReadData(char *buffer, unsigned buffer_len); virtual void EndLoading(BOOL force=FALSE); virtual CommState ConnectionEstablished(); virtual void SetProgressInformation(ProgressState progress_level, unsigned long progress_info1, const void *progress_info2); }; #endif // _URL_LHN_H_
using namespace std; #include <stdio.h> #include <stdlib.h> #include <string> #include <netinet/in.h> #include <unistd.h> #include <sys/socket.h> #define PORT 8080 class connection { int socket_file_descriptor, domain, protocal; char communication_type; int connection_optional_level, connection_optional_name; int set_socket_option; // class constructor public: connection() { domain = AF_INET; protocal = 0; communication_type = SOCK_STREAM; socket_file_descriptor = NULL; connection_optional_level = 1; connection_optional_name = SOL_SOCKET; set_socket_option = NULL; } // This function creates socket for connection initialization public: int create_socket() { socket_file_descriptor = socket(domain, communication_type, protocal); if (socket_file_descriptor == 0) { perror("The socket unexpectedly refused to build up!"); exit(EXIT_FAILURE); } // force for socket bind on the defined PORT set_socket_option = setsockopt(socket_file_descriptor, connection_optional_name, SO_REUSEADDR | SO_REUSEPORT, &connection_optional_level, sizeof(connection_optional_level)); if (set_socket_option) { perror("The socket unexpectedly refused to rebuild up!"); exit(EXIT_FAILURE); } return socket_file_descriptor; } };
//program to print the pattern #include<iostream> #include<conio.h> using namespace std; int main() { int i,j,n=1; for(i=1;i<=4;i++) { for(j=1;j<=i;j++) { cout<<n; n++; } cout<<"\n"; } return 0; }
#include "VanzatorAnimale.h" #include <typeinfo> #include "VanzatorClienti.h" #include "animal.h" #include "sarpe.h" #include "iguana.h" #include "caine.h" #include "Pisica.h" #include "Iepure.h" #include "caracatita.h" #include "corb.h" #include "papagal.h" #include "foca.h" #include "peste.h" #include "porumbel.h" #include "testoasa.h" VanzatorAnimale* VanzatorAnimale::instance = NULL; unordered_map < int , queue <animal*> > VanzatorAnimale::Stoc; VanzatorAnimale* VanzatorAnimale::GetInstance() { if (!instance) { instance = new VanzatorAnimale(); } return instance; } VanzatorAnimale::VanzatorAnimale() { animal* c = new Papagal(); Stoc[1].push(c); animal* c1 = new Porumbel(); Stoc[2].push(c1); animal* c2 = new Corb(); Stoc[3].push(c2); animal* c3 = new Sarpe(); Stoc[4].push(c3); animal* c4 = new Iguana(); Stoc[5].push(c4); animal* c5 = new Testoasa(); Stoc[6].push(c5); animal* c6 = new Peste(); Stoc[7].push(c6); animal* c7 = new Foca(); Stoc[8].push(c7); animal* c8 = new Caracatita(); Stoc[9].push(c8); animal* c9 = new Pisica(); Stoc[10].push(c9); animal* c10 = new Caine(); Stoc[11].push(c10); animal* c11 = new Iepure(); Stoc[12].push(c11); } VanzatorAnimale::~VanzatorAnimale() { instance=NULL; } void VanzatorAnimale::cautare(animal* an) { Client* clt=NULL; VanzatorClienti* VztCl = VanzatorClienti::GetInstance(); if (VztCl->Stoc[an->getIDAnimal()].size()) { clt = VztCl->Stoc[an->getIDAnimal()].front(); VztCl->Stoc[an->getIDAnimal()].pop(); } if (clt!=NULL) { Inventariere(an,clt); } else { inserare(an); } } void VanzatorAnimale::inserare(animal* an) { an->TreceInCusca(); }
// // Created by manout on 18-3-4. // #ifndef ALOGRITHMS_RBTREE_H #define ALOGRITHMS_RBTREE_H template <typename Key, typename Value> class RBTree { public : using key_type = Key; using key_refer = Key&; using const_key_refer = const Key&; using key_pointer = Key*; using const_key_pointer = const Key*; using value_type = Value; using value_refer = Value&; using const_value_refer = const Value&; using value_pointer = Value*; using const_value_pointer = const Value*; value_pointer find(key_refer key); bool insert(key_refer key, value_refer value); void remove(key_refer key); private: enum Color { BLACK,RED }; struct RBNode { Key key; Value value; Color color = BLACK; RBNode* parent = nullptr; RBNode* left = nullptr; RBNode* right = nullptr; RBNode* grandparent(); RBNode* uncle(); RBNode* silbing(); void relplace(RBNode* n); RBNode(Key k, Value v):key(k), value(v){} }; using node_pointer = RBNode*; void left_rotate(node_pointer node); void right_rotate(node_pointer node); void fix_up(node_pointer node); node_pointer find_(key_refer key); void remove_(node_pointer node); node_pointer tree_max(node_pointer root); node_pointer tree_min(node_pointer root); void delete_case1(node_pointer node); void delete_case2(node_pointer node); void delete_case3(node_pointer node); void delete_case4(node_pointer node); void delete_case5(node_pointer node); void delete_case6(node_pointer node); private: static node_pointer nil = new RBNode(Key(), Value()); RBNode* root; int level; int count; }; template<typename Key, typename Value> RBTree::RBNode *RBTree<Key, Value>::RBNode::grandparent() { return this->parent->parent; } template<typename Key, typename Value> RBTree::RBNode *RBTree<Key, Value>::RBNode::uncle() { { if (this->parent == grandparent()->left) { return grandparent()->right; }else { return grandparent()->left; } } } template<typename Key, typename Value> RBTree::RBNode *RBTree<Key, Value>::RBNode::silbing() { if (this == this->parent->left) return this->parent->right; return this->parent->left; } template<typename Key, typename Value> void RBTree<Key, Value>::RBNode::relplace(RBTree::RBNode *n) { if (this->parent not_eq nullptr) { n->parent = this->parent; if (this == this->parent->left) { this->parent->left = n; }else { this->parent->right = n; } } } template<typename Key, typename Value> void RBTree<Key, Value>::left_rotate(RBTree::node_pointer node) { node_pointer y = node->right; node->right = y->left; if (y not_eq nil) { y->left->parent = node; } y->parent = node->parent; if (node->parent == nil) { this->root = y; }else if (node == node->parent->left) { node->parent->left = y; }else { node->parent->right = y; } y->left = node; node->parent = y; } template<typename Key, typename Value> void RBTree<Key, Value>::right_rotate(RBTree::node_pointer node) { node_pointer x = node->left; node->left = x->right; if (x not_eq nil) { x->right->parent = node; } x->parent = node->parent; if (x->parent == nil) { this->root = x; }else if (node == node->parent->right) { node->parent->right = x; }else { node->parent->left = x; } x->right = node; node->parent = x; } template<typename Key, typename Value> bool RBTree<Key, Value>::insert(key_refer key, value_refer value) { node_pointer curr_node = this->root; if (curr_node == nullptr) { this->root = new RBNode(key, value); this->root->left = nil; this->root->right = nil; this->root->color = Color::RED; return true; } while (curr_node->left not_eq nil and curr_node->right not_eq nil) { if (curr_node->key == key) { return false; }else if (curr_node->key < key) { curr_node = curr_node->right; }else if (curr_node->key > key) { curr_node = curr_node->left; } } if (curr_node->key == key) { return false; }else if (curr_node->key < key) { curr_node->right = new RBNode(key, value); curr_node->right->parent = curr_node; curr_node->right->left = curr_node->right = nil; curr_node->right->color = Color::RED; fix_up(curr_node->right); }else if (curr_node->key > key) { curr_node->left = new RBNode(key, value); curr_node->left ->parent = curr_node; curr_node->left->left = curr_node->right = nil; curr_node->left->color = Color::RED; fix_up(curr_node->left); } return true; } template<typename Key, typename Value> void RBTree<Key, Value>::fix_up(RBTree::node_pointer node) { /** case 1: the new node is the root*/ if (node->parent == nullptr) { node->color = Color::BLACK; return; } /** case 2: the new node's parent node is black*/ if (node->parent->color == Color::BLACK) { /** nothing to do*/ return ; } /** case 3: the new node's parent and it's uncle is both red*/ if (node->uncle() not_eq nullptr and node->uncle()->color == Color::RED) { node->parent->color = Color::BLACK; node->uncle()->color = Color::BLACK; node->grandparent()->color = Color::RED; fix_up(node->grandparent()); return ; } /** case 4: the new node is a right node and it's parent is a left node*/ if (node == node->parent->right and node->parent == node->grandparent()->left) { left_rotate(node->parent); node = node->left; }/** the new node is a left node and it's parent is a right node*/ else if (node == node->parent->left and node->parent == node->grandparent()->right) { right_rotate(node->parent); node = node->right; } /** case 5: the new node's parent is red and it's uncle is black or missing, the new * node is a left node and the it's parent is also a left node, do the left * rotate to the grandparent node , * or the opposite, * the new node is right node and it's parent is also a right node * do the right rotate to the grandparent * */ node->parent->color = Color::BLACK; node->grandparent()->color = Color::RED; if (node == node->parent->left and node->parent == node->grandparent()->left) { right_rotate(node->grandparent()); }else { left_rotate(node->grandparent()); } } template<typename Key, typename Value> node_pointer RBTree<Key, Value>::find_(Key &key) { node_pointer curr_node = this->root; while (curr_node->left not_eq nil and curr_node->right not_eq nil) { if (curr_node->key == key) { return curr_node; } if (curr_node->key < key) { curr_node = curr_node->right; }else { curr_node = curr_node->left; } } if (curr_node->left not_eq nil) { if (curr_node->left->key == key) return curr_node->left; else return nullptr; } else if (curr_node->right not_eq nil) { if (curr_node->right->key == key) return curr_node->right; } return nullptr; } template<typename Key, typename Value> RBTree::value_pointer RBTree<Key, Value>::find(Key &key) { return &find_(key)->value; } template<typename Key, typename Value> void RBTree<Key, Value>::remove(Key &key) { node_pointer node = find_(key); if (node == nullptr)return ; node_pointer max_node = tree_max(node); node->key = max_node->key; node->value = max_node->value; remove_(max_node); } template<typename Key, typename Value> RBTree::node_pointer RBTree<Key, Value>::tree_max(RBTree::node_pointer root) { while (root->right not_eq nil) { root = root->right; } return root; } template<typename Key, typename Value> RBTree::node_pointer RBTree<Key, Value>::tree_min(RBTree::node_pointer root) { while (root->left not_eq nil) { root = root->left; } return root; } template<typename Key, typename Value> void RBTree<Key, Value>::remove_(RBTree::node_pointer node) { /** the node must have one non null child*/ node_pointer son = node->left == nil ? node->right : node->left; node->relplace(son); if (node->color == Color::BLACK) { if (son->color == Color::RED) { son->color = Color ::BLACK; }else { delete_case1(son); } } delete node; } template<typename Key, typename Value> void RBTree<Key, Value>::delete_case1(RBTree::node_pointer node) { /** case 1: the node is red, just delete it and return*/ if (node->parent not_eq nullptr) delete_case2(node); } template<typename Key, typename Value> void RBTree<Key, Value>::delete_case2(RBTree::node_pointer node) { node_pointer sibling = node->silbing(); if (sibling->color == Color::RED) { node->parent->color = Color ::RED; sibling->color = Color ::BLACK; if (node == node->parent->left) { left_rotate(node->parent); }else { right_rotate(node->parent); } } delete_case3(node); } template<typename Key, typename Value> void RBTree<Key, Value>::delete_case3(RBTree::node_pointer node) { node_pointer silbing = node->silbing(); if (node->parent->color == BLACK and silbing->color == BLACK and silbing->left->color == BLACK and silbing->right->color == BLACK) { silbing->color = Color ::RED; delete_case1(node->parent); }else { delete_case4(node); } } template<typename Key, typename Value> void RBTree<Key, Value>::delete_case4(RBTree::node_pointer node) { node_pointer silbing = node->silbing(); if (node->parent->color == RED and silbing->color == BLACK and silbing->left->color == BLACK and silbing->right->color == BLACK) { silbing->color = Color ::RED; node->parent->color = Color ::RED; }else { delete_case5(node); } } template<typename Key, typename Value> void RBTree<Key, Value>::delete_case5(RBTree::node_pointer node) { node_pointer sibling = node->silbing(); if (sibling->color == RED) { if (node == node->parent->left and sibling->left->color == RED and sibling->right->color == BLACK) { sibling->color = RED; sibling->left->color = BLACK; right_rotate(sibling); }else if (node == node->parent->right and sibling->left->color == BLACK and sibling->right->color == RED) { sibling->color = RED; sibling->right->color = BLACK; left_rotate(sibling); } } delete_case6(node); } template<typename Key, typename Value> void RBTree<Key, Value>::delete_case6(RBTree::node_pointer node) { node_pointer sibling = node->silbing(); sibling->color = node->parent->color; node->parent->color = BLACK; if (node == node->parent->left) { sibling->right->color = BLACK; left_rotate(node->parent); }else { sibling->left->color = BLACK; right_rotate(node->parent); } } #endif //ALOGRITHMS_RBTREE_H
#include "Teki.hpp" #include "Barrage.hpp" #include "Bullet.hpp" #include "CollisionCircle.hpp" #include "define.hpp" #include "Central.hpp" #include "TitleScene.hpp" #include "UseDxLib.hpp" namespace game { Teki::Teki() :m_barrage(std::make_unique<Barrage>(200)), m_collision(std::make_unique<CollisionCircle>(GetRefPos())) { //あたり判定の設定 m_collision->SetCollisionID(CollisionID::TekiID); m_collision->SetR(7); m_collision->SetOffsetPos(Vec2(8, 8)); SetPos( WINDOW_W / 2,30); SetSpeed(2); SetAddPos(GetSpeed(), 0); } Teki::~Teki() { } void Teki::Update() { //弾幕の処理 if (m_hp > 20) { TekiBarrage1(); mode = 0; } else if (m_hp > 0) { mode = 1; ModeCheck(); TekiBarrage2(); } //衝突したオブジェクトの処理 m_collision->GetColliBuf([&hp=m_hp](CollisionID id) { if (id == CollisionID::PlayerBulletID) hp--; }); if (m_hp <= 0) Central::GetInstance().ChangeScene(std::make_unique<TitleScene>()); //移動 SetPos(GetPos()+GetAddPos()); if (GetPos().x > WINDOW_W - 16 || GetPos().x < 0)SetAddPos(-GetAddPos().x,0); //弾リスト更新 m_barrage->Update(); //敵文字描画 DxLib::DrawString(GetPos().x,GetPos().y,"敵",DxLib::GetColor(255,255,255)); } void Teki::ModeCheck() noexcept { if (beforMode != mode) {cont = 0; beforMode = mode; } } void Teki::TekiBarrage1() { cont++; if (cont % 20 == 0) { BulletInfo bInfo; bInfo.pos = GetPos(); bInfo.addPos = { 0,7 }; bInfo.id = CollisionID::TekiBulletID; m_barrage->AddMakeBullet(bInfo); } } void Teki::TekiBarrage2() { cont++; if (cont % 28 == 0) { BulletInfo bInfo[3]; bInfo[0].addPos = {0,2.5}; bInfo[1].addPos = { cos(120.0 / 180 * PI)*2.5,sin(120.0 / 180 * PI)*2.5 }; bInfo[2].addPos = { cos(60.0 / 180 * PI)*2.5,sin(60.0 / 180 * PI)*2.5 }; for (int i = 0; i < 3; i++) { bInfo[i].id = CollisionID::TekiBulletID; bInfo[i].pos = GetPos(); m_barrage->AddMakeBullet(bInfo[i]); } } } }
/************************************************************************************** * File Name : ChatBox.cpp * Project Name : Keyboard Warriors * Primary Author : JeongHak Kim * Secondary Author : * Copyright Information : * "All content 2019 DigiPen (USA) Corporation, all rights reserved." **************************************************************************************/ #include <GL/glew.h> #include "ChatBox.hpp" #include "Shader.h" #include "Mesh.h" #include "Draw.hpp" #include "PATH.hpp" void ChatBox::Initialize(mat3<float> world_to_ndc) noexcept { worldToNDC = world_to_ndc; chatBoxShader.LoadShapeShader(); textShader.LoadTextShader(); chatBoxTransform.SetTranslation({ -430.0f, -250.0f }); chatBoxTransform.SetScale({ 330.0f, 170.0f }); textTransform.SetTranslation({ -430.0f, -250.0f }); chatBox.CreateShape(chatBoxShader, MESH::create_rectangle({ 0.0f }, { 1.0f }, chatBoxColor), worldToNDC * chatBoxTransform.GetModelToWorld()); bitmapFont.LoadFromFile(PATH::bitmapfont_fnt); text.SetFont(bitmapFont); } void ChatBox::AddHistory(std::wstring message) noexcept { if (index == 3) { history.at(2) = history.at(1); history.at(1) = history.at(0); history.at(0) = message; } else { history.at(index) = message; ++index; } } void ChatBox::DrawMessageBox() noexcept { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); Draw::DrawShape(chatBox); glDisable(GL_BLEND); if (index != 0) { std::wstring something; for (int i = 0; i < index; ++i) { something += history.at(i) + L'\n'; } something.pop_back(); text.SetString(something); Draw::DrawText(textShader, worldToNDC * textTransform.GetModelToWorld(), text); } }
#ifndef CSoftInstallMessage_H #define CSoftInstallMessage_H #include "CMessage.h" #include <QObject> //Ãŵê±àºÅ×¢²á class CSoftInstallMessage : public CMessage { Q_OBJECT public: CSoftInstallMessage(CMessageEventMediator* pMessageEventMediator, QObject *parent = 0); ~CSoftInstallMessage(); virtual void packedSendMessage(NetMessage& netMessage); virtual bool treatMessage(const NetMessage& netMessage, CMessageFactory* pFactory, SocketContext* clientSocket); protected: QString m_strName; QString m_strVersion; bool m_bAddSuccess; }; #endif // CSoftInstallMessage_H
#ifndef Interactions_h #define Interactions_h 1 class Interactions { public: Interactions(); ~Interactions(); public: void AddComptonInteractionPerVolume(G4int pos, G4int vol); void globalTimePerVolume(G4int pos, G4double gtime); void localTimePerVolume(G4int pos, G4double ltime); void Analysis(void); void Clear(void); void Print(void); //! Increase the Compton interactions counter inline void AddComptonInteraction(void){Num_Compton_Int++;}; inline G4int GetComptonInteraction(void){return Num_Compton_Int;}; //! Assign the forced ID for gamma of 1275, 511 and 511 keV inline void SetGammaID(G4int gamma_id){gamma_ID=gamma_id;}; inline void SetGammaID_real(G4int gamma_id){gamma_ID_real=gamma_id;}; inline G4int GetGammaID(void){return gamma_ID;}; inline G4int GetGammaID_real(void){return gamma_ID_real;}; //! Volumes counter inline void AddVolumeCounter(void){vol_counter++;}; inline G4int GetVolumeCounter(void){return vol_counter;}; inline G4int* GetVolume(void){return Volume;}; inline G4double* GetglobalTime(void){return globalTime;}; inline G4double* GetlocalTime(void){return localTime;}; //! Good event inline void Set_good_event_flag(G4bool flag){good_event_flag=flag;}; inline G4bool Get_good_event_flag(void){return good_event_flag;}; public: G4int NumberOfVolumes; G4int vol_counter; private: //! Volume when the Compton interaction occurs, each volume has o unique ID G4int* Volume; G4double* globalTime; G4double* localTime; //! Number of Compton interactions in Soil or/and object, or plates. 1275, 511 and 511 keV G4int Num_Compton_Int; //! Forced ID for gamma of 1275, 511 and 511 keV G4int gamma_ID; G4int gamma_ID_real; G4bool good_event_flag; }; #endif
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> 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 N 777 int n, m; int pr[N]; int was[N][N]; int conn; struct Tp { int x, y; } a[N]; int fs(int x) { if (pr[x] != x) pr[x] = fs(pr[x]); return pr[x]; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); scanf("%d", &n); for (int i= 0; i < n; ++i) { scanf("%d%d", &a[i].x, &a[i].y); } for (int i = 1; i <= n; ++i) pr[i] = i; conn = 0; scanf("%d", &m); for (int i = 0; i < m; ++i) { int x, y; scanf("%d%d", &x, &y); --x; --y; was[x][y] = was[y][x] = 1; if (fs(x) != fs(y)){ pr[fs(x)] = fs(y); ++conn; } } vector< pair<int, pair<int, int> > > e; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (!was[i][j]) { e.push_back(make_pair(sqr(a[i].x - a[j].x) + sqr(a[i].y - a[j].y), make_pair(i, j))); } } } sort(e.begin(), e.end()); for (int i = 0; i < e.size() && conn < n - 1; ++i) { int x = e[i].second.first; int y = e[i].second.second; if (fs(x) != fs(y)) { pr[fs(x)] = fs(y); ++conn; printf("%d %d\n", x + 1, y + 1); } } return 0; }
#include<bits/stdc++.h> using namespace std; char c[1000]; int cont; int main() { while(gets(c)) { for(int i=0;c[i];i++) { if(isalpha(c[i]) && !isalpha(c[i+1])) cont++; } cout<<cont<<endl; cont=0; } }
#ifndef _NFA_H_ #define _NFA_H_ #include <string> #include <memory> namespace my_regex{ // 如果VS版本是2015 // 则字符用utf32表示,省的麻烦 #if _MSC_VER < 1900 typedef char my_char; typedef std::string my_string; #else typedef char32_t my_char; typedef std::u32string my_string; #endif class nfa_node; typedef std::shared_ptr<nfa_node> p_nfa_node; typedef std::shared_ptr<const nfa_node> cp_nfa_node; class NFA { public: NFA() = delete; explicit NFA(const my_string &reg) :reg(reg) { create_nfa_node(reg); } public: // 生成一个dot文件 // 可以用graphviz工具来将dot文件转化为pdf等格式 // 如 dot -Tpdf -o file.pdf file.dot void create_dot_file(const my_string &filename); // 利用生成的NFA来尝试匹配一个字符串str // 返回匹配到第几个字符 size_t try_match(const my_string &str); void set_reg(const my_string &_reg) { reg = _reg; create_nfa_node(reg); } private: // 从一个正则表达式reg生成NFA void create_nfa_node(const my_string &reg); cp_nfa_node start; my_string reg; }; } #endif // _NFA_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef WINDOWSCOMMON_PLUGINWINDOW_H #define WINDOWSCOMMON_PLUGINWINDOW_H #ifdef _PLUGIN_SUPPORT_ #include "modules/libgogi/pi_impl/mde_opview.h" #include "modules/libgogi/pi_impl/mde_native_window.h" class WindowsPluginNativeWindow : public MDENativeWindow { public: WindowsPluginNativeWindow(const MDE_RECT &rect, HWND win, HWND global_hwnd, HINSTANCE global_instance); ~WindowsPluginNativeWindow(); void SetParent(HWND parent); void DelayWindowDestruction() { m_hwnd = NULL; } HWND GetTransparentWindow() { return m_transwin; } virtual void MoveWindow(int x, int y); virtual void ResizeWindow(int w, int h); virtual void UpdateWindow(); virtual void ShowWindow(BOOL show); virtual void SetRedirected(BOOL redir); virtual void UpdateBackbuffer(OpBitmap* backbuffer); virtual void SetClipRegion(MDE_Region* rgn); /** * Call Updating(TRUE) before calling function that can trigger * WM_WINDOWPOSCHANGING message or other similar that we want * to handle only when call is made from Opera. Remember to call * Updating(FALSE) after. */ void Updating(BOOL update) { m_updating = update; } /** * Can be called inside window procedure for example to check * if given message was triggered by Opera. Might be used to filter * out messages sent by plugins that try to change position, size or * visibility of our (plugin) windows. */ BOOL IsBeingUpdated() { return m_updating; } private: HWND m_hwnd; HWND m_parent_hwnd; HINSTANCE m_global_instance; HWND m_transwin; HBITMAP m_native_backbuffer; HDC m_backbuffer_dc; HDC m_transwin_dc; int m_native_backbuffer_width; int m_native_backbuffer_height; BOOL m_reparent_to_transwin; BOOL m_updating; // Used to work around scrolling artifact when having gdi window as a child of directx // window static HBITMAP dummyBitmap; static HDC dummyDC; }; #endif // _PLUGIN_SUPPORT_ #endif // WINDOWSCOMMON_PLUGINWINDOW_H
#include <functional> #include <queue> #include <vector> #include <iostream> #include <map> using namespace std; vector<int> twoSum(vector<int>& nums, int target) { map<int,int> index; for(int i=0; i<nums.size(); ++i) { index[nums[i]] = i; cout << nums[i] << "==>" << i << endl; } for(int i=0; i<nums.size(); ++i) { auto it = index.find(target-nums[i]); cout << "target: " << target << ", curr num: " << nums[i] << endl; if (it != index.end() && it->second != i) { cout << "Found: " << i << ": " << it->second << endl; return vector<int>{i, it->second}; } } return vector<int>(); } int main() { vector<int> v{3,2,4}; twoSum(v, 6); return 0; }
// C++ equivalent for exon_ChIP_extract_from_TagAlign.py // // Takes a config file with only one window parameter which is the number of // base pairs before and after the locations that will be counted. #include "rapidjson/document.h" #include "rapidjson/writer.h" #include "rapidjson/stringbuffer.h" #include <iostream> #include <fstream> #include <string> #include <tuple> #include <vector> #include <deque> #define RECENT_LINES_BUFFER_LENGTH 5000 using namespace rapidjson; using namespace std; // parse input line // lines of tagAlign file are 6 tab-separated fields. // We are about the first and second, which are the chromosome // and offest // On success return 1, if end of file or error, return 0 int get_read_loc(tuple<int,int>&loc, ifstream & ChIP_file, Document & chr_order){ string throw_away; // string to hold un-used values at end of lines string ChIP_chr_str; string ChIP_loc_str; getline(ChIP_file,ChIP_chr_str,'\t'); getline(ChIP_file,ChIP_loc_str,'\t'); if (! getline(ChIP_file,throw_away)){ cerr << "getline return 0 when reading ChIP_file" << endl; return 0; } // read in the site position and interpret it as a decimal integer. int ChIP_chr=chr_order[ChIP_chr_str.c_str()].GetInt(); int ChIP_loc=stoi(ChIP_loc_str); loc=tuple <int,int>(ChIP_chr,ChIP_loc); // loc=tuple <int,int>(0,0); return 1; } void reverse(vector <int> & vec){ vector<int> tmp(vec.size()); for (int x =vec.size()-1; x >= 0;--x){ tmp[x]= vec[vec.size()-x-1]; } vec=tmp; } int main(int argc, char** argv) { if (argc != 6){ cerr << "invalid usage: ./chip_extract <config.json> <sample_ID> <Mark_ID> <sites.json> <chipreads.TagAlign>" <<endl; exit(1); } char *config_fn=argv[1]; char *sampleID=argv[2]; char *MarkID=argv[3]; char *sites_fn=argv[4]; char *ChIP_fn=argv[5]; // Open and parse config file ifstream config_file; config_file.open(config_fn); if (!config_file.is_open()){ cerr << "could not open config file <" << config_fn << ">" << endl; exit(1); } // Read config file and parse into JSON format string config_line; getline(config_file,config_line); Document config; config.Parse(config_line.c_str()); config_file.close(); string chr_order_fn = config["chromosome_order_fn"].GetString(); int window_size = config["window_size"].GetInt(); // The number of windows of window_size base pairs before and after the // locations provided around which reads are counted int num_windows = config["num_windows_per_side"].GetInt(); // Open and parse chromosome order file ifstream chr_file; chr_file.open(chr_order_fn); if (!chr_file.is_open()){ cerr << "could not open chromosome order file <"<< chr_order_fn <<">" << endl; exit(1); } string chr_line; getline(chr_file,chr_line); Document chr_order; chr_order.Parse(chr_line.c_str()); chr_file.close(); // open file of ordered site locations int buff_size=100000; ifstream sites_file; // char *sites_buff = new char[buff_size]; char sites_buff [buff_size]; sites_file.rdbuf()->pubsetbuf(sites_buff,buff_size); sites_file.open(sites_fn); if (!sites_file.is_open()){ cerr << "could not open file with sites to label <"<< sites_fn <<">" << endl; exit(1); } string site_line; getline(sites_file,site_line); Document current_site; current_site.Parse(site_line.c_str()); string site_chr=current_site["seqname"].GetString(); // read in the site position and interpret it as a decimal integer. //int site_pos=stoi(current_site["five_p_loc"].GetString()); int site_pos=current_site["location"].GetInt(); int site_chr_val = chr_order[site_chr.c_str()].GetInt(); tuple<int,int> site_strt(site_chr_val,site_pos-window_size*num_windows); tuple<int,int> site_end(site_chr_val,site_pos+window_size*num_windows); // create a vector to hold the read counts for every window that is twice // 'num_windows' because it must hold reads on both sides of the site. vector<int> site_reads(num_windows*2); for (int x= 0; x < site_reads.size();++x) site_reads[x]=0; // zero it out // open up the TagAlign file ifstream tag_align_file; // char *buff = new char[buff_size]; char buff [buff_size]; tag_align_file.rdbuf()->pubsetbuf(buff,buff_size); tag_align_file.open(ChIP_fn); if (!tag_align_file.is_open()){ cerr << "could not open tagAlign file <"<< ChIP_fn <<">" << endl; exit(1); } int count=0; tuple<int,int> ChIP_read_loc(0,0); string throw_away; // string to dump ends of lines that are unused into do{ // print every million or so lines. if (!(++count % (1<< 20)) ) cerr << "line: " << count <<" \n"; if (!get_read_loc(ChIP_read_loc,tag_align_file,chr_order)){ cerr << "get_read_loc returned 0, exitting now" << endl; exit(0); } // if the the read is before the current site, continue to the next read if (ChIP_read_loc < site_strt) continue; // if the read is with the range of the current site add it to the count. if (ChIP_read_loc <= site_end) { int bin_idx = int((get<1>(ChIP_read_loc)-get<1>(site_strt))/window_size); if( bin_idx == 2*num_windows) --bin_idx; site_reads[bin_idx]+=1; continue; } //at this point we know the read is past the current site, so we must move to the next site. if (current_site["strand"].GetInt() == -1){ reverse(site_reads); } cout << site_chr << string("\t") << site_pos << string("\t") << sampleID << string("\t") << MarkID << "\t[" ; for (int x= 0; x < site_reads.size()-1;++x) cout << site_reads[x] << string(", "); cout <<site_reads[site_reads.size()-1]; cout << string("]") ; cout << endl; // cout<< "#" << current_site["five_p_loc"].GetString() << endl; /* Value &sample_dict = current_site[sample_ID]; string sample_json= sample_dict.GetString(); Document new_sample_doc; new_sample_doc.Parse(sample_json); Value myArray(kArrayType); myArray.SetObject(); Document::AllocatorType& allocator = new_sample_doc.GetAllocator(); for ( int i = 0; i < site_reads.size();++i){ myArray.PushBack(site_reads[i],allocator); } */ // trace back in case windows are overlapping int dist_to_go_back = int(tag_align_file.tellg())>10000? 10000:int( tag_align_file.tellg()); tag_align_file.seekg(-dist_to_go_back,tag_align_file.cur); if (!getline(tag_align_file,throw_away)){ cerr << "error after seeking back in tag align file" <<endl; exit(1); } // first print out the current site with the new read count info if (!getline(sites_file,site_line)) break; current_site.Parse(site_line.c_str()); // reset site_reads for (int x= 0; x < site_reads.size();++x) site_reads[x]=0; // zero it out site_chr=current_site["seqname"].GetString(); site_pos=current_site["location"].GetInt(); //site_pos=stoi(current_site["five_p_loc"].GetString()); site_chr_val = chr_order[site_chr.c_str()].GetInt(); site_strt=tuple<int,int>(site_chr_val,site_pos-window_size*num_windows); site_end=tuple<int,int> (site_chr_val,site_pos+window_size*num_windows); }while (true); sites_file.close(); tag_align_file.close(); return 0; }
/* Write a recursive function to convert a given string into the number it represents. That is input will be a numeric string that contains only numbers, you need to convert the string into corresponding integer and return the answer. Input format : Numeric string S (string, Eg. "1234") Output format : Corresponding integer N (int, Eg. 1234) Constraints : 0 <= |S| <= 9 where |S| represents length of string S. Sample Input 1 : 00001231 Sample Output 1 : 1231 Sample Input 2 : 12567 Sample Output 2 : 12567 */ #include<bits/stdc++.h> using namespace std; int stringToInt(char input[]){ int intvalue = atoi(input); return intvalue; } int main(){ char input[50]; cin>>input; cout<<stringToInt(input)<<endl; return 0; }
#include "pch.h" #include "followingEnemy.h" followingEnemy::followingEnemy() { m_hasColided = false; reachedEdge = true; scorpionSpawnPos = XMVectorSet(0.0f, 0.0f, 0.0f, 0.0f); } void followingEnemy::init(bool colidable, int wvpCBufferIndex, Model* mdl, Player *player) { initializeDynamic(colidable, false, wvpCBufferIndex, 16, DirectX::XMFLOAT3(1, 1, 1), DirectX::XMFLOAT3(0, 0, 0), mdl); thePlayer = player; XMFLOAT3 scorpionPos; XMStoreFloat3(&scorpionPos, getMoveCompPtr()->position); XMFLOAT4 scorpionRot; XMStoreFloat4(&scorpionRot, getMoveCompPtr()->rotation); scorpionBB = BoundingOrientedBox(scorpionPos, XMFLOAT3(1.2f, 2.f, 1.2f), scorpionRot); } void followingEnemy::update(float dt) { followPlayer(dt); scorpionBB.Center = XMFLOAT3(getMoveCompPtr()->position.m128_f32[0], getMoveCompPtr()->position.m128_f32[1], getMoveCompPtr()->position.m128_f32[2]); XMVECTOR aRotation = XMQuaternionRotationRollPitchYawFromVector(getMoveCompPtr()->rotation); XMFLOAT4 rot; XMStoreFloat4(&rot, aRotation); scorpionBB.Orientation = rot; } void followingEnemy::onPlayerColide() { } void followingEnemy::setReachedEdge(bool aValue) { reachedEdge = aValue; } BoundingOrientedBox* followingEnemy::getBB() { return &scorpionBB; } bool followingEnemy::getReachedEdge() { return reachedEdge; } void followingEnemy::followPlayer(float dt) { XMVECTOR walkDirection; XMVECTOR playerPosition; XMVECTOR previousPosition; XMVECTOR scorpionPos = getMoveCompPtr()->position; if (getSpawnPosOnce == false) { scorpionSpawnPos = getMoveCompPtr()->position; getSpawnPosOnce = true; } XMVECTOR upDir = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); XMVECTOR playerRotation = thePlayer->getMoveCompPtr()->rotation; float playerRotationY = XMVectorGetY(playerRotation); playerPosition = thePlayer->getMoveCompPtr()->position; playerPosition = XMVectorSetY(playerPosition, 5.f); previousPosition = playerPosition; XMVECTOR walkBackDirection; walkBackDirection = scorpionSpawnPos - scorpionPos; walkBackDirection = XMVector3Normalize(walkBackDirection); walkDirection = playerPosition -scorpionPos; walkDirection = XMVector3Normalize(walkDirection); if ( reachedEdge == false) { getMoveCompPtr()->position += (walkDirection * dt * 9); float targetRotation = (float)atan2((double)(walkDirection.m128_f32[0]), (double)(walkDirection.m128_f32[2])) + XM_PI; float rotationDifference = targetRotation - currentRotationY; if (rotationDifference < XM_PI ) { rotationDifference -= (float)XM_PI * 2; } if (rotationDifference > -XM_PI ) { rotationDifference += (float)XM_PI * 2; } currentRotationY += (rotationDifference)*dt * 5; getMoveCompPtr()->rotation = XMVectorSet(0.0f, currentRotationY, 0.0f, 0.0f); } else { if (XMVectorGetX(walkBackDirection) <= 0.f && XMVectorGetY(walkBackDirection) <= 0.f && XMVectorGetZ(walkBackDirection) <= 0.f) { getMoveCompPtr()->rotation = XMVectorSet(0.0f, XMConvertToRadians(180.0f), 0.0f, 0.0f); } else { getMoveCompPtr()->position += (walkBackDirection * dt * 9); float targetRotation = (float)atan2((double)(walkBackDirection.m128_f32[0]), (double)(walkBackDirection.m128_f32[2])) + XM_PI; float rotationDifference = targetRotation - currentRotationY; if (rotationDifference < XM_PI) { rotationDifference -= (float)XM_PI * 2; } if (rotationDifference > -XM_PI) { rotationDifference += (float)XM_PI * 2; } currentRotationY += (rotationDifference)*dt * 5; getMoveCompPtr()->rotation = XMVectorSet(0.0f, currentRotationY, 0.0f, 0.0f); } } }
#ifndef ZOO_SCENE_ #define ZOO_SCENE_ #include "cocos2d.h" #include "ui\UIScale9Sprite.h" class ZooScene : public cocos2d::Layer { public: static cocos2d::Scene* createScene(); virtual bool init(); CREATE_FUNC(ZooScene); void timer(float t); void pretimer(float t); bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); void addDog(); private: void ShowAnimal(std::string animal); cocos2d::Sprite* Girl; cocos2d::Sprite* Mother; cocos2d::SpriteFrame* StandMother; cocos2d::Sprite* Background; cocos2d::Sprite* Peacock; cocos2d::Sprite* MovingPeacock; cocos2d::Sprite* Dog; cocos2d::SpriteFrame* InvertGirl; cocos2d::Vector<cocos2d::SpriteFrame *> WGV; cocos2d::Vector<cocos2d::SpriteFrame*> WMV; cocos2d::Vector<cocos2d::SpriteFrame*> WPV; //cocos2d::Texture2D* PeaTexture[8]; cocos2d::Vector<cocos2d::SpriteFrame *> WDV; cocos2d::Label* warning; int peacockSeq; bool isWarningMother; bool isMotherWalk; float BGlen; int steps; int countTime; int countWord; bool atAnimal; bool atPeacock; float BodyWidth; bool touchMother; bool beginLost; bool askMother; bool isGirlRun; bool touchDog; bool isDogTime; bool isDogExist; bool isDogStay; bool isGirlInvert; bool isAnimalShow; int starNum; cocos2d::Sprite* star; cocos2d::Sprite* starTalk; cocos2d::LabelTTF* grades; cocos2d::Size visibleSize; cocos2d::ui::Scale9Sprite* AnimalDia; cocos2d::Dictionary* sentence; cocos2d::LabelTTF* Word; }; #endif
#include "ComputeMovingAverage.hpp" std::vector<double> ComputeMovingAverage (const std::vector<double> & Values, std::vector<double>::size_type p) { ///////////////////////////////////////////////////////////////////// /// Your implementation for question 5 std::vector<double>::size_type N = Values.size(); // optimisation in case p == 1u if (p == 1u) { return Values; } // local variable to store the values, a copy of which gets returned std::vector<double> RunningMeanP; if ((p > N) || (N == 0u) || (p == 0u)) { // there is nothing to compute. return empty vector // ideally, p == 0u should throw an exception, but we don't know about those yet... return RunningMeanP; } const std::vector<double>::size_type num_elements_moving_average = N - p + 1u; RunningMeanP.resize(num_elements_moving_average); // calculate RunningMeanP.at(0u) first for (std::vector<double>::size_type i = 0u; i != p; ++i) { RunningMeanP.at(0u) += Values.at(i) / p; } // then calculate the remaining elements // here, we use an optimisation to avoid needing nested loops // but this comes at the potential cost of losing accuracy // // A suitable alternative is to use nested loops! for (std::vector<double>::size_type i = 1u; i != num_elements_moving_average; ++i) { RunningMeanP.at(i) = RunningMeanP.at(i - 1u) - Values.at(i - 1u) / p + Values.at(i + p - 1u) / p; } return RunningMeanP; ///////////////////////////////////////////////////////////////////// }
/*********************************************************************** h:NoiseLightManager ************************************************************************/ #pragma once namespace Noise3D { //灯光类型 enum NOISE_LIGHT_TYPE { NOISE_LIGHT_TYPE_DYNAMIC_DIR = 0, NOISE_LIGHT_TYPE_DYNAMIC_POINT = 1, NOISE_LIGHT_TYPE_DYNAMIC_SPOT = 2, NOISE_LIGHT_TYPE_STATIC_DIR = 3, NOISE_LIGHT_TYPE_STATIC_POINT = 4, NOISE_LIGHT_TYPE_STATIC_SPOT = 5 }; class /*_declspec(dllexport)*/ ILightManager: IFactory<IDirLightD>, IFactory<IPointLightD>, IFactory<ISpotLightD>, IFactory<IDirLightS>, IFactory<IPointLightS>, IFactory<ISpotLightS> { public: IDirLightD* CreateDynamicDirLight(N_UID lightName); IPointLightD* CreateDynamicPointLight(N_UID lightName); ISpotLightD* CreateDynamicSpotLight(N_UID lightName); IDirLightS* CreateStaticDirLight(N_UID lightName,const N_DirLightDesc& desc); IPointLightS* CreateStaticPointLight(N_UID lightName, const N_PointLightDesc& desc); ISpotLightS* CreateStaticSpotLight(N_UID lightName, const N_SpotLightDesc& desc); IDirLightD* GetDirLightD(N_UID lightName); IDirLightD* GetDirLightD(UINT index); IPointLightD* GetPointLightD(N_UID lightName); IPointLightD* GetPointLightD(UINT index); ISpotLightD* GetSpotLightD(N_UID lightName); ISpotLightD* GetSpotLightD(UINT index); IDirLightS* GetDirLightS(N_UID lightName); IDirLightS* GetDirLightS(UINT index); IPointLightS* GetPointLightS(N_UID lightName); IPointLightS* GetPointLightS(UINT index); ISpotLightS* GetSpotLightS(N_UID lightName); ISpotLightS* GetSpotLightS(UINT index); bool DeleteDirLightD(N_UID lightName); bool DeleteDirLightD(IDirLightD* pLight); bool DeletePointLightD(N_UID lightName); bool DeletePointLightD(IPointLightD* pLight); bool DeleteSpotLightD(N_UID lightName); bool DeleteSpotLightD(ISpotLightD* pLight); bool DeleteDirLightS(N_UID lightName); bool DeleteDirLightS(IDirLightS* pLight); bool DeletePointLightS(N_UID lightName); bool DeletePointLightS(IPointLightS* pLight); bool DeleteSpotLightS(N_UID lightName); bool DeleteSpotLightS(ISpotLightS* pLight); void SetDynamicLightingEnabled(bool isEnabled); //void SetStaticLightingEnabled(bool isEnabled); bool IsDynamicLightingEnabled(); //bool IsStaticLightingEnabled(); UINT GetLightCount(NOISE_LIGHT_TYPE lightType); UINT GetDynamicLightCount(); UINT GetStaticLightCount(); UINT GetTotalLightCount(); private: friend IRenderer;//access to 'CanUpdateStaticLights' friend IFactory<ILightManager>; //构造函数 ILightManager(); ~ILightManager(); bool mIsDynamicLightingEnabled; bool mIsStaticLightingEnabled; bool mCanUpdateStaticLights; }; }
#include<iostream> using namespace std; int main() { int n; cout<<"Enter a number:"; cin>>n; while(n>=10) { n/=10; } cout<<"First digit="<<n; return 0; }
// // Created by jeremyelkayam on 10/14/20. // #pragma once #include "entity.hpp" #include <SFML/Audio.hpp> class SpecialItem : public Entity { protected: bool active, consumed; //The amount of time this special item has existed in seconds. float age; //The amount of time after which this special item will appear. const float appear_time; sf::Sound used_sound; public: SpecialItem(sf::Texture &texture, sf::SoundBuffer &used_sound_buffer, float a_appear_time); bool item_active() {return active;} bool effect_active() {return used_sound.getStatus() == sf::Sound::Playing;} void update(float s_elapsed); void consume(); virtual void spawn(float xcor, float ycor); bool ready_to_spawn(){return age >= appear_time && !consumed && !active; } void draw(sf::RenderWindow &window, ColorGrid &color_grid) const override; };
#include "../../gl_framework.h" using namespace glmock; extern "C" { #undef glAttachShader void CALL_CONV glAttachShader(GLuint program, GLuint shader) { } DLL_EXPORT PFNGLATTACHSHADERPROC __glewAttachShader = &glAttachShader; }
/* ID: andonov921 TASK: preface LANG: C++ */ #include <iostream> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <string> #include <algorithm> #include <sstream> #include <climits> #include <fstream> #include <cmath> using namespace std; /// ********* debug template by Bidhan Roy ********* template < typename F, typename S > ostream& operator << ( ostream& os, const pair< F, S > & p ) { return os << "(" << p.first << ", " << p.second << ")"; } template < typename T > ostream &operator << ( ostream & os, const vector< T > &v ) { os << "{"; typename vector< T > :: const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "}"; } template < typename T > ostream &operator << ( ostream & os, const set< T > &v ) { os << "["; typename set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename T > ostream &operator << ( ostream & os, const unordered_set< T > &v ) { os << "["; typename unordered_set< T > :: const_iterator it; for ( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << *it; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const map< F, S > &v ) { os << "["; typename map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << ": " << it -> second ; } return os << "]"; } template < typename F, typename S > ostream &operator << ( ostream & os, const unordered_map< F, S > &v ) { os << "["; typename unordered_map< F , S >::const_iterator it; for( it = v.begin(); it != v.end(); it++ ) { if( it != v.begin() ) os << ", "; os << it -> first << ": " << it -> second ; } return os << "]"; } #define debug(x) cerr << #x << " = " << x << endl; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<char> VC; typedef vector<string> VS; typedef vector<VI> VVI; typedef vector<VL> VVL; typedef vector<VS> VVS; typedef vector<VC> VVC; ifstream fin("preface.in"); ofstream fout("preface.out"); int n; unordered_map<char, int> symbol_to_count; unordered_map<int, string> num_to_symbol = { {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}, }; VI nums = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; VC symbols = {'I', 'V', 'X', 'L', 'C', 'D', 'M'}; void read_input(){ fin >> n; // 1 < = n <= 3500 } string convert_dec_to_roman(int x){ string res = ""; for(auto num : nums){ while(x >= num){ res += num_to_symbol[num]; x -= num; } } return res; } void count(string roman){ for(auto c : roman){ symbol_to_count[c]++; } } void solve(){ for(int i=1;i<=n;i++){ string roman = convert_dec_to_roman(i); count(roman); } for(auto symb : symbols){ if(!symbol_to_count.count(symb)) continue; fout << symb << " " << symbol_to_count[symb] << "\n"; } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); read_input(); solve(); return 0; }
#include<stdio.h> #include<conio.h> int KthSmallest(int*, int*, int); void main(){ int arr1[50]; int size1; int arr2[50]; int size2; int k; scanf_s("%d%d%d", &size1, &size2,&k); if (k <= (size1 + size2)) { for (int i = 0; i < size1; i++) scanf_s("%d", &arr1[i]); for (int i = 0; i < size2; i++) scanf_s("%d", &arr2[i]); printf("%d",KthSmallest(arr1, arr2, k)); } else { printf("Invalid :P"); } _getch(); } int KthSmallest(int *a1, int *a2, int k){ int i = 0;//for first array int j = 0;//for second array int prev; while (k>0) { if (a1[i] < a2[j]){ prev = a1[i]; i++; } else if (a1[i] > a2[j]){ prev = a2[j]; j++; } k--; } return prev; }
#pragma once #include <vector> typedef unsigned int uint; typedef int DATA; bool CheckSetAvail(std::vector<DATA> &myArray, uint pos, DATA data); void ResetArray(std::vector<DATA> &myArray, uint pos, DATA data); bool ArrayFull(std::vector<DATA> &myArray); bool SetData(std::vector<DATA> &myArray, const std::vector<uint> &availArray, uint pos);
#ifndef HEAP_H #define HEAP_H class Heap{ private: int *m_pData; unsigned int m_size; private: unsigned int getLeftChildIndex(unsigned int index); unsigned int getRightChildIndex(unsigned int index); void swapNodeValue(unsigned int firstNodeIndex, unsigned int secondNodeIndex); bool nodeHasALeftChild(unsigned int index); bool nodeHasARightChild(unsigned int index); void checkBranchUnderLeft(unsigned int index, bool wasSwaped); void checkBranchUnderRight(unsigned int index, bool wasSwaped); void trySwapNodes(unsigned int index, unsigned int childIndex, bool wasSwaped); void decrementSize(); public: Heap(int *pData, unsigned int size); void heapify(); void pop(); }; #endif
/* * 方法一:小根堆 */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /*struct cmp{ bool operator ()(ListNode *l1,ListNode *l2){ return l1->val < l2->val; } };*/ class Solution1 { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size() < 1) return NULL; //priority_queue<ListNode*,vector<ListNode*>,cmp> Q; priority_queue<int,vector<int>,greater<int> > Q; for(int i=0; i<lists.size(); ++i){ ListNode *temp = lists[i]; while(temp){ Q.push(temp->val); temp = temp->next; } } ListNode *newHead = new ListNode(-1); ListNode *temp = newHead; while(Q.empty() == false){ temp->next = new ListNode(Q.top()); Q.pop(); temp = temp->next; } return newHead->next; } }; /* * 方法二:归并排序 */ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution2 { public: ListNode* mergeKLists(vector<ListNode*>& lists) { if(lists.size() < 1) return NULL; ListNode *head = mergeK(lists,0,lists.size()-1); return head; } ListNode* mergeK(vector<ListNode*> &lists,int left,int right){ if(left >= right) return lists[left]; int mid = left + (right-left)/2; ListNode *l1 = mergeK(lists,left,mid); ListNode *l2 = mergeK(lists,mid+1,right); return mergeTwo(l1,l2); } ListNode* mergeTwo(ListNode *l1,ListNode *l2){ if(!l1 && !l2) return NULL; if(!l1 || !l2) return !l1? l2:l1; ListNode *head = new ListNode(-1); ListNode *temp = head; while(l1 && l2){ if(l1->val < l2->val){ temp->next = l1; l1 = l1->next; }else{ temp->next = l2; l2 = l2->next; } temp = temp->next; } if(l1){ temp->next = l1; } if(l2){ temp->next = l2; } return head->next; } };
#include <stdio.h> int main() { int controlador = 1, resp; float num1, num2, soma; while (controlador < 6) { printf("\nBem vindo, digite dois numeros para soma: "); printf("\nSoma %d de 6.", controlador); printf("\n\nNumero um: "); scanf("%f", &num1); printf("\nNumero dois: "); scanf("%f", &num2); soma = num1 + num2; printf("\nSua soma deu %.2f", soma); printf("\nDeseja continuar?"); printf("\n(1)Sim / (2)Nao\n"); scanf("%d", &resp); if (resp == 1){ controlador = controlador + 1; } else if (resp == 2){ break; } else { printf("Resposta invalida!!!"); } } }
#include "Types.h" using namespace OpenFlight; //------------------------------------------------------------------------------ //--- Matrix4f //------------------------------------------------------------------------------ Matrix4f::Matrix4f() { mInternalStorage = isRowMajor; mData[0][0] = 1; mData[0][1] = 0; mData[0][2] = 0; mData[0][3] = 0; mData[1][0] = 0; mData[1][1] = 1; mData[1][2] = 0; mData[1][3] = 0; mData[2][0] = 0; mData[2][1] = 0; mData[2][2] = 1; mData[2][3] = 0; mData[3][0] = 0; mData[3][1] = 0; mData[3][2] = 0; mData[3][3] = 1; } //------------------------------------------------------------------------------ //--- Vertex //------------------------------------------------------------------------------ //------------------------------------------------------------------------- bool Vertex::hasFlag(Vertex::flag iFlag) const { return (bool)(mFlags & (uint16_t)iFlag); }
#include "Player.h" #include "Logger.h" #include "IProcess.h" #include "HallHandler.h" #include "GameCmd.h" #include "ProcessFactory.h" int pase_json(Json::Value& value, const char* key, int def) { int v = def; try{ v = value[key].asInt(); } catch(...) { v = def; } return v; } void Player::init() { timer.init(this); id = 0; memset(name, 0, sizeof(name)); tid = -1; //牌座ID tab_index = -1; //当前在桌子的位置 score = 0; //积分 money = 0; //金币数 carrycoin = 0; //这盘牌携带金币数 nwin = 0; //赢牌数 nlose = 0; //输牌数 memset(json, 0, sizeof(json)); //json字符串 status = 0; //状态 0 未登录 1 已登录 2 入座等待开局 3 正在游戏 4 结束游戏 source = 0; //用户来源 clevel = 0; //当前金币场底注 0-无底注 memset(card_array, 0, sizeof(card_array)); //当前手牌 memset(Knowcard_array, 0, sizeof(Knowcard_array)); hascard = false; memset(player_array, 0, sizeof(player_array)); memset(CenterCard, 0, sizeof(CenterCard)); memset(betCoinList, 0, sizeof(betCoinList)); finalgetCoin = 0; finalcardvalue = -1; thisroundhasbet = false; hasallin = false; optype = 0; limitcoin = -1; isdropline = false; currcardvalue = 0; rasecoin = 0; bactive = false; playNum = 0; isKnow = false; hasrase = false; } void Player::reset() { memset(card_array, 0, sizeof(card_array)); //当前手牌 memset(Knowcard_array, 0, sizeof(Knowcard_array)); hascard = false; memset(betCoinList, 0, sizeof(betCoinList)); memset(CenterCard, 0, sizeof(CenterCard)); rasecoin = 0; hasrase = false; } int Player::login() { IProcess* process = ProcessFactory::getProcesser(HALL_USER_LOGIN); return process->doRequest(this->handler, NULL, NULL); } int Player::logout() { IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_LEAVE); return process->doRequest(this->handler, NULL, NULL); } int Player::check() { IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_LOOK_CARD); return process->doRequest(this->handler, NULL, NULL); } int Player::call() { if(this->limitcoin < (this->currMaxCoin - this->betCoinList[this->currRound])) return allin(); IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_BET_CALL); return process->doRequest(this->handler, NULL, NULL); } int Player::rase() { if(this->currMaxCoin > 0) { short diff = (this->rasecoin - this->currMaxCoin) / this->currMaxCoin; if(diff < 1) return call(); } IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_BET_RASE); return process->doRequest(this->handler, NULL, NULL); } int Player::allin() { IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_ALL_IN); return process->doRequest(this->handler, NULL, NULL); } int Player::stargame() { IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_START_GAME); return process->doRequest(this->handler, NULL, NULL); } int Player::throwcard() { IProcess* process = ProcessFactory::getProcesser(CLIENT_MSG_THROW_CARD); return process->doRequest(this->handler, NULL, NULL); } int Player::heartbeat() { IProcess* process = ProcessFactory::getProcesser(USER_HEART_BEAT); return process->doRequest(this->handler, NULL, NULL); } bool Player::robotIsLargest() { /*BYTE bRobotCardArray[5]; BYTE bPlayerCardArray[5]; memcpy(bRobotCardArray,this->card_array,sizeof(this->card_array)); this->currcardvalue = m_GameLogic.GetCardKind(bRobotCardArray,currRound==5 ? 5 : currRound + 1); printf("========================robot currcardvalue:%d\n", this->currcardvalue); for(int i = 0; i < GAME_PLAYER; ++i) { if(this->player_array[i].id != 0 && this->player_array[i].hascard) { memcpy(bPlayerCardArray,this->player_array[i].card_array + 1,currRound==5 ? 4 : currRound); if(m_GameLogic.CompareCard(bPlayerCardArray,currRound==5 ? 4 : currRound, bRobotCardArray, currRound==5 ? 5 : currRound + 1)) return false; } }*/ return true; } bool Player::robotKonwIsLargest() { BYTE bRobotCardArray[5]; BYTE bPlayerCardArray[5]; memcpy(bRobotCardArray,this->Knowcard_array,sizeof(this->Knowcard_array)); m_GameLogic.SortCardList(bRobotCardArray,5); this->currcardvalue = m_GameLogic.GetCardType(bRobotCardArray,5); //_LOG_DEBUG_("========================robot currcardvalue:%d\n", this->currcardvalue); for(int i = 0; i < GAME_PLAYER; ++i) { if(this->player_array[i].id != 0 && this->player_array[i].hascard) { memcpy(bPlayerCardArray,this->player_array[i].Knowcard_array,5); if(m_GameLogic.CompareCard(bPlayerCardArray, bRobotCardArray, 5) == 2) return false; } } return true; } short Player::getPlayNum() { short countplayer = 1; for(int i = 0; i < GAME_PLAYER; ++i) { if(this->player_array[i].id != 0 && this->player_array[i].hascard) { countplayer++; } } return countplayer; } void Player::setRaseCoin() { this->rasecoin = this->ante; } void Player::setKnowRaseCoin() { int64_t diffcoin = this->limitcoin - this->currMaxCoin; if(diffcoin <= 0) return ; this->rasecoin = this->currMaxCoin; if(diffcoin <= this->ante*4) this->rasecoin += diffcoin; else { short mul = 0; int64_t score = diffcoin - this->ante*4; if(score > 0) { int num = score/this->ante; if(num > 0) mul = rand()%num + 1; } this->rasecoin += this->ante*4 + mul*this->ante; } if(currRound <= 2) { int randnum = rand()%100; if(randnum < 60) { if(this->rasecoin < this->PoolCoin/2) { if(this->PoolCoin/2 > this->limitcoin) this->rasecoin = this->limitcoin; else this->rasecoin = this->PoolCoin/2; } } else { if(this->rasecoin < this->PoolCoin) { if(this->PoolCoin > this->limitcoin) this->rasecoin = this->limitcoin; else this->rasecoin = this->PoolCoin; } } } if(this->rasecoin < this->currMaxCoin) this->rasecoin = this->currMaxCoin; } int Player::setRandRaseCoin( const BYTE nMin, BYTE nMul ) { short mul = 0; if(this->limitcoin < this->currMaxCoin) return 0; mul = rand()%nMul + 1; mul += nMin; if(this->ante*mul < this->currMaxCoin) this->rasecoin = this->currMaxCoin; else { if( this->limitcoin <= this->ante*mul) this->rasecoin = this->limitcoin; else this->rasecoin = this->ante*mul; } return 1; } //===========================Timer================================== void Player::stopAllTimer() { timer.stopAllTimer(); } void Player::startBetCoinTimer(int uid,int timeout) { timer.startBetCoinTimer(uid, timeout); } void Player::stopBetCoinTimer() { timer.stopBetCoinTimer(); } void Player::startLeaveTimer(int timeout) { timer.startLeaveTimer(timeout); } void Player::stopLeaveTimer() { timer.stopLeaveTimer(); } void Player::startActiveLeaveTimer(int timeout) { timer.startActiveLeaveTimer(timeout); } void Player::stopActiveLeaveTimer() { timer.stopActiveLeaveTimer(); } void Player::startHeartTimer(int uid,int timeout) { timer.startHeartTimer(uid, timeout); } void Player::stopHeartTimer() { timer.stopHeartTimer(); } void Player::startStartGameTimer(int timeout) { timer.startStartGameTimer(timeout); } void Player::stopStartGameTimer() { timer.stopStartGameTimer(); }
#include "asteroid.hpp" #include "game.hpp" #include "player.hpp" #include "scrolling_bg.hpp" #include "spawn_point.hpp" #include <sgfx/key.hpp> #include <sgfx/primitives.hpp> #include <chrono> int main(int argc, char* argv[]) { using namespace sgfx; auto g = game{}; g.spawn<scrolling_bg>("img/bg.rle"); g.spawn<player>("img/ship", player::key_config{sgfx::key::left, sgfx::key::right, sgfx::key::up, sgfx::key::down, sgfx::key::space}); g.spawn(make_spawn_point( {{0, 0}, {100, 100}}, [](auto proxy, auto pos) { proxy.template spawn<asteroid>("img/asteroid.rle", pos); }, std::chrono::seconds{3})); g.run(); return 0; }
#include <fstream> #include <sstream> #include <dirent.h> #include <time.h> #include <math.h> #include <stdlib.h> #include "saltyreader.h" void ComputeMMR (bool winner, signed short one_mmr, signed short two_mmr, unsigned short one_games, unsigned short two_games, signed short *new_one_mmr, signed short *new_two_mmr) { signed short max = one_mmr > two_mmr ? one_mmr : two_mmr; signed short min = one_mmr <= two_mmr ? one_mmr : two_mmr; signed short new_one = 0; signed short new_two = 0; float max_diff; float diff = max_diff = (max - min) * 6; if (diff > 400) diff = 400; if ((winner && max == one_mmr) || (!winner && max == two_mmr)) { new_one = (signed short)((1 - diff / 400) * (1 + 7 / ((float) one_games)) * 3); new_two = (signed short)((1 - diff / 400) * (1 + 7 / ((float) two_games)) * 3); } else if ((winner && max == two_mmr) || (!winner && max == one_mmr)) { new_one = (signed short)((1 + max_diff / 400) * (1 + 7 / ((float) one_games)) * 3); new_two = (signed short)((1 + max_diff / 400) * (1 + 7 / ((float) two_games)) * 3); } new_one *= winner ? 1 : -1; new_two *= winner ? -1 : 1; new_one_mmr [0] = one_mmr + new_one; new_two_mmr [0] = two_mmr + new_two; } SaltyReader::SaltyReader () {} SaltyReader::~SaltyReader () {} std::string SaltyReader::GetMMR (std::string player, std::string *games) { std::fstream reader ("mmr", std::ios::in | std::ios::ate | std::ios::binary); std::streampos size; std::string name; char *buffer; if (reader.fail ()) { games [0] = "0"; return "0"; } else { size = reader.tellg (); buffer = new char [size]; reader.seekg (0, std::ios::beg); reader.read (buffer, size); reader.close (); for (int i = 0; i < (int) size;) { for (; buffer [i] != 0; i ++) name += buffer [i]; if (name == player) { ShortUnion short_union_mmr, short_union_games; short_union_games.byte.b1 = buffer [i + 2]; short_union_games.byte.b2 = buffer [i + 1]; games [0] = ToString (short_union_games.s); short_union_mmr.byte.b1 = buffer [i + 4]; short_union_mmr.byte.b2 = buffer [i + 3]; return ToString (short_union_mmr.s); } i += 6; name.clear (); } delete [] buffer; games [0] = "0"; return "0"; } } std::vector <CharacterRecord> SaltyReader::GetAllStats () { std::fstream reader ("mmr", std::ios::in | std::ios::ate | std::ios::binary); std::streampos size; std::string name; std::vector <CharacterRecord> stats; CharacterRecord record; char *buffer; if (reader.fail ()) { return stats; } else { size = reader.tellg (); buffer = new char [size]; reader.seekg (0, std::ios::beg); reader.read (buffer, size); reader.close (); ShortUnion short_union_games; ShortUnion short_union_mmr; for (int i = 0; i < (int) size; i ++) { record = CharacterRecord (); for (; buffer [i] != 0; i ++) name += buffer [i]; record.name = name; i ++; short_union_games.byte.b2 = buffer [i ++]; short_union_games.byte.b1 = buffer [i ++]; record.games = (unsigned short) short_union_games.s; short_union_mmr.byte.b2 = buffer [i ++]; short_union_mmr.byte.b1 = buffer [i ++]; record.mmr = (signed short) short_union_mmr.s; name.clear (); stats.push_back (record); } delete [] buffer; return stats; } } bool SaltyReader::FindMatchup (Matchup *out_matchup, std::string player_one, std::string player_two) { std::string file_name = "matchups/" + player_one + "$" + player_two + ".sbm"; std::fstream reader (file_name.c_str (), std::ios::in | std::ios::ate | std::ios::binary); Matchup matchup; bool reverse = false; if (reader.fail ()) { file_name = "matchups/" + player_two + "$" + player_one + ".sbm"; reader.open (file_name.c_str (), std::ios::in | std::ios::ate | std::ios::binary); if (reader.fail ()) { out_matchup [0] = Matchup (); return false; } else reverse = true; } Fight fight; std::streampos size; char *buffer; size = reader.tellg (); buffer = new char [(int) size]; reader.seekg (0, std::ios::beg); reader.read (buffer, size); matchup.player_one = player_one; matchup.player_two = player_two; ShortUnion one_games, two_games; ShortUnion one_mmr, two_mmr; ShortUnion one_mmr_change, two_mmr_change; for (int i = 0; i < (int) size; i ++) { fight = Fight (); fight.month = (unsigned char) buffer [i]; fight.day = (unsigned char) buffer [i + 1]; fight.year = (unsigned char) buffer [i + 2]; fight.winner = (unsigned char) buffer [i + 3]; one_games.byte.b2 = buffer [i + 4]; one_games.byte.b1 = buffer [i + 5]; two_games.byte.b2 = buffer [i + 6]; two_games.byte.b1 = buffer [i + 7]; one_mmr.byte.b2 = buffer [i + 8]; one_mmr.byte.b1 = buffer [i + 9]; two_mmr.byte.b2 = buffer [i + 10]; two_mmr.byte.b1 = buffer [i + 11]; one_mmr_change.byte.b2 = buffer [i + 12]; one_mmr_change.byte.b1 = buffer [i + 13]; two_mmr_change.byte.b2 = buffer [i + 14]; two_mmr_change.byte.b1 = buffer [i + 15]; fight.one_games = (unsigned short) one_games.s; fight.two_games = (unsigned short) two_games.s; fight.one_mmr = (signed short) one_mmr.s; fight.two_mmr = (signed short) two_mmr.s; fight.one_mmr_change = (signed short) one_mmr_change.s; fight.two_mmr_change = (signed short) two_mmr_change.s; if (reverse) fight.Reverse (); matchup.fight_log.push_back (fight); i += 15; } out_matchup [0] = matchup; return true; } bool SaltyReader::GetBetPercent (std::string player_one, std::string player_two, std::string *percent) { std::fstream reader ("mmr", std::ios::in | std::ios::ate | std::ios::binary); std::streampos size; std::string name; signed short one_mmr = 0; signed short two_mmr = 0; signed short diff = 0; float percent_float; int random; bool player; char *buffer; if (reader.fail ()) { percent [0] = "0%"; return true; } else { size = reader.tellg (); buffer = new char [size]; reader.seekg (0, std::ios::beg); reader.read (buffer, size); reader.close (); for (int i = 0; i < (int) size; i ++) { ShortUnion short_union_mmr; for (; buffer [i] != 0; i ++) name += buffer [i]; if (name == player_one) { short_union_mmr.byte.b1 = buffer [i + 4]; short_union_mmr.byte.b2 = buffer [i + 3]; one_mmr = short_union_mmr.s; } else if (name == player_two) { short_union_mmr.byte.b1 = buffer [i + 4]; short_union_mmr.byte.b2 = buffer [i + 3]; two_mmr = short_union_mmr.s; } name.clear (); } diff = one_mmr - two_mmr; if (diff > 80) diff = 80; else if (diff < -80) diff = -80; percent_float = 100 * ((80 + (float) diff) / 160); //srand (time (NULL)); //random = rand () % 100; player = one_mmr > two_mmr; if (diff == 0) percent [0] = "50%"; else percent [0] = player ? ToString ((int)(percent_float)) + "%" : ToString ((int)(100 - percent_float)) + "%"; return player; } } void SaltyReader::AddFight (std::string player_one, std::string player_two, bool winner, std::string *winner_mmr) { DIR *dir; dirent *ent; time_t current; tm *time_info; std::fstream reader ("mmr", std::ios::in | std::ios::ate | std::ios::binary); std::streampos size; std::string file_name; signed short one_mmr = 0; signed short two_mmr = 0; signed short mmr_gain_winner = 0; char *buffer, *old_buffer; bool new_matchup = true; Fight new_fight = Fight (); if (reader.fail ()) { buffer = new char [player_one.size () + player_two.size () + 12]; ComputeMMR (winner, 0, 0, 1, 1, &new_fight.one_mmr, &new_fight.two_mmr); new_fight.one_mmr_change = new_fight.one_mmr; new_fight.two_mmr_change = new_fight.two_mmr; new_fight.one_games = new_fight.two_games = 1; mmr_gain_winner = winner ? new_fight.one_mmr : new_fight.two_mmr; winner_mmr [0] = winner ? ToString (new_fight.one_mmr) : ToString (new_fight.two_mmr); int i = 0; int j; for (; i < player_one.size (); i ++) buffer [i] = player_one [i]; buffer [i ++] = 0; buffer [i ++] = 0; buffer [i ++] = 1; buffer [i ++] = (new_fight.one_mmr >> 8) & 0xFF; buffer [i ++] = new_fight.one_mmr & 0xFF; buffer [i ++] = 0; for (j = i; (j - i) < player_two.size (); j ++) buffer [j] = player_two [j - i]; buffer [j ++] = 0; buffer [j ++] = 0; buffer [j ++] = 1; buffer [j ++] = (new_fight.two_mmr >> 8) & 0xFF; buffer [j ++] = new_fight.two_mmr & 0xFF; buffer [j ++] = 0; std::ofstream writer ("mmr", std::ofstream::out | std::ofstream::binary); writer.write (buffer, player_one.size () + player_two.size () + 12); } else { unsigned short one_games = 0; unsigned short two_games = 0; bool one_reg = false; bool two_reg = false; int mmr_pos_one = 0; int mmr_pos_two = 0; int buffer_len = 0; std::string name; size = reader.tellg (); old_buffer = new char [size]; reader.seekg (0, std::ios::beg); reader.read (old_buffer, size); reader.close (); remove ("/mmr"); for (int i = 0; i < (int) size;) { for (; old_buffer [i] != 0; i ++) name += old_buffer [i]; if (name == player_one) { one_games = (signed short)(old_buffer [i + 2] | (old_buffer [i + 1] << 8)); one_mmr = (signed short)(old_buffer [i + 4] | (old_buffer [i + 3] << 8)); mmr_pos_one = i; one_reg = true; } else if (name == player_two) { two_games = (signed short)(old_buffer [i + 2] | (old_buffer [i + 1] << 8)); two_mmr = (signed short)(old_buffer [i + 4] | (old_buffer [i + 3] << 8)); mmr_pos_two = i; two_reg = true; } i += 6; name.clear (); } one_games ++; two_games ++; if (one_reg && two_reg) buffer_len = (int) size; else if (one_reg) buffer_len = (int) size + player_two.size () + 6; else if (two_reg) buffer_len = (int) size + player_one.size () + 6; else buffer_len = (int) size + player_one.size () + player_two.size () + 12; buffer = new char [buffer_len]; for (int i = 0; i < (int) size; i ++) buffer [i] = old_buffer [i]; delete [] old_buffer; mmr_gain_winner = winner ? one_mmr : two_mmr; new_fight.one_mmr_change = one_mmr; new_fight.two_mmr_change = two_mmr; ComputeMMR (winner, one_mmr, two_mmr, one_games, two_games, &one_mmr, &two_mmr); mmr_gain_winner = winner ? (one_mmr - mmr_gain_winner) : (two_mmr - mmr_gain_winner); new_fight.one_mmr_change = one_mmr - new_fight.one_mmr_change; new_fight.two_mmr_change = two_mmr - new_fight.two_mmr_change; new_fight.one_games = one_games; new_fight.two_games = two_games; new_fight.one_mmr = one_mmr; new_fight.two_mmr = two_mmr; if (one_reg && two_reg) { buffer [mmr_pos_one + 1] = (one_games >> 8) & 0xFF; buffer [mmr_pos_one + 2] = one_games & 0xFF; buffer [mmr_pos_one + 3] = (one_mmr >> 8) & 0xFF; buffer [mmr_pos_one + 4] = one_mmr & 0xFF; buffer [mmr_pos_two + 1] = (two_games >> 8) & 0xFF; buffer [mmr_pos_two + 2] = two_games & 0xFF; buffer [mmr_pos_two + 3] = (two_mmr >> 8) & 0xFF; buffer [mmr_pos_two + 4] = two_mmr & 0xFF; } else if (one_reg) { buffer [mmr_pos_one + 1] = (one_games >> 8) & 0xFF; buffer [mmr_pos_one + 2] = one_games & 0xFF; buffer [mmr_pos_one + 3] = (one_mmr >> 8) & 0xFF; buffer [mmr_pos_one + 4] = one_mmr & 0xFF; for (int i = 0; i < player_two.size (); i ++) buffer [(int) size + i] = player_two [i]; buffer [(int) size + player_two.size ()] = 0; buffer [(int) size + player_two.size () + 1] = (two_games >> 8) & 0xFF; buffer [(int) size + player_two.size () + 2] = two_games & 0xFF; buffer [(int) size + player_two.size () + 3] = (two_mmr >> 8) & 0xFF; buffer [(int) size + player_two.size () + 4] = two_mmr & 0xFF; buffer [(int) size + player_two.size () + 5] = 0; } else if (two_reg) { buffer [mmr_pos_two + 1] = (two_games >> 8) & 0xFF; buffer [mmr_pos_two + 2] = two_games & 0xFF; buffer [mmr_pos_two + 3] = (two_mmr >> 8) & 0xFF; buffer [mmr_pos_two + 4] = two_mmr & 0xFF; for (int i = 0; i < player_one.size (); i ++) buffer [(int) size + i] = player_one [i]; buffer [(int) size + player_one.size ()] = 0; buffer [(int) size + player_one.size () + 1] = (one_games >> 8) & 0xFF; buffer [(int) size + player_one.size () + 2] = one_games & 0xFF; buffer [(int) size + player_one.size () + 3] = (one_mmr >> 8) & 0xFF; buffer [(int) size + player_one.size () + 4] = one_mmr & 0xFF; buffer [(int) size + player_one.size () + 5] = 0; } else { for (int i = 0; i < player_one.size (); i ++) buffer [(int) size + i] = player_one [i]; buffer [(int) size + player_one.size ()] = 0; buffer [(int) size + player_one.size () + 1] = (one_games >> 8) & 0xFF; buffer [(int) size + player_one.size () + 2] = one_games & 0xFF; buffer [(int) size + player_one.size () + 3] = (one_mmr >> 8) & 0xFF; buffer [(int) size + player_one.size () + 4] = one_mmr & 0xFF; buffer [(int) size + player_one.size () + 5] = 0; for (int i = 0; i < player_two.size (); i ++) buffer [(int) size + player_one.size () + 6 + i] = player_two [i]; buffer [(int) size + player_one.size () + player_two.size () + 6] = 0; buffer [(int) size + player_one.size () + player_two.size () + 7] = (two_games >> 8) & 0xFF; buffer [(int) size + player_one.size () + player_two.size () + 8] = two_games & 0xFF; buffer [(int) size + player_one.size () + player_two.size () + 9] = (two_mmr >> 8) & 0xFF; buffer [(int) size + player_one.size () + player_two.size () + 10] = two_mmr & 0xFF; buffer [(int) size + player_one.size () + player_two.size () + 11] = 0; } std::ofstream writer ("mmr", std::ofstream::out | std::ofstream::binary); writer.write (buffer, buffer_len); delete [] buffer; winner_mmr [0] = ToString (mmr_gain_winner); } dir = opendir ("matchups"); file_name = player_one + "$" + player_two + ".sbm"; time (&current); time_info = localtime (&current); if (dir == NULL) { CreateDirectory ("matchups", NULL); dir = opendir ("matchups"); } for (int i = 0; (ent = readdir (dir)) != NULL; i ++) { if (i > 1 && file_name == ent->d_name) new_matchup = false; } file_name.insert (0, "matchups/"); if (new_matchup) { size = 0; buffer = new char [16]; } else { std::fstream matchup (file_name.c_str (), std::ios::in | std::ios::ate | std::ios::binary); size = matchup.tellg (); buffer = new char [(int) size + 16]; matchup.seekg (0, std::ios::beg); matchup.read (buffer, size); remove (file_name.c_str ()); } buffer [(int) size] = (char)(time_info->tm_mon + 1); buffer [(int) size + 1] = (char) time_info->tm_mday; buffer [(int) size + 2] = (char)(time_info->tm_year - 116); buffer [(int) size + 3] = winner ? 1 : 0; buffer [(int) size + 4] = (new_fight.one_games >> 8) & 0xFF; buffer [(int) size + 5] = new_fight.one_games & 0xFF; buffer [(int) size + 6] = (new_fight.two_games >> 8) & 0xFF; buffer [(int) size + 7] = new_fight.two_games & 0xFF; buffer [(int) size + 8] = (new_fight.one_mmr >> 8) & 0xFF; buffer [(int) size + 9] = new_fight.one_mmr & 0xFF; buffer [(int) size + 10] = (new_fight.two_mmr >> 8) & 0xFF; buffer [(int) size + 11] = new_fight.two_mmr & 0xFF; buffer [(int) size + 12] = (new_fight.one_mmr_change >> 8) & 0xFF; buffer [(int) size + 13] = new_fight.one_mmr_change & 0xFF; buffer [(int) size + 14] = (new_fight.two_mmr_change >> 8) & 0xFF; buffer [(int) size + 15] = new_fight.two_mmr_change & 0xFF; std::ofstream writer (file_name.c_str (), std::ofstream::out | std::ofstream::binary); writer.write (buffer, (int) size + 16); }
#include <SFML/Graphics.hpp> #include <iostream> #include "Player.h" #include "Entity.h" #include "Bullet.h" #include <vector> #include <ostream> #include "Fighter.h" #include <string> #include "Explosion.h" #include "Powerups.h" #include "Nscorepowerup.h" #include "Scorepowerup.h" using namespace std; int main() { //Variables int counter = 0; int counter1 = 0; int counter2 = 0; int counter3 = 0; //CLOCKS AND TIMERS sf::Clock clock; sf::Clock clock2; sf::Clock enemySpawnClock; sf::Clock clock3; sf::Clock clockpowerup; //Window sf::RenderWindow window(sf::VideoMode(1200, 700), "Testing"); window.setKeyRepeatEnabled(false); window.setTitle("SFML SHTU-Game-ProgrammingAssignment"); //Load Background texture sf::Texture BackgroundTexture; if (!BackgroundTexture.loadFromFile("Background.png")) std::cout << "Texture Error" << std::endl; sf::Sprite background(BackgroundTexture); background.setScale(3.0f, 2.0f); //background.setRotation(90); //Load Player Texture sf::Texture PlayerTexture; if (!PlayerTexture.loadFromFile("SpriteShip.png")) std::cout << "Texture Error" << std::endl; //Load Bullet Texture sf::Texture BulletTexture; if (!BulletTexture.loadFromFile("Bullet.png")) std::cout << "Texture Error" << std::endl; //Load Fighter Texture sf::Texture FighterTexture; if (!FighterTexture.loadFromFile("alien.png")) std::cout << "Texture Error" << std::endl; //Load explosion Texture sf::Texture ExplosionTexture; if (!ExplosionTexture.loadFromFile("explosion_5.png")) std::cout << "Texture Error" << std::endl; //Load coin texture sf::Texture Cointexture; if (!Cointexture.loadFromFile("coinsprite.png")) std::cout << "Texture Error" << std::endl; //Load mine texture sf::Texture MineTexture; if (!MineTexture.loadFromFile("spacestation.png")) std::cout << "Texture Error" << std::endl; //Load Font sf::Font Font; if (!Font.loadFromFile("ARIAL.TTF")) std::cout << "Texture Error FONT" << std::endl; //Create Player class Player Player1; //Create bullets //Playerbullets class Bullet bullet1(BulletTexture, 1, false); class Bullet bullet2(BulletTexture, 2, false); class Bullet bullet3(BulletTexture, 3, false); class Bullet enemybullet(BulletTexture, 4, true); //Create Fighter class Fighter Fighter1; //LoadTexturesToObjects Player1._Sprite.setTexture(PlayerTexture); //Player Fighter1._Sprite.setTexture(FighterTexture); //Fighter //Load Font to text object Player1._Text.setFont(Font); Player1._Text2.setFont(Font); //Create player bullet vectors vector<Bullet>::const_iterator iter; vector<Bullet> bulletArray; //Create Fighter vectors vector<Fighter>::const_iterator iter1; vector<Fighter> fighterArray; //TESTBULLETARRAY vector<Bullet>::const_iterator iter3; vector<Bullet> TESTbulletArray; //EXPLOASIONVECTOR vector<Explosion>::const_iterator iterexp; vector<Explosion> Explosionvector; typedef std::vector<Powerups*> powerupvector; powerupvector powerups1; // Local variables for position of player int pposx; int pposy; sf::FloatRect globalbounds; //Local score variable int score; //Game Loop while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); else if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) window.close(); } window.clear(); //Clear Window //Give value to local variables for player position globalbounds = Player1._Sprite.getGlobalBounds(); pposx = Player1._Sprite.getPosition().x; pposy = Player1._Sprite.getPosition().y; //TIMERS sf::Time elapsed1 = clock.getElapsedTime(); sf::Time elapsed2 = clock2.getElapsedTime(); sf::Time Framerate = clock3.getElapsedTime(); sf::Time elapsedSpawn = enemySpawnClock.getElapsedTime(); sf::Time poweruptime = clockpowerup.getElapsedTime(); //DELETE OBJECTS counter = 0; for (iter = bulletArray.begin(); iter != bulletArray.end(); iter++) { if (bulletArray[counter].checkColl(window.getSize().x, window.getSize().y) == true || bulletArray[counter].destroy == true) { bulletArray.erase(iter); break; } counter++; } counter = 0; for (iter1 = fighterArray.begin(); iter1 != fighterArray.end(); iter1++) { if (fighterArray[counter].Destroy(window.getSize().x, window.getSize().y) == true || fighterArray[counter].dead == true) { Explosionvector.push_back(Explosion(fighterArray[counter]._Sprite.getPosition().x, fighterArray[counter]._Sprite.getPosition().y, ExplosionTexture)); fighterArray.erase(iter1); break; } counter++; } //PLAYER MOVEMENT------------------------------------------------ if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) { //Move Up Player1.moveUp(); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) { //Move Down Player1.moveDown(window.getSize().y); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) { //Move Right Player1.moveRight(window.getSize().x); } if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) { //Move Left Player1.moveLeft(); } //firebutton if (elapsed1.asSeconds() >= Player1.attackSpeed) { clock.restart(); if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) { if (bulletArray.size()) { //bullet1.dir(Player1, bullet1); // Update directions of bullets for different directions (Uncomment in bullet.h and in bullet.cpp file ) bullet1.fire(pposx, pposy); bulletArray.push_back(bullet1); bullet2.fire1(pposx, pposy); bulletArray.push_back(bullet2); bullet3.fire2(pposx, pposy); bulletArray.push_back(bullet3); } } } //Player SPRINT if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift)) { Player1.setSpeed(0.15); } else { Player1.setSpeed(0.10); } //End player movement---------------------------------------------- //POWERUPS if (poweruptime.asSeconds() >= 1) { clockpowerup.restart(); powerups1.push_back(new Nscorepowerup(MineTexture)); powerups1.push_back(new Scorepowerup(Cointexture)); } //ENEMY------------------------------------------------------------ //Enemy spawns if (elapsedSpawn.asSeconds() >= 3) { if (fighterArray.size() <= 3) { Fighter1.randomnspawnerEnemies(); fighterArray.push_back(Fighter1); } enemySpawnClock.restart(); } //Enemy bullets if (elapsed2.asSeconds() >= Fighter1.attackSpeed) { clock2.restart(); counter = 0; for (iter1 = fighterArray.begin(); iter1 != fighterArray.end(); iter1++) { enemybullet.enemyfire(fighterArray[counter]._Sprite.getPosition().x, fighterArray[counter]._Sprite.getPosition().y); bulletArray.push_back(enemybullet); counter++; } } //COLLISIONS --------------------------------------------------------------------------------------------------------------------------- //Player Bullets Collide With Fighter if (Framerate.asMilliseconds() >= 30) { if (Framerate.asMilliseconds() >= 1) { clock3.restart(); counter = 0; for (iter = bulletArray.begin(); iter != bulletArray.end(); iter++) { counter1 = 0; if (!bulletArray[counter].Enemybullet) { for (iter1 = fighterArray.begin(); iter1 != fighterArray.end(); iter1++) { if (bulletArray[counter]._Sprite.getGlobalBounds().intersects(fighterArray[counter1]._Sprite.getGlobalBounds())) { bulletArray[counter].destroy = true; fighterArray[counter1].dead = true; Player1.setTextObjectsScore(1); break; } counter1++; } } counter++; } } //Enemy Bullets Collide With Player if (Framerate.asMilliseconds() >= 1) { clock3.restart(); counter = 0; for (iter = bulletArray.begin(); iter != bulletArray.end(); iter++) { if (bulletArray[counter].Enemybullet) { if (bulletArray[counter]._Sprite.getGlobalBounds().intersects(globalbounds)) { bulletArray[counter].destroy = true; Player1.setTextObjectsHealth(1); break; } } counter++; } } //Player collides with fighter if (Framerate.asMilliseconds() >= 1) { clock3.restart(); counter = 0; for (iter1 = fighterArray.begin(); iter1 != fighterArray.end(); iter1++) { if (fighterArray[counter]._Sprite.getGlobalBounds().intersects(Player1._Sprite.getGlobalBounds())) { fighterArray[counter].dead = true; Player1.setTextObjectsHealth(0); Explosionvector.push_back(Explosion(fighterArray[counter]._Sprite.getPosition().x, fighterArray[counter]._Sprite.getPosition().y, ExplosionTexture)); break; } counter++; } } } //if player is dead if (Player1.hp <= 0) { window.close(); } //Draw objects----------------------------------------------------- window.draw(background); //Draw bullets----------------------------------------------------- counter = 0; for (iter = bulletArray.begin(); iter != bulletArray.end(); iter++) { if (!bulletArray[counter].Enemybullet) { bulletArray[counter].updateDir(Player1._projectileSpeed, bulletArray[counter].type); window.draw(bulletArray[counter]._Sprite); } else { bulletArray[counter].updateDir(Fighter1._projectileSpeed, bulletArray[counter].type); window.draw(bulletArray[counter]._Sprite); } counter++; } //Draw Fighters --------- ------------ ------------ ---------- -------- counter = 0; for (iter1 = fighterArray.begin(); iter1 != fighterArray.end(); iter1++){ fighterArray[counter].dir(fighterArray[counter].checkColl(window.getSize().x, window.getSize().y)); window.draw(fighterArray[counter]._Sprite); counter++; } //DRAW EXPLOSIONS counter = 0; for (iterexp = Explosionvector.begin(); iterexp != Explosionvector.end(); iterexp++) { window.draw(Explosionvector[counter]._Sprite); sf::Time explotime = Explosionvector[counter].Clock.getElapsedTime(); if (explotime.asSeconds() >= 1) { Explosionvector.erase(iterexp); break; } counter++; } //Draw powerups and tick them and destroy them if collision is detected for (powerupvector::size_type i = 0; i < powerups1.size(); i++) { window.draw(powerups1.at(i)->Getsprite()); score = powerups1.at(i)->tick(pposx,pposy, Player1.score, globalbounds); if (powerups1.at(i)->isactive == false) { powerups1.erase(powerups1.begin() + i); } Player1.score = score; } Player1.setTextObjectsScore(0); window.draw(Player1._Sprite); //Draw Player Sprite window.draw(Player1._Text); //Draw player hp window.draw(Player1._Text2); //Draw player score window.display(); //Display Window } return 0; }
//It is very hard to wash and especially to dry clothes in winter. But Jane is a very smart girl. //She is not afraid of this boring process. Jane has decided to use a radiator to make drying faster. // But the radiator is small, so it can hold only one thing at a time. // //Jane wants to perform drying in the minimal possible time. She asked you to write a program that // will calculate the minimal time for a given set of clothes. // //There are n clothes Jane has just washed. Each of them took ai water during washing. Every minute //the amount of water contained in each thing decreases by one //(of course, only if the thing is not completely dry yet). When amount of water contained becomes //zero the cloth becomes dry and is ready to be packed. // //Every minute Jane can select one thing to dry on the radiator. The radiator is very hot, so the //amount of water in this thing decreases by k this minute //(but not less than zero — if the thing contains less than k water, the resulting amount of water // will be zero). // //The task is to minimize the total time of drying by means of using the radiator effectively. The //drying process ends when all the clothes are dry. // ///**Input*/ //The first line contains a single integer n (1 ≤ n ≤ 100 000). The second line contains ai separated //by spaces (1 ≤ ai ≤ 109). The third line contains k (1 ≤ k ≤ 109). // ///**Output*/ //Output a single integer — the minimal possible number of minutes required to dry all clothes. /** *设将一件衣服弄干共需要x分钟,设烘干的时间为y,则自然干的时间为(x-y), *将衣服弄干的条件即为k*y+(x-y)>= a [i],化简为:y*(k-1)+x >= a[i],因此y = (a[i]-x)/(k-1)。 *ok函数用于测试总时间 */ #include <iostream> #include<cstdio> #include<algorithm> using namespace std; long long a[100005]; long long b[100005]; long long N,k; bool ok(long long t) { long long ans = 0; for(int i=0; i<N; i++) { b[i] = a[i]-t; } for(int i=0; i<N; i++) { if(b[i]>0) { if(b[i]%(k-1)==0) { ans+=b[i]/(k-1); } else { ans+=b[i]/(k-1); ans++; } } } if(ans>t) //使用烘干机时间>总时间 return true; else return false; } int main() { int i; long long sum=0; scanf("%lld",&N);//衣服数 // printf("%d\n",N); for(i=0; i<N; i++) { scanf("%lld",&a[i]); // printf("%d\n",t); // q.push(t); } sort(a,a+N); while(scanf("%lld",&k)!=EOF)//每分钟烘干水量 // printf("%d\n",k); { if(k==1) { printf("%lld",a[N-1]); continue; } long long st=0,mid,ed=a[N-1]; while(st<ed-1) { mid = st+(ed-st)/2; if(ok(mid)) st = mid; else ed = mid; } printf("%lld\n",ed); } return 0; } /******网上答案*******/ //设将一件衣服弄干共需要x分钟,设烘干的时间为y,则自然干的时间为(x-y), //将衣服弄干的条件即为k*y+(x-y)>= a [i],化简为:y*(k-1)+x >= a[i],因此y = (a[i]-x)/(k-1)。 // // // // //#include<iostream> //#include<cstdio> //#include<cmath> //#include<string> //#include<algorithm> //#define maxn 100010 //#define LL long long //using namespace std; // //LL a[maxn],b[maxn]; //LL n,k; //bool ck(LL x) //x估计总时间 //{ // for(LL i=1; i<=n; ++i) // b[i] = a[i]-x; // LL cnt = 0; // for(LL i=1; i<=n; ++i) // { // if(b[i]>0) // { // if(b[i]%(k-1)==0) // cnt+=b[i]/(k-1); //烘干时间y // else // { // cnt+=b[i]/(k-1); // cnt++; // } // } // } // if(cnt>x) // return true; //烘干时间>总时间 // else // return false; //烘干时间<总时间 //} //int main() //{ // while(scanf("%lld",&n)!=EOF) // { // for(LL i=1; i<=n; ++i) // { // scanf("%lld",&a[i]); // } // sort(a+1,a+1+n); // scanf("%lld",&k); // if(k==1) // { // printf("%lld\n",a[n]); // continue; // } // LL l=0,r=a[n],mid=0; // while(l<r-1) // { // mid = l+(r-l)/2; // if(ck(mid)) // { // l = mid; //// cout<<"a"<<l; // } // else // { // r = mid; //// cout<<"b"<<r; // } // } // printf("%lld\n",r); // } // return 0; //} // //
#include <cstdio> #include <iostream> #include <algorithm> #include <cstring> using namespace std; #define maxn 1000005 int a[maxn]; int main() { int n; while(scanf("%d", &n) && n){ int x, ans = 0; //用哈希 memset(a, 0, sizeof(a)); for(int i = 0; i < n; i++){ scanf("%d", &x); a[x]++; //计数 } for(int i = 1; i <= n; i++){ if(i <= 2){ ans += a[i] / 2; a[i] %= 2; }else{ if(a[i] && a[i-1] && a[i-2]){ ans++; a[i]--; a[i-1]--; a[i-2]--; } ans += a[i] / 2; a[i] %= 2; } } printf("%d\n", ans); } }
#ifndef None_HPP #define None_HPP #include <QObject> // Object source comes without any _moc/.moc includes class NonePrivate; class None : public QObject { Q_OBJECT public: None(); ~None(); private: NonePrivate* const d; }; #endif
#include "GeoPosition.h" #include "Route.h" #include "HttpAgent.h" #include <QJsonDocument> #include <QJsonObject> namespace wpp { namespace qt { //#ifndef Q_OS_IOS //GeoPosition(QObject *parent = 0) // : QObject(parent), geoSource(0), // receiver(0), method(0), m_delegate(0) //{ // qDebug() << "GeoPosition()..."; //} //#endif #ifndef Q_OS_IOS //ios implementation in GeoPosition.mm void GeoPosition::requestAuthorization() { } #endif void GeoPosition::checkCountry(const QString& apiKey) { // http://api.map.baidu.com/location/ip?ak=<key>&coor=bd09ll wpp::qt::Route route("", "GET", "api.map.baidu.com", "/location/ip"); QMap<QString, QVariant> reqParams; reqParams["ak"] = apiKey; reqParams["coor"] = "bd09ll"; wpp::qt::HttpAgent &httpAgent = wpp::qt::HttpAgent::getInstance(); httpAgent.async(this,SLOT(onResponseCheckCountry(QNetworkReply*,const QMap<QString, QVariant>&, const QMap<QString, QVariant>&)), "GET", route, reqParams); } void GeoPosition::onResponseCheckCountry(QNetworkReply* reply, const QMap<QString, QVariant>& reqParams, const QMap<QString, QVariant>& args) { qDebug() << __FUNCTION__; if ( wpp::qt::HttpAgent::replyHasError(__FUNCTION__, reply) ) return; QByteArray responseBody = reply->readAll(); QJsonObject json( QJsonDocument::fromJson(responseBody).object() ); /* { "address": "HK|香港|香港|None|None|0|0", "content": { "address": "香港特别行政区", "address_detail": { "city": "香港特别行政区", "city_code": 2912, "district": "", "province": "香港特别行政区", "street": "", "street_number": "" }, "point": { "x": "114.xxxxxx", "y": "22.xxxxx" } }, "status": 0 } */ if ( json["status"].toInt() == 0 ) { QString address = json["address"].toString(); QStringList addressSplits = address.split("|"); QString countryCode = addressSplits.first();//CN, HK, ... qDebug() << "countryCode=" << countryCode; setCountryCode(countryCode); } } } }
/* -*- Mode: c++; indent-tabs-mode: nil; c-file-style: "gnu" -*- * * Copyright (C) 1995-2005 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #ifndef XPVALUE_H #define XPVALUE_H #include "modules/xpath/src/xpdefs.h" class XPath_Node; class XPath_NodeSet; class XPath_NodeList; class XPath_Context; class XPath_Value { private: unsigned refcount; public: XPath_ValueType type; union { XPath_Node *node; XPath_NodeSet *nodeset; XPath_NodeList *nodelist; bool boolean; double number; uni_char *string; XPath_Value *nextfree; } data; static XPath_Value *NewL (XPath_Context *context); static void Free (XPath_Context *context, XPath_Value *value); XPath_Value (); ~XPath_Value (); void Reset (XPath_Context *context); void SetFree (XPath_Context *context, XPath_Value *nextfree); BOOL AsBoolean (); double AsNumberL (); const uni_char *AsStringL (TempBuffer &buffer); static double AsNumber (const uni_char *string); static double AsNumberL (const uni_char *string, unsigned string_length); static const uni_char *AsString (BOOL boolean); static const uni_char *AsStringL (double number, TempBuffer &buffer); XPath_Value *ConvertToBooleanL (XPath_Context *context); XPath_Value *ConvertToNumberL (XPath_Context *context); XPath_Value *ConvertToStringL (XPath_Context *context); BOOL IsValid () { return type == XP_VALUE_INVALID; } static XPath_Value *MakeL (XPath_Context *context, XPath_ValueType type); static XPath_Value *MakeBooleanL (XPath_Context *context, BOOL value); static XPath_Value *MakeNumberL (XPath_Context *context, double number); static XPath_Value *MakeStringL (XPath_Context *context, const uni_char *string = 0, unsigned length = ~0u); static XPath_Value *IncRef (XPath_Value *value); static void DecRef (XPath_Context *context, XPath_Value *value); static double Zero (); }; class XPath_ValueAnchor { protected: XPath_Context *context; XPath_Value *value; public: XPath_ValueAnchor (XPath_Context *context, XPath_Value *value); ~XPath_ValueAnchor (); }; #define XP_ANCHOR_VALUE(context, name) XPath_ValueAnchor name##anchor(context, name); #endif // XPVALUE_H
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 44722; int prime[maxn + 10],vis[maxn + 10],m; int cou[maxn + 10]; vector<int> sav; void init() { memset(vis,0,sizeof(vis)); for (int i = 2;i <= maxn; i++) if (!vis[i]) { vis[i] = true; prime[m++] = i; for (int j = i << 1;j <= maxn; j += i) vis[j] = true; } } int main() { int t; init(); scanf("%d",&t); while (t--) { int n,k; memset(cou,0,sizeof(cou)); sav.clear(); scanf("%d",&n); for (int i = 1;i <= n; i++) { scanf("%d",&k); for (int j = 0;j < m; j++) { while (!(k%prime[j])) {k /= prime[j]; cou[j]++;} if (k == 1) break; } if (k != 1) sav.push_back(k); } sort(sav.begin(),sav.end()); long long s1 = -1,s2 = -1; for (int j = 0;j < m; j++) { if (cou[j] && s1 == -1) {s1 = prime[j];cou[j]--;} if (cou[j] && s2 == -1) {s2 = prime[j];cou[j]--;} if (s1 != -1 && s2 != -1) break; } if (s2 == -1) if (s1 == -1) { if (sav.size() > 1) s1 = sav[0],s2 = sav[1]; } else { if (sav.size() > 0) s2 = sav[0]; } if (s1 == -1 && s2 == -1) printf("-1\n"); else printf("%lld\n",s1*s2); } return 0; }
#include <bits/stdc++.h> using namespace std; #define TESTC "" #define PROBLEM "1225" #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) int main(int argc, char const *argv[]) { #ifdef DBG freopen("uva" PROBLEM TESTC ".in", "r", stdin); freopen("uva" PROBLEM ".out", "w", stdout); #endif int table[10005][10]; memset(table,0,sizeof(table)); int tmp,i,j; for( i = 1 ; i < 10005 ; i++ ){ tmp = i; for( j = 0 ; j < 10 ; j++ ) table[i][j] = table[i-1][j]; while( tmp > 0 ){ j = tmp%10; tmp = tmp/10; table[i][j]++; } } int times,number; scanf("%d",&times); while( times-- ){ scanf("%d",&number); for( i = 0 ; i < 9 ; i++ ) printf("%d ",table[number][i] ); printf("%d\n",table[number][9] ); } return 0; }
#include "Road.hpp"// change this to Road #include "Animal.hpp" #include "Tortoise.hpp" #include "Hare.hpp" #include "Elephant.hpp" #include "Duck.hpp" #include "Competition.hpp" //#include "Road.cpp" // delete this if it doesnot work #include<iostream> #include<string> using namespace std; int main() { Competition game; game.addRoad(100); Hare rabbit; Tortoise tor; //Elephant elephant; //Dog dog; Elephant elephant; game.addPlayer(&rabbit); //game.start(); //Tortoise tor; //Dog dawg; game.addPlayer(&tor); //game.addPlayer(&elephant); //game.addPlayer(&dog); int pattern[] = {1, 2, -1, 5, 0}; int size = sizeof(pattern)/ sizeof(pattern[0]); Duck duck("Duck", 'D', pattern , size, 0); game.addPlayer(&duck); game.addPlayer(&elephant); game.start(); //clear(); return 0; }
#include<cstdio> #include<cstring> using namespace std; bool e[1048576]; int main() { int n; scanf("%d",&n); while(1) { int d,i; scanf("%d",&d); if(d==-1) break; else scanf("%d",&i); int d1=d,ans=1; while(i>0) { while(d1>1) { d1--; e[ans]=!e[ans]; if(e[ans]==1) ans=ans*2; else ans=ans*2+1; } i--; if(i==0) printf("%d\n",ans); d1=d; ans=1; } memset(e,0,sizeof(e)); } fclose(stdin); fclose(stdout); }
#include<bits/stdc++.h> using namespace std; #define ll long long ll t, n, k,a[5001], ans, incmnm, incmxm; int findAnswer(ll index,ll i,ll currentAnswer[], ll mnm,ll mxm){ if(index == k){ // cout << currentAnswer<< mnm << mxm; // currentAnswer[] /= (mnm * mxm); // ans *= currentAnswer; for (int j = 0; j < k; j++) ans *= currentAnswer[j]; ans /= (mnm * mxm); ans %= (1000000000 + 7); // cout <<mnm << mxm << endl; return 0; } if(i >= n) return 0; currentAnswer[index] = a[i]; incmnm = min(mnm, a[i]); incmxm = max(mxm, a[i]); // include current ele(a[i]) findAnswer(index + 1, i + 1, currentAnswer, incmnm, incmxm); // exclude current ele (a[i]) findAnswer(index, i + 1, currentAnswer, mnm, mxm); } int main(){ cin >> t; for(ll _ = 0; _ < t; _++){ cin >> n >> k; for(int i = 0; i < n; i++) cin >> a[i]; ans = 1; ll temp[k]; findAnswer(0, 0,temp, 10001, -1); cout << ans<< endl; } }
// 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 "DaemonCommandsHandler.h" #include "P2p/NetNode.h" #include "Common/Util.h" #include "CryptoNoteCore/Miner.h" #include "CryptoNoteCore/Core.h" #include "CryptoNoteCore/Currency.h" #include "CryptoNoteProtocol/CryptoNoteProtocolHandler.h" #include "Serialization/SerializationTools.h" #include "version.h" namespace { template <typename T> static bool print_as_json(const T &obj) { std::cout << cn::storeToJson(obj) << ENDL; return true; } } // namespace DaemonCommandsHandler::DaemonCommandsHandler(cn::core &core, cn::NodeServer &srv, logging::LoggerManager &log) : m_core(core), m_srv(srv), logger(log, "daemon"), m_logManager(log) { m_consoleHandler.setHandler("exit", boost::bind(&DaemonCommandsHandler::exit, this, boost::arg<1>()), "Shutdown the daemon"); m_consoleHandler.setHandler("help", boost::bind(&DaemonCommandsHandler::help, this, boost::arg<1>()), "Show this help"); m_consoleHandler.setHandler("save", boost::bind(&DaemonCommandsHandler::save, this, boost::arg<1>()), "Save the Blockchain data safely"); m_consoleHandler.setHandler("print_pl", boost::bind(&DaemonCommandsHandler::print_pl, this, boost::arg<1>()), "Print peer list"); m_consoleHandler.setHandler("rollback_chain", boost::bind(&DaemonCommandsHandler::rollback_chain, this, boost::arg<1>()), "Rollback chain to specific height, rollback_chain <height>"); m_consoleHandler.setHandler("print_cn", boost::bind(&DaemonCommandsHandler::print_cn, this, boost::arg<1>()), "Print connections"); m_consoleHandler.setHandler("print_bci", boost::bind(&DaemonCommandsHandler::print_bci, this, boost::arg<1>()), "Print blockchain current height"); m_consoleHandler.setHandler("print_bc", boost::bind(&DaemonCommandsHandler::print_bc, this, boost::arg<1>()), "Print blockchain info in a given blocks range, print_bc <begin_height> [<end_height>]"); m_consoleHandler.setHandler("print_block", boost::bind(&DaemonCommandsHandler::print_block, this, boost::arg<1>()), "Print block, print_block <block_hash> | <block_height>"); m_consoleHandler.setHandler("print_stat", boost::bind(&DaemonCommandsHandler::print_stat, this, boost::arg<1>()), "Print statistics, print_stat <nothing=last> | <block_hash> | <block_height>"); m_consoleHandler.setHandler("print_tx", boost::bind(&DaemonCommandsHandler::print_tx, this, boost::arg<1>()), "Print transaction, print_tx <transaction_hash>"); m_consoleHandler.setHandler("start_mining", boost::bind(&DaemonCommandsHandler::start_mining, this, boost::arg<1>()), "Start mining for specified address, start_mining <addr> [threads=1]"); m_consoleHandler.setHandler("stop_mining", boost::bind(&DaemonCommandsHandler::stop_mining, this, boost::arg<1>()), "Stop mining"); m_consoleHandler.setHandler("print_pool", boost::bind(&DaemonCommandsHandler::print_pool, this, boost::arg<1>()), "Print transaction pool (long format)"); m_consoleHandler.setHandler("print_pool_sh", boost::bind(&DaemonCommandsHandler::print_pool_sh, this, boost::arg<1>()), "Print transaction pool (short format)"); m_consoleHandler.setHandler("show_hr", boost::bind(&DaemonCommandsHandler::show_hr, this, boost::arg<1>()), "Start showing hash rate"); m_consoleHandler.setHandler("hide_hr", boost::bind(&DaemonCommandsHandler::hide_hr, this, boost::arg<1>()), "Stop showing hash rate"); m_consoleHandler.setHandler("set_log", boost::bind(&DaemonCommandsHandler::set_log, this, boost::arg<1>()), "set_log <level> - Change current log level, <level> is a number 0-4"); } const std::string DaemonCommandsHandler::get_commands_str() { std::stringstream ss; ss << CCX_RELEASE_VERSION << std::endl; ss << "Commands: " << std::endl; std::string usage = m_consoleHandler.getUsage(); boost::replace_all(usage, "\n", "\n "); usage.insert(0, " "); ss << usage << std::endl; return ss.str(); } bool DaemonCommandsHandler::exit(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"exit\""; return true; } logger(logging::DEBUGGING) << "Attempting: exit"; m_consoleHandler.requestStop(); m_srv.sendStopSignal(); logger(logging::DEBUGGING) << "Finished: exit"; return true; } bool DaemonCommandsHandler::help(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"help\""; return true; } logger(logging::DEBUGGING) << "Attempting: help"; logger(logging::INFO) << get_commands_str(); logger(logging::DEBUGGING) << "Finished: help"; return true; } bool DaemonCommandsHandler::save(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"save\""; return true; } logger(logging::DEBUGGING) << "Attempting: save"; if(!m_core.saveBlockchain()) { logger(logging::ERROR) << "Could not save the blockchain data!"; return false; } logger(logging::DEBUGGING) << "Finished: save"; return true; } bool DaemonCommandsHandler::print_pl(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"print_pl\""; return true; } logger(logging::DEBUGGING) << "Attempting: print_pl"; m_srv.log_peerlist(); logger(logging::DEBUGGING) << "Finished: print_pl"; return true; } bool DaemonCommandsHandler::show_hr(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"show_hr\""; return true; } logger(logging::DEBUGGING) << "Attempting: show_hr"; if (!m_core.get_miner().is_mining()) logger(logging::WARNING) << "Mining is not started. You need to start mining before you can see hash rate."; else m_core.get_miner().do_print_hashrate(true); logger(logging::DEBUGGING) << "Finished: show_hr"; return true; } bool DaemonCommandsHandler::hide_hr(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"hide_hr\""; return true; } logger(logging::DEBUGGING) << "Attempting: hide_hr"; m_core.get_miner().do_print_hashrate(false); logger(logging::DEBUGGING) << "Finished: hide_hr"; return true; } bool DaemonCommandsHandler::print_cn(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"print_cn\""; return true; } logger(logging::DEBUGGING) << "Attempting: print_cn"; m_srv.get_payload_object().log_connections(); logger(logging::DEBUGGING) << "Finished: print_cn"; return true; } bool DaemonCommandsHandler::print_bc(const std::vector<std::string> &args) { if (!args.size()) { logger(logging::ERROR) << "Usage: \"print_bc <block_from> [<block_to>]\""; return false; } logger(logging::DEBUGGING) << "Attempting: print_bc"; uint32_t start_index = 0; uint32_t end_index = 0; uint32_t end_block_parametr = m_core.get_current_blockchain_height(); if (!common::fromString(args[0], start_index)) { logger(logging::ERROR) << "Incorrect start block!"; return false; } if (args.size() > 1 && !common::fromString(args[1], end_index)) { logger(logging::ERROR) << "Incorrect end block!"; return false; } if (end_index == 0) end_index = end_block_parametr; if (end_index > end_block_parametr) { logger(logging::ERROR) << "end block shouldn't be greater than " << end_block_parametr; return false; } if (end_index <= start_index) { logger(logging::ERROR) << "end block should be greater than starter block index"; return false; } m_core.print_blockchain(start_index, end_index); logger(logging::DEBUGGING) << "Finished: print_bc"; return true; } bool DaemonCommandsHandler::print_bci(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"print_bci\""; return true; } logger(logging::DEBUGGING) << "Attempting: print_bci"; m_core.print_blockchain_index(false); logger(logging::DEBUGGING) << "Finished: print_bci"; return true; } bool DaemonCommandsHandler::set_log(const std::vector<std::string> &args) { if (args.size() != 1) { logger(logging::ERROR) << "Usage: \"set_log <0-4>\" 0-4 being log level."; return true; } logger(logging::DEBUGGING) << "Attempting: set_log"; uint16_t l = 0; if (!common::fromString(args[0], l)) { logger(logging::ERROR) << "Incorrect number format, use: set_log <0-4> (0-4 being log level)"; return true; } ++l; if (l > logging::TRACE) { logger(logging::ERROR) << "Incorrect number range, use: set_log <0-4> (0-4 being log level)"; return true; } m_logManager.setMaxLevel(static_cast<logging::Level>(l)); logger(logging::DEBUGGING) << "Finished: set_log"; return true; } bool DaemonCommandsHandler::print_block_by_height(uint32_t height) { logger(logging::DEBUGGING) << "Attempting: print_block_by_height"; std::list<cn::Block> blocks; m_core.get_blocks(height, 1, blocks); if (1 == blocks.size()) { logger(logging::INFO) << "block_id: " << get_block_hash(blocks.front()); print_as_json(blocks.front()); } else { uint32_t current_height; crypto::Hash top_id; m_core.get_blockchain_top(current_height, top_id); logger(logging::ERROR) << "block wasn't found. Current block chain height: " << current_height << ", requested: " << height; return false; } logger(logging::DEBUGGING) << "Finished: print_block_by_height"; return true; } bool DaemonCommandsHandler::rollback_chain(const std::vector<std::string> &args) { if (args.empty()) { logger(logging::ERROR) << "Usage: \"rollback_chain <block_height>\""; return true; } logger(logging::DEBUGGING) << "Attempting: rollback_chain"; const std::string &arg = args.front(); uint32_t height = boost::lexical_cast<uint32_t>(arg); rollbackchainto(height); logger(logging::DEBUGGING) << "Finished: rollback_chain"; return true; } bool DaemonCommandsHandler::rollbackchainto(uint32_t height) { logger(logging::DEBUGGING) << "Attempting: rollbackchainto"; m_core.rollback_chain_to(height); logger(logging::DEBUGGING) << "Finished: rollbackchainto"; return true; } bool DaemonCommandsHandler::print_block_by_hash(const std::string &arg) { logger(logging::DEBUGGING) << "Attempting: print_block_by_hash"; crypto::Hash block_hash; if (!parse_hash256(arg, block_hash)) return false; std::list<crypto::Hash> block_ids; block_ids.push_back(block_hash); std::list<cn::Block> blocks; std::list<crypto::Hash> missed_ids; m_core.get_blocks(block_ids, blocks, missed_ids); if (1 == blocks.size()) { print_as_json(blocks.front()); } else { logger(logging::ERROR) << "block wasn't found: " << arg; return false; } logger(logging::DEBUGGING) << "Finished: print_block_by_hash"; return true; } uint64_t DaemonCommandsHandler::calculatePercent(const cn::Currency &currency, uint64_t value, uint64_t total) { logger(logging::DEBUGGING) << "Attempting: calculatePercent"; double to_calc = (double)currency.coin() * static_cast<double>(value) / static_cast<double>(total); logger(logging::DEBUGGING) << "Finished: calculatePercent"; return static_cast<uint64_t>(100.0 * to_calc); } bool DaemonCommandsHandler::print_stat(const std::vector<std::string> &args) { logger(logging::DEBUGGING) << "Attempting: print_stat"; uint32_t height = 0; uint32_t maxHeight = m_core.get_current_blockchain_height() - 1; if (args.empty()) { height = maxHeight; } else { try { height = boost::lexical_cast<uint32_t>(args.front()); } catch (boost::bad_lexical_cast &) { crypto::Hash block_hash; if (!parse_hash256(args.front(), block_hash) || !m_core.getBlockHeight(block_hash, height)) { return false; } } if (height > maxHeight) { logger(logging::INFO) << "printing for last available block: " << maxHeight; height = maxHeight; } } uint64_t totalCoinsInNetwork = m_core.coinsEmittedAtHeight(height); uint64_t totalCoinsOnDeposits = m_core.depositAmountAtHeight(height); uint64_t amountOfActiveCoins = totalCoinsInNetwork - totalCoinsOnDeposits; const auto &currency = m_core.currency(); std::string print_status = "\n"; print_status += "Block Height: " + std::to_string(height) + "\n"; print_status += "Block Difficulty: " + std::to_string(m_core.difficultyAtHeight(height)) + "\n"; print_status += "Coins Minted (Total Supply): " + currency.formatAmount(totalCoinsInNetwork) + "\n"; print_status += "Deposits (Locked Coins): " + currency.formatAmount(totalCoinsOnDeposits) + " (" + currency.formatAmount(calculatePercent(currency, totalCoinsOnDeposits, totalCoinsInNetwork)) + "%)\n"; print_status += "Active Coins (Circulation Supply): " + currency.formatAmount(amountOfActiveCoins) + " (" + currency.formatAmount(calculatePercent(currency, amountOfActiveCoins, totalCoinsInNetwork)) + "%)\n"; print_status += "Rewards (Paid Interest): " + currency.formatAmount(m_core.depositInterestAtHeight(height)) + "\n"; logger(logging::INFO) << print_status; logger(logging::DEBUGGING) << "Finished: print_stat"; return true; } bool DaemonCommandsHandler::print_block(const std::vector<std::string> &args) { if (args.empty()) { logger(logging::ERROR) << "Usage: print_block <block_hash> | <block_height>"; return true; } logger(logging::DEBUGGING) << "Attempting: print_block"; const std::string &arg = args.front(); try { uint32_t height = boost::lexical_cast<uint32_t>(arg); print_block_by_height(height); } catch (boost::bad_lexical_cast &) { print_block_by_hash(arg); } logger(logging::DEBUGGING) << "Finished: print_block"; return true; } bool DaemonCommandsHandler::print_tx(const std::vector<std::string> &args) { if (args.empty()) { logger(logging::ERROR) << "Usage: print_tx <transaction hash>"; return true; } logger(logging::DEBUGGING) << "Attempting: print_tx"; const std::string &str_hash = args.front(); crypto::Hash tx_hash; if (!parse_hash256(str_hash, tx_hash)) return true; std::vector<crypto::Hash> tx_ids; tx_ids.push_back(tx_hash); std::list<cn::Transaction> txs; std::list<crypto::Hash> missed_ids; m_core.getTransactions(tx_ids, txs, missed_ids, true); if (1 == txs.size()) print_as_json(txs.front()); else logger(logging::ERROR) << "Transaction was not found: <" << str_hash << ">"; logger(logging::DEBUGGING) << "Finished: print_tx"; return true; } bool DaemonCommandsHandler::print_pool(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"print_pool\""; return true; } logger(logging::DEBUGGING) << "Attempting: print_pool"; logger(logging::INFO) << "Pool state: \n" << m_core.print_pool(false); logger(logging::DEBUGGING) << "Finished: print_pool"; return true; } bool DaemonCommandsHandler::print_pool_sh(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"print_pool_sh\""; return true; } logger(logging::DEBUGGING) << "Attempting: print_pool_sh"; logger(logging::INFO) << "Pool state: \n" << m_core.print_pool(true); logger(logging::DEBUGGING) << "Finished: print_pool_sh"; return true; } bool DaemonCommandsHandler::start_mining(const std::vector<std::string> &args) { if (args.empty()) { logger(logging::ERROR) << "Usage: start_mining <addr> [threads=1]"; return true; } logger(logging::DEBUGGING) << "Attempting: start_mining"; cn::AccountPublicAddress adr; if (!m_core.currency().parseAccountAddressString(args.front(), adr)) { logger(logging::ERROR) << "Invalid wallet address!"; return true; } size_t threads_count = 1; if (args.size() > 1) { bool ok = common::fromString(args[1], threads_count); threads_count = (ok && 0 < threads_count) ? threads_count : 1; } m_core.get_miner().start(adr, threads_count); logger(logging::DEBUGGING) << "Finished: start_mining"; return true; } bool DaemonCommandsHandler::stop_mining(const std::vector<std::string> &args) { if (!args.empty()) { logger(logging::ERROR) << "Usage: \"stop_mining\""; return true; } logger(logging::DEBUGGING) << "Attempting: stop_mining"; m_core.get_miner().stop(); logger(logging::DEBUGGING) << "Finished: stop_mining"; return true; }
#include "Background.h" #include <iostream> void Background::sort(int* tab) { int tmp; for (int i = 0; i < sizeof(tab); i++) { for (int j = 0; j < sizeof(tab) - 1; j++) { if (tab[i] > tab[j]) { tmp = tab[i]; tab[i] = tab[j]; tab[j] = tmp; } } } } void Background::median(std::vector<Image> images, Image* bg) { int size = images.size(); int* r = new int[size]; int* g = new int[size]; int* b = new int[size]; for (int x = 0; x < images.at(0).getHeight(); x++) { for (int y = 0; y < images.at(0).getWidth(); y++) { for (int i = 0; i < size; i++) { r[i] = images.at(i).getColor(x, y).r; g[i] = images.at(i).getColor(x, y).g; b[i] = images.at(i).getColor(x, y).b; } sort(r); sort(g); sort(b); Color c; c.r = r[int(size / 2)]; c.g = g[int(size / 2)]; c.b = b[int(size / 2)]; bg->setColor(x, y, c); } } }
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/core/core.hpp> #include <algorithm> #include <std_msgs/Int32.h> #include <std_msgs/Float32MultiArray.h> #include <std_msgs/Bool.h> #include <geometry_msgs/Pose.h> #include <apriltags/AprilTagDetections.h> #include <visualization_msgs/MarkerArray.h> //#include <explore/costmap_client.h> using namespace cv; using namespace std; static const std::string OPENCV_WINDOW = "Pokemon Search"; static const std::string GREY_WINDOW = "灰度"; static const std::string CANNY_WINDOW = "canny"; bool good = false; Mat img; int fileNum = 1; int zeroCount = 0; bool flag = false; bool listen_tag = true; vector<bool> tagTake(100); map<int, geometry_msgs::Pose> tagMap; map<int, double> tagNumric; unsigned last_markers_count_ = 0; class Searcher { ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber image_sub_; ros::Publisher image_pub_; ros::Subscriber save_sub_; ros::Publisher tag_pub_; ros::Subscriber camera_sub_; ros::Subscriber tag_sub_; ros::Publisher marker_array_publisher_; // tf::TransformListener tf_listener_; // Costmap2DClient costmap_client_; public: Searcher() : it_(nh_) { // Subscribe to input video feed and publish output video feed image_sub_ = it_.subscribe("/camera/rgb/image_raw", 1, &Searcher::imageCb, this); save_sub_ = nh_.subscribe("/pokemon_go/save", 1, &Searcher::saveImg, this); image_pub_ = nh_.advertise<std_msgs::Int32>("/pokemon_go/searcher", 1); tag_pub_ = nh_.advertise<geometry_msgs::Pose>("/apriltag_pose", 1); tag_sub_ = nh_.subscribe("/apriltags/detections", 1, &Searcher::collect_tag, this); // camera_sub_ = nh_.subscribe("/apriltag_save", 1, &Searcher::screenShot, this); marker_array_publisher_ = nh_.advertise<visualization_msgs::MarkerArray>("tags", 5); // tf_listener_ = tf::TransformListener(ros::Duration(10.0)); // costmap_client_ = Costmap2DClient(nh_, nh_, &tf_listener_); cv::namedWindow(OPENCV_WINDOW); // cv::namedWindow(GREY_WINDOW); // cv::namedWindow(CANNY_WINDOW); } ~Searcher() { cv::destroyWindow(OPENCV_WINDOW); // cv::destroyWindow(GREY_WINDOW); } void collect_tag(const apriltags::AprilTagDetections &apriltags) { for (auto atg : apriltags.detections) { tagMap[atg.id] = atg.pose; double tmp = atg.pose.orientation.x + atg.pose.orientation.y + atg.pose.orientation.z + atg.pose.orientation.w; // printf("id:%d x:%f y:%f z:%f w:%f sum:%f\n", atg.id, atg.pose.orientation.x, atg.pose.orientation.y, // atg.pose.orientation.z, atg.pose.orientation.w, tmp); if (abs(tagNumric[atg.id] - tmp) > 0.1 && good && tagTake[atg.id] == false) { tagTake[atg.id] = true; tagNumric[atg.id] = tmp; autoSave(); } } visualizeFrontiers(); } void visualizeFrontiers() { ROS_DEBUG("visualising %lu tags", tagMap.size()); visualization_msgs::MarkerArray markers_msg; std::vector <visualization_msgs::Marker> &markers = markers_msg.markers; visualization_msgs::Marker m; m.header.frame_id = "/my_frame"; m.header.stamp = ros::Time::now(); m.ns = "tags"; m.scale.x = 1.0; m.scale.y = 1.0; m.scale.z = 1.0; m.color.r = 0; m.color.g = 0; m.color.b = 255; m.color.a = 255; // lives forever m.lifetime = ros::Duration(0); m.frame_locked = true; m.action = visualization_msgs::Marker::ADD; size_t id = 0; for (auto &tag_iter : tagMap) { m.type = visualization_msgs::Marker::POINTS; m.id = int(id); m.scale.x = 0.1; m.scale.y = 0.1; m.scale.z = 0.1; markers.push_back(m); ++id; m.type = visualization_msgs::Marker::SPHERE; m.id = int(id); m.pose.position = tag_iter.second.position; } size_t current_markers_count = markers.size(); // delete previous markers, which are now unused m.action = visualization_msgs::Marker::DELETE; for (; id < last_markers_count_; ++id) { m.id = int(id); markers.push_back(m); } last_markers_count_ = current_markers_count; marker_array_publisher_.publish(markers_msg); } void saveImg(std_msgs::Bool save) { auto it = *(tagMap.begin()); ROS_ERROR("id:%d x:%f y:%f", it.first, it.second.position.x, it.second.position.y); tag_pub_.publish(it.second); } void autoSave() { stringstream stream; stream << "/home/jeremy/pokemon/pokemon" << fileNum << ".jpg"; imwrite(stream.str(), img); cout << "pokemon" << fileNum << " had Saved." << endl; fileNum++; } void screenShot(std_msgs::Bool a) { autoSave(); } void imageCb(const sensor_msgs::ImageConstPtr &msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception &e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } // 传递出去的信息,外框和内框共16个点 std_msgs::Float32MultiArray rect; // Draw an target square on the video stream int height = cv_ptr->image.rows; int width = cv_ptr->image.cols; //detect the white pokemon, 记录白框的四个顶点 Rect r = detect(cv_ptr, width, height); // 78 185 252 240 // 640 480 -> 320 240 // cout << "x: " <<abs((r.br().x+r.tl().x)/2-320) << endl; // cout << "y: " <<abs((r.tl().y+r.br().y)/2-240) << endl; // cout << "width: " <<r.br().x-r.tl().x << endl; float rate = float((r.br().x-r.tl().x))/float((r.br().y-r.tl().y)); // cout << "y_center: " <<(r.tl().y+r.br().y)/2 << endl; // printf("width:%d height%f x_center:%f y_center:%f\n", r.br().x-r.tl().x, r.br().y-r.tl().y, (r.br().x+r.tl().x)/2,(r.tl().y+r.br().y)/2); // printf("width:%d height%d\n", width, height); // if (rate<0.8) cout << rate<< endl; if (abs((r.br().x+r.tl().x)/2-320)<150 && r.tl().y < 240 && r.br().y > 240 && r.br().x - r.tl().x > 120 && rate < 1) { good = true; // cout << "good:"<<rate<< endl; } else good = false; // Update GUI Window cv::imshow(OPENCV_WINDOW, cv_ptr->image); cv::waitKey(3); } Rect detect(cv_bridge::CvImagePtr &cv_ptr, int weight, int height) { int iLowH = 0, iHighH = 180, iLowS = 0, iHighS = 40, iLowV = 200, iHighV = 255; img = cv_ptr->image; Mat imgHSV; vector <Mat> hsvSplit; cvtColor(img, imgHSV, COLOR_BGR2HSV); split(imgHSV, hsvSplit); equalizeHist(hsvSplit[2], hsvSplit[2]); merge(hsvSplit, imgHSV); Mat imgThresholded; inRange(imgHSV, Scalar(iLowH, iLowS, iLowV), Scalar(iHighH, iHighS, iHighV), imgThresholded); //Threshold the image //开操作 (去除一些噪点) Mat element = getStructuringElement(MORPH_RECT, Size(5, 5)); morphologyEx(imgThresholded, imgThresholded, MORPH_OPEN, element); //闭操作 (连接一些连通域) morphologyEx(imgThresholded, imgThresholded, MORPH_CLOSE, element); GaussianBlur(imgThresholded, imgThresholded, Size(3, 3), 0, 0); // imshow(GREY_WINDOW, imgThresholded); Mat cannyImage; Canny(imgThresholded, cannyImage, 128, 255, 3); vector <vector<Point>> contours; vector <Vec4i> hierarchy; findContours(cannyImage, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0)); //绘制轮廓 for (int i = 0; i < (int) contours.size(); i++) { drawContours(cannyImage, contours, i, Scalar(255), 1, 8); } // imshow(CANNY_WINDOW, cannyImage); //用矩形圈出轮廓并返回位置坐标 Point2f vertex[4]; float max_s = 0; int max_idx = 0; vector <Rect> rectangles; vector<int> idx; for (int i = 0; i < contours.size(); i++) { vector <Point> points = contours[i]; RotatedRect box = minAreaRect(Mat(points)); // Point2f tem_vertex[4]; // box.points(tem_vertex); rectangles.push_back(box.boundingRect()); idx.push_back(i); // rectangle(img, rectangles[i].tl(), rectangles[i].br(), CV_RGB(255,0,255)); } vector<int> idxNOT; for (int i = 0; i < idx.size(); i++) { Rect r = rectangles[idx[i]]; if (r.br().y < height / 3) idxNOT.push_back(idx[i]); if (r.tl().y > 3 * height / 5) idxNOT.push_back(idx[i]); } vector<int> diff; std::set_difference(idx.begin(), idx.end(), idxNOT.begin(), idxNOT.end(), std::inserter(diff, diff.begin())); idx = diff; for (int i = 0; i < diff.size(); i++) { rectangle(img, rectangles[diff[i]].tl(), rectangles[diff[i]].br(), CV_RGB(255, 0, 255)); } MERGE: for (int i = 0; i < idx.size(); i++) { int id1 = idx[i]; vector<int> merge; for (int j = i + 1; j < idx.size(); j++) { int id2 = idx[j]; if (id1 != id2 && cross(rectangles[id1], rectangles[id2])) { merge.push_back(id2); } } if (!merge.empty()) { for (int i = 0; i < merge.size(); i++) { idx.erase(find(idx.begin(), idx.end(), merge[i])); } mergeRec(id1, merge, rectangles); goto MERGE; } } for (int i = 0; i < idx.size(); i++) { Rect r = rectangles[idx[i]]; float s = r.area(); if (s > max_s) { max_s = s; max_idx = idx[i]; } rectangle(img, r.tl(), r.br(), CV_RGB(0, 0, 255)); } rectangle(img, rectangles[max_idx].tl(), rectangles[max_idx].br(), CV_RGB(255, 255, 0)); return rectangles[max_idx]; // namedWindow("绘制的最小矩形面积",WINDOW_NORMAL); // imshow("绘制的最小矩形面积",img); } float dis(Point p1, Point p2) { return sqrt(pow((p1.x - p2.x), 2) + pow((p1.y - p2.y), 2)); } bool cross(Rect r1, Rect r2) { int error = 20; return (r1 + Size(0, error) & r2).area() > 0 || (r1 & r2 + Size(0, error)).area() > 0; } void mergeRec(int id, vector<int> &merge, vector <Rect> &rectangles) { for (int i = 0; i < merge.size(); i++) { rectangles[id] = rectangles[id] | rectangles[merge[i]]; } } }; int main(int argc, char** argv) { ros::init(argc, argv, "pokemon_searching"); Searcher ic; ros::spin(); return 0; }
#include "../include/Coin.h" #include "../include/Camera.h" #include "../include/TextureManager.h" #include "../include/CoinScoreManager.h" #include "../include/AudioManager.h" namespace gnGame { Coin::Coin(const Vector2& _pos) : Item() , collider() { this->transform.setPos(_pos); this->sprite.setTexture(TextureManager::getTexture("Coin")); } void Coin::onStart() { } void Coin::onUpdate() { auto screen = Camera::toScreenPos(this->transform.pos); // 画像が16.0f分ずれているので、コライダーの一も16.0fずらす collider.update(screen + Vector2{ 8.0f, 8.0f }, 24.0f); sprite.draw(screen, Vector2::One, 0.0f, false); } void Coin::onCollision(Player& _player) { AudioManager::getIns()->setPosition("SE_coin", 0); AudioManager::getIns()->play("SE_coin"); CoinScoreManager::getIns()->addScore(); } ICollider& gnGame::Coin::getCollider() { return collider; } }
#include <vector> // #include <chuffed/Vec.h> #include <chuffed/core/propagator.h> #include <chuffed/globals/mddglobals.h> #include <chuffed/mdd/MDD.h> #include <chuffed/mdd/mdd_prop.h> #include <chuffed/mdd/opts.h> #include <chuffed/mdd/weighted_dfa.h> #include <chuffed/mdd/wmdd_prop.h> // #include <chuffed/mdd/case.h> typedef struct { int state; int value; int dest; } dfa_trans; static void addMDDProp(vec<IntVar*>& x, MDDTable& tab, MDDNodeInt m, const MDDOpts& mopts); // MDDNodeInt fd_regular(MDDTable& tab, int n, int nstates, vec< vec<int> >& transition, int q0, // vec<int>& accepts, bool offset = true); static MDDNodeInt mdd_table(MDDTable& mddtab, int arity, vec<int>& doms, vec<vec<int> >& entries, bool is_pos); void addMDD(vec<IntVar*>& x, MDD m, const MDDOpts& mdd_opts) { if (m.val == m.table->ttt().val) { return; } addMDDProp(x, *(m.table), m.val, mdd_opts); /* if(mdd_opts.decomp == MDDOpts::D_PROP) { addMDDProp(x, *(m.table), m.val, mdd_opts); } else { mdd_decomp_dc(x, *(m.table), m.val); } */ } static void addMDDProp(vec<IntVar*>& x, MDDTable& tab, MDDNodeInt m, const MDDOpts& mopts) { vec<int> doms; vec<IntView<> > w; vec<intpair> bounds; for (int i = 0; i < x.size(); i++) { bounds.push(intpair(x[i]->getMin(), x[i]->getMax())); doms.push(x[i]->getMax() + 1); // assert( x[i]->getMin() == 0 ); } // m = tab.bound(m, bounds); // m = tab.expand(0, m); for (int i = 0; i < x.size(); i++) { x[i]->specialiseToEL(); } for (int i = 0; i < x.size(); i++) { w.push(IntView<>(x[i], 1, 0)); } auto* templ = new MDDTemplate(tab, m, doms); new MDDProp<0>(templ, w, mopts); } // x: Vars | q: # states | s: alphabet size | d[state,symbol] -> state | q0: start state | f: // accepts States range from 1..q (0 is reserved as dead) // void mdd_regular(vec<IntVar*>& x, int q, int s, vec<vec<int> >& d, int q0, vec<int>& f, bool offset, const MDDOpts& mopts) { MDDTable tab(x.size()); MDDNodeInt m(fd_regular(tab, x.size(), q + 1, d, q0, f, offset)); addMDDProp(x, tab, m, mopts); } void mdd_table(vec<IntVar*>& x, vec<vec<int> >& t, const MDDOpts& mopts) { vec<int> doms; int maxdom = 0; for (int i = 0; i < x.size(); i++) { // assert(x[i]->getMin() == 0); doms.push(x[i]->getMax() + 1); // Could also generate maxdom from tuples. if ((x[i]->getMax() + 1) > maxdom) { maxdom = x[i]->getMax() + 1; } } MDDTable tab(x.size()); // Assumes a positive table. MDDNodeInt m(mdd_table(tab, x.size(), doms, t, true)); // tab.print_mdd_tikz(m); addMDDProp(x, tab, m, mopts); } // MDD mdd_table(MDDTable& mddtab, int arity, vec<int>& doms, vec< std::vector<unsigned int> >& // entries, bool is_pos) MDDNodeInt mdd_table(MDDTable& mddtab, int arity, vec<int>& doms, vec<vec<int> >& entries, bool is_pos) { assert(doms.size() == arity); MDDNodeInt table = MDDFALSE; for (int i = 0; i < entries.size(); i++) { table = mddtab.mdd_or(table, mddtab.tuple(entries[i])); } if (!is_pos) { std::vector<unsigned int> vdoms; for (int i = 0; i < doms.size(); i++) { vdoms.push_back(doms[i]); } // mddtab.print_mdd_tikz(table); table = mddtab.mdd_not(table); } return table; } MDDNodeInt fd_regular(MDDTable& tab, int n, int nstates, vec<vec<int> >& transition, int q0, vec<int>& accepts, bool offset) { std::vector<std::vector<MDDNodeInt> > states; for (int i = 0; i < nstates; i++) { states.emplace_back(); states[i].push_back(MDDFALSE); } for (int i = 0; i < accepts.size(); i++) { states[accepts[i] - 1][0] = MDDTRUE; } // Inefficient implementation. Should fix. int prevlevel = 0; for (int j = n - 1; j >= 0; j--) { for (int i = 0; i < nstates - 1; i++) { std::vector<edgepair> cases; for (int k = 0; k < transition[i].size(); k++) { if (transition[i][k] > 0) { cases.emplace_back(offset ? k + 1 : k, states[transition[i][k] - 1][prevlevel]); } } states[i].push_back(tab.mdd_case(j, cases)); } prevlevel++; } MDDNodeInt out(states[q0 - 1][states[0].size() - 1]); return out; } // x: Vars | q: # states | s: alphabet size | d[state,symbol] -> state | q0: start state | f: // accepts States range from 1..q (0 is reserved as dead) offset -> alphabet symbols are 1..s // (0..s-1 otherwise) // void wmdd_cost_regular(vec<IntVar*>& x, int q, int s, vec<vec<int> >& d, vec<vec<int> >& w, int q0, vec<int>& f, IntVar* cost, const MDDOpts& mopts) { vec<WDFATrans> T; // Construct the weighted transitions. for (int qi = 0; qi < q; qi++) { vec<int>& d_q(d[qi]); vec<int>& w_q(w[qi]); for (int vi = 0; vi < s; vi++) { WDFATrans t = {w_q[vi], d_q[vi]}; T.push(t); } } EVLayerGraph g; EVLayerGraph::NodeID root = wdfa_to_layergraph(g, x.size(), s, (WDFATrans*)T, q, q0, f); evgraph_to_wmdd(x, cost, g, root, mopts); }
/** * 2016 Mohd Fahmi Noorain * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * * DISCLAIMER * * @author Mohd Fahmi Noorain <fahmy@qotak.com> * @copyright 2016 Mohd Fahmi Noorain * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ #ifndef FIREWALL_H #define FIREWALL_H #include <QHostAddress> #include <QFile> #include <QProcess> #include <QVariant> #include "Common.h" namespace Qai { class Firewall : public QObject { Q_OBJECT public: explicit Firewall(QObject *parent = 0); int init(); void setSourceInterface(const QString &sourceInterface); void setDestinationInterface(const QString &destinationInterface); signals: public slots: int findMacAddress(const QHostAddress &hostAddress, User &user); int updateUserPermission(const User &user); private: int execute(const QString &cmd); int execute(const QString &cmd, const QStringList &args); QString mSourceInterface, mDestinationInterface; }; } #endif // FIREWALL_H
#include "iostream" #include "Y.h" using namespace std; void Y::func(int n){ cout<<"in Y n="<<n<<endl; }
#include <chuffed/core/propagator.h> #include <chuffed/core/sat.h> #include <chuffed/vars/int-var.h> extern std::map<IntVar*, std::string> intVarString; IntVarSL::IntVarSL(const IntVar& other, vec<int>& _values) : IntVar(other), values(_values) { initVals(); // handle min, max and vals int l = 0; while (values[l] < min) { if (++l == values.size()) { TL_FAIL(); } } while (vals[values[l]] == 0) { if (++l == values.size()) { TL_FAIL(); } } min = values[l]; // printf("l = %d\n", l); int u = values.size() - 1; while (values[u] > max) { if (u-- == 0) { TL_FAIL(); } } while (vals[values[u]] == 0) { if (u-- == 0) { TL_FAIL(); } } max = values[u]; // printf("u = %d\n", u); for (int i = min, k = l; i <= max; i++) { if (i == values[k]) { k++; continue; } vals[i] = 0; } for (int i = l; i <= u; i++) { values[i - l] = values[i]; } values.resize(u - l + 1); // for (int i = 0; i < values.size(); i++) printf("%d ", values[i]); // printf("\n"); // create the IntVarEL IntVar* v = newIntVar(0, values.size() - 1); // inherit the name from this SL intVarString[v] = intVarString[this]; v->specialiseToEL(); el = (IntVarEL*)v; // Override literal name values std::string label = intVarString[el]; for (int i = 0; i < values.size(); i++) { std::string val = std::to_string(values[i]); litString[toInt(el->getLit(i, LR_NE))] = label + "!=" + val; litString[toInt(el->getLit(i, LR_EQ))] = label + "==" + val; litString[toInt(el->getLit(i, LR_GE))] = label + ">=" + val; litString[toInt(el->getLit(i, LR_LE))] = label + "<=" + val; } // rechannel channel info for (int i = 0; i < values.size(); i++) { Lit p = el->getLit(i, LR_NE); sat.c_info[var(p)].cons_id = var_id; } for (int i = 0; i <= values.size(); i++) { Lit p = el->getLit(i, LR_GE); sat.c_info[var(p)].cons_id = var_id; } // transfer pinfo to el for (int i = 0; i < pinfo.size(); i++) { el->pinfo.push(pinfo[i]); } pinfo.clear(true); } void IntVarSL::attach(Propagator* p, int pos, int eflags) { if (isFixed()) { p->wakeup(pos, eflags); } else { el->pinfo.push(PropInfo(p, pos, eflags)); } } int IntVarSL::find_index(int v, RoundMode type) const { int l = 0; int u = values.size() - 1; int m; while (true) { m = (l + u) / 2; if (values[m] == v) { return m; } if (values[m] < v) { l = m + 1; } else { u = m - 1; } if (u < l) { break; } } switch (type) { case ROUND_DOWN: return u; case ROUND_UP: return l; case ROUND_NONE: return -1; default: NEVER; } } // t = 0: [x != v], t = 1: [x = v], t = 2: [x >= v], t = 3: [x <= v] Lit IntVarSL::getLit(int64_t v, LitRel t) { switch (t) { case LR_NE: { int u = find_index(v, ROUND_NONE); return (u == -1 ? lit_True : el->getLit(u, LR_NE)); } case LR_EQ: { int u = find_index(v, ROUND_NONE); return (u == -1 ? lit_False : el->getLit(u, LR_EQ)); } case LR_GE: return el->getLit(find_index(v, ROUND_UP), LR_GE); case LR_LE: return el->getLit(find_index(v, ROUND_DOWN), LR_LE); default: NEVER; } } bool IntVarSL::setMin(int64_t v, Reason r, bool channel) { assert(setMinNotR(v)); // debug(); // printf("setMin: v = %lld, u = %d\n", v, find_index(v, ROUND_UP)); if (!el->setMin(find_index(v, ROUND_UP), r, channel)) { return false; } min = values[el->min]; return true; } bool IntVarSL::setMax(int64_t v, Reason r, bool channel) { assert(setMaxNotR(v)); // debug(); // printf("setMax: v = %lld, u = %d\n", v, find_index(v, ROUND_DOWN)); if (!el->setMax(find_index(v, ROUND_DOWN), r, channel)) { return false; } max = values[el->max]; return true; } bool IntVarSL::setVal(int64_t v, Reason r, bool channel) { assert(setValNotR(v)); int u = find_index(v, ROUND_NONE); if (u == -1) { if (channel) { sat.cEnqueue(lit_False, r); } assert(sat.confl); return false; } if (!el->setVal(u, r, channel)) { return false; } if (min < v) { min = v; } if (max > v) { max = v; } return true; } bool IntVarSL::remVal(int64_t v, Reason r, bool channel) { assert(remValNotR(v)); int u = find_index(v, ROUND_NONE); assert(u != -1); if (!el->remVal(u, r, channel)) { return false; } vals[v] = 0; min = values[el->min]; max = values[el->max]; return true; } void IntVarSL::channel(int val, LitRel val_type, int sign) { // fprintf(stderr, "funny channel\n"); auto type = static_cast<LitRel>(static_cast<int>(val_type) * 3 ^ sign); el->set(val, type, false); if (type == 0) { vals[values[val]] = 0; } min = values[el->min]; max = values[el->max]; } void IntVarSL::debug() { printf("min = %d, max = %d, el->min = %d, el->max = %d\n", (int)min, (int)max, (int)el->min, (int)el->max); for (int i = 0; i < values.size(); i++) { printf("%d ", values[i]); } printf("\n"); }
/* vi: set et sw=4 ts=4 cino=t0,(0: */ /* * Copyright (C) 2012 Alberto Mardegan <info@mardy.it> * * This file is part of minusphoto. * * minusphoto 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. * * minusphoto 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 minusphoto. If not, see <http://www.gnu.org/licenses/>. */ #include "debug.h" #include "model-selection.h" #include <QAbstractListModel> using namespace Minusphoto; ModelSelection::ModelSelection(QObject *parent): QObject(parent), _model(0), _isEmpty(true), _lastIndex(-1) { } void ModelSelection::setModel(QAbstractListModel *model) { if (model == _model) return; if (_model != 0) { _model->disconnect(this); } _model = model; if (model) { connect(model, SIGNAL(dataChanged(const QModelIndex&,const QModelIndex&)), SLOT(onDataChanged(const QModelIndex&,const QModelIndex&))); connect(model, SIGNAL(rowsRemoved(const QModelIndex&,int,int)), this, SLOT(onRowsRemoved(const QModelIndex&,int,int))); } clear(); } QList<int> ModelSelection::indexes() const { QList<int> sortedIndexes = _indexes.toList(); qSort(sortedIndexes); return sortedIndexes; } void ModelSelection::clear() { _indexes.clear(); _lastIndex = -1; update(); } void ModelSelection::selectAll() { int len = _model->rowCount(); for (int i = 0; i < len; i++) { _indexes.insert(i); } _lastIndex = -1; update(); } void ModelSelection::setSelection(int index) { _indexes.clear(); _indexes.insert(index); _lastIndex = index; update(); } void ModelSelection::setShiftSelection(int index) { if (_lastIndex < 0) return setSelection(index); int first, last; if (_lastIndex > index) { first = index; last = _lastIndex; } else { first = _lastIndex; last = index; } for (int i = first; i <= last; i++) _indexes.insert(i); _lastIndex = index; update(); } void ModelSelection::setCtrlSelection(int index) { if (_indexes.contains(index)) { _indexes.remove(index); } else { _indexes.insert(index); } _lastIndex = index; update(); } QList<QVariant> ModelSelection::items(const QByteArray &roleName) const { QList<QVariant> list; QList<int> sortedIndexes = _indexes.toList(); qSort(sortedIndexes); const QHash<int, QByteArray> &roleMap = _model->roleNames(); int role = roleMap.key(roleName); foreach (int index, sortedIndexes) { QVariant item = _model->data(_model->index(index), role); list.append(item); } return list; } QVariantMap ModelSelection::get(int index) const { QVariantMap map; const QHash<int, QByteArray> &roles = _model->roleNames(); QHash<int, QByteArray>::const_iterator i = roles.constBegin(); QModelIndex modelIndex = _model->index(index); while (i != roles.constEnd()) { map[QString::fromLatin1(i.value())] = _model->data(modelIndex, i.key()); ++i; } return map; } void ModelSelection::removeItems() { if (_isEmpty) return; QList<int> sortedIndexes = _indexes.toList(); qSort(sortedIndexes); /* Start removing rows from the end, so we don't have to update the indexes */ int last = -1; int count = 0; int len = sortedIndexes.count(); for (int i = len - 1; i >= 0; i--) { int index = sortedIndexes[i]; if (index == last - count) { count++; } else { if (last >= 0) { _model->removeRows(last - count + 1, count); } last = index; count = 1; } } _model->removeRows(last - count + 1, count); } void ModelSelection::update() { if (_indexes.isEmpty() != _isEmpty) { _isEmpty = _indexes.isEmpty(); Q_EMIT isEmptyChanged(); } Q_EMIT indexesChanged(); Q_EMIT itemsChanged(); } void ModelSelection::onRowsRemoved(const QModelIndex &, int first, int last) { int count = last - first + 1; ModelIndexes newIndexes; foreach (int index, _indexes) { if (index < first) { newIndexes.insert(index); } else if (index > last) { newIndexes.insert(index - count); } } _indexes = newIndexes; update(); } void ModelSelection::onDataChanged(const QModelIndex &, const QModelIndex &) { update(); }
// Created on: 2013-12-20 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-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 BVH_Triangulation_HeaderFile #define BVH_Triangulation_HeaderFile #include <BVH_PrimitiveSet.hxx> //! Triangulation as an example of BVH primitive set. //! \tparam T Numeric data type //! \tparam N Vector dimension template<class T, int N> class BVH_Triangulation : public BVH_PrimitiveSet<T, N> { public: typedef typename BVH::VectorType<T, N>::Type BVH_VecNt; public: //! Creates empty triangulation. BVH_Triangulation() {} //! Creates empty triangulation. BVH_Triangulation (const opencascade::handle<BVH_Builder<T, N> >& theBuilder) : BVH_PrimitiveSet<T, N> (theBuilder) { // } //! Releases resources of triangulation. virtual ~BVH_Triangulation() {} public: //! Array of vertex coordinates. typename BVH::ArrayType<T, N>::Type Vertices; //! Array of indices of triangle vertices. BVH_Array4i Elements; public: //! Returns total number of triangles. virtual Standard_Integer Size() const Standard_OVERRIDE { return BVH::Array<Standard_Integer, 4>::Size (Elements); } //! Returns AABB of entire set of objects. using BVH_PrimitiveSet<T, N>::Box; //! Returns AABB of the given triangle. virtual BVH_Box<T, N> Box (const Standard_Integer theIndex) const Standard_OVERRIDE { const BVH_Vec4i& anIndex = BVH::Array<Standard_Integer, 4>::Value (Elements, theIndex); const BVH_VecNt& aPoint0 = BVH::Array<T, N>::Value (Vertices, anIndex.x()); const BVH_VecNt& aPoint1 = BVH::Array<T, N>::Value (Vertices, anIndex.y()); const BVH_VecNt& aPoint2 = BVH::Array<T, N>::Value (Vertices, anIndex.z()); BVH_VecNt aMinPoint (aPoint0), aMaxPoint (aPoint0); BVH::BoxMinMax<T, N>::CwiseMin (aMinPoint, aPoint1); BVH::BoxMinMax<T, N>::CwiseMin (aMinPoint, aPoint2); BVH::BoxMinMax<T, N>::CwiseMax (aMaxPoint, aPoint1); BVH::BoxMinMax<T, N>::CwiseMax (aMaxPoint, aPoint2); return BVH_Box<T, N> (aMinPoint, aMaxPoint); } //! Returns centroid position along the given axis. virtual T Center (const Standard_Integer theIndex, const Standard_Integer theAxis) const Standard_OVERRIDE { const BVH_Vec4i& anIndex = BVH::Array<Standard_Integer, 4>::Value (Elements, theIndex); const BVH_VecNt& aPoint0 = BVH::Array<T, N>::Value (Vertices, anIndex.x()); const BVH_VecNt& aPoint1 = BVH::Array<T, N>::Value (Vertices, anIndex.y()); const BVH_VecNt& aPoint2 = BVH::Array<T, N>::Value (Vertices, anIndex.z()); return (BVH::VecComp<T, N>::Get (aPoint0, theAxis) + BVH::VecComp<T, N>::Get (aPoint1, theAxis) + BVH::VecComp<T, N>::Get (aPoint2, theAxis)) * static_cast<T> (1.0 / 3.0); } //! Performs transposing the two given triangles in the set. virtual void Swap (const Standard_Integer theIndex1, const Standard_Integer theIndex2) Standard_OVERRIDE { BVH_Vec4i& anIndices1 = BVH::Array<Standard_Integer, 4>::ChangeValue (Elements, theIndex1); BVH_Vec4i& anIndices2 = BVH::Array<Standard_Integer, 4>::ChangeValue (Elements, theIndex2); std::swap (anIndices1, anIndices2); } }; #endif // _BVH_Triangulation_Header
#define CATCH_CONFIG_MAIN #include "../external/catch2/catch.hpp" #include "../src/array/contains.hpp" #include <vector> #include <string> #include <array> template <typename T> struct TestStruct { std::vector<T> val; T findVal; bool actual; TestStruct(std::vector<T> val, T findVal, bool actual) : val(val), actual(actual), findVal(findVal) { } }; TEST_CASE("Array Contains With Integer Vector", "[contains]") { std::vector<TestStruct<int>> testVec{ { {1, 2, 3, 4, 5, 6}, 5, true } }; for (auto &&var : testVec) { REQUIRE(Array::contains(var.val, var.findVal) == var.actual); } } template <typename T, int _tVal> struct TestStruct2 { std::array<T, _tVal> val; T findVal; bool actual; TestStruct2(std::array<T, _tVal> val, T findVal, bool actual) : val(val), actual(actual), findVal(findVal) { } }; TEST_CASE("Array Contains With String Array", "[contains]") { std::vector<TestStruct2<std::string, 3>> testVec{ { {"melon", "watermelon", "cherry"}, "melon", true } }; for (auto &&var : testVec) { REQUIRE(Array::contains(var.val, var.findVal) == var.actual); } }
#include<iostream> void achman (int *, int); void nvazman(int *,int); int foo (int,int*,int, void (*funkcia)(int *,int) ); int main() { int chap = 5; int array [5]; std::cout<<"Mutqagreq 5 hat tiv "; for(int i = 0; 5 > i; ++i){ std::cin>> array[i]; } int* arg = &array[0]; void (*funkcia)(int *,int) ; int payman; std::cout<<"Mutqagreq paymany\n1 - Achman kargov\n2 - Nvazman kargov\n"; std::cin>>payman; if(3 == foo(payman,array,chap,funkcia)){ std::cout<<"Sxal payman\n"; } return 0; } int foo (int payman,int*array,int chap, void (*funkcia)(int *,int) ){ if(1 == payman){ funkcia = achman; } else if (2 == payman){ funkcia = nvazman; } else { return 3; } (*funkcia)(array,chap); return 1; } void achman (int * array, int chap){ int i; int j; int k; for(i = 0; i < chap; i++){ for(j = 0; j < chap; j++){ if(array[i] < array[j]){ k = array[i]; array[i] = array[j]; array[j]=k; } } } for(i = 0; i < chap; i++){ std::cout<< array[i]<<" "; } std::cout<<"\n"; } void nvazman (int * array, int chap){ int i; int j; int k; for(i = 0; i < chap; i++){ for(j = 0; j < chap; j++){ if(array[i] > array[j]){ k = array[i]; array[i] = array[j]; array[j]=k; } } } for(i = 0; i < chap; i++){ std::cout<< array[i]<<" "; } std::cout<<"\n"; }
#pragma once #include "Element.h" class q_A { elem *a; elem *b; int k; public: q_A(); ~q_A(); void del(); void add(int user_value); void print_queue(); int calc(); void copy_queue(q_A &op1); q_A *merge(q_A *op1); elem *get_a(); elem *get_b(); int get_k(); void set_k(int num); void set_a(elem *value); void set_b(elem *value); };
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <iostream> #include <stdint.h> #include "ros/ros.h" #include "node_robot_msgs/robot_info_report.h" #include "node_robot_msgs/agent_feedback.h" using namespace std; class Robot_monitor { public: Robot_monitor(); ~Robot_monitor(); void run(); private: unsigned int robot_num; vector<unsigned int> work_task_id; vector<unsigned int> id; vector<string> state; node_robot_msgs::agent_feedback monitor_info; ros::NodeHandle m_handle; ros::ServiceServer robot_info_server; ros::Publisher robot_info_pub; bool server_deal(node_robot_msgs::robot_info_report::Request &req,node_robot_msgs::robot_info_report::Response &res); };
#ifndef _LAMP_H #define _LAMP_H #include "common_defines.h" class Lamp { public: Lamp(); ~Lamp(); void startup(int _row, int _col, int _num, string _name); string getName() { return(name); } void serializeJson(Writer<StringBuffer>* writer); bool setState(LampState _newState); LampState getState() { return(state); } private: int row, col, num; string name; LampState state; //use accessors? }; #endif //_LAMP_H
#pragma once #include <unordered_set> /// CRTP template to maintain a global set of all instances. /// /// Inheritance from this class should probably be private with `friend struct global_set<Derived>`. template<class Derived> struct global_set { using set_t = std::unordered_set<Derived*>; using iterator = typename set_t::iterator; global_set() { globset.insert(static_cast<Derived*>(this)); } ~global_set() { globset.erase(static_cast<Derived*>(this)); } // global statics static iterator begin() { return globset.begin(); } static iterator end() { return globset.end(); } static set_t globset; }; template<class Derived> typename global_set<Derived>::set_t global_set<Derived>::globset;
#include "GameSetupState.h" #include "GameplayState.h" #include "SDL.h" #include "SDL_image.h" #include <iostream> #include <vector> #include "Game.h" #include "MapLoader.h" #include "Map.h" #include "Player.h" #include "ImGui/imgui.h" #include "ImGui/imgui_sdl.h" #include "Cards.h" #include "PlayerStrategies.h" #include "Singleton.h" GameSetupState GameSetupState::mGameSetupState; SDL_Renderer* GameSetupState::renderer = nullptr; std::vector<bool> GameSetupState::players = { true, true, false, false, false }; std::vector<int> GameSetupState::strategies = { 0, 0, 0, 0, 0 }; // 0 = human, 1 = moderate cpu , 2 = greedy cpu std::vector<int> GameSetupState::ages = { 18, 18, 18, 18, 18 }; bool GameSetupState::mapLoaded = false; const int TWO_PLAYER_COIN_PURSE = 14; const int THREE_PLAYER_COIN_PURSE = 11; const int FOUR_PLAYER_COIN_PURSE = 9; const int FIVE_PLAYER_COIN_PURSE = 8; const int TWO_PLAYER_CARDS = 13; const int THREE_PLAYER_CARDS = 10; const int FOUR_PLAYER_CARDS = 8; const int FIVE_PLAYER_CARDS = 7; void GameSetupState::init(Game* game) { renderer = SDL_CreateRenderer(game->getWindow(), -1, SDL_RENDERER_ACCELERATED); ImGui::CreateContext(); ImGuiSDL::Initialize(renderer, 800, 640); } void GameSetupState::clean(Game* game) { ImGuiSDL::Deinitialize(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(game->getWindow()); ImGui::DestroyContext(); std::cout << "Game Setup State Cleaned\n"; } void GameSetupState::pause() { printf("Main menu paused\n"); } void GameSetupState::resume() { printf("Main menu resumed\n"); } void GameSetupState::handleEvents(Game* game) { ImGuiIO& io = ImGui::GetIO(); int wheel = 0; SDL_Event event; while (SDL_PollEvent(&event) != 0) { switch (event.type) { case SDL_QUIT: game->setRunning(false); break; case SDL_WINDOWEVENT: if (event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { io.DisplaySize.x = static_cast<float>(event.window.data1); io.DisplaySize.y = static_cast<float>(event.window.data2); } else if (event.type == SDL_MOUSEWHEEL) { wheel = event.wheel.y; } default: break; } } int mouseX, mouseY; const int buttons = SDL_GetMouseState(&mouseX, &mouseY); io.MousePos = ImVec2(static_cast<float>(mouseX), static_cast<float>(mouseY)); io.MouseDown[0] = buttons & SDL_BUTTON(SDL_BUTTON_LEFT); io.MouseDown[1] = buttons & SDL_BUTTON(SDL_BUTTON_RIGHT); io.MouseWheel = static_cast<float>(wheel); ImGui::NewFrame(); //ImGui::ShowDemoWindow(); handleMapPicker(game); handlePlayerPicker(game); handleGameStart(game); } void GameSetupState::update(Game* game) { } void GameSetupState::draw(Game* game) { SDL_RenderClear(renderer); ImGui::Render(); ImGuiSDL::Render(ImGui::GetDrawData()); SDL_RenderPresent(renderer); } void GameSetupState::handleMapPicker(Game* game) { ImGui::Begin("Choose your map", NULL, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize); ImVec2 windowSize(300, 500); ImGui::SetWindowSize(windowSize); ImVec2 windowPos(5, 20); ImGui::SetWindowPos(windowPos); std::vector<std::string> maps = MapLoader::getInstalledMaps(); static int selected = -1; for (int n = 0; n < maps.size(); n++) { char buffer[200]; const char* map = maps.at(n).c_str(); sprintf_s(buffer, "%s", map); if (ImGui::Selectable(buffer, selected == n)) { selected = n; MapLoader::selectedMap = maps.at(n); std::cout << "User selected: " << maps.at(n) << std::endl; } } ImVec2 buttonSize(100, 50); static bool load = false; if (ImGui::Button("Load this Map", buttonSize)) { if (selected != -1) load = initMapLoader(game); } if (load & 1) ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Map Succesfully Loaded."); else ImGui::Text("Check console for Map validation."); ImGui::End(); } void GameSetupState::handlePlayerPicker(Game* game) { ImGui::Begin("Choose Players", NULL, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize); ImVec2 windowSize(490, 500); ImGui::SetWindowSize(windowSize); ImVec2 windowPos(305, 20); ImGui::SetWindowPos(windowPos); ImGui::Columns(3, "mixed"); ImGui::Separator(); ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(7.0f, 0.8f, 0.8f)); ImGui::Button("Player 1"); ImGui::PopStyleColor(3); static int age1 = ages[0]; ImGui::SliderInt("age1", &age1, 0, 100); static int e1 = 0; ImGui::RadioButton("Human", &e1, 0); ImGui::RadioButton("Moderate CPU", &e1, 1); ImGui::RadioButton("Greedy CPU", &e1, 2); ImGui::Text(""); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Player 1 playing"); ImGui::NextColumn(); ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(1 / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(1 / 7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(1 / 7.0f, 0.8f, 0.8f)); ImGui::Button("Player 2"); ImGui::PopStyleColor(3); static int age2 = ages[1]; ImGui::SliderInt("age2", &age2, 0, 100); static int e2 = 0; ImGui::RadioButton("Human ", &e2, 0); ImGui::RadioButton("Moderate CPU ", &e2, 1); ImGui::RadioButton("Greedy CPU ", &e2, 2); ImGui::Text(""); ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Player 2 playing"); ImGui::NextColumn(); ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(3 / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(3 / 7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(3 / 7.0f, 0.8f, 0.8f)); ImGui::Button("Player 3"); static int age3 = ages[2]; ImGui::PopStyleColor(3); ImGui::SliderInt("age3", &age3, 0, 100); static int e3 = 0; ImGui::RadioButton("Human ", &e3, 0); ImGui::RadioButton("Moderate CPU ", &e3, 1); ImGui::RadioButton("Greedy CPU ", &e3, 2); static bool status3 = players[2]; if (ImGui::Button("Add/Remove Player 3")) { status3 = !status3; players[2] = status3; } if (status3 & 1) ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Player 3 added."); else ImGui::TextDisabled("Player 3 NOT playing"); ImGui::NextColumn(); ImGui::Separator(); ImGui::Columns(3, "mixed"); ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(4 / 7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(4 / 7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(4 / 7.0f, 0.8f, 0.8f)); ImGui::Button("Player 4"); ImGui::PopStyleColor(3); static int age4 = ages[3]; ImGui::SliderInt("age4", &age4, 0, 100); static int e4 = 0; ImGui::RadioButton("Human ", &e4, 0); ImGui::RadioButton("Moderate CPU ", &e4, 1); ImGui::RadioButton("Greedy CPU ", &e4, 2); static bool status4 = players[3]; if (ImGui::Button("Add/Remove Player 4")) { status4 = !status4; players[3] = status4; } if (status4 & 1) ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Player 4 added."); else ImGui::TextDisabled("Player 4 NOT playing"); ImGui::NextColumn(); ImGui::Button("Player 5"); static int age5 = ages[4]; ImGui::SliderInt("age5", &age5, 0, 100); static int e5 = 0; ImGui::RadioButton("Human ", &e5, 0); ImGui::RadioButton("Moderate CPU ", &e5, 1); ImGui::RadioButton("Greedy CPU ", &e5, 2); static bool status5 = players[4]; if (ImGui::Button("Add/Remove Player 5")) { status5 = !status5; players[4] = status5; } if (status5 & 1) ImGui::TextColored(ImVec4(1.0f, 1.0f, 0.0f, 1.0f), "Player 5 added."); else ImGui::TextDisabled("Player 5 NOT playing"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ages[0] = age1; ages[1] = age2; ages[2] = age3; ages[3] = age4; ages[4] = age5; strategies[0] = e1; strategies[1] = e2; strategies[2] = e3; strategies[3] = e4; strategies[4] = e5; ImGui::End(); } void GameSetupState::handleGameStart(Game* game) { bool select = false; ImGui::Begin("Start Game", NULL, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar); ImVec2 windowSize(200, 66); ImGui::SetWindowSize(windowSize); ImVec2 windowPos(595, 520); ImGui::SetWindowPos(windowPos); ImGui::PushStyleColor(ImGuiCol_Button, (ImVec4)ImColor::HSV(7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, (ImVec4)ImColor::HSV(7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, (ImVec4)ImColor::HSV(7.0f, 0.8f, 0.8f)); ImVec2 buttonSize(190, 50); if (ImGui::Button("START GAME!", buttonSize)) { if (mapLoaded) select = true; } ImGui::PopStyleColor(3); ImGui::End(); if (select) { //Creating a deck Deck* deck = new Deck(); game->setDeck(deck); deck->printDeck(); setupPlayers(game); std::cout << endl << "--Player Hands--\n"; for (Player* p : game->players()) { if (!p->getHand()) std::cout << p->getName() << " - Hand: " << "Empty" << endl; } game->changeState(GameplayState::Instance()); } } bool GameSetupState::initMapLoader(Game* game) { MapLoader* mapLoader = nullptr; mapLoaded = false; mapLoader = MapLoader::initiateMapPicker(); if (mapLoader) { std::cout << *mapLoader << std::endl; SingletonClass::instance(&mapLoader->getMapName(), mapLoader->getNumCountries(), mapLoader->getNumContinents()); GraphWorld::TileMap* tileMap = new GraphWorld::TileMap(); SingletonClass::instance()->setTileMap(tileMap); game->setMapLoader(mapLoader); if (mapLoader->load(tileMap, MAP_HEIGHT, MAP_WIDTH)) { SingletonClass::instance()->printMap(); std::cout << "Map Successfully loaded." << std::endl; mapLoaded = true; return true; } //delete map; delete tileMap; delete mapLoader; return false; } } void GameSetupState::setupPlayers(Game* game) { std::string name; int x = 1; for (int i = 0; i < players.size(); i++) { name = "Player " + to_string(x); if (players[i]) { Player* p = new Player(&name, ages[i]); //Setting the Strategy if (strategies[i] == 0) p->setStrategy(new Human()); else if (strategies[i] == 1) p->setStrategy(new ModerateCPU()); else if (strategies[i] == 2) p->setStrategy(new GreedyCPU()); game->players().push_back(p); x++; } } assignCoins(game); } void GameSetupState::assignCoins(Game* game) { std::vector players = game->players(); const int numPlayers = players.size(); switch (numPlayers) { case 2: game->players().at(0)->setCoinPurse(TWO_PLAYER_COIN_PURSE); game->players().at(1)->setCoinPurse(TWO_PLAYER_COIN_PURSE); game->players().at(0)->setCardToPlay(TWO_PLAYER_CARDS); game->players().at(1)->setCardToPlay(TWO_PLAYER_CARDS); break; case 3: game->players().at(0)->setCoinPurse(THREE_PLAYER_COIN_PURSE); game->players().at(1)->setCoinPurse(THREE_PLAYER_COIN_PURSE); game->players().at(2)->setCoinPurse(THREE_PLAYER_COIN_PURSE); game->players().at(0)->setCardToPlay(THREE_PLAYER_CARDS); game->players().at(1)->setCardToPlay(THREE_PLAYER_CARDS); game->players().at(2)->setCardToPlay(THREE_PLAYER_CARDS); break; case 4: game->players().at(0)->setCoinPurse(FOUR_PLAYER_COIN_PURSE); game->players().at(1)->setCoinPurse(FOUR_PLAYER_COIN_PURSE); game->players().at(2)->setCoinPurse(FOUR_PLAYER_COIN_PURSE); game->players().at(3)->setCoinPurse(FOUR_PLAYER_COIN_PURSE); game->players().at(0)->setCardToPlay(FOUR_PLAYER_CARDS); game->players().at(1)->setCardToPlay(FOUR_PLAYER_CARDS); game->players().at(2)->setCardToPlay(FOUR_PLAYER_CARDS); game->players().at(3)->setCardToPlay(FOUR_PLAYER_CARDS); break; case 5: game->players().at(0)->setCoinPurse(FIVE_PLAYER_COIN_PURSE); game->players().at(1)->setCoinPurse(FIVE_PLAYER_COIN_PURSE); game->players().at(2)->setCoinPurse(FIVE_PLAYER_COIN_PURSE); game->players().at(3)->setCoinPurse(FIVE_PLAYER_COIN_PURSE); game->players().at(4)->setCoinPurse(FIVE_PLAYER_COIN_PURSE); game->players().at(0)->setCardToPlay(FIVE_PLAYER_CARDS); game->players().at(1)->setCardToPlay(FIVE_PLAYER_CARDS); game->players().at(2)->setCardToPlay(FIVE_PLAYER_CARDS); game->players().at(3)->setCardToPlay(FIVE_PLAYER_CARDS); game->players().at(4)->setCardToPlay(FIVE_PLAYER_CARDS); break; default: break; } }
/*************************************************************************** * Copyright (C) 2009-2010 by Dario Freddi * * drf@chakra-project.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * 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, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef BACKEND_H #define BACKEND_H #include "Visibility.h" #include "QueueItem.h" #include "Globals.h" #include "Package.h" #include "Database.h" #include "Group.h" #include <QtCore/QStringList> #include <QtCore/QEvent> #include <QtCore/QMetaType> class QUrl; namespace Aqpm { typedef QHash< QString, Aqpm::QueueItem::Action > Targets; class BackendPrivate; /** * \brief The main and only entry point for performing operations with Aqpm * * Backend encapsulates all the needed logic to perform each and every operation with Aqpm. * It can work both in synchronous and asynchronous mode, and it provides access to all the most * common functionalities in Alpm. 90% of the features are covered in Aqpm, although some very * advanced and uncommon ones are not present, and you will need them only if you're attempting to * develop a full-fledged frontend. * \par * The class is implemented as a singleton and it spawns an additional thread where Alpm will be jailed. * Since alpm was not designed to support threads, Aqpm implements a queue to avoid accidental concurrent access * to alpm methods. You are free to use Aqpm in multithreaded environments without having to worry. * \par * Aqpm \b _NEEDS_ to work as standard, non-privileged user. Failure in doing so might lead to unsecure behavior. * Aqpm uses privilege escalation with PolicyKit to perform privileged actions. Everything is done for you, even * if you can choose to manage the authentication part by yourself, in case you want more tight integration with * your GUI * * \note All the methods in this class, unless noted otherwise, are thread safe * * \author Dario Freddi */ class AQPM_EXPORT Backend : public QObject { Q_OBJECT Q_DISABLE_COPY(Backend) public: /** * Defines the action type in a synchonous operation. There is a matching entry for * every function available */ enum ActionType { GetAvailableDatabases, GetAvailableGroups, GetPackagesFromDatabase, GetLocalDatabase, GetPackagesFromGroup, GetUpgradeablePackages, GetInstalledPackages, GetPackageDependencies, GetPackageGroups, GetDependenciesOnPackage, CountPackages, GetProviders, IsProviderInstalled, GetPackageDatabase, IsInstalled, GetAlpmVersion, ClearQueue, AddItemToQueue, GetQueue, SetAnswer, GetPackage, GetGroup, GetDatabase, SetUpAlpm, TestLibrary, IsOnTransaction, SetFlags, ReloadPacmanConfiguration, UpdateDatabase, ProcessQueue, DownloadQueue, Initialization, SystemUpgrade, PerformAction, InterruptTransaction, Ready, SetAqpmRoot, AqpmRoot, RetrieveAdditionalTargetsForQueue, LoadPackageFromLocalFile, SearchPackages, SearchFiles }; /** * \return The current instance of the Backend */ static Backend *instance(); /** * \return Aqpm's version */ static QString version(); /** * \return \c true if the backend is ready to be used, \c false if it's still in the initialization phase */ bool ready() const; /** * This method initializes Aqpm safely, if needed, and sets up Aqpm. Once this method has returned, Aqpm * is ready to be used. setUpAlpm() is already called by this function, you don't need to call it again. * If the backend had been already initialized elsewhere, this function will simply return immediately. * It is strongly advised to always use this function to initialize Aqpm. * * \note this function will work only if it will be the VERY FIRST CALL to Backend::instance(). Failure in * doing so might lead to undefined behavior. */ void safeInitialization(); /** * Default destructor */ virtual ~Backend(); /** * Performs a test on the library to check if Alpm and Aqpm are ready to be used * * \return \c true if the library is ready, \c false if there was a problem while testing it */ bool testLibrary() const; bool isOnTransaction() const; /** * Attempts to change the root directory of package management to \c root. This has the effect * of "chrooting" Aqpm to a new root, letting you also use the configuration present in the new root * \note This method is mapped to the org.chakraproject.aqpm.setaqpmroot action * * \param root The new root, without the ending slash (e.g.: "/media/myotherdisk") * \param applyToConfiguration Whether to use the configuration found in \c root or the standard config file * \returns Whether the change was successful or not */ bool setAqpmRoot(const QString &root, bool applyToConfiguration) const; /** * \returns The current root directory used by aqpm, without the ending slash */ QString aqpmRoot() const; /** * Performs an action asynchronously. You are not advised to use this method as it is right now, * since it's still a work in progress */ void performAsyncAction(ActionType type, const QVariantMap &args); /** * Gets a list of all available remote databases on the system. This list does not include * the local database. * * \return every sync database registered */ Database::List availableDatabases() const; /** * Returns the local database, which carries all installed packages * * \return the local database */ Database *localDatabase(); Group::List availableGroups() const; Package::List upgradeablePackages() const; Package::List installedPackages() const; int countPackages(Globals::PackageStatus status) const; bool isProviderInstalled(const QString &provider) const; /** * \brief Starts an update operation. * This function starts up the process, eventually requiring authentication. * Please note that the operation is completely asynchronous: this method will * return immediately. You can monitor the transaction throughout Backend's signals */ void updateDatabase(); /** * \brief Starts a system upgrade operation * * Starts up a system upgrade operation (equal to pacman -Su), eventually requiring authentication. * Please note that the operation is completely asynchronous: this method will * return immediately. You can monitor the transaction throughout Backend's signals * * \param flags the flags to be used in this transaction * \param downgrade whether the upgrade will be able to downgrade packages */ void fullSystemUpgrade(Globals::TransactionFlags flags, bool downgrade = false); bool reloadPacmanConfiguration() const; // In case the user modifies it. QString alpmVersion() const; /** * Clears the current queue */ void clearQueue(); /** * Adds an item to the current queue. Please note that items should be added just once. * They can be both in the format "package" or "database/package". * * \param name the name of the item * \param action the type of action to be done on the item * * \see processQueue */ void addItemToQueue(const QString &name, QueueItem::Action action); void addItemToQueue(Package *package, QueueItem::Action action); /** * \brief Starts processing the current queue * * Starts up a sync operation (equal to pacman -S \<targets\>), eventually requiring authentication. * Please note that the operation is completely asynchronous: this method will * return immediately. You can monitor the transaction throughout Backend's signals. * \par * All the items in the current queue will be processed, and when the transaction will be * over, the queue will get cleared, even if there were errors * * \param flags the flags to be used in this transaction * * \see addItemToQueue */ void processQueue(Globals::TransactionFlags flags); /** * \brief Starts downloading the current queue * * Starts up a sync download-only operation (equal to pacman -Sw \<targets\>), * eventually requiring authentication. * Please note that the operation is completely asynchronous: this method will * return immediately. You can monitor the transaction throughout Backend's signals. * \par * All the items in the current queue will be processed, and when the transaction will be * over, the queue will get cleared, even if there were errors * * \param flags the flags to be used in this transaction * * \see addItemToQueue */ void downloadQueue(); void retrieveAdditionalTargetsForQueue(Globals::TransactionFlags flags); QueueItem::List queue() const; void interruptTransaction(); void setAnswer(int answer); Package::List searchPackages(const QStringList &targets, const Database::List &dbs = Database::List()) const; Package::List searchFiles(const QString &filename) const; Package *package(const QString &name, const QString &repo); Group *group(const QString &name); Database *database(const QString &name); Package *loadPackageFromLocalFile(const QString &path); Q_SIGNALS: void dbStatusChanged(const QString &repo, int action); void dbQty(const QStringList &db); void transactionStarted(); void transactionReleased(); void streamTotalDownloadSize(qint64 size); void streamDlProg(const QString &c, int bytedone, int bytetotal, int speed, int listdone, int listtotal); void streamTransProgress(Aqpm::Globals::TransactionProgress event, const QString &pkgname, int percent, int howmany, int remain); void streamTransEvent(Aqpm::Globals::TransactionEvent event, const QVariantMap &args); void streamTransQuestion(Aqpm::Globals::TransactionQuestion event, const QVariantMap &args); void errorOccurred(Aqpm::Globals::Errors code, const QVariantMap &args); void logMessageStreamed(const QString &msg); void additionalTargetsRetrieved(const Aqpm::Targets &targets); void operationFinished(bool success); void backendReady(); private: Backend(); BackendPrivate * const d; friend class BackendPrivate; friend class BackendThread; friend class SynchronousLoop; Q_PRIVATE_SLOT(d, void __k__backendReady()) Q_PRIVATE_SLOT(d, void __k__setUpSelf(BackendThread *t)) Q_PRIVATE_SLOT(d, void __k__streamError(int code, const QVariantMap &args)) Q_PRIVATE_SLOT(d, void __k__doStreamTransProgress(int event, const QString &pkgname, int percent, int howmany, int remain)) Q_PRIVATE_SLOT(d, void __k__doStreamTransEvent(int event, const QVariantMap &args)) Q_PRIVATE_SLOT(d, void __k__doStreamTransQuestion(int event, const QVariantMap &args)) Q_PRIVATE_SLOT(d, void __k__computeDownloadProgress(qlonglong downloaded, qlonglong total, const QString &filename)) Q_PRIVATE_SLOT(d, void __k__totalOffsetReceived(int offset)) Q_PRIVATE_SLOT(d, void __k__operationFinished(bool result)) }; } Q_DECLARE_METATYPE(Aqpm::Targets) #endif /* BACKEND_H */
/* ***** 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_DICOMSERIESWRITER_HPP_ #define _GDCMIO_DICOMSERIESWRITER_HPP_ #include <fwData/Acquisition.hpp> #include "gdcmIO/writer/DicomModuleWriter.hxx" #include "gdcmIO/DicomInstance.hpp" namespace gdcmIO { namespace writer { /** * @brief This class write DICOM series Modules in a data set. * * @class DicomSeriesWriter. * @author IRCAD (Research and Development Team). * @date 2011. */ class GDCMIO_CLASS_API DicomSeriesWriter : public DicomModuleWriter< ::fwData::Acquisition > { public: GDCMIO_API DicomSeriesWriter(); GDCMIO_API virtual ~DicomSeriesWriter(); /** * @brief Write General Series Module in a data set. * * @see PS 3.3 C.7.3.1 * * @note setObject() have to be called before this method. * * @param a_gDs Root of a data set for a DICOM file. */ GDCMIO_API virtual void write(::gdcm::DataSet & a_gDs); GDCMIO_API fwGettersSettersDocMacro(SeriesID, seriesID, unsigned int, The index of series); private: unsigned int m_seriesID; ///< Index of the series (eg : 1 or 2 or ...) }; } // namespace writer } // namespace gdcmIO #endif /* _GDCMIO_DICOMSERIESWRITER_HPP_ */
// // Core.hpp // GLFW3 // // Created by William Meaton on 08/12/2015. // Copyright © 2015 WillMeaton.uk. All rights reserved. // #ifndef Core_hpp #define Core_hpp #include "Runner.hpp" //This file is required. class Core : public BaseCore{ public: Core(){}; ~Core(); void draw(); void update(); void setup(); void keyPressed(int key); void keyReleased(int key); void mousePressed(int button); void mouseReleased(int button); void exitCalled(); }; #endif /* Core_hpp */
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButtonCalc_clicked(); void on_lineEditNumberOfLiters_cursorPositionChanged(int arg1, int arg2); void on_doubleSpinBoxSpend_editingFinished(); void on_pushButtonCalc_2_clicked(); void on_actionExit_3_triggered(); void on_pushButton_clicked(); void on_doubleSpinBoxDistance_2_editingFinished(); void on_lineEditNumberOfLiters_3_cursorPositionChanged(int arg1, int arg2); void on_lineEditNumberOfLiters_4_cursorPositionChanged(int arg1, int arg2); void on_doubleSpinBoxSpend_2_editingFinished(); void on_lineEditNumberOfLiters_5_cursorPositionChanged(int arg1, int arg2); void on_pushButtonCalc_3_clicked(); void on_doubleSpinBoxPrice_2_editingFinished(); void on_doubleSpinBoxPrice_3_editingFinished(); void on_lineEditNumberOfLiters_2_cursorPositionChanged(int arg1, int arg2); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
class Category_668 { duplicate = 543; }; class Category_671 { duplicate = 543; };
/* * Task.cpp * * Created on: Jun 10, 2017 * Author: root */ #include "Task.h" #include <stdlib.h> #include "../Log/Logger.h" #include "../Memory/MemAllocator.h" namespace CommBaseOut { Task::Task():m_flag(false),m_count(0),m_pID(0) { } Task::~Task() { if(m_pID) { DELETE_BASE(m_pID, eMemoryArray); m_pID = 0; } } int Task::Start(int num, pthread_attr_t *attr) { m_count = num; m_pID = NEW_BASE(pthread_t, num); // pthread_t[num]; // m_pID = (pthread_t *)NEW_BASE(pthread_t, num); // pthread_t[num]; m_flag = false; for(int i=0; i<num; ++i) { if(pthread_create(&m_pID[i], attr, ThreadRun, this)) { LOG_BASE(FILEINFO, "pthread_create failed"); return eCreateThreadErr; } } return eTaskSuccess; } int Task::End() { if(!m_flag) { m_flag = true; void *status = 0; for(int i=0; i<m_count; ++i) { pthread_join(m_pID[i], &status); } if(m_pID) { DELETE_BASE(m_pID, eMemoryArray); m_pID = 0; } } return eTaskSuccess; } void *Task::ThreadRun(void *p) { Task *task = static_cast<Task *>(p); task->svr(); return 0; } int Task::svr() { return eTaskSuccess; } }
/* ** EPITECH PROJECT, 2019 ** OOP_indie_studio_2018 ** File description: ** main */ #include "FileNotFoundException.hpp" #include "Game.hpp" #include <iostream> int main(int ac, char **av) { if (ac > 1) { std::cout << av[1] << " is not necessary" << std::endl <<"USAGE: ./bomberman port" << std::endl; return (84); } else { try { Game game; game.begin(); } catch (FileNotFoundException &fnf) { fnf.what(); return (84); } catch (Exception &e) { std::cerr << e.what() << std::endl; return (84); } } return (0); }
#include "consts.h" #include "paths.h" #include "serialization.h" #include "assertion.h" #include <nlohmann/json.hpp> #include <fstream> void ConstsImpl::Load() { DOUT() << "Loading Constants" << std::endl; std::ifstream file(Paths::Assets + "consts.json"); if (!file.good()) { THROWERROR("Can't open " + Paths::Assets + "consts.json file"); } nlohmann::json j; file >> j; j.at("CanvasSize").get_to(CanvasSize); j.at("TileSize").get_to(TileSize); j.at("MaxLayers").get_to(MaxLayers); UpdateWindowSize(WindowSize); DOUT() << "Successfully loaded Constants" << std::endl; } void ConstsImpl::Reset() { CanvasSize = { 0, 0 }; Scale = 0; TileSize = 0; } const ConstsImpl& Consts() { return ConstsMut(); } ConstsImpl& ConstsMut() { static ConstsImpl impl; return impl; } void UpdateWindowSize(glm::uvec2 size) { auto& impl = ConstsMut(); impl.WindowSize = size; glm::uvec2 scale = size / impl.CanvasSize; impl.Scale = std::min(scale.x, scale.y); }
//#include<string> // //namespace HW{ // string UpcaseString(const string& string){ // const char* str = string.c_str(); // int length = string.length(); // char dif = 'a' - 'A'; // char*newStr = new char[length + 1]; // //memcpy(newStr, string.c_str(), length + 1); // for (int i = 0; i < length; i++){ // if (newStr[i] >= 'a' && newStr[i] <= 'z') // newStr[i] -= dif; // } // string resStr = newStr; // delete[] newStr; // return resStr; // } //}
#include <Servo.h> //DC motor pin int motorA = 6; int motorB = 5; //button input pin int button1 = 8; int button2 = 9; int button3 = 10; //button input state int stateA; int stateB; int stateC; //Servo declaration Servo myservo; //Feature creep int launchCode = 0; int lAngle = 0; int lSpeed = 0; void setup() { pinMode(button1, INPUT); pinMode(button2, INPUT); pinMode(button3, INPUT); pinMode(motorA, OUTPUT); pinMode(motorB, OUTPUT); myservo.attach(11); myservo.write(90); Serial.begin(9600); Serial.println("PaperPlane Launcher v1 - Tristan Technologies"); } void loop() { stateA = digitalRead(button1); stateB = digitalRead(button2); stateC = digitalRead(button3); //For debug Serial.print(stateA); Serial.print(" "); Serial.print(stateB); Serial.print(" "); Serial.println(stateC); if(stateA) { //button1 pressed action lAngle = 0; lSpeed = 255; launchCode = 1; } else if(stateB) { //button2 pressed action lAngle = 90; lSpeed = 255; launchCode = 1; } else if(stateC) { //button3 pressed action lAngle = 179; lSpeed = 255; launchCode = 1; } else { lAngle = 0; lSpeed = 0; launchCode = 0; } if(launchCode == 1) { myservo.write(lAngle); delay(500); //Rev up motor(might want to change speed) analogWrite(motorA,lSpeed); analogWrite(motorB,lSpeed); //Waiting for launch Serial.write("Launching..."); delay(5000); Serial.write("launch end"); launchCode = 0; } }
// Created on: 2008-01-20 // Created by: Alexander A. BORODIN // Copyright (c) 2008-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 _Font_FontMgr_HeaderFile #define _Font_FontMgr_HeaderFile #include <Standard.hxx> #include <Standard_Transient.hxx> #include <Font_NListOfSystemFont.hxx> #include <Font_StrictLevel.hxx> #include <Font_UnicodeSubset.hxx> #include <NCollection_DataMap.hxx> #include <NCollection_IndexedMap.hxx> #include <NCollection_Shared.hxx> #include <TColStd_SequenceOfHAsciiString.hxx> class TCollection_HAsciiString; class NCollection_Buffer; DEFINE_STANDARD_HANDLE(Font_FontMgr, Standard_Transient) //! Collects and provides information about available fonts in system. class Font_FontMgr : public Standard_Transient { DEFINE_STANDARD_RTTIEXT(Font_FontMgr, Standard_Transient) public: //! Return global instance of font manager. Standard_EXPORT static Handle(Font_FontMgr) GetInstance(); //! Return font aspect as string. static const char* FontAspectToString (Font_FontAspect theAspect) { switch (theAspect) { case Font_FontAspect_UNDEFINED: return "undefined"; case Font_FontAspect_Regular: return "regular"; case Font_FontAspect_Bold: return "bold"; case Font_FontAspect_Italic: return "italic"; case Font_FontAspect_BoldItalic: return "bold-italic"; } return "invalid"; } //! Return flag to use fallback fonts in case if used font does not include symbols from specific Unicode subset; TRUE by default. Standard_EXPORT static Standard_Boolean& ToUseUnicodeSubsetFallback(); public: //! Return the list of available fonts. void AvailableFonts (Font_NListOfSystemFont& theList) const { for (Font_FontMap::Iterator aFontIter (myFontMap); aFontIter.More(); aFontIter.Next()) { theList.Append (aFontIter.Value()); } } //! Return the list of available fonts. Font_NListOfSystemFont GetAvailableFonts() const { Font_NListOfSystemFont aList; AvailableFonts (aList); return aList; } //! Returns sequence of available fonts names Standard_EXPORT void GetAvailableFontsNames (TColStd_SequenceOfHAsciiString& theFontsNames) const; //! Returns font that match given parameters. //! If theFontName is empty string returned font can have any FontName. //! If theFontAspect is Font_FA_Undefined returned font can have any FontAspect. //! If theFontSize is "-1" returned font can have any FontSize. Standard_EXPORT Handle(Font_SystemFont) GetFont (const Handle(TCollection_HAsciiString)& theFontName, const Font_FontAspect theFontAspect, const Standard_Integer theFontSize) const; //! Returns font that match given name or NULL if such font family is NOT registered. //! Note that unlike FindFont(), this method ignores font aliases and does not look for fall-back. Standard_EXPORT Handle(Font_SystemFont) GetFont (const TCollection_AsciiString& theFontName) const; //! Tries to find font by given parameters. //! If the specified font is not found tries to use font names mapping. //! If the requested family name not found -> search for any font family with given aspect and height. //! If the font is still not found, returns any font available in the system. //! Returns NULL in case when the fonts are not found in the system. //! @param theFontName [in] font family to find or alias name //! @param theStrictLevel [in] search strict level for using aliases and fallback //! @param theFontAspect [in] [out] font aspect to find (considered only if family name is not found); //! can be modified if specified font alias refers to another style (compatibility with obsolete aliases) //! @param theDoFailMsg [in] put error message on failure into default messenger Standard_EXPORT Handle(Font_SystemFont) FindFont (const TCollection_AsciiString& theFontName, Font_StrictLevel theStrictLevel, Font_FontAspect& theFontAspect, Standard_Boolean theDoFailMsg = Standard_True) const; //! Tries to find font by given parameters. Handle(Font_SystemFont) FindFont (const TCollection_AsciiString& theFontName, Font_FontAspect& theFontAspect) const { return FindFont (theFontName, Font_StrictLevel_Any, theFontAspect); } //! Tries to find fallback font for specified Unicode subset. //! Returns NULL in case when fallback font is not found in the system. //! @param theSubset [in] Unicode subset //! @param theFontAspect [in] font aspect to find Standard_EXPORT Handle(Font_SystemFont) FindFallbackFont (Font_UnicodeSubset theSubset, Font_FontAspect theFontAspect) const; //! Read font file and retrieve information from it (the list of font faces). Standard_EXPORT Standard_Boolean CheckFont (NCollection_Sequence<Handle(Font_SystemFont)>& theFonts, const TCollection_AsciiString& theFontPath) const; //! Read font file and retrieve information from it. Standard_EXPORT Handle(Font_SystemFont) CheckFont (const Standard_CString theFontPath) const; //! Register new font. //! If there is existing entity with the same name and properties but different path //! then font will be overridden or ignored depending on theToOverride flag. Standard_EXPORT Standard_Boolean RegisterFont (const Handle(Font_SystemFont)& theFont, const Standard_Boolean theToOverride); //! Register new fonts. Standard_Boolean RegisterFonts (const NCollection_Sequence<Handle(Font_SystemFont)>& theFonts, const Standard_Boolean theToOverride) { Standard_Boolean isRegistered = Standard_False; for (NCollection_Sequence<Handle(Font_SystemFont)>::Iterator aFontIter (theFonts); aFontIter.More(); aFontIter.Next()) { isRegistered = RegisterFont (aFontIter.Value(), theToOverride) || isRegistered; } return isRegistered; } public: //! Return flag for tracing font aliases usage via Message_Trace messages; TRUE by default. Standard_Boolean ToTraceAliases() const { return myToTraceAliases; } //! Set flag for tracing font alias usage; useful to trace which fonts are actually used. //! Can be disabled to avoid redundant messages with Message_Trace level. void SetTraceAliases (Standard_Boolean theToTrace) { myToTraceAliases = theToTrace; } //! Return font names with defined aliases. //! @param theAliases [out] alias names Standard_EXPORT void GetAllAliases (TColStd_SequenceOfHAsciiString& theAliases) const; //! Return aliases to specified font name. //! @param theFontNames [out] font names associated with alias name //! @param theAliasName [in] alias name Standard_EXPORT void GetFontAliases (TColStd_SequenceOfHAsciiString& theFontNames, const TCollection_AsciiString& theAliasName) const; //! Register font alias. //! //! Font alias allows using predefined short-cuts like Font_NOF_MONOSPACE or Font_NOF_SANS_SERIF, //! and defining several fallback fonts like Font_NOF_CJK ("cjk") or "courier" for fonts, //! which availability depends on system. //! //! By default, Font_FontMgr registers standard aliases, which could be extended or replaced by application //! basing on better knowledge of the system or basing on additional fonts packaged with application itself. //! Aliases are defined "in advance", so that they could point to non-existing fonts, //! and they are resolved dynamically on request - first existing font is returned in case of multiple aliases to the same name. //! //! @param theAliasName [in] alias name or name of another font to be used as alias //! @param theFontName [in] font to be used as substitution for alias //! @return FALSE if alias has been already registered Standard_EXPORT bool AddFontAlias (const TCollection_AsciiString& theAliasName, const TCollection_AsciiString& theFontName); //! Unregister font alias. //! @param theAliasName [in] alias name or name of another font to be used as alias; //! all aliases will be removed in case of empty name //! @param theFontName [in] font to be used as substitution for alias; //! all fonts will be removed in case of empty name //! @return TRUE if alias has been removed Standard_EXPORT bool RemoveFontAlias (const TCollection_AsciiString& theAliasName, const TCollection_AsciiString& theFontName); public: //! Collects available fonts paths. Standard_EXPORT void InitFontDataBase(); //! Clear registry. Can be used for testing purposes. Standard_EXPORT void ClearFontDataBase(); //! Return DejaVu font as embed a single fallback font. //! It can be used in cases when there is no own font file. //! Note: result buffer is readonly and should not be changed, //! any data modification can lead to unpredictable consequences. Standard_EXPORT static Handle(NCollection_Buffer) EmbedFallbackFont(); private: //! Creates empty font manager object Standard_EXPORT Font_FontMgr(); private: //! Map storing registered fonts. class Font_FontMap : public NCollection_IndexedMap<Handle(Font_SystemFont), Font_SystemFont> { public: //! Empty constructor. Font_FontMap() {} //! Try finding font with specified parameters or the closest one. //! @param theFontName [in] font family to find (or empty string if family name can be ignored) //! @return best match font or NULL if not found Handle(Font_SystemFont) Find (const TCollection_AsciiString& theFontName) const; public: //! Computes a hash code for the system font, in the range [1, theUpperBound]. Based on Font Family, so that the //! whole family with different aspects can be found within the same bucket of some map //! @param theHExtendedString the handle referred to extended string which hash code is to be computed //! @param theUpperBound the upper bound of the range a computing hash code must be within //! @return a computed hash code, in the range [1, theUpperBound] static Standard_Integer HashCode (const Handle (Font_SystemFont) & theSystemFont, const Standard_Integer theUpperBound) { return ::HashCode (theSystemFont->FontKey(), theUpperBound); } //! Matching two instances, for Map interface. static bool IsEqual (const Handle(Font_SystemFont)& theFont1, const Handle(Font_SystemFont)& theFont2) { return theFont1->IsEqual (theFont2); } }; //! Structure defining font alias. struct Font_FontAlias { TCollection_AsciiString FontName; Font_FontAspect FontAspect; Font_FontAlias (const TCollection_AsciiString& theFontName, Font_FontAspect theFontAspect = Font_FontAspect_UNDEFINED) : FontName (theFontName), FontAspect (theFontAspect) {} Font_FontAlias() : FontAspect (Font_FontAspect_UNDEFINED) {} }; //! Sequence of font aliases. typedef NCollection_Shared< NCollection_Sequence<Font_FontAlias> > Font_FontAliasSequence; //! Register font alias. void addFontAlias (const TCollection_AsciiString& theAliasName, const Handle(Font_FontAliasSequence)& theAliases, Font_FontAspect theAspect = Font_FontAspect_UNDEFINED); private: Font_FontMap myFontMap; NCollection_DataMap<TCollection_AsciiString, Handle(Font_FontAliasSequence)> myFontAliases; Handle(Font_FontAliasSequence) myFallbackAlias; Standard_Boolean myToTraceAliases; }; #endif // _Font_FontMgr_HeaderFile
#include "precompiled.h" #include "texture/texture.h" #include "texture/texturecache.h" #include "render/render.h" #include "render/rendergroup.h" #include "render/dx.h" namespace texture { }; using namespace texture; DXTexture::DXTexture(const std::string& name) : texture(NULL), name(name), is_transparent(false), use_texture(true), is_lightmap(false), draw(true), sky(false), overbright(NULL) { } DXTexture::~DXTexture() { if (texture) texture->Release(); } bool DXTexture::activate(bool deactivate_current) { render::frame_texswaps++; if (is_lightmap) { if (deactivate_current) { if (render::current_lightmap) render::current_lightmap->deactivate(); } render::current_lightmap = this; render::device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); render::device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE2X); render::device->SetTexture(1, texture); return true; } if (deactivate_current) { if (render::current_texture) render::current_texture->deactivate(); } render::current_texture = this; //if (shader) // shader->activate(this); //if (!use_texture) // return true; render::device->SetTexture(0, texture); return true; } void DXTexture::deactivate() { if (is_lightmap) { render::device->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE2X); render::device->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); render::current_lightmap = NULL; return; } render::current_texture = NULL; //if (shader) // shader->deactivate(this); } void DXTexture::acquire() { } void DXTexture::release() { }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2009 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef _MODULE_DATABASE_SEC_POLICY_H_ #define _MODULE_DATABASE_SEC_POLICY_H_ #include "modules/database/src/opdatabase_base.h" #ifdef DATABASE_MODULE_MANAGER_SUPPORT #include "modules/sqlite/sqlite3.h" class PS_PolicyFactory; class PS_Policy : public PS_ObjectTypes { public: enum QuotaHandling { KQuotaDeny = 0, KQuotaAskUser = 1, KQuotaAllow = 2 }; enum AccessValues { KAccessDeny = 0, KAccessAllow = 1 }; enum SecAttrUint { KUintStart, /** * Timeout for query execution * 0 to disable, anything else to enable */ KQueryExecutionTimeout, /** * When the quota exceeds, this attribute * tells how it should be handled: * - KQuotaDeny deny * - KQuotaAskUser ask user through WindowCommander API. * Only done if called asynchronously, else it's denied * - KQuotaAllow ignore * Unrecognized value is handled as KQuotaDeny. * When value is denied, ERR_QUOTA_EXCEEDED * will be returned */ KOriginExceededHandling, /** * Maximum size in bytes that a result set with caching * enabled can get to. * After passing this limit, any call to SqlResultSet::StepL * will return PS_Status::ERR_RSET_TOO_BIG */ KMaxResultSetSize, /** * Maximum number of databases per type and origin: * 0 - unlimited * anything else - limit */ KMaxObjectsPerOrigin, /** * Tells if access to the database should b allowed or not: * 0 - deny * 1 - allows but returns PS_Status::SHOULD_ASK_FOR_ACCESS * so the callee can decide whether to ask the user or not * 2 - allows */ KAccessToObject, KUintEnd }; enum SecAttrUint64 { KUint64Start, /** * Global browser quota for ALL databases. * Value in bytes * 0 to disable, anything else to enable */ KGlobalQuota, /** * Database quota for the given domain * Value in bytes * 0 to disable, anything else to enable */ KOriginQuota, KUint64End }; enum SecAttrUniStr { KUniStrStart, /** * Path to the main folder where the data files should be placed * This will typically point to the profile folder, widget folder, or extension folder * NOTE: the index file will also be placed here ! * If NULL is returned assume OOM. * If an empty string is returned assume that the information is * not available so the call should fail gracefully. */ KMainFolderPath, /** * Named of folder inside KMainFolderPath where the database datafiles should be placed * For instance, if we're on a widget KMainFolderPath will point to the widget data folder * and this will be the name of the folder inside KMainFolderPath that will store the data files */ KSubFolder, KUniStrEnd }; static const unsigned UINT_ATTR_INVALID = (unsigned)-1; static const OpFileLength UINT64_ATTR_INVALID = FILE_LENGTH_NONE; virtual OpFileLength GetAttribute(SecAttrUint64 attr, URL_CONTEXT_ID context_id, const uni_char* domain = NULL, const Window* window = NULL) const; virtual unsigned GetAttribute(SecAttrUint attr, URL_CONTEXT_ID context_id, const uni_char* domain = NULL, const Window* window = NULL) const; /** * The returned pointer is only valid until the next call to * GetAttribute(). This method does not indicate whether it * succeeds, but unless stated otherwise in the documentation of * the requested attribute, it is reasonable to assume that it * will return NULL on errors. However, unless stated otherwise in * the documentation of the requested attribute, NULL is also a valid * non-error return value. */ virtual const uni_char* GetAttribute(SecAttrUniStr attr, URL_CONTEXT_ID context_id, const uni_char* domain = NULL, const Window* window = NULL) const; virtual OP_STATUS SetAttribute(SecAttrUint64 attr, URL_CONTEXT_ID context_id, OpFileLength new_value, const uni_char* domain = NULL, const Window* window = NULL); virtual OP_STATUS SetAttribute(SecAttrUint attr, URL_CONTEXT_ID context_id, unsigned new_value, const uni_char* domain = NULL, const Window* window = NULL); virtual BOOL IsConfigurable(SecAttrUint64 attr) const; virtual BOOL IsConfigurable(SecAttrUint attr) const; virtual BOOL IsConfigurable(SecAttrUniStr attr) const; protected: friend class PS_PolicyFactory; PS_Policy(PS_Policy* parent = NULL); virtual ~PS_Policy(); //GetDefaultPolicyL PS_Policy* m_parent_policy; }; #ifdef SUPPORT_DATABASE_INTERNAL /************* * Classes to filter sql statements *************/ class SqlValidator { public: enum Type { INVALID = 0, TRUSTED = 1, UNTRUSTED = 2 }; SqlValidator() {} virtual ~SqlValidator() {} virtual int Validate(int sqlite_action, const char* d1, const char* d2, const char* d3, const char* d4) const = 0; virtual Type GetType() const { return INVALID; } }; enum SqlActionFlags { SQL_ACTION_ALLOWED_UNTRUSTED = 0x01, SQL_ACTION_AFFECTS_TRANSACTION = 0x02, SQL_ACTION_IS_STATEMENT = 0x04 }; #endif //SUPPORT_DATABASE_INTERNAL //expose the default definitions as well #include "modules/database/sec_policy_defs.h" #ifdef HAS_COMPLEX_GLOBALS # define CONST_STRUCT_ARRAY_DECL(name,type,size) static const type name[size] #else # define CONST_STRUCT_ARRAY_DECL(name,type,size) type name[size];void init_##name() #endif // HAS_COMPLEX_GLOBALS class PS_PolicyFactory : private PS_Policy { public: PS_PolicyFactory(); ~PS_PolicyFactory(); PS_Policy* GetPolicy(PS_ObjectType type); const PS_Policy* GetPolicy(PS_ObjectType type) const; #ifdef SUPPORT_DATABASE_INTERNAL const SqlValidator* GetSqlValidator(SqlValidator::Type) const; struct SqlActionProperties { int statement_type; unsigned flags; }; enum{ MAX_SQL_ACTIONS = SQLITE_SAVEPOINT+1 }; BOOL GetSqlActionFlag(unsigned action, unsigned flag) const { OP_ASSERT(flag<MAX_SQL_ACTIONS);return (m_sql_action_properties[action].flags & flag)!=0; } #endif //SUPPORT_DATABASE_INTERNAL /** * Shorthand method to access the policy object directly */ OpFileLength GetPolicyAttribute(PS_ObjectType type, SecAttrUint64 attr, URL_CONTEXT_ID context_id, const uni_char* domain = NULL, const Window* window = NULL) const; unsigned GetPolicyAttribute(PS_ObjectType type, SecAttrUint attr, URL_CONTEXT_ID context_id, const uni_char* domain = NULL, const Window* window = NULL) const; const uni_char* GetPolicyAttribute(PS_ObjectType type, SecAttrUniStr attr, URL_CONTEXT_ID context_id, const uni_char* domain = NULL, const Window* window = NULL) const; private: #ifdef SUPPORT_DATABASE_INTERNAL CONST_STRUCT_ARRAY_DECL(m_sql_action_properties, SqlActionProperties, MAX_SQL_ACTIONS); #ifdef DEBUG_ENABLE_OPASSERT void EnsureSqlActionsConstruction(); #endif // DEBUG_ENABLE_OPASSERT #endif // SUPPORT_DATABASE_INTERNAL OpDefaultGlobalPolicy m_default_global_policy; #ifdef DATABASE_STORAGE_SUPPORT WSD_DatabaseGlobalPolicy m_database_global_policy; #endif // DATABASE_STORAGE_SUPPORT #ifdef WEBSTORAGE_ENABLE_SIMPLE_BACKEND WebStoragePolicy m_local_storage_policy; WebStoragePolicy m_session_storage_policy; #ifdef WEBSTORAGE_WIDGET_PREFS_SUPPORT WidgetPreferencesPolicy m_widget_prefs_policy; #endif #ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT WebStorageUserScriptPolicy m_user_js_storage_policy; #endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT #endif //WEBSTORAGE_ENABLE_SIMPLE_BACKEND #ifdef SUPPORT_DATABASE_INTERNAL //sql validators TrustedSqlValidator m_trusted_sql_validator; UntrustedSqlValidator m_untrusted_sql_validator; #endif //SUPPORT_DATABASE_INTERNAL #ifdef SELFTEST public: void SetOverridePolicy(PS_Policy* p) { m_override_policy = p; } PS_Policy* GetOverridePolicy() { return m_override_policy; } PS_Policy* m_override_policy; #endif }; #endif //DATABASE_MODULE_MANAGER_SUPPORT #endif//_MODULE_DATABASE_SEC_POLICY_H_
#ifndef MATERIALBUFFER_H #define MATERIALBUFFER_H #include <Buffers/UniformBuffer.h> #include <glm/glm.hpp> class CMaterialBuffer final : public CUniformBuffer { public: CMaterialBuffer(); void setDiffuseColor(const glm::vec3 &color) const; void setSpecularColor(const glm::vec3 &color) const; void setAmbientColor(const glm::vec3 &color) const; void setUseDiffuseTexture(GLint use); void setUseSpecularTexture(GLint use); void setUseNormalTexture(GLint use); void setShininess(GLfloat shininess); }; #endif // MATERIALBUFFER_H